diffstalkerd 0.5.1 → 0.6.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 CHANGED
@@ -11,7 +11,9 @@ pulls it in automatically, so most users never install it directly.
11
11
 
12
12
  Its primary client is the `diffstalker` CLI (`packages/cli`), which spawns or
13
13
  attaches to this daemon over a unix socket and consumes it through the typed
14
- `@diffstalker/client`. A web client is planned against the same API.
14
+ `@diffstalker/client`. A read-only web UI (Vue) ships inside this package and is
15
+ served at `GET /` when the daemon binds a TCP port (`--port N`) — same-origin,
16
+ since a browser can't reach the unix socket and the daemon sends no CORS headers.
15
17
 
16
18
  ## Running
17
19
 
@@ -34,12 +36,21 @@ Options:
34
36
  --follow-file PATH Hook file to follow (created when missing)
35
37
  (default: ~/.cache/diffstalker/target)
36
38
  --no-follow Disable follow mode (no hook-file watcher)
39
+ --web-root PATH Directory of built web-UI assets to serve at GET /
40
+ (default: ./web next to the daemon bundle; the published
41
+ package ships it there. Missing dir → API-only, non-fatal)
37
42
  --help, -h Show this help
38
43
  ```
39
44
 
40
45
  `--socket` and `--port` are mutually exclusive; so are `--follow-file` and
41
46
  `--no-follow`.
42
47
 
48
+ A browser can only reach the daemon over TCP (`--port`), not a unix socket, and
49
+ the daemon sends no CORS headers — so the web UI is served same-origin from the
50
+ daemon itself. `GET /` and any unmatched non-API GET path return the SPA's
51
+ `index.html` (client-side routing); hashed `/assets/*` are served with a long
52
+ immutable cache. The REST/SSE API always takes precedence over static files.
53
+
43
54
  Without `--socket`/`--port`, the daemon binds a unix socket at
44
55
  `$XDG_RUNTIME_DIR/diffstalker/diffstalkerd.sock`. The directory is created
45
56
  with mode `0700` and the socket is chmod'd to `0600` (owner only). If
@@ -92,7 +103,7 @@ values are rejected with a 400 so they can never be parsed as git flags.
92
103
  | POST | `/repos` | Open a repo: `{"path": "/abs/path"}` → `{id, path}` (201 created, 200 already open) |
93
104
  | DELETE | `/repos/:id` | Close a repo (refcounted per open) |
94
105
  | GET | `/repos/:id/worktrees` | Registered worktrees (`path`, `branch`, `head`, `isBare`): main worktree, linked worktrees, and the bare entry in a bare-worktree layout |
95
- | GET | `/repos/:id/status` | Shared state: status, hunk counts, stash list, in-progress operation, error |
106
+ | GET | `/repos/:id/status` | Shared state: status, hunk counts, stash list, in-progress operation, error, working-file mtimes (path → mtimeMs; what browser clients build mtime-based auto mode on) |
96
107
  | GET | `/repos/:id/diff?path=&staged=` | Diff; whole tree without `path`, staged side with `staged=true` |
97
108
  | GET | `/repos/:id/history?count=` | Commit history (`CommitInfo[]`, default 100, ISO dates) |
98
109
  | 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) |
package/dist/index.js CHANGED
@@ -1,52 +1,55 @@
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}
1
+ import*as j$ from"node:fs";import*as s$ from"node:path";import{fileURLToPath as Z3}from"node:url";import*as a$ from"node:os";import*as K$ from"node:path";var t$="diffstalker";function Q$(){return K$.join(process.env.XDG_CACHE_HOME||K$.join(a$.homedir(),".cache"),t$)}function r$(){return process.env.XDG_RUNTIME_DIR?K$.join(process.env.XDG_RUNTIME_DIR,t$):null}import*as N2 from"node:http";import*as l from"node:fs";import*as G2 from"node:net";function M$($){let Z={};for(let[K,Q]of $)Z[K]=Q;return Z}function C2($){if(!$)return null;return{staged:M$($.staged),unstaged:M$($.unstaged)}}function m($){return{status:$.status,hunkCounts:C2($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress,mtimes:$.mtimes?M$($.mtimes):null}}function a($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[K,Q]of $)Z[String(K)]=a(Q);return Z}if(Array.isArray($))return $.map(a);if($!==null&&typeof $==="object"){let Z={};for(let[K,Q]of Object.entries($))Z[K]=a(Q);return Z}return $}var T2=1048576;class B extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function I($,Z,K){let Q=JSON.stringify(a(K));$.writeHead(Z,{"content-type":"application/json"}),$.end(Q)}function H2($,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 D2($){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>T2)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 C${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})}match($,Z){for(let K of this.routes){if(K.method!==$)continue;let Q=H2(K,Z);if(Q)return{handler:K.handler,params:Q}}return null}async handle($,Z,K){try{let Q=new URL($.url??"/","http://localhost"),Y=Q.pathname.split("/").filter(Boolean),V=$.method??"GET",X=this.match(V,Y);if(!X){if(K&&V==="GET"){await K($,Z,Q.pathname);return}throw new B(404,`Unknown route: ${V} ${Q.pathname}`)}let z=await D2($);await X.handler({req:$,res:Z,params:X.params,query:Q.searchParams,body:z})}catch(Q){if(Z.headersSent){Z.end();return}let Y=Q instanceof B?Q.status:500,V=Q instanceof Error?Q.message:String(Q);I(Z,Y,{error:V})}}}import*as T$ from"node:fs";import*as S from"node:path";var q2=new Set(["health","repos","events","follow"]),F2={".html":"text/html; charset=utf-8",".js":"text/javascript; charset=utf-8",".mjs":"text/javascript; charset=utf-8",".css":"text/css; charset=utf-8",".svg":"image/svg+xml",".json":"application/json",".map":"application/json",".woff2":"font/woff2",".woff":"font/woff",".ttf":"font/ttf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".ico":"image/x-icon",".wasm":"application/wasm",".txt":"text/plain; charset=utf-8",".webmanifest":"application/manifest+json"},e$="no-cache",S2="public, max-age=31536000, immutable";async function $0($,Z,K){let Q;try{Q=await T$.promises.readFile(Z)}catch{throw new B(404,`Not found: ${S.basename(Z)}`)}$.writeHead(200,{"content-type":F2[S.extname(Z)]??"application/octet-stream","cache-control":K,"content-length":Q.length}),$.end(Q)}function Z0($){let Z=S.resolve($);return async(K,Q,Y)=>{let V;try{V=decodeURIComponent(Y)}catch{throw new B(400,`Malformed percent-encoding in path: ${Y}`)}if(V.includes("\x00"))throw new B(400,"Invalid path");let X=V.split("/").filter(Boolean);if(X.length>0&&q2.has(X[0]))throw new B(404,`Unknown route: GET ${Y}`);let z=X.length>0?S.resolve(Z,X.join("/")):Z;if(z!==Z&&!z.startsWith(Z+S.sep))throw new B(403,"Forbidden");if((await T$.promises.stat(z).catch(()=>null))?.isFile()){await $0(Q,z,X[0]==="assets"?S2:e$);return}await $0(Q,S.join(Z,"index.html"),e$)}}import{createHash as h2}from"node:crypto";class K0{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 H$=new Map;function Q0($){let Z=H$.get($);if(!Z)Z=new K0,H$.set($,Z);return Z}function Y0($){H$.delete($)}import*as T from"node:path";import*as w from"node:fs";import{execFileSync as c2}from"node:child_process";import{watch as u0}from"chokidar";import{EventEmitter as f2}from"node:events";import p0 from"ignore";function V0($){process.stderr.write(`[diffstalker warn] ${$}
2
+ `)}import{simpleGit as R2}from"simple-git";function n(){return{...process.env,LC_ALL:"C",LANG:"C"}}var w2={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0};function G($){return R2({baseDir:$,unsafe:w2}).env(n())}import{execFileSync as U0}from"node:child_process";import*as o from"node:fs";import*as D$ from"node:path";async function Y$($,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 U=(await K.raw(["check-ignore","--",...X])).trim().split(`
3
+ `).filter((W)=>W.length>0);for(let W of U)Q.add(W)}catch{}}return Q}function X0($){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 v2($,Z){try{let K=D$.join($,Z);if(!(await o.promises.stat(K)).isFile())return 0;return(await o.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 q$($){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((A)=>A.working_dir==="?").map((A)=>A.path),z=await Y$($,X);for(let A of Q.files){if(A.index==="!"||A.working_dir==="!"||z.has(A.path))continue;let j=`${A.path}-${A.index!==" "&&A.index!=="?"}`;if(V.has(j))continue;if(V.add(j),A.index&&A.index!==" "&&A.index!=="?")Y.push({path:A.path,status:z0(A.index),staged:!0});if(A.working_dir&&A.working_dir!==" ")Y.push({path:A.path,status:A.working_dir==="?"?"untracked":z0(A.working_dir),staged:!1})}let[U,W]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),_=X0(U),J=X0(W);for(let A of Y){let j=A.staged?_.get(A.path):J.get(A.path);if(j)A.insertions=j.insertions,A.deletions=j.deletions}let x=Y.filter((A)=>A.status==="untracked");if(x.length>0){let A=await Promise.all(x.map((j)=>v2($,j.path)));for(let j=0;j<x.length;j++)x[j].insertions=A[j],x[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 W0($,Z){await G($).add(["--",Z])}async function J0($,Z){await G($).reset(["HEAD","--",Z])}async function O0($){await G($).add("-A")}async function _0($){await G($).reset(["HEAD"])}async function A0($,Z){await G($).checkout(["--",Z])}async function B0($,Z){await G($).clean("f",["--",Z])}async function x0($,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 L0($){let Z=G($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function N0($,Z){U0("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:n()})}function G0($,Z){U0("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:n()})}async function j0($){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 I0($){return await G($).fetch(),"Fetch complete"}async function M0($){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 C0($,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 F$($){let Z=G($);try{return(await Z.stashList()).all.map((Q,Y)=>({index:Y,message:Q.message}))}catch{return[]}}async function T0($,Z){let K=G($),Q=["push"];if(Z)Q.push("-m",Z);return await K.stash(Q),"Stashed"}async function H0($,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 V$($){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 D0($,Z){return await G($).raw(["switch","--",Z]),`Switched to ${Z}`}async function q0($,Z){return await G($).raw(["switch","-c",Z]),`Created ${Z}`}async function F0($,Z=1){return await G($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function S0($,Z){return await G($).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function E0($,Z){return await G($).raw(["revert","--no-edit","--end-of-options",Z]),"Reverted"}async function c($){let Z=G($),K;try{K=(await Z.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let Q=(Y)=>o.existsSync(D$.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 R0($){let Z=await c($);if(!Z)throw Error("No operation in progress to abort");return await G($).raw([Z,"--abort"]),`Aborted ${Z}`}async function w0($){return await G($).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function v0($){return(await G($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((Q)=>Q.length>0)}import*as P0 from"node:fs";import*as t from"node:path";import*as b from"node:fs";import*as d from"node:path";function S$(){return d.join(Q$(),"base-branches.json")}function b2(){let $=d.dirname(S$());if(!b.existsSync($))b.mkdirSync($,{recursive:!0})}function b0(){try{let $=S$();if(b.existsSync($))return JSON.parse(b.readFileSync($,"utf-8"))}catch{}return{}}function k2($){b2(),b.writeFileSync(S$(),JSON.stringify($,null,2)+`
8
+ `)}function X$($){let Z=b0(),K=d.resolve($);return Z[K]}function k0($,Z){let K=b0(),Q=d.resolve($);K[Q]=Z,k2(K)}function y0($){let Z=$.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(Z)return{oldStart:parseInt(Z[1],10),newStart:parseInt(Z[2],10)};return null}function i($){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=y0(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 z$($){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 U$ extends Error{constructor($){super(`No common history with ${$}`);this.name="NoCommonHistoryError"}}async function s($,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=i(V);return{raw:V,lines:X}}catch{return{raw:"",lines:[]}}}async function m0($,Z){try{let K=t.resolve($),Q=t.resolve(K,Z);if(Q!==K&&!Q.startsWith(K+t.sep))return{raw:"",lines:[]};let Y=P0.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 W of X)V.push({type:"addition",content:"+"+W,newLineNum:z++});return{raw:V.map((W)=>W.content).join(`
12
+ `),lines:V}}catch{return{raw:"",lines:[]}}}async function E$($){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 U=z[1].split(",").map((W)=>W.trim());for(let W of U){if(W.startsWith("HEAD")||W.startsWith("tag:")||!W.includes("/"))continue;let _=W.replace(/^.*-> /,"");if(_.includes("/")&&!K.has(_))K.add(_),Q.push(_)}}V.lastIndex=0}if(Q.length>0)Q.sort((X,z)=>{let U=X.split("/").slice(1).join("/"),W=z.split("/").slice(1).join("/"),_=U==="main"||U==="master",J=W==="main"||W==="master";if(_&&!J)return-1;if(!_&&J)return 1;if(_&&J){let x=X.startsWith("origin/"),A=z.startsWith("origin/");if(x&&!A)return 1;if(!x&&A)return-1}return 0})}catch{}return[...new Set(Q)]}async function R$($){return(await E$($))[0]??null}async function w$($){return X$($)??await R$($)}async function f($,Z){let K=G($);try{return await K.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}async function v$($,Z){let K=G($),Y=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Y)throw new U$(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`]),U=V.trim().split(`
14
+ `).filter((O)=>O),W=new Map;for(let O of U){let L=O.split("\t");if(L.length>=3){let M=L[0]==="-"?0:parseInt(L[0],10),q=L[1]==="-"?0:parseInt(L[1],10),C=L.slice(2).join("\t");W.set(C,{additions:M,deletions:q})}}let _=X.trim().split(`
15
+ `).filter((O)=>O),J=new Map;for(let O of _){let L=O.split("\t");if(L.length>=2){let M=L[0][0],q=L[L.length-1],C;switch(M){case"A":C="added";break;case"D":C="deleted";break;case"R":C="renamed";break;default:C="modified"}J.set(q,C)}}let x=[],A=z.split(/(?=^diff --git )/m).filter((O)=>O.trim());for(let O of A){let L=O.match(/^diff --git a\/.+ b\/(.+)$/m);if(!L)continue;let M=L[1],q=i(O),C=W.get(M)||{additions:0,deletions:0},P=J.get(M)||"modified";x.push({path:M,status:P,additions:C.additions,deletions:C.deletions,diff:{raw:O,lines:q}})}let j=0,D=0;for(let O of x)j+=O.additions,D+=O.deletions;let $$=(await K.status()).files.length,Z$=(await K.log({from:Y,to:"HEAD"})).all.map((O)=>({hash:O.hash,shortHash:O.hash.slice(0,7),message:O.message.split(`
16
+ `)[0],author:O.author_name,date:new Date(O.date),refs:O.refs||""}));return x.sort((O,L)=>O.path.localeCompare(L.path)),{baseBranch:Z,stats:{filesChanged:x.length,additions:j,deletions:D},files:x,commits:Z$,uncommittedCount:$$}}async function c0($,Z){let K=G($);try{let Q=await K.raw(["show","--format=","--end-of-options",Z]),Y=i(Q);return{raw:Q,lines:Y}}catch{return{raw:"",lines:[]}}}async function f0($,Z){let K=G($),Q=await v$($,Z),Y=await K.diff(["--cached","--numstat"]),V=await K.diff(["--numstat"]),X=await K.diff(["--cached"]),z=await K.diff([]),U=new Map;for(let O of Y.trim().split(`
17
+ `).filter((L)=>L)){let L=O.split("\t");if(L.length>=3){let M=L[0]==="-"?0:parseInt(L[0],10),q=L[1]==="-"?0:parseInt(L[1],10),C=L.slice(2).join("\t");U.set(C,{additions:M,deletions:q,staged:!0,unstaged:!1})}}for(let O of V.trim().split(`
18
+ `).filter((L)=>L)){let L=O.split("\t");if(L.length>=3){let M=L[0]==="-"?0:parseInt(L[0],10),q=L[1]==="-"?0:parseInt(L[1],10),C=L.slice(2).join("\t"),P=U.get(C);if(P)P.additions+=M,P.deletions+=q,P.unstaged=!0;else U.set(C,{additions:M,deletions:q,staged:!1,unstaged:!0})}}let W=await K.status(),_=new Map;for(let O of W.files)if(O.index==="A"||O.working_dir==="?")_.set(O.path,"added");else if(O.index==="D"||O.working_dir==="D")_.set(O.path,"deleted");else if(O.index==="R")_.set(O.path,"renamed");else _.set(O.path,"modified");let J=[],A=(X+z).split(/(?=^diff --git )/m).filter((O)=>O.trim()),j=new Set;for(let O of A){let L=O.match(/^diff --git a\/.+ b\/(.+)$/m);if(!L)continue;let M=L[1];if(j.has(M))continue;j.add(M);let q=i(O),C=U.get(M)||{additions:0,deletions:0},P=_.get(M)||"modified";J.push({path:M,status:P,additions:C.additions,deletions:C.deletions,diff:{raw:O,lines:q},isUncommitted:!0})}let D=new Set(Q.files.map((O)=>O.path)),R=[];for(let O of Q.files){let L=J.find((M)=>M.path===O.path);if(L)R.push(O),R.push(L);else R.push(O)}for(let O of J)if(!D.has(O.path))R.push(O);let $$=0,I$=0,Z$=new Set;for(let O of R)Z$.add(O.path),$$+=O.additions,I$+=O.deletions;return R.sort((O,L)=>O.path.localeCompare(L.path)),{baseBranch:Q.baseBranch,stats:{filesChanged:Z$.size,additions:$$,deletions:I$},files:R,commits:Q.commits,uncommittedCount:Q.uncommittedCount}}import*as g0 from"node:fs";import*as d0 from"node:path";var y2=/^diff --git a\/.+ b\/(.+)$/;function P2($){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 m2($){let Z=[],K="",Q=null,Y=()=>{if(Q&&K)Z.push({file:K,key:`${K}\x00${P2(Q.body)}`,headerLine:Q.headerLine});Q=null};for(let V of $.lines)if(V.type==="header"){Y();let X=V.content.match(y2);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 b${repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let K of m2($)){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 g0.statSync(d0.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}class k$ extends f2{repoPath;queue;hunkTimes;gitWatcher=null;workingDirWatcher=null;ignorers=new Map;_state={status:null,isLoading:!1,error:null,hunkCounts:null,stashList:[],operationInProgress:null,mtimes:null};constructor($,Z){super();this.repoPath=$,this.queue=Z,this.hunkTimes=new b$($)}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=p0();Z.add(".git");let K=T.join(this.repoPath,".gitignore");if(w.existsSync(K))Z.add(w.readFileSync(K,"utf-8"));let Q=T.join(this.repoPath,".git","info","exclude");if(w.existsSync(Q))Z.add(w.readFileSync(Q,"utf-8"));$.set("",Z);try{let Y=c2("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:n()});for(let V of Y.split("\x00")){if(!V||V===".gitignore")continue;if(!V.endsWith(".gitignore"))continue;let X=T.dirname(V),z=T.join(this.repoPath,V);try{let U=w.readFileSync(z,"utf-8"),W=p0();W.add(U),$.set(X,W)}catch(U){V0(`Failed to read ${z}: ${U instanceof Error?U.message:U}`)}}}catch{}return $}startWatching(){let $=T.join(this.repoPath,".git");if(!w.existsSync($))return;let Z=T.join($,"index"),K=T.join($,"HEAD"),Q=T.join($,"refs"),Y=T.join(this.repoPath,".gitignore");this.gitWatcher=u0([Z,K,Q,Y],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=u0(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(X)=>{let z=T.relative(this.repoPath,X);if(!z)return!1;let U=z.split("/");for(let W=0;W<U.length;W++){let _=W===0?"":U.slice(0,W).join("/"),J=this.ignorers.get(_);if(J){let x=W===0?z:U.slice(W).join("/");if(J.ignores(x))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()}statMtimes($){let Z=new Map;for(let K of $.files){if(Z.has(K.path))continue;try{Z.set(K.path,w.statSync(T.join(this.repoPath,K.path)).mtimeMs)}catch{}}return Z}scheduleRefresh(){this.queue.scheduleRefresh(async()=>{await this.doRefresh()})}scheduleStatusRefresh(){this.queue.scheduleRefresh(async()=>{try{let $=await q$(this.repoPath);if(!$.isRepo){this.updateState({status:$,isLoading:!1,error:"Not a git repository"});return}this.updateState({status:$,mtimes:this.statMtimes($),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 q$(this.repoPath);if(!$.isRepo){this.updateState({status:$,isLoading:!1,error:"Not a git repository"});return}let[Z,K,Q,Y]=await Promise.all([s(this.repoPath,void 0,!1),s(this.repoPath,void 0,!0),F$(this.repoPath),c(this.repoPath)]),V={unstaged:z$(Z.raw),staged:z$(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,mtimes:this.statMtimes($),isLoading:!1})}catch($){this.updateState({isLoading:!1,error:$ instanceof Error?$.message:"Unknown error"})}}async stage($){try{await this.queue.enqueueMutation(()=>W0(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(()=>J0(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()=>N0(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()=>G0(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"?()=>B0(this.repoPath,$.path):()=>A0(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(()=>O0(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>_0(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(()=>x0(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(()=>F$(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as g2}from"node:events";class y$ extends g2{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",()=>j0(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>I0(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>M0(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>T0(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>H0(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>V$(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>D0(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>q0(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>F0(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>S0(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>E0(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>R0(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>w0(this.repoPath))}}class h0{workingTree;remote;repoPath;constructor($){this.repoPath=$;let Z=Q0($);this.workingTree=new k$($,Z),this.remote=new y$($,Z,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()})}dispose(){this.workingTree.dispose(),Y0(this.repoPath)}}var W$=new Map;function l0($){let Z=W$.get($);if(!Z)Z=new h0($),W$.set($,Z);return Z}function P$($){let Z=W$.get($);if(Z)Z.dispose(),W$.delete($)}import*as g from"node:fs";import*as E from"node:path";async function n0($){let Z=i0($);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 J$($){let Z=i0($);if(!Z)return[];try{let Q=await G(Z).raw(["worktree","list","--porcelain"]);return p2(Q)}catch{return[]}}function o0($){let Z=null,K=-1/0;for(let Q of $){if(Q.isBare)continue;let Y=d2(Q.path);if(Y>K)K=Y,Z=Q}return Z}function d2($){let Z=u2($),K=Z?[E.join(Z,"index"),E.join(Z,"HEAD")]:[$],Q=-1/0;for(let Y of K)try{let V=g.statSync(Y).mtimeMs;if(V>Q)Q=V}catch{}return Q}function u2($){let Z=E.join($,".git");try{if(g.statSync(Z).isDirectory())return Z;let K=g.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!K)return null;let Q=K[1].trim();return E.isAbsolute(Q)?Q:E.resolve($,Q)}catch{return null}}function p2($){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 i0($){try{if(g.statSync($).isDirectory())return $;return E.dirname($)}catch{let Z=E.dirname($);return Z!==$&&g.existsSync(Z)?Z:null}}function l2($){return h2("sha256").update($).digest("hex").slice(0,12)}class m${events;byId=new Map;byPath=new Map;constructor($={}){this.events=$}async openRepo($){let Z=await n0($);if(!Z){let V=o0(await J$($));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=l0(Z);Q.workingTree.startWatching();let Y={id:l2(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),P$(Z.path),this.events.onClosed?.(Z.id),!0}disposeAll(){for(let $ of this.byId.values())P$($.path);this.byId.clear(),this.byPath.clear()}}var s0=25000;function O$($,Z,K){$.write(`event: ${Z}
20
20
  data: ${K}
21
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
22
+ `)}class c${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:(U)=>{let W=JSON.stringify(m(U));if(W===z.lastData)return;z.lastData=W;for(let _ of X)O$(_,"state-change",W)},keepAlive:setInterval(()=>{for(let U of X)U.write(`: ping
23
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
24
+ `)},s0),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(m(Z.workingTree.state));O$(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 f${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
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
26
+ `)},s0),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),O$(Z,"snapshot",JSON.stringify(K))}broadcast($,Z){let K=JSON.stringify(Z);for(let Q of this.subscribers)O$(Q,$,K)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as u from"node:fs";import*as B$ from"node:path";import{watch as n2}from"chokidar";import{EventEmitter as o2}from"node:events";import*as _$ from"node:fs";import*as A$ from"node:path";import*as g$ from"node:os";function a0($){if($.startsWith("~/"))return A$.join(g$.homedir(),$.slice(2));if($==="~")return g$.homedir();return $}function t0($){let Z=A$.dirname($);if(!_$.existsSync(Z))_$.mkdirSync(Z,{recursive:!0})}function d$($){let Z=$.split(`
27
+ `);for(let K=Z.length-1;K>=0;K--){let Q=Z[K].trim();if(Q)return Q}return""}class u$ extends o2{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=a0($);return B$.isAbsolute(Z)?Z:B$.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=u.readFileSync(this.targetFile,"utf-8"),Z=d$($);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
28
  `),process.stderr.write(` Source file: ${this.targetFile}
29
29
  `),process.stderr.write(` Raw content: "${Z}"
30
30
  `),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
31
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
32
+ `);this.lastReadPath=K,this.updateState({path:K,lastUpdate:Q,rawContent:Z})}}catch{}}start(){if(t0(this.targetFile),!u.existsSync(this.targetFile))u.writeFileSync(this.targetFile,"");try{let $=u.readFileSync(this.targetFile,"utf-8"),Z=d$($);if(Z){let K=this.processContent(Z),Q=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${Q.toISOString()}] Initial path read
33
33
  `),process.stderr.write(` Source file: ${this.targetFile}
34
34
  `),process.stderr.write(` Raw content: "${Z}"
35
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)
36
+ `);this.lastReadPath=K,this._state={path:K,lastUpdate:Q,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=n2(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 r0={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class p${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 u$(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 e0($){$.get("/health",({res:Z})=>{I(Z,200,{ok:!0,ready:!0})})}import*as x$ from"node:fs";import*as F from"node:path";function N($,Z){let K=$.getRepo(Z);if(!K)throw new B(404,`Unknown repo id: ${Z}`);return K}function v($,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 p($,Z){let K=v($,Z);if(K.startsWith("-"))throw new B(400,`Invalid "${Z}" (must not start with "-"): ${K}`);return K}function Z2($,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 h$($,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 K2($,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 h($,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 Q2($,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 k($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new B(500,"Repository status unavailable");return Z}function $2($,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 L$($,Z,K){let Q=await k($),Y=$2(Q,Z,K);if(!Y)await $.refresh(),Q=await k($),Y=$2(Q,Z,K);if(!Y)throw new B(404,`File not in status: ${Z}`);return Y}function l$($,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 Y2($){try{return await x$.promises.realpath($)}catch{return null}}async function n$($,Z){let K=await x$.promises.realpath(F.resolve($)),Q=await Y2(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 V2($,Z){let K=await x$.promises.realpath(F.resolve($)),Q=[];for(let Y of Z){let V=await Y2(F.join($,Y.path));if(V===null||V===K||V.startsWith(K+F.sep))Q.push(Y)}return Q}function o$($){return $?.code??null}function i2($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function y($,Z,K){$.clearError(),await K();let Q=$.state.error;if(Q){I(Z,i2(Q),{error:Q});return}await $.refresh(),I(Z,200,{state:m($.state)})}function s2($){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test($)?409:500}async function H($,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){I(Z,s2(V.error),{error:V.error});return}let X=$.manager.workingTree;await X.refresh(),I(Z,200,{state:m(X.state),result:V.lastResult})}function X2($,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}));I(Q,200,Y)}),$.post("/repos",async({body:Q,res:Y})=>{let V=v(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(()=>{});I(Y,X.created?201:200,{id:X.handle.id,path:X.handle.path})}),$.get("/repos/:id/worktrees",async({params:Q,res:Y})=>{let V=N(K,Q.id);I(Y,200,await J$(V.path))}),$.delete("/repos/:id",({params:Q,res:Y})=>{N(K,Q.id),K.closeRepo(Q.id),I(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 U2($){return $.trim()}async function a2($){let Z=(Q)=>Q.filter((Y)=>Y.staged).length,K=Z((await k($)).files);if(K===0)await $.refresh(),K=Z((await k($)).files);return K}function W2($,Z){let{registry:K,sse:Q}=Z;$.get("/repos/:id/status",async({params:Y,res:V})=>{let X=N(K,Y.id);await k(X.manager.workingTree);let z=m(X.manager.workingTree.state);z.operationInProgress=await c(X.path),I(V,200,z)}),$.get("/repos/:id/diff",async({params:Y,query:V,res:X})=>{let z=N(K,Y.id),U=V.get("path")??void 0,W=h(V,"staged",!1),_;if(U){let x=(await k(z.manager.workingTree)).files.some((A)=>A.path===U&&A.status==="untracked");if(x&&W)throw new B(400,`staged=true is meaningless for untracked file: ${U} (untracked files have no staged diff)`);_=x?await m0(z.path,U):await s(z.path,U,W)}else _=await s(z.path,void 0,W);z.manager.workingTree.stampDiff(_),I(X,200,_)}),$.post("/repos/:id/stage",async({params:Y,body:V,res:X})=>{let z=N(K,Y.id),U=v(V,"path"),W=z.manager.workingTree,_=await L$(W,U,!1);await y(W,X,()=>W.stage(_))}),$.post("/repos/:id/unstage",async({params:Y,body:V,res:X})=>{let z=N(K,Y.id),U=v(V,"path"),W=z.manager.workingTree,_=await L$(W,U,!0);await y(W,X,()=>W.unstage(_))}),$.post("/repos/:id/stage-all",async({params:Y,res:V})=>{let z=N(K,Y.id).manager.workingTree;await y(z,V,()=>z.stageAll())}),$.post("/repos/:id/unstage-all",async({params:Y,res:V})=>{let z=N(K,Y.id).manager.workingTree;await y(z,V,()=>z.unstageAll())}),$.post("/repos/:id/discard",async({params:Y,body:V,res:X})=>{let z=N(K,Y.id),U=v(V,"path"),W=z.manager.workingTree,_=await L$(W,U,!1);if(_.staged)throw new B(409,`Cannot discard a staged file: ${U} (unstage it first)`);await y(W,X,()=>W.discard(_))}),$.post("/repos/:id/commit",async({params:Y,body:V,res:X})=>{let z=N(K,Y.id),U=v(V,"message",{allowEmpty:!0}),W=K2(V,"amend"),_=z.manager.workingTree,J=await a2(_),x=z2(U,J,W);if(!x.valid)throw new B(400,x.error??"Invalid commit");await y(_,X,()=>_.commit(U2(U),W))}),$.post("/repos/:id/stage-hunk",async({params:Y,body:V,res:X})=>{let z=N(K,Y.id),U=v(V,"patch"),W=z.manager.workingTree;await y(W,X,()=>W.stageHunk(U))}),$.post("/repos/:id/unstage-hunk",async({params:Y,body:V,res:X})=>{let z=N(K,Y.id),U=v(V,"patch"),W=z.manager.workingTree;await y(W,X,()=>W.unstageHunk(U))}),$.get("/repos/:id/events",({params:Y,req:V,res:X})=>{let z=N(K,Y.id);Q.subscribe(Y.id,z.manager,V,X)})}async function t2($){let Z=await w$($);if(Z&&await f($,Z))return Z;if(X$($)){let K=await R$($);if(K&&await f($,K))return K}throw new B(422,"No usable base branch")}function J2($,Z){let{registry:K}=Z;$.get("/repos/:id/history",async({params:Q,query:Y,res:V})=>{let X=N(K,Q.id),z=Q2(Y,"count",100);I(V,200,await C0(X.path,z))}),$.get("/repos/:id/commits/:hash/diff",async({params:Q,res:Y})=>{let V=N(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 f(V.path,X))throw new B(404,`Unknown commit: ${X}`);I(Y,200,await c0(V.path,X))}),$.get("/repos/:id/head-message",async({params:Q,res:Y})=>{let V=N(K,Q.id);I(Y,200,{message:await L0(V.path)})}),$.get("/repos/:id/branches",async({params:Q,res:Y})=>{let V=N(K,Q.id);I(Y,200,await V$(V.path))}),$.get("/repos/:id/base-branches",async({params:Q,res:Y})=>{let V=N(K,Q.id);I(Y,200,await E$(V.path))}),$.get("/repos/:id/compare/base",async({params:Q,res:Y})=>{let V=N(K,Q.id);I(Y,200,{base:await w$(V.path)})}),$.put("/repos/:id/compare/base",async({params:Q,body:Y,res:V})=>{let X=N(K,Q.id),z=p(Y,"branch");if(!await f(X.path,z))throw new B(400,`Not a valid base ref: ${z}`);k0(X.path,z),I(V,200,{base:z})}),$.get("/repos/:id/compare",async({params:Q,query:Y,res:V})=>{let X=N(K,Q.id),z=h(Y,"uncommitted",!1),U=Y.get("base"),W;if(U!==null){if(!await f(X.path,U))throw new B(400,`Unknown base ref: ${U}`);W=U}else W=await t2(X.path);let _;try{_=z?await f0(X.path,W):await v$(X.path,W)}catch(J){if(J instanceof U$)throw new B(422,J.message);throw J}I(V,200,_)})}function O2($,Z){let{registry:K}=Z;$.post("/repos/:id/push",async({params:Q,res:Y})=>{let V=N(K,Q.id);await H(V,Y,()=>V.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:Q,res:Y})=>{let V=N(K,Q.id);await H(V,Y,()=>V.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:Q,res:Y})=>{let V=N(K,Q.id);await H(V,Y,()=>V.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:Q,body:Y,res:V})=>{let X=N(K,Q.id),z=Z2(Y,"message");await H(X,V,()=>X.manager.remote.stash(z))}),$.post("/repos/:id/stash-pop",async({params:Q,body:Y,res:V})=>{let X=N(K,Q.id),z=h$(Y,"index",{min:0,fallback:0});await H(X,V,()=>X.manager.remote.stashPop(z))}),$.post("/repos/:id/switch-branch",async({params:Q,body:Y,res:V})=>{let X=N(K,Q.id),z=p(Y,"name");await H(X,V,()=>X.manager.remote.switchBranch(z))}),$.post("/repos/:id/create-branch",async({params:Q,body:Y,res:V})=>{let X=N(K,Q.id),z=p(Y,"name");await H(X,V,()=>X.manager.remote.createBranch(z))}),$.post("/repos/:id/soft-reset",async({params:Q,body:Y,res:V})=>{let X=N(K,Q.id),z=h$(Y,"count",{min:1,fallback:1});if(!await f(X.path,`HEAD~${z}`))throw new B(400,`Cannot soft-reset ${z} commit(s): HEAD~${z} does not exist`);await H(X,V,()=>X.manager.remote.softReset(z))}),$.post("/repos/:id/cherry-pick",async({params:Q,body:Y,res:V})=>{let X=N(K,Q.id),z=p(Y,"hash");await H(X,V,()=>X.manager.remote.cherryPick(z))}),$.post("/repos/:id/revert",async({params:Q,body:Y,res:V})=>{let X=N(K,Q.id),z=p(Y,"hash");await H(X,V,()=>X.manager.remote.revertCommit(z))}),$.post("/repos/:id/abort",async({params:Q,res:Y})=>{let V=N(K,Q.id);if(!await c(V.path))throw new B(409,"No operation in progress to abort");await H(V,Y,()=>V.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:Q,res:Y})=>{let V=N(K,Q.id);if(await c(V.path)!=="rebase")throw new B(409,"No rebase in progress to continue");await H(V,Y,()=>V.manager.remote.rebaseContinue())})}import*as N$ from"node:fs";import*as r from"node:path";function i$($){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 r2=1048576,_2=5000;class G$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function A2($,Z,K,Q){let Y=K?.hideHidden??!0,V=K?.hideGitignored??!0,X=r.join($,Z),z=await N$.promises.readdir(X,{withFileTypes:!0}),U=z.map((J)=>Z?r.join(Z,J.name):J.name),W=V?await Y$($,U):new Set,_=[];for(let J of z){if(Y&&J.name.startsWith("."))continue;let x=Z?r.join(Z,J.name):J.name;if(V&&W.has(x))continue;let A=J.isDirectory(),j={name:J.name,path:x,type:A?"dir":"file"};if(Q)if(A){if(Q.directories.has(x))j.hasChanges=!0}else{let D=Q.files.get(x);if(D)j.gitStatus=D.status,j.staged=D.staged}_.push(j)}return _.sort((J,x)=>{if(J.type==="dir"&&x.type!=="dir")return-1;if(J.type!=="dir"&&x.type==="dir")return 1;return J.name.localeCompare(x.name)}),_}function e2($){let Z=Math.min($.length,8192);for(let K=0;K<Z;K++)if($[K]===0)return!0;return!1}async function B2($,Z){let K=r.join($,Z),Q=await N$.promises.stat(K);if(!Q.isFile())throw new G$(Z);if(Q.size>r2)return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:Q.size,totalLines:0};let Y=await N$.promises.readFile(K);if(e2(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>_2)V=X.slice(0,_2).join(`
38
+ `),z=!0;return{content:V,binary:!1,truncated:z,tooLarge:!1,size:Q.size,totalLines:X.length}}function x2($,Z){let{registry:K}=Z;$.get("/repos/:id/tree",async({params:Q,query:Y,res:V})=>{let X=N(K,Q.id),z=Y.get("dir")??"",U=h(Y,"hidden",!1),W=h(Y,"ignored",!1);l$(X.path,z),await n$(X.path,z);let _=await k(X.manager.workingTree),J=i$(_.files),x;try{x=await A2(X.path,z,{hideHidden:!U,hideGitignored:!W},J)}catch(A){let j=o$(A);if(j==="ENOENT")throw new B(404,`No such directory: ${z||"/"}`);if(j==="ENOTDIR")throw new B(400,`Not a directory: ${z}`);throw A}I(V,200,await V2(X.path,x))}),$.get("/repos/:id/file",async({params:Q,query:Y,res:V})=>{let X=N(K,Q.id),z=Y.get("path");if(!z)throw new B(400,'Missing "path" query parameter');l$(X.path,z),await n$(X.path,z);try{I(V,200,await B2(X.path,z))}catch(U){if(U instanceof G$)throw new B(400,U.message);let W=o$(U);if(W==="ENOENT"||W==="ENOTDIR")throw new B(404,`No such file: ${z}`);throw U}}),$.get("/repos/:id/files",async({params:Q,res:Y})=>{let V=N(K,Q.id);I(Y,200,await v0(V.path))})}function L2($,Z){let{registry:K,daemonEvents:Q,follow:Y}=Z;$.get("/events",({req:V,res:X})=>{let z=K.listRepos().map((U)=>({id:U.id,path:U.path}));Q.subscribe(V,X,z)}),$.get("/follow",({res:V})=>{I(V,200,Y?Y.state:r0)})}function $3($){if(!l.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let K=G2.connect($);K.once("connect",()=>{K.destroy(),Z(!0)}),K.once("error",()=>{K.destroy(),Z(!1)})}catch{Z(!1)}})}function j2($={}){let Z=new c$,K=new f$,Q=new m$({onOpened:(J)=>K.broadcast("repo-opened",{id:J.id,path:J.path}),onClosed:(J)=>{Z.closeRepo(J),K.broadcast("repo-closed",{id:J})}}),Y=$.followFile?new p$(Q,K,$.followFile):null,V=new C$,X={registry:Q,sse:Z,daemonEvents:K,follow:Y};e0(V),X2(V,X),W2(V,X),J2(V,X),O2(V,X),x2(V,X),L2(V,X),Y?.start();let z=$.webRoot?Z0($.webRoot):void 0,U=N2.createServer((J,x)=>{V.handle(J,x,z).catch(()=>x.end())}),W=new Set;U.on("connection",(J)=>{W.add(J),J.on("close",()=>W.delete(J))});let _=null;return{address(){return U.address()},async listen(J){if(J.socketPath){if(await $3(J.socketPath))throw Error(`diffstalkerd already running at ${J.socketPath}`);l.rmSync(J.socketPath,{force:!0})}return new Promise((x,A)=>{let j=(R)=>A(R);U.once("error",j);let D=()=>{if(U.removeListener("error",j),_)l.chmodSync(_,384);x()};if(J.fd!==void 0)U.listen({fd:J.fd},D);else if(J.socketPath)_=J.socketPath,process.umask(63),U.listen(J.socketPath,D);else if(J.port!==void 0)U.listen(J.port,J.host??"127.0.0.1",D);else A(Error("listen() requires a socketPath, a port, or an fd"))})},close(){Y?.dispose(),Z.destroy(),K.destroy(),Q.disposeAll();for(let J of W)J.destroy();return new Promise((J,x)=>{U.close((A)=>{if(_)l.rmSync(_,{force:!0});if(A)x(A);else J()})})}}}var M2="diffstalkerd.sock",K3=3,I2=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
39
39
 
40
40
  Usage: diffstalkerd [options]
41
41
 
42
42
  Options:
43
43
  --socket PATH Bind a unix socket at PATH
44
- (default: $XDG_RUNTIME_DIR/diffstalker/${N2})
44
+ (default: $XDG_RUNTIME_DIR/diffstalker/${M2})
45
45
  --port N Bind TCP port N instead of a unix socket
46
46
  --host H Host to bind with --port (default: 127.0.0.1)
47
47
  --follow-file PATH Hook file to follow (created when missing)
48
48
  (default: ~/.cache/diffstalker/target)
49
49
  --no-follow Disable follow mode (no hook-file watcher)
50
+ --web-root PATH Directory with the built web UI to serve at GET /
51
+ (default: web/ next to the daemon's compiled module;
52
+ when missing, the daemon serves the API only)
50
53
  --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};
54
+ `;function e($,Z,K){let Q=$[Z];if(Q===void 0||Q.startsWith("--"))throw Error(`${K} requires a value`);return Q}function Q3($){let Z={};for(let K=0;K<$.length;K++){let Q=$[K];switch(Q){case"--help":case"-h":return"help";case"--socket":Z.socketPath=e($,++K,"--socket");break;case"--port":if(Z.port=Number(e($,++K,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--host":Z.host=e($,++K,"--host");break;case"--follow-file":Z.followFile=e($,++K,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;case"--web-root":Z.webRoot=e($,++K,"--web-root");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 Y3(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function V3($){if($.socketPath!==void 0||$.port!==void 0)return;if(Y3()){$.fd=K3;return}let Z=r$();if(!Z)console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
55
+ Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1);j$.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=s$.join(Z,M2)}function X3($){let Z=$??Z3(new URL("web/",import.meta.url));if(j$.existsSync(Z))return Z;console.error(`diffstalkerd: web UI assets not found at ${Z}; serving API only`);return}async function z3(){process.title="diffstalkerd";let $;try{$=Q3(process.argv.slice(2))}catch(z){console.error(z instanceof Error?z.message:String(z)),console.error(I2),process.exit(2)}if($==="help"){console.log(I2);return}V3($);let Z=$.noFollow?void 0:$.followFile??s$.join(Q$(),"target"),K=X3($.webRoot),Q=j2({followFile:Z,webRoot:K});if(await Q.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}`);if(K){if(console.error(`diffstalkerd serving web UI from ${K}`),$.port!==void 0){let z=$.host??"127.0.0.1",W=z==="127.0.0.1"||z==="localhost"||z==="::1"?`http://diffstalker.localhost:${$.port}/`:`http://${z}:${$.port}/`;console.error(`diffstalkerd: web UI at ${W}`)}}let Y=!1,V=(z)=>{if(Y)return;Y=!0,console.error(`Received ${z}, shutting down`),Q.close().then(()=>process.exit(0)).catch((U)=>{console.error(U instanceof Error?U.message:String(U)),process.exit(1)})};process.on("SIGINT",()=>V("SIGINT")),process.on("SIGTERM",()=>V("SIGTERM")),process.on("SIGHUP",()=>V("SIGHUP"));let X=(z,U)=>{console.error(`diffstalkerd ${z}:`,U instanceof Error?U.stack??U.message:U),Q.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(z)=>X("uncaught exception",z)),process.on("unhandledRejection",(z)=>X("unhandled rejection",z))}z3().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{Q3 as parseArgs};