epiq 1.8.6 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/gui/abap-2J4LSWVV.js +1 -0
- package/dist/gui/actionscript-3-QBCO7GBI.js +1 -0
- package/dist/gui/ada-D5ESCCWX.js +1 -0
- package/dist/gui/ahk-7PFXBG6H.js +1 -0
- package/dist/gui/ahk2-K5PQCZEP.js +1 -0
- package/dist/gui/andromeeda-RHRS4Q5O.js +1 -0
- package/dist/gui/angular-html-YBC4GTV4.js +1 -0
- package/dist/gui/angular-ts-ZIU7OVGE.js +1 -0
- package/dist/gui/apache-U32KA2FB.js +1 -0
- package/dist/gui/apex-VTA27EIA.js +1 -0
- package/dist/gui/apl-3N2QYEVK.js +1 -0
- package/dist/gui/applescript-WKBNOJN3.js +1 -0
- package/dist/gui/ara-LOYFRK44.js +1 -0
- package/dist/gui/asciidoc-BIAX4CUU.js +1 -0
- package/dist/gui/asm-5NJNIH7L.js +1 -0
- package/dist/gui/astro-RDSHXCML.js +1 -0
- package/dist/gui/aurora-x-FAPHH5YB.js +1 -0
- package/dist/gui/awk-ESSJ54IN.js +1 -0
- package/dist/gui/ayu-dark-GAZUJSFG.js +1 -0
- package/dist/gui/ayu-light-S3HDK3P6.js +1 -0
- package/dist/gui/ayu-mirage-FRLUTQCD.js +1 -0
- package/dist/gui/ballerina-I5G6WI4V.js +1 -0
- package/dist/gui/bat-XQTE6ROZ.js +1 -0
- package/dist/gui/beancount-LP7NWB5A.js +1 -0
- package/dist/gui/berry-KUSHPXSF.js +1 -0
- package/dist/gui/bibtex-5Q4QFORS.js +1 -0
- package/dist/gui/bicep-RLEFUJBB.js +1 -0
- package/dist/gui/bird2-H2ROQN7N.js +1 -0
- package/dist/gui/blade-62REZWJW.js +1 -0
- package/dist/gui/bsl-3ICADNA4.js +1 -0
- package/dist/gui/c-Q4CAL6EN.js +1 -0
- package/dist/gui/c3-CHQTUKMB.js +1 -0
- package/dist/gui/cadence-GMQVA7GB.js +1 -0
- package/dist/gui/cairo-ZPLUE773.js +1 -0
- package/dist/gui/catppuccin-frappe-WTOO7TQU.js +1 -0
- package/dist/gui/catppuccin-latte-A2LSA3LJ.js +1 -0
- package/dist/gui/catppuccin-macchiato-RCIP7S3P.js +1 -0
- package/dist/gui/catppuccin-mocha-OS7AM3GC.js +1 -0
- package/dist/gui/chapel-3Z633JGJ.js +1 -0
- package/dist/gui/chunk-26MLVG6L.js +1 -0
- package/dist/gui/chunk-2SOBHFBG.js +1 -0
- package/dist/gui/chunk-2YYHCOMV.js +1 -0
- package/dist/gui/chunk-37IWMLTX.js +1 -0
- package/dist/gui/chunk-3FGBQ6A6.js +1 -0
- package/dist/gui/chunk-3ZKK7SIN.js +1 -0
- package/dist/gui/chunk-3ZQCKWX3.js +1 -0
- package/dist/gui/chunk-46DHNZDP.js +1 -0
- package/dist/gui/chunk-4L4526WS.js +1 -0
- package/dist/gui/chunk-55JTXQF7.js +164 -0
- package/dist/gui/chunk-5BZ5GSXY.js +1 -0
- package/dist/gui/chunk-5LBKFR6X.js +1 -0
- package/dist/gui/chunk-5UNDITZ6.js +1 -0
- package/dist/gui/chunk-5YAVAROY.js +1 -0
- package/dist/gui/chunk-63FIM4UN.js +1 -0
- package/dist/gui/chunk-6ASVBJNB.js +1 -0
- package/dist/gui/chunk-6R3KEE7K.js +1 -0
- package/dist/gui/chunk-6RHIU6UJ.js +1 -0
- package/dist/gui/chunk-6WZKLANJ.js +1 -0
- package/dist/gui/chunk-6YUFSVTA.js +1 -0
- package/dist/gui/chunk-74DAPDUZ.js +1 -0
- package/dist/gui/chunk-7DL6FRG7.js +1 -0
- package/dist/gui/chunk-AJYDCVPS.js +1 -0
- package/dist/gui/chunk-ALTLFZIS.js +1 -0
- package/dist/gui/chunk-BQQOMDF3.js +1 -0
- package/dist/gui/chunk-CJN6NEEF.js +1 -0
- package/dist/gui/chunk-DCJRCM7E.js +1 -0
- package/dist/gui/chunk-DD73BSYL.js +1 -0
- package/dist/gui/chunk-DHEVTTF6.js +1 -0
- package/dist/gui/chunk-DXKN75GC.js +1 -0
- package/dist/gui/chunk-E3W66Q2M.js +1 -0
- package/dist/gui/chunk-E56XDXUN.js +1 -0
- package/dist/gui/chunk-ESXHTAGG.js +1 -0
- package/dist/gui/chunk-FNPLEVVQ.js +1 -0
- package/dist/gui/chunk-FROJTAOT.js +1 -0
- package/dist/gui/chunk-FYI27QRJ.js +1 -0
- package/dist/gui/chunk-G7PZUARL.js +1 -0
- package/dist/gui/chunk-HHEBGI74.js +1 -0
- package/dist/gui/chunk-IGL365IS.js +1 -0
- package/dist/gui/chunk-IHPQHJTE.js +1 -0
- package/dist/gui/chunk-JFHYNQRZ.js +1 -0
- package/dist/gui/chunk-JXMQU3VM.js +1 -0
- package/dist/gui/chunk-KWIOD2XB.js +1 -0
- package/dist/gui/chunk-M3W3D44W.js +1 -0
- package/dist/gui/chunk-MAHOIE36.js +1 -0
- package/dist/gui/chunk-MLTQE63C.js +1 -0
- package/dist/gui/chunk-MSGQCPM6.js +1 -0
- package/dist/gui/chunk-NA4VE6LQ.js +1 -0
- package/dist/gui/chunk-O36SAGVH.js +1 -0
- package/dist/gui/chunk-OOY6SNOQ.js +1 -0
- package/dist/gui/chunk-OR5FHECQ.js +1 -0
- package/dist/gui/chunk-P7GHE3RQ.js +1 -0
- package/dist/gui/chunk-PHEOHAKT.js +1 -0
- package/dist/gui/chunk-PRHZBKTR.js +1 -0
- package/dist/gui/chunk-PYRZ523Z.js +1 -0
- package/dist/gui/chunk-PZEZXK43.js +1 -0
- package/dist/gui/chunk-QIL2Z2PV.js +1 -0
- package/dist/gui/chunk-QOHIV2P6.js +1 -0
- package/dist/gui/chunk-QP5MZ6PD.js +1 -0
- package/dist/gui/chunk-QZTMXTQ5.js +1 -0
- package/dist/gui/chunk-RVQECLU5.js +1 -0
- package/dist/gui/chunk-SILA42W7.js +1 -0
- package/dist/gui/chunk-T3N6MPDP.js +1 -0
- package/dist/gui/chunk-TGZ7ELPN.js +1 -0
- package/dist/gui/chunk-TK4ZAFYM.js +1 -0
- package/dist/gui/chunk-TV7I3SW3.js +1 -0
- package/dist/gui/chunk-UVQC6P2E.js +1 -0
- package/dist/gui/chunk-V6RWMCFC.js +1 -0
- package/dist/gui/chunk-W2DTVSTF.js +1 -0
- package/dist/gui/chunk-WKNCCTIH.js +1 -0
- package/dist/gui/chunk-WS3EQ3SY.js +1 -0
- package/dist/gui/chunk-WTRKJZEH.js +1 -0
- package/dist/gui/chunk-WY4VX6QJ.js +1 -0
- package/dist/gui/chunk-XIVHKWKD.js +1 -0
- package/dist/gui/chunk-XZQZMXAN.js +1 -0
- package/dist/gui/chunk-Y2SOJ45P.js +1 -0
- package/dist/gui/chunk-YBPUFKZG.js +1 -0
- package/dist/gui/chunk-YC22HROH.js +1 -0
- package/dist/gui/chunk-Z6EXOQLM.js +1 -0
- package/dist/gui/chunk-ZD72CDNJ.js +1 -0
- package/dist/gui/chunk-ZYM5HG5R.js +1 -0
- package/dist/gui/clarity-DYA2JUGZ.js +1 -0
- package/dist/gui/clojure-G7IURXNK.js +1 -0
- package/dist/gui/cmake-4DZSTAWG.js +1 -0
- package/dist/gui/cobol-DUCWHDIZ.js +1 -0
- package/dist/gui/codeowners-IKIECA5K.js +1 -0
- package/dist/gui/codeql-EK6NFINM.js +1 -0
- package/dist/gui/coffee-HZ62PXBN.js +1 -0
- package/dist/gui/common-lisp-C5JFPP2W.js +1 -0
- package/dist/gui/coq-QNZJXEO2.js +1 -0
- package/dist/gui/cpp-LVH4DUEH.js +1 -0
- package/dist/gui/crystal-OEOE5VN5.js +1 -0
- package/dist/gui/csharp-Y6M5EGHH.js +1 -0
- package/dist/gui/css-MYBAEYPV.js +1 -0
- package/dist/gui/csv-W2N6UZ5O.js +1 -0
- package/dist/gui/cue-XLSH6VNO.js +1 -0
- package/dist/gui/cypher-LIAJ2AQF.js +1 -0
- package/dist/gui/d-KOZ5GW3B.js +1 -0
- package/dist/gui/dark-plus-HCLPH6DY.js +1 -0
- package/dist/gui/dart-HSXEG6I6.js +1 -0
- package/dist/gui/dax-XUGRY6W7.js +1 -0
- package/dist/gui/desktop-NXYZUBRS.js +1 -0
- package/dist/gui/diff-62RZJUWL.js +1 -0
- package/dist/gui/diffs-worker.js +5 -0
- package/dist/gui/docker-5PAL7A2H.js +1 -0
- package/dist/gui/dotenv-QNGBJ7H6.js +1 -0
- package/dist/gui/dracula-JHW4RJTX.js +1 -0
- package/dist/gui/dracula-soft-5EFEA2BQ.js +1 -0
- package/dist/gui/dream-maker-EHSANE6P.js +1 -0
- package/dist/gui/edge-GY7QH5MJ.js +1 -0
- package/dist/gui/elixir-TXRUL5QI.js +1 -0
- package/dist/gui/elm-O2IRWDLI.js +1 -0
- package/dist/gui/emacs-lisp-YSAYXSLO.js +1 -0
- package/dist/gui/erb-LOH7WKGU.js +1 -0
- package/dist/gui/erlang-J6XNI2HL.js +1 -0
- package/dist/gui/everforest-dark-YYJDFM4G.js +1 -0
- package/dist/gui/everforest-light-6VKVRX63.js +1 -0
- package/dist/gui/fennel-UIF7WTON.js +1 -0
- package/dist/gui/fish-XNUBLCAF.js +1 -0
- package/dist/gui/fluent-UFZK23ZF.js +1 -0
- package/dist/gui/fortran-fixed-form-GF4EQUFG.js +1 -0
- package/dist/gui/fortran-free-form-PXTWSUJU.js +1 -0
- package/dist/gui/fsharp-NXUAWXAF.js +1 -0
- package/dist/gui/gdresource-3Z6GJTMS.js +1 -0
- package/dist/gui/gdscript-NR3VITKY.js +1 -0
- package/dist/gui/gdshader-M5YZ63Y2.js +1 -0
- package/dist/gui/genie-BO3CX2XQ.js +1 -0
- package/dist/gui/gherkin-LWGWZ3RS.js +1 -0
- package/dist/gui/git-commit-RPQOTEF3.js +1 -0
- package/dist/gui/git-rebase-TF2QJEAL.js +1 -0
- package/dist/gui/github-dark-REFHQ7KZ.js +1 -0
- package/dist/gui/{github-dark-default-VHJFG2UV.js → github-dark-default-HNVWMHF4.js} +1 -7
- package/dist/gui/github-dark-dimmed-JJPACVZZ.js +1 -0
- package/dist/gui/github-dark-high-contrast-MKQ5JYLO.js +1 -0
- package/dist/gui/github-light-IM7NG6OB.js +1 -0
- package/dist/gui/github-light-default-QU2YVTXI.js +1 -0
- package/dist/gui/github-light-high-contrast-OUURX2TU.js +1 -0
- package/dist/gui/gleam-5HTZJ72P.js +1 -0
- package/dist/gui/glimmer-js-PFOARH3K.js +1 -0
- package/dist/gui/glimmer-ts-LZJTTHVF.js +1 -0
- package/dist/gui/glsl-2WUTP43R.js +1 -0
- package/dist/gui/gn-FLOS4RZF.js +1 -0
- package/dist/gui/gnuplot-AA3IX5VA.js +1 -0
- package/dist/gui/go-D4ZGPS2Z.js +1 -0
- package/dist/gui/graphql-XZVYVEOX.js +1 -0
- package/dist/gui/groovy-E5CINRXU.js +1 -0
- package/dist/gui/gruvbox-dark-hard-UFIAEKPP.js +1 -0
- package/dist/gui/{gruvbox-dark-medium-BELAJCDV.js → gruvbox-dark-medium-XK6AECTF.js} +1 -7
- package/dist/gui/gruvbox-dark-soft-WNTU4C4A.js +1 -0
- package/dist/gui/gruvbox-light-hard-VLLYGWMV.js +1 -0
- package/dist/gui/gruvbox-light-medium-MOKQOXML.js +1 -0
- package/dist/gui/gruvbox-light-soft-OVPAH42P.js +1 -0
- package/dist/gui/hack-R5BPE4XT.js +1 -0
- package/dist/gui/haml-F7BK2NAC.js +1 -0
- package/dist/gui/handlebars-TDZDKBFN.js +1 -0
- package/dist/gui/haskell-OMKSKXE4.js +1 -0
- package/dist/gui/haxe-DA2WYZGW.js +1 -0
- package/dist/gui/hcl-CRLVRE3Z.js +1 -0
- package/dist/gui/hjson-UIMUDXPE.js +1 -0
- package/dist/gui/hlsl-I7ZGIUMO.js +1 -0
- package/dist/gui/horizon-NQLSMOTK.js +1 -0
- package/dist/gui/horizon-bright-RLXCKKC2.js +1 -0
- package/dist/gui/houston-LOYTQEEC.js +1 -0
- package/dist/gui/html-7XII5ONP.js +1 -0
- package/dist/gui/html-derivative-JQOMEZ36.js +1 -0
- package/dist/gui/http-EJHR5COJ.js +1 -0
- package/dist/gui/hurl-AFBMX2SV.js +1 -0
- package/dist/gui/hxml-SPWPZW4Z.js +1 -0
- package/dist/gui/hy-GTUAPP6L.js +1 -0
- package/dist/gui/imba-PR2LWKPL.js +1 -0
- package/dist/gui/ini-KJTRFM25.js +1 -0
- package/dist/gui/java-DSZN5VJV.js +1 -0
- package/dist/gui/javascript-XR4WJT5N.js +1 -0
- package/dist/gui/jinja-ANXS2HAO.js +1 -0
- package/dist/gui/jison-QLTVNL3C.js +1 -0
- package/dist/gui/json-3EUJJ54W.js +1 -0
- package/dist/gui/json5-IDTK7YOE.js +1 -0
- package/dist/gui/jsonc-6ZTWASVR.js +1 -0
- package/dist/gui/jsonl-MLAJJYGB.js +1 -0
- package/dist/gui/jsonnet-R4IMWKFV.js +1 -0
- package/dist/gui/jssm-BZWTK76Y.js +1 -0
- package/dist/gui/jsx-TXRT3F4T.js +1 -0
- package/dist/gui/julia-BBWH3F3Q.js +1 -0
- package/dist/gui/just-NTMFF2RX.js +1 -0
- package/dist/gui/kanagawa-dragon-HEOKFLSM.js +1 -0
- package/dist/gui/kanagawa-lotus-FLUYKNAJ.js +1 -0
- package/dist/gui/kanagawa-wave-W5JS3SJB.js +1 -0
- package/dist/gui/kdl-JLCHZWOT.js +1 -0
- package/dist/gui/kotlin-3JSE5GFW.js +1 -0
- package/dist/gui/kusto-6X3HWIDS.js +1 -0
- package/dist/gui/laserwave-RYH62ULF.js +1 -0
- package/dist/gui/latex-DAN4LSSN.js +1 -0
- package/dist/gui/lean-WK3JB7KT.js +1 -0
- package/dist/gui/less-EARLTJNN.js +1 -0
- package/dist/gui/light-plus-5B5GHCAO.js +1 -0
- package/dist/gui/liquid-NGA53ZPS.js +1 -0
- package/dist/gui/llvm-J5EFVCQS.js +1 -0
- package/dist/gui/log-2G4LLVHC.js +1 -0
- package/dist/gui/logo-TCNRKRD5.js +1 -0
- package/dist/gui/lua-JIKWKGJV.js +1 -0
- package/dist/gui/luau-SFLPX4FF.js +1 -0
- package/dist/gui/main.js +1643 -78722
- package/dist/gui/make-NJO3L26C.js +1 -0
- package/dist/gui/markdown-33JM3RBU.js +1 -0
- package/dist/gui/marko-5E7LEGXI.js +1 -0
- package/dist/gui/material-theme-BENJVRUI.js +1 -0
- package/dist/gui/material-theme-darker-7UJLVDMH.js +1 -0
- package/dist/gui/material-theme-lighter-PPK5M2KX.js +1 -0
- package/dist/gui/material-theme-ocean-GSEYSNHR.js +1 -0
- package/dist/gui/material-theme-palenight-BT7M3Z7N.js +1 -0
- package/dist/gui/matlab-XHMB4W76.js +1 -0
- package/dist/gui/mdc-NGUCNP3J.js +1 -0
- package/dist/gui/mdx-XWES6DQN.js +1 -0
- package/dist/gui/mermaid-FU5XZ4UI.js +1 -0
- package/dist/gui/min-dark-M65IJXSI.js +1 -0
- package/dist/gui/min-light-6C5NEZVA.js +1 -0
- package/dist/gui/mipsasm-PZKYVJ7H.js +1 -0
- package/dist/gui/mojo-IHPQ75I5.js +1 -0
- package/dist/gui/monokai-JG2G5WZJ.js +1 -0
- package/dist/gui/moonbit-RKDBWPCI.js +1 -0
- package/dist/gui/move-7QARO2MW.js +1 -0
- package/dist/gui/narrat-ACZ2QBHY.js +1 -0
- package/dist/gui/nextflow-SE5ZBILO.js +1 -0
- package/dist/gui/nextflow-groovy-OUI4UFJZ.js +1 -0
- package/dist/gui/nginx-X4AEE2Y3.js +1 -0
- package/dist/gui/night-owl-O35XCMH2.js +1 -0
- package/dist/gui/night-owl-light-V2Y4RCYQ.js +1 -0
- package/dist/gui/nim-5SOHKETF.js +1 -0
- package/dist/gui/nix-X5MVXECB.js +1 -0
- package/dist/gui/nord-LP5RXKO4.js +1 -0
- package/dist/gui/nsis-4ITGWURL.js +1 -0
- package/dist/gui/nushell-ZFA4HPZK.js +1 -0
- package/dist/gui/objective-c-LNJ26AQV.js +1 -0
- package/dist/gui/objective-cpp-6MQLZISN.js +1 -0
- package/dist/gui/ocaml-T4K5GHXS.js +1 -0
- package/dist/gui/odin-6FP5C6CH.js +1 -0
- package/dist/gui/one-dark-pro-D45YYOSC.js +1 -0
- package/dist/gui/one-light-7SELK2HX.js +1 -0
- package/dist/gui/openscad-EW4KI2UZ.js +1 -0
- package/dist/gui/org-L7PJD5VW.js +1 -0
- package/dist/gui/pascal-RC4O2NCX.js +1 -0
- package/dist/gui/perl-7QWV5WJH.js +1 -0
- package/dist/gui/php-3P3VLQXF.js +1 -0
- package/dist/gui/pierre-dark-UUALILXQ.js +1 -0
- package/dist/gui/pierre-dark-protanopia-deuteranopia-GNBYHTF4.js +1 -0
- package/dist/gui/pierre-dark-soft-J5EIFRXM.js +1 -0
- package/dist/gui/pierre-dark-tritanopia-6YRJO27P.js +1 -0
- package/dist/gui/{pierre-dark-vibrant-74HELCEP.js → pierre-dark-vibrant-NJEA5K4W.js} +1 -7
- package/dist/gui/pierre-light-ZQTWM32A.js +1 -0
- package/dist/gui/pierre-light-protanopia-deuteranopia-FUEM3DXT.js +1 -0
- package/dist/gui/pierre-light-soft-TCQDDSNP.js +1 -0
- package/dist/gui/pierre-light-tritanopia-OV2PHN3L.js +1 -0
- package/dist/gui/pierre-light-vibrant-AZKXRX64.js +1 -0
- package/dist/gui/pkl-RPQFMJHD.js +1 -0
- package/dist/gui/plastic-PAFZF6UX.js +1 -0
- package/dist/gui/plsql-W3DB43CI.js +1 -0
- package/dist/gui/po-5BV5ST4S.js +1 -0
- package/dist/gui/poimandres-4AUR6LMN.js +1 -0
- package/dist/gui/polar-2A4DMGDX.js +1 -0
- package/dist/gui/postcss-TNHQ4NSC.js +1 -0
- package/dist/gui/powerquery-VUKZRFZR.js +1 -0
- package/dist/gui/powershell-TK6ME3LY.js +1 -0
- package/dist/gui/prisma-EI7DDMP7.js +1 -0
- package/dist/gui/prolog-AVYZOBBB.js +1 -0
- package/dist/gui/proto-24ZKYESH.js +1 -0
- package/dist/gui/pug-BBOBRMAQ.js +1 -0
- package/dist/gui/puppet-K3V25A6J.js +1 -0
- package/dist/gui/purescript-FOAG6MUG.js +1 -0
- package/dist/gui/python-RGDF5IZE.js +1 -0
- package/dist/gui/qml-XFYRCCU2.js +1 -0
- package/dist/gui/qmldir-25IWZ43Y.js +1 -0
- package/dist/gui/qss-3QVASW5Z.js +1 -0
- package/dist/gui/r-4SYQX3YB.js +1 -0
- package/dist/gui/racket-ZXK4SKKC.js +1 -0
- package/dist/gui/raku-QA35WOMY.js +1 -0
- package/dist/gui/razor-4TWVQHTU.js +1 -0
- package/dist/gui/rbs-3NEBMVOA.js +1 -0
- package/dist/gui/red-FHDCYAGC.js +1 -0
- package/dist/gui/reg-DDDCCL2S.js +1 -0
- package/dist/gui/regexp-WCMKSTB5.js +1 -0
- package/dist/gui/rel-UZZH4IDH.js +1 -0
- package/dist/gui/riscv-ZLG5M6ET.js +1 -0
- package/dist/gui/ron-CJ5PF6JZ.js +1 -0
- package/dist/gui/rose-pine-7HOL5AMQ.js +1 -0
- package/dist/gui/rose-pine-dawn-ILHX5FOL.js +1 -0
- package/dist/gui/rose-pine-moon-KLXMC5MV.js +1 -0
- package/dist/gui/rosmsg-G5A6MUGH.js +1 -0
- package/dist/gui/rst-BOZJLDXS.js +1 -0
- package/dist/gui/ruby-ERSYBX2A.js +1 -0
- package/dist/gui/rust-D6W4ZLZ4.js +1 -0
- package/dist/gui/sas-MEFFXSOG.js +1 -0
- package/dist/gui/sass-WKJBO4S6.js +1 -0
- package/dist/gui/scala-URQSYH5Q.js +1 -0
- package/dist/gui/scheme-X3MMQWU4.js +1 -0
- package/dist/gui/scss-WPGS5D6U.js +1 -0
- package/dist/gui/sdbl-II465DZK.js +1 -0
- package/dist/gui/shaderlab-UOD53IUD.js +1 -0
- package/dist/gui/shellscript-K2EAVF55.js +1 -0
- package/dist/gui/shellsession-4BNORSYP.js +1 -0
- package/dist/gui/slack-dark-PKA4XJM5.js +1 -0
- package/dist/gui/slack-ochin-M6NLSFYN.js +1 -0
- package/dist/gui/smalltalk-6HWUSNWG.js +1 -0
- package/dist/gui/smithy-3NE7ZMNJ.js +1 -0
- package/dist/gui/snazzy-light-XP7LR76H.js +1 -0
- package/dist/gui/solarized-dark-OZQGSSTI.js +1 -0
- package/dist/gui/solarized-light-FIEQXCCQ.js +1 -0
- package/dist/gui/solidity-EJNFJ37K.js +1 -0
- package/dist/gui/soy-MZEYLXUU.js +1 -0
- package/dist/gui/sparql-ILD7IWLS.js +1 -0
- package/dist/gui/splunk-FMTEVKBA.js +1 -0
- package/dist/gui/sql-2KVUOGK2.js +1 -0
- package/dist/gui/ssh-config-44SOGF2N.js +1 -0
- package/dist/gui/stata-YMFQSMUD.js +1 -0
- package/dist/gui/stylus-A5FIEREC.js +1 -0
- package/dist/gui/surrealql-VKFTSBUL.js +1 -0
- package/dist/gui/svelte-H4D3PMRS.js +1 -0
- package/dist/gui/swift-N6UUV4WM.js +1 -0
- package/dist/gui/synthwave-84-PD5BOFK2.js +1 -0
- package/dist/gui/system-verilog-NNY6GQOQ.js +1 -0
- package/dist/gui/systemd-RVODVMDH.js +1 -0
- package/dist/gui/talonscript-ENLOEX56.js +1 -0
- package/dist/gui/tasl-GC4YOF35.js +1 -0
- package/dist/gui/tcl-UAQKRIMQ.js +1 -0
- package/dist/gui/templ-3SR7WDHA.js +1 -0
- package/dist/gui/terraform-WWPSCXCZ.js +1 -0
- package/dist/gui/tex-7CMEVGPS.js +1 -0
- package/dist/gui/tokyo-night-K7YYNJI2.js +1 -0
- package/dist/gui/toml-EV2WQVY5.js +1 -0
- package/dist/gui/ts-tags-UEGU4VKD.js +1 -0
- package/dist/gui/tsv-NTCI55EL.js +1 -0
- package/dist/gui/tsx-CW7A3IBI.js +1 -0
- package/dist/gui/turtle-LR4PTJRE.js +1 -0
- package/dist/gui/twig-VLD6HZP7.js +1 -0
- package/dist/gui/typescript-BXBSQ4TF.js +1 -0
- package/dist/gui/typespec-SPATFDEV.js +1 -0
- package/dist/gui/typst-IBXX7HGO.js +1 -0
- package/dist/gui/v-CNCWXBH3.js +1 -0
- package/dist/gui/vala-COQFDBCD.js +1 -0
- package/dist/gui/vb-ZKUVQ2IB.js +1 -0
- package/dist/gui/verilog-AE42CTAL.js +1 -0
- package/dist/gui/vesper-G6AAATZ5.js +1 -0
- package/dist/gui/vhdl-TUUYGSZC.js +1 -0
- package/dist/gui/viml-NJSEO5HU.js +1 -0
- package/dist/gui/vitesse-black-2JMSBH2Y.js +1 -0
- package/dist/gui/vitesse-dark-MZIINQYJ.js +1 -0
- package/dist/gui/vitesse-light-PUU6ALJN.js +1 -0
- package/dist/gui/vue-G3BU3ZXC.js +1 -0
- package/dist/gui/vue-html-JVIPDA3J.js +1 -0
- package/dist/gui/vue-vine-2J4EFZYJ.js +1 -0
- package/dist/gui/vyper-X5IIQBLQ.js +1 -0
- package/dist/gui/wasm-PBY6OWX6.js +1 -0
- package/dist/gui/wasm-RWK3SGH4.js +1 -0
- package/dist/gui/wenyan-SVN34UX2.js +1 -0
- package/dist/gui/wgsl-JT3SSBOT.js +1 -0
- package/dist/gui/wikitext-ZINAKQJN.js +1 -0
- package/dist/gui/wit-IPHVVCU7.js +1 -0
- package/dist/gui/wolfram-BM2HK6J7.js +1 -0
- package/dist/gui/xml-OPIMP5GR.js +1 -0
- package/dist/gui/xsl-IQGV6DOU.js +1 -0
- package/dist/gui/yaml-P37LLXQD.js +1 -0
- package/dist/gui/zenscript-3FWIWZXX.js +1 -0
- package/dist/gui/zig-3HPW2CFC.js +1 -0
- package/dist/index.js +99 -89
- package/dist/mcp.js +91 -81
- package/package.json +9 -4
- package/readme.md +2 -1
- package/dist/gui/abap-QUGURUBX.js +0 -10
- package/dist/gui/actionscript-3-3B35LJ6O.js +0 -10
- package/dist/gui/ada-UZZSP2VN.js +0 -10
- package/dist/gui/ahk-AV2XNNVZ.js +0 -10
- package/dist/gui/ahk2-KEAF4H55.js +0 -10
- package/dist/gui/andromeeda-2GR76PYB.js +0 -7
- package/dist/gui/angular-html-TCKFTSN3.js +0 -10
- package/dist/gui/angular-ts-OWXT6U2F.js +0 -44
- package/dist/gui/apache-K3WQQUQC.js +0 -10
- package/dist/gui/apex-76A7OZCW.js +0 -10
- package/dist/gui/apl-QUJH6REI.js +0 -31
- package/dist/gui/applescript-DYSSLNAH.js +0 -10
- package/dist/gui/ara-JBUHYAMO.js +0 -10
- package/dist/gui/asciidoc-GVSAY7ID.js +0 -10
- package/dist/gui/asm-7T5K47RE.js +0 -10
- package/dist/gui/astro-ROBUIKHM.js +0 -34
- package/dist/gui/aurora-x-CCBQ7SH7.js +0 -7
- package/dist/gui/awk-X3RXUDTD.js +0 -10
- package/dist/gui/ayu-dark-PIU367MT.js +0 -7
- package/dist/gui/ayu-light-Y4QUM4BU.js +0 -7
- package/dist/gui/ayu-mirage-LSLYYZ6M.js +0 -7
- package/dist/gui/ballerina-X5OCGDT7.js +0 -10
- package/dist/gui/bat-6N655JFC.js +0 -7
- package/dist/gui/beancount-737SRZDB.js +0 -10
- package/dist/gui/berry-27ZIFCK5.js +0 -10
- package/dist/gui/bibtex-PCJ2P64N.js +0 -7
- package/dist/gui/bicep-KZTPGRFB.js +0 -10
- package/dist/gui/bird2-4JCG5OZF.js +0 -10
- package/dist/gui/blade-TDVDX7TO.js +0 -39
- package/dist/gui/bsl-35Z2FTGV.js +0 -14
- package/dist/gui/c-7CKX2DSI.js +0 -7
- package/dist/gui/c3-DR3DV77K.js +0 -10
- package/dist/gui/cadence-OYNPDM3M.js +0 -10
- package/dist/gui/cairo-COXU6RBH.js +0 -14
- package/dist/gui/catppuccin-frappe-P2B2FXCB.js +0 -7
- package/dist/gui/catppuccin-latte-AIEPHNSB.js +0 -7
- package/dist/gui/catppuccin-macchiato-CLAJLZV7.js +0 -7
- package/dist/gui/catppuccin-mocha-DJZW5ULN.js +0 -7
- package/dist/gui/chapel-5CK5YMSY.js +0 -14
- package/dist/gui/chunk-2IVRELJI.js +0 -9
- package/dist/gui/chunk-2JKKPALB.js +0 -9
- package/dist/gui/chunk-2PUAXP2T.js +0 -38
- package/dist/gui/chunk-2QHMH6QB.js +0 -9
- package/dist/gui/chunk-2XE676KO.js +0 -9
- package/dist/gui/chunk-2YCLQAMI.js +0 -9
- package/dist/gui/chunk-3567J5D4.js +0 -14
- package/dist/gui/chunk-3BGADQKG.js +0 -9
- package/dist/gui/chunk-45O7TJOW.js +0 -9
- package/dist/gui/chunk-4DOSCG4B.js +0 -26
- package/dist/gui/chunk-4IZ5IRSO.js +0 -9
- package/dist/gui/chunk-5TDK5Y5S.js +0 -9
- package/dist/gui/chunk-67HINKFV.js +0 -9
- package/dist/gui/chunk-6TG6XZZD.js +0 -14
- package/dist/gui/chunk-76C5RMV7.js +0 -9
- package/dist/gui/chunk-7CB7TITS.js +0 -9
- package/dist/gui/chunk-7YLAFQQ7.js +0 -27
- package/dist/gui/chunk-AZIN3OHL.js +0 -14
- package/dist/gui/chunk-BW7B23CF.js +0 -9
- package/dist/gui/chunk-C774R7J7.js +0 -26
- package/dist/gui/chunk-CB7BCEL4.js +0 -9
- package/dist/gui/chunk-CYKSS2Y7.js +0 -9
- package/dist/gui/chunk-DCJCRTKO.js +0 -14
- package/dist/gui/chunk-DKOWBU7G.js +0 -9
- package/dist/gui/chunk-DWAALHPK.js +0 -9
- package/dist/gui/chunk-EZITVRXA.js +0 -9
- package/dist/gui/chunk-FAHLSHNR.js +0 -9
- package/dist/gui/chunk-FALFVRCV.js +0 -14
- package/dist/gui/chunk-GL2Q3EDW.js +0 -9
- package/dist/gui/chunk-H66FQEKW.js +0 -9
- package/dist/gui/chunk-HGZA2JNF.js +0 -9
- package/dist/gui/chunk-HQG63PQL.js +0 -9
- package/dist/gui/chunk-HSNCWORT.js +0 -9
- package/dist/gui/chunk-IJCSV645.js +0 -14
- package/dist/gui/chunk-ILHZPDJC.js +0 -9
- package/dist/gui/chunk-IYFWWBRC.js +0 -34
- package/dist/gui/chunk-J6IKJJ34.js +0 -34
- package/dist/gui/chunk-JBVY6KB5.js +0 -9
- package/dist/gui/chunk-JJHUDSW7.js +0 -9
- package/dist/gui/chunk-JLIS73DH.js +0 -14
- package/dist/gui/chunk-JO5JNDTX.js +0 -9
- package/dist/gui/chunk-JV223PVL.js +0 -14
- package/dist/gui/chunk-JVCCJA2A.js +0 -30
- package/dist/gui/chunk-KGH6JTBL.js +0 -9
- package/dist/gui/chunk-KM2QKTEE.js +0 -50
- package/dist/gui/chunk-KSXADT4K.js +0 -9
- package/dist/gui/chunk-MT4FGOLU.js +0 -9
- package/dist/gui/chunk-NAD33WBI.js +0 -14
- package/dist/gui/chunk-NE25QJUZ.js +0 -9
- package/dist/gui/chunk-OII47WE4.js +0 -14
- package/dist/gui/chunk-OWEPHUF3.js +0 -14
- package/dist/gui/chunk-Q2AHPUVI.js +0 -9
- package/dist/gui/chunk-Q567VMM5.js +0 -9
- package/dist/gui/chunk-QFOAKHDY.js +0 -9
- package/dist/gui/chunk-QH2T6GYZ.js +0 -9
- package/dist/gui/chunk-QU263C3I.js +0 -9
- package/dist/gui/chunk-QYOJGBVM.js +0 -14
- package/dist/gui/chunk-R27EWKMH.js +0 -58
- package/dist/gui/chunk-RW4VQAW5.js +0 -18
- package/dist/gui/chunk-S7GWCO5B.js +0 -9
- package/dist/gui/chunk-SBETFYFF.js +0 -30
- package/dist/gui/chunk-SF5VS2XA.js +0 -9
- package/dist/gui/chunk-SZ2AIRR5.js +0 -9
- package/dist/gui/chunk-TKLN6WSC.js +0 -9
- package/dist/gui/chunk-TS3VPCJT.js +0 -9
- package/dist/gui/chunk-UUL2FFKC.js +0 -53
- package/dist/gui/chunk-VB3O6QM4.js +0 -9
- package/dist/gui/chunk-VEW77XHD.js +0 -9
- package/dist/gui/chunk-VVHT2QDI.js +0 -14
- package/dist/gui/chunk-WAWKOXXW.js +0 -18
- package/dist/gui/chunk-WBGGZ2J4.js +0 -9
- package/dist/gui/chunk-WC4BNZJP.js +0 -9
- package/dist/gui/chunk-XOMTOLBK.js +0 -9
- package/dist/gui/chunk-YBPIMBI6.js +0 -9
- package/dist/gui/chunk-YCL6DOP5.js +0 -9
- package/dist/gui/chunk-YJV35WLF.js +0 -14
- package/dist/gui/chunk-YOOITCA2.js +0 -22
- package/dist/gui/chunk-YWGUZU7U.js +0 -9
- package/dist/gui/chunk-YXIK6PVL.js +0 -9
- package/dist/gui/chunk-ZMZROCQO.js +0 -9
- package/dist/gui/clarity-X6Y4EF32.js +0 -10
- package/dist/gui/clojure-HWHJFZBF.js +0 -7
- package/dist/gui/cmake-4WVDKLXE.js +0 -7
- package/dist/gui/cobol-BK36TVIL.js +0 -20
- package/dist/gui/codeowners-PKXUEH4G.js +0 -10
- package/dist/gui/codeql-GSSNZAAP.js +0 -10
- package/dist/gui/coffee-CGHHEFIM.js +0 -8
- package/dist/gui/common-lisp-V4DD5MQE.js +0 -10
- package/dist/gui/coq-QVWLCVBB.js +0 -10
- package/dist/gui/cpp-KAUF3RSB.js +0 -10
- package/dist/gui/crystal-7TGOAT76.js +0 -34
- package/dist/gui/csharp-RRPDDXD7.js +0 -7
- package/dist/gui/css-S4XR6RYL.js +0 -7
- package/dist/gui/csv-ZNGJRB22.js +0 -7
- package/dist/gui/cue-7HOXZRS4.js +0 -10
- package/dist/gui/cypher-EAUAMJM6.js +0 -10
- package/dist/gui/d-CBA7NL6B.js +0 -10
- package/dist/gui/dark-plus-BOB45KCW.js +0 -7
- package/dist/gui/dart-MZSRF3IM.js +0 -7
- package/dist/gui/dax-Q4BTRBTA.js +0 -10
- package/dist/gui/desktop-NKAUWTGR.js +0 -10
- package/dist/gui/diff-RVUP6GV7.js +0 -7
- package/dist/gui/docker-KGDTLYEN.js +0 -7
- package/dist/gui/dotenv-5YOSIPZS.js +0 -10
- package/dist/gui/dracula-F56RSW6N.js +0 -7
- package/dist/gui/dracula-soft-CV5NUT6A.js +0 -7
- package/dist/gui/dream-maker-RGHMRX3B.js +0 -10
- package/dist/gui/edge-R66O24VV.js +0 -24
- package/dist/gui/elixir-5LJ2OUDN.js +0 -10
- package/dist/gui/elm-UWVV5ID7.js +0 -15
- package/dist/gui/emacs-lisp-TAO5U74P.js +0 -10
- package/dist/gui/erb-VBZVG65V.js +0 -35
- package/dist/gui/erlang-NLTHURFZ.js +0 -8
- package/dist/gui/everforest-dark-JBR4GKJA.js +0 -7
- package/dist/gui/everforest-light-AIUWRSLR.js +0 -7
- package/dist/gui/fennel-U2PEW23D.js +0 -10
- package/dist/gui/fish-KA4MOTTR.js +0 -10
- package/dist/gui/fluent-TC32ABGF.js +0 -10
- package/dist/gui/fortran-fixed-form-HMHOKX2P.js +0 -14
- package/dist/gui/fortran-free-form-T5IDESEJ.js +0 -7
- package/dist/gui/fsharp-QTHVHR6A.js +0 -8
- package/dist/gui/gdresource-ANDGJRDE.js +0 -18
- package/dist/gui/gdscript-2MXOLWT4.js +0 -7
- package/dist/gui/gdshader-RPDJURLG.js +0 -7
- package/dist/gui/genie-KQGSIM6L.js +0 -10
- package/dist/gui/gherkin-UU7PIT6E.js +0 -10
- package/dist/gui/git-commit-2OSO66MB.js +0 -8
- package/dist/gui/git-rebase-QIB3QI3O.js +0 -8
- package/dist/gui/github-dark-H5MJU2XK.js +0 -7
- package/dist/gui/github-dark-dimmed-UMS2CKX4.js +0 -7
- package/dist/gui/github-dark-high-contrast-N7ADHDRY.js +0 -7
- package/dist/gui/github-light-L3SBY5N4.js +0 -7
- package/dist/gui/github-light-default-N7QH7CFJ.js +0 -7
- package/dist/gui/github-light-high-contrast-2RMTNJOX.js +0 -7
- package/dist/gui/gleam-MB2OP4K4.js +0 -10
- package/dist/gui/glimmer-js-YJIW2B6M.js +0 -26
- package/dist/gui/glimmer-ts-RBWTLTMH.js +0 -26
- package/dist/gui/glsl-F7QZR37K.js +0 -8
- package/dist/gui/gn-F5BIWANZ.js +0 -10
- package/dist/gui/gnuplot-5K7Z5OR2.js +0 -10
- package/dist/gui/go-C26CLWJG.js +0 -7
- package/dist/gui/graphql-LOUCQJXE.js +0 -11
- package/dist/gui/groovy-DVSWXLFJ.js +0 -7
- package/dist/gui/gruvbox-dark-hard-WCNUL35F.js +0 -7
- package/dist/gui/gruvbox-dark-soft-DA4S6ZCG.js +0 -7
- package/dist/gui/gruvbox-light-hard-G3DA2CVN.js +0 -7
- package/dist/gui/gruvbox-light-medium-XC4P77WY.js +0 -7
- package/dist/gui/gruvbox-light-soft-AXFRXVRJ.js +0 -7
- package/dist/gui/hack-7E22AMLX.js +0 -20
- package/dist/gui/haml-DLYDG7TX.js +0 -9
- package/dist/gui/handlebars-EXMYBU7Q.js +0 -11
- package/dist/gui/haskell-PZFDAWUI.js +0 -10
- package/dist/gui/haxe-VZSRFGDC.js +0 -7
- package/dist/gui/hcl-NAPQ56UJ.js +0 -10
- package/dist/gui/hjson-7YO44GAE.js +0 -10
- package/dist/gui/hlsl-P6H2KE4L.js +0 -7
- package/dist/gui/horizon-ABEUFKCJ.js +0 -7
- package/dist/gui/horizon-bright-4IF4JCRZ.js +0 -7
- package/dist/gui/houston-ACBQLVIG.js +0 -7
- package/dist/gui/html-37GWH2QE.js +0 -9
- package/dist/gui/html-derivative-TSWK6LSQ.js +0 -10
- package/dist/gui/http-MBDMTHEC.js +0 -31
- package/dist/gui/hurl-WAATKOCB.js +0 -27
- package/dist/gui/hxml-LG2R5CDK.js +0 -14
- package/dist/gui/hy-4MDQ72ZR.js +0 -10
- package/dist/gui/imba-AMDQ2OVM.js +0 -10
- package/dist/gui/ini-BSRRTTCB.js +0 -7
- package/dist/gui/java-VPDWWQCN.js +0 -7
- package/dist/gui/javascript-YSK6TDHD.js +0 -7
- package/dist/gui/jinja-PJIERUUD.js +0 -23
- package/dist/gui/jison-6R6YZ4D3.js +0 -14
- package/dist/gui/json-CDBUD4K4.js +0 -7
- package/dist/gui/json5-GQ5EPJPN.js +0 -10
- package/dist/gui/jsonc-EUK6K7BC.js +0 -7
- package/dist/gui/jsonl-AZZ6LVAP.js +0 -10
- package/dist/gui/jsonnet-TG4672OU.js +0 -10
- package/dist/gui/jssm-POLM2BGU.js +0 -10
- package/dist/gui/jsx-HNQJHG7G.js +0 -7
- package/dist/gui/julia-EQ4JLFSR.js +0 -15
- package/dist/gui/just-3SVPXB4P.js +0 -49
- package/dist/gui/kanagawa-dragon-4QPQEBJF.js +0 -7
- package/dist/gui/kanagawa-lotus-E2SVDYBP.js +0 -7
- package/dist/gui/kanagawa-wave-ZAYNGKIP.js +0 -7
- package/dist/gui/kdl-GX2QLRI3.js +0 -10
- package/dist/gui/kotlin-GKENNT4G.js +0 -10
- package/dist/gui/kusto-YE5J7WH7.js +0 -10
- package/dist/gui/laserwave-FEC67QFP.js +0 -7
- package/dist/gui/latex-AULDPOF3.js +0 -9
- package/dist/gui/lean-WU3KGKFX.js +0 -10
- package/dist/gui/less-G3PHK6XJ.js +0 -7
- package/dist/gui/light-plus-IWZ7H7K5.js +0 -7
- package/dist/gui/liquid-GRGQYWEM.js +0 -26
- package/dist/gui/llvm-GZMF4RGX.js +0 -10
- package/dist/gui/log-IVFPTJO5.js +0 -7
- package/dist/gui/logo-QKNO4KB4.js +0 -10
- package/dist/gui/lua-2SFYRRVQ.js +0 -8
- package/dist/gui/luau-7LGUQMID.js +0 -10
- package/dist/gui/make-6IBN4RHX.js +0 -7
- package/dist/gui/markdown-RGBXB5KM.js +0 -7
- package/dist/gui/marko-6ENW4ITK.js +0 -26
- package/dist/gui/material-theme-JOKMNPZD.js +0 -7
- package/dist/gui/material-theme-darker-7MTKLCCM.js +0 -7
- package/dist/gui/material-theme-lighter-VOBCBDGF.js +0 -7
- package/dist/gui/material-theme-ocean-HIZIQ6ZI.js +0 -7
- package/dist/gui/material-theme-palenight-MDKGMWOS.js +0 -7
- package/dist/gui/matlab-NVRQWPT4.js +0 -10
- package/dist/gui/mdc-3KJ5Z26I.js +0 -25
- package/dist/gui/mdx-TUFOPE2U.js +0 -10
- package/dist/gui/mermaid-2ELHPTEI.js +0 -10
- package/dist/gui/min-dark-H6FRUPEW.js +0 -7
- package/dist/gui/min-light-AAKNJKN7.js +0 -7
- package/dist/gui/mipsasm-CMTR7652.js +0 -10
- package/dist/gui/mojo-QON2ZHI5.js +0 -10
- package/dist/gui/monokai-4IQYQQA3.js +0 -7
- package/dist/gui/moonbit-YXIFXWNL.js +0 -10
- package/dist/gui/move-5AVESP7D.js +0 -10
- package/dist/gui/narrat-P67ZRVLF.js +0 -10
- package/dist/gui/nextflow-IA3AKAOV.js +0 -14
- package/dist/gui/nextflow-groovy-3TZGSHZN.js +0 -7
- package/dist/gui/nginx-A674IMF2.js +0 -15
- package/dist/gui/night-owl-YKMG5AEG.js +0 -7
- package/dist/gui/night-owl-light-FK52JHEJ.js +0 -7
- package/dist/gui/nim-TNAHEHQE.js +0 -15
- package/dist/gui/nix-PKII6ZAX.js +0 -17
- package/dist/gui/nord-UMPZ4MDR.js +0 -7
- package/dist/gui/nsis-RLNIMWJ4.js +0 -10
- package/dist/gui/nushell-XCKRAB5V.js +0 -10
- package/dist/gui/objective-c-VW6IYVZR.js +0 -7
- package/dist/gui/objective-cpp-A6HOVYIZ.js +0 -10
- package/dist/gui/ocaml-LEW2N47R.js +0 -7
- package/dist/gui/odin-ZYNZP2Z7.js +0 -10
- package/dist/gui/one-dark-pro-7ZD2R4C3.js +0 -7
- package/dist/gui/one-light-S6GW5JPC.js +0 -7
- package/dist/gui/openscad-S55J35RH.js +0 -10
- package/dist/gui/org-HWNUVJ3K.js +0 -203
- package/dist/gui/pascal-PQJYR7AK.js +0 -10
- package/dist/gui/perl-NRCSCL2T.js +0 -13
- package/dist/gui/php-7FKD7NQ6.js +0 -14
- package/dist/gui/pierre-dark-2VX7FTVH.js +0 -7
- package/dist/gui/pierre-dark-protanopia-deuteranopia-IWPDHMFY.js +0 -7
- package/dist/gui/pierre-dark-soft-PBZEND7C.js +0 -7
- package/dist/gui/pierre-dark-tritanopia-H4RGFNEU.js +0 -7
- package/dist/gui/pierre-light-2CTJ4CSM.js +0 -7
- package/dist/gui/pierre-light-protanopia-deuteranopia-SGQCEX2P.js +0 -7
- package/dist/gui/pierre-light-soft-FSLVXWQU.js +0 -7
- package/dist/gui/pierre-light-tritanopia-YDWTX7OC.js +0 -7
- package/dist/gui/pierre-light-vibrant-CBHQI6SK.js +0 -7
- package/dist/gui/pkl-BBS5JDCX.js +0 -10
- package/dist/gui/plastic-24BUHBC6.js +0 -7
- package/dist/gui/plsql-WTYXI2RI.js +0 -10
- package/dist/gui/po-GLVRZSLC.js +0 -10
- package/dist/gui/poimandres-6BCLQCCV.js +0 -7
- package/dist/gui/polar-HQ7LUSDG.js +0 -10
- package/dist/gui/postcss-5ILUXDAM.js +0 -7
- package/dist/gui/powerquery-T2DA4K5Q.js +0 -10
- package/dist/gui/powershell-YAEHZVQU.js +0 -7
- package/dist/gui/prisma-UYCP5C7X.js +0 -10
- package/dist/gui/prolog-JLW5JO7Q.js +0 -10
- package/dist/gui/proto-XPAGGVMR.js +0 -10
- package/dist/gui/pug-4D7KLPNZ.js +0 -10
- package/dist/gui/puppet-CAH3DWTQ.js +0 -10
- package/dist/gui/purescript-TY5CZSBG.js +0 -10
- package/dist/gui/python-AJWUUEXZ.js +0 -7
- package/dist/gui/qml-3P7XGIWB.js +0 -14
- package/dist/gui/qmldir-MU3RYVKI.js +0 -10
- package/dist/gui/qss-GQ3SQE63.js +0 -10
- package/dist/gui/r-MZS2GKC3.js +0 -7
- package/dist/gui/racket-EJOVFY7Q.js +0 -10
- package/dist/gui/raku-N7M6AP4Z.js +0 -7
- package/dist/gui/razor-XMDVCJ7X.js +0 -20
- package/dist/gui/rbs-3XJPBJS3.js +0 -10
- package/dist/gui/red-DQ454N4M.js +0 -7
- package/dist/gui/reg-FCSLOXMU.js +0 -10
- package/dist/gui/regexp-OU4NYHVA.js +0 -7
- package/dist/gui/rel-GPRT753E.js +0 -10
- package/dist/gui/riscv-IO6X3OUS.js +0 -10
- package/dist/gui/ron-LAUU7JCT.js +0 -10
- package/dist/gui/rose-pine-FGMQPAXN.js +0 -7
- package/dist/gui/rose-pine-dawn-XZHKMJMS.js +0 -7
- package/dist/gui/rose-pine-moon-44RDFYAS.js +0 -7
- package/dist/gui/rosmsg-HKG52NBT.js +0 -10
- package/dist/gui/rst-PIASADIQ.js +0 -56
- package/dist/gui/ruby-Z6MF5JYI.js +0 -25
- package/dist/gui/rust-C45CB5ZB.js +0 -7
- package/dist/gui/sas-EOAR3TJ3.js +0 -14
- package/dist/gui/sass-KEOLMOQJ.js +0 -10
- package/dist/gui/scala-O3LM5FKD.js +0 -7
- package/dist/gui/scheme-NGQ2H462.js +0 -10
- package/dist/gui/scss-WAYO2YAL.js +0 -8
- package/dist/gui/sdbl-G5J5BQHJ.js +0 -7
- package/dist/gui/shaderlab-XU7645J6.js +0 -14
- package/dist/gui/shellscript-QPJOW65X.js +0 -7
- package/dist/gui/shellsession-LCJMCYFU.js +0 -14
- package/dist/gui/slack-dark-VD234CKF.js +0 -7
- package/dist/gui/slack-ochin-QY7RWW52.js +0 -7
- package/dist/gui/smalltalk-LMQWJTYB.js +0 -10
- package/dist/gui/smithy-XKBQ5TXG.js +0 -10
- package/dist/gui/snazzy-light-7DJMADZF.js +0 -7
- package/dist/gui/solarized-dark-PXF6MHWO.js +0 -7
- package/dist/gui/solarized-light-XQPVPM7L.js +0 -7
- package/dist/gui/solidity-67AFBEYM.js +0 -10
- package/dist/gui/soy-C25UWDWI.js +0 -16
- package/dist/gui/sparql-GG32TI6Q.js +0 -14
- package/dist/gui/splunk-Q7OG3S6M.js +0 -10
- package/dist/gui/sql-6F3HA23R.js +0 -7
- package/dist/gui/ssh-config-EK5IZW3T.js +0 -10
- package/dist/gui/stata-54FRWEK5.js +0 -14
- package/dist/gui/stylus-TKKFQVIW.js +0 -7
- package/dist/gui/surrealql-2O6L6FVR.js +0 -14
- package/dist/gui/svelte-RQW3BSQN.js +0 -26
- package/dist/gui/swift-XM6BATYX.js +0 -7
- package/dist/gui/synthwave-84-T7XO3VP6.js +0 -7
- package/dist/gui/system-verilog-5A7OWIS7.js +0 -7
- package/dist/gui/systemd-YG2GIELU.js +0 -10
- package/dist/gui/talonscript-PIYOSW4G.js +0 -10
- package/dist/gui/tasl-LSN6MJU3.js +0 -10
- package/dist/gui/tcl-QL7GI7GB.js +0 -10
- package/dist/gui/templ-LLH4QDAT.js +0 -22
- package/dist/gui/terraform-7ESBXUP7.js +0 -10
- package/dist/gui/tex-X4LXVCV7.js +0 -8
- package/dist/gui/tokyo-night-FBILIEZB.js +0 -7
- package/dist/gui/toml-ZPLDESJA.js +0 -10
- package/dist/gui/ts-tags-HZGRWBOR.js +0 -81
- package/dist/gui/tsv-DFQOAT3Y.js +0 -10
- package/dist/gui/tsx-HKUFCS2K.js +0 -7
- package/dist/gui/turtle-JNLUZA5M.js +0 -7
- package/dist/gui/twig-OEKA6N6I.js +0 -30
- package/dist/gui/typescript-TJKT3IXK.js +0 -7
- package/dist/gui/typespec-LYVFB2R5.js +0 -10
- package/dist/gui/typst-NRT4OQOK.js +0 -243
- package/dist/gui/v-Y4OWOLQI.js +0 -10
- package/dist/gui/vala-MD66CNI7.js +0 -10
- package/dist/gui/vb-CPQUJ3PO.js +0 -7
- package/dist/gui/verilog-ECIZCOEU.js +0 -7
- package/dist/gui/vesper-JUVJQUCS.js +0 -7
- package/dist/gui/vhdl-QJIATVDS.js +0 -10
- package/dist/gui/viml-SAWLYNSC.js +0 -10
- package/dist/gui/vitesse-black-44DSWBPL.js +0 -7
- package/dist/gui/vitesse-dark-ZB4X3SXC.js +0 -7
- package/dist/gui/vitesse-light-T4PKXN2B.js +0 -7
- package/dist/gui/vue-YZTXYZUC.js +0 -63
- package/dist/gui/vue-html-3OB5SOZU.js +0 -14
- package/dist/gui/vue-vine-ZQNB45F6.js +0 -34
- package/dist/gui/vyper-545OELAD.js +0 -10
- package/dist/gui/wasm-6SXLSWDK.js +0 -13
- package/dist/gui/wasm-UNG3ITYZ.js +0 -10
- package/dist/gui/wenyan-6MAMINLZ.js +0 -10
- package/dist/gui/wgsl-GTGWOC2E.js +0 -10
- package/dist/gui/wikitext-X3KHSBD4.js +0 -10
- package/dist/gui/wit-RN2FK5B5.js +0 -10
- package/dist/gui/wolfram-X3KENW2V.js +0 -10
- package/dist/gui/xml-Y333D7KT.js +0 -8
- package/dist/gui/xsl-ZBX7NBWE.js +0 -9
- package/dist/gui/yaml-HXOTARZF.js +0 -7
- package/dist/gui/zenscript-UJ7J7IFX.js +0 -10
- package/dist/gui/zig-6J4JS6G3.js +0 -7
package/dist/index.js
CHANGED
|
@@ -1,106 +1,116 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
`,"utf8"),u("Created project.json",null)}catch(o){return
|
|
4
|
-
`);return i===-1?"":s.slice(i+1)}finally{
|
|
5
|
-
`);if(n[n.length-1]===""&&n.pop(),t<=
|
|
2
|
+
import cn from"chalk";import{render as $M}from"ink";import UM from"meow";import jM from"react";import Vb from"chalk";import Vx from"node:crypto";var Qn={Success:"success",Fail:"fail"},c=e=>({status:Qn.Fail,message:e,value:null}),u=(e,t)=>({status:Qn.Success,message:e,value:t}),a=e=>e.status==="fail",be=e=>e.status==="success";var kn="EPIQ_USER_NAME",Li="EPIQ_USER_ID",ym="0123456789ABCDEFGHJKMNPQRSTVWXYZ",zx=26,Yl=80,Xl=e=>/^[0-9A-HJKMNP-TV-Z]{26}$/.test(e),ki=e=>e.trim().length>0&&e.length<=Yl,ao=e=>e.trim().toLowerCase(),Kx=e=>{let t=Vx.createHash("sha256").update(`epiq:actor:${ao(e)}`).digest(),n="";for(let r=0;r<zx;r++)n+=ym[(t[r]??0)%ym.length];return n},lo=(e,t=process.env)=>{let n=(t[kn]??"").trim(),r=(t[Li]??"").trim();return n?ki(n)?!r&&e.userId&&e.userName&&ao(e.userName)===ao(n)?u("Actor override names the configured user",{userId:e.userId,userName:e.userName}):r&&!Xl(r)?c(`${Li} must be 26 characters of Crockford base32`):r&&e.userId&&r===e.userId?c(`${Li} is the configured user's own id; using it under a different name would rename them on the board`):u("Resolved actor from environment",{userId:r||Kx(n),userName:r?n:ao(n)}):c(`${kn} must be 1-${Yl} characters of text`):r?c(`${Li} is set without ${kn}`):u("No actor override",null)},Jl=(e,t,n=process.env)=>{let r=e.trim();if(!ki(r))return c(`${t} must be 1-${Yl} characters of text`);let o=(n[kn]??"").trim();return o&&ao(o)!==ao(r)?c(`${t} names ${r}, but ${kn} names ${o}`):(o||(n[kn]=r),u("Applied actor name argument",o||r))};import NI from"node:path";import{z as Yt}from"zod";var co=e=>{let t=typeof e=="number"?e:Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<3e3||t>864e5?null:t},uo=e=>e==null||!Number.isFinite(e)?1e4:Math.min(864e5,Math.max(1,e));import us from"node:fs";import mn from"node:path";import Zn from"node:fs";import It from"node:path";import ss from"node:fs";import{ulid as qx}from"ulid";import{z as Di}from"zod";var Yx="__epiq_state__",Xx=Di.object({projectId:Di.string().min(1),stateBranch:Di.string().min(1),createdAt:Di.iso.datetime()}),Bi=()=>({projectId:qx(),stateBranch:Yx,createdAt:new Date().toISOString()}),Tt=e=>{let t=mo(e);if(!ss.existsSync(t))return c("Missing .epiq/project.json");try{let n=ss.readFileSync(t,"utf8"),r=JSON.parse(n),o=Xx.safeParse(r);return o.success?u("Read project.json",o.data):c(`Invalid .epiq/project.json: ${o.error.issues.map(s=>`${s.path.join(".")}: ${s.message}`).join(", ")}`)}catch(n){return c(n instanceof Error?`Failed to read .epiq/project.json: ${n.message}`:"Failed to read .epiq/project.json")}},dn=e=>{let t=Tt(e);return a(t)?c(t.message):u("Read projectId",t.value.projectId)},Ql=({repoRoot:e,fileContents:t})=>{let n=Mr(e),r=mo(e);try{if(ss.mkdirSync(n,{recursive:!0}),ss.existsSync(r)){let o=Tt(e);return a(o)?c(o.message):u("Project already initialized",null)}return ss.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
3
|
+
`,"utf8"),u("Created project.json",null)}catch(o){return c(o instanceof Error?`Failed to initialize project: ${o.message}`:"Failed to initialize project")}};import Jx from"node:os";import Qx from"node:path";var Vt=".epiq-global",Dn=()=>process.env.EPIQ_GLOBAL_DIR??Qx.join(Jx.homedir(),Vt);var Zl=(e,t)=>{let n=new Map,r=t??((...s)=>JSON.stringify(s)),o=((...s)=>{let i=r(...s);if(!n.has(i)){let l=e(...s).then(d=>(a(d)&&n.delete(i),d));n.set(i,l)}return n.get(i)});return o.clear=()=>n.clear(),o};import zt from"fs";import oc from"path";import Zx from"util";var vm=500,sc=4*1024*1024,ec=16*1024,eI=50,tc=0,bm=()=>process.env.EPIQ_MCP==="true",tI=()=>{let e=process.cwd(),t=Oi(e);return a(t)?bm()?oc.join(Dn(),"epiq-mcp.log"):void 0:oc.join(t.value,gt,"log","epiq.log")},nI=(e,t)=>{let n=zt.statSync(e).size;if(n<=t)return zt.readFileSync(e,"utf8");let r=zt.openSync(e,"r");try{let o=Buffer.alloc(t);zt.readSync(r,o,0,t,n-t);let s=o.toString("utf8"),i=s.indexOf(`
|
|
4
|
+
`);return i===-1?"":s.slice(i+1)}finally{zt.closeSync(r)}};function rI(e){if(!zt.existsSync(e))return;let t=zt.statSync(e).size,n=nI(e,sc).split(`
|
|
5
|
+
`);if(n[n.length-1]===""&&n.pop(),t<=sc&&n.length<=vm)return;let r=n.slice(-vm).join(`
|
|
6
6
|
`)+`
|
|
7
|
-
`;
|
|
8
|
-
`;try{
|
|
9
|
-
`);
|
|
10
|
-
`)))}),o.on("close",f=>{let g=f??1;if(n){
|
|
11
|
-
`)));return}
|
|
12
|
-
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,g=0;for(let
|
|
7
|
+
`;zt.writeFileSync(e,r,"utf8")}var oI=e=>{if(e.length<=ec)return e;let t=e.length-ec;return`${e.slice(0,ec)} \u2026 [${t} more chars]`};function nc(e,t,n=!1){let r=tI();if(!r)return;let o=oI(Zx.format(...t)),s=new Date,l=`[${n?s.toISOString().slice(11,19):s.toISOString()}] ${e} ${o}
|
|
8
|
+
`;try{zt.mkdirSync(oc.dirname(r),{recursive:!0}),zt.appendFileSync(r,l,"utf8"),tc++,(tc>=eI||zt.statSync(r).size>sc)&&(tc=0,rI(r))}catch{}}var rc=()=>bm()?process.env.EPIQ_MCP_LOG_LEVEL??"error":process.env.EPIQ_LOG_LEVEL??"debug",se={info(...e){let t=rc();(t==="info"||t==="debug")&&nc("[Info]",e,!1)},debug(...e){rc()==="debug"&&nc("[Debug]",e,!0)},error(...e){let t=rc();if(t==="error"||t==="info"||t==="debug"){let r=e.some(o=>o instanceof Error)?void 0:new Error().stack;nc("[Error]",[...e,r].filter(Boolean),!1)}}};globalThis.logger=se;import{spawn as Im}from"node:child_process";import Kt from"node:fs";import un from"node:path";var Ae={stage:({cwd:e,pathspec:t,ignoreRemoval:n=!1})=>j({args:["add",...n?["--ignore-removal"]:[],...t],cwd:e}),commit:({cwd:e,message:t,allowEmpty:n=!1,pathspec:r})=>j({args:["commit","--no-verify",...n?["--allow-empty"]:[],"-m",t,...r?.length?["--",...r]:[]],cwd:e}),fetch:({cwd:e,remote:t,branch:n})=>j({args:["fetch",t,`+refs/heads/${n}:refs/remotes/${t}/${n}`],cwd:e}),rebaseOnto:({cwd:e,ref:t})=>j({args:["-c","rebase.autoStash=true","rebase",t],cwd:e}),checkout:({cwd:e,branch:t})=>j({args:["checkout",t],cwd:e}),push:({cwd:e,remote:t,branch:n,setUpstream:r=!1})=>{let o=t&&n?["push","--no-verify",...r?["-u"]:[],t,n]:["push","--no-verify"];return j({args:o,cwd:e})},setUpstream:({cwd:e,branch:t,upstream:n})=>j({args:["branch","--set-upstream-to",n,t],cwd:e}),worktreeAdd:({cwd:e,worktreeRoot:t,branch:n})=>j({args:["worktree","add",t,n],cwd:e}),worktreeRemove:({cwd:e,worktreeRoot:t})=>j({args:["worktree","remove","--force",t],cwd:e}),worktreePrune:({cwd:e})=>j({args:["worktree","prune"],cwd:e})};var Ue=e=>{let t=me(e);if(a(t))return c("Unable to resolve epiq project root");let n=Tt(t.value);return a(n)?c("Unable to read project.json"):u("Resolved state branch",n.value.stateBranch)},wt="origin";var ic=1e4,sI=12e4,iI=new Set(["fetch","push","pull","clone","ls-remote","rebase","checkout","worktree"]),aI=e=>{let t=e.find((n,r)=>!n.startsWith("-")&&e[r-1]!=="-c");return t&&iI.has(t)?sI:ic},lI=()=>{let e=process.platform==="win32"?["git.exe","git"]:["git"];for(let t of(process.env.PATH??"").split(un.delimiter))if(t)for(let n of e){let r=un.join(t,n);try{if(!Kt.statSync(r).isFile())continue;return Kt.accessSync(r,Kt.constants.X_OK),r}catch{continue}}return"git"},Em=lI(),Sm={...process.env,GIT_TERMINAL_PROMPT:"0",GIT_ASKPASS:"echo",GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND??"ssh -o BatchMode=yes -o ConnectTimeout=10"},Rm=({args:e,cwd:t,allowFail:n})=>new Promise(r=>{if(!Kt.existsSync(t)){let f=`Git cwd does not exist: ${t}`;if(n){r({stdout:"",stderr:f,exitCode:1});return}r(c(f));return}let o=Im(Em,e,{cwd:t,stdio:["ignore","pipe","pipe"],env:Sm}),s=!1,i="",l="",d=f=>{s||(s=!0,clearTimeout(p),r(f))},m=aI(e),p=setTimeout(()=>{o.kill("SIGTERM");let f=[`git ${e.join(" ")}`,`cwd=${t}`,`Git command timed out after ${m}ms`].join(`
|
|
9
|
+
`);d(n?{stdout:i,stderr:f,exitCode:124}:c(f))},m);o.stdout.setEncoding("utf8"),o.stderr.setEncoding("utf8"),o.stdout.on("data",f=>{i+=f}),o.stderr.on("data",f=>{l+=f}),o.on("error",f=>{if(n){d({stdout:i,stderr:f.message,exitCode:1});return}d(c([`git ${e.join(" ")}`,`cwd=${t}`,f.message].join(`
|
|
10
|
+
`)))}),o.on("close",f=>{let g=f??1;if(n){d({stdout:i,stderr:l,exitCode:g});return}if(g!==0){d(c([`git ${e.join(" ")}`,l.trim()||i.trim()||"Git command failed"].filter(Boolean).join(`
|
|
11
|
+
`)));return}d(u("Git command succeeded",{stdout:i,stderr:l,exitCode:g}))})}),j=({args:e,cwd:t})=>Rm({args:e,cwd:t,allowFail:!1}),De=({args:e,cwd:t})=>Rm({args:e,cwd:t,allowFail:!0}),Fi=(e,t)=>new Promise(n=>{if(e.length===0){n(u("No blobs to read",new Map));return}let r=Im(Em,["cat-file","--batch"],{cwd:t,stdio:["pipe","pipe","pipe"],env:Sm}),o=[],s="",i=!1,l=m=>{i||(i=!0,clearTimeout(d),n(m))},d=setTimeout(()=>{r.kill("SIGTERM"),l(c(`git cat-file --batch timed out after ${ic}ms`))},ic);r.stdout.on("data",m=>o.push(m)),r.stderr.setEncoding("utf8"),r.stderr.on("data",m=>{s+=m}),r.on("error",m=>l(c(m.message))),r.on("close",m=>{if(m!==0){l(c(`git cat-file --batch exited ${m}${s?`
|
|
12
|
+
${s}`:""}`));return}let p=Buffer.concat(o),f=new Map,g=0;for(let y of e){let x=p.indexOf(10,g);if(x===-1){l(c(`git cat-file --batch output ended before a header for ${y}`));return}let b=p.toString("utf8",g,x);g=x+1;let R=/^[0-9a-f]{4,64} \S+ (\d+)$/.exec(b);if(!R||!R[1]){l(c(`Unexpected git cat-file --batch header: "${b}"`));return}let S=Number(R[1]);f.set(y,p.toString("utf8",g,g+S)),g+=S+1}l(u("Read blobs",f))}),r.stdin.write(e.join(`
|
|
13
13
|
`)+`
|
|
14
|
-
`),r.stdin.end()}),
|
|
15
|
-
${r.message}`);let o=await
|
|
16
|
-
${o.message}`):u("Created commit and resolved SHA",o.value.stdout.trim())},
|
|
17
|
-
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(
|
|
18
|
-
${t.stderr.trim()}`):u("Aborted stale rebase",!0)},
|
|
19
|
-
${o.message}`);let s=await
|
|
20
|
-
${s.message}`);let i=await
|
|
21
|
-
`+r.message);let o=
|
|
22
|
-
`+o.message):u("Ensured epiq storage",n)},
|
|
23
|
-
`,
|
|
24
|
-
`,
|
|
14
|
+
`),r.stdin.end()}),fo=async({cwd:e,message:t,pathspec:n})=>{let r=await Ae.commit({cwd:e,message:t,pathspec:n});if(a(r))return c(`Failed to create commit
|
|
15
|
+
${r.message}`);let o=await j({args:["rev-parse","HEAD"],cwd:e});return a(o)?c(`Commit created, but failed to read HEAD SHA
|
|
16
|
+
${o.message}`):u("Created commit and resolved SHA",o.value.stdout.trim())},_i=async e=>{let t=await j({cwd:e,args:["rev-parse","--git-dir"]});if(a(t))return c(t.message);let n=t.value.stdout.trim();return u("Resolved git dir",un.isAbsolute(n)?n:un.resolve(e,n))},ac=async e=>{let t=await _i(e);if(a(t))return c(t.message);let n=t.value,r={MERGE_HEAD:"merge in progress"};for(let[s,i]of Object.entries(r))if(Kt.existsSync(un.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(Kt.existsSync(un.join(n,s)))return u("Checked for in-progress Git operation",i);return u("Checked for in-progress Git operation",null)},Cm=async e=>{let t=await ac(e);return a(t)?c(t.message):u("Checked for in-progress Git operation",t.value!==null)},Bn=async({repoRoot:e})=>{let n=(await De({args:["remote","get-url",wt],cwd:e})).exitCode===0;return u(`Checked remote ${n}`,n)},is=async({repoRoot:e,branch:t})=>{let n=await De({args:["ls-remote","--heads",wt,t],cwd:e});return n.exitCode!==0?c(n.stderr.trim()||`Unable to inspect remote branch ${wt}/${t}`):u("Checked remote branch",n.stdout.trim().length>0)},$i=async({repoRoot:e,branch:t})=>{let n=await De({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):c(n.stderr.trim()||`Unable to inspect branch ${t}`)},po=e=>{try{return Kt.realpathSync.native(e)}catch{return un.resolve(e)}},Nm=async({repoRoot:e,worktreeRoot:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return c(n.message);let r=po(t),o=n.value.stdout.split(`
|
|
17
|
+
`).filter(s=>s.startsWith("worktree ")).map(s=>s.slice(9)).map(po).includes(r);return u("Checked worktree registration",o)},lc=async e=>{let t=await De({args:["rev-parse","--abbrev-ref","--symbolic-full-name","@{u}"],cwd:e});return u("Checked upstream",t.exitCode===0&&t.stdout.trim().length>0)},Ui=async e=>{let t=await j({args:["rev-parse","--abbrev-ref","HEAD"],cwd:e});return a(t)?c(t.message):u("Resolved current branch",t.value.stdout.trim())},Am=async e=>{let t=await j({args:["rev-parse","--short","HEAD"],cwd:e});return a(t)?c(t.message):u("Resolved short HEAD sha",t.value.stdout.trim())},Tm=e=>e.includes("fetch first")||e.includes("non-fast-forward"),wm=async e=>{let t=await De({cwd:e,args:["rev-parse","--absolute-git-dir"]});if(t.exitCode!==0)return!1;let n=t.stdout.trim();return n?Kt.existsSync(un.join(n,"rebase-merge"))||Kt.existsSync(un.join(n,"rebase-apply")):!1},cI=3,dI=120,uI=e=>new Promise(t=>setTimeout(t,e)),mI=async(e,t)=>{let n=await Ae.rebaseOnto({cwd:e,ref:t});for(let r=1;r<cI;r+=1){if(!a(n)||await wm(e))return n;await uI(dI),n=await Ae.rebaseOnto({cwd:e,ref:t})}return n},Mm=async(e,{preserve:t=[]}={})=>{let n=await _i(e);if(a(n))return c(n.message);let r=n.value,o=[];for(let s of Kt.readdirSync(r))if(s.endsWith(".lock")&&!t.includes(s))try{Kt.rmSync(un.join(r,s),{force:!0}),o.push(s)}catch{}return u("Cleared stale git lock files",o)},cc=async e=>{if(!await wm(e))return u("No rebase to abort",!1);let t=await De({cwd:e,args:["rebase","--abort"]});return t.exitCode!==0?c(`Failed to abort the rebase in progress at ${e}
|
|
18
|
+
${t.stderr.trim()}`):u("Aborted stale rebase",!0)},xm=async e=>{let t=await De({args:["rev-parse","HEAD"],cwd:e});return t.exitCode===0?t.stdout.trim():null},as=e=>/could not resolve host/i.test(e)||/connection refused|connection timed out|operation timed out/i.test(e)||/network is unreachable|no route to host/i.test(e)||/failed to connect to/i.test(e),pI=e=>e.includes("couldn't find remote ref")||e.includes("Could not find remote branch"),ls=async({cwd:e,branch:t})=>{let n=await cc(e);if(a(n))return c(n.message);let r=await xm(e),o=await Ae.fetch({cwd:e,remote:wt,branch:t});if(a(o))return pI(o.message)?u("Remote branch missing, skipped pull",!1):c(`Failed to fetch ${t}
|
|
19
|
+
${o.message}`);let s=await mI(e,`${wt}/${t}`);if(a(s))return c(`Failed during rebase
|
|
20
|
+
${s.message}`);let i=await xm(e),l=r!==null&&i!==null&&r!==i;return u(l?"Pulled with rebase":"Already up to date",l)},Pm=async e=>{let t=await De({args:["rev-list","--count","@{u}..HEAD"],cwd:e});return t.exitCode!==0?u("No upstream to compare against",!1):u("Compared against upstream",Number(t.stdout.trim())>0)},Lm=async e=>{let t=await De({args:["status","--porcelain","--untracked-files=all"],cwd:e});return t.exitCode!==0?c(t.stderr.trim()||"Unable to inspect the worktree for changes"):u("Inspected worktree for changes",t.stdout.trim().length>0)},km=async(e,t)=>{let n=await De({args:["diff","--cached","--quiet",...t?.length?["--",...t]:[]],cwd:e});return n.exitCode===0?u("No staged changes",!1):n.exitCode===1?u("Has staged changes",!0):c(n.stderr.trim()||"Unable to inspect staged changes")};var Dm=async e=>{let t=await Ui(e);return a(t)?c(t.message):u("Checked detached HEAD state",t.value==="HEAD")};var Fm="4b825dc642cb6eb9a060e54bf8d69288fbee4904",_m=e=>It.join(gt,On,e),$m=()=>It.join(gt,mc),Um=Dn,Pr=()=>It.join(Um(),"worktrees"),he=({repoRoot:e})=>{let t=dn(e);return a(t)?c(t.message):u("Resolved state branch root",It.join(Pr(),t.value))},fI=e=>It.join(e,gt),Bm=e=>It.join(fI(e),On);var cs=e=>{try{return Zn.mkdirSync(e,{recursive:!0}),u("Ensured directory",void 0)}catch(t){return c(t instanceof Error?t.message:String(t))}},ds=()=>{let e=Um(),t=Pr(),n=!Zn.existsSync(e)||!Zn.existsSync(t),r=cs(e);if(a(r))return c(`Ensure epiq home failed.
|
|
21
|
+
`+r.message);let o=cs(t);return a(o)?c(`Ensure worktrees dir failed.
|
|
22
|
+
`+o.message):u("Ensured epiq storage",n)},jm=e=>{Zn.existsSync(e)&&(se.debug("[sync] remove path",e),Zn.rmSync(e,{recursive:!0,force:!0}))};var gI=`*.jsonl merge=union
|
|
23
|
+
`,hI=`*~pending*.jsonl
|
|
24
|
+
`,dc=()=>It.join(gt,On,".gitattributes"),uc=()=>It.join(gt,On,".gitignore"),Om=(e,t)=>{try{Zn.readFileSync(e,"utf8")!==t&&Zn.writeFileSync(e,t)}catch{Zn.writeFileSync(e,t)}},Hm=(e,t)=>{for(let n of[Bm(e),Bm(t)]){let r=cs(n);if(a(r))return c(r.message)}return Om(It.join(t,dc()),gI),Om(It.join(t,uc()),hI),u("Ensured state branch",void 0)},Wm=async e=>{let t=await j({args:["ls-tree","--name-only","HEAD"],cwd:e});if(a(t))return c(`ensure state branch is storage only failed
|
|
25
25
|
`+t.message);let r=t.value.stdout.trim().split(`
|
|
26
|
-
`).filter(Boolean).filter(i=>i!==
|
|
27
|
-
${o.message}`);let s=await
|
|
28
|
-
`),u("Config written",null)}catch{return l(`Unable to write ~/${Pt}/config.json`)}},vt=e=>{let t=Or();if(a(t))return l("Failed to read existing config");let n={...t.value,...e};return yu(n)},bt=()=>{let e=Za(),t=el();if(a(t))return l(`Unable to create ~/${Pt}`);if(!(We.readFile(e)!==null)){let I=yu(Uv);if(a(I))throw new Error(`Unable to create ~/${Pt}/config.json`)}let r=Or();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,autoSync:d,autoSyncDebounceMs:c,attachmentMaxKb:m,logLevel:p,viewMode:f}=r.value,g=Lr({userId:i,userName:s});if(a(g))return l(g.message);let v=g.value??{userId:i,userName:s};return!v.userName||!v.userId?l(`User name or ID not configured in ~/${Pt}/config.json`):(process.env.EPIQ_LOG_LEVEL=p,u("successfully loaded settings",{logLevel:p??"debug",preferredEditor:o??"",userName:v.userName,userId:v.userId,autoSync:d??!1,autoSyncIntervalMs:c??1e4,attachmentMaxKb:m??null,viewMode:f??"dense"}))};import{useSyncExternalStore as Hv}from"react";var Ao={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,viewMode:null},tl=new Set,Wv=()=>{for(let e of tl)e()},le=()=>Ao,vu=()=>Hv(e=>(tl.add(e),()=>{tl.delete(e)}),()=>Ao),Ye=e=>(Ao={...Ao,...e},Wv(),Ao);import{spawn as Gv}from"node:child_process";import nl from"node:process";var rl=e=>{let t=nl.platform==="darwin"?"open":nl.platform==="win32"?"cmd":"xdg-open",n=nl.platform==="win32"?["/c","start","",e]:[e];Gv(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as ny}from"node:fs/promises";import Yn from"chalk";import _g from"string-width";import{decodeTime as bu}from"ulid";var _s=1440*60*1e3,To=(e,t=Date.now())=>e>t+_s?t:e,Ce=e=>To(bu(e)),_r=e=>{let t=Date.now()+_s,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},Us=e=>{try{return u("Decoded date",new Date(Ce(e)))}catch(t){return l("Decoding failed + "+t.message)}},Mn=e=>{if(!e?.id)return null;try{return bu(e.id)}catch{return null}};var js="removed",ot=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):l("Unable to find node in breadcrumb")},xu=["png","jpg","gif","webp"];var K={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function ol(e){return e.context===K.WORKSPACE}function B(e){return e.context===K.TICKET}function Pn(e){return e.context===K.TEXT}function gt(e){return e.context===K.FIELD}function wo(e){return e.context===K.FIELD_LIST}var Kt=e=>e.context===K.SWIMLANE,Ln=e=>e.context===K.BOARD,Mo=e=>e.context===K.COMMENT;import{useSyncExternalStore as LE}from"react";var b={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette"};var Iu=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",Su=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",Eu=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",Ru=(e,t)=>{if(Su(e,e.sequence))return S.MoveCursorLeftOfWord;if(Eu(e,e.sequence))return S.MoveCursorRightOfWord;if(Iu(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.GetLastCommandFromHistory;case"down":return S.GetNextCommandFromHistory;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}},Cu=(e,t)=>{if(Su(e,e.sequence))return S.MoveCursorLeftOfWord;if(Eu(e,e.sequence))return S.MoveCursorRightOfWord;if(Iu(e,e.sequence))return S.EraseInputWord;switch(e.name){case"tab":return S.AutoCompleteCommand;case"up":return S.NavPreviousItem;case"down":return S.NavNextItem;case"left":return S.MoveCursorLeft;case"right":return S.MoveCursorRight;case"return":return S.Confirm;case"backspace":return t?S.EraseInput:S.ExitCommandLine;case"escape":return S.ExitCommandLine;default:return S.CaptureInput}};import Nu from"string-width";function $s(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var yn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",Vv=/\u001B\[[0-9;]*m/,sl="\x1B[0m",zv=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),il=(e,t)=>{if(t<=0)return"";if(Nu(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let d of e.split(/(\u001B\[[0-9;]*m)/))if(d!==""){if(Vv.test(d)){o+=d,i=d!==sl&&d!=="\x1B[m";continue}for(let c of zv(d)){let m=Nu(c);if(s+m>r)return`${o}...${i?sl:""}`;o+=c,s+=m}}return`${o}...${i?sl:""}`},ye=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),Au=e=>e.charAt(0).toUpperCase()+e.slice(1);var Tu=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},wu=(e,t)=>t?e.get(t)??[]:[];var Mu=new WeakMap,Kv=e=>{let t=Mu.get(e);return t||(t=Tu(e),Mu.set(e,t)),t};var Pu=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return wu(Kv(e),r).filter(s=>$s(r,s)>=n)};var qv={hint:"",hints:[],overlap:0,remainder:""},Lu=({inputToMatch:e,lastWord:t,isLastWordCompleted:n},r)=>{if(n||e==="")return qv;let o=Pu({wordList:r,inputToMatch:e,overlapThreshold:1});return Yv(t,o)},Yv=(e,t)=>{let n=t[0]??"",r=$s(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,d=!!s,p=(d&&i?o:n)+(d&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import{ulid as Qv}from"ulid";var Po=24n,Xv=Po*4n,qt=(1n<<Xv)-1n,Jv=/^[0-9a-f]+$/;function ku(e){return!e||!Jv.test(e)?l(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function xt(e,t=Po){if(e<0n)return l("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function st(e,t){if(!e&&!t)return xt(qt/2n,Po);let n=e?ku(e):u("Resolved lower bound",0n);if(a(n))return n;let r=t?ku(t):u("Resolved upper bound",qt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return l("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?l("No rank space available between neighbors"):xt(i,Po)}function Du(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=qt*BigInt(r+1)/(t+1n),s=xt(o,Po);if(a(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var al=(e,t)=>{let n=de(e),r=Du(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],d=r.value[s];if(!i||!d)return l("Unable to assign rebalance rank");o[i.id]=d}return u("Created rebalance event",{id:Qv(),action:"rebalance.children",payload:{parent:e,ranks:o},...t})};import{ulid as $b}from"ulid";var ve={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var O=e=>e.slice(-7).toUpperCase(),Hs=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?O(e).includes(n):!0};var be={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:K.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:O(e)},context:K.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:K.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:K.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:K.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:O(e)},context:K.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:K.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:K.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var Zv=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ie,Ws]=Zv;var ll=(e,t)=>l(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),F=(e,t)=>({...ll(e,t),convergence:!0}),ko=e=>a(e)&&e.convergence===!0,vn=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!ko(n)),skipped:t.filter(ko)}},bn=e=>{e.length!==0&&z.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},Bu=e=>{let t=R.getNode(e);if(!t||!B(t)||t.isDeleted)return null;let n=Ou(t);return a(n)?n:null},Fu=e=>{if(!cl())return null;for(let t of e){let n=Bu(t);if(n)return n;let r=h().nodes[t]?.parentNodeId;if(!r)continue;let o=Bu(r);if(o)return o}return null},eb=(e,t)=>{let n=R.getNode(e);n&&R.updateNode({...n,log:[...n.log??[],t]})},tb=e=>{let t=[e],n=h().nodes[e]?.parentNodeId;return n&&t.push(n),t},dl=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 tb(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":default:return[]}},nb=e=>{we(t=>({...t,eventLog:[...t.eventLog,e]}))},rb=e=>{let t=e.userId,n=e.userName;return!t?.length||!n?.length?ll("Invalid user ID format",e):u("Valid user",null)},dt=null,ob=e=>{for(let[t,n]of e.nodeLog){let r=R.getNode(t);r&&R.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&we(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),Fu([...e.virtualNodeIds])},sb=(e,t)=>{let n=rb(e);if(a(n))return n;let r=[...new Set(dl(e))];if(dt){for(let s of r){if(!t){let i=dt.nodeLog.get(s);i?i.push(e):dt.nodeLog.set(s,[e])}if(cl()){dt.virtualNodeIds.add(s);let i=h().nodes[s]?.parentNodeId;i&&dt.virtualNodeIds.add(i)}}return t||dt.appLog.push(e),null}t||(r.forEach(s=>eb(s,e)),nb(e));let o=Fu(r);return o||null},Lo=(e,t,n)=>R.getNode(e)?F(`a node with id ${e} already exists`,n):t===e?F("a node cannot be its own parent",n):null,ib={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=be.workspace(t,n,r),s=Do(o);if(a(s))return ll(s.message,e);let i=R.createNode(o);return a(i)?F(i.message??"Failed to initialize workspace",e):ol(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Lo(t,void 0,e);if(o)return o;let s=R.createNode(be.workspace(t,n,r));return a(s)?F(s.message??"Failed to add workspace",e):ol(s.value)?u("Added workspace",{action:e.action,result:s.value}):l("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Lo(t,r,e);if(s)return s;let i=R.createNode(be.board(t,n,r,o));return a(i)?F(i.message??"Unable to create board",e):Ln(i.value)?u("Added board",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Lo(t,r,e);if(s)return s;let i=R.createNode(be.swimlane(t,n,r,o));return a(i)?F(i.message??"Unable to create swimlane",e):Kt(i.value)?u("Added swimlane",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Lo(t,r,e);if(s)return s;let i=R.createNode(be.ticket(t,n,r,o));return a(i)?F(i.message??"Unable to create issue",e):B(i.value)?u("Added issue",{action:e.action,result:i.value}):l("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=Lo(t,r,e);if(i)return i;let d=R.createNode(be.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(ve.DESCRIPTION)?"vertical":"horizontal"}));return a(d)?F(d.message??`Unable to create field: ${n}`,e):gt(d.value)?u("Added field",{action:e.action,result:d.value}):l("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!R.getNode(t))return F(`Unable to locate node with id ${t}`,e);let o=R.renameNode(t,n);return a(o)?F(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=R.tombstoneNode(t);return a(n)?F(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=R.createTag({id:t,name:n});return a(r)?F(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=R.tombstoneTag(t);return a(n)?F(n.message??"Unable to delete tag",e):u("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=R.restoreTag(t,n);return a(r)?F(r.message??"Unable to restore tag",e):u("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=R.createContributor({id:t,name:n});return a(r)?F(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=R.renameContributor(t,n);return a(r)?F(r.message??"Unable to rename contributor",e):u("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=R.tombstoneContributor(t);return a(n)?F(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=R.restoreContributor(t,n);return a(r)?F(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=R.tag(t,n);return a(r)?F(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=R.untag(t,n);return a(r)?F(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=R.assign(t,n);return a(r)?F(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=R.unassign(t,n);return a(r)?F(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=R.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?F(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=R.editValue(t,n);return a(r)?F(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=R.getNode(t);if(!o)return F("Unable to locate issue",e);if(!B(o))return F("Can only close issues",e);let s=R.getNode(ie);if(!s)return F("Unable to locate target swimlane",e);if(n!==s.id)return F("Close target must be closed swimlane",e);let i=R.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?F(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=R.getNode(t);if(!o)return F("Unable to locate issue",e);if(!B(o))return F("Can only reopen issues",e);let s=R.getNode(ie);if(!s)return F("Unable to locate closed swimlane",e);if(n===s.id)return F("Cannot reopen issue into closed swimlane",e);if(!R.getNode(n))return F("Reopen parent no longer exists",e);let d=R.moveNodeToRank({id:t,parentId:n,rank:r});return a(d)?F(d.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=R.lockNode(t);return a(n)?F(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=R.getNode(r);if(!s)return F(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return F(`Node ${r} is not child of ${t}`,e);let i=R.updateNode({...s,rank:o});if(a(i))return F(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=R.createComment({id:t,issue:n,authorId:r,authorName:R.getContributor(r)?.name??"Unknown",md:o,deleted:!1});return a(s)?F(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=R.getComment(t);if(!o)return F("Unable to locate comment",e);if(o.issue!==n)return F("Comment does not belong to issue",e);let s=R.editComment(t,r);return a(s)?F(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=R.getComment(t);if(!r)return F("Unable to locate comment",e);if(r.issue!==n)return F("Comment does not belong to issue",e);let o=R.deleteComment(t);return a(o)?F(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,d=R.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(d)?F(d.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=R.getAttachment(t);if(!r)return F("Unable to locate attachment",e);if(r.issue!==n)return F("Attachment does not belong to issue",e);let o=R.deleteAttachment(t);return a(o)?F(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=R.linkUserId({contributorId:t,userId:e.userId});return a(n)?F(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};function kn(e,t=!1){let n=ib[e.action];if(!n)return l(`Unknown event action "${e.action}", likely created by a newer epiq version. Evt id: ${e.id}`);if(!It()&&e.action!=="init.workspace")return F(`${e.action} arrived before the workspace was initialized`,e);if(e.action==="init.workspace"&&dt){if(dt.genesisApplied)return F("the workspace is already initialized",e);dt.genesisApplied=!0}let r;try{r=n(e)}catch(s){return F(`threw while materializing (${s instanceof Error?s.message:String(s)})`,e)}if(a(r))return r;let o=sb(e,t);return o||r}var Bt=e=>{let t=Gs(()=>{let n=dt===null;n&&(dt={appLog:[],nodeLog:new Map,virtualNodeIds:new Set,genesisApplied:!1});try{let r=e.map(o=>kn(o));if(n&&dt){let o=ob(dt);if(o)return e.map(()=>o)}return r}finally{n&&(dt=null)}});return a(t)?e.map(()=>l(t.message)):t.value};import El from"node:path";import{decodeTime as wb,monotonicFactory as Mb}from"ulid";import{z as ar}from"zod";var ul=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";import Ae from"node:fs";import ir from"node:path";import{ulid as ab}from"ulid";var zs="~pending",ml=/~pending(-[0-9a-z]+)*$/i,Uu=/-f(\d+)$/,ju=e=>{let t=e.indexOf(".");return t===-1?`${e}${zs}`:e.slice(0,t)+zs+e.slice(t)},pl=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},$u=e=>{let[t,n]=pl(e);return ml.test(t)?t.replace(ml,"")+n:null},Hu=e=>e.replace(ml,""),Ks=e=>e.endsWith(".jsonl")&&$u(e)!==null,Wu=e=>{let[t]=pl(e),n=Uu.exec(t);return n&&Ks(e)?Number(n[1]):null},lb=e=>ju(e).replace(zs,`${zs}-${ab().toLowerCase()}`),db=(e,t)=>{let[n,r]=pl(e);return`${n.replace(Uu,"")}-f${t}${r}`},Gu=(e,t)=>ir.join(Dt(e),ju(t)),cb=(e,t)=>Math.max(0,Ae.statSync(e).size-(Wu(t)??0)),Vu=e=>{let t=Dt(e);try{return Ae.existsSync(t)?Ae.readdirSync(t).filter(Ks).some(n=>cb(ir.join(t,n),n)>0):!1}catch{return!0}},ub=3,zu=(e,t)=>{for(let n=1;;n++){let r=Ae.openSync(e,"a"),o;try{Ae.writeSync(r,t),o=Ae.fstatSync(r).ino}finally{Ae.closeSync(r)}let s;try{s=Ae.statSync(e).ino}catch{s=null}if(s===o||n>=ub)return}},mb=e=>{let t;try{t=Ae.openSync(e,"r")}catch{return!0}try{let{size:n}=Ae.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ae.readSync(t,r,0,1,n-1),r[0]===10}finally{Ae.closeSync(t)}},Vs=10,_u=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(Vs)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ae.appendFileSync(e,Buffer.concat([Buffer.from(mb(e)?"":`
|
|
29
|
-
`),o,Buffer.from(o[o.length-1]===Vs?"":`
|
|
30
|
-
`)
|
|
31
|
-
`)
|
|
32
|
-
`),n&&(n.current=c);let f=El.basename(i.value);return rm(t,f,c),Xu(t,f),u("Event persisted",{path:i.value,entry:p.value})}catch(o){let s=o instanceof Error?o.message:"Unknown persist error";return l(`Failed to persist event: ${s}`)}}function cm(e,t,n){let r=Rl(t,n);if(a(r))return l(r.message);let o={...e,id:r.value[0]},s=kn(o);if(s.status!==Tn.Success)return s;let i=ei({event:o,rootDir:t,edge:n,id:r.value});return a(i)?i:s}function D(e,t){if(e.length===0||!e[0])return l("No events provided");if(h().readOnly)return l(h().readOnlyReason??"Cannot change the board while time travelling");let n=Gs(()=>{let r={},o=Hb(e[0],t,r);if(a(o))return l(o.message);let s=e.map(d=>cm(d,t,r)),i=s.filter(a);return i.length>0?l("Materialize and persist failed: "+i.map(d=>d.message).join(", ")):u("Materialization succeeded",s.map(d=>d.value))});return a(n)?l(n.message):n.value??l("Materialize and persist produced nothing")}var Hb=(e,t,n)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let r=R.getContributor(e.userId),o={id:$b(),action:r?"rename.contributor":"create.contributor",payload:{id:e.userId,name:e.userName},userId:e.userId,userName:e.userName};if(r&&(r.tombstoned||r.name===e.userName))return u("Contributor name is current",void 0);let s=cm(o,t,n);return a(s)?l(s.message):u("Contributor name recorded",void 0)};var dr=e=>e.trim().toLocaleLowerCase(),Cl=(e,t)=>dr(e).includes(dr(t));var Wb=e=>{let{tags:t}=h();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},Gb=e=>{let{contributors:t}=h();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},um=null,mm=new Map,Vb=()=>{let e=h().eventLog??[];if(e===um)return mm;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return um=e,mm=t,t},zb=e=>{let{contributors:t}=h(),n=Vb().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},pm=(e,t)=>{let n=dr(t.value);if(!n)return!0;switch(t.target){case"title":return Cl(e.title??"",n);case"description":return Cl(e.props.description??"",n);case"tag":return Wb(e).map(dr).some(o=>o.includes(n));case"assignee":return Gb(e).map(dr).some(o=>o.includes(n));case"actor":return zb(e).map(dr).some(o=>o.includes(n));case"ref":return Hs(e.id,t.value);default:return!0}};var Nl=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,Kb=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,fm=(e,t)=>Object.values(e).filter(n=>Kb(n,t)).sort(Nl),gm=(e,t)=>{let n={};for(let r of Object.values(e)){if(B(r)&&t.length>0&&!t.every(s=>pm(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Nl);return n},hm=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(Nl);return n};var ym=e=>ti(de(e),{at:"end"}),ti=(e,t={at:"end"})=>{let n=o=>a(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(st(void 0,void 0));let r=()=>n(st(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(st(void 0,o.rank)):l("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(st(o.rank,void 0)):l("Unable to resolve last sibling")}case"before":{let o=vm(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(st(i?.rank,s.rank))}case"after":{let o=vm(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(st(s.rank,i?.rank))}}},de=e=>{let t=h();if(!xm()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return fm(t.nodes,e)},vm=(e,t)=>e.findIndex(n=>n.id===t),bm=(e,t,n={at:"end"})=>ti(de(t).filter(r=>r.id!==e),n),Xt=(e,t,n,r,o)=>{let s=bm(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=al(e,r);if(a(i))return i;let d=D([i.value],o);if(a(d))return d;let c=bm(t,e,n);return a(c)?c:c.value.needsRebalance?l("Rank rebalance failed to create space"):u("Resolved rank after rebalance",c.value.rank)},In=(e,t,n)=>{let r=ym(e);if(a(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=al(e,t);if(a(o))return o;let s=D([o.value],n);if(a(s))return s;let i=ym(e);return a(i)?i:i.value.needsRebalance?l("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var _={exit(){process.exit(0)},enterChildNode(){let e=h(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=X(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||_.navigate({contextNode:o,selectedIndex:X(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=h();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=X(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;_.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>Im(1),navigateToPreviousItem:()=>Im(-1),navigateToNextContainer:()=>Sm(1),navigateToPreviousContainer:()=>Sm(-1),navigate:({contextNode:e,selectedIndex:t})=>{N({contextNodeId:e.id,selectedIndex:t})}},Im=e=>{let{selectedIndex:t,contextNode:n}=h(),r=X(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;_.navigate({selectedIndex:s,contextNode:n})},Sm=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=h();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=X(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let d=s.at(i+e)??s.at(0);if(!d)return;let c=X(d.id),m=Math.max(0,c.length-1),p=Math.min(Math.max(0,r),m),f=c.length?p:-1;_.navigate({contextNode:d,selectedIndex:f})};var Rm=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Cm=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=h();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},qb=e=>{let t=h().nodes[e];return!!t&&!t.isDeleted&>(t)&&t.childRenderAxis==="vertical"},ni=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r||r.isDeleted)return!1;let o=de(r.id);return _.navigate({contextNode:r,selectedIndex:Rm(t,o.length)}),!0},Nm=e=>{let{nodes:t}=h(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return ni(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=de(o.id).findIndex(d=>d.id===n.id);return i>=0?(_.navigate({contextNode:o,selectedIndex:i}),!0):Nm(o.id)},Em=e=>{let{nodes:t}=h(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Nm(n))return!0;n=t[n]?.parentNodeId}return!1},Yb=e=>{if(!e)return!1;let t=h().nodes[e];return!!t&&!t.isDeleted},Am=e=>{let{nodes:t,rootNodeId:n}=h();if(qb(e.contextNodeId)&&ni(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(Yb(e.selectedNodeId)&&e.selectedNodeId&&Em(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(ni(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&ni(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(Em(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return l("Unable to restore navigation");let o=de(r.id);return _.navigate({contextNode:r,selectedIndex:Rm(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as Xb,ulid as Jt}from"ulid";var Oo=Xb();function Jb(){let e=it();if(a(e))return l("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return l("No workspace found in event log");let[r]=X(n.id),[o]=r?X(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return u("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?u("Resolved boot nav target",{contextNode:r,selectedIndex:0}):u("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function Qb(){let e=Jb();return a(e)?e:_.navigate(e.value)}function Tm({userId:e,userName:t}){let n=Oo(),r=Oo(),o=Oo(),s=Oo(),i=Oo(),d=st(void 0,void 0);if(a(d))return d;let c=st(void 0,void 0);if(a(c))return c;let m=st(c.value,void 0);if(a(m))return m;let p=st(void 0,void 0);if(a(p))return p;let f=st(p.value,void 0);if(a(f))return f;let g=st(f.value,void 0);if(a(g))return g;let v=st(void 0,void 0);return a(v)?v:u("Created default events",[{id:Jt(),userId:e,userName:t,action:"init.workspace",payload:{id:n,name:"Workspace",rank:d.value}},{id:Jt(),userId:e,userName:t,action:"create.contributor",payload:{id:e,name:t}},{id:Jt(),userId:e,userName:t,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:c.value}},{id:Jt(),userId:e,userName:t,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Jt(),userId:e,userName:t,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Jt(),userId:e,userName:t,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Jt(),userId:e,userName:t,action:"add.board",payload:{id:Ws,name:"Closed",parent:n,rank:m.value}},{id:Jt(),userId:e,userName:t,action:"add.swimlane",payload:{id:ie,name:"Closed",parent:Ws,rank:v.value}},{id:Jt(),userId:e,userName:t,action:"lock.node",payload:{id:Ws}},{id:Jt(),userId:e,userName:t,action:"lock.node",payload:{id:ie}}])}var Zb=()=>{let e=it();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},ex=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");z.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");z.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function Ot(e,t=[]){if(Zb())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=be.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Do(s);return a(i)?i:(N({hasProjectDefinition:!1,mode:b.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return l("Initialized Epiq project has no workspace init event");let n=Bt(e),{fatal:r,skipped:o}=vn(n);return r.length>0?l(`Materializing failed:
|
|
26
|
+
`).filter(Boolean).filter(i=>i!==gt);if(r.length===0)return u("State branch is storage-only",!1);let o=await j({args:["rm","-r","--ignore-unmatch","--",...r],cwd:e});if(a(o))return c(`Failed to clean storage branch
|
|
27
|
+
${o.message}`);let s=await fo({cwd:e,message:"[epiq:repair-storage-branch]",pathspec:r});return a(s)?c(s.message):u("Cleaned storage branch",!0)},qt=Zl(async(e=process.cwd())=>{let t=await j({args:["rev-parse","--show-toplevel"],cwd:e});return a(t)?c("Not inside a Git repository"):u("Resolved repo root",t.value.stdout.trim())},e=>It.resolve(e)),UP=Zl(async e=>{let t=await j({args:["rev-parse","--git-dir"],cwd:e});if(a(t))return c(t.message);let n=t.value.stdout.trim(),r=It.isAbsolute(n)?n:It.join(e,n);return u("Resolved git dir",r)},e=>It.resolve(e));var KP=process.env.IS_LOCAL==="true",gt=".epiq",On="events",mc="media",yI="project.json",Mr=e=>mn.join(e,gt),mo=e=>mn.join(Mr(e),yI),Et=e=>mn.join(Mr(e),On),ms=e=>mn.join(Mr(e),mc),Gm=e=>mn.join(e,gt),vI=e=>{let t=mn.join(e,gt);return us.existsSync(t)&&us.statSync(t).isDirectory()},ps=e=>{let t=mo(e);return us.existsSync(t)&&us.statSync(t).isFile()},Oi=e=>{let t=mn.resolve(e);for(;;){if(vI(t))return u("Resolved closest .epiq root",t);let n=mn.dirname(t);if(n===t)return c("No .epiq directory found in any parent");t=n}},pc="No .epiq/project.json found in any parent",me=e=>{let t=mn.resolve(e);for(;;){if(ps(t))return u("Resolved closest epiq project root",t);let n=mn.dirname(t);if(n===t)return c(pc);t=n}},Vm=e=>{let t=Et(e);try{return us.mkdirSync(t,{recursive:!0}),u("Resolved events dir",t)}catch(n){return c(n instanceof Error?`Failed to ensure events dir: ${n.message}`:"Failed to ensure events dir")}},Se=async()=>{let e=await qt(process.cwd());if(a(e))return e;let t=he({repoRoot:e.value});return a(t)?t:u("Resolved persist root",t.value)};import{accessSync as bI,copyFileSync as xI,existsSync as ji,mkdirSync as zm,readdirSync as Km,readFileSync as II,renameSync as EI,rmSync as SI,statSync as qm,unlinkSync as RI,writeFileSync as CI}from"node:fs";import go from"node:path";var fc=e=>typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string",ot={writeToFile:(e,t)=>{try{let n=go.dirname(e);ji(n)||zm(n,{recursive:!0});let r=typeof t=="string"?t:JSON.stringify(t,null,2);CI(e,r,"utf-8")}catch(n){logger.error(`Failed to write file at ${e}:`,n)}},readFile:e=>{try{return II(e,"utf-8")}catch(t){return logger.error(`Failed to read file at ${e}:`,t),null}},readFileJSON(e){try{let t=ot.readFile(e);return t===null?null:JSON.parse(t)}catch(t){return logger.error(`Failed to read JSON at ${e}:`,t),null}},dirExists:e=>{try{return ji(e)&&qm(e).isDirectory()}catch{return!1}},async fileExists(e){try{return await bI(e),!0}catch{return!1}},mkDir:e=>zm(e,{recursive:!0}),locateFolder:e=>{let t=process.cwd(),{root:n}=go.parse(t);for(;;){let r=go.join(t,e);try{if(ji(r)&&qm(r).isDirectory())return r}catch{logger.error(`Unable to locate folder ${e}`)}if(t===n)break;t=go.dirname(t)}return null},readFirstJSON(e){try{if(!ot.dirExists(e))return null;let t=Km(e).filter(r=>r.endsWith(".json")).sort()[0];if(!t)return null;let n=go.join(e,t);return ot.readFileJSON(n)}catch(t){return logger.error(`Could not read first JSON in folder ${e}`,t),null}},listDir:e=>{try{return ot.dirExists(e)?Km(e):[]}catch(t){return logger.error(`Failed to list dir ${e}`,t),[]}},rmFile(e){try{RI(e)}catch(t){(!fc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove file ${e}`)}},rmDir(e){try{SI(e,{recursive:!0,force:!0})}catch(t){(!fc(t)||t.code!=="ENOENT")&&logger.error(`Unable to remove dir ${e}`)}},moveFile(e,t,n){if(this.mkDir(go.dirname(t)),!n?.overwrite&&ji(t))throw new Error(`moveFile: destination exists: ${t}`);n?.overwrite&&this.rmFile(t);try{EI(e,t)}catch(r){if(fc(r)&&r.code==="EXDEV"){xI(e,t),this.rmFile(e);return}throw r}}};var AI={logLevel:"info",userId:"",userName:"",preferredEditor:"",autoSync:!1},Xm=Yt.object({logLevel:Yt.enum(["info","error","debug"]),preferredEditor:Yt.string().optional(),userName:Yt.string().optional(),userId:Yt.string().optional(),autoSync:Yt.boolean().nullable().optional(),autoSyncDebounceMs:Yt.number().optional(),attachmentMaxKb:Yt.number().optional(),viewMode:Yt.enum(["dense","wide"]).optional(),declinedEmailBoards:Yt.array(Yt.string()).optional()}).partial(),TI="config.json",Jm=Dn,gc=()=>NI.join(Jm(),TI),hc=()=>{try{return ot.mkDir(Jm()),u(`Ensured ~/${Vt} exists`,null)}catch{return c(`Unable to create ~/${Vt}`)}},wI=e=>{let t;try{t=JSON.parse(e)}catch{return c(`Invalid ~/${Vt}/config.json JSON`)}let n=Xm.safeParse(t??{});return n.success?u("Parsed config",n.data):c(`Invalid ~/${Vt}/config.json shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},pn=()=>{let e=hc();if(a(e))return c(e.message);let t=gc(),n=ot.readFile(t);return n==null||n.trim()===""?u("No config found, using empty config",{logLevel:"info",autoSync:null,preferredEditor:"",userId:"",userName:"",autoSyncIntervalMs:1e4}):wI(n)},Qm=e=>{let t=hc();if(a(t))return c(t.message);let n=Xm.safeParse(e);if(!n.success)return c(`Invalid config: ${n.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`);let r=gc();try{return ot.writeToFile(r,JSON.stringify(n.data,null,2)+`
|
|
28
|
+
`),u("Config written",null)}catch{return c(`Unable to write ~/${Vt}/config.json`)}},Bt=e=>{let t=pn();if(a(t))return c("Failed to read existing config");let n={...t.value,...e};return Qm(n)},ht=()=>{let e=gc(),t=hc();if(a(t))return c(`Unable to create ~/${Vt}`);if(!(ot.readFile(e)!==null)){let b=Qm(AI);if(a(b))throw new Error(`Unable to create ~/${Vt}/config.json`)}let r=pn();if(a(r))throw new Error(r.message||"Unable to load settings");let{preferredEditor:o,userName:s,userId:i,declinedEmailBoards:l,autoSync:d,autoSyncDebounceMs:m,attachmentMaxKb:p,logLevel:f,viewMode:g}=r.value,y=lo({userId:i,userName:s});if(a(y))return c(y.message);let x=y.value??{userId:i,userName:s};return!x.userName||!x.userId?c(`User name or ID not configured in ~/${Vt}/config.json`):(process.env.EPIQ_LOG_LEVEL=f,u("successfully loaded settings",{gitEmail:null,gitName:null,declinedEmailBoards:l??[],logLevel:f??"debug",preferredEditor:o??"",userName:x.userName,userId:x.userId,autoSync:d??!1,autoSyncIntervalMs:m??1e4,attachmentMaxKb:p??null,viewMode:g??"dense"}))};import{useSyncExternalStore as MI}from"react";var fs={logLevel:"info",autoSyncIntervalMs:null,attachmentMaxKb:null,autoSync:null,preferredEditor:null,userName:null,userId:null,gitEmail:null,gitName:null,declinedEmailBoards:[],viewMode:null},yc=new Set,PI=()=>{for(let e of yc)e()},V=()=>fs,Zm=()=>MI(e=>(yc.add(e),()=>{yc.delete(e)}),()=>fs),je=e=>(fs={...fs,...e},PI(),fs);import{spawn as LI}from"node:child_process";import vc from"node:process";var bc=e=>{let t=vc.platform==="darwin"?"open":vc.platform==="win32"?"cmd":"xdg-open",n=vc.platform==="win32"?["/c","start","",e]:[e];LI(t,n,{detached:!0,stdio:"ignore"}).unref()};import{readFile as Wb,stat as dw}from"node:fs/promises";import{createHash as uw}from"node:crypto";import Er from"chalk";import Rv from"string-width";import{decodeTime as ep}from"ulid";var Hi=1440*60*1e3,gs=(e,t=Date.now())=>e>t+Hi?t:e,Be=e=>gs(ep(e)),ho=e=>{let t=Date.now()+Hi,n=e.find(o=>o!==null&&o<=t)??null;if(n===null)return[...e];let r=null;return e.map(o=>{if(o===null)return null;let s=o<=t?o:r??n;return r=s,s})},yo=e=>{try{return u("Decoded date",new Date(Be(e)))}catch(t){return c("Decoding failed + "+t.message)}},er=e=>{if(!e?.id)return null;try{return ep(e.id)}catch{return null}};import vo from"chalk";var at={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},h={accent:at.cyan,accent2:at.magenta,primary:at.white,secondary:at.grayDark,secondary2:at.grayLight,gray:at.gray,green:at.green,yellow:at.yellow,red:at.red};var L={red:at.red,yellow:at.yellow,green:at.green,blue:at.blue,magenta:at.magenta,cyan:at.cyan},Wi={urgent:L.red,critical:L.red,important:L.red,blocker:L.red,asap:L.red,immediate:L.red,fail:L.red,failure:L.red,broken:L.red,bug:L.red,error:L.red,incident:L.red,outage:L.red,production:L.red,crash:L.red,security:L.red,warning:L.yellow,warn:L.yellow,risky:L.yellow,risk:L.yellow,attention:L.yellow,pending:L.yellow,review:L.yellow,"needs-review":L.yellow,qa:L.yellow,testing:L.yellow,test:L.yellow,validate:L.yellow,verification:L.yellow,staging:L.yellow,check:L.yellow,"follow-up":L.yellow,followup:L.yellow,waiting:L.yellow,blocked:L.yellow,hold:L.yellow,done:L.green,complete:L.green,completed:L.green,success:L.green,ok:L.green,stable:L.green,resolved:L.green,fixed:L.green,closed:L.green,merged:L.green,released:L.green,deployed:L.green,approved:L.green,verified:L.green,working:L.green,healthy:L.green,pass:L.green,passing:L.green,info:L.blue,information:L.blue,note:L.blue,docs:L.blue,documentation:L.blue,doc:L.blue,guide:L.blue,help:L.blue,explanation:L.blue,detail:L.blue,details:L.blue,context:L.blue,design:L.blue,discussion:L.blue,proposal:L.blue,idea:L.blue,feature:L.magenta,enhancement:L.magenta,improvement:L.magenta,refactor:L.magenta,refactoring:L.magenta,cleanup:L.magenta,optimize:L.magenta,optimization:L.magenta,perf:L.magenta,performance:L.magenta,upgrade:L.magenta,migration:L.magenta,modernize:L.magenta,debt:L.magenta,todo:L.cyan,next:L.cyan,planned:L.cyan,plan:L.cyan,future:L.cyan,backlog:L.cyan,investigate:L.cyan,explore:L.cyan,prototype:L.cyan};var Ic={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},tp=(e,t,n)=>Math.max(t,Math.min(n,e)),xc=(e,t,n)=>e+(t-e)*n,np=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},kI=e=>e.toLowerCase().trim(),DI=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,l=s*(1-Math.abs(i%2-1)),d=0,m=0,p=0;i>=0&&i<1?(d=s,m=l):i>=1&&i<2?(d=l,m=s):i>=2&&i<3?(m=s,p=l):i>=3&&i<4?(m=l,p=s):i>=4&&i<5?(d=l,p=s):(d=s,p=l);let f=o-s/2;return[Math.round((d+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},rp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var BI=(e,t,n)=>{let r=tp(n,0,1);return[Math.round(xc(e[0],t[0],r)),Math.round(xc(e[1],t[1],r)),Math.round(xc(e[2],t[2],r))]};var OI=(e,t,n)=>BI(e,t,n),Ec=e=>{let t=np(e)%360,n=DI(t,Ic.stringColor.saturation,Ic.stringColor.lightness);return rp(n)},qe=(e,t=Wi)=>{let n=kI(e??"");return n&&t[n]?t[n]:Ec(n)};var op=e=>{let t=Ic.gradient.stops,n=tp(e,0,1);if(t.length===0)return[0,0,0];if(t.length===1)return t[0];let r=t.length-1,o=n*r,s=Math.min(Math.floor(o),r-1),i=o-s;return OI(t[s],t[s+1],i)},Gi=e=>rp(op(e)),Vi=e=>np(e.toLowerCase().trim())/4294967295,sp=e=>{let t=Vi(e);return op(t)},FI=e=>{let[t,n,r]=sp(e);return{normal:o=>vo.bgRgb(t,n,r).black(o),cursor:o=>vo.bgRgb(t,n,r).white.bold(o)}},Sc=e=>{let[t,n,r]=sp(e);return{fg:o=>vo.rgb(t,n,r)(o),fgCursor:o=>vo.rgb(t,n,r).inverse(o),bg:o=>vo.bgRgb(t,n,r).black(o),bgCursor:o=>vo.bgRgb(t,n,r).white.bold(o)}},zi=e=>FI(e).normal(` ${e} `);var _I="Unknown",Ki=(e,t)=>t?.length?t:e?.length?e:_I,Ye=(e,t)=>{let n=Ki(e,t);return{id:e?.length?e:n,name:n,color:qe(n)}};var bo="removed",yt=(e,t)=>{let n=e.find(r=>r.context===t);return n!==void 0?u("Found node",n):c("Unable to find node in breadcrumb")},ip=["png","jpg","gif","webp"];var et=e=>e.trim().toLowerCase(),tr=e=>{let t=et(e);return t.length>0&&t.length<=254&&/^[^\s@]+@[^\s@]+$/.test(t)},hs=(e,t)=>`${et(e)} ${t}`,Rc=e=>!e.tombstoned,ys=(e,t)=>{let n=et(t),r=new Set;for(let o of Object.values(e))Rc(o)&&o.email===n&&r.add(o.contributor);return[...r]},fn=(e,t)=>{let n=new Set;for(let r of Object.values(e))Rc(r)&&r.contributor===t&&n.add(r.email);return[...n]},ap=e=>{let t=new Map;for(let r of Object.values(e)){if(!Rc(r))continue;let o=t.get(r.email)??new Set;o.add(r.contributor),t.set(r.email,o)}let n=new Map;for(let[r,o]of t){let[s]=[...o];o.size===1&&s&&n.set(r,s)}return n};var qi=(e,t)=>e===t.authorId||e===t.contributor;var ie={WORKSPACE:"WORKSPACE",BOARD:"BOARD",SWIMLANE:"SWIMLANE",TICKET:"TICKET",FIELD:"FIELD",FIELD_LIST:"FIELD_LIST",TEXT:"TEXT",COMMENT:"COMMENT"};function Cc(e){return e.context===ie.WORKSPACE}function _(e){return e.context===ie.TICKET}function nr(e){return e.context===ie.TEXT}function lt(e){return e.context===ie.FIELD}function vs(e){return e.context===ie.FIELD_LIST}var gn=e=>e.context===ie.SWIMLANE,rr=e=>e.context===ie.BOARD,bs=e=>e.context===ie.COMMENT;import{useSyncExternalStore as lA}from"react";var I={DEFAULT:"default",MOVE:"move",HELP:"help",COMMAND_LINE:"cmd-line",PALETTE:"palette",IDENTITY:"identity"};var lp=(e,t)=>e.ctrl&&e.name==="w"||e.meta&&e.name==="backspace"||t==="",cp=(e,t)=>e.meta&&e.name==="b"||t==="\x1Bb",dp=(e,t)=>e.meta&&e.name==="f"||t==="\x1Bf",up=(e,t)=>{if(cp(e,e.sequence))return E.MoveCursorLeftOfWord;if(dp(e,e.sequence))return E.MoveCursorRightOfWord;if(lp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.GetLastCommandFromHistory;case"down":return E.GetNextCommandFromHistory;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}},mp=(e,t)=>{if(cp(e,e.sequence))return E.MoveCursorLeftOfWord;if(dp(e,e.sequence))return E.MoveCursorRightOfWord;if(lp(e,e.sequence))return E.EraseInputWord;switch(e.name){case"tab":return E.AutoCompleteCommand;case"up":return E.NavPreviousItem;case"down":return E.NavNextItem;case"left":return E.MoveCursorLeft;case"right":return E.MoveCursorRight;case"return":return E.Confirm;case"backspace":return t?E.EraseInput:E.ExitCommandLine;case"escape":return E.ExitCommandLine;default:return E.CaptureInput}};import pp from"string-width";function Yi(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e[r]===t[r];)r++;return r}var Fn=(e,t)=>t<=0?"":e.length<=t?e:t<=3?"...".slice(0,t):e.slice(0,t-3)+"...",$I=/\u001B\[[0-9;]*m/,Nc="\x1B[0m",UI=e=>[...new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)].map(({segment:t})=>t),_n=(e,t)=>{if(t<=0)return"";if(pp(e)<=t)return e;if(t<=3)return"...".slice(0,t);let r=t-3,o="",s=0,i=!1;for(let l of e.split(/(\u001B\[[0-9;]*m)/))if(l!==""){if($I.test(l)){o+=l,i=l!==Nc&&l!=="\x1B[m";continue}for(let d of UI(l)){let m=pp(d);if(s+m>r)return`${o}...${i?Nc:""}`;o+=d,s+=m}}return`${o}...${i?Nc:""}`},Re=e=>typeof e!="string"?"":e.replace(/[\x00-\x08\x0B-\x1F\x7F]/g,"").replace(/[\r\n\t]/g," ").replace(/\s+/g," ").trim(),fp=e=>e.charAt(0).toUpperCase()+e.slice(1);var gp=e=>{let t=new Map;for(let n of e){let r=n.toLowerCase();for(let o=1;o<=n.length;o++){let s=r.slice(0,o),i=t.get(s);i?i.push(n):t.set(s,[n])}}return t},hp=(e,t)=>t?e.get(t)??[]:[];var yp=new WeakMap,jI=e=>{let t=yp.get(e);return t||(t=gp(e),yp.set(e,t)),t};var vp=({wordList:e,inputToMatch:t,overlapThreshold:n=1})=>{let r=t.toLowerCase();return hp(jI(e),r).filter(s=>Yi(r,s.toLowerCase())>=n)};var HI={hint:"",hints:[],overlap:0,remainder:""},xp=({inputToMatch:e,lastWord:t,isLastWordCompleted:n,inputString:r},o,s=[])=>{if(n||e===""){let[l]=s;return s.length===1&&l&&!r.trim()?bp("",[l]):HI}let i=vp({wordList:o,inputToMatch:e,overlapThreshold:1});return bp(t,i)},bp=(e,t)=>{let n=t[0]??"",r=Yi(e.toLowerCase(),n.toLowerCase()),[o,s]=n.split(":"),i=r<(o??"").length,l=!!s,p=(l&&i?o:n)+(l&&i?":":" "),f=p.slice(r);return{hint:p,hints:t,overlap:r,remainder:f}};import xs from"node:fs";import Is from"node:path";import{z as xo}from"zod";var Xi="recent-projects.json",WI=20,GI=xo.object({projectId:xo.string().min(1),root:xo.string().min(1),lastOpenedAt:xo.number().finite()}),VI=xo.object({projects:xo.array(GI)}),Ep=()=>Is.join(Dn(),Xi),Io=e=>Is.basename(e)||e,Ip=e=>{let t=Is.resolve(e);try{return xs.realpathSync(t)}catch{return t}},Sp=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,Rp=e=>{if(!ps(e.root))return!1;let t=dn(e.root);return!a(t)&&t.value===e.projectId},Cp=()=>{let e=Ep();if(!xs.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(xs.readFileSync(e,"utf8"))}catch(r){return c(`Invalid ${Xi}: ${r instanceof Error?r.message:String(r)}`)}let n=VI.safeParse(t);return n.success?u("Read recent projects",n.data.projects):c(`Invalid ${Xi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},zI=e=>{let t=Ep();try{xs.mkdirSync(Is.dirname(t),{recursive:!0}),xs.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
29
|
+
`,"utf8")}catch(n){return c(`Unable to write ${Xi}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},$n=({exclude:e}={})=>{let t=Cp();if(a(t))return t;let n=e===void 0?null:Ip(e);return u("Listed recent projects",t.value.filter(r=>n===null||Ip(r.root)!==n).filter(Rp).sort(Sp))},Ji=({root:e,now:t=Date.now()})=>{let n=Is.resolve(e),r=dn(n);if(a(r))return c(r.message);let o=r.value,s=Cp(),i=a(s)?[]:s.value,l=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(d=>d.projectId!==o&&d.root!==n)].filter(Rp).sort(Sp).slice(0,WI);return zI(l)};var Ac=null,Np=e=>{Ac=e},Ap=e=>Ac?Ac(e):[];var Tp=[],Eo=e=>{Tp=e},So=()=>Tp;var Un=()=>{let e=V(),t=!!e.userName?.trim(),n=!!e.preferredEditor?.trim(),r=e.autoSync===!0||e.autoSync===!1,o=wp(),s=o.length>0?null:Tc(),i=s!==null&&(e.declinedEmailBoards??[]).includes(s),l=o.length>0||i||s===null;return{isSetupDone:n&&t&&r&&l,isSetPreferredEditor:n,isSetUserName:t,userName:e.userName,preferredEditor:e.preferredEditor,autoSync:e.autoSync===void 0?null:e.autoSync,isSetAutoSync:r,isSetEmails:l,claimedEmails:o,emailSetupDeclined:i}},Tc=()=>{let e=me(process.cwd());if(a(e))return null;let t=dn(e.value);return a(t)?null:t.value||null},wp=()=>{let{userId:e}=V();return e?Ap(e):[]},Mp=()=>wp().length>0;var wc=()=>{let e=me(process.cwd());if(a(e))return!1;let t=Tt(e.value);return be(t)},Pp=e=>e===!0?"on":e===!1?"off":null,Lp=e=>e==="on"?!0:e==="off"?!1:null,kp=()=>{let e=Un();if(!e.isSetUserName)return"config username ";if(!e.isSetPreferredEditor)return"config editor ";if(!e.isSetAutoSync)return"config autoSync ";if(!wc())return"init";if(!e.isSetEmails){let{gitEmail:t}=V(),n=So()[0]??t;return n&&tr(n)?`config emails ${n}`:"config emails "}return null};var KI=["00KM6CZ900T7180RM46K0JAYNF","00JR3R8E00A1Z4X9FGP9DV0SM5"],[ye,Qi]=KI;var qI=e=>e.props.tags??[],YI=e=>e.props.assignees??[],hn=e=>qI(e).map(t=>N.getTag(t)).filter(t=>!!t),yn=e=>YI(e).map(t=>N.getContributor(t)).filter(t=>!!t),Zi=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?c("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",hn(n))},ea=()=>{let{breadCrumb:e,selectedNode:t}=v(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!_(n)?c("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",yn(n))};var C={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""};var XI=/^(\d+)(h|d|w|mo|y)$/,JI=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,QI=({year:e,month:t,day:n,hour:r=0,minute:o=0})=>{let s=new Date(e,t-1,n,r,o);return s.getFullYear()===e&&s.getMonth()===t-1&&s.getDate()===n&&s.getHours()===r&&s.getMinutes()===o},ZI=(e,t=new Date)=>{let n=e.match(XI);if(!n)return null;let[,r,o]=n,s=Number(r);if(!Number.isInteger(s)||s<=0)return null;let i=new Date(t);switch(o){case"h":return i.setHours(i.getHours()-s),i;case"d":return i.setDate(i.getDate()-s),i;case"w":return i.setDate(i.getDate()-s*7),i;case"mo":return i.setMonth(i.getMonth()-s),i;case"y":return i.setFullYear(i.getFullYear()-s),i;default:return null}},eE=e=>{let t=e.match(JI);if(!t)return null;let[,n,r,o,s,i]=t,l=Number(n),d=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return QI({year:l,month:d,day:m,hour:p,minute:f})?new Date(l,d-1,m,p,f):null},Lr=e=>{let t=e.trim().toLowerCase();return ZI(t)??eE(t)};var Dp=/^(\d+)(s|m)?$/,ta=e=>{let t=e.trim().toLowerCase().match(Dp);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},na=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&Dp.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},Bp=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,tE=[{unit:"h",from:1,to:24},{unit:"d",from:1,to:7},{unit:"w",from:1,to:52},{unit:"mo",from:1,to:12},{unit:"y",from:1,to:5}],Mc=(e=tE)=>{let t=[];for(let{unit:n,from:r,to:o}of e)for(let s=r;s<=o;s++)t.push(`${s}${n}`);return t};var nE=["BOARD","TICKET","SWIMLANE","COMMENT"],ve={EDITOR:"editor",VIEW:"view",USERNAME:"username",EMAILS:"emails",EMAILS_UNCLAIM:"emails-unclaim",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},Mt={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Xe={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},rE=[ve.EDITOR,ve.VIEW,ve.USERNAME,ve.EMAILS,ve.EMAILS_UNCLAIM,ve.AUTOSYNC,ve.SYNC_DEBOUNCE_MS,ve.ATTACHMENT_MAX_KB,ve.LOG_LEVEL],oE=(e=v().selectedNode?.context)=>{switch(e){case"TICKET":return[Mt.TITLE,Mt.DESCRIPTION];case"BOARD":case"SWIMLANE":return[Mt.TITLE];case"COMMENT":return[Mt.COMMENT];default:return[]}},Lc=[String(3e3),"5000","15000","30000","60000"],kc=["250","500","1000"],_p=["10s","20s","30s","45s"],kr=[C.EXIT,C.SYNC,C.HELP,C.EXPORT,C.CONFIG,C.YANK],ra=[C.NEW,C.EDIT,C.DELETE,C.MOVE],Pc=[C.TAG,C.UNTAG,C.ASSIGN,C.UNASSIGN,C.CLOSE_ISSUE,C.RE_OPEN_ISSUE,C.EDIT,C.COMMENT],Op=[C.FILTER,C.PEEK,C.REPLAY],sE={WORKSPACE:[...kr,...ra],BOARD:[...Op,...kr,...ra],SWIMLANE:[...Op,...kr,...ra],TICKET:[...kr,...ra,...Pc],FIELD:[...kr,...Pc],FIELD_LIST:[...kr,...Pc],TEXT:[...kr],COMMENT:[C.EDIT,C.DELETE,C.YANK]},iE=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Es=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&_(n)),Fp=e=>e.parentNodeId===ye,aE=({selectedNode:e,breadCrumb:t})=>{let n=oE(e?.context);return Es({breadCrumb:t,selectedNode:e})?n.includes(Mt.DESCRIPTION)?n:[...n,Mt.DESCRIPTION]:n},lE=({selectedNode:e,breadCrumb:t})=>{let n=Es({breadCrumb:t,selectedNode:e});return n?[Xe.REF,Xe.TITLE,...n.props?.description?.trim()?[Xe.DESCRIPTION]:[],...hn(n).length>0?[Xe.TAGS]:[],...yn(n).length>0?[Xe.ASSIGNEES]:[]]:e?[Xe.REF,Xe.TITLE]:[]},Dc=()=>{let e=$n({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},cE=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=Un();if(!r)return[C.HELP,C.CONFIG];if(!wc())return[C.HELP,C.INIT,C.OPEN];if(t)return[C.HELP,C.PEEK,C.REPLAY,C.EXPORT,C.CONFIG,C.YANK];let o=e?.context,s=o&&nE.includes(o),i=[...new Set([...n,e].map(d=>d?.context).flatMap(d=>d?sE[d]:[]))],l=Es({breadCrumb:n,selectedNode:e});return i.filter(d=>d===C.MOVE?!1:d===C.YANK?!!(l??e):d===C.EDIT?s||!!l:d===C.DELETE?s:d===C.UNTAG?!!(l&&hn(l).length>0):d===C.UNASSIGN?!!(l&&yn(l).length>0):d===C.RE_OPEN_ISSUE?!!(l&&Fp(l)):d===C.CLOSE_ISSUE?!!(l&&!Fp(l)):!0)},Oe=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=v())=>{let s=t.context??"WORKSPACE";return{[C.NONE]:cE({breadCrumb:o,readOnly:r,selectedNode:n}),[C.EXIT]:["confirm"],[C.EXPORT]:[],[C.SYNC]:[],[C.INIT]:[],[C.OPEN]:e===C.OPEN?Dc():[],[C.HELP]:[],[C.PEEK]:[...Mc(),"now","prev","next"],[C.REPLAY]:[...Mc()],[C.EDIT]:aE({selectedNode:n,breadCrumb:o}),[C.YANK]:lE({selectedNode:n,breadCrumb:o}),[C.COMMENT]:[],[C.DELETE]:["confirm"],[C.RE_OPEN_ISSUE]:["confirm"],[C.CLOSE_ISSUE]:["confirm"],[C.MOVE]:["start","confirm","next","previous","jump-next","jump-previous","to-next","to-previous","cancel"],[C.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[C.TAG]:[...new Set([...Object.keys(Wi),...N.getExistingTags()])],[C.UNTAG]:[...Zi()?.value?.map(({name:l})=>l)??[]],[C.UNASSIGN]:[...ea()?.value?.map(({name:l})=>l)??[]],[C.ASSIGN]:N.getExistingAssignees(),[C.NEW]:iE(s),[C.CONFIG]:[...rE]}[e]??[]};import Qp from"chalk";var $p=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import fE from"zod";import dE from"node:crypto";import Ss from"node:fs";import Hp from"node:path";var Up="/media/",jp=e=>`${Up}${e}`,Bc=(e,t)=>`})`;var vn=500,uE=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,Br=(e,t)=>`${e}.${t}`,mE=e=>uE.test(e),Wp=e=>e.length>=8&&e.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))?u("Sniffed image type","png"):e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?u("Sniffed image type","jpg"):e.length>=6&&(e.subarray(0,6).equals(Buffer.from("GIF87a","ascii"))||e.subarray(0,6).equals(Buffer.from("GIF89a","ascii")))?u("Sniffed image type","gif"):e.length>=12&&e.subarray(0,4).equals(Buffer.from("RIFF","ascii"))&&e.subarray(8,12).equals(Buffer.from("WEBP","ascii"))?u("Sniffed image type","webp"):c(`Unsupported image format. Allowed: ${ip.join(", ")}`),Gp=e=>dE.createHash("sha256").update(e).digest("hex"),pE=(e,t=vn)=>{if(e.length===0)return c("Attachment is empty");if(e.length>t*1024)return c(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=Wp(e);return a(n)?n:u("Validated attachment data",{hash:Gp(e),ext:n.value,bytes:e.length})},Vp=(e,t,n=vn)=>{let r=pE(t,n);if(a(r))return r;let o=ms(e),s=Hp.join(o,Br(r.value.hash,r.value.ext));try{Ss.existsSync(s)||(Ss.mkdirSync(o,{recursive:!0}),Ss.writeFileSync(s,t))}catch(i){return c(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},zp=(e,t,n=vn)=>{if(!mE(t))return c("Invalid attachment file name");let r=Hp.join(ms(e),t);if(!Ss.existsSync(r))return c("Attachment blob not found");let o;try{o=Ss.readFileSync(r)}catch(d){return c(`Unable to read attachment blob: ${d instanceof Error?d.message:String(d)}`)}if(o.length>n*1024)return c(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(Gp(o)!==s)return c("Attachment blob does not match its content hash");let l=Wp(o);return a(l)?l:l.value!==i?c("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var Rs=50,Cs=5e3,Kp=()=>{let e=ae().commandMeta.inputString,t=fE.coerce.number().int().min(Rs).max(Cs).safeParse(e);if(!t.success)return c(`Attachment size cap must be ${Rs}-${Cs} KB (default ${vn})`);let n=Bt({attachmentMaxKb:t.data});return a(n)?n:(je({attachmentMaxKb:t.data}),u(`Attachment size cap set to ${t.data} KB`,null))};var ct=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as gE}from"node:crypto";var hE="0123456789ABCDEFGHJKMNPQRSTVWXYZ",yE=e=>{let t=gE("sha256").update(e).digest(),n=0n;for(let o=0;o<16;o++)n=n<<8n|BigInt(t[o]);let r="";for(let o=0;o<26;o++){let s=BigInt((25-o)*5);r+=hE[Number(n>>s&31n)]}return r},qp=new Map,Pe=(e,t)=>{let n=`${e}:virtual:${t}`,r=qp.get(n);if(r!==void 0)return r;let o=yE(n);return qp.set(n,o),o};import Yp from"chalk";var Ce=e=>Yp.dim(e),He=e=>Yp.hex(h.primary)(e),We=({prefix:e="",wordList:t,postfix:n="",noOfHints:r=100,inputString:o,minLengthForHints:s=1})=>{let i=o.trim();if(i.length<s)return"";let p=[...t.filter(Boolean).filter(f=>f.startsWith(i))].sort((f,g)=>Vi(f)-Vi(g)).slice(0,r).map(f=>zi(f)).join(" ");return p?`${Ce(e)}${p}${Ce(n)}`:""};var bn={None:"none",Invalid:"invalid",Valid:"valid"};var vE=["BOARD","TICKET","SWIMLANE"],Xp=()=>{let e=v().selectedNode;if(!e?.context)return z({message:Ce("Missing target context")});if(vE.includes(e.context))return le();if(e.parentNodeId){let t=v().nodes[e.parentNodeId];if(t?.id===Pe(t?.parentNodeId??"","comments"))return le()}return z({message:Ce("Command not available in this context")})},fe="<ENTER> to confirm",bE=()=>{let{userId:e}=V(),t=xe();return!e||a(t)?[]:fn(t.value.emailLinks,e)},le=(e="",t=[],n=!0)=>({message:n?Ce(e):e,validity:bn.Valid,completionWordList:t}),z=({message:e,completionWordList:t=[]})=>({validity:bn.Invalid,message:e,completionWordList:t}),Co=e=>e.length===0,Jp=(e,t)=>{let n=yt(v().breadCrumb,"BOARD");if(a(n))return z({message:He("Command is not applicable in this context")});let r=yo(n.value.id);return a(r)?z({message:He(`Unable to ${t}: board id is not a valid ULID`)}):Bp({date:e,horizonDate:r.value})?null:z({message:He(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},oa=e=>` ${Qp.hex("#000").bgHex(qe(e))(` ${e} `)} `,Oc=({modifier:e})=>{let t="confirm";return e===t?le(fe):z({message:Co(e)?Ce("if you are certain, enter ")+zi(t):"",completionWordList:[t]})},xE=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?z({message:Ce(n)}):le():z({message:Co(r)?t:"",completionWordList:[...e]}),Ro=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>Co(n)&&Co(r)?z({message:e,completionWordList:[]}):le(t??fe),IE=({modifier:e,inputString:t})=>{let n=Dc();return!Co(e)||!Co(t)?le(fe):z({message:n.length?Ce("number from the list, or a path"):Ce("path to an epiq project"),completionWordList:n})},EE=({modifier:e,inputString:t})=>{let n=Oe(C.CONFIG);if(!n.includes(e))return z({message:We({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case ve.EDITOR:{let r=[...$p];return t.trim()?r.includes(t.trim())?le(fe):z({message:We({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):z({message:We({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ve.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?le(fe):z({message:We({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case ve.USERNAME:{let r=V().gitName,o=r?[r]:[],s=t.trim(),i=o.filter(m=>m.startsWith(s)),d=i.length===1&&i[0]===s?"":We({prefix:"name: ",wordList:o,inputString:s,minLengthForHints:0});return s?d?le(`${d} ${Ce(fe)}`,o,!1):le(fe,o):z({message:d||He("Enter a user name. Saved in ")+Qp.bgBlack("~/.epiq-global/config.json"),completionWordList:o})}case ve.EMAILS:{let r=V().gitEmail,o=So(),s=o.length>0||!r?o:[r],i=[...s,"none"],l=t.trim(),d=(x,b)=>z({message:We({prefix:x,wordList:i,noOfHints:3,inputString:b,minLengthForHints:0}),completionWordList:i});if(!l)return le(`${fe} to see your addresses, or name one`,i);let m=l.split(/[,\s]+/).filter(Boolean),p=m[m.length-1]??"",f=x=>x==="none"||s.includes(x.toLowerCase()),g=x=>i.some(b=>b.startsWith(x.toLowerCase())),y=m.filter(x=>!f(x)&&!g(x));return y.length>0?z({message:He(`no address here matches ${y.join(", ")} \u2014 pick one from the list, or its number`),completionWordList:i}):f(p)?le(fe):d("",p)}case ve.EMAILS_UNCLAIM:{let r=bE(),o=t.trim();return r.length===0?z({message:He("you have not claimed any addresses"),completionWordList:[]}):o&&r.includes(o.toLowerCase())?le(fe):z({message:We({prefix:"give an address back ",wordList:r,noOfHints:3,inputString:o,minLengthForHints:0}),completionWordList:r})}case ve.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?le(fe):z({message:We({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case ve.AUTOSYNC:{let r=["on","off"],o=V().autoSync;if(!r.includes(t.trim())){let s=Pp(o);return z({message:We({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return le(fe)}case ve.ATTACHMENT_MAX_KB:{let r=V().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<Rs||o>Cs){let s=We({prefix:" examples: ",wordList:kc,minLengthForHints:0,inputString:t});return z({message:He(`provide a size cap in KB (${Rs}-${Cs}). current: ${r??vn} KB.`)+s,completionWordList:kc})}return le(fe)}case ve.SYNC_DEBOUNCE_MS:{let r=V().autoSyncIntervalMs,o=co(t);if(!t.trim()||o===null){let s=We({prefix:" examples: ",wordList:Lc,minLengthForHints:0,inputString:t});return z({message:He(`provide a duration between ${3e3}ms and ${864e5}ms. current duration: ${r}ms.`)+s,completionWordList:Lc})}return le(fe)}default:return z({message:He("Unknown config option"),completionWordList:n})}},SE=({modifier:e,inputString:t})=>{let n=Oe(C.EDIT);if(!n.length)return z({message:He("Command not available in this context")});if(!n.includes(e)){let r=We({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return z({message:r||He("Unknown edit option"),completionWordList:n})}switch(e){case Mt.COMMENT:return t.trim()?le(fe):z({message:Ce("write a comment...")});case Mt.TITLE:return le(fe);case Mt.DESCRIPTION:{let{preferredEditor:r}=V();return r?le(Ce("<ENTER> to edit in ")+r):z({message:"No editor selected"})}default:return z({message:He("Unknown edit option"),completionWordList:n})}},RE=({modifier:e})=>{let t=Oe(C.YANK);return t.length?t.includes(e)?le(fe+Ce(" and copy to clipboard")):z({message:We({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):z({message:He("Nothing selected to copy from")})},CE={[C.EXPORT]:()=>le(fe+Ce(", and create export markdown file")),[C.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return le(fe);let n={message:Ce("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=Lr(r);if(!r||!o)return z(n);let s=Jp(o,"peek");return s||le(fe)},[C.REPLAY]:e=>{let{dateInput:t,durationInput:n}=na(e.modifier,e.inputString),r={message:Ce("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=Lr(t);if(!t||!o)return z(r);let s=Jp(o,"replay");return s||(n&&ta(n)===null?z({message:He("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):le("<ENTER> to replay board history",n?_p:[]))},[C.EXIT]:()=>le(fe+Ce(" and exit the application")),[C.INIT]:()=>le(fe),[C.OPEN]:IE,[C.PALETTE]:()=>le(fe),[C.FILTER]:e=>{if(e.modifier==="clear")return le(fe);let t=s=>Oe(C.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return z({message:We({wordList:Oe(C.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Oe(C.FILTER)});let n=Object.values(v().tags).map(s=>s.name),r=Object.values(v().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?z({message:We({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):le():z({message:We({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[C.NONE]:e=>{let t=Oe(C.NONE);return z({message:We({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[C.NEW]:e=>xE({list:Oe(C.NEW),hint:We({wordList:Oe(C.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[C.HELP]:()=>le(fe),[C.EDIT]:SE,[C.COMMENT]:e=>{let t=Ro({hint:Ce(`write a comment (max ${4e3} char)...`),onOk:Ce(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===bn.Invalid?t:e.inputString.length>4e3?le(He("max input exceeded")):t},[C.CONFIG]:EE,[C.YANK]:RE,[C.DELETE]:e=>{let t=Xp();return t.validity==="invalid"?t:Oc(e)},[C.CLOSE_ISSUE]:e=>Oc(e),[C.RE_OPEN_ISSUE]:e=>Oc(e),[C.MOVE]:e=>{let t=Xp();return t.validity==="invalid"?t:Ro({hint:We({prefix:"hey hacker! These commands are blocked for you... ",wordList:Oe(C.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[C.TAG]:e=>{let n=N.getExistingTags().slice(0,10).map(oa).join("");return Ro({hint:n.length?Ce("create tag or reuse:")+n+Ce(""):Ce("create tag ...")})(e)},[C.UNTAG]:e=>{let t=Zi();if(a(t))return z({message:He("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(oa).slice(0,10);return n.length?Ro({hint:Ce(" ... ")+n.join("")})(e):z({message:He("Issue has no tags"),completionWordList:[]})},[C.ASSIGN]:e=>{let t=N.getExistingAssignees().map(oa).slice(0,10);return Ro({hint:Ce("assignees... ")+t.join("")})(e)},[C.UNASSIGN]:e=>{let t=ea();if(a(t))return z({message:He("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(oa).slice(0,10);return n.length?Ro({hint:Ce("remove assignee... ")+n.join("")})(e):z({message:He("Issue has no assignees"),completionWordList:[]})},[C.SYNC]:()=>le(fe)},Zp=Object.fromEntries(Object.entries(CE).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var sa=["add","fix","bug","log","run","api","cli","ui","ux","test","mock","stub","sync","hash","sign","fork","push","pull","lock","warn","leak","hang","node","seed","lint","edit","save","load","read","send","drop","swap","wrap","port","host","role","user","auth","flag","diff","perf","docs","todo","task","team","epic","spec","remove","update","change","improve","enhance","refactor","rewrite","redesign","implement","build","create","delete","rename","migrate","upgrade","downgrade","revert","rollback","restore","replace","deprecate","cleanup","simplify","optimize","stabilize","harden","document","clarify","investigate","debug","reproduce","triage","mitigate","remediate","resolve","escalate","verify","validate","benchmark","profile","audit","monitor","instrument","configure","provision","deploy","release","publish","integrate","automate","support","enable","disable","prevent","handle","ensure","prioritize","estimate","schedule","track","install","uninstall","enforce","expose","extract","inject","override","extend","customize","localize","translate","redirect","forward","dispatch","broadcast","subscribe","unsubscribe","register","allocate","reserve","persist","retrieve","archive","expire","refresh","reload","reset","recover","replay","retry","scaffold","bootstrap","finalize","terminate","suspend","resume","cancel","abort","notify","alert","trigger","debounce","frontend","backend","fullstack","infrastructure","architecture","integration","application","environment","framework","platform","service","component","module","gateway","pipeline","container","orchestrator","middleware","endpoint","interface","database","datastore","cache","queue","scheduler","worker","daemon","runtime","library","package","plugin","extension","webhook","microservice","monolith","repository","namespace","cluster","sandbox","tenant","dashboard","console","portal","client","server","browser","mobile","desktop","kernel","driver","protocol","schema","migration","fixture","template","snippet","config","manifest","bundle","exception","incident","defect","regression","degradation","malfunction","instability","intermittent","workaround","failure","outage","crash","freeze","corruption","inconsistency","severity","criticality","diagnostics","analysis","blocker","flaky","timeout","mismatch","misconfiguration","boundary","overflow","underflow","panic","stacktrace","breakage","breaking","oversight","ambiguity","discrepancy","anomaly","authorize","authenticate","confidentiality","availability","accessibility","reliability","compliance","governance","encrypt","decrypt","integrity","traceability","accountability","protection","privileges","permissions","sanitize","escape","vulnerability","exposure","secrets","credentials","certificate","session","cookie","identity","tokenization","rotation","scanning","hardening","threat","exploit","payload","injection","phishing","breach","dependency","orchestrate","synchronize","compatibility","incompatibility","interoperability","observability","telemetry","discovery","registration","coordination","distribution","isolation","virtualization","networking","routing","proxy","firewall","balancer","failover","topology","replica","shard","region","capacity","quota","metrics","logging","tracing","alerting","monitoring","heartbeat","liveness","rollover","serialize","deserialize","initialize","instantiate","propagate","aggregate","consolidate","normalize","standardize","transform","reconcile","correlate","index","partition","enrich","filter","stream","batch","parse","encode","decode","compress","decompress","deduplicate","paginate","query","ingest","export","import","backup","snapshot","mapping","record","dataset","metadata","checksum","rollup","lookup","cursor","truncate","concurrency","parallelism","contention","deadlock","throttle","backpressure","fragmentation","saturation","exhaustion","replicate","redundancy","obsolescence","starvation","overload","latency","throughput","scalability","bottleneck","memoize","prefetch","warmup","autoscale","horizontal","vertical","elasticity","recursion","allocation","leakage","garbage","collection","pooling","buffering","caching","eviction","staleness","modularize","encapsulate","abstraction","extensibility","configurability","maintainability","recoverability","readability","testability","debuggability","reusability","simplicity","consistency","linting","formatting","typecheck","coverage","tooling","scaffolding","boilerplate","technical","cleanliness","naming","comments","docstring","testing","unittest","mocking","stubbing","assertion","smoke","sanity","fuzzing","flakiness","harness","scenario","baseline","performance","functionality","requirement","recommendation","improvement","enhancement","description","acceptance","criteria","deliverable","milestone","iteration","backlog","roadmap","followup","hotfix","patch","changelog","rollout","feature","spike","proposal","specification","priority","sprint","story","subtask","assignee","reviewer","reproduction","context","expected","actual","impact","workflow","version","tracking","discussion","decision","tradeoff","feedback","approval","planning","breakdown","scoping"];var NE=3,AE=new Set(["the","and","for","are","but","not","you","all","any","can","was","one","our","out","use","this","that","with","have","from","will","your","they","them","then","than","when","what","were","been","into","should","would","could","about"]),TE=e=>{let t=[];for(let n of Object.values(e.nodes)){n.title&&t.push(n.title);let r=n.props;typeof r.description=="string"&&t.push(r.description),typeof r.value=="string"&&t.push(r.value)}for(let n of Object.values(e.tags))t.push(n.name);for(let n of Object.values(e.contributors))t.push(n.name);for(let n of Object.values(e.comments))t.push(n.md);return t},wE=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=NE&&!AE.has(t)&&!/^\d+$/.test(t)),ME=e=>{let t=new Map;for(let s of TE(e))for(let i of wE(s))t.set(i,(t.get(i)??0)+1);let n=[...t.entries()].sort((s,i)=>i[1]-s[1]||s[0].localeCompare(i[0])).map(([s])=>s),r=new Set(n),o=sa.filter(s=>!r.has(s));return[...n,...o]},ef=sa,tf=-1,nf=()=>{let e=xe();if(a(e))return sa;let t=e.value,n=t.eventLog.length;return n!==tf&&(ef=ME(t),tf=n),ef};var rf=e=>Object.values(C).includes(e),of=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:l,completionWordList:d}=Zp[n].validate(n,r,s),m=n!==C.PEEK&&n!==C.REPLAY,p=o==="command"||o==="modifier"?Oe(n):m?nf():[],{mode:f}=v(),g=f===I.COMMAND_LINE?i??"":"",y=[...d,...p];return{validity:l,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?xp(e,y,d):{hint:"",hints:[],remainder:"",overlap:0}}};var sf=e=>{let t=e.trimStart(),n=LE(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=kE(e),l=rf(r)?r:null,d=l!==null,m=r!=="",p=l?Oe(l)??[]:[],f=l&&p.includes(o)?o:"",g="word";n.length===0||n.length===1&&!s?g="command":(n.length===1&&s||n.length===2&&!s)&&(g="modifier");let y=s?"":i,x=PE(t,l,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:l,isCommandKeyword:d,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:y,inputString:x}},PE=(e,t,n)=>{let r=e;return t&&r.startsWith(t)&&(r=r.slice(t.length)),r=r.replace(/^\s+/,""),n&&r.startsWith(n)&&(r=r.slice(n.length),r=r.replace(/^\s+/,"")),r},LE=e=>e.trim()?e.trim().split(/\s+/):[],kE=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as DE}from"react";var No=e=>e===Fc||e===":",Fc=" ",As=40,dt={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:bn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},_c=new Set,af=()=>{for(let e of _c)e()},$c=e=>(_c.add(e),()=>_c.delete(e)),Ft=e=>{let n=e(dt),r=sf(n.value),o=n.cursorPosition===n.value.length;dt={...n,commandMeta:of(r,o)},af()},Ts=({message:e,status:t})=>{let n=structuredClone(dt);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,dt=n,af(),u(e,null)},Uc=e=>{Ft(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},jc=e=>{Ft(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&No(n[o-1]);)o--;for(;o>0&&!No(n[o-1]);)o--}else{for(;o<n.length&&!No(n[o]);)o++;for(;o<n.length&&No(n[o]);)o++}return{...t,cursorPosition:o}})},lf=()=>{Ft(e=>{let t=e.value.slice(e.cursorPosition),n=Math.max(0,e.cursorPosition-1);return{...e,value:e.value.slice(0,n)+t,cursorPosition:n,commandIsPending:!1}})},cf=()=>{Ft(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&No(t[r-1]);)r--;for(;r>0&&!No(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},ia=e=>{Ft(t=>{let n=Math.max(0,Math.min(t.cursorPosition,t.value.length)),r=t.value.slice(0,n),o=t.value.slice(n),s=e(r,t.commandMeta.autoCompletion),i=s+o,l=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:l,commandIsPending:!1}})},df=()=>{Ft(e=>({...e,commandIsPending:!0}))},Q=e=>{Ft(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},uf=({addToHistory:e=!0,line:t})=>{Ft(n=>{let r=t??n.value;return{...n,commandHistory:e&&r.trim()?[r,...n.commandHistory].slice(0,As):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}})},mf=e=>{Ft(t=>({...t,commandHistory:e.slice(0,As),commandHistoryIndex:-1}))},pf=()=>{Ft(e=>e.commandHistoryIndex===-1?e:{...e,commandHistoryIndex:-1})},ff=()=>{Ft(e=>{let t=Math.min(e.commandHistoryIndex+1,e.commandHistory.length-1),n=e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},gf=()=>{Ft(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},ae=()=>dt,hf=()=>DE($c,ae,ae),aa=()=>{let[e,...t]=dt.value.split(Fc);return t.join(Fc).trim()};var E={NavPreviousItem:"navPreviousItem",NavNextItem:"navNextItem",NavPreviousItemJump:"navPreviousItemJump",NavNextItemJump:"navNextItemJump",NavToPreviousContainer:"navToPreviousContainer",NavToNextContainer:"navToNextContainer",MovePreviousItem:"movePreviousItem",MoveNextItem:"moveNextItem",MovePreviousItemJump:"movePreviousItemJump",MoveNextItemJump:"moveNextItemJump",MoveToPreviousContainer:"moveToPreviousContainer",MoveToNextContainer:"moveToNextContainer",Confirm:"confirm",Exit:"exit",ViewHelp:"viewHelp",HideHelp:"hideHelp",InitMove:"initMove",ConfirmMove:"confirmMove",Delete:"Delete",InitCommandPalette:"initCommandPalette",InitCommandLine:"initCommandLine",ExitCommandLine:"exitCommandLine",CaptureInput:"captureInput",EraseInput:"eraseInput",AddItem:"addItem",GetLastCommandFromHistory:"getLastCommandFromHistory",GetNextCommandFromHistory:"getNextCommandFromHistory",AutoCompleteCommand:"autoCompleteCommand",MoveCursorLeft:"MoveCursorLeft",MoveCursorRight:"MoveCursorRight",MoveCursorLeftOfWord:"MoveCursorLeftOfWord",MoveCursorRightOfWord:"MoveCursorRightOfWord",EraseInputWord:"EraseInputWord",None:"None",Edit:"edit",EditTitle:"editTitle",EditDescription:"editDescription",Yank:"yank",OpenInEditor:"openInEditor",MarkDiffLine:"markDiffLine",CommentOnDiffLine:"commentOnDiffLine",SetViewDense:"SetViewDense",SetViewWide:"SetViewWide"},BE=e=>e.shift===!0,OE={[E.NavPreviousItem]:E.NavPreviousItemJump,[E.NavNextItem]:E.NavNextItemJump,[E.MovePreviousItem]:E.MovePreviousItemJump,[E.MoveNextItem]:E.MoveNextItemJump};function FE(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function _E(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function $E(e,t,n){let r=v().contextNode.childNavigationAcrossParents;switch(t){case"up":return e==="vertical"?n.prevItem:r?n.prevContainer:null;case"down":return e==="vertical"?n.nextItem:r?n.nextContainer:null;case"left":return e==="horizontal"?n.prevItem:r?n.prevContainer:null;case"right":return e==="horizontal"?n.nextItem:r?n.nextContainer:null}}function yf(e,t){let n=ae();if(e.sequence==="?"&&t!==I.PALETTE)return E.InitCommandPalette;if(e.sequence===":"&&t!==I.COMMAND_LINE)return E.InitCommandLine;if(t===I.MOVE)switch(e.name){case"m":case"return":return E.ConfirmMove}if(t===I.COMMAND_LINE)return up(e,n.value);if(t===I.PALETTE)return mp(e,n.value);let r=FE(e)||_E(e);if(r)return UE(r,t,BE(e));if(e.ctrl&&e.name==="c")return E.Exit;switch(e.name){case"r":return E.EditTitle;case"e":return E.EditDescription;case"n":return E.AddItem;case"m":return E.InitMove;case"d":return E.Delete;case"y":return E.Yank;case"o":return E.OpenInEditor;case"s":return E.MarkDiffLine;case"c":return E.CommentOnDiffLine;case"return":return E.Confirm;case"space":return E.Confirm;case"v":return V().viewMode==="wide"?E.SetViewDense:E.SetViewWide;case"q":case"escape":return E.Exit;default:return null}}function UE(e,t,n=!1){let r=t===I.MOVE?{prevItem:E.MovePreviousItem,nextItem:E.MoveNextItem,prevContainer:E.MoveToPreviousContainer,nextContainer:E.MoveToNextContainer}:{prevItem:E.NavPreviousItem,nextItem:E.NavNextItem,prevContainer:E.NavToPreviousContainer,nextContainer:E.NavToNextContainer},o=$E(v().contextNode.childRenderAxis,e,r);return!o||!n?o:OE[o]??o}import{ulid as WE}from"ulid";var ws=24n,jE=ws*4n,Xt=(1n<<jE)-1n,HE=/^[0-9a-f]+$/;function vf(e){return!e||!HE.test(e)?c(`Invalid hex rank: ${e}`):u("Converted rank to bigint",BigInt("0x"+e))}function Pt(e,t=ws){if(e<0n)return c("Negative rank not allowed");let n=e.toString(16);return u("Converted bigint to hex rank",n.padStart(Number(t),"0"))}function vt(e,t){if(!e&&!t)return Pt(Xt/2n,ws);let n=e?vf(e):u("Resolved lower bound",0n);if(a(n))return n;let r=t?vf(t):u("Resolved upper bound",Xt);if(a(r))return r;let o=n.value,s=r.value;if(s<=o)return c("Neighbouring ranks leave no space between them");let i=(o+s)/2n;return i===o||i===s?c("No rank space available between neighbors"):Pt(i,ws)}function bf(e){if(e<=0)return u("Resolved empty rank list",[]);let t=BigInt(e),n=[];for(let r=0;r<e;r++){let o=Xt*BigInt(r+1)/(t+1n),s=Pt(o,ws);if(a(s))return s;n.push(s.value)}return u("Resolved evenly spaced ranks",n)}var D=({userId:e})=>({userId:e}),xf=e=>({action:e.action,payload:e.payload});var Hc=["init.workspace","add.workspace","add.board","add.swimlane","add.issue","add.field","edit.title","delete.node","create.tag","tombstone.tag","restore.tag","create.contributor","rename.contributor","tombstone.contributor","restore.contributor","add.issue.assignee","remove.issue.assignee","add.issue.tag","remove.issue.tag","move.node","edit.description","add.issue.comment","edit.issue.comment","delete.issue.comment","add.issue.attachment","delete.issue.attachment","close.issue","reopen.issue","lock.node","rebalance.children","link.contributor.user","link.contributor.email","unlink.contributor.email"];var SD=new Set(Hc);var Wc=(e,t)=>{let n=Ie(e),r=bf(n.length);if(a(r))return r;let o={};for(let s=0;s<n.length;s++){let i=n[s],l=r.value[s];if(!i||!l)return c("Unable to assign rebalance rank");o[i.id]=l}return u("Created rebalance event",{id:WE(),action:"rebalance.children",payload:{parent:e,ranks:o},...D(t)})};import{z as Or}from"zod";var If=1,Ef=Or.tuple([Or.string().min(1),Or.string().min(1).nullable()]),GE=Or.looseObject({v:Or.literal(If),id:Ef}),FD=Or.looseObject({v:Or.number().int().positive(),id:Ef}),VE=e=>Object.prototype.hasOwnProperty.call(e,"__proto__"),zE=e=>{let t={};for(let n of Object.keys(e))n!=="__proto__"&&(t[n]=e[n]);return t},Sf=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return c("Invalid persisted event envelope: expected an object");let{v:t,id:n}=e;if(typeof t!="number"||!Number.isSafeInteger(t)||t<=0)return c("Invalid persisted event envelope: v");if(!Array.isArray(n)||n.length!==2)return c("Invalid persisted event envelope: id");let[r,o]=n;return typeof r!="string"||r.length===0?c("Invalid persisted event envelope: id.0"):o!==null&&(typeof o!="string"||o.length===0)?c("Invalid persisted event envelope: id.1"):u("Parsed persisted event envelope",VE(e)?zE(e):e)};var KE=[1];var qE=new Set(KE),Gc=e=>qE.has(e),Rf=e=>{let t=GE.safeParse(e);return t.success?u("Parsed persisted event",t.data):c(`Invalid persisted event: ${t.error.issues.map(n=>n.path.join(".")||n.message).join(", ")}`)},Vc=(e,t)=>{let n={[e.action]:e.payload,v:If,id:t};return Rf(n)};import ks from"node:fs";import pa from"node:path";import{decodeTime as rS}from"ulid";import{z as Qc}from"zod";import zc from"node:fs";import YE from"node:path";var Ms=e=>e?.code==="ENOENT",Kc=3,qc=e=>zc.readdirSync(e).filter(t=>t.endsWith(".jsonl")).sort(),xn=e=>{let t=Et(e);for(let n=1;;n++){if(!zc.existsSync(t))return"none";let r=[],o=!1;for(let s of qc(t))try{let{size:i,mtimeMs:l}=zc.statSync(YE.join(t,s));r.push(`${s}:${i}:${l}`)}catch(i){if(!Ms(i))throw i;if(n<Kc){o=!0;break}}if(!o)return r.join("|")}},Cf=e=>new Map(e.split("|").filter(Boolean).map(t=>{let n=t.indexOf(":");return[t.slice(0,n),t.slice(n+1)]})),Yc=(e,t,n)=>{let r=Cf(t),o=xn(e),s=Cf(o);for(let[i,l]of s)if(i!==n&&r.get(i)!==l)return null;for(let i of r.keys())if(i!==n&&!s.has(i))return null;return o},or=null,Nf=e=>or&&or.root===e?or.signature:null,Af=(e,t)=>{or={root:e,signature:t}},Tf=(e,t)=>{if(!or||or.root!==e)return;let n=Yc(e,or.signature,t);or=n===null?null:{root:e,signature:n}};import Ge from"node:fs";import Fr from"node:path";import{ulid as XE}from"ulid";var ca="~pending",Xc=/~pending(-[0-9a-z]+)*$/i,Mf=/-f(\d+)$/,Pf=e=>{let t=e.indexOf(".");return t===-1?`${e}${ca}`:e.slice(0,t)+ca+e.slice(t)},da=e=>{let t=e.indexOf(".");return t===-1?[e,""]:[e.slice(0,t),e.slice(t)]},JE=e=>{let[t,n]=da(e);return Xc.test(t)?t.replace(Xc,"")+n:null},Jc=e=>e.replace(Xc,""),_r=e=>e.endsWith(".jsonl")&&JE(e)!==null,Ps=e=>Jc(da(e)[0]),Lf=e=>{let[t]=da(e),n=Mf.exec(t);return n&&_r(e)?Number(n[1]):null},QE=e=>Pf(e).replace(ca,`${ca}-${XE().toLowerCase()}`),ZE=(e,t)=>{let[n,r]=da(e);return`${n.replace(Mf,"")}-f${t}${r}`},kf=(e,t)=>Fr.join(Et(e),Pf(t)),eS=(e,t)=>Math.max(0,Ge.statSync(e).size-(Lf(t)??0)),Df=e=>{let t=Et(e);try{return Ge.existsSync(t)?Ge.readdirSync(t).filter(_r).some(n=>eS(Fr.join(t,n),n)>0):!1}catch{return!0}},tS=3,Bf=(e,t)=>{for(let n=1;;n++){let r=Ge.openSync(e,"a"),o;try{Ge.writeSync(r,t),o=Ge.fstatSync(r).ino}finally{Ge.closeSync(r)}let s;try{s=Ge.statSync(e).ino}catch{s=null}if(s===o||n>=tS)return}},nS=e=>{let t;try{t=Ge.openSync(e,"r")}catch{return!0}try{let{size:n}=Ge.fstatSync(t);if(n===0)return!0;let r=Buffer.alloc(1);return Ge.readSync(t,r,0,1,n-1),r[0]===10}finally{Ge.closeSync(t)}},la=10,wf=(e,t,n=!1)=>{let r=n?t.length:t.lastIndexOf(la)+1;if(r===0)return{bytes:0,lines:0};let o=t.subarray(0,r);if(o.toString("utf8").trim().length===0)return{bytes:r,lines:0};Ge.appendFileSync(e,Buffer.concat([Buffer.from(nS(e)?"":`
|
|
30
|
+
`),o,Buffer.from(o[o.length-1]===la?"":`
|
|
31
|
+
`)]));let s=0;for(let i of o)i===la&&s++;return o[o.length-1]!==la&&s++,{bytes:r,lines:s}},ua=(e,t)=>{let n=Et(e);if(!Ge.existsSync(n))return u("No events directory",0);try{let r=Ps(t),o=Ge.readdirSync(n).filter(l=>_r(l)&&Ps(l)===r),s=Fr.join(n,t),i=0;for(let l of o){let d=Lf(l);if(d!==null){let g=Fr.join(n,l),y=Ge.readFileSync(g).subarray(d);i+=wf(s,y,!0).lines,Ge.rmSync(g,{force:!0});continue}let m=/~pending-/i.test(l)?l:QE(t),p=Fr.join(n,m);m!==l&&Ge.renameSync(Fr.join(n,l),p);let f=wf(s,Ge.readFileSync(p));i+=f.lines,Ge.renameSync(p,Fr.join(n,ZE(m,f.bytes)))}return u("Folded pending logs",i)}catch(r){return c(`Unable to fold pending event logs in ${n}: ${r instanceof Error?r.message:String(r)}`)}};var fa="unknown",oS=Qc.object({userId:Qc.string().min(1).default(fa),userName:Qc.string().min(1).default(fa)}),$f=new Set(["id","v","userId","userName"]),ma=e=>{let t=Object.entries(e).filter(([o])=>!$f.has(o));if(t.length!==1)return null;let n=t[0]?.[1];if(typeof n!="object"||n===null)return null;let r=n.id;return typeof r=="string"&&r.length>0?r:null},sS=/^[0-9a-hjkmnp-tv-z]{26}$/i,iS=e=>sS.test(e)?e.toUpperCase():e,Uf=e=>{let t=pa.basename(e,".jsonl"),n=t.indexOf("."),r=Jc(n===-1?t:t.slice(0,n)),o=n===-1?void 0:t.slice(n+1),s=oS.safeParse({userId:iS(r),userName:o});return s.success?u("Parsed event file actor",s.data):c(`Invalid event file name ${pa.basename(e)}: ${s.error.issues.map(i=>i.path.join(".")||i.message).join(", ")}`)},aS=e=>{let t=Object.keys(e).filter(n=>n!=="id"&&n!=="v");return t.length!==1?c(`Invalid persisted event: expected exactly 1 action key, got ${t.length}`):!t[0]||!(t[0]in e)?c("Invalid persisted event: action key is missing or invalid"):u("Resolved persisted action",t[0])},lS=(e,t)=>t in e,sr=new Map,cS=3e5,dS=512,Ls=0,Zc=e=>e.entries.length+e.quarantined.length,uS=(e,t,n,r)=>{let o=sr.get(e);o&&(Ls-=Zc(o));let s={stamp:t,entries:n,quarantined:r};sr.delete(e),sr.set(e,s),Ls+=Zc(s);for(let[i,l]of sr){if(Ls<=cS&&sr.size<=dS)break;i!==e&&(sr.delete(i),Ls-=Zc(l))}},mS=()=>{sr.clear(),Ls=0},pS=2n,Of=1000000n,fS=e=>{try{let{size:t,mtimeNs:n}=ks.statSync(e,{bigint:!0});return{value:`${t}:${n}`,settled:BigInt(Date.now())*Of-n>pS*Of}}catch{return null}},jf=(e,t)=>{let n=Uf(e);if(a(n))return c(n.message);let r=fS(e),o=r?sr.get(e):void 0;if(r&&o&&o.stamp===r.value){if(t)for(let p of o.quarantined)t.push(p);return u("Parsed persisted events file",[...o.entries])}let s;try{s=ks.readFileSync(e,"utf8")}catch(p){if(Ms(p))return u("Event file missing",null);throw p}let i=[],l=pa.basename(e),d=[],m=(p,f)=>{d.push({eventId:null,reason:"corrupt-line",detail:`${l}:${p} (${f})`,targetNodeId:null})};for(let[p,f]of s.split(`
|
|
32
|
+
`).entries()){let g=f.trim();if(!g)continue;let y;try{y=JSON.parse(g)}catch{m(p+1,"invalid JSON");continue}let x=Sf(y);if(a(x)){m(p+1,x.message);continue}i.push({...x.value,userId:n.value.userId,userName:n.value.userName})}if(t)for(let p of d)t.push(p);return r?.settled&&uS(e,r.value,i,d),u("Parsed persisted events file",[...i])},Ff=(e,t)=>e<t?-1:e>t?1:0,ed=(e,t)=>{let n=Ff(e.id[0],t.id[0]);return n!==0?n:Ff(JSON.stringify(e),JSON.stringify(t))},_f=(e,t)=>{let n=new Map,r=new Map;for(let p of e){let f=p.id[0],g=p.id[1]??null;n.set(f,p);let y=r.get(g)??[];y.push(p),r.set(g,y)}for(let p of r.values())p.sort(ed);let o=[],s=new Set,i=p=>{let f=[p];for(;f.length>0;){let g=f.pop(),y=g.id[0];if(s.has(y))continue;o.push(g),s.add(y);let x=r.get(y)??[];for(let b=x.length-1;b>=0;b--)f.push(x[b])}},l=(r.get(null)??[]).filter(p=>{let f=Object.keys(p).filter(g=>!$f.has(g));return f.length===1&&f[0]===t});for(let p of l)i(p);let d=e.filter(p=>{let f=p.id[0],g=p.id[1]??null;return s.has(f)?!1:g===null||!n.has(g)}).sort(ed);for(let p of d)i(p);let m=e.filter(p=>!s.has(p.id[0])).sort(ed);for(let p of m)i(p);return o},td=e=>ho(e.map(t=>{try{return rS(t.id[0])}catch{return null}})),Hf=(e,t)=>{let n=new Set,r=[],o=[],s=td(e);for(let i=0;i<e.length;i++){let l=e[i],d=l.id[0],m=l.id[1],p=s[i]??null;!(p!==null&&p<t)||m&&n.has(m)?(n.add(d),o.push(l)):r.push(l)}return{appliedEvents:r,unappliedEvents:o}},Wf=e=>{let t=new Set(e.actions),n=S=>t.has(S),r=S=>{let{userId:T,userName:A,...P}=S,M=aS(P);if(a(M))return c(M.message);let O=M.value,W=S.id?.[0];return W?lS(P,O)?u("Decoded persisted event",{id:W,action:O,payload:P[O],userId:T}):c(`Persisted event is missing payload for action: ${O}`):c("Persisted event is missing id")},o=(S,T)=>{let A=[],P=new Map,M=new Map;for(let O of S){if(!Gc(O.v)){M.set(O.v,(M.get(O.v)??0)+1),T?.push({eventId:O.id[0],reason:"unsupported-schema-version",detail:`v${O.v}`,targetNodeId:ma(O)});continue}let W=r(O);if(a(W)){T?.push({eventId:O.id[0],reason:"invalid-payload",detail:W.message,targetNodeId:ma(O)});continue}let X=W.value.action;if(!n(X)){P.set(X,(P.get(X)??0)+1),T?.push({eventId:O.id[0],reason:"unknown-action",detail:X,targetNodeId:ma(O)});continue}let Ee=e.readPayload(X,W.value.payload);if(a(Ee)){T?.push({eventId:O.id[0],reason:"invalid-payload",detail:Ee.message,targetNodeId:ma(O)});continue}A.push(W.value)}if(P.size>0){let O=[...P.entries()].map(([W,X])=>`${W} (x${X})`).join(", ");se.info(`Skipped events with unknown actions, likely created by a newer epiq version: ${O}. Upgrade to apply them.`)}if(M.size>0){let O=[...M.entries()].map(([W,X])=>`v${W} (x${X})`).join(", ");se.info(`Skipped events with unsupported schema versions, created by a newer epiq version: ${O}. Upgrade to apply them.`)}return u("Decoded reconstructed events",A)},s=null;function i(S,T){let A=Et(S),P=xn(S);if(!ks.existsSync(A))return u("No events found",[]);let M=[],O=[];for(let X=1;;X++){M=[],O=[];let Ee=!1;for(let F of qc(A)){let J=jf(pa.join(A,F),O);if(a(J))return c(J.message);if(J.value===null){if(X<Kc){Ee=!0;break}continue}for(let Ke of J.value)M.push(Ke)}if(!Ee)break}if(T)for(let X of O)T.push(X);let W=_f(M,e.genesis);return s={root:S,signature:P,edge:W.at(-1)?.id?.[0]??null},u("All events loaded",W)}function l(S){let T=[],A=i(S,T);if(a(A))return c(A.message);let P=o(A.value,T);return a(P)?c(P.message):u("Loaded merged events",{events:P.value,unreadable:T})}function d(S){let T=i(S);return a(T)?c(T.message):u("Loaded event actors",T.value.map(({userId:A,userName:P})=>({userId:A,userName:P})))}function m(S){let T=new Map,A=Et(S),P;try{if(!ks.existsSync(A))return T;P=ks.readdirSync(A)}catch{return T}let M=new Set;for(let W of P){if(!W.endsWith(".jsonl"))continue;let X=Uf(W);if(a(X))continue;let{userId:Ee,userName:F}=X.value;if(!Ee||!F||F===fa)continue;let J=T.get(Ee);J!==void 0&&J!==F&&M.add(Ee),T.set(Ee,F)}if(M.size===0)return T;let O=d(S);if(a(O))return T;for(let{userId:W,userName:X}of O.value)M.has(W)&&(!X||X===fa||T.set(W,X));return T}function p(S){let T=l(S);return a(T)?c(T.message):u("Loaded merged events",T.value.events)}function f(S,T){let A=i(S);if(a(A))return c(A.message);let{appliedEvents:P,unappliedEvents:M}=Hf(A.value,T),O=o(P);if(a(O))return c(O.message);let W=o(M);return a(W)?c(W.message):u("Loaded merged events before time",{appliedEvents:O.value,unappliedEvents:W.value})}function g(S=process.cwd()){let T=xn(S);if(s&&s.root===S&&s.signature===T)return u("Loaded edge reference, unchanged",s.edge);let A=i(S);return a(A)?c(A.message):u("Loaded edge reference",A.value.at(-1)?.id?.[0]??null)}function y(S,T,A){if(!s||s.root!==S)return;let P=Yc(S,s.signature,T);s=P===null?null:{root:S,signature:P,edge:A}}function x(){s=null,mS()}let b=S=>_f(S,e.genesis);function R(S){let T=i(S);if(a(T))return c(T.message);let A=td(T.value);return u("Loaded effective event times",new Map(T.value.map((P,M)=>[P.id[0],A[M]??null])))}return{fromPersistedEvent:r,decodeReconstructedEvents:o,loadMergedEventsWithUnreadable:l,loadEventActors:d,loadActorNames:m,loadMergedEvents:p,loadMergedEventsBefore:f,getEdgeRef:g,advanceEdgeRef:y,clearEdgeCache:x,getSortedEvents:b,loadEffectiveEventTimes:R}};var ga=(e,t)=>c(`${t.action.split(".").join(" ")+" failed, "+e.toLowerCase()}. Evt id: ${t.id}`),$=(e,t)=>({...ga(e,t),convergence:!0}),Ao=e=>a(e)&&e.convergence===!0,In=e=>{let t=e.filter(a);return{fatal:t.filter(n=>!Ao(n)),skipped:t.filter(Ao)}},En=e=>{e.length!==0&&se.info(`Skipped ${e.length} event(s) that could not be applied to this state: ${e.map(t=>t.message).join("; ")}`)},gS=e=>e.userId?.length?null:ga("Invalid user ID format",e),Gf=e=>{let t=null;function n(o,s=!1){let i=e.apply[o.action];if(!i)return c(`Unknown event action "${o.action}", likely created by a newer epiq version. Evt id: ${o.id}`);if(!e.replay.isInitialized()&&o.action!==e.genesis)return $(`${o.action} arrived before the state was initialized`,o);if(o.action===e.genesis&&t){if(t.genesisApplied)return $("the state is already initialized",o);t.genesisApplied=!0}let l;try{l=i(o)}catch(p){return $(`threw while materializing (${p instanceof Error?p.message:String(p)})`,o)}if(a(l))return l;let d=gS(o);if(d)return d;let m=e.replay.afterApply(o,{batched:t!==null,bypassLogging:s});return m||l}return{materialize:n,materializeAll:o=>{let s=e.replay.batch(()=>{let i=t===null;i&&(t={genesisApplied:!1});let l=!1;try{let d=o.map(m=>n(m));if(i){l=!0;let m=e.replay.flush();if(m)return o.map(()=>m)}return d}finally{i&&(t=null,l||e.replay.flush())}});return a(s)?o.map(()=>c(s.message)):s.value}}};import zf from"node:fs";import nd from"node:path";import{decodeTime as hS,monotonicFactory as yS}from"ulid";var Vf=e=>e.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/\.jsonl/g,"-jsonl").replace(/^-+|-+$/g,"")||"unknown";var vS=0xffffffffffff,bS=Hi,xS=e=>{let t=Date.now(),n;try{n=hS(e)}catch{return t}return n>=vS?t:n>t+bS?(se.error("[persist] edge id is too far in the future; seeding from the wall clock instead",{edgeRef:e,edgeTime:n,now:t}),t):Math.max(t,n+1)},ir=({userId:e})=>`${Vf(e)}.jsonl`,Kf=(e,t)=>{let n;try{if(!zf.existsSync(e))return[t];n=zf.readdirSync(e)}catch{return[t]}let r=Ps(t);return[...n.filter(s=>!s.endsWith(".jsonl")||s===t||_r(s)?!1:Ps(s)===r).sort(),t]},qf=(e,{userId:t})=>{let n=ir({userId:t});if(!/^(?!.*\.jsonl.*\.jsonl).*\.jsonl$/.test(n))return c(`Invalid event log file name: ${n}`);let o=nd.join(Et(e),n);return u("Successfully resolved event log path",o)},Yf=e=>{let t=yS();function n(o,s){let i;if(s&&s.current!==void 0)i=s.current;else{let d=e.getEdgeRef(o);if(a(d))return c(d.message);i=d.value}let l=i?t(xS(i)):t();return u("Minted event id",[l,i])}function r({event:o,rootDir:s,edge:i,id:l}){try{let d=Vm(s);if(a(d))return d;let m=qf(s,{userId:o.userId});if(a(m))return m;let p=kf(s,nd.basename(m.value)),f=l?u("Minted event id",l):n(s,i);if(a(f))return c(f.message);let[g,y]=f.value,x=Vc(xf(o),[g,y]);if(a(x))return c(x.message);Bf(p,`${JSON.stringify(x.value)}
|
|
33
|
+
`),i&&(i.current=g);let b=nd.basename(p);return e.advanceEdgeRef(s,b,g),Tf(s,b),u("Event persisted",{path:p,entry:x.value})}catch(d){let m=d instanceof Error?d.message:"Unknown persist error";return c(`Failed to persist event: ${m}`)}}return{mintEventId:n,persist:r}};var Xf=(e,t,n)=>{function r(s,i,l){let d=n.mintEventId(i,l);if(a(d))return c(d.message);let m={...s,id:d.value[0]},p=t.materialize(m);if(p.status!==Qn.Success)return p;let f=n.persist({event:m,rootDir:i,edge:l,id:d.value});return a(f)?f:p}function o(s,i){if(s.length===0||!s[0])return c("No events provided");let l=e.write.readOnlyReason();if(l)return c(l);let d=e.replay.batch(()=>{let m={},p=e.write.beforeWrite(s[0],y=>r(y,i,m));if(a(p))return c(p.message);let f=s.map(y=>r(y,i,m)),g=f.filter(a);return g.length>0?c("Materialize and persist failed: "+g.map(y=>y.message).join(", ")):u("Materialization succeeded",f.map(y=>y.value))});return a(d)?c(d.message):d.value??c("Materialize and persist produced nothing")}return{materializeAndPersist:r,materializeAndPersistAll:o}};var Jf=e=>{let t=Gf(e),n=Wf(e),r=Yf(n),o=Xf(e,t,r);return{...t,...n,...r,...o}};import{z as Z}from"zod";var K=Z.string().min(1),Jt=Z.string(),ar=Z.string(),ha=Z.looseObject({id:K}),rd=Z.looseObject({id:K,name:Jt,parent:K,rank:ar}),IS={"init.workspace":Z.looseObject({id:K,name:Jt,rank:ar}),"add.workspace":Z.looseObject({id:K,name:Jt,rank:ar}),"add.board":rd,"add.swimlane":rd,"add.issue":rd,"add.field":Z.looseObject({id:K,name:Jt,parent:K,rank:ar}),"edit.title":Z.looseObject({id:K,name:Jt}),"delete.node":ha,"lock.node":ha,"move.node":Z.looseObject({id:K,parent:K,rank:ar}),"edit.description":Z.looseObject({id:K,md:Z.string()}),"close.issue":Z.looseObject({id:K,parent:K,rank:ar}),"reopen.issue":Z.looseObject({id:K,parent:K,rank:ar}),"create.tag":Z.looseObject({id:K,name:Jt}),"tombstone.tag":ha,"restore.tag":Z.looseObject({id:K,name:Jt}),"create.contributor":Z.looseObject({id:K,name:Jt}),"rename.contributor":Z.looseObject({id:K,name:Jt}),"tombstone.contributor":ha,"restore.contributor":Z.looseObject({id:K,name:Jt}),"link.contributor.user":Z.looseObject({contributor:K}),"link.contributor.email":Z.looseObject({contributor:K,email:K}),"unlink.contributor.email":Z.looseObject({contributor:K,email:K}),"add.issue.assignee":Z.looseObject({id:K,assignee:K}),"remove.issue.assignee":Z.looseObject({id:K,assignee:K}),"add.issue.tag":Z.looseObject({id:K,tag:K}),"remove.issue.tag":Z.looseObject({id:K,tag:K}),"add.issue.comment":Z.looseObject({id:K,issue:K,md:Z.string()}),"edit.issue.comment":Z.looseObject({id:K,issue:K,md:Z.string()}),"delete.issue.comment":Z.looseObject({id:K,issue:K}),"add.issue.attachment":Z.looseObject({id:K,issue:K,hash:Z.string().min(1),ext:Z.string().min(1),name:Jt,bytes:Z.number()}),"delete.issue.attachment":Z.looseObject({id:K,issue:K}),"rebalance.children":Z.looseObject({parent:K,ranks:Z.record(Z.string(),ar)})},Qf=(e,t)=>{let r=IS[e].safeParse(t);return r.success?u("Payload is readable",void 0):c(`${e}: ${r.error.issues.map(o=>`${o.path.join(".")||"payload"} ${o.message}`).join(", ")}`)};import{ulid as ES}from"ulid";var Zf=(e,t)=>{if(e.action==="create.contributor"||e.action==="rename.contributor")return u("Contributor write already in flight",void 0);let{userId:n,userName:r}=V();if(!r||n!==e.userId)return u("Not this actor own write",void 0);let o=N.getContributor(e.userId),s={id:ES(),action:o?"rename.contributor":"create.contributor",payload:{id:e.userId,name:r},userId:e.userId};if(o&&(o.tombstoned||o.name===r))return u("Contributor name is current",void 0);let i=t(s);return a(i)?c(i.message):u("Contributor name recorded",void 0)};var Te={DESCRIPTION:"Description",ASSIGNEES:"Assignees",TAGS:"Tags",HISTORY:"History",DIFF:"Diff",COMMENTS:"Comments",ATTACHMENTS:"Attachments"};var H=e=>e.slice(-7).toUpperCase(),ya=(e,t)=>{let n=t.replace(/-/g,"").trim().toUpperCase();return n?H(e).includes(n):!0};var Ne={workspace:(e,t,n)=>({id:e,title:t,rank:n,isDeleted:!1,props:{},context:ie.WORKSPACE,childRenderAxis:"vertical",parentNodeId:null,readonly:!0,log:[]}),board:(e,t,n,r,o=!1)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:H(e)},context:ie.BOARD,childRenderAxis:"horizontal",parentNodeId:n,readonly:o,log:[]}),swimlane:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:ie.SWIMLANE,childRenderAxis:"vertical",childNavigationAcrossParents:!0,parentNodeId:n,readonly:!1,log:[]}),field:({id:e,name:t,parentNodeId:n,rank:r,props:o={},childRenderAxis:s="horizontal",isVirtual:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:ie.FIELD,childRenderAxis:s,parentNodeId:n,readonly:!1,log:[],isVirtual:i}),fieldList:({id:e,name:t,parentNodeId:n,rank:r,childRenderAxis:o="horizontal",isVirtual:s=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:{},context:ie.FIELD_LIST,childRenderAxis:o,parentNodeId:n,readonly:!1,log:[],isVirtual:s}),ticket:(e,t,n,r)=>({id:e,title:t,rank:r,isDeleted:!1,props:{ref:H(e)},context:ie.TICKET,childRenderAxis:"vertical",parentNodeId:n,readonly:!1,log:[]}),text:({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!0,isVirtual:s=!0,disabled:i=!1})=>({id:e,title:t,rank:r,isDeleted:!1,props:i?{disabled:!0}:{},context:ie.TEXT,childRenderAxis:"vertical",parentNodeId:n,readonly:o,log:[],isVirtual:s}),comment:({id:e,name:t,parentNodeId:n,rank:r,props:o={},readonly:s=!0,isVirtual:i=!0})=>({id:e,title:t,rank:r,isDeleted:!1,props:o,context:ie.COMMENT,childRenderAxis:"vertical",parentNodeId:n,readonly:s,log:[],isVirtual:i})};var Ds=(e,t,n)=>N.getNode(e)?$(`a node with id ${e} already exists`,n):t===e?$("a node cannot be its own parent",n):null,eg={"init.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ne.workspace(t,n,r),s=Bs(o);if(a(s))return ga(s.message,e);let i=N.createNode(o);return a(i)?$(i.message??"Failed to initialize workspace",e):Cc(i.value)?u("Workspace initialized",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.workspace":e=>{let{id:t,name:n,rank:r}=e.payload,o=Ds(t,void 0,e);if(o)return o;let s=N.createNode(Ne.workspace(t,n,r));return a(s)?$(s.message??"Failed to add workspace",e):Cc(s.value)?u("Added workspace",{action:e.action,result:s.value}):c("Unexpected create node return value")},"add.board":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.board(t,n,r,o));return a(i)?$(i.message??"Unable to create board",e):rr(i.value)?u("Added board",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.swimlane":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.swimlane(t,n,r,o));return a(i)?$(i.message??"Unable to create swimlane",e):gn(i.value)?u("Added swimlane",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.issue":e=>{let{id:t,name:n,parent:r,rank:o}=e.payload,s=Ds(t,r,e);if(s)return s;let i=N.createNode(Ne.ticket(t,n,r,o));return a(i)?$(i.message??"Unable to create issue",e):_(i.value)?u("Added issue",{action:e.action,result:i.value}):c("Unexpected create node return value")},"add.field":e=>{let{id:t,name:n,parent:r,val:o,rank:s}=e.payload,i=Ds(t,r,e);if(i)return i;let l=N.createNode(Ne.field({id:t,name:n,parentNodeId:r,rank:s,props:{value:o},childRenderAxis:n.includes(Te.DESCRIPTION)?"vertical":"horizontal"}));return a(l)?$(l.message??`Unable to create field: ${n}`,e):lt(l.value)?u("Added field",{action:e.action,result:l.value}):c("Unexpected create node return value")},"edit.title":e=>{let{id:t,name:n}=e.payload;if(!N.getNode(t))return $(`Unable to locate node with id ${t}`,e);let o=N.renameNode(t,n);return a(o)?$(o.message??"Unable to edit title",e):u("Edited title",{action:e.action,result:o.value})},"delete.node":e=>{let{id:t}=e.payload,n=N.tombstoneNode(t);return a(n)?$(n.message??"Unable to delete node",e):u("Deleted node",{action:e.action,result:n.value})},"create.tag":e=>{let{id:t,name:n}=e.payload,r=N.createTag({id:t,name:n});return a(r)?$(r.message??"Unable to create tag",e):u("Tag added",{action:e.action,result:r.value})},"tombstone.tag":e=>{let{id:t}=e.payload,n=N.tombstoneTag(t);return a(n)?$(n.message??"Unable to delete tag",e):u("Tag tombstoned",{action:e.action,result:n.value})},"restore.tag":e=>{let{id:t,name:n}=e.payload,r=N.restoreTag(t,n);return a(r)?$(r.message??"Unable to restore tag",e):u("Tag restored",{action:e.action,result:r.value})},"create.contributor":e=>{let{id:t,name:n}=e.payload,r=N.createContributor({id:t,name:n});return a(r)?$(r.message??"Unable to create contributor",e):u("Contributor created",{action:e.action,result:r.value})},"rename.contributor":e=>{let{id:t,name:n}=e.payload,r=N.renameContributor(t,n);return a(r)?$(r.message??"Unable to rename contributor",e):u("Contributor renamed",{action:e.action,result:r.value})},"tombstone.contributor":e=>{let{id:t}=e.payload,n=N.tombstoneContributor(t);return a(n)?$(n.message??"Unable to remove contributor",e):u("Contributor tombstoned",{action:e.action,result:n.value})},"restore.contributor":e=>{let{id:t,name:n}=e.payload,r=N.restoreContributor(t,n);return a(r)?$(r.message??"Unable to restore contributor",e):u("Contributor restored",{action:e.action,result:r.value})},"add.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=N.tag(t,n);return a(r)?$(r.message??"Unable to tag issue",e):u("Issue tagged",{action:e.action,result:{tag:n}})},"remove.issue.tag":e=>{let{id:t,tag:n}=e.payload,r=N.untag(t,n);return a(r)?$(r.message??"Unable to untag issue",e):u("Issue untagged",{action:e.action,result:{tag:n}})},"add.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=N.assign(t,n);return a(r)?$(r.message??"Unable to assign issue",e):u("Assigned successfully",{action:e.action,result:{assignee:n}})},"remove.issue.assignee":e=>{let{id:t,assignee:n}=e.payload,r=N.unassign(t,n);return a(r)?$(r.message??"Unable to unassign issue",e):u("Issue unassigned",{action:e.action,result:{assignee:n}})},"move.node":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(o)?$(o.message??"Failed to move node",e):u("Moved node",{action:e.action,result:o.value})},"edit.description":e=>{let{id:t,md:n}=e.payload,r=N.editValue(t,n);return a(r)?$(r.message??"Unable to edit description",e):u("Set node value",{action:e.action,result:r.value})},"close.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return $("Unable to locate issue",e);if(!_(o))return $("Can only close issues",e);let s=N.getNode(ye);if(!s)return $("Unable to locate target swimlane",e);if(n!==s.id)return $("Close target must be closed swimlane",e);let i=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(i)?$(i.message??"Unable to close issue",e):u("Issue closed",{action:e.action,result:{id:t}})},"reopen.issue":e=>{let{id:t,parent:n,rank:r}=e.payload,o=N.getNode(t);if(!o)return $("Unable to locate issue",e);if(!_(o))return $("Can only reopen issues",e);let s=N.getNode(ye);if(!s)return $("Unable to locate closed swimlane",e);if(n===s.id)return $("Cannot reopen issue into closed swimlane",e);if(!N.getNode(n))return $("Reopen parent no longer exists",e);let l=N.moveNodeToRank({id:t,parentId:n,rank:r});return a(l)?$(l.message??"Unable to reopen issue",e):u("Issue reopened",{action:e.action,result:{id:t}})},"lock.node":e=>{let{id:t}=e.payload,n=N.lockNode(t);return a(n)?$(n.message??"Unable to lock node",e):u("Node locked",{action:e.action,result:n.value})},"rebalance.children":e=>{let{parent:t,ranks:n}=e.payload;for(let[r,o]of Object.entries(n)){let s=N.getNode(r);if(!s)return $(`Unable to locate node ${r}`,e);if(s.parentNodeId!==t)return $(`Node ${r} is not child of ${t}`,e);let i=N.updateNode({...s,rank:o});if(a(i))return $(i.message??"Unable to rebalance child",e)}return u("Rebalanced children",{action:e.action,result:{parent:t}})},"add.issue.comment":e=>{let{id:t,issue:n,author:r,md:o}=e.payload,s=N.createComment({id:t,issue:n,authorId:r,md:o,deleted:!1});return a(s)?$(s.message??"Unable to add comment",e):u("Comment added",{action:e.action,result:{id:t,issue:n,author:r,md:o}})},"edit.issue.comment":e=>{let{id:t,issue:n,md:r}=e.payload,o=N.getComment(t);if(!o)return $("Unable to locate comment",e);if(o.issue!==n)return $("Comment does not belong to issue",e);let s=N.editComment(t,r);return a(s)?$(s.message??"Unable to edit comment",e):u("Comment edited",{action:e.action,result:{id:t,issue:n,md:r}})},"delete.issue.comment":e=>{let{id:t,issue:n}=e.payload,r=N.getComment(t);if(!r)return $("Unable to locate comment",e);if(r.issue!==n)return $("Comment does not belong to issue",e);let o=N.deleteComment(t);return a(o)?$(o.message??"Unable to delete comment",e):u("Comment deleted",{action:e.action,result:{id:t,issue:n}})},"add.issue.attachment":e=>{let{id:t,issue:n,hash:r,ext:o,name:s,bytes:i}=e.payload,l=N.createAttachment({id:t,issue:n,hash:r,ext:o,name:s,bytes:i,deleted:!1});return a(l)?$(l.message??"Unable to add attachment",e):u("Attachment added",{action:e.action,result:{id:t,issue:n,hash:r}})},"delete.issue.attachment":e=>{let{id:t,issue:n}=e.payload,r=N.getAttachment(t);if(!r)return $("Unable to locate attachment",e);if(r.issue!==n)return $("Attachment does not belong to issue",e);let o=N.deleteAttachment(t);return a(o)?$(o.message??"Unable to delete attachment",e):u("Attachment deleted",{action:e.action,result:{id:t,issue:n}})},"link.contributor.email":e=>{let{contributor:t,email:n}=e.payload;if(!tr(n))return $(`not an email address: ${n}`,e);let r=N.linkContributorEmail({email:n,contributor:t,authorId:e.userId});return a(r)?$(r.message??"Unable to link email",e):u("Email linked to contributor",{action:e.action,result:r.value})},"unlink.contributor.email":e=>{let{contributor:t,email:n}=e.payload,r=N.unlinkContributorEmail(n,t,e.userId);return a(r)?$(r.message??"Unable to unlink email",e):u("Email unlinked from contributor",{action:e.action,result:r.value})},"link.contributor.user":e=>{let{contributor:t}=e.payload,n=N.linkUserId({contributorId:t,userId:e.userId});return a(n)?$(n.message??"Unable to link contributor",e):u("Contributor linked to user",{action:e.action,result:{contributor:t,userId:e.userId}})}};var tg=e=>{let t=N.getNode(e);if(!t||!_(t)||t.isDeleted)return null;let n=og(t);return a(n)?n:null},ng=e=>{if(!sd())return null;for(let t of e){let n=tg(t);if(n)return n;let r=v().nodes[t]?.parentNodeId;if(!r)continue;let o=tg(r);if(o)return o}return null},SS=(e,t)=>{let n=N.getNode(e);n&&N.updateNode({...n,log:[...n.log??[],t]})},RS=e=>{let t=[e],n=v().nodes[e]?.parentNodeId;return n&&t.push(n),t},od=e=>{switch(e.action){case"add.issue.comment":case"edit.issue.comment":case"delete.issue.comment":case"add.issue.attachment":case"delete.issue.attachment":return[e.payload.issue];case"delete.node":case"edit.description":return RS(e.payload.id);case"init.workspace":case"add.workspace":case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"edit.title":case"lock.node":case"move.node":case"close.issue":case"reopen.issue":case"add.issue.tag":case"remove.issue.tag":case"add.issue.assignee":case"remove.issue.assignee":return[e.payload.id];case"rebalance.children":return Object.keys(e.payload.ranks);case"create.tag":case"tombstone.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"link.contributor.user":case"link.contributor.email":case"unlink.contributor.email":default:return[]}},CS=e=>{Fe(t=>({...t,eventLog:[...t.eventLog,e]}))},jn=null,NS=e=>{for(let[t,n]of e.nodeLog){let r=N.getNode(t);r&&N.updateNode({...r,log:[...r.log??[],...n]})}return e.appLog.length>0&&Fe(t=>({...t,eventLog:[...t.eventLog,...e.appLog]})),ng([...e.virtualNodeIds])},rg={isInitialized:()=>_t(),batch:e=>va(e),afterApply(e,{batched:t,bypassLogging:n}){let r=[...new Set(od(e))];if(t){jn??={appLog:[],nodeLog:new Map,virtualNodeIds:new Set};for(let o of r){if(!n){let s=jn.nodeLog.get(o);s?s.push(e):jn.nodeLog.set(o,[e])}if(sd()){jn.virtualNodeIds.add(o);let s=v().nodes[o]?.parentNodeId;s&&jn.virtualNodeIds.add(s)}}return n||jn.appLog.push(e),null}return n||(r.forEach(o=>SS(o,e)),CS(e)),ng(r)},flush(){if(!jn)return null;let e=jn;return jn=null,NS(e)}};var pe=()=>{let{userName:e,userId:t}=V();return e?t?Xl(t)?ki(e)?u("Successfully resolved actor ID",{userId:t,userName:e}):c("Invalid user name in config"):c("Invalid user ID in config"):c("User ID not configured"):c("User name not configured")};var AS={genesis:"init.workspace",actions:Hc,readPayload:Qf,apply:eg,replay:rg,write:{readOnlyReason:()=>{let e=v();return e.readOnly?e.readOnlyReason??"Cannot change the board while time travelling":null},beforeWrite:Zf}},TS=Jf(AS),{materialize:Os,materializeAll:Qt,fromPersistedEvent:WO,decodeReconstructedEvents:GO,loadMergedEventsWithUnreadable:Zt,loadEventActors:sg,loadActorNames:lr,loadMergedEvents:cr,loadMergedEventsBefore:ba,getEdgeRef:VO,advanceEdgeRef:zO,clearEdgeCache:KO,getSortedEvents:qO,loadEffectiveEventTimes:xa,mintEventId:YO,persist:ig,materializeAndPersist:XO,materializeAndPersistAll:B}=TS;var $r=e=>e.trim().toLocaleLowerCase(),id=(e,t)=>$r(e).includes($r(t));var wS=e=>{let{tags:t}=v();return(e.props.tags??[]).map(n=>t[n]).filter(n=>n!==void 0&&!n.tombstoned).map(n=>n.name)},MS=e=>{let{contributors:t}=v();return(e.props.assignees??[]).map(n=>{let r=t[n];return r?r.name:void 0}).filter(n=>!!n)},ag=null,lg=new Map,PS=()=>{let e=v().eventLog??[];if(e===ag)return lg;let t=new Map;for(let n of e){if(!n.userId)continue;let r=n.payload;for(let o of[r.id,r.issue]){if(typeof o!="string")continue;let s=t.get(o)??new Set;s.add(n.userId),t.set(o,s)}}return ag=e,lg=t,t},LS=e=>{let{contributors:t}=v(),n=PS().get(e.id);return n?[...n].map(r=>t[r]?.name).filter(r=>!!r):[]},cg=(e,t)=>{let n=$r(t.value);if(!n)return!0;switch(t.target){case"title":return id(e.title??"",n);case"description":return id(e.props.description??"",n);case"tag":return wS(e).map($r).some(o=>o.includes(n));case"assignee":return MS(e).map($r).some(o=>o.includes(n));case"actor":return LS(e).map($r).some(o=>o.includes(n));case"ref":return ya(e.id,t.value);default:return!0}};var ad=(e,t)=>e.rank<t.rank?-1:e.rank>t.rank?1:0,kS=(e,t)=>!!e&&!e.isDeleted&&e.parentNodeId===t,dg=(e,t)=>Object.values(e).filter(n=>kS(n,t)).sort(ad),ug=(e,t)=>{let n={};for(let r of Object.values(e)){if(_(r)&&t.length>0&&!t.every(s=>cg(r,s))||!r.parentNodeId||r.isDeleted)continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(ad);return n},mg=(e,t)=>{let n={};for(let r of Object.values(e)){if(!r.parentNodeId||r.isDeleted||!t.has(r.parentNodeId))continue;let o=n[r.parentNodeId];o?o.push(r):n[r.parentNodeId]=[r]}for(let r of Object.keys(n))n[r].sort(ad);return n};var pg=e=>Ia(Ie(e),{at:"end"}),Ia=(e,t={at:"end"})=>{let n=o=>a(o)?u("Rank space exhausted",{rank:"",needsRebalance:!0}):u("Resolved rank",{rank:o.value,needsRebalance:!1});if(e.length===0)return n(vt(void 0,void 0));let r=()=>n(vt(e[e.length-1]?.rank,void 0));switch(t.at){case"start":{let o=e[0];return o?n(vt(void 0,o.rank)):c("Unable to resolve first sibling")}case"end":{let o=e[e.length-1];return o?n(vt(o.rank,void 0)):c("Unable to resolve last sibling")}case"before":{let o=fg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o>0?e[o-1]:void 0;return n(vt(i?.rank,s.rank))}case"after":{let o=fg(e,t.sibling),s=o<0?void 0:e[o];if(!s)return r();let i=o<e.length-1?e[o+1]:void 0;return n(vt(s.rank,i?.rank))}}},Ie=e=>{let t=v();if(!hg()&&t.filters.length===0){let n=t.renderedChildrenIndex[e];if(n)return n}return dg(t.nodes,e)},fg=(e,t)=>e.findIndex(n=>n.id===t),gg=(e,t,n={at:"end"})=>Ia(Ie(t).filter(r=>r.id!==e),n),Sn=(e,t,n,r,o)=>{let s=gg(t,e,n);if(a(s))return s;if(!s.value.needsRebalance)return u("Resolved rank",s.value.rank);let i=Wc(e,r);if(a(i))return i;let l=B([i.value],o);if(a(l))return l;let d=gg(t,e,n);return a(d)?d:d.value.needsRebalance?c("Rank rebalance failed to create space"):u("Resolved rank after rebalance",d.value.rank)},Hn=(e,t,n)=>{let r=pg(e);if(a(r))return r;if(!r.value.needsRebalance)return u("Resolved rank",r.value.rank);let o=Wc(e,t);if(a(o))return o;let s=B([o.value],n);if(a(s))return s;let i=pg(e);return a(i)?i:i.value.needsRebalance?c("Rank rebalance failed to create space"):u("Resolved rank after rebalance",i.value.rank)};var Fs=5,U={exit(){process.exit(0)},enterChildNode(){let e=v(),t=e.contextNode,n=Math.max(0,e.selectedIndex),r=de(t.id),o=r[n];o&&(t.context==="FIELD"&&r.length===0||o.context==="COMMENT"||o.context==="TEXT"||U.navigate({contextNode:o,selectedIndex:de(o.id).length?0:-1}))},enterParentNode(){let{contextNode:e,nodes:t}=v();if(!e.parentNodeId){logger.info("Missing parent node id");return}let n=t[e.parentNodeId];if(!n){logger.error("Parent not found");return}let r=de(n.id),o=r.findIndex(({id:i})=>i===e.id),s=r.length===0?-1:o>=0?o:0;U.navigate({contextNode:n,selectedIndex:s})},navigateToNextItem:()=>yg(1),navigateToPreviousItem:()=>yg(-1),jumpToNextItem:()=>vg(Fs),jumpToPreviousItem:()=>vg(-Fs),navigateToNextContainer:()=>bg(1),navigateToPreviousContainer:()=>bg(-1),navigate:({contextNode:e,selectedIndex:t})=>{w({contextNodeId:e.id,selectedIndex:t})}},yg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=de(n.id).length;if(r===0)return;let s=(Math.max(0,t)+e+r)%r;U.navigate({selectedIndex:s,contextNode:n})},vg=e=>{let{selectedIndex:t,contextNode:n}=v(),r=de(n.id).length;if(r===0)return;let o=Math.max(0,t),s=Math.min(Math.max(o+e,0),r-1);U.navigate({selectedIndex:s,contextNode:n})},bg=e=>{let{contextNode:t,nodes:n,selectedIndex:r}=v();if(!t.childNavigationAcrossParents)return;if(!t.parentNodeId){logger.error("Missing parent node id");return}let o=n[t.parentNodeId];if(!o)return;let s=de(o.id),i=s.findIndex(g=>g.id===t.id);if(i<0)return;let l=s.at(i+e)??s.at(0);if(!l)return;let d=de(l.id),m=Math.max(0,d.length-1),p=Math.min(Math.max(0,r),m),f=d.length?p:-1;U.navigate({contextNode:l,selectedIndex:f})};var Ig=(e,t)=>t<=0?-1:Math.max(0,Math.min(e,t-1)),Eg=()=>{let{contextNode:e,selectedIndex:t,selectedNode:n}=v();return{contextNodeId:e.id,selectedNodeId:n?.id??null,parentNodeId:e.id,selectedIndex:t}},DS=e=>{let t=v().nodes[e];return!!t&&!t.isDeleted&<(t)&&t.childRenderAxis==="vertical"},Ea=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r||r.isDeleted)return!1;let o=Ie(r.id);return U.navigate({contextNode:r,selectedIndex:Ig(t,o.length)}),!0},Sg=e=>{let{nodes:t}=v(),n=t[e];if(!n||n.isDeleted)return!1;let r=n.parentNodeId;if(!r)return Ea(n.id,0);let o=t[r];if(!o||o.isDeleted)return!1;let i=Ie(o.id).findIndex(l=>l.id===n.id);return i>=0?(U.navigate({contextNode:o,selectedIndex:i}),!0):Sg(o.id)},xg=e=>{let{nodes:t}=v(),n=e,r=new Set;for(;n&&!r.has(n);){if(r.add(n),Sg(n))return!0;n=t[n]?.parentNodeId}return!1},BS=e=>{if(!e)return!1;let t=v().nodes[e];return!!t&&!t.isDeleted},Rg=e=>{let{nodes:t,rootNodeId:n}=v();if(DS(e.contextNodeId)&&Ea(e.contextNodeId,e.selectedIndex))return u("Restored navigation inside text container",null);if(BS(e.selectedNodeId)&&e.selectedNodeId&&xg(e.selectedNodeId))return u("Restored navigation to selected node or ancestor",null);if(Ea(e.contextNodeId,e.selectedIndex))return u("Restored navigation to previous container",null);if(e.parentNodeId&&Ea(e.parentNodeId,e.selectedIndex))return u("Restored navigation to previous parent",null);if(xg(e.contextNodeId))return u("Restored navigation to previous container or ancestor",null);let r=t[n];if(!r||r.isDeleted)return c("Unable to restore navigation");let o=Ie(r.id);return U.navigate({contextNode:r,selectedIndex:Ig(e.selectedIndex,o.length)}),u("Restored navigation to root",null)};import{monotonicFactory as OS,ulid as Rn}from"ulid";var _s=OS();function FS(){let e=xe();if(a(e))return c("Unable to boot. State not initialized");let t=e.value,n=Object.values(t.nodes).find(s=>s.context==="WORKSPACE");if(!n)return c("No workspace found in event log");let[r]=de(n.id),[o]=r?de(r.id):[];if(o){let s=t.renderedChildrenIndex?.[o.id]??[];return u("Resolved boot nav target",{contextNode:o,selectedIndex:s.length>0?0:-1})}else return r?u("Resolved boot nav target",{contextNode:r,selectedIndex:0}):u("Resolved boot nav target",{contextNode:n,selectedIndex:0})}function _S(){let e=FS();return a(e)?e:U.navigate(e.value)}function Cg({userId:e,userName:t}){let n=_s(),r=_s(),o=_s(),s=_s(),i=_s(),l=vt(void 0,void 0);if(a(l))return l;let d=vt(void 0,void 0);if(a(d))return d;let m=vt(d.value,void 0);if(a(m))return m;let p=vt(void 0,void 0);if(a(p))return p;let f=vt(p.value,void 0);if(a(f))return f;let g=vt(f.value,void 0);if(a(g))return g;let y=vt(void 0,void 0);return a(y)?y:u("Created default events",[{id:Rn(),userId:e,action:"init.workspace",payload:{id:n,name:"Workspace",rank:l.value}},{id:Rn(),userId:e,action:"create.contributor",payload:{id:e,name:t}},{id:Rn(),userId:e,action:"add.board",payload:{id:r,name:"Default",parent:n,rank:d.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:o,name:"Todo",parent:r,rank:p.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:s,name:"In progress",parent:r,rank:f.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:i,name:"Done",parent:r,rank:g.value}},{id:Rn(),userId:e,action:"add.board",payload:{id:Qi,name:"Closed",parent:n,rank:m.value}},{id:Rn(),userId:e,action:"add.swimlane",payload:{id:ye,name:"Closed",parent:Qi,rank:y.value}},{id:Rn(),userId:e,action:"lock.node",payload:{id:Qi}},{id:Rn(),userId:e,action:"lock.node",payload:{id:ye}}])}var $S=()=>{let e=xe();if(a(e))return!1;let{timeMode:t}=e.value;return t==="peek"||t==="replay"},US=e=>{if(e.length===0)return;let t=e.filter(r=>r.reason==="corrupt-line"||r.reason==="invalid-payload"),n=e.filter(r=>r.reason==="unsupported-schema-version"||r.reason==="unknown-action");if(n.length>0){let r=[...new Set(n.map(o=>o.detail))].join(", ");se.info(`This build cannot read ${n.length} event(s) in the log (${r}). They are skipped, so anything they changed may be out of date until you upgrade.`)}if(t.length>0){let r=[...new Set(t.map(o=>o.detail))].join(", ");se.info(`Skipped ${t.length} corrupt line(s) in the event log (${r}). The rest of the board loaded normally; those events are unrecoverable.`)}};function en(e,t=[]){if($S())return u("Skipped boot while checked out at a historical point",null);if(!e.length){let s=Ne.workspace("temporary-uninitialized-workspace","Workspace","a0"),i=Bs(s);return a(i)?i:(w({hasProjectDefinition:!1,mode:I.DEFAULT}),u("Booted uninitialized workspace placeholder",null))}if(!e.some(s=>s.action==="init.workspace"))return c("Initialized Epiq project has no workspace init event");let n=Qt(e),{fatal:r,skipped:o}=In(n);return r.length>0?c(`Materializing failed:
|
|
33
34
|
${r.map(s=>s.message).join(`
|
|
34
|
-
`)}`):(
|
|
35
|
-
`,"utf8"),u("Wrote the state branch identity",void 0)}catch(n){return
|
|
36
|
-
`);var
|
|
37
|
-
`).filter(t=>t.trim().length>0),
|
|
38
|
-
`);
|
|
35
|
+
`)}`):(En(o),_S(),w({hasProjectDefinition:!0}),US(t),u("State booted successfully",null))}import{WebSocket as jS}from"ws";var Sa=new Set,Ng=e=>{Sa.add(e),e.on("close",()=>{Sa.delete(e)}),e.on("error",()=>{Sa.delete(e)})},Ur=e=>{let t=JSON.stringify(e);for(let n of Sa)n.readyState===jS.OPEN&&n.send(t)};var Ra=e=>{_t()&&(w({syncStatus:e}),Ur({type:"sync-status",payload:e}))},To=(e="Syncing...")=>{Ra({status:"syncing",msg:e})},jr=(e="Synced")=>{Ra({status:"synced",msg:e})},ld=e=>{Ra({status:"failed",msg:e})},Ca=e=>{Ra({status:"offline",msg:e})},Ve=e=>(ld(e),c(e));var tn=(e,t)=>(logger.error(`[boot:${e}] ${t}`),c(`[boot:${e}] ${t}`)),wo=e=>{if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return String(e)}},ge=(e,t)=>(a(t)&&logger.info(`[${e}]:failed`,t.message),t);import Vg from"node:fs";import Wn from"node:fs";import Gn from"node:path";import Na from"node:fs";import Ag from"node:path";var ut=".epiq/project.json",Tg=e=>Ag.join(e,ut),HS=e=>{if(!Na.existsSync(Tg(e)))return u("State branch carries no identity yet",null);let t=Tt(e);return a(t)?c(`On the state branch: ${t.message}`):u("Read the state branch identity",t.value)},cd=(e,t)=>{try{let n=Tg(e);return Na.mkdirSync(Ag.dirname(n),{recursive:!0}),Na.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
36
|
+
`,"utf8"),u("Wrote the state branch identity",void 0)}catch(n){return c(n instanceof Error?`Failed to write the state branch identity: ${n.message}`:"Failed to write the state branch identity")}},WS=({checkout:e,branch:t,stateBranch:n})=>[`This checkout's ${ut} names project ${e.projectId}`,`(created ${e.createdAt}), but the state branch ${n}`,`belongs to project ${t.projectId} (created ${t.createdAt}).`,"","The branch holds the board, so its id is the one that counts. Point the","checkout at it and commit the change:","",` git show ${n}:${ut} > ${ut}`,"","A second id is minted when init runs in a checkout that has no","project file while the state branch already exists; nothing on the","board is lost by it, but every checkout has to agree on one."].join(`
|
|
37
|
+
`);var wg=({repoRoot:e,stateBranchRoot:t,stateBranch:n})=>{if(!Na.existsSync(mo(e)))return u("No project file to compare","no-checkout-file");let r=Tt(e);if(a(r))return c(r.message);let o=HS(t);if(a(o))return c(o.message);if(o.value===null){let s=cd(t,r.value);return a(s)?c(s.message):u("Stamped the state branch with this project","stamped")}return o.value.projectId!==r.value.projectId?c(WS({checkout:r.value,branch:o.value,stateBranch:n})):u("The checkout and the state branch agree","matched")};import Cn from"node:fs";import $s from"node:path";var Mo=e=>e.split(`
|
|
38
|
+
`).filter(t=>t.trim().length>0),Mg=e=>{let t=$s.join(e,gt,On);try{if(!Cn.existsSync(t))return u("No events directory",[]);let n=Cn.readdirSync(t).filter(r=>r.endsWith(".jsonl")).filter(r=>Mo(Cn.readFileSync($s.join(t,r),"utf8")).length>0);return u("Looked for stranded event logs",n)}catch(n){return c(`Unable to check ${t} for event logs before deleting it: ${n instanceof Error?n.message:String(n)}`)}},Pg=e=>$s.join(e,gt,On),Lg=e=>{let t=Pg(e),n=new Map;try{if(!Cn.existsSync(t))return n;for(let r of Cn.readdirSync(t))if(r.endsWith(".jsonl")&&!_r(r))try{n.set(r,Mo(Cn.readFileSync($s.join(t,r),"utf8")))}catch(o){if(!Ms(o))throw o}}catch{return n}return n},GS=e=>{try{let t=JSON.parse(e);return typeof t=="object"&&t!==null}catch{return!1}},kg=(e,t)=>{if(t.size===0)return[];let n=Pg(e),r=[];for(let[o,s]of t){if(s.length===0)continue;let i=$s.join(n,o);try{let l=Cn.existsSync(i)?Cn.readFileSync(i,"utf8"):null,d=new Set(l===null?[]:Mo(l)),m=s.filter(f=>!d.has(f)).filter(GS);if(m.length===0)continue;Cn.mkdirSync(n,{recursive:!0});let p=l!==null&&l.length>0&&!l.endsWith(`
|
|
39
|
+
`);Cn.appendFileSync(i,`${p?`
|
|
39
40
|
`:""}${m.join(`
|
|
40
41
|
`)}
|
|
41
|
-
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},
|
|
42
|
-
`),
|
|
43
|
-
`));
|
|
44
|
-
${n.message}`);let r=n.value.stdout.trim(),o=await
|
|
45
|
-
${o.message}`):u("Created state branch",!0)},
|
|
46
|
-
`+n.message);if(n.value)return u("Local state branch already exists",!1);let r=await
|
|
47
|
-
`+r.message);let o=r.value,s=o?await
|
|
48
|
-
`+s.message);let i=s.value;if(o&&i){let
|
|
49
|
-
${
|
|
50
|
-
${
|
|
51
|
-
`),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)},
|
|
52
|
-
`+r.message);if(
|
|
53
|
-
`));
|
|
54
|
-
${o.message}`):u("Created state branch worktree",!0)},
|
|
55
|
-
`));if(s&&s!==o){let
|
|
56
|
-
`));
|
|
57
|
-
${m.message}`)}if(s&&!
|
|
58
|
-
${
|
|
59
|
-
${
|
|
60
|
-
${o.message}`):u("Checked out state branch",!0)},
|
|
61
|
-
${
|
|
62
|
-
${
|
|
63
|
-
${s.message}`):u("Staged state branch event file",n)},
|
|
64
|
-
${r.message}`):u("Staged state branch media files",t)}
|
|
65
|
-
${n.message}`):u("Staged event log config",t)}
|
|
66
|
-
`+r.message):
|
|
67
|
-
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return u(i?"Pushed state branch":"Remote already up to date",i)},Wm=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Gt(e);if(a(o))return o;let s=o.value,i=[Eo(),await Uo({repoRoot:e,stateBranchName:s}),await On({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await px({stateBranchRoot:t,stateBranchName:s}),await du(t),n?await fx({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let d of i){if(a(d))return l(d.message);r=r||!!d.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import li from"node:fs";import Pl from"node:os";import gx from"node:path";var hx="epiq-sync.lock",Gm=600*1e3,yx=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},vx=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},bx=e=>e&&(e.hostname!==Pl.hostname()||vx(e.pid))?Date.now()-e.startedAt>Gm:!0,zm=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,Ml=e=>{try{return yx(li.readFileSync(e,"utf8"))}catch{return null}},Vm=(e,t)=>{let n={pid:process.pid,hostname:Pl.hostname(),startedAt:Date.now(),operation:t};try{return li.writeFileSync(e,JSON.stringify(n),{flag:"wx"}),!0}catch{return!1}},xx=async({worktreeRoot:e,operation:t})=>{let n=await za(e);if(a(n))return l(n.message);let r=gx.join(n.value,hx),o=()=>{try{let d=Ml(r);d&&d.pid===process.pid&&li.rmSync(r)}catch{}};if(Vm(r,t))return u("Acquired sync lock",{acquired:!0,release:o});let s=Ml(r);if(!bx(s))return u("Sync lock is held",{acquired:!1,heldBy:s});z.info(`Breaking an abandoned sync lock: ${s?zm(s):"unreadable lock file"}`);try{li.rmSync(r,{force:!0})}catch{}if(Vm(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,release:o});let i=Ml(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:i??{pid:-1,hostname:Pl.hostname(),startedAt:Date.now(),operation:"unknown"}})},di=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await xx({worktreeRoot:e,operation:t});if(a(r))return l(r.message);if(!r.value.acquired)return z.info(`Skipping ${t}: the state worktree is held by ${zm(r.value.heldBy)}`),u("State worktree is held by another process",null);let{release:o}=r.value;try{return u("Ran under the sync lock",await n())}finally{o()}};var Sx=async({cwd:e,ensureUpstream:t})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:e,ensureUpstream:t});let n=ae("getRepoRootDir",await kt(e));if(a(n))return l(n.message);let r=n.value;logger.debug("[sync] repo root",r);let o=ae("getStateBranchRoot",fe({repoRoot:r}));if(a(o))return l(o.message);let s=o.value;logger.debug("[sync] state branch root",s),logger.debug("[sync] bootstrapping state branch storage",{repoRoot:r,stateBranchRoot:s,ensureUpstream:t});let i=ae("bootstrapStateBranchStorage",await Wm({repoRoot:r,stateBranchRoot:s,ensureUpstream:t}));if(a(i))return l(i.message);logger.debug("[sync] bootstrap result",{bootstrapped:i.value,stateBranchRoot:s}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:s});let d=ae("hasInProgressGitOperation(stateBranchRoot)",await Ds(s));if(a(d))return l(d.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:d.value}),d.value)return logger.info("[sync] state branch git operation in progress"),l("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 c=ae("ensureStateBranchLayout",lu(r,s));return a(c)?l(c.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}),u("Sync preconditions satisfied",{repoRoot:r,stateBranchRoot:s,bootstrapped:i.value}))},Ex=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=ae("stageStateBranchOwnEventFile",await ai({stateBranchRoot:t,eventFileName:n}));if(a(r))return l(r.message);let o=ae("stageStateBranchMediaFiles",await jm({stateBranchRoot:t}));if(a(o))return l(o.message);let s=ae("stageStateBranchEventConfig",await $m({stateBranchRoot:t}));if(a(s))return l(s.message);let i=[r.value,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let d=ae("hasStagedChanges(after stage)",await Zc(t,i));if(a(d))return l(d.message);if(logger.debug("[sync] state branch change check after stage result",{changed:d.value}),!d.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 c=ae("createStateBranchSyncCommit",await Hm({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(c)?l(c.message):(logger.debug("[sync] created sync commit",c.value),u("Committed own event file",{createdCommit:!0,commitSha:c.value}))},Ll=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return si(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},Km=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}),l("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),l("Own event file must end with .jsonl");Ur();let n=ae("ensureSyncReady",await Sx({cwd:e,ensureUpstream:!0}));if(a(n))return Te(n.message);let{repoRoot:r,stateBranchRoot:o,bootstrapped:s}=n.value,i=ae("isDetachedHead(stateBranchRoot)",await eu(o));if(a(i))return Te(i.message);if(logger.debug("[sync] detached state branch check result",{detached:i.value}),i.value)return Te("Cannot run :sync while the state branch is in detached HEAD state");let d=!1,c,m=!1,p=!1,f=ae("getStateBranch",Gt(r));if(a(f))return Te(f.message);let g=f.value;logger.debug("[sync] resolved state branch",{stateBranch:g,stateBranchRoot:o});let v=ae("flushPendingLogs",qs(o,t));a(v)&&logger.error(`[sync] ${v.message}`);let I=ae("commitOwnEventFileToStateBranch",await Ex({repoRoot:r,stateBranchRoot:o,ownEventFileName:t}));if(a(I))return Te(I.message);d=I.value.createdCommit,c=I.value.commitSha;let x=ae("hasRemote",await fn({repoRoot:o}));if(a(x))return Te(x.message);if(!x.value)return Ll({repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:c,bootstrapped:s},"no remote");let C=ae("pullBranchRebaseIfPresent",await Io({cwd:o,branch:g}));if(a(C))return xo(C.message)?Ll({repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:c,bootstrapped:s}):Te(C.message);m=C.value;let A=ae("isAheadOfUpstream",await Jc(o));if(a(A))return Te(A.message);if(d||s||A.value){logger.info("[sync] pushing state branch",{createdCommit:d,bootstrapped:s,stateBranchRoot:o});let M=ae("pushStateBranch",await jo({stateBranchRoot:o,repoRoot:r}));if(a(M)&&Yc(M.message)){let w=ae("pullBranchRebaseIfPresent(retry)",await Io({cwd:o,branch:g}));if(a(w))return Te(w.message);m=m||w.value,M=ae("pushStateBranch(retry)",await jo({stateBranchRoot:o,repoRoot:r}))}if(a(M))return xo(M.message)?Ll({repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:c,bootstrapped:s}):Te(M.message);p=M.value}if(d){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:o});let M=ae("git rev-parse HEAD",await U({args:["rev-parse","HEAD"],cwd:o}));if(a(M))return Te(M.message);c=M.value.stdout.trim(),logger.debug("[sync] final sync commit sha",c)}return ur(p?"Synced and pushed":m||d?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:r,stateBranchRoot:o,createdCommit:d,commitSha:c,pulled:m,pushed:p,bootstrapped:s,offline:!1})},kl=async(e,t)=>{let n=Bm(e);try{return await t()}finally{let r=Fm(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},ci=async e=>{let t=e.cwd??process.cwd(),n=await kt(t);if(a(n))return Te(n.message);let r=fe({repoRoot:n.value});if(a(r))return Te(r.message);let o=r.value;if(!Ix.existsSync(o))return Km(e);let s=await di({worktreeRoot:o,operation:"sync",fn:()=>kl(o,()=>Km(e))});return a(s)?Te(s.message):s.value===null?u("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var Zt=null,ui=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Zt,currentStatus:h().syncStatus?.status,currentMessage:h().syncStatus?.msg}),Zt)return logger.debug("[sync] syncAndReloadState joining existing promise"),Zt;logger.debug("[sync] syncAndReloadState creating promise"),Zt=Rx();try{let e=await Zt;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:h().syncStatus?.status,statusMessageAfterResolve:h().syncStatus?.msg}),a(e)&&h().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),N({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}),Zt||l(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:h().syncStatus?.status,statusMessageBeforeClear:h().syncStatus?.msg}),Zt=null}},Rx=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:h().mode,syncStatus:h().syncStatus});let e=qm();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:h().mode,message:e.message,syncStatus:h().syncStatus}),e;if(Zt)return Zt;logger.debug("[sync] syncAndReloadState:start");let t=ae("resolveActorId",ne());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),l("Unable to resolve event log path");N({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:h().syncStatus});let n=lr(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=ae("syncEpiqWithRemote",await ci({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),N({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:h().syncStatus}),Te(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=Dl(o);return a(i)?i:(N({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:h().syncStatus}),u("Synced",!0))},Dl=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=ae("loadMergedEvents",St(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:h().syncStatus}),l(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=qm();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:h().mode,message:n.message,syncStatus:h().syncStatus}),n;let r=Cm(),o=h().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id,selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual}),!h().selectedNode?.isVirtual&&!h().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=ae("bootStateFromEventLog",Ot(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:h().syncStatus}),l(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:h().selectedNode?.isVirtual,contextNodeIsVirtual:h().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),N({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=ae("restoreNavigationAnchor",Am(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:h().selectedNode?.id,contextNodeId:h().contextNode?.id}),a(s)?(N({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:h().syncStatus}),s):u("Reloaded state from event log",null)},qm=()=>h().mode===b.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:h().mode,syncStatus:h().syncStatus}),N({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),l("Will not re-materialize if not in default mode, to not lose edit data"));var Hr=3e3,Ym=e=>{let t=Number(e.trim());return!Number.isFinite(t)||!Number.isInteger(t)||t<Hr?null:t},Xm=0,Bl,Fl=!1,$o=!1,Ol=()=>{if(Fl)return!0;let e=it();return a(e)?!1:e.value.syncStatus.status==="syncing"},Cx=()=>{let e=le().autoSyncIntervalMs??1e4,t=Date.now()-Xm;return Math.max(0,e-t)},Jm=()=>{Bl||(Bl=setTimeout(async()=>{if(Bl=void 0,!!It()){if(Ol()){$o=!0;return}$o=!1,await Nx()}},Cx()))},Nx=async()=>{if(h().readOnly||h().timeMode==="peek"||h().timeMode==="replay")return l("Cannot auto-sync while peeking");if(!It())return l("Cannot auto-sync before state is initialized");if(Ol())return $o=!0,l("Sync already in progress");Fl=!0,Xm=Date.now(),N({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await ui()}finally{Fl=!1,$o&&Jm()}},mi=()=>{It()&&($o=!0,!Ol()&&Jm())};import Ho from"node:fs";import Wo from"node:path";import{z as Wr}from"zod";var pi="recent-projects.json",Ax=20,Tx=Wr.object({projectId:Wr.string().min(1),root:Wr.string().min(1),lastOpenedAt:Wr.number().finite()}),wx=Wr.object({projects:Wr.array(Tx)}),Zm=()=>Wo.join(un(),pi),Gr=e=>Wo.basename(e)||e,Qm=e=>{let t=Wo.resolve(e);try{return Ho.realpathSync(t)}catch{return t}},ep=(e,t)=>t.lastOpenedAt-e.lastOpenedAt,tp=e=>{if(!No(e.root))return!1;let t=vo(e.root);return!a(t)&&t.value===e.projectId},np=()=>{let e=Zm();if(!Ho.existsSync(e))return u("No recent projects recorded",[]);let t;try{t=JSON.parse(Ho.readFileSync(e,"utf8"))}catch(r){return l(`Invalid ${pi}: ${r instanceof Error?r.message:String(r)}`)}let n=wx.safeParse(t);return n.success?u("Read recent projects",n.data.projects):l(`Invalid ${pi} shape: ${n.error.issues.map(r=>r.path.join(".")||r.message).join(", ")}`)},Mx=e=>{let t=Zm();try{Ho.mkdirSync(Wo.dirname(t),{recursive:!0}),Ho.writeFileSync(t,JSON.stringify({projects:e},null,2)+`
|
|
68
|
-
`,"utf8")}catch(n){return l(`Unable to write ${pi}: ${n instanceof Error?n.message:String(n)}`)}return u("Recorded recent project",e)},Rn=({exclude:e}={})=>{let t=np();if(a(t))return t;let n=e===void 0?null:Qm(e);return u("Listed recent projects",t.value.filter(r=>n===null||Qm(r.root)!==n).filter(tp).sort(ep))},fi=({root:e,now:t=Date.now()})=>{let n=Wo.resolve(e),r=vo(n);if(a(r))return l(r.message);let o=r.value,s=np(),i=a(s)?[]:s.value,d=[{projectId:o,root:n,lastOpenedAt:t},...i.filter(c=>c.projectId!==o&&c.root!==n)].filter(tp).sort(ep).slice(0,Ax);return Mx(d)};var _n=()=>{let e=le(),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}},rp=()=>{let e=Se(process.cwd());if(a(e))return!1;let t=pt(e.value);return me(t)},op=e=>e===!0?"on":e===!1?"off":null,sp=e=>e==="on"?!0:e==="off"?!1:null;var Je={bg:"#1a1b26",fg:"#c8d3ff",grayDark:"#3a3e54",gray:"#46507a",grayLight:"#969bb5",cyan:"#88d5ee",cyanSoft:"#8fe6fb",blue:"#5b8cff",magenta:"#a78bfa",magentaSoft:"#c4b5fd",green:"#8fdc8c",yellow:"#f1c27d",red:"#ff7a90",white:"#ffffff"},y={accent:Je.cyan,accent2:Je.magenta,primary:Je.white,secondary:Je.grayDark,secondary2:Je.grayLight,gray:Je.gray,green:Je.green,yellow:Je.yellow,red:Je.red};var T={red:Je.red,yellow:Je.yellow,green:Je.green,blue:Je.blue,magenta:Je.magenta,cyan:Je.cyan},Vr={urgent:T.red,critical:T.red,important:T.red,blocker:T.red,asap:T.red,immediate:T.red,fail:T.red,failure:T.red,broken:T.red,bug:T.red,error:T.red,incident:T.red,outage:T.red,production:T.red,crash:T.red,security:T.red,warning:T.yellow,warn:T.yellow,risky:T.yellow,risk:T.yellow,attention:T.yellow,pending:T.yellow,review:T.yellow,"needs-review":T.yellow,qa:T.yellow,testing:T.yellow,test:T.yellow,validate:T.yellow,verification:T.yellow,staging:T.yellow,check:T.yellow,"follow-up":T.yellow,followup:T.yellow,waiting:T.yellow,blocked:T.yellow,hold:T.yellow,done:T.green,complete:T.green,completed:T.green,success:T.green,ok:T.green,stable:T.green,resolved:T.green,fixed:T.green,closed:T.green,merged:T.green,released:T.green,deployed:T.green,approved:T.green,verified:T.green,working:T.green,healthy:T.green,pass:T.green,passing:T.green,info:T.blue,information:T.blue,note:T.blue,docs:T.blue,documentation:T.blue,doc:T.blue,guide:T.blue,help:T.blue,explanation:T.blue,detail:T.blue,details:T.blue,context:T.blue,design:T.blue,discussion:T.blue,proposal:T.blue,idea:T.blue,feature:T.magenta,enhancement:T.magenta,improvement:T.magenta,refactor:T.magenta,refactoring:T.magenta,cleanup:T.magenta,optimize:T.magenta,optimization:T.magenta,perf:T.magenta,performance:T.magenta,upgrade:T.magenta,migration:T.magenta,modernize:T.magenta,debt:T.magenta,todo:T.cyan,next:T.cyan,planned:T.cyan,plan:T.cyan,future:T.cyan,backlog:T.cyan,investigate:T.cyan,explore:T.cyan,prototype:T.cyan};var Px=e=>e.props.tags??[],Lx=e=>e.props.assignees??[],Un=e=>Px(e).map(t=>R.getTag(t)).filter(t=>!!t),jn=e=>Lx(e).map(t=>R.getContributor(t)).filter(t=>!!t),gi=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!B(n)?l("Invalid untag target"):u("Retrieved tags from ticket in breadcrumb",Un(n))},hi=()=>{let{breadCrumb:e,selectedNode:t}=h(),n=[...e,t].find(r=>r?.context==="TICKET");return!n||!B(n)?l("Invalid unassign target"):u("Retrieved assignees from ticket in breadcrumb",jn(n))};var E={PALETTE:"?",EXIT:"exit",INIT:"init",OPEN:"open",HELP:"help",NEW:"new",TAG:"tag",UNTAG:"untag",MOVE:"move",PEEK:"peek",REPLAY:"replay",FILTER:"filter",ASSIGN:"assign",UNASSIGN:"unassign",DELETE:"delete",CLOSE_ISSUE:"close",RE_OPEN_ISSUE:"reopen",COMMENT:"comment",CONFIG:"config",EDIT:"edit",YANK:"yank",SYNC:"sync",EXPORT:"export",NONE:""};var kx=/^(\d+)(h|d|w|mo|y)$/,Dx=/^(\d{4})-(\d{2})-(\d{2})(?:(?::|\s)(\d{2}):(\d{2}))?$/,Bx=({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},Fx=(e,t=new Date)=>{let n=e.match(kx);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}},Ox=e=>{let t=e.match(Dx);if(!t)return null;let[,n,r,o,s,i]=t,d=Number(n),c=Number(r),m=Number(o),p=s?Number(s):0,f=i?Number(i):0;return Bx({year:d,month:c,day:m,hour:p,minute:f})?new Date(d,c-1,m,p,f):null},mr=e=>{let t=e.trim().toLowerCase();return Fx(t)??Ox(t)};var ip=/^(\d+)(s|m)?$/,yi=e=>{let t=e.trim().toLowerCase().match(ip);if(!t)return null;let n=Number(t[1]);return!Number.isInteger(n)||n<=0?null:t[2]==="m"?n*6e4:n*1e3},vi=(e,t)=>{let n=(t??"").trim().split(/\s+/).filter(Boolean),r=n.length>0&&ip.test(n.at(-1))?n.pop():"";return{dateInput:e||n.join(" "),durationInput:r}},ap=({date:e,horizonDate:t})=>t?e.getTime()>=t.getTime():!0,_x=[{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}],_l=(e=_x)=>{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 Ux=["BOARD","TICKET","SWIMLANE","COMMENT"],xe={EDITOR:"editor",VIEW:"view",USERNAME:"username",AUTOSYNC:"autoSync",SYNC_DEBOUNCE_MS:"syncDebounceMs",ATTACHMENT_MAX_KB:"attachmentMaxKb",LOG_LEVEL:"logLevel"},ht={TITLE:"title",DESCRIPTION:"description",COMMENT:"comment"},Me={REF:"ref",TITLE:"title",DESCRIPTION:"description",TAGS:"tags",ASSIGNEES:"assignees"},jx=[xe.EDITOR,xe.VIEW,xe.USERNAME,xe.AUTOSYNC,xe.SYNC_DEBOUNCE_MS,xe.ATTACHMENT_MAX_KB,xe.LOG_LEVEL],$x=(e=h().selectedNode?.context)=>{switch(e){case"TICKET":return[ht.TITLE,ht.DESCRIPTION];case"BOARD":case"SWIMLANE":return[ht.TITLE];case"COMMENT":return[ht.COMMENT];default:return[]}},jl=[String(Hr),"5000","15000","30000","60000"],$l=["250","500","1000"],cp=["10s","20s","30s","45s"],pr=[E.EXIT,E.SYNC,E.HELP,E.EXPORT,E.CONFIG,E.YANK],bi=[E.NEW,E.EDIT,E.DELETE,E.MOVE],Ul=[E.TAG,E.UNTAG,E.ASSIGN,E.UNASSIGN,E.CLOSE_ISSUE,E.RE_OPEN_ISSUE,E.EDIT,E.COMMENT],lp=[E.FILTER,E.PEEK,E.REPLAY],Hx={WORKSPACE:[...pr,...bi],BOARD:[...lp,...pr,...bi],SWIMLANE:[...lp,...pr,...bi],TICKET:[...pr,...bi,...Ul],FIELD:[...pr,...Ul],FIELD_LIST:[...pr,...Ul],TEXT:[...pr],COMMENT:[E.EDIT,E.DELETE,E.YANK]},Wx=e=>e==="WORKSPACE"?["board"]:["issue","swimlane","board"],Go=({breadCrumb:e,selectedNode:t})=>[...e,t].find(n=>n!=null&&B(n)),dp=e=>e.parentNodeId===ie,Gx=({selectedNode:e,breadCrumb:t})=>{let n=$x(e?.context);return Go({breadCrumb:t,selectedNode:e})?n.includes(ht.DESCRIPTION)?n:[...n,ht.DESCRIPTION]:n},Vx=({selectedNode:e,breadCrumb:t})=>{let n=Go({breadCrumb:t,selectedNode:e});return n?[Me.REF,Me.TITLE,...n.props?.description?.trim()?[Me.DESCRIPTION]:[],...Un(n).length>0?[Me.TAGS]:[],...jn(n).length>0?[Me.ASSIGNEES]:[]]:e?[Me.REF,Me.TITLE]:[]},Hl=()=>{let e=Rn({exclude:process.cwd()});return a(e)?[]:[...e.value.map((t,n)=>String(n+1)),...e.value.map(t=>t.root)]},zx=({selectedNode:e,readOnly:t,breadCrumb:n})=>{let{isSetupDone:r}=_n();if(!r)return[E.HELP,E.CONFIG];if(!rp())return[E.HELP,E.INIT,E.OPEN];if(t)return[E.HELP,E.PEEK,E.REPLAY,E.EXPORT,E.CONFIG,E.YANK];let o=e?.context,s=o&&Ux.includes(o),i=[...new Set([...n,e].map(c=>c?.context).flatMap(c=>c?Hx[c]:[]))],d=Go({breadCrumb:n,selectedNode:e});return i.filter(c=>c===E.MOVE?!1:c===E.YANK?!!(d??e):c===E.EDIT?s||!!d:c===E.DELETE?s:c===E.UNTAG?!!(d&&Un(d).length>0):c===E.UNASSIGN?!!(d&&jn(d).length>0):c===E.RE_OPEN_ISSUE?!!(d&&dp(d)):c===E.CLOSE_ISSUE?!!(d&&!dp(d)):!0)},Ne=(e,{contextNode:t,selectedNode:n,readOnly:r,breadCrumb:o}=h())=>{let s=t.context??"WORKSPACE";return{[E.NONE]:zx({breadCrumb:o,readOnly:r,selectedNode:n}),[E.EXIT]:["confirm"],[E.EXPORT]:[],[E.SYNC]:[],[E.INIT]:[],[E.OPEN]:e===E.OPEN?Hl():[],[E.HELP]:[],[E.PEEK]:[..._l(),"now","prev","next"],[E.REPLAY]:[..._l()],[E.EDIT]:Gx({selectedNode:n,breadCrumb:o}),[E.YANK]:Vx({selectedNode:n,breadCrumb:o}),[E.COMMENT]:[],[E.DELETE]:["confirm"],[E.RE_OPEN_ISSUE]:["confirm"],[E.CLOSE_ISSUE]:["confirm"],[E.MOVE]:["start","confirm","next","previous","to-next","to-previous","cancel"],[E.FILTER]:["tag","assignee","actor","description","title","ref","clear"],[E.TAG]:[...new Set([...Object.keys(Vr),...R.getExistingTags()])],[E.UNTAG]:[...gi()?.value?.map(({name:d})=>d)??[]],[E.UNASSIGN]:[...hi()?.value?.map(({name:d})=>d)??[]],[E.ASSIGN]:R.getExistingAssignees(),[E.NEW]:Wx(s),[E.CONFIG]:[...jx]}[e]??[]};import Tp from"chalk";var up=["vim","nvim","nano","micro","emacs","hx","code","code-insiders","subl","notepad","notepad++","idea","webstorm","default","system","$EDITOR","$VISUAL"];import Jx from"zod";import Kx from"node:crypto";import Vo from"node:fs";import fp from"node:path";var mp="/media/",pp=e=>`${mp}${e}`,Wl=(e,t)=>`})`;var en=500,qx=/^[a-f0-9]{64}\.(png|jpg|gif|webp)$/,fr=(e,t)=>`${e}.${t}`,Yx=e=>qx.test(e),gp=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"):l(`Unsupported image format. Allowed: ${xu.join(", ")}`),hp=e=>Kx.createHash("sha256").update(e).digest("hex"),Xx=(e,t=en)=>{if(e.length===0)return l("Attachment is empty");if(e.length>t*1024)return l(`Attachment exceeds the ${t} KB size cap (${Math.ceil(e.length/1024)} KB)`);let n=gp(e);return a(n)?n:u("Validated attachment data",{hash:hp(e),ext:n.value,bytes:e.length})},yp=(e,t,n=en)=>{let r=Xx(t,n);if(a(r))return r;let o=Co(e),s=fp.join(o,fr(r.value.hash,r.value.ext));try{Vo.existsSync(s)||(Vo.mkdirSync(o,{recursive:!0}),Vo.writeFileSync(s,t))}catch(i){return l(`Unable to write attachment blob: ${i instanceof Error?i.message:String(i)}`)}return u("Wrote attachment blob",r.value)},vp=(e,t,n=en)=>{if(!Yx(t))return l("Invalid attachment file name");let r=fp.join(Co(e),t);if(!Vo.existsSync(r))return l("Attachment blob not found");let o;try{o=Vo.readFileSync(r)}catch(c){return l(`Unable to read attachment blob: ${c instanceof Error?c.message:String(c)}`)}if(o.length>n*1024)return l(`Attachment exceeds the ${n} KB size cap and will not be served`);let[s,i]=t.split(".");if(hp(o)!==s)return l("Attachment blob does not match its content hash");let d=gp(o);return a(d)?d:d.value!==i?l("Attachment blob content does not match its extension"):u("Resolved attachment blob",{filePath:r,ext:i,bytes:o.length})};var zo=50,Ko=5e3,bp=()=>{let e=re().commandMeta.inputString,t=Jx.coerce.number().int().min(zo).max(Ko).safeParse(e);if(!t.success)return l(`Attachment size cap must be ${zo}-${Ko} KB (default ${en})`);let n=vt({attachmentMaxKb:t.data});return a(n)?n:(Ye({attachmentMaxKb:t.data}),N({mode:b.DEFAULT}),u(`Attachment size cap set to ${t.data} KB`,null))};import zr from"chalk";var Vl={stringColor:{saturation:50,lightness:60},gradient:{stops:[[174,150,240],[92,138,232],[102,204,226]]}},xp=(e,t,n)=>Math.max(t,Math.min(n,e)),Gl=(e,t,n)=>e+(t-e)*n,Ip=e=>{let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t},Qx=e=>e.toLowerCase().trim(),Zx=(e,t,n)=>{let r=t/100,o=n/100,s=(1-Math.abs(2*o-1))*r,i=e/60,d=s*(1-Math.abs(i%2-1)),c=0,m=0,p=0;i>=0&&i<1?(c=s,m=d):i>=1&&i<2?(c=d,m=s):i>=2&&i<3?(m=s,p=d):i>=3&&i<4?(m=d,p=s):i>=4&&i<5?(c=d,p=s):(c=s,p=d);let f=o-s/2;return[Math.round((c+f)*255),Math.round((m+f)*255),Math.round((p+f)*255)]},Sp=([e,t,n])=>`#${e.toString(16).padStart(2,"0")}${t.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}`;var eI=(e,t,n)=>{let r=xp(n,0,1);return[Math.round(Gl(e[0],t[0],r)),Math.round(Gl(e[1],t[1],r)),Math.round(Gl(e[2],t[2],r))]};var tI=(e,t,n)=>eI(e,t,n),qo=e=>{let t=Ip(e)%360,n=Zx(t,Vl.stringColor.saturation,Vl.stringColor.lightness);return Sp(n)},ce=(e,t=Vr)=>{let n=Qx(e??"");return n&&t[n]?t[n]:qo(n)};var Ep=e=>{let t=Vl.gradient.stops,n=xp(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 tI(t[s],t[s+1],i)},xi=e=>Sp(Ep(e)),Ii=e=>Ip(e.toLowerCase().trim())/4294967295,Rp=e=>{let t=Ii(e);return Ep(t)},nI=e=>{let[t,n,r]=Rp(e);return{normal:o=>zr.bgRgb(t,n,r).black(o),cursor:o=>zr.bgRgb(t,n,r).white.bold(o)}},zl=e=>{let[t,n,r]=Rp(e);return{fg:o=>zr.rgb(t,n,r)(o),fgCursor:o=>zr.rgb(t,n,r).inverse(o),bg:o=>zr.bgRgb(t,n,r).black(o),bgCursor:o=>zr.bgRgb(t,n,r).white.bold(o)}},Si=e=>nI(e).normal(` ${e} `);var Qe=(e,t,n)=>t.length>n?`${e} cannot exceed ${n} characters (got ${t.length})`:null;import{createHash as rI}from"node:crypto";var oI="0123456789ABCDEFGHJKMNPQRSTVWXYZ",sI=e=>{let t=rI("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+=oI[Number(n>>s&31n)]}return r},De=(e,t)=>sI(`${e}:virtual:${t}`);import Cp from"chalk";var ge=e=>Cp.dim(e),Be=e=>Cp.hex(y.primary)(e),Ge=({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)=>Ii(f)-Ii(g)).slice(0,r).map(f=>Si(f)).join(" ");return p?`${ge(e)}${p}${ge(n)}`:""};var tn={None:"none",Invalid:"invalid",Valid:"valid"};var iI=["BOARD","TICKET","SWIMLANE"],Np=()=>{let e=h().selectedNode;if(!e?.context)return W({message:ge("Missing target context")});if(iI.includes(e.context))return ee();if(e.parentNodeId){let t=h().nodes[e.parentNodeId];if(t?.id===De(t?.parentNodeId??"","comments"))return ee()}return W({message:ge("Command not available in this context")})},ue="<ENTER> to confirm",ee=(e="",t=[])=>({message:ge(e),validity:tn.Valid,completionWordList:t}),W=({message:e,completionWordList:t=[]})=>({validity:tn.Invalid,message:e,completionWordList:t}),qr=e=>e.length===0,Ap=(e,t)=>{let n=ot(h().breadCrumb,"BOARD");if(a(n))return W({message:Be("Command is not applicable in this context")});let r=Us(n.value.id);return a(r)?W({message:Be(`Unable to ${t}: board id is not a valid ULID`)}):ap({date:e,horizonDate:r.value})?null:W({message:Be(`nothing to ${t} before ${r.value.toISOString().slice(0,16).replace("T"," ")}`)})},Ei=e=>` ${Tp.hex("#000").bgHex(ce(e))(` ${e} `)} `,Kl=({modifier:e})=>{let t="confirm";return e===t?ee(ue):W({message:qr(e)?ge("if you are certain, enter ")+Si(t):"",completionWordList:[t]})},aI=({list:e,hint:t,onValue:n})=>({modifier:r,inputString:o})=>e.includes(r)?o.trim().length<1?W({message:ge(n)}):ee():W({message:qr(r)?t:"",completionWordList:[...e]}),Kr=({hint:e,onOk:t})=>({modifier:n,inputString:r})=>qr(n)&&qr(r)?W({message:e,completionWordList:[]}):ee(t??ue),lI=({modifier:e,inputString:t})=>{let n=Hl();return!qr(e)||!qr(t)?ee(ue):W({message:n.length?ge("number from the list, or a path"):ge("path to an epiq project"),completionWordList:n})},dI=({modifier:e,inputString:t})=>{let n=Ne(E.CONFIG);if(!n.includes(e))return W({message:Ge({prefix:"... ",wordList:n,inputString:e,minLengthForHints:0}),completionWordList:n});switch(e){case xe.EDITOR:{let r=[...up];return t.trim()?r.includes(t.trim())?ee(ue):W({message:Ge({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r}):W({message:Ge({prefix:"editors: ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case xe.VIEW:{let r=["dense","wide"];return r.includes(t.trim())?ee(ue):W({message:Ge({prefix:"view... ",wordList:r,inputString:t,minLengthForHints:0}),completionWordList:r})}case xe.USERNAME:return t.trim()?ee(ue):W({message:Be("Enter a user name. Saved in ")+Tp.bgBlack("~/.epiq-global/config.json")});case xe.LOG_LEVEL:{let r=["debug","error","info"],o=t.trim();return r.includes(o)?ee(ue):W({message:Ge({prefix:"one of: ",wordList:[...r],inputString:o,postfix:" persisted in ~/.epiq-global/config.json",minLengthForHints:0}),completionWordList:[...r]})}case xe.AUTOSYNC:{let r=["on","off"],o=le().autoSync;if(!r.includes(t.trim())){let s=op(o);return W({message:Ge({prefix:`should auto-sync (recommended)${s!==null?", currently: "+s:""} `,wordList:r,noOfHints:3,inputString:t,minLengthForHints:0}),completionWordList:r})}return ee(ue)}case xe.ATTACHMENT_MAX_KB:{let r=le().attachmentMaxKb,o=Number.parseInt(t.trim(),10);if(!t.trim()||Number.isNaN(o)||o<zo||o>Ko){let s=Ge({prefix:" examples: ",wordList:$l,minLengthForHints:0,inputString:t});return W({message:Be(`provide a size cap in KB (${zo}-${Ko}). current: ${r??en} KB.`)+s,completionWordList:$l})}return ee(ue)}case xe.SYNC_DEBOUNCE_MS:{let r=le().autoSyncIntervalMs,o=Ym(t);if(!t.trim()||o===null||o<Hr){let s=Ge({prefix:" examples: ",wordList:jl,minLengthForHints:0,inputString:t});return W({message:Be(`provide duration above ${Hr}ms. current duration: ${r}ms.`)+s,completionWordList:jl})}return ee(ue)}default:return W({message:Be("Unknown config option"),completionWordList:n})}},cI=({modifier:e,inputString:t})=>{let n=Ne(E.EDIT);if(!n.length)return W({message:Be("Command not available in this context")});if(!n.includes(e)){let r=Ge({prefix:"edit... ",wordList:n,inputString:e,minLengthForHints:0});return W({message:r||Be("Unknown edit option"),completionWordList:n})}switch(e){case ht.COMMENT:return t.trim()?ee(ue):W({message:ge("write a comment...")});case ht.TITLE:return ee(ue);case ht.DESCRIPTION:{let{preferredEditor:r}=le();return r?ee(ge("<ENTER> to edit in ")+r):W({message:"No editor selected"})}default:return W({message:Be("Unknown edit option"),completionWordList:n})}},uI=({modifier:e})=>{let t=Ne(E.YANK);return t.length?t.includes(e)?ee(ue+ge(" and copy to clipboard")):W({message:Ge({prefix:"yank... ",wordList:t,inputString:e,minLengthForHints:0}),completionWordList:t}):W({message:Be("Nothing selected to copy from")})},mI={[E.EXPORT]:()=>ee(ue+ge(", and create export markdown file")),[E.PEEK]:e=>{let t=e.modifier;if(t==="now"||t==="prev"||t==="next")return ee(ue);let n={message:ge("historical state from: '1h', '2d', '23h', '1mo', '2y', 'prev', 'next' or full date as YYYY-MM-DD")},r=t||e.inputString.trim(),o=mr(r);if(!r||!o)return W(n);let s=Ap(o,"peek");return s||ee(ue)},[E.REPLAY]:e=>{let{dateInput:t,durationInput:n}=vi(e.modifier,e.inputString),r={message:ge("replay forward from: '1h', '2d', '1mo', '2y' or full date as YYYY-MM-DD, with optional duration (e.g. '2y 30s')")},o=mr(t);if(!t||!o)return W(r);let s=Ap(o,"replay");return s||(n&&yi(n)===null?W({message:Be("duration must be positive (e.g. 30s, 2m, or a number of seconds)")}):ee("<ENTER> to replay board history",n?cp:[]))},[E.EXIT]:()=>ee(ue+ge(" and exit the application")),[E.INIT]:()=>ee(ue),[E.OPEN]:lI,[E.PALETTE]:()=>ee(ue),[E.FILTER]:e=>{if(e.modifier==="clear")return ee(ue);let t=s=>Ne(E.FILTER).includes(s);if(!e.modifier||!t(e.modifier))return W({message:Ge({wordList:Ne(E.FILTER),inputString:e.inputString,minLengthForHints:0}),completionWordList:Ne(E.FILTER)});let n=Object.values(h().tags).map(s=>s.name),r=Object.values(h().contributors).map(s=>s.name),o=e.modifier==="tag"?n:e.modifier==="assignee"?r:[];return e.inputString?o.length&&!o.includes(e.inputString.trim())?W({message:Ge({prefix:`existing ${e.modifier}s... `,wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o}):ee():W({message:Ge({prefix:"one of... ",wordList:o,noOfHints:10,inputString:e.inputString,minLengthForHints:0}),completionWordList:o})},[E.NONE]:e=>{let t=Ne(E.NONE);return W({message:Ge({prefix:"... ",wordList:t,inputString:e.inputString,minLengthForHints:0}),completionWordList:t})},[E.NEW]:e=>aI({list:Ne(E.NEW),hint:Ge({wordList:Ne(E.NEW),noOfHints:3,inputString:e.inputString,minLengthForHints:0}),onValue:"provide a name..."})(e),[E.HELP]:()=>ee(ue),[E.EDIT]:cI,[E.COMMENT]:e=>{let t=Kr({hint:ge(`write a comment (max ${4e3} char)...`),onOk:ge(`(${e.inputString.length}/${4e3})`)})(e);return t.validity===tn.Invalid?t:e.inputString.length>4e3?ee(Be("max input exceeded")):t},[E.CONFIG]:dI,[E.YANK]:uI,[E.DELETE]:e=>{let t=Np();return t.validity==="invalid"?t:Kl(e)},[E.CLOSE_ISSUE]:e=>Kl(e),[E.RE_OPEN_ISSUE]:e=>Kl(e),[E.MOVE]:e=>{let t=Np();return t.validity==="invalid"?t:Kr({hint:Ge({prefix:"hey hacker! These commands are blocked for you... ",wordList:Ne(E.MOVE),noOfHints:10,inputString:e.inputString})})(e)},[E.TAG]:e=>{let n=R.getExistingTags().slice(0,10).map(Ei).join("");return Kr({hint:n.length?ge("create tag or reuse:")+n+ge(""):ge("create tag ...")})(e)},[E.UNTAG]:e=>{let t=gi();if(a(t))return W({message:Be("Invalid untag target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ei).slice(0,10);return n.length?Kr({hint:ge(" ... ")+n.join("")})(e):W({message:Be("Issue has no tags"),completionWordList:[]})},[E.ASSIGN]:e=>{let t=R.getExistingAssignees().map(Ei).slice(0,10);return Kr({hint:ge("assignees... ")+t.join("")})(e)},[E.UNASSIGN]:e=>{let t=hi();if(a(t))return W({message:Be("Invalid unassign target"),completionWordList:[]});let n=t.value.map(({name:r})=>r).map(Ei).slice(0,10);return n.length?Kr({hint:ge("remove assignee... ")+n.join("")})(e):W({message:Be("Issue has no assignees"),completionWordList:[]})},[E.SYNC]:()=>ee(ue)},wp=Object.fromEntries(Object.entries(mI).map(([e,t])=>[e,{validate:(n,r,o)=>t({modifier:r,command:n,inputString:o})}]));var Ri=["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 pI=3,fI=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"]),gI=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},hI=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=pI&&!fI.has(t)&&!/^\d+$/.test(t)),yI=e=>{let t=new Map;for(let s of gI(e))for(let i of hI(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=Ri.filter(s=>!r.has(s));return[...n,...o]},Mp=Ri,Pp=-1,Lp=()=>{let e=it();if(a(e))return Ri;let t=e.value,n=t.eventLog.length;return n!==Pp&&(Mp=yI(t),Pp=n),Mp};var kp=e=>Object.values(E).includes(e),Dp=(e,t)=>{let n=e.command??"",{modifier:r,target:o,inputString:s}=e,{message:i,validity:d,completionWordList:c}=wp[n].validate(n,r,s),m=n!==E.PEEK&&n!==E.REPLAY,p=o==="command"||o==="modifier"?Ne(n):m?Lp():[],{mode:f}=h(),g=f===b.COMMAND_LINE?i??"":"",v=[...c,...p];return{validity:d,command:e.command,modifier:e.modifier,inputString:e.inputString,infoMessage:g,autoCompletion:t?Lu(e,v):{hint:"",hints:[],remainder:"",overlap:0}}};var Bp=e=>{let t=e.trimStart(),n=bI(t),r=n[0]??"",o=n[1]??"",s=/\s$/.test(e),i=xI(e),d=kp(r)?r:null,c=d!==null,m=r!=="",p=d?Ne(d)??[]:[],f=d&&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 v=s?"":i,I=vI(t,d,f);return{raw:e,trimmedStart:t,words:n,firstWord:r,lastWord:i,hasCommand:m,command:d,isCommandKeyword:c,isLastWordCompleted:s,modifier:f,target:g,inputToMatch:v,inputString:I}},vI=(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},bI=e=>e.trim()?e.trim().split(/\s+/):[],xI=e=>e.trimEnd().split(/\s+/).at(-1)??"";import{useSyncExternalStore as II}from"react";var Yr=e=>e===ql||e===":",ql=" ",Ze={commandHistory:[],value:"",commandHistoryIndex:-1,cursorPosition:0,commandIsPending:!1,commandMeta:{command:null,modifier:"",infoMessage:"",inputString:"",validity:tn.None,autoCompletion:{hint:"",hints:[],remainder:"",overlap:0}}},Yl=new Set,Fp=()=>{for(let e of Yl)e()},Xl=e=>(Yl.add(e),()=>Yl.delete(e)),nn=e=>{let n=e(Ze),r=Bp(n.value),o=n.cursorPosition===n.value.length;Ze={...n,commandMeta:Dp(r,o)},Fp()},Yo=({message:e,status:t})=>{let n=structuredClone(Ze);return n.commandMeta={...n.commandMeta,infoMessage:e??"",validity:t==="fail"?"invalid":"valid"},n.commandIsPending=!0,Ze=n,Fp(),u(e,null)},Jl=e=>{nn(t=>({...t,cursorPosition:Math.max(0,Math.min(t.value.length,t.cursorPosition+e))}))},Ql=e=>{nn(t=>{let{value:n,cursorPosition:r}=t,o=r;if(e==="left"){for(;o>0&&Yr(n[o-1]);)o--;for(;o>0&&!Yr(n[o-1]);)o--}else{for(;o<n.length&&!Yr(n[o]);)o++;for(;o<n.length&&Yr(n[o]);)o++}return{...t,cursorPosition:o}})},Op=()=>{nn(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}})},_p=()=>{nn(e=>{let{value:t,cursorPosition:n}=e,r=n;for(;r>0&&Yr(t[r-1]);)r--;for(;r>0&&!Yr(t[r-1]);)r--;let o=t.slice(n);return{...e,value:t.slice(0,r)+o,cursorPosition:r,commandIsPending:!1}})},Ci=e=>{nn(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,d=Math.max(0,Math.min(s.length,i.length));return{...t,value:i,cursorPosition:d,commandIsPending:!1}})},Up=()=>{nn(e=>({...e,commandIsPending:!0}))},te=e=>{nn(t=>({...t,value:e,cursorPosition:e.length,commandIsPending:!1}))},jp=({addToHistory:e=!0})=>{nn(n=>({...n,commandHistory:e?[n.value,...n.commandHistory].slice(0,40):n.commandHistory,commandHistoryIndex:-1,commandIsPending:!1,value:"",cursorPosition:0}))},$p=()=>{nn(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}})},Hp=()=>{nn(e=>{let t=Math.max(e.commandHistoryIndex-1,-1),n=t===-1?"":e.commandHistory[t]??"";return{...e,commandHistoryIndex:t,value:n,cursorPosition:n.length}})},re=()=>Ze,Wp=()=>II(Xl,re,re),Ni=()=>{let[e,...t]=Ze.value.split(ql);return t.join(ql).trim()};var S={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 SI(e){switch(e.name){case"up":case"down":case"left":case"right":return e.name;default:return null}}function EI(e){switch(e.name){case"k":return"up";case"j":return"down";case"h":return"left";case"l":return"right";default:return null}}function RI(e,t,n){let r=h().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 Gp(e,t){let n=re();if(e.sequence==="?"&&t!==b.PALETTE)return S.InitCommandPalette;if(e.sequence===":"&&t!==b.COMMAND_LINE)return S.InitCommandLine;if(t===b.MOVE)switch(e.name){case"m":case"return":return S.ConfirmMove}if(t===b.COMMAND_LINE)return Ru(e,n.value);if(t===b.PALETTE)return Cu(e,n.value);let r=SI(e)||EI(e);if(r)return CI(r,t);if(e.ctrl&&e.name==="c")return S.Exit;switch(e.name){case"r":return S.EditTitle;case"e":return S.EditDescription;case"n":return S.AddItem;case"m":return S.InitMove;case"d":return S.Delete;case"y":return S.Yank;case"return":return S.Confirm;case"space":return S.Confirm;case"v":return le().viewMode==="wide"?S.SetViewDense:S.SetViewWide;case"q":case"escape":return S.Exit;default:return null}}function CI(e,t){let n=t===b.MOVE?{prevItem:S.MovePreviousItem,nextItem:S.MoveNextItem,prevContainer:S.MoveToPreviousContainer,nextContainer:S.MoveToNextContainer}:{prevItem:S.NavPreviousItem,nextItem:S.NavNextItem,prevContainer:S.NavToPreviousContainer,nextContainer:S.NavToNextContainer};return RI(h().contextNode.childRenderAxis,e,n)}var Ai=e=>{let{context:t}=h().contextNode;if(!t)return j.None;switch(e){case E.EXIT:return j.Exit;case E.EXPORT:return j.Export;case E.INIT:return j.Init;case E.OPEN:return j.OpenProject;case E.DELETE:return j.Delete;case E.EDIT:return j.Edit;case E.COMMENT:return j.Comment;case E.HELP:return j.ViewHelp;case E.RE_OPEN_ISSUE:return j.ReopenIssue;case E.CLOSE_ISSUE:return j.CloseIssue;case E.TAG:return j.TagTicket;case E.UNTAG:return j.UntagTicket;case E.ASSIGN:return j.AssignUserToTicket;case E.UNASSIGN:return j.UnassignUserFromTicket;case E.NEW:return j.NewItem;case E.FILTER:return j.Filter;case E.MOVE:return j.Move;case E.PEEK:return j.Peek;case E.REPLAY:return j.Replay;case E.CONFIG:return j.Config;case E.YANK:return j.Yank;case E.SYNC:return j.Sync;default:return j.None}},j={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"};import Tf from"node:fs";import CS from"node:path";import NS from"react";import{Box as ES}from"ink";import Di from"react";import VI from"chalk";import{Box as td,Text as zI}from"ink";import rn from"react";import{Text as Vp}from"ink";import zp,{useEffect as Kp,useState as NI}from"react";var qp={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "]},et=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=J(),r=qp[n]??qp.default,[o,s]=NI(0);if(Kp(()=>{s(0)},[r]),Kp(()=>{if(!e)return;let d=setInterval(()=>{s(c=>(c+1)%r.length)},500);return()=>clearInterval(d)},[e,r]),!e)return zp.createElement(Vp,null,t);let i=r[o]??r[0]??t;return zp.createElement(Vp,{color:y.accent,dimColor:o===1},i)};import{Box as Zl,Text as AI}from"ink";import Ti from"react";var TI=(e,t,n,r)=>{let o=c=>Math.max(1,e[c]??1),s=n,i=n+1,d=o(n);for(;i<t&&d+o(i)<=r;)d+=o(i),i++;for(;s>0&&d+o(s-1)<=r;)s--,d+=o(s);return{start:s,end:i}},Et=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),d=Math.max(1,Math.ceil(r)),c=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/d)),p=Math.max(0,e.length-m),{start:f,end:g}=o?TI(o,e.length,c,i):s?{start:Math.min(p,Math.max(0,c-m+1)),end:Math.min(p,Math.max(0,c-m+1))+m}:{start:Math.min(p,Math.floor(c/m)*m),end:Math.min(p,Math.floor(c/m)*m)+m},v=Math.max(1,g-f),I=e.slice(f,g),x=e.length>v,C=i,A=x?Math.max(1,Math.floor(v/e.length*C)):C,M=Math.max(0,C-A),w=Math.max(1,e.length-v),L=x?Math.floor(f/w*M):0;return Ti.createElement(Zl,{flexDirection:"row",height:i,width:"100%"},Ti.createElement(Zl,{flexDirection:"column",flexGrow:1,height:i},I),Ti.createElement(Zl,{flexDirection:"column",width:1,height:C},Array.from({length:C}).map((k,Ie)=>Ti.createElement(AI,{key:Ie,color:x&&Ie>=L&&Ie<L+A?y.accent:y.secondary},x?"\u2502":" "))))};import{Box as Qr,Text as Zr}from"ink";import ct from"react";var Yp,ed,wI=()=>{let{eventLog:e=[]}=h();if(ed&&Yp===e)return ed;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Yp=e,ed=t,t},wi=e=>wI().has(e);import{Text as MI}from"ink";import PI from"react";var LI=e=>e.toLowerCase().trim(),kI=(e,t=Vr)=>{let n=LI(e);return t[n]?t[n]:qo(n)},$n=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:yn(o,n);return PI.createElement(MI,{underline:t,color:kI(o)},"@"+s,wi(e)?"":"\u2197")};import{Text as DI}from"ink";import BI from"react";var Xr=({id:e,isSelected:t,maxWidth:n})=>{let r=R.getTag(e);if(!r)return;let o=n===void 0?r.name:yn(r.name,n);return BI.createElement(DI,{underline:t,backgroundColor:ce(r.name),color:y.secondary}," "+o+" ")};import{useEffect as FI,useState as OI}from"react";var _I=80,Xp=1400,Mi=new Set,Xo=null,UI=e=>(Mi.add(e),Xo||(Xo=setInterval(()=>{for(let t of Mi)t()},_I)),()=>{Mi.delete(e),Mi.size===0&&Xo&&(clearInterval(Xo),Xo=null)}),jI=()=>{let e=Date.now()%Xp/Xp;return e<.5?e*2:(1-e)*2},Jr=e=>{let[,t]=OI(0);return FI(()=>{if(e)return UI(()=>t(n=>n+1))},[e]),xi(jI())};var $I=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),yn(e.slice(o).trim(),n)]},Jp=3,HI=2,WI=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,d=i>0?String(i).length+1:0;if(r+s.width+d>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},Qp=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=Jr(r),s=e-4,i=s-7-1,[d,c]=$I(ye(t.title),i,s),m=c?null:yn(ye(t.props.description),s)||null,p=Un(t),f=jn(t).map(A=>({...A,name:A.name})),g=Math.max(1,s-Jp),v=R.getCommentsByIssue(t.id),I=v.length?String(v.length).length+2+1:0,{shown:x,hidden:C}=WI([...p.map(A=>({id:A.id,isTag:!0,width:Math.min(A.name.length,g)+Jp})),...f.map(A=>({id:A.id,isTag:!1,width:Math.min(A.name.length,g)+HI+(wi(A.id)?0:1)}))],s-I);return ct.createElement(Qr,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?y.accent:y.secondary,justifyContent:"space-between"},ct.createElement(Qr,{paddingLeft:1,paddingRight:1,flexDirection:"column"},ct.createElement(Qr,{justifyContent:"space-between"},ct.createElement(Zr,{color:y.primary},d),ct.createElement(Zr,{color:y.secondary2,dimColor:!0},O(t.id))),c&&ct.createElement(Zr,{color:y.primary},c),m&&ct.createElement(Zr,{color:y.secondary2,dimColor:!0},m)),ct.createElement(Qr,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},ct.createElement(Qr,{flexDirection:"row"},x.map(A=>ct.createElement(Qr,{paddingRight:1,key:A.id},A.isTag?ct.createElement(Xr,{id:A.id,maxWidth:g}):ct.createElement($n,{id:A.id,maxWidth:g}))),C>0&&ct.createElement(Zr,{color:y.secondary2,dimColor:!0},"+",C)),v.length>0&&ct.createElement(Zr,{color:y.accent},"[",v.length,"]")))};import{Box as gr,Text as Jo}from"ink";import yt from"react";var GI=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,Zp=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let d=Jr(s),c=(r.props.tags??[]).map(k=>R.getTag(k)).filter(k=>!!k),m=(r.props.assignees??[]).map(k=>R.getContributor(k)).map(k=>k&&{...k,name:k.name}).filter(k=>!!k),p=1,f=c.length*(1+p),g=m.length*(2+p),v=c.map(k=>yt.createElement(gr,{key:k.id,paddingRight:p},yt.createElement(Jo,{color:ce(k.name)},"\u25A0"))),I=m.map(k=>yt.createElement(gr,{key:k.id,paddingRight:p},yt.createElement(Jo,{color:qo(k.name)},"@"+k.name.at(0)))),x=s?d:o?y.accent:i===b.MOVE?y.secondary:y.primary,C=R.getCommentsByIssue(r.id),A=C.length?String(C.length).length+2+p:0,M=C.length?yt.createElement(gr,{paddingRight:p},yt.createElement(Jo,{color:y.accent},"[",C.length,"]")):null,w=f+g+A,L=Math.max(1,n-t-w-(w>0?1:0));return yt.createElement(gr,{justifyContent:"space-between"},yt.createElement(gr,null,yt.createElement(gr,{width:t},o?yt.createElement(et,{isSelected:!0}):yt.createElement(Jo,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),yt.createElement(Jo,{wrap:"truncate",color:x},GI(r.title,L))),yt.createElement(gr,null,v,I,M))};var KI=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:d})=>{let{renderedChildrenIndex:c,replay:m}=J(),p=c[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,v=Jr(g),I=`${e.title} ${VI.hex(y.secondary2).dim("("+p.length+")")}`,x=3,C=o?1:5,A=s&&i===-1,M=n-3-(o?1:0)-(A?2:0),w=Math.max(2,String(p.length).length+1),L=r-x-1,k=rn.createElement(td,{borderStyle:"round",borderColor:y.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},rn.createElement(et,{isSelected:t}),rn.createElement(zI,{bold:!0,color:g?v:t?y.accent:y.primary},I," ",e.readonly?"\u{1F512}":"")),Ie=(Ke,Mt)=>{let mt=s&&i===Mt;if(!B(Ke))return null;let $e=f?.has(Ke.id)??!1;return o?rn.createElement(Zp,{key:Ke.id,index:Mt,labelWidth:w,width:M,ticket:Ke,isSelected:mt,isFlashing:$e,mode:d}):rn.createElement(Qp,{key:Ke.id,width:M,ticket:Ke,isSelected:mt,isFlashing:$e})};return rn.createElement(td,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?y.accent:y.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},k,rn.createElement(td,null,p.length>0&&rn.createElement(Et,{selectedIndex:i,height:L,itemHeight:C},p.map(Ie)),A&&rn.createElement(et,{isSelected:!0})))},ef=rn.memo(KI);import{Box as yr,Text as pd}from"ink";import Fe,{useMemo as Zo}from"react";var tf=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},nf=(e,t,n)=>be.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 no,Text as Cn}from"ink";import tt,{useEffect as qI,useMemo as YI,useRef as XI}from"react";import{decodeTime as rf}from"ulid";var to=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"},Pi=e=>String(e).padStart(2,"0"),Li=e=>`${e.getFullYear()}-${Pi(e.getMonth()+1)}-${Pi(e.getDate())} ${Pi(e.getHours())}:${Pi(e.getMinutes())}`;var JI=e=>De(e,"attachments"),QI=e=>R.getAttachmentsByIssue(e.id).sort((t,n)=>rf(t.id)-rf(n.id)),of=e=>{for(let t of e)R.deleteNode(t.id)},ZI=(e,t,n)=>be.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),eS=(e,t)=>{let n=R.getNode(JI(e.id));if(!n||!gt(n))return[];let r=t.map((o,s)=>ZI(o,s,n.id)).map(o=>R.createNode(o)).filter(me).map(({value:o})=>o).filter(gt);return t.length>0&&h().selectedIndex<0&&_.navigate({contextNode:n,selectedIndex:0}),r},tS=e=>`${Math.max(1,Math.round(e/1024))} KB`;function sf({ticket:e,width:t,height:n}){let r=YI(()=>QI(e),[e]),o=XI([]);qI(()=>(of(o.current),o.current=eS(e,r),()=>{of(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=J(),d=Math.max(1,n-4),c=Math.max(12,t-32);return r.length===0?tt.createElement(no,{flexDirection:"column",width:t,height:n,padding:1},tt.createElement(Cn,{color:y.primary},"No attachments yet."),tt.createElement(no,{paddingTop:1},tt.createElement(Cn,{color:y.primary},"Attach images from the browser GUI"),tt.createElement(Cn,{color:y.accent}," epiq gui "),tt.createElement(Cn,{color:y.primary},"by dropping or pasting them."))):tt.createElement(no,{flexDirection:"column",width:t,height:n},tt.createElement(no,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},tt.createElement(Cn,{color:y.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),tt.createElement(Et,{height:d,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>c?m.name.slice(0,c-1)+"\u2026":m.name;return tt.createElement(no,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},tt.createElement(Cn,{color:y.accent},f?"\u276F ":" "),tt.createElement(no,{paddingLeft:1},tt.createElement(Cn,{color:y.secondary2},`#${p+1} `),tt.createElement(Cn,{color:f?y.accent:y.primary},g),tt.createElement(Cn,{color:y.secondary2}," "+tS(m.bytes)+" "+to(Ce(m.id)))))})))}import{Box as Hn,Text as Wn}from"ink";import Pe,{useEffect as dS,useMemo as bf,useRef as cS}from"react";import{decodeTime as xf}from"ulid";var lf=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,nd=e=>e.replace(lf,"");var af=e=>e==="additions"||e==="deletions",rd=e=>{let t=lf.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!af(r.side)||!af(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var df=/```\n([\s\S]*?)\n?```\s*$/,cf=e=>df.exec(e)?.[1]??null,nS=/`[^`\n]+`[^\n]*\n?$/,uf=e=>nd(e).replace(df,"").replace(nS,"").trim(),rS=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},od=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${rS(e)}`;var oS=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let d=i;for(;d.length>n;)s&&(o.push(s),s=""),o.push(d.slice(0,n)),d=d.slice(n);s?s.length+1+d.length<=n?s=`${s} ${d}`:(o.push(s),s=d):s=d}return s&&o.push(s),o},Qo=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},sS=/!\[([^\]]*)\]\([^)]*\)/g,iS=e=>e.replace(sS,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),aS=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),lS=4,pf=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(lS)),sd=e=>{let t=!1;return e.map(pf).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=rd(n);if(r)return{kind:"caption",text:od(r)};let o=iS(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:Qo(s[1]??"")}:{kind:"text",spans:Qo(o)}})},ff=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],mf=(e,t)=>{let n=[];for(let r of sd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of ff(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of oS(aS(r.spans),t))n.push({kind:r.kind,spans:Qo(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},gf=(e,t)=>{let n=rd(e),r=n?cf(e):null;if(!n||r===null)return mf(nd(e).split(`
|
|
69
|
-
`),t)
|
|
70
|
-
`).
|
|
71
|
-
`),t),{kind:"blank"}]:[],{kind:"caption",text:od(n)},...s.flatMap((c,m)=>ff(c,Math.max(1,t-d)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]};import{Box as hf,Text as hr}from"ink";import Rt from"react";var yf=({spans:e,bold:t,wrap:n})=>Rt.createElement(hr,{color:y.primary,bold:t,wrap:n},e.map((r,o)=>r.code?Rt.createElement(hr,{key:o,color:y.yellow},r.text):Rt.createElement(hr,{key:o},r.text))),id=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return Rt.createElement(hr,null," ");case"fence":return Rt.createElement(hr,{color:y.secondary2},"```");case"caption":return Rt.createElement(hr,{color:y.accent,wrap:r},e.text);case"heading":return Rt.createElement(yf,{spans:e.spans,bold:!0,wrap:r});case"text":return Rt.createElement(yf,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return Rt.createElement(hr,{backgroundColor:y.secondary,color:y.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},vf=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return Rt.createElement(hf,{flexDirection:"column"},e.map((o,s)=>Rt.createElement(hf,{key:s},Rt.createElement(id,{line:o,width:t,gutter:r}))))};var uS=4,mS=e=>De(e,"comments"),pS=e=>R.getCommentsByIssue(e.id).sort((t,n)=>xf(t.id)-xf(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,authorName:t.authorName,md:t.md})),If=e=>{for(let t of e)R.deleteNode(t.id)},fS=(e,t)=>{let n=R.getNode(mS(e.id));if(!n||!gt(n))return[];let r=t.map((o,s)=>nf(o,s,n.id)).map(R.createNode).filter(me).map(({value:o})=>o).filter(Mo);return t.length>0&&h().selectedIndex<0&&_.navigate({contextNode:n,selectedIndex:0}),r};function Sf({ticket:e,width:t,height:n}){let r=bf(()=>pS(e),[e]),o=cS([]);dS(()=>(If(o.current),o.current=fS(e,r),()=>{If(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=J(),d=Math.max(1,n-4),c=Math.max(20,t-8),m=bf(()=>r.map(f=>{let g=gf(f.md,c);return g.length>0?g:[{kind:"blank"}]}),[r,c]),p=m.map(f=>f.length+uS);return r.length===0?Pe.createElement(Hn,{flexDirection:"column",width:t,height:n,padding:1},Pe.createElement(Wn,{color:y.primary},"No comments yet."),Pe.createElement(Hn,{paddingTop:1},Pe.createElement(Wn,{color:y.primary},"Use"),Pe.createElement(Wn,{color:y.accent}," :comment "),Pe.createElement(Wn,{color:y.primary},"to add the first one."))):Pe.createElement(Hn,{flexDirection:"column",width:t,height:n},Pe.createElement(Hn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:y.secondary,borderStyle:"single",paddingBottom:1},Pe.createElement(Wn,{color:y.secondary2},"Comments (",r.length,") ")),Pe.createElement(Et,{height:d,itemHeights:p,selectedIndex:s},r.map((f,g)=>{let v=g===s;return Pe.createElement(Hn,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Pe.createElement(Hn,{flexDirection:"row",paddingBottom:1},Pe.createElement(Wn,{color:y.accent},v?"\u276F ":" "),Pe.createElement(Hn,{paddingLeft:1},Pe.createElement(Wn,{color:y.secondary2},`#${g+1} `),Pe.createElement($n,{id:f.authorId}),Pe.createElement(Wn,{color:y.secondary2}," "+to(Ce(f.id))))),Pe.createElement(Hn,{paddingLeft:3,paddingBottom:1},Pe.createElement(vf,{lines:m[g]??[],width:c})))})))}import{Box as ki,Text as gS}from"ink";import Nn from"react";var Ef=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=J(),{title:o}=t,s=t.parentNodeId?R.getNode(t.parentNodeId):void 0,i=s&&B(s)?o===ve.ASSIGNEES?s.props.assignees??[]:o===ve.TAGS?(s.props.tags??[]).filter(d=>R.getTag(d)):[]:[];return Nn.createElement(ki,{alignItems:"center",paddingTop:1},Nn.createElement(ki,{minWidth:12},Nn.createElement(et,{isSelected:n}),Nn.createElement(gS,{color:n?y.accent:y.secondary2},o,":")),Nn.createElement(ki,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((d,c)=>{let m=r.id===t.id&&c===e;return Nn.createElement(ki,{key:`${o}-${d}`,paddingRight:2,minHeight:1},Nn.createElement(et,{isSelected:m}),o===ve.ASSIGNEES?Nn.createElement($n,{isSelected:m,id:d}):o===ve.TAGS?Nn.createElement(Xr,{isSelected:m,id:d}):null)})))};import{Box as ro,Text as dd}from"ink";import Ct,{useEffect as hS,useMemo as cd}from"react";var ad=e=>Math.max(5,String(Math.max(e,1)).length+3),Rf=(e,t)=>Math.max(0,e-6-ad(t));var ld=(e,t=0)=>Math.max(1,e-5-2*t);var yS="\u2029",Cf=(e,t)=>`${e}::inline-line::${t}`,ud=new Map,Nf=e=>{let t=ud.get(e)??[];ud.delete(e);for(let n of t)R.deleteNode(n)},vS=(e,t)=>{Nf(e);let n=[];t.forEach((r,o)=>{let s=xt(BigInt(o+1));if(!me(s))return;let i=R.createNode(be.text({id:Cf(e,o),name:`Line ${o+1}`,parentNodeId:e,rank:s.value,props:{value:r},readonly:!0,isVirtual:!0}));me(i)&&n.push(i.value.id)}),ud.set(e,n)},md=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:d}=J(),c=cd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=cd(()=>c.join("\0"),[c]);hS(()=>(vS(e,c),()=>{Nf(e)}),[e,m]);let p=ad(c.length),f=Rf(s,c.length),v=cd(()=>sd(c).map(I=>{if(I.kind==="code"||I.kind==="caption")return{...I,text:il(I.text,f)};if(I.kind==="text"||I.kind==="heading"){let x=I.spans.map(C=>C.code?`\`${C.text}\``:C.text).join("");return{...I,spans:Qo(il(x,f))}}return I}),[c,f]).map((I,x)=>{let C=d.id===e&&i===x;return Ct.createElement(ro,{key:Cf(e,x)},Ct.createElement(ro,{flexShrink:0},Ct.createElement(dd,{color:C?y.primary:y.secondary2,dimColor:!C},`${x+1} `.padStart(p,"\xA0"))),I.kind==="blank"?Ct.createElement(dd,{backgroundColor:C?"gray":void 0},yS):Ct.createElement(ro,null,Ct.createElement(id,{line:I,width:I.kind==="code"?f:0,wrap:"truncate-end"})))});return Ct.createElement(ro,{flexDirection:"column",paddingTop:1},Ct.createElement(ro,null,Ct.createElement(et,{isSelected:o}),Ct.createElement(dd,{color:o?y.accent:y.secondary2},t)),Ct.createElement(ro,{flexDirection:"row",borderStyle:"round",borderColor:y.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Ct.createElement(Et,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},v)))};var bS=e=>De(e,"description"),xS=e=>De(e,"comments"),IS=e=>De(e,"history"),SS=e=>De(e,"attachments"),Af=({ticket:e,height:t})=>{let n=Zo(()=>tf(e),[e]),{selectedIndex:r,contextNode:o}=J(),s=process.stdout.columns||120,i=Zo(()=>bS(e.id),[e.id]),d=Zo(()=>xS(e.id),[e.id]),c=Zo(()=>IS(e.id),[e.id]),m=Zo(()=>SS(e.id),[e.id]),p=R.getAttachmentsByIssue(e.id).length,f=o.id===e.id,g=o.id===d||o.parentNodeId===d,v=o.id===c||o.parentNodeId===c,I=o.id===m||o.parentNodeId===m,x=X(e.id);if(g){let L=t-3;return Fe.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(Sf,{ticket:e,width:s,height:L}))}if(I){let L=t-3;return Fe.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Fe.createElement(sf,{ticket:e,width:s,height:L}))}if(v){let w=R.getNode(c),L=w&>(w)?w.props.value??"":"",k=ld(t);return Fe.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},w?Fe.createElement(md,{id:w.id,label:"Event log",text:L,selected:!1,maxWidth:s,rows:k}):null)}let C=x.reduce((w,L)=>wo(L)||L.id===d||L.id===m||L.id===c?w+1:w,0),A=ld(t,C),M=(w,L)=>w.id===i?Fe.createElement(md,{key:w.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:L,maxWidth:s,rows:A}):wo(w)?Fe.createElement(Ef,{key:w.id,parent:w,selected:L,selectedIndex:r}):w.id===d?Fe.createElement(yr,{key:w.id,paddingTop:1},Fe.createElement(et,{isSelected:L}),Fe.createElement(pd,{backgroundColor:y.secondary,color:L?y.accent:y.primary},` Comments (${n}) \u203A\u203A `)):w.id===m?Fe.createElement(yr,{key:w.id,paddingTop:1},Fe.createElement(et,{isSelected:L}),Fe.createElement(pd,{backgroundColor:y.secondary,color:L?y.accent:y.primary},` Attachments (${p}) \u203A\u203A `)):w.id===c?Fe.createElement(yr,{key:w.id,paddingTop:1},Fe.createElement(et,{isSelected:L}),Fe.createElement(pd,{backgroundColor:y.secondary,color:L?y.accent:y.primary}," History \u203A\u203A ")):null;return Fe.createElement(yr,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},x.map((w,L)=>M(w,f&&r===L)))};var RS=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:d})=>{let c=t.context,m=c===K.TICKET||c===K.FIELD_LIST||c===K.FIELD,p=c===K.BOARD||c===K.SWIMLANE,f=c===K.TICKET?t:r.find(C=>C.context===K.TICKET),g=Math.floor(d/3),v=Math.floor(d/Math.max(e.length,1)),I=Math.min(v,g),x=s==="dense";return Di.createElement(ES,{flexDirection:"row",height:i},p&&e.map((C,A)=>{let M=t.id===C.id,w=M?n:-1,L=t.context===K.BOARD&&n===A;return Di.createElement(ef,{key:C.id,height:i,width:I,swimlane:C,isSelected:L,isDense:x,isFocused:M,listSelectedIndex:w,mode:o})}),m&&f&&Di.createElement(Af,{height:i,ticket:f}))},Bi=Di.memo(RS);import{render as AS}from"ink";import{Writable as TS}from"node:stream";var es=e=>String(e).padStart(2,"0"),wS=e=>{let t=e.getUTCFullYear(),n=es(e.getUTCMonth()+1),r=es(e.getUTCDate()),o=es(e.getUTCHours()),s=es(e.getUTCMinutes()),i=es(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},MS=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",PS=async(e,{width:t,height:n})=>{let r="",o=new TS({write(i,d,c){let m=LS(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),c()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=AS(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},LS=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),wf=async()=>{let{viewMode:e}=le(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=h(),i=r.find(A=>A.context==="BOARD");if(!i)return l("No board found to export");let d=120,c=40,m=await PS(NS.createElement(Bi,{height:c,width:d,swimlanes:(s[i.id]??[]).filter(A=>A!==void 0&&Kt(A)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:d,height:c});if(!m)return l("Failed to render board export");let p=Ls(process.cwd());if(a(p))return l("Unable to export, epiq root not found");let f=new Date,g=wS(f),v=`board_${MS(i.title)}_${g}.md`,I=cu(p.value);Tf.mkdirSync(I,{recursive:!0});let x=CS.join(I,v),C=`# Board - ${i.title}
|
|
42
|
+
`,"utf8"),r.push(`${o} (${m.length})`)}catch{continue}}return r},VS=(e,t)=>{let n=new Set(Mo(t));return Mo(e).filter(r=>!n.has(r))},zS=(e,t,n)=>[`Refusing to commit ${e}: it is missing ${t.length} of the ${n} event(s) already committed.`,"","The event log is append-only, so a line can never legitimately go","missing. The working copy on disk is damaged; committing it would","publish that damage to everyone who pulls, and the log carries no way","to undo it.","","Nothing has been committed. The committed history is intact \u2014 recover","the file from it before syncing again:",` git show HEAD:${e}`,"","First dropped event:",` ${t[0]?.slice(0,200)??"<none>"}`].join(`
|
|
43
|
+
`),Dg=async({stateBranchRoot:e,relativePath:t,workingContent:n})=>{let r=await De({args:["show",`HEAD:${t}`],cwd:e});if(r.exitCode!==0)return u("No committed log to compare against",void 0);let o=VS(r.stdout,n);return o.length>0?c(zS(t,o,Mo(r.stdout).length)):u("Event log only grew",void 0)};var KS="[epiq:init-repo]",Og=async e=>{let t=await De({args:["rev-parse","--verify","--quiet","HEAD"],cwd:e});if(t.exitCode===0)return u("Initial commit already exists",!1);if(!(t.exitCode===1&&t.stdout.trim()===""&&t.stderr.trim()===""))return c(["Could not determine whether the repository has any commits, so nothing was written.",`git rev-parse exited ${t.exitCode}`,t.stderr.trim()].filter(Boolean).join(`
|
|
44
|
+
`));se.info("Creating initial commit");let r=await j({args:["hash-object","-w","-t","tree","/dev/null"],cwd:e});if(a(r))return c(r.message);let o=await j({args:["commit-tree",r.value.stdout.trim(),"-m",KS],cwd:e});if(a(o))return c(o.message);let s=await j({args:["update-ref","HEAD",o.value.stdout.trim()],cwd:e});return a(s)?c(s.message):u("Created initial commit",!0)},Bg=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/^[-/.]+|[-/.]+$/g,"")||"unknown",qS=async e=>{let t=await Ui(e);if(a(t))return c(t.message);let n=await Am(e);return a(n)?c(n.message):u("Built sync commit message",`[sync|branch:${Bg(t.value)}:sha:${Bg(n.value)}]`)},dd=async({repoRoot:e,stateBranchName:t})=>{se.info(`Creating ${t}`);let n=await j({args:["commit-tree",Fm,"-m","[epiq:init-state-branch]"],cwd:e});if(a(n))return c(`Failed to create state branch commit
|
|
45
|
+
${n.message}`);let r=n.value.stdout.trim(),o=await j({args:["update-ref",`refs/heads/${t}`,r],cwd:e});return a(o)?c(`Failed to create ${t}
|
|
46
|
+
${o.message}`):u("Created state branch",!0)},Us=async({repoRoot:e,stateBranchName:t})=>{let n=await $i({repoRoot:e,branch:t});if(a(n))return c(`Ensure local state branch failed
|
|
47
|
+
`+n.message);if(n.value)return u("Local state branch already exists",!1);let r=await Bn({repoRoot:e});if(a(r))return c(`Ensure local state branch failed
|
|
48
|
+
`+r.message);let o=r.value,s=o?await is({repoRoot:e,branch:t}):u("No remote, no remote state branch",!1);if(a(s))return c(`Ensure local state branch failed
|
|
49
|
+
`+s.message);let i=s.value;if(o&&i){let l=await Ae.fetch({cwd:e,remote:wt,branch:t});if(a(l))return c(`Failed to fetch ${t} from remote
|
|
50
|
+
${l.message}`)}if(i){let l=await j({args:["branch","--track",t,`${wt}/${t}`],cwd:e});return a(l)?c(`Failed to create local ${t} from remote
|
|
51
|
+
${l.message}`):u("Created local state branch from remote",!0)}return dd({repoRoot:e,stateBranchName:t})},YS=async({repoRoot:e,branch:t})=>{let n=await j({args:["worktree","list","--porcelain"],cwd:e});if(a(n))return c(n.message);let r=n.value.stdout.split(`
|
|
52
|
+
`),o=null;for(let s of r){if(s.startsWith("worktree ")){o=s.slice(9);continue}if(s===`branch refs/heads/${t}`&&o)return u("Found worktree for branch",o)}return u("No worktree found for branch",null)},XS=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=cs(Gn.dirname(t));if(a(r))return c(`Failed to create state branch worktree
|
|
53
|
+
`+r.message);if(Wn.existsSync(t)&&!Wn.existsSync(Gn.join(t,".git"))){let s=Mg(t);if(a(s))return c(s.message);if(s.value.length>0)return c([`Refusing to delete ${t}.`,"","It is not a usable worktree \u2014 it has no .git \u2014 but it still holds",`${s.value.length} event log(s) with content:`,...s.value.map(i=>` ${i}`),"","Deleting it would destroy them, and with no .git here there is no","committed copy to recover from. Move the directory aside and","salvage the logs before letting epiq recreate the worktree."].join(`
|
|
54
|
+
`));se.info("Removing broken state branch worktree path"),jm(t)}se.info("Creating state branch worktree");let o=await Ae.worktreeAdd({cwd:e,worktreeRoot:t,branch:n});return a(o)?c(`Failed to create state branch worktree
|
|
55
|
+
${o.message}`):u("Created state branch worktree",!0)},dr=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await QS({repoRoot:e,stateBranchRoot:t,stateBranchName:n});if(a(r))return r;let o=wg({repoRoot:e,stateBranchRoot:t,stateBranch:n});return a(o)?c(o.message):(o.value==="stamped"&&se.info("Stamped the state branch with this project\u2019s identity"),r)},JS=(e,t)=>{let n=po(Pr());return Gn.dirname(e)===n&&Gn.dirname(t)===n},QS=async({repoRoot:e,stateBranchRoot:t,stateBranchName:n})=>{let r=await YS({repoRoot:e,branch:n});if(a(r))return c(r.message);let o=po(t),s=r.value?po(r.value):null;if(s&&s===o&&Wn.existsSync(s))return u("State branch already checked out in expected worktree",!1);if(s&&s!==o&&JS(s,o))return c([`The state branch ${n} is checked out under project ${Gn.basename(s)}, but this checkout names project ${Gn.basename(o)}.`,"","Two ids for one branch means a checkout minted a second identity for","a board that already existed. Nothing on the board is lost by it, but",`every checkout has to agree on one: compare ${ut} here`,`with \`git show ${n}:${ut}\`, and keep the branch's.`].join(`
|
|
56
|
+
`));if(s&&s!==o){let d=await Lm(s);if(a(d))return c(d.message);if(d.value||Df(s))return c([`Refusing to move the state branch worktree away from ${s}.`,"","It holds changes that are not committed yet, which for this","branch means events no sync has published. Removing it would","destroy them outright \u2014 there is no stash or reflog to recover","a deleted worktree from.","",`This worktree is expected at ${o}, so something else is`,"using a different EPIQ_GLOBAL_DIR against the same repository.","Sync from that location first, or point both at the same one."].join(`
|
|
57
|
+
`));se.info("Moving state branch worktree to expected location");let m=await Ae.worktreeRemove({cwd:e,worktreeRoot:s});if(a(m))return c(`Failed to remove existing state branch worktree
|
|
58
|
+
${m.message}`)}if(s&&!Wn.existsSync(s)){se.info("Pruning stale state branch worktree");let d=await Ae.worktreePrune({cwd:e});if(a(d))return c(`Failed to prune stale worktrees
|
|
59
|
+
${d.message}`)}let i=await Nm({repoRoot:e,worktreeRoot:t});if(a(i))return c(i.message);let l=Wn.existsSync(t);if(i.value&&l)return u("State branch worktree already exists",!1);if(i.value&&!l){se.info("Pruning missing registered state branch worktree");let d=await Ae.worktreePrune({cwd:e});if(a(d))return c(`Failed to prune stale worktrees
|
|
60
|
+
${d.message}`)}return XS({repoRoot:e,stateBranchRoot:t,stateBranchName:n})},ZS=async({stateBranchRoot:e,stateBranchName:t})=>{let n=await Ui(e);if(a(n))return c(n.message);if(n.value===t)return u("State branch already checked out",!1);(await De({cwd:e,args:["rebase","--abort"]})).exitCode===0&&se.info("Aborted stale state branch rebase");let o=await Ae.checkout({cwd:e,branch:t});return a(o)?c(`Failed to checkout ${t}
|
|
61
|
+
${o.message}`):u("Checked out state branch",!0)},eR=async({repoRoot:e,stateBranchRoot:t})=>{let n=await lc(t);if(a(n))return c(n.message);if(n.value)return u("State branch upstream already configured",!1);let r=await Bn({repoRoot:t});if(a(r))return c(r.message);if(!r.value)return u("No remote available for state branch upstream",!1);let o=Ue(e);if(a(o))return o;let s=o.value,i=await is({repoRoot:t,branch:s});if(a(i))return c(i.message);if(!i.value)return u("Remote state branch missing; upstream will be configured on first push",!1);se.info(`Configuring ${s} upstream`);let l=await Ae.fetch({cwd:t,remote:wt,branch:s});if(a(l))return c(`Failed to fetch ${s}
|
|
62
|
+
${l.message}`);let d=await Ae.setUpstream({cwd:t,branch:s,upstream:`${wt}/${s}`});return a(d)?c(`Failed to set state branch upstream
|
|
63
|
+
${d.message}`):u("Configured state branch upstream",!0)},Aa=async({stateBranchRoot:e,eventFileName:t})=>{let n=_m(t),r=Gn.join(e,n);if(!Wn.existsSync(r))return u("No event file to stage",null);let o=await Dg({stateBranchRoot:e,relativePath:n,workingContent:Wn.readFileSync(r,"utf8")});if(a(o))return c(o.message);let s=await Ae.stage({cwd:e,pathspec:[n]});return a(s)?c(`Failed to stage state branch event file
|
|
64
|
+
${s.message}`):u("Staged state branch event file",n)},Fg=async({stateBranchRoot:e})=>{let t=$m(),n=Gn.join(e,t);if(!Wn.existsSync(n))return u("No media directory to stage",null);let r=await Ae.stage({cwd:e,pathspec:[t],ignoreRemoval:!0});return a(r)?c(`Failed to stage state branch media files
|
|
65
|
+
${r.message}`):u("Staged state branch media files",t)},_g=async({stateBranchRoot:e})=>{let t=[dc(),uc(),ut].filter(r=>Wn.existsSync(Gn.join(e,r)));if(t.length===0)return u("No event log config to stage",[]);let n=await Ae.stage({cwd:e,pathspec:t});return a(n)?c(`Failed to stage event log config
|
|
66
|
+
${n.message}`):u("Staged event log config",t)},$g=async({repoRoot:e,stateBranchRoot:t,pathspec:n})=>{let r=await qS(e);return a(r)?c(`Create state branch sync commit failed
|
|
67
|
+
`+r.message):fo({cwd:t,message:r.value,pathspec:n})},js=async({repoRoot:e,stateBranchRoot:t})=>{let n=await lc(t);if(a(n))return c(n.message);let r=Ue(e);if(a(r))return r;let o=r.value,s=n.value?await Ae.push({cwd:t}):await Ae.push({cwd:t,remote:wt,branch:o,setUpstream:!0});if(a(s))return c(`Failed during state branch push
|
|
68
|
+
${s.message}`);let i=!`${s.value.stdout}${s.value.stderr}`.includes("Everything up-to-date");return u(i?"Pushed state branch":"Remote already up to date",i)},Ug=async({repoRoot:e,stateBranchRoot:t,ensureUpstream:n})=>{let r=!1,o=Ue(e);if(a(o))return o;let s=o.value,i=[ds(),await Us({repoRoot:e,stateBranchName:s}),await dr({repoRoot:e,stateBranchRoot:t,stateBranchName:s}),await ZS({stateBranchRoot:t,stateBranchName:s}),await Wm(t),n?await eR({stateBranchRoot:t,repoRoot:e}):u("Skipped state branch upstream bootstrap",!1)];for(let l of i){if(a(l))return c(l.message);r=r||!!l.value}return u(n?"Bootstrapped state storage":"Bootstrapped state storage readonly",r)};import Po from"node:fs";import md from"node:os";import tR from"node:path";var pd="epiq-sync.lock",jg=600*1e3,nR=e=>{try{let t=JSON.parse(e);return typeof t.pid!="number"||typeof t.hostname!="string"||typeof t.startedAt!="number"||typeof t.operation!="string"?null:t}catch{return null}},rR=e=>{try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}},oR=e=>e?e.hostname!==md.hostname()||rR(e.pid)?Date.now()-e.startedAt>jg?"stale":null:"dead":"stale",Wg=e=>`${e.operation} (pid ${e.pid} on ${e.hostname}, started ${new Date(e.startedAt).toISOString()})`,ud=e=>{try{return nR(Po.readFileSync(e,"utf8"))}catch{return null}},Hg=(e,t)=>{let n={pid:process.pid,hostname:md.hostname(),startedAt:Date.now(),operation:t},r=`${e}.${process.pid}.pending.lock`;try{return Po.writeFileSync(r,JSON.stringify(n)),Po.linkSync(r,e),!0}catch{return!1}finally{try{Po.rmSync(r,{force:!0})}catch{}}},sR=async({worktreeRoot:e,operation:t})=>{let n=await _i(e);if(a(n))return c(n.message);let r=tR.join(n.value,pd),o=()=>{try{let d=ud(r);d&&d.pid===process.pid&&Po.rmSync(r)}catch{}};if(Hg(r,t))return u("Acquired sync lock",{acquired:!0,claim:"clean",release:o});let s=ud(r),i=oR(s);if(i===null)return u("Sync lock is held",{acquired:!1,heldBy:s});se.info(`Breaking an abandoned sync lock: ${s?Wg(s):"unreadable lock file"}`);try{Po.rmSync(r,{force:!0})}catch{}if(Hg(r,t))return u("Acquired sync lock after breaking a stale one",{acquired:!0,claim:i,release:o});let l=ud(r);return u("Sync lock taken by another process",{acquired:!1,heldBy:l??{pid:-1,hostname:md.hostname(),startedAt:Date.now(),operation:"unknown"}})},Hs=async({worktreeRoot:e,operation:t,fn:n})=>{let r=await sR({worktreeRoot:e,operation:t});if(a(r))return c(r.message);if(!r.value.acquired)return se.info(`Skipping ${t}: the state worktree is held by ${Wg(r.value.heldBy)}`),u("State worktree is held by another process",null);let{claim:o,release:s}=r.value;try{return u("Ran under the sync lock",await n(o))}finally{s()}};var iR=async({claim:e,cwd:t,ensureUpstream:n})=>{logger.debug("[sync] ensureSyncReady:start",{cwd:t,ensureUpstream:n});let r=ge("getRepoRootDir",await qt(t));if(a(r))return c(r.message);let o=r.value;logger.debug("[sync] repo root",o);let s=ge("getStateBranchRoot",he({repoRoot:o}));if(a(s))return c(s.message);let i=s.value;if(logger.debug("[sync] state branch root",i),e!=="stale"&&Vg.existsSync(i)){let p=await Mm(i,{preserve:[pd]});if(a(p))return c(p.message);p.value.length>0&&logger.info("[sync] cleared git lock files left by a dead process",{removed:p.value,stateBranchRoot:i});let f=ge("abortRebaseIfPresent(stateBranchRoot)",await cc(i));if(a(f))return c(f.message)}logger.debug("[sync] bootstrapping state branch storage",{repoRoot:o,stateBranchRoot:i,ensureUpstream:n});let l=ge("bootstrapStateBranchStorage",await Ug({repoRoot:o,stateBranchRoot:i,ensureUpstream:n}));if(a(l))return c(l.message);logger.debug("[sync] bootstrap result",{bootstrapped:l.value,stateBranchRoot:i}),logger.debug("[sync] checking state branch git operation",{stateBranchRoot:i});let d=ge("getInProgressGitOperation(stateBranchRoot)",await ac(i));if(a(d))return c(d.message);if(logger.debug("[sync] state branch git operation check result",{inProgress:d.value}),d.value!==null)return logger.info("[sync] state branch git operation in progress",{claim:e}),c(`Cannot sync while there is a ${d.value} in the state branch at ${i}`);logger.debug("[sync] ensuring state branch layout",{repoRoot:o,stateBranchRoot:i});let m=ge("ensureStateBranchLayout",Hm(o,i));return a(m)?c(m.message):(logger.debug("[sync] state branch layout ready"),logger.debug("[sync] ensureSyncReady:done",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}),u("Sync preconditions satisfied",{repoRoot:o,stateBranchRoot:i,bootstrapped:l.value}))},aR=async({repoRoot:e,stateBranchRoot:t,ownEventFileName:n})=>{logger.debug("[sync] committing own event file from state branch",{ownEventFileName:n,stateBranchRoot:t}),logger.debug("[sync] staging own event file",{stateBranchRoot:t,ownEventFileName:n});let r=[];for(let m of Kf(Et(t),n)){let p=ge("stageStateBranchOwnEventFile",await Aa({stateBranchRoot:t,eventFileName:m}));if(a(p))return c(p.message);r.push(p.value)}let o=ge("stageStateBranchMediaFiles",await Fg({stateBranchRoot:t}));if(a(o))return c(o.message);let s=ge("stageStateBranchEventConfig",await _g({stateBranchRoot:t}));if(a(s))return c(s.message);let i=[...r,o.value,...s.value].filter(m=>m!==null);if(i.length===0)return u("Nothing to stage",{createdCommit:!1});let l=ge("hasStagedChanges(after stage)",await km(t,i));if(a(l))return c(l.message);if(logger.debug("[sync] state branch change check after stage result",{changed:l.value}),!l.value)return logger.info("[sync] no own event file changes to commit"),u("No own event file changes to commit",{createdCommit:!1});logger.debug("[sync] creating sync commit");let d=ge("createStateBranchSyncCommit",await $g({repoRoot:e,stateBranchRoot:t,pathspec:i}));return a(d)?c(d.message):(logger.debug("[sync] created sync commit",d.value),u("Committed own event file",{createdCommit:!0,commitSha:d.value}))},fd=(e,t="offline")=>{let n=e.createdCommit?`Committed locally, ${t}`:t==="offline"?"Offline":"No remote";return Ca(n),u(n,{...e,pulled:!1,pushed:!1,offline:!0})},Gg=async({cwd:e=process.cwd(),ownEventFileName:t},n)=>{if(logger.debug("[sync] syncEpiqWithRemote:start",{cwd:e,ownEventFileName:t}),t.includes("/")||t.includes("\\"))return logger.error("[sync] invalid own event file name: contains path separator",{ownEventFileName:t}),c("Own event file must be a file name, not a path");if(!t.endsWith(".jsonl"))return logger.error("[sync] invalid own event file name: missing .jsonl suffix",{ownEventFileName:t}),c("Own event file must end with .jsonl");To();let r=ge("ensureSyncReady",await iR({claim:n,cwd:e,ensureUpstream:!0}));if(a(r))return Ve(r.message);let{repoRoot:o,stateBranchRoot:s,bootstrapped:i}=r.value,l=ge("isDetachedHead(stateBranchRoot)",await Dm(s));if(a(l))return Ve(l.message);if(logger.debug("[sync] detached state branch check result",{detached:l.value}),l.value)return Ve("Cannot run :sync while the state branch is in detached HEAD state");let d=!1,m,p=!1,f=!1,g=ge("getStateBranch",Ue(o));if(a(g))return Ve(g.message);let y=g.value;logger.debug("[sync] resolved state branch",{stateBranch:y,stateBranchRoot:s});let x=ge("flushPendingLogs",ua(s,t));a(x)&&logger.error(`[sync] ${x.message}`);let b=ge("commitOwnEventFileToStateBranch",await aR({repoRoot:o,stateBranchRoot:s,ownEventFileName:t}));if(a(b))return Ve(b.message);d=b.value.createdCommit,m=b.value.commitSha;let R=ge("hasRemote",await Bn({repoRoot:s}));if(a(R))return Ve(R.message);if(!R.value)return fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i},"no remote");let S=ge("pullBranchRebaseIfPresent",await ls({cwd:s,branch:y}));if(a(S))return as(S.message)?fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i}):Ve(S.message);p=S.value;let T=ge("isAheadOfUpstream",await Pm(s));if(a(T))return Ve(T.message);if(d||i||T.value){logger.info("[sync] pushing state branch",{createdCommit:d,bootstrapped:i,stateBranchRoot:s});let A=ge("pushStateBranch",await js({stateBranchRoot:s,repoRoot:o}));if(a(A)&&Tm(A.message)){let P=ge("pullBranchRebaseIfPresent(retry)",await ls({cwd:s,branch:y}));if(a(P))return Ve(P.message);p=p||P.value,A=ge("pushStateBranch(retry)",await js({stateBranchRoot:s,repoRoot:o}))}if(a(A))return as(A.message)?fd({repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,bootstrapped:i}):Ve(A.message);f=A.value}if(d){logger.debug("[sync] resolving final sync commit sha",{stateBranchRoot:s});let A=ge("git rev-parse HEAD",await j({args:["rev-parse","HEAD"],cwd:s}));if(a(A))return Ve(A.message);m=A.value.stdout.trim(),logger.debug("[sync] final sync commit sha",m)}return jr(f?"Synced and pushed":p||d?"Synced local state":"Already synced"),logger.debug("[sync] syncEpiqWithRemote:done"),u("Synced event logs with state branch",{repoRoot:o,stateBranchRoot:s,createdCommit:d,commitSha:m,pulled:p,pushed:f,bootstrapped:i,offline:!1})},Ta=async(e,t)=>{let n=Lg(e);try{return await t()}finally{let r=kg(e,n);r.length>0&&logger.error(`[sync] restored event log lines git dropped from the worktree: ${r.join(", ")}`)}},wa=async e=>{let t=e.cwd??process.cwd(),n=await qt(t);if(a(n))return Ve(n.message);let r=he({repoRoot:n.value});if(a(r))return Ve(r.message);let o=r.value;if(!Vg.existsSync(o))return Gg(e,"clean");let s=await Hs({worktreeRoot:o,operation:"sync",fn:i=>Ta(o,()=>Gg(e,i))});return a(s)?Ve(s.message):s.value===null?u("Another process is syncing this board",{repoRoot:n.value,stateBranchRoot:o,createdCommit:!1,pulled:!1,pushed:!1,bootstrapped:!1,offline:!1,skipped:!0}):s.value};var Nn=null,Ma=async()=>{if(logger.debug("[sync] syncAndReloadState enter",{hasPromise:!!Nn,currentStatus:v().syncStatus?.status,currentMessage:v().syncStatus?.msg}),Nn)return logger.debug("[sync] syncAndReloadState joining existing promise"),Nn;logger.debug("[sync] syncAndReloadState creating promise"),Nn=lR();try{let e=await Nn;return logger.debug("[sync] syncAndReloadState promise resolved",{success:!a(e),message:(a(e),e.message),statusAfterResolve:v().syncStatus?.status,statusMessageAfterResolve:v().syncStatus?.msg}),a(e)&&v().syncStatus?.status==="syncing"&&(logger.debug("[sync] syncAndReloadState correcting stale syncing status"),w({syncStatus:{msg:e.message,status:"failed"}})),e}catch(e){let t=e instanceof Error?e.message:String(e);return logger.error("[sync] syncAndReloadState promise threw",{message:t,error:e}),Nn||c(t)}finally{logger.debug("[sync] syncAndReloadState clearing promise",{statusBeforeClear:v().syncStatus?.status,statusMessageBeforeClear:v().syncStatus?.msg}),Nn=null}},lR=async()=>{logger.debug("[sync] syncAndReloadStateUnsafe:start",{mode:v().mode,syncStatus:v().syncStatus});let e=zg();if(e)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by mode",{mode:v().mode,message:e.message,syncStatus:v().syncStatus}),e;if(Nn)return Nn;logger.debug("[sync] syncAndReloadState:start");let t=ge("resolveActorId",pe());if(a(t)||!t.value)return logger.info("[sync] unable to resolve actor id",{message:a(t)?t.message:"Missing actor id"}),c("Unable to resolve event log path");w({syncStatus:{msg:"Reloading synced state",status:"syncing"}}),logger.debug("[sync] sync status patched to syncing",{syncStatus:v().syncStatus});let n=ir(t.value);logger.debug("[sync] resolved own event file name",{ownEventFileName:n}),logger.debug("[sync] syncEpiqWithRemote:start");let r=ge("syncEpiqWithRemote",await wa({ownEventFileName:n}));if(logger.debug("[sync] syncEpiqWithRemote:result",{success:!a(r),message:(a(r),r.message)}),a(r))return logger.error("[sync] syncAndReloadState:sync failed",r.message),w({syncStatus:{msg:"Sync failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after sync failure",{syncStatus:v().syncStatus}),Ve(`Unable to sync state. ${r.message}`);let{stateBranchRoot:o,offline:s}=r.value,i=gd(o);return a(i)?i:(w({hasProjectDefinition:!0,syncStatus:s?{msg:"Committed locally, offline",status:"offline"}:{msg:"Synced",status:"synced"}}),logger.debug("[sync] syncAndReloadState:done",{syncStatus:v().syncStatus}),u("Synced",!0))},gd=e=>{logger.debug("[sync] loading merged events after sync",{stateBranchRoot:e});let t=ge("loadMergedEvents",Zt(e));if(logger.debug("[sync] loadMergedEvents:result",{success:!a(t),message:(a(t),t.message),count:a(t)?void 0:t.value.events.length}),a(t))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after load failure",{syncStatus:v().syncStatus}),c(`Unable to load events. ${t.message}`);logger.debug("[sync] loaded merged events after sync",{count:t.value.events.length});let n=zg();if(n)return logger.debug("[sync] syncAndReloadStateUnsafe:blocked by late mode check",{mode:v().mode,message:n.message,syncStatus:v().syncStatus}),n;let r=Eg(),o=v().filters;if(logger.debug("[sync] captured navigation anchor",{navigationAnchor:r,selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id,selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual}),!v().selectedNode?.isVirtual&&!v().contextNode?.isVirtual){logger.debug("[sync] bootStateFromEventLog:start",{eventCount:t.value.events.length});let i=ge("bootStateFromEventLog",en(t.value.events,t.value.unreadable));if(logger.debug("[sync] bootStateFromEventLog:result",{success:!a(i),message:(a(i),i.message)}),a(i))return w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after boot failure",{syncStatus:v().syncStatus}),c(`Unable to boot synced state. ${i.message}`)}else logger.debug("[sync] skipped bootStateFromEventLog for virtual node",{selectedNodeIsVirtual:v().selectedNode?.isVirtual,contextNodeIsVirtual:v().contextNode?.isVirtual});logger.debug("[sync] booted state from synced events"),w({filters:o}),logger.debug("[sync] restoreNavigationAnchor:start");let s=ge("restoreNavigationAnchor",Rg(r));return logger.debug("[sync] restoreNavigationAnchor:result",{success:!a(s),message:a(s)?s.message:"Navigation restored",selectedNodeId:v().selectedNode?.id,contextNodeId:v().contextNode?.id}),a(s)?(w({syncStatus:{msg:"Reload failed",status:"failed"}}),logger.debug("[sync] sync status patched to failed after restore failure",{syncStatus:v().syncStatus}),s):u("Reloaded state from event log",null)},zg=()=>v().mode===I.DEFAULT?null:(logger.debug("[sync] failReloadIfNotDefaultMode",{mode:v().mode,syncStatus:v().syncStatus}),w({syncStatus:{msg:"Reload skipped while editing",status:"pending"}}),c("Will not re-materialize if not in default mode, to not lose edit data"));var Kg=0,hd,yd=!1,Ws=!1,vd=()=>{if(yd)return!0;let e=xe();return a(e)?!1:e.value.syncStatus.status==="syncing"},cR=()=>{let e=uo(V().autoSyncIntervalMs),t=Date.now()-Kg;return Math.max(0,e-t)},qg=()=>{hd||(hd=setTimeout(async()=>{if(hd=void 0,!!_t()){if(vd()){Ws=!0;return}Ws=!1,await dR()}},cR()))},dR=async()=>{if(v().readOnly||v().timeMode==="peek"||v().timeMode==="replay")return c("Cannot auto-sync while peeking");if(!_t())return c("Cannot auto-sync before state is initialized");if(vd())return Ws=!0,c("Sync already in progress");yd=!0,Kg=Date.now(),w({syncStatus:{msg:"Auto-syncing",status:"syncing"}});try{return await Ma()}finally{yd=!1,Ws&&qg()}},Pa=()=>{_t()&&(Ws=!0,!vd()&&qg())};var La=e=>{let{context:t}=v().contextNode;if(!t)return G.None;switch(e){case C.EXIT:return G.Exit;case C.EXPORT:return G.Export;case C.INIT:return G.Init;case C.OPEN:return G.OpenProject;case C.DELETE:return G.Delete;case C.EDIT:return G.Edit;case C.COMMENT:return G.Comment;case C.HELP:return G.ViewHelp;case C.RE_OPEN_ISSUE:return G.ReopenIssue;case C.CLOSE_ISSUE:return G.CloseIssue;case C.TAG:return G.TagTicket;case C.UNTAG:return G.UntagTicket;case C.ASSIGN:return G.AssignUserToTicket;case C.UNASSIGN:return G.UnassignUserFromTicket;case C.NEW:return G.NewItem;case C.FILTER:return G.Filter;case C.MOVE:return G.Move;case C.PEEK:return G.Peek;case C.REPLAY:return G.Replay;case C.CONFIG:return G.Config;case C.YANK:return G.Yank;case C.SYNC:return G.Sync;default:return G.None}},G={Exit:"exit",Init:"init",OpenProject:"open-project",None:"none",ViewHelp:"view-help",Rename:"rename",Edit:"edit",Delete:"delete",Filter:"filter",Move:"move",Peek:"peek",Replay:"replay",Yank:"yank",Config:"config",NewItem:"add-new-item",TagTicket:"ticket-tag",UntagTicket:"ticket-untag",AssignUserToTicket:"ticket-assign-user",UnassignUserFromTicket:"ticket-unassign-user",CloseIssue:"close-issue",ReopenIssue:"re-open-issue",Comment:"comment-issue",Sync:"sync",Export:"export"};import ay from"node:fs";import tN from"node:path";import nN from"react";import{Box as ZC}from"ink";import Ya from"react";import TR from"chalk";import{Box as Id,Text as wR}from"ink";import An from"react";import{Text as Yg}from"ink";import Xg,{useEffect as Jg,useState as uR}from"react";var Qg={help:["\u276F "],default:["\u276F "],move:["\u25C6 ","\u25C6 "],"cmd-line":["\u276F "],palette:["\u276F "],identity:["\u276F "]},St=({isSelected:e,placeholder:t=" "})=>{let{mode:n}=oe(),r=Qg[n]??Qg.default,[o,s]=uR(0);if(Jg(()=>{s(0)},[r]),Jg(()=>{if(!e)return;let l=setInterval(()=>{s(d=>(d+1)%r.length)},500);return()=>clearInterval(l)},[e,r]),!e)return Xg.createElement(Yg,null,t);let i=r[o]??r[0]??t;return Xg.createElement(Yg,{color:h.accent,dimColor:o===1},i)};import{Box as bd,Text as mR}from"ink";import ka from"react";var pR=(e,t,n,r)=>{let o=d=>Math.max(1,e[d]??1),s=n,i=n+1,l=o(n);for(;i<t&&l+o(i)<=r;)l+=o(i),i++;for(;s>0&&l+o(s-1)<=r;)s--,l+=o(s);return{start:s,end:i}},mt=({children:e=[],height:t,selectedIndex:n,itemHeight:r=1,itemHeights:o,scrollByOne:s=!1})=>{if(e.length===0)return null;let i=Math.max(1,Math.floor(t)),l=Math.max(1,Math.ceil(r)),d=Math.max(0,Math.min(n,e.length-1)),m=Math.max(1,Math.floor(i/l)),p=Math.max(0,e.length-m),{start:f,end:g}=o?pR(o,e.length,d,i):s?{start:Math.min(p,Math.max(0,d-m+1)),end:Math.min(p,Math.max(0,d-m+1))+m}:{start:Math.min(p,Math.floor(d/m)*m),end:Math.min(p,Math.floor(d/m)*m)+m},y=Math.max(1,g-f),x=e.slice(f,g),b=e.length>y,R=i,S=b?Math.max(1,Math.floor(y/e.length*R)):R,T=Math.max(0,R-S),A=Math.max(1,e.length-y),P=b?Math.floor(f/A*T):0;return ka.createElement(bd,{flexDirection:"row",height:i,width:"100%"},ka.createElement(bd,{flexDirection:"column",flexGrow:1,height:i},x),ka.createElement(bd,{flexDirection:"column",width:1,height:R},Array.from({length:R}).map((M,O)=>ka.createElement(mR,{key:O,color:b&&O>=P&&O<P+S?h.accent:h.secondary},b?"\u2502":" "))))};import{Box as Do,Text as Bo}from"ink";import Rt from"react";var Zg,xd,fR=()=>{let{eventLog:e=[]}=v();if(xd&&Zg===e)return xd;let t=new Set;for(let n of e)n?.userId&&t.add(n.userId);return Zg=e,xd=t,t},Da=e=>fR().has(e);import{Text as gR}from"ink";import hR from"react";var ur=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getContributor(e);if(!r)return;let o=r.name,s=n===void 0?o:Fn(o,n);return hR.createElement(gR,{underline:t,color:qe(o)},"@"+s,Da(e)?"":"\u2197")};import{Text as yR}from"ink";import vR from"react";var Lo=({id:e,isSelected:t,maxWidth:n})=>{let r=N.getTag(e);if(!r)return;let o=n===void 0?r.name:Fn(r.name,n);return vR.createElement(yR,{underline:t,backgroundColor:qe(r.name),color:h.secondary}," "+o+" ")};import{useEffect as bR,useState as xR}from"react";var IR=80,eh=1400,Ba=new Set,Gs=null,ER=e=>(Ba.add(e),Gs||(Gs=setInterval(()=>{for(let t of Ba)t()},IR)),()=>{Ba.delete(e),Ba.size===0&&Gs&&(clearInterval(Gs),Gs=null)}),SR=()=>{let e=Date.now()%eh/eh;return e<.5?e*2:(1-e)*2},ko=e=>{let[,t]=xR(0);return bR(()=>{if(e)return ER(()=>t(n=>n+1))},[e]),Gi(SR())};var RR=(e,t,n)=>{if(e.length<=t)return[e,null];let r=e.lastIndexOf(" ",t),o=r>0?r:t;return[e.slice(0,o),Fn(e.slice(o).trim(),n)]},th=3,CR=2,NR=(e,t)=>{let n=[],r=0;for(let[o,s]of e.entries()){let i=e.length-o-1,l=i>0?String(i).length+1:0;if(r+s.width+l>t)break;r+=s.width,n.push(s)}return{shown:n,hidden:e.length-n.length}},nh=({width:e,ticket:t,isSelected:n,isFlashing:r=!1})=>{let o=ko(r),s=e-4,i=s-7-1,[l,d]=RR(Re(t.title),i,s),m=d?null:Fn(Re(t.props.description),s)||null,p=hn(t),f=yn(t).map(S=>({...S,name:S.name})),g=Math.max(1,s-th),y=N.getCommentsByIssue(t.id),x=y.length?String(y.length).length+2+1:0,{shown:b,hidden:R}=NR([...p.map(S=>({id:S.id,isTag:!0,width:Math.min(S.name.length,g)+th})),...f.map(S=>({id:S.id,isTag:!1,width:Math.min(S.name.length,g)+CR+(Da(S.id)?0:1)}))],s-x);return Rt.createElement(Do,{borderStyle:"round",height:5,flexDirection:"column",overflow:"hidden",borderDimColor:!n,borderColor:r?o:n?h.accent:h.secondary,justifyContent:"space-between"},Rt.createElement(Do,{paddingLeft:1,paddingRight:1,flexDirection:"column"},Rt.createElement(Do,{justifyContent:"space-between"},Rt.createElement(Bo,{color:h.primary},l),Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},H(t.id))),d&&Rt.createElement(Bo,{color:h.primary},d),m&&Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},m)),Rt.createElement(Do,{flexDirection:"row",paddingLeft:1,paddingRight:1,justifyContent:"space-between"},Rt.createElement(Do,{flexDirection:"row"},b.map(S=>Rt.createElement(Do,{paddingRight:1,key:S.id},S.isTag?Rt.createElement(Lo,{id:S.id,maxWidth:g}):Rt.createElement(ur,{id:S.id,maxWidth:g}))),R>0&&Rt.createElement(Bo,{color:h.secondary2,dimColor:!0},"+",R)),y.length>0&&Rt.createElement(Bo,{color:h.accent},"[",y.length,"]")))};import{Box as Hr,Text as Vs}from"ink";import Lt from"react";var AR=(e,t)=>e.length>t?e.slice(0,Math.max(0,t-1))+"\u2026":e,rh=({index:e,labelWidth:t,width:n,ticket:r,isSelected:o,isFlashing:s=!1,mode:i})=>{let l=ko(s),d=(r.props.tags??[]).map(M=>N.getTag(M)).filter(M=>!!M),m=(r.props.assignees??[]).map(M=>N.getContributor(M)).map(M=>M&&{...M,name:M.name}).filter(M=>!!M),p=1,f=d.length*(1+p),g=m.length*(2+p),y=d.map(M=>Lt.createElement(Hr,{key:M.id,paddingRight:p},Lt.createElement(Vs,{color:qe(M.name)},"\u25A0"))),x=m.map(M=>Lt.createElement(Hr,{key:M.id,paddingRight:p},Lt.createElement(Vs,{color:Ec(M.name)},"@"+M.name.at(0)))),b=s?l:o?h.accent:i===I.MOVE?h.secondary:h.primary,R=N.getCommentsByIssue(r.id),S=R.length?String(R.length).length+2+p:0,T=R.length?Lt.createElement(Hr,{paddingRight:p},Lt.createElement(Vs,{color:h.accent},"[",R.length,"]")):null,A=f+g+S,P=Math.max(1,n-t-A-(A>0?1:0));return Lt.createElement(Hr,{justifyContent:"space-between"},Lt.createElement(Hr,null,Lt.createElement(Hr,{width:t},o?Lt.createElement(St,{isSelected:!0}):Lt.createElement(Vs,{color:"gray",dimColor:!0},String(e+1).padStart(t-1)+" ")),Lt.createElement(Vs,{wrap:"truncate",color:b},AR(r.title,P))),Lt.createElement(Hr,null,y,x,T))};var MR=({swimlane:e,isSelected:t,width:n,height:r,isDense:o,isFocused:s,listSelectedIndex:i,mode:l})=>{let{renderedChildrenIndex:d,replay:m}=oe(),p=d[e.id]??[],f=m?new Set(m.flashNodeIds):null,g=f?.has(e.id)??!1,y=ko(g),x=`${e.title} ${TR.hex(h.secondary2).dim("("+p.length+")")}`,b=3,R=o?1:5,S=s&&i===-1,T=n-3-(o?1:0)-(S?2:0),A=Math.max(2,String(p.length).length+1),P=r-b-1,M=An.createElement(Id,{borderStyle:"round",borderColor:h.secondary,justifyContent:"flex-start",borderLeft:!1,borderTop:!1,borderRight:!1,marginRight:o?1:0},An.createElement(St,{isSelected:t}),An.createElement(wR,{bold:!0,color:g?y:t?h.accent:h.primary},x," ",e.readonly?"\u{1F512}":"")),O=(W,X)=>{let Ee=s&&i===X;if(!_(W))return null;let F=f?.has(W.id)??!1;return o?An.createElement(rh,{key:W.id,index:X,labelWidth:A,width:T,ticket:W,isSelected:Ee,isFlashing:F,mode:l}):An.createElement(nh,{key:W.id,width:T,ticket:W,isSelected:Ee,isFlashing:F})};return An.createElement(Id,{flexDirection:"column",width:n,borderStyle:"round",borderColor:t?h.accent:h.secondary,paddingRight:0,paddingLeft:o?1:0,height:r},M,An.createElement(Id,null,p.length>0&&An.createElement(mt,{selectedIndex:i,height:P,itemHeight:R},p.map(O)),S&&An.createElement(St,{isSelected:!0})))},oh=An.memo(MR);import{Box as Wo,Text as KC}from"ink";import Ct,{useMemo as Go}from"react";var sh=e=>{let t=new Set((e.log??[]).filter(n=>n.action==="delete.issue.comment").map(n=>n.payload.id));return(e.log??[]).filter(n=>n.action==="add.issue.comment"&&n.payload.issue===e.id&&!t.has(n.payload.id)).length},ih=(e,t,n)=>Ne.comment({id:e.id,parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.id,props:{value:e.md},readonly:!1,isVirtual:!0});var ah=e=>e.action==="add.issue.comment";import{Box as Oo,Text as Vn}from"ink";import pt,{useEffect as PR,useMemo as LR,useRef as kR}from"react";import{decodeTime as lh}from"ulid";var pr=e=>{let t=Date.now()-e,n=[{label:"y",ms:1e3*60*60*24*365},{label:"mo",ms:1e3*60*60*24*30},{label:"w",ms:1e3*60*60*24*7},{label:"d",ms:1e3*60*60*24},{label:"h",ms:1e3*60*60},{label:"m",ms:1e3*60},{label:"s",ms:1e3}];for(let{label:r,ms:o}of n){let s=Math.floor(t/o);if(s>=1)return`${s}${r} ago`}return"just now"},Oa=e=>String(e).padStart(2,"0"),Fa=e=>`${e.getFullYear()}-${Oa(e.getMonth()+1)}-${Oa(e.getDate())} ${Oa(e.getHours())}:${Oa(e.getMinutes())}`;var DR=e=>Pe(e,"attachments"),BR=e=>N.getAttachmentsByIssue(e.id).sort((t,n)=>lh(t.id)-lh(n.id)),ch=e=>{for(let t of e)N.deleteNode(t.id)},OR=(e,t,n)=>Ne.field({id:e.id,name:e.name,parentNodeId:n,rank:String(t).padStart(6,"0"),isVirtual:!0}),FR=(e,t)=>{let n=N.getNode(DR(e.id));if(!n||!lt(n))return[];let r=t.map((o,s)=>OR(o,s,n.id)).map(o=>N.createNode(o)).filter(be).map(({value:o})=>o).filter(lt);return t.length>0&&v().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r},_R=e=>`${Math.max(1,Math.round(e/1024))} KB`;function dh({ticket:e,width:t,height:n}){let r=LR(()=>BR(e),[e]),o=kR([]);PR(()=>(ch(o.current),o.current=FR(e,r),()=>{ch(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=oe(),l=Math.max(1,n-4),d=Math.max(12,t-32);return r.length===0?pt.createElement(Oo,{flexDirection:"column",width:t,height:n,padding:1},pt.createElement(Vn,{color:h.primary},"No attachments yet."),pt.createElement(Oo,{paddingTop:1},pt.createElement(Vn,{color:h.primary},"Attach images from the browser GUI"),pt.createElement(Vn,{color:h.accent}," epiq gui "),pt.createElement(Vn,{color:h.primary},"by dropping or pasting them."))):pt.createElement(Oo,{flexDirection:"column",width:t,height:n},pt.createElement(Oo,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},pt.createElement(Vn,{color:h.secondary2},"Attachments (",r.length,") \u2014 enter to open"," ")),pt.createElement(mt,{height:l,itemHeight:2,selectedIndex:s},r.map((m,p)=>{let f=p===s,g=m.name.length>d?m.name.slice(0,d-1)+"\u2026":m.name;return pt.createElement(Oo,{key:m.id,flexDirection:"row",paddingX:1,paddingBottom:1},pt.createElement(Vn,{color:h.accent},f?"\u276F ":" "),pt.createElement(Oo,{paddingLeft:1},pt.createElement(Vn,{color:h.secondary2},`#${p+1} `),pt.createElement(Vn,{color:f?h.accent:h.primary},g),pt.createElement(Vn,{color:h.secondary2}," "+_R(m.bytes)+" "+pr(Be(m.id)))))})))}import{Box as fr,Text as gr}from"ink";import Je,{useEffect as KR,useMemo as Rh,useRef as qR}from"react";import{decodeTime as Ch}from"ulid";var mh=/<!--\s*epiq-diff-comment:(.+?)-->\n?/,Ed=e=>e.replace(mh,""),$R=e=>`<!-- epiq-diff-comment:${JSON.stringify(e).replaceAll(">","\\u003e")} -->`,uh=e=>e==="additions"||e==="deletions",zs=e=>{let t=mh.exec(e);if(!t?.[1])return null;let n;try{n=JSON.parse(t[1])}catch{return null}let r=n;return typeof r?.filePath!="string"||typeof r.start!="number"||typeof r.end!="number"||typeof r.note!="string"||!uh(r.side)||!uh(r.endSide)||r.sha!==void 0&&typeof r.sha!="string"||r.issueRef!==void 0&&typeof r.issueRef!="string"?null:r};var ph=/```\n([\s\S]*?)\n?```\s*$/,fh=e=>ph.exec(e)?.[1]??null,UR=/`[^`\n]+`[^\n]*\n?$/,gh=e=>Ed(e).replace(ph,"").replace(UR,"").trim(),hh=e=>{let n=(e.endSide??e.side)==="deletions"?"removed":"added";return e.start===e.end?`line ${e.start} (${n})`:`lines ${e.start}-${e.end} (${n})`},Sd=e=>`${e.issueRef?`${e.issueRef} \xB7 `:""}${e.filePath} ${hh(e)}`;var jR=e=>{let t=e.split(`
|
|
69
|
+
`),n=t.filter(r=>r.trim()!=="").reduce((r,o)=>{let s=/^[ \t]*/.exec(o)?.[0].length??0;return r===null?s:Math.min(r,s)},null);return n?t.map(r=>r.slice(n)).join(`
|
|
70
|
+
`):e},yh=({snippet:e,...t})=>{let n=t.note.trim();return[...n?[n,""]:[],$R({...t,note:n}),`\`${t.filePath}\` ${hh(t)}`,"```",jR(e),"```"].join(`
|
|
71
|
+
`)};var HR=(e,t)=>{let n=Math.max(1,Math.floor(t)),r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[""];let o=[],s="";for(let i of r){let l=i;for(;l.length>n;)s&&(o.push(s),s=""),o.push(l.slice(0,n)),l=l.slice(n);s?s.length+1+l.length<=n?s=`${s} ${l}`:(o.push(s),s=l):s=l}return s&&o.push(s),o},Ks=e=>{let t=e.split("`");return t.length%2===0?[{text:e}]:t.map((n,r)=>r%2===1?{text:n,code:!0}:{text:n}).filter(n=>n.text.length>0)},WR=/!\[([^\]]*)\]\([^)]*\)/g,GR=e=>e.replace(WR,(t,n)=>n.trim()?`[image: ${n.trim()}]`:"[image]"),VR=e=>e.map(t=>t.code?`\`${t.text}\``:t.text).join(""),zR=4,qs=e=>e.replace(/\r$/,"").replaceAll(" "," ".repeat(zR)),Rd=e=>{let t=!1;return e.map(qs).map(n=>{if(/^\s*```/.test(n))return t=!t,{kind:"fence"};if(t)return{kind:"code",text:n};let r=zs(n);if(r)return{kind:"caption",text:Sd(r)};let o=GR(n);if(o.trim()==="")return{kind:"blank"};let s=/^#{1,6}\s+(.*)$/.exec(o);return s?{kind:"heading",spans:Ks(s[1]??"")}:{kind:"text",spans:Ks(o)}})},bh=(e,t)=>e.length<=t?[e]:e.match(new RegExp(`.{1,${t}}`,"g"))??[""],vh=(e,t)=>{let n=[];for(let r of Rd(e))if(r.kind!=="fence"){if(r.kind==="blank"){n.length>0&&n[n.length-1]?.kind!=="blank"&&n.push(r);continue}if(r.kind==="code"){for(let o of bh(r.text,t))n.push({kind:"code",text:o});continue}if(r.kind==="caption"){n.push(r);continue}for(let o of HR(VR(r.spans),t))n.push({kind:r.kind,spans:Ks(o)})}for(;n.length>0&&n[n.length-1]?.kind==="blank";)n.pop();return n},xh=(e,t)=>{let n=zs(e),r=n?fh(e):null;if(!n||r===null)return vh(Ed(e).split(`
|
|
72
|
+
`),t);let o=gh(e),s=r.split(`
|
|
73
|
+
`).map(qs),i=n.side===n.endSide?n.start:void 0,l=i===void 0?0:String(i+s.length-1).length+3;return[...o?[...vh(o.split(`
|
|
74
|
+
`),t),{kind:"blank"}]:[],{kind:"caption",text:Sd(n)},...s.flatMap((d,m)=>bh(d,Math.max(1,t-l)).map((p,f)=>({kind:"code",text:p,number:i===void 0||f>0?void 0:i+m})))]};import{Box as Ih,Text as Wr}from"ink";import $t from"react";var Eh=({spans:e,bold:t,wrap:n})=>$t.createElement(Wr,{color:h.primary,bold:t,wrap:n},e.map((r,o)=>r.code?$t.createElement(Wr,{key:o,color:h.yellow},r.text):$t.createElement(Wr,{key:o},r.text))),Cd=({line:e,width:t,gutter:n=0,wrap:r})=>{switch(e.kind){case"blank":return $t.createElement(Wr,null," ");case"fence":return $t.createElement(Wr,{color:h.secondary2},"```");case"caption":return $t.createElement(Wr,{color:h.accent,wrap:r},e.text);case"heading":return $t.createElement(Eh,{spans:e.spans,bold:!0,wrap:r});case"text":return $t.createElement(Eh,{spans:e.spans,wrap:r});case"code":{let o=n>0?`${e.number===void 0?"":String(e.number)}`.padStart(n-3)+" \u2502 ":"";return $t.createElement(Wr,{backgroundColor:h.secondary,color:h.primary,wrap:r},o,e.text.padEnd(Math.max(0,t-o.length)))}}},Sh=({lines:e,width:t})=>{let n=e.flatMap(o=>o.kind==="code"&&o.number!==void 0?[o.number]:[]),r=n.length>0?String(Math.max(...n)).length+3:0;return $t.createElement(Ih,{flexDirection:"column"},e.map((o,s)=>$t.createElement(Ih,{key:s},$t.createElement(Cd,{line:o,width:t,gutter:r}))))};var YR=4,XR=e=>Pe(e,"comments"),JR=e=>N.getCommentsByIssue(e.id).sort((t,n)=>Ch(t.id)-Ch(n.id)).map(t=>({id:t.id,issue:t.issue,authorId:t.authorId,md:t.md})),Nh=e=>{for(let t of e)N.deleteNode(t.id)},QR=(e,t)=>{let n=N.getNode(XR(e.id));if(!n||!lt(n))return[];let r=t.map((o,s)=>ih(o,s,n.id)).map(N.createNode).filter(be).map(({value:o})=>o).filter(bs);return t.length>0&&v().selectedIndex<0&&U.navigate({contextNode:n,selectedIndex:0}),r};function Ah({ticket:e,width:t,height:n}){let r=Rh(()=>JR(e),[e]),o=qR([]);KR(()=>(Nh(o.current),o.current=QR(e,r),()=>{Nh(o.current),o.current=[]}),[e,r]);let{selectedIndex:s}=oe(),l=Math.max(1,n-4),d=Math.max(20,t-8),m=Rh(()=>r.map(f=>{let g=xh(f.md,d);return g.length>0?g:[{kind:"blank"}]}),[r,d]),p=m.map(f=>f.length+YR);return r.length===0?Je.createElement(fr,{flexDirection:"column",width:t,height:n,padding:1},Je.createElement(gr,{color:h.primary},"No comments yet."),Je.createElement(fr,{paddingTop:1},Je.createElement(gr,{color:h.primary},"Use"),Je.createElement(gr,{color:h.accent}," :comment "),Je.createElement(gr,{color:h.primary},"to add the first one."))):Je.createElement(fr,{flexDirection:"column",width:t,height:n},Je.createElement(fr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},Je.createElement(gr,{color:h.secondary2},"Comments (",r.length,") ")),Je.createElement(mt,{height:l,itemHeights:p,selectedIndex:s},r.map((f,g)=>{let y=g===s;return Je.createElement(fr,{key:f.id,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},Je.createElement(fr,{flexDirection:"row",paddingBottom:1},Je.createElement(gr,{color:h.accent},y?"\u276F ":" "),Je.createElement(fr,{paddingLeft:1},Je.createElement(gr,{color:h.secondary2},`#${g+1} `),Je.createElement(ur,{id:f.authorId}),Je.createElement(gr,{color:h.secondary2}," "+pr(Be(f.id))))),Je.createElement(fr,{paddingLeft:3,paddingBottom:1},Je.createElement(Sh,{lines:m[g]??[],width:d})))})))}import{Box as Vr,Text as Tn}from"ink";import Qe,{useEffect as ey,useRef as FC,useState as _C}from"react";var nn=e=>{let t=me(e??process.cwd());return a(t)?c(t.message):u("Resolved Epiq repo root",t.value)},Fo=e=>/^[0-9a-f]{7,40}$/i.test(e);var ZR="EPIQ_CACHE_MS",_a=e=>{let t=process.env[ZR];if(t===void 0||t.trim()==="")return e;let n=Number(t);return Number.isFinite(n)&&n>=0?n:e};var _o="",Th="",wh=5e3,$o=null;var eC=(e,t,n)=>(t===void 0||e>=Math.floor(t/1e3)*1e3)&&(n===void 0||e<=n),Uo=async(e={})=>{let t=nn(e.repoRoot);if(a(t))return c(t.message);let n=Tt(t.value);if(a(n))return c(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&$o&&$o.repoRoot===t.value&&$o.stateBranch===n.value.stateBranch&&Date.now()-$o.fetchedAt<_a(wh))return u("Computed commit timeline",$o.result);let o=await j({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=${Th}%H${_o}%at${_o}%an${_o}%ae${_o}%s`]});if(a(o))return c(o.message);let s=o.value.stdout.split(Th).filter(i=>i.trim().length>0).map(i=>{let[l,...d]=i.split(`
|
|
75
|
+
`),[m,p,f,g,...y]=(l??"").split(_o);if(!m||!p)return null;let x=d.join(" "),b=Number(/(\d+) insertion/.exec(x)?.[1]??0),R=Number(/(\d+) deletion/.exec(x)?.[1]??0);return{sha:m,time:Number(p)*1e3,author:f??"unknown",authorEmail:g??"",subject:y.join(_o),linesChanged:b+R,insertions:b,deletions:R}}).filter(i=>i!==null).filter(i=>eC(i.time,e.start,e.end));return r&&($o={repoRoot:t.value,stateBranch:n.value.stateBranch,fetchedAt:Date.now(),result:s}),u("Computed commit timeline",s)},zn=async e=>{let t=e.ref.trim();if(!t)return c("ref must not be empty");if(t.length!==7)return c(`"${t}" is ${t.length} characters; a ref is ${7}. Read it off the issue rather than slicing the id by hand.`);let n=await Uo({repoRoot:e.repoRoot});if(a(n))return c(n.message);let r=`${t.toUpperCase()} `,o=l=>l.subject.toUpperCase().startsWith(r),s=n.value,i=[];for(let[l,d]of s.entries()){if(!o(d))continue;let m=s[l+1];i.push({...d,precedingSha:m&&o(m)?m.sha:null})}return u("Matched commits by ref",i)};var Nd=async e=>{if(!Fo(e.sha))return c("Invalid commit sha");let t=nn(e.repoRoot);if(a(t))return c(t.message);let n=await j({cwd:t.value,args:["show","--no-ext-diff","--no-color","--patch","--find-renames","--format=",e.sha]});return a(n)?c(n.message):u("Read commit patch",n.value.stdout)},tC=200,Mh=e=>/^0+$/.test(e),$a=/^:\d{6} \d{6} ([0-9a-f]{40}) ([0-9a-f]{40}) [A-Z]\d*\t(.+)$/,Ph=/^(\d+|-)\t(\d+|-)\t(.+)$/,kh=async(e,t,n,r)=>{let o=await j({cwd:e,args:["diff","--raw","--numstat","--no-renames","--abbrev=40",t,n,...r&&r.length>0?["--",...r]:[]]});if(a(o))return c(o.message);let s=o.value.stdout.split(`
|
|
76
|
+
`).filter(m=>m!==""),i=s.filter(m=>!$a.test(m)&&!Ph.test(m));if(i.length>0)return c(`Could not parse ${i.length} line(s) of "git diff --raw --numstat" output, e.g. "${i[0]}"`);let l=new Map;for(let m of s){let p=Ph.exec(m);p&&l.set(p[3]??"",{insertions:p[1]==="-"?0:Number(p[1]),deletions:p[2]==="-"?0:Number(p[2]),isBinary:p[1]==="-"&&p[2]==="-"})}let d=s.filter(m=>$a.test(m)).map(m=>{let p=$a.exec(m),f=p?.[1]??"",g=p?.[2]??"",y=p?.[3]??"";return{path:y,beforeBlob:Mh(f)?null:f,afterBlob:Mh(g)?null:g,...l.get(y)??{insertions:0,deletions:0,isBinary:!1}}});return u("Listed changed files with blob hashes",d)},Dh=async(e,t)=>{if(t.length>tC)return c(`${t.length} files changed \u2014 too many to show as a diff`);let n=t.flatMap(s=>s.isBinary?[]:[s.beforeBlob,s.afterBlob].filter(i=>i!==null)),r=await Fi(n,e);if(a(r))return c(r.message);let o=r.value;return u("Read changed file contents",t.map(s=>({path:s.path,before:s.isBinary||!s.beforeBlob?"":o.get(s.beforeBlob)??"",after:s.isBinary||!s.afterBlob?"":o.get(s.afterBlob)??"",insertions:s.insertions,deletions:s.deletions,isBinary:s.isBinary})))},Ad=async e=>{if(!Fo(e.sha))return c("Invalid commit sha");let t=nn(e.repoRoot);if(a(t))return c(t.message);let n=t.value,r=await kh(n,`${e.sha}~1`,e.sha);if(a(r))return c(r.message);if(r.value.length===0)return c("No changed files found for this commit");let o=await Dh(n,r.value);if(a(o))return c(o.message);let s=o.value;return u("Loaded commit diff",{sha:e.sha,files:s})},nC=/^[0-9a-f]{40}$/,rC=async(e,t,n)=>{let r=await j({cwd:e,args:["log","--raw","--no-renames","--abbrev=40","--format=%H",`${t}..${n}`]});if(a(r))return c(r.message);let o=new Map,s=null;for(let i of r.value.stdout.split(`
|
|
77
|
+
`)){if(nC.test(i)){s=new Set,o.set(i,s);continue}let l=$a.exec(i);l&&s&&s.add(l[3]??"")}return u("Listed changed paths per commit",o)},Lh=e=>{let t=new Set;for(let n of e)for(let r of n)t.add(r);return t},oC=async(e,t,n)=>{if(t===n)return!0;let r=await j({cwd:e,args:["merge-base","--is-ancestor",t,n]});return!a(r)},sC="4b825dc642cb6eb9a060e54bf8d69288fbee4904",iC=async(e,t)=>{let n=await j({cwd:e,args:["rev-parse","--verify","--quiet",`${t}^1`]});return a(n)?sC:`${t}~1`},Td=async e=>{let t=nn(e.repoRoot);if(a(t))return c(t.message);let n=t.value,r=await zn({repoRoot:n,ref:e.ref});if(a(r))return c(r.message);let o=r.value;if(o.length===0)return c("No commits reference this ticket");let s=o[0].sha,i=s;for(let A=o.length-1;A>0;A--){let P=o[A].sha;if(await oC(n,P,s)){i=P;break}}let l=await iC(n,i),d=await rC(n,l,s);if(a(d))return c(d.message);let m=d.value,p=new Set(o.map(A=>A.sha)),f=[...m.keys()].filter(A=>p.has(A)),g=f.length===m.size,y=new Map;for(let A of f)for(let P of m.get(A)??[])y.has(P)||y.set(P,A);let x=(A,P)=>u("Loaded squashed diff",{ref:e.ref.trim().toUpperCase(),from:l,to:s,commits:f.length,files:A.map(M=>({...M,sha:y.get(M.path)??s})),contiguous:g,overlappingPaths:P}),b,R=[];if(!g){let A=Lh(f.map(M=>m.get(M)??new Set)),P=Lh([...m.entries()].filter(([M])=>!p.has(M)).map(([,M])=>M));if(A.size===0)return x([],[]);b=[...A],R=[...A].filter(M=>P.has(M)).sort()}let S=await kh(n,l,s,b);if(a(S))return c(S.message);let T=await Dh(n,S.value);return a(T)?c(T.message):x(T.value,R)};var aC=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$/,Ua=e=>{if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),n="";for(let r=0;r<t.length;r++){if(t[r]!=="\\"){n+=t[r];continue}let o=t[++r];if(o==="n")n+=`
|
|
78
|
+
`;else if(o==="t")n+=" ";else if(o==='"'||o==="\\")n+=o;else if(o&&/[0-7]/.test(o)){let s=t.slice(r,r+3);n+=String.fromCharCode(parseInt(s,8)),r+=2}else o!==void 0&&(n+=o)}try{return decodeURIComponent(escape(n))}catch{return n}},Bh=e=>{let t=Ua(e.trim());return t==="/dev/null"?null:t.replace(/^[ab]\//,"")},Md=e=>{let t=[],n=null,r=0,o=0,s=()=>{let i={path:"",oldPath:null,binary:!1,added:0,removed:0,lines:[]};return t.push(i),i};for(let i of e.split(`
|
|
79
|
+
`)){if(i.startsWith("diff --git ")){n=s();let p=i.slice(11),f=p.lastIndexOf(" b/");f!==-1&&(n.path=Ua(p.slice(f+1)).replace(/^b\//,""));continue}if(!n){if(!i.trim())continue;n=s()}let l=n,d=l.lines.length===0;if(d&&i.startsWith("--- ")){let p=Bh(i.slice(4));p&&(l.oldPath=p);continue}if(d&&i.startsWith("+++ ")){let p=Bh(i.slice(4));p&&(l.path=p);continue}if(d&&i.startsWith("rename from ")){l.oldPath=Ua(i.slice(12));continue}if(d&&i.startsWith("rename to ")){l.path=Ua(i.slice(10));continue}if(d&&(i.startsWith("Binary files ")||i.startsWith("GIT binary patch"))){l.binary=!0,l.lines.push({kind:"note",text:"Binary file"});continue}let m=aC.exec(i);if(m){r=Number(m[1]),o=Number(m[3]),l.lines.push({kind:"hunk",text:i});continue}if(!d){if(i.startsWith("\\")){l.lines.push({kind:"note",text:i.slice(1).trim()});continue}if(i.startsWith("+")){l.added++,l.lines.push({kind:"added",text:i.slice(1),newLine:o++});continue}if(i.startsWith("-")){l.removed++,l.lines.push({kind:"removed",text:i.slice(1),oldLine:r++});continue}if(i.startsWith(" ")){l.lines.push({kind:"context",text:i.slice(1),oldLine:r++,newLine:o++});continue}i===""&&l.lines.push({kind:"context",text:"",oldLine:r++,newLine:o++})}}for(let i of t)!i.path&&i.oldPath&&(i.path=i.oldPath);return t.filter(i=>i.path!=="")},wd=e=>e.oldPath&&e.oldPath!==e.path?e.oldPath:null;var Pd=e=>e.flatMap(t=>[{kind:"file",text:`${wd(t)?`${wd(t)} \u2192 `:""}${t.path}`,file:t},...t.lines]),ja=e=>{let t="",n=-1;return e.map(r=>(r.kind==="file"&&(t=r.file.path),r.kind==="hunk"&&n++,{file:t,hunk:n}))},Ld=(e,t,n)=>{let r=t.map(i=>zs(i.md)).filter(i=>i!==null&&i.sha===n&&i.side==="additions");if(r.length===0)return new Set;let o=ja(e),s=new Set;return e.forEach((i,l)=>{let d=i.newLine;if(d===void 0)return;let m=o[l]?.file;r.some(p=>p.filePath===m&&p.start<=d&&d<=p.end)&&s.add(l)}),s},Oh=(e,t)=>e===t?`line:${e}`:`lines:${e}-${t}`,lC=/^lines?:(\d+)(?:-(\d+))?(?:\s+|$)/,Fh=e=>{let t=lC.exec(e);if(!t)return null;let n=Number(t[1]),r=t[2]===void 0?n:Number(t[2]);return{start:Math.min(n,r),end:Math.max(n,r),note:e.slice(t[0].length)}},_h=(e,t)=>ja(e)[t]?.file??null,$h=(e,t,n,r)=>{let o=ja(e),s=d=>e.findIndex((m,p)=>o[p]?.file===t&&(m.kind==="added"||m.kind==="context")&&m.newLine===d),i=s(n),l=s(r);return i===-1||l===-1?{ok:!1,reason:`${t} has no line ${i===-1?n:r} on the new side`}:kd(e,i,l)},kd=(e,t,n)=>{let[r,o]=t<=n?[t,n]:[n,t],s=e[r],i=e[o];if(!s||!i)return{ok:!1,reason:"That line is not in the diff"};let l=g=>(g.kind==="added"||g.kind==="context")&&g.newLine!==void 0;if(!l(s)||!l(i))return{ok:!1,reason:"Comments anchor to the new side: pick an added or unchanged line"};let d=ja(e),m=d[r],p=d[o];if(m.file!==p.file)return{ok:!1,reason:"A comment covers one file at a time"};if(m.hunk!==p.hunk)return{ok:!1,reason:"A comment covers one hunk at a time"};let f=e.slice(r,o+1).filter(l);return{ok:!0,value:{filePath:m.file,start:f[0].newLine,end:f[f.length-1].newLine,snippet:f.map(g=>g.text).join(`
|
|
80
|
+
`)}}};import{existsSync as Fd}from"node:fs";import{chmod as _d}from"node:fs/promises";import Wa from"node:path";import{spawn as cC,spawnSync as dC}from"node:child_process";import uC from"node:os";import Uh from"node:path";import{ulid as mC}from"ulid";function Dd(e){let t=[],n="",r=!1,o=null;for(let s of e.trim()){if(o){s===o?o=null:n+=s;continue}if(s==='"'||s==="'"){o=s,r=!0;continue}if(/\s/.test(s)){r&&t.push(n),n="",r=!1;continue}n+=s,r=!0}return r&&t.push(n),t}function pC(e){let t=e.trim();return t==="$EDITOR"?process.env.EDITOR:t==="$VISUAL"?process.env.VISUAL:t}function Ha(){let{preferredEditor:e}=V(),t=[e?pC(e):void 0,process.env.VISUAL,process.env.EDITOR].filter(n=>!!n?.trim());return[...new Set(t)]}function Bd(e){let[t=""]=Dd(e);return/(^|\/)code(-insiders)?$/.test(t)}function jh(e,t){let[n="",...r]=Dd(e);return{command:n,args:[...r,...t]}}function Hh(e,t){return jh(e,Bd(e)?["--wait",t]:[t])}function fC(e,t,n,r="new"){return jh(e,[r==="new"?"--new-window":"--reuse-window","--diff",t,n])}function Wh(e){let t=Uh.join(uC.tmpdir(),"epiq");ot.mkDir(t);let n=Uh.join(t,mC());ot.writeToFile(n,e??"");let r=Ha();for(let o of r){let{command:s,args:i}=Hh(o,n);if(!s)continue;let l=dC(s,i,{stdio:"inherit"});if(!l.error&&l.status===0){let d=ot.readFile(n);if(d==null)return c("Unable to read edited file");let m=d.replace(/\r?\n$/,"");return u("Successfully edited",m)}}return c("Unable to open editor")}var gC=new Set(["vim","vi","nvim","nano","pico","ed"]);function hC(e){let[t=""]=Dd(e),n=t.split("/").pop()??t;return gC.has(n)}var yC=600;function Gh({command:e,args:t},n){return new Promise(r=>{if(!e){r(c(`"${n}" is not a usable editor command`));return}let o=cC(e,t,{stdio:"ignore",detached:!0}),s=!1,i=d=>{s||(s=!0,clearTimeout(l),r(d))};o.on("error",d=>i(c(d.message))),o.on("exit",d=>{i(d===0?u("Opened editor",!0):c(`"${n}" exited with code ${d}`))});let l=setTimeout(()=>{o.unref(),i(u("Opened editor",!0))},yC)})}function vC(e,t){return hC(e)?Promise.resolve(c(`"${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}`)):Gh(Hh(e,t),e)}function Od(e,t,n,r="new"){return Gh(fC(e,t,n,r),e)}async function Vh(e){let t=Ha();if(t.length===0)return c("No editor configured (preferredEditor, VISUAL, or EDITOR)");let n=c("Unable to open editor");for(let r of t){let o=await vC(r,e);if(!a(o))return o;n=o,logger.error(`Failed to open editor "${r}" for ${e}: ${o.message}`)}return n}import{chmodSync as bC,existsSync as xC,lstatSync as IC,mkdirSync as EC}from"node:fs";import SC from"node:os";import RC from"node:path";var Ys=(...e)=>{let t=RC.join(SC.tmpdir(),"epiq",...e);try{return xC(t)&&IC(t).isSymbolicLink()?c(`Refusing to write through a symlink at ${t}`):(EC(t,{recursive:!0,mode:448}),bC(t,448),u("Prepared private temp dir",t))}catch(n){return c(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var CC=async(e,t)=>{let n=await j({cwd:e,args:["show",t]});if(a(n))return c(n.message);let r=Ys("commit-diffs");if(a(r))return c(r.message);let o=Wa.join(r.value,`${t}.diff`);return Fd(o)||(ot.writeToFile(o,n.value.stdout),await _d(o,292)),Vh(o)},NC=12,AC=800,zh=async(e,t,n)=>{let r=await j({cwd:e,args:["show",`${t}:${n}`]});return a(r)?"":r.value.stdout},TC=async(e,t)=>{let n=await j({cwd:e,args:["diff","--name-only",`${t}~1`,t]});if(a(n))return c(n.message);let r=n.value.stdout.split(`
|
|
81
|
+
`).map(o=>o.trim()).filter(Boolean);return r.length===0?c("No changed files found for this commit"):u("Listed changed files",r)},wC=async(e,t,n)=>{let r=await TC(e,t);if(a(r))return c(r.message);let o=r.value;if(o.length>NC)return c(`Commit touches ${o.length} files \u2014 too many for a side-by-side view`);let s=Ys("commit-diffs",t);if(a(s))return c(s.message);let i=s.value,l=await Promise.all(o.map(async(g,y)=>{let[x,b]=await Promise.all([zh(e,`${t}~1`,g),zh(e,t,g)]),R=Wa.basename(g),S=Wa.join(i,String(y),"before",R),T=Wa.join(i,String(y),"after",R);return Fd(S)||(ot.writeToFile(S,x),await _d(S,292)),Fd(T)||(ot.writeToFile(T,b),await _d(T,292)),{beforePath:S,afterPath:T}})),[d,...m]=l;if(!d)return c("No changed files found for this commit");let p=await Od(n,d.beforePath,d.afterPath,"new");if(a(p)||m.length===0)return p;await new Promise(g=>setTimeout(g,AC));let f=await Promise.all(m.map(({beforePath:g,afterPath:y})=>Od(n,g,y,"reuse")));for(let g of f)a(g)&&logger.error(`Failed to open an additional diff tab for ${t}: ${g.message}`);return p},Xs=async e=>{if(!Fo(e.sha))return c("Invalid commit sha");let t=nn(e.repoRoot);if(a(t))return c(t.message);let n=t.value,r=Ha()[0];if(r&&Bd(r)){let o=await wC(n,e.sha,r);if(!a(o))return o;logger.error(`Side-by-side diff failed for ${e.sha}, falling back to unified diff: ${o.message}`)}return CC(n,e.sha)};import{Box as rn,Text as Kn}from"ink";import _e,{useEffect as Hd,useMemo as Xh,useRef as LC,useState as kC}from"react";var Ga=(e,t,n)=>{let r=[],o=va(()=>{for(let s=0;s<t;s++){let i=Pt(BigInt(s+1));if(!be(i))continue;let l=N.createNode(Ne.text({id:n(s),name:`Line ${s+1}`,parentNodeId:e,rank:i.value,readonly:!0,isVirtual:!0}));be(l)&&r.push(l.value)}});return a(o)&&logger.error(`Line nodes: ${o.message}`),r},jo=e=>{N.deleteNodes(e.map(t=>t.id))};import{useSyncExternalStore as MC}from"react";var za=null,Va=null,$d=new Set,Kh=()=>{for(let e of $d)e()},Ud=e=>{za=e,Kh()},Ka=()=>za,qh={mark:null},Gr=e=>{Va=e,qh={mark:e},Kh()};var jd=e=>Va&&Va.sha===e?Va.row:null,Yh=()=>MC(e=>($d.add(e),()=>{$d.delete(e)}),()=>qh),hr=()=>{let{contextNode:e}=v();return za&&za.sha===e.id?e.id:null};import DC from"string-width";var Wd=(e,t)=>`${e}::patch::${t}`,BC=e=>{switch(e){case"added":return h.green;case"removed":return h.red;case"hunk":return h.accent;case"file":return h.primary;default:return h.secondary2}},Jh=(e,t)=>{let n=DC(e);return n>=t?e:e+"\xA0".repeat(t-n)},OC=e=>e==="added"?"+":e==="removed"?"-":" ",Qh=e=>e.kind==="file"||e.kind==="hunk"||e.kind==="note"||e.newLine===void 0?"":String(e.newLine);function Zh({ticket:e,sha:t,subject:n,width:r,height:o}){let[s,i]=kC({state:"loading"});Hd(()=>{let A=!0;return i({state:"loading"}),Nd({sha:t}).then(P=>{A&&i(a(P)?{state:"failed",message:P.message}:{state:"loaded",rows:Pd(Md(P.value))})}),()=>{A=!1}},[t]);let l=s.state==="loaded"?s.rows:null,d=l!==null&&l.length>4e3,m=LC([]);Hd(()=>(jo(m.current),m.current=l&&!d?Ga(t,l.length,A=>Wd(t,A)):[],()=>{jo(m.current),m.current=[]}),[t,l,d]),Hd(()=>(Ud(l?{sha:t,rows:l}:null),Gr(null),()=>{Ud(null),Gr(null)}),[t,l]);let{selectedIndex:p}=oe(),{mark:f}=Yh(),g=Xh(()=>l?Ld(l,N.getCommentsByIssue(e.id),t):new Set,[l,t,e]),y=f&&f.sha===t?f.row:null,x=A=>y!==null&&A>=Math.min(y,p)&&A<=Math.max(y,p),b=Xh(()=>l?Math.max(5,l.reduce((A,P)=>Math.max(A,Qh(P).length),0)+2):5,[l]),R=Math.max(1,o-4),S=Math.max(8,r-b-6);if(s.state!=="loaded")return _e.createElement(rn,{flexDirection:"column",width:r,height:o,padding:1},_e.createElement(Kn,{color:h.primary},s.state==="loading"?"Reading the diff\u2026":`Could not read the diff: ${s.message}`));let T=A=>_e.createElement(rn,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},_e.createElement(Kn,{color:h.secondary2,wrap:"truncate-end"},_n(`${t.slice(0,7)} ${n} \u2014 ${A}`,Math.max(8,r-6))));return s.rows.length===0?_e.createElement(rn,{flexDirection:"column",width:r,height:o},T("no changes"),_e.createElement(rn,{paddingX:1},_e.createElement(Kn,{color:h.primary},"This commit changed no files."))):d?_e.createElement(rn,{flexDirection:"column",width:r,height:o},T("too large to draw here"),_e.createElement(rn,{paddingX:1,flexDirection:"column"},_e.createElement(Kn,{color:h.primary},`${s.rows.length.toLocaleString()} lines of diff.`),_e.createElement(Kn,{color:h.secondary2},"Press o to open it in your editor."))):_e.createElement(rn,{flexDirection:"column",width:r,height:o},T(y===null?"enter to comment on a line, s to start a range, o editor, q back":"move to the other end, then enter to comment \u2014 s clears the mark"),_e.createElement(mt,{scrollByOne:!0,height:R,selectedIndex:p,itemHeight:1},s.rows.map((A,P)=>{let M=P===p,O=BC(A.kind);if(A.kind==="file")return _e.createElement(rn,{key:Wd(t,P),paddingX:1},_e.createElement(Kn,{backgroundColor:h.secondary,color:M?h.accent:O,bold:!0,wrap:"truncate-end"},Jh(` ${_n(qs(A.text),S)}`,S+b+1)));let W=x(P),X=`${OC(A.kind)}${_n(qs(A.text),S)}`;return _e.createElement(rn,{key:Wd(t,P),paddingX:1},_e.createElement(rn,{flexShrink:0},_e.createElement(Kn,{color:M||W?h.accent:h.secondary2,dimColor:!M&&!W,wrap:"truncate-end"},`${M?"\u276F":"\xA0"}${W?"\u258C":"\xA0"}${Qh(A).padStart(b-2,"\xA0")}`)),_e.createElement(rn,{flexShrink:0},_e.createElement(Kn,{color:h.yellow,wrap:"truncate-end"},g.has(P)?"\u2502":"\xA0")),_e.createElement(Kn,{color:M?h.accent:O,backgroundColor:M||W?h.secondary:void 0,wrap:"truncate-end"},M||W?Jh(X,S+1):X))})))}var $C=e=>Pe(e,"diff"),ty=e=>{for(let t of e)N.deleteNode(t.id)},UC=(e,t,n)=>Ne.field({id:e.sha,name:e.subject,parentNodeId:n,rank:String(t).padStart(6,"0"),childRenderAxis:"vertical",isVirtual:!0}),jC=(e,t)=>{let n=N.getNode($C(e.id));if(!n||!lt(n))return[];let r=t.map((o,s)=>UC(o,s,n.id)).map(o=>N.createNode(o)).filter(be).map(({value:o})=>o).filter(lt);return t.length>0&&v().selectedIndex<0&&v().contextNode.id===n.id&&U.navigate({contextNode:n,selectedIndex:0}),r},HC=e=>`+${e.insertions} -${e.deletions}`;function ny({ticket:e,width:t,height:n}){let[r,o]=_C({state:"loading"}),s=H(e.id);ey(()=>{let x=!0;return o({state:"loading"}),zn({ref:s}).then(b=>{x&&o(a(b)?{state:"failed",message:b.message}:{state:"loaded",commits:b.value})}),()=>{x=!1}},[s]);let i=FC([]),l=r.state==="loaded"?r.commits:null;ey(()=>(ty(i.current),i.current=l?jC(e,l):[],()=>{ty(i.current),i.current=[]}),[e,l]);let{selectedIndex:d,contextNode:m}=oe(),p=l?.find(x=>x.sha===m.id)??null,g=Math.max(1,n-4),y=Math.max(12,t-34);return r.state!=="loaded"?Qe.createElement(Vr,{flexDirection:"column",width:t,height:n,padding:1},Qe.createElement(Tn,{color:h.primary},r.state==="loading"?"Reading commits\u2026":`Could not read commits: ${r.message}`)):p?Qe.createElement(Zh,{ticket:e,sha:p.sha,subject:p.subject,width:t,height:n}):r.commits.length===0?Qe.createElement(Vr,{flexDirection:"column",width:t,height:n,padding:1},Qe.createElement(Tn,{color:h.primary},"No commits reference this ticket."),Qe.createElement(Vr,{paddingTop:1},Qe.createElement(Tn,{color:h.primary},"Commits are matched by the"),Qe.createElement(Tn,{color:h.accent},` ${s} `),Qe.createElement(Tn,{color:h.primary},"prefix on their subject line."))):Qe.createElement(Vr,{flexDirection:"column",width:t,height:n},Qe.createElement(Vr,{paddingLeft:4,borderLeft:!1,borderRight:!1,borderBottom:!1,borderTop:!0,borderColor:h.secondary,borderStyle:"single",paddingBottom:1},Qe.createElement(Tn,{color:h.secondary2},`Diff (${r.commits.length}) \u2014 enter to read, o to open in your editor `)),Qe.createElement(mt,{height:g,itemHeight:2,selectedIndex:d},r.commits.map((x,b)=>{let R=b===d,S=x.subject.length>y?x.subject.slice(0,y-1)+"\u2026":x.subject;return Qe.createElement(Vr,{key:x.sha,flexDirection:"row",paddingX:1,paddingBottom:1},Qe.createElement(Tn,{color:h.accent},R?"\u276F ":" "),Qe.createElement(Vr,{paddingLeft:1},Qe.createElement(Tn,{color:h.secondary2},`${x.sha.slice(0,7)} `),Qe.createElement(Tn,{color:R?h.accent:h.primary},S),Qe.createElement(Tn,{color:h.secondary2},` ${HC(x)} ${pr(x.time)}`)))})))}import{Box as qa,Text as WC}from"ink";import qn from"react";var ry=({selectedIndex:e,parent:t,selected:n})=>{let{contextNode:r}=oe(),{title:o}=t,s=t.parentNodeId?N.getNode(t.parentNodeId):void 0,i=s&&_(s)?o===Te.ASSIGNEES?s.props.assignees??[]:o===Te.TAGS?(s.props.tags??[]).filter(l=>N.getTag(l)):[]:[];return qn.createElement(qa,{alignItems:"center",paddingTop:1},qn.createElement(qa,{minWidth:12},qn.createElement(St,{isSelected:n}),qn.createElement(WC,{color:n?h.accent:h.secondary2},o,":")),qn.createElement(qa,{flexDirection:"row",marginLeft:1,paddingRight:1},i.map((l,d)=>{let m=r.id===t.id&&d===e;return qn.createElement(qa,{key:`${o}-${l}`,paddingRight:2,minHeight:1},qn.createElement(St,{isSelected:m}),o===Te.ASSIGNEES?qn.createElement(ur,{isSelected:m,id:l}):o===Te.TAGS?qn.createElement(Lo,{isSelected:m,id:l}):null)})))};import{Box as Ho,Text as zd}from"ink";import Ut,{useEffect as GC,useMemo as Kd,useRef as VC}from"react";var Gd=e=>Math.max(5,String(Math.max(e,1)).length+3),oy=(e,t)=>Math.max(0,e-6-Gd(t));var Vd=(e,t=0,n=0)=>Math.max(1,e-5-2*t-(n>0?1+n:0));var zC="\u2029",sy=(e,t)=>`${e}::inline-line::${t}`,qd=({id:e,label:t,text:n,rows:r,selected:o,maxWidth:s})=>{let{selectedIndex:i,contextNode:l}=oe(),d=Kd(()=>typeof n=="string"?n.split(/\r?\n|\u2028|\u2029/):[],[n]),m=Kd(()=>d.join("\0"),[d]),p=VC([]);GC(()=>(jo(p.current),p.current=Ga(e,d.length,b=>sy(e,b)),()=>{jo(p.current),p.current=[]}),[e,m]);let f=Gd(d.length),g=oy(s,d.length),x=Kd(()=>Rd(d).map(b=>{if(b.kind==="code"||b.kind==="caption")return{...b,text:_n(b.text,g)};if(b.kind==="text"||b.kind==="heading"){let R=b.spans.map(S=>S.code?`\`${S.text}\``:S.text).join("");return{...b,spans:Ks(_n(R,g))}}return b}),[d,g]).map((b,R)=>{let S=l.id===e&&i===R;return Ut.createElement(Ho,{key:sy(e,R)},Ut.createElement(Ho,{flexShrink:0},Ut.createElement(zd,{color:S?h.primary:h.secondary2,dimColor:!S},`${R+1} `.padStart(f,"\xA0"))),b.kind==="blank"?Ut.createElement(zd,{backgroundColor:S?"gray":void 0},zC):Ut.createElement(Ho,null,Ut.createElement(Cd,{line:b,width:b.kind==="code"?g:0,wrap:"truncate-end"})))});return Ut.createElement(Ho,{flexDirection:"column",paddingTop:1},Ut.createElement(Ho,null,Ut.createElement(St,{isSelected:o}),Ut.createElement(zd,{color:o?h.accent:h.secondary2},t)),Ut.createElement(Ho,{flexDirection:"row",borderStyle:"round",borderColor:h.secondary,paddingLeft:1,marginLeft:1,overflowY:"hidden"},Ut.createElement(mt,{scrollByOne:!0,height:r,selectedIndex:i,itemHeight:1},x)))};var qC=e=>Pe(e,"description"),YC=e=>Pe(e,"comments"),XC=e=>Pe(e,"history"),JC=e=>Pe(e,"diff"),QC=e=>Pe(e,"attachments"),iy=({ticket:e,height:t})=>{let n=Go(()=>sh(e),[e]),{selectedIndex:r,contextNode:o}=oe(),s=process.stdout.columns||120,i=Go(()=>qC(e.id),[e.id]),l=Go(()=>YC(e.id),[e.id]),d=Go(()=>XC(e.id),[e.id]),m=Go(()=>JC(e.id),[e.id]),p=Go(()=>QC(e.id),[e.id]),f=N.getAttachmentsByIssue(e.id).length,g=o.id===e.id,y=o.id===l||o.parentNodeId===l,x=o.id===d||o.parentNodeId===d,b=o.id===p||o.parentNodeId===p,R=o.id===m||o.parentNodeId===m,S=de(e.id);if(y){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(Ah,{ticket:e,width:s,height:J}))}if(b){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(dh,{ticket:e,width:s,height:J}))}if(R){let J=t-3;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},Ct.createElement(ny,{ticket:e,width:s,height:J}))}if(x){let F=N.getNode(d),J=F&<(F)?F.props.value??"":"",Ke=Vd(t);return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},F?Ct.createElement(qd,{id:F.id,label:"Event log",text:J,selected:!1,maxWidth:s,rows:Ke}):null)}let T=[d,m,l,p],A=F=>T.includes(F),P=S.reduce((F,J)=>vs(J)?F+1:F,0),M=S.reduce((F,J)=>A(J.id)?F+1:F,0),O=S.findIndex(F=>A(F.id)),W=Vd(t,P,M),X=(F,J,Ke,Jn)=>Ct.createElement(Wo,{key:F.id,paddingTop:J===O?1:0},Ct.createElement(St,{isSelected:Ke}),Ct.createElement(KC,{backgroundColor:h.secondary,color:Ke?h.accent:h.primary},Jn)),Ee=(F,J,Ke)=>F.id===i?Ct.createElement(qd,{key:F.id,id:i,label:"Description (press e to edit)",text:e.props.description??"",selected:J,maxWidth:s,rows:W}):vs(F)?Ct.createElement(ry,{key:F.id,parent:F,selected:J,selectedIndex:r}):F.id===l?X(F,Ke,J,` Comments (${n}) \u203A\u203A `):F.id===p?X(F,Ke,J,` Attachments (${f}) \u203A\u203A `):F.id===d?X(F,Ke,J," History \u203A\u203A "):F.id===m?X(F,Ke,J," Diff \u203A\u203A "):null;return Ct.createElement(Wo,{width:s,flexDirection:"column",paddingRight:1,paddingBottom:1,minHeight:t},S.map((F,J)=>Ee(F,g&&r===J,J)))};var eN=({swimlanes:e,contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,viewMode:s,height:i,width:l})=>{let d=t.context,m=d===ie.TICKET||d===ie.FIELD_LIST||d===ie.FIELD,p=d===ie.BOARD||d===ie.SWIMLANE,f=d===ie.TICKET?t:r.find(R=>R.context===ie.TICKET),g=Math.floor(l/3),y=Math.floor(l/Math.max(e.length,1)),x=Math.min(y,g),b=s==="dense";return Ya.createElement(ZC,{flexDirection:"row",height:i},p&&e.map((R,S)=>{let T=t.id===R.id,A=T?n:-1,P=t.context===ie.BOARD&&n===S;return Ya.createElement(oh,{key:R.id,height:i,width:x,swimlane:R,isSelected:P,isDense:b,isFocused:T,listSelectedIndex:A,mode:o})}),m&&f&&Ya.createElement(iy,{height:i,ticket:f}))},Xa=Ya.memo(eN);import{render as rN}from"ink";import{Writable as oN}from"node:stream";var Js=e=>String(e).padStart(2,"0"),sN=e=>{let t=e.getUTCFullYear(),n=Js(e.getUTCMonth()+1),r=Js(e.getUTCDate()),o=Js(e.getUTCHours()),s=Js(e.getUTCMinutes()),i=Js(e.getUTCSeconds());return`${t}-${n}-${r}_${o}-${s}-${i}`},iN=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").toLowerCase()||"board",aN=async(e,{width:t,height:n})=>{let r="",o=new oN({write(i,l,d){let m=lN(i.toString()).trimEnd();m.trim().length>0&&m.includes("\u256D")&&(r=m),d()}});o.columns=t,o.rows=n,o.isTTY=!0;let s=rN(e,{stdout:o,debug:!1,exitOnCtrlC:!1,patchConsole:!1,incrementalRendering:!1});return await new Promise(i=>setTimeout(i,0)),s.unmount(),r},lN=e=>e.replace(/\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,""),ly=async()=>{let{viewMode:e}=V(),{contextNode:t,selectedIndex:n,breadCrumb:r,mode:o,renderedChildrenIndex:s}=v(),i=r.find(S=>S.context==="BOARD");if(!i)return c("No board found to export");let l=120,d=40,m=await aN(nN.createElement(Xa,{height:d,width:l,swimlanes:(s[i.id]??[]).filter(S=>S!==void 0&&gn(S)),contextNode:t,selectedIndex:n,breadCrumb:r,viewMode:e??"dense",mode:o}),{width:l,height:d});if(!m)return c("Failed to render board export");let p=Oi(process.cwd());if(a(p))return c("Unable to export, epiq root not found");let f=new Date,g=sN(f),y=`board_${iN(i.title)}_${g}.md`,x=Gm(p.value);ay.mkdirSync(x,{recursive:!0});let b=tN.join(x,y),R=`# Board - ${i.title}
|
|
72
82
|
Date: ${f.toISOString()}
|
|
73
83
|
|
|
74
84
|
\`\`\`text
|
|
75
85
|
${m}
|
|
76
86
|
\`\`\`
|
|
77
|
-
`;return
|
|
78
|
-
`).map(
|
|
87
|
+
`;return ay.writeFileSync(b,R,"utf8"),u("Exported board layout",b)};import{useSyncExternalStore as PW}from"react";var Ja,cN=new Set,cy=()=>{for(let e of cN)e()};var yr=()=>{if(!Ja)throw new Error("Ui state not initialized. Call initUiState() first.");return Ja};var dy=(e={})=>(Ja=e,cy(),u("UX state initialized",null)),dN=e=>{let t=yr();return Ja=e(t),cy(),u("UX state updated",null)},vr=e=>dN(t=>({...t,...e}));import{ulid as Yd}from"ulid";var uy=async e=>{let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(e.modifier===Mt.DESCRIPTION)return mN();if(r&&bs(r))return uN(e);if(e.modifier===Mt.TITLE){let o=pe();if(a(o))return c("Unable to resolve user ID");let s=r;if(!s)return c("Missing node");if(s.readonly)return c("Cannot rename readonly node");let i=e.inputString.trim();if(!i)return c("Provide a title");let l=await Se();return a(l)?l:B([{id:Yd(),action:"edit.title",payload:{id:s.id,name:i},...D(o.value)}],l.value)}return c("Unknown edit command")},uN=async e=>{let t=pe();if(a(t))return c("Unable to resolve user ID");let{contextNode:n,selectedIndex:r}=v(),o=de(n.id)[r];if(!o||!bs(o))return c("Select a comment first");if(o.readonly)return c("Cannot edit readonly comment");let s=n.parentNodeId;if(!s)return c("Unable to resolve comment issue");let i=v().nodes[s];if(!i||!_(i))return c("Unable to resolve comment issue");if(i.readonly)return c("Cannot edit readonly issue");let l=o.id.split(":").at(0)??"",d=N.getComment(l);if(!d||d.deleted)return c("Unable to resolve comment");if(d.issue!==i.id)return c("Comment does not belong to selected issue");if(d.authorId!==t.value.userId)return c("You can only edit your own comments"+d.authorId+"<->"+t.value.userId);let m=e.inputString.trim();if(!m)return c("Provide a comment");let p=await Se();if(a(p))return p;let f=p.value;return B([{id:Yd(),action:"edit.issue.comment",payload:{id:d.id,issue:i.id,md:m},...D(t.value)}],f)},mN=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let t=await Se();if(a(t))return t;let n=t.value,{breadCrumb:r,selectedNode:o}=v(),s=yt([...r,o],"TICKET");if(a(s))return c("Edit target must be an issue");let i=s.value;if(!_(i))return c("Edit target must be an issue");if(i.readonly)return c("Cannot edit readonly issue");let l=de(i.id).find(f=>f.title===Te.DESCRIPTION);if(!l)return c("No target found");if(l.readonly)return c("Cannot edit readonly field");let d=i.props.description??"";if(typeof d!="string")return c("Selected field is not editable text");let m=Wh(d);if(a(m))return c("Failed to edit field");let p=m.value;return p===d?u("No changes made",null):B([{id:Yd(),action:"edit.description",payload:{id:i.id,md:p},...D(e.value)}],n)};import fN from"node:fs";import Jd from"node:path";import Xd from"node:fs";import pN from"node:path";var my=async e=>{let t=pN.join(e,".gitignore"),n=Xd.existsSync(t)?Xd.readFileSync(t,"utf8"):"",r=[".epiq/events/",".epiq/log/"],o=n.split(`
|
|
88
|
+
`).map(d=>d.trim()),s=r.filter(d=>!o.some(m=>m===d||m===d.replace(/\/$/,"")||m==="/"+d||m==="/"+d.replace(/\/$/,"")));if(s.length===0)return u("Local epiq paths already ignored",!1);let l=["# [epiq]: local hydrated state is never committed",...s].join(`
|
|
79
89
|
`);return n=n.trimEnd()+`
|
|
80
90
|
|
|
81
|
-
${
|
|
82
|
-
`,
|
|
83
|
-
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},
|
|
84
|
-
`));let o;try{o=JSON.parse(r.value.stdout)}catch(
|
|
85
|
-
`));let c=it();if(a(c))return ts(16,c.message);let{rootNodeId:m,nodes:p}=c.value,f=p[m];return f?(_.navigate({contextNode:f,selectedIndex:0}),N({hasProjectDefinition:!0,mode:b.DEFAULT}),u(s,null)):ts(16,"Unable to resolve initialized root node")};import{ulid as ZS}from"ulid";import{ulid as QS}from"ulid";var Hf=null,zn=()=>structuredClone(Hf),ns=e=>{Hf=e},Wf=()=>{let{contextNode:e,selectedIndex:t}=h(),r=de(e.id)[t];return r?u("Resolved selected child",r):l("Target node not found")},xd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=de(t).filter(o=>o.id!==e);return ti(r,n)},Gf=({id:e,parentId:t,position:n={at:"end"}})=>{let r=ne();if(a(r))return l("Unable to resolve user ID");let o=xd({parentId:t,id:e,position:n});return a(o)?o:u("Created pending move state",{id:QS(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},Vf=e=>{ns(e);let t=kn(e,!0);return a(t)?t:u("Node moved successfully",t.value)};function Id(e){let t=Wf();if(a(t))return t;let{contextNode:n,nodes:r}=h();if(!n.parentNodeId)return l("Missing parent node id");let o=r[n.parentNodeId];if(!o)return l("Missing parent node");let s=de(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return l("Current node not found among siblings");let d=s[i+e];if(!d)return l("Missing sibling node");let c=Gf({id:t.value.id,parentId:d.id,position:{at:"end"}});return a(c)?c:Vf(c.value)}function Sd(e){let t=Wf();if(a(t))return t;let{contextNode:n,selectedIndex:r}=h(),s=de(n.id)[r+e];if(!s)return l("Missing sibling node");let i=Gf({id:t.value.id,parentId:n.id,position:{at:e===1?"after":"before",sibling:s.id}});return a(i)?i:Vf(i.value)}var zf=()=>{let e=zn();if(!e)return l("No pending move state");let t=e.payload.id,n=e.payload.parent,r=h().nodes[n];if(!r)return l("Move parent not found");let o=de(n).findIndex(s=>s.id===t);return o===-1?l("Moved node not found among rendered children"):(_.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},_i=(e,t="Moved preview")=>{if(a(e))return e;let n=zf();return a(n)?n:(N({mode:b.MOVE}),u(t,null))},Kf=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t}=re().commandMeta,{contextNode:n,selectedIndex:r}=h(),o=de(n.id)[r];if(!o)return N({mode:b.DEFAULT}),l("No move target");if(t==="start"){if(o.readonly)return l("Target node is read-only");if(r===-1)return l("No item selected");if(!o.parentNodeId)return l("Target has no parent");let s=de(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return l("Target not found among siblings");let d=s[i-1],c=s[i+1],m=c!=null?{at:"before",sibling:c.id}:d!=null?{at:"after",sibling:d.id}:{at:"start"},p=xd({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(ns({id:ZS(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...e.value}),N({mode:b.MOVE}),u("Move initialized",null))}if(t==="next")return _i(Sd(1));if(t==="previous")return _i(Sd(-1));if(t==="to-next")return _i(Id(1));if(t==="to-previous")return _i(Id(-1));if(t==="confirm"){let s=zn();if(!s)return l("No pending move to confirm");let i=await zt();if(a(i))return i;let d=D([s],i.value);if(a(d))return d;let c=zf();return a(c)?c:(ns(null),N({mode:b.DEFAULT}),u("Moved item",null))}return t==="cancel"?(ns(null),N({mode:b.DEFAULT}),u("Cancelling move",null)):l("Invalid move modifier")};import{ulid as ji}from"ulid";import{monotonicFactory as eE,ulid as tE}from"ulid";var nE=eE(),Ui=({name:e,parent:t,rank:n,user:{userId:r,userName:o}})=>{let s=nE();return u("Created issue events",[{id:tE(),userId:r,userName:o,action:"add.issue",payload:{id:s,parent:t,name:e,rank:n}}])};var qf=async(e,t)=>{let n=ne();if(a(n))return l("Unable to resolve user ID");let r=await zt();if(a(r))return r;let o=r.value;if(!t.inputString)return l(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:d}=h(),c=m=>{let p=D([m],o);if(a(p))return p;let f=R.getNode(p.value[0].result.id);if(!f)return l("Created node not found");if(!f.parentNodeId)return p;let g=R.getNode(f.parentNodeId);return g?(_.navigate({contextNode:g,selectedIndex:R.getSiblings(f.parentNodeId).findIndex(({id:v})=>v===f.id)}),p):l("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=h(),p=R.getNode(m);if(!p)return l("Workspace not found");let f=In(p.id,n.value,o);return a(f)?f:c({id:ji(),action:"add.board",payload:{id:ji(),name:t.inputString,parent:p.id,rank:f.value},...n.value})}if(t.modifier==="swimlane"){let m=ot(s,"BOARD");if(a(m))return l("Unable to add swimlane in this context");let p=In(m.value.id,n.value,o);return a(p)?p:c({id:ji(),action:"add.swimlane",payload:{id:ji(),name:t.inputString,parent:m.value.id,rank:p.value},...n.value})}if(t.modifier==="issue"){let m=X(i.id)[d],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let M=ot(s,"SWIMLANE");return a(M)?null:M.value})();if(!p)return l("Unable to add issue in this context");let f=In(p.id,n.value,o);if(a(f))return f;let g=Ui({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(g))return g;let v=g.value,I=D([...v],o);if(a(I))return I;if(!I.value[0])return l("Issue creation failed");let A=v.find(M=>M.action==="add.issue")?.payload.id;return A?(_.navigate({contextNode:p,selectedIndex:R.getSiblings(p.id).findIndex(({id:M})=>M===A)}),u("Issue created",null)):l("Unable to determine ticket id")}return u("Success",null)};import iE from"node:os";import Jf from"node:path";var rE=e=>e.some(t=>t.action==="init.workspace"),Yf=async(e,t)=>{let n=Gt(e);return a(n)?l(n.message):Io({cwd:t,branch:n.value})},oE=e=>{let t=Se(process.cwd());if(a(t))return!1;let n=fe({repoRoot:t.value});return!a(n)&&n.value===e},$i=async e=>{let t=fe({repoRoot:e});if(a(t))return _t(3,t.message);let n=t.value,r=await On({repoRoot:e,stateBranchRoot:n,stateBranchName:Ps().stateBranch});if(a(r))return _t(3,r.message);let o=St(n);if(a(o))return _t(3,o.message);if(!rE(o.value.events)){let m=await Yf(e,n);if(a(m)&&logger.info(3,m.message),o=St(n),a(o))return _t(3,o.message)}let{events:s,unreadable:i}=o.value,d=Ot(s,i);if(a(d))return _t(4,d.message);N({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let c=fi({root:e});return a(c)&&logger.info(c.message),u("Loaded project",void 0)},sE=async e=>{let t=fe({repoRoot:e});if(a(t))return l(t.message);let n=t.value,r=await fn({repoRoot:n});if(a(r))return l(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await di({worktreeRoot:n,operation:"boot pull",fn:()=>kl(n,()=>(Ur("Pulling"),Yf(e,n)))});if(a(o))return Te(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return xo(s.message)?(si("Offline"),u("Offline",void 0)):Te(s.message);if(!s.value)return ur("Already synced"),u("Already synced",void 0);if(!oE(n))return u("Project changed during the pull",void 0);let i=Dl(n);return a(i)?i:(ur("Pulled"),u("Pulled and reloaded",void 0))},Hi=e=>{sE(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${jr(t)}`)})},Xf=()=>{let e=Ot([]);return a(e)?_t(4,e.message):(N({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var aE=e=>e==="~"||e.startsWith("~/")?Jf.join(iE.homedir(),e.slice(1)):e,lE=(e,t)=>{let n=e.trim();if(!n)return l("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?u("Resolved recent project",o.root):l(`No recent project #${n}`)}let r=Se(Jf.resolve(aE(n)));return a(r)?l(`No epiq project at ${n}`):u("Resolved project path",r.value)},Qf=async()=>{let e=Ni();if(te(""),h().hasProjectDefinition)return l("Already in a project; run epiq from another directory");let t=Rn({exclude:process.cwd()}),n=a(t)?[]:t.value,r=lE(e,n);if(a(r))return l(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(d){return l(`Unable to enter ${o}: ${d instanceof Error?d.message:String(d)}`)}let i=await $i(o);return a(i)?(process.chdir(s),l(i.message)):(Hi(o),u(`Opened ${Gr(o)}`,null))};var Wi=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=h(),s=Qs(n,t);if(a(s))return l(s.message);let{appliedEvents:i,unappliedEvents:d}=s.value,c=jt();if(a(c))return c;let m=Bt(i),{fatal:p,skipped:f}=vn(m);if(p.length>0)return jt(),N(o),l(p.map(v=>v.message).join(", "));bn(f);let g=h().nodes[e];return g?(_.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:d})):(jt(),N(o),l("Board did not exist at that date"))};var Zf=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)};var dE=20,cE=16,uE=150,Gi=null,Vi=null;var vr=()=>{Gi!==null&&(clearInterval(Gi),Gi=null),Vi!==null&&(clearTimeout(Vi),Vi=null)},eg=()=>{vr(),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},tg=({events:e,startTime:t,durationMs:n})=>{vr();let r=e.length,o=_r(e.map(f=>Mn(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=Zf(o),d=Math.max(1,Math.round(n*dE/1e3)),c=Math.max(Math.round(n/d),cE),m=0,p=0;N({mode:b.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),Gi=setInterval(()=>{m++;let f=m/d,g=[],v,I;for(;p<r&&i[p]<=f;){let C=e[p],A=kn(C);if(a(A)){if(ko(A)){p++;continue}eg();return}g.push(...dl(C)),v=C,I=o[p],p++}if(p>=r||m>=d){for(;p<r;p++){let A=kn(e[p]);if(a(A)&&!ko(A))break}let C=h().replay;N({unappliedEvents:[],replay:C&&{...C,progress:1,appliedCount:r}}),vr(),Vi=setTimeout(eg,uE);return}let x=h().replay;N({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:v?I??x?.currentTime??t:x?.currentTime??t,currentLabel:v?zi(v):x?.currentLabel??"",flashNodeIds:v?[...new Set(g)]:x?.flashNodeIds??[]}})},c)};var ng=async()=>{let e=ot(h().breadCrumb,"BOARD");if(a(e))return e;let t=await kt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=fe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=re().commandMeta;if(vr(),r==="now"){let d=Fn(n.value);if(a(d))return l(d.message);let c=jt();if(a(c))return c;let m=Bt(d.value),{fatal:p,skipped:f}=vn(m);return p.length>0?l(p.map(g=>g.message).join(", ")):(bn(f),N({mode:b.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let d=Zs(n.value);if(a(d))return d;let c=r==="prev"?h().eventLog.at(-1):h().unappliedEvents.at(0),m=c===void 0?null:Mn(c),p=(c===void 0?null:d.value.get(c.id)??null)??(m===null?null:To(m));if(p===null)return l(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let d=mr(r||o.trim());if(!d)return l("Invalid peek date");s=d.getTime()}let i=Wi({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(N({mode:b.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var rg=async()=>{let e=ot(h().breadCrumb,"BOARD");if(a(e))return e;let t=await kt(process.cwd());if(a(t))return l("Unable to locate repo root");let n=fe({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=re().commandMeta,{dateInput:s,durationInput:i}=vi(r,o);if(vr(),h().syncStatus.status==="syncing")return l("Cannot replay while syncing, try again in a moment");let d=mr(s);if(!d)return l("Invalid replay date");let c=i?yi(i):15e3;if(c===null)return l("Invalid replay duration (try e.g. 30s or 2m)");let m=d.getTime(),p=h(),f=Wi({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(jt(),N(p),u("Nothing to replay from that point",!0)):(tg({events:g,startTime:m,durationMs:c}),u("Replaying board history",!0))};import{spawn as pE}from"node:child_process";var fE=()=>{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"]}}},og=async e=>new Promise(t=>{let{command:n,args:r}=fE();try{let o=pE(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(l(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):l(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(l(`Clipboard tool not available (${n})`))}});var rs=async(e,t)=>{if(!e.trim())return l(`Nothing to copy: ${t} is empty`);let n=await og(e);return a(n)?n:u(`Copied ${t} to clipboard`,null)},sg=async e=>{let{breadCrumb:t,selectedNode:n}=h(),r=Go({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return l("Nothing selected to copy from");switch(e.modifier){case Me.REF:return rs(O(o.id),"ref");case Me.TITLE:return rs(o.title,"title");case Me.DESCRIPTION:return r?rs(r.props?.description??"","description"):l("No issue in scope");case Me.TAGS:{if(!r)return l("No issue in scope");let s=Un(r).map(({name:i})=>i);return rs(s.join(", "),"tags")}case Me.ASSIGNEES:{if(!r)return l("No issue in scope");let s=jn(r).map(({name:i})=>i);return rs(s.join(", "),"assignees")}default:return l("Yank one of: ref, title, description, tags, assignees")}};var ig=async()=>{te(""),N({mode:b.DEFAULT});let e=it();if(a(e))return l(e.message);if(e.value.syncStatus.status==="syncing")return l("Sync already in progress");N({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await ui();return a(t)?(N({syncStatus:{msg:t.message,status:"failed"}}),t):(N({mode:b.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as ag}from"ulid";var Oe=async()=>{let e=await zt();return a(e)?e:u("Resolved persist root",e.value)};var gE=e=>e.action==="add.issue.comment",lg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(!r)return l("Unable to resolve child to delete");let o=await Oe();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=B(t)?t.id:t.parentNodeId;if(!i)return l("Unable to resolve comment issue");let d=h().nodes[i];if(!d||!B(d))return l("Unable to resolve comment issue");let c=d.log?.filter(gE).find(m=>m.payload.id===s);return c?c.payload.author!==e.value.userId?l("You can only delete your own comments"):D([{id:ag(),action:"delete.issue.comment",payload:{id:s,issue:i},...e.value}],o.value):l("Unable to resolve comment")}return D([{id:ag(),action:"delete.node",payload:{id:r.id},...e.value}],o.value)};import{ulid as hE}from"ulid";var dg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(!r)return l("Unable to close issue, no target found");if(!B(r))return l("Cannot close in this context");let o=h().nodes[ie];if(!o)return l("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return l("Issue is already closed");let s=await Oe();if(a(s))return s;let i=s.value,d=Xt(o.id,r.id,{at:"end"},e.value,i);if(a(d))return d;let c=D([{id:hE(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:d.value},...e.value}],i);return a(c)?c:u("Issue closed",null)};import{ulid as yE}from"ulid";var Ki=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};var cg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(!r)return l("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):ut(r.id,"TICKET");if(a(o))return l("Cannot reopen in this context");let s=o.value,i=h().nodes[ie];if(!i)return l("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return l("Issue is not closed");if(!B(s))return l("Target node is not issue");let d=Ki(s);if(!d)return l("Unable to resolve previous parent from issue history");if(d===i.id)return l("Previous parent resolves to closed swimlane");let c=h().nodes[d];if(!c)return l("Previous parent no longer exists");let m=await Oe();if(a(m))return m;let p=m.value,f=Xt(c.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let g=D([{id:yE(),action:"reopen.issue",payload:{id:s.id,parent:c.id,rank:f.value},...e.value}],p);return a(g)?g:u("Issue reopened",null)};import{ulid as vE}from"ulid";var ug=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=h(),r=X(t.id)[n];if(!r)return l("Missing node");if(r.readonly)return l("Cannot rename readonly node");let o=Ni();if(!o)return l("Provide a title");let s=await Oe();return a(s)?s:D([{id:vE(),action:"edit.title",payload:{id:r.id,name:o},...e.value}],s.value)};import{ulid as bE}from"ulid";var mg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return l("Provide a tag");let o=R.findTagByName(r);if(!o)return l(`Tag "${r}" does not exist`);let{selectedNode:s}=h();if(!s)return l("Invalid untag target");let i=ut(s.id,"TICKET");if(a(i))return l("Unable to untag issue in this context");let d=i.value;if(!B(d))return l("Target node is not issue");if(!(d.props.tags??[]).includes(o.id))return l("Issue is not tagged with that tag");let m=await Oe();return a(m)?m:D([{id:bE(),action:"remove.issue.tag",payload:{id:d.id,tag:o.id},...e.value}],m.value)};import{ulid as Ed}from"ulid";var pg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return l("Provide a tag");let{selectedNode:o}=h();if(!o)return l("Invalid tag target");let s=ut(o.id,"TICKET");if(a(s))return l("Unable to tag issue in this context");let i=s.value;if(!B(i))return l("Target node is not issue");let d=await Oe();if(a(d))return d;let c=R.findTagByName(r),m=c?.id??Ed();return(i.props.tags??[]).includes(m)?l("Already tagged with that tag"):D([...c?[]:[{id:Ed(),action:"create.tag",payload:{id:m,name:r},...e.value}],{id:Ed(),action:"add.issue.tag",payload:{id:i.id,tag:m},...e.value}],d.value)};import{ulid as Rd}from"ulid";var qi=()=>{let{eventLog:e=[],contributors:t}=h(),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))n.set(o.id,o.name);return[...n.entries()].map(([o,s])=>({id:o,name:s,isExternal:!r.has(o)}))};var fg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return l("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return l("Provide an assignee");let{selectedIndex:i,contextNode:d}=h(),c=X(d.id)[i];if(!c)return l("Invalid assign target");let m=ut(c.id,"TICKET");if(a(m))return l("Unable to assign issue in this context");let p=m.value;if(!B(p))return l("Target node is not issue");let f=await Oe();if(a(f))return f;let g=qi(),v=!o&&s.toLowerCase()==="me",I,x;if(v)I=e.value.userId,x=g.find(M=>M.id===I)?.name??e.value.userName;else{let M=g.filter(L=>L.name===s);if(M.length>1)return l(`"${s}" matches ${M.length} contributors (${M.map(L=>L.id).join(", ")}). Assign from the GUI to choose by id.`);let w=M[0];if(!w&&!o)return l(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);I=w?.id??Rd(),x=w?.name??s}if((p.props.assignees??[]).includes(I))return l("Assignee already assigned");let A=!!h().contributors[I];return D([...A?[]:[{id:Rd(),action:"create.contributor",payload:{id:I,name:x},...e.value}],{id:Rd(),action:"add.issue.assignee",payload:{id:p.id,assignee:I},...e.value}],f.value)};import{ulid as xE}from"ulid";var gg=async()=>{let e=ne();if(a(e))return l("Unable to resolve user ID");let{modifier:t,inputString:n}=re().commandMeta,r=(t||n).trim();if(!r)return l("Provide an assignee to remove");let{selectedNode:o}=h();if(!o)return l("Invalid unassign target");let s=ut(o.id,"TICKET");if(a(s))return l("Unable to unassign in this context");let i=s.value;if(!B(i))return l("Target node is not issue");let d=i.props.assignees??[],c=r.toLowerCase()==="me",m=c?d.filter(g=>g===e.value.userId):qi().filter(g=>g.name===r&&d.includes(g.id)).map(g=>g.id);if(m.length>1)return l(`"${r}" matches ${m.length} assignees (${m.join(", ")}). Unassign from the GUI to choose by id.`);let p=m[0];if(!p)return l(c?"Issue is not assigned to you":`Issue is not assigned to "${r}"`);let f=await Oe();return a(f)?f:D([{id:xE(),action:"remove.issue.assignee",payload:{id:i.id,assignee:p},...e.value}],f.value)};import{ulid as hg}from"ulid";var yg=async e=>{let t=e.inputString.trim();if(!t)return l("Provide a comment");if(t.length>4e3)return l(`Cannot exceed ${4e3} characters`);let n=ne();if(a(n))return l("Unable to resolve user ID");let{breadCrumb:r,selectedNode:o}=h(),s=ot([...r,o],"TICKET");if(a(s))return l("Edit target must be an issue");let i=s.value;if(!i)return l("Invalid comment target");let d=i.context==="TICKET"?u("Resolved ticket",i):ut(i.id,"TICKET");if(a(d))return l("Unable to comment on issue in this context");let c=d.value;if(!B(c))return l("Target node is not issue");let m=await Oe();return a(m)?m:D([{id:hg(),action:"add.issue.comment",payload:{id:hg(),issue:c.id,author:n.value.userId,md:t},...n.value}],m.value)};import{ulid as SE}from"ulid";import IE from"zod";var vg=()=>{let e=re().commandMeta.inputString,t=IE.coerce.number().int().min(3e3).safeParse(e);if(!t.success)return l("Auto sync duration must be a number of at least 3000 ms");let n=vt({autoSyncDebounceMs:t.data});return a(n)?n:(Ye({autoSyncIntervalMs:t.data}),N({mode:b.DEFAULT}),u(`Auto sync interval set to ${t.data}ms`,null))};var bg=()=>{let e=re().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return l("Invalid response");let t=sp(e),n=vt({autoSync:t});return a(n)?n:(Ye({autoSync:t}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var xg=()=>{let e=re().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return l("Invalid response");let n=vt({logLevel:e});return a(n)?n:(Ye({logLevel:e}),N({mode:b.DEFAULT}),u(`Auto sync set to "${e}"`,null))};var Ig=e=>{let t=e.inputString.trim();switch(e.modifier){case xe.USERNAME:{if(process.env[cn])return l(`Cannot change the configured user while ${cn} names this process`);let n=Or();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,d=r||SE();if(!i||!d)return l("Unable to resolve user name or id");let c=vt({userName:i,userId:d,preferredEditor:o??""});return a(c)?c:(Ye({userName:i,userId:d}),N({mode:b.DEFAULT}),u(`Username set to "${i}"`,null))}case xe.EDITOR:{if(!t)return l("No editor provided");let n=vt({preferredEditor:t});return a(n)?n:(Ye({preferredEditor:t}),N({mode:b.DEFAULT}),u(`Editor configuration set to "${t}"`,null))}case xe.VIEW:{if(t!=="wide"&&t!=="dense")return l("Invalid view mode");let n=vt({viewMode:t});return a(n)?n:(Ye({viewMode:t}),N({mode:b.DEFAULT}),u(`View set to "${t}"`,null))}case xe.AUTOSYNC:return bg();case xe.LOG_LEVEL:return xg();case xe.SYNC_DEBOUNCE_MS:return vg();case xe.ATTACHMENT_MAX_KB:return bp();default:return l("Unknown config command")}};var Yi=[{systemOnly:!0,intent:j.Move,description:"Internal move-state command",mode:b.COMMAND_LINE,action:Kf},{intent:j.Delete,description:"Delete the currently selected node",mode:b.COMMAND_LINE,action:lg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:b.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=re().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Ne(E.FILTER).map(d=>d.split(n)[0]).includes(i))(r))return l("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return we(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:b.DEFAULT})),u("Filter updated",null)}},{intent:j.ViewHelp,description:"Open the help screen",mode:b.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Vn({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),N({mode:b.HELP}),u("Viewing help",null)}},{intent:j.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:b.COMMAND_LINE,action:dg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:b.COMMAND_LINE,action:cg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Init,description:"Initialize Epiq in the current git repository",mode:b.COMMAND_LINE,action:$f},{intent:j.OpenProject,description:"Open a recently used epiq project, by number or path",mode:b.COMMAND_LINE,action:Qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.NewItem,description:"Create a new board, swimlane, or issue",mode:b.COMMAND_LINE,action:qf,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Rename,description:"Rename the currently selected node",mode:b.COMMAND_LINE,action:ug,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.UntagTicket,description:"Remove a tag from the selected issue",mode:b.COMMAND_LINE,action:mg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.TagTicket,description:"Add or create a tag on the selected issue",mode:b.COMMAND_LINE,action:pg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.AssignUserToTicket,description:"Assign a user to the selected issue",mode:b.COMMAND_LINE,action:fg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:b.COMMAND_LINE,action:gg,onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Comment,description:"Add a comment to the selected issue",mode:b.COMMAND_LINE,action:async(e,t)=>yg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Sync,description:"Pull, commit, and push Epiq state",mode:b.COMMAND_LINE,action:ig},{intent:j.Peek,description:"View board state at another point in time",mode:b.COMMAND_LINE,action:ng},{intent:j.Replay,description:"Replay board history forward from a point in time",mode:b.COMMAND_LINE,action:rg},{intent:j.Export,description:"Export the current board layout to markdown",mode:b.COMMAND_LINE,action:async()=>{let e=await wf();return a(e)?e:(N({mode:b.DEFAULT}),u("Export successful",!0))}},{intent:j.Exit,description:"Exit the application",mode:b.COMMAND_LINE,action:async()=>(_.exit(),u("Exit successful",!0))},{intent:j.Edit,description:"Edit title or description",mode:b.COMMAND_LINE,action:async(e,t)=>_f(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:b.COMMAND_LINE,action:async(e,t)=>sg(t),onSuccess:()=>N({mode:b.DEFAULT})},{intent:j.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:b.COMMAND_LINE,action:(e,t)=>Ig(t)}];var EE=new Set(["peek","replay","filter","view-help","yank"]),on=async({isForceExecutedBySystem:e=!1}={})=>{let{commandMeta:{command:t,validity:n,modifier:r,inputString:o}}=re();if(!t)return l("No command to confirm");if(!e&&n===tn.Invalid)return l("Invalid command");let s=Ai(t);Up();let{readOnly:i}=h();if(i&&!EE.has(s))return Yo({status:Tn.Fail,message:"Command not available in readonly state",value:null});let d=Yi.filter(m=>e||m.systemOnly!==!0).find(m=>m.intent===s);if(!d)return Yo({status:Tn.Fail,message:"Command not found",value:null});let c;try{c=await d.action(d,{command:t,inputString:o,modifier:r})}catch(m){return Yo({status:Tn.Fail,message:m instanceof Error?m.message:"Command failed",value:null})}return a(c)?Yo(c):(jp({addToHistory:!e}),d.onSuccess?.(),le().autoSync&&mi(),c)};var Xi=[{intent:S.Exit,mode:b.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(N({mode:b.COMMAND_LINE}),te("move cancel"),on({isForceExecutedBySystem:!0}))},{intent:S.InitMove,mode:b.DEFAULT,description:"[m] move",action:()=>(N({mode:b.COMMAND_LINE}),te("move start"),on({isForceExecutedBySystem:!0}))},{intent:S.ConfirmMove,mode:b.MOVE,description:"[m] confirm move",action:()=>(N({mode:b.COMMAND_LINE}),te("move confirm"),on({isForceExecutedBySystem:!0}))}],Ji=[{intent:S.MovePreviousItem,mode:b.MOVE,action:()=>zn()?(N({mode:b.COMMAND_LINE}),te("move previous"),on({isForceExecutedBySystem:!0})):l("No pending move")},{intent:S.MoveNextItem,mode:b.MOVE,action:()=>zn()?(N({mode:b.COMMAND_LINE}),te("move next"),on({isForceExecutedBySystem:!0})):l("No pending move")}],Sg=[{intent:S.MoveToNextContainer,mode:b.MOVE,action:()=>zn()?(N({mode:b.COMMAND_LINE}),te("move to-next"),on({isForceExecutedBySystem:!0})):l("No pending move")},{intent:S.MoveToPreviousContainer,mode:b.MOVE,action:()=>zn()?(N({mode:b.COMMAND_LINE}),te("move to-previous"),on({isForceExecutedBySystem:!0})):l("No pending move")}];var Eg={[K.WORKSPACE]:[...Xi,...Ji],[K.BOARD]:[...Xi,...Ji],[K.SWIMLANE]:[...Xi,...Ji,...Sg],[K.TICKET]:[],[K.FIELD]:[],[K.FIELD_LIST]:[],[K.TEXT]:[],[K.COMMENT]:[]};import CE from"node:fs";import NE from"node:path";import{spawn as RE}from"node:child_process";function Rg(e){let t=process.platform,o=RE(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var Cg=e=>{let t=Se(process.cwd());if(a(t))return l("Unable to resolve project root");let n=fe({repoRoot:t.value});if(a(n))return l(n.message);let r=fr(e.hash,e.ext),o=NE.join(Co(n.value),r);return CE.existsSync(o)?(Rg(o),u(`Opened ${e.name}`,null)):l("Attachment file not found \u2014 run :sync to fetch it")};var Ng=()=>{te("");let{pendingNavTarget:e}=Gn();N({mode:b.DEFAULT}),e&&_.navigate(e),Vn({pendingNavTarget:void 0})},Ag=[{intent:S.ExitCommandLine,mode:b.HELP,action:()=>(Ng(),u("Exiting help",null))},{intent:S.Exit,mode:b.HELP,action:()=>(Ng(),u("Closed help",null))},{intent:S.NavPreviousItem,mode:b.HELP,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:S.NavNextItem,mode:b.HELP,action:()=>(_.navigateToNextItem(),u("Navigating to next help item",null))},{intent:S.NavToPreviousContainer,mode:b.HELP,action:()=>(_.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:S.NavToNextContainer,mode:b.HELP,action:()=>(_.navigateToNextContainer(),u("Navigating to next help container",null))}];var AE=e=>{N({mode:b.COMMAND_LINE});let{pendingNavTarget:t}=Gn();t&&_.navigate(t),Vn({pendingNavTarget:void 0}),te(`${e} `)},Tg=()=>{te("");let{pendingNavTarget:e}=Gn();e&&_.navigate(e),Vn({pendingNavTarget:void 0}),N({mode:b.DEFAULT})},wg=[{intent:S.InitCommandPalette,mode:b.DEFAULT,description:"[?] command palette",action:()=>{te("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=h();return Vn({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),N({mode:b.PALETTE}),u("Opening command palette",null)}},{intent:S.Confirm,mode:b.PALETTE,action:()=>{let{selectedNode:e}=h();if(!e||!Pn(e))return l("Command only applicable on text nodes");if(e.props.disabled)return l("Command is not available in this context");let t=e.title;return t?(AE(t),u("Selected command",t)):u("No command selected",null)}},{intent:S.ExitCommandLine,mode:b.PALETTE,action:()=>(Tg(),u("Exiting palette",null))},{intent:S.Exit,mode:b.PALETTE,action:()=>(Tg(),u("Closed command palette",null))},{intent:S.NavPreviousItem,mode:b.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.PALETTE,action:()=>(_.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.PALETTE,action:()=>(_.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.PALETTE,action:()=>(_.navigateToNextContainer(),u("Navigating to next container",null))}];var Mg=[{intent:S.InitCommandLine,mode:b.DEFAULT,description:"[:] write command",action:()=>(N({mode:b.COMMAND_LINE}),te(""),u("Entering command line mode",null))},...Ag,...wg,{intent:S.AddItem,mode:b.DEFAULT,description:"[n] new...",action:()=>(N({mode:b.COMMAND_LINE}),te(`${E.NEW} `),u("Adding new item",null))},{intent:S.Delete,mode:b.DEFAULT,description:"[d] delete",action:()=>(N({mode:b.COMMAND_LINE}),te(`${E.DELETE} `),u("Deleting item",null))},{intent:S.Confirm,mode:b.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=h();if(!de(e?.id??"")?.length){let r=e?R.getAttachment(e.id):void 0;if(r)return Cg(r);if(e?.title===ve.DESCRIPTION)return N({mode:b.COMMAND_LINE}),te(`${E.EDIT} description `),u("Propose command",!0);if(e?.title===ve.ASSIGNEES)return N({mode:b.COMMAND_LINE}),te(`${E.ASSIGN} `),u("Propose command",!0);if(e?.title===ve.TAGS)return N({mode:b.COMMAND_LINE}),te(`${E.TAG} `),u("Propose command",!0);if(t.title===ve.DESCRIPTION&&e?.context==="TEXT")return N({mode:b.COMMAND_LINE}),te(`${E.EDIT} description `),u("Propose command",!0)}return _.enterChildNode(),u("Entering context",null)}},{intent:S.Yank,mode:b.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=h(),t=e?.title===ve.DESCRIPTION?Me.DESCRIPTION:e?.title===ve.TAGS?Me.TAGS:e?.title===ve.ASSIGNEES?Me.ASSIGNEES:Me.REF,r=Ne(E.YANK).includes(t)?t:Me.REF;return N({mode:b.COMMAND_LINE}),te(`${E.YANK} ${r}`),u("Propose command",!0)}},{intent:S.EditTitle,mode:b.DEFAULT,description:"[r] rename title",action:()=>(N({mode:b.COMMAND_LINE}),te(`${E.EDIT} title ${h().selectedNode?.title}`),u("Exiting context",null))},{intent:S.EditDescription,mode:b.DEFAULT,description:"[e] edit desc",action:()=>(N({mode:b.COMMAND_LINE}),te(`${E.EDIT} description `),u("Exiting context",null))},{intent:S.Exit,mode:b.DEFAULT,description:"[q] exit context",action:()=>(_.enterParentNode(),u("Exiting context",null))},{intent:S.NavPreviousItem,mode:b.DEFAULT,description:"[arrows/hjkl] navigate",action:()=>(_.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:S.NavNextItem,mode:b.DEFAULT,action:()=>(_.navigateToNextItem(),u("Navigating to next item",null))},{intent:S.NavToPreviousContainer,mode:b.DEFAULT,action:()=>(_.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:S.NavToNextContainer,mode:b.DEFAULT,action:()=>(_.navigateToNextContainer(),u("Navigating to next container",null))}];var TE=500,wE=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),Pg=e=>{let t=wE(e);t&&Ci(n=>(n+t).slice(0,TE))};var ME=[b.COMMAND_LINE,b.PALETTE],PE=e=>[{intent:S.MoveCursorLeft,mode:e,action:()=>(Jl(-1),u("Moving cursor left",null))},{intent:S.MoveCursorRight,mode:e,action:()=>(Jl(1),u("Moving cursor right",null))},{intent:S.MoveCursorLeftOfWord,mode:e,action:()=>(Ql("left"),u("Moving cursor left of word",null))},{intent:S.MoveCursorRightOfWord,mode:e,action:()=>(Ql("right"),u("Moving cursor right of word",null))},{intent:S.AutoCompleteCommand,mode:e,action:()=>(Ci((t,{remainder:n})=>{let r=n?t+n:t,o="";return r==="edit title "&&(o=h().selectedNode?.title??""),r+o}),u("Auto-completing command",null))},{intent:S.CaptureInput,mode:e,action:(t,{sequence:n})=>(Pg(n??""),u("Capturing input",null))},{intent:S.EraseInput,mode:e,action:()=>(Op(),u("Erasing input",null))},{intent:S.EraseInputWord,mode:e,action:()=>(_p(),u("Erasing input word",null))}],Lg=[{intent:S.Confirm,mode:b.COMMAND_LINE,action:()=>(on(),u("Executing command",null))},{intent:S.ViewHelp,mode:b.DEFAULT,action:()=>(N({mode:b.HELP}),u("Viewing help",null))},...ME.flatMap(PE),{intent:S.ExitCommandLine,mode:b.COMMAND_LINE,action:()=>(N({mode:b.DEFAULT}),u("Exiting command line",null))},{intent:S.GetLastCommandFromHistory,mode:b.COMMAND_LINE,action:()=>($p(),u("Getting last command from history",null))},{intent:S.GetNextCommandFromHistory,mode:b.COMMAND_LINE,action:()=>(Hp(),u("Getting next command from history",null))}];var Cd=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},kg=({keys:e})=>e.length===1?0:1,Dg=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(Cd).filter(r=>r!==null).sort((r,o)=>kg(r)-kg(o))};function Bg(e,t,n){let r=t[e];if(!r)return l("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let d=o[o.length-1];return!d||d.id!==n?l("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Fg=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 Nt,Nd,Ad=new Set,Td=()=>{for(let e of Ad)e()},kE=e=>(Ad.add(e),()=>Ad.delete(e));function wd(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return l("derive(): contextNodeId is missing");if(!r)return l("derive(): rootNode is missing");if(!o[r])return l("derive(): unable to find root node");let d=o[t];if(!d)return l("Unable to derive state, contextNode not found");let c=Bg(t,o,r);if(a(c))return logger.error(c.message),c;let m=c.value,{context:p}=d,f=[...Mg,...Eg[p]??[],...Lg],g=Dg(f,n),v=Fg(f),I=DE(o,s),x=I[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:d,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:v,selectedNode:x,renderedChildrenIndex:I})}var h=()=>{if(!Nt)throw new Error("State not initialized. Call initWorkspaceState() first.");return Nt},it=()=>Nt?u("Retrieved state",Nt):l("State not initialized. Call initWorkspaceState() first.");function Do(e){Nd=e;let t=Se(process.cwd()),n=!1;if(!a(t)){let s=pt(t.value);if(a(s))return l(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},mode:b.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=wd(r);return a(o)?o:(Nt=o.value,Td(),u("State initialized",null))}var br=!1,os=null;function we(e){let t=h(),n=e(t);if(br)return n.nodes!==t.nodes&&(Kn=null),os=n,Nt={...t,...n},u("State updated",null);let r=wd(n);return a(r)?l(r.message??"Unable to update state"):(Nt=r.value,Td(),u("State updated",null))}function Gs(e){if(br)return u("Joined batch",e());br=!0,os=null,Kn=new Set;let t=()=>{let n=os;if(br=!1,os=null,n===null)return null;let r=wd(n);return a(r)?l(r.message??"Unable to update state"):(Nt=r.value,Td(),u("State updated",null))};try{let n=e(),r=t();return r&&a(r)?l(r.message):u("State updated",n)}finally{br&&t()}}var xm=()=>br,N=e=>we(t=>({...t,...e}));function xr(e,t,n){if(!br)return we(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=h(),o=r[e]??{};if(e==="nodes"){let i=o[t],d=n;i?.parentNodeId&&Kn?.add(i.parentNodeId),d.parentNodeId&&Kn?.add(d.parentNodeId)}o[t]=n;let s={...r,[e]:o};return os=s,Nt={...r,...s},u("State updated",null)}var J=()=>LE(kE,h,h),Kn=null,Og=null,DE=(e,t)=>{let n=Nt?.renderedChildrenIndex,r=n!==void 0&&Kn!==null&&e===Og&&t.length===0&&Nt?.filters.length===0,o;if(r){o={...n};let s=hm(e,Kn);for(let i of Kn){let d=s[i];d?o[i]=d:delete o[i]}}else o=gm(e,t);return Og=e,Kn=new Set,o},X=e=>h()?.renderedChildrenIndex[e]??[],jt=()=>Nd?Do(Nd):l("Cannot reset state: no initial workspace found"),It=()=>Nt!==void 0;var ut=(e,t)=>{let{nodes:n}=h(),r=n[e];if(!r)return l("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return u("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return l(`No ancestor found for context: ${t}`)},Md=(e,t)=>{let{nodes:n}=h(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},qn=(e,t)=>e?e.readonly?l({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:l("Node not found"),R={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.userId&&n.userId!==t)return l("Contributor is already linked to another user");let r={...n,userId:t},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){we(t=>{let n={...t.nodes};return delete n[e],{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create comment, missing issue");if(!B(t))return l("Can only comment on issues");let n=xr("comments",e.id,{...e,deleted:!1});return a(n)?l("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return l("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return l("Unable to edit comment, missing issue");if(!B(r))return l("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=xr("comments",e,o);return a(s)?l("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return l("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=xr("comments",e,n);return a(r)?l("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return h().comments?.[e]},getCommentsByIssue(e){return Object.values(h().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return l("Unable to create attachment, missing issue");if(!B(t))return l("Can only attach to issues");let n=we(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?l("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return l("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=we(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?l("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return h().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(h().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(h().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=h(),r=n[e];if(!r)return l("Edit target node not found");let o=qn(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 l("Rename target node not found");let r=qn(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=h();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=h();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return de(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=h(),o=this.getNode(e),s=this.getNode(t);if(!o)return l("Node not found");if(!s)return l("Target parent not found");if(r===e)return l("Cannot move root node");if(e===t)return l("Cannot move node into itself");let i=qn(o,"move");if(i)return i;if(Md(t,e))return l("Cannot move node into its own descendant");let d={...o,parentNodeId:t,rank:n};return this.updateNode(d),u("Moved node successfully",d)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=h(),o=this.getNode(e);if(!o)return l("Node not found");if(r===e)return l("Cannot delete root node");let s=qn(o,"delete");if(s)return s;let i=new Set,d=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of de(p.id))d(f.id)}};d(e);let c={...structuredClone(t)};for(let m of i){if(!c[m])return l("Unable to locate node to delete");c[m]={...c[m],isDeleted:!0}}return n?(N({nodes:c}),u("Successfully tomb stoned",o)):l("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return l("Contributor not found");let n={...t,name:js,tombstoned:!0},r=we(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?l("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");if(n.tombstoned)return l("Cannot rename a removed contributor");let r={...n,name:t},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return l("Contributor not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?l("Unable to restore contributor"):u("Restored contributor",r)},createContributor(e){let t=we(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?l("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return l("Unable to assign contributor, missing contributor");if(!r)return l("Unable to assign contributor, missing target");let o=qn(r,"edit");if(o)return o;if(!B(r))return l("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return l("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),u("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return l("Unable to unassign, missing contributor");if(!r)return l("Unable to unassign, missing target");let o=qn(r,"edit");if(o)return o;if(!B(r))return l("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(d=>d!==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 l("Unable to add tag, missing tag");if(!r)return l("Unable to add tag, missing target");let o=qn(r,"edit");if(o)return o;if(!B(r))return l("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return l("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),u("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return l("Unable to remove tag, missing tag");if(!r)return l("Unable to remove tag, missing target");let o=qn(r,"edit");if(o)return o;if(!B(r))return l("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(d=>d!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return l("Tag not found");let n={...t,tombstoned:!0},r=we(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?l("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return l("Tag not found");let r={...n,name:t,tombstoned:!1},o=we(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?l("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=we(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?l("Could not create tag"):u("Tag created",e)},createNode(e){let t=xr("nodes",e.id,e);return a(t)?l("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return l("Failed to locate node");let n={...t,readonly:!0},r=xr("nodes",e,n);return a(r)?l(r.message):u("Locked node",n)},updateNode(e){let t=xr("nodes",e.id,e);return a(t)?t:u("Updated node",e)},getContributor(e){return h().contributors[e]},getTag(e){let t=h().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return h().tags[e]},getTags(){return Object.values(h().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return h().nodes[e]},getSiblings(e){return de(e)}};var BE=(e,t)=>e+" ".repeat(Math.max(0,t-_g(e))),FE=(e,t)=>" ".repeat(Math.max(0,t-_g(e)))+e,Qi=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),OE=(e,t)=>t?e<t?"up":e>t?"down":null:null,_E=(e,t)=>{let n=R.getNode(e.payload.parent),r=n?Yn.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=OE(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Ug=e=>`${Math.max(1,Math.round(e/1024))} KB`,jg=e=>R.getAttachment(e)?.name??"",UE=e=>{switch(e.action){case"add.issue.tag":{let t=h().tags[e.payload.tag];return t?Yn.bgHex(ce(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?Yn.bgHex(ce(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Yn.hex(ce(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?Yn.hex(ce(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"add.issue.attachment":return`"${e.payload.name}" ${Yn.dim(`(${Ug(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=jg(e.payload.id);return t?`"${t}"`:""}default:return""}},jE=e=>{let t=to(Ce(e));return Yn.gray(FE(t,8))},$E=12,HE=e=>BE(`${e}`,$E),WE=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=h().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=h().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=h().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"move.node":{let t=R.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Ug(e.payload.bytes)})`;case"delete.issue.attachment":{let t=jg(e.payload.id);return t?`"${t}"`:""}default:return""}},zi=e=>[Qi(e.action),WE(e)].filter(Boolean).join(" "),$g=(e,t)=>{let n=jE(e.id),r=HE(e.userName),o=Yn.dim("\u203A"),s=e.action==="move.node"?_E(e,t):[Qi(e.action),UE(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var GE=e=>De(e,"comments"),VE=e=>De(e,"description"),zE=e=>De(e,"assignees"),KE=e=>De(e,"tags"),qE=e=>De(e,"history"),YE=e=>De(e,"attachments"),Zi=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let d=R.getNode(e);if(!d){let p=R.createNode({...be.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(p)?p:u("Virtual field created",void 0)}if(!gt(d))return l(`Existing virtual node ${e} is not a field`);if(!(d.title!==t||d.parentNodeId!==n||d.rank!==r||d.props.value!==o||d.readonly!==s||d.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=R.updateNode({...d,title:t,parentNodeId:n,rank:r,props:{...d.props,value:o},readonly:s,childRenderAxis:i});return a(m)?m:u("Virtual field updated",void 0)},Hg=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=R.getNode(e);if(!i){let m=R.createNode({...be.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:u("Virtual field list created",void 0)}if(!wo(i))return l(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return u("Virtual field list unchanged",void 0);let c=R.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(c)?c:u("Virtual field list updated",void 0)},Ou=e=>{let t=xt(qt/4n),n=xt(qt/2n),r=xt(qt*3n/4n),o=xt(qt*7n/8n),s=xt(qt*15n/16n),i=xt(qt*13n/16n);if(a(t))return t;if(a(n))return n;if(a(r))return r;if(a(o))return o;if(a(s))return s;if(a(i))return i;let d=Zi({id:VE(e.id),name:ve.DESCRIPTION,parentNodeId:e.id,rank:t.value,value:e.props.description??"",childRenderAxis:"vertical"});if(a(d))return d;let c=Hg({id:zE(e.id),name:ve.ASSIGNEES,parentNodeId:e.id,rank:n.value,readonly:!0});if(a(c))return c;let m=Hg({id:KE(e.id),name:ve.TAGS,parentNodeId:e.id,rank:r.value,readonly:!0});if(a(m))return m;let p=Zi({id:GE(e.id),name:ve.COMMENTS,parentNodeId:e.id,rank:o.value,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(p))return p;let f=Zi({id:YE(e.id),name:ve.ATTACHMENTS,parentNodeId:e.id,rank:s.value,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(f))return f;let g=Zi({id:qE(e.id),name:ve.HISTORY,parentNodeId:e.id,rank:i.value,value:XE(e),readonly:!0,childRenderAxis:"vertical"});return a(g)?g:u("Ticket virtual nodes materialized",void 0)},XE=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=>$g(r,n.get(r.action)??[])).join(`
|
|
86
|
-
`)},Wg=!0,Gg=e=>{Wg=e},cl=()=>Wg;import AC from"node:http";import Ar from"node:path";import{fileURLToPath as TC}from"node:url";var JE=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},Pd=(e,t)=>{let n=[];for(let r of e){let o=JE(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=Mn(r);n.push({laneId:o,enteredAt:s===null?t:To(s)})}return n},ea=(e,t)=>Pd(e,t).at(-1)?.enteredAt??t;import{existsSync as Bd}from"node:fs";import{chmod as Fd}from"node:fs/promises";import ta from"node:path";import{chmodSync as QE,existsSync as ZE,lstatSync as eR,mkdirSync as tR}from"node:fs";import nR from"node:os";import rR from"node:path";var Ld=(...e)=>{let t=rR.join(nR.tmpdir(),"epiq",...e);try{return ZE(t)&&eR(t).isSymbolicLink()?l(`Refusing to write through a symlink at ${t}`):(tR(t,{recursive:!0,mode:448}),QE(t,448),u("Prepared private temp dir",t))}catch(n){return l(`Unable to prepare ${t}: ${n instanceof Error?n.message:String(n)}`)}};var oR=new Set(["create.tag","create.contributor","add.swimlane"]),sR=e=>{let t=new Map;for(let n of e){if(!oR.has(n.action))continue;let r=n.payload;r?.id&&r.name&&t.set(r.id,r.name)}return t},iR=e=>{let t=new Map,n=new Map;for(let r of e){let o=r.payload;!o?.id||!o.parent||(r.action==="move.node"&&t.set(r.id,n.get(o.id)),n.set(o.id,o.parent))}return t},zg=e=>{let t=e.payload;return e.action==="tombstone.tag"||e.action==="restore.tag"?t?.id:t?.tag},aR=e=>{let t=new Set,n=new Map;for(let r of e){let o=r.payload,s=o?.id;s&&(r.action==="add.issue"&&t.add(s),o.parent&&n.set(s,o.parent))}return{issueIds:t,parentById:n}},lR=(e,{issueIds:t,parentById:n})=>{let r=e.payload;if(r?.issue)return r.issue;let o=new Set,s=r?.id;for(;s!==void 0&&!o.has(s);){if(t.has(s))return s;o.add(s),s=n.get(s)}return null},dR=new Set(["add.issue","move.node","close.issue","reopen.issue"]),cR=(e,t)=>{let n=new Map;return e.map((r,o)=>{let s=t[o]??null;if(s===null)return{lane:null,laneBefore:null};let i=r.payload,d=null;if(dR.has(r.action)&&i?.id===s&&i.parent){let c=n.get(s);c!==void 0&&c!==i.parent&&(d=c),n.set(s,i.parent)}return{lane:n.get(s)??null,laneBefore:d}})},Vg=90,uR=e=>{let t=e.trim().split(`
|
|
87
|
-
`)[0]?.trim()??"";return t.length>Vg?`${t.slice(0,Vg).trimEnd()}\u2026`:t},mR=(e,t,n)=>{let r=e.payload,o=zg(e),s=e.action?Qi(e.action):"";if(r?.md!==void 0){let d=uR(r.md);return d?`${s}: ${d}`:s}if(e.action==="move.node"&&r?.parent){let d=t.get(r.parent);return d?n.get(e.id)===r.parent?`Moved within ${d}`:`Moved to ${d}`:s}let i=o!==void 0?t.get(o)??"":r?.assignee!==void 0?t.get(r.assignee)??"":r?.name!==void 0?`"${r.name}"`:"";return[s,i].filter(Boolean).join(" ")},kd=(e,t,n)=>{if(!e)return null;let r=t.get(e)??n??e;return{id:e,name:r,color:ce(r)}},pR=(e,t)=>{let n=e.payload;return{actor:kd(e.userId,t,e.userName),tag:kd(zg(e),t),assignee:kd(n?.assignee,t)}},Kg=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let d=o.action==="close.issue"?r(i):null,c=s.parent??s.issue;return c&&t.set(i,c),d!==null?d:n.has(i)?i:r(i)})},qg=(e,t)=>{let n=Kg(e);return e.filter((r,o)=>n[o]===t)},fR=e=>{let t=sR(e),n=iR(e),r=aR(e),o=e.map(m=>lR(m,r)),s=cR(e,o),i=Kg(e),d=_r(e.map(m=>Mn(m)));return e.flatMap((m,p)=>{let f=d[p]??null;return f===null?[]:[{id:m.id,t:f,action:m.action,label:mR(m,t,n),issue:o[p]??null,...s[p],board:i[p]??null,...pR(m,t)}]}).sort((m,p)=>m.t-p.t)},gR=e=>{let t=new Map;for(let r of e){if(r.issue===null||r.lane===null)continue;let o=t.get(r.issue)??[],s=o[o.length-1];(s===void 0||s.lane!==r.lane)&&(o.push({t:r.t,lane:r.lane,board:r.board}),t.set(r.issue,o))}let n=new Map;for(let[r,o]of t){let s=o[o.length-1];n.set(r,{changes:o,from:o[0].t,closedFrom:s.lane===ie?s.t:null})}return n},hR=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return e[n-1]},Yg=(e,t,n)=>{let r={};for(let[o,s]of e){if(s.from>=t||s.closedFrom!==null&&s.closedFrom<t)continue;let i=hR(s.changes,t);i===void 0||i.lane===ie||n&&i.board!==n||(r[o]=i.lane)}return r},yR=e=>{let t={};for(let n of e){let r=n.payload;!r?.id||r.name===void 0||(n.action==="add.swimlane"||n.action==="edit.title"&&r.id in t)&&(t[r.id]=r.name)}return t},ss=null,Xg=e=>{let t=Yt(e);if(ss&&ss.root===e&&ss.signature===t)return u("Timeline entries, cached",ss.index);let n=Fn(e);if(a(n))return l(n.message);let r=fR(n.value),o={entries:r,lanes:gR(r),laneNames:yR(n.value)};return ss={root:e,signature:t,index:o},u("Timeline entries, built",o)};var Jg=1e5,vR=2e4,na=null,Qg=Promise.resolve(),Xn=e=>{let t=Qg.then(e,e);return Qg=t.then(()=>{},()=>{}),t},ra=e=>{let t=Se(e??process.cwd());return a(t)?l(t.message):u("Resolved Epiq repo root",t.value)},oa=e=>{let t=ra(e);return a(t)?t:fe({repoRoot:t.value})},Ve=()=>{if(!It())return{mode:"live",asOfTime:null};let{timeMode:e}=h();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:na}},Zg=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return n},oh=async(e={})=>{let t=oa(e.repoRoot);if(a(t))return l(t.message);let n=Xg(t.value);if(a(n))return l(n.message);let r=n.value.entries,o=Date.now(),s=e.end??o,i=e.start??r[0]?.t??s;if(s<=i)return u("Empty time window",{bucketMs:0,buckets:[],events:[],lanesAtStart:{},laneNames:n.value.laneNames,closedLane:ie,earliest:i,latest:s});let d=Zg(r,i),c=Zg(r,s),m=r.slice(d,c).filter(I=>!e.boardId||I.board===e.boardId).map(({board:I,...x})=>x),p=m.map(I=>I.t),f=Math.max(1,Math.ceil((s-i)/Jg)),g=new Map;for(let I of p){let x=Math.min(Jg-1,Math.floor((I-i)/f)),C=i+x*f;g.set(C,(g.get(C)??0)+1)}let v=[...g.entries()].sort(([I],[x])=>I-x).map(([I,x])=>({t:I,count:x}));return u("Computed event timeline",{bucketMs:f,buckets:v,events:m.length>vR?[]:m,lanesAtStart:Yg(n.value.lanes,i,e.boardId),laneNames:n.value.laneNames,closedLane:ie,earliest:i,latest:s})},is="",eh="",bR=5e3,oo=null;var Od=async(e={})=>{let t=ra(e.repoRoot);if(a(t))return l(t.message);let n=pt(t.value);if(a(n))return l(n.message);let r=e.start===void 0&&e.end===void 0;if(r&&oo&&oo.repoRoot===t.value&&oo.stateBranch===n.value.stateBranch&&Date.now()-oo.fetchedAt<bR)return u("Computed commit timeline",oo.result);let o=await U({cwd:t.value,args:["log","--branches","--not",n.value.stateBranch,...e.start!==void 0?[`--since=@${Math.floor(e.start/1e3)}`]:[],...e.end!==void 0?[`--until=@${Math.floor(e.end/1e3)}`]:[],"--shortstat",`--format=${eh}%H${is}%at${is}%an${is}%s`]});if(a(o))return l(o.message);let s=o.value.stdout.split(eh).filter(i=>i.trim().length>0).map(i=>{let[d,...c]=i.split(`
|
|
88
|
-
`),
|
|
89
|
-
`)
|
|
90
|
-
`).filter(d=>d!==""),o=r.filter(d=>!Dd.test(d)&&!rh.test(d));if(o.length>0)return l(`Could not parse ${o.length} line(s) of "git diff --raw --numstat" output, e.g. "${o[0]}"`);let s=new Map;for(let d of r){let c=rh.exec(d);c&&s.set(c[3]??"",{insertions:c[1]==="-"?0:Number(c[1]),deletions:c[2]==="-"?0:Number(c[2])})}let i=r.filter(d=>Dd.test(d)).map(d=>{let c=Dd.exec(d),m=c?.[1]??"",p=c?.[2]??"",f=c?.[3]??"";return{path:f,beforeBlob:nh(m)?null:m,afterBlob:nh(p)?null:p,...s.get(f)??{insertions:0,deletions:0}}});return i.length===0?l("No changed files found for this commit"):u("Listed changed files with blob hashes",i)},ah=async e=>{if(!sh(e.sha))return l("Invalid commit sha");let t=ra(e.repoRoot);if(a(t))return l(t.message);let n=t.value,r=await NR(n,e.sha);if(a(r))return l(r.message);let o=r.value;if(o.length>CR)return l(`Commit touches ${o.length} files \u2014 too many to show as a diff`);let s=o.flatMap(m=>[m.beforeBlob,m.afterBlob].filter(p=>p!==null)),i=await ks(s,n);if(a(i))return l(i.message);let d=i.value,c=o.map(m=>({path:m.path,before:m.beforeBlob?d.get(m.beforeBlob)??"":"",after:m.afterBlob?d.get(m.afterBlob)??"":"",insertions:m.insertions,deletions:m.deletions}));return u("Loaded commit diff",{sha:e.sha,files:c})},lh=e=>{let t=Fn(e);if(a(t))return l(t.message);let n=jt();if(a(n))return l(n.message);na=null;let r=Bt(t.value),{fatal:o,skipped:s}=vn(r);return o.length>0?l(o.map(i=>i.message).join(", ")):(bn(s),N({readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},AR=(e,t)=>{na=null;let n=lh(e);return a(n)?l(`${t} (recovery to live also failed: ${n.message})`):l(t)},_d=e=>Xn(async()=>{let t=oa(e.repoRoot);if(a(t))return l(t.message);let n=Qs(t.value,e.targetTime);if(a(n))return l(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=jt();if(a(s))return s;let i=Bt(r),{fatal:d,skipped:c}=vn(i);return d.length>0?AR(t.value,d.map(m=>m.message).join(", ")):(bn(c),N({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),na=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),dh=async e=>{let t=oa(e.repoRoot);if(a(t))return l(t.message);let n=Zs(t.value);if(a(n))return l(n.message);let r=n.value.get(e.eventId)??null;return r===null?l("Event not found in the log"):_d({repoRoot:e.repoRoot,targetTime:r+1})},ch=(e={})=>Xn(async()=>{let t=oa(e.repoRoot);if(a(t))return l(t.message);let n=lh(t.value);return a(n)?l(n.message):u("Returned to live state",!0)});import TR from"node:fs";var Ir=e=>{let t=Se(e??process.cwd());return a(t)?l(t.message):u("Resolved Epiq repo root",t.value)},ia=null,Q=async(e,t)=>{let n=Ir(e);if(a(n))return n;let r=fe({repoRoot:n.value});if(a(r))return l(r.message);let o=Gt(n.value);if(a(o))return l(o.message);if(!(ia!==null&&ia.repoRoot===n.value&&ia.stateBranchRoot===r.value&&TR.existsSync(or(r.value)))){let p=await Uo({repoRoot:n.value,stateBranchName:o.value});if(a(p))return l(p.message);let f=await On({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(f))return l(f.message);ia={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let p=await U({cwd:r.value,args:["pull","--ff-only"]});a(p)&&z.info(3,p.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},d=Yt(r.value);if(qu(r.value)===d&&It()&&Ve().mode==="live")return u("Booted Epiq state, unchanged",i);let c=St(r.value);if(a(c))return l(c.message);let m=Ot(c.value.events,c.value.unreadable);return a(m)?l(m.message):(Yu(r.value,d),u("Booted Epiq state",i))},Z=()=>{let e=bt();return a(e)?l(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):l("Unable to retrieve user name"):l("Unable to retrieve user id")},V=()=>{let e=it();return a(e)?l(e.message):e};var so=e=>(e.props.tags??[]).map(t=>R.getTag(t)).filter(t=>t!=null).map(t=>({id:t.id,name:t.name,color:ce(t.name)}));var io=e=>(e.props.assignees??[]).map(t=>R.getContributor(t)).filter(t=>t!=null).map(({id:t,name:n})=>({id:t,name:n,color:ce(n)}));import wR from"node:fs";import MR from"node:path";import{ulid as jd}from"ulid";var _e=e=>{let t=V();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Issue not found"):B(n)?n.readonly?l("Issue is readonly"):u("Found issue",n):l("Target must be an issue")},Jn=e=>{let t=V();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Swimlane not found"):Kt(n)?n.readonly?l("Swimlane is readonly"):u("Found swimlane",n):l("Target must be a swimlane")},Ud=e=>{let t=V();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?l("Board not found"):Ln(n)?n.readonly?l("Board is readonly"):u("Found board",n):l("Target must be a board")};var PR=e=>{if(e.filePath)try{return u("Read attachment file",{data:wR.readFileSync(e.filePath),name:e.name??MR.basename(e.filePath)})}catch(t){return l(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?u("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):l("Provide either filePath or dataBase64")},aa=()=>{let e=bt();return a(e)?en:e.value.attachmentMaxKb??en},$d=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=PR(e);if(a(s))return s;let i=yp(t.value.stateBranchRoot,s.value.data,aa());if(a(i))return i;let d=ye(s.value.name).trim()||"image",c=jd(),m={id:jd(),...n.value,action:"add.issue.attachment",payload:{id:c,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:d,bytes:i.value.bytes}},p=D([m],t.value.stateBranchRoot);if(a(p))return l(p.message);let f=fr(i.value.hash,i.value.ext);return u("Added issue attachment",{id:c,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Wl(d,f)})},Hd=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return l("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return l("You can only delete your own attachments");let s=_e(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let d={id:jd(),...n.value,action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},c=D([d],t.value.stateBranchRoot);return a(c)?l(c.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},Wd=async e=>{let t=await Q(e.repoRoot,{pull:!1});return a(t)?t:vp(t.value.stateBranchRoot,e.fileName,aa())};var LR=365*24*60*60*1e3,Sr=()=>{let e=V();if(a(e))return e;let t=Ve(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(x=>Ln(x)&&!x.isDeleted),s=Date.now()-LR,i=new Map,d=new Map;for(let x of r)if(!x.isDeleted){if(Kt(x)&&x.parentNodeId){let C=i.get(x.parentNodeId)??[];C.push(x),i.set(x.parentNodeId,C)}if(B(x)&&x.parentNodeId){if(x.parentNodeId===ie&&Ce(x.id)<s)continue;let C=d.get(x.parentNodeId)??[];C.push(x),d.set(x.parentNodeId,C)}}let c=new Set;for(let x of d.values())for(let C of x)c.add(C.id);let m=bt();if(a(m))return m;let p={},f=R.getCommentsGroupedByIssue();for(let x of r.filter(B))x.isDeleted||!c.has(x.id)||(p[x.id]=(f.get(x.id)??[]).map(C=>{let A=R.getContributor(C.authorId);return{id:C.id,issueId:C.issue,body:C.md,author:{id:C.authorId,name:A?.name??"Unknown",color:ce(A?.name??C.authorId??"Unknown")},createdAt:Ce(C.id)}}));let g=new Map;for(let x of e.value.eventLog)x.action==="add.issue.attachment"&&g.set(x.payload.id,x.payload.author);let v={},I=R.getAttachmentsGroupedByIssue();for(let x of r.filter(B))x.isDeleted||!c.has(x.id)||(v[x.id]=(I.get(x.id)??[]).map(C=>({id:C.id,issueId:C.issue,name:C.name,fileName:fr(C.hash,C.ext),bytes:C.bytes,createdAt:Ce(C.id),canDelete:g.get(C.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((x,C)=>x.rank.localeCompare(C.rank)).map(x=>({id:x.id,ref:O(x.id),title:x.title,readonly:!!x.readonly||n,swimlanes:(i.get(x.id)??[]).sort((C,A)=>C.rank.localeCompare(A.rank)).map(C=>({id:C.id,title:C.title,readonly:!!C.readonly||n,issues:(d.get(C.id)??[]).sort((A,M)=>A.rank.localeCompare(M.rank)).map(A=>({id:A.id,ref:O(A.id),title:ye(A.title),description:A.props.description??"",createdAt:Ce(A.id),enteredLaneAt:ea(A.log??[],Ce(A.id)),readonly:!!A.readonly||n,tags:so(A),assignees:io(A),parentNodeId:A.parentNodeId,isClosed:A.parentNodeId===ie})),parentNodeId:C.parentNodeId}))})),tags:R.getTags().map(x=>({...x,color:ce(x.name)})),contributors:Object.values(e.value.contributors).map(x=>({...x,color:ce(x.name)})),user:{name:m.value.userName??"",id:m.value.userId??"",color:ce(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:v,attachmentMaxKb:aa(),timeTravel:t})},uh=null,kR=e=>{if(e===uh)return;let t=fi({root:e});if(a(t)){z.info(t.message);return}uh=e},At=async(e={})=>{if(Ve().mode!=="live")return Sr();let t=await Q(e.repoRoot,{pull:!1});return a(t)?t:(kR(t.value.repoRoot),Sr())},as=async(e={})=>{Ur();let t=Ir(e.repoRoot);if(a(t))return l("Sync failed");let n=Z();if(a(n))return n;let r=await ci({cwd:t.value,ownEventFileName:lr(n.value)});return a(r)?(Al(r.message),r):(ur(),u("Synced",r.value))};import{ulid as Tt}from"ulid";var ls=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):l("Provide issueId or issueIds")},ao=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?u(r,t):l(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},Gd=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:O(r),reason:o.message}):n.done.push({id:r,ref:O(r)})}return n};var fh=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Kd(e){let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=V();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(B).filter(d=>!d.isDeleted).filter(d=>e.includeClosed||d.parentNodeId!==ie).filter(d=>e.boardId?(d.parentNodeId?r[d.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(d=>!e.swimlaneId||d.parentNodeId===e.swimlaneId).filter(d=>!e.tag||so(d).some(c=>fh(c.name,e.tag))).filter(d=>!e.assignee||io(d).some(c=>fh(c.name,e.assignee))).filter(d=>!o||d.title.toLowerCase().includes(o)||(d.props.description??"").toLowerCase().includes(o)),i=d=>ye((d.parentNodeId?r[d.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(d=>({id:d.id,ref:O(d.id),title:ye(d.title),swimlane:i(d),tags:so(d).map(c=>c.name),assignees:io(d).map(c=>c.name)}))):u("Listed issues",s.map(d=>({id:d.id,ref:O(d.id),title:ye(d.title),description:d.props.description??"",createdAt:Ce(d.id),enteredLaneAt:ea(d.log??[],Ce(d.id)),parentNodeId:d.parentNodeId,isClosed:d.parentNodeId===ie,readonly:!!d.readonly,tags:so(d),assignees:io(d)})))}var qd=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=ye(e.title);if(!o)return l("Issue title cannot be empty");let s=e.description??"",i=Qe("Issue title",o,300)??Qe("Issue description",s,2e4);if(i)return l(i);if((e.tagNames?.length??0)>20)return l(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return l(`Cannot set more than ${20} assignees at once`);let d=Jn(e.parentId);if(a(d))return d;let c=In(e.parentId,n.value,t.value.stateBranchRoot);if(a(c))return c;let m=Ui({name:o,parent:e.parentId,user:n.value,rank:c.value});if(a(m))return m;let p=[...m.value],f=p.find(x=>x.action==="add.issue")?.payload.id;if(!f)return l("Unable to determine created issue id");s&&p.push({id:Tt(),...n.value,action:"edit.description",payload:{id:f,md:s}});let g=[];for(let x of e.tagNames??[]){let C=ye(x).trim();if(!C||g.some(L=>L.name===C))continue;let A=Qe("Tag name",C,60);if(A)return l(A);let M=R.findTagByName(C),w=M?.id??Tt();M||p.push({id:Tt(),...n.value,action:"create.tag",payload:{id:w,name:C}}),p.push({id:Tt(),...n.value,action:"add.issue.tag",payload:{id:f,tag:w}}),g.push({id:w,name:C})}let v=[];for(let x of e.assigneeNames??[]){let C=ye(x).trim();if(!C||v.some(L=>L.name===C))continue;let A=Qe("Assignee name",C,80);if(A)return l(A);let M=Object.values(r.value.contributors).find(L=>L.name===C),w=M?.id??Tt();M||p.push({id:Tt(),...n.value,action:"create.contributor",payload:{id:w,name:C}}),p.push({id:Tt(),...n.value,action:"add.issue.assignee",payload:{id:f,assignee:w}}),v.push({id:w,name:C})}let I=D(p,t.value.stateBranchRoot);return a(I)?l(I.message):u("Created issue",{id:f,ref:O(f),title:o,parentId:e.parentId,description:s,tags:g,assignees:v})},DR=(e,t,n)=>{let r=_e(e);if(a(r))return r;let o=Xt(ie,e,{at:"end"},t,n);if(a(o))return o;let s={id:Tt(),...t,action:"close.issue",payload:{id:e,parent:ie,rank:o.value}},i=D([s],n);return a(i)?l(i.message):u("Closed issue",{id:e,ref:O(e)})};async function Yd(e){let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=ls(e);if(a(r))return r;let o=s=>DR(s,n.value,t.value.stateBranchRoot);return e.issueIds?ao("Closed",Gd(r.value,o)):o(r.value[0])}var Xd=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o||o.isDeleted)return l("Issue not found");if(!B(o))return l("Target must be an issue");if(o.parentNodeId!==ie)return l("Issue is not closed");let s=Ki(o);if(!s)return l("Unable to resolve previous parent from issue history");if(s===ie)return l("Previous parent resolves to closed swimlane");let i=Jn(s);if(a(i))return i;let d=i.value,c=Xt(d.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(c))return c;let m={id:Tt(),...n.value,action:"reopen.issue",payload:{id:o.id,parent:d.id,rank:c.value}},p=D([m],t.value.stateBranchRoot);return a(p)?l(p.message):u("Reopened issue",{id:o.id,ref:O(o.id),parentId:d.id})},BR=(e,t,n,r)=>{let o=_e(e);if(a(o))return o;let s=Jn(t.parentId);if(a(s))return s;let i=Xt(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let d={id:Tt(),...n,action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},c=D([d],r);return a(c)?l(c.message):u("Moved issue",{id:e,ref:O(e),parentId:t.parentId})};async function Jd(e){let t=Ir(e.repoRoot);if(a(t))return t;let n=Z();if(a(n))return n;let r=fe({repoRoot:t.value});if(a(r))return r;let o=St(r.value);if(a(o))return o;let s=Ot(o.value.events,o.value.unreadable);if(a(s))return s;let i=ls(e);if(a(i))return i;let d=c=>BR(c,e,n.value,r.value);return e.issueIds?ao("Moved",Gd(i.value,d)):d(i.value[0])}var Qd=e=>{let t=V();if(a(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:Ce(r.id),action:r.action,label:zi(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:{id:r.userId,name:r.userName,color:ce(r.userName)}}))):l("Issue not found")},Zd=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=o.value,i=Qe("Issue description",e.description,2e4);if(i)return l(i);let d=s.props.description??"";if(d===e.description)return u("No changes made",{id:e.issueId,ref:O(e.issueId),description:d});let c={id:Tt(),...n.value,action:"edit.description",payload:{id:e.issueId,md:e.description}},m=D([c],t.value.stateBranchRoot);return a(m)?l(m.message):u("Edited issue description",{id:e.issueId,ref:O(e.issueId),description:e.description})},ec=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=o.value,i=ye(e.title);if(!i.trim())return l("Issue title cannot be empty");let d=Qe("Issue title",i,300);if(d)return l(d);if(s.title===i)return u("No changes made",{id:e.issueId,ref:O(e.issueId),title:i});let c={id:Tt(),...n.value,action:"edit.title",payload:{id:e.issueId,name:i}},m=D([c],t.value.stateBranchRoot);return a(m)?l(m.message):u("Edited issue title",{id:e.issueId,ref:O(e.issueId),title:i})};import{ulid as Qn}from"ulid";var tc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.nodes[r.value.rootNodeId];if(!o)return l("Workspace not found");if(Ve().mode!=="live")return l("Cannot add a board while time travelling");let s=ye(e.title);if(!s.trim())return l("Board title cannot be empty");let i=Qe("Board title",s,300);if(i)return l(i);let d=In(o.id,n.value,t.value.stateBranchRoot);if(a(d))return d;let c=Qn(),m={id:Qn(),...n.value,action:"add.board",payload:{id:c,name:s,parent:o.id,rank:d.value}},p=D([m],t.value.stateBranchRoot);return a(p)?l(p.message):u("Created board",{id:c,ref:O(c),title:s})},nc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o||o.isDeleted)return l("Board not found");if(!Ln(o))return l("Edit target must be a board");if(o.readonly)return l("Cannot edit readonly board");if(Ve().mode!=="live")return l("Cannot rename a board while time travelling");let s=ye(e.title);if(!s.trim())return l("Board title cannot be empty");let i=Qe("Board title",s,300);if(i)return l(i);if(o.title===s)return u("No changes made",{id:e.boardId,ref:O(e.boardId),title:s});let d={id:Qn(),...n.value,action:"edit.title",payload:{id:e.boardId,name:s}},c=D([d],t.value.stateBranchRoot);return a(c)?l(c.message):u("Edited board title",{id:e.boardId,ref:O(e.boardId),title:s})};var rc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=Ud(e.boardId);if(a(o))return o;if(Ve().mode!=="live")return l("Cannot add a swimlane while time travelling");let s=ye(e.title);if(!s.trim())return l("Swimlane title cannot be empty");let i=Qe("Swimlane title",s,300);if(i)return l(i);let d=In(e.boardId,n.value,t.value.stateBranchRoot);if(a(d))return d;let c=Qn(),m={id:Qn(),...n.value,action:"add.swimlane",payload:{id:c,name:s,parent:e.boardId,rank:d.value}},p=D([m],t.value.stateBranchRoot);return a(p)?l(p.message):u("Created swimlane",{id:c,ref:O(c),title:s,boardId:e.boardId})},oc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=Jn(e.swimlaneId);if(a(o))return o;let s=o.value,i=ye(e.title);if(!i.trim())return l("Swimlane title cannot be empty");let d=Qe("Swimlane title",i,300);if(d)return l(d);if(s.title===i)return u("No changes made",{id:e.swimlaneId,ref:O(e.swimlaneId),title:i});let c={id:Qn(),...n.value,action:"edit.title",payload:{id:e.swimlaneId,name:i}},m=D([c],t.value.stateBranchRoot);return a(m)?l(m.message):u("Edited swimlane title",{id:e.swimlaneId,ref:O(e.swimlaneId),title:i})},sc=async e=>{let t=Ir(e.repoRoot);if(a(t))return t;let n=Z();if(a(n))return n;let r=fe({repoRoot:t.value});if(a(r))return r;let o=St(r.value);if(a(o))return o;let s=Ot(o.value.events,o.value.unreadable);if(a(s))return s;let i=Jn(e.swimlaneId);if(a(i))return i;let d=Ud(e.boardId);if(a(d))return d;let c=Xt(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(c))return c;let m={id:Qn(),...n.value,action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:c.value}},p=D([m],r.value);return a(p)?l(p.message):u("Moved swimlane",{id:e.swimlaneId,ref:O(e.swimlaneId),boardId:e.boardId})},ic=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=Jn(e.swimlaneId);if(a(o))return o;let s={id:Qn(),...n.value,action:"delete.node",payload:{id:e.swimlaneId}},i=D([s],t.value.stateBranchRoot);return a(i)?l(i.message):u("Deleted swimlane",{id:e.swimlaneId,ref:O(e.swimlaneId)})};import{ulid as ds}from"ulid";async function ac(e){let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=ls(e);if(a(r))return r;let o=ye(e.tagName).trim();if(!o)return l("Tag name cannot be empty");let s=Qe("Tag name",o,60);if(s)return l(s);let i={done:[],failed:[]};for(let v of r.value){let I=_e(v);a(I)?i.failed.push({id:v,ref:O(v),reason:I.message}):i.done.push({id:v,ref:O(v)})}if(!e.issueIds&&i.failed[0])return l(i.failed[0].reason);if(i.done.length===0)return l(ao("Tagged",i).message);let d=R.findTagByName(o),c=d?.id??ds(),m=[...d?[]:[{id:ds(),...n.value,action:"create.tag",payload:{id:c,name:o}}],...i.done.map(({id:v})=>({id:ds(),...n.value,action:"add.issue.tag",payload:{id:v,tag:c}}))],p=D(m,t.value.stateBranchRoot);if(a(p))return l(p.message);let f={id:c,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=ao("Tagged",i);return a(g)?g:u(g.message,{...g.value,tag:f})}var lc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return l("Tag not found");if(o.tombstoned)return l("Tag is already deleted");let s=[{id:ds(),...n.value,action:"tombstone.tag",payload:{id:e.tagId}}],i=D(s,t.value.stateBranchRoot);return a(i)?l(i.message):u("Deleted tag",{id:o.id,name:o.name})};var dc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;if(!r.value.tags[e.tagId])return l("Tag not found");let s={id:ds(),...n.value,action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=D([s],t.value.stateBranchRoot);return a(i)?l(i.message):u("Removed issue tag",{id:e.issueId,ref:O(e.issueId),tagId:e.tagId})};import{ulid as Rr}from"ulid";var FR=()=>{let e=it(),t=a(e)?[]:e.value.eventLog??[],n=new Map;for(let r of t)r.userId&&r.userName&&n.set(r.userId,r.userName);return n},hh=(e,t)=>{let n=new Map(e);for(let r of Object.values(t))n.set(r.id,r.name);return n};var yh=async(e,t)=>{let n=Sl(e);if(a(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}},cc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=e.self?n.value.userId:e.assigneeId;if(s){let C=r.value.contributors[s],A=C?void 0:await yh(t.value.stateBranchRoot,s);if(!C&&!A)return l("Unknown assignee id");let M=C??A,w=[...C?[]:[{id:Rr(),...n.value,action:"create.contributor",payload:{id:M.id,name:M.name}}],{id:Rr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:M.id}}],L=D(w,t.value.stateBranchRoot);return a(L)?l(L.message):u("Added issue assignee",{id:e.issueId,ref:O(e.issueId),assignee:{id:M.id,name:M.name}})}let i=ye(e.assigneeName??"").trim();if(!i)return l("Provide assigneeId, self or assigneeName");let d=Qe("Assignee name",i,80);if(d)return l(d);let m=[...hh(FR(),r.value.contributors).entries()].filter(([,C])=>C===i);if(m.length>1)return l(`"${i}" matches ${m.length} contributors (${m.map(([C])=>C).join(", ")}). Assign by assigneeId to choose.`);let p=m[0];if(!p&&!e.createUnlinked)return l(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let[f=Rr(),g=i]=p??[],I=[...!!r.value.contributors[f]?[]:[{id:Rr(),...n.value,action:"create.contributor",payload:{id:f,name:g}}],{id:Rr(),...n.value,action:"add.issue.assignee",payload:{id:e.issueId,assignee:f}}],x=D(I,t.value.stateBranchRoot);return a(x)?l(x.message):u("Added issue assignee",{id:e.issueId,ref:O(e.issueId),assignee:{id:f,name:g}})},uc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;if(!r.value.contributors[e.contributorId])return l("Contributor not found");if(await yh(t.value.stateBranchRoot,e.contributorId))return l("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:Rr(),...n.value,action:"tombstone.contributor",payload:{id:e.contributorId}}],d=D(i,t.value.stateBranchRoot);return a(d)?l(d.message):u("Tombstoned contributor",{id:e.contributorId,name:js})};var mc=async(e={})=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=Fn(t.value.stateBranchRoot);if(a(o))return l(o.message);let s=e.boardId?qg(o.value,e.boardId):o.value,i=new Map,d=new Set,c=new Set,m=Sl(t.value.stateBranchRoot);if(a(m))return l(m.message);for(let v of m.value)v.userId&&c.add(v.userId);for(let v of s)v.userId&&(i.set(v.userId,v.userName??""),d.add(v.userId));let p=r.value.contributors,g=[...hh(i,p).entries()].map(([v,I])=>({id:v,name:I,color:ce(I),isSelf:v===n.value.userId,isExternal:!d.has(v),isRemoved:p[v]?.tombstoned===!0,hasAuthoredAnywhere:c.has(v)}));return u("Listed board contributors",g)},pc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;if(!r.value.contributors[e.assigneeId])return l("Assignee not found");let s={id:Rr(),...n.value,action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=D([s],t.value.stateBranchRoot);return a(i)?l(i.message):u("Removed issue assignee",{id:e.issueId,ref:O(e.issueId),assigneeId:e.assigneeId})};import{ulid as la}from"ulid";var cs=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=_e(e.issueId);if(a(o))return o;let s=e.body.trim();if(!s)return l("Comment cannot be empty");if(s.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=la(),d={id:la(),...n.value,action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},c=D([d],t.value.stateBranchRoot);return a(c)?l(c.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},us=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return l("Unable to resolve comment");if(o.payload.author!==n.value.userId)return l("You can only delete your own comments");let s=_e(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let d={id:la(),...n.value,action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},c=D([d],t.value.stateBranchRoot);return a(c)?l(c.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},fc=async e=>{let t=await Q(e.repoRoot,{pull:!1});if(a(t))return t;let n=Z();if(a(n))return n;let r=V();if(a(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return l("Unable to resolve comment");if(o.payload.author!==n.value.userId)return l("You can only edit your own comments");let s=_e(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return l("Comment was deleted");let d=e.body.trim();if(!d)return l("Comment cannot be empty");if(d.length>4e3)return l(`Comment cannot exceed ${4e3} characters (got ${d.length})`);let c={id:la(),...n.value,action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:d}},m=D([c],t.value.stateBranchRoot);return a(m)?l(m.message):u("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:d})};var sn="1.8.6";import OR from"node:fs";import vh from"node:path";var ms=Number(process.env.EPIQ_GUI_PORT)||3710,gc="/api/instance",hc="epiq",da=e=>{try{return OR.realpathSync(vh.resolve(e))}catch{return vh.resolve(e)}},_R=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===hc&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},bh=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${gc}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return _R(s)?s:null}catch{return null}finally{clearTimeout(r)}};var UR=e=>({...e,boards:(e.boards??[]).map(t=>({...t,swimlanes:(t.swimlanes??[]).map(n=>({...n,issues:(n.issues??[]).map(r=>({...r,description:""}))}))})),commentsByIssueId:Object.fromEntries(Object.entries(e.commentsByIssueId??{}).filter(([,t])=>t.length>0).map(([t,n])=>[t,n.map(r=>({...r,body:""}))])),attachmentsByIssueId:Object.fromEntries(Object.entries(e.attachmentsByIssueId??{}).filter(([,t])=>t.length>0))}),Cr=e=>a(e)?e:u(e.message,UR(e.value)),xh=(e,t)=>{let n=(e.boards??[]).flatMap(r=>r.swimlanes??[]).flatMap(r=>r.issues??[]).find(r=>r.id===t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}};var jR=15e3,Ih=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=Se(e.project.repoRoot);if(a(g))return null;let v=fe({repoRoot:g.value});return a(v)?null:Yt(v.value)}let d=()=>{let g=Or();return a(g)?(z.error(g.message),null):g.value},c=()=>{let g=d();if(!g)return!1;let{autoSync:v,preferredEditor:I}=g,x=bt(),C=a(x)?null:x.value.userName;return!!(v&&C&&I)},m=()=>{let g=d()?.autoSyncDebounceMs??jR;return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)){r=!0,o=Date.now();try{await Xn(async()=>{if(Ve().mode!=="live")return;await as({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let v=Cr(await At({repoRoot:e.project.repoRoot}));a(v)||cr({type:"state",payload:v})})}finally{r=!1,f()}}};function f(){n||!c()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,dispose:()=>{n=!0,t&&clearTimeout(t)}}};var $R=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),yc=(e,t)=>{if(!e)return!1;if(e==="null")return!0;let n;try{n=new URL(e)}catch{return!0}return n.protocol!=="http:"||n.port!==String(t)?!0:!$R.has(n.hostname)},Sh=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:yc(e.origin,t)?{status:403,message:"Cross-origin request"}:e.method==="POST"&&!(e.contentType??"").toLowerCase().startsWith("application/json")?{status:415,message:"Expected content-type: application/json"}:null;import{WebSocketServer as RC}from"ws";var an=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var HR=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},Eh=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...an(i),changed:i.addedCount+i.removed})).reduce((i,d)=>i===null||d.changed>i.changed?d:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>HR(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}};var Ue={line:["//"],block:[["/*","*/"]]},wt={line:["#"],block:[]},vc={line:["--"],block:[]},lo={line:[],block:[["<!--","-->"]]},WR={line:[],block:[]},$=(e,t)=>({name:e,comment:t}),ca=$("TypeScript",Ue),ua=$("JavaScript",Ue),Rh={ts:ca,tsx:ca,mts:ca,cts:ca,js:ua,jsx:ua,mjs:ua,cjs:ua,py:$("Python",{line:["#"],block:[['"""','"""']]}),rb:$("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:$("Go",Ue),rs:$("Rust",Ue),java:$("Java",Ue),kt:$("Kotlin",Ue),swift:$("Swift",Ue),c:$("C",Ue),h:$("C",Ue),cc:$("C++",Ue),cpp:$("C++",Ue),hpp:$("C++",Ue),cs:$("C#",Ue),php:$("PHP",Ue),scala:$("Scala",Ue),dart:$("Dart",Ue),lua:$("Lua",vc),hs:$("Haskell",vc),sql:$("SQL",vc),ex:$("Elixir",wt),exs:$("Elixir",wt),pl:$("Perl",wt),r:$("R",wt),jl:$("Julia",wt),sh:$("Shell",wt),bash:$("Shell",wt),zsh:$("Shell",wt),vue:$("Vue",lo),svelte:$("Svelte",lo),html:$("HTML",lo),xml:$("XML",lo),md:$("Markdown",lo),mdx:$("Markdown",lo),css:$("CSS",{line:[],block:[["/*","*/"]]}),scss:$("CSS",Ue),less:$("CSS",Ue),yml:$("YAML",wt),yaml:$("YAML",wt),toml:$("TOML",wt),ini:$("INI",wt),json:$("JSON",WR)},GR="Other",Ch=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},Nr=e=>Rh[Ch(e)]?.name??GR,ps=e=>Rh[Ch(e)]?.comment??null,VR=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],zR=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,co=e=>zR.test(e)||VR.some(t=>t.test(e)),KR=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,qR=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,YR=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,$t=e=>KR.test(e)||qR.test(e)||YR.test(e),Nh=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),Ah=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),Th=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),XR=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,JR=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,wh=e=>XR.test(e),Mh=e=>JR.test(e);var Ph=/\b(TODO|FIXME|HACK|XXX)\b/,QR=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,bc=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},ZR=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},Lh=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,d=0,c=0;for(let p of e.files){if(p.binary||$t(p.path))continue;let f=ps(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=Nr(p.path),v=n.get(g)??{comment:0,code:0};for(let{text:I}of p.added){let x=bc(I,f);if(Ph.test(I)&&i++,x==="blank"){s++;continue}if(x==="comment"){r++,v.comment++,f&&QR.test(ZR(I,f))&&c++;continue}o++,v.code++}for(let{text:I}of p.removedLines)Ph.test(I)&&d++;n.set(g,v)}let m=r+o;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:d,commentedOutCodeLines:c}};var eC=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,ma=6,xc=10,tC=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},nC=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},rC=e=>{if(e.length<ma*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+ma<=e.length;r++){let o=e.slice(r,r+ma);if(o.some(d=>d.text.length<3))continue;let s=o.map(d=>d.text).join(`
|
|
91
|
-
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let
|
|
92
|
-
`)){if(f.startsWith(
|
|
93
|
-
`)){let f=
|
|
94
|
-
`)){let A=bc(C,v);A==="comment"&&x.comment++,A==="code"&&x.code++}c.set(I,x)}let m=new Map;for(let[p,f]of c){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var jh=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let d of e.files)if(!(d.binary||$t(d.path))&&co(d.path)){t+=d.addedCount,n+=d.removed,d.status==="added"&&r.push(an(d)),d.status==="deleted"&&o.push(an(d));for(let{text:c}of d.added)wh(c)&&s++,Mh(c)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var fC=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,$h=async({repoRoot:e,ref:t,commits:n})=>{let r=await _h({repoRoot:e,shas:n.map(d=>d.sha)});if(a(r))return l(r.message);let o=r.value,s=fC(n),i=s?await Uh({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:Eh({commits:n,patch:o}),languages:Dh({patch:o,languagesBefore:i?.languages??null}),tests:jh({patch:o}),comments:Lh({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:kh({patch:o})})};var gC=32,fs=new Map;var hC=(e,t)=>{if(fs.set(e,t),fs.size>gC){let n=fs.keys().next();n.done||fs.delete(n.value)}return t},pa=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return l("idOrRef must not be empty");let n=t.length>7?O(t):t.toUpperCase(),r=Se(e.repoRoot??process.cwd());if(a(r))return l(r.message);let o=r.value,s=await sa({repoRoot:o,ref:n});if(a(s))return l(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.author,subject:p.subject})),d=[o,n,i.map(p=>p.sha).join(",")].join(" "),c=fs.get(d);if(c)return u("Derived issue stats",c);let m=await $h({repoRoot:o,ref:n,commits:i});return a(m)?l(m.message):u("Derived issue stats",hC(d,m.value))};var yC="Filed here",Hh=(e,t)=>e.set(t,(e.get(t)??0)+1),Wh=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?yC:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),Gh=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let d of t)for(let[c,m]of d.entries()){if(m!==e)continue;s++,Hh(r,d[c-1]??null);let p=d[c+1];p!==void 0&&(i++,Hh(o,p))}return{arrived:s,departed:i,arrivesFrom:Wh(r,s,n),movesOnTo:Wh(o,i,n)}};var Vh=e=>{if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]};var gs=1440*60*1e3,vC=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*gs,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[d,c]of i.entries()){let m=s.get(c.laneId);if(!m)continue;let p=i[d+1]?.enteredAt,f=Math.max(0,Math.ceil((c.enteredAt-o)/gs)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/gs)-1);for(let v=f;v<=g;v++)m[v].push(o+v*gs-c.enteredAt)}return Object.fromEntries([...s].map(([i,d])=>[i,d.map((c,m)=>({t:o+m*gs,median:Vh(c.sort((p,f)=>p-f)),count:c.length}))]))},zh=({laneId:e,journeys:t,now:n,days:r})=>vC({laneIds:[e],journeys:t,now:n,days:r})[e];var bC=40,xC=30,IC=()=>({tickets:0,commits:0,insertions:0,deletions:0}),SC=async(e,t)=>{let n=IC();for(let r of t.slice(0,bC)){let o=await pa({repoRoot:e,idOrRef:O(r)});a(o)||o.value.shape.commits===0||(n.tickets++,n.commits+=o.value.shape.commits,n.insertions+=o.value.shape.insertions,n.deletions+=o.value.shape.deletions)}return n},Kh=async e=>{let t=V();if(a(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return l("Swimlane not found");let o=Object.values(n).filter(B),s=o.map(c=>Pd(c.log??[],Ce(c.id))),i=Gh(e.swimlaneId,s.map(c=>c.map(m=>m.laneId)),c=>n[c]?.title??"Elsewhere"),d=o.filter(c=>c.parentNodeId===e.swimlaneId).map(c=>c.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:Ce(e.swimlaneId),...i,stayTrend:zh({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:xC}),code:await SC(e.repoRoot,d)})};var qh=new Set(["sync","issues:create","board:create","board:edit:title","swimlane:create","swimlane:edit:title","swimlane:delete","swimlane:move","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","tag:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var Yh=e=>{let t=Rn({exclude:e});return a(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Gr(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Xh=e=>{let t=Rn();if(a(t))return l(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):l(`Not a recent project: ${e}`)};import{z as P}from"zod";var q=P.string().min(1),Jh=P.discriminatedUnion("at",[P.object({at:P.literal("start")}),P.object({at:P.literal("end")}),P.object({at:P.literal("before"),sibling:q}),P.object({at:P.literal("after"),sibling:q})]),hs=P.number().finite(),oe=(e,t)=>P.object({type:P.literal(e),payload:t}),fa=e=>P.object({type:P.literal(e)}),EC=P.discriminatedUnion("type",[fa("state:get"),fa("issues:list"),fa("sync"),fa("time-travel:live"),oe("project:open",P.object({root:P.string().min(1)})),oe("issues:create",P.object({title:P.string(),parentId:q,description:P.string().optional(),tagNames:P.array(P.string()).optional()})),oe("board:create",P.object({title:P.string()})),oe("board:edit:title",P.object({boardId:q,title:P.string()})),oe("swimlane:create",P.object({title:P.string(),boardId:q})),oe("swimlane:edit:title",P.object({swimlaneId:q,title:P.string()})),oe("swimlane:delete",P.object({swimlaneId:q})),oe("swimlane:move",P.object({swimlaneId:q,boardId:q,position:Jh.optional()})),oe("issues:move",P.object({issueId:q,parentId:q,position:Jh.optional()})),oe("issue:edit:title",P.object({issueId:q,title:P.string()})),oe("issue:edit:description",P.object({issueId:q,description:P.string()})),oe("issue:tag:add",P.object({issueId:q,tagName:P.string()})),oe("issue:tag:remove",P.object({issueId:q,tagId:q})),oe("contributor:remove",P.object({contributorId:q})),oe("tag:remove",P.object({tagId:q})),P.object({type:P.literal("contributors:get"),payload:P.object({boardId:q.optional()}).optional()}),oe("issue:assignee:add",P.object({issueId:q,assigneeId:q.optional(),assigneeName:P.string().optional(),createUnlinked:P.boolean().optional()})),oe("issue:assignee:remove",P.object({issueId:q,assigneeId:q})),oe("issue:close",P.object({issueId:q})),oe("issue:reopen",P.object({issueId:q})),oe("issue:comment:add",P.object({issueId:q,body:P.string()})),oe("issue:comment:delete",P.object({issueId:q,commentId:q})),oe("issue:comment:edit",P.object({issueId:q,commentId:q,body:P.string()})),oe("issue:get",P.object({issueId:q})),P.object({type:P.literal("timeline:get"),payload:P.object({start:hs.optional(),end:hs.optional(),boardId:q.optional(),requestId:P.number().finite().optional()}).optional()}),P.object({type:P.literal("commits:get"),payload:P.object({start:hs.optional(),end:hs.optional(),requestId:P.number().finite().optional()}).optional()}),oe("time-travel:scrub",P.object({targetTime:hs})),oe("time-travel:checkout-event",P.object({eventId:P.string().min(1)})),oe("commit:inspect",P.object({sha:P.string()})),oe("commit:diff:get",P.object({sha:P.string()})),oe("issue:commits:get",P.object({issueId:q})),oe("issue:stats:get",P.object({issueId:q})),oe("swimlane:stats:get",P.object({swimlaneId:q}))]);var Qh=e=>{let t=EC.safeParse(e);return t.success?{ok:!0,message:t.data}:{ok:!1,error:`Invalid message: ${t.error.issues.map(r=>`${r.path.join(".")||"<root>"}: ${r.message}`).join(", ")}`}};var CC=1024*1024,Ec=()=>{cr({type:"state",payload:Cr(Sr())})},se=(e,t)=>{e.send(JSON.stringify(t))},ys=async(e,t)=>{let n=Cr(await At({repoRoot:t}));return a(n)&&n.message===Ja?se(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Yh(t)}}):se(e,{type:"state",payload:n})},NC=async(e,t)=>{let n=()=>se(e,{type:"state",payload:Cr(Sr())});if(Ve().mode!=="live")return n();let r=await At({repoRoot:t});return Ve().mode!=="live"?n():se(e,{type:"state",payload:Cr(r)})},Le=async(e,t,n,r,o)=>{if(se(e,{type:r,payload:o}),a(o))return se(e,{type:"failed",payload:o.message});n(),NC(e,t)},Zh=(e,t,{onStateChanged:n,getPort:r})=>{new RC({server:e,path:"/ws",maxPayload:CC,verifyClient:s=>!yc(s.origin,r())}).on("connection",s=>{wm(s),s.on("message",async i=>{let d=async c=>{let{type:m}=c,p=t.repoRoot;if(m==="project:open"){let f=Xh(c.payload.root);return se(s,{type:"project:open:result",payload:f}),a(f)?void 0:(t.repoRoot=f.value,ys(s,f.value))}if(m==="timeline:get"){let{requestId:f,...g}=c.payload??{};return se(s,{type:"timeline",requestId:f,payload:await oh({repoRoot:p,...g})})}if(m==="issue:get"){let f=c.payload?.issueId,g=Sr(),v=Qd(f);return se(s,{type:"issue",payload:a(g)?g:u("Issue detail",{...xh(g.value,f),history:a(v)?[]:v.value})})}if(m==="commits:get"){let{requestId:f,...g}=c.payload??{};return se(s,{type:"commits",requestId:f,payload:await Od({repoRoot:p,...g})})}if(m==="commit:inspect")return se(s,{type:"commit:inspect:result",payload:await ih({repoRoot:p,sha:c.payload.sha})});if(m==="commit:diff:get"){let{sha:f}=c.payload;return se(s,{type:"commit:diff:result",payload:{sha:f,result:await ah({repoRoot:p,sha:f})}})}if(m==="issue:commits:get"){let{issueId:f}=c.payload;return se(s,{type:"issue:commits:result",payload:{issueId:f,result:await sa({repoRoot:p,ref:O(f)})}})}if(m==="issue:stats:get"){let{issueId:f}=c.payload;return se(s,{type:"issue:stats:result",payload:{issueId:f,result:await pa({repoRoot:p,idOrRef:O(f)})}})}if(m==="swimlane:stats:get"){let{swimlaneId:f}=c.payload;return se(s,{type:"swimlane:stats:result",payload:{swimlaneId:f,result:await Kh({repoRoot:p,swimlaneId:f})}})}if(m==="time-travel:scrub"){let f=await _d({repoRoot:p,targetTime:c.payload.targetTime});return se(s,{type:"time-travel:result",payload:f}),a(f)?void 0:Ec()}if(m==="time-travel:checkout-event"){let f=await dh({repoRoot:p,eventId:c.payload.eventId});return se(s,{type:"time-travel:result",payload:f}),a(f)?void 0:Ec()}if(m==="time-travel:live"){let f=await ch({repoRoot:p});return se(s,{type:"time-travel:result",payload:f}),a(f)?void 0:Ec()}if(m==="state:get")return ys(s,p);if(m==="sync"){let f=await as({repoRoot:p});return se(s,{type:"sync:result",payload:f}),n(),ys(s,p)}if(m==="issue:comment:add"){let f=await cs({repoRoot:p,...c.payload});return Le(s,p,n,"issue:comment:add:result",f)}if(m==="issue:comment:edit"){let f=await fc({repoRoot:p,...c.payload});return Le(s,p,n,"issue:comment:edit:result",f)}if(m==="issue:comment:delete"){let f=await us({repoRoot:p,...c.payload});return se(s,{type:"issue:comment:delete:result",payload:f}),a(f)?se(s,{type:"failed",payload:f.message}):(n(),ys(s,p))}if(m==="issue:edit:description"){let f=await Zd({repoRoot:p,...c.payload});return Le(s,p,n,"issue:edit:description:result",f)}if(m==="issue:edit:title"){let f=await ec({repoRoot:p,...c.payload});return Le(s,p,n,"issue:edit:title:result",f)}if(m==="issue:tag:add"){let f=await ac({repoRoot:p,...c.payload});return Le(s,p,n,"issue:tag:add:result",f)}if(m==="issue:tag:remove"){let f=await dc({repoRoot:p,...c.payload});return Le(s,p,n,"issue:tag:remove:result",f)}if(m==="contributor:remove"){let f=await uc({repoRoot:p,...c.payload});return Le(s,p,n,"contributor:remove:result",f)}if(m==="tag:remove"){let f=await lc({repoRoot:p,...c.payload});return Le(s,p,n,"tag:remove:result",f)}if(m==="contributors:get")return se(s,{type:"contributors",payload:await mc({repoRoot:p,...c.payload})});if(m==="issue:assignee:add"){let f=await cc({repoRoot:p,...c.payload});return Le(s,p,n,"issue:assignee:add:result",f)}if(m==="issue:assignee:remove"){let f=await pc({repoRoot:p,...c.payload});return Le(s,p,n,"issue:assignee:remove:result",f)}if(m==="issues:list")return se(s,{type:"issues",payload:await Kd({repoRoot:p})});if(m==="issues:create"){let f=await qd({...c.payload,repoRoot:p});return se(s,{type:"issues:create:result",payload:f}),a(f)?cr({type:"failed",payload:f.message}):(n(),ys(s,p))}if(m==="board:create"){let f=await tc({...c.payload,repoRoot:p});return Le(s,p,n,"board:create:result",f)}if(m==="board:edit:title"){let f=await nc({...c.payload,repoRoot:p});return Le(s,p,n,"board:edit:title:result",f)}if(m==="swimlane:create"){let f=await rc({...c.payload,repoRoot:p});return Le(s,p,n,"swimlane:create:result",f)}if(m==="swimlane:edit:title"){let f=await oc({...c.payload,repoRoot:p});return Le(s,p,n,"swimlane:edit:title:result",f)}if(m==="swimlane:delete"){let f=await ic({...c.payload,repoRoot:p});return Le(s,p,n,"swimlane:delete:result",f)}if(m==="swimlane:move"){if(!c.payload.position)return se(s,{type:"error",message:"Missing move position"});let f=await sc({...c.payload,repoRoot:p});return Le(s,p,n,"swimlane:move:result",f)}if(m==="issues:move"){if(!c.payload.position)return se(s,{type:"error",message:"Missing move position"});let f=await Jd({...c.payload,repoRoot:p});return Le(s,p,n,"issues:move:result",f)}if(m==="issue:close"){let f=await Yd({repoRoot:p,issueId:c.payload.issueId});return Le(s,p,n,"issue:close:result",f)}if(m==="issue:reopen"){let f=await Xd({repoRoot:p,issueId:c.payload.issueId});return Le(s,p,n,"issue:reopen:result",f)}return se(s,{type:"error",message:"Unknown message type"})};try{let c=Qh(JSON.parse(i.toString()));if(!c.ok)return se(s,{type:"error",message:c.error});let m=c.message;return qh.has(m.type)?await Xn(async()=>Ve().mode!=="live"?se(s,{type:"failed",payload:"Read-only while viewing history"}):d(m)):await d(m)}catch(c){return se(s,{type:"error",message:c instanceof Error?c.message:String(c)})}})})};var wC=Ar.dirname(TC(import.meta.url)),MC=process.env.IS_LOCAL==="true"?Ar.resolve(process.cwd(),"dist/gui"):Ar.join(wC,"gui"),ga,PC=async()=>(ga===void 0&&(ga=await import("node:sea").catch(()=>null)),ga?.isSea()?ga:null),Ee=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},LC=e=>Ee(e,409,{isError:!0,message:"Read-only while viewing history"}),ha=(e,t)=>Xn(async()=>Ve().mode!=="live"?LC(e):t()),ey=async(e,t=1024*1024)=>new Promise((n,r)=>{let o=[],s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o.push(i)}),e.on("end",()=>{let i=Buffer.concat(o).toString("utf8");try{n(i?JSON.parse(i):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),kC=2*1024*1024,DC={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},BC=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",ty=async(e,t)=>{let n=e==="/"?"index.html":decodeURIComponent(e).replace(/^\/+/,""),r=Ar.resolve(MC),o=Ar.resolve(r,n),s=Ar.relative(r,o);if(s.startsWith("..")||Ar.isAbsolute(s))return Ee(t,403,{isError:!0,message:"Forbidden"});let i=await PC();try{let d=i?Buffer.from(i.getAsset(`gui/${s}`)):await ny(o);return t.writeHead(200,{"content-type":BC(o)}),t.end(d)}catch{return Ee(t,404,{isError:!0,message:`Not found: ${n}`})}},FC=async(e,t=ms)=>new Promise((n,r)=>{let o=s=>{let i=c=>{if(e.off("listening",d),c.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(c)},d=()=>{e.off("error",i);let c=e.address();if(!c||typeof c=="string"){r(new Error("Unable to resolve address"));return}n(c.port)};e.once("error",i),e.once("listening",d),e.listen(s,"127.0.0.1")};o(t)}),ry=async e=>{Gg(!1);let t=0,n={repoRoot:e.repoRoot},r=AC.createServer(async(i,d)=>{let c=new URL(i.url??"/","http://127.0.0.1"),m=Sh({method:i.method,origin:i.headers.origin,contentType:i.headers["content-type"]},t);if(m)return Ee(d,m.status,{isError:!0,message:m.message});if(i.method==="GET"&&c.pathname===gc)return Ee(d,200,{app:hc,repoRoot:da(n.repoRoot),version:sn,pid:process.pid});if(c.pathname==="/api/state")return Ee(d,200,await At({repoRoot:n.repoRoot}));if(i.method==="POST"&&c.pathname==="/api/comments")try{let p=await ey(i);if(!p.issueId||!p.body?.trim())return Ee(d,400,{isError:!0,message:"Missing issueId or body"});let f=p.issueId,g=p.body;return await ha(d,async()=>{let v=await cs({repoRoot:n.repoRoot,issueId:f,body:g});return a(v)?Ee(d,400,{isError:!0,message:v.message}):Ee(d,200,await At({repoRoot:n.repoRoot}))})}catch(p){return Ee(d,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add comment"})}if(i.method==="POST"&&c.pathname==="/api/attachments")try{let p=await ey(i,kC);if(!p.issueId||!p.dataBase64)return Ee(d,400,{isError:!0,message:"Missing issueId or dataBase64"});let f=p.issueId,g=p.dataBase64,v=p.name??"";return await ha(d,async()=>{let I=await $d({repoRoot:n.repoRoot,issueId:f,name:v,dataBase64:g});return a(I)?Ee(d,400,{isError:!0,message:I.message}):Ee(d,200,{...await At({repoRoot:n.repoRoot}),attachment:I.value})})}catch(p){return Ee(d,400,{isError:!0,message:p instanceof Error?p.message:"Unable to add attachment"})}if(i.method==="DELETE"&&c.pathname.startsWith("/api/attachments/")){let p=decodeURIComponent(c.pathname.replace("/api/attachments/",""));return p?ha(d,async()=>{let f=await Hd({repoRoot:n.repoRoot,attachmentId:p});return a(f)?Ee(d,400,{isError:!0,message:f.message}):Ee(d,200,await At({repoRoot:n.repoRoot}))}):Ee(d,400,{isError:!0,message:"Missing attachment id"})}if(i.method==="GET"&&c.pathname.startsWith("/media/")){let p=decodeURIComponent(c.pathname.replace("/media/","")),f=await Wd({repoRoot:n.repoRoot,fileName:p});if(a(f))return Ee(d,404,{isError:!0,message:f.message});try{let g=await ny(f.value.filePath);return d.writeHead(200,{"content-type":DC[f.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),d.end(g)}catch{return Ee(d,404,{isError:!0,message:"Attachment blob not found"})}}if(i.method==="DELETE"&&c.pathname.startsWith("/api/comments/")){let p=decodeURIComponent(c.pathname.replace("/api/comments/",""));return p?ha(d,async()=>{let f=await us({repoRoot:n.repoRoot,commentId:p});return a(f)?Ee(d,400,{isError:!0,message:f.message}):Ee(d,200,await At({repoRoot:n.repoRoot}))}):Ee(d,400,{isError:!0,message:"Missing comment id"})}return c.pathname.startsWith("/board/")||c.pathname==="/log"?ty("/",d):ty(c.pathname,d)});try{t=await FC(r)}catch(i){return l(i instanceof Error?`Unable to start GUI server: ${i.message}`:`Unable to start GUI server: ${String(i)}`)}let o=Ih({project:n});Zh(r,n,{onStateChanged:()=>o.queueSync(),getPort:()=>t}),r.on("close",o.dispose);let s=r.address();return!s||typeof s=="string"?(r.close(),l("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${s.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var sy=async e=>{let t=Lr({});if(a(t))return l(t.message);let n=bt();me(n)&&Ye(n.value);let r=await bh(ms);if(r&&r.repoRoot===da(e.repoRoot)){let i=`http://127.0.0.1:${ms}`;return console.log(`Epiq GUI already running for this project at ${oy.cyan(i)}`),rl(i),u("Reused running GUI",{url:i})}let o=await ry({...e,boardId:""});if(a(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${oy.cyan(s)}`),rl(s),u("Started GUI",{url:s})};import{Box as nr}from"ink";import Re from"react";import{Box as Rc,Text as vs}from"ink";import Ht,{useEffect as OC,useMemo as _C}from"react";import{ulid as UC}from"ulid";var iy=({text:e,match:t,color:n,highlightColor:r=y.secondary,dimColor:o=!1})=>{if(!t)return Ht.createElement(vs,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),d=s.indexOf(i);return d===-1?Ht.createElement(vs,{color:n,dimColor:o},e):Ht.createElement(vs,{color:n,dimColor:o},e.slice(0,d),Ht.createElement(vs,{backgroundColor:r,bold:!0},e.slice(d,d+t.length)),e.slice(d+t.length))},ay=UC(),jC=e=>`${e}`,$C=e=>{let{pendingNavTarget:t}=Gn();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Ne(E.NONE,{breadCrumb:n,contextNode:r,readOnly:h().readOnly,selectedNode:o}));return[...new Set(Object.values(E))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==E.PALETTE).map(i=>{let d=Ai(i),c=Yi.find(m=>m.intent===d);return{command:i,description:c?.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,d)=>i.isAvailable!==d.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(d.command))},HC=e=>be.text({id:ay,parentNodeId:e,rank:"000000",name:"Command Palette",props:{},readonly:!0,isVirtual:!0}),WC=(e,t,n)=>be.text({id:jC(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,props:{value:e.description,disabled:!e.isAvailable},readonly:!0,isVirtual:!0}),Cc=[],GC=e=>{ly();let t=R.createNode(HC(h().rootNodeId));a(t)||!Pn(t.value)||(Cc=[t.value,...e.map((n,r)=>WC(n,r,ay)).map(R.createNode).filter(me).map(({value:n})=>n).filter(Pn)],_.navigate({contextNode:t.value,selectedIndex:0}))},ly=()=>{let e=Cc.map(t=>t.id);Cc=[];for(let t of e)R.deleteNode(t)};function dy({width:e,height:t}){let r=Wp().value.trim().toLowerCase(),o=_C(()=>$C(r),[r]);OC(()=>(GC(o),()=>{ly()}),[o]);let s=h().selectedIndex;return Ht.createElement(Rc,{flexDirection:"column",width:e,height:t-2},Ht.createElement(Et,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,d)=>{let c=d===s,m=i.isAvailable?y.accent:y.secondary2,p=i.isAvailable?"":"[unavailable] ";return Ht.createElement(Rc,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:y.secondary,borderStyle:"single"},Ht.createElement(vs,{color:m,dimColor:!i.isAvailable},c?"\u276F ":" ",Ht.createElement(iy,{text:Au(i.command),match:r,color:m,dimColor:!i.isAvailable})),Ht.createElement(Rc,{paddingLeft:2},Ht.createElement(iy,{text:p+i.description,match:r.length>=2?r:"",color:c&&i.isAvailable?y.primary:y.secondary2,dimColor:!i.isAvailable})))})))}import{Box as sN}from"ink";import ba from"react";import xs from"chalk";import{Box as Nc,Text as py}from"ink";import bs,{useEffect as fy,useMemo as VC,useState as gy}from"react";var uo=["\u2803","\u2806","\u2830","\u2818"],cy=120,uy=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%uo.length+uo.length)%uo.length;return uo[r]}return e?"?":":"},my=({infoMessage:e,isPending:t})=>t&&e.includes(ue)?"":e;var hy=xs.hex(y.secondary),zC=xs.inverse,KC=xs.inverse.hex(y.secondary2),qC={hint:"",hints:[],overlap:0,remainder:""},vy=({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}},YC=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=ce(t);return{bg:r=>xs.bgHex(n).black(r),bgCursor:r=>xs.bgHex(n).inverse.black(r)}}return zl(t)},XC=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=vy({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}},yy=()=>({value:Ze.value,cursorPosition:Ze.cursorPosition,commandIsPending:Ze.commandIsPending,autoCompletion:Ze.commandMeta.autoCompletion??qC,infoMessage:Ze.commandMeta.infoMessage,validationStatus:Ze.commandMeta.validity,command:Ze.commandMeta.command,inputString:Ze.commandMeta.inputString,modifier:Ze.commandMeta.modifier}),JC=(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,by=({width:e,mode:t})=>{let[n,r]=gy(yy());fy(()=>{let M=()=>{let L=yy();r(k=>JC(k,L)?k:L)},w=Xl(M);return M(),()=>{w()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:d,autoCompletion:c,command:m,modifier:p,validationStatus:f}=n,g=d&&f===tn.Invalid,v=my({infoMessage:i,isPending:d}),[I,x]=gy(0);fy(()=>{if(!d){x(0);return}let M=setInterval(()=>{x(w=>(w+1)%uo.length)},cy);return()=>{clearInterval(M)}},[d]);let C=uy({isPalette:t===b.PALETTE,isPending:d,frame:I}),A=VC(()=>{let M=Math.max(0,Math.min(s,o.length)),w=vy({value:o,command:m}),L=XC({value:o,command:m,modifier:p}),k=m?zl(m):null,Ie=YC({command:m,modifier:p}),Ke=(qe,nt)=>{let Mr=w&&nt>=w.start&&nt<w.end,ka=L&&nt>=L.start&&nt<L.end;return Mr&&k?k.fg(qe):ka&&Ie?Ie.bg(qe):qe},Mt=(qe,nt)=>{let Mr=w&&nt>=w.start&&nt<w.end,ka=L&&nt>=L.start&&nt<L.end;return Mr&&k?k.fgCursor(qe):ka&&Ie?Ie.bgCursor(qe):zC(qe)},mt=o.slice(0,M),$e=o[M]??" ",An=M<o.length?o.slice(M+1):"",rr=Array.from(mt).map((qe,nt)=>Ke(qe,nt)).join(""),wr=Mt($e,M),ho=Array.from(An).map((qe,nt)=>Ke(qe,M+1+nt)).join("");if(c.hint){let qe=c.hint[c.overlap]??$e;wr=KC(qe),ho=hy(c.remainder.slice(1)+An)}return rr+wr+ho},[o,s,c,m,p]);return bs.createElement(Nc,{flexDirection:"column",justifyContent:"flex-start"},bs.createElement(Nc,{flexDirection:"column",paddingX:1,borderColor:y.secondary,borderStyle:"round",width:e},bs.createElement(Nc,null,bs.createElement(py,null,hy(C),A),v&&bs.createElement(py,{wrap:"truncate",color:g?y.red:y.secondary2},` ${v} `))))};import{Box as QC,Text as Is}from"ink";import mo from"react";var xy=" ",ZC=({keys:e,label:t})=>e.length+1+t.length,eN=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?xy.length:0)+ZC(o);if(r+i>t-4)break;n.push(o),r+=i}return n},Iy=({width:e,availableHints:t})=>{let n=eN(t,e);return mo.createElement(QC,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1},n.length?mo.createElement(Is,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>mo.createElement(Is,{key:`${o}-${s}`},i>0?xy:"",mo.createElement(Is,{color:y.accent},o),mo.createElement(Is,{color:y.secondary2}," ",s)))):mo.createElement(Is,{color:y.secondary2},"\xA0"))};import{Box as tN,Text as ya}from"ink";import Ss,{useEffect as nN,useRef as po,useState as rN}from"react";var oN=40,va=.3,Ac="\u2500",Sy=1,Ey=16,Ry=({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*Sy,[d,c]=rN(0),m=po(r);m.current=r;let p=po(0),f=po(0),g=po(0),v=po(0),I=po(0);if(nN(()=>{if(!n){p.current=0,g.current=0,v.current=0,I.current=0,c(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let w=setInterval(()=>{let L=Date.now(),k=m.current;if(k!==g.current){let $e=k-g.current,An=L-f.current;if($e<0)v.current=0,I.current=0;else if($e>0&&An>0){let rr=$e/An;v.current=v.current===0?rr:v.current*(1-va)+rr*va,I.current=I.current===0?$e:I.current*(1-va)+$e*va}p.current=k,f.current=L,g.current=k}let Ie=L-f.current,Ke=Math.min(I.current,v.current*Ie),Mt=Math.min(1,p.current+Ke),mt=Math.round(Mt*i);c($e=>$e===mt?$e:mt)},oN);return()=>clearInterval(w)},[n,i]),!t)return null;let x=w=>{let L=s>1?w/(s-1):0,k=Math.round(L*(Ey-1))/(Ey-1);return xi(k)},C=Math.min(s,Math.floor(d/Sy)),A=[];for(let w=0;w<C;w++){let L=x(w),k=A[A.length-1];k&&k.color===L?k.text+=Ac:A.push({text:Ac,color:L})}let M=Ac.repeat(Math.max(0,s-C));return Ss.createElement(tN,{width:e,borderStyle:"round",borderColor:y.secondary,paddingX:1,columnGap:1},Ss.createElement(ya,{color:y.secondary2},"\u25B6"),Ss.createElement(ya,null,A.map((w,L)=>Ss.createElement(ya,{key:L,color:w.color},w.text)),Ss.createElement(ya,{color:y.secondary,dimColor:!0},M)))};var Es=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=J(),o=t===b.COMMAND_LINE||t===b.PALETTE;return ba.createElement(sN,null,o?ba.createElement(by,{width:e,mode:t}):r==="replay"?ba.createElement(Ry,{width:e}):ba.createElement(Iy,{width:e,mode:t,availableHints:n}))};import{Box as Zn,Text as fo}from"ink";import at,{useEffect as iN,useMemo as aN}from"react";import{ulid as Cy}from"ulid";var Ia=Cy(),lN=()=>[...new Set([...h().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(Cd).filter(e=>e!==null).sort(({keys:e},{keys:t})=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(({keys:e,label:t})=>({keys:e,action:t})),dN=e=>be.text({id:Ia,parentNodeId:e,rank:"000000",name:"Help",props:{},isVirtual:!0,readonly:!0}),cN=(e,t,n)=>be.text({id:Cy(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,props:{value:e.action},readonly:!0,isVirtual:!0}),xa=[],Ny=()=>{let e=xa.filter(n=>n.id!==Ia).map(n=>n.id),t=xa.filter(n=>n.id===Ia).map(n=>n.id);xa=[];for(let n of[...e,...t])R.deleteNode(n)},uN=e=>{Ny();let t=R.createNode(dN(h().rootNodeId));if(a(t)||!Pn(t.value))return logger.error("Could not attach help nodes");xa=[t.value,...e.map((n,r)=>cN(n,r,Ia)).map(R.createNode).filter(me).map(({value:n})=>n).filter(Pn)],_.navigate({contextNode:t.value,selectedIndex:0})},Ay=({width:e,height:t})=>{let n=aN(()=>lN(),[]);iN(()=>(uN(n),()=>{Ny()}),[n]);let r=h().selectedIndex;return at.createElement(Zn,{flexDirection:"column",marginTop:3,borderColor:y.secondary,borderStyle:"round",width:e,height:t-2},at.createElement(Zn,{paddingX:1,justifyContent:"center"},at.createElement(fo,{color:y.accent},"Help"),at.createElement(fo,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),at.createElement(Zn,{paddingX:1,marginTop:1},at.createElement(Zn,{width:20,justifyContent:"flex-end"},at.createElement(fo,{color:y.secondary},"Key(s)")),at.createElement(Zn,{flexGrow:1,width:40,paddingLeft:2},at.createElement(fo,{color:y.secondary},"Action"))),at.createElement(Et,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let d=i===r;return at.createElement(Zn,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},at.createElement(Zn,{width:20,justifyContent:"flex-end"},at.createElement(fo,{color:y.accent},o)),at.createElement(Zn,{flexGrow:1,width:40,paddingLeft:2},at.createElement(fo,{color:d?y.primary:y.secondary2},s)))})))};import mN from"chalk";import{Box as Tr,Text as je}from"ink";import he from"react";var pN=8,fN=()=>{let e=Rn({exclude:process.cwd()});return a(e)?[]:e.value.slice(0,pN)},Ty=({width:e,height:t})=>{let n=fN();return he.createElement(Tr,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},he.createElement(je,{color:y.accent,bold:!0},"Initialize project"),he.createElement(je,null,`This folder is not an ${mN.hex(y.accent)("epiq")} project yet.`),he.createElement(je,{color:y.primary},"To start tracking issues here, we need to initialize a new",he.createElement(je,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json "),"file in this repository."),he.createElement(Tr,{marginTop:1,flexDirection:"column"},he.createElement(Tr,null,he.createElement(je,{color:y.accent}," "),he.createElement(je,{color:y.primary},"Type "),he.createElement(je,{backgroundColor:y.secondary}," :init "))),he.createElement(Tr,{marginTop:1},he.createElement(je,{color:y.secondary2},"This will create, commit and push "),he.createElement(je,{color:y.primary,backgroundColor:y.secondary}," .epiq/project.json ")),n.length>0&&he.createElement(Tr,{marginTop:1,flexDirection:"column"},he.createElement(je,{color:y.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>he.createElement(Tr,{key:r.projectId},he.createElement(je,{color:y.accent},` ${o+1} `),he.createElement(je,{color:y.primary},Gr(r.root)),he.createElement(je,{color:y.secondary2},` ${r.root}`))),he.createElement(Tr,{marginTop:1},he.createElement(je,{color:y.accent}," "),he.createElement(je,{color:y.primary},"Type "),he.createElement(je,{backgroundColor:y.secondary}," :open 1 "),he.createElement(je,{color:y.secondary2}," or "),he.createElement(je,{backgroundColor:y.secondary}," :open <path> "))))};import{Box as Sa,Text as ln}from"ink";import ze from"react";var gN=({isDone:e,command:t,value:n})=>ze.createElement(Sa,null,ze.createElement(ln,{color:y.accent,dimColor:e},e?" \u2714 ":" "),ze.createElement(ln,{dimColor:e},"Type "),ze.createElement(ln,{backgroundColor:y.secondary,dimColor:e}," "+t+" "),n!==void 0&&ze.createElement(ze.Fragment,null,ze.createElement(ln,{dimColor:e}," "),ze.createElement(ln,{color:y.secondary,dimColor:e},"<"+n+">"))),hN=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function Tc({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:d}=_n(),c=[{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:d,command:":config autosync",value:i,message:"Almost there. Configure auto sync."}],m=c.findIndex(f=>!f.done),p=m===-1?void 0:c[m];return ze.createElement(Sa,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:y.secondary,rowGap:1},ze.createElement(ln,{color:y.accent,bold:!0},"Welcome! \u{1F539}"),ze.createElement(ln,null,"Let's get you started - it's a breeze."),ze.createElement(ln,{color:y.secondary2},"Remember - you can always search available commands by typing:",ze.createElement(ln,{color:y.accent}," ? ")),p&&ze.createElement(ln,{color:y.secondary2},p.message),ze.createElement(Sa,{flexDirection:"column"},c.map((f,g)=>m===-1||g<=m?ze.createElement(Sa,{key:f.key,marginBottom:1},ze.createElement(gN,{isDone:f.done,command:f.command,value:f.done?hN(f.value):void 0})):null)))}import Aa from"chalk";import{Box as Cs,Text as go}from"ink";import ke from"react";import{Box as Ea,Text as wy}from"ink";import er from"react";import yN from"chalk";var vN=e=>(R.getTag(e)?.name??"").length+3,bN=e=>{let t=R.getContributor(e);return(t?t.name:"").length+3},My=({width:e})=>{let{viewMode:t}=le(),n=J(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,d=i[o.id]?.[s],c=ut(d?.id??o.id,"TICKET"),m=me(c)?c.value:void 0,p=(m?.props.tags??[]).filter(k=>R.getTag(k)),f=m?.props.assignees??[],g=m?.parentNodeId?!Md(o.id,m.parentNodeId)&&t==="dense":!1,v=r.map((k,Ie)=>{let Ke=Ie===r.length-1,Mt=de(k.id),mt=Ke?Mt?.[s]?.title:void 0;return`${Ie?" / ":""}${k.title??""}${mt?` \u25B8 ${mt}`:""}`}).join(""),I=m?R.getCommentsByIssue(m.id):[],x=I.length?String(I.length).length+11:0,C=g?p.reduce((k,Ie)=>k+vN(Ie),0)+f.reduce((k,Ie)=>k+bN(Ie),0)+x:0,A=d?.id!=null&&!(t==="wide"&&B(d)),M=Math.max(0,e-C),w=v.substring(0,M)+(A?yN.hex(y.secondary2).dim(` ${O(d.id)}`):""),L=g?[...p.map(k=>er.createElement(Ea,{key:`tag-${k}`,paddingLeft:1},er.createElement(Xr,{id:k}))),...f.map(k=>er.createElement(Ea,{key:`assignee-${k}`,paddingLeft:1},er.createElement($n,{id:k}))),I.length?er.createElement(Ea,{key:"comments",paddingLeft:1},er.createElement(wy,{color:y.accent},"[",I.length," comment",I.length===1?"":"s","]")):null]:[];return er.createElement(Ea,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},er.createElement(wy,{color:y.secondary2},w),L)};import{Box as xN,Text as Py}from"ink";import Ra from"react";var IN=({filters:e})=>Ra.createElement(xN,{columnGap:1},Ra.createElement(Py,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>Ra.createElement(Py,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ly=Ra.memo(IN);import{Box as SN,Text as Ca}from"ink";import Rs from"react";function ky(){let{eventLog:e,unappliedEvents:t}=J(),n=e.at(-1)?.id,r=Us(n??""),o=me(r)?Li(r.value):"INVALID DATE";return Rs.createElement(SN,{paddingLeft:1},Rs.createElement(Ca,{backgroundColor:y.accent,color:y.secondary}," Readonly "),Rs.createElement(Ca,{color:y.accent}," "+t.length+" edits ago at "+o+"."),Rs.createElement(Ca,{color:y.accent}," Resume with "),Rs.createElement(Ca,{backgroundColor:y.accent,color:y.secondary}," ",":peek now"," "))}import{Box as EN,Text as wc}from"ink";import Na from"react";function Dy(){let{replay:e}=J();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return Na.createElement(EN,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},Na.createElement(wc,{backgroundColor:y.accent,color:y.secondary}," \u25B6 REPLAY "),Na.createElement(wc,{color:y.secondary2},Li(new Date(r))),Na.createElement(wc,{color:y.accent},`${t}/${n} edits`))}import Mc from"chalk";import{Box as RN,Text as By}from"ink";import Pc,{useEffect as CN,useState as NN}from"react";var AN=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],TN=150,Fy=12,wN=.36,Oy=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)}},MN=({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)}`},PN=(e,t,n)=>{let r=Oy(e),o=Oy(t);return MN({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},LN=(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 PN(s,i,o)};function _y({syncStatus:e,autoSync:t}){let[n,r]=NN(0);CN(()=>{if(e.status!=="syncing"){r(0);return}let d=0,c=setInterval(()=>{d+=1;let m=(Math.sin(d*wN)+1)/2,p=Math.round(m*(Fy-1));r(f=>f===p?f:p)},TN);return()=>clearInterval(c)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:y.secondary2,failed:y.yellow,offline:y.secondary2,pending:y.secondary2,syncing:LN(AN,n/(Fy-1))??""}[e.status];return Pc.createElement(RN,null,Pc.createElement(By,null,Mc.hex(y.secondary2).dim(t?"Sync (auto): ":"Sync: ")),Pc.createElement(By,null,Mc.hex(i)("\u25CF")+Mc.hex(y.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import Wy from"chalk";import{Text as Gy}from"ink";import Vy,{useEffect as FN,useState as ON}from"react";import Lc from"chalk";var kN="https://registry.npmjs.org/epiq/latest",kc=null,Uy=0,DN=1e3*60*60*24,jy=e=>e.replace(/^v/,""),BN=(e,t)=>{let n=jy(e).split(".").map(Number),r=jy(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},$y=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(kc&&Date.now()-Uy<DN)return kc;try{let t=await fetch(kN);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?BN(r,e)>0:!1};return kc=o,Uy=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Hy=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?Lc.hex(y.accent).dim(s):Lc.hex(y.secondary).dim(s)).join(Lc.hex(y.secondary2).dim("."))};function zy(){let[e,t]=ON({current:sn,latest:null,updateAvailable:!1});return FN(()=>{let n=!0;return $y(sn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Vy.createElement(Gy,{dimColor:!0,color:y.secondary2},sn+" "):Vy.createElement(Gy,null,Wy.hex(y.secondary2).dim(sn),Wy.hex(y.accent).dim(" \u2197 "),Hy(sn,e.latest))}function Ns({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=J(),{userName:i,preferredEditor:d,autoSync:c}=le(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?yn(s.currentLabel,Math.max(0,p)):"";return ke.createElement(Cs,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?ke.createElement(Cs,{paddingLeft:1},ke.createElement(go,{color:y.secondary2},g)):f?ke.createElement(go,null," "):o===b.PALETTE?ke.createElement(Cs,null,ke.createElement(go,{color:y.accent},"Command Palette"),ke.createElement(go,{dimColor:!0,color:y.secondary2}," ","- search, select and press enter")):ke.createElement(Cs,{paddingLeft:1},e.length>0?ke.createElement(Ly,{filters:e}):ke.createElement(My,{width:p})),n==="live"?ke.createElement(Cs,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},ke.createElement(_y,{autoSync:!!c,syncStatus:r}),ke.createElement(go,null,Aa.hex(y.secondary2).dim("Mode: ")+Aa.hex(y.secondary2).dim(o.padEnd(8," "))," "),ke.createElement(Ky,{icon:"@",value:i}),ke.createElement(Ky,{icon:"\u276F",value:d}),ke.createElement(zy,null)):"",n==="peek"?ke.createElement(ky,null):"",n==="replay"?ke.createElement(Dy,null):"")}function Ky({icon:e,value:t}){return ke.createElement(go,null,Aa.dim(e)+Aa.hex(y.accent)(` ${t??"-"} `))}import{Box as _N,Text as UN}from"ink";import As from"react";import{Box as Ta,Text as Dc}from"ink";import tr from"react";function Bc(){let e=J(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?X(t?.id):[];return tr.createElement(Ta,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:y.secondary,width:s},tr.createElement(Ta,{padding:1,paddingTop:0,paddingBottom:0},tr.createElement(Dc,null,"Select a board:")),tr.createElement(Ta,{padding:1,flexDirection:"column"},i.map((d,c)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===c,f=X(d.id).flatMap(({id:g})=>de(g)).length;return tr.createElement(Ta,{key:d.id??c},tr.createElement(Dc,{color:m?y.accent:y.secondary2},tr.createElement(et,{isSelected:m})),tr.createElement(Dc,{color:m?y.accent:y.secondary2},d.title," (",f," issues)",d.readonly?" \u{1F512}":""))})))}var jN=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:d}=J(),c=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return As.createElement(_N,{flexDirection:"row"},e.context==="WORKSPACE"?As.createElement(Bc,null):c?As.createElement(Bi,{height:f,width:i,swimlanes:(d[c.id]??[]).filter(g=>g!==void 0&&Kt(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):As.createElement(UN,null))},qy=As.memo(jN);import{useEffect as $N}from"react";var HN=e=>{$N(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=le();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:d,mode:c}=h();c==="default"&&!d&&mi(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},Yy=({autoSync:e})=>(HN(e),null);function Fc({width:e,height:t}){let n=J(),{autoSync:r,viewMode:o}=vu(),s=n.filters;if(n.mode===b.HELP)return Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ay,{width:e,height:t}));if(n.mode===b.PALETTE)return Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ns,{filters:s}),Re.createElement(dy,{width:e,height:t-2}),Re.createElement(Es,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=_n(),d=!i,c=i&&!n.hasProjectDefinition;if(d)return Re.createElement(nr,{flexDirection:"column"},Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ns,{hideBreadCrumb:!0,filters:s}),Re.createElement(Tc,{height:t,width:e})),Re.createElement(Es,{width:e,mode:n.mode,availableHints:[]}));if(c)return Re.createElement(nr,{flexDirection:"column"},Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ns,{hideBreadCrumb:!0,filters:s}),Re.createElement(Ty,{height:t,width:e})),Re.createElement(Es,{width:e,mode:n.mode,availableHints:[]}));let m=ot(n.breadCrumb??[],"BOARD");if(me(m)){let p=m.value.id,f=X(p).length,g=3,v=Math.floor(e/g),I=Math.floor(e/Math.max(f,1));e=Math.min(I,v)*Math.max(f,g)}return Re.createElement(nr,{flexDirection:"column"},Re.createElement(Yy,{autoSync:r}),Re.createElement(nr,{flexDirection:"column"},Re.createElement(Ns,{filters:s}),Re.createElement(qy,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),Re.createElement(Es,{width:e,mode:n.mode,availableHints:n.availableHints}))}import WN from"readline";var wa,Ma,dn,GN=new Set([S.MoveCursorLeft,S.EraseInputWord,S.MoveCursorLeftOfWord,S.MoveCursorRight,S.MoveCursorRightOfWord,S.NavToPreviousContainer,S.NavToNextContainer,S.NavPreviousItem,S.NavNextItem,S.SetViewDense,S.SetViewWide,S.Confirm,S.Exit,S.Yank,S.InitCommandLine,S.InitCommandPalette,S.ExitCommandLine,S.CaptureInput,S.EraseInput,S.EraseInputWord,S.HideHelp,S.ViewHelp,S.SetViewDense,S.SetViewWide,S.GetLastCommandFromHistory,S.GetNextCommandFromHistory,S.AutoCompleteCommand]),VN=new Set([S.NavPreviousItem,S.NavNextItem,S.NavToPreviousContainer,S.NavToNextContainer,S.Confirm,S.Exit,S.InitCommandPalette,S.InitMove,S.MoveNextItem,S.MovePreviousItem,S.MoveToNextContainer,S.MoveToPreviousContainer,S.Delete,S.AddItem,S.EditTitle,S.EditDescription,S.ConfirmMove,S.Edit,S.ViewHelp,S.Yank]),Xy=async e=>{if(e.ctrl&&e.name==="c")return _.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=h(),s=Gp(e,n);if(!s||r&&!GN.has(s)||o==="replay"&&n===b.DEFAULT&&VN.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(d){logger.error(d)}},zN=()=>async function(t,n){n.name!=="escape"&&(dn&&(clearTimeout(dn),dn=void 0),await Xy(n))},KN=()=>async function(t){if(t.length===1&&t[0]===27){dn&&clearTimeout(dn),dn=setTimeout(()=>{Xy({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),dn=void 0},25);return}dn&&(clearTimeout(dn),dn=void 0)};function Jy(){wa&&process.stdin.removeListener("keypress",wa),Ma&&process.stdin.removeListener("data",Ma),wa=zN(),Ma=KN(),WN.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Ma),process.stdin.on("keypress",wa)}async function Qy(){try{let e=Lr({});if(a(e))return _t(0,e.message);let t=bt();me(t)&&Ye(t.value);let n=Se(process.cwd()),r=me(n)?await $i(n.value):Xf();if(a(r))return r;let o=Oc();return a(o)?_t(6,o.message):(Jy(),me(n)&&Hi(n.value),u("Booted Epiq",void 0))}catch(e){return _t(0,jr(e))}}Pf();var JN=`${Wt.bold("Epiq CLI")}
|
|
91
|
+
${l}
|
|
92
|
+
`,Xd.writeFileSync(t,n,"utf8"),se.info(`Added ${s.join(", ")} to .gitignore (epiq local state)`),u("Local epiq paths ignored",!0)};var gN=async e=>{let t=await j({cwd:e,args:["status","--porcelain"]});return a(t)?t:u("Checked git diff",t.value.stdout.split(`
|
|
93
|
+
`).filter(n=>n.trim().length>0).map(n=>n.slice(3)))},ue=(e,t)=>c(`[${e}] ${t}`),py=async({cwd:e,user:t})=>{let n=Bi(),r=await qt(e);if(a(r))return ue(1,r.message);let o=r.value,s=await Cm(o);if(a(s))return ue(2,s.message);if(s.value)return ue(2,`Cannot initialize Epiq while a git operation is in progress: ${s.value}`);let i=await gN(o);if(a(i))return ue(2.5,i.message);if(i.value.length>0)return ue(3,`Cannot initialize Epiq with uncommitted changes (${i.value.join(", ")}). Commit or stash your changes first.`);if(ps(o))return ue(4,"Epiq project already initialized");let{userId:l,userName:d}=t;if(!l||!d)return ue(5,"Missing Epiq user id");let m=await Og(o);if(a(m))return ue(6,m.message);let p=n.stateBranch,f=await $i({repoRoot:o,branch:p});if(a(f))return ue(6,f.message);if(f.value)return ue(6,`State branch already exists: ${p}`);let g=await hN({repoRoot:o,stateBranch:p});if(a(g))return ue(6,g.message);if(g.value)return yN({repoRoot:o,stateBranch:p});let y=await dd({repoRoot:o,stateBranchName:p});if(a(y))return ue(6,y.message);let x=ds();if(a(x))return ue(7,x.message);let b=Jd.join(Pr(),n.projectId),R=await dr({repoRoot:o,stateBranchRoot:b,stateBranchName:p});if(a(R))return ue(8,R.message);let S=Jd.join(b,".epiq");fN.mkdirSync(S,{recursive:!0});let T=Cg({userId:l,userName:d});if(a(T))return ue(9,T.message);for(let ft of T.value){let io=ig({event:ft,rootDir:b});if(a(io))return ue(9,io.message)}let A=ir({userId:l}),P=ua(b,A);if(a(P))return ue(9,P.message);let M=cd(b,n);if(a(M))return ue(9,M.message);let O=await Aa({stateBranchRoot:b,eventFileName:A});if(a(O))return ue(10,O.message);let W=await Ae.stage({cwd:b,pathspec:[ut]});if(a(W))return ue(10,W.message);let X=await fo({cwd:b,message:"[epiq:init]"});if(a(X))return ue(10,X.message);let Ee=await my(o);if(a(Ee))return ue(11,Ee.message);let F=Ql({repoRoot:o,fileContents:n});if(a(F))return ue(12,F.message);let J=await Ae.stage({cwd:o,pathspec:[".epiq/project.json",".gitignore"]});if(a(J))return ue(13,J.message);let Ke=await Ae.commit({cwd:o,message:"[epiq:init-project]",pathspec:[".epiq/project.json",".gitignore"]});if(a(Ke))return ue(13,Ke.message);let Jn=[],os=await j({cwd:o,args:["push","-u","origin","HEAD"]});a(os)&&Jn.push(`[init:14] ${os.message}`);let it=await js({repoRoot:o,stateBranchRoot:b});return a(it)&&Jn.push(`[init:15] ${it.message}`),u("Project initialized",{repoRoot:o,projectId:n.projectId,stateBranch:p,stateBranchRoot:b,defaultEvents:T.value,warnings:Jn})},hN=async({repoRoot:e,stateBranch:t})=>{let n=await Bn({repoRoot:e});if(a(n))return c(n.message);if(!n.value)return u("No remote",!1);let r=await is({repoRoot:e,branch:t});return a(r)?c(`Could not ask origin whether ${t} exists: ${r.message}`):r},yN=async({repoRoot:e,stateBranch:t})=>{let n=await j({cwd:e,args:["fetch","origin",t]});if(a(n))return ue(6,n.message);let r=await j({cwd:e,args:["show",`origin/${t}:${ut}`]});if(a(r))return ue(6,[`This repository is already an epiq project: origin has the state branch ${t}.`,"Initialising again would mint a second id for the same board.","","The branch was written before branches carried their identity, so restore",`${ut} from a checkout that has it, for example:`,"",` git show origin/main:${ut} > ${ut}`,"","and commit it; every later boot then stamps the branch, and the next clone adopts it."].join(`
|
|
94
|
+
`));let o;try{o=JSON.parse(r.value.stdout)}catch(x){return ue(6,`The identity on origin/${t} is not readable: ${x instanceof Error?x.message:String(x)}`)}let s=Ql({repoRoot:e,fileContents:o});if(a(s))return ue(12,s.message);let i=await Ae.stage({cwd:e,pathspec:[ut]});if(a(i))return ue(13,i.message);let l=await Ae.commit({cwd:e,message:"[epiq:adopt-project]",pathspec:[ut]});if(a(l))return ue(13,l.message);let d=ds();if(a(d))return ue(7,d.message);let m=Jd.join(Pr(),o.projectId),p=await Us({repoRoot:e,stateBranchName:t});if(a(p))return ue(8,p.message);let f=await dr({repoRoot:e,stateBranchRoot:m,stateBranchName:t});if(a(f))return ue(8,f.message);let g=[],y=await j({cwd:e,args:["push","-u","origin","HEAD"]});return a(y)&&g.push(`[init:14] ${y.message}`),u("Adopted the project origin already holds",{repoRoot:e,projectId:o.projectId,stateBranch:o.stateBranch,stateBranchRoot:m,defaultEvents:[],warnings:g})};var Qs=(e,t)=>c(`[${e}] ${t}`),fy=async()=>{Q("");let e=Un();if(!e.isSetupDone||!e.userName)return Qs(5,"Missing Epiq user configuration (userId / userName). Run setup first.");let t=V(),n=t.userName,r=t.userId;if(!r||!n)return Qs(5,"Missing Epiq user id");let o=await py({cwd:process.cwd(),user:{userId:r,userName:n}});if(a(o))return o;let s="Project initialized!";for(let g of o.value.warnings)s+=` Warn: ${g}`;let l=Qt(o.value.defaultEvents).filter(a);if(l.length>0)return Qs(16,l.map(g=>g.message).join(`
|
|
95
|
+
`));let d=xe();if(a(d))return Qs(16,d.message);let{rootNodeId:m,nodes:p}=d.value,f=p[m];return f?(U.navigate({contextNode:f,selectedIndex:0}),w({hasProjectDefinition:!0}),u(s,null)):Qs(16,"Unable to resolve initialized root node")};import{ulid as bN}from"ulid";import{ulid as vN}from"ulid";var gy=null,on=()=>structuredClone(gy),Zs=e=>{gy=e},hy=()=>{let{contextNode:e,selectedIndex:t}=v(),r=Ie(e.id)[t];return r?u("Resolved selected child",r):c("Target node not found")},Qd=({id:e,parentId:t,position:n={at:"end"}})=>{let r=Ie(t).filter(o=>o.id!==e);return Ia(r,n)},yy=({id:e,parentId:t,position:n={at:"end"}})=>{let r=pe();if(a(r))return c("Unable to resolve user ID");let o=Qd({parentId:t,id:e,position:n});return a(o)?o:u("Created pending move state",{id:vN(),...r.value,action:"move.node",payload:{id:e,parent:t,rank:o.value.rank}})},vy=e=>{Zs(e);let t=Os(e,!0);return a(t)?t:u("Node moved successfully",t.value)};function Zd(e){let t=hy();if(a(t))return t;let{contextNode:n,nodes:r}=v();if(!n.parentNodeId)return c("Missing parent node id");let o=r[n.parentNodeId];if(!o)return c("Missing parent node");let s=Ie(o.id),i=s.findIndex(({id:m})=>m===n.id);if(i<0)return c("Current node not found among siblings");let l=s[i+e];if(!l)return c("Missing sibling node");let d=yy({id:t.value.id,parentId:l.id,position:{at:"end"}});return a(d)?d:vy(d.value)}function ei(e,t=1){let n=hy();if(a(n))return n;let{contextNode:r,selectedIndex:o}=v(),s=Ie(r.id),i=Math.min(Math.max(o+e*t,0),s.length-1),l=i===o?void 0:s[i];if(!l)return c("Missing sibling node");let d=yy({id:n.value.id,parentId:r.id,position:{at:e===1?"after":"before",sibling:l.id}});return a(d)?d:vy(d.value)}var by=()=>{let e=on();if(!e)return c("No pending move state");let t=e.payload.id,n=e.payload.parent,r=v().nodes[n];if(!r)return c("Move parent not found");let o=Ie(n).findIndex(s=>s.id===t);return o===-1?c("Moved node not found among rendered children"):(U.navigate({contextNode:r,selectedIndex:o}),u("Synchronized navigation to moved node",null))},Vo=(e,t="Moved preview")=>{if(a(e))return on()&&w({mode:I.MOVE}),e;let n=by();return a(n)?n:(w({mode:I.MOVE}),u(t,null))},xy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t}=ae().commandMeta,{contextNode:n,selectedIndex:r}=v(),o=Ie(n.id)[r];if(!o)return w({mode:I.DEFAULT}),c("No move target");if(t==="start"){if(o.readonly)return c("Target node is read-only");if(r===-1)return c("No item selected");if(!o.parentNodeId)return c("Target has no parent");let s=Ie(o.parentNodeId),i=s.findIndex(({id:f})=>f===o.id);if(i===-1)return c("Target not found among siblings");let l=s[i-1],d=s[i+1],m=d!=null?{at:"before",sibling:d.id}:l!=null?{at:"after",sibling:l.id}:{at:"start"},p=Qd({parentId:o.parentNodeId,id:o.id,position:m});return a(p)?p:(Zs({id:bN(),action:"move.node",payload:{id:o.id,parent:o.parentNodeId,rank:p.value.rank},...D(e.value)}),w({mode:I.MOVE}),u("Move initialized",null))}if(t==="next")return Vo(ei(1));if(t==="previous")return Vo(ei(-1));if(t==="jump-next")return Vo(ei(1,Fs));if(t==="jump-previous")return Vo(ei(-1,Fs));if(t==="to-next")return Vo(Zd(1));if(t==="to-previous")return Vo(Zd(-1));if(t==="confirm"){let s=on();if(!s)return c("No pending move to confirm");let i=await Se();if(a(i))return i;let l=B([s],i.value);if(a(l))return l;let d=by();return a(d)?d:(Zs(null),w({mode:I.DEFAULT}),u("Moved item",null))}return t==="cancel"?(Zs(null),w({mode:I.DEFAULT}),u("Cancelling move",null)):c("Invalid move modifier")};import{ulid as Za}from"ulid";import{monotonicFactory as xN,ulid as IN}from"ulid";var EN=xN(),Qa=({name:e,parent:t,rank:n,user:{userId:r}})=>{let o=EN();return u("Created issue events",[{id:IN(),userId:r,action:"add.issue",payload:{id:o,parent:t,name:e,rank:n}}])};var Iy=async(e,t)=>{let n=pe();if(a(n))return c("Unable to resolve user ID");let r=await Se();if(a(r))return r;let o=r.value;if(!t.inputString)return c(`provide a name for your ${t.modifier}`);let{breadCrumb:s,contextNode:i,selectedIndex:l}=v(),d=m=>{let p=B([m],o);if(a(p))return p;let f=N.getNode(p.value[0].result.id);if(!f)return c("Created node not found");if(!f.parentNodeId)return p;let g=N.getNode(f.parentNodeId);return g?(U.navigate({contextNode:g,selectedIndex:N.getSiblings(f.parentNodeId).findIndex(({id:y})=>y===f.id)}),p):c("Parent node not found")};if(t.modifier==="board"){let{rootNodeId:m}=v(),p=N.getNode(m);if(!p)return c("Workspace not found");let f=Hn(p.id,n.value,o);return a(f)?f:d({id:Za(),action:"add.board",payload:{id:Za(),name:t.inputString,parent:p.id,rank:f.value},...D(n.value)})}if(t.modifier==="swimlane"){let m=yt(s,"BOARD");if(a(m))return c("Unable to add swimlane in this context");let p=Hn(m.value.id,n.value,o);return a(p)?p:d({id:Za(),action:"add.swimlane",payload:{id:Za(),name:t.inputString,parent:m.value.id,rank:p.value},...D(n.value)})}if(t.modifier==="issue"){let m=de(i.id)[l],p=i.context==="SWIMLANE"?i:i.context==="BOARD"&&m?.context==="SWIMLANE"?m:(()=>{let T=yt(s,"SWIMLANE");return a(T)?null:T.value})();if(!p)return c("Unable to add issue in this context");let f=Hn(p.id,n.value,o);if(a(f))return f;let g=Qa({name:t.inputString,parent:p.id,rank:f.value,user:n.value});if(a(g))return g;let y=g.value,x=B([...y],o);if(a(x))return x;if(!x.value[0])return c("Issue creation failed");let S=y.find(T=>T.action==="add.issue")?.payload.id;return S?(U.navigate({contextNode:p,selectedIndex:N.getSiblings(p.id).findIndex(({id:T})=>T===S)}),u("Issue created",null)):c("Unable to determine ticket id")}return u("Success",null)};import PN from"node:os";import Ty from"node:path";import ti from"node:fs";import SN from"node:path";import{z as zr}from"zod";var ni="command-history.json",RN=20,CN=zr.object({projectId:zr.string().min(1),commands:zr.array(zr.string()),lastUsedAt:zr.number().finite()}),NN=zr.object({projects:zr.array(CN)}),Ey=()=>{let e=Ys();return a(e)?e:u("Resolved command history path",SN.join(e.value,ni))},AN=()=>{try{let e=me(process.cwd());return a(e)?null:e.value}catch{return null}},Sy=e=>{if(!ti.existsSync(e))return u("No command history recorded",{state:"read",projects:[]});let t;try{t=ti.readFileSync(e,"utf8")}catch(o){return c(`Unable to read ${ni}: ${o instanceof Error?o.message:String(o)}`)}let n;try{n=JSON.parse(t)}catch(o){return u("Unparsable command history",{state:"corrupt",reason:`Invalid ${ni}: ${o instanceof Error?o.message:String(o)}`})}let r=NN.safeParse(n);return r.success?u("Read command history",{state:"read",projects:r.data.projects}):u("Command history in an unknown shape",{state:"corrupt",reason:`Invalid ${ni} shape: ${r.error.issues.map(o=>o.path.join(".")||o.message).join(", ")}`})},Ry=({root:e})=>{let t=dn(e);if(a(t))return c(t.message);let n=Ey();if(a(n))return n;let r=Sy(n.value);if(a(r))return r;let o=r.value;if(o.state==="corrupt")return c(o.reason);let s=o.projects.find(i=>i.projectId===t.value);return u("Read command history",s?.commands.slice(0,As)??[])},Cy=({commands:e,root:t=AN(),now:n=Date.now()})=>{if(t===null)return u("No project; command history not stored",null);let r=dn(t);if(a(r))return c(r.message);let o=Ey();if(a(o))return o;let s=o.value,i=Sy(s);if(a(i))return i;let l=i.value,d=l.state==="read"?l.projects:[],m=[{projectId:r.value,commands:e.slice(0,As),lastUsedAt:n},...d.filter(f=>f.projectId!==r.value)].sort((f,g)=>g.lastUsedAt-f.lastUsedAt).slice(0,RN),p=`${s}.${process.pid}.tmp`;try{ti.writeFileSync(p,JSON.stringify({projects:m},null,2)+`
|
|
96
|
+
`,"utf8"),ti.renameSync(p,s)}catch(f){try{ti.rmSync(p,{force:!0})}catch{}return c(`Unable to write ${ni}: ${f instanceof Error?f.message:String(f)}`)}return u("Stored command history",null)};var TN=e=>e.some(t=>t.action==="init.workspace"),Ny=async(e,t)=>{let n=Ue(e);return a(n)?c(n.message):ls({cwd:t,branch:n.value})},wN=e=>{let t=me(process.cwd());if(a(t))return!1;let n=he({repoRoot:t.value});return!a(n)&&n.value===e},el=async e=>{let t=he({repoRoot:e});if(a(t))return tn(3,t.message);let n=t.value,r=await dr({repoRoot:e,stateBranchRoot:n,stateBranchName:Bi().stateBranch});if(a(r))return tn(3,r.message);let o=Zt(n);if(a(o))return tn(3,o.message);if(!TN(o.value.events)){let p=await Hs({worktreeRoot:n,operation:"boot pull",fn:()=>Ta(n,()=>Ny(e,n))});if(a(p)?logger.info(3,p.message):p.value===null?logger.info(3,"Another process holds the state worktree, skipped pull"):a(p.value)&&logger.info(3,p.value.message),o=Zt(n),a(o))return tn(3,o.message)}let{events:s,unreadable:i}=o.value,l=en(s,i);if(a(l))return tn(4,l.message);w({hasProjectDefinition:!0,hasInitializingEvents:!!s.length});let d=Ji({root:e});a(d)&&logger.info(d.message);let m=Ry({root:e});return a(m)&&logger.info(m.message),mf(a(m)?[]:m.value),u("Loaded project",void 0)},MN=async e=>{let t=he({repoRoot:e});if(a(t))return c(t.message);let n=t.value,r=await Bn({repoRoot:n});if(a(r))return c(r.message);if(!r.value)return u("No remote to pull",void 0);let o=await Hs({worktreeRoot:n,operation:"boot pull",fn:()=>Ta(n,()=>(To("Pulling"),Ny(e,n)))});if(a(o))return Ve(o.message);if(o.value===null)return u("Another process holds the state worktree",void 0);let s=o.value;if(a(s))return as(s.message)?(Ca("Offline"),u("Offline",void 0)):Ve(s.message);if(!s.value)return jr("Already synced"),u("Already synced",void 0);if(!wN(n))return u("Project changed during the pull",void 0);let i=gd(n);return a(i)?i:(jr("Pulled"),u("Pulled and reloaded",void 0))},tl=e=>{MN(e).then(t=>{a(t)&&logger.info(3,t.message)}).catch(t=>{logger.error(`[boot] pull failed: ${wo(t)}`)})},Ay=()=>{let e=en([]);return a(e)?tn(4,e.message):(w({hasProjectDefinition:!1,hasInitializingEvents:!1}),u("Booted without a project",void 0))};var LN=e=>e==="~"||e.startsWith("~/")?Ty.join(PN.homedir(),e.slice(1)):e,kN=(e,t)=>{let n=e.trim();if(!n)return c("Provide a number from the list or a path to a project");if(/^\d+$/.test(n)){let o=t[Number(n)-1];return o?u("Resolved recent project",o.root):c(`No recent project #${n}`)}let r=me(Ty.resolve(LN(n)));return a(r)?c(`No epiq project at ${n}`):u("Resolved project path",r.value)},wy=async()=>{let e=aa();if(Q(""),v().hasProjectDefinition)return c("Already in a project; run epiq from another directory");let t=$n({exclude:process.cwd()}),n=a(t)?[]:t.value,r=kN(e,n);if(a(r))return c(r.message);let o=r.value,s=process.cwd();try{process.chdir(o)}catch(l){return c(`Unable to enter ${o}: ${l instanceof Error?l.message:String(l)}`)}let i=await el(o);return a(i)?(process.chdir(s),c(i.message)):(tl(o),u(`Opened ${Io(o)}`,null))};var nl=({boardId:e,targetTime:t,stateBranchRoot:n,selectedIndex:r})=>{let o=v(),s=ba(n,t);if(a(s))return c(s.message);let{appliedEvents:i,unappliedEvents:l}=s.value,d=sn();if(a(d))return d;let m=Qt(i),{fatal:p,skipped:f}=In(m);if(p.length>0)return sn(),w(o),c(p.map(y=>y.message).join(", "));En(f);let g=v().nodes[e];return g?(U.navigate({contextNode:g,selectedIndex:r}),u("",{unappliedEvents:l})):(sn(),w(o),c("Board did not exist at that date"))};var My=e=>{let t=[],n=0;for(let o=0;o<e.length;o++){let s=o===0?0:Math.max(0,e[o]-e[o-1]);n+=Math.sqrt(s),t[o]=n}let r=n;return t.map((o,s)=>r>0?o/r:(s+1)/e.length)};var DN=20,BN=16,ON=150,rl=null,ol=null;var Kr=()=>{rl!==null&&(clearInterval(rl),rl=null),ol!==null&&(clearTimeout(ol),ol=null)},Py=()=>{Kr(),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null,selectedIndex:0})},Ly=({events:e,startTime:t,durationMs:n})=>{Kr();let r=e.length,o=ho(e.map(f=>er(f))).map(f=>f??t),s=o[r-1]??Date.now(),i=My(o),l=Math.max(1,Math.round(n*DN/1e3)),d=Math.max(Math.round(n/l),BN),m=0,p=0;w({mode:I.DEFAULT,readOnly:!0,timeMode:"replay",unappliedEvents:e,replay:{progress:0,appliedCount:0,totalCount:r,currentTime:t,startTime:t,endTime:s,currentLabel:"",flashNodeIds:[]}}),rl=setInterval(()=>{m++;let f=m/l,g=[],y,x;for(;p<r&&i[p]<=f;){let R=e[p],S=Os(R);if(a(S)){if(Ao(S)){p++;continue}Py();return}g.push(...od(R)),y=R,x=o[p],p++}if(p>=r||m>=l){for(;p<r;p++){let S=Os(e[p]);if(a(S)&&!Ao(S))break}let R=v().replay;w({unappliedEvents:[],replay:R&&{...R,progress:1,appliedCount:r}}),Kr(),ol=setTimeout(Py,ON);return}let b=v().replay;w({unappliedEvents:e.slice(p),replay:{progress:Math.min(1,f),appliedCount:p,totalCount:r,startTime:t,endTime:s,currentTime:y?x??b?.currentTime??t:b?.currentTime??t,currentLabel:y?sl(y):b?.currentLabel??"",flashNodeIds:y?[...new Set(g)]:b?.flashNodeIds??[]}})},d)};var ky=async()=>{let e=yt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await qt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=he({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ae().commandMeta;if(Kr(),r==="now"){let l=cr(n.value);if(a(l))return c(l.message);let d=sn();if(a(d))return d;let m=Qt(l.value),{fatal:p,skipped:f}=In(m);return p.length>0?c(p.map(g=>g.message).join(", ")):(En(f),w({mode:I.DEFAULT,readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Peeking now",!0))}let s;if(r==="prev"||r==="next"){let l=xa(n.value);if(a(l))return l;let d=r==="prev"?v().eventLog.at(-1):v().unappliedEvents.at(0),m=d===void 0?null:er(d),p=(d===void 0?null:l.value.get(d.id)??null)??(m===null?null:gs(m));if(p===null)return c(r==="prev"?"No previous event to peek":"No next event to peek");s=r==="prev"?p:p+1}else{let l=Lr(r||o.trim());if(!l)return c("Invalid peek date");s=l.getTime()}let i=nl({boardId:e.value.id,targetTime:s,stateBranchRoot:n.value,selectedIndex:0});return a(i)?i:(w({mode:I.DEFAULT,readOnly:!0,timeMode:"peek",unappliedEvents:i.value.unappliedEvents,replay:null}),u("Peeking",!0))};var Dy=async()=>{let e=yt(v().breadCrumb,"BOARD");if(a(e))return e;let t=await qt(process.cwd());if(a(t))return c("Unable to locate repo root");let n=he({repoRoot:t.value});if(a(n))return n;let{modifier:r,inputString:o}=ae().commandMeta,{dateInput:s,durationInput:i}=na(r,o);if(Kr(),v().syncStatus.status==="syncing")return c("Cannot replay while syncing, try again in a moment");let l=Lr(s);if(!l)return c("Invalid replay date");let d=i?ta(i):15e3;if(d===null)return c("Invalid replay duration (try e.g. 30s or 2m)");let m=l.getTime(),p=v(),f=nl({boardId:e.value.id,targetTime:m,stateBranchRoot:n.value,selectedIndex:-1});if(a(f))return f;let{unappliedEvents:g}=f.value;return g.length===0?(sn(),w(p),u("Nothing to replay from that point",!0)):(Ly({events:g,startTime:m,durationMs:d}),u("Replaying board history",!0))};import{spawn as _N}from"node:child_process";var $N=()=>{switch(process.platform){case"darwin":return{command:"pbcopy",args:[]};case"win32":return{command:"clip",args:[]};default:return process.env.WAYLAND_DISPLAY?{command:"wl-copy",args:[]}:{command:"xclip",args:["-selection","clipboard"]}}},By=async e=>new Promise(t=>{let{command:n,args:r}=$N();try{let o=_N(n,r,{stdio:["pipe","ignore","ignore"]});o.on("error",()=>t(c(`Clipboard tool not available (${n})`))),o.on("close",s=>t(s===0?u("Copied to clipboard",null):c(`Clipboard tool failed (${n})`))),o.stdin.on("error",()=>{}),o.stdin.write(e),o.stdin.end()}catch{t(c(`Clipboard tool not available (${n})`))}});var ri=async(e,t)=>{if(!e.trim())return c(`Nothing to copy: ${t} is empty`);let n=await By(e);return a(n)?n:u(`Copied ${t} to clipboard`,null)},Oy=async e=>{let{breadCrumb:t,selectedNode:n}=v(),r=Es({breadCrumb:t,selectedNode:n}),o=r??n;if(!o)return c("Nothing selected to copy from");switch(e.modifier){case Xe.REF:return ri(H(o.id),"ref");case Xe.TITLE:return ri(o.title,"title");case Xe.DESCRIPTION:return r?ri(r.props?.description??"","description"):c("No issue in scope");case Xe.TAGS:{if(!r)return c("No issue in scope");let s=hn(r).map(({name:i})=>i);return ri(s.join(", "),"tags")}case Xe.ASSIGNEES:{if(!r)return c("No issue in scope");let s=yn(r).map(({name:i})=>i);return ri(s.join(", "),"assignees")}default:return c("Yank one of: ref, title, description, tags, assignees")}};var Fy=async()=>{Q(""),w({mode:I.DEFAULT});let e=xe();if(a(e))return c(e.message);if(e.value.syncStatus.status==="syncing")return c("Sync already in progress");w({syncStatus:{msg:"Syncing",status:"syncing"}});let t=await Ma();return a(t)?(w({syncStatus:{msg:t.message,status:"failed"}}),t):(w({mode:I.DEFAULT,syncStatus:{msg:"Synced",status:"synced"}}),t)};import{ulid as _y}from"ulid";var $y=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to resolve child to delete");let o=await Se();if(a(o))return o;if(r.context==="COMMENT"){let s=r.id,i=_(t)?t.id:t.parentNodeId;if(!i)return c("Unable to resolve comment issue");let l=v().nodes[i];if(!l||!_(l))return c("Unable to resolve comment issue");let d=l.log?.filter(ah).find(m=>m.payload.id===s);return d?d.payload.author!==e.value.userId?c("You can only delete your own comments"):B([{id:_y(),action:"delete.issue.comment",payload:{id:s,issue:i},...D(e.value)}],o.value):c("Unable to resolve comment")}return B([{id:_y(),action:"delete.node",payload:{id:r.id},...D(e.value)}],o.value)};import{ulid as UN}from"ulid";var Uy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to close issue, no target found");if(!_(r))return c("Cannot close in this context");let o=v().nodes[ye];if(!o)return c("Unable to locate closed swimlane");if(r.parentNodeId===o.id)return c("Issue is already closed");let s=await Se();if(a(s))return s;let i=s.value,l=Sn(o.id,r.id,{at:"end"},e.value,i);if(a(l))return l;let d=B([{id:UN(),action:"close.issue",payload:{id:r.id,parent:o.id,rank:l.value},...D(e.value)}],i);return a(d)?d:u("Issue closed",null)};import{ulid as jN}from"ulid";var il=e=>{let t=e.log??[];for(let n=t.length-1;n>=0;n--){let r=t[n];if(r&&r.action==="close.issue"&&r.payload.id===e.id){for(let o=n-1;o>=0;o--){let s=t[o];if(s&&"id"in s.payload&&s.payload.id===e.id&&"parent"in s.payload&&s.payload.parent)return s.payload.parent}return null}}return null};var jy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Unable to reopen issue, no target found");let o=r.context==="TICKET"?u("Resolved ticket",r):Nt(r.id,"TICKET");if(a(o))return c("Cannot reopen in this context");let s=o.value,i=v().nodes[ye];if(!i)return c("Unable to locate closed swimlane");if(s.parentNodeId!==i.id)return c("Issue is not closed");if(!_(s))return c("Target node is not issue");let l=il(s);if(!l)return c("Unable to resolve previous parent from issue history");if(l===i.id)return c("Previous parent resolves to closed swimlane");let d=v().nodes[l];if(!d)return c("Previous parent no longer exists");let m=await Se();if(a(m))return m;let p=m.value,f=Sn(d.id,s.id,{at:"end"},e.value,p);if(a(f))return f;let g=B([{id:jN(),action:"reopen.issue",payload:{id:s.id,parent:d.id,rank:f.value},...D(e.value)}],p);return a(g)?g:u("Issue reopened",null)};import{ulid as HN}from"ulid";var Hy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{contextNode:t,selectedIndex:n}=v(),r=de(t.id)[n];if(!r)return c("Missing node");if(r.readonly)return c("Cannot rename readonly node");let o=aa();if(!o)return c("Provide a title");let s=await Se();return a(s)?s:B([{id:HN(),action:"edit.title",payload:{id:r.id,name:o},...D(e.value)}],s.value)};import{ulid as WN}from"ulid";var Wy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let o=N.findTagByName(r);if(!o)return c(`Tag "${r}" does not exist`);let{selectedNode:s}=v();if(!s)return c("Invalid untag target");let i=Nt(s.id,"TICKET");if(a(i))return c("Unable to untag issue in this context");let l=i.value;if(!_(l))return c("Target node is not issue");if(!(l.props.tags??[]).includes(o.id))return c("Issue is not tagged with that tag");let m=await Se();return a(m)?m:B([{id:WN(),action:"remove.issue.tag",payload:{id:l.id,tag:o.id},...D(e.value)}],m.value)};import{ulid as eu}from"ulid";var Gy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide a tag");let{selectedNode:o}=v();if(!o)return c("Invalid tag target");let s=Nt(o.id,"TICKET");if(a(s))return c("Unable to tag issue in this context");let i=s.value;if(!_(i))return c("Target node is not issue");let l=await Se();if(a(l))return l;let d=N.findTagByName(r),m=d?.id??eu();return(i.props.tags??[]).includes(m)?c("Already tagged with that tag"):B([...d?[]:[{id:eu(),action:"create.tag",payload:{id:m,name:r},...D(e.value)}],{id:eu(),action:"add.issue.tag",payload:{id:i.id,tag:m},...D(e.value)}],l.value)};import{ulid as tu}from"ulid";var oi=({events:e,registry:t,logFileNames:n})=>{let r=new Map(n),o=new Set;for(let s of e)s.userId&&(r.has(s.userId)||r.set(s.userId,""),o.add(s.userId));for(let s of Object.values(t))r.set(s.id,s.name);return[...r.entries()].map(([s,i])=>({id:s,name:i,isExternal:!o.has(s)}))},Vy=({authorName:e,authorEmail:t,owners:n,registry:r})=>{let o=et(t),s=n.get(o),i=s?r[s]:void 0;return s?{...Ye(s,i?.name),resolved:!0}:{...Ye(o||e,e),resolved:!1}};var al=e=>{let{eventLog:t=[],contributors:n}=v();return oi({events:t,registry:n,logFileNames:lr(e)})};var zy=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee");let o=r.startsWith("!"),s=(o?r.slice(1):r).trim();if(!s)return c("Provide an assignee");let{selectedIndex:i,contextNode:l}=v(),d=de(l.id)[i];if(!d)return c("Invalid assign target");let m=Nt(d.id,"TICKET");if(a(m))return c("Unable to assign issue in this context");let p=m.value;if(!_(p))return c("Target node is not issue");let f=await Se();if(a(f))return f;let g=al(f.value),y=!o&&s.toLowerCase()==="me",x,b;if(y)x=e.value.userId,b=g.find(T=>T.id===x)?.name??e.value.userName;else{let T=g.filter(P=>P.name===s);if(T.length>1)return c(`"${s}" matches ${T.length} contributors (${T.map(P=>P.id).join(", ")}). Assign from the GUI to choose by id.`);let A=T[0];if(!A&&!o)return c(`No contributor named "${s}". Use "!${s}" to add them as an external assignee.`);x=A?.id??tu(),b=A?.name??s}if((p.props.assignees??[]).includes(x))return c("Assignee already assigned");let S=!!v().contributors[x];return B([...S?[]:[{id:tu(),action:"create.contributor",payload:{id:x,name:b},...D(e.value)}],{id:tu(),action:"add.issue.assignee",payload:{id:p.id,assignee:x},...D(e.value)}],f.value)};import{ulid as GN}from"ulid";var Ky=async()=>{let e=pe();if(a(e))return c("Unable to resolve user ID");let{modifier:t,inputString:n}=ae().commandMeta,r=(t||n).trim();if(!r)return c("Provide an assignee to remove");let{selectedNode:o}=v();if(!o)return c("Invalid unassign target");let s=Nt(o.id,"TICKET");if(a(s))return c("Unable to unassign in this context");let i=s.value;if(!_(i))return c("Target node is not issue");let l=i.props.assignees??[],d=r.toLowerCase()==="me",m=await Se();if(a(m))return m;let p=d?l.filter(g=>g===e.value.userId):al(m.value).filter(g=>g.name===r&&l.includes(g.id)).map(g=>g.id);if(p.length>1)return c(`"${r}" matches ${p.length} assignees (${p.join(", ")}). Unassign from the GUI to choose by id.`);let f=p[0];return f?B([{id:GN(),action:"remove.issue.assignee",payload:{id:i.id,assignee:f},...D(e.value)}],m.value):c(d?"Issue is not assigned to you":`Issue is not assigned to "${r}"`)};import{ulid as qy}from"ulid";var VN=e=>{let t=e.trim(),n=hr(),r=n?Fh(t):null;if(!n||!r)return{ok:!0,md:t,anchored:!1};let o=Ka();if(!o||o.sha!==n)return{ok:!1,reason:"No diff is open"};let s=_h(o.rows,Math.max(0,v().selectedIndex));if(!s)return{ok:!1,reason:"That line is not in a file"};let i=$h(o.rows,s,r.start,r.end);return i.ok?{ok:!0,anchored:!0,md:yh({filePath:i.value.filePath,start:i.value.start,end:i.value.end,side:"additions",endSide:"additions",note:r.note,sha:n,snippet:i.value.snippet})}:{ok:!1,reason:i.reason}},Yy=async e=>{let t=VN(e.inputString);if(!t.ok)return c(t.reason);let{md:n,anchored:r}=t;if(!n)return c("Provide a comment");if(n.length>4e3)return c(r?`The note and the ${n.length} characters of quoted lines exceed ${4e3}; comment on fewer lines`:`Cannot exceed ${4e3} characters`);let o=pe();if(a(o))return c("Unable to resolve user ID");let{breadCrumb:s,selectedNode:i}=v(),l=yt([...s,i],"TICKET");if(a(l))return c("Edit target must be an issue");let d=l.value;if(!d)return c("Invalid comment target");let m=d.context==="TICKET"?u("Resolved ticket",d):Nt(d.id,"TICKET");if(a(m))return c("Unable to comment on issue in this context");let p=m.value;if(!_(p))return c("Target node is not issue");let f=await Se();if(a(f))return f;let g=await B([{id:qy(),action:"add.issue.comment",payload:{id:qy(),issue:p.id,author:o.value.userId,md:n},...D(o.value)}],f.value);return r&&!a(g)&&Gr(null),g};import{ulid as JN}from"ulid";var ll=e=>e.userName?.trim()?e.preferredEditor?.trim()?null:"no editor configured":"no username configured",zN=e=>{let t=ht();return a(t)?ll({userName:e.userName,preferredEditor:e.preferredEditor})??t.message:ll(t.value)},si=()=>{let e=pn();return a(e)?c(e.message):u("Read auto sync settings",{enabled:e.value.autoSync===!0,intervalMs:uo(e.value.autoSyncDebounceMs),blockedReason:zN(e.value)})},zo=e=>{let t=e.intervalMs===void 0?void 0:co(e.intervalMs);if(e.intervalMs!==void 0&&t===null)return c(`Auto sync interval must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=si();if(a(n))return n;let r=Bt({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncDebounceMs:t}});if(a(r))return c(r.message);je({...e.enabled===void 0?{}:{autoSync:e.enabled},...t==null?{}:{autoSyncIntervalMs:t}});let o=si();return a(o)?u("Changed auto sync settings",{...n.value,...e.enabled===void 0?{}:{enabled:e.enabled},...t==null?{}:{intervalMs:t}}):o};var Xy=()=>{let e=ae().commandMeta.inputString,t=co(e);if(t===null)return c(`Auto sync duration must be a whole number of milliseconds between ${3e3} and ${864e5}`);let n=zo({intervalMs:t});return a(n)?n:u(`Auto sync interval set to ${t}ms`,null)};var Jy=()=>{let e=ae().commandMeta.inputString.trim();if(e!=="on"&&e!=="off")return c("Invalid response");let t=Lp(e),n=zo({enabled:t===!0});return a(n)?n:u(`Auto sync set to "${e}"`,null)};import{ulid as YN}from"ulid";var nu=e=>e.toLowerCase().split(/[^a-z0-9]+/).filter(t=>t.length>=2),Qy="",Zy=new Map,KN=15e3;var qN=async(e,t)=>{let n=`${e} ${t??""}`,r=Zy.get(n);if(r&&Date.now()-r.at<_a(KN))return u("Cached author scan",r.authors);let o=await De({cwd:e,args:["log","--branches",...t?["--not",t]:[],`--format=%an${Qy}%ae`]});if(o.exitCode!==0)return c(`Could not read this repository's history: ${(o.stderr??"").trim()||`git exited ${o.exitCode}`}`);let s=new Map;for(let i of(o.stdout??"").split(`
|
|
97
|
+
`)){let l=i.lastIndexOf(Qy);if(l===-1)continue;let d=i.slice(0,l),m=et(i.slice(l+1));if(!tr(m))continue;let p=s.get(m)??{names:new Set,commits:0};d&&p.names.add(d),p.commits+=1,s.set(m,p)}return Zy.set(n,{at:Date.now(),authors:s}),u("Scanned repository authors",s)},wn=async({repoRoot:e,stateBranch:t,names:n,links:r})=>{let o=await qN(e,t);if(a(o))return c(o.message);let s=o.value,i=new Map;for(let d of Object.values(r)){if(d.tombstoned)continue;let m=i.get(d.email)??new Set;m.add(d.contributor),i.set(d.email,m)}let l=new Set(n.flatMap(d=>nu(d??"")));return u("Found candidates",[...s.entries()].map(([d,m])=>({email:d,names:[...m.names],commits:m.commits,looksLikeYours:[...m.names].some(p=>nu(p).some(f=>l.has(f)))||nu(d.split("@")[0]??"").some(p=>l.has(p)),claimedBy:[...i.get(d)??[]]})).sort((d,m)=>d.looksLikeYours===m.looksLikeYours?m.commits-d.commits:Number(m.looksLikeYours)-Number(d.looksLikeYours)))},br=e=>e.filter(t=>t.claimedBy.length===0);var ev=()=>{let e=Tc();if(!e)return u("Nothing here to decline",null);let t=pn(),n=a(t)?[]:t.value.declinedEmailBoards??[],r=[...new Set([...n,e])],o=Bt({declinedEmailBoards:r});return a(o)?c(o.message):(je({declinedEmailBoards:[...new Set([...V().declinedEmailBoards??[],e])]}),u("Declined",null))},tv=async()=>{let e=ae().commandMeta.inputString.trim();if(e==="none"){let R=ev();return a(R)?R:u("Left unlinked. Your commits will show the name git signed them with. Run :config emails again to change that.",null)}let{userId:t,userName:n,gitName:r}=V();if(!t)return c("Set a username first with :config username");let o=xe();if(a(o))return c("Board is not loaded");let s=me(process.cwd());if(a(s))return c(s.message);let i=Ue(s.value),l=await wn({repoRoot:s.value,stateBranch:a(i)?void 0:i.value,names:[n,r],links:o.value.emailLinks});if(a(l))return l;let m=br(l.value);if(Eo(m.map(R=>R.email)),m.length===0){if(!Mp()){let R=ev();if(a(R))return R}return u("No unclaimed addresses in this history.",null)}if(!e)return w({mode:I.IDENTITY}),u("Opened identity",null);let p=e.split(/[,\s]+/).filter(Boolean),f=[],g=[];for(let R of p){let S=m.find(T=>T.email===et(R));if(!S){g.push(R);continue}f.includes(S)||f.push(S)}if(g.length>0)return c(`Not on the list: ${g.join(", ")}. Pick one of ${m.map(R=>R.email).join(", ")}.`);let y=he({repoRoot:s.value});if(a(y))return y;let x=f.map(R=>({id:YN(),action:"link.contributor.email",payload:{contributor:t,email:R.email},userId:t})),b=B(x,y.value);return a(b)?c(b.message):u(`Claimed ${f.map(R=>R.email).join(", ")}. Every commit by ${f.length===1?"that address":"those addresses"} is now yours.`,null)};import{ulid as XN}from"ulid";var nv=()=>{let e=ae().commandMeta.inputString.trim(),{userId:t}=V();if(!t)return c("Set a username first with :config username");let n=xe();if(a(n))return c("Board is not loaded");let r=fn(n.value.emailLinks,t);if(r.length===0)return c("You have not claimed any addresses.");if(!e)return c(`Which one? ${r.join(", ")}.`);let o=r.find(d=>d===et(e));if(!o)return c(`You have not claimed ${e}. Yours: ${r.join(", ")}.`);let s=me(process.cwd());if(a(s))return s;let i=he({repoRoot:s.value});if(a(i))return i;let l=B([{id:XN(),action:"unlink.contributor.email",payload:{contributor:t,email:o},userId:t}],i.value);return a(l)?c(l.message):u(`Unclaimed ${o}`,null)};var rv=()=>{let e=ae().commandMeta.inputString.trim();if(!["debug","error","info"].includes(e))return c("Invalid response");let n=Bt({logLevel:e});return a(n)?n:(je({logLevel:e}),u(`Auto sync set to "${e}"`,null))};var ov=e=>{let t=e.inputString.trim();switch(e.modifier){case ve.USERNAME:{if(process.env[kn])return c(`Cannot change the configured user while ${kn} names this process`);let n=pn();if(a(n))return n;let{userId:r,preferredEditor:o,userName:s}=n.value,i=t||s,l=r||JN();if(!i||!l)return c("Unable to resolve user name or id");let d=Bt({userName:i,userId:l,preferredEditor:o??""});return a(d)?d:(je({userName:i,userId:l}),u(`Username set to "${i}"`,null))}case ve.EDITOR:{if(!t)return c("No editor provided");let n=Bt({preferredEditor:t});return a(n)?n:(je({preferredEditor:t}),u(`Editor configuration set to "${t}"`,null))}case ve.VIEW:{if(t!=="wide"&&t!=="dense")return c("Invalid view mode");let n=Bt({viewMode:t});return a(n)?n:(je({viewMode:t}),u(`View set to "${t}"`,null))}case ve.EMAILS:return tv();case ve.EMAILS_UNCLAIM:return nv();case ve.AUTOSYNC:return Jy();case ve.LOG_LEVEL:return rv();case ve.SYNC_DEBOUNCE_MS:return Xy();case ve.ATTACHMENT_MAX_KB:return Kp();default:return c("Unknown config command")}};var ru=()=>{let e=kp(),t=v().mode;if(!(t!==I.COMMAND_LINE&&t!==I.DEFAULT)){if(!e){w({mode:I.DEFAULT});return}w({mode:I.COMMAND_LINE}),Q(e)}};var cl=[{systemOnly:!0,intent:G.Move,description:"Internal move-state command",mode:I.COMMAND_LINE,action:xy},{intent:G.Delete,description:"Delete the currently selected node",mode:I.COMMAND_LINE,action:$y,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Filter,description:"Filter the board, for example `:filter tag urgent`",mode:I.COMMAND_LINE,action:()=>{let{modifier:e,inputString:t}=ae().commandMeta,n=/(!=|=)/,[r]=e.split(n);if(!r||!(i=>Oe(C.FILTER).map(l=>l.split(n)[0]).includes(i))(r))return c("Invalid filter modifier");let s={target:r,operator:"=",value:t.trim()};return Fe(i=>({...i,filters:e==="clear"?[]:[...i.filters,s],mode:I.DEFAULT})),u("Filter updated",null)}},{intent:G.ViewHelp,description:"Open the help screen",mode:I.COMMAND_LINE,action:()=>{let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return vr({pendingNavTarget:{contextNode:e,breadCrumb:r,selectedIndex:t,selectedNode:n}}),w({mode:I.HELP}),u("Viewing help",null)}},{intent:G.CloseIssue,description:"Move the selected issue to the closed swimlane",mode:I.COMMAND_LINE,action:Uy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.ReopenIssue,description:"Move a closed issue back to its previous swimlane",mode:I.COMMAND_LINE,action:jy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Init,description:"Initialize Epiq in the current git repository",mode:I.COMMAND_LINE,action:fy,onSuccess:ru},{intent:G.OpenProject,description:"Open a recently used epiq project, by number or path",mode:I.COMMAND_LINE,action:wy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.NewItem,description:"Create a new board, swimlane, or issue",mode:I.COMMAND_LINE,action:Iy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Rename,description:"Rename the currently selected node",mode:I.COMMAND_LINE,action:Hy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UntagTicket,description:"Remove a tag from the selected issue",mode:I.COMMAND_LINE,action:Wy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.TagTicket,description:"Add or create a tag on the selected issue",mode:I.COMMAND_LINE,action:Gy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.AssignUserToTicket,description:"Assign a user to the selected issue",mode:I.COMMAND_LINE,action:zy,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.UnassignUserFromTicket,description:"Remove an assignee from the selected issue",mode:I.COMMAND_LINE,action:Ky,onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Comment,description:"Add a comment to the selected issue",mode:I.COMMAND_LINE,action:async(e,t)=>Yy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Sync,description:"Pull, commit, and push Epiq state",mode:I.COMMAND_LINE,action:Fy},{intent:G.Peek,description:"View board state at another point in time",mode:I.COMMAND_LINE,action:ky},{intent:G.Replay,description:"Replay board history forward from a point in time",mode:I.COMMAND_LINE,action:Dy},{intent:G.Export,description:"Export the current board layout to markdown",mode:I.COMMAND_LINE,action:async()=>{let e=await ly();return a(e)?e:(w({mode:I.DEFAULT}),u("Export successful",!0))}},{intent:G.Exit,description:"Exit the application",mode:I.COMMAND_LINE,action:async()=>(U.exit(),u("Exit successful",!0))},{intent:G.Edit,description:"Edit title or description",mode:I.COMMAND_LINE,action:async(e,t)=>uy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Yank,description:"Yank (copy) ref, title, description, tags, or assignees to the clipboard",mode:I.COMMAND_LINE,action:async(e,t)=>Oy(t),onSuccess:()=>w({mode:I.DEFAULT})},{intent:G.Config,description:"Update editor, username, view, autosync, or sync debounce",mode:I.COMMAND_LINE,action:(e,t)=>ov(t),onSuccess:ru}];var QN=new Set(["peek","replay","filter","view-help","yank"]),jt=async({isForceExecutedBySystem:e=!1}={})=>{let{value:t,commandMeta:{command:n,validity:r,modifier:o,inputString:s}}=ae();if(!n)return c("No command to confirm");if(!e&&r===bn.Invalid)return c("Invalid command");let i=La(n);df();let{readOnly:l}=v();if(l&&!QN.has(i))return Ts({status:Qn.Fail,message:"Command not available in readonly state",value:null});let d=cl.filter(f=>e||f.systemOnly!==!0).find(f=>f.intent===i);if(!d)return Ts({status:Qn.Fail,message:"Command not found",value:null});let m;try{m=await d.action(d,{command:n,inputString:s,modifier:o})}catch(f){return Ts({status:Qn.Fail,message:f instanceof Error?f.message:"Command failed",value:null})}if(a(m))return Ts(m);let p=!e;if(uf({addToHistory:p,line:t}),p){let f=Cy({commands:ae().commandHistory});a(f)&&logger.info(f.message)}return d.onSuccess?.(),V().autoSync&&Pa(),m};var dl=[{intent:E.Exit,mode:I.MOVE,description:"[<Esc>] exit context / cancel",action:()=>(w({mode:I.COMMAND_LINE}),Q("move cancel"),jt({isForceExecutedBySystem:!0}))},{intent:E.InitMove,mode:I.DEFAULT,description:"[m] move",action:()=>(w({mode:I.COMMAND_LINE}),Q("move start"),jt({isForceExecutedBySystem:!0}))},{intent:E.ConfirmMove,mode:I.MOVE,description:"[m] confirm move",action:()=>(w({mode:I.COMMAND_LINE}),Q("move confirm"),jt({isForceExecutedBySystem:!0}))}],ul=[{intent:E.MovePreviousItem,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveNextItem,mode:I.MOVE,description:"[arrows/hjkl] move (shift x5)",action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move next"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MovePreviousItemJump,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move jump-previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveNextItemJump,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move jump-next"),jt({isForceExecutedBySystem:!0})):c("No pending move")}],sv=[{intent:E.MoveToNextContainer,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move to-next"),jt({isForceExecutedBySystem:!0})):c("No pending move")},{intent:E.MoveToPreviousContainer,mode:I.MOVE,action:()=>on()?(w({mode:I.COMMAND_LINE}),Q("move to-previous"),jt({isForceExecutedBySystem:!0})):c("No pending move")}];var iv={[ie.WORKSPACE]:[...dl,...ul],[ie.BOARD]:[...dl,...ul],[ie.SWIMLANE]:[...dl,...ul,...sv],[ie.TICKET]:[],[ie.FIELD]:[],[ie.FIELD_LIST]:[],[ie.TEXT]:[],[ie.COMMENT]:[]};import eA from"node:fs";import tA from"node:path";import{spawn as ZN}from"node:child_process";function av(e){let t=process.platform,o=ZN(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{detached:!0,stdio:"ignore",shell:!1});return o.unref(),o.on("error",()=>{}),!0}var lv=e=>{let t=me(process.cwd());if(a(t))return c("Unable to resolve project root");let n=he({repoRoot:t.value});if(a(n))return c(n.message);let r=Br(e.hash,e.ext),o=tA.join(ms(n.value),r);return eA.existsSync(o)?(av(o),u(`Opened ${e.name}`,null)):c("Attachment file not found \u2014 run :sync to fetch it")};var cv=()=>{Q("");let{pendingNavTarget:e}=yr();w({mode:I.DEFAULT}),e&&U.navigate(e),vr({pendingNavTarget:void 0})},dv=[{intent:E.ExitCommandLine,mode:I.HELP,action:()=>(cv(),u("Exiting help",null))},{intent:E.Exit,mode:I.HELP,action:()=>(cv(),u("Closed help",null))},{intent:E.NavPreviousItem,mode:I.HELP,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous help item",null))},{intent:E.NavNextItem,mode:I.HELP,action:()=>(U.navigateToNextItem(),u("Navigating to next help item",null))},{intent:E.NavPreviousItemJump,mode:I.HELP,action:()=>(U.jumpToPreviousItem(),u("Jumping to previous help item",null))},{intent:E.NavNextItemJump,mode:I.HELP,action:()=>(U.jumpToNextItem(),u("Jumping to next help item",null))},{intent:E.NavToPreviousContainer,mode:I.HELP,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous help container",null))},{intent:E.NavToNextContainer,mode:I.HELP,action:()=>(U.navigateToNextContainer(),u("Navigating to next help container",null))}];var uv=()=>{Q(""),w({mode:I.DEFAULT})},mv=[{intent:E.Confirm,mode:I.IDENTITY,description:"[enter] claim the first",action:()=>{let[e]=So();return e?(w({mode:I.COMMAND_LINE}),Q(`config emails ${e}`),u("Proposed claim",null)):u("Nothing left to claim",null)}},{intent:E.ExitCommandLine,mode:I.IDENTITY,action:()=>(uv(),u("Closed identity",null))},{intent:E.Exit,mode:I.IDENTITY,description:"[esc] close",action:()=>(uv(),u("Closed identity",null))}];var nA=e=>{w({mode:I.COMMAND_LINE});let{pendingNavTarget:t}=yr();t&&U.navigate(t),vr({pendingNavTarget:void 0}),Q(`${e} `)},pv=()=>{Q("");let{pendingNavTarget:e}=yr();e&&U.navigate(e),vr({pendingNavTarget:void 0}),w({mode:I.DEFAULT})},fv=[{intent:E.InitCommandPalette,mode:I.DEFAULT,description:"[?] command palette",action:()=>{Q("");let{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}=v();return vr({pendingNavTarget:{contextNode:e,selectedIndex:t,selectedNode:n,breadCrumb:r}}),w({mode:I.PALETTE}),u("Opening command palette",null)}},{intent:E.Confirm,mode:I.PALETTE,action:()=>{let{selectedNode:e}=v();if(!e||!nr(e))return c("Command only applicable on text nodes");if(e.props.disabled)return c("Command is not available in this context");let t=e.title;return t?(nA(t),u("Selected command",t)):u("No command selected",null)}},{intent:E.ExitCommandLine,mode:I.PALETTE,action:()=>(pv(),u("Exiting palette",null))},{intent:E.Exit,mode:I.PALETTE,action:()=>(pv(),u("Closed command palette",null))},{intent:E.NavPreviousItem,mode:I.PALETTE,description:"[arrows/hjkl] navigate",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.PALETTE,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:E.NavToPreviousContainer,mode:I.PALETTE,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.PALETTE,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))}];var gv=()=>{let e=hr();if(!e)return u("Nothing to comment on here",null);let t=Ka();if(!t||t.sha!==e)return c("The diff is still loading");let{selectedIndex:n}=v(),r=Math.max(0,n),o=kd(t.rows,jd(e)??r,r);return o.ok?(w({mode:I.COMMAND_LINE}),Q(`${C.COMMENT} ${Oh(o.value.start,o.value.end)} `),u("Commenting on a diff line",null)):c(o.reason)},hv=[{intent:E.InitCommandLine,mode:I.DEFAULT,description:"[:] write command",action:()=>(w({mode:I.COMMAND_LINE}),Q(""),u("Entering command line mode",null))},...dv,...mv,...fv,{intent:E.AddItem,mode:I.DEFAULT,description:"[n] new...",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.NEW} `),u("Adding new item",null))},{intent:E.Delete,mode:I.DEFAULT,description:"[d] delete",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.DELETE} `),u("Deleting item",null))},{intent:E.Confirm,mode:I.DEFAULT,description:"[<Enter>] confirm/enter",action:()=>{let{selectedNode:e,contextNode:t}=v();if(!Ie(e?.id??"")?.length){let r=e?N.getAttachment(e.id):void 0;if(r)return lv(r);if(hr())return gv();if(e?.title===Te.DESCRIPTION)return w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Propose command",!0);if(e?.title===Te.ASSIGNEES)return w({mode:I.COMMAND_LINE}),Q(`${C.ASSIGN} `),u("Propose command",!0);if(e?.title===Te.TAGS)return w({mode:I.COMMAND_LINE}),Q(`${C.TAG} `),u("Propose command",!0);if(t.title===Te.DESCRIPTION&&e?.context==="TEXT")return w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Propose command",!0)}return U.enterChildNode(),u("Entering context",null)}},{intent:E.OpenInEditor,mode:I.DEFAULT,action:()=>{let{selectedNode:e,contextNode:t}=v(),n=t.parentNodeId,o=!!n&&t.id===Pe(n,"diff")?e?.id:hr()??void 0;return o?Xs({sha:o}):u("Nothing here opens in an editor",null)}},{intent:E.MarkDiffLine,mode:I.DEFAULT,action:()=>{let e=hr();if(!e)return u("Nothing to mark here",null);let{selectedIndex:t}=v(),n=jd(e);return Gr(n===t?null:{sha:e,row:Math.max(0,t)}),u("Marked diff line",null)}},{intent:E.CommentOnDiffLine,mode:I.DEFAULT,action:()=>hr()?gv():u("Nothing to comment on here",null)},{intent:E.Yank,mode:I.DEFAULT,description:"[y] yank",action:()=>{let{selectedNode:e}=v(),t=e?.title===Te.DESCRIPTION?Xe.DESCRIPTION:e?.title===Te.TAGS?Xe.TAGS:e?.title===Te.ASSIGNEES?Xe.ASSIGNEES:Xe.REF,r=Oe(C.YANK).includes(t)?t:Xe.REF;return w({mode:I.COMMAND_LINE}),Q(`${C.YANK} ${r}`),u("Propose command",!0)}},{intent:E.EditTitle,mode:I.DEFAULT,description:"[r] rename title",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} title ${v().selectedNode?.title}`),u("Exiting context",null))},{intent:E.EditDescription,mode:I.DEFAULT,description:"[e] edit desc",action:()=>(w({mode:I.COMMAND_LINE}),Q(`${C.EDIT} description `),u("Exiting context",null))},{intent:E.Exit,mode:I.DEFAULT,description:"[q] exit context",action:()=>(U.enterParentNode(),u("Exiting context",null))},{intent:E.NavPreviousItem,mode:I.DEFAULT,description:"[arrows/hjkl] navigate (shift x5)",action:()=>(U.navigateToPreviousItem(),u("Navigating to previous item",null))},{intent:E.NavNextItem,mode:I.DEFAULT,action:()=>(U.navigateToNextItem(),u("Navigating to next item",null))},{intent:E.NavPreviousItemJump,mode:I.DEFAULT,action:()=>(U.jumpToPreviousItem(),u("Jumping to previous item",null))},{intent:E.NavNextItemJump,mode:I.DEFAULT,action:()=>(U.jumpToNextItem(),u("Jumping to next item",null))},{intent:E.NavToPreviousContainer,mode:I.DEFAULT,action:()=>(U.navigateToPreviousContainer(),u("Navigating to previous container",null))},{intent:E.NavToNextContainer,mode:I.DEFAULT,action:()=>(U.navigateToNextContainer(),u("Navigating to next container",null))}];var rA=500,oA=e=>e.replace(/[\r\n]/g,"").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g,""),yv=e=>{let t=oA(e);t&&ia(n=>(n+t).slice(0,rA))};var sA=[I.COMMAND_LINE,I.PALETTE],iA=e=>e==="edit title "?v().selectedNode?.title??"":"",aA=e=>[{intent:E.MoveCursorLeft,mode:e,action:()=>(Uc(-1),u("Moving cursor left",null))},{intent:E.MoveCursorRight,mode:e,action:()=>(Uc(1),u("Moving cursor right",null))},{intent:E.MoveCursorLeftOfWord,mode:e,action:()=>(jc("left"),u("Moving cursor left of word",null))},{intent:E.MoveCursorRightOfWord,mode:e,action:()=>(jc("right"),u("Moving cursor right of word",null))},{intent:E.AutoCompleteCommand,mode:e,action:()=>(ia((t,{remainder:n})=>{let r=n?t+n:t;return r+iA(r)}),u("Auto-completing command",null))},{intent:E.CaptureInput,mode:e,action:(t,{sequence:n})=>(yv(n??""),u("Capturing input",null))},{intent:E.EraseInput,mode:e,action:()=>(lf(),u("Erasing input",null))},{intent:E.EraseInputWord,mode:e,action:()=>(cf(),u("Erasing input word",null))}],vv=[{intent:E.Confirm,mode:I.COMMAND_LINE,action:()=>(jt(),u("Executing command",null))},{intent:E.ViewHelp,mode:I.DEFAULT,action:()=>(w({mode:I.HELP}),u("Viewing help",null))},...sA.flatMap(aA),{intent:E.ExitCommandLine,mode:I.COMMAND_LINE,action:()=>(pf(),w({mode:I.DEFAULT}),u("Exiting command line",null))},{intent:E.GetLastCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(ff(),u("Getting last command from history",null))},{intent:E.GetNextCommandFromHistory,mode:I.COMMAND_LINE,action:()=>(gf(),u("Getting next command from history",null))}];var ou=e=>{let t=/^\[(.+?)\]\s*(.+)$/.exec(e);return t?{keys:t[1]??"",label:t[2]??""}:null},bv=({keys:e})=>e.length===1?0:1,xv=(e,t)=>{let n=new Set;for(let r of e)r.mode!==t||!r.description||n.add(r.description);return[...n].map(ou).filter(r=>r!==null).sort((r,o)=>bv(r)-bv(o))};function Iv(e,t,n){let r=t[e];if(!r)return c("buildBreadCrumb(): current node not found");let o=[],s=new Set,i=r;for(;i&&!s.has(i.id)&&(o.push(i),s.add(i.id),!(i.id===n||!i.parentNodeId));)i=t[i.parentNodeId];let l=o[o.length-1];return!l||l.id!==n?c("buildBreadCrumb(): node is not connected to root"):(o.reverse(),u("Breadcrumb built",o))}var Ev=e=>{let t={};for(let n of e)n.intent&&(t[n.mode]||(t[n.mode]={}),t[n.mode][n.intent]=n);return t};var At,su,iu=new Set,au=()=>{for(let e of iu)e()},cA=e=>(iu.add(e),()=>iu.delete(e));function lu(e){let{contextNodeId:t,mode:n,rootNodeId:r,nodes:o,filters:s}=e;if(!t)return c("derive(): contextNodeId is missing");if(!r)return c("derive(): rootNode is missing");if(!o[r])return c("derive(): unable to find root node");let l=o[t];if(!l)return c("Unable to derive state, contextNode not found");let d=Iv(t,o,r);if(a(d))return logger.error(d.message),d;let m=d.value,{context:p}=l,f=[...hv,...iv[p]??[],...vv],g=xv(f,n),y=Ev(f),x=dA(o,s),b=x[t]?.[e.selectedIndex]??null;return u("Derived successfully",{...e,contextNode:l,breadCrumb:m,availableHints:g,availableActions:f,actionIndex:y,selectedNode:b,renderedChildrenIndex:x})}var v=()=>{if(!At)throw new Error("State not initialized. Call initWorkspaceState() first.");return At},xe=()=>At?u("Retrieved state",At):c("State not initialized. Call initWorkspaceState() first.");Np(e=>At?fn(At.emailLinks,e):[]);function Bs(e){su=e;let t=me(process.cwd()),n=!1;if(!a(t)){let s=Tt(t.value);if(a(s))return c(s.message);n=!0}let r={readOnly:!1,filters:[],tags:{},contributors:{},emailLinks:{},mode:I.DEFAULT,nodes:{[e.id]:e},rootNodeId:e.id,contextNodeId:e.id,renderedChildrenIndex:{},selectedIndex:-1,syncStatus:{status:"synced",msg:""},eventLog:[],unappliedEvents:[],replay:null,timeMode:"live",hasProjectDefinition:n,hasInitializingEvents:!1,comments:{},attachments:{}},o=lu(r);return a(o)?o:(At=o.value,au(),u("State initialized",null))}var qr=!1,ii=null;function Fe(e){let t=v(),n=e(t);if(qr)return n.nodes!==t.nodes&&(xr=null),ii=n,At={...t,...n},u("State updated",null);let r=lu(n);return a(r)?c(r.message??"Unable to update state"):(At=r.value,au(),u("State updated",null))}function va(e){if(qr)return u("Joined batch",e());qr=!0,ii=null,xr=new Set;let t=()=>{let n=ii;if(qr=!1,ii=null,n===null)return null;let r=lu(n);return a(r)?c(r.message??"Unable to update state"):(At=r.value,au(),u("State updated",null))};try{let n=e(),r=t();return r&&a(r)?c(r.message):u("State updated",n)}finally{qr&&t()}}var hg=()=>qr,w=e=>Fe(t=>({...t,...e}));function Yr(e,t,n){if(!qr)return Fe(i=>({...i,[e]:{...i[e]??{},[t]:n}}));let r=v(),o=r[e]??{};if(e==="nodes"){let i=o[t],l=n;i?.parentNodeId&&xr?.add(i.parentNodeId),l.parentNodeId&&xr?.add(l.parentNodeId)}o[t]=n;let s={...r,[e]:o};return ii=s,At={...r,...s},u("State updated",null)}var oe=()=>lA(cA,v,v),xr=null,Sv=null,dA=(e,t)=>{let n=At?.renderedChildrenIndex,r=n!==void 0&&xr!==null&&e===Sv&&t.length===0&&At?.filters.length===0,o;if(r){o={...n};let s=mg(e,xr);for(let i of xr){let l=s[i];l?o[i]=l:delete o[i]}}else o=ug(e,t);return Sv=e,xr=new Set,o},de=e=>v()?.renderedChildrenIndex[e]??[],sn=()=>su?Bs(su):c("Cannot reset state: no initial workspace found"),_t=()=>At!==void 0;var Nt=(e,t)=>{let{nodes:n}=v(),r=n[e];if(!r)return c("Node not found");if(r.context===t)return u("Resolved ancestor node",r);let o=new Set([r.id]),s=r.parentNodeId?n[r.parentNodeId]:void 0;for(;s&&!o.has(s.id);){if(s.context===t)return u("Resolved ancestor node",s);o.add(s.id),s=s.parentNodeId?n[s.parentNodeId]:void 0}return c(`No ancestor found for context: ${t}`)},cu=(e,t)=>{let{nodes:n}=v(),r=new Set,o=n[e];for(;o?.parentNodeId&&!r.has(o.id);){if(o.parentNodeId===t)return!0;r.add(o.id),o=n[o.parentNodeId]}return!1},Ir=(e,t)=>e?e.readonly?c({move:"Cannot move readonly node",rename:"Cannot rename readonly node",edit:"Cannot edit readonly node",delete:"Cannot delete readonly node"}[t]):null:c("Node not found"),N={linkUserId({contributorId:e,userId:t}){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.userId&&n.userId!==t)return c("Contributor is already linked to another user");let r={...n,userId:t},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to link contributor to user"):u("Linked contributor to user",r)},deleteNode(e){N.deleteNodes([e])},deleteNodes(e){e.length!==0&&Fe(t=>{let n={...t.nodes};for(let r of e)delete n[r];return{...t,nodes:n}})},createComment(e){let t=this.getNode(e.issue);if(!t)return c("Unable to create comment, missing issue");if(!_(t))return c("Can only comment on issues");let n=Yr("comments",e.id,{...e,deleted:!1});return a(n)?c("Unable to create comment"):u("Created comment",{...e,deleted:!1})},editComment(e,t){let n=this.getComment(e);if(!n)return c("Unable to edit comment, missing comment");let r=this.getNode(n.issue);if(!r)return c("Unable to edit comment, missing issue");if(!_(r))return c("Can only edit issue comments");let o={...n,md:t,deleted:!1},s=Yr("comments",e,o);return a(s)?c("Unable to edit comment"):u("Edited comment",o)},deleteComment(e){let t=this.getComment(e);if(!t)return c("Unable to delete comment, missing comment");let n={...t,deleted:!0},r=Yr("comments",e,n);return a(r)?c("Unable to delete comment"):u("Deleted comment",n)},getComment(e){return v().comments?.[e]},getCommentsByIssue(e){return Object.values(v().comments??{}).filter(t=>t.issue===e&&!t.deleted)},getCommentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().comments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},createAttachment(e){let t=this.getNode(e.issue);if(!t)return c("Unable to create attachment, missing issue");if(!_(t))return c("Can only attach to issues");let n=Fe(r=>({...r,attachments:{...r.attachments??{},[e.id]:{...e,deleted:!1}}}));return a(n)?c("Unable to create attachment"):u("Created attachment",{...e,deleted:!1})},deleteAttachment(e){let t=this.getAttachment(e);if(!t)return c("Unable to delete attachment, missing attachment");let n={...t,deleted:!0},r=Fe(o=>({...o,attachments:{...o.attachments??{},[e]:n}}));return a(r)?c("Unable to delete attachment"):u("Deleted attachment",n)},getAttachment(e){return v().attachments?.[e]},getAttachmentsByIssue(e){return Object.values(v().attachments??{}).filter(t=>t.issue===e&&!t.deleted)},getAttachmentsGroupedByIssue(){let e=new Map;for(let t of Object.values(v().attachments??{})){if(t.deleted)continue;let n=e.get(t.issue);n?n.push(t):e.set(t.issue,[t])}return e},editValue(e,t){let{nodes:n}=v(),r=n[e];if(!r)return c("Edit target node not found");let o=Ir(r,"edit");if(o)return o;let s={...r,props:{...r.props,description:t}};return this.updateNode(s),u("Issue description updated",{md:t})},renameNode(e,t){let n=this.getNode(e);if(!n)return c("Rename target node not found");let r=Ir(n,"rename");if(r)return r;let o={...n,title:t};return this.updateNode(o),u("Renamed node",o)},getExistingTags(){let{tags:e}=v();return[...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getExistingAssignees(){let{contributors:e}=v();return["me",...new Set(Object.values(e).map(t=>t.name).filter(Boolean))]},getFieldByTitle(e,t){return Ie(e).find(n=>n.title===t)},moveNodeToRank({id:e,parentId:t,rank:n}){let{rootNodeId:r}=v(),o=this.getNode(e),s=this.getNode(t);if(!o)return c("Node not found");if(!s)return c("Target parent not found");if(r===e)return c("Cannot move root node");if(e===t)return c("Cannot move node into itself");let i=Ir(o,"move");if(i)return i;if(cu(t,e))return c("Cannot move node into its own descendant");let l={...o,parentNodeId:t,rank:n};return this.updateNode(l),u("Moved node successfully",l)},tombstoneNode(e){let{nodes:t,contextNodeId:n,rootNodeId:r}=v(),o=this.getNode(e);if(!o)return c("Node not found");if(r===e)return c("Cannot delete root node");let s=Ir(o,"delete");if(s)return s;let i=new Set,l=m=>{let p=t[m];if(!(!p||i.has(m))){i.add(m);for(let f of Ie(p.id))l(f.id)}};l(e);let d={...structuredClone(t)};for(let m of i){if(!d[m])return c("Unable to locate node to delete");d[m]={...d[m],isDeleted:!0}}return n?(w({nodes:d}),u("Successfully tomb stoned",o)):c("Unable to delete undefined")},tombstoneContributor(e){let t=this.getContributor(e);if(!t)return c("Contributor not found");let n={...t,name:bo,tombstoned:!0},r=Fe(o=>({...o,contributors:{...o.contributors,[e]:n}}));return a(r)?c("Unable to remove contributor"):u("Tombstoned contributor",n)},renameContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");if(n.tombstoned)return c("Cannot rename a removed contributor");let r={...n,name:t},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to rename contributor"):u("Renamed contributor",r)},restoreContributor(e,t){let n=this.getContributor(e);if(!n)return c("Contributor not found");let r={...n,name:t,tombstoned:!1},o=Fe(s=>({...s,contributors:{...s.contributors,[e]:r}}));return a(o)?c("Unable to restore contributor"):u("Restored contributor",r)},linkContributorEmail({email:e,contributor:t,authorId:n}){if(!this.getContributor(t))return c("Unable to link email, missing contributor");let r={email:et(e),contributor:t,authorId:n},o=hs(r.email,t),s=v().emailLinks[o];if(s&&!s.tombstoned)return u("Email already linked",s);let i=Fe(l=>({...l,emailLinks:{...l.emailLinks,[o]:r}}));return a(i)?c("Unable to link email"):u("Linked email to contributor",r)},unlinkContributorEmail(e,t,n){let r=hs(e,t),o=v().emailLinks[r];if(!o)return c("Unable to unlink, no such link");if(o.tombstoned)return u("Email already unlinked",o);if(!qi(n,o))return c("Only the author of a link or the contributor it names may remove it");let s={...o,tombstoned:!0},i=Fe(l=>({...l,emailLinks:{...l.emailLinks,[r]:s}}));return a(i)?c("Unable to unlink email"):u("Unlinked email from contributor",s)},getEmailLinks(){return v().emailLinks},createContributor(e){let t=Fe(n=>({...n,contributors:{...n.contributors,[e.id]:e}}));return a(t)?c("Unable to create contributor"):u("Created contributor",e)},assign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return c("Unable to assign contributor, missing contributor");if(!r)return c("Unable to assign contributor, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.assignees??[];if(s.includes(t))return c("Contributor already assigned");let i={...r,props:{...r.props,assignees:[...s,t]}};return this.updateNode(i),u("Assigned contributor",{assignee:t})},unassign(e,t){let n=this.getContributor(t),r=this.getNode(e);if(!n)return c("Unable to unassign, missing contributor");if(!r)return c("Unable to unassign, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.assignees??[];if(!s.includes(t))return u("Issue is not assigned to that contributor",{assignee:t});let i={...r,props:{...r.props,assignees:s.filter(l=>l!==t)}};return this.updateNode(i),u("Assignee removed",{assignee:t})},tag(e,t){let n=this.getTag(t),r=this.getNode(e);if(!n)return c("Unable to add tag, missing tag");if(!r)return c("Unable to add tag, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.tags??[];if(s.includes(t))return c("Tag already assigned");let i={...r,props:{...r.props,tags:[...s,t]}};return this.updateNode(i),u("Tag added",{tag:t})},untag(e,t){let n=this.getTagRecord(t),r=this.getNode(e);if(!n)return c("Unable to remove tag, missing tag");if(!r)return c("Unable to remove tag, missing target");let o=Ir(r,"edit");if(o)return o;if(!_(r))return c("Target is not an issue");let s=r.props.tags??[];if(!s.includes(t))return u("Issue is not tagged with that tag",{tag:t});let i={...r,props:{...r.props,tags:s.filter(l=>l!==t)}};return this.updateNode(i),u("Tag removed",{tag:t})},tombstoneTag(e){let t=this.getTagRecord(e);if(!t)return c("Tag not found");let n={...t,tombstoned:!0},r=Fe(o=>({...o,tags:{...o.tags,[e]:n}}));return a(r)?c("Unable to delete tag"):u("Tombstoned tag",n)},restoreTag(e,t){let n=this.getTagRecord(e);if(!n)return c("Tag not found");let r={...n,name:t,tombstoned:!1},o=Fe(s=>({...s,tags:{...s.tags,[e]:r}}));return a(o)?c("Unable to restore tag"):u("Restored tag",r)},createTag(e){let t=Fe(n=>({...n,tags:{...n.tags,[e.id]:e}}));return a(t)?c("Could not create tag"):u("Tag created",e)},createNode(e){let t=Yr("nodes",e.id,e);return a(t)?c("Unable to create node"):u("Node created",e)},lockNode(e){let t=this.getNode(e);if(!t)return c("Failed to locate node");let n={...t,readonly:!0},r=Yr("nodes",e,n);return a(r)?c(r.message):u("Locked node",n)},updateNode(e){let t=Yr("nodes",e.id,e);return a(t)?t:u("Updated node",e)},getContributor(e){return v().contributors[e]},getTag(e){let t=v().tags[e];return t?.tombstoned?void 0:t},getTagRecord(e){return v().tags[e]},getTags(){return Object.values(v().tags).filter(e=>!e.tombstoned)},findTagByName(e){return this.getTags().find(t=>t.name===e)},getNode(e){return v().nodes[e]},getSiblings(e){return Ie(e)}};var uA=(e,t)=>e+" ".repeat(Math.max(0,t-Rv(e))),mA=(e,t)=>" ".repeat(Math.max(0,t-Rv(e)))+e,ml=e=>({"add.issue":"Created with title","add.issue.assignee":"Assigned to","remove.issue.assignee":"Unassigned from","close.issue":"Closed","delete.node":"Deleted","edit.title":"Changed title to","edit.description":"Changed description","reopen.issue":"Reopened","add.issue.tag":"Tagged with","remove.issue.tag":"Removed tag","lock.node":"Locked node","move.node":"Moved issue","add.issue.comment":"Commented","delete.issue.comment":"Deleted comment","add.issue.attachment":"Attached","delete.issue.attachment":"Removed attachment","edit.issue.comment":"Edited comment","init.workspace":"Created workspace","add.workspace":"Created workspace","add.board":"Created board","add.swimlane":"Created swimlane","add.field":"Added field","create.tag":"Created tag","tombstone.tag":"Deleted tag","restore.tag":"Restored tag","create.contributor":"Added contributor","rename.contributor":"Renamed contributor","link.contributor.user":"Linked contributor","link.contributor.email":"Claimed","unlink.contributor.email":"Unclaimed","tombstone.contributor":"Removed contributor","restore.contributor":"Restored contributor","rebalance.children":"Rebalanced order"})[e]??(e.endsWith("e")?`${e}d`:`${e}ed`),pA=(e,t)=>t?e<t?"up":e>t?"down":null:null,fA=(e,t)=>{let n=N.getNode(e.payload.parent),r=n?Er.dim.bgBlack(` ${n.title} `):"unknown",o=t.at(-1);if(o&&"parent"in o&&"rank"in o&&o.parent===e.payload.parent){let s=pA(e.payload.rank,o.rank);if(s)return`Moved ${s} in ${r}`}return`Moved issue to ${r}`},Cv=e=>`${Math.max(1,Math.round(e/1024))} KB`,Nv=e=>N.getAttachment(e)?.name??"",gA=e=>{switch(e.action){case"add.issue.tag":{let t=v().tags[e.payload.tag];return t?Er.bgHex(qe(t.name))(` ${t.name} `):"unknown tag"}case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?Er.bgHex(qe(t.name))(` ${t.name} `):"unknown tag"}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Er.hex(qe(t.name))(` ${t.name} `):"unknown user"}case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?Er.hex(qe(t.name))(` ${t.name} `):"unknown user"}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return`"${"name"in e.payload?e.payload.name:""}"`;case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"add.issue.attachment":return`"${e.payload.name}" ${Er.dim(`(${Cv(e.payload.bytes)})`)}`;case"delete.issue.attachment":{let t=Nv(e.payload.id);return t?`"${t}"`:""}default:return""}},hA=e=>{let t=pr(Be(e));return Er.gray(mA(t,8))},yA=12,vA=e=>uA(`${e}`,yA),bA=e=>{let t=xe();return a(t)?e:Ki(e,t.value.contributors[e]?.name)},xA=e=>{switch(e.action){case"add.issue.tag":case"remove.issue.tag":{let t=v().tags[e.payload.tag];return t?t.name:""}case"add.issue.assignee":case"remove.issue.assignee":{let t=v().contributors[e.payload.assignee];return t?t.name:""}case"tombstone.tag":{let t=v().tags[e.payload.id];return t?`"${t.name}"`:""}case"add.board":case"add.swimlane":case"add.issue":case"add.field":case"create.tag":case"restore.tag":case"create.contributor":case"rename.contributor":case"edit.title":return"name"in e.payload?`"${e.payload.name}"`:"";case"link.contributor.email":case"unlink.contributor.email":return e.payload.email;case"move.node":{let t=N.getNode(e.payload.parent);return t?`to ${t.title}`:""}case"add.issue.attachment":return`"${e.payload.name}" (${Cv(e.payload.bytes)})`;case"delete.issue.attachment":{let t=Nv(e.payload.id);return t?`"${t}"`:""}default:return""}},sl=e=>[ml(e.action),xA(e)].filter(Boolean).join(" "),Av=(e,t)=>{let n=hA(e.id),r=vA(bA(e.userId)),o=Er.dim("\u203A"),s=e.action==="move.node"?fA(e,t):[ml(e.action),gA(e)].filter(Boolean).join(" ");return`${r} ${n} ${o} ${s}`};var IA=e=>Pe(e,"comments"),EA=e=>Pe(e,"description"),SA=e=>Pe(e,"assignees"),RA=e=>Pe(e,"tags"),CA=e=>Pe(e,"history"),NA=e=>Pe(e,"diff"),AA=e=>Pe(e,"attachments"),ai=({id:e,name:t,parentNodeId:n,rank:r,value:o,readonly:s=!1,childRenderAxis:i="horizontal"})=>{let l=N.getNode(e);if(!l){let p=N.createNode({...Ne.field({id:e,name:t,parentNodeId:n,rank:r,props:{value:o},isVirtual:!0}),readonly:s,childRenderAxis:i});return a(p)?p:u("Virtual field created",void 0)}if(!lt(l))return c(`Existing virtual node ${e} is not a field`);if(!(l.title!==t||l.parentNodeId!==n||l.rank!==r||l.props.value!==o||l.readonly!==s||l.childRenderAxis!==i))return u("Virtual field unchanged",void 0);let m=N.updateNode({...l,title:t,parentNodeId:n,rank:r,props:{...l.props,value:o},readonly:s,childRenderAxis:i});return a(m)?m:u("Virtual field updated",void 0)},Tv=({id:e,name:t,parentNodeId:n,rank:r,readonly:o=!1,childRenderAxis:s="horizontal"})=>{let i=N.getNode(e);if(!i){let m=N.createNode({...Ne.fieldList({id:e,name:t,parentNodeId:n,rank:r,isVirtual:!0}),readonly:o,childRenderAxis:s});return a(m)?m:u("Virtual field list created",void 0)}if(!vs(i))return c(`Existing virtual node ${e} is not a field list`);if(!(i.title!==t||i.parentNodeId!==n||i.rank!==r||i.readonly!==o||i.childRenderAxis!==s))return u("Virtual field list unchanged",void 0);let d=N.updateNode({...i,title:t,parentNodeId:n,rank:r,readonly:o,childRenderAxis:s});return a(d)?d:u("Virtual field list updated",void 0)},pl=null,TA=()=>{if(pl)return u("Virtual field ranks",pl);let e=Pt(Xt/4n),t=Pt(Xt/2n),n=Pt(Xt*3n/4n),r=Pt(Xt*7n/8n),o=Pt(Xt*15n/16n),s=Pt(Xt*13n/16n),i=Pt(Xt*27n/32n);return a(e)?e:a(t)?t:a(n)?n:a(r)?r:a(o)?o:a(s)?s:a(i)?i:(pl={description:e.value,assignees:t.value,tags:n.value,comments:r.value,attachments:o.value,log:s.value,diff:i.value},u("Virtual field ranks",pl))},og=e=>{let t=TA();if(a(t))return t;let n=t.value,r=ai({id:EA(e.id),name:Te.DESCRIPTION,parentNodeId:e.id,rank:n.description,value:e.props.description??"",childRenderAxis:"vertical"});if(a(r))return r;let o=Tv({id:SA(e.id),name:Te.ASSIGNEES,parentNodeId:e.id,rank:n.assignees,readonly:!0});if(a(o))return o;let s=Tv({id:RA(e.id),name:Te.TAGS,parentNodeId:e.id,rank:n.tags,readonly:!0});if(a(s))return s;let i=ai({id:IA(e.id),name:Te.COMMENTS,parentNodeId:e.id,rank:n.comments,value:"",readonly:!1,childRenderAxis:"vertical"});if(a(i))return i;let l=ai({id:AA(e.id),name:Te.ATTACHMENTS,parentNodeId:e.id,rank:n.attachments,value:"",readonly:!0,childRenderAxis:"vertical"});if(a(l))return l;let d=ai({id:CA(e.id),name:Te.HISTORY,parentNodeId:e.id,rank:n.log,value:wA(e),readonly:!0,childRenderAxis:"vertical"});if(a(d))return d;let m=ai({id:NA(e.id),name:Te.DIFF,parentNodeId:e.id,rank:n.diff,value:"",readonly:!0,childRenderAxis:"vertical"});return a(m)?m:u("Ticket virtual nodes materialized",void 0)},wA=e=>{let t=[...e.log].reverse(),n=new Map;for(let r of t){let o=n.get(r.action)??[];o.push(r.payload),n.set(r.action,o)}return t.map(r=>Av(r,n.get(r.action)??[])).join(`
|
|
98
|
+
`)},wv=!0,Mv=e=>{wv=e},sd=()=>wv;import mw from"node:http";import ro from"node:path";import{fileURLToPath as pw}from"node:url";var MA=e=>{switch(e.action){case"add.issue":case"move.node":case"close.issue":case"reopen.issue":return e.payload.parent;default:return null}},du=(e,t)=>{let n=[];for(let r of e){let o=MA(r);if(o===null||o===n.at(-1)?.laneId)continue;let s=er(r);n.push({laneId:o,enteredAt:s===null?t:gs(s)})}return n},fl=(e,t)=>du(e,t).at(-1)?.enteredAt??t;var PA=e=>e.payload??{},uu=e=>{let t=new Map,n={},r=new Set,o=new Set,s=new Set;for(let i of e){let{id:l,name:d}=PA(i);if(l)switch(i.action){case"create.contributor":case"create.tag":t.set(l,d??""),r.add(l),o.delete(l);break;case"rename.contributor":d!==void 0&&r.has(l)&&!o.has(l)&&t.set(l,d);break;case"tombstone.contributor":r.has(l)&&(t.set(l,bo),o.add(l));break;case"restore.contributor":case"restore.tag":d!==void 0&&r.has(l)&&(t.set(l,d),o.delete(l));break;case"add.board":d!==void 0&&(t.set(l,d),s.add(l));break;case"add.swimlane":d!==void 0&&(t.set(l,d),s.add(l),n[l]=d);break;case"edit.title":d!==void 0&&s.has(l)&&(t.set(l,d),l in n&&(n[l]=d));break;default:break}}return{byId:t,lanes:n}};var LA=e=>{let t=new Map,n=new Map;for(let r of e){let o=r.payload;!o?.id||!o.parent||(r.action==="move.node"&&t.set(r.id,n.get(o.id)),n.set(o.id,o.parent))}return t},Lv=e=>{let t=e.payload;return e.action==="tombstone.tag"||e.action==="restore.tag"?t?.id:t?.tag},kA=e=>{let t=new Set,n=new Map;for(let r of e){let o=r.payload,s=o?.id;s&&(r.action==="add.issue"&&t.add(s),o.parent&&n.set(s,o.parent))}return{issueIds:t,parentById:n}},DA=(e,{issueIds:t,parentById:n})=>{let r=e.payload;if(r?.issue)return r.issue;let o=new Set,s=r?.id;for(;s!==void 0&&!o.has(s);){if(t.has(s))return s;o.add(s),s=n.get(s)}return null},BA=new Set(["add.issue.comment","edit.issue.comment","delete.issue.comment"]),OA=e=>BA.has(e.action)?e.payload?.id??null:null,FA=new Set(["add.issue","move.node","close.issue","reopen.issue"]),_A=(e,t)=>{let n=new Map;return e.map((r,o)=>{let s=t[o]??null;if(s===null)return{lane:null,laneBefore:null};let i=r.payload,l=null;if(FA.has(r.action)&&i?.id===s&&i.parent){let d=n.get(s);d!==void 0&&d!==i.parent&&(l=d),n.set(s,i.parent)}return{lane:n.get(s)??null,laneBefore:l}})},Pv=90,$A=e=>{let t=e.trim().split(`
|
|
99
|
+
`)[0]?.trim()??"";return t.length>Pv?`${t.slice(0,Pv).trimEnd()}\u2026`:t},UA=(e,t,n)=>{let r=e.payload,o=Lv(e),s=e.action?ml(e.action):"";if(r?.md!==void 0){let l=$A(r.md);return l?`${s}: ${l}`:s}if(e.action==="move.node"&&r?.parent){let l=t.get(r.parent);return l?n.get(e.id)===r.parent?`Moved within ${l}`:`Moved to ${l}`:s}let i=o!==void 0?t.get(o)??"":r?.assignee!==void 0?t.get(r.assignee)??"":r?.email!==void 0?r.email:r?.name!==void 0?`"${r.name}"`:"";return[s,i].filter(Boolean).join(" ")},mu=(e,t)=>e?Ye(e,t.get(e)):null,jA=(e,t)=>{let n=e.payload;return{actor:mu(e.userId,t),tag:mu(Lv(e),t),assignee:mu(n?.assignee,t)}},kv=e=>{let t=new Map,n=new Set,r=o=>{let s=new Set,i=o;for(;i&&!s.has(i);){if(n.has(i))return i;s.add(i),i=t.get(i)}return null};return e.map(o=>{let s=o.payload,i=s?.id;if(!i)return null;o.action==="add.board"&&n.add(i);let l=o.action==="close.issue"?r(i):null,d=s.parent??s.issue;return d&&t.set(i,d),l!==null?l:n.has(i)?i:r(i)})},Dv=e=>HA.has(e),HA=new Set(["create.contributor","rename.contributor","tombstone.contributor","restore.contributor","link.contributor.user","link.contributor.email","unlink.contributor.email"]),Bv=(e,t)=>{let n=kv(e);return e.filter((r,o)=>n[o]===t)},WA=(e,t=new Map)=>{let n=new Map([...t,...uu(e).byId]),r=LA(e),o=kA(e),s=e.map(p=>DA(p,o)),i=_A(e,s),l=kv(e),d=ho(e.map(p=>er(p)));return e.flatMap((p,f)=>{let g=d[f]??null;return g===null?[]:[{id:p.id,t:g,action:p.action,label:UA(p,n,r),issue:s[f]??null,target:OA(p),...i[f],board:l[f]??null,...jA(p,n)}]}).sort((p,f)=>p.t-f.t)},GA=e=>{let t=new Map;for(let r of e){if(r.issue===null||r.lane===null)continue;let o=t.get(r.issue)??[],s=o[o.length-1];(s===void 0||s.lane!==r.lane)&&(o.push({t:r.t,lane:r.lane,board:r.board}),t.set(r.issue,o))}let n=new Map;for(let[r,o]of t){let s=o[o.length-1];n.set(r,{changes:o,from:o[0].t,closedFrom:s.lane===ye?s.t:null})}return n},VA=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return e[n-1]},Ov=(e,t,n)=>{let r={};for(let[o,s]of e){if(s.from>=t||s.closedFrom!==null&&s.closedFrom<t)continue;let i=VA(s.changes,t);i===void 0||i.lane===ye||n&&i.board!==n||(r[o]=i.lane)}return r},zA=e=>uu(e).lanes,li=null,Fv=e=>{let t=xn(e);if(li&&li.root===e&&li.signature===t)return u("Timeline entries, cached",li.index);let n=cr(e);if(a(n))return c(n.message);let r=WA(n.value,lr(e)),o={entries:r,lanes:GA(r),laneNames:zA(n.value)};return li={root:e,signature:t,index:o},u("Timeline entries, built",o)};var _v=1e5,KA=2e4,gl=null,$v=Promise.resolve(),Sr=e=>{let t=$v.then(e,e);return $v=t.then(()=>{},()=>{}),t},hl=e=>{let t=nn(e);return a(t)?t:he({repoRoot:t.value})},st=()=>{if(!_t())return{mode:"live",asOfTime:null};let{timeMode:e}=v();return e==="live"?{mode:"live",asOfTime:null}:{mode:"scrub",asOfTime:gl}},Uv=(e,t)=>{let n=0,r=e.length;for(;n<r;){let o=n+r>>1;e[o].t<t?n=o+1:r=o}return n},jv=async(e={})=>{let t=hl(e.repoRoot);if(a(t))return c(t.message);let n=Fv(t.value);if(a(n))return c(n.message);let r=n.value.entries,o=Date.now(),s=e.end??o,i=e.start??r[0]?.t??s;if(s<=i)return u("Empty time window",{bucketMs:0,buckets:[],capped:!1,events:[],lanesAtStart:{},laneNames:n.value.laneNames,closedLane:ye,earliest:i,latest:s});let l=Uv(r,i),d=Uv(r,s),m=r.slice(l,d).filter(b=>!e.boardId||b.board===e.boardId||Dv(b.action)),p=m.map(b=>b.t),f=Math.max(1,Math.ceil((s-i)/_v)),g=new Map;for(let b of p){let R=Math.min(_v-1,Math.floor((b-i)/f)),S=i+R*f;g.set(S,(g.get(S)??0)+1)}let y=[...g.entries()].sort(([b],[R])=>b-R).map(([b,R])=>({t:b,count:R})),x=m.length>KA;return u("Computed event timeline",{bucketMs:f,buckets:y,capped:x,events:x?[]:m,lanesAtStart:Ov(n.value.lanes,i,e.boardId),laneNames:n.value.laneNames,closedLane:ye,earliest:i,latest:s})},Hv=e=>{let t=cr(e);if(a(t))return c(t.message);let n=sn();if(a(n))return c(n.message);gl=null;let r=Qt(t.value),{fatal:o,skipped:s}=In(r);return o.length>0?c(o.map(i=>i.message).join(", ")):(En(s),w({readOnly:!1,readOnlyReason:void 0,timeMode:"live",unappliedEvents:[],replay:null}),u("Restored live state",!0))},qA=(e,t)=>{gl=null;let n=Hv(e);return a(n)?c(`${t} (recovery to live also failed: ${n.message})`):c(t)},pu=e=>Sr(async()=>{let t=hl(e.repoRoot);if(a(t))return c(t.message);let n=ba(t.value,e.targetTime);if(a(n))return c(n.message);let{appliedEvents:r,unappliedEvents:o}=n.value,s=sn();if(a(s))return s;let i=Qt(r),{fatal:l,skipped:d}=In(i);return l.length>0?qA(t.value,l.map(m=>m.message).join(", ")):(En(d),w({readOnly:!0,timeMode:"peek",unappliedEvents:o,replay:null}),gl=e.targetTime,u("Checked out historical state",{asOfTime:e.targetTime}))}),Wv=async e=>{let t=hl(e.repoRoot);if(a(t))return c(t.message);let n=xa(t.value);if(a(n))return c(n.message);let r=n.value.get(e.eventId)??null;return r===null?c("Event not found in the log"):pu({repoRoot:e.repoRoot,targetTime:r+1})},Gv=(e={})=>Sr(async()=>{let t=hl(e.repoRoot);if(a(t))return c(t.message);let n=Hv(t.value);return a(n)?c(n.message):u("Returned to live state",!0)});import XA from"node:fs";var Vv=new Map,YA=3e4,zv=async e=>{let t=Vv.get(e);if(t&&Date.now()-t.readAt<YA)return{name:t.name,email:t.email};let n=await De({args:["config","--get-regexp","^user\\.(name|email)$"],cwd:e}),r=null,o=null;if(n.exitCode===0)for(let s of(n.stdout??"").split(`
|
|
100
|
+
`)){let i=s.indexOf(" ");if(i===-1)continue;let l=s.slice(0,i),d=s.slice(i+1);l==="user.name"&&(r=d.trim()||null),l==="user.email"&&(o=et(d)||null)}return Vv.set(e,{name:r,email:o,readAt:Date.now()}),{name:r,email:o}},yl=async e=>(await zv(e)).email,Rr=async e=>(await zv(e)).name;var Xr=e=>{let t=me(e??process.cwd());return a(t)?c(t.message):u("Resolved Epiq repo root",t.value)},vl=null,ee=async(e,t)=>{let n=Xr(e);if(a(n))return n;let r=he({repoRoot:n.value});if(a(r))return c(r.message);let o=Ue(n.value);if(a(o))return c(o.message);if(!(vl!==null&&vl.repoRoot===n.value&&vl.stateBranchRoot===r.value&&XA.existsSync(Mr(r.value)))){let f=await Us({repoRoot:n.value,stateBranchName:o.value});if(a(f))return c(f.message);let g=await dr({repoRoot:n.value,stateBranchRoot:r.value,stateBranchName:o.value});if(a(g))return c(g.message);vl={repoRoot:n.value,stateBranchRoot:r.value}}if(t?.pull??!1){let f=await j({cwd:r.value,args:["pull","--ff-only"]});a(f)&&se.info(3,f.message)}let i={repoRoot:n.value,stateBranchRoot:r.value},l=ht();a(l)||je(l.value),je({gitEmail:await yl(n.value),gitName:await Rr(n.value)});let d=xn(r.value);if(Nf(r.value)===d&&_t()&&st().mode==="live")return u("Booted Epiq state, unchanged",i);let m=Zt(r.value);if(a(m))return c(m.message);let p=en(m.value.events,m.value.unreadable);return a(p)?c(p.message):(Af(r.value,d),u("Booted Epiq state",i))},te=()=>{let e=ht();return a(e)?c(e.message):e.value.userId?e.value.userName?u("Resolved actor",{userId:e.value.userId,userName:e.value.userName}):c("Unable to retrieve user name"):c("Unable to retrieve user id")},q=()=>{let e=xe();return a(e)?c(e.message):e};var Ko=e=>hn(e).map(t=>Ye(t.id,t.name));var qo=e=>yn(e).map(({id:t,name:n})=>Ye(t,n));import JA from"node:fs";import QA from"node:path";import{ulid as gu}from"ulid";var tt=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Issue not found"):_(n)?n.readonly?c("Issue is readonly"):u("Found issue",n):c("Target must be an issue")},Cr=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Swimlane not found"):gn(n)?n.readonly?c("Swimlane is readonly"):u("Found swimlane",n):c("Target must be a swimlane")},fu=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return!n||n.isDeleted?c("Board not found"):rr(n)?n.readonly?c("Board is readonly"):u("Found board",n):c("Target must be a board")};var ZA=e=>{if(e.filePath)try{return u("Read attachment file",{data:JA.readFileSync(e.filePath),name:e.name??QA.basename(e.filePath)})}catch(t){return c(`Unable to read ${e.filePath}: ${t instanceof Error?t.message:String(t)}`)}return e.dataBase64?u("Decoded attachment data",{data:Buffer.from(e.dataBase64,"base64"),name:e.name??"image"}):c("Provide either filePath or dataBase64")},bl=()=>{let e=ht();return a(e)?vn:e.value.attachmentMaxKb??vn},hu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=ZA(e);if(a(s))return s;let i=Vp(t.value.stateBranchRoot,s.value.data,bl());if(a(i))return i;let l=Re(s.value.name).trim()||"image",d=gu(),m={id:gu(),...D(n.value),action:"add.issue.attachment",payload:{id:d,issue:e.issueId,author:n.value.userId,hash:i.value.hash,ext:i.value.ext,name:l,bytes:i.value.bytes}},p=B([m],t.value.stateBranchRoot);if(a(p))return c(p.message);let f=Br(i.value.hash,i.value.ext);return u("Added issue attachment",{id:d,issueId:e.issueId,fileName:f,bytes:i.value.bytes,markdown:Bc(l,f)})},yu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.attachment"&&m.payload.id===e.attachmentId);if(!o)return c("Unable to resolve attachment");if(o.payload.author!==n.value.userId)return c("You can only delete your own attachments");let s=tt(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.attachment"&&m.payload.id===e.attachmentId))return u("Attachment already deleted",{id:e.attachmentId,issueId:o.payload.issue});let l={id:gu(),...D(n.value),action:"delete.issue.attachment",payload:{id:e.attachmentId,issue:o.payload.issue}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Deleted issue attachment",{id:e.attachmentId,issueId:o.payload.issue})},vu=async e=>{let t=await ee(e.repoRoot,{pull:!1});return a(t)?t:zp(t.value.stateBranchRoot,e.fileName,bl())};var eT=365*24*60*60*1e3,bu=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return u("Issue description",n&&_(n)&&!n.isDeleted?n.props.description??"":"")},Jr=()=>{let e=q();if(a(e))return e;let t=st(),n=t.mode!=="live",r=Object.values(e.value.nodes),o=r.filter(b=>rr(b)&&!b.isDeleted),s=Date.now()-eT,i=new Map,l=new Map;for(let b of r)if(!b.isDeleted){if(gn(b)&&b.parentNodeId){let R=i.get(b.parentNodeId)??[];R.push(b),i.set(b.parentNodeId,R)}if(_(b)&&b.parentNodeId){if(b.parentNodeId===ye&&Be(b.id)<s)continue;let R=l.get(b.parentNodeId)??[];R.push(b),l.set(b.parentNodeId,R)}}let d=new Set;for(let b of l.values())for(let R of b)d.add(R.id);let m=ht();if(a(m))return m;let p={},f=N.getCommentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!d.has(b.id)||(p[b.id]=(f.get(b.id)??[]).map(R=>{let S=N.getContributor(R.authorId);return{id:R.id,issueId:R.issue,body:R.md,author:Ye(R.authorId,S?.name),createdAt:Be(R.id)}}));let g=new Map;for(let b of e.value.eventLog)b.action==="add.issue.attachment"&&g.set(b.payload.id,b.payload.author);let y={},x=N.getAttachmentsGroupedByIssue();for(let b of r.filter(_))b.isDeleted||!d.has(b.id)||(y[b.id]=(x.get(b.id)??[]).map(R=>({id:R.id,issueId:R.issue,name:R.name,fileName:Br(R.hash,R.ext),bytes:R.bytes,createdAt:Be(R.id),canDelete:g.get(R.id)===m.value.userId})));return u("Retrieved Epiq GUI state",{boards:o.sort((b,R)=>b.rank.localeCompare(R.rank)).map(b=>({id:b.id,ref:H(b.id),title:b.title,readonly:!!b.readonly||n,swimlanes:(i.get(b.id)??[]).sort((R,S)=>R.rank.localeCompare(S.rank)).map(R=>({id:R.id,title:R.title,readonly:!!R.readonly||n,issues:(l.get(R.id)??[]).sort((S,T)=>S.rank.localeCompare(T.rank)).map(S=>({id:S.id,ref:H(S.id),title:Re(S.title),description:S.props.description??"",createdAt:Be(S.id),enteredLaneAt:fl(S.log??[],Be(S.id)),readonly:!!S.readonly||n,tags:Ko(S),assignees:qo(S),parentNodeId:S.parentNodeId,isClosed:S.parentNodeId===ye})),parentNodeId:R.parentNodeId}))})),tags:N.getTags().map(b=>({...b,...Ye(b.id,b.name)})),contributors:Object.values(e.value.contributors).map(b=>({...b,...Ye(b.id,b.name)})),user:{id:m.value.userId??"",name:m.value.userName??"",color:qe(m.value.userName??"")},commentsByIssueId:p,attachmentsByIssueId:y,attachmentMaxKb:bl(),timeTravel:t})},Kv=null,tT=e=>{if(e===Kv)return;let t=Ji({root:e});if(a(t)){se.info(t.message);return}Kv=e},Ht=async(e={})=>{if(st().mode!=="live")return Jr();let t=await ee(e.repoRoot,{pull:!1});return a(t)?t:(tT(t.value.repoRoot),Jr())},ci=async(e={})=>{To();let t=Xr(e.repoRoot);if(a(t))return c("Sync failed");let n=te();if(a(n))return n;let r=await wa({cwd:t.value,ownEventFileName:ir(n.value)});return a(r)?(ld(r.message),r):(jr(),u("Synced",r.value))};import{ulid as Wt}from"ulid";var di=e=>{let t=[...new Set([...e.issueIds??[],...e.issueId?[e.issueId]:[]])];return t.length?u("Resolved targets",t):c("Provide issueId or issueIds")},Yo=(e,t)=>{let n=t.done.length,r=`${e} ${n} issue${n===1?"":"s"}`+(t.failed.length?`, ${t.failed.length} failed`:"");return n?u(r,t):c(`${r}: ${t.failed.map(o=>`${o.ref} ${o.reason}`).join("; ")}`)},ui=(e,t)=>{let n={done:[],failed:[]};for(let r of e){let o=t(r);a(o)?n.failed.push({id:r,ref:H(r),reason:o.message}):n.done.push({id:r,ref:H(r)})}return n};var Xv=(e,t)=>e.trim().toLowerCase()===t.trim().toLowerCase();async function Eu(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=q();if(a(n))return n;let r=n.value.nodes,o=e.query?.trim().toLowerCase(),s=Object.values(r).filter(_).filter(l=>!l.isDeleted).filter(l=>e.includeClosed||l.parentNodeId!==ye).filter(l=>e.boardId?(l.parentNodeId?r[l.parentNodeId]:void 0)?.parentNodeId===e.boardId:!0).filter(l=>!e.swimlaneId||l.parentNodeId===e.swimlaneId).filter(l=>!e.tag||Ko(l).some(d=>Xv(d.name,e.tag))).filter(l=>!e.assignee||qo(l).some(d=>Xv(d.name,e.assignee))).filter(l=>!o||l.title.toLowerCase().includes(o)||(l.props.description??"").toLowerCase().includes(o)),i=l=>Re((l.parentNodeId?r[l.parentNodeId]?.title:void 0)??"");return e.brief?u("Listed issues",s.map(l=>({id:l.id,ref:H(l.id),title:Re(l.title),swimlane:i(l),tags:Ko(l).map(d=>d.name),assignees:qo(l).map(d=>d.name)}))):u("Listed issues",s.map(l=>({id:l.id,ref:H(l.id),title:Re(l.title),description:l.props.description??"",createdAt:Be(l.id),enteredLaneAt:fl(l.log??[],Be(l.id)),parentNodeId:l.parentNodeId,isClosed:l.parentNodeId===ye,readonly:!!l.readonly,tags:Ko(l),assignees:qo(l)})))}var Su=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Re(e.title);if(!o)return c("Issue title cannot be empty");let s=e.description??"",i=ct("Issue title",o,300)??ct("Issue description",s,2e4);if(i)return c(i);if((e.tagNames?.length??0)>20)return c(`Cannot set more than ${20} tags at once`);if((e.assigneeNames?.length??0)>20)return c(`Cannot set more than ${20} assignees at once`);let l=Cr(e.parentId);if(a(l))return l;let d=Hn(e.parentId,n.value,t.value.stateBranchRoot);if(a(d))return d;let m=Qa({name:o,parent:e.parentId,user:n.value,rank:d.value});if(a(m))return m;let p=[...m.value],f=p.find(b=>b.action==="add.issue")?.payload.id;if(!f)return c("Unable to determine created issue id");s&&p.push({id:Wt(),...D(n.value),action:"edit.description",payload:{id:f,md:s}});let g=[];for(let b of e.tagNames??[]){let R=Re(b).trim();if(!R||g.some(P=>P.name===R))continue;let S=ct("Tag name",R,60);if(S)return c(S);let T=N.findTagByName(R),A=T?.id??Wt();T||p.push({id:Wt(),...D(n.value),action:"create.tag",payload:{id:A,name:R}}),p.push({id:Wt(),...D(n.value),action:"add.issue.tag",payload:{id:f,tag:A}}),g.push({id:A,name:R})}let y=[];for(let b of e.assigneeNames??[]){let R=Re(b).trim();if(!R||y.some(P=>P.name===R))continue;let S=ct("Assignee name",R,80);if(S)return c(S);let T=Object.values(r.value.contributors).find(P=>P.name===R),A=T?.id??Wt();T||p.push({id:Wt(),...D(n.value),action:"create.contributor",payload:{id:A,name:R}}),p.push({id:Wt(),...D(n.value),action:"add.issue.assignee",payload:{id:f,assignee:A}}),y.push({id:A,name:R})}let x=B(p,t.value.stateBranchRoot);return a(x)?c(x.message):u("Created issue",{id:f,ref:H(f),title:o,parentId:e.parentId,description:s,tags:g,assignees:y})},nT=(e,t,n)=>{let r=tt(e);if(a(r))return r;let o=Sn(ye,e,{at:"end"},t,n);if(a(o))return o;let s={id:Wt(),...D(t),action:"close.issue",payload:{id:e,parent:ye,rank:o.value}},i=B([s],n);return a(i)?c(i.message):u("Closed issue",{id:e,ref:H(e)})};async function Ru(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=di(e);if(a(r))return r;let o=s=>nT(s,n.value,t.value.stateBranchRoot);return e.issueIds?Yo("Closed",ui(r.value,o)):o(r.value[0])}var Cu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[e.issueId];if(!o||o.isDeleted)return c("Issue not found");if(!_(o))return c("Target must be an issue");if(o.parentNodeId!==ye)return c("Issue is not closed");let s=il(o);if(!s)return c("Unable to resolve previous parent from issue history");if(s===ye)return c("Previous parent resolves to closed swimlane");let i=Cr(s);if(a(i))return i;let l=i.value,d=Sn(l.id,o.id,{at:"end"},n.value,t.value.stateBranchRoot);if(a(d))return d;let m={id:Wt(),...D(n.value),action:"reopen.issue",payload:{id:o.id,parent:l.id,rank:d.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Reopened issue",{id:o.id,ref:H(o.id),parentId:l.id})},rT=(e,t,n,r)=>{let o=tt(e);if(a(o))return o;let s=Cr(t.parentId);if(a(s))return s;let i=Sn(t.parentId,e,t.position??{at:"end"},n,r);if(a(i))return i;let l={id:Wt(),...D(n),action:"move.node",payload:{id:e,parent:t.parentId,rank:i.value}},d=B([l],r);return a(d)?c(d.message):u("Moved issue",{id:e,ref:H(e),parentId:t.parentId})};async function Nu(e){let t=Xr(e.repoRoot);if(a(t))return t;let n=te();if(a(n))return n;let r=he({repoRoot:t.value});if(a(r))return r;let o=Zt(r.value);if(a(o))return o;let s=en(o.value.events,o.value.unreadable);if(a(s))return s;let i=di(e);if(a(i))return i;let l=d=>rT(d,e,n.value,r.value);return e.issueIds?Yo("Moved",ui(i.value,l)):l(i.value[0])}var Au=e=>{let t=q();if(a(t))return t;let n=t.value.nodes[e];return n?u("Read issue history",(n.log??[]).map(r=>({id:r.id,t:Be(r.id),action:r.action,label:sl(r),...r.action==="move.node"?{parentId:r.payload.parent}:{},actor:Ye(r.userId,t.value.contributors[r.userId]?.name)}))):c("Issue not found")},Tu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=o.value,i=ct("Issue description",e.description,2e4);if(i)return c(i);let l=s.props.description??"";if(l===e.description)return u("No changes made",{id:e.issueId,ref:H(e.issueId),description:l});let d={id:Wt(),...D(n.value),action:"edit.description",payload:{id:e.issueId,md:e.description}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue description",{id:e.issueId,ref:H(e.issueId),description:e.description})},wu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=o.value,i=Re(e.title);if(!i.trim())return c("Issue title cannot be empty");let l=ct("Issue title",i,300);if(l)return c(l);if(s.title===i)return u("No changes made",{id:e.issueId,ref:H(e.issueId),title:i});let d={id:Wt(),...D(n.value),action:"edit.title",payload:{id:e.issueId,name:i}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue title",{id:e.issueId,ref:H(e.issueId),title:i})};import{ulid as Nr}from"ulid";var Mu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[r.value.rootNodeId];if(!o)return c("Workspace not found");if(st().mode!=="live")return c("Cannot add a board while time travelling");let s=Re(e.title);if(!s.trim())return c("Board title cannot be empty");let i=ct("Board title",s,300);if(i)return c(i);let l=Hn(o.id,n.value,t.value.stateBranchRoot);if(a(l))return l;let d=Nr(),m={id:Nr(),...D(n.value),action:"add.board",payload:{id:d,name:s,parent:o.id,rank:l.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Created board",{id:d,ref:H(d),title:s})},Pu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.nodes[e.boardId];if(!o||o.isDeleted)return c("Board not found");if(!rr(o))return c("Edit target must be a board");if(o.readonly)return c("Cannot edit readonly board");if(st().mode!=="live")return c("Cannot rename a board while time travelling");let s=Re(e.title);if(!s.trim())return c("Board title cannot be empty");let i=ct("Board title",s,300);if(i)return c(i);if(o.title===s)return u("No changes made",{id:e.boardId,ref:H(e.boardId),title:s});let l={id:Nr(),...D(n.value),action:"edit.title",payload:{id:e.boardId,name:s}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Edited board title",{id:e.boardId,ref:H(e.boardId),title:s})};var Lu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=fu(e.boardId);if(a(o))return o;if(st().mode!=="live")return c("Cannot add a swimlane while time travelling");let s=Re(e.title);if(!s.trim())return c("Swimlane title cannot be empty");let i=ct("Swimlane title",s,300);if(i)return c(i);let l=Hn(e.boardId,n.value,t.value.stateBranchRoot);if(a(l))return l;let d=Nr(),m={id:Nr(),...D(n.value),action:"add.swimlane",payload:{id:d,name:s,parent:e.boardId,rank:l.value}},p=B([m],t.value.stateBranchRoot);return a(p)?c(p.message):u("Created swimlane",{id:d,ref:H(d),title:s,boardId:e.boardId})},ku=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Cr(e.swimlaneId);if(a(o))return o;let s=o.value,i=Re(e.title);if(!i.trim())return c("Swimlane title cannot be empty");let l=ct("Swimlane title",i,300);if(l)return c(l);if(s.title===i)return u("No changes made",{id:e.swimlaneId,ref:H(e.swimlaneId),title:i});let d={id:Nr(),...D(n.value),action:"edit.title",payload:{id:e.swimlaneId,name:i}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited swimlane title",{id:e.swimlaneId,ref:H(e.swimlaneId),title:i})},Du=async e=>{let t=Xr(e.repoRoot);if(a(t))return t;let n=te();if(a(n))return n;let r=he({repoRoot:t.value});if(a(r))return r;let o=Zt(r.value);if(a(o))return o;let s=en(o.value.events,o.value.unreadable);if(a(s))return s;let i=Cr(e.swimlaneId);if(a(i))return i;let l=fu(e.boardId);if(a(l))return l;let d=Sn(e.boardId,e.swimlaneId,e.position??{at:"end"},n.value,r.value);if(a(d))return d;let m={id:Nr(),...D(n.value),action:"move.node",payload:{id:e.swimlaneId,parent:e.boardId,rank:d.value}},p=B([m],r.value);return a(p)?c(p.message):u("Moved swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId),boardId:e.boardId})},Bu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=Cr(e.swimlaneId);if(a(o))return o;let s={id:Nr(),...D(n.value),action:"delete.node",payload:{id:e.swimlaneId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Deleted swimlane",{id:e.swimlaneId,ref:H(e.swimlaneId)})};import{ulid as mi}from"ulid";async function Ou(e){let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=di(e);if(a(r))return r;let o=Re(e.tagName).trim();if(!o)return c("Tag name cannot be empty");let s=ct("Tag name",o,60);if(s)return c(s);let i=ui(r.value,tt);if(!e.issueIds&&i.failed[0])return c(i.failed[0].reason);if(i.done.length===0)return c(Yo("Tagged",i).message);let l=N.findTagByName(o),d=l?.id??mi(),m=[...l?[]:[{id:mi(),...D(n.value),action:"create.tag",payload:{id:d,name:o}}],...i.done.map(({id:y})=>({id:mi(),...D(n.value),action:"add.issue.tag",payload:{id:y,tag:d}}))],p=B(m,t.value.stateBranchRoot);if(a(p))return c(p.message);let f={id:d,name:o};if(!e.issueIds)return u("Added issue tag",{...i.done[0],tag:f});let g=Yo("Tagged",i);return a(g)?g:u(g.message,{...g.value,tag:f})}var Fu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.tags[e.tagId];if(!o)return c("Tag not found");if(o.tombstoned)return c("Tag is already deleted");let s=[{id:mi(),...D(n.value),action:"tombstone.tag",payload:{id:e.tagId}}],i=B(s,t.value.stateBranchRoot);return a(i)?c(i.message):u("Deleted tag",{id:o.id,name:o.name})};var _u=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;if(!r.value.tags[e.tagId])return c("Tag not found");let s={id:mi(),...D(n.value),action:"remove.issue.tag",payload:{id:e.issueId,tag:e.tagId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Removed issue tag",{id:e.issueId,ref:H(e.issueId),tagId:e.tagId})};import{ulid as Zr}from"ulid";var Qv=async(e,t)=>{let n=lr(e).get(t);return n===void 0?void 0:{id:t,name:n}},$u=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=e.self?n.value.userId:e.assigneeId;if(s){let b=r.value.contributors[s],R=b?void 0:await Qv(t.value.stateBranchRoot,s);if(!b&&!R)return c("Unknown assignee id");let S=b??R,T=[...b?[]:[{id:Zr(),...D(n.value),action:"create.contributor",payload:{id:S.id,name:S.name}}],{id:Zr(),...D(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:S.id}}],A=B(T,t.value.stateBranchRoot);return a(A)?c(A.message):u("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:S.id,name:S.name}})}let i=Re(e.assigneeName??"").trim();if(!i)return c("Provide assigneeId, self or assigneeName");let l=ct("Assignee name",i,80);if(l)return c(l);let d=oi({events:r.value.eventLog??[],registry:r.value.contributors,logFileNames:lr(t.value.stateBranchRoot)}).filter(b=>b.name===i);if(d.length>1)return c(`"${i}" matches ${d.length} contributors (${d.map(({id:b})=>b).join(", ")}). Assign by assigneeId to choose.`);let m=d[0];if(!m&&!e.createUnlinked)return c(`No contributor named "${i}". Assign by id, or pass createUnlinked to add them as an external assignee.`);let p=m?.id??Zr(),f=m?.name??i,y=[...!!r.value.contributors[p]?[]:[{id:Zr(),...D(n.value),action:"create.contributor",payload:{id:p,name:f}}],{id:Zr(),...D(n.value),action:"add.issue.assignee",payload:{id:e.issueId,assignee:p}}],x=B(y,t.value.stateBranchRoot);return a(x)?c(x.message):u("Added issue assignee",{id:e.issueId,ref:H(e.issueId),assignee:{id:p,name:f}})},Uu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;if(!r.value.contributors[e.contributorId])return c("Contributor not found");if(await Qv(t.value.stateBranchRoot,e.contributorId))return c("Cannot remove a contributor who has authored events \u2014 their name appears throughout the log");let i=[{id:Zr(),...D(n.value),action:"tombstone.contributor",payload:{id:e.contributorId}}],l=B(i,t.value.stateBranchRoot);return a(l)?c(l.message):u("Tombstoned contributor",{id:e.contributorId,name:bo})};var ju=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=cr(t.value.stateBranchRoot);if(a(o))return c(o.message);let s=e.boardId?Bv(o.value,e.boardId):o.value,i=new Set,l=sg(t.value.stateBranchRoot);if(a(l))return c(l.message);for(let p of l.value)p.userId&&i.add(p.userId);let d=r.value.contributors,m=oi({events:s,registry:d,logFileNames:lr(t.value.stateBranchRoot)}).map(({id:p,name:f,isExternal:g})=>({...Ye(p,f),isSelf:p===n.value.userId,isExternal:g,isRemoved:d[p]?.tombstoned===!0,hasAuthoredAnywhere:i.has(p)}));return u("Listed board contributors",m)},Hu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;if(!r.value.contributors[e.assigneeId])return c("Assignee not found");let s={id:Zr(),...D(n.value),action:"remove.issue.assignee",payload:{id:e.issueId,assignee:e.assigneeId}},i=B([s],t.value.stateBranchRoot);return a(i)?c(i.message):u("Removed issue assignee",{id:e.issueId,ref:H(e.issueId),assigneeId:e.assigneeId})};import{ulid as xl}from"ulid";var pi=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=tt(e.issueId);if(a(o))return o;let s=e.body.trim();if(!s)return c("Comment cannot be empty");if(s.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${s.length})`);let i=xl(),l={id:xl(),...D(n.value),action:"add.issue.comment",payload:{id:i,issue:e.issueId,md:s,author:n.value.userId}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Added issue comment",{id:i,issueId:e.issueId,body:s})},fi=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(m=>m.action==="add.issue.comment"&&m.payload.id===e.commentId);if(!o)return c("Unable to resolve comment");if(o.payload.author!==n.value.userId)return c("You can only delete your own comments");let s=tt(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(m=>m.action==="delete.issue.comment"&&m.payload.id===e.commentId))return u("Comment already deleted",{id:e.commentId,issueId:o.payload.issue});let l={id:xl(),...D(n.value),action:"delete.issue.comment",payload:{id:e.commentId,issue:o.payload.issue}},d=B([l],t.value.stateBranchRoot);return a(d)?c(d.message):u("Deleted issue comment",{id:e.commentId,issueId:o.payload.issue})},Wu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=r.value.eventLog.find(p=>p.action==="add.issue.comment"&&p.payload.id===e.commentId);if(!o)return c("Unable to resolve comment");if(o.payload.author!==n.value.userId)return c("You can only edit your own comments");let s=tt(o.payload.issue);if(a(s))return s;if(r.value.eventLog.some(p=>p.action==="delete.issue.comment"&&p.payload.id===e.commentId))return c("Comment was deleted");let l=e.body.trim();if(!l)return c("Comment cannot be empty");if(l.length>4e3)return c(`Comment cannot exceed ${4e3} characters (got ${l.length})`);let d={id:xl(),...D(n.value),action:"edit.issue.comment",payload:{id:e.commentId,issue:o.payload.issue,md:l}},m=B([d],t.value.stateBranchRoot);return a(m)?c(m.message):u("Edited issue comment",{id:e.commentId,issueId:o.payload.issue,body:l})};import{ulid as Zv}from"ulid";var Gu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;if(!tr(e.email))return c(`Not an email address: ${e.email}`);let o=et(e.email),s=e.contributorId??n.value.userId;if(!r.value.contributors[s])return c(`Unknown contributor: ${s}`);let i=ys(r.value.emailLinks,o);if(i.includes(s))return u(`${o} is already yours`,{contributor:s,email:o,contested:i.filter(d=>d!==s)});let l=B([{id:Zv(),action:"link.contributor.email",payload:{contributor:s,email:o},userId:n.value.userId}],t.value.stateBranchRoot);return a(l)?c(l.message):u(i.length>0?`Claimed ${o}, but somebody else claims it too, so it now resolves to neither of you`:`Claimed ${o}`,{contributor:s,email:o,contested:i})},Vu=async e=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let o=et(e.email),s=e.contributorId??n.value.userId,i=r.value.emailLinks[hs(o,s)];if(!i||i.tombstoned)return c(`No such link: ${o} to ${s}`);if(!qi(n.value.userId,i))return c("Only whoever made a claim, or the contributor it names, may undo it");let l=B([{id:Zv(),action:"unlink.contributor.email",payload:{contributor:s,email:o},userId:n.value.userId}],t.value.stateBranchRoot);return a(l)?c(l.message):u(`Unclaimed ${o}`,{contributor:s,email:o})},Il=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=q();if(a(n))return n;let{emailLinks:r,contributors:o}=n.value,s=new Map;for(let f of Object.values(r)){if(f.tombstoned)continue;let g=s.get(f.email)??new Set;g.add(f.contributor),s.set(f.email,g)}let i=[...s.entries()].map(([f,g])=>({email:f,contested:g.size>1,claimants:[...g].map(y=>Ye(y,o[y]?.name))})).sort((f,g)=>f.email.localeCompare(g.email)),l=te(),d=a(l)?[]:fn(r,l.value.userId),m=V().gitEmail,p=m?ys(r,m).filter(f=>a(l)||f!==l.value.userId):[];return u("Listed contributor emails",{emails:i,mine:d,git:m?{email:m,linkedToMe:d.includes(m),heldByOthers:p.map(f=>Ye(f,o[f]?.name))}:null})},El=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let{userId:o,userName:s}=n.value,i=Ue(t.value.repoRoot),l=await wn({repoRoot:t.value.repoRoot,stateBranch:a(i)?void 0:i.value,names:[s,await Rr(t.value.repoRoot)],links:r.value.emailLinks});if(a(l))return l;let d=br(l.value),m=d.filter(p=>p.looksLikeYours);return u(d.length===0?"No unclaimed addresses in this history":`${d.length} unclaimed address(es) in this history, ${m.length>0?`${m.length} of which look like yours`:"none obviously yours"}. Show them to the user and link only the ones they confirm; each is a permanent event that replicates to every clone.`,{contributor:o,candidates:d,likely:m.length})};var eb=(e,t)=>{let n=0,r=0,o=null;for(let s of e){if(s.userId!==t)continue;s.action==="add.issue"&&n++,s.action==="add.issue.comment"&&r++;let i=yo(s.id);if(a(i))continue;let l=i.value.getTime();(o===null||l<o)&&(o=l)}return{tickets:n,comments:r,joinedAt:o}};var zu=async(e={})=>{let t=await ee(e.repoRoot,{pull:!1});if(a(t))return t;let n=te();if(a(n))return n;let r=q();if(a(r))return r;let{userId:o,userName:s}=n.value,i=eb(r.value.eventLog,o),l=Ue(t.value.repoRoot),d=await wn({repoRoot:t.value.repoRoot,stateBranch:a(l)?void 0:l.value,names:[s,await Rr(t.value.repoRoot)],links:r.value.emailLinks}),m=a(d)?[]:d.value.filter(p=>p.claimedBy.length===1&&p.claimedBy[0]===o);return u("Derived personal stats",{...i,scanned:!a(d),commits:m.reduce((p,f)=>p+f.commits,0),claimedEmails:m.length})};var Mn="1.10.0";import oT from"node:fs";import tb from"node:path";var gi=Number(process.env.EPIQ_GUI_PORT)||3710,Ku="/api/instance",qu="epiq",Sl=e=>{try{return oT.realpathSync(tb.resolve(e))}catch{return tb.resolve(e)}},sT=e=>{let t=e;return typeof t=="object"&&t!==null&&t.app===qu&&typeof t.repoRoot=="string"&&typeof t.version=="string"&&typeof t.pid=="number"},nb=async(e,t=500)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),t);try{let o=await fetch(`http://127.0.0.1:${e}${Ku}`,{signal:n.signal});if(!o.ok)return null;let s=await o.json();return sT(s)?s:null}catch{return null}finally{clearTimeout(r)}};var iT=/^(```|~~~)[^\n]*\n[\s\S]*?\n\1[ \t]*$/gm,aT=/^(?:```|~~~)[\s\S]*$/m,lT=/^[ \t]*\|?[ \t]*:?-{2,}:?[ \t]*(?:\|[ \t]*:?-{2,}:?[ \t]*)*\|?[ \t]*$/gm,cT=/^[ \t]*\|.*$/gm,dT=/!\[[^\]]*\]\([^)]*\)/g,uT=/\[([^\]]*)\]\([^)]*\)/g,mT=/^[ \t]*(?:[#>]+[ \t]*|[-*+][ \t]+|\d+[.)][ \t]+)/gm,pT=/^[ \t]*(?:-{3,}|\*{3,}|_{3,})[ \t]*$/gm,fT=/[*`~]/g,gT=/(?<![0-9A-Za-z])_|_(?![0-9A-Za-z])/g,hT=e=>Re(e.replace(iT," ").replace(aT," ").replace(dT," ").replace(uT,"$1").replace(pT," ").replace(lT," ").replace(cT,t=>t.replaceAll("|"," ")).replace(mT,"").replace(fT,"").replace(gT,"")),yT=.5,rb=(e,t)=>{if(t<=0)return"";let n=hT(e);if(n.length<=t)return n;let r="\u2026",o=t-r.length;if(o<=0)return r.slice(0,t);let s=n.slice(0,o),i=s.lastIndexOf(" ");return`${(i>=o*yT?s.slice(0,i):s).trimEnd()}${r}`};var vT=e=>({...e,boards:(e.boards??[]).map(t=>({...t,swimlanes:(t.swimlanes??[]).map(n=>({...n,issues:(n.issues??[]).map(r=>({...r,description:""}))}))})),commentsByIssueId:Object.fromEntries(Object.entries(e.commentsByIssueId??{}).filter(([,t])=>t.length>0).map(([t,n])=>[t,n.map(r=>({...r,body:""}))])),attachmentsByIssueId:Object.fromEntries(Object.entries(e.attachmentsByIssueId??{}).filter(([,t])=>t.length>0))}),eo=e=>a(e)?e:u(e.message,vT(e.value)),bT=(e,t)=>(e.boards??[]).flatMap(n=>n.swimlanes??[]).flatMap(n=>n.issues??[]).find(n=>n.id===t),ob=(e,t)=>{let n=bT(e,t);return{issueId:t,description:n?.description??"",comments:e.commentsByIssueId?.[t]??[]}},xT=280,sb=(e,t)=>({issueId:e,excerpt:rb(t,xT)});var ib=e=>{let t,n=!1,r=!1,o=0,s=i();function i(){let g=me(e.project.repoRoot);if(a(g))return null;let y=he({repoRoot:g.value});return a(y)?null:xn(y.value)}let l=()=>{let g=pn();return a(g)?(se.error(g.message),null):g.value},d=()=>{let g=l();if(!g)return!1;let y=ht();return a(y)?!1:!!g.autoSync&&ll(y.value)===null},m=()=>{let g=uo(l()?.autoSyncDebounceMs);return Math.max(0,g-(Date.now()-o))},p=async()=>{if(!(n||r)&&d()){r=!0,o=Date.now();try{await Sr(async()=>{if(st().mode!=="live")return;await ci({repoRoot:e.project.repoRoot});let g=i();if(g===null||g===s)return;s=g;let y=eo(await Ht({repoRoot:e.project.repoRoot}));a(y)||Ur({type:"state",payload:y})})}finally{r=!1,f()}}};function f(){n||!d()||r||t||(t=setTimeout(()=>{t=void 0,p()},m()))}return f(),{queueSync:f,reschedule:()=>{t&&(clearTimeout(t),t=void 0),f()},dispose:()=>{n=!0,t&&clearTimeout(t)}}};var IT=new Set(["127.0.0.1","[::1]","localhost","epiq.localhost"]),Yu=(e,t)=>{if(!e)return!1;if(e==="null")return!0;let n;try{n=new URL(e)}catch{return!0}return n.protocol!=="http:"||n.port!==String(t)?!0:!IT.has(n.hostname)},ab=(e,t)=>e.method==="GET"||e.method==="HEAD"?null:Yu(e.origin,t)?{status:403,message:"Cross-origin request"}:e.method==="POST"&&!(e.contentType??"").toLowerCase().startsWith("application/json")?{status:415,message:"Expected content-type: application/json"}:null;import{WebSocketServer as aw}from"ws";var Pn=e=>({path:e.path,sha:e.shas[e.shas.length-1]??""});var ET=e=>{let t=e.lastIndexOf("/");return t===-1?".":e.slice(0,t)},lb=({commits:e,patch:t})=>{let n=e.map(i=>i.time),o=t.files.map(i=>({...Pn(i),changed:i.addedCount+i.removed})).reduce((i,l)=>i===null||l.changed>i.changed?l:i,null),s=t.insertions+t.deletions;return{commits:e.length,authors:[...new Set(e.map(i=>i.author))].sort(),firstCommitAt:n.length?Math.min(...n):null,lastCommitAt:n.length?Math.max(...n):null,files:t.files.length,filesAdded:t.files.filter(i=>i.status==="added").length,filesModified:t.files.filter(i=>i.status==="modified").length,filesDeleted:t.files.filter(i=>i.status==="deleted").length,binaryFiles:t.files.filter(i=>i.binary).length,directories:new Set(t.files.map(i=>ET(i.path))).size,insertions:t.insertions,deletions:t.deletions,net:t.insertions-t.deletions,largestFile:o,concentration:o&&s>0?o.changed/s:0,selfChurn:t.selfChurn,truncated:t.truncated}};var nt={line:["//"],block:[["/*","*/"]]},Gt={line:["#"],block:[]},Xu={line:["--"],block:[]},Xo={line:[],block:[["<!--","-->"]]},ST={line:[],block:[]},Y=(e,t)=>({name:e,comment:t}),Rl=Y("TypeScript",nt),Cl=Y("JavaScript",nt),cb={ts:Rl,tsx:Rl,mts:Rl,cts:Rl,js:Cl,jsx:Cl,mjs:Cl,cjs:Cl,py:Y("Python",{line:["#"],block:[['"""','"""']]}),rb:Y("Ruby",{line:["#"],block:[["=begin","=end"]]}),go:Y("Go",nt),rs:Y("Rust",nt),java:Y("Java",nt),kt:Y("Kotlin",nt),swift:Y("Swift",nt),c:Y("C",nt),h:Y("C",nt),cc:Y("C++",nt),cpp:Y("C++",nt),hpp:Y("C++",nt),cs:Y("C#",nt),php:Y("PHP",nt),scala:Y("Scala",nt),dart:Y("Dart",nt),lua:Y("Lua",Xu),hs:Y("Haskell",Xu),sql:Y("SQL",Xu),ex:Y("Elixir",Gt),exs:Y("Elixir",Gt),pl:Y("Perl",Gt),r:Y("R",Gt),jl:Y("Julia",Gt),sh:Y("Shell",Gt),bash:Y("Shell",Gt),zsh:Y("Shell",Gt),vue:Y("Vue",Xo),svelte:Y("Svelte",Xo),html:Y("HTML",Xo),xml:Y("XML",Xo),md:Y("Markdown",Xo),mdx:Y("Markdown",Xo),css:Y("CSS",{line:[],block:[["/*","*/"]]}),scss:Y("CSS",nt),less:Y("CSS",nt),yml:Y("YAML",Gt),yaml:Y("YAML",Gt),toml:Y("TOML",Gt),ini:Y("INI",Gt),json:Y("JSON",ST)},RT="Other",db=e=>{let t=e.slice(e.lastIndexOf("/")+1),n=t.lastIndexOf(".");return n<=0?"":t.slice(n+1).toLowerCase()},to=e=>cb[db(e)]?.name??RT,hi=e=>cb[db(e)]?.comment??null,CT=[/\.(test|spec)\.[a-z0-9]+$/i,/(^|\/)test_[^/]+\.py$/,/_test\.[a-z0-9]+$/i,/(^|\/)conftest\.py$/,/Tests?\.(java|kt|cs|scala)$/],NT=/(^|\/)(tests?|__tests__|spec|specs|e2e|src\/test|features)\//i,Jo=e=>NT.test(e)||CT.some(t=>t.test(e)),AT=/(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|go\.sum|poetry\.lock|Gemfile\.lock|composer\.lock)$/,TT=/(^|\/)(node_modules|dist|build|out|target|vendor|coverage|\.next|__snapshots__)\//,wT=/(\.min\.(js|css)|\.map|\.snap|\.pb\.go|_pb2\.py)$/,an=e=>AT.test(e)||TT.test(e)||wT.test(e),ub=e=>/(^|\/)(package\.json|go\.mod|Cargo\.toml|requirements[^/]*\.txt|pyproject\.toml|Gemfile|composer\.json|pom\.xml|build\.gradle(\.kts)?)$/.test(e),mb=e=>/(^|\/)\.github\/workflows\//.test(e)||/(^|\/)(Dockerfile|docker-compose[^/]*\.ya?ml|Makefile|Jenkinsfile|\.gitlab-ci\.yml)$/.test(e)||/\.tf$/.test(e),pb=e=>/\.(md|mdx|rst|txt)$/i.test(e)||/(^|\/)docs?\//i.test(e),MT=/\b(it|test|describe|context|suite)\.skip\b|\bx(it|describe|test)\s*\(|@pytest\.mark\.skip|@unittest\.skip|\bt\.Skip\s*\(|@(Ignore|Disabled)\b/,PT=/\b(it|test|describe|context|suite)\.only\b|\bf(it|describe|test)\s*\(/,fb=e=>MT.test(e),gb=e=>PT.test(e);var hb=/\b(TODO|FIXME|HACK|XXX)\b/,LT=/[;{}]\s*$|^\s*(const|let|var|function|def|class|if|for|while|return|import|export|await|print)\b.*[=(]/,Ju=(e,t)=>{let n=e.trim();return n===""?"blank":t&&(t.line.some(r=>n.startsWith(r))||t.block.some(([r])=>n.startsWith(r))||t.block.some(([r])=>r==="/*")&&(n.startsWith("*")||n.startsWith("*/")))?"comment":"code"},kT=(e,t)=>{let n=e.trim();for(let r of[...t.line,...t.block.flat(),"*"])if(n.startsWith(r)){n=n.slice(r.length).trim();break}return n},yb=({patch:e,repoShareByLanguage:t})=>{let n=new Map,r=0,o=0,s=0,i=0,l=0,d=0;for(let p of e.files){if(p.binary||an(p.path))continue;let f=hi(p.path);if(!f||f.line.length===0&&f.block.length===0)continue;let g=to(p.path),y=n.get(g)??{comment:0,code:0};for(let{text:x}of p.added){let b=Ju(x,f);if(hb.test(x)&&i++,b==="blank"){s++;continue}if(b==="comment"){r++,y.comment++,f&<.test(kT(x,f))&&d++;continue}o++,y.code++}for(let{text:x}of p.removedLines)hb.test(x)&&l++;n.set(g,y)}let m=r+o;return{byLanguage:[...n.entries()].map(([p,f])=>({name:p,commentLines:f.comment,codeLines:f.code,share:f.comment+f.code===0?0:f.comment/(f.comment+f.code),repoShare:t?.get(p)??null})).sort((p,f)=>f.commentLines+f.codeLines-(p.commentLines+p.codeLines)),commentLines:r,codeLines:o,blankLines:s,share:m===0?0:r/m,todoLinesAdded:i,todoLinesRemoved:l,commentedOutCodeLines:d}};var DT=/\bconsole\.(log|debug|dir)\s*\(|\bdebugger\b|^\s*print\s*\(|\bfmt\.Print(ln|f)?\s*\(|\bSystem\.out\.print|\bdbg!\s*\(/,Nl=6,Qu=10,BT=e=>{let t=0;for(let n of e){if(n.trim()===""||n.startsWith(" "))continue;let r=n.length-n.trimStart().length;r>0&&(t===0||r<t)&&(t=r)}return Math.min(Math.max(t,2),8)},OT=(e,t)=>{let n=e.length-e.trimStart().length;if(n===0)return 0;let r=e.slice(0,n).split(" ").length-1;return r>0?r:Math.floor(n/t)},FT=e=>{if(e.length<Nl*2)return 0;let t=new Map,n=new Array(e.length).fill(!1);for(let r=0;r+Nl<=e.length;r++){let o=e.slice(r,r+Nl);if(o.some(l=>l.text.length<3))continue;let s=o.map(l=>l.text).join(`
|
|
101
|
+
`),i=t.get(s);if(i===void 0){t.set(s,{...o[0],at:r});continue}if(i.file!==o[0]?.file)for(let l=0;l<Nl;l++)n[i.at+l]=!0,n[r+l]=!0}return n.filter(Boolean).length},vb=({patch:e})=>{let t=[],n=[],r=[],o=!1,s=0,i=0,l=null,d=[];for(let[m,p]of e.files.entries()){if(an(p.path)&&t.push(Pn(p)),ub(p.path)&&n.push(Pn(p)),mb(p.path)&&r.push(Pn(p)),pb(p.path)&&(o=!0),p.binary||an(p.path))continue;let f=p.added.map(x=>x.text),g=BT(f),y=p.status!=="deleted";for(let x of f){DT.test(x)&&s++;let b=OT(x,g);b>i&&(i=b,l=Pn(p)),y&&d.push({text:x.trim(),file:m})}d.push({text:" ",file:m})}return{generatedPaths:t.slice(0,Qu),dependencyManifests:n.slice(0,Qu),buildOrCiPaths:r.slice(0,Qu),docsTouched:o,debugPrintLinesAdded:s,maxIndentLevels:i,deepestFile:l,duplicatedLines:FT(d)}};var bb=({patch:e,languagesBefore:t})=>{let n=new Map,r=0;for(let i of e.files){if(i.binary)continue;let l=i.addedCount+i.removed;if(an(i.path)){r+=l;continue}let d=to(i.path),m=n.get(d)??{name:d,added:0,removed:0,addedInTests:0,share:0};m.added+=i.addedCount,m.removed+=i.removed,Jo(i.path)&&(m.addedInTests+=i.addedCount),n.set(d,m)}let o=[...n.values()].reduce((i,l)=>i+l.added+l.removed,0),s=[...n.values()].map(i=>({...i,share:o===0?0:(i.added+i.removed)/o})).sort((i,l)=>l.added+l.removed-(i.added+i.removed));return{languages:s,introduced:t===null?[]:s.filter(i=>!t.has(i.name)).map(i=>i.name),generatedLines:r}};var _T=200,Zu=2e5,$T=5e4,xb=25,UT=64*1024*1024,em="",jT=/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/,HT=/^diff --git a\/(.+) b\/\1$/,Ib=(e,t)=>e==="/dev/null"?null:e.startsWith(t)?e.slice(2):e,Eb=(e,t)=>e===null?"added":t===null?"deleted":"modified",WT=()=>({byPath:new Map,insertions:0,deletions:0,selfChurn:0,retainedLines:0}),GT=(e,t)=>{let n=e.byPath,r="",o=null,s=null,i=null,l=!1,d=0,m=(f,g)=>g==="modified"&&f==="added"?"added":g,p=(f,g)=>{let y=n.get(f);if(y)return y.entry.status=m(y.entry.status,g),y.entry.shas.includes(r)||y.entry.shas.push(r),y;let b={entry:{path:f,status:g,binary:!1,added:[],addedCount:0,removed:0,removedLines:[],shas:[r]},pendingByText:new Map};return n.set(f,b),b};for(let f of t.split(`
|
|
102
|
+
`)){if(f.startsWith(em)){r=f.slice(em.length).trim(),o=null,s=null,i=null,l=!1;continue}if(f.startsWith("diff --git ")){o=null,i=null,l=!0,s=HT.exec(f)?.[1]??null;continue}if(l&&f.startsWith("Binary files ")&&s){let[,y=""]=/^Binary files (.*) differ$/.exec(f)??[],[x="",b=""]=y.split(" and ");o=p(s,Eb(x==="/dev/null"?null:x,b==="/dev/null"?null:b)),o.entry.binary=!0;continue}if(l&&f.startsWith("--- ")){i=Ib(f.slice(4),"a/");continue}if(l&&f.startsWith("+++ ")){let y=Ib(f.slice(4),"b/"),x=y??i??s;x&&(o=p(x,Eb(i,y)));continue}let g=jT.exec(f);if(g){d=Number(g[1]),l=!1;continue}if(o){if(f.startsWith("+")){let y=f.slice(1);e.insertions++,o.entry.addedCount++,e.retainedLines<Zu&&(o.entry.added.push({sha:r,line:d,text:y}),e.retainedLines++),o.pendingByText.size<$T&&o.pendingByText.set(y,(o.pendingByText.get(y)??0)+1),d++;continue}if(f.startsWith("-")){let y=f.slice(1);e.deletions++,o.entry.removed++,e.retainedLines<Zu&&(o.entry.removedLines.push({sha:r,line:0,text:y}),e.retainedLines++);let x=o.pendingByText.get(y)??0;x>0&&y.trim().length>2&&(e.selfChurn++,o.pendingByText.set(y,x-1))}}}},VT=e=>({files:[...e.byPath.values()].map(t=>t.entry),insertions:e.insertions,deletions:e.deletions,selfChurn:e.selfChurn,retainedLines:e.retainedLines});var Sb=async({repoRoot:e,shas:t})=>{if(t.length===0)return u("No commits to scan",{files:[],insertions:0,deletions:0,selfChurn:0,scannedCommits:0,truncated:!1});let n=t.slice(0,_T).reverse(),r=WT(),o=0,s=0,i=!1;for(let d=0;d<n.length;d+=xb){let m=n.slice(d,d+xb),p=await j({cwd:e,args:["-c","core.quotePath=false","show","--unified=0","--no-renames","--no-color",`--format=${em}%H`,...m]});if(a(p))return c(p.message);if(GT(r,p.value.stdout),o+=p.value.stdout.length,s+=m.length,o>UT){i=!0;break}}let l=VT(r);return u("Scanned ticket patch",{files:l.files,insertions:l.insertions,deletions:l.deletions,selfChurn:l.selfChurn,scannedCommits:s,truncated:i||s<t.length||l.retainedLines>=Zu})};var zT=40,KT=/^\d{6} blob ([0-9a-f]{40})\t(.+)$/,Rb=async({repoRoot:e,sha:t})=>{let n=await De({cwd:e,args:["-c","core.quotePath=false","ls-tree","-r",`${t}~1`]});if(n.exitCode!==0)return null;let r=new Set,o=new Map;for(let p of n.stdout.split(`
|
|
103
|
+
`)){let f=KT.exec(p);if(!f)continue;let[,g="",y=""]=f;if(an(y))continue;let x=to(y);if(r.add(x),Jo(y)||!hi(y))continue;let b=o.get(x)??[];b.length<zT&&(b.push({blob:g,path:y}),o.set(x,b))}let s=[...o.values()].flat(),i=await Fi(s.map(p=>p.blob),e);if(a(i))return{languages:r,commentShareByLanguage:new Map};let l=i.value,d=new Map;for(let{blob:p,path:f}of s){let g=l.get(p);if(g===void 0)continue;let y=hi(f),x=to(f),b=d.get(x)??{comment:0,code:0};for(let R of g.split(`
|
|
104
|
+
`)){let S=Ju(R,y);S==="comment"&&b.comment++,S==="code"&&b.code++}d.set(x,b)}let m=new Map;for(let[p,f]of d){let g=f.comment+f.code;g>0&&m.set(p,f.comment/g)}return{languages:r,commentShareByLanguage:m}};var Cb=({patch:e})=>{let t=0,n=0,r=[],o=[],s=0,i=0;for(let l of e.files)if(!(l.binary||an(l.path))&&Jo(l.path)){t+=l.addedCount,n+=l.removed,l.status==="added"&&r.push(Pn(l)),l.status==="deleted"&&o.push(Pn(l));for(let{text:d}of l.added)fb(d)&&s++,gb(d)&&i++}return{testLinesAdded:t,testLinesRemoved:n,addedTestFiles:r,deletedTestFiles:o,skippedTestLinesAdded:s,focusedTestLinesAdded:i}};var qT=e=>e.reduce((t,n)=>t===null||n.time<t.time?n:t,null)?.sha??null,Nb=async({repoRoot:e,ref:t,commits:n})=>{let r=await Sb({repoRoot:e,shas:n.map(l=>l.sha)});if(a(r))return c(r.message);let o=r.value,s=qT(n),i=s?await Rb({repoRoot:e,sha:s}):null;return u("Derived issue stats",{ref:t,shape:lb({commits:n,patch:o}),languages:bb({patch:o,languagesBefore:i?.languages??null}),tests:Cb({patch:o}),comments:yb({patch:o,repoShareByLanguage:i?.commentShareByLanguage??null}),flags:vb({patch:o})})};var yi=e=>{if(a(e))return e;let t=xe(),n=a(t)?{}:t.value.emailLinks,r=a(t)?{}:t.value.contributors,o=ap(n),s=e.value.map(i=>({...i,authorIdentity:Vy({authorName:i.author,authorEmail:i.authorEmail,owners:o,registry:r})}));return u(e.message,s)};var YT=32,vi=new Map;var XT=(e,t)=>{if(vi.set(e,t),vi.size>YT){let n=vi.keys().next();n.done||vi.delete(n.value)}return t},Al=async(e={idOrRef:""})=>{let t=e.idOrRef.trim();if(!t)return c("idOrRef must not be empty");let n=t.length>7?H(t):t.toUpperCase(),r=me(e.repoRoot??process.cwd());if(a(r))return c(r.message);let o=r.value,s=yi(await zn({repoRoot:o,ref:n}));if(a(s))return c(s.message);let i=s.value.map(p=>({sha:p.sha,time:p.time,author:p.authorIdentity?.resolved?p.authorIdentity.name:p.author,subject:p.subject})),l=[o,n,i.map(p=>`${p.sha}:${p.author}`).join(",")].join(" "),d=vi.get(l);if(d)return u("Derived issue stats",d);let m=await Nb({repoRoot:o,ref:n,commits:i});return a(m)?c(m.message):u("Derived issue stats",XT(l,m.value))};var JT=new RegExp(`^[0-9A-Z]{${7}}$`),QT=e=>{let t=e.indexOf(" ");if(t===-1)return null;let n=e.slice(0,t).toUpperCase();return JT.test(n)?n:null},ZT=e=>{let t={};for(let n of e){let r=QT(n.subject);if(!r)continue;let o=t[r]??={commits:0,insertions:0,deletions:0};o.commits++,o.insertions+=n.insertions,o.deletions+=n.deletions}return t},Ab=async(e={})=>{let t=await Uo({repoRoot:e.repoRoot});return a(t)?t:u("Collected diff stats by ref",ZT(t.value))};var ew="Filed here",Tb=(e,t)=>e.set(t,(e.get(t)??0)+1),wb=(e,t,n)=>[...e.entries()].map(([r,o])=>({laneId:r,title:r===null?ew:n(r),count:o,share:t===0?0:o/t})).sort((r,o)=>o.count-r.count||r.title.localeCompare(o.title)),Mb=(e,t,n)=>{let r=new Map,o=new Map,s=0,i=0;for(let l of t)for(let[d,m]of l.entries()){if(m!==e)continue;s++,Tb(r,l[d-1]??null);let p=l[d+1];p!==void 0&&(i++,Tb(o,p))}return{arrived:s,departed:i,arrivesFrom:wb(r,s,n),movesOnTo:wb(o,i,n)}};var Pb=e=>{if(e.length===0)return null;let t=Math.floor(e.length/2);return e.length%2===0?(e[t-1]+e[t])/2:e[t]};var bi=1440*60*1e3,tw=({laneIds:e,journeys:t,now:n,days:r})=>{let o=n-(r-1)*bi,s=new Map(e.map(i=>[i,Array.from({length:r},()=>[])]));for(let i of t)for(let[l,d]of i.entries()){let m=s.get(d.laneId);if(!m)continue;let p=i[l+1]?.enteredAt,f=Math.max(0,Math.ceil((d.enteredAt-o)/bi)),g=p===void 0?r-1:Math.min(r-1,Math.ceil((p-o)/bi)-1);for(let y=f;y<=g;y++)m[y].push(o+y*bi-d.enteredAt)}return Object.fromEntries([...s].map(([i,l])=>[i,l.map((d,m)=>({t:o+m*bi,median:Pb(d.sort((p,f)=>p-f)),count:d.length}))]))},Lb=({laneId:e,journeys:t,now:n,days:r})=>tw({laneIds:[e],journeys:t,now:n,days:r})[e];var nw=40,rw=30,ow=()=>({tickets:0,commits:0,insertions:0,deletions:0}),sw=async(e,t)=>{let n=ow();for(let r of t.slice(0,nw)){let o=await Al({repoRoot:e,idOrRef:H(r)});a(o)||o.value.shape.commits===0||(n.tickets++,n.commits+=o.value.shape.commits,n.insertions+=o.value.shape.insertions,n.deletions+=o.value.shape.deletions)}return n},kb=async e=>{let t=q();if(a(t))return t;let{nodes:n}=t.value;if(!n[e.swimlaneId])return c("Swimlane not found");let o=Object.values(n).filter(_),s=o.map(d=>du(d.log??[],Be(d.id))),i=Mb(e.swimlaneId,s.map(d=>d.map(m=>m.laneId)),d=>n[d]?.title??"Elsewhere"),l=o.filter(d=>d.parentNodeId===e.swimlaneId).map(d=>d.id);return u("Derived swimlane stats",{swimlaneId:e.swimlaneId,createdAt:Be(e.swimlaneId),...i,stayTrend:Lb({laneId:e.swimlaneId,journeys:s,now:Date.now(),days:rw}),code:await sw(e.repoRoot,l)})};var Db=new Set(["sync","email:link","email:unlink","issues:create","board:create","board:edit:title","swimlane:create","swimlane:edit:title","swimlane:delete","swimlane:move","issues:move","issue:close","issue:reopen","issue:edit:title","issue:edit:description","issue:tag:add","issue:tag:remove","contributor:remove","tag:remove","issue:assignee:add","issue:assignee:remove","issue:comment:add","issue:comment:delete"]);var Bb=e=>{let t=$n({exclude:e});return a(t)?[]:t.value.map(n=>({projectId:n.projectId,name:Io(n.root),root:n.root,lastOpenedAt:n.lastOpenedAt}))},Ob=e=>{let t=$n();if(a(t))return c(t.message);let n=t.value.find(r=>r.root===e);return n?u("Resolved recent project",n.root):c(`Not a recent project: ${e}`)};import{z as k}from"zod";var re=k.string().min(1),Fb=k.discriminatedUnion("at",[k.object({at:k.literal("start")}),k.object({at:k.literal("end")}),k.object({at:k.literal("before"),sibling:re}),k.object({at:k.literal("after"),sibling:re})]),xi=k.number().finite(),ce=(e,t)=>k.object({type:k.literal(e),payload:t}),no=e=>k.object({type:k.literal(e)}),iw=k.discriminatedUnion("type",[no("state:get"),no("issues:list"),no("sync"),no("time-travel:live"),no("diff-stats:get"),ce("project:open",k.object({root:k.string().min(1)})),ce("issues:create",k.object({title:k.string(),parentId:re,description:k.string().optional(),tagNames:k.array(k.string()).optional()})),ce("board:create",k.object({title:k.string()})),ce("board:edit:title",k.object({boardId:re,title:k.string()})),ce("swimlane:create",k.object({title:k.string(),boardId:re})),ce("swimlane:edit:title",k.object({swimlaneId:re,title:k.string()})),ce("swimlane:delete",k.object({swimlaneId:re})),ce("swimlane:move",k.object({swimlaneId:re,boardId:re,position:Fb.optional()})),ce("issues:move",k.object({issueId:re,parentId:re,position:Fb.optional()})),ce("issue:edit:title",k.object({issueId:re,title:k.string()})),ce("issue:edit:description",k.object({issueId:re,description:k.string()})),ce("issue:tag:add",k.object({issueId:re,tagName:k.string()})),ce("issue:tag:remove",k.object({issueId:re,tagId:re})),ce("contributor:remove",k.object({contributorId:re})),ce("tag:remove",k.object({tagId:re})),k.object({type:k.literal("contributors:get"),payload:k.object({boardId:re.optional()}).optional()}),ce("issue:assignee:add",k.object({issueId:re,assigneeId:re.optional(),assigneeName:k.string().optional(),createUnlinked:k.boolean().optional()})),ce("issue:assignee:remove",k.object({issueId:re,assigneeId:re})),ce("issue:close",k.object({issueId:re})),ce("issue:reopen",k.object({issueId:re})),ce("issue:comment:add",k.object({issueId:re,body:k.string()})),ce("issue:comment:delete",k.object({issueId:re,commentId:re})),ce("issue:comment:edit",k.object({issueId:re,commentId:re,body:k.string()})),ce("issue:get",k.object({issueId:re})),ce("issue:preview:get",k.object({issueId:re})),k.object({type:k.literal("timeline:get"),payload:k.object({start:xi.optional(),end:xi.optional(),boardId:re.optional(),requestId:k.number().finite().optional()}).optional()}),k.object({type:k.literal("commits:get"),payload:k.object({start:xi.optional(),end:xi.optional(),requestId:k.number().finite().optional()}).optional()}),ce("time-travel:scrub",k.object({targetTime:xi})),ce("time-travel:checkout-event",k.object({eventId:k.string().min(1)})),ce("commit:inspect",k.object({sha:k.string()})),k.object({type:k.literal("emails:get")}),ce("email:link",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ce("email:unlink",k.object({email:k.string().min(1).max(254),contributorId:k.string().min(1).optional()})),ce("commit:diff:get",k.object({sha:k.string()})),ce("issue:commits:get",k.object({issueId:re})),ce("issue:squashed-diff:get",k.object({issueId:re})),ce("issue:stats:get",k.object({issueId:re})),ce("swimlane:stats:get",k.object({swimlaneId:re})),no("me:stats:get"),no("settings:get"),ce("settings:set",k.object({autoSync:k.boolean().optional(),autoSyncIntervalMs:k.number().finite().optional()}))]);var _b=e=>{let t=iw.safeParse(e);return t.success?{ok:!0,message:t.data}:{ok:!1,error:`Invalid message: ${t.error.issues.map(r=>`${r.path.join(".")||"<root>"}: ${r.message}`).join(", ")}`}};var lw=1024*1024,tm=()=>{Ur({type:"state",payload:eo(Jr())})},ne=(e,t)=>{e.send(JSON.stringify(t))},Ii=async(e,t)=>{let n=eo(await Ht({repoRoot:t}));return a(n)&&n.message===pc?ne(e,{type:"state:unavailable",payload:{message:n.message,repoRoot:t,recentProjects:Bb(t)}}):ne(e,{type:"state",payload:n})},cw=async(e,t)=>{let n=()=>ne(e,{type:"state",payload:eo(Jr())});if(st().mode!=="live")return n();let r=await Ht({repoRoot:t});return st().mode!=="live"?n():ne(e,{type:"state",payload:eo(r)})},ze=async(e,t,n,r,o)=>{if(ne(e,{type:r,payload:o}),a(o))return ne(e,{type:"failed",payload:o.message});n(),cw(e,t)},$b=(e,t,{onStateChanged:n,onSyncSettingsChanged:r,getPort:o})=>{new aw({server:e,path:"/ws",maxPayload:lw,verifyClient:i=>!Yu(i.origin,o())}).on("connection",i=>{Ng(i),i.on("message",async l=>{let d=async m=>{let{type:p}=m,f=t.repoRoot;if(p==="project:open"){let g=Ob(m.payload.root);return ne(i,{type:"project:open:result",payload:g}),a(g)?void 0:(t.repoRoot=g.value,Ii(i,g.value))}if(p==="timeline:get"){let{requestId:g,...y}=m.payload??{};return ne(i,{type:"timeline",requestId:g,payload:await jv({repoRoot:f,...y})})}if(p==="issue:get"){let g=m.payload?.issueId,y=Jr(),x=Au(g);return ne(i,{type:"issue",payload:a(y)?y:u("Issue detail",{...ob(y.value,g),history:a(x)?[]:x.value})})}if(p==="issue:preview:get"){let{issueId:g}=m.payload,y=bu(g);return ne(i,{type:"issue:preview:result",payload:{issueId:g,result:a(y)?y:u("Issue preview",sb(g,y.value))}})}if(p==="commits:get"){let{requestId:g,...y}=m.payload??{};return ne(i,{type:"commits",requestId:g,payload:yi(await Uo({repoRoot:f,...y}))})}if(p==="emails:get")return ne(i,{type:"emails",payload:await Il({repoRoot:f}),suggestions:await El({repoRoot:f})});if(p==="email:link"||p==="email:unlink"){let y=await(p==="email:link"?Gu:Vu)({repoRoot:f,...m.payload});return ne(i,{type:"emails",payload:await Il({repoRoot:f}),suggestions:await El({repoRoot:f}),lastAction:a(y)?{ok:!1,message:y.message}:{ok:!0,message:y.message}}),ze(i,f,n,`${p}:result`,y)}if(p==="me:stats:get")return ne(i,{type:"me:stats",payload:await zu({repoRoot:f})});if(p==="settings:get")return ne(i,{type:"settings",payload:si()});if(p==="settings:set"){let g=zo({enabled:m.payload.autoSync,intervalMs:m.payload.autoSyncIntervalMs});return a(g)||r(),ne(i,{type:"settings",payload:a(g)?si():g,lastAction:a(g)?{ok:!1,message:g.message}:{ok:!0,message:g.message}})}if(p==="commit:inspect")return ne(i,{type:"commit:inspect:result",payload:await Xs({repoRoot:f,sha:m.payload.sha})});if(p==="commit:diff:get"){let{sha:g}=m.payload;return ne(i,{type:"commit:diff:result",payload:{sha:g,result:await Ad({repoRoot:f,sha:g})}})}if(p==="issue:commits:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:commits:result",payload:{issueId:g,result:yi(await zn({repoRoot:f,ref:H(g)}))}})}if(p==="issue:squashed-diff:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:squashed-diff:result",payload:{issueId:g,result:await Td({repoRoot:f,ref:H(g)})}})}if(p==="issue:stats:get"){let{issueId:g}=m.payload;return ne(i,{type:"issue:stats:result",payload:{issueId:g,result:await Al({repoRoot:f,idOrRef:H(g)})}})}if(p==="diff-stats:get")return ne(i,{type:"diff-stats",payload:await Ab({repoRoot:f})});if(p==="swimlane:stats:get"){let{swimlaneId:g}=m.payload;return ne(i,{type:"swimlane:stats:result",payload:{swimlaneId:g,result:await kb({repoRoot:f,swimlaneId:g})}})}if(p==="time-travel:scrub"){let g=await pu({repoRoot:f,targetTime:m.payload.targetTime});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="time-travel:checkout-event"){let g=await Wv({repoRoot:f,eventId:m.payload.eventId});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="time-travel:live"){let g=await Gv({repoRoot:f});return ne(i,{type:"time-travel:result",payload:g}),a(g)?void 0:tm()}if(p==="state:get")return Ii(i,f);if(p==="sync"){let g=await ci({repoRoot:f});return ne(i,{type:"sync:result",payload:g}),n(),Ii(i,f)}if(p==="issue:comment:add"){let g=await pi({repoRoot:f,...m.payload});return ze(i,f,n,"issue:comment:add:result",g)}if(p==="issue:comment:edit"){let g=await Wu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:comment:edit:result",g)}if(p==="issue:comment:delete"){let g=await fi({repoRoot:f,...m.payload});return ne(i,{type:"issue:comment:delete:result",payload:g}),a(g)?ne(i,{type:"failed",payload:g.message}):(n(),Ii(i,f))}if(p==="issue:edit:description"){let g=await Tu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:edit:description:result",g)}if(p==="issue:edit:title"){let g=await wu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:edit:title:result",g)}if(p==="issue:tag:add"){let g=await Ou({repoRoot:f,...m.payload});return ze(i,f,n,"issue:tag:add:result",g)}if(p==="issue:tag:remove"){let g=await _u({repoRoot:f,...m.payload});return ze(i,f,n,"issue:tag:remove:result",g)}if(p==="contributor:remove"){let g=await Uu({repoRoot:f,...m.payload});return ze(i,f,n,"contributor:remove:result",g)}if(p==="tag:remove"){let g=await Fu({repoRoot:f,...m.payload});return ze(i,f,n,"tag:remove:result",g)}if(p==="contributors:get")return ne(i,{type:"contributors",payload:await ju({repoRoot:f,...m.payload})});if(p==="issue:assignee:add"){let g=await $u({repoRoot:f,...m.payload});return ze(i,f,n,"issue:assignee:add:result",g)}if(p==="issue:assignee:remove"){let g=await Hu({repoRoot:f,...m.payload});return ze(i,f,n,"issue:assignee:remove:result",g)}if(p==="issues:list")return ne(i,{type:"issues",payload:await Eu({repoRoot:f})});if(p==="issues:create"){let g=await Su({...m.payload,repoRoot:f});return ne(i,{type:"issues:create:result",payload:g}),a(g)?Ur({type:"failed",payload:g.message}):(n(),Ii(i,f))}if(p==="board:create"){let g=await Mu({...m.payload,repoRoot:f});return ze(i,f,n,"board:create:result",g)}if(p==="board:edit:title"){let g=await Pu({...m.payload,repoRoot:f});return ze(i,f,n,"board:edit:title:result",g)}if(p==="swimlane:create"){let g=await Lu({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:create:result",g)}if(p==="swimlane:edit:title"){let g=await ku({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:edit:title:result",g)}if(p==="swimlane:delete"){let g=await Bu({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:delete:result",g)}if(p==="swimlane:move"){if(!m.payload.position)return ne(i,{type:"error",message:"Missing move position"});let g=await Du({...m.payload,repoRoot:f});return ze(i,f,n,"swimlane:move:result",g)}if(p==="issues:move"){if(!m.payload.position)return ne(i,{type:"error",message:"Missing move position"});let g=await Nu({...m.payload,repoRoot:f});return ze(i,f,n,"issues:move:result",g)}if(p==="issue:close"){let g=await Ru({repoRoot:f,issueId:m.payload.issueId});return ze(i,f,n,"issue:close:result",g)}if(p==="issue:reopen"){let g=await Cu({repoRoot:f,issueId:m.payload.issueId});return ze(i,f,n,"issue:reopen:result",g)}return ne(i,{type:"error",message:"Unknown message type"})};try{let m=_b(JSON.parse(l.toString()));if(!m.ok)return ne(i,{type:"error",message:m.error});let p=m.message;return Db.has(p.type)?await Sr(async()=>st().mode!=="live"?ne(i,{type:"failed",payload:"Read-only while viewing history"}):d(p)):await d(p)}catch(m){return ne(i,{type:"error",message:m instanceof Error?m.message:String(m)})}})})};var fw=ro.dirname(pw(import.meta.url)),gw=process.env.IS_LOCAL==="true"?ro.resolve(process.cwd(),"dist/gui"):ro.join(fw,"gui"),Tl,hw=async()=>(Tl===void 0&&(Tl=await import("node:sea").catch(()=>null)),Tl?.isSea()?Tl:null),Le=(e,t,n)=>{e.writeHead(t,{"content-type":"application/json"}),e.end(JSON.stringify(n))},yw=e=>Le(e,409,{isError:!0,message:"Read-only while viewing history"}),wl=(e,t)=>Sr(async()=>st().mode!=="live"?yw(e):t()),Ub=async(e,t=1024*1024)=>new Promise((n,r)=>{let o=[],s=0;e.on("data",i=>{if(s+=i.length,s>t){e.destroy(),r(new Error("Request body too large"));return}o.push(i)}),e.on("end",()=>{let i=Buffer.concat(o).toString("utf8");try{n(i?JSON.parse(i):{})}catch{r(new Error("Invalid JSON body"))}}),e.on("error",r)}),vw=2*1024*1024,bw={png:"image/png",jpg:"image/jpeg",gif:"image/gif",webp:"image/webp"},xw=e=>e.endsWith(".html")?"text/html; charset=utf-8":e.endsWith(".js")?"text/javascript; charset=utf-8":e.endsWith(".css")?"text/css; charset=utf-8":e.endsWith(".json")?"application/json; charset=utf-8":e.endsWith(".ico")?"image/x-icon":"application/octet-stream",jb=new Map,Iw=e=>`"${uw("sha1").update(e).digest("base64url")}"`,Ew=async e=>{try{let{size:t,mtimeMs:n}=await dw(e);return`${t}:${n}`}catch{return null}},Sw=e=>{try{return decodeURIComponent(e)}catch{return null}},Hb=async(e,t,n)=>{let r=e==="/"?"/index.html":Sw(e);if(r===null)return Le(n,404,{isError:!0,message:"Not found"});let o=r.replace(/^\/+/,""),s=ro.resolve(gw),i=ro.resolve(s,o),l=ro.relative(s,i);if(l.startsWith("..")||ro.isAbsolute(l))return Le(n,403,{isError:!0,message:"Forbidden"});let d=await hw(),m=d?"sea":await Ew(i),p=m===null?void 0:jb.get(l),f=p&&p.stamp===m?p.etag:null;if(f&&t.headers["if-none-match"]===f)return n.writeHead(304,{etag:f,"cache-control":"no-cache"}),n.end();try{let g=d?Buffer.from(d.getAsset(`gui/${l}`)):await Wb(i),y=f??Iw(g);return m!==null&&jb.set(l,{stamp:m,etag:y}),n.writeHead(200,{"content-type":xw(i),etag:y,"cache-control":"no-cache"}),n.end(g)}catch{return Le(n,404,{isError:!0,message:`Not found: ${o}`})}},Rw=async(e,t=gi)=>new Promise((n,r)=>{let o=s=>{let i=d=>{if(e.off("listening",l),d.code==="EADDRINUSE"&&s===t){e.removeListener("error",i),o(0);return}r(d)},l=()=>{e.off("error",i);let d=e.address();if(!d||typeof d=="string"){r(new Error("Unable to resolve address"));return}n(d.port)};e.once("error",i),e.once("listening",l),e.listen(s,"127.0.0.1")};o(t)}),Gb=async e=>{Mv(!1);let t=0,n={repoRoot:e.repoRoot},r=mw.createServer((l,d)=>{o(l,d).catch(m=>(logger.error(`[gui] ${l.method} ${l.url}: ${m instanceof Error?m.message:String(m)}`),d.headersSent?d.end():Le(d,500,{isError:!0,message:"Internal error"})))});async function o(l,d){let m=new URL(l.url??"/","http://127.0.0.1"),p=ab({method:l.method,origin:l.headers.origin,contentType:l.headers["content-type"]},t);if(p)return Le(d,p.status,{isError:!0,message:p.message});if(l.method==="GET"&&m.pathname===Ku)return Le(d,200,{app:qu,repoRoot:Sl(n.repoRoot),version:Mn,pid:process.pid});if(m.pathname==="/api/state")return Le(d,200,await Ht({repoRoot:n.repoRoot}));if(l.method==="POST"&&m.pathname==="/api/comments")try{let f=await Ub(l);if(!f.issueId||!f.body?.trim())return Le(d,400,{isError:!0,message:"Missing issueId or body"});let g=f.issueId,y=f.body;return await wl(d,async()=>{let x=await pi({repoRoot:n.repoRoot,issueId:g,body:y});return a(x)?Le(d,400,{isError:!0,message:x.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))})}catch(f){return Le(d,400,{isError:!0,message:f instanceof Error?f.message:"Unable to add comment"})}if(l.method==="POST"&&m.pathname==="/api/attachments")try{let f=await Ub(l,vw);if(!f.issueId||!f.dataBase64)return Le(d,400,{isError:!0,message:"Missing issueId or dataBase64"});let g=f.issueId,y=f.dataBase64,x=f.name??"";return await wl(d,async()=>{let b=await hu({repoRoot:n.repoRoot,issueId:g,name:x,dataBase64:y});return a(b)?Le(d,400,{isError:!0,message:b.message}):Le(d,200,{...await Ht({repoRoot:n.repoRoot}),attachment:b.value})})}catch(f){return Le(d,400,{isError:!0,message:f instanceof Error?f.message:"Unable to add attachment"})}if(l.method==="DELETE"&&m.pathname.startsWith("/api/attachments/")){let f=decodeURIComponent(m.pathname.replace("/api/attachments/",""));return f?wl(d,async()=>{let g=await yu({repoRoot:n.repoRoot,attachmentId:f});return a(g)?Le(d,400,{isError:!0,message:g.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))}):Le(d,400,{isError:!0,message:"Missing attachment id"})}if(l.method==="GET"&&m.pathname.startsWith("/media/")){let f=decodeURIComponent(m.pathname.replace("/media/","")),g=await vu({repoRoot:n.repoRoot,fileName:f});if(a(g))return Le(d,404,{isError:!0,message:g.message});try{let y=await Wb(g.value.filePath);return d.writeHead(200,{"content-type":bw[g.value.ext]??"application/octet-stream","cache-control":"public, max-age=31536000, immutable"}),d.end(y)}catch{return Le(d,404,{isError:!0,message:"Attachment blob not found"})}}if(l.method==="DELETE"&&m.pathname.startsWith("/api/comments/")){let f=decodeURIComponent(m.pathname.replace("/api/comments/",""));return f?wl(d,async()=>{let g=await fi({repoRoot:n.repoRoot,commentId:f});return a(g)?Le(d,400,{isError:!0,message:g.message}):Le(d,200,await Ht({repoRoot:n.repoRoot}))}):Le(d,400,{isError:!0,message:"Missing comment id"})}return m.pathname.startsWith("/board/")||m.pathname==="/log"?Hb("/",l,d):Hb(m.pathname,l,d)}try{t=await Rw(r)}catch(l){return c(l instanceof Error?`Unable to start GUI server: ${l.message}`:`Unable to start GUI server: ${String(l)}`)}let s=ib({project:n});$b(r,n,{onStateChanged:()=>s.queueSync(),onSyncSettingsChanged:()=>s.reschedule(),getPort:()=>t}),r.on("close",s.dispose);let i=r.address();return!i||typeof i=="string"?(r.close(),c("Unable to resolve GUI server address")):u("Started GUI server",{url:`http://epiq.localhost:${i.port}${e.boardId?`/board/${e.boardId}`:""}`,server:r})};var zb=async e=>{let t=lo({});if(a(t))return c(t.message);let n=ht();be(n)&&je(n.value);let r=await nb(gi);if(r&&r.repoRoot===Sl(e.repoRoot)){let i=`http://127.0.0.1:${gi}`;return console.log(`Epiq GUI already running for this project at ${Vb.cyan(i)}`),bc(i),u("Reused running GUI",{url:i})}let o=await Gb({...e,boardId:""});if(a(o))return o;let{url:s}=o.value;return console.log(`Epiq GUI running at ${Vb.cyan(s)}`),bc(s),u("Started GUI",{url:s})};import{Box as Xn}from"ink";import ke from"react";import{Box as nm,Text as Ei}from"ink";import ln,{useEffect as Cw,useMemo as Nw}from"react";import{ulid as Aw}from"ulid";var Kb=({text:e,match:t,color:n,highlightColor:r=h.secondary,dimColor:o=!1})=>{if(!t)return ln.createElement(Ei,{color:n,dimColor:o},e);let s=e.toLowerCase(),i=t.toLowerCase(),l=s.indexOf(i);return l===-1?ln.createElement(Ei,{color:n,dimColor:o},e):ln.createElement(Ei,{color:n,dimColor:o},e.slice(0,l),ln.createElement(Ei,{backgroundColor:r,bold:!0},e.slice(l,l+t.length)),e.slice(l+t.length))},qb=Aw(),Tw=e=>`${e}`,ww=e=>{let{pendingNavTarget:t}=yr();if(!t)return[];let{breadCrumb:n,contextNode:r,selectedNode:o}=t,s=new Set(Oe(C.NONE,{breadCrumb:n,contextNode:r,readOnly:v().readOnly,selectedNode:o}));return[...new Set(Object.values(C))].filter(i=>i!=="move").filter(i=>i.length>0).filter(i=>i!==C.PALETTE).map(i=>{let l=La(i),d=cl.find(m=>m.intent===l);return{command:i,description:d?.description??`[${i}] Run command`,isAvailable:s.has(i)}}).filter(i=>i.command.toLowerCase().startsWith(e)||e.length>=2&&i.description.toLowerCase().includes(e)).sort((i,l)=>i.isAvailable!==l.isAvailable?i.isAvailable?-1:1:i.command.localeCompare(l.command))},Mw=e=>Ne.text({id:qb,parentNodeId:e,rank:"000000",name:"Command Palette",readonly:!0,isVirtual:!0}),Pw=(e,t,n)=>Ne.text({id:Tw(e.command),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.command,disabled:!e.isAvailable,readonly:!0,isVirtual:!0}),rm=[],Lw=e=>{Yb();let t=N.createNode(Mw(v().rootNodeId));a(t)||!nr(t.value)||(rm=[t.value,...e.map((n,r)=>Pw(n,r,qb)).map(N.createNode).filter(be).map(({value:n})=>n).filter(nr)],U.navigate({contextNode:t.value,selectedIndex:0}))},Yb=()=>{let e=rm.map(t=>t.id);rm=[];for(let t of e)N.deleteNode(t)};function Xb({width:e,height:t}){let r=hf().value.trim().toLowerCase(),o=Nw(()=>ww(r),[r]);Cw(()=>(Lw(o),()=>{Yb()}),[o]);let s=v().selectedIndex;return ln.createElement(nm,{flexDirection:"column",width:e,height:t-2},ln.createElement(mt,{height:t-4,itemHeight:3,selectedIndex:s},o.map((i,l)=>{let d=l===s,m=i.isAvailable?h.accent:h.secondary2,p=i.isAvailable?"":"[unavailable] ";return ln.createElement(nm,{key:i.command,flexDirection:"column",paddingX:1,borderLeft:!1,borderBottom:!1,borderRight:!1,borderColor:h.secondary,borderStyle:"single"},ln.createElement(Ei,{color:m,dimColor:!i.isAvailable},d?"\u276F ":" ",ln.createElement(Kb,{text:fp(i.command),match:r,color:m,dimColor:!i.isAvailable})),ln.createElement(nm,{paddingLeft:2},ln.createElement(Kb,{text:p+i.description,match:r.length>=2?r:"",color:d&&i.isAvailable?h.primary:h.secondary2,dimColor:!i.isAvailable})))})))}import{Box as Kw}from"ink";import Ll from"react";import Ri from"chalk";import{Box as Si,Text as ex}from"ink";import oo,{useEffect as tx,useMemo as kw,useState as nx}from"react";var Qo=["\u2803","\u2806","\u2830","\u2818"],Jb=120,Qb=({isPalette:e,isPending:t,frame:n})=>{if(t){let r=(n%Qo.length+Qo.length)%Qo.length;return Qo[r]}return e?"?":":"},Zb=({infoMessage:e,isPending:t})=>t&&e.includes(fe)?"":e;var rx=Ri.hex(h.secondary),Dw=Ri.inverse,Bw=Ri.inverse.hex(h.secondary2),Ow={hint:"",hints:[],overlap:0,remainder:""},sx=({value:e,command:t})=>{if(!t)return null;let n=e.trimStart(),o=e.length-n.length;return e.slice(o,o+t.length)!==t?null:{start:o,end:o+t.length}},Fw=({command:e,modifier:t})=>{if(!t)return null;if(e==="tag"||e==="assign"){let n=qe(t);return{bg:r=>Ri.bgHex(n).black(r),bgCursor:r=>Ri.bgHex(n).inverse.black(r)}}return Sc(t)},_w=({value:e,command:t,modifier:n})=>{if(!t||!n)return null;let r=sx({value:e,command:t});if(!r)return null;let s=e.slice(r.end).match(/^\s*/)?.[0].length??0,i=r.end+s;return e.slice(i,i+n.length)!==n?null:{start:i,end:i+n.length}},ox=()=>({value:dt.value,cursorPosition:dt.cursorPosition,commandIsPending:dt.commandIsPending,autoCompletion:dt.commandMeta.autoCompletion??Ow,infoMessage:dt.commandMeta.infoMessage,validationStatus:dt.commandMeta.validity,command:dt.commandMeta.command,inputString:dt.commandMeta.inputString,modifier:dt.commandMeta.modifier}),$w=(e,t)=>e.value===t.value&&e.cursorPosition===t.cursorPosition&&e.commandIsPending===t.commandIsPending&&e.infoMessage===t.infoMessage&&e.autoCompletion.hint===t.autoCompletion.hint&&e.autoCompletion.overlap===t.autoCompletion.overlap&&e.autoCompletion.remainder===t.autoCompletion.remainder&&e.validationStatus===t.validationStatus&&e.command===t.command&&e.modifier===t.modifier&&e.inputString===t.inputString,ix=({width:e,mode:t})=>{let[n,r]=nx(ox());tx(()=>{let T=()=>{let P=ox();r(M=>$w(M,P)?M:P)},A=$c(T);return T(),()=>{A()}},[]);let{value:o,cursorPosition:s,infoMessage:i,commandIsPending:l,autoCompletion:d,command:m,modifier:p,validationStatus:f}=n,g=l&&f===bn.Invalid,y=Zb({infoMessage:i,isPending:l}),[x,b]=nx(0);tx(()=>{if(!l){b(0);return}let T=setInterval(()=>{b(A=>(A+1)%Qo.length)},Jb);return()=>{clearInterval(T)}},[l]);let R=Qb({isPalette:t===I.PALETTE,isPending:l,frame:x}),S=kw(()=>{let T=Math.max(0,Math.min(s,o.length)),A=sx({value:o,command:m}),P=_w({value:o,command:m,modifier:p}),M=m?Sc(m):null,O=Fw({command:m,modifier:p}),W=(it,ft)=>{let io=A&&ft>=A.start&&ft<A.end,ql=P&&ft>=P.start&&ft<P.end;return io&&M?M.fg(it):ql&&O?O.bg(it):it},X=(it,ft)=>{let io=A&&ft>=A.start&&ft<A.end,ql=P&&ft>=P.start&&ft<P.end;return io&&M?M.fgCursor(it):ql&&O?O.bgCursor(it):Dw(it)},Ee=o.slice(0,T),F=o[T]??" ",J=T<o.length?o.slice(T+1):"",Ke=Array.from(Ee).map((it,ft)=>W(it,ft)).join(""),Jn=X(F,T),os=Array.from(J).map((it,ft)=>W(it,T+1+ft)).join("");if(d.hint){let it=d.hint[d.overlap]??F;Jn=Bw(it),os=rx(d.remainder.slice(1)+J)}return Ke+Jn+os},[o,s,d,m,p]);return oo.createElement(Si,{flexDirection:"column",justifyContent:"flex-start"},oo.createElement(Si,{flexDirection:"column",paddingX:1,borderColor:h.secondary,borderStyle:"round",width:e},oo.createElement(Si,{height:1,flexWrap:"nowrap"},oo.createElement(Si,{flexShrink:0},oo.createElement(ex,{wrap:"truncate-start"},rx(R),S)),y&&oo.createElement(Si,{flexShrink:1,minWidth:0},oo.createElement(ex,{wrap:"truncate",color:g?h.red:h.secondary2},` ${y} `)))))};import{Box as Uw,Text as Ci}from"ink";import Zo from"react";var ax=" ",jw=({keys:e,label:t})=>e.length+1+t.length,Hw=(e,t)=>{let n=[],r=0;for(let o of e){let i=(n.length>0?ax.length:0)+jw(o);if(r+i>t-4)break;n.push(o),r+=i}return n},lx=({width:e,availableHints:t})=>{let n=Hw(t,e);return Zo.createElement(Uw,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1},n.length?Zo.createElement(Ci,{wrap:"truncate"},n.map(({keys:o,label:s},i)=>Zo.createElement(Ci,{key:`${o}-${s}`},i>0?ax:"",Zo.createElement(Ci,{color:h.accent},o),Zo.createElement(Ci,{color:h.secondary2}," ",s)))):Zo.createElement(Ci,{color:h.secondary2},"\xA0"))};import{Box as Ww,Text as Ml}from"ink";import Ni,{useEffect as Gw,useRef as es,useState as Vw}from"react";var zw=40,Pl=.3,om="\u2500",cx=1,dx=16,ux=({width:e})=>{let{replay:t}=oe(),n=t!==null,r=t?Math.min(1,Math.max(0,t.progress)):0,s=Math.max(4,e-6),i=s*cx,[l,d]=Vw(0),m=es(r);m.current=r;let p=es(0),f=es(0),g=es(0),y=es(0),x=es(0);if(Gw(()=>{if(!n){p.current=0,g.current=0,y.current=0,x.current=0,d(0);return}p.current=m.current,f.current=Date.now(),g.current=m.current;let A=setInterval(()=>{let P=Date.now(),M=m.current;if(M!==g.current){let F=M-g.current,J=P-f.current;if(F<0)y.current=0,x.current=0;else if(F>0&&J>0){let Ke=F/J;y.current=y.current===0?Ke:y.current*(1-Pl)+Ke*Pl,x.current=x.current===0?F:x.current*(1-Pl)+F*Pl}p.current=M,f.current=P,g.current=M}let O=P-f.current,W=Math.min(x.current,y.current*O),X=Math.min(1,p.current+W),Ee=Math.round(X*i);d(F=>F===Ee?F:Ee)},zw);return()=>clearInterval(A)},[n,i]),!t)return null;let b=A=>{let P=s>1?A/(s-1):0,M=Math.round(P*(dx-1))/(dx-1);return Gi(M)},R=Math.min(s,Math.floor(l/cx)),S=[];for(let A=0;A<R;A++){let P=b(A),M=S[S.length-1];M&&M.color===P?M.text+=om:S.push({text:om,color:P})}let T=om.repeat(Math.max(0,s-R));return Ni.createElement(Ww,{width:e,borderStyle:"round",borderColor:h.secondary,paddingX:1,columnGap:1},Ni.createElement(Ml,{color:h.secondary2},"\u25B6"),Ni.createElement(Ml,null,S.map((A,P)=>Ni.createElement(Ml,{key:P,color:A.color},A.text)),Ni.createElement(Ml,{color:h.secondary,dimColor:!0},T)))};var Ai=({width:e,mode:t,availableHints:n})=>{let{timeMode:r}=oe(),o=t===I.COMMAND_LINE||t===I.PALETTE;return Ll.createElement(Kw,null,o?Ll.createElement(ix,{width:e,mode:t}):r==="replay"?Ll.createElement(ux,{width:e}):Ll.createElement(lx,{width:e,mode:t,availableHints:n}))};import{Box as Ar,Text as ts}from"ink";import bt,{useEffect as qw,useMemo as Yw}from"react";import{ulid as mx}from"ulid";var Dl=mx(),Xw=()=>[...new Set([...v().availableActions].map(e=>e.description).filter(e=>e!==void 0))].map(ou).filter(e=>e!==null).sort(({keys:e},{keys:t})=>e.length===1&&t.length!==1?-1:e.length!==1&&t.length===1?1:e.localeCompare(t,void 0,{sensitivity:"base"})).map(({keys:e,label:t})=>({keys:e,action:t})),Jw=e=>Ne.text({id:Dl,parentNodeId:e,rank:"000000",name:"Help",isVirtual:!0,readonly:!0}),Qw=(e,t,n)=>Ne.text({id:mx(),parentNodeId:n,rank:String(t).padStart(6,"0"),name:e.keys,readonly:!0,isVirtual:!0}),kl=[],px=()=>{let e=kl.filter(n=>n.id!==Dl).map(n=>n.id),t=kl.filter(n=>n.id===Dl).map(n=>n.id);kl=[];for(let n of[...e,...t])N.deleteNode(n)},Zw=e=>{px();let t=N.createNode(Jw(v().rootNodeId));if(a(t)||!nr(t.value))return logger.error("Could not attach help nodes");kl=[t.value,...e.map((n,r)=>Qw(n,r,Dl)).map(N.createNode).filter(be).map(({value:n})=>n).filter(nr)],U.navigate({contextNode:t.value,selectedIndex:0})},fx=({width:e,height:t})=>{let n=Yw(()=>Xw(),[]);qw(()=>(Zw(n),()=>{px()}),[n]);let r=v().selectedIndex;return bt.createElement(Ar,{flexDirection:"column",marginTop:3,borderColor:h.secondary,borderStyle:"round",width:e,height:t-2},bt.createElement(Ar,{paddingX:1,justifyContent:"center"},bt.createElement(ts,{color:h.accent},"Help"),bt.createElement(ts,{dimColor:!0}," \u2014 navigate with arrows/hjkl, press q to close")),bt.createElement(Ar,{paddingX:1,marginTop:1},bt.createElement(Ar,{width:20,justifyContent:"flex-end"},bt.createElement(ts,{color:h.secondary},"Key(s)")),bt.createElement(Ar,{flexGrow:1,width:40,paddingLeft:2},bt.createElement(ts,{color:h.secondary},"Action"))),bt.createElement(mt,{height:t-7,itemHeight:1,selectedIndex:r},n.map(({keys:o,action:s},i)=>{let l=i===r;return bt.createElement(Ar,{paddingX:1,key:`${o}-${s}-${i}`,flexDirection:"row"},bt.createElement(Ar,{width:20,justifyContent:"flex-end"},bt.createElement(ts,{color:h.accent},o)),bt.createElement(Ar,{flexGrow:1,width:40,paddingLeft:2},bt.createElement(ts,{color:l?h.primary:h.secondary2},s)))})))};import{Box as ns,Text as xt}from"ink";import we,{useEffect as eM,useState as sm}from"react";var Bl=({index:e,email:t,note:n,noteColor:r})=>we.createElement(ns,null,we.createElement(xt,{color:h.accent},e===void 0?" ":` ${e}.`),we.createElement(xt,null," ",t),n&&we.createElement(xt,{color:r??h.secondary2},` ${n}`)),gx=({height:e})=>{let[t,n]=sm([]),[r,o]=sm([]),[s,i]=sm(null),{userName:l,gitEmail:d,gitName:m,userId:p}=V();return eM(()=>{let f=!0;return(async()=>{let y=xe(),x=me(process.cwd());if(a(y)||a(x)||!p)return;let b=y.value.emailLinks,R=fn(b,p);n(R.map(P=>({email:P,others:ys(b,P).filter(M=>M!==p).map(M=>y.value.contributors[M]?.name??M)})));let S=Ue(x.value),T=await wn({repoRoot:x.value,stateBranch:a(S)?void 0:S.value,names:[l,m],links:b});if(!f)return;if(a(T)){i(T.message);return}let A=br(T.value);Eo(A.map(P=>P.email)),o(A)})(),()=>{f=!1}},[p,l,m,d]),we.createElement(ns,{height:e-4,flexDirection:"column",paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},we.createElement(ns,null,we.createElement(xt,{color:h.accent,bold:!0},l??"Not configured"),we.createElement(xt,{color:h.secondary2}," on this board")),s&&we.createElement(xt,{color:h.red},s),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},"CLAIMED"),t.length===0?we.createElement(Bl,{email:"Nothing claimed \u2014 your commits show the name git signed them with.",note:""}):t.map(f=>we.createElement(Bl,{key:f.email,email:f.email,note:f.others.length>0?`CONTESTED: also ${f.others.join(", ")}, resolves to nobody`:f.email===d?"your git identity here":void 0,noteColor:f.others.length>0?h.yellow:void 0}))),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},"UNCLAIMED IN THIS HISTORY"),r.length===0?we.createElement(Bl,{email:"Nothing left to claim here."}):r.map(f=>we.createElement(Bl,{key:f.email,email:f.email,note:`${f.commits} commit${f.commits===1?"":"s"} as ${f.names.join(", ")||"unknown"}`}))),we.createElement(ns,{flexDirection:"column"},we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},"[enter]")," writes a claim for the first into the command line, to confirm or change."),we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},":config emails")," claims by address,",we.createElement(xt,{color:h.accent}," :config emails-unclaim "),"gives one back."),we.createElement(xt,{color:h.secondary2},we.createElement(xt,{color:h.accent},"[esc]")," to close")))};import tM from"chalk";import{Box as so,Text as rt}from"ink";import Me from"react";var nM=8,rM=()=>{let e=$n({exclude:process.cwd()});return a(e)?[]:e.value.slice(0,nM)},hx=({width:e,height:t})=>{let n=rM();return Me.createElement(so,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},Me.createElement(rt,{color:h.accent,bold:!0},"Initialize project"),Me.createElement(rt,null,`This folder is not an ${tM.hex(h.accent)("epiq")} project yet.`),Me.createElement(rt,{color:h.primary},"To start tracking issues here, we need to initialize a new",Me.createElement(rt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json "),"file in this repository."),Me.createElement(so,{marginTop:1,flexDirection:"column"},Me.createElement(so,null,Me.createElement(rt,{color:h.accent}," "),Me.createElement(rt,{color:h.primary},"Type "),Me.createElement(rt,{backgroundColor:h.secondary}," :init "))),Me.createElement(so,{marginTop:1},Me.createElement(rt,{color:h.secondary2},"This will create, commit and push "),Me.createElement(rt,{color:h.primary,backgroundColor:h.secondary}," .epiq/project.json ")),n.length>0&&Me.createElement(so,{marginTop:1,flexDirection:"column"},Me.createElement(rt,{color:h.accent,bold:!0},"Or open a recent project"),n.map((r,o)=>Me.createElement(so,{key:r.projectId},Me.createElement(rt,{color:h.accent},` ${o+1} `),Me.createElement(rt,{color:h.primary},Io(r.root)),Me.createElement(rt,{color:h.secondary2},` ${r.root}`))),Me.createElement(so,{marginTop:1},Me.createElement(rt,{color:h.accent}," "),Me.createElement(rt,{color:h.primary},"Type "),Me.createElement(rt,{backgroundColor:h.secondary}," :open 1 "),Me.createElement(rt,{color:h.secondary2}," or "),Me.createElement(rt,{backgroundColor:h.secondary}," :open <path> "))))};import{Box as Fl,Text as Dt}from"ink";import $e from"react";import{Box as Ol,Text as Yn}from"ink";import kt,{useEffect as oM,useState as yx}from"react";var vx=()=>{let[e,t]=yx(null),[n,r]=yx(null);return oM(()=>{let o=!0;return(async()=>{let i=xe(),l=me(process.cwd());if(a(i)||a(l))return;let d=Ue(l.value),{userName:m,gitName:p}=V(),f=await wn({repoRoot:l.value,stateBranch:a(d)?void 0:d.value,names:[m,p],links:i.value.emailLinks});if(!o)return;if(a(f)){r(f.message);return}let g=br(f.value);Eo(g.map(y=>y.email)),t(g)})(),()=>{o=!1}},[]),n?kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.red},n)):e===null?null:e.length===0?kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.secondary2},"No unclaimed addresses in this history \u2014 type",kt.createElement(Yn,{color:h.accent}," :config emails none "),"to move on.")):kt.createElement(Ol,{flexDirection:"column",marginTop:1},e.map(o=>kt.createElement(Yn,{key:o.email},kt.createElement(Yn,{color:h.accent}," \xB7 "),kt.createElement(Yn,null,o.email),kt.createElement(Yn,{color:h.secondary2},` ${o.commits} commit${o.commits===1?"":"s"} as ${o.names.join(", ")||"unknown"}`))),kt.createElement(Ol,{marginTop:1},kt.createElement(Yn,{color:h.secondary2},"Claim yours by address, or",kt.createElement(Yn,{color:h.accent}," none "),"to skip.")))};var sM=({isDone:e,command:t,value:n,verb:r="Type",hint:o})=>$e.createElement(Fl,null,$e.createElement(Dt,{color:h.accent,dimColor:e},e?" \u2714 ":" "),$e.createElement(Dt,{dimColor:e},r," "),$e.createElement(Dt,{backgroundColor:h.secondary,dimColor:e}," "+t+" "),n!==void 0&&$e.createElement($e.Fragment,null,$e.createElement(Dt,{dimColor:e}," "),$e.createElement(Dt,{color:h.secondary,dimColor:e},"<"+n+">")),o),iM=(e,t)=>e.length===0?void 0:_n(e.join(", "),Math.max(12,t-34)),aM=e=>{if(typeof e=="string")return e;if(typeof e=="boolean")return e?"on":"off"};function im({width:e,height:t}){let{isSetPreferredEditor:n,isSetUserName:r,userName:o,preferredEditor:s,autoSync:i,isSetAutoSync:l,isSetEmails:d,claimedEmails:m,emailSetupDeclined:p}=Un(),f=[{key:"username",done:r,command:":config username",value:o,message:"First, choose your username."},{key:"editor",done:n,command:":config editor",value:s,message:"Nice. Now pick your editor."},{key:"autosync",done:l,command:":config autosync",value:i,message:"Almost there. Configure auto sync."},{key:"emails",done:d,command:":config emails",value:p?"declined":iM(m,e),message:"Last one. Claim the git addresses whose commits are yours, so the board calls them by your name."}],g=f.findIndex(x=>!x.done),y=g===-1?void 0:f[g];return $e.createElement(Fl,{height:t-4,flexDirection:"column",width:e,paddingTop:1,paddingLeft:2,borderStyle:"round",borderColor:h.secondary,rowGap:1},$e.createElement(Dt,{color:h.accent,bold:!0},"Welcome! \u{1F539}"),$e.createElement(Dt,null,"Let's get you started - it's a breeze."),$e.createElement(Dt,{color:h.secondary2},"Remember - you can always search available commands by typing:",$e.createElement(Dt,{color:h.accent}," ? ")),y&&$e.createElement(Dt,{color:h.secondary2},y.message),$e.createElement(Fl,{flexDirection:"column"},f.map((x,b)=>{if(!(g===-1||b<=g))return null;let S=b===g,T=S&&g===0;return $e.createElement(Fl,{key:x.key,flexDirection:"column",marginBottom:1},$e.createElement(sM,{isDone:x.done,command:T?":config us":x.command,value:x.done?aM(x.value):void 0,verb:S&&!T?"Waiting:":"Type",hint:T?$e.createElement(Dt,{color:h.secondary2}," then ",$e.createElement(Dt,{color:h.accent},"tab")," to auto-complete ",$e.createElement(Dt,{backgroundColor:h.secondary},` ${x.command.split(" ").pop()} `)):void 0}),x.key==="emails"&&!x.done&&$e.createElement(vx,null))})))}import Hl from"chalk";import{Box as wi,Text as rs}from"ink";import Ze from"react";import{Box as _l,Text as bx}from"ink";import Tr from"react";import lM from"chalk";var cM=e=>(N.getTag(e)?.name??"").length+3,dM=e=>{let t=N.getContributor(e);return(t?t.name:"").length+3},xx=({width:e})=>{let{viewMode:t}=V(),n=oe(),{breadCrumb:r,contextNode:o,selectedIndex:s,renderedChildrenIndex:i}=n,l=i[o.id]?.[s],d=Nt(l?.id??o.id,"TICKET"),m=be(d)?d.value:void 0,p=(m?.props.tags??[]).filter(M=>N.getTag(M)),f=m?.props.assignees??[],g=m?.parentNodeId?!cu(o.id,m.parentNodeId)&&t==="dense":!1,y=r.map((M,O)=>{let W=O===r.length-1,X=Ie(M.id),Ee=W?X?.[s]?.title:void 0;return`${O?" / ":""}${M.title??""}${Ee?` \u25B8 ${Ee}`:""}`}).join(""),x=m?N.getCommentsByIssue(m.id):[],b=x.length?String(x.length).length+11:0,R=g?p.reduce((M,O)=>M+cM(O),0)+f.reduce((M,O)=>M+dM(O),0)+b:0,S=l?.id!=null&&!(t==="wide"&&_(l)),T=Math.max(0,e-R),A=y.substring(0,T)+(S?lM.hex(h.secondary2).dim(` ${H(l.id)}`):""),P=g?[...p.map(M=>Tr.createElement(_l,{key:`tag-${M}`,paddingLeft:1},Tr.createElement(Lo,{id:M}))),...f.map(M=>Tr.createElement(_l,{key:`assignee-${M}`,paddingLeft:1},Tr.createElement(ur,{id:M}))),x.length?Tr.createElement(_l,{key:"comments",paddingLeft:1},Tr.createElement(bx,{color:h.accent},"[",x.length," comment",x.length===1?"":"s","]")):null]:[];return Tr.createElement(_l,{overflow:"hidden",justifyContent:"flex-start",alignItems:"flex-start"},Tr.createElement(bx,{color:h.secondary2},A),P)};import{Box as uM,Text as Ix}from"ink";import $l from"react";var mM=({filters:e})=>$l.createElement(uM,{columnGap:1},$l.createElement(Ix,{color:"red"},"APPLIED FILTERS:"),e.map(({value:t,target:n,operator:r})=>$l.createElement(Ix,{backgroundColor:"black",color:"white"},` ${n}${r}"${t}" `))),Ex=$l.memo(mM);import{Box as pM,Text as Ul}from"ink";import Ti from"react";function Sx(){let{eventLog:e,unappliedEvents:t}=oe(),n=e.at(-1)?.id,r=yo(n??""),o=be(r)?Fa(r.value):"INVALID DATE";return Ti.createElement(pM,{paddingLeft:1},Ti.createElement(Ul,{backgroundColor:h.accent,color:h.secondary}," Readonly "),Ti.createElement(Ul,{color:h.accent}," "+t.length+" edits ago at "+o+"."),Ti.createElement(Ul,{color:h.accent}," Resume with "),Ti.createElement(Ul,{backgroundColor:h.accent,color:h.secondary}," ",":peek now"," "))}import{Box as fM,Text as am}from"ink";import jl from"react";function Rx(){let{replay:e}=oe();if(!e)return null;let{appliedCount:t,totalCount:n,currentTime:r}=e;return jl.createElement(fM,{paddingRight:2,columnGap:1,justifyContent:"flex-end"},jl.createElement(am,{backgroundColor:h.accent,color:h.secondary}," \u25B6 REPLAY "),jl.createElement(am,{color:h.secondary2},Fa(new Date(r))),jl.createElement(am,{color:h.accent},`${t}/${n} edits`))}import lm from"chalk";import{Box as gM,Text as Cx}from"ink";import cm,{useEffect as hM,useState as yM}from"react";var vM=["#4c567a","#9d7cd8","#7aa2f7","#7dcfff","#9d7cd8"],bM=150,Nx=12,xM=.36,Ax=e=>{let t=e.replace("#","");return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}},IM=({r:e,g:t,b:n})=>{let r=o=>Math.round(Math.max(0,Math.min(255,o))).toString(16).padStart(2,"0");return`#${r(e)}${r(t)}${r(n)}`},EM=(e,t,n)=>{let r=Ax(e),o=Ax(t);return IM({r:r.r+(o.r-r.r)*n,g:r.g+(o.g-r.g)*n,b:r.b+(o.b-r.b)*n})},SM=(e,t)=>{if(e.length===1)return e[0];let n=t*(e.length-1),r=Math.floor(n),o=n-r,s=e[r],i=e[Math.min(r+1,e.length-1)];return EM(s,i,o)};function Tx({syncStatus:e,autoSync:t}){let[n,r]=yM(0);hM(()=>{if(e.status!=="syncing"){r(0);return}let l=0,d=setInterval(()=>{l+=1;let m=(Math.sin(l*xM)+1)/2,p=Math.round(m*(Nx-1));r(f=>f===p?f:p)},bM);return()=>clearInterval(d)},[e.status]);let o={synced:" ",failed:"---",offline:"off",syncing:"...",pending:"idle"},i={synced:h.secondary2,failed:h.yellow,offline:h.secondary2,pending:h.secondary2,syncing:SM(vM,n/(Nx-1))??""}[e.status];return cm.createElement(gM,null,cm.createElement(Cx,null,lm.hex(h.secondary2).dim(t?"Sync (auto): ":"Sync: ")),cm.createElement(Cx,null,lm.hex(i)("\u25CF")+lm.hex(h.secondary2).dim(` ${o[e.status].padEnd(4)} `)))}import kx from"chalk";import{Text as Dx}from"ink";import Bx,{useEffect as AM,useState as TM}from"react";import dm from"chalk";var RM="https://registry.npmjs.org/epiq/latest",um=null,wx=0,CM=1e3*60*60*24,Mx=e=>e.replace(/^v/,""),NM=(e,t)=>{let n=Mx(e).split(".").map(Number),r=Mx(t).split(".").map(Number);for(let o=0;o<Math.max(n.length,r.length);o++){let s=n[o]??0,i=r[o]??0;if(s>i)return 1;if(s<i)return-1}return 0},Px=async e=>{if(process.env.IS_CI==="true")return{current:"1.2.3",latest:"1.2.3",updateAvailable:!1};if(um&&Date.now()-wx<CM)return um;try{let t=await fetch(RM);if(!t.ok)throw new Error(`Failed to fetch latest version: ${t.status}`);let r=(await t.json()).version??null,o={current:e,latest:r,updateAvailable:r?NM(r,e)>0:!1};return um=o,wx=Date.now(),o}catch{return{current:e,latest:null,updateAvailable:!1}}},Lx=(e,t)=>{let n=e.split("."),r=t.split("."),o=r.findIndex((s,i)=>s!=n[i]);return r.map((s,i)=>i>=o?dm.hex(h.accent).dim(s):dm.hex(h.secondary).dim(s)).join(dm.hex(h.secondary2).dim("."))};function Ox(){let[e,t]=TM({current:Mn,latest:null,updateAvailable:!1});return AM(()=>{let n=!0;return Px(Mn).then(r=>{n&&t(r)}),()=>{n=!1}},[]),!e.updateAvailable||!e.latest?Bx.createElement(Dx,{dimColor:!0,color:h.secondary2},Mn+" "):Bx.createElement(Dx,null,kx.hex(h.secondary2).dim(Mn),kx.hex(h.accent).dim(" \u2197 "),Lx(Mn,e.latest))}function Mi({filters:e,hideBreadCrumb:t=!1}){let{timeMode:n,syncStatus:r,mode:o,replay:s}=oe(),{userName:i,preferredEditor:l,autoSync:d}=V(),m=64,p=process.stdout.columns-m-8,f=t||n==="replay",g=s?Fn(s.currentLabel,Math.max(0,p)):"";return Ze.createElement(wi,{justifyContent:"space-between",flexDirection:"row","max-width":process.stdout.columns-40,overflow:"hidden"},n==="replay"?Ze.createElement(wi,{paddingLeft:1},Ze.createElement(rs,{color:h.secondary2},g)):f?Ze.createElement(rs,null," "):o===I.PALETTE?Ze.createElement(wi,null,Ze.createElement(rs,{color:h.accent},"Command Palette"),Ze.createElement(rs,{dimColor:!0,color:h.secondary2}," ","- search, select and press enter")):Ze.createElement(wi,{paddingLeft:1},e.length>0?Ze.createElement(Ex,{filters:e}):Ze.createElement(xx,{width:p})),n==="live"?Ze.createElement(wi,{columnGap:1,paddingRight:2,"max-width":m,overflow:"hidden",justifyContent:"flex-end"},Ze.createElement(Tx,{autoSync:!!d,syncStatus:r}),Ze.createElement(rs,null,Hl.hex(h.secondary2).dim("Mode: ")+Hl.hex(h.secondary2).dim(o.padEnd(8," "))," "),Ze.createElement(Fx,{icon:"@",value:i}),Ze.createElement(Fx,{icon:"\u276F",value:l}),Ze.createElement(Ox,null)):"",n==="peek"?Ze.createElement(Sx,null):"",n==="replay"?Ze.createElement(Rx,null):"")}function Fx({icon:e,value:t}){return Ze.createElement(rs,null,Hl.dim(e)+Hl.hex(h.accent)(` ${t??"-"} `))}import{Box as wM,Text as MM}from"ink";import Pi from"react";import{Box as Wl,Text as mm}from"ink";import wr from"react";function pm(){let e=oe(),t=e.nodes[e.rootNodeId],o=process.stdout.rows-1-3,s=process.stdout.columns||120,i=t?.id?de(t?.id):[];return wr.createElement(Wl,{flexDirection:"column",height:o,padding:1,borderStyle:"round",borderColor:h.secondary,width:s},wr.createElement(Wl,{padding:1,paddingTop:0,paddingBottom:0},wr.createElement(mm,null,"Select a board:")),wr.createElement(Wl,{padding:1,flexDirection:"column"},i.map((l,d)=>{let m=e.contextNode.context==="WORKSPACE"&&e.selectedIndex===d,f=de(l.id).flatMap(({id:g})=>Ie(g)).length;return wr.createElement(Wl,{key:l.id??d},wr.createElement(mm,{color:m?h.accent:h.secondary2},wr.createElement(St,{isSelected:m})),wr.createElement(mm,{color:m?h.accent:h.secondary2},l.title," (",f," issues)",l.readonly?" \u{1F512}":""))})))}var PM=({contextNode:e,selectedIndex:t,breadCrumb:n,mode:r,viewMode:o,height:s,width:i})=>{let{renderedChildrenIndex:l}=oe(),d=n.find(({context:g})=>g==="BOARD"),f=s-1-3;return Pi.createElement(wM,{flexDirection:"row"},e.context==="WORKSPACE"?Pi.createElement(pm,null):d?Pi.createElement(Xa,{height:f,width:i,swimlanes:(l[d.id]??[]).filter(g=>g!==void 0&&gn(g)),contextNode:e,selectedIndex:t,breadCrumb:n,viewMode:o,mode:r}):Pi.createElement(MM,null))},_x=Pi.memo(PM);import{useEffect as LM}from"react";var kM=e=>{LM(()=>{if(!e)return;let t,n=!1,r=()=>{if(n)return;let{autoSyncIntervalMs:o,userName:s,preferredEditor:i}=V();i&&s&&o&&(t=setTimeout(()=>{if(n)return;let{readOnly:l,mode:d}=v();d==="default"&&!l&&Pa(),r()},o))};return r(),()=>{n=!0,t&&clearTimeout(t)}},[e])},$x=({autoSync:e})=>(kM(e),null);function fm({width:e,height:t}){let n=oe(),{autoSync:r,viewMode:o}=Zm(),s=n.filters;if(n.mode===I.HELP)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(fx,{width:e,height:t}));if(n.mode===I.IDENTITY)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(gx,{width:e,height:t}));if(n.mode===I.PALETTE)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{filters:s}),ke.createElement(Xb,{width:e,height:t-2}),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:n.availableHints}));let{isSetupDone:i}=Un(),l=!i,d=i&&!n.hasProjectDefinition;if(l)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{hideBreadCrumb:!0,filters:s}),ke.createElement(im,{height:t,width:e})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:[]}));if(d)return ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{hideBreadCrumb:!0,filters:s}),ke.createElement(hx,{height:t,width:e})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:[]}));let m=yt(n.breadCrumb??[],"BOARD");if(be(m)){let p=m.value.id,f=de(p).length,g=3,y=Math.floor(e/g),x=Math.floor(e/Math.max(f,1));e=Math.min(x,y)*Math.max(f,g)}return ke.createElement(Xn,{flexDirection:"column"},ke.createElement($x,{autoSync:r}),ke.createElement(Xn,{flexDirection:"column"},ke.createElement(Mi,{filters:s}),ke.createElement(_x,{width:e,height:t,contextNode:n.contextNode,selectedIndex:n.selectedIndex,breadCrumb:n.breadCrumb,viewMode:o??"dense",mode:n.mode})),ke.createElement(Ai,{width:e,mode:n.mode,availableHints:n.availableHints}))}import DM from"readline";var Gl,Vl,Ln,BM=new Set([E.MoveCursorLeft,E.EraseInputWord,E.MoveCursorLeftOfWord,E.MoveCursorRight,E.MoveCursorRightOfWord,E.NavToPreviousContainer,E.NavToNextContainer,E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.SetViewDense,E.SetViewWide,E.Confirm,E.Exit,E.Yank,E.InitCommandLine,E.InitCommandPalette,E.ExitCommandLine,E.CaptureInput,E.EraseInput,E.EraseInputWord,E.HideHelp,E.ViewHelp,E.SetViewDense,E.SetViewWide,E.GetLastCommandFromHistory,E.GetNextCommandFromHistory,E.AutoCompleteCommand]),OM=new Set([E.NavPreviousItem,E.NavNextItem,E.NavPreviousItemJump,E.NavNextItemJump,E.NavToPreviousContainer,E.NavToNextContainer,E.Confirm,E.Exit,E.InitCommandPalette,E.InitMove,E.MoveNextItem,E.MovePreviousItem,E.MoveNextItemJump,E.MovePreviousItemJump,E.MoveToNextContainer,E.MoveToPreviousContainer,E.Delete,E.AddItem,E.EditTitle,E.EditDescription,E.ConfirmMove,E.Edit,E.ViewHelp,E.Yank]),Ux=async e=>{if(e.ctrl&&e.name==="c")return U.exit();let{actionIndex:t,mode:n,readOnly:r,timeMode:o}=v(),s=yf(e,n);if(!s||r&&!BM.has(s)||o==="replay"&&n===I.DEFAULT&&OM.has(s))return;let i=t[n]?.[s];if(i?.action)try{await i.action(i,e)}catch(l){logger.error(l)}},FM=()=>async function(t,n){n.name!=="escape"&&(Ln&&(clearTimeout(Ln),Ln=void 0),await Ux(n))},_M=()=>async function(t){if(t.length===1&&t[0]===27){Ln&&clearTimeout(Ln),Ln=setTimeout(()=>{Ux({name:"escape",ctrl:!1,meta:!1,shift:!1,sequence:"\x1B"}),Ln=void 0},25);return}Ln&&(clearTimeout(Ln),Ln=void 0)};function jx(){Gl&&process.stdin.removeListener("keypress",Gl),Vl&&process.stdin.removeListener("data",Vl),Gl=FM(),Vl=_M(),DM.emitKeypressEvents(process.stdin),process.stdin.isTTY&&process.stdin.setRawMode(!0),process.stdin.on("data",Vl),process.stdin.on("keypress",Gl)}async function Hx(){try{let e=lo({});if(a(e))return tn(0,e.message);let t=ht();be(t)&&je(t.value);let n=me(process.cwd());je({gitEmail:await yl(process.cwd()),gitName:await Rr(process.cwd())});let r=be(n)?await el(n.value):Ay();if(a(r))return r;let o=gm();return a(o)?tn(6,o.message):(jx(),be(n)&&tl(n.value),u("Booted Epiq",void 0))}catch(e){return tn(0,wo(e))}}dy();var HM=`${cn.bold("Epiq CLI")}
|
|
95
105
|
|
|
96
|
-
${
|
|
97
|
-
${
|
|
106
|
+
${cn.dim("Boot in directory:")}
|
|
107
|
+
${cn.cyan("$ epiq")}
|
|
98
108
|
|
|
99
|
-
${
|
|
100
|
-
${
|
|
109
|
+
${cn.dim("Launch GUI:")}
|
|
110
|
+
${cn.cyan("$ epiq gui")}
|
|
101
111
|
|
|
102
|
-
${
|
|
103
|
-
${
|
|
104
|
-
`,
|
|
105
|
-
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await
|
|
106
|
-
${e.message}`)),process.exitCode=1)}export{
|
|
112
|
+
${cn.dim("Act as somebody other than the configured user:")}
|
|
113
|
+
${cn.cyan("$ epiq --as claude")}
|
|
114
|
+
`,hm=UM(HM,{importMeta:import.meta,version:Mn,flags:{init:{type:"boolean",default:!1},as:{type:"string"}}}),zl=hm.input[0];zl&&zl!=="gui"&&(console.error(cn.red(`Unknown command: ${zl}`)),process.exit(1));if(hm.flags.as!==void 0){let e=Jl(hm.flags.as,"--as");a(e)&&(console.error(cn.red(e.message)),process.exit(1))}var Wx=process.stdout.columns||120,Gx=process.stdout.rows||20,Kl=null,WM=e=>{try{return Kl?(Kl.rerender(e),u("Rerendered app",void 0)):(Kl=$M(e),u("Rendered app",void 0))}catch(t){return c(`Unable to render app: ${wo(t)}`)}},gm=()=>WM(jM.createElement(fm,{width:Wx,height:Gx}));process.stdout.on("resize",()=>{if(Wx=process.stdout.columns||120,Gx=process.stdout.rows||20,!Kl)return;let e=gm();a(e)&&logger.info(`[boot:resize] ${e.message}`)});if(zl==="gui"){let e=await zb({repoRoot:process.cwd()});a(e)&&(console.error(cn.red(`Failed to start Epiq GUI:
|
|
115
|
+
${e.message}`)),process.exitCode=1)}else{console.clear();let e=await Hx();a(e)&&(logger.info(e.message),console.error(cn.red(`Failed to boot Epiq:
|
|
116
|
+
${e.message}`)),process.exitCode=1)}export{gm as renderApp};
|