diffstalkerd 0.4.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/README.md +188 -0
- package/bin/diffstalkerd +5 -0
- package/dist/index.js +52 -0
- package/package.json +67 -0
package/README.md
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# @diffstalker/daemon
|
|
2
|
+
|
|
3
|
+
`diffstalkerd` is the diffstalker daemon: a Node http server that exposes
|
|
4
|
+
`@diffstalker/core` (git status, diffs, staging, live change events) behind a
|
|
5
|
+
REST API + Server-Sent Events. It lets non-terminal clients (editors, web UIs,
|
|
6
|
+
scripts) talk to the same git state engine the TUI uses.
|
|
7
|
+
|
|
8
|
+
The package is private and bin-only: it is not published and not importable.
|
|
9
|
+
The only entry point is the `diffstalkerd` executable.
|
|
10
|
+
|
|
11
|
+
Its primary client is the `diffstalker` CLI (`packages/cli`), which spawns or
|
|
12
|
+
attaches to this daemon over a unix socket and consumes it through the typed
|
|
13
|
+
`@diffstalker/client`. A web client is planned against the same API.
|
|
14
|
+
|
|
15
|
+
## Running
|
|
16
|
+
|
|
17
|
+
From the repo root:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
bun packages/daemon/src/index.ts # development (source)
|
|
21
|
+
bun run build # compile all packages
|
|
22
|
+
node packages/daemon/dist/index.js # run the compiled daemon
|
|
23
|
+
packages/daemon/bin/diffstalkerd # same, via the bin wrapper
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Options:
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
--socket PATH Bind a unix socket at PATH
|
|
30
|
+
(default: $XDG_RUNTIME_DIR/diffstalker/diffstalkerd.sock)
|
|
31
|
+
--port N Bind TCP port N instead of a unix socket
|
|
32
|
+
--host H Host to bind with --port (default: 127.0.0.1)
|
|
33
|
+
--follow-file PATH Hook file to follow (created when missing)
|
|
34
|
+
(default: ~/.cache/diffstalker/target)
|
|
35
|
+
--no-follow Disable follow mode (no hook-file watcher)
|
|
36
|
+
--help, -h Show this help
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
`--socket` and `--port` are mutually exclusive; so are `--follow-file` and
|
|
40
|
+
`--no-follow`.
|
|
41
|
+
|
|
42
|
+
Without `--socket`/`--port`, the daemon binds a unix socket at
|
|
43
|
+
`$XDG_RUNTIME_DIR/diffstalker/diffstalkerd.sock`. The directory is created
|
|
44
|
+
with mode `0700` and the socket is chmod'd to `0600` (owner only). If
|
|
45
|
+
`XDG_RUNTIME_DIR` is unset, the daemon refuses to start — there is
|
|
46
|
+
deliberately no `/tmp` fallback. Pass `--socket PATH` explicitly instead.
|
|
47
|
+
|
|
48
|
+
If a live daemon already answers on the socket path, startup fails; a stale
|
|
49
|
+
socket file (nothing listening) is removed and reused.
|
|
50
|
+
|
|
51
|
+
There is no authentication yet. Keep the daemon on a unix socket or
|
|
52
|
+
localhost; a bearer-token check is planned before it may bind further.
|
|
53
|
+
|
|
54
|
+
## Environment
|
|
55
|
+
|
|
56
|
+
- `XDG_RUNTIME_DIR` — base for the default socket path. Required when no
|
|
57
|
+
`--socket`/`--port` is given.
|
|
58
|
+
- `XDG_CACHE_HOME` — base for the default follow hook file
|
|
59
|
+
(`$XDG_CACHE_HOME/diffstalker/target`, falling back to `~/.cache`).
|
|
60
|
+
- `LISTEN_FDS` / `LISTEN_PID` — systemd socket activation. When systemd hands
|
|
61
|
+
the process a pre-bound socket (`LISTEN_PID` matches and `LISTEN_FDS >= 1`),
|
|
62
|
+
the daemon listens on the inherited fd (fd 3) and does not create, chmod, or
|
|
63
|
+
unlink any socket file. Explicit `--socket`/`--port` takes precedence.
|
|
64
|
+
|
|
65
|
+
## API
|
|
66
|
+
|
|
67
|
+
Current surface. All bodies are JSON; errors are non-2xx with `{"error": "..."}`.
|
|
68
|
+
|
|
69
|
+
Naming rule: mutations are `POST /repos/:id/<verb-kebab>` (`switch-branch`,
|
|
70
|
+
`soft-reset`, `stage-hunk`); nouns with GET/PUT (`/branches`,
|
|
71
|
+
`/compare/base`) are resources.
|
|
72
|
+
|
|
73
|
+
Every mutation responds with the unified envelope `{state, result?}`:
|
|
74
|
+
`state` is the refreshed shared state (same shape as `GET /status`) and
|
|
75
|
+
`result` is the optional human-readable outcome text of remote/branch/undo
|
|
76
|
+
operations. Status codes: 400 for invalid input (missing fields,
|
|
77
|
+
flag-shaped refs, resets past the root), 404 for unknown repo ids / files
|
|
78
|
+
not in status, 409 when the repo state refuses the operation (conflicts,
|
|
79
|
+
rejected pushes, an operation already in progress, nothing to abort), 500
|
|
80
|
+
for real failures.
|
|
81
|
+
|
|
82
|
+
Ref-like fields (`name`, `hash`, `branch`) must not start with `-`; such
|
|
83
|
+
values are rejected with a 400 so they can never be parsed as git flags.
|
|
84
|
+
|
|
85
|
+
### Reads
|
|
86
|
+
|
|
87
|
+
| Method | Path | What |
|
|
88
|
+
| ------ | -------------------------- | ------------------------------------------------ |
|
|
89
|
+
| GET | `/health` | `{ok, ready}` |
|
|
90
|
+
| GET | `/repos` | List open repos (`id`, `path`, `branch`) |
|
|
91
|
+
| POST | `/repos` | Open a repo: `{"path": "/abs/path"}` → `{id, path}` (201 created, 200 already open) |
|
|
92
|
+
| DELETE | `/repos/:id` | Close a repo (refcounted per open) |
|
|
93
|
+
| GET | `/repos/:id/worktrees` | Registered worktrees (`path`, `branch`, `head`, `isBare`): main worktree, linked worktrees, and the bare entry in a bare-worktree layout |
|
|
94
|
+
| GET | `/repos/:id/status` | Shared state: status, hunk counts, stash list, in-progress operation, error |
|
|
95
|
+
| GET | `/repos/:id/diff?path=&staged=` | Diff; whole tree without `path`, staged side with `staged=true` |
|
|
96
|
+
| GET | `/repos/:id/history?count=` | Commit history (`CommitInfo[]`, default 100, ISO dates) |
|
|
97
|
+
| GET | `/repos/:id/commits/:hash/diff` | Diff introduced by one commit (404 on unknown hash; merge and `--allow-empty` commits are 200 with an empty diff, matching the CLI) |
|
|
98
|
+
| GET | `/repos/:id/head-message` | HEAD commit message for amend prefill: `{message}` (`""` when the repo has no commits) |
|
|
99
|
+
| GET | `/repos/:id/branches` | Local branches (`name`, `current`, `tracking`) |
|
|
100
|
+
| GET | `/repos/:id/base-branches` | Candidate compare bases (remote branches in recent history) |
|
|
101
|
+
| GET | `/repos/:id/compare/base` | Effective compare base: `{base}` (persisted choice or discovered default, null when none) |
|
|
102
|
+
| PUT | `/repos/:id/compare/base` | Persist the compare base: `{"branch": "origin/main"}` → `{base}`; the ref is validated first (400 on an unknown ref, nothing persisted) |
|
|
103
|
+
| GET | `/repos/:id/compare?base=&uncommitted=` | Base-vs-HEAD `CompareDiff` (three-dot); base defaults to the effective base — a stale persisted base falls back to the discovered default, 422 when nothing usable resolves; an explicit unknown `base` is a 400; a base with no common history is a 422; `uncommitted=true` merges working-tree changes |
|
|
104
|
+
| GET | `/repos/:id/tree?dir=&hidden=&ignored=` | One directory level (`name`, `path`, `type`), gitignored/hidden filtered by default (`hidden=true` / `ignored=true` include them, mirroring the TUI toggles), files annotated with `gitStatus` + `staged`, changed dirs with `hasChanges` (400 outside the repo root or on a file, 404 unknown dir) |
|
|
105
|
+
| GET | `/repos/:id/file?path=` | File content for display with flags: `{content, binary, truncated, tooLarge, size, totalLines}` — binary/oversized come back with empty content and the flag set, never prose; 400 for anything that is not a regular file (directory, FIFO, device) or resolves outside the repo root |
|
|
106
|
+
| GET | `/repos/:id/files` | All tracked + untracked (not ignored) paths: the fuzzy-finder source |
|
|
107
|
+
| GET | `/repos/:id/events` | SSE: `snapshot` on connect, then `state-change` events from the file watcher |
|
|
108
|
+
| GET | `/events` | Daemon-scope SSE: `snapshot` (open repos) on connect, then `repo-opened` / `repo-closed` / `follow-change` |
|
|
109
|
+
| GET | `/follow` | Follow state: `{targetFile, enabled, followedRepoId, followedPath}` |
|
|
110
|
+
|
|
111
|
+
### Mutations (all respond `{state, result?}`)
|
|
112
|
+
|
|
113
|
+
| Method | Path | Body / behavior |
|
|
114
|
+
| ------ | -------------------------- | ------------------------------------------------ |
|
|
115
|
+
| POST | `/repos/:id/stage` | `{"path": "file.txt"}` — stage one file (404 when not in status) |
|
|
116
|
+
| POST | `/repos/:id/unstage` | `{"path": "file.txt"}` — unstage one file |
|
|
117
|
+
| POST | `/repos/:id/stage-all` | Stage everything |
|
|
118
|
+
| POST | `/repos/:id/unstage-all` | Unstage everything |
|
|
119
|
+
| POST | `/repos/:id/discard` | `{"path": "file.txt"}` — discard an unstaged change / delete an untracked file; 409 on a staged file (unstage first) |
|
|
120
|
+
| POST | `/repos/:id/stage-hunk` | `{"patch": "<unified diff>"}` — apply one hunk to the index; a stale patch is a 409 |
|
|
121
|
+
| POST | `/repos/:id/unstage-hunk` | `{"patch": "<unified diff>"}` — reverse-apply one hunk |
|
|
122
|
+
| POST | `/repos/:id/commit` | `{"message": "...", "amend"?: bool}` — 400 on an empty message or nothing staged; a commit that creates no commit is never a 200 |
|
|
123
|
+
| POST | `/repos/:id/push` | Push the current branch; rejected push is a 409 |
|
|
124
|
+
| POST | `/repos/:id/fetch` | Fetch from the remote |
|
|
125
|
+
| POST | `/repos/:id/pull` | Pull with rebase; a conflict is a 409 and leaves the repo mid-rebase — see `/abort` |
|
|
126
|
+
| POST | `/repos/:id/stash` | `{"message"?: "..."}` — stash the working tree |
|
|
127
|
+
| POST | `/repos/:id/stash-pop` | `{"index"?: 0}` — pop a stash entry (see `stashList` in the state); a conflicting pop is a 409 and keeps the entry |
|
|
128
|
+
| POST | `/repos/:id/switch-branch` | `{"name": "main"}` — switch branches |
|
|
129
|
+
| POST | `/repos/:id/create-branch` | `{"name": "feat-x"}` — create and switch |
|
|
130
|
+
| POST | `/repos/:id/soft-reset` | `{"count"?: 1}` — move HEAD back, keep changes staged; past the root commit is a 400 |
|
|
131
|
+
| POST | `/repos/:id/cherry-pick` | `{"hash": "abc123"}` — apply a commit; a conflict is a 409 |
|
|
132
|
+
| POST | `/repos/:id/revert` | `{"hash": "abc123"}` — revert a commit with a new commit |
|
|
133
|
+
| POST | `/repos/:id/abort` | Abort whatever multi-step operation the repo is stopped in (rebase, cherry-pick, revert, merge); 409 when nothing is in progress |
|
|
134
|
+
| POST | `/repos/:id/rebase-continue` | Continue a stopped rebase after conflicts are resolved and staged; 409 when no rebase is in progress |
|
|
135
|
+
|
|
136
|
+
A conflicted `pull`/`cherry-pick` leaves the repo stopped mid-operation;
|
|
137
|
+
`GET /status` reports it in `operationInProgress` and `POST /abort`
|
|
138
|
+
returns the repo to its pre-operation state — no shell required.
|
|
139
|
+
|
|
140
|
+
History, compare, and explorer data are stateless, pulled on demand: the
|
|
141
|
+
daemon never holds a client's selection, loaded history, or tree expansion.
|
|
142
|
+
A commit or branch switch fires the working-tree `state-change` event (the
|
|
143
|
+
git watcher covers HEAD/refs), which is the client's signal to re-pull.
|
|
144
|
+
|
|
145
|
+
Note on `/file`'s `truncated` flag: it strictly means the content was cut
|
|
146
|
+
at the display line limit. A merely large file that fits within the limit
|
|
147
|
+
is served whole with `truncated: false` (the old TUI code conflated the
|
|
148
|
+
two: a >100KB file used to be flagged truncated regardless).
|
|
149
|
+
|
|
150
|
+
Repo ids are stable hashes of the worktree root, so a cached id still
|
|
151
|
+
addresses the same repo after a daemon restart.
|
|
152
|
+
|
|
153
|
+
## Follow mode
|
|
154
|
+
|
|
155
|
+
The daemon owns the truth, clients decide policy. It watches ONE hook file
|
|
156
|
+
(`--follow-file`, default `~/.cache/diffstalker/target`; created when
|
|
157
|
+
missing); external tools append a repo or file path to it to signal "focus
|
|
158
|
+
this". On change the daemon resolves the path to a worktree root (same
|
|
159
|
+
normalization as `POST /repos`, including bare containers), auto-opens the
|
|
160
|
+
repo, and broadcasts `follow-change {repoId, path, rawContent}` on
|
|
161
|
+
`GET /events` — `path` is the resolved hook-file content (it may point at a
|
|
162
|
+
file inside the repo), `rawContent` the literal line. Content that does not
|
|
163
|
+
resolve to a git repository broadcasts nothing and leaves the follow state
|
|
164
|
+
untouched.
|
|
165
|
+
|
|
166
|
+
The daemon holds one internal "follow" reference on the followed repo so it
|
|
167
|
+
stays open with no clients attached; switching targets releases the previous
|
|
168
|
+
follow-ref (closing that repo when nothing else holds it — clients see
|
|
169
|
+
`repo-closed`). Whether a client reacts to `follow-change` is entirely
|
|
170
|
+
client-side; the daemon keeps no per-client follow state. A daemon restart
|
|
171
|
+
re-follows whatever the hook file last pointed at. `GET /follow` reports the
|
|
172
|
+
current state; with `--no-follow` it reports `{enabled: false}` and no
|
|
173
|
+
watcher exists.
|
|
174
|
+
|
|
175
|
+
Examples over the default unix socket:
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
SOCK="$XDG_RUNTIME_DIR/diffstalker/diffstalkerd.sock"
|
|
179
|
+
|
|
180
|
+
curl --unix-socket "$SOCK" http://localhost/health
|
|
181
|
+
curl --unix-socket "$SOCK" -X POST -d '{"path": "/home/me/repo"}' http://localhost/repos
|
|
182
|
+
curl --unix-socket "$SOCK" http://localhost/repos/<id>/status
|
|
183
|
+
curl --unix-socket "$SOCK" 'http://localhost/repos/<id>/diff?path=file.txt'
|
|
184
|
+
curl --unix-socket "$SOCK" -X POST -d '{"path": "file.txt"}' http://localhost/repos/<id>/stage
|
|
185
|
+
curl --unix-socket "$SOCK" -N http://localhost/repos/<id>/events
|
|
186
|
+
curl --unix-socket "$SOCK" -N http://localhost/events
|
|
187
|
+
curl --unix-socket "$SOCK" http://localhost/follow
|
|
188
|
+
```
|
package/bin/diffstalkerd
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import*as x2 from"node:fs";import*as l$ from"node:path";import*as n$ from"node:os";import*as $$ from"node:path";var o$="diffstalker";function Z$(){return $$.join(process.env.XDG_CACHE_HOME||$$.join(n$.homedir(),".cache"),o$)}function i$(){return process.env.XDG_RUNTIME_DIR?$$.join(process.env.XDG_RUNTIME_DIR,o$):null}import*as _2 from"node:http";import*as h from"node:fs";import*as O2 from"node:net";function s$($){let Z={};for(let[K,Q]of $)Z[K]=Q;return Z}function L2($){if(!$)return null;return{staged:s$($.staged),unstaged:s$($.unstaged)}}function y($){return{status:$.status,hunkCounts:L2($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress}}function s($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[K,Q]of $)Z[String(K)]=s(Q);return Z}if(Array.isArray($))return $.map(s);if($!==null&&typeof $==="object"){let Z={};for(let[K,Q]of Object.entries($))Z[K]=s(Q);return Z}return $}var G2=1048576;class B extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function C($,Z,K){let Q=JSON.stringify(s(K));$.writeHead(Z,{"content-type":"application/json"}),$.end(Q)}function j2($,Z){if($.segments.length!==Z.length)return null;let K={};for(let Q=0;Q<$.segments.length;Q++){let Y=$.segments[Q];if(Y.startsWith(":"))try{K[Y.slice(1)]=decodeURIComponent(Z[Q])}catch{throw new B(400,`Malformed percent-encoding in path: ${Z[Q]}`)}else if(Y!==Z[Q])return null}return K}async function C2($){if($.method!=="POST"&&$.method!=="PUT"&&$.method!=="PATCH")return;let Z=[],K=0;for await(let Y of $){let V=Y;if(K+=V.length,K>G2)throw new B(413,"Request body too large");Z.push(V)}let Q=Buffer.concat(Z).toString("utf-8");if(!Q.trim())return;try{return JSON.parse(Q)}catch{throw new B(400,"Invalid JSON body")}}class j${routes=[];get($,Z){this.add("GET",$,Z)}post($,Z){this.add("POST",$,Z)}put($,Z){this.add("PUT",$,Z)}delete($,Z){this.add("DELETE",$,Z)}add($,Z,K){this.routes.push({method:$,segments:Z.split("/").filter(Boolean),handler:K})}async handle($,Z){try{let K=new URL($.url??"/","http://localhost"),Q=K.pathname.split("/").filter(Boolean),Y=$.method??"GET",V=null;for(let z of this.routes){if(z.method!==Y)continue;let J=j2(z,Q);if(J){V={handler:z.handler,params:J};break}}if(!V)throw new B(404,`Unknown route: ${Y} ${K.pathname}`);let X=await C2($);await V.handler({req:$,res:Z,params:V.params,query:K.searchParams,body:X})}catch(K){if(Z.headersSent){Z.end();return}let Q=K instanceof B?K.status:500,Y=K instanceof Error?K.message:String(K);C(Z,Q,{error:Y})}}}import{createHash as P2}from"node:crypto";class a${queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue($){return new Promise((Z,K)=>{this.queue.push({execute:$,resolve:Z,reject:K}),this.processNext()})}enqueueMutation($){return this.pendingMutations++,this.enqueue($).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh($){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await $()}).catch(()=>{this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let $=this.queue.shift();try{let Z=await $.execute();$.resolve(Z)}catch(Z){$.reject(Z instanceof Error?Z:Error(String(Z)))}finally{this.isProcessing=!1,this.processNext()}}}var C$=new Map;function t$($){let Z=C$.get($);if(!Z)Z=new a$,C$.set($,Z);return Z}function r$($){C$.delete($)}import*as H from"node:path";import*as c from"node:fs";import{execFileSync as R2}from"node:child_process";import{watch as P0}from"chokidar";import{EventEmitter as w2}from"node:events";import m0 from"ignore";function e$($){process.stderr.write(`[diffstalker warn] ${$}
|
|
2
|
+
`)}import{simpleGit as M2}from"simple-git";function l(){return{...process.env,LC_ALL:"C",LANG:"C"}}var H2={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0};function G($){return M2({baseDir:$,unsafe:H2}).env(l())}import{execFileSync as K0}from"node:child_process";import*as n from"node:fs";import*as I$ from"node:path";async function K$($,Z){if(Z.length===0)return new Set;let K=G($),Q=new Set,Y=100;for(let V=0;V<Z.length;V+=Y){let X=Z.slice(V,V+Y);try{let J=(await K.raw(["check-ignore","--",...X])).trim().split(`
|
|
3
|
+
`).filter((U)=>U.length>0);for(let U of J)Q.add(U)}catch{}}return Q}function $0($){let Z=new Map;for(let K of $.trim().split(`
|
|
4
|
+
`)){if(!K)continue;let Q=K.split("\t");if(Q.length>=3){let Y=Q[0]==="-"?0:parseInt(Q[0],10),V=Q[1]==="-"?0:parseInt(Q[1],10),X=Q.slice(2).join("\t");Z.set(X,{insertions:Y,deletions:V})}}return Z}async function T2($,Z){try{let K=I$.join($,Z);if(!(await n.promises.stat(K)).isFile())return 0;return(await n.promises.readFile(K,"utf-8")).split(`
|
|
5
|
+
`).filter((V)=>V.length>0).length}catch{return 0}}function Z0($){switch($){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";default:return"modified"}}async function M$($){let Z=G($);if(!await Z.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let Q=await Z.status(),Y=[],V=new Set,X=Q.files.filter((O)=>O.working_dir==="?").map((O)=>O.path),z=await K$($,X);for(let O of Q.files){if(O.index==="!"||O.working_dir==="!"||z.has(O.path))continue;let j=`${O.path}-${O.index!==" "&&O.index!=="?"}`;if(V.has(j))continue;if(V.add(j),O.index&&O.index!==" "&&O.index!=="?")Y.push({path:O.path,status:Z0(O.index),staged:!0});if(O.working_dir&&O.working_dir!==" ")Y.push({path:O.path,status:O.working_dir==="?"?"untracked":Z0(O.working_dir),staged:!1})}let[J,U]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),W=$0(J),A=$0(U);for(let O of Y){let j=O.staged?W.get(O.path):A.get(O.path);if(j)O.insertions=j.insertions,O.deletions=j.deletions}let N=Y.filter((O)=>O.status==="untracked");if(N.length>0){let O=await Promise.all(N.map((j)=>T2($,j.path)));for(let j=0;j<N.length;j++)N[j].insertions=O[j],N[j].deletions=0}return{files:Y,branch:{current:Q.current||"HEAD",tracking:Q.tracking||void 0,ahead:Q.ahead,behind:Q.behind},isRepo:!0}}async function Q0($,Z){await G($).add(["--",Z])}async function Y0($,Z){await G($).reset(["HEAD","--",Z])}async function V0($){await G($).add("-A")}async function X0($){await G($).reset(["HEAD"])}async function z0($,Z){await G($).checkout(["--",Z])}async function U0($,Z){await G($).clean("f",["--",Z])}async function W0($,Z,K=!1){if(!(await G($).commit(Z,void 0,K?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function J0($){let Z=G($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function _0($,Z){K0("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:l()})}function O0($,Z){K0("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:l()})}async function A0($){let Q=(await G($).push()).pushed;if(Q.length===0)return"Everything up-to-date";return Q.map((Y)=>`${Y.local} → ${Y.remote}`).join(", ")}async function B0($){return await G($).fetch(),"Fetch complete"}async function x0($){let K=await G($).pull(["--rebase"]);if(K.summary.changes===0&&K.summary.insertions===0&&K.summary.deletions===0)return"Already up-to-date";return`${K.summary.changes} file(s) changed`}async function N0($,Z=50){let K=G($);try{return(await K.log({n:Z})).all.map((Y)=>({hash:Y.hash,shortHash:Y.hash.slice(0,7),message:Y.message.split(`
|
|
6
|
+
`)[0],author:Y.author_name,date:new Date(Y.date),refs:Y.refs||""}))}catch{return[]}}async function H$($){let Z=G($);try{return(await Z.stashList()).all.map((Q,Y)=>({index:Y,message:Q.message}))}catch{return[]}}async function L0($,Z){let K=G($),Q=["push"];if(Z)Q.push("-m",Z);return await K.stash(Q),"Stashed"}async function G0($,Z=0){let K=G($);await K.stash(["pop",`stash@{${Z}}`]);let Q=(await K.raw(["diff","--name-only","--diff-filter=U"])).trim();if(Q)throw Error(`Stash pop hit conflicts in: ${Q.split(`
|
|
7
|
+
`).join(", ")}`);return"Stash popped"}async function Q$($){let K=await G($).branchLocal();return K.all.map((Q)=>({name:Q,current:Q===K.current,tracking:K.branches[Q]?.label||void 0}))}async function j0($,Z){return await G($).raw(["switch","--",Z]),`Switched to ${Z}`}async function C0($,Z){return await G($).raw(["switch","-c",Z]),`Created ${Z}`}async function I0($,Z=1){return await G($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function M0($,Z){return await G($).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function H0($,Z){return await G($).raw(["revert","--no-edit","--end-of-options",Z]),"Reverted"}async function P($){let Z=G($),K;try{K=(await Z.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let Q=(Y)=>n.existsSync(I$.join(K,Y));if(Q("rebase-merge")||Q("rebase-apply"))return"rebase";if(Q("CHERRY_PICK_HEAD"))return"cherry-pick";if(Q("REVERT_HEAD"))return"revert";if(Q("MERGE_HEAD"))return"merge";return null}async function T0($){let Z=await P($);if(!Z)throw Error("No operation in progress to abort");return await G($).raw([Z,"--abort"]),`Aborted ${Z}`}async function D0($){return await G($).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function F0($){return(await G($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((Q)=>Q.length>0)}import*as R0 from"node:fs";import*as a from"node:path";import*as R from"node:fs";import*as g from"node:path";function T$(){return g.join(Z$(),"base-branches.json")}function D2(){let $=g.dirname(T$());if(!R.existsSync($))R.mkdirSync($,{recursive:!0})}function q0(){try{let $=T$();if(R.existsSync($))return JSON.parse(R.readFileSync($,"utf-8"))}catch{}return{}}function F2($){D2(),R.writeFileSync(T$(),JSON.stringify($,null,2)+`
|
|
8
|
+
`)}function Y$($){let Z=q0(),K=g.resolve($);return Z[K]}function E0($,Z){let K=q0(),Q=g.resolve($);K[Q]=Z,F2(K)}function S0($){let Z=$.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(Z)return{oldStart:parseInt(Z[1],10),newStart:parseInt(Z[2],10)};return null}function o($){let Z=$.split(`
|
|
9
|
+
`);if(Z.length>1&&Z[Z.length-1]==="")Z.pop();let K=[],Q=0,Y=0;for(let V of Z)if(V.startsWith("diff --git")||V.startsWith("index ")||V.startsWith("---")||V.startsWith("+++")||V.startsWith("new file")||V.startsWith("deleted file")||V.startsWith("Binary files")||V.startsWith("similarity index")||V.startsWith("rename from")||V.startsWith("rename to"))K.push({type:"header",content:V});else if(V.startsWith("@@")){let X=S0(V);if(X)Q=X.oldStart,Y=X.newStart;K.push({type:"hunk",content:V})}else if(V.startsWith("+"))K.push({type:"addition",content:V,newLineNum:Y++});else if(V.startsWith("-"))K.push({type:"deletion",content:V,oldLineNum:Q++});else K.push({type:"context",content:V,oldLineNum:Q++,newLineNum:Y++});return K}function V$($){let Z=new Map;if(!$)return Z;let K=null;for(let Q of $.split(`
|
|
10
|
+
`))if(Q.startsWith("diff --git")){let Y=Q.match(/^diff --git a\/.+ b\/(.+)$/);if(Y){if(K=Y[1],!Z.has(K))Z.set(K,0)}}else if(Q.startsWith("@@")&&K)Z.set(K,(Z.get(K)??0)+1);return Z}class X$ extends Error{constructor($){super(`No common history with ${$}`);this.name="NoCommonHistoryError"}}async function i($,Z,K=!1){let Q=G($);try{let Y=[];if(K)Y.push("--cached");if(Z)Y.push("--",Z);let V=await Q.diff(Y),X=o(V);return{raw:V,lines:X}}catch{return{raw:"",lines:[]}}}async function w0($,Z){try{let K=a.resolve($),Q=a.resolve(K,Z);if(Q!==K&&!Q.startsWith(K+a.sep))return{raw:"",lines:[]};let Y=R0.readFileSync(Q,"utf-8"),V=[{type:"header",content:`diff --git a/${Z} b/${Z}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${Z}`}],X=Y.split(`
|
|
11
|
+
`);V.push({type:"hunk",content:`@@ -0,0 +1,${X.length} @@`});let z=1;for(let U of X)V.push({type:"addition",content:"+"+U,newLineNum:z++});return{raw:V.map((U)=>U.content).join(`
|
|
12
|
+
`),lines:V}}catch{return{raw:"",lines:[]}}}async function D$($){let Z=G($),K=new Set,Q=[];try{let Y=await Z.raw(["log","--oneline","--decorate=short","--all","-n","200"]),V=/\(([^)]+)\)/g;for(let X of Y.split(`
|
|
13
|
+
`)){let z=V.exec(X);if(z){let J=z[1].split(",").map((U)=>U.trim());for(let U of J){if(U.startsWith("HEAD")||U.startsWith("tag:")||!U.includes("/"))continue;let W=U.replace(/^.*-> /,"");if(W.includes("/")&&!K.has(W))K.add(W),Q.push(W)}}V.lastIndex=0}if(Q.length>0)Q.sort((X,z)=>{let J=X.split("/").slice(1).join("/"),U=z.split("/").slice(1).join("/"),W=J==="main"||J==="master",A=U==="main"||U==="master";if(W&&!A)return-1;if(!W&&A)return 1;if(W&&A){let N=X.startsWith("origin/"),O=z.startsWith("origin/");if(N&&!O)return 1;if(!N&&O)return-1}return 0})}catch{}return[...new Set(Q)]}async function F$($){return(await D$($))[0]??null}async function q$($){return Y$($)??await F$($)}async function m($,Z){let K=G($);try{return await K.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}async function E$($,Z){let K=G($),Y=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Y)throw new X$(Z);let V=await K.raw(["diff","--numstat",`${Y}...HEAD`]),X=await K.raw(["diff","--name-status",`${Y}...HEAD`]),z=await K.raw(["diff",`${Y}...HEAD`]),J=V.trim().split(`
|
|
14
|
+
`).filter((_)=>_),U=new Map;for(let _ of J){let x=_.split("\t");if(x.length>=3){let I=x[0]==="-"?0:parseInt(x[0],10),D=x[1]==="-"?0:parseInt(x[1],10),M=x.slice(2).join("\t");U.set(M,{additions:I,deletions:D})}}let W=X.trim().split(`
|
|
15
|
+
`).filter((_)=>_),A=new Map;for(let _ of W){let x=_.split("\t");if(x.length>=2){let I=x[0][0],D=x[x.length-1],M;switch(I){case"A":M="added";break;case"D":M="deleted";break;case"R":M="renamed";break;default:M="modified"}A.set(D,M)}}let N=[],O=z.split(/(?=^diff --git )/m).filter((_)=>_.trim());for(let _ of O){let x=_.match(/^diff --git a\/.+ b\/(.+)$/m);if(!x)continue;let I=x[1],D=o(_),M=U.get(I)||{additions:0,deletions:0},k=A.get(I)||"modified";N.push({path:I,status:k,additions:M.additions,deletions:M.deletions,diff:{raw:_,lines:D}})}let j=0,E=0;for(let _ of N)j+=_.additions,E+=_.deletions;let r=(await K.status()).files.length,e=(await K.log({from:Y,to:"HEAD"})).all.map((_)=>({hash:_.hash,shortHash:_.hash.slice(0,7),message:_.message.split(`
|
|
16
|
+
`)[0],author:_.author_name,date:new Date(_.date),refs:_.refs||""}));return N.sort((_,x)=>_.path.localeCompare(x.path)),{baseBranch:Z,stats:{filesChanged:N.length,additions:j,deletions:E},files:N,commits:e,uncommittedCount:r}}async function v0($,Z){let K=G($);try{let Q=await K.raw(["show","--format=","--end-of-options",Z]),Y=o(Q);return{raw:Q,lines:Y}}catch{return{raw:"",lines:[]}}}async function b0($,Z){let K=G($),Q=await E$($,Z),Y=await K.diff(["--cached","--numstat"]),V=await K.diff(["--numstat"]),X=await K.diff(["--cached"]),z=await K.diff([]),J=new Map;for(let _ of Y.trim().split(`
|
|
17
|
+
`).filter((x)=>x)){let x=_.split("\t");if(x.length>=3){let I=x[0]==="-"?0:parseInt(x[0],10),D=x[1]==="-"?0:parseInt(x[1],10),M=x.slice(2).join("\t");J.set(M,{additions:I,deletions:D,staged:!0,unstaged:!1})}}for(let _ of V.trim().split(`
|
|
18
|
+
`).filter((x)=>x)){let x=_.split("\t");if(x.length>=3){let I=x[0]==="-"?0:parseInt(x[0],10),D=x[1]==="-"?0:parseInt(x[1],10),M=x.slice(2).join("\t"),k=J.get(M);if(k)k.additions+=I,k.deletions+=D,k.unstaged=!0;else J.set(M,{additions:I,deletions:D,staged:!1,unstaged:!0})}}let U=await K.status(),W=new Map;for(let _ of U.files)if(_.index==="A"||_.working_dir==="?")W.set(_.path,"added");else if(_.index==="D"||_.working_dir==="D")W.set(_.path,"deleted");else if(_.index==="R")W.set(_.path,"renamed");else W.set(_.path,"modified");let A=[],O=(X+z).split(/(?=^diff --git )/m).filter((_)=>_.trim()),j=new Set;for(let _ of O){let x=_.match(/^diff --git a\/.+ b\/(.+)$/m);if(!x)continue;let I=x[1];if(j.has(I))continue;j.add(I);let D=o(_),M=J.get(I)||{additions:0,deletions:0},k=W.get(I)||"modified";A.push({path:I,status:k,additions:M.additions,deletions:M.deletions,diff:{raw:_,lines:D},isUncommitted:!0})}let E=new Set(Q.files.map((_)=>_.path)),b=[];for(let _ of Q.files){let x=A.find((I)=>I.path===_.path);if(x)b.push(_),b.push(x);else b.push(_)}for(let _ of A)if(!E.has(_.path))b.push(_);let r=0,G$=0,e=new Set;for(let _ of b)e.add(_.path),r+=_.additions,G$+=_.deletions;return b.sort((_,x)=>_.path.localeCompare(x.path)),{baseBranch:Q.baseBranch,stats:{filesChanged:e.size,additions:r,deletions:G$},files:b,commits:Q.commits,uncommittedCount:Q.uncommittedCount}}import*as k0 from"node:fs";import*as y0 from"node:path";var q2=/^diff --git a\/.+ b\/(.+)$/;function E2($){let Z=5381;for(let K of $){for(let Q=0;Q<K.length;Q++)Z=(Z<<5)+Z+K.charCodeAt(Q)|0;Z=(Z<<5)+Z+10|0}return(Z>>>0).toString(36)}function S2($){let Z=[],K="",Q=null,Y=()=>{if(Q&&K)Z.push({file:K,key:`${K}\x00${E2(Q.body)}`,headerLine:Q.headerLine});Q=null};for(let V of $.lines)if(V.type==="header"){Y();let X=V.content.match(q2);if(X)K=X[1]}else if(V.type==="hunk")Y(),Q={headerLine:V,body:[]};else if(Q&&(V.type==="addition"||V.type==="deletion"))Q.body.push(V.content);return Y(),Z}class S${repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let K of S2($)){let Q=this.stamps.get(K.key);if(Q===void 0){let Y=Z.get(K.file);if(Y===void 0)Y=this.mtimeOf(K.file),Z.set(K.file,Y);Q=Y,this.stamps.set(K.key,Q)}K.headerLine.editedAt=Q}}prune($){for(let Z of this.stamps.keys()){let K=Z.slice(0,Z.indexOf("\x00"));if(!$.has(K))this.stamps.delete(Z)}}mtimeOf($){try{return k0.statSync(y0.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}class R$ extends w2{repoPath;queue;hunkTimes;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;_state={status:null,isLoading:!1,error:null,hunkCounts:null,stashList:[],operationInProgress:null};constructor($,Z){super();this.repoPath=$,this.queue=Z,this.hunkTimes=new S$($)}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("state-change",this._state)}setError($){this.updateState({error:$})}clearError(){if(this._state.error!==null)this.updateState({error:null})}stampDiff($){this.hunkTimes.stamp($)}loadGitignores(){let $=new Map,Z=m0();Z.add(".git");let K=H.join(this.repoPath,".gitignore");if(c.existsSync(K))Z.add(c.readFileSync(K,"utf-8"));let Q=H.join(this.repoPath,".git","info","exclude");if(c.existsSync(Q))Z.add(c.readFileSync(Q,"utf-8"));$.set("",Z);try{let Y=R2("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:l()});for(let V of Y.split("\x00")){if(!V||V===".gitignore")continue;if(!V.endsWith(".gitignore"))continue;let X=H.dirname(V),z=H.join(this.repoPath,V);try{let J=c.readFileSync(z,"utf-8"),U=m0();U.add(J),$.set(X,U)}catch(J){e$(`Failed to read ${z}: ${J instanceof Error?J.message:J}`)}}}catch{}return $}startWatching(){let $=H.join(this.repoPath,".git");if(!c.existsSync($))return;let Z=H.join($,"index"),K=H.join($,"HEAD"),Q=H.join($,"refs"),Y=H.join(this.repoPath,".gitignore");this.gitWatcher=P0([Z,K,Q,Y],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=P0(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(X)=>{let z=H.relative(this.repoPath,X);if(!z)return!1;let J=z.split("/");for(let U=0;U<J.length;U++){let W=U===0?"":J.slice(0,U).join("/"),A=this.ignorers.get(W);if(A){let N=U===0?z:J.slice(U).join("/");if(A.ignores(N))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let V=()=>this.scheduleRefresh();this.gitWatcher.on("change",(X)=>{if(X===Y)this.ignorers=this.loadGitignores();V()}),this.gitWatcher.on("add",V),this.gitWatcher.on("unlink",V),this.gitWatcher.on("error",(X)=>{let z=X instanceof Error?X.message:String(X);this.setError(`Git watcher error: ${z}`)}),this.workingDirWatcher.on("change",V),this.workingDirWatcher.on("add",V),this.workingDirWatcher.on("unlink",V),this.workingDirWatcher.on("error",(X)=>{let z=X instanceof Error?X.message:String(X);this.setError(`Working dir watcher error: ${z}`)})}dispose(){this.gitWatcher?.close(),this.workingDirWatcher?.close()}scheduleRefresh(){this.queue.scheduleRefresh(async()=>{await this.doRefresh()})}scheduleStatusRefresh(){this.queue.scheduleRefresh(async()=>{try{let $=await M$(this.repoPath);if(!$.isRepo){this.updateState({status:$,isLoading:!1,error:"Not a git repository"});return}this.updateState({status:$,isLoading:!1})}catch($){this.updateState({isLoading:!1,error:$ instanceof Error?$.message:"Unknown error"})}})}async refresh(){await this.queue.enqueue(()=>this.doRefresh())}async doRefresh(){this.updateState({isLoading:!0,error:null});try{let $=await M$(this.repoPath);if(!$.isRepo){this.updateState({status:$,isLoading:!1,error:"Not a git repository"});return}let[Z,K,Q,Y]=await Promise.all([i(this.repoPath,void 0,!1),i(this.repoPath,void 0,!0),H$(this.repoPath),P(this.repoPath)]),V={unstaged:V$(Z.raw),staged:V$(K.raw)};this.hunkTimes.stamp(Z),this.hunkTimes.stamp(K),this.hunkTimes.prune(new Set($.files.map((X)=>X.path))),this.updateState({status:$,hunkCounts:V,stashList:Q,operationInProgress:Y,isLoading:!1})}catch($){this.updateState({isLoading:!1,error:$ instanceof Error?$.message:"Unknown error"})}}async stage($){try{await this.queue.enqueueMutation(()=>Q0(this.repoPath,$.path)),this.scheduleStatusRefresh()}catch(Z){await this.refresh(),this.updateState({error:`Failed to stage ${$.path}: ${Z instanceof Error?Z.message:String(Z)}`})}}async unstage($){try{await this.queue.enqueueMutation(()=>Y0(this.repoPath,$.path)),this.scheduleStatusRefresh()}catch(Z){await this.refresh(),this.updateState({error:`Failed to unstage ${$.path}: ${Z instanceof Error?Z.message:String(Z)}`})}}async stageHunk($){try{await this.queue.enqueueMutation(async()=>_0(this.repoPath,$)),this.scheduleRefresh()}catch(Z){await this.refresh(),this.updateState({error:`Failed to stage hunk: ${Z instanceof Error?Z.message:String(Z)}`})}}async unstageHunk($){try{await this.queue.enqueueMutation(async()=>O0(this.repoPath,$)),this.scheduleRefresh()}catch(Z){await this.refresh(),this.updateState({error:`Failed to unstage hunk: ${Z instanceof Error?Z.message:String(Z)}`})}}async discard($){if($.staged)return;let Z=$.status==="untracked"?()=>U0(this.repoPath,$.path):()=>z0(this.repoPath,$.path);try{await this.queue.enqueueMutation(Z),await this.refresh()}catch(K){this.updateState({error:`Failed to discard ${$.path}: ${K instanceof Error?K.message:String(K)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>V0(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>X0(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to unstage all: ${$ instanceof Error?$.message:String($)}`})}}async commit($,Z=!1){try{await this.queue.enqueue(()=>W0(this.repoPath,$,Z)),await this.refresh()}catch(K){this.updateState({error:`Failed to commit: ${K instanceof Error?K.message:String(K)}`})}}async loadStashList(){try{let $=await this.queue.enqueue(()=>H$(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as v2}from"node:events";class w$ extends v2{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor($,Z,K){super();this.repoPath=$,this.queue=Z,this.callbacks=K}get remoteState(){return this._remoteState}updateRemoteState($){this._remoteState={...this._remoteState,...$},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation($,Z){this.updateRemoteState({operation:$,inProgress:!0,error:null,lastResult:null});try{let K=await this.queue.enqueue(Z);this.updateRemoteState({inProgress:!1,lastResult:K}),this.callbacks.scheduleRefresh()}catch(K){let Q=K instanceof Error?K.message:String(K);this.updateRemoteState({inProgress:!1,error:Q})}return this._remoteState}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>A0(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>B0(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>x0(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>L0(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>G0(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>Q$(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>j0(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>C0(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>I0(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>M0(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>H0(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>T0(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>D0(this.repoPath))}}class c0{workingTree;remote;repoPath;constructor($){this.repoPath=$;let Z=t$($);this.workingTree=new R$($,Z),this.remote=new w$($,Z,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()})}dispose(){this.workingTree.dispose(),r$(this.repoPath)}}var z$=new Map;function f0($){let Z=z$.get($);if(!Z)Z=new c0($),z$.set($,Z);return Z}function v$($){let Z=z$.get($);if(Z)Z.dispose(),z$.delete($)}import*as f from"node:fs";import*as q from"node:path";async function g0($){let Z=u0($);if(!Z)return null;try{let K=G(Z);if((await K.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await K.raw(["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function U$($){let Z=u0($);if(!Z)return[];try{let Q=await G(Z).raw(["worktree","list","--porcelain"]);return y2(Q)}catch{return[]}}function d0($){let Z=null,K=-1/0;for(let Q of $){if(Q.isBare)continue;let Y=b2(Q.path);if(Y>K)K=Y,Z=Q}return Z}function b2($){let Z=k2($),K=Z?[q.join(Z,"index"),q.join(Z,"HEAD")]:[$],Q=-1/0;for(let Y of K)try{let V=f.statSync(Y).mtimeMs;if(V>Q)Q=V}catch{}return Q}function k2($){let Z=q.join($,".git");try{if(f.statSync(Z).isDirectory())return Z;let K=f.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!K)return null;let Q=K[1].trim();return q.isAbsolute(Q)?Q:q.resolve($,Q)}catch{return null}}function y2($){let Z=[],K=null;for(let Q of $.split(`
|
|
19
|
+
`))if(Q.startsWith("worktree ")){if(K)Z.push(K);K={path:Q.slice(9).trim(),branch:null,head:null,isBare:!1}}else if(!K)continue;else if(Q.startsWith("HEAD "))K.head=Q.slice(5).trim();else if(Q.startsWith("branch "))K.branch=Q.slice(7).trim().replace(/^refs\/heads\//,"");else if(Q==="bare")K.isBare=!0;if(K)Z.push(K);return Z}function u0($){try{if(f.statSync($).isDirectory())return $;return q.dirname($)}catch{let Z=q.dirname($);return Z!==$&&f.existsSync(Z)?Z:null}}function m2($){return P2("sha256").update($).digest("hex").slice(0,12)}class b${events;byId=new Map;byPath=new Map;constructor($={}){this.events=$}async openRepo($){let Z=await g0($);if(!Z){let V=d0(await U$($));if(!V)throw Error(`Not a git repository: ${$}`);Z=V.path}let K=this.byPath.get(Z);if(K)return K.refCount++,{handle:K,created:!1};let Q=f0(Z);Q.workingTree.startWatching();let Y={id:m2(Z),path:Z,manager:Q,refCount:1};return this.byId.set(Y.id,Y),this.byPath.set(Z,Y),this.events.onOpened?.(Y),{handle:Y,created:!0}}getRepo($){return this.byId.get($)}listRepos(){return[...this.byId.values()]}closeRepo($){let Z=this.byId.get($);if(!Z)return!1;if(Z.refCount--,Z.refCount>0)return!1;return this.byId.delete(Z.id),this.byPath.delete(Z.path),v$(Z.path),this.events.onClosed?.(Z.id),!0}disposeAll(){for(let $ of this.byId.values())v$($.path);this.byId.clear(),this.byPath.clear()}}var p0=25000;function W$($,Z,K){$.write(`event: ${Z}
|
|
20
|
+
data: ${K}
|
|
21
|
+
|
|
22
|
+
`)}class k${channels=new Map;subscribe($,Z,K,Q){Q.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let Y=this.channels.get($);if(!Y){let X=new Set,z={manager:Z,subscribers:X,listener:(J)=>{let U=JSON.stringify(y(J));if(U===z.lastData)return;z.lastData=U;for(let W of X)W$(W,"state-change",U)},keepAlive:setInterval(()=>{for(let J of X)J.write(`: ping
|
|
23
|
+
|
|
24
|
+
`)},p0),lastData:null};Z.workingTree.on("state-change",z.listener),z.keepAlive.unref(),Y=z,this.channels.set($,Y)}Y.subscribers.add(Q),K.on("close",()=>this.unsubscribe($,Q));let V=JSON.stringify(y(Z.workingTree.state));W$(Q,"snapshot",V)}unsubscribe($,Z){let K=this.channels.get($);if(!K)return;if(K.subscribers.delete(Z),K.subscribers.size===0)this.teardown($,K)}teardown($,Z){Z.manager.workingTree.off("state-change",Z.listener),clearInterval(Z.keepAlive);for(let K of Z.subscribers)K.end();Z.subscribers.clear(),this.channels.delete($)}closeRepo($){let Z=this.channels.get($);if(Z)this.teardown($,Z)}destroy(){for(let[$,Z]of this.channels)this.teardown($,Z)}}class y${subscribers=new Set;keepAlive=null;subscribe($,Z,K){if(Z.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),this.subscribers.add(Z),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let Q of this.subscribers)Q.write(`: ping
|
|
25
|
+
|
|
26
|
+
`)},p0),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),W$(Z,"snapshot",JSON.stringify(K))}broadcast($,Z){let K=JSON.stringify(Z);for(let Q of this.subscribers)W$(Q,$,K)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as d from"node:fs";import*as O$ from"node:path";import{watch as c2}from"chokidar";import{EventEmitter as f2}from"node:events";import*as J$ from"node:fs";import*as _$ from"node:path";import*as P$ from"node:os";function h0($){if($.startsWith("~/"))return _$.join(P$.homedir(),$.slice(2));if($==="~")return P$.homedir();return $}function l0($){let Z=_$.dirname($);if(!J$.existsSync(Z))J$.mkdirSync(Z,{recursive:!0})}function m$($){let Z=$.split(`
|
|
27
|
+
`);for(let K=Z.length-1;K>=0;K--){let Q=Z[K].trim();if(Q)return Q}return""}class c$ extends f2{targetFile;debug;watcher=null;debounceTimer=null;lastReadPath=null;_state={path:null,lastUpdate:null,rawContent:null,sourceFile:null};constructor($,Z=!1){super();this.targetFile=$,this.debug=Z,this._state.sourceFile=$}get state(){return this._state}updateState($){this._state={...this._state,...$},this.emit("path-change",this._state)}processContent($){if(!$)return null;let Z=h0($);return O$.isAbsolute(Z)?Z:O$.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=d.readFileSync(this.targetFile,"utf-8"),Z=m$($);if(Z&&Z!==this.lastReadPath){let K=this.processContent(Z),Q=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${Q.toISOString()}] Path change detected
|
|
28
|
+
`),process.stderr.write(` Source file: ${this.targetFile}
|
|
29
|
+
`),process.stderr.write(` Raw content: "${Z}"
|
|
30
|
+
`),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
|
|
31
|
+
`),process.stderr.write(` Resolved: "${K}"
|
|
32
|
+
`);this.lastReadPath=K,this.updateState({path:K,lastUpdate:Q,rawContent:Z})}}catch{}}start(){if(l0(this.targetFile),!d.existsSync(this.targetFile))d.writeFileSync(this.targetFile,"");try{let $=d.readFileSync(this.targetFile,"utf-8"),Z=m$($);if(Z){let K=this.processContent(Z),Q=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${Q.toISOString()}] Initial path read
|
|
33
|
+
`),process.stderr.write(` Source file: ${this.targetFile}
|
|
34
|
+
`),process.stderr.write(` Raw content: "${Z}"
|
|
35
|
+
`),process.stderr.write(` Resolved: "${K}"
|
|
36
|
+
`);this.lastReadPath=K,this._state={path:K,lastUpdate:Q,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=c2(this.targetFile,{persistent:!0,ignoreInitial:!0}),this.watcher.on("change",()=>this.readTargetDebounced()),this.watcher.on("add",()=>this.readTargetDebounced())}stop(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null;if(this.watcher)this.watcher.close(),this.watcher=null}}var n0={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class f${registry;hub;targetFile;watcher;followedRepoId=null;followedPath=null;disposed=!1;queue=Promise.resolve();constructor($,Z,K){this.registry=$,this.hub=Z,this.targetFile=K,this.watcher=new c$(K)}get state(){return{targetFile:this.targetFile,enabled:!0,followedRepoId:this.followedRepoId,followedPath:this.followedPath}}start(){if(this.watcher.on("path-change",($)=>this.enqueue($)),this.watcher.start(),this.watcher.state.path)this.enqueue(this.watcher.state)}enqueue($){this.queue=this.queue.then(()=>this.follow($)).catch(()=>{})}async follow($){if(this.disposed||!$.path)return;let Z;try{Z=await this.registry.openRepo($.path)}catch{return}if(this.disposed){this.registry.closeRepo(Z.handle.id);return}if(Z.created)Z.handle.manager.workingTree.refresh().catch(()=>{});if(Z.handle.id===this.followedRepoId)this.registry.closeRepo(Z.handle.id);else{let K=this.followedRepoId;if(this.followedRepoId=Z.handle.id,this.followedPath=Z.handle.path,K)this.registry.closeRepo(K)}this.hub.broadcast("follow-change",{repoId:Z.handle.id,path:$.path,rawContent:$.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}function o0($){$.get("/health",({res:Z})=>{C(Z,200,{ok:!0,ready:!0})})}import*as A$ from"node:fs";import*as F from"node:path";function L($,Z){let K=$.getRepo(Z);if(!K)throw new B(404,`Unknown repo id: ${Z}`);return K}function S($,Z,K){if(typeof $!=="object"||$===null)throw new B(400,`Expected a JSON body with "${Z}"`);let Q=$[Z];if(typeof Q!=="string"||!K?.allowEmpty&&Q.length===0)throw new B(400,`Missing "${Z}" (string) in body`);return Q}function u($,Z){let K=S($,Z);if(K.startsWith("-"))throw new B(400,`Invalid "${Z}" (must not start with "-"): ${K}`);return K}function s0($,Z){if(typeof $!=="object"||$===null)return;let K=$[Z];if(K===void 0)return;if(typeof K!=="string"||K.length===0)throw new B(400,`Invalid "${Z}" (expected a non-empty string)`);return K}function g$($,Z,K){if(typeof $!=="object"||$===null)return K.fallback;let Q=$[Z];if(Q===void 0)return K.fallback;if(typeof Q!=="number"||!Number.isInteger(Q)||Q<K.min)throw new B(400,`Invalid "${Z}" (expected an integer >= ${K.min})`);return Q}function a0($,Z){if(typeof $!=="object"||$===null)return!1;let K=$[Z];if(K===void 0)return!1;if(typeof K!=="boolean")throw new B(400,`Invalid "${Z}" (expected a boolean)`);return K}function p($,Z,K){let Q=$.get(Z);if(Q===null)return K;if(Q==="true")return!0;if(Q==="false")return!1;throw new B(400,`Invalid "${Z}" (expected true or false): ${Q}`)}function t0($,Z,K){let Q=$.get(Z);if(Q===null)return K;let Y=Number(Q);if(!Number.isInteger(Y)||Y<1)throw new B(400,`Invalid "${Z}" (expected a positive integer): ${Q}`);return Y}async function w($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new B(500,"Repository status unavailable");return Z}function i0($,Z,K){let Q=$.files.filter((Y)=>Y.path===Z);if(Q.length===0)return null;return Q.find((Y)=>Y.staged===K)??Q[0]}async function B$($,Z,K){let Q=await w($),Y=i0(Q,Z,K);if(!Y)await $.refresh(),Q=await w($),Y=i0(Q,Z,K);if(!Y)throw new B(404,`File not in status: ${Z}`);return Y}function d$($,Z){let K=F.resolve($),Q=F.resolve(K,Z);if(Q!==K&&!Q.startsWith(K+F.sep))throw new B(400,`Path escapes repository root: ${Z}`)}async function r0($){try{return await A$.promises.realpath($)}catch{return null}}async function u$($,Z){let K=await A$.promises.realpath(F.resolve($)),Q=await r0(F.join($,Z));if(Q===null)return;if(Q!==K&&!Q.startsWith(K+F.sep))throw new B(400,`Path escapes repository root: ${Z}`)}async function e0($,Z){let K=await A$.promises.realpath(F.resolve($)),Q=[];for(let Y of Z){let V=await r0(F.join($,Y.path));if(V===null||V===K||V.startsWith(K+F.sep))Q.push(Y)}return Q}function p$($){return $?.code??null}function g2($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function v($,Z,K){$.clearError(),await K();let Q=$.state.error;if(Q){C(Z,g2(Q),{error:Q});return}await $.refresh(),C(Z,200,{state:y($.state)})}function d2($){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test($)?409:500}async function T($,Z,K){let Q=$.manager.remote,Y=()=>new B(409,`A ${Q.remoteState.operation??"remote"} operation is already in progress`);if(Q.remoteState.inProgress)throw Y();let V=await K();if(V===null)throw Y();if(V.error){C(Z,d2(V.error),{error:V.error});return}let X=$.manager.workingTree;await X.refresh(),C(Z,200,{state:y(X.state),result:V.lastResult})}function $2($,Z){let{registry:K}=Z;$.get("/repos",({res:Q})=>{let Y=K.listRepos().map((V)=>({id:V.id,path:V.path,branch:V.manager.workingTree.state.status?.branch.current??null}));C(Q,200,Y)}),$.post("/repos",async({body:Q,res:Y})=>{let V=S(Q,"path"),X;try{X=await K.openRepo(V)}catch(z){throw new B(400,z instanceof Error?z.message:String(z))}if(X.created)X.handle.manager.workingTree.refresh().catch(()=>{});C(Y,X.created?201:200,{id:X.handle.id,path:X.handle.path})}),$.get("/repos/:id/worktrees",async({params:Q,res:Y})=>{let V=L(K,Q.id);C(Y,200,await U$(V.path))}),$.delete("/repos/:id",({params:Q,res:Y})=>{L(K,Q.id),K.closeRepo(Q.id),C(Y,200,{})})}function Z2($,Z,K){if(!$.trim())return{valid:!1,error:"Commit message cannot be empty"};if(Z===0&&!K)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function K2($){return $.trim()}async function u2($){let Z=(Q)=>Q.filter((Y)=>Y.staged).length,K=Z((await w($)).files);if(K===0)await $.refresh(),K=Z((await w($)).files);return K}function Q2($,Z){let{registry:K,sse:Q}=Z;$.get("/repos/:id/status",async({params:Y,res:V})=>{let X=L(K,Y.id);await w(X.manager.workingTree);let z=y(X.manager.workingTree.state);z.operationInProgress=await P(X.path),C(V,200,z)}),$.get("/repos/:id/diff",async({params:Y,query:V,res:X})=>{let z=L(K,Y.id),J=V.get("path")??void 0,U=p(V,"staged",!1),W;if(J){let N=(await w(z.manager.workingTree)).files.some((O)=>O.path===J&&O.status==="untracked");if(N&&U)throw new B(400,`staged=true is meaningless for untracked file: ${J} (untracked files have no staged diff)`);W=N?await w0(z.path,J):await i(z.path,J,U)}else W=await i(z.path,void 0,U);z.manager.workingTree.stampDiff(W),C(X,200,W)}),$.post("/repos/:id/stage",async({params:Y,body:V,res:X})=>{let z=L(K,Y.id),J=S(V,"path"),U=z.manager.workingTree,W=await B$(U,J,!1);await v(U,X,()=>U.stage(W))}),$.post("/repos/:id/unstage",async({params:Y,body:V,res:X})=>{let z=L(K,Y.id),J=S(V,"path"),U=z.manager.workingTree,W=await B$(U,J,!0);await v(U,X,()=>U.unstage(W))}),$.post("/repos/:id/stage-all",async({params:Y,res:V})=>{let z=L(K,Y.id).manager.workingTree;await v(z,V,()=>z.stageAll())}),$.post("/repos/:id/unstage-all",async({params:Y,res:V})=>{let z=L(K,Y.id).manager.workingTree;await v(z,V,()=>z.unstageAll())}),$.post("/repos/:id/discard",async({params:Y,body:V,res:X})=>{let z=L(K,Y.id),J=S(V,"path"),U=z.manager.workingTree,W=await B$(U,J,!1);if(W.staged)throw new B(409,`Cannot discard a staged file: ${J} (unstage it first)`);await v(U,X,()=>U.discard(W))}),$.post("/repos/:id/commit",async({params:Y,body:V,res:X})=>{let z=L(K,Y.id),J=S(V,"message",{allowEmpty:!0}),U=a0(V,"amend"),W=z.manager.workingTree,A=await u2(W),N=Z2(J,A,U);if(!N.valid)throw new B(400,N.error??"Invalid commit");await v(W,X,()=>W.commit(K2(J),U))}),$.post("/repos/:id/stage-hunk",async({params:Y,body:V,res:X})=>{let z=L(K,Y.id),J=S(V,"patch"),U=z.manager.workingTree;await v(U,X,()=>U.stageHunk(J))}),$.post("/repos/:id/unstage-hunk",async({params:Y,body:V,res:X})=>{let z=L(K,Y.id),J=S(V,"patch"),U=z.manager.workingTree;await v(U,X,()=>U.unstageHunk(J))}),$.get("/repos/:id/events",({params:Y,req:V,res:X})=>{let z=L(K,Y.id);Q.subscribe(Y.id,z.manager,V,X)})}async function p2($){let Z=await q$($);if(Z&&await m($,Z))return Z;if(Y$($)){let K=await F$($);if(K&&await m($,K))return K}throw new B(422,"No usable base branch")}function Y2($,Z){let{registry:K}=Z;$.get("/repos/:id/history",async({params:Q,query:Y,res:V})=>{let X=L(K,Q.id),z=t0(Y,"count",100);C(V,200,await N0(X.path,z))}),$.get("/repos/:id/commits/:hash/diff",async({params:Q,res:Y})=>{let V=L(K,Q.id),X=Q.hash;if(!/^[0-9a-f]{4,40}$/i.test(X))throw new B(400,`Invalid commit hash: ${X}`);if(!await m(V.path,X))throw new B(404,`Unknown commit: ${X}`);C(Y,200,await v0(V.path,X))}),$.get("/repos/:id/head-message",async({params:Q,res:Y})=>{let V=L(K,Q.id);C(Y,200,{message:await J0(V.path)})}),$.get("/repos/:id/branches",async({params:Q,res:Y})=>{let V=L(K,Q.id);C(Y,200,await Q$(V.path))}),$.get("/repos/:id/base-branches",async({params:Q,res:Y})=>{let V=L(K,Q.id);C(Y,200,await D$(V.path))}),$.get("/repos/:id/compare/base",async({params:Q,res:Y})=>{let V=L(K,Q.id);C(Y,200,{base:await q$(V.path)})}),$.put("/repos/:id/compare/base",async({params:Q,body:Y,res:V})=>{let X=L(K,Q.id),z=u(Y,"branch");if(!await m(X.path,z))throw new B(400,`Not a valid base ref: ${z}`);E0(X.path,z),C(V,200,{base:z})}),$.get("/repos/:id/compare",async({params:Q,query:Y,res:V})=>{let X=L(K,Q.id),z=p(Y,"uncommitted",!1),J=Y.get("base"),U;if(J!==null){if(!await m(X.path,J))throw new B(400,`Unknown base ref: ${J}`);U=J}else U=await p2(X.path);let W;try{W=z?await b0(X.path,U):await E$(X.path,U)}catch(A){if(A instanceof X$)throw new B(422,A.message);throw A}C(V,200,W)})}function V2($,Z){let{registry:K}=Z;$.post("/repos/:id/push",async({params:Q,res:Y})=>{let V=L(K,Q.id);await T(V,Y,()=>V.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:Q,res:Y})=>{let V=L(K,Q.id);await T(V,Y,()=>V.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:Q,res:Y})=>{let V=L(K,Q.id);await T(V,Y,()=>V.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:Q,body:Y,res:V})=>{let X=L(K,Q.id),z=s0(Y,"message");await T(X,V,()=>X.manager.remote.stash(z))}),$.post("/repos/:id/stash-pop",async({params:Q,body:Y,res:V})=>{let X=L(K,Q.id),z=g$(Y,"index",{min:0,fallback:0});await T(X,V,()=>X.manager.remote.stashPop(z))}),$.post("/repos/:id/switch-branch",async({params:Q,body:Y,res:V})=>{let X=L(K,Q.id),z=u(Y,"name");await T(X,V,()=>X.manager.remote.switchBranch(z))}),$.post("/repos/:id/create-branch",async({params:Q,body:Y,res:V})=>{let X=L(K,Q.id),z=u(Y,"name");await T(X,V,()=>X.manager.remote.createBranch(z))}),$.post("/repos/:id/soft-reset",async({params:Q,body:Y,res:V})=>{let X=L(K,Q.id),z=g$(Y,"count",{min:1,fallback:1});if(!await m(X.path,`HEAD~${z}`))throw new B(400,`Cannot soft-reset ${z} commit(s): HEAD~${z} does not exist`);await T(X,V,()=>X.manager.remote.softReset(z))}),$.post("/repos/:id/cherry-pick",async({params:Q,body:Y,res:V})=>{let X=L(K,Q.id),z=u(Y,"hash");await T(X,V,()=>X.manager.remote.cherryPick(z))}),$.post("/repos/:id/revert",async({params:Q,body:Y,res:V})=>{let X=L(K,Q.id),z=u(Y,"hash");await T(X,V,()=>X.manager.remote.revertCommit(z))}),$.post("/repos/:id/abort",async({params:Q,res:Y})=>{let V=L(K,Q.id);if(!await P(V.path))throw new B(409,"No operation in progress to abort");await T(V,Y,()=>V.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:Q,res:Y})=>{let V=L(K,Q.id);if(await P(V.path)!=="rebase")throw new B(409,"No rebase in progress to continue");await T(V,Y,()=>V.manager.remote.rebaseContinue())})}import*as x$ from"node:fs";import*as t from"node:path";function h$($){let Z={files:new Map,directories:new Set};for(let K of $){Z.files.set(K.path,{status:K.status,staged:K.staged});let Q=K.path.split("/"),Y="";for(let V=0;V<Q.length-1;V++)Y=Y?`${Y}/${Q[V]}`:Q[V],Z.directories.add(Y);Z.directories.add("")}return Z}var h2=1048576,X2=5000;class N$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function z2($,Z,K,Q){let Y=K?.hideHidden??!0,V=K?.hideGitignored??!0,X=t.join($,Z),z=await x$.promises.readdir(X,{withFileTypes:!0}),J=z.map((A)=>Z?t.join(Z,A.name):A.name),U=V?await K$($,J):new Set,W=[];for(let A of z){if(Y&&A.name.startsWith("."))continue;let N=Z?t.join(Z,A.name):A.name;if(V&&U.has(N))continue;let O=A.isDirectory(),j={name:A.name,path:N,type:O?"dir":"file"};if(Q)if(O){if(Q.directories.has(N))j.hasChanges=!0}else{let E=Q.files.get(N);if(E)j.gitStatus=E.status,j.staged=E.staged}W.push(j)}return W.sort((A,N)=>{if(A.type==="dir"&&N.type!=="dir")return-1;if(A.type!=="dir"&&N.type==="dir")return 1;return A.name.localeCompare(N.name)}),W}function l2($){let Z=Math.min($.length,8192);for(let K=0;K<Z;K++)if($[K]===0)return!0;return!1}async function U2($,Z){let K=t.join($,Z),Q=await x$.promises.stat(K);if(!Q.isFile())throw new N$(Z);if(Q.size>h2)return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:Q.size,totalLines:0};let Y=await x$.promises.readFile(K);if(l2(Y))return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:Q.size,totalLines:0};let V=Y.toString("utf-8"),X=V.split(`
|
|
37
|
+
`),z=!1;if(X.length>X2)V=X.slice(0,X2).join(`
|
|
38
|
+
`),z=!0;return{content:V,binary:!1,truncated:z,tooLarge:!1,size:Q.size,totalLines:X.length}}function W2($,Z){let{registry:K}=Z;$.get("/repos/:id/tree",async({params:Q,query:Y,res:V})=>{let X=L(K,Q.id),z=Y.get("dir")??"",J=p(Y,"hidden",!1),U=p(Y,"ignored",!1);d$(X.path,z),await u$(X.path,z);let W=await w(X.manager.workingTree),A=h$(W.files),N;try{N=await z2(X.path,z,{hideHidden:!J,hideGitignored:!U},A)}catch(O){let j=p$(O);if(j==="ENOENT")throw new B(404,`No such directory: ${z||"/"}`);if(j==="ENOTDIR")throw new B(400,`Not a directory: ${z}`);throw O}C(V,200,await e0(X.path,N))}),$.get("/repos/:id/file",async({params:Q,query:Y,res:V})=>{let X=L(K,Q.id),z=Y.get("path");if(!z)throw new B(400,'Missing "path" query parameter');d$(X.path,z),await u$(X.path,z);try{C(V,200,await U2(X.path,z))}catch(J){if(J instanceof N$)throw new B(400,J.message);let U=p$(J);if(U==="ENOENT"||U==="ENOTDIR")throw new B(404,`No such file: ${z}`);throw J}}),$.get("/repos/:id/files",async({params:Q,res:Y})=>{let V=L(K,Q.id);C(Y,200,await F0(V.path))})}function J2($,Z){let{registry:K,daemonEvents:Q,follow:Y}=Z;$.get("/events",({req:V,res:X})=>{let z=K.listRepos().map((J)=>({id:J.id,path:J.path}));Q.subscribe(V,X,z)}),$.get("/follow",({res:V})=>{C(V,200,Y?Y.state:n0)})}function n2($){if(!h.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let K=O2.connect($);K.once("connect",()=>{K.destroy(),Z(!0)}),K.once("error",()=>{K.destroy(),Z(!1)})}catch{Z(!1)}})}function A2($={}){let Z=new k$,K=new y$,Q=new b$({onOpened:(W)=>K.broadcast("repo-opened",{id:W.id,path:W.path}),onClosed:(W)=>{Z.closeRepo(W),K.broadcast("repo-closed",{id:W})}}),Y=$.followFile?new f$(Q,K,$.followFile):null,V=new j$,X={registry:Q,sse:Z,daemonEvents:K,follow:Y};o0(V),$2(V,X),Q2(V,X),Y2(V,X),V2(V,X),W2(V,X),J2(V,X),Y?.start();let z=_2.createServer((W,A)=>{V.handle(W,A).catch(()=>A.end())}),J=new Set;z.on("connection",(W)=>{J.add(W),W.on("close",()=>J.delete(W))});let U=null;return{async listen(W){if(W.socketPath){if(await n2(W.socketPath))throw Error(`diffstalkerd already running at ${W.socketPath}`);h.rmSync(W.socketPath,{force:!0})}return new Promise((A,N)=>{let O=(E)=>N(E);z.once("error",O);let j=()=>{if(z.removeListener("error",O),U)h.chmodSync(U,384);A()};if(W.fd!==void 0)z.listen({fd:W.fd},j);else if(W.socketPath)U=W.socketPath,process.umask(63),z.listen(W.socketPath,j);else if(W.port!==void 0)z.listen(W.port,W.host??"127.0.0.1",j);else N(Error("listen() requires a socketPath, a port, or an fd"))})},close(){Y?.dispose(),Z.destroy(),K.destroy(),Q.disposeAll();for(let W of J)W.destroy();return new Promise((W,A)=>{z.close((N)=>{if(U)h.rmSync(U,{force:!0});if(N)A(N);else W()})})}}}var N2="diffstalkerd.sock",o2=3,B2=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
|
|
39
|
+
|
|
40
|
+
Usage: diffstalkerd [options]
|
|
41
|
+
|
|
42
|
+
Options:
|
|
43
|
+
--socket PATH Bind a unix socket at PATH
|
|
44
|
+
(default: $XDG_RUNTIME_DIR/diffstalker/${N2})
|
|
45
|
+
--port N Bind TCP port N instead of a unix socket
|
|
46
|
+
--host H Host to bind with --port (default: 127.0.0.1)
|
|
47
|
+
--follow-file PATH Hook file to follow (created when missing)
|
|
48
|
+
(default: ~/.cache/diffstalker/target)
|
|
49
|
+
--no-follow Disable follow mode (no hook-file watcher)
|
|
50
|
+
--help, -h Show this help
|
|
51
|
+
`;function L$($,Z,K){let Q=$[Z];if(Q===void 0||Q.startsWith("--"))throw Error(`${K} requires a value`);return Q}function i2($){let Z={};for(let K=0;K<$.length;K++){let Q=$[K];switch(Q){case"--help":case"-h":return"help";case"--socket":Z.socketPath=L$($,++K,"--socket");break;case"--port":if(Z.port=Number(L$($,++K,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--host":Z.host=L$($,++K,"--host");break;case"--follow-file":Z.followFile=L$($,++K,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;default:throw Error(`Unknown argument: ${Q}`)}}if(Z.socketPath!==void 0&&Z.port!==void 0)throw Error("--socket and --port are mutually exclusive");if(Z.followFile!==void 0&&Z.noFollow)throw Error("--follow-file and --no-follow are mutually exclusive");return Z}function s2(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function a2($){if($.socketPath!==void 0||$.port!==void 0)return;if(s2()){$.fd=o2;return}let Z=i$();if(!Z)console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
|
|
52
|
+
Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1);x2.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=l$.join(Z,N2)}async function t2(){process.title="diffstalkerd";let $;try{$=i2(process.argv.slice(2))}catch(X){console.error(X instanceof Error?X.message:String(X)),console.error(B2),process.exit(2)}if($==="help"){console.log(B2);return}a2($);let Z=$.noFollow?void 0:$.followFile??l$.join(Z$(),"target"),K=A2({followFile:Z});if(await K.listen($),$.fd!==void 0)console.error(`diffstalkerd listening on inherited socket (fd ${$.fd})`);else if($.socketPath)console.error(`diffstalkerd listening on unix socket ${$.socketPath}`);else console.error(`diffstalkerd listening on ${$.host??"127.0.0.1"}:${$.port}`);if(Z)console.error(`diffstalkerd following ${Z}`);let Q=!1,Y=(X)=>{if(Q)return;Q=!0,console.error(`Received ${X}, shutting down`),K.close().then(()=>process.exit(0)).catch((z)=>{console.error(z instanceof Error?z.message:String(z)),process.exit(1)})};process.on("SIGINT",()=>Y("SIGINT")),process.on("SIGTERM",()=>Y("SIGTERM")),process.on("SIGHUP",()=>Y("SIGHUP"));let V=(X,z)=>{console.error(`diffstalkerd ${X}:`,z instanceof Error?z.stack??z.message:z),K.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(X)=>V("uncaught exception",X)),process.on("unhandledRejection",(X)=>V("unhandled rejection",X))}t2().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{i2 as parseArgs};
|
package/package.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "diffstalkerd",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "diffstalker daemon: REST API + SSE git state over a unix socket",
|
|
5
|
+
"author": "yogh-io",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/yogh-io/diffstalker.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/yogh-io/diffstalker#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/yogh-io/diffstalker/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"bin": {
|
|
17
|
+
"diffstalkerd": "bin/diffstalkerd"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist/index.js",
|
|
21
|
+
"bin",
|
|
22
|
+
"README.md"
|
|
23
|
+
],
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"scripts": {
|
|
28
|
+
"dev": "bun --watch src/index.ts",
|
|
29
|
+
"build": "rm -rf dist && tsc -b",
|
|
30
|
+
"build:prod": "bun run build && bun build dist/index.js --outfile dist/index.js --minify --target node --external chokidar --external simple-git --external ignore",
|
|
31
|
+
"start": "bun dist/index.js",
|
|
32
|
+
"test": "bun test src/*.test.ts src/**/*.test.ts",
|
|
33
|
+
"test:watch": "bun test --watch src/*.test.ts src/**/*.test.ts",
|
|
34
|
+
"lint": "eslint src/ && depcruise src/ --config .dependency-cruiser.cjs",
|
|
35
|
+
"lint:fix": "eslint src/ --fix",
|
|
36
|
+
"deps": "depcruise src/ --config .dependency-cruiser.cjs",
|
|
37
|
+
"format": "prettier --write src/",
|
|
38
|
+
"format:check": "prettier --check src/",
|
|
39
|
+
"prepublishOnly": "bun run build:prod"
|
|
40
|
+
},
|
|
41
|
+
"keywords": [
|
|
42
|
+
"git",
|
|
43
|
+
"diff",
|
|
44
|
+
"daemon",
|
|
45
|
+
"diffstalker"
|
|
46
|
+
],
|
|
47
|
+
"engines": {
|
|
48
|
+
"node": ">=20.10.0"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"chokidar": "^4.0.3",
|
|
52
|
+
"ignore": "^7.0.5",
|
|
53
|
+
"simple-git": "^3.27.0"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@diffstalker/core": "0.4.0",
|
|
57
|
+
"@eslint/js": "^9.39.2",
|
|
58
|
+
"@types/node": "^22.10.7",
|
|
59
|
+
"dependency-cruiser": "^17.3.7",
|
|
60
|
+
"eslint": "^9.39.2",
|
|
61
|
+
"eslint-config-prettier": "^10.1.8",
|
|
62
|
+
"eslint-plugin-sonarjs": "^3.0.6",
|
|
63
|
+
"prettier": "^3.8.0",
|
|
64
|
+
"typescript": "^5.7.3",
|
|
65
|
+
"typescript-eslint": "^8.53.1"
|
|
66
|
+
}
|
|
67
|
+
}
|