diffstalkerd 0.6.0 → 0.7.1

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
@@ -116,7 +116,8 @@ values are rejected with a 400 so they can never be parsed as git flags.
116
116
  | GET | `/repos/:id/tree?dir=&hidden=&ignored=` | One directory level (`name`, `path`, `type`), gitignored/hidden filtered by default (`hidden=true` / `ignored=true` include them, mirroring the TUI toggles), files annotated with `gitStatus` + `staged`, changed dirs with `hasChanges` (400 outside the repo root or on a file, 404 unknown dir) |
117
117
  | GET | `/repos/:id/file?path=` | File content for display with flags: `{content, binary, truncated, tooLarge, size, totalLines}` — binary/oversized come back with empty content and the flag set, never prose; 400 for anything that is not a regular file (directory, FIFO, device) or resolves outside the repo root |
118
118
  | GET | `/repos/:id/files` | All tracked + untracked (not ignored) paths: the fuzzy-finder source |
119
- | GET | `/repos/:id/events` | SSE: `snapshot` on connect, then `state-change` events from the file watcher |
119
+ | GET | `/repos/:id/journal?since=` | Append-only edit journal: `{epoch, prunedBefore, entries}`; `since=<seq>` returns only entries with a higher seq (all when omitted) |
120
+ | GET | `/repos/:id/events` | SSE: `snapshot` on connect, then `state-change` events from the file watcher and `journal-append {entries}` per journal observation |
120
121
  | GET | `/events` | Daemon-scope SSE: `snapshot` (open repos) on connect, then `repo-opened` / `repo-closed` / `follow-change` |
121
122
  | GET | `/follow` | Follow state: `{targetFile, enabled, followedRepoId, followedPath}` |
122
123
 
@@ -162,6 +163,32 @@ two: a >100KB file used to be flagged truncated regardless).
162
163
  Repo ids are stable hashes of the worktree root, so a cached id still
163
164
  addresses the same repo after a daemon restart.
164
165
 
166
+ ### Journal
167
+
168
+ `GET /repos/:id/journal` serves the repo's append-only edit journal: an
169
+ immutable, seq-ordered log of per-hunk diff blurbs plus boundary dividers
170
+ (commits, checkouts, stashes, operation transitions). Entries are
171
+ JSON-native; the embedded `diff` is a `DiffResult` in the same wire shape
172
+ as `/diff` responses.
173
+
174
+ - `entries` — those with `seq > since` (all when `since` is omitted);
175
+ `seq` is the only ordering axis, `ts` (epoch ms) is a display label.
176
+ - `epoch` — opaque string minted per journal store. A mismatch with a
177
+ client's cached epoch means the store was reset (daemon restart, LRU
178
+ eviction): discard the cache and refetch from scratch.
179
+ - `prunedBefore` — highest pruned seq, 0 when nothing is pruned. A value
180
+ above a client's last seen seq is a gap `?since` can never fill: full
181
+ refetch.
182
+
183
+ New entries stream as `journal-append {entries}` on the per-repo
184
+ `GET /repos/:id/events` channel, one event per observation (possibly
185
+ several hunks), batched so clients apply them atomically.
186
+
187
+ The journal store lives above the repo's manager lifecycle: closing a
188
+ repo's last client (a browser F5) disposes the manager but keeps the
189
+ store, so a reopen resumes the same chronology under the same epoch.
190
+ Stores are LRU-capped daemon-wide; an open repo's store is never evicted.
191
+
165
192
  ## Follow mode
166
193
 
167
194
  The daemon owns the truth, clients decide policy. It watches ONE hook file
package/dist/index.js CHANGED
@@ -1,47 +1,59 @@
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
- data: ${K}
1
+ var Y7=Object.create;var{getPrototypeOf:X7,defineProperty:j4,getOwnPropertyNames:Q7}=Object;var z7=Object.prototype.hasOwnProperty;function W7($){return this[$]}var J7,U7,G7=($,Z,V)=>{var K=$!=null&&typeof $==="object";if(K){var X=Z?J7??=new WeakMap:U7??=new WeakMap,Y=X.get($);if(Y)return Y}V=$!=null?Y7(X7($)):{};let Q=Z||!$||!$.__esModule?j4(V,"default",{value:$,enumerable:!0}):V;for(let z of Q7($))if(!z7.call(Q,z))j4(Q,z,{get:W7.bind($,z),enumerable:!0});if(K)X.set($,Q);return Q};var O7=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var I5=O7((Y9,C5)=>{var P=-1,k=1,w=0;function Y$($,Z,V,K,X){if($===Z){if($)return[[w,$]];return[]}if(V!=null){var Y=c7($,Z,V);if(Y)return Y}var Q=s$($,Z),z=$.substring(0,Q);$=$.substring(Q),Z=Z.substring(Q),Q=I$($,Z);var W=$.substring($.length-Q);$=$.substring(0,$.length-Q),Z=Z.substring(0,Z.length-Q);var J=v7($,Z);if(z)J.unshift([w,z]);if(W)J.push([w,W]);if(i$(J,X),K)y7(J);return J}function v7($,Z){var V;if(!$)return[[k,Z]];if(!Z)return[[P,$]];var K=$.length>Z.length?$:Z,X=$.length>Z.length?Z:$,Y=K.indexOf(X);if(Y!==-1){if(V=[[k,K.substring(0,Y)],[w,X],[k,K.substring(Y+X.length)]],$.length>Z.length)V[0][0]=V[2][0]=P;return V}if(X.length===1)return[[P,$],[k,Z]];var Q=P7($,Z);if(Q){var z=Q[0],W=Q[1],J=Q[2],G=Q[3],U=Q[4],B=Y$(z,J),O=Y$(W,G);return B.concat([[w,U]],O)}return k7($,Z)}function k7($,Z){var V=$.length,K=Z.length,X=Math.ceil((V+K)/2),Y=X,Q=2*X,z=Array(Q),W=Array(Q);for(var J=0;J<Q;J++)z[J]=-1,W[J]=-1;z[Y+1]=0,W[Y+1]=0;var G=V-K,U=G%2!==0,B=0,O=0,N=0,T=0;for(var R=0;R<X;R++){for(var L=-R+B;L<=R-O;L+=2){var S=Y+L,q;if(L===-R||L!==R&&z[S-1]<z[S+1])q=z[S+1];else q=z[S-1]+1;var M=q-L;while(q<V&&M<K&&$.charAt(q)===Z.charAt(M))q++,M++;if(z[S]=q,q>V)O+=2;else if(M>K)B+=2;else if(U){var j=Y+G-L;if(j>=0&&j<Q&&W[j]!==-1){var A=V-W[j];if(q>=A)return U5($,Z,q,M)}}}for(var E=-R+N;E<=R-T;E+=2){var j=Y+E,A;if(E===-R||E!==R&&W[j-1]<W[j+1])A=W[j+1];else A=W[j-1]+1;var F=A-E;while(A<V&&F<K&&$.charAt(V-A-1)===Z.charAt(K-F-1))A++,F++;if(W[j]=A,A>V)T+=2;else if(F>K)N+=2;else if(!U){var S=Y+G-E;if(S>=0&&S<Q&&z[S]!==-1){var q=z[S],M=Y+q-S;if(A=V-A,q>=A)return U5($,Z,q,M)}}}}return[[P,$],[k,Z]]}function U5($,Z,V,K){var X=$.substring(0,V),Y=Z.substring(0,K),Q=$.substring(V),z=Z.substring(K),W=Y$(X,Y),J=Y$(Q,z);return W.concat(J)}function s$($,Z){if(!$||!Z||$.charAt(0)!==Z.charAt(0))return 0;var V=0,K=Math.min($.length,Z.length),X=K,Y=0;while(V<X){if($.substring(Y,X)==Z.substring(Y,X))V=X,Y=V;else K=X;X=Math.floor((K-V)/2+V)}if(j5($.charCodeAt(X-1)))X--;return X}function G5($,Z){var V=$.length,K=Z.length;if(V==0||K==0)return 0;if(V>K)$=$.substring(V-K);else if(V<K)Z=Z.substring(0,V);var X=Math.min(V,K);if($==Z)return X;var Y=0,Q=1;while(!0){var z=$.substring(X-Q),W=Z.indexOf(z);if(W==-1)return Y;if(Q+=W,W==0||$.substring(X-Q)==Z.substring(0,Q))Y=Q,Q++}}function I$($,Z){if(!$||!Z||$.slice(-1)!==Z.slice(-1))return 0;var V=0,K=Math.min($.length,Z.length),X=K,Y=0;while(V<X){if($.substring($.length-X,$.length-Y)==Z.substring(Z.length-X,Z.length-Y))V=X,Y=V;else K=X;X=Math.floor((K-V)/2+V)}if(N5($.charCodeAt($.length-X)))X--;return X}function P7($,Z){var V=$.length>Z.length?$:Z,K=$.length>Z.length?Z:$;if(V.length<4||K.length*2<V.length)return null;function X(O,N,T){var R=O.substring(T,T+Math.floor(O.length/4)),L=-1,S="",q,M,j,A;while((L=N.indexOf(R,L+1))!==-1){var E=s$(O.substring(T),N.substring(L)),F=I$(O.substring(0,T),N.substring(0,L));if(S.length<F+E)S=N.substring(L-F,L)+N.substring(L,L+E),q=O.substring(0,T-F),M=O.substring(T+E),j=N.substring(0,L-F),A=N.substring(L+E)}if(S.length*2>=O.length)return[q,M,j,A,S];else return null}var Y=X(V,K,Math.ceil(V.length/4)),Q=X(V,K,Math.ceil(V.length/2)),z;if(!Y&&!Q)return null;else if(!Q)z=Y;else if(!Y)z=Q;else z=Y[4].length>Q[4].length?Y:Q;var W,J,G,U;if($.length>Z.length)W=z[0],J=z[1],G=z[2],U=z[3];else G=z[0],U=z[1],W=z[2],J=z[3];var B=z[4];return[W,J,G,U,B]}function y7($){var Z=!1,V=[],K=0,X=null,Y=0,Q=0,z=0,W=0,J=0;while(Y<$.length){if($[Y][0]==w)V[K++]=Y,Q=W,z=J,W=0,J=0,X=$[Y][1];else{if($[Y][0]==k)W+=$[Y][1].length;else J+=$[Y][1].length;if(X&&X.length<=Math.max(Q,z)&&X.length<=Math.max(W,J))$.splice(V[K-1],0,[P,X]),$[V[K-1]+1][0]=k,K--,K--,Y=K>0?V[K-1]:-1,Q=0,z=0,W=0,J=0,X=null,Z=!0}Y++}if(Z)i$($);x7($),Y=1;while(Y<$.length){if($[Y-1][0]==P&&$[Y][0]==k){var G=$[Y-1][1],U=$[Y][1],B=G5(G,U),O=G5(U,G);if(B>=O){if(B>=G.length/2||B>=U.length/2)$.splice(Y,0,[w,U.substring(0,B)]),$[Y-1][1]=G.substring(0,G.length-B),$[Y+1][1]=U.substring(B),Y++}else if(O>=G.length/2||O>=U.length/2)$.splice(Y,0,[w,G.substring(0,O)]),$[Y-1][0]=k,$[Y-1][1]=U.substring(0,U.length-O),$[Y+1][0]=P,$[Y+1][1]=G.substring(O),Y++;Y++}Y++}}var O5=/[^a-zA-Z0-9]/,B5=/\s/,M5=/[\r\n]/,b7=/\n\r?\n$/,_7=/^\r?\n\r?\n/;function x7($){function Z(O,N){if(!O||!N)return 6;var T=O.charAt(O.length-1),R=N.charAt(0),L=T.match(O5),S=R.match(O5),q=L&&T.match(B5),M=S&&R.match(B5),j=q&&T.match(M5),A=M&&R.match(M5),E=j&&O.match(b7),F=A&&N.match(_7);if(E||F)return 5;else if(j||A)return 4;else if(L&&!q&&M)return 3;else if(q||M)return 2;else if(L||S)return 1;return 0}var V=1;while(V<$.length-1){if($[V-1][0]==w&&$[V+1][0]==w){var K=$[V-1][1],X=$[V][1],Y=$[V+1][1],Q=I$(K,X);if(Q){var z=X.substring(X.length-Q);K=K.substring(0,K.length-Q),X=z+X.substring(0,X.length-Q),Y=z+Y}var W=K,J=X,G=Y,U=Z(K,X)+Z(X,Y);while(X.charAt(0)===Y.charAt(0)){K+=X.charAt(0),X=X.substring(1)+Y.charAt(0),Y=Y.substring(1);var B=Z(K,X)+Z(X,Y);if(B>=U)U=B,W=K,J=X,G=Y}if($[V-1][1]!=W){if(W)$[V-1][1]=W;else $.splice(V-1,1),V--;if($[V][1]=J,G)$[V+1][1]=G;else $.splice(V+1,1),V--}}V++}}function i$($,Z){$.push([w,""]);var V=0,K=0,X=0,Y="",Q="",z;while(V<$.length){if(V<$.length-1&&!$[V][1]){$.splice(V,1);continue}switch($[V][0]){case k:X++,Q+=$[V][1],V++;break;case P:K++,Y+=$[V][1],V++;break;case w:var W=V-X-K-1;if(Z){if(W>=0&&A5($[W][1])){var J=$[W][1].slice(-1);if($[W][1]=$[W][1].slice(0,-1),Y=J+Y,Q=J+Q,!$[W][1]){$.splice(W,1),V--;var G=W-1;if($[G]&&$[G][0]===k)X++,Q=$[G][1]+Q,G--;if($[G]&&$[G][0]===P)K++,Y=$[G][1]+Y,G--;W=G}}if(H5($[V][1])){var J=$[V][1].charAt(0);$[V][1]=$[V][1].slice(1),Y+=J,Q+=J}}if(V<$.length-1&&!$[V][1]){$.splice(V,1);break}if(Y.length>0||Q.length>0){if(Y.length>0&&Q.length>0){if(z=s$(Q,Y),z!==0){if(W>=0)$[W][1]+=Q.substring(0,z);else $.splice(0,0,[w,Q.substring(0,z)]),V++;Q=Q.substring(z),Y=Y.substring(z)}if(z=I$(Q,Y),z!==0)$[V][1]=Q.substring(Q.length-z)+$[V][1],Q=Q.substring(0,Q.length-z),Y=Y.substring(0,Y.length-z)}var U=X+K;if(Y.length===0&&Q.length===0)$.splice(V-U,U),V=V-U;else if(Y.length===0)$.splice(V-U,U,[k,Q]),V=V-U+1;else if(Q.length===0)$.splice(V-U,U,[P,Y]),V=V-U+1;else $.splice(V-U,U,[P,Y],[k,Q]),V=V-U+2}if(V!==0&&$[V-1][0]===w)$[V-1][1]+=$[V][1],$.splice(V,1);else V++;X=0,K=0,Y="",Q="";break}}if($[$.length-1][1]==="")$.pop();var B=!1;V=1;while(V<$.length-1){if($[V-1][0]===w&&$[V+1][0]===w){if($[V][1].substring($[V][1].length-$[V-1][1].length)===$[V-1][1])$[V][1]=$[V-1][1]+$[V][1].substring(0,$[V][1].length-$[V-1][1].length),$[V+1][1]=$[V-1][1]+$[V+1][1],$.splice(V-1,1),B=!0;else if($[V][1].substring(0,$[V+1][1].length)==$[V+1][1])$[V-1][1]+=$[V+1][1],$[V][1]=$[V][1].substring($[V+1][1].length)+$[V+1][1],$.splice(V+1,1),B=!0}V++}if(B)i$($,Z)}function j5($){return $>=55296&&$<=56319}function N5($){return $>=56320&&$<=57343}function H5($){return N5($.charCodeAt(0))}function A5($){return j5($.charCodeAt($.length-1))}function m7($){var Z=[];for(var V=0;V<$.length;V++)if($[V][1].length>0)Z.push($[V]);return Z}function o$($,Z,V,K){if(A5($)||H5(K))return null;return m7([[w,$],[P,Z],[k,V],[w,K]])}function c7($,Z,V){var K=typeof V==="number"?{index:V,length:0}:V.oldRange,X=typeof V==="number"?null:V.newRange,Y=$.length,Q=Z.length;if(K.length===0&&(X===null||X.length===0)){var z=K.index,W=$.slice(0,z),J=$.slice(z),G=X?X.index:null;$:{var U=z+Q-Y;if(G!==null&&G!==U)break $;if(U<0||U>Q)break $;var B=Z.slice(0,U),O=Z.slice(U);if(O!==J)break $;var N=Math.min(z,U),T=W.slice(0,N),R=B.slice(0,N);if(T!==R)break $;var L=W.slice(N),S=B.slice(N);return o$(T,L,S,J)}$:{if(G!==null&&G!==z)break $;var q=z,B=Z.slice(0,q),O=Z.slice(q);if(B!==W)break $;var M=Math.min(Y-q,Q-q),j=J.slice(J.length-M),A=O.slice(O.length-M);if(j!==A)break $;var L=J.slice(0,J.length-M),S=O.slice(0,O.length-M);return o$(W,L,S,j)}}if(K.length>0&&X&&X.length===0)$:{var T=$.slice(0,K.index),j=$.slice(K.index+K.length),N=T.length,M=j.length;if(Q<N+M)break $;var R=Z.slice(0,N),A=Z.slice(Q-M);if(T!==R||j!==A)break $;var L=$.slice(N,Y-M),S=Z.slice(N,Q-M);return o$(T,L,S,j)}return null}function T$($,Z,V,K){return Y$($,Z,V,K,!0)}T$.INSERT=k;T$.DELETE=P;T$.EQUAL=w;C5.exports=T$});import*as b$ from"node:fs";import*as M4 from"node:path";import{fileURLToPath as D8}from"node:url";import*as N4 from"node:os";import*as W$ from"node:path";var H4="diffstalker";function J$(){return W$.join(process.env.XDG_CACHE_HOME||W$.join(N4.homedir(),".cache"),H4)}function A4(){return process.env.XDG_RUNTIME_DIR?W$.join(process.env.XDG_RUNTIME_DIR,H4):null}import*as e5 from"node:http";import*as t from"node:fs";import*as $7 from"node:net";function _$($){let Z={};for(let[V,K]of $)Z[V]=K;return Z}function B7($){if(!$)return null;return{staged:_$($.staged),unstaged:_$($.unstaged)}}function d($){return{status:$.status,hunkCounts:B7($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress,mtimes:$.mtimes?_$($.mtimes):null}}function x$($){return $}function M7($){return $.entries.length>0?$.entries[0].seq-1:$.nextSeq-1}function C4($,Z){let V=Z>0?$.entries.filter((K)=>K.seq>Z):$.entries;return{epoch:$.epoch,prunedBefore:M7($),entries:x$(V)}}function V$($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[V,K]of $)Z[String(V)]=V$(K);return Z}if(Array.isArray($))return $.map(V$);if($!==null&&typeof $==="object"){let Z={};for(let[V,K]of Object.entries($))Z[V]=V$(K);return Z}return $}var j7=1048576;class H extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function D($,Z,V){let K=JSON.stringify(V$(V));$.writeHead(Z,{"content-type":"application/json"}),$.end(K)}function N7($,Z){if($.segments.length!==Z.length)return null;let V={};for(let K=0;K<$.segments.length;K++){let X=$.segments[K];if(X.startsWith(":"))try{V[X.slice(1)]=decodeURIComponent(Z[K])}catch{throw new H(400,`Malformed percent-encoding in path: ${Z[K]}`)}else if(X!==Z[K])return null}return V}async function H7($){if($.method!=="POST"&&$.method!=="PUT"&&$.method!=="PATCH")return;let Z=[],V=0;for await(let X of $){let Y=X;if(V+=Y.length,V>j7)throw new H(413,"Request body too large");Z.push(Y)}let K=Buffer.concat(Z).toString("utf-8");if(!K.trim())return;try{return JSON.parse(K)}catch{throw new H(400,"Invalid JSON body")}}class m${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,V){this.routes.push({method:$,segments:Z.split("/").filter(Boolean),handler:V})}match($,Z){for(let V of this.routes){if(V.method!==$)continue;let K=N7(V,Z);if(K)return{handler:V.handler,params:K}}return null}async handle($,Z,V){try{let K=new URL($.url??"/","http://localhost"),X=K.pathname.split("/").filter(Boolean),Y=$.method??"GET",Q=this.match(Y,X);if(!Q){if(V&&Y==="GET"){await V($,Z,K.pathname);return}throw new H(404,`Unknown route: ${Y} ${K.pathname}`)}let z=await H7($);await Q.handler({req:$,res:Z,params:Q.params,query:K.searchParams,body:z})}catch(K){if(Z.headersSent){Z.end();return}let X=K instanceof H?K.status:500,Y=K instanceof Error?K.message:String(K);D(Z,X,{error:Y})}}}import*as c$ from"node:fs";import*as x from"node:path";var A7=new Set(["health","repos","events","follow"]),C7={".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"},I4="no-cache",I7="public, max-age=31536000, immutable";async function T4($,Z,V){let K;try{K=await c$.promises.readFile(Z)}catch{throw new H(404,`Not found: ${x.basename(Z)}`)}$.writeHead(200,{"content-type":C7[x.extname(Z)]??"application/octet-stream","cache-control":V,"content-length":K.length}),$.end(K)}function L4($){let Z=x.resolve($);return async(V,K,X)=>{let Y;try{Y=decodeURIComponent(X)}catch{throw new H(400,`Malformed percent-encoding in path: ${X}`)}if(Y.includes("\x00"))throw new H(400,"Invalid path");let Q=Y.split("/").filter(Boolean);if(Q.length>0&&A7.has(Q[0]))throw new H(404,`Unknown route: GET ${X}`);let z=Q.length>0?x.resolve(Z,Q.join("/")):Z;if(z!==Z&&!z.startsWith(Z+x.sep))throw new H(403,"Forbidden");if((await c$.promises.stat(z).catch(()=>null))?.isFile()){await T4(K,z,Q[0]==="assets"?I7:I4);return}await T4(K,x.join(Z,"index.html"),I4)}}import{createHash as U8}from"node:crypto";class D4{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue($){return new Promise((Z,V)=>{this.queue.push({execute:$,resolve:Z,reject:V}),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 g$=new Map;function R4($){let Z=g$.get($);if(!Z)Z=new D4,g$.set($,Z);return Z}function q4($){g$.delete($)}import*as v from"node:path";import*as b from"node:fs";import{execFileSync as p7}from"node:child_process";import{watch as T5}from"chokidar";import{EventEmitter as h7}from"node:events";import L5 from"ignore";function U$($){process.stderr.write(`[diffstalker warn] ${$}
2
+ `)}import{simpleGit as T7}from"simple-git";function e(){return{...process.env,LC_ALL:"C",LANG:"C"}}var L7={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0};function I($){return T7({baseDir:$,unsafe:L7}).env(e())}import{execFileSync as w4}from"node:child_process";import*as $$ from"node:fs";import*as u$ from"node:path";async function G$($,Z){if(Z.length===0)return new Set;let V=I($),K=new Set,X=100;for(let Y=0;Y<Z.length;Y+=X){let Q=Z.slice(Y,Y+X);try{let W=(await V.raw(["check-ignore","--",...Q])).trim().split(`
3
+ `).filter((J)=>J.length>0);for(let J of W)K.add(J)}catch{}}return K}function S4($){let Z=new Map;for(let V of $.trim().split(`
4
+ `)){if(!V)continue;let K=V.split("\t");if(K.length>=3){let X=K[0]==="-"?0:parseInt(K[0],10),Y=K[1]==="-"?0:parseInt(K[1],10),Q=K.slice(2).join("\t");Z.set(Q,{insertions:X,deletions:Y})}}return Z}async function D7($,Z){try{let V=u$.join($,Z);if(!(await $$.promises.stat(V)).isFile())return 0;return(await $$.promises.readFile(V,"utf-8")).split(`
5
+ `).filter((Y)=>Y.length>0).length}catch{return 0}}function E4($){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 p$($){let Z=I($);if(!await Z.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let K=await Z.status(),X=[],Y=new Set,Q=K.files.filter((O)=>O.working_dir==="?").map((O)=>O.path),z=await G$($,Q);for(let O of K.files){if(O.index==="!"||O.working_dir==="!"||z.has(O.path))continue;let N=`${O.path}-${O.index!==" "&&O.index!=="?"}`;if(Y.has(N))continue;if(Y.add(N),O.index&&O.index!==" "&&O.index!=="?")X.push({path:O.path,status:E4(O.index),staged:!0});if(O.working_dir&&O.working_dir!==" ")X.push({path:O.path,status:O.working_dir==="?"?"untracked":E4(O.working_dir),staged:!1})}let[W,J]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),G=S4(W),U=S4(J);for(let O of X){let N=O.staged?G.get(O.path):U.get(O.path);if(N)O.insertions=N.insertions,O.deletions=N.deletions}let B=X.filter((O)=>O.status==="untracked");if(B.length>0){let O=await Promise.all(B.map((N)=>D7($,N.path)));for(let N=0;N<B.length;N++)B[N].insertions=O[N],B[N].deletions=0}return{files:X,branch:{current:K.current||"HEAD",tracking:K.tracking||void 0,ahead:K.ahead,behind:K.behind},isRepo:!0}}async function v4($,Z){await I($).add(["--",Z])}async function k4($,Z){await I($).reset(["HEAD","--",Z])}async function P4($){await I($).add("-A")}async function y4($){await I($).reset(["HEAD"])}async function b4($,Z){await I($).checkout(["--",Z])}async function _4($,Z){await I($).clean("f",["--",Z])}async function x4($,Z,V=!1){if(!(await I($).commit(Z,void 0,V?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function m4($){let Z=I($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function c4($,Z){w4("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:e()})}function g4($,Z){w4("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:e()})}async function u4($){let K=(await I($).push()).pushed;if(K.length===0)return"Everything up-to-date";return K.map((X)=>`${X.local} → ${X.remote}`).join(", ")}async function p4($){return await I($).fetch(),"Fetch complete"}async function h4($){let V=await I($).pull(["--rebase"]);if(V.summary.changes===0&&V.summary.insertions===0&&V.summary.deletions===0)return"Already up-to-date";return`${V.summary.changes} file(s) changed`}async function f4($,Z=50){let V=I($);try{return(await V.log({n:Z})).all.map((X)=>({hash:X.hash,shortHash:X.hash.slice(0,7),message:X.message.split(`
6
+ `)[0],author:X.author_name,date:new Date(X.date),refs:X.refs||""}))}catch{return[]}}async function O$($){let Z=I($);try{return(await Z.stashList()).all.map((K,X)=>({index:X,message:K.message}))}catch{return[]}}async function d4($,Z){let V=I($),K=["push"];if(Z)K.push("-m",Z);return await V.stash(K),"Stashed"}async function l4($,Z=0){let V=I($);await V.stash(["pop",`stash@{${Z}}`]);let K=(await V.raw(["diff","--name-only","--diff-filter=U"])).trim();if(K)throw Error(`Stash pop hit conflicts in: ${K.split(`
7
+ `).join(", ")}`);return"Stash popped"}async function B$($){let V=await I($).branchLocal();return V.all.map((K)=>({name:K,current:K===V.current,tracking:V.branches[K]?.label||void 0}))}async function n4($,Z){return await I($).raw(["switch","--",Z]),`Switched to ${Z}`}async function a4($,Z){return await I($).raw(["switch","-c",Z]),`Created ${Z}`}async function o4($,Z=1){return await I($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function s4($,Z){return await I($).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function i4($,Z){return await I($).raw(["revert","--no-edit","--end-of-options",Z]),"Reverted"}async function g($){let Z=I($),V;try{V=(await Z.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let K=(X)=>$$.existsSync(u$.join(V,X));if(K("rebase-merge")||K("rebase-apply"))return"rebase";if(K("CHERRY_PICK_HEAD"))return"cherry-pick";if(K("REVERT_HEAD"))return"revert";if(K("MERGE_HEAD"))return"merge";return null}async function r4($){let Z=await g($);if(!Z)throw Error("No operation in progress to abort");return await I($).raw([Z,"--abort"]),`Aborted ${Z}`}async function t4($){return await I($).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function e4($){return(await I($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((K)=>K.length>0)}import*as K5 from"node:fs";import*as K$ from"node:path";import*as u from"node:fs";import*as a from"node:path";function h$(){return a.join(J$(),"base-branches.json")}function R7(){let $=a.dirname(h$());if(!u.existsSync($))u.mkdirSync($,{recursive:!0})}function $5(){try{let $=h$();if(u.existsSync($))return JSON.parse(u.readFileSync($,"utf-8"))}catch{}return{}}function q7($){R7(),u.writeFileSync(h$(),JSON.stringify($,null,2)+`
8
+ `)}function M$($){let Z=$5(),V=a.resolve($);return Z[V]}function Z5($,Z){let V=$5(),K=a.resolve($);V[K]=Z,q7(V)}function V5($){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 V=[],K=0,X=0;for(let Y of Z)if(Y.startsWith("diff --git")||Y.startsWith("index ")||Y.startsWith("---")||Y.startsWith("+++")||Y.startsWith("new file")||Y.startsWith("deleted file")||Y.startsWith("Binary files")||Y.startsWith("similarity index")||Y.startsWith("rename from")||Y.startsWith("rename to"))V.push({type:"header",content:Y});else if(Y.startsWith("@@")){let Q=V5(Y);if(Q)K=Q.oldStart,X=Q.newStart;V.push({type:"hunk",content:Y})}else if(Y.startsWith("+"))V.push({type:"addition",content:Y,newLineNum:X++});else if(Y.startsWith("-"))V.push({type:"deletion",content:Y,oldLineNum:K++});else V.push({type:"context",content:Y,oldLineNum:K++,newLineNum:X++});return V}function j$($){let Z=new Map;if(!$)return Z;let V=null;for(let K of $.split(`
10
+ `))if(K.startsWith("diff --git")){let X=K.match(/^diff --git a\/.+ b\/(.+)$/);if(X){if(V=X[1],!Z.has(V))Z.set(V,0)}}else if(K.startsWith("@@")&&V)Z.set(V,(Z.get(V)??0)+1);return Z}class N$ extends Error{constructor($){super(`No common history with ${$}`);this.name="NoCommonHistoryError"}}async function Z$($,Z,V=!1){let K=I($);try{let X=[];if(V)X.push("--cached");if(Z)X.push("--",Z);let Y=await K.diff(X),Q=o(Y);return{raw:Y,lines:Q}}catch{return{raw:"",lines:[]}}}var F7="4b825dc642cb6eb9a060e54bf8d69288fbee4904",Y5="(unborn)",S7=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function H$($){let Z=I($);try{return(await Z.raw(["rev-parse","HEAD"])).trim()}catch(V){let K=V instanceof Error?V.message:String(V);if(S7.test(K))return Y5;throw V}}async function X5($){let Z=I($),K=await H$($)===Y5?F7:"HEAD",X=await Z.raw(["diff","-U3",K,"--"]);return{raw:X,lines:o(X)}}async function A$($,Z){try{let V=K$.resolve($),K=K$.resolve(V,Z);if(K!==V&&!K.startsWith(V+K$.sep))return{raw:"",lines:[]};let X=K5.readFileSync(K,"utf-8"),Y=[{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}`}],Q=X.endsWith(`
11
+ `),z=X.split(`
12
+ `);if(Q)z.pop();if(X.length>0){Y.push({type:"hunk",content:`@@ -0,0 +1,${z.length} @@`});let J=1;for(let G of z)Y.push({type:"addition",content:"+"+G,newLineNum:J++});if(!Q)Y.push({type:"context",content:"\"})}return{raw:Y.map((J)=>J.content).join(`
13
+ `),lines:Y}}catch{return{raw:"",lines:[]}}}async function f$($){let Z=I($),V=new Set,K=[];try{let X=await Z.raw(["log","--oneline","--decorate=short","--all","-n","200"]),Y=/\(([^)]+)\)/g;for(let Q of X.split(`
14
+ `)){let z=Y.exec(Q);if(z){let W=z[1].split(",").map((J)=>J.trim());for(let J of W){if(J.startsWith("HEAD")||J.startsWith("tag:")||!J.includes("/"))continue;let G=J.replace(/^.*-> /,"");if(G.includes("/")&&!V.has(G))V.add(G),K.push(G)}}Y.lastIndex=0}if(K.length>0)K.sort((Q,z)=>{let W=Q.split("/").slice(1).join("/"),J=z.split("/").slice(1).join("/"),G=W==="main"||W==="master",U=J==="main"||J==="master";if(G&&!U)return-1;if(!G&&U)return 1;if(G&&U){let B=Q.startsWith("origin/"),O=z.startsWith("origin/");if(B&&!O)return 1;if(!B&&O)return-1}return 0})}catch{}return[...new Set(K)]}async function d$($){return(await f$($))[0]??null}async function l$($){return M$($)??await d$($)}async function l($,Z){let V=I($);try{return await V.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}async function n$($,Z){let V=I($),X=(await V.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!X)throw new N$(Z);let Y=await V.raw(["diff","--numstat",`${X}...HEAD`]),Q=await V.raw(["diff","--name-status",`${X}...HEAD`]),z=await V.raw(["diff",`${X}...HEAD`]),W=Y.trim().split(`
15
+ `).filter((M)=>M),J=new Map;for(let M of W){let j=M.split("\t");if(j.length>=3){let A=j[0]==="-"?0:parseInt(j[0],10),E=j[1]==="-"?0:parseInt(j[1],10),F=j.slice(2).join("\t");J.set(F,{additions:A,deletions:E})}}let G=Q.trim().split(`
16
+ `).filter((M)=>M),U=new Map;for(let M of G){let j=M.split("\t");if(j.length>=2){let A=j[0][0],E=j[j.length-1],F;switch(A){case"A":F="added";break;case"D":F="deleted";break;case"R":F="renamed";break;default:F="modified"}U.set(E,F)}}let B=[],O=z.split(/(?=^diff --git )/m).filter((M)=>M.trim());for(let M of O){let j=M.match(/^diff --git a\/.+ b\/(.+)$/m);if(!j)continue;let A=j[1],E=o(M),F=J.get(A)||{additions:0,deletions:0},f=U.get(A)||"modified";B.push({path:A,status:f,additions:F.additions,deletions:F.deletions,diff:{raw:M,lines:E}})}let N=0,T=0;for(let M of B)N+=M.additions,T+=M.deletions;let L=(await V.status()).files.length,q=(await V.log({from:X,to:"HEAD"})).all.map((M)=>({hash:M.hash,shortHash:M.hash.slice(0,7),message:M.message.split(`
17
+ `)[0],author:M.author_name,date:new Date(M.date),refs:M.refs||""}));return B.sort((M,j)=>M.path.localeCompare(j.path)),{baseBranch:Z,stats:{filesChanged:B.length,additions:N,deletions:T},files:B,commits:q,uncommittedCount:L}}async function Q5($,Z){let V=I($);try{let K=await V.raw(["show","--format=","--end-of-options",Z]),X=o(K);return{raw:K,lines:X}}catch{return{raw:"",lines:[]}}}async function z5($,Z){let V=I($),K=await n$($,Z),X=await V.diff(["--cached","--numstat"]),Y=await V.diff(["--numstat"]),Q=await V.diff(["--cached"]),z=await V.diff([]),W=new Map;for(let M of X.trim().split(`
18
+ `).filter((j)=>j)){let j=M.split("\t");if(j.length>=3){let A=j[0]==="-"?0:parseInt(j[0],10),E=j[1]==="-"?0:parseInt(j[1],10),F=j.slice(2).join("\t");W.set(F,{additions:A,deletions:E,staged:!0,unstaged:!1})}}for(let M of Y.trim().split(`
19
+ `).filter((j)=>j)){let j=M.split("\t");if(j.length>=3){let A=j[0]==="-"?0:parseInt(j[0],10),E=j[1]==="-"?0:parseInt(j[1],10),F=j.slice(2).join("\t"),f=W.get(F);if(f)f.additions+=A,f.deletions+=E,f.unstaged=!0;else W.set(F,{additions:A,deletions:E,staged:!1,unstaged:!0})}}let J=await V.status(),G=new Map;for(let M of J.files)if(M.index==="A"||M.working_dir==="?")G.set(M.path,"added");else if(M.index==="D"||M.working_dir==="D")G.set(M.path,"deleted");else if(M.index==="R")G.set(M.path,"renamed");else G.set(M.path,"modified");let U=[],O=(Q+z).split(/(?=^diff --git )/m).filter((M)=>M.trim()),N=new Set;for(let M of O){let j=M.match(/^diff --git a\/.+ b\/(.+)$/m);if(!j)continue;let A=j[1];if(N.has(A))continue;N.add(A);let E=o(M),F=W.get(A)||{additions:0,deletions:0},f=G.get(A)||"modified";U.push({path:A,status:f,additions:F.additions,deletions:F.deletions,diff:{raw:M,lines:E},isUncommitted:!0})}let T=new Set(K.files.map((M)=>M.path)),R=[];for(let M of K.files){let j=U.find((A)=>A.path===M.path);if(j)R.push(M),R.push(j);else R.push(M)}for(let M of U)if(!T.has(M.path))R.push(M);let L=0,S=0,q=new Set;for(let M of R)q.add(M.path),L+=M.additions,S+=M.deletions;return R.sort((M,j)=>M.path.localeCompare(j.path)),{baseBranch:K.baseBranch,stats:{filesChanged:q.size,additions:L,deletions:S},files:R,commits:K.commits,uncommittedCount:K.uncommittedCount}}import*as W5 from"node:fs";import*as J5 from"node:path";var E7=/^diff --git a\/.+ b\/(.+)$/;function C$($){let Z=5381;for(let V of $){for(let K=0;K<V.length;K++)Z=(Z<<5)+Z+V.charCodeAt(K)|0;Z=(Z<<5)+Z+10|0}return(Z>>>0).toString(36)}function w7($){let Z=[],V="",K=null,X=()=>{if(K&&V)Z.push({file:V,key:`${V}\x00${C$(K.body)}`,headerLine:K.headerLine});K=null};for(let Y of $.lines)if(Y.type==="header"){X();let Q=Y.content.match(E7);if(Q)V=Q[1]}else if(Y.type==="hunk")X(),K={headerLine:Y,body:[]};else if(K&&(Y.type==="addition"||Y.type==="deletion"))K.body.push(Y.content);return X(),Z}class a${repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let V of w7($)){let K=this.stamps.get(V.key);if(K===void 0){let X=Z.get(V.file);if(X===void 0)X=this.mtimeOf(V.file),Z.set(V.file,X);K=X,this.stamps.set(V.key,K)}V.headerLine.editedAt=K}}prune($){for(let Z of this.stamps.keys()){let V=Z.slice(0,Z.indexOf("\x00"));if(!$.has(V))this.stamps.delete(Z)}}mtimeOf($){try{return W5.statSync(J5.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}var g7=G7(I5(),1);var u7=/^diff --git a\/.+ b\/(.+)$/;function r$($){return u7.exec($)?.[1]??null}function L$($){let Z=new Map,V=$.raw.split(`
20
+ `);if(V.length>1&&V[V.length-1]==="")V.pop();let K=null;for(let Q of V){if(Q.startsWith("diff --git")){let z=r$(Q);if(z!==null)K=Z.get(z)??{rawLines:[],lines:[]},Z.set(z,K)}K?.rawLines.push(Q)}let X=null;for(let Q of $.lines){if(Q.type==="header"){let z=r$(Q.content);if(z!==null)X=Z.get(z)?.lines??null}X?.push(Q)}let Y=new Map;for(let[Q,z]of Z)Y.set(Q,{raw:z.rawLines.join(`
21
+ `)+`
22
+ `,lines:z.lines});return Y}var D$="diffstalker-journal: oversize untracked snapshot omitted";var f7=262144;class R$ extends h7{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 a$($)}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=L5();Z.add(".git");let V=v.join(this.repoPath,".gitignore");if(b.existsSync(V))Z.add(b.readFileSync(V,"utf-8"));let K=v.join(this.repoPath,".git","info","exclude");if(b.existsSync(K))Z.add(b.readFileSync(K,"utf-8"));$.set("",Z);try{let X=p7("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:e()});for(let Y of X.split("\x00")){if(!Y||Y===".gitignore")continue;if(!Y.endsWith(".gitignore"))continue;let Q=v.dirname(Y),z=v.join(this.repoPath,Y);try{let W=b.readFileSync(z,"utf-8"),J=L5();J.add(W),$.set(Q,J)}catch(W){U$(`Failed to read ${z}: ${W instanceof Error?W.message:W}`)}}}catch{}return $}startWatching(){let $=v.join(this.repoPath,".git");if(!b.existsSync($))return;let Z=v.join($,"index"),V=v.join($,"HEAD"),K=v.join($,"refs"),X=v.join(this.repoPath,".gitignore");this.gitWatcher=T5([Z,V,K,X],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=T5(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(Q)=>{let z=v.relative(this.repoPath,Q);if(!z)return!1;let W=z.split("/");for(let J=0;J<W.length;J++){let G=J===0?"":W.slice(0,J).join("/"),U=this.ignorers.get(G);if(U){let B=J===0?z:W.slice(J).join("/");if(U.ignores(B))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let Y=()=>this.scheduleRefresh();this.gitWatcher.on("change",(Q)=>{if(Q===X)this.ignorers=this.loadGitignores();Y()}),this.gitWatcher.on("add",Y),this.gitWatcher.on("unlink",Y),this.gitWatcher.on("error",(Q)=>{let z=Q instanceof Error?Q.message:String(Q);this.setError(`Git watcher error: ${z}`)}),this.workingDirWatcher.on("change",Y),this.workingDirWatcher.on("add",Y),this.workingDirWatcher.on("unlink",Y),this.workingDirWatcher.on("error",(Q)=>{let z=Q instanceof Error?Q.message:String(Q);this.setError(`Working dir watcher error: ${z}`)})}dispose(){this.gitWatcher?.close(),this.workingDirWatcher?.close()}statMtimes($){let Z=new Map;for(let V of $.files){if(Z.has(V.path))continue;try{Z.set(V.path,b.statSync(v.join(this.repoPath,V.path)).mtimeMs)}catch{}}return Z}pendingRefreshKind=null;scheduleRefresh(){this.requestRefresh("full")}scheduleStatusRefresh(){this.requestRefresh("status")}requestRefresh($){if(this.pendingRefreshKind!==null){if($==="full")this.pendingRefreshKind="full";return}if(this.queue.hasPendingMutations())return;this.pendingRefreshKind=$,this.queue.scheduleRefresh(async()=>{let Z=this.pendingRefreshKind??"full";if(this.pendingRefreshKind=null,Z==="full")await this.doRefresh();else await this.doStatusRefresh()})}async doStatusRefresh(){try{let $=await p$(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});let $=Date.now(),Z=await H$(this.repoPath).catch(()=>null);try{let V=await p$(this.repoPath);if(!V.isRepo){this.updateState({status:V,isLoading:!1,error:"Not a git repository"});return}let[K,X,Y,Q,z]=await Promise.all([Z$(this.repoPath,void 0,!1),Z$(this.repoPath,void 0,!0),O$(this.repoPath),g(this.repoPath),this.gatherJournalInputs(V,Z,$)]),W={unstaged:j$(K.raw),staged:j$(X.raw)};this.hunkTimes.stamp(K),this.hunkTimes.stamp(X),this.hunkTimes.prune(new Set(V.files.map((G)=>G.path)));let J=this.statMtimes(V);if(this.updateState({status:V,hunkCounts:W,stashList:Y,operationInProgress:Q,mtimes:J,isLoading:!1}),z!==null)this.emit("journal-observation",{status:V,headDiff:z.headDiff,headOid:z.headOid,stashCount:z.stashCount,operationInProgress:z.operationInProgress,mtimes:z.mtimes,at:Date.now()})}catch(V){this.updateState({isLoading:!1,error:V instanceof Error?V.message:"Unknown error"})}}async snapshotJournalGuard($){let[Z,V]=await Promise.all([g(this.repoPath),O$(this.repoPath)]);return{operation:Z,stashCount:V.length,mtimes:this.statMtimes($)}}static journalGuardMoved($,Z){if($.operation!==Z.operation||$.stashCount!==Z.stashCount)return!0;if($.mtimes.size!==Z.mtimes.size)return!0;for(let[V,K]of $.mtimes)if(Z.mtimes.get(V)!==K)return!0;return!1}sectionWrittenDuringGather($,Z,V){let K=new Set(Z);for(let X of $.files)if(X.status==="untracked")K.add(X.path);for(let X of K)try{let Y=b.statSync(v.join(this.repoPath,X));if(Math.floor(Y.mtimeMs)>V)return!0}catch{}return!1}async gatherJournalInputs($,Z,V){if(Z===null)return null;try{let K=await this.snapshotJournalGuard($),X=await X5(this.repoPath),Y=new Set(L$(X).keys()),Q=[];if(X.raw)Q.push(X.raw.endsWith(`
23
+ `)?X.raw:X.raw+`
24
+ `);let z=[...X.lines];await this.appendUntrackedSections($,Y,Q,z);let W=await H$(this.repoPath);if(Z!==W)return null;let J=await this.snapshotJournalGuard($);if(R$.journalGuardMoved(K,J))return null;if(this.sectionWrittenDuringGather($,Y,V))return null;return{headDiff:{raw:Q.join(""),lines:z},headOid:W,stashCount:J.stashCount,operationInProgress:J.operation,mtimes:J.mtimes}}catch{return null}}async appendUntrackedSections($,Z,V,K){let X=new Set;for(let Y of $.files){if(Y.status!=="untracked"||X.has(Y.path)||Z.has(Y.path))continue;X.add(Y.path);let Q;try{Q=b.statSync(v.join(this.repoPath,Y.path))}catch{continue}if(!Q.isFile())continue;if(Q.size>f7){this.appendOversizeSection(Y.path,Q,V,K);continue}let z=await A$(this.repoPath,Y.path);if(!z.raw)continue;V.push(z.raw.endsWith(`
25
+ `)?z.raw:z.raw+`
26
+ `),K.push(...z.lines)}}appendOversizeSection($,Z,V,K){let X=[`diff --git a/${$} b/${$}`,"new file mode 100644",`${D$} size=${Z.size} mtime=${Math.round(Z.mtimeMs)}`];V.push(X.join(`
27
+ `)+`
28
+ `),K.push(...X.map((Y)=>({type:"header",content:Y})))}async stage($){try{await this.queue.enqueueMutation(()=>v4(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(()=>k4(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()=>c4(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()=>g4(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"?()=>_4(this.repoPath,$.path):()=>b4(this.repoPath,$.path);try{await this.queue.enqueueMutation(Z),await this.refresh()}catch(V){this.updateState({error:`Failed to discard ${$.path}: ${V instanceof Error?V.message:String(V)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>P4(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>y4(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(()=>x4(this.repoPath,$,Z)),await this.refresh()}catch(V){this.updateState({error:`Failed to commit: ${V instanceof Error?V.message:String(V)}`})}}async loadStashList(){try{let $=await this.queue.enqueue(()=>O$(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as d7}from"node:events";class t$ extends d7{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor($,Z,V){super();this.repoPath=$,this.queue=Z,this.callbacks=V}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 V=await this.queue.enqueue(Z);this.updateRemoteState({inProgress:!1,lastResult:V}),this.callbacks.scheduleRefresh()}catch(V){let K=V instanceof Error?V.message:String(V);this.updateRemoteState({inProgress:!1,error:K})}return this._remoteState}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>u4(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>p4(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>h4(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>d4(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>l4(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>B$(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>n4(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>a4(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>o4(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>s4(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>i4(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>r4(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>t4(this.repoPath))}}import{EventEmitter as l7}from"node:events";import{randomBytes as n7}from"node:crypto";var a7=262144,o7=500,s7=16777216,q5=Number.MAX_SAFE_INTEGER,i7=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function r7($){let Z=i7.exec($);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldCount:Z[2]!==void 0?parseInt(Z[2],10):1}}function t7($,Z){let V=r7(Z);if(!V)return[];let K=V.oldCount===0?V.oldStart+1:V.oldStart,X=[],Y=null;for(let Q of $){let z=Q.content[0];if(z==="\\")continue;if(z==="-")Y=e7(Y,K),K++;else if(z==="+")Y=Y??{hasDel:!1,delStart:0,delEnd:0,anchor:K-1};else D5(X,Y),Y=null,K++}return D5(X,Y),X}function e7($,Z){if(!$)return{hasDel:!0,delStart:Z,delEnd:Z,anchor:Z-1};if(!$.hasDel)$.hasDel=!0,$.delStart=Z;return $.delEnd=Z,$}function D5($,Z){if(!Z)return;$.push(Z.hasDel?[2*Z.delStart,2*Z.delEnd]:[2*Z.anchor,2*Z.anchor+2])}function e$($){if($.length===0)return{start:0,count:0};let Z=1/0,V=-1/0;for(let[Y,Q]of $){if(Y<Z)Z=Y;if(Q>V)V=Q}if(V>=q5)return{start:0,count:0};let K=Math.ceil(Z/2),X=Math.floor(V/2);return{start:K,count:X-K+1}}function $8($){let Z=[],V=null,K=[],X=null;for(let Q of $.lines)if(Q.type==="hunk")X={header:Q,body:[]},K.push(X);else if(X)X.body.push(Q);else if(Z.push(Q),Q.content.startsWith("rename from "))V=Q.content.slice(12);if(K.length===0){let Q=Z.some((z)=>z.content.startsWith(D$));return{hunks:[{runs:[[0,q5]],bodyHash:C$([$.raw]),ins:0,del:0,span:{start:0,count:0},diff:$,oversize:Q}],renamedFrom:V,hunkless:!0}}return{hunks:K.map(({header:Q,body:z})=>{let W=t7(z,Q.content),J=[],G=0,U=0;for(let O of z){let N=O.content[0];if(N==="\\")continue;if(N==="+")G++,J.push(O.content);else if(N==="-")U++,J.push(O.content)}let B=[...Z,Q,...z];return{runs:W,bodyHash:C$(J),ins:G,del:U,span:e$(W),diff:{raw:B.map((O)=>O.content).join(`
29
+ `)+`
30
+ `,lines:B}}}),renamedFrom:V,hunkless:!1}}function Z8($){if($.oversize===!0)return null;return $.diff.raw.length>a7?null:$.diff}function V8($,Z,V){if($===0&&Z>0)return"shrunk";let K=$+Z;if(K>V)return"expanded";if(K<V)return"shrunk";return"edited"}function R5($,Z){let V=[];return $.forEach((K,X)=>{for(let[Y,Q]of K.runs)V.push({lo:Y,hi:Q,node:Z+X})}),V.sort((K,X)=>K.lo-X.lo),V}function K8($,Z){let V=Array.from({length:$.length+Z.length},(W,J)=>J),K=(W)=>{while(V[W]!==W)V[W]=V[V[W]],W=V[W];return W},X=(W,J)=>{let G=K(W),U=K(J);if(G!==U)V[G]=U},Y=R5($,0),Q=R5(Z,$.length),z=0;for(let W of Y){while(z<Q.length&&Q[z].hi<W.lo)z++;for(let J=z;J<Q.length&&Q[J].lo<=W.hi;J++)X(W.node,Q[J].node)}return V.map((W,J)=>K(J))}function Y8($,Z){let V=K8($,Z),K=new Map,X=(Y)=>{let Q=K.get(Y);if(!Q)Q={prevIdx:[],nextIdx:[],minLo:1/0},K.set(Y,Q);return Q};return $.forEach((Y,Q)=>{let z=X(V[Q]);z.prevIdx.push(Q);for(let[W]of Y.runs)if(W<z.minLo)z.minLo=W}),Z.forEach((Y,Q)=>{let z=X(V[$.length+Q]);z.nextIdx.push(Q);for(let[W]of Y.runs)if(W<z.minLo)z.minLo=W}),[...K.values()].sort((Y,Q)=>Y.minLo-Q.minLo)}function X8($,Z,V){let K=[],X=Z.map(()=>null),Y=V;for(let Q of Y8($,Z)){let z=Q.prevIdx.map((U)=>$[U]),W=Q.nextIdx.map((U)=>Z[U]);if(z.length===1&&W.length===1&&z[0].bodyHash===W[0].bodyHash){let U=W[0];X[Q.nextIdx[0]]={seq:z[0].seq,runs:U.runs,bodyHash:U.bodyHash,ins:U.ins,del:U.del};continue}if(W.length===0){for(let U of z)K.push({seq:Y++,kind:"reverted",span:e$(U.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[U.seq],siblings:1});continue}let J=z.map((U)=>U.seq),G=z.reduce((U,B)=>U+B.ins+B.del,0);for(let U of Q.nextIdx){let B=Z[U],O={seq:Y++,kind:z.length===0?"created":V8(B.ins,B.del,G),span:B.span,stats:{insertions:B.ins,deletions:B.del},diff:Z8(B),supersedes:[...J],siblings:W.length};K.push(O),X[U]={seq:O.seq,runs:B.runs,bodyHash:B.bodyHash,ins:B.ins,del:B.del}}}return{entries:K,nextLive:X.filter((Q)=>Q!==null)}}function Q8($,Z){let V=Array($.length).fill(!1),K=Array(Z.length).fill(null);for(let z=0;z<Z.length;z++){let W=$.findIndex((J,G)=>!V[G]&&J.bodyHash===Z[z].bodyHash);if(W!==-1)V[W]=!0,K[z]=$[W].seq}for(let z=0;z<Z.length;z++){if(K[z]!==null)continue;let W=V.findIndex((J)=>!J);if(W!==-1)V[W]=!0,K[z]=$[W].seq}let X=$[$.length-1].seq,Y=Z.map((z,W)=>{return{seq:K[W]??X,runs:z.runs,bodyHash:z.bodyHash,ins:z.ins,del:z.del}}),Q=$.filter((z,W)=>!V[W]).map((z)=>z.seq);return{carried:Y,retired:Q}}function q$(){return{entries:[],epoch:`${Date.now().toString(36)}-${n7(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class $4 extends l7{store;constructor($){super();this.store=$}get journalStore(){return this.store}observe($){try{this.doObserve($)}catch(Z){U$(`Journal observation skipped: ${Z instanceof Error?Z.message:String(Z)}`)}}doObserve($){let Z=[];if(this.store.lastHeadOid===null){if($.operationInProgress===null)this.seed($,Z)}else if(this.handleOperations($,Z));else if($.headOid!==this.store.lastHeadOid)this.rebaseline($,Z);else this.classify($,Z);if(Z.length>0)this.store.entries.push(...Z),this.emit("append",Z),this.pruneStore()}pruneStore(){let $=new Set;for(let Z of this.store.live.values())for(let V of Z)$.add(V.seq);this.pruneBodies($),this.pruneEntries($)}pruneBodies($){let Z=0;for(let V of this.store.entries)if(V.type==="hunk"&&V.diff!==null)Z+=V.diff.raw.length;for(let V of this.store.entries){if(Z<=s7)return;if(V.type!=="hunk"||V.diff===null||$.has(V.seq))continue;Z-=V.diff.raw.length,V.diff=null}}pruneEntries($){let Z=this.store.entries,V=0;while(Z.length-V>o7&&(Z[V].type==="boundary"||!$.has(Z[V].seq)))V++;if(V>0)Z.splice(0,V)}handleOperations($,Z){let V=this.store.lastOperation;if($.operationInProgress!==null){if(V===null)Z.push(this.boundary("op-start",$.operationInProgress,[],$.at)),this.store.lastOperation=$.operationInProgress;return!0}if(V!==null)Z.push(this.boundary("op-end",V,[],$.at)),this.store.lastOperation=null;return!1}seed($,Z){Z.push(this.boundary("journal-start",$.status.branch.current,[],$.at));let{files:V}=this.parseObservation($),K=[...V.keys()].sort((X,Y)=>this.tsFor($,X)-this.tsFor($,Y));for(let X of K)this.classifyPath(X,[],V.get(X).hunks,$,!0,Z);this.store.lastHeadOid=$.headOid,this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount,this.store.lastOperation=null}rebaseline($,Z){let{files:V,deferred:K}=this.parseObservation($),X=$.status.branch.current===this.store.lastBranch,Y=X?"commit":"checkout",Q=X?$.headOid.slice(0,7):$.status.branch.current,{resolves:z,newLive:W}=this.carrySurvivors(V,K);Z.push(this.boundary(Y,Q,z,$.at)),this.store.live=W;for(let[J,{hunks:G}]of V){if(W.has(J))continue;this.classifyPath(J,[],G,$,!1,Z)}this.store.lastHeadOid=$.headOid,this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}carrySurvivors($,Z){let V=[],K=new Map;for(let[X,Y]of this.store.live){if(Z.has(X)){K.set(X,Y);continue}let Q=$.get(X);if(!Q){V.push(...Y.map((J)=>J.seq));continue}let{carried:z,retired:W}=Q8(Y,Q.hunks);V.push(...W),K.set(X,z)}return{resolves:V,newLive:K}}classify($,Z){let{files:V,deferred:K}=this.parseObservation($);this.handleRenames($,V,Z),this.handleDisappearances($,V,K,Z);for(let[X,{hunks:Y,renamedFrom:Q,hunkless:z}]of V){let W=this.store.live.get(X)??[];if(z&&Q!==null&&W.length>0)continue;this.classifyPath(X,W,Y,$,!1,Z)}this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}handleRenames($,Z,V){for(let[K,X]of Z){let Y=X.renamedFrom;if(Y===null||Y===K)continue;if(!this.store.live.has(Y)||Z.has(Y))continue;let Q=(this.store.live.get(K)??[]).map((z)=>z.seq);this.store.live.set(K,this.store.live.get(Y)),this.store.live.delete(Y),V.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,K),path:K,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:Q,siblings:1,seeded:!1})}}handleDisappearances($,Z,V,K){let X=[...this.store.live.keys()].filter((Y)=>!Z.has(Y)&&!V.has(Y));if(X.length===0)return;if($.stashCount>this.store.lastStashCount){let Y=X.flatMap((Q)=>this.store.live.get(Q).map((z)=>z.seq));K.push(this.boundary("stash","stash",Y,$.at));for(let Q of X)this.store.live.delete(Q);return}for(let Y of X){let Q=this.store.live.get(Y);K.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,Y),path:Y,status:this.statusOf($,Y),kind:"reverted",span:e$(Q.flatMap((z)=>z.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:Q.map((z)=>z.seq),siblings:1,seeded:!1}),this.store.live.delete(Y)}}classifyPath($,Z,V,K,X,Y){let{entries:Q,nextLive:z}=X8(Z,V,this.store.nextSeq);this.store.nextSeq+=Q.length;let W=this.tsFor(K,$),J=this.statusOf(K,$);for(let G of Q){let U={type:"hunk",seq:G.seq,ts:W,path:$,status:J,kind:G.kind==="created"&&J==="renamed"?"renamed":G.kind,span:G.span,stats:G.stats,diff:G.diff,supersedes:G.supersedes,siblings:G.siblings,seeded:X};Y.push(U)}if(z.length>0)this.store.live.set($,z);else this.store.live.delete($)}parseObservation($){let Z=new Map;for(let[K,X]of L$($.headDiff))Z.set(K,$8(X));let V=new Set;for(let K of $.status.files)if(K.status==="untracked"&&!Z.has(K.path))V.add(K.path);return{files:Z,deferred:V}}boundary($,Z,V,K){return{type:"boundary",seq:this.store.nextSeq++,ts:K,kind:$,label:Z,resolves:V}}tsFor($,Z){let V=$.mtimes?.get(Z);return V===void 0?$.at:Math.min(V,$.at)}statusOf($,Z){return $.status.files.find((V)=>V.path===Z)?.status??"modified"}}class Z4{workingTree;remote;journal;repoPath;constructor($,Z){this.repoPath=$;let V=R4($);this.workingTree=new R$($,V),this.remote=new t$($,V,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new $4(Z??q$()),this.workingTree.on("journal-observation",(K)=>this.journal.observe(K))}dispose(){this.workingTree.dispose(),q4(this.repoPath)}}import*as n from"node:fs";import*as m from"node:path";async function F5($){let Z=E5($);if(!Z)return null;try{let V=I(Z);if((await V.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await V.raw(["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function F$($){let Z=E5($);if(!Z)return[];try{let K=await I(Z).raw(["worktree","list","--porcelain"]);return J8(K)}catch{return[]}}function S5($){let Z=null,V=-1/0;for(let K of $){if(K.isBare)continue;let X=z8(K.path);if(X>V)V=X,Z=K}return Z}function z8($){let Z=W8($),V=Z?[m.join(Z,"index"),m.join(Z,"HEAD")]:[$],K=-1/0;for(let X of V)try{let Y=n.statSync(X).mtimeMs;if(Y>K)K=Y}catch{}return K}function W8($){let Z=m.join($,".git");try{if(n.statSync(Z).isDirectory())return Z;let V=n.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!V)return null;let K=V[1].trim();return m.isAbsolute(K)?K:m.resolve($,K)}catch{return null}}function J8($){let Z=[],V=null;for(let K of $.split(`
31
+ `))if(K.startsWith("worktree ")){if(V)Z.push(V);V={path:K.slice(9).trim(),branch:null,head:null,isBare:!1}}else if(!V)continue;else if(K.startsWith("HEAD "))V.head=K.slice(5).trim();else if(K.startsWith("branch "))V.branch=K.slice(7).trim().replace(/^refs\/heads\//,"");else if(K==="bare")V.isBare=!0;if(V)Z.push(V);return Z}function E5($){try{if(n.statSync($).isDirectory())return $;return m.dirname($)}catch{let Z=m.dirname($);return Z!==$&&n.existsSync(Z)?Z:null}}function G8($){return U8("sha256").update($).digest("hex").slice(0,12)}var O8=32;class w5{cap;stores=new Map;constructor($=O8){this.cap=$}acquire($){let Z=this.stores.get($);if(Z)this.stores.delete($);else Z=q$();return this.stores.set($,Z),Z}prune($){if(this.stores.size<=this.cap)return;for(let Z of this.stores.keys()){if(this.stores.size<=this.cap)return;if($(Z))continue;this.stores.delete(Z)}}has($){return this.stores.has($)}get size(){return this.stores.size}}class V4{events;byId=new Map;byPath=new Map;journalStores=new w5;constructor($={}){this.events=$}async openRepo($){let Z=await F5($);if(!Z){let Q=S5(await F$($));if(!Q)throw Error(`Not a git repository: ${$}`);Z=Q.path}let V=this.byPath.get(Z);if(V)return V.refCount++,{handle:V,created:!1};let K=G8(Z),X=new Z4(Z,this.journalStores.acquire(K));X.workingTree.startWatching();let Y={id:K,path:Z,manager:X,refCount:1};return this.byId.set(Y.id,Y),this.byPath.set(Z,Y),this.journalStores.prune((Q)=>this.byId.has(Q)),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),Z.manager.dispose(),this.events.onClosed?.(Z.id),!0}disposeAll(){for(let $ of this.byId.values())$.manager.dispose();this.byId.clear(),this.byPath.clear()}}var v5=25000;function X$($,Z,V){$.write(`event: ${Z}
32
+ data: ${V}
21
33
 
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
34
+ `)}class K4{channels=new Map;subscribe($,Z,V,K){K.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let X=this.channels.get($);if(!X){let Q=new Set,z={manager:Z,subscribers:Q,listener:(W)=>{let J=JSON.stringify(d(W));if(J===z.lastData)return;z.lastData=J;for(let G of Q)X$(G,"state-change",J)},journalListener:(W)=>{let J=JSON.stringify({epoch:Z.journal.journalStore.epoch,entries:x$(W)});for(let G of Q)X$(G,"journal-append",J)},keepAlive:setInterval(()=>{for(let W of Q)W.write(`: ping
23
35
 
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
36
+ `)},v5),lastData:null};Z.workingTree.on("state-change",z.listener),Z.journal.on("append",z.journalListener),z.keepAlive.unref(),X=z,this.channels.set($,X)}X.subscribers.add(K),V.on("close",()=>this.unsubscribe($,K));let Y=JSON.stringify(d(Z.workingTree.state));X$(K,"snapshot",Y)}unsubscribe($,Z){let V=this.channels.get($);if(!V)return;if(V.subscribers.delete(Z),V.subscribers.size===0)this.teardown($,V)}teardown($,Z){Z.manager.workingTree.off("state-change",Z.listener),Z.manager.journal.off("append",Z.journalListener),clearInterval(Z.keepAlive);for(let V of Z.subscribers)V.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 Y4{subscribers=new Set;keepAlive=null;subscribe($,Z,V){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 K of this.subscribers)K.write(`: ping
25
37
 
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
38
+ `)},v5),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),X$(Z,"snapshot",JSON.stringify(V))}broadcast($,Z){let V=JSON.stringify(Z);for(let K of this.subscribers)X$(K,$,V)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as s from"node:fs";import*as w$ from"node:path";import{watch as B8}from"chokidar";import{EventEmitter as M8}from"node:events";import*as S$ from"node:fs";import*as E$ from"node:path";import*as X4 from"node:os";function k5($){if($.startsWith("~/"))return E$.join(X4.homedir(),$.slice(2));if($==="~")return X4.homedir();return $}function P5($){let Z=E$.dirname($);if(!S$.existsSync(Z))S$.mkdirSync(Z,{recursive:!0})}function Q4($){let Z=$.split(`
39
+ `);for(let V=Z.length-1;V>=0;V--){let K=Z[V].trim();if(K)return K}return""}class z4 extends M8{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=k5($);return w$.isAbsolute(Z)?Z:w$.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=s.readFileSync(this.targetFile,"utf-8"),Z=Q4($);if(Z&&Z!==this.lastReadPath){let V=this.processContent(Z),K=new Date;if(this.debug&&V)process.stderr.write(`[diffstalker ${K.toISOString()}] Path change detected
28
40
  `),process.stderr.write(` Source file: ${this.targetFile}
29
41
  `),process.stderr.write(` Raw content: "${Z}"
30
42
  `),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
31
- `),process.stderr.write(` Resolved: "${K}"
32
- `);this.lastReadPath=K,this.updateState({path:K,lastUpdate:Q,rawContent:Z})}}catch{}}start(){if(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
43
+ `),process.stderr.write(` Resolved: "${V}"
44
+ `);this.lastReadPath=V,this.updateState({path:V,lastUpdate:K,rawContent:Z})}}catch{}}start(){if(P5(this.targetFile),!s.existsSync(this.targetFile))s.writeFileSync(this.targetFile,"");try{let $=s.readFileSync(this.targetFile,"utf-8"),Z=Q4($);if(Z){let V=this.processContent(Z),K=new Date;if(this.debug&&V)process.stderr.write(`[diffstalker ${K.toISOString()}] Initial path read
33
45
  `),process.stderr.write(` Source file: ${this.targetFile}
34
46
  `),process.stderr.write(` Raw content: "${Z}"
35
- `),process.stderr.write(` Resolved: "${K}"
36
- `);this.lastReadPath=K,this._state={path:K,lastUpdate:Q,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=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)
47
+ `),process.stderr.write(` Resolved: "${V}"
48
+ `);this.lastReadPath=V,this._state={path:V,lastUpdate:K,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=B8(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 y5={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class W4{registry;hub;targetFile;watcher;followedRepoId=null;followedPath=null;disposed=!1;queue=Promise.resolve();constructor($,Z,V){this.registry=$,this.hub=Z,this.targetFile=V,this.watcher=new z4(V)}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 V=this.followedRepoId;if(this.followedRepoId=Z.handle.id,this.followedPath=Z.handle.path,V)this.registry.closeRepo(V)}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 b5($){$.get("/health",({res:Z})=>{D(Z,200,{ok:!0,ready:!0})})}import*as v$ from"node:fs";import*as _ from"node:path";function C($,Z){let V=$.getRepo(Z);if(!V)throw new H(404,`Unknown repo id: ${Z}`);return V}function c($,Z,V){if(typeof $!=="object"||$===null)throw new H(400,`Expected a JSON body with "${Z}"`);let K=$[Z];if(typeof K!=="string"||!V?.allowEmpty&&K.length===0)throw new H(400,`Missing "${Z}" (string) in body`);return K}function i($,Z){let V=c($,Z);if(V.startsWith("-"))throw new H(400,`Invalid "${Z}" (must not start with "-"): ${V}`);return V}function x5($,Z){if(typeof $!=="object"||$===null)return;let V=$[Z];if(V===void 0)return;if(typeof V!=="string"||V.length===0)throw new H(400,`Invalid "${Z}" (expected a non-empty string)`);return V}function J4($,Z,V){if(typeof $!=="object"||$===null)return V.fallback;let K=$[Z];if(K===void 0)return V.fallback;if(typeof K!=="number"||!Number.isInteger(K)||K<V.min)throw new H(400,`Invalid "${Z}" (expected an integer >= ${V.min})`);return K}function m5($,Z){if(typeof $!=="object"||$===null)return!1;let V=$[Z];if(V===void 0)return!1;if(typeof V!=="boolean")throw new H(400,`Invalid "${Z}" (expected a boolean)`);return V}function r($,Z,V){let K=$.get(Z);if(K===null)return V;if(K==="true")return!0;if(K==="false")return!1;throw new H(400,`Invalid "${Z}" (expected true or false): ${K}`)}function c5($,Z,V){let K=$.get(Z);if(K===null)return V;let X=Number(K);if(!Number.isInteger(X)||X<1)throw new H(400,`Invalid "${Z}" (expected a positive integer): ${K}`);return X}async function p($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new H(500,"Repository status unavailable");return Z}function _5($,Z,V){let K=$.files.filter((X)=>X.path===Z);if(K.length===0)return null;return K.find((X)=>X.staged===V)??K[0]}async function k$($,Z,V){let K=await p($),X=_5(K,Z,V);if(!X)await $.refresh(),K=await p($),X=_5(K,Z,V);if(!X)throw new H(404,`File not in status: ${Z}`);return X}function U4($,Z){let V=_.resolve($),K=_.resolve(V,Z);if(K!==V&&!K.startsWith(V+_.sep))throw new H(400,`Path escapes repository root: ${Z}`)}async function g5($){try{return await v$.promises.realpath($)}catch{return null}}async function G4($,Z){let V=await v$.promises.realpath(_.resolve($)),K=await g5(_.join($,Z));if(K===null)return;if(K!==V&&!K.startsWith(V+_.sep))throw new H(400,`Path escapes repository root: ${Z}`)}async function u5($,Z){let V=await v$.promises.realpath(_.resolve($)),K=[];for(let X of Z){let Y=await g5(_.join($,X.path));if(Y===null||Y===V||Y.startsWith(V+_.sep))K.push(X)}return K}function O4($){return $?.code??null}function j8($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function h($,Z,V){$.clearError(),await V();let K=$.state.error;if(K){D(Z,j8(K),{error:K});return}await $.refresh(),D(Z,200,{state:d($.state)})}function N8($){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test($)?409:500}async function y($,Z,V){let K=$.manager.remote,X=()=>new H(409,`A ${K.remoteState.operation??"remote"} operation is already in progress`);if(K.remoteState.inProgress)throw X();let Y=await V();if(Y===null)throw X();if(Y.error){D(Z,N8(Y.error),{error:Y.error});return}let Q=$.manager.workingTree;await Q.refresh(),D(Z,200,{state:d(Q.state),result:Y.lastResult})}function p5($,Z){let{registry:V}=Z;$.get("/repos",({res:K})=>{let X=V.listRepos().map((Y)=>({id:Y.id,path:Y.path,branch:Y.manager.workingTree.state.status?.branch.current??null}));D(K,200,X)}),$.post("/repos",async({body:K,res:X})=>{let Y=c(K,"path"),Q;try{Q=await V.openRepo(Y)}catch(z){throw new H(400,z instanceof Error?z.message:String(z))}if(Q.created)Q.handle.manager.workingTree.refresh().catch(()=>{});D(X,Q.created?201:200,{id:Q.handle.id,path:Q.handle.path})}),$.get("/repos/:id/worktrees",async({params:K,res:X})=>{let Y=C(V,K.id);D(X,200,await F$(Y.path))}),$.delete("/repos/:id",({params:K,res:X})=>{C(V,K.id),V.closeRepo(K.id),D(X,200,{})})}function h5($,Z,V){if(!$.trim())return{valid:!1,error:"Commit message cannot be empty"};if(Z===0&&!V)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function f5($){return $.trim()}async function H8($){let Z=(K)=>K.filter((X)=>X.staged).length,V=Z((await p($)).files);if(V===0)await $.refresh(),V=Z((await p($)).files);return V}function d5($,Z){let{registry:V,sse:K}=Z;$.get("/repos/:id/status",async({params:X,res:Y})=>{let Q=C(V,X.id);await p(Q.manager.workingTree);let z=d(Q.manager.workingTree.state);z.operationInProgress=await g(Q.path),D(Y,200,z)}),$.get("/repos/:id/diff",async({params:X,query:Y,res:Q})=>{let z=C(V,X.id),W=Y.get("path")??void 0,J=r(Y,"staged",!1),G;if(W){let B=(await p(z.manager.workingTree)).files.some((O)=>O.path===W&&O.status==="untracked");if(B&&J)throw new H(400,`staged=true is meaningless for untracked file: ${W} (untracked files have no staged diff)`);G=B?await A$(z.path,W):await Z$(z.path,W,J)}else G=await Z$(z.path,void 0,J);z.manager.workingTree.stampDiff(G),D(Q,200,G)}),$.post("/repos/:id/stage",async({params:X,body:Y,res:Q})=>{let z=C(V,X.id),W=c(Y,"path"),J=z.manager.workingTree,G=await k$(J,W,!1);await h(J,Q,()=>J.stage(G))}),$.post("/repos/:id/unstage",async({params:X,body:Y,res:Q})=>{let z=C(V,X.id),W=c(Y,"path"),J=z.manager.workingTree,G=await k$(J,W,!0);await h(J,Q,()=>J.unstage(G))}),$.post("/repos/:id/stage-all",async({params:X,res:Y})=>{let z=C(V,X.id).manager.workingTree;await h(z,Y,()=>z.stageAll())}),$.post("/repos/:id/unstage-all",async({params:X,res:Y})=>{let z=C(V,X.id).manager.workingTree;await h(z,Y,()=>z.unstageAll())}),$.post("/repos/:id/discard",async({params:X,body:Y,res:Q})=>{let z=C(V,X.id),W=c(Y,"path"),J=z.manager.workingTree,G=await k$(J,W,!1);if(G.staged)throw new H(409,`Cannot discard a staged file: ${W} (unstage it first)`);await h(J,Q,()=>J.discard(G))}),$.post("/repos/:id/commit",async({params:X,body:Y,res:Q})=>{let z=C(V,X.id),W=c(Y,"message",{allowEmpty:!0}),J=m5(Y,"amend"),G=z.manager.workingTree,U=await H8(G),B=h5(W,U,J);if(!B.valid)throw new H(400,B.error??"Invalid commit");await h(G,Q,()=>G.commit(f5(W),J))}),$.post("/repos/:id/stage-hunk",async({params:X,body:Y,res:Q})=>{let z=C(V,X.id),W=c(Y,"patch"),J=z.manager.workingTree;await h(J,Q,()=>J.stageHunk(W))}),$.post("/repos/:id/unstage-hunk",async({params:X,body:Y,res:Q})=>{let z=C(V,X.id),W=c(Y,"patch"),J=z.manager.workingTree;await h(J,Q,()=>J.unstageHunk(W))}),$.get("/repos/:id/events",({params:X,req:Y,res:Q})=>{let z=C(V,X.id);K.subscribe(X.id,z.manager,Y,Q)})}async function A8($){let Z=await l$($);if(Z&&await l($,Z))return Z;if(M$($)){let V=await d$($);if(V&&await l($,V))return V}throw new H(422,"No usable base branch")}function l5($,Z){let{registry:V}=Z;$.get("/repos/:id/history",async({params:K,query:X,res:Y})=>{let Q=C(V,K.id),z=c5(X,"count",100);D(Y,200,await f4(Q.path,z))}),$.get("/repos/:id/commits/:hash/diff",async({params:K,res:X})=>{let Y=C(V,K.id),Q=K.hash;if(!/^[0-9a-f]{4,40}$/i.test(Q))throw new H(400,`Invalid commit hash: ${Q}`);if(!await l(Y.path,Q))throw new H(404,`Unknown commit: ${Q}`);D(X,200,await Q5(Y.path,Q))}),$.get("/repos/:id/head-message",async({params:K,res:X})=>{let Y=C(V,K.id);D(X,200,{message:await m4(Y.path)})}),$.get("/repos/:id/branches",async({params:K,res:X})=>{let Y=C(V,K.id);D(X,200,await B$(Y.path))}),$.get("/repos/:id/base-branches",async({params:K,res:X})=>{let Y=C(V,K.id);D(X,200,await f$(Y.path))}),$.get("/repos/:id/compare/base",async({params:K,res:X})=>{let Y=C(V,K.id);D(X,200,{base:await l$(Y.path)})}),$.put("/repos/:id/compare/base",async({params:K,body:X,res:Y})=>{let Q=C(V,K.id),z=i(X,"branch");if(!await l(Q.path,z))throw new H(400,`Not a valid base ref: ${z}`);Z5(Q.path,z),D(Y,200,{base:z})}),$.get("/repos/:id/compare",async({params:K,query:X,res:Y})=>{let Q=C(V,K.id),z=r(X,"uncommitted",!1),W=X.get("base"),J;if(W!==null){if(!await l(Q.path,W))throw new H(400,`Unknown base ref: ${W}`);J=W}else J=await A8(Q.path);let G;try{G=z?await z5(Q.path,J):await n$(Q.path,J)}catch(U){if(U instanceof N$)throw new H(422,U.message);throw U}D(Y,200,G)})}function C8($){let Z=$.get("since");if(Z===null)return 0;if(!/^\d+$/.test(Z))throw new H(400,`Invalid "since" (expected a non-negative integer): ${Z}`);return Number(Z)}function n5($,Z){let{registry:V}=Z;$.get("/repos/:id/journal",({params:K,query:X,res:Y})=>{let Q=C(V,K.id),z=C8(X);D(Y,200,C4(Q.manager.journal.journalStore,z))})}function a5($,Z){let{registry:V}=Z;$.post("/repos/:id/push",async({params:K,res:X})=>{let Y=C(V,K.id);await y(Y,X,()=>Y.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:K,res:X})=>{let Y=C(V,K.id);await y(Y,X,()=>Y.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:K,res:X})=>{let Y=C(V,K.id);await y(Y,X,()=>Y.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:K,body:X,res:Y})=>{let Q=C(V,K.id),z=x5(X,"message");await y(Q,Y,()=>Q.manager.remote.stash(z))}),$.post("/repos/:id/stash-pop",async({params:K,body:X,res:Y})=>{let Q=C(V,K.id),z=J4(X,"index",{min:0,fallback:0});await y(Q,Y,()=>Q.manager.remote.stashPop(z))}),$.post("/repos/:id/switch-branch",async({params:K,body:X,res:Y})=>{let Q=C(V,K.id),z=i(X,"name");await y(Q,Y,()=>Q.manager.remote.switchBranch(z))}),$.post("/repos/:id/create-branch",async({params:K,body:X,res:Y})=>{let Q=C(V,K.id),z=i(X,"name");await y(Q,Y,()=>Q.manager.remote.createBranch(z))}),$.post("/repos/:id/soft-reset",async({params:K,body:X,res:Y})=>{let Q=C(V,K.id),z=J4(X,"count",{min:1,fallback:1});if(!await l(Q.path,`HEAD~${z}`))throw new H(400,`Cannot soft-reset ${z} commit(s): HEAD~${z} does not exist`);await y(Q,Y,()=>Q.manager.remote.softReset(z))}),$.post("/repos/:id/cherry-pick",async({params:K,body:X,res:Y})=>{let Q=C(V,K.id),z=i(X,"hash");await y(Q,Y,()=>Q.manager.remote.cherryPick(z))}),$.post("/repos/:id/revert",async({params:K,body:X,res:Y})=>{let Q=C(V,K.id),z=i(X,"hash");await y(Q,Y,()=>Q.manager.remote.revertCommit(z))}),$.post("/repos/:id/abort",async({params:K,res:X})=>{let Y=C(V,K.id);if(!await g(Y.path))throw new H(409,"No operation in progress to abort");await y(Y,X,()=>Y.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:K,res:X})=>{let Y=C(V,K.id);if(await g(Y.path)!=="rebase")throw new H(409,"No rebase in progress to continue");await y(Y,X,()=>Y.manager.remote.rebaseContinue())})}import*as P$ from"node:fs";import*as Q$ from"node:path";function B4($){let Z={files:new Map,directories:new Set};for(let V of $){Z.files.set(V.path,{status:V.status,staged:V.staged});let K=V.path.split("/"),X="";for(let Y=0;Y<K.length-1;Y++)X=X?`${X}/${K[Y]}`:K[Y],Z.directories.add(X);Z.directories.add("")}return Z}var I8=1048576,o5=5000;class y$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function s5($,Z,V,K){let X=V?.hideHidden??!0,Y=V?.hideGitignored??!0,Q=Q$.join($,Z),z=await P$.promises.readdir(Q,{withFileTypes:!0}),W=z.map((U)=>Z?Q$.join(Z,U.name):U.name),J=Y?await G$($,W):new Set,G=[];for(let U of z){if(X&&U.name.startsWith("."))continue;let B=Z?Q$.join(Z,U.name):U.name;if(Y&&J.has(B))continue;let O=U.isDirectory(),N={name:U.name,path:B,type:O?"dir":"file"};if(K)if(O){if(K.directories.has(B))N.hasChanges=!0}else{let T=K.files.get(B);if(T)N.gitStatus=T.status,N.staged=T.staged}G.push(N)}return G.sort((U,B)=>{if(U.type==="dir"&&B.type!=="dir")return-1;if(U.type!=="dir"&&B.type==="dir")return 1;return U.name.localeCompare(B.name)}),G}function T8($){let Z=Math.min($.length,8192);for(let V=0;V<Z;V++)if($[V]===0)return!0;return!1}async function i5($,Z){let V=Q$.join($,Z),K=await P$.promises.stat(V);if(!K.isFile())throw new y$(Z);if(K.size>I8)return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:K.size,totalLines:0};let X=await P$.promises.readFile(V);if(T8(X))return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:K.size,totalLines:0};let Y=X.toString("utf-8"),Q=Y.split(`
49
+ `),z=!1;if(Q.length>o5)Y=Q.slice(0,o5).join(`
50
+ `),z=!0;return{content:Y,binary:!1,truncated:z,tooLarge:!1,size:K.size,totalLines:Q.length}}function r5($,Z){let{registry:V}=Z;$.get("/repos/:id/tree",async({params:K,query:X,res:Y})=>{let Q=C(V,K.id),z=X.get("dir")??"",W=r(X,"hidden",!1),J=r(X,"ignored",!1);U4(Q.path,z),await G4(Q.path,z);let G=await p(Q.manager.workingTree),U=B4(G.files),B;try{B=await s5(Q.path,z,{hideHidden:!W,hideGitignored:!J},U)}catch(O){let N=O4(O);if(N==="ENOENT")throw new H(404,`No such directory: ${z||"/"}`);if(N==="ENOTDIR")throw new H(400,`Not a directory: ${z}`);throw O}D(Y,200,await u5(Q.path,B))}),$.get("/repos/:id/file",async({params:K,query:X,res:Y})=>{let Q=C(V,K.id),z=X.get("path");if(!z)throw new H(400,'Missing "path" query parameter');U4(Q.path,z),await G4(Q.path,z);try{D(Y,200,await i5(Q.path,z))}catch(W){if(W instanceof y$)throw new H(400,W.message);let J=O4(W);if(J==="ENOENT"||J==="ENOTDIR")throw new H(404,`No such file: ${z}`);throw W}}),$.get("/repos/:id/files",async({params:K,res:X})=>{let Y=C(V,K.id);D(X,200,await e4(Y.path))})}function t5($,Z){let{registry:V,daemonEvents:K,follow:X}=Z;$.get("/events",({req:Y,res:Q})=>{let z=V.listRepos().map((W)=>({id:W.id,path:W.path}));K.subscribe(Y,Q,z)}),$.get("/follow",({res:Y})=>{D(Y,200,X?X.state:y5)})}function L8($){if(!t.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let V=$7.connect($);V.once("connect",()=>{V.destroy(),Z(!0)}),V.once("error",()=>{V.destroy(),Z(!1)})}catch{Z(!1)}})}function Z7($={}){let Z=new K4,V=new Y4,K=new V4({onOpened:(U)=>V.broadcast("repo-opened",{id:U.id,path:U.path}),onClosed:(U)=>{Z.closeRepo(U),V.broadcast("repo-closed",{id:U})}}),X=$.followFile?new W4(K,V,$.followFile):null,Y=new m$,Q={registry:K,sse:Z,daemonEvents:V,follow:X};b5(Y),p5(Y,Q),d5(Y,Q),l5(Y,Q),n5(Y,Q),a5(Y,Q),r5(Y,Q),t5(Y,Q),X?.start();let z=$.webRoot?L4($.webRoot):void 0,W=e5.createServer((U,B)=>{Y.handle(U,B,z).catch(()=>B.end())}),J=new Set;W.on("connection",(U)=>{J.add(U),U.on("close",()=>J.delete(U))});let G=null;return{address(){return W.address()},getRepo(U){return K.getRepo(U)},async listen(U){if(U.socketPath){if(await L8(U.socketPath))throw Error(`diffstalkerd already running at ${U.socketPath}`);t.rmSync(U.socketPath,{force:!0})}return new Promise((B,O)=>{let N=(R)=>O(R);W.once("error",N);let T=()=>{if(W.removeListener("error",N),G)t.chmodSync(G,384);B()};if(U.fd!==void 0)W.listen({fd:U.fd},T);else if(U.socketPath)G=U.socketPath,process.umask(63),W.listen(U.socketPath,T);else if(U.port!==void 0)W.listen(U.port,U.host??"127.0.0.1",T);else O(Error("listen() requires a socketPath, a port, or an fd"))})},close(){X?.dispose(),Z.destroy(),V.destroy(),K.disposeAll();for(let U of J)U.destroy();return new Promise((U,B)=>{W.close((O)=>{if(G)t.rmSync(G,{force:!0});if(O)B(O);else U()})})}}}var K7="diffstalkerd.sock",R8=3,V7=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
39
51
 
40
52
  Usage: diffstalkerd [options]
41
53
 
42
54
  Options:
43
55
  --socket PATH Bind a unix socket at PATH
44
- (default: $XDG_RUNTIME_DIR/diffstalker/${M2})
56
+ (default: $XDG_RUNTIME_DIR/diffstalker/${K7})
45
57
  --port N Bind TCP port N instead of a unix socket
46
58
  --host H Host to bind with --port (default: 127.0.0.1)
47
59
  --follow-file PATH Hook file to follow (created when missing)
@@ -51,5 +63,5 @@ Options:
51
63
  (default: web/ next to the daemon's compiled module;
52
64
  when missing, the daemon serves the API only)
53
65
  --help, -h Show this help
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};
66
+ `;function z$($,Z,V){let K=$[Z];if(K===void 0||K.startsWith("--"))throw Error(`${V} requires a value`);return K}function q8($){let Z={};for(let V=0;V<$.length;V++){let K=$[V];switch(K){case"--help":case"-h":return"help";case"--socket":Z.socketPath=z$($,++V,"--socket");break;case"--port":if(Z.port=Number(z$($,++V,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--host":Z.host=z$($,++V,"--host");break;case"--follow-file":Z.followFile=z$($,++V,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;case"--web-root":Z.webRoot=z$($,++V,"--web-root");break;default:throw Error(`Unknown argument: ${K}`)}}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 F8(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function S8($){if($.socketPath!==void 0||$.port!==void 0)return;if(F8()){$.fd=R8;return}let Z=A4();if(!Z)console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
67
+ Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1);b$.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=M4.join(Z,K7)}function E8($){let Z=$??D8(new URL("web/",import.meta.url));if(b$.existsSync(Z))return Z;console.error(`diffstalkerd: web UI assets not found at ${Z}; serving API only`);return}async function w8(){process.title="diffstalkerd";let $;try{$=q8(process.argv.slice(2))}catch(z){console.error(z instanceof Error?z.message:String(z)),console.error(V7),process.exit(2)}if($==="help"){console.log(V7);return}S8($);let Z=$.noFollow?void 0:$.followFile??M4.join(J$(),"target"),V=E8($.webRoot),K=Z7({followFile:Z,webRoot:V});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}`);if(V){if(console.error(`diffstalkerd serving web UI from ${V}`),$.port!==void 0){let z=$.host??"127.0.0.1",J=z==="127.0.0.1"||z==="localhost"||z==="::1"?`http://diffstalker.localhost:${$.port}/`:`http://${z}:${$.port}/`;console.error(`diffstalkerd: web UI at ${J}`)}}let X=!1,Y=(z)=>{if(X)return;X=!0,console.error(`Received ${z}, shutting down`),K.close().then(()=>process.exit(0)).catch((W)=>{console.error(W instanceof Error?W.message:String(W)),process.exit(1)})};process.on("SIGINT",()=>Y("SIGINT")),process.on("SIGTERM",()=>Y("SIGTERM")),process.on("SIGHUP",()=>Y("SIGHUP"));let Q=(z,W)=>{console.error(`diffstalkerd ${z}:`,W instanceof Error?W.stack??W.message:W),K.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(z)=>Q("uncaught exception",z)),process.on("unhandledRejection",(z)=>Q("unhandled rejection",z))}w8().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{q8 as parseArgs};