diffstalkerd 0.8.0 → 0.8.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/CHANGELOG.md CHANGED
@@ -7,6 +7,39 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.8.1] - 2026-07-28
11
+
12
+ ### Added
13
+
14
+ - **Web UI: recent repos group by project.** The header's "Recent" list now
15
+ collapses a repo's worktrees into one row (like the "Open on daemon" list
16
+ already did), instead of one row per worktree; picking a multi-worktree
17
+ project opens its most recently edited worktree. Both lists label a
18
+ project with the same "N worktrees" count — all of its worktrees, not
19
+ just the open ones — so one project reads identically in either. A recent
20
+ entry that no longer resolves to any worktree (a removed worktree
21
+ directory still in local prefs) is dropped instead of showing as its own
22
+ stray row.
23
+ - **Web UI: the worktree switcher is a two-line dropdown, split into
24
+ Recent and Stale.** Replaces the native `<select>` (whose closed state
25
+ leaked the active worktree's last-edited time into the trigger) with a
26
+ custom panel: each row notes commits ahead of its base branch and a
27
+ relative "edited N ago" time. A long-lived project accumulates worktrees
28
+ without bound, so anything touched in the last week is Recent and always
29
+ shown, while the rest collapses to three rows behind an "N more" reveal.
30
+ The active worktree stays visible even when it falls outside that
31
+ preview.
32
+ - **Web UI: the Changes tab shows its changed-file count** — `Changes (4)`,
33
+ or `Changes (0)` on a clean tree — so the tab says whether there is
34
+ anything to look at without having to open it first.
35
+ - **Web UI: wrap long lines.** A small, deliberately low-key "Wrap" toggle in
36
+ the corner of every diff pane (Changes, Compare, History) and the Explorer
37
+ file viewer — off by default, persisted, closer to a Notepad/Word "Word
38
+ Wrap" checkbox than the header's headline display toggles. Unified diffs
39
+ and the file viewer wrap; split diffs always stay on their normal
40
+ horizontal-scroll layout (a wrapped del/add pair can wrap to a different
41
+ line count per side, which would desync the two columns).
42
+
10
43
  ## [0.8.0] - 2026-07-26
11
44
 
12
45
  A security-hardening and web-UI-polish release. The daemon is now
package/README.md CHANGED
@@ -119,7 +119,8 @@ values are rejected with a 400 so they can never be parsed as git flags.
119
119
  | GET | `/repos` | List open repos (`id`, `path`, `branch`) |
120
120
  | POST | `/repos` | Open a repo: `{"path": "/abs/path"}` → `{id, path}` (201 created, 200 already open) |
121
121
  | DELETE | `/repos/:id` | Close a repo (refcounted per open) |
122
- | GET | `/repos/:id/worktrees` | Registered worktrees (`path`, `branch`, `head`, `isBare`): main worktree, linked worktrees, and the bare entry in a bare-worktree layout |
122
+ | GET | `/repos/:id/worktrees` | Registered worktrees (`path`, `branch`, `head`, `isBare`, `lastActivity`, `aheadOfBase`): main worktree, linked worktrees, and the bare entry in a bare-worktree layout |
123
+ | GET | `/worktrees?path=` | Same as above, but for a raw filesystem path instead of an already-opened repo id (e.g. a recently-visited repo a client hasn't opened on this daemon) |
123
124
  | GET | `/repos/:id/status` | Shared state: status, hunk counts, stash list, in-progress operation, error, working-file mtimes (path → mtimeMs; what browser clients build mtime-based auto mode on) |
124
125
  | GET | `/repos/:id/diff?path=&staged=` | Diff; whole tree without `path`, staged side with `staged=true` |
125
126
  | GET | `/repos/:id/history?count=` | Commit history (`CommitInfo[]`, default 100, ISO dates) |
package/dist/index.js CHANGED
@@ -1,59 +1,59 @@
1
- var G7=Object.create;var{getPrototypeOf:O7,defineProperty:N4,getOwnPropertyNames:B7}=Object;var M7=Object.prototype.hasOwnProperty;function j7($){return this[$]}var N7,H7,A7=($,Z,V)=>{var K=$!=null&&typeof $==="object";if(K){var Y=Z?N7??=new WeakMap:H7??=new WeakMap,X=Y.get($);if(X)return X}V=$!=null?G7(O7($)):{};let Q=Z||!$||!$.__esModule?N4(V,"default",{value:$,enumerable:!0}):V;for(let z of B7($))if(!M7.call(Q,z))N4(Q,z,{get:j7.bind($,z),enumerable:!0});if(K)Y.set($,Q);return Q};var C7=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var w5=C7((C9,E5)=>{var y=-1,k=1,w=0;function Y$($,Z,V,K,Y){if($===Z){if($)return[[w,$]];return[]}if(V!=null){var X=r7($,Z,V);if(X)return X}var Q=i$($,Z),z=$.substring(0,Q);$=$.substring(Q),Z=Z.substring(Q),Q=T$($,Z);var W=$.substring($.length-Q);$=$.substring(0,$.length-Q),Z=Z.substring(0,Z.length-Q);var J=f7($,Z);if(z)J.unshift([w,z]);if(W)J.push([w,W]);if(r$(J,Y),K)n7(J);return J}function f7($,Z){var V;if(!$)return[[k,Z]];if(!Z)return[[y,$]];var K=$.length>Z.length?$:Z,Y=$.length>Z.length?Z:$,X=K.indexOf(Y);if(X!==-1){if(V=[[k,K.substring(0,X)],[w,Y],[k,K.substring(X+Y.length)]],$.length>Z.length)V[0][0]=V[2][0]=y;return V}if(Y.length===1)return[[y,$],[k,Z]];var Q=l7($,Z);if(Q){var z=Q[0],W=Q[1],J=Q[2],U=Q[3],G=Q[4],O=Y$(z,J),B=Y$(W,U);return O.concat([[w,G]],B)}return d7($,Z)}function d7($,Z){var V=$.length,K=Z.length,Y=Math.ceil((V+K)/2),X=Y,Q=2*Y,z=Array(Q),W=Array(Q);for(var J=0;J<Q;J++)z[J]=-1,W[J]=-1;z[X+1]=0,W[X+1]=0;var U=V-K,G=U%2!==0,O=0,B=0,j=0,D=0;for(var R=0;R<Y;R++){for(var T=-R+O;T<=R-B;T+=2){var S=X+T,F;if(T===-R||T!==R&&z[S-1]<z[S+1])F=z[S+1];else F=z[S-1]+1;var M=F-T;while(F<V&&M<K&&$.charAt(F)===Z.charAt(M))F++,M++;if(z[S]=F,F>V)B+=2;else if(M>K)O+=2;else if(G){var N=X+U-T;if(N>=0&&N<Q&&W[N]!==-1){var A=V-W[N];if(F>=A)return C5($,Z,F,M)}}}for(var E=-R+j;E<=R-D;E+=2){var N=X+E,A;if(E===-R||E!==R&&W[N-1]<W[N+1])A=W[N+1];else A=W[N-1]+1;var q=A-E;while(A<V&&q<K&&$.charAt(V-A-1)===Z.charAt(K-q-1))A++,q++;if(W[N]=A,A>V)D+=2;else if(q>K)j+=2;else if(!G){var S=X+U-E;if(S>=0&&S<Q&&z[S]!==-1){var F=z[S],M=X+F-S;if(A=V-A,F>=A)return C5($,Z,F,M)}}}}return[[y,$],[k,Z]]}function C5($,Z,V,K){var Y=$.substring(0,V),X=Z.substring(0,K),Q=$.substring(V),z=Z.substring(K),W=Y$(Y,X),J=Y$(Q,z);return W.concat(J)}function i$($,Z){if(!$||!Z||$.charAt(0)!==Z.charAt(0))return 0;var V=0,K=Math.min($.length,Z.length),Y=K,X=0;while(V<Y){if($.substring(X,Y)==Z.substring(X,Y))V=Y,X=V;else K=Y;Y=Math.floor((K-V)/2+V)}if(R5($.charCodeAt(Y-1)))Y--;return Y}function I5($,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 Y=Math.min(V,K);if($==Z)return Y;var X=0,Q=1;while(!0){var z=$.substring(Y-Q),W=Z.indexOf(z);if(W==-1)return X;if(Q+=W,W==0||$.substring(Y-Q)==Z.substring(0,Q))X=Q,Q++}}function T$($,Z){if(!$||!Z||$.slice(-1)!==Z.slice(-1))return 0;var V=0,K=Math.min($.length,Z.length),Y=K,X=0;while(V<Y){if($.substring($.length-Y,$.length-X)==Z.substring(Z.length-Y,Z.length-X))V=Y,X=V;else K=Y;Y=Math.floor((K-V)/2+V)}if(F5($.charCodeAt($.length-Y)))Y--;return Y}function l7($,Z){var V=$.length>Z.length?$:Z,K=$.length>Z.length?Z:$;if(V.length<4||K.length*2<V.length)return null;function Y(B,j,D){var R=B.substring(D,D+Math.floor(B.length/4)),T=-1,S="",F,M,N,A;while((T=j.indexOf(R,T+1))!==-1){var E=i$(B.substring(D),j.substring(T)),q=T$(B.substring(0,D),j.substring(0,T));if(S.length<q+E)S=j.substring(T-q,T)+j.substring(T,T+E),F=B.substring(0,D-q),M=B.substring(D+E),N=j.substring(0,T-q),A=j.substring(T+E)}if(S.length*2>=B.length)return[F,M,N,A,S];else return null}var X=Y(V,K,Math.ceil(V.length/4)),Q=Y(V,K,Math.ceil(V.length/2)),z;if(!X&&!Q)return null;else if(!Q)z=X;else if(!X)z=Q;else z=X[4].length>Q[4].length?X:Q;var W,J,U,G;if($.length>Z.length)W=z[0],J=z[1],U=z[2],G=z[3];else U=z[0],G=z[1],W=z[2],J=z[3];var O=z[4];return[W,J,U,G,O]}function n7($){var Z=!1,V=[],K=0,Y=null,X=0,Q=0,z=0,W=0,J=0;while(X<$.length){if($[X][0]==w)V[K++]=X,Q=W,z=J,W=0,J=0,Y=$[X][1];else{if($[X][0]==k)W+=$[X][1].length;else J+=$[X][1].length;if(Y&&Y.length<=Math.max(Q,z)&&Y.length<=Math.max(W,J))$.splice(V[K-1],0,[y,Y]),$[V[K-1]+1][0]=k,K--,K--,X=K>0?V[K-1]:-1,Q=0,z=0,W=0,J=0,Y=null,Z=!0}X++}if(Z)r$($);s7($),X=1;while(X<$.length){if($[X-1][0]==y&&$[X][0]==k){var U=$[X-1][1],G=$[X][1],O=I5(U,G),B=I5(G,U);if(O>=B){if(O>=U.length/2||O>=G.length/2)$.splice(X,0,[w,G.substring(0,O)]),$[X-1][1]=U.substring(0,U.length-O),$[X+1][1]=G.substring(O),X++}else if(B>=U.length/2||B>=G.length/2)$.splice(X,0,[w,U.substring(0,B)]),$[X-1][0]=k,$[X-1][1]=G.substring(0,G.length-B),$[X+1][0]=y,$[X+1][1]=U.substring(B),X++;X++}X++}}var T5=/[^a-zA-Z0-9]/,L5=/\s/,D5=/[\r\n]/,a7=/\n\r?\n$/,o7=/^\r?\n\r?\n/;function s7($){function Z(B,j){if(!B||!j)return 6;var D=B.charAt(B.length-1),R=j.charAt(0),T=D.match(T5),S=R.match(T5),F=T&&D.match(L5),M=S&&R.match(L5),N=F&&D.match(D5),A=M&&R.match(D5),E=N&&B.match(a7),q=A&&j.match(o7);if(E||q)return 5;else if(N||A)return 4;else if(T&&!F&&M)return 3;else if(F||M)return 2;else if(T||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],Y=$[V][1],X=$[V+1][1],Q=T$(K,Y);if(Q){var z=Y.substring(Y.length-Q);K=K.substring(0,K.length-Q),Y=z+Y.substring(0,Y.length-Q),X=z+X}var W=K,J=Y,U=X,G=Z(K,Y)+Z(Y,X);while(Y.charAt(0)===X.charAt(0)){K+=Y.charAt(0),Y=Y.substring(1)+X.charAt(0),X=X.substring(1);var O=Z(K,Y)+Z(Y,X);if(O>=G)G=O,W=K,J=Y,U=X}if($[V-1][1]!=W){if(W)$[V-1][1]=W;else $.splice(V-1,1),V--;if($[V][1]=J,U)$[V+1][1]=U;else $.splice(V+1,1),V--}}V++}}function r$($,Z){$.push([w,""]);var V=0,K=0,Y=0,X="",Q="",z;while(V<$.length){if(V<$.length-1&&!$[V][1]){$.splice(V,1);continue}switch($[V][0]){case k:Y++,Q+=$[V][1],V++;break;case y:K++,X+=$[V][1],V++;break;case w:var W=V-Y-K-1;if(Z){if(W>=0&&S5($[W][1])){var J=$[W][1].slice(-1);if($[W][1]=$[W][1].slice(0,-1),X=J+X,Q=J+Q,!$[W][1]){$.splice(W,1),V--;var U=W-1;if($[U]&&$[U][0]===k)Y++,Q=$[U][1]+Q,U--;if($[U]&&$[U][0]===y)K++,X=$[U][1]+X,U--;W=U}}if(q5($[V][1])){var J=$[V][1].charAt(0);$[V][1]=$[V][1].slice(1),X+=J,Q+=J}}if(V<$.length-1&&!$[V][1]){$.splice(V,1);break}if(X.length>0||Q.length>0){if(X.length>0&&Q.length>0){if(z=i$(Q,X),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),X=X.substring(z)}if(z=T$(Q,X),z!==0)$[V][1]=Q.substring(Q.length-z)+$[V][1],Q=Q.substring(0,Q.length-z),X=X.substring(0,X.length-z)}var G=Y+K;if(X.length===0&&Q.length===0)$.splice(V-G,G),V=V-G;else if(X.length===0)$.splice(V-G,G,[k,Q]),V=V-G+1;else if(Q.length===0)$.splice(V-G,G,[y,X]),V=V-G+1;else $.splice(V-G,G,[y,X],[k,Q]),V=V-G+2}if(V!==0&&$[V-1][0]===w)$[V-1][1]+=$[V][1],$.splice(V,1);else V++;Y=0,K=0,X="",Q="";break}}if($[$.length-1][1]==="")$.pop();var O=!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),O=!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),O=!0}V++}if(O)r$($,Z)}function R5($){return $>=55296&&$<=56319}function F5($){return $>=56320&&$<=57343}function q5($){return F5($.charCodeAt(0))}function S5($){return R5($.charCodeAt($.length-1))}function i7($){var Z=[];for(var V=0;V<$.length;V++)if($[V][1].length>0)Z.push($[V]);return Z}function s$($,Z,V,K){if(S5($)||q5(K))return null;return i7([[w,$],[y,Z],[k,V],[w,K]])}function r7($,Z,V){var K=typeof V==="number"?{index:V,length:0}:V.oldRange,Y=typeof V==="number"?null:V.newRange,X=$.length,Q=Z.length;if(K.length===0&&(Y===null||Y.length===0)){var z=K.index,W=$.slice(0,z),J=$.slice(z),U=Y?Y.index:null;$:{var G=z+Q-X;if(U!==null&&U!==G)break $;if(G<0||G>Q)break $;var O=Z.slice(0,G),B=Z.slice(G);if(B!==J)break $;var j=Math.min(z,G),D=W.slice(0,j),R=O.slice(0,j);if(D!==R)break $;var T=W.slice(j),S=O.slice(j);return s$(D,T,S,J)}$:{if(U!==null&&U!==z)break $;var F=z,O=Z.slice(0,F),B=Z.slice(F);if(O!==W)break $;var M=Math.min(X-F,Q-F),N=J.slice(J.length-M),A=B.slice(B.length-M);if(N!==A)break $;var T=J.slice(0,J.length-M),S=B.slice(0,B.length-M);return s$(W,T,S,N)}}if(K.length>0&&Y&&Y.length===0)$:{var D=$.slice(0,K.index),N=$.slice(K.index+K.length),j=D.length,M=N.length;if(Q<j+M)break $;var R=Z.slice(0,j),A=Z.slice(Q-M);if(D!==R||N!==A)break $;var T=$.slice(j,X-M),S=Z.slice(j,Q-M);return s$(D,T,S,N)}return null}function L$($,Z,V,K){return Y$($,Z,V,K,!0)}L$.INSERT=k;L$.DELETE=y;L$.EQUAL=w;E5.exports=L$});import*as _$ from"node:fs";import*as j4 from"node:path";import{fileURLToPath as b8}from"node:url";import*as H4 from"node:os";import*as W$ from"node:path";var A4="diffstalker";function J$(){return W$.join(process.env.XDG_CACHE_HOME||W$.join(H4.homedir(),".cache"),A4)}function C4(){return process.env.XDG_RUNTIME_DIR?W$.join(process.env.XDG_RUNTIME_DIR,A4):null}import*as Q7 from"node:http";import*as e from"node:fs";import*as z7 from"node:net";function x$($){let Z={};for(let[V,K]of $)Z[V]=K;return Z}function I7($){if(!$)return null;return{staged:x$($.staged),unstaged:x$($.unstaged)}}function l($){return{status:$.status,hunkCounts:I7($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress,mtimes:$.mtimes?x$($.mtimes):null}}function m$($){return $}function T7($){return $.entries.length>0?$.entries[0].seq-1:$.nextSeq-1}function I4($,Z){let V=Z>0?$.entries.filter((K)=>K.seq>Z):$.entries;return{epoch:$.epoch,prunedBefore:T7($),entries:m$(V)}}function X$($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[V,K]of $)Z[String(V)]=X$(K);return Z}if(Array.isArray($))return $.map(X$);if($!==null&&typeof $==="object"){let Z={};for(let[V,K]of Object.entries($))Z[V]=X$(K);return Z}return $}var L7=1048576;class H extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function L($,Z,V){let K=JSON.stringify(X$(V));$.writeHead(Z,{"content-type":"application/json"}),$.end(K)}function D7($,Z){if($.segments.length!==Z.length)return null;let V={};for(let K=0;K<$.segments.length;K++){let Y=$.segments[K];if(Y.startsWith(":"))try{V[Y.slice(1)]=decodeURIComponent(Z[K])}catch{throw new H(400,`Malformed percent-encoding in path: ${Z[K]}`)}else if(Y!==Z[K])return null}return V}async function R7($){if($.method!=="POST"&&$.method!=="PUT"&&$.method!=="PATCH")return;let Z=[],V=0;for await(let Y of $){let X=Y;if(V+=X.length,V>L7)throw new H(413,"Request body too large");Z.push(X)}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 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,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=D7(V,Z);if(K)return{handler:V.handler,params:K}}return null}async handle($,Z,V){try{let K=new URL($.url??"/","http://localhost"),Y=K.pathname.split("/").filter(Boolean),X=$.method??"GET",Q=this.match(X,Y);if(!Q){if(V&&X==="GET"){await V($,Z,K.pathname);return}throw new H(404,`Unknown route: ${X} ${K.pathname}`)}let z=await R7($);await Q.handler({req:$,res:Z,params:Q.params,query:K.searchParams,body:z})}catch(K){if(Z.headersSent){Z.end();return}let Y=K instanceof H?K.status:500,X=K instanceof Error?K.message:String(K);L(Z,Y,{error:X})}}}import*as g$ from"node:fs";import*as x from"node:path";var F7=new Set(["health","repos","events","follow"]),q7={".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"},T4="no-cache",S7="public, max-age=31536000, immutable";async function L4($,Z,V){let K;try{K=await g$.promises.readFile(Z)}catch{throw new H(404,`Not found: ${x.basename(Z)}`)}$.writeHead(200,{"content-type":q7[x.extname(Z)]??"application/octet-stream","cache-control":V,"content-length":K.length}),$.end(K)}function D4($){let Z=x.resolve($);return async(V,K,Y)=>{let X;try{X=decodeURIComponent(Y)}catch{throw new H(400,`Malformed percent-encoding in path: ${Y}`)}if(X.includes("\x00"))throw new H(400,"Invalid path");let Q=X.split("/").filter(Boolean);if(Q.length>0&&F7.has(Q[0]))throw new H(404,`Unknown route: GET ${Y}`);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 g$.promises.stat(z).catch(()=>null))?.isFile()){await L4(K,z,Q[0]==="assets"?S7:T4);return}await L4(K,x.join(Z,"index.html"),T4)}}function E7($){try{let Z=new URL(`http://${$}`).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function w7($){try{let Z=new URL($).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function R4($){return $==="localhost"||$==="::1"||$.endsWith(".localhost")||$.startsWith("127.")}function v7($){return $==="127.0.0.1"||$==="::1"||$.startsWith("127.")}function F4($){if($===null)return!1;if(typeof $==="string")return!0;return v7($.address)}function q4($){let Z=$.headers.host;if(Z!==void 0){let Q=E7(Z);if(Q===null||!R4(Q))return{status:421,message:"Host not allowed (loopback only)"}}let V=$.method??"GET";if(!(V!=="GET"&&V!=="HEAD"&&V!=="OPTIONS"))return null;let Y=$.headers["sec-fetch-site"];if(Y&&Y!=="same-origin"&&Y!=="none")return{status:403,message:"Cross-site request blocked"};let X=$.headers.origin;if(X!==void 0&&X!==""){let Q=w7(X);if(Q===null||!R4(Q))return{status:403,message:"Cross-origin request blocked"}}return null}var S4={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"no-referrer","Content-Security-Policy":["default-src 'self'","script-src 'self'","style-src 'self' 'unsafe-inline'","img-src 'self' data:","font-src 'self' data:","connect-src 'self'","object-src 'none'","base-uri 'self'","frame-ancestors 'none'"].join("; ")};import{createHash as I8}from"node:crypto";class E4{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 u$=new Map;function w4($){let Z=u$.get($);if(!Z)Z=new E4,u$.set($,Z);return Z}function v4($){u$.delete($)}import*as v from"node:path";import*as m from"node:fs";import{execFileSync as $8}from"node:child_process";import{watch as v5}from"chokidar";import{EventEmitter as Z8}from"node:events";import k5 from"ignore";function U$($){process.stderr.write(`[diffstalker warn] ${$}
2
- `)}import{simpleGit as k7}from"simple-git";function $$(){return{...process.env,LC_ALL:"C",LANG:"C"}}var P7={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0};function I($){return k7({baseDir:$,unsafe:P7}).env($$())}import{execFileSync as b4}from"node:child_process";import*as Z$ from"node:fs";import*as p$ from"node:path";async function G$($,Z){if(Z.length===0)return new Set;let V=I($),K=new Set,Y=100;for(let X=0;X<Z.length;X+=Y){let Q=Z.slice(X,X+Y);try{let W=(await V.raw(["check-ignore","--",...Q])).trim().split(`
1
+ var O7=Object.create;var{getPrototypeOf:M7,defineProperty:N4,getOwnPropertyNames:B7}=Object;var j7=Object.prototype.hasOwnProperty;function N7($){return this[$]}var H7,A7,C7=($,Z,V)=>{var K=$!=null&&typeof $==="object";if(K){var Y=Z?H7??=new WeakMap:A7??=new WeakMap,X=Y.get($);if(X)return X}V=$!=null?O7(M7($)):{};let Q=Z||!$||!$.__esModule?N4(V,"default",{value:$,enumerable:!0}):V;for(let z of B7($))if(!j7.call(Q,z))N4(Q,z,{get:N7.bind($,z),enumerable:!0});if(K)Y.set($,Q);return Q};var I7=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var v5=I7((D9,w5)=>{var y=-1,k=1,w=0;function W$($,Z,V,K,Y){if($===Z){if($)return[[w,$]];return[]}if(V!=null){var X=e7($,Z,V);if(X)return X}var Q=i$($,Z),z=$.substring(0,Q);$=$.substring(Q),Z=Z.substring(Q),Q=L$($,Z);var W=$.substring($.length-Q);$=$.substring(0,$.length-Q),Z=Z.substring(0,Z.length-Q);var J=l7($,Z);if(z)J.unshift([w,z]);if(W)J.push([w,W]);if(r$(J,Y),K)o7(J);return J}function l7($,Z){var V;if(!$)return[[k,Z]];if(!Z)return[[y,$]];var K=$.length>Z.length?$:Z,Y=$.length>Z.length?Z:$,X=K.indexOf(Y);if(X!==-1){if(V=[[k,K.substring(0,X)],[w,Y],[k,K.substring(X+Y.length)]],$.length>Z.length)V[0][0]=V[2][0]=y;return V}if(Y.length===1)return[[y,$],[k,Z]];var Q=a7($,Z);if(Q){var z=Q[0],W=Q[1],J=Q[2],U=Q[3],G=Q[4],O=W$(z,J),M=W$(W,U);return O.concat([[w,G]],M)}return n7($,Z)}function n7($,Z){var V=$.length,K=Z.length,Y=Math.ceil((V+K)/2),X=Y,Q=2*Y,z=Array(Q),W=Array(Q);for(var J=0;J<Q;J++)z[J]=-1,W[J]=-1;z[X+1]=0,W[X+1]=0;var U=V-K,G=U%2!==0,O=0,M=0,j=0,D=0;for(var R=0;R<Y;R++){for(var L=-R+O;L<=R-M;L+=2){var S=X+L,F;if(L===-R||L!==R&&z[S-1]<z[S+1])F=z[S+1];else F=z[S-1]+1;var B=F-L;while(F<V&&B<K&&$.charAt(F)===Z.charAt(B))F++,B++;if(z[S]=F,F>V)M+=2;else if(B>K)O+=2;else if(G){var N=X+U-L;if(N>=0&&N<Q&&W[N]!==-1){var A=V-W[N];if(F>=A)return I5($,Z,F,B)}}}for(var E=-R+j;E<=R-D;E+=2){var N=X+E,A;if(E===-R||E!==R&&W[N-1]<W[N+1])A=W[N+1];else A=W[N-1]+1;var q=A-E;while(A<V&&q<K&&$.charAt(V-A-1)===Z.charAt(K-q-1))A++,q++;if(W[N]=A,A>V)D+=2;else if(q>K)j+=2;else if(!G){var S=X+U-E;if(S>=0&&S<Q&&z[S]!==-1){var F=z[S],B=X+F-S;if(A=V-A,F>=A)return I5($,Z,F,B)}}}}return[[y,$],[k,Z]]}function I5($,Z,V,K){var Y=$.substring(0,V),X=Z.substring(0,K),Q=$.substring(V),z=Z.substring(K),W=W$(Y,X),J=W$(Q,z);return W.concat(J)}function i$($,Z){if(!$||!Z||$.charAt(0)!==Z.charAt(0))return 0;var V=0,K=Math.min($.length,Z.length),Y=K,X=0;while(V<Y){if($.substring(X,Y)==Z.substring(X,Y))V=Y,X=V;else K=Y;Y=Math.floor((K-V)/2+V)}if(F5($.charCodeAt(Y-1)))Y--;return Y}function T5($,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 Y=Math.min(V,K);if($==Z)return Y;var X=0,Q=1;while(!0){var z=$.substring(Y-Q),W=Z.indexOf(z);if(W==-1)return X;if(Q+=W,W==0||$.substring(Y-Q)==Z.substring(0,Q))X=Q,Q++}}function L$($,Z){if(!$||!Z||$.slice(-1)!==Z.slice(-1))return 0;var V=0,K=Math.min($.length,Z.length),Y=K,X=0;while(V<Y){if($.substring($.length-Y,$.length-X)==Z.substring(Z.length-Y,Z.length-X))V=Y,X=V;else K=Y;Y=Math.floor((K-V)/2+V)}if(q5($.charCodeAt($.length-Y)))Y--;return Y}function a7($,Z){var V=$.length>Z.length?$:Z,K=$.length>Z.length?Z:$;if(V.length<4||K.length*2<V.length)return null;function Y(M,j,D){var R=M.substring(D,D+Math.floor(M.length/4)),L=-1,S="",F,B,N,A;while((L=j.indexOf(R,L+1))!==-1){var E=i$(M.substring(D),j.substring(L)),q=L$(M.substring(0,D),j.substring(0,L));if(S.length<q+E)S=j.substring(L-q,L)+j.substring(L,L+E),F=M.substring(0,D-q),B=M.substring(D+E),N=j.substring(0,L-q),A=j.substring(L+E)}if(S.length*2>=M.length)return[F,B,N,A,S];else return null}var X=Y(V,K,Math.ceil(V.length/4)),Q=Y(V,K,Math.ceil(V.length/2)),z;if(!X&&!Q)return null;else if(!Q)z=X;else if(!X)z=Q;else z=X[4].length>Q[4].length?X:Q;var W,J,U,G;if($.length>Z.length)W=z[0],J=z[1],U=z[2],G=z[3];else U=z[0],G=z[1],W=z[2],J=z[3];var O=z[4];return[W,J,U,G,O]}function o7($){var Z=!1,V=[],K=0,Y=null,X=0,Q=0,z=0,W=0,J=0;while(X<$.length){if($[X][0]==w)V[K++]=X,Q=W,z=J,W=0,J=0,Y=$[X][1];else{if($[X][0]==k)W+=$[X][1].length;else J+=$[X][1].length;if(Y&&Y.length<=Math.max(Q,z)&&Y.length<=Math.max(W,J))$.splice(V[K-1],0,[y,Y]),$[V[K-1]+1][0]=k,K--,K--,X=K>0?V[K-1]:-1,Q=0,z=0,W=0,J=0,Y=null,Z=!0}X++}if(Z)r$($);r7($),X=1;while(X<$.length){if($[X-1][0]==y&&$[X][0]==k){var U=$[X-1][1],G=$[X][1],O=T5(U,G),M=T5(G,U);if(O>=M){if(O>=U.length/2||O>=G.length/2)$.splice(X,0,[w,G.substring(0,O)]),$[X-1][1]=U.substring(0,U.length-O),$[X+1][1]=G.substring(O),X++}else if(M>=U.length/2||M>=G.length/2)$.splice(X,0,[w,U.substring(0,M)]),$[X-1][0]=k,$[X-1][1]=G.substring(0,G.length-M),$[X+1][0]=y,$[X+1][1]=U.substring(M),X++;X++}X++}}var L5=/[^a-zA-Z0-9]/,D5=/\s/,R5=/[\r\n]/,s7=/\n\r?\n$/,i7=/^\r?\n\r?\n/;function r7($){function Z(M,j){if(!M||!j)return 6;var D=M.charAt(M.length-1),R=j.charAt(0),L=D.match(L5),S=R.match(L5),F=L&&D.match(D5),B=S&&R.match(D5),N=F&&D.match(R5),A=B&&R.match(R5),E=N&&M.match(s7),q=A&&j.match(i7);if(E||q)return 5;else if(N||A)return 4;else if(L&&!F&&B)return 3;else if(F||B)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],Y=$[V][1],X=$[V+1][1],Q=L$(K,Y);if(Q){var z=Y.substring(Y.length-Q);K=K.substring(0,K.length-Q),Y=z+Y.substring(0,Y.length-Q),X=z+X}var W=K,J=Y,U=X,G=Z(K,Y)+Z(Y,X);while(Y.charAt(0)===X.charAt(0)){K+=Y.charAt(0),Y=Y.substring(1)+X.charAt(0),X=X.substring(1);var O=Z(K,Y)+Z(Y,X);if(O>=G)G=O,W=K,J=Y,U=X}if($[V-1][1]!=W){if(W)$[V-1][1]=W;else $.splice(V-1,1),V--;if($[V][1]=J,U)$[V+1][1]=U;else $.splice(V+1,1),V--}}V++}}function r$($,Z){$.push([w,""]);var V=0,K=0,Y=0,X="",Q="",z;while(V<$.length){if(V<$.length-1&&!$[V][1]){$.splice(V,1);continue}switch($[V][0]){case k:Y++,Q+=$[V][1],V++;break;case y:K++,X+=$[V][1],V++;break;case w:var W=V-Y-K-1;if(Z){if(W>=0&&E5($[W][1])){var J=$[W][1].slice(-1);if($[W][1]=$[W][1].slice(0,-1),X=J+X,Q=J+Q,!$[W][1]){$.splice(W,1),V--;var U=W-1;if($[U]&&$[U][0]===k)Y++,Q=$[U][1]+Q,U--;if($[U]&&$[U][0]===y)K++,X=$[U][1]+X,U--;W=U}}if(S5($[V][1])){var J=$[V][1].charAt(0);$[V][1]=$[V][1].slice(1),X+=J,Q+=J}}if(V<$.length-1&&!$[V][1]){$.splice(V,1);break}if(X.length>0||Q.length>0){if(X.length>0&&Q.length>0){if(z=i$(Q,X),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),X=X.substring(z)}if(z=L$(Q,X),z!==0)$[V][1]=Q.substring(Q.length-z)+$[V][1],Q=Q.substring(0,Q.length-z),X=X.substring(0,X.length-z)}var G=Y+K;if(X.length===0&&Q.length===0)$.splice(V-G,G),V=V-G;else if(X.length===0)$.splice(V-G,G,[k,Q]),V=V-G+1;else if(Q.length===0)$.splice(V-G,G,[y,X]),V=V-G+1;else $.splice(V-G,G,[y,X],[k,Q]),V=V-G+2}if(V!==0&&$[V-1][0]===w)$[V-1][1]+=$[V][1],$.splice(V,1);else V++;Y=0,K=0,X="",Q="";break}}if($[$.length-1][1]==="")$.pop();var O=!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),O=!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),O=!0}V++}if(O)r$($,Z)}function F5($){return $>=55296&&$<=56319}function q5($){return $>=56320&&$<=57343}function S5($){return q5($.charCodeAt(0))}function E5($){return F5($.charCodeAt($.length-1))}function t7($){var Z=[];for(var V=0;V<$.length;V++)if($[V][1].length>0)Z.push($[V]);return Z}function s$($,Z,V,K){if(E5($)||S5(K))return null;return t7([[w,$],[y,Z],[k,V],[w,K]])}function e7($,Z,V){var K=typeof V==="number"?{index:V,length:0}:V.oldRange,Y=typeof V==="number"?null:V.newRange,X=$.length,Q=Z.length;if(K.length===0&&(Y===null||Y.length===0)){var z=K.index,W=$.slice(0,z),J=$.slice(z),U=Y?Y.index:null;$:{var G=z+Q-X;if(U!==null&&U!==G)break $;if(G<0||G>Q)break $;var O=Z.slice(0,G),M=Z.slice(G);if(M!==J)break $;var j=Math.min(z,G),D=W.slice(0,j),R=O.slice(0,j);if(D!==R)break $;var L=W.slice(j),S=O.slice(j);return s$(D,L,S,J)}$:{if(U!==null&&U!==z)break $;var F=z,O=Z.slice(0,F),M=Z.slice(F);if(O!==W)break $;var B=Math.min(X-F,Q-F),N=J.slice(J.length-B),A=M.slice(M.length-B);if(N!==A)break $;var L=J.slice(0,J.length-B),S=M.slice(0,M.length-B);return s$(W,L,S,N)}}if(K.length>0&&Y&&Y.length===0)$:{var D=$.slice(0,K.index),N=$.slice(K.index+K.length),j=D.length,B=N.length;if(Q<j+B)break $;var R=Z.slice(0,j),A=Z.slice(Q-B);if(D!==R||N!==A)break $;var L=$.slice(j,X-B),S=Z.slice(j,Q-B);return s$(D,L,S,N)}return null}function D$($,Z,V,K){return W$($,Z,V,K,!0)}D$.INSERT=k;D$.DELETE=y;D$.EQUAL=w;w5.exports=D$});import*as x$ from"node:fs";import*as j4 from"node:path";import{fileURLToPath as x8}from"node:url";import*as H4 from"node:os";import*as G$ from"node:path";var A4="diffstalker";function O$(){return G$.join(process.env.XDG_CACHE_HOME||G$.join(H4.homedir(),".cache"),A4)}function C4(){return process.env.XDG_RUNTIME_DIR?G$.join(process.env.XDG_RUNTIME_DIR,A4):null}import*as z7 from"node:http";import*as e from"node:fs";import*as W7 from"node:net";function m$($){let Z={};for(let[V,K]of $)Z[V]=K;return Z}function T7($){if(!$)return null;return{staged:m$($.staged),unstaged:m$($.unstaged)}}function l($){return{status:$.status,hunkCounts:T7($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress,mtimes:$.mtimes?m$($.mtimes):null}}function c$($){return $}function L7($){return $.entries.length>0?$.entries[0].seq-1:$.nextSeq-1}function I4($,Z){let V=Z>0?$.entries.filter((K)=>K.seq>Z):$.entries;return{epoch:$.epoch,prunedBefore:L7($),entries:c$(V)}}function Y$($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[V,K]of $)Z[String(V)]=Y$(K);return Z}if(Array.isArray($))return $.map(Y$);if($!==null&&typeof $==="object"){let Z={};for(let[V,K]of Object.entries($))Z[V]=Y$(K);return Z}return $}var D7=1048576;class H extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function T($,Z,V){let K=JSON.stringify(Y$(V));$.writeHead(Z,{"content-type":"application/json"}),$.end(K)}function R7($,Z){if($.segments.length!==Z.length)return null;let V={};for(let K=0;K<$.segments.length;K++){let Y=$.segments[K];if(Y.startsWith(":"))try{V[Y.slice(1)]=decodeURIComponent(Z[K])}catch{throw new H(400,`Malformed percent-encoding in path: ${Z[K]}`)}else if(Y!==Z[K])return null}return V}async function F7($){if($.method!=="POST"&&$.method!=="PUT"&&$.method!=="PATCH")return;let Z=[],V=0;for await(let Y of $){let X=Y;if(V+=X.length,V>D7)throw new H(413,"Request body too large");Z.push(X)}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 g${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=R7(V,Z);if(K)return{handler:V.handler,params:K}}return null}async handle($,Z,V){try{let K=new URL($.url??"/","http://localhost"),Y=K.pathname.split("/").filter(Boolean),X=$.method??"GET",Q=this.match(X,Y);if(!Q){if(V&&X==="GET"){await V($,Z,K.pathname);return}throw new H(404,`Unknown route: ${X} ${K.pathname}`)}let z=await F7($);await Q.handler({req:$,res:Z,params:Q.params,query:K.searchParams,body:z})}catch(K){if(Z.headersSent){Z.end();return}let Y=K instanceof H?K.status:500,X=K instanceof Error?K.message:String(K);T(Z,Y,{error:X})}}}import*as u$ from"node:fs";import*as x from"node:path";var q7=new Set(["health","repos","events","follow"]),S7={".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"},T4="no-cache",E7="public, max-age=31536000, immutable";async function L4($,Z,V){let K;try{K=await u$.promises.readFile(Z)}catch{throw new H(404,`Not found: ${x.basename(Z)}`)}$.writeHead(200,{"content-type":S7[x.extname(Z)]??"application/octet-stream","cache-control":V,"content-length":K.length}),$.end(K)}function D4($){let Z=x.resolve($);return async(V,K,Y)=>{let X;try{X=decodeURIComponent(Y)}catch{throw new H(400,`Malformed percent-encoding in path: ${Y}`)}if(X.includes("\x00"))throw new H(400,"Invalid path");let Q=X.split("/").filter(Boolean);if(Q.length>0&&q7.has(Q[0]))throw new H(404,`Unknown route: GET ${Y}`);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 u$.promises.stat(z).catch(()=>null))?.isFile()){await L4(K,z,Q[0]==="assets"?E7:T4);return}await L4(K,x.join(Z,"index.html"),T4)}}function w7($){try{let Z=new URL(`http://${$}`).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function v7($){try{let Z=new URL($).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function R4($){return $==="localhost"||$==="::1"||$.endsWith(".localhost")||$.startsWith("127.")}function k7($){return $==="127.0.0.1"||$==="::1"||$.startsWith("127.")}function F4($){if($===null)return!1;if(typeof $==="string")return!0;return k7($.address)}function q4($){let Z=$.headers.host;if(Z!==void 0){let Q=w7(Z);if(Q===null||!R4(Q))return{status:421,message:"Host not allowed (loopback only)"}}let V=$.method??"GET";if(!(V!=="GET"&&V!=="HEAD"&&V!=="OPTIONS"))return null;let Y=$.headers["sec-fetch-site"];if(Y&&Y!=="same-origin"&&Y!=="none")return{status:403,message:"Cross-site request blocked"};let X=$.headers.origin;if(X!==void 0&&X!==""){let Q=v7(X);if(Q===null||!R4(Q))return{status:403,message:"Cross-origin request blocked"}}return null}var S4={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"no-referrer","Content-Security-Policy":["default-src 'self'","script-src 'self'","style-src 'self' 'unsafe-inline'","img-src 'self' data:","font-src 'self' data:","connect-src 'self'","object-src 'none'","base-uri 'self'","frame-ancestors 'none'"].join("; ")};import{createHash as L8}from"node:crypto";class E4{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 p$=new Map;function w4($){let Z=p$.get($);if(!Z)Z=new E4,p$.set($,Z);return Z}function v4($){p$.delete($)}import*as v from"node:path";import*as m from"node:fs";import{execFileSync as V8}from"node:child_process";import{watch as k5}from"chokidar";import{EventEmitter as K8}from"node:events";import P5 from"ignore";function M$($){process.stderr.write(`[diffstalker warn] ${$}
2
+ `)}import{simpleGit as P7}from"simple-git";function $$(){return{...process.env,LC_ALL:"C",LANG:"C"}}var y7={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0};function I($){return P7({baseDir:$,unsafe:y7}).env($$())}import{execFileSync as b4}from"node:child_process";import*as Z$ from"node:fs";import*as h$ from"node:path";async function B$($,Z){if(Z.length===0)return new Set;let V=I($),K=new Set,Y=100;for(let X=0;X<Z.length;X+=Y){let Q=Z.slice(X,X+Y);try{let W=(await V.raw(["check-ignore","--",...Q])).trim().split(`
3
3
  `).filter((J)=>J.length>0);for(let J of W)K.add(J)}catch{}}return K}function P4($){let Z=new Map;for(let V of $.trim().split(`
4
- `)){if(!V)continue;let K=V.split("\t");if(K.length>=3){let Y=K[0]==="-"?0:parseInt(K[0],10),X=K[1]==="-"?0:parseInt(K[1],10),Q=K.slice(2).join("\t");Z.set(Q,{insertions:Y,deletions:X})}}return Z}async function y7($,Z){try{let V=p$.join($,Z);if(!(await Z$.promises.stat(V)).isFile())return 0;return(await Z$.promises.readFile(V,"utf-8")).split(`
5
- `).filter((X)=>X.length>0).length}catch{return 0}}function y4($){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 h$($){let Z=I($);if(!await Z.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let K=await Z.status(),Y=[],X=new Set,Q=K.files.filter((B)=>B.working_dir==="?").map((B)=>B.path),z=await G$($,Q);for(let B of K.files){if(B.index==="!"||B.working_dir==="!"||z.has(B.path))continue;let j=`${B.path}-${B.index!==" "&&B.index!=="?"}`;if(X.has(j))continue;if(X.add(j),B.index&&B.index!==" "&&B.index!=="?")Y.push({path:B.path,status:y4(B.index),staged:!0});if(B.working_dir&&B.working_dir!==" ")Y.push({path:B.path,status:B.working_dir==="?"?"untracked":y4(B.working_dir),staged:!1})}let[W,J]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),U=P4(W),G=P4(J);for(let B of Y){let j=B.staged?U.get(B.path):G.get(B.path);if(j)B.insertions=j.insertions,B.deletions=j.deletions}let O=Y.filter((B)=>B.status==="untracked");if(O.length>0){let B=await Promise.all(O.map((j)=>y7($,j.path)));for(let j=0;j<O.length;j++)O[j].insertions=B[j],O[j].deletions=0}return{files:Y,branch:{current:K.current||"HEAD",tracking:K.tracking||void 0,ahead:K.ahead,behind:K.behind},isRepo:!0}}async function _4($,Z){await I($).add(["--",Z])}async function x4($,Z){await I($).reset(["HEAD","--",Z])}async function m4($){await I($).add("-A")}async function c4($){await I($).reset(["HEAD"])}async function g4($,Z){await I($).checkout(["--",Z])}async function u4($,Z){await I($).clean("f",["--",Z])}async function p4($,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 h4($){let Z=I($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function f4($,Z){b4("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:$$()})}function d4($,Z){b4("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:$$()})}async function l4($){let K=(await I($).push()).pushed;if(K.length===0)return"Everything up-to-date";return K.map((Y)=>`${Y.local} → ${Y.remote}`).join(", ")}async function n4($){return await I($).fetch(),"Fetch complete"}async function a4($){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 o4($,Z=50){let V=I($);try{return(await V.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 O$($){let Z=I($);try{return(await Z.stashList()).all.map((K,Y)=>({index:Y,message:K.message}))}catch{return[]}}async function s4($,Z){let V=I($),K=["push"];if(Z)K.push("-m",Z);return await V.stash(K),"Stashed"}async function i4($,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 r4($,Z){return await I($).raw(["switch","--",Z]),`Switched to ${Z}`}async function t4($,Z){return await I($).raw(["switch","-c",Z]),`Created ${Z}`}async function e4($,Z=1){return await I($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function $5($,Z){return await I($).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function Z5($,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=(Y)=>Z$.existsSync(p$.join(V,Y));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 V5($){let Z=await g($);if(!Z)throw Error("No operation in progress to abort");return await I($).raw([Z,"--abort"]),`Aborted ${Z}`}async function K5($){return await I($).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function X5($){return(await I($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((K)=>K.length>0)}import*as s from"node:fs";import*as V$ from"node:path";import*as u from"node:fs";import*as a from"node:path";function f$(){return a.join(J$(),"base-branches.json")}function b7(){let $=a.dirname(f$());if(!u.existsSync($))u.mkdirSync($,{recursive:!0})}function Y5(){try{let $=f$();if(u.existsSync($))return JSON.parse(u.readFileSync($,"utf-8"))}catch{}return{}}function _7($){b7(),u.writeFileSync(f$(),JSON.stringify($,null,2)+`
8
- `)}function M$($){let Z=Y5(),V=a.resolve($);return Z[V]}function Q5($,Z){let V=Y5(),K=a.resolve($);V[K]=Z,_7(V)}function z5($){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,Y=0;for(let X of Z)if(X.startsWith("diff --git")||X.startsWith("index ")||X.startsWith("---")||X.startsWith("+++")||X.startsWith("new file")||X.startsWith("deleted file")||X.startsWith("Binary files")||X.startsWith("similarity index")||X.startsWith("rename from")||X.startsWith("rename to"))V.push({type:"header",content:X});else if(X.startsWith("@@")){let Q=z5(X);if(Q)K=Q.oldStart,Y=Q.newStart;V.push({type:"hunk",content:X})}else if(X.startsWith("+"))V.push({type:"addition",content:X,newLineNum:Y++});else if(X.startsWith("-"))V.push({type:"deletion",content:X,oldLineNum:K++});else V.push({type:"context",content:X,oldLineNum:K++,newLineNum:Y++});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 Y=K.match(/^diff --git a\/.+ b\/(.+)$/);if(Y){if(V=Y[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 K$($,Z,V=!1){let K=I($);try{let Y=[];if(V)Y.push("--cached");if(Z)Y.push("--",Z);let X=await K.diff(Y),Q=o(X);return{raw:X,lines:Q}}catch{return{raw:"",lines:[]}}}var x7="4b825dc642cb6eb9a060e54bf8d69288fbee4904",W5="(unborn)",m7=/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(m7.test(K))return W5;throw V}}async function J5($){let Z=I($),K=await H$($)===W5?x7:"HEAD",Y=await Z.raw(["diff","-U3",K,"--"]);return{raw:Y,lines:o(Y)}}var c7=1048576;async function A$($,Z){try{let V=V$.resolve($),K=V$.resolve(V,Z);if(K!==V&&!K.startsWith(V+V$.sep))return{raw:"",lines:[]};let Y,X;try{Y=s.realpathSync(K),X=s.realpathSync(V)}catch{return{raw:"",lines:[]}}if(Y!==X&&!Y.startsWith(X+V$.sep))return{raw:"",lines:[]};let Q=s.statSync(Y);if(!Q.isFile()||Q.size>c7)return{raw:"",lines:[]};let z=s.readFileSync(K,"utf-8"),W=[{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}`}],J=z.endsWith(`
4
+ `)){if(!V)continue;let K=V.split("\t");if(K.length>=3){let Y=K[0]==="-"?0:parseInt(K[0],10),X=K[1]==="-"?0:parseInt(K[1],10),Q=K.slice(2).join("\t");Z.set(Q,{insertions:Y,deletions:X})}}return Z}async function b7($,Z){try{let V=h$.join($,Z);if(!(await Z$.promises.stat(V)).isFile())return 0;return(await Z$.promises.readFile(V,"utf-8")).split(`
5
+ `).filter((X)=>X.length>0).length}catch{return 0}}function y4($){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 f$($){let Z=I($);if(!await Z.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let K=await Z.status(),Y=[],X=new Set,Q=K.files.filter((M)=>M.working_dir==="?").map((M)=>M.path),z=await B$($,Q);for(let M of K.files){if(M.index==="!"||M.working_dir==="!"||z.has(M.path))continue;let j=`${M.path}-${M.index!==" "&&M.index!=="?"}`;if(X.has(j))continue;if(X.add(j),M.index&&M.index!==" "&&M.index!=="?")Y.push({path:M.path,status:y4(M.index),staged:!0});if(M.working_dir&&M.working_dir!==" ")Y.push({path:M.path,status:M.working_dir==="?"?"untracked":y4(M.working_dir),staged:!1})}let[W,J]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),U=P4(W),G=P4(J);for(let M of Y){let j=M.staged?U.get(M.path):G.get(M.path);if(j)M.insertions=j.insertions,M.deletions=j.deletions}let O=Y.filter((M)=>M.status==="untracked");if(O.length>0){let M=await Promise.all(O.map((j)=>b7($,j.path)));for(let j=0;j<O.length;j++)O[j].insertions=M[j],O[j].deletions=0}return{files:Y,branch:{current:K.current||"HEAD",tracking:K.tracking||void 0,ahead:K.ahead,behind:K.behind},isRepo:!0}}async function _4($,Z){await I($).add(["--",Z])}async function x4($,Z){await I($).reset(["HEAD","--",Z])}async function m4($){await I($).add("-A")}async function c4($){await I($).reset(["HEAD"])}async function g4($,Z){await I($).checkout(["--",Z])}async function u4($,Z){await I($).clean("f",["--",Z])}async function p4($,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 h4($){let Z=I($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function f4($,Z){b4("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:$$()})}function d4($,Z){b4("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:$$()})}async function l4($){let K=(await I($).push()).pushed;if(K.length===0)return"Everything up-to-date";return K.map((Y)=>`${Y.local} → ${Y.remote}`).join(", ")}async function n4($){return await I($).fetch(),"Fetch complete"}async function a4($){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 o4($,Z=50){let V=I($);try{return(await V.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 j$($){let Z=I($);try{return(await Z.stashList()).all.map((K,Y)=>({index:Y,message:K.message}))}catch{return[]}}async function s4($,Z){let V=I($),K=["push"];if(Z)K.push("-m",Z);return await V.stash(K),"Stashed"}async function i4($,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 N$($){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 r4($,Z){return await I($).raw(["switch","--",Z]),`Switched to ${Z}`}async function t4($,Z){return await I($).raw(["switch","-c",Z]),`Created ${Z}`}async function e4($,Z=1){return await I($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function $5($,Z){return await I($).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function Z5($,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=(Y)=>Z$.existsSync(h$.join(V,Y));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 V5($){let Z=await g($);if(!Z)throw Error("No operation in progress to abort");return await I($).raw([Z,"--abort"]),`Aborted ${Z}`}async function K5($){return await I($).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function X5($){return(await I($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((K)=>K.length>0)}import*as s from"node:fs";import*as K$ from"node:path";import*as u from"node:fs";import*as a from"node:path";function d$(){return a.join(O$(),"base-branches.json")}function _7(){let $=a.dirname(d$());if(!u.existsSync($))u.mkdirSync($,{recursive:!0})}function Y5(){try{let $=d$();if(u.existsSync($))return JSON.parse(u.readFileSync($,"utf-8"))}catch{}return{}}function x7($){_7(),u.writeFileSync(d$(),JSON.stringify($,null,2)+`
8
+ `)}function V$($){let Z=Y5(),V=a.resolve($);return Z[V]}function Q5($,Z){let V=Y5(),K=a.resolve($);V[K]=Z,x7(V)}function z5($){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,Y=0;for(let X of Z)if(X.startsWith("diff --git")||X.startsWith("index ")||X.startsWith("---")||X.startsWith("+++")||X.startsWith("new file")||X.startsWith("deleted file")||X.startsWith("Binary files")||X.startsWith("similarity index")||X.startsWith("rename from")||X.startsWith("rename to"))V.push({type:"header",content:X});else if(X.startsWith("@@")){let Q=z5(X);if(Q)K=Q.oldStart,Y=Q.newStart;V.push({type:"hunk",content:X})}else if(X.startsWith("+"))V.push({type:"addition",content:X,newLineNum:Y++});else if(X.startsWith("-"))V.push({type:"deletion",content:X,oldLineNum:K++});else V.push({type:"context",content:X,oldLineNum:K++,newLineNum:Y++});return V}function H$($){let Z=new Map;if(!$)return Z;let V=null;for(let K of $.split(`
10
+ `))if(K.startsWith("diff --git")){let Y=K.match(/^diff --git a\/.+ b\/(.+)$/);if(Y){if(V=Y[1],!Z.has(V))Z.set(V,0)}}else if(K.startsWith("@@")&&V)Z.set(V,(Z.get(V)??0)+1);return Z}class A$ extends Error{constructor($){super(`No common history with ${$}`);this.name="NoCommonHistoryError"}}async function X$($,Z,V=!1){let K=I($);try{let Y=[];if(V)Y.push("--cached");if(Z)Y.push("--",Z);let X=await K.diff(Y),Q=o(X);return{raw:X,lines:Q}}catch{return{raw:"",lines:[]}}}var m7="4b825dc642cb6eb9a060e54bf8d69288fbee4904",W5="(unborn)",c7=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function C$($){let Z=I($);try{return(await Z.raw(["rev-parse","HEAD"])).trim()}catch(V){let K=V instanceof Error?V.message:String(V);if(c7.test(K))return W5;throw V}}async function J5($){let Z=I($),K=await C$($)===W5?m7:"HEAD",Y=await Z.raw(["diff","-U3",K,"--"]);return{raw:Y,lines:o(Y)}}var g7=1048576;async function I$($,Z){try{let V=K$.resolve($),K=K$.resolve(V,Z);if(K!==V&&!K.startsWith(V+K$.sep))return{raw:"",lines:[]};let Y,X;try{Y=s.realpathSync(K),X=s.realpathSync(V)}catch{return{raw:"",lines:[]}}if(Y!==X&&!Y.startsWith(X+K$.sep))return{raw:"",lines:[]};let Q=s.statSync(Y);if(!Q.isFile()||Q.size>g7)return{raw:"",lines:[]};let z=s.readFileSync(K,"utf-8"),W=[{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}`}],J=z.endsWith(`
11
11
  `),U=z.split(`
12
- `);if(J)U.pop();if(z.length>0){W.push({type:"hunk",content:`@@ -0,0 +1,${U.length} @@`});let O=1;for(let B of U)W.push({type:"addition",content:"+"+B,newLineNum:O++});if(!J)W.push({type:"context",content:"\"})}return{raw:W.map((O)=>O.content).join(`
13
- `),lines:W}}catch{return{raw:"",lines:[]}}}async function d$($){let Z=I($),V=new Set,K=[];try{let Y=await Z.raw(["log","--oneline","--decorate=short","--all","-n","200"]),X=/\(([^)]+)\)/g;for(let Q of Y.split(`
14
- `)){let z=X.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 U=J.replace(/^.*-> /,"");if(U.includes("/")&&!V.has(U))V.add(U),K.push(U)}}X.lastIndex=0}if(K.length>0)K.sort((Q,z)=>{let W=Q.split("/").slice(1).join("/"),J=z.split("/").slice(1).join("/"),U=W==="main"||W==="master",G=J==="main"||J==="master";if(U&&!G)return-1;if(!U&&G)return 1;if(U&&G){let O=Q.startsWith("origin/"),B=z.startsWith("origin/");if(O&&!B)return 1;if(!O&&B)return-1}return 0})}catch{}return[...new Set(K)]}async function l$($){return(await d$($))[0]??null}async function n$($){return M$($)??await l$($)}async function n($,Z){let V=I($);try{return await V.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}async function a$($,Z){let V=I($),Y=(await V.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Y)throw new N$(Z);let X=await V.raw(["diff","--numstat",`${Y}...HEAD`]),Q=await V.raw(["diff","--name-status",`${Y}...HEAD`]),z=await V.raw(["diff",`${Y}...HEAD`]),W=X.trim().split(`
15
- `).filter((M)=>M),J=new Map;for(let M of W){let N=M.split("\t");if(N.length>=3){let A=N[0]==="-"?0:parseInt(N[0],10),E=N[1]==="-"?0:parseInt(N[1],10),q=N.slice(2).join("\t");J.set(q,{additions:A,deletions:E})}}let U=Q.trim().split(`
16
- `).filter((M)=>M),G=new Map;for(let M of U){let N=M.split("\t");if(N.length>=2){let A=N[0][0],E=N[N.length-1],q;switch(A){case"A":q="added";break;case"D":q="deleted";break;case"R":q="renamed";break;default:q="modified"}G.set(E,q)}}let O=[],B=z.split(/(?=^diff --git )/m).filter((M)=>M.trim());for(let M of B){let N=M.match(/^diff --git a\/.+ b\/(.+)$/m);if(!N)continue;let A=N[1],E=o(M),q=J.get(A)||{additions:0,deletions:0},d=G.get(A)||"modified";O.push({path:A,status:d,additions:q.additions,deletions:q.deletions,diff:{raw:M,lines:E}})}let j=0,D=0;for(let M of O)j+=M.additions,D+=M.deletions;let T=(await V.status()).files.length,F=(await V.log({from:Y,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 O.sort((M,N)=>M.path.localeCompare(N.path)),{baseBranch:Z,stats:{filesChanged:O.length,additions:j,deletions:D},files:O,commits:F,uncommittedCount:T}}async function U5($,Z){let V=I($);try{let K=await V.raw(["show","--format=","--end-of-options",Z]),Y=o(K);return{raw:K,lines:Y}}catch{return{raw:"",lines:[]}}}async function G5($,Z){let V=I($),K=await a$($,Z),Y=await V.diff(["--cached","--numstat"]),X=await V.diff(["--numstat"]),Q=await V.diff(["--cached"]),z=await V.diff([]),W=new Map;for(let M of Y.trim().split(`
18
- `).filter((N)=>N)){let N=M.split("\t");if(N.length>=3){let A=N[0]==="-"?0:parseInt(N[0],10),E=N[1]==="-"?0:parseInt(N[1],10),q=N.slice(2).join("\t");W.set(q,{additions:A,deletions:E,staged:!0,unstaged:!1})}}for(let M of X.trim().split(`
19
- `).filter((N)=>N)){let N=M.split("\t");if(N.length>=3){let A=N[0]==="-"?0:parseInt(N[0],10),E=N[1]==="-"?0:parseInt(N[1],10),q=N.slice(2).join("\t"),d=W.get(q);if(d)d.additions+=A,d.deletions+=E,d.unstaged=!0;else W.set(q,{additions:A,deletions:E,staged:!1,unstaged:!0})}}let J=await V.status(),U=new Map;for(let M of J.files)if(M.index==="A"||M.working_dir==="?")U.set(M.path,"added");else if(M.index==="D"||M.working_dir==="D")U.set(M.path,"deleted");else if(M.index==="R")U.set(M.path,"renamed");else U.set(M.path,"modified");let G=[],B=(Q+z).split(/(?=^diff --git )/m).filter((M)=>M.trim()),j=new Set;for(let M of B){let N=M.match(/^diff --git a\/.+ b\/(.+)$/m);if(!N)continue;let A=N[1];if(j.has(A))continue;j.add(A);let E=o(M),q=W.get(A)||{additions:0,deletions:0},d=U.get(A)||"modified";G.push({path:A,status:d,additions:q.additions,deletions:q.deletions,diff:{raw:M,lines:E},isUncommitted:!0})}let D=new Set(K.files.map((M)=>M.path)),R=[];for(let M of K.files){let N=G.find((A)=>A.path===M.path);if(N)R.push(M),R.push(N);else R.push(M)}for(let M of G)if(!D.has(M.path))R.push(M);let T=0,S=0,F=new Set;for(let M of R)F.add(M.path),T+=M.additions,S+=M.deletions;return R.sort((M,N)=>M.path.localeCompare(N.path)),{baseBranch:K.baseBranch,stats:{filesChanged:F.size,additions:T,deletions:S},files:R,commits:K.commits,uncommittedCount:K.uncommittedCount}}import*as O5 from"node:fs";import*as B5 from"node:path";var g7=/^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 u7($){let Z=[],V="",K=null,Y=()=>{if(K&&V)Z.push({file:V,key:`${V}\x00${C$(K.body)}`,headerLine:K.headerLine});K=null};for(let X of $.lines)if(X.type==="header"){Y();let Q=X.content.match(g7);if(Q)V=Q[1]}else if(X.type==="hunk")Y(),K={headerLine:X,body:[]};else if(K&&(X.type==="addition"||X.type==="deletion"))K.body.push(X.content);return Y(),Z}class o${repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let V of u7($)){let K=this.stamps.get(V.key);if(K===void 0){let Y=Z.get(V.file);if(Y===void 0)Y=this.mtimeOf(V.file),Z.set(V.file,Y);K=Y,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 O5.statSync(B5.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}import*as p from"node:fs";import*as P from"node:path";async function M5($){let Z=A5($);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 I$($){let Z=A5($);if(!Z)return[];try{let K=await I(Z).raw(["worktree","list","--porcelain"]);return h7(K)}catch{return[]}}function j5($){let Z=null,V=-1/0;for(let K of $){if(K.isBare)continue;let Y=p7(K.path);if(Y>V)V=Y,Z=K}return Z}function p7($){let Z=N5($),V=Z?[P.join(Z,"index"),P.join(Z,"HEAD")]:[$],K=-1/0;for(let Y of V)try{let X=p.statSync(Y).mtimeMs;if(X>K)K=X}catch{}return K}function N5($){let Z=P.join($,".git");try{if(p.statSync(Z).isDirectory())return Z;let V=p.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!V)return null;let K=V[1].trim();return P.isAbsolute(K)?K:P.resolve($,K)}catch{return null}}function H5($){let Z=N5($);if(Z===null)return null;let V=Z;try{let K=p.readFileSync(P.join(Z,"commondir"),"utf8").trim();if(K)V=P.isAbsolute(K)?K:P.resolve(Z,K)}catch{}return{gitDir:Z,commonDir:V}}function h7($){let Z=[],V=null;for(let K of $.split(`
20
- `))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 A5($){try{if(p.statSync($).isDirectory())return $;return P.dirname($)}catch{let Z=P.dirname($);return Z!==$&&p.existsSync(Z)?Z:null}}var t7=A7(w5(),1);var e7=/^diff --git a\/.+ b\/(.+)$/;function t$($){return e7.exec($)?.[1]??null}function D$($){let Z=new Map,V=$.raw.split(`
12
+ `);if(J)U.pop();if(z.length>0){W.push({type:"hunk",content:`@@ -0,0 +1,${U.length} @@`});let O=1;for(let M of U)W.push({type:"addition",content:"+"+M,newLineNum:O++});if(!J)W.push({type:"context",content:"\"})}return{raw:W.map((O)=>O.content).join(`
13
+ `),lines:W}}catch{return{raw:"",lines:[]}}}async function l$($){let Z=I($),V=new Set,K=[];try{let Y=await Z.raw(["log","--oneline","--decorate=short","--all","-n","200"]),X=/\(([^)]+)\)/g;for(let Q of Y.split(`
14
+ `)){let z=X.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 U=J.replace(/^.*-> /,"");if(U.includes("/")&&!V.has(U))V.add(U),K.push(U)}}X.lastIndex=0}if(K.length>0)K.sort((Q,z)=>{let W=Q.split("/").slice(1).join("/"),J=z.split("/").slice(1).join("/"),U=W==="main"||W==="master",G=J==="main"||J==="master";if(U&&!G)return-1;if(!U&&G)return 1;if(U&&G){let O=Q.startsWith("origin/"),M=z.startsWith("origin/");if(O&&!M)return 1;if(!O&&M)return-1}return 0})}catch{}return[...new Set(K)]}async function Q$($){return(await l$($))[0]??null}async function n$($){return V$($)??await Q$($)}async function n($,Z){let V=I($);try{return await V.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}async function a$($,Z){let V=I($),Y=(await V.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Y)throw new A$(Z);let X=await V.raw(["diff","--numstat",`${Y}...HEAD`]),Q=await V.raw(["diff","--name-status",`${Y}...HEAD`]),z=await V.raw(["diff",`${Y}...HEAD`]),W=X.trim().split(`
15
+ `).filter((B)=>B),J=new Map;for(let B of W){let N=B.split("\t");if(N.length>=3){let A=N[0]==="-"?0:parseInt(N[0],10),E=N[1]==="-"?0:parseInt(N[1],10),q=N.slice(2).join("\t");J.set(q,{additions:A,deletions:E})}}let U=Q.trim().split(`
16
+ `).filter((B)=>B),G=new Map;for(let B of U){let N=B.split("\t");if(N.length>=2){let A=N[0][0],E=N[N.length-1],q;switch(A){case"A":q="added";break;case"D":q="deleted";break;case"R":q="renamed";break;default:q="modified"}G.set(E,q)}}let O=[],M=z.split(/(?=^diff --git )/m).filter((B)=>B.trim());for(let B of M){let N=B.match(/^diff --git a\/.+ b\/(.+)$/m);if(!N)continue;let A=N[1],E=o(B),q=J.get(A)||{additions:0,deletions:0},d=G.get(A)||"modified";O.push({path:A,status:d,additions:q.additions,deletions:q.deletions,diff:{raw:B,lines:E}})}let j=0,D=0;for(let B of O)j+=B.additions,D+=B.deletions;let L=(await V.status()).files.length,F=(await V.log({from:Y,to:"HEAD"})).all.map((B)=>({hash:B.hash,shortHash:B.hash.slice(0,7),message:B.message.split(`
17
+ `)[0],author:B.author_name,date:new Date(B.date),refs:B.refs||""}));return O.sort((B,N)=>B.path.localeCompare(N.path)),{baseBranch:Z,stats:{filesChanged:O.length,additions:j,deletions:D},files:O,commits:F,uncommittedCount:L}}async function U5($,Z){let V=I($);try{let K=await V.raw(["show","--format=","--end-of-options",Z]),Y=o(K);return{raw:K,lines:Y}}catch{return{raw:"",lines:[]}}}async function G5($,Z){let V=I($),K=await a$($,Z),Y=await V.diff(["--cached","--numstat"]),X=await V.diff(["--numstat"]),Q=await V.diff(["--cached"]),z=await V.diff([]),W=new Map;for(let B of Y.trim().split(`
18
+ `).filter((N)=>N)){let N=B.split("\t");if(N.length>=3){let A=N[0]==="-"?0:parseInt(N[0],10),E=N[1]==="-"?0:parseInt(N[1],10),q=N.slice(2).join("\t");W.set(q,{additions:A,deletions:E,staged:!0,unstaged:!1})}}for(let B of X.trim().split(`
19
+ `).filter((N)=>N)){let N=B.split("\t");if(N.length>=3){let A=N[0]==="-"?0:parseInt(N[0],10),E=N[1]==="-"?0:parseInt(N[1],10),q=N.slice(2).join("\t"),d=W.get(q);if(d)d.additions+=A,d.deletions+=E,d.unstaged=!0;else W.set(q,{additions:A,deletions:E,staged:!1,unstaged:!0})}}let J=await V.status(),U=new Map;for(let B of J.files)if(B.index==="A"||B.working_dir==="?")U.set(B.path,"added");else if(B.index==="D"||B.working_dir==="D")U.set(B.path,"deleted");else if(B.index==="R")U.set(B.path,"renamed");else U.set(B.path,"modified");let G=[],M=(Q+z).split(/(?=^diff --git )/m).filter((B)=>B.trim()),j=new Set;for(let B of M){let N=B.match(/^diff --git a\/.+ b\/(.+)$/m);if(!N)continue;let A=N[1];if(j.has(A))continue;j.add(A);let E=o(B),q=W.get(A)||{additions:0,deletions:0},d=U.get(A)||"modified";G.push({path:A,status:d,additions:q.additions,deletions:q.deletions,diff:{raw:B,lines:E},isUncommitted:!0})}let D=new Set(K.files.map((B)=>B.path)),R=[];for(let B of K.files){let N=G.find((A)=>A.path===B.path);if(N)R.push(B),R.push(N);else R.push(B)}for(let B of G)if(!D.has(B.path))R.push(B);let L=0,S=0,F=new Set;for(let B of R)F.add(B.path),L+=B.additions,S+=B.deletions;return R.sort((B,N)=>B.path.localeCompare(N.path)),{baseBranch:K.baseBranch,stats:{filesChanged:F.size,additions:L,deletions:S},files:R,commits:K.commits,uncommittedCount:K.uncommittedCount}}import*as O5 from"node:fs";import*as M5 from"node:path";var u7=/^diff --git a\/.+ b\/(.+)$/;function T$($){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 p7($){let Z=[],V="",K=null,Y=()=>{if(K&&V)Z.push({file:V,key:`${V}\x00${T$(K.body)}`,headerLine:K.headerLine});K=null};for(let X of $.lines)if(X.type==="header"){Y();let Q=X.content.match(u7);if(Q)V=Q[1]}else if(X.type==="hunk")Y(),K={headerLine:X,body:[]};else if(K&&(X.type==="addition"||X.type==="deletion"))K.body.push(X.content);return Y(),Z}class o${repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let V of p7($)){let K=this.stamps.get(V.key);if(K===void 0){let Y=Z.get(V.file);if(Y===void 0)Y=this.mtimeOf(V.file),Z.set(V.file,Y);K=Y,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 O5.statSync(M5.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}import*as p from"node:fs";import*as P from"node:path";async function B5($){let Z=C5($);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 z$($){let Z=C5($);if(!Z)return[];try{let K=await I(Z).raw(["worktree","list","--porcelain"]),Y=d7(K),X=await f7(Y,Z);return Y.map((Q)=>({...Q,lastActivity:Q.isBare?null:h7(N5(Q.path)),aheadOfBase:X.get(Q.path)??null}))}catch{return[]}}function h7($){return Number.isFinite($)?$:null}async function f7($,Z){let V=$.filter((X)=>!X.isBare);if(V.length===0)return new Map;let K=await Q$(Z).catch(()=>null),Y=await Promise.all(V.map(async(X)=>{let Q=V$(X.path)??K;if(!Q)return null;try{let W=await I(X.path).raw(["rev-list","--count","--end-of-options",`${Q}..HEAD`]);return[X.path,parseInt(W.trim(),10)]}catch{return null}}));return new Map(Y.filter((X)=>X!==null))}function j5($){let Z=null,V=-1/0;for(let K of $){if(K.isBare)continue;let Y=N5(K.path);if(Y>V)V=Y,Z=K}return Z}function N5($){let Z=H5($),V=Z?[P.join(Z,"index"),P.join(Z,"HEAD")]:[$],K=-1/0;for(let Y of V)try{let X=p.statSync(Y).mtimeMs;if(X>K)K=X}catch{}return K}function H5($){let Z=P.join($,".git");try{if(p.statSync(Z).isDirectory())return Z;let V=p.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!V)return null;let K=V[1].trim();return P.isAbsolute(K)?K:P.resolve($,K)}catch{return null}}function A5($){let Z=H5($);if(Z===null)return null;let V=Z;try{let K=p.readFileSync(P.join(Z,"commondir"),"utf8").trim();if(K)V=P.isAbsolute(K)?K:P.resolve(Z,K)}catch{}return{gitDir:Z,commonDir:V}}function d7($){let Z=[],V=null;for(let K of $.split(`
20
+ `))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 C5($){try{if(p.statSync($).isDirectory())return $;return P.dirname($)}catch{let Z=P.dirname($);return Z!==$&&p.existsSync(Z)?Z:null}}var $8=C7(v5(),1);var Z8=/^diff --git a\/.+ b\/(.+)$/;function t$($){return Z8.exec($)?.[1]??null}function R$($){let Z=new Map,V=$.raw.split(`
21
21
  `);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=t$(Q);if(z!==null)K=Z.get(z)??{rawLines:[],lines:[]},Z.set(z,K)}K?.rawLines.push(Q)}let Y=null;for(let Q of $.lines){if(Q.type==="header"){let z=t$(Q.content);if(z!==null)Y=Z.get(z)?.lines??null}Y?.push(Q)}let X=new Map;for(let[Q,z]of Z)X.set(Q,{raw:z.rawLines.join(`
22
22
  `)+`
23
- `,lines:z.lines});return X}var R$="diffstalker-journal: oversize untracked snapshot omitted";var V8=262144;class F$ extends Z8{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 o$($)}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=k5();Z.add(".git");let V=v.join(this.repoPath,".gitignore");if(m.existsSync(V))Z.add(m.readFileSync(V,"utf-8"));let K=v.join(this.repoPath,".git","info","exclude");if(m.existsSync(K))Z.add(m.readFileSync(K,"utf-8"));$.set("",Z);try{let Y=$8("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:$$()});for(let X of Y.split("\x00")){if(!X||X===".gitignore")continue;if(!X.endsWith(".gitignore"))continue;let Q=v.dirname(X),z=v.join(this.repoPath,X);try{let W=m.readFileSync(z,"utf-8"),J=k5();J.add(W),$.set(Q,J)}catch(W){U$(`Failed to read ${z}: ${W instanceof Error?W.message:W}`)}}}catch{}return $}startWatching(){let $=H5(this.repoPath);if($===null)return;let Z=v.join($.gitDir,"index"),V=v.join($.gitDir,"HEAD"),K=v.join($.commonDir,"refs"),Y=v.join($.commonDir,"packed-refs"),X=v.join(this.repoPath,".gitignore");this.gitWatcher=v5([Z,V,K,Y,X],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=v5(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(z)=>{let W=v.relative(this.repoPath,z);if(!W)return!1;let J=W.split("/");for(let U=0;U<J.length;U++){let G=U===0?"":J.slice(0,U).join("/"),O=this.ignorers.get(G);if(O){let B=U===0?W:J.slice(U).join("/");if(O.ignores(B))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let Q=()=>this.scheduleRefresh();this.gitWatcher.on("change",(z)=>{if(z===X)this.ignorers=this.loadGitignores();Q()}),this.gitWatcher.on("add",Q),this.gitWatcher.on("unlink",Q),this.gitWatcher.on("error",(z)=>{let W=z instanceof Error?z.message:String(z);this.setError(`Git watcher error: ${W}`)}),this.workingDirWatcher.on("change",Q),this.workingDirWatcher.on("add",Q),this.workingDirWatcher.on("unlink",Q),this.workingDirWatcher.on("error",(z)=>{let W=z instanceof Error?z.message:String(z);this.setError(`Working dir watcher error: ${W}`)})}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,m.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 h$(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 h$(this.repoPath);if(!V.isRepo){this.updateState({status:V,isLoading:!1,error:"Not a git repository"});return}let[K,Y,X,Q,z]=await Promise.all([K$(this.repoPath,void 0,!1),K$(this.repoPath,void 0,!0),O$(this.repoPath),g(this.repoPath),this.gatherJournalInputs(V,Z,$)]),W={unstaged:j$(K.raw),staged:j$(Y.raw)};this.hunkTimes.stamp(K),this.hunkTimes.stamp(Y),this.hunkTimes.prune(new Set(V.files.map((U)=>U.path)));let J=this.statMtimes(V);if(this.updateState({status:V,hunkCounts:W,stashList:X,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 Y of $.files)if(Y.status==="untracked")K.add(Y.path);for(let Y of K)try{let X=m.statSync(v.join(this.repoPath,Y));if(Math.floor(X.mtimeMs)>V)return!0}catch{}return!1}async gatherJournalInputs($,Z,V){if(Z===null)return null;try{let K=await this.snapshotJournalGuard($),Y=await J5(this.repoPath),X=new Set(D$(Y).keys()),Q=[];if(Y.raw)Q.push(Y.raw.endsWith(`
23
+ `,lines:z.lines});return X}var F$="diffstalker-journal: oversize untracked snapshot omitted";var X8=262144;class q$ extends K8{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 o$($)}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=P5();Z.add(".git");let V=v.join(this.repoPath,".gitignore");if(m.existsSync(V))Z.add(m.readFileSync(V,"utf-8"));let K=v.join(this.repoPath,".git","info","exclude");if(m.existsSync(K))Z.add(m.readFileSync(K,"utf-8"));$.set("",Z);try{let Y=V8("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:$$()});for(let X of Y.split("\x00")){if(!X||X===".gitignore")continue;if(!X.endsWith(".gitignore"))continue;let Q=v.dirname(X),z=v.join(this.repoPath,X);try{let W=m.readFileSync(z,"utf-8"),J=P5();J.add(W),$.set(Q,J)}catch(W){M$(`Failed to read ${z}: ${W instanceof Error?W.message:W}`)}}}catch{}return $}startWatching(){let $=A5(this.repoPath);if($===null)return;let Z=v.join($.gitDir,"index"),V=v.join($.gitDir,"HEAD"),K=v.join($.commonDir,"refs"),Y=v.join($.commonDir,"packed-refs"),X=v.join(this.repoPath,".gitignore");this.gitWatcher=k5([Z,V,K,Y,X],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=k5(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(z)=>{let W=v.relative(this.repoPath,z);if(!W)return!1;let J=W.split("/");for(let U=0;U<J.length;U++){let G=U===0?"":J.slice(0,U).join("/"),O=this.ignorers.get(G);if(O){let M=U===0?W:J.slice(U).join("/");if(O.ignores(M))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let Q=()=>this.scheduleRefresh();this.gitWatcher.on("change",(z)=>{if(z===X)this.ignorers=this.loadGitignores();Q()}),this.gitWatcher.on("add",Q),this.gitWatcher.on("unlink",Q),this.gitWatcher.on("error",(z)=>{let W=z instanceof Error?z.message:String(z);this.setError(`Git watcher error: ${W}`)}),this.workingDirWatcher.on("change",Q),this.workingDirWatcher.on("add",Q),this.workingDirWatcher.on("unlink",Q),this.workingDirWatcher.on("error",(z)=>{let W=z instanceof Error?z.message:String(z);this.setError(`Working dir watcher error: ${W}`)})}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,m.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 f$(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 C$(this.repoPath).catch(()=>null);try{let V=await f$(this.repoPath);if(!V.isRepo){this.updateState({status:V,isLoading:!1,error:"Not a git repository"});return}let[K,Y,X,Q,z]=await Promise.all([X$(this.repoPath,void 0,!1),X$(this.repoPath,void 0,!0),j$(this.repoPath),g(this.repoPath),this.gatherJournalInputs(V,Z,$)]),W={unstaged:H$(K.raw),staged:H$(Y.raw)};this.hunkTimes.stamp(K),this.hunkTimes.stamp(Y),this.hunkTimes.prune(new Set(V.files.map((U)=>U.path)));let J=this.statMtimes(V);if(this.updateState({status:V,hunkCounts:W,stashList:X,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),j$(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 Y of $.files)if(Y.status==="untracked")K.add(Y.path);for(let Y of K)try{let X=m.statSync(v.join(this.repoPath,Y));if(Math.floor(X.mtimeMs)>V)return!0}catch{}return!1}async gatherJournalInputs($,Z,V){if(Z===null)return null;try{let K=await this.snapshotJournalGuard($),Y=await J5(this.repoPath),X=new Set(R$(Y).keys()),Q=[];if(Y.raw)Q.push(Y.raw.endsWith(`
24
24
  `)?Y.raw:Y.raw+`
25
- `);let z=[...Y.lines];await this.appendUntrackedSections($,X,Q,z);let W=await H$(this.repoPath);if(Z!==W)return null;let J=await this.snapshotJournalGuard($);if(F$.journalGuardMoved(K,J))return null;if(this.sectionWrittenDuringGather($,X,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 Y=new Set;for(let X of $.files){if(X.status!=="untracked"||Y.has(X.path)||Z.has(X.path))continue;Y.add(X.path);let Q;try{Q=m.statSync(v.join(this.repoPath,X.path))}catch{continue}if(!Q.isFile())continue;if(Q.size>V8){this.appendOversizeSection(X.path,Q,V,K);continue}let z=await A$(this.repoPath,X.path);if(!z.raw)continue;V.push(z.raw.endsWith(`
25
+ `);let z=[...Y.lines];await this.appendUntrackedSections($,X,Q,z);let W=await C$(this.repoPath);if(Z!==W)return null;let J=await this.snapshotJournalGuard($);if(q$.journalGuardMoved(K,J))return null;if(this.sectionWrittenDuringGather($,X,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 Y=new Set;for(let X of $.files){if(X.status!=="untracked"||Y.has(X.path)||Z.has(X.path))continue;Y.add(X.path);let Q;try{Q=m.statSync(v.join(this.repoPath,X.path))}catch{continue}if(!Q.isFile())continue;if(Q.size>X8){this.appendOversizeSection(X.path,Q,V,K);continue}let z=await I$(this.repoPath,X.path);if(!z.raw)continue;V.push(z.raw.endsWith(`
26
26
  `)?z.raw:z.raw+`
27
- `),K.push(...z.lines)}}appendOversizeSection($,Z,V,K){let Y=[`diff --git a/${$} b/${$}`,"new file mode 100644",`${R$} size=${Z.size} mtime=${Math.round(Z.mtimeMs)}`];V.push(Y.join(`
27
+ `),K.push(...z.lines)}}appendOversizeSection($,Z,V,K){let Y=[`diff --git a/${$} b/${$}`,"new file mode 100644",`${F$} size=${Z.size} mtime=${Math.round(Z.mtimeMs)}`];V.push(Y.join(`
28
28
  `)+`
29
- `),K.push(...Y.map((X)=>({type:"header",content:X})))}async stage($){try{await this.queue.enqueueMutation(()=>_4(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(()=>x4(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()=>f4(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()=>d4(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"?()=>u4(this.repoPath,$.path):()=>g4(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(()=>m4(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>c4(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(()=>p4(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 K8}from"node:events";class e$ extends K8{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",()=>l4(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>n4(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>a4(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>s4(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>i4(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",()=>r4(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>t4(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>e4(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>$5(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>Z5(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>V5(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>K5(this.repoPath))}}import{EventEmitter as X8}from"node:events";import{randomBytes as Y8}from"node:crypto";var Q8=262144,z8=500,W8=16777216,b5=Number.MAX_SAFE_INTEGER,J8=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function U8($){let Z=J8.exec($);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldCount:Z[2]!==void 0?parseInt(Z[2],10):1}}function G8($,Z){let V=U8(Z);if(!V)return[];let K=V.oldCount===0?V.oldStart+1:V.oldStart,Y=[],X=null;for(let Q of $){let z=Q.content[0];if(z==="\\")continue;if(z==="-")X=O8(X,K),K++;else if(z==="+")X=X??{hasDel:!1,delStart:0,delEnd:0,anchor:K-1};else P5(Y,X),X=null,K++}return P5(Y,X),Y}function O8($,Z){if(!$)return{hasDel:!0,delStart:Z,delEnd:Z,anchor:Z-1};if(!$.hasDel)$.hasDel=!0,$.delStart=Z;return $.delEnd=Z,$}function P5($,Z){if(!Z)return;$.push(Z.hasDel?[2*Z.delStart,2*Z.delEnd]:[2*Z.anchor,2*Z.anchor+2])}function $4($){if($.length===0)return{start:0,count:0};let Z=1/0,V=-1/0;for(let[X,Q]of $){if(X<Z)Z=X;if(Q>V)V=Q}if(V>=b5)return{start:0,count:0};let K=Math.ceil(Z/2),Y=Math.floor(V/2);return{start:K,count:Y-K+1}}function B8($){let Z=[],V=null,K=[],Y=null;for(let Q of $.lines)if(Q.type==="hunk")Y={header:Q,body:[]},K.push(Y);else if(Y)Y.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(R$));return{hunks:[{runs:[[0,b5]],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=G8(z,Q.content),J=[],U=0,G=0;for(let B of z){let j=B.content[0];if(j==="\\")continue;if(j==="+")U++,J.push(B.content);else if(j==="-")G++,J.push(B.content)}let O=[...Z,Q,...z];return{runs:W,bodyHash:C$(J),ins:U,del:G,span:$4(W),diff:{raw:O.map((B)=>B.content).join(`
29
+ `),K.push(...Y.map((X)=>({type:"header",content:X})))}async stage($){try{await this.queue.enqueueMutation(()=>_4(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(()=>x4(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()=>f4(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()=>d4(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"?()=>u4(this.repoPath,$.path):()=>g4(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(()=>m4(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>c4(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(()=>p4(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(()=>j$(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as Y8}from"node:events";class e$ extends Y8{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",()=>l4(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>n4(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>a4(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>s4(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>i4(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>N$(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>r4(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>t4(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>e4(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>$5(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>Z5(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>V5(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>K5(this.repoPath))}}import{EventEmitter as Q8}from"node:events";import{randomBytes as z8}from"node:crypto";var W8=262144,J8=500,U8=16777216,_5=Number.MAX_SAFE_INTEGER,G8=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function O8($){let Z=G8.exec($);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldCount:Z[2]!==void 0?parseInt(Z[2],10):1}}function M8($,Z){let V=O8(Z);if(!V)return[];let K=V.oldCount===0?V.oldStart+1:V.oldStart,Y=[],X=null;for(let Q of $){let z=Q.content[0];if(z==="\\")continue;if(z==="-")X=B8(X,K),K++;else if(z==="+")X=X??{hasDel:!1,delStart:0,delEnd:0,anchor:K-1};else y5(Y,X),X=null,K++}return y5(Y,X),Y}function B8($,Z){if(!$)return{hasDel:!0,delStart:Z,delEnd:Z,anchor:Z-1};if(!$.hasDel)$.hasDel=!0,$.delStart=Z;return $.delEnd=Z,$}function y5($,Z){if(!Z)return;$.push(Z.hasDel?[2*Z.delStart,2*Z.delEnd]:[2*Z.anchor,2*Z.anchor+2])}function $4($){if($.length===0)return{start:0,count:0};let Z=1/0,V=-1/0;for(let[X,Q]of $){if(X<Z)Z=X;if(Q>V)V=Q}if(V>=_5)return{start:0,count:0};let K=Math.ceil(Z/2),Y=Math.floor(V/2);return{start:K,count:Y-K+1}}function j8($){let Z=[],V=null,K=[],Y=null;for(let Q of $.lines)if(Q.type==="hunk")Y={header:Q,body:[]},K.push(Y);else if(Y)Y.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(F$));return{hunks:[{runs:[[0,_5]],bodyHash:T$([$.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=M8(z,Q.content),J=[],U=0,G=0;for(let M of z){let j=M.content[0];if(j==="\\")continue;if(j==="+")U++,J.push(M.content);else if(j==="-")G++,J.push(M.content)}let O=[...Z,Q,...z];return{runs:W,bodyHash:T$(J),ins:U,del:G,span:$4(W),diff:{raw:O.map((M)=>M.content).join(`
30
30
  `)+`
31
- `,lines:O}}}),renamedFrom:V,hunkless:!1}}function M8($){if($.oversize===!0)return null;return $.diff.raw.length>Q8?null:$.diff}function j8($,Z,V){if($===0&&Z>0)return"shrunk";let K=$+Z;if(K>V)return"expanded";if(K<V)return"shrunk";return"edited"}function y5($,Z){let V=[];return $.forEach((K,Y)=>{for(let[X,Q]of K.runs)V.push({lo:X,hi:Q,node:Z+Y})}),V.sort((K,Y)=>K.lo-Y.lo),V}function N8($,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},Y=(W,J)=>{let U=K(W),G=K(J);if(U!==G)V[U]=G},X=y5($,0),Q=y5(Z,$.length),z=0;for(let W of X){while(z<Q.length&&Q[z].hi<W.lo)z++;for(let J=z;J<Q.length&&Q[J].lo<=W.hi;J++)Y(W.node,Q[J].node)}return V.map((W,J)=>K(J))}function H8($,Z){let V=N8($,Z),K=new Map,Y=(X)=>{let Q=K.get(X);if(!Q)Q={prevIdx:[],nextIdx:[],minLo:1/0},K.set(X,Q);return Q};return $.forEach((X,Q)=>{let z=Y(V[Q]);z.prevIdx.push(Q);for(let[W]of X.runs)if(W<z.minLo)z.minLo=W}),Z.forEach((X,Q)=>{let z=Y(V[$.length+Q]);z.nextIdx.push(Q);for(let[W]of X.runs)if(W<z.minLo)z.minLo=W}),[...K.values()].sort((X,Q)=>X.minLo-Q.minLo)}function A8($,Z,V){let K=[],Y=Z.map(()=>null),X=V;for(let Q of H8($,Z)){let z=Q.prevIdx.map((G)=>$[G]),W=Q.nextIdx.map((G)=>Z[G]);if(z.length===1&&W.length===1&&z[0].bodyHash===W[0].bodyHash){let G=W[0];Y[Q.nextIdx[0]]={seq:z[0].seq,runs:G.runs,bodyHash:G.bodyHash,ins:G.ins,del:G.del};continue}if(W.length===0){for(let G of z)K.push({seq:X++,kind:"reverted",span:$4(G.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[G.seq],siblings:1});continue}let J=z.map((G)=>G.seq),U=z.reduce((G,O)=>G+O.ins+O.del,0);for(let G of Q.nextIdx){let O=Z[G],B={seq:X++,kind:z.length===0?"created":j8(O.ins,O.del,U),span:O.span,stats:{insertions:O.ins,deletions:O.del},diff:M8(O),supersedes:[...J],siblings:W.length};K.push(B),Y[G]={seq:B.seq,runs:O.runs,bodyHash:O.bodyHash,ins:O.ins,del:O.del}}}return{entries:K,nextLive:Y.filter((Q)=>Q!==null)}}function C8($,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,U)=>!V[U]&&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 Y=$[$.length-1].seq,X=Z.map((z,W)=>{return{seq:K[W]??Y,runs:z.runs,bodyHash:z.bodyHash,ins:z.ins,del:z.del}}),Q=$.filter((z,W)=>!V[W]).map((z)=>z.seq);return{carried:X,retired:Q}}function q$(){return{entries:[],epoch:`${Date.now().toString(36)}-${Y8(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class Z4 extends X8{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<=W8)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>z8&&(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((Y,X)=>this.tsFor($,Y)-this.tsFor($,X));for(let Y of K)this.classifyPath(Y,[],V.get(Y).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($),Y=$.status.branch.current===this.store.lastBranch,X=Y?"commit":"checkout",Q=Y?$.headOid.slice(0,7):$.status.branch.current,{resolves:z,newLive:W}=this.carrySurvivors(V,K);Z.push(this.boundary(X,Q,z,$.at)),this.store.live=W;for(let[J,{hunks:U}]of V){if(W.has(J))continue;this.classifyPath(J,[],U,$,!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[Y,X]of this.store.live){if(Z.has(Y)){K.set(Y,X);continue}let Q=$.get(Y);if(!Q){V.push(...X.map((J)=>J.seq));continue}let{carried:z,retired:W}=C8(X,Q.hunks);V.push(...W),K.set(Y,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[Y,{hunks:X,renamedFrom:Q,hunkless:z}]of V){let W=this.store.live.get(Y)??[];if(z&&Q!==null&&W.length>0)continue;this.classifyPath(Y,W,X,$,!1,Z)}this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}handleRenames($,Z,V){for(let[K,Y]of Z){let X=Y.renamedFrom;if(X===null||X===K)continue;if(!this.store.live.has(X)||Z.has(X))continue;let Q=(this.store.live.get(K)??[]).map((z)=>z.seq);this.store.live.set(K,this.store.live.get(X)),this.store.live.delete(X),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 Y=[...this.store.live.keys()].filter((X)=>!Z.has(X)&&!V.has(X));if(Y.length===0)return;if($.stashCount>this.store.lastStashCount){let X=Y.flatMap((Q)=>this.store.live.get(Q).map((z)=>z.seq));K.push(this.boundary("stash","stash",X,$.at));for(let Q of Y)this.store.live.delete(Q);return}for(let X of Y){let Q=this.store.live.get(X);K.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,X),path:X,status:this.statusOf($,X),kind:"reverted",span:$4(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(X)}}classifyPath($,Z,V,K,Y,X){let{entries:Q,nextLive:z}=A8(Z,V,this.store.nextSeq);this.store.nextSeq+=Q.length;let W=this.tsFor(K,$),J=this.statusOf(K,$);for(let U of Q){let G={type:"hunk",seq:U.seq,ts:W,path:$,status:J,kind:U.kind==="created"&&J==="renamed"?"renamed":U.kind,span:U.span,stats:U.stats,diff:U.diff,supersedes:U.supersedes,siblings:U.siblings,seeded:Y};X.push(G)}if(z.length>0)this.store.live.set($,z);else this.store.live.delete($)}parseObservation($){let Z=new Map;for(let[K,Y]of D$($.headDiff))Z.set(K,B8(Y));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 V4{workingTree;remote;journal;repoPath;constructor($,Z){this.repoPath=$;let V=w4($);this.workingTree=new F$($,V),this.remote=new e$($,V,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new Z4(Z??q$()),this.workingTree.on("journal-observation",(K)=>this.journal.observe(K))}dispose(){this.workingTree.dispose(),v4(this.repoPath)}}function T8($){return I8("sha256").update($).digest("hex").slice(0,12)}var L8=32;class _5{cap;stores=new Map;constructor($=L8){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 K4{events;byId=new Map;byPath=new Map;journalStores=new _5;constructor($={}){this.events=$}async openRepo($){let Z=await M5($);if(!Z){let Q=j5(await I$($));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=T8(Z),Y=new V4(Z,this.journalStores.acquire(K));Y.workingTree.startWatching();let X={id:K,path:Z,manager:Y,refCount:1};return this.byId.set(X.id,X),this.byPath.set(Z,X),this.journalStores.prune((Q)=>this.byId.has(Q)),this.events.onOpened?.(X),{handle:X,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 x5=25000;function Q$($,Z,V){$.write(`event: ${Z}
31
+ `,lines:O}}}),renamedFrom:V,hunkless:!1}}function N8($){if($.oversize===!0)return null;return $.diff.raw.length>W8?null:$.diff}function H8($,Z,V){if($===0&&Z>0)return"shrunk";let K=$+Z;if(K>V)return"expanded";if(K<V)return"shrunk";return"edited"}function b5($,Z){let V=[];return $.forEach((K,Y)=>{for(let[X,Q]of K.runs)V.push({lo:X,hi:Q,node:Z+Y})}),V.sort((K,Y)=>K.lo-Y.lo),V}function A8($,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},Y=(W,J)=>{let U=K(W),G=K(J);if(U!==G)V[U]=G},X=b5($,0),Q=b5(Z,$.length),z=0;for(let W of X){while(z<Q.length&&Q[z].hi<W.lo)z++;for(let J=z;J<Q.length&&Q[J].lo<=W.hi;J++)Y(W.node,Q[J].node)}return V.map((W,J)=>K(J))}function C8($,Z){let V=A8($,Z),K=new Map,Y=(X)=>{let Q=K.get(X);if(!Q)Q={prevIdx:[],nextIdx:[],minLo:1/0},K.set(X,Q);return Q};return $.forEach((X,Q)=>{let z=Y(V[Q]);z.prevIdx.push(Q);for(let[W]of X.runs)if(W<z.minLo)z.minLo=W}),Z.forEach((X,Q)=>{let z=Y(V[$.length+Q]);z.nextIdx.push(Q);for(let[W]of X.runs)if(W<z.minLo)z.minLo=W}),[...K.values()].sort((X,Q)=>X.minLo-Q.minLo)}function I8($,Z,V){let K=[],Y=Z.map(()=>null),X=V;for(let Q of C8($,Z)){let z=Q.prevIdx.map((G)=>$[G]),W=Q.nextIdx.map((G)=>Z[G]);if(z.length===1&&W.length===1&&z[0].bodyHash===W[0].bodyHash){let G=W[0];Y[Q.nextIdx[0]]={seq:z[0].seq,runs:G.runs,bodyHash:G.bodyHash,ins:G.ins,del:G.del};continue}if(W.length===0){for(let G of z)K.push({seq:X++,kind:"reverted",span:$4(G.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[G.seq],siblings:1});continue}let J=z.map((G)=>G.seq),U=z.reduce((G,O)=>G+O.ins+O.del,0);for(let G of Q.nextIdx){let O=Z[G],M={seq:X++,kind:z.length===0?"created":H8(O.ins,O.del,U),span:O.span,stats:{insertions:O.ins,deletions:O.del},diff:N8(O),supersedes:[...J],siblings:W.length};K.push(M),Y[G]={seq:M.seq,runs:O.runs,bodyHash:O.bodyHash,ins:O.ins,del:O.del}}}return{entries:K,nextLive:Y.filter((Q)=>Q!==null)}}function T8($,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,U)=>!V[U]&&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 Y=$[$.length-1].seq,X=Z.map((z,W)=>{return{seq:K[W]??Y,runs:z.runs,bodyHash:z.bodyHash,ins:z.ins,del:z.del}}),Q=$.filter((z,W)=>!V[W]).map((z)=>z.seq);return{carried:X,retired:Q}}function S$(){return{entries:[],epoch:`${Date.now().toString(36)}-${z8(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class Z4 extends Q8{store;constructor($){super();this.store=$}get journalStore(){return this.store}observe($){try{this.doObserve($)}catch(Z){M$(`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<=U8)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>J8&&(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((Y,X)=>this.tsFor($,Y)-this.tsFor($,X));for(let Y of K)this.classifyPath(Y,[],V.get(Y).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($),Y=$.status.branch.current===this.store.lastBranch,X=Y?"commit":"checkout",Q=Y?$.headOid.slice(0,7):$.status.branch.current,{resolves:z,newLive:W}=this.carrySurvivors(V,K);Z.push(this.boundary(X,Q,z,$.at)),this.store.live=W;for(let[J,{hunks:U}]of V){if(W.has(J))continue;this.classifyPath(J,[],U,$,!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[Y,X]of this.store.live){if(Z.has(Y)){K.set(Y,X);continue}let Q=$.get(Y);if(!Q){V.push(...X.map((J)=>J.seq));continue}let{carried:z,retired:W}=T8(X,Q.hunks);V.push(...W),K.set(Y,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[Y,{hunks:X,renamedFrom:Q,hunkless:z}]of V){let W=this.store.live.get(Y)??[];if(z&&Q!==null&&W.length>0)continue;this.classifyPath(Y,W,X,$,!1,Z)}this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}handleRenames($,Z,V){for(let[K,Y]of Z){let X=Y.renamedFrom;if(X===null||X===K)continue;if(!this.store.live.has(X)||Z.has(X))continue;let Q=(this.store.live.get(K)??[]).map((z)=>z.seq);this.store.live.set(K,this.store.live.get(X)),this.store.live.delete(X),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 Y=[...this.store.live.keys()].filter((X)=>!Z.has(X)&&!V.has(X));if(Y.length===0)return;if($.stashCount>this.store.lastStashCount){let X=Y.flatMap((Q)=>this.store.live.get(Q).map((z)=>z.seq));K.push(this.boundary("stash","stash",X,$.at));for(let Q of Y)this.store.live.delete(Q);return}for(let X of Y){let Q=this.store.live.get(X);K.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,X),path:X,status:this.statusOf($,X),kind:"reverted",span:$4(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(X)}}classifyPath($,Z,V,K,Y,X){let{entries:Q,nextLive:z}=I8(Z,V,this.store.nextSeq);this.store.nextSeq+=Q.length;let W=this.tsFor(K,$),J=this.statusOf(K,$);for(let U of Q){let G={type:"hunk",seq:U.seq,ts:W,path:$,status:J,kind:U.kind==="created"&&J==="renamed"?"renamed":U.kind,span:U.span,stats:U.stats,diff:U.diff,supersedes:U.supersedes,siblings:U.siblings,seeded:Y};X.push(G)}if(z.length>0)this.store.live.set($,z);else this.store.live.delete($)}parseObservation($){let Z=new Map;for(let[K,Y]of R$($.headDiff))Z.set(K,j8(Y));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 V4{workingTree;remote;journal;repoPath;constructor($,Z){this.repoPath=$;let V=w4($);this.workingTree=new q$($,V),this.remote=new e$($,V,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new Z4(Z??S$()),this.workingTree.on("journal-observation",(K)=>this.journal.observe(K))}dispose(){this.workingTree.dispose(),v4(this.repoPath)}}function D8($){return L8("sha256").update($).digest("hex").slice(0,12)}var R8=32;class x5{cap;stores=new Map;constructor($=R8){this.cap=$}acquire($){let Z=this.stores.get($);if(Z)this.stores.delete($);else Z=S$();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 K4{events;byId=new Map;byPath=new Map;journalStores=new x5;constructor($={}){this.events=$}async openRepo($){let Z=await B5($);if(!Z){let Q=j5(await z$($));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=D8(Z),Y=new V4(Z,this.journalStores.acquire(K));Y.workingTree.startWatching();let X={id:K,path:Z,manager:Y,refCount:1};return this.byId.set(X.id,X),this.byPath.set(Z,X),this.journalStores.prune((Q)=>this.byId.has(Q)),this.events.onOpened?.(X),{handle:X,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 m5=25000;function J$($,Z,V){$.write(`event: ${Z}
32
32
  data: ${V}
33
33
 
34
- `)}class X4{channels=new Map;subscribe($,Z,V,K){K.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let Y=this.channels.get($);if(!Y){let Q=new Set,z={manager:Z,subscribers:Q,listener:(W)=>{let J=JSON.stringify(l(W));if(J===z.lastData)return;z.lastData=J;for(let U of Q)Q$(U,"state-change",J)},journalListener:(W)=>{let J=JSON.stringify({epoch:Z.journal.journalStore.epoch,entries:m$(W)});for(let U of Q)Q$(U,"journal-append",J)},keepAlive:setInterval(()=>{for(let W of Q)W.write(`: ping
34
+ `)}class X4{channels=new Map;subscribe($,Z,V,K){K.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let Y=this.channels.get($);if(!Y){let Q=new Set,z={manager:Z,subscribers:Q,listener:(W)=>{let J=JSON.stringify(l(W));if(J===z.lastData)return;z.lastData=J;for(let U of Q)J$(U,"state-change",J)},journalListener:(W)=>{let J=JSON.stringify({epoch:Z.journal.journalStore.epoch,entries:c$(W)});for(let U of Q)J$(U,"journal-append",J)},keepAlive:setInterval(()=>{for(let W of Q)W.write(`: ping
35
35
 
36
- `)},x5),lastData:null};Z.workingTree.on("state-change",z.listener),Z.journal.on("append",z.journalListener),z.keepAlive.unref(),Y=z,this.channels.set($,Y)}Y.subscribers.add(K),V.on("close",()=>this.unsubscribe($,K));let X=JSON.stringify(l(Z.workingTree.state));Q$(K,"snapshot",X)}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
36
+ `)},m5),lastData:null};Z.workingTree.on("state-change",z.listener),Z.journal.on("append",z.journalListener),z.keepAlive.unref(),Y=z,this.channels.set($,Y)}Y.subscribers.add(K),V.on("close",()=>this.unsubscribe($,K));let X=JSON.stringify(l(Z.workingTree.state));J$(K,"snapshot",X)}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
37
37
 
38
- `)},x5),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),Q$(Z,"snapshot",JSON.stringify(V))}broadcast($,Z){let V=JSON.stringify(Z);for(let K of this.subscribers)Q$(K,$,V)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as i from"node:fs";import*as w$ from"node:path";import{watch as D8}from"chokidar";import{EventEmitter as R8}from"node:events";import*as S$ from"node:fs";import*as E$ from"node:path";import*as Q4 from"node:os";function m5($){if($.startsWith("~/"))return E$.join(Q4.homedir(),$.slice(2));if($==="~")return Q4.homedir();return $}function c5($){let Z=E$.dirname($);if(!S$.existsSync(Z))S$.mkdirSync(Z,{recursive:!0})}function z4($){let Z=$.split(`
39
- `);for(let V=Z.length-1;V>=0;V--){let K=Z[V].trim();if(K)return K}return""}class W4 extends R8{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=m5($);return w$.isAbsolute(Z)?Z:w$.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=i.readFileSync(this.targetFile,"utf-8"),Z=z4($);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
38
+ `)},m5),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),J$(Z,"snapshot",JSON.stringify(V))}broadcast($,Z){let V=JSON.stringify(Z);for(let K of this.subscribers)J$(K,$,V)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as i from"node:fs";import*as v$ from"node:path";import{watch as F8}from"chokidar";import{EventEmitter as q8}from"node:events";import*as E$ from"node:fs";import*as w$ from"node:path";import*as Q4 from"node:os";function c5($){if($.startsWith("~/"))return w$.join(Q4.homedir(),$.slice(2));if($==="~")return Q4.homedir();return $}function g5($){let Z=w$.dirname($);if(!E$.existsSync(Z))E$.mkdirSync(Z,{recursive:!0})}function z4($){let Z=$.split(`
39
+ `);for(let V=Z.length-1;V>=0;V--){let K=Z[V].trim();if(K)return K}return""}class W4 extends q8{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=c5($);return v$.isAbsolute(Z)?Z:v$.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=i.readFileSync(this.targetFile,"utf-8"),Z=z4($);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
40
40
  `),process.stderr.write(` Source file: ${this.targetFile}
41
41
  `),process.stderr.write(` Raw content: "${Z}"
42
42
  `),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
43
43
  `),process.stderr.write(` Resolved: "${V}"
44
- `);this.lastReadPath=V,this.updateState({path:V,lastUpdate:K,rawContent:Z})}}catch{}}start(){if(c5(this.targetFile),!i.existsSync(this.targetFile))i.writeFileSync(this.targetFile,"");try{let $=i.readFileSync(this.targetFile,"utf-8"),Z=z4($);if(Z){let V=this.processContent(Z),K=new Date;if(this.debug&&V)process.stderr.write(`[diffstalker ${K.toISOString()}] Initial path read
44
+ `);this.lastReadPath=V,this.updateState({path:V,lastUpdate:K,rawContent:Z})}}catch{}}start(){if(g5(this.targetFile),!i.existsSync(this.targetFile))i.writeFileSync(this.targetFile,"");try{let $=i.readFileSync(this.targetFile,"utf-8"),Z=z4($);if(Z){let V=this.processContent(Z),K=new Date;if(this.debug&&V)process.stderr.write(`[diffstalker ${K.toISOString()}] Initial path read
45
45
  `),process.stderr.write(` Source file: ${this.targetFile}
46
46
  `),process.stderr.write(` Raw content: "${Z}"
47
47
  `),process.stderr.write(` Resolved: "${V}"
48
- `);this.lastReadPath=V,this._state={path:V,lastUpdate:K,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=D8(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 g5={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class J4{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 W4(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}}import*as u5 from"node:os";function p5($){$.get("/health",({res:Z})=>{L(Z,200,{ok:!0,ready:!0,home:u5.homedir()})})}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 r($,Z){let V=c($,Z);if(V.startsWith("-"))throw new H(400,`Invalid "${Z}" (must not start with "-"): ${V}`);return V}function f5($,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 U4($,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 d5($,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 t($,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 l5($,Z,V,K){let Y=$.get(Z);if(Y===null)return V;let X=Number(Y);if(!Number.isInteger(X)||X<1)throw new H(400,`Invalid "${Z}" (expected a positive integer): ${Y}`);if(K!==void 0&&X>K)throw new H(400,`Invalid "${Z}" (must be <= ${K}): ${Y}`);return X}async function h($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new H(500,"Repository status unavailable");return Z}function h5($,Z,V){let K=$.files.filter((Y)=>Y.path===Z);if(K.length===0)return null;return K.find((Y)=>Y.staged===V)??K[0]}async function k$($,Z,V){let K=await h($),Y=h5(K,Z,V);if(!Y)await $.refresh(),K=await h($),Y=h5(K,Z,V);if(!Y)throw new H(404,`File not in status: ${Z}`);return Y}function G4($,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 n5($){try{return await v$.promises.realpath($)}catch{return null}}async function O4($,Z){let V=await v$.promises.realpath(_.resolve($)),K=await n5(_.join($,Z));if(K===null)return;if(K!==V&&!K.startsWith(V+_.sep))throw new H(400,`Path escapes repository root: ${Z}`)}async function a5($,Z){let V=await v$.promises.realpath(_.resolve($)),K=[];for(let Y of Z){let X=await n5(_.join($,Y.path));if(X===null||X===V||X.startsWith(V+_.sep))K.push(Y)}return K}function B4($){return $?.code??null}function F8($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function f($,Z,V){$.clearError(),await V();let K=$.state.error;if(K){L(Z,F8(K),{error:K});return}await $.refresh(),L(Z,200,{state:l($.state)})}function q8($){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test($)?409:500}async function b($,Z,V){let K=$.manager.remote,Y=()=>new H(409,`A ${K.remoteState.operation??"remote"} operation is already in progress`);if(K.remoteState.inProgress)throw Y();let X=await V();if(X===null)throw Y();if(X.error){L(Z,q8(X.error),{error:X.error});return}let Q=$.manager.workingTree;await Q.refresh(),L(Z,200,{state:l(Q.state),result:X.lastResult})}function o5($,Z){let{registry:V}=Z;$.get("/repos",({res:K})=>{let Y=V.listRepos().map((X)=>({id:X.id,path:X.path,branch:X.manager.workingTree.state.status?.branch.current??null}));L(K,200,Y)}),$.post("/repos",async({body:K,res:Y})=>{let X=c(K,"path"),Q;try{Q=await V.openRepo(X)}catch(z){throw new H(400,z instanceof Error?z.message:String(z))}if(Q.created)Q.handle.manager.workingTree.refresh().catch(()=>{});L(Y,Q.created?201:200,{id:Q.handle.id,path:Q.handle.path})}),$.get("/repos/:id/worktrees",async({params:K,res:Y})=>{let X=C(V,K.id);L(Y,200,await I$(X.path))}),$.delete("/repos/:id",({params:K,res:Y})=>{C(V,K.id),V.closeRepo(K.id),L(Y,200,{})})}function s5($,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 i5($){return $.trim()}async function S8($){let Z=(K)=>K.filter((Y)=>Y.staged).length,V=Z((await h($)).files);if(V===0)await $.refresh(),V=Z((await h($)).files);return V}function r5($,Z){let{registry:V,sse:K}=Z;if($.get("/repos/:id/status",async({params:Y,res:X})=>{let Q=C(V,Y.id);await h(Q.manager.workingTree);let z=l(Q.manager.workingTree.state);z.operationInProgress=await g(Q.path),L(X,200,z)}),$.get("/repos/:id/diff",async({params:Y,query:X,res:Q})=>{let z=C(V,Y.id),W=X.get("path")??void 0,J=t(X,"staged",!1),U;if(W){let O=(await h(z.manager.workingTree)).files.some((B)=>B.path===W&&B.status==="untracked");if(O&&J)throw new H(400,`staged=true is meaningless for untracked file: ${W} (untracked files have no staged diff)`);U=O?await A$(z.path,W):await K$(z.path,W,J)}else U=await K$(z.path,void 0,J);z.manager.workingTree.stampDiff(U),L(Q,200,U)}),$.post("/repos/:id/stage",async({params:Y,body:X,res:Q})=>{let z=C(V,Y.id),W=c(X,"path"),J=z.manager.workingTree,U=await k$(J,W,!1);await f(J,Q,()=>J.stage(U))}),$.post("/repos/:id/unstage",async({params:Y,body:X,res:Q})=>{let z=C(V,Y.id),W=c(X,"path"),J=z.manager.workingTree,U=await k$(J,W,!0);await f(J,Q,()=>J.unstage(U))}),$.get("/repos/:id/events",({params:Y,req:X,res:Q})=>{let z=C(V,Y.id);K.subscribe(Y.id,z.manager,X,Q)}),Z.apiMode==="full")E8($,Z)}function E8($,Z){let{registry:V}=Z;$.post("/repos/:id/stage-all",async({params:K,res:Y})=>{let Q=C(V,K.id).manager.workingTree;await f(Q,Y,()=>Q.stageAll())}),$.post("/repos/:id/unstage-all",async({params:K,res:Y})=>{let Q=C(V,K.id).manager.workingTree;await f(Q,Y,()=>Q.unstageAll())}),$.post("/repos/:id/discard",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=c(Y,"path"),W=Q.manager.workingTree,J=await k$(W,z,!1);if(J.staged)throw new H(409,`Cannot discard a staged file: ${z} (unstage it first)`);await f(W,X,()=>W.discard(J))}),$.post("/repos/:id/commit",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=c(Y,"message",{allowEmpty:!0}),W=d5(Y,"amend"),J=Q.manager.workingTree,U=await S8(J),G=s5(z,U,W);if(!G.valid)throw new H(400,G.error??"Invalid commit");await f(J,X,()=>J.commit(i5(z),W))}),$.post("/repos/:id/stage-hunk",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=c(Y,"patch"),W=Q.manager.workingTree;await f(W,X,()=>W.stageHunk(z))}),$.post("/repos/:id/unstage-hunk",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=c(Y,"patch"),W=Q.manager.workingTree;await f(W,X,()=>W.unstageHunk(z))})}async function w8($){let Z=await n$($);if(Z&&await n($,Z))return Z;if(M$($)){let V=await l$($);if(V&&await n($,V))return V}throw new H(422,"No usable base branch")}function t5($,Z){let{registry:V}=Z;if($.get("/repos/:id/history",async({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=l5(Y,"count",100,5000);L(X,200,await o4(Q.path,z))}),$.get("/repos/:id/commits/:hash/diff",async({params:K,res:Y})=>{let X=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 n(X.path,Q))throw new H(404,`Unknown commit: ${Q}`);L(Y,200,await U5(X.path,Q))}),$.get("/repos/:id/head-message",async({params:K,res:Y})=>{let X=C(V,K.id);L(Y,200,{message:await h4(X.path)})}),$.get("/repos/:id/branches",async({params:K,res:Y})=>{let X=C(V,K.id);L(Y,200,await B$(X.path))}),$.get("/repos/:id/base-branches",async({params:K,res:Y})=>{let X=C(V,K.id);L(Y,200,await d$(X.path))}),$.get("/repos/:id/compare/base",async({params:K,res:Y})=>{let X=C(V,K.id);L(Y,200,{base:await n$(X.path)})}),Z.apiMode==="full")$.put("/repos/:id/compare/base",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"branch");if(!await n(Q.path,z))throw new H(400,`Not a valid base ref: ${z}`);Q5(Q.path,z),L(X,200,{base:z})});$.get("/repos/:id/compare",async({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=t(Y,"uncommitted",!1),W=Y.get("base"),J;if(W!==null){if(!await n(Q.path,W))throw new H(400,`Unknown base ref: ${W}`);J=W}else J=await w8(Q.path);let U;try{U=z?await G5(Q.path,J):await a$(Q.path,J)}catch(G){if(G instanceof N$)throw new H(422,G.message);throw G}L(X,200,U)})}function v8($){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 e5($,Z){let{registry:V}=Z;$.get("/repos/:id/journal",({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=v8(Y);L(X,200,I4(Q.manager.journal.journalStore,z))})}function $7($,Z){let{registry:V}=Z;$.post("/repos/:id/push",async({params:K,res:Y})=>{let X=C(V,K.id);await b(X,Y,()=>X.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:K,res:Y})=>{let X=C(V,K.id);await b(X,Y,()=>X.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:K,res:Y})=>{let X=C(V,K.id);await b(X,Y,()=>X.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=f5(Y,"message");await b(Q,X,()=>Q.manager.remote.stash(z))}),$.post("/repos/:id/stash-pop",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=U4(Y,"index",{min:0,fallback:0});await b(Q,X,()=>Q.manager.remote.stashPop(z))}),$.post("/repos/:id/switch-branch",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"name");await b(Q,X,()=>Q.manager.remote.switchBranch(z))}),$.post("/repos/:id/create-branch",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"name");await b(Q,X,()=>Q.manager.remote.createBranch(z))}),$.post("/repos/:id/soft-reset",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=U4(Y,"count",{min:1,fallback:1});if(!await n(Q.path,`HEAD~${z}`))throw new H(400,`Cannot soft-reset ${z} commit(s): HEAD~${z} does not exist`);await b(Q,X,()=>Q.manager.remote.softReset(z))}),$.post("/repos/:id/cherry-pick",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"hash");await b(Q,X,()=>Q.manager.remote.cherryPick(z))}),$.post("/repos/:id/revert",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"hash");await b(Q,X,()=>Q.manager.remote.revertCommit(z))}),$.post("/repos/:id/abort",async({params:K,res:Y})=>{let X=C(V,K.id);if(!await g(X.path))throw new H(409,"No operation in progress to abort");await b(X,Y,()=>X.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:K,res:Y})=>{let X=C(V,K.id);if(await g(X.path)!=="rebase")throw new H(409,"No rebase in progress to continue");await b(X,Y,()=>X.manager.remote.rebaseContinue())})}import*as P$ from"node:fs";import*as z$ from"node:path";function M4($){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("/"),Y="";for(let X=0;X<K.length-1;X++)Y=Y?`${Y}/${K[X]}`:K[X],Z.directories.add(Y);Z.directories.add("")}return Z}var k8=1048576,Z7=5000;class y$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function V7($,Z,V,K){let Y=V?.hideHidden??!0,X=V?.hideGitignored??!0,Q=z$.join($,Z),z=await P$.promises.readdir(Q,{withFileTypes:!0}),W=z.map((G)=>Z?z$.join(Z,G.name):G.name),J=X?await G$($,W):new Set,U=[];for(let G of z){if(Y&&G.name.startsWith("."))continue;let O=Z?z$.join(Z,G.name):G.name;if(X&&J.has(O))continue;let B=G.isDirectory(),j={name:G.name,path:O,type:B?"dir":"file"};if(K)if(B){if(K.directories.has(O))j.hasChanges=!0}else{let D=K.files.get(O);if(D)j.gitStatus=D.status,j.staged=D.staged}U.push(j)}return U.sort((G,O)=>{if(G.type==="dir"&&O.type!=="dir")return-1;if(G.type!=="dir"&&O.type==="dir")return 1;return G.name.localeCompare(O.name)}),U}function P8($){let Z=Math.min($.length,8192);for(let V=0;V<Z;V++)if($[V]===0)return!0;return!1}async function K7($,Z){let V=z$.join($,Z),K=await P$.promises.stat(V);if(!K.isFile())throw new y$(Z);if(K.size>k8)return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:K.size,totalLines:0};let Y=await P$.promises.readFile(V);if(P8(Y))return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:K.size,totalLines:0};let X=Y.toString("utf-8"),Q=X.split(`
49
- `),z=!1;if(Q.length>Z7)X=Q.slice(0,Z7).join(`
50
- `),z=!0;return{content:X,binary:!1,truncated:z,tooLarge:!1,size:K.size,totalLines:Q.length}}function X7($,Z){let{registry:V}=Z;$.get("/repos/:id/tree",async({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=Y.get("dir")??"",W=t(Y,"hidden",!1),J=t(Y,"ignored",!1);G4(Q.path,z),await O4(Q.path,z);let U=await h(Q.manager.workingTree),G=M4(U.files),O;try{O=await V7(Q.path,z,{hideHidden:!W,hideGitignored:!J},G)}catch(B){let j=B4(B);if(j==="ENOENT")throw new H(404,`No such directory: ${z||"/"}`);if(j==="ENOTDIR")throw new H(400,`Not a directory: ${z}`);throw B}L(X,200,await a5(Q.path,O))}),$.get("/repos/:id/file",async({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=Y.get("path");if(!z)throw new H(400,'Missing "path" query parameter');G4(Q.path,z),await O4(Q.path,z);try{L(X,200,await K7(Q.path,z))}catch(W){if(W instanceof y$)throw new H(400,W.message);let J=B4(W);if(J==="ENOENT"||J==="ENOTDIR")throw new H(404,`No such file: ${z}`);throw W}}),$.get("/repos/:id/files",async({params:K,res:Y})=>{let X=C(V,K.id);L(Y,200,await X5(X.path))})}function Y7($,Z){let{registry:V,daemonEvents:K,follow:Y}=Z;$.get("/events",({req:X,res:Q})=>{let z=V.listRepos().map((W)=>({id:W.id,path:W.path}));K.subscribe(X,Q,z)}),$.get("/follow",({res:X})=>{L(X,200,Y?Y.state:g5)})}function y8($){if(!e.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let V=z7.connect($);V.once("connect",()=>{V.destroy(),Z(!0)}),V.once("error",()=>{V.destroy(),Z(!1)})}catch{Z(!1)}})}function W7($={}){let Z=new X4,V=new Y4,K=new K4({onOpened:(O)=>V.broadcast("repo-opened",{id:O.id,path:O.path}),onClosed:(O)=>{Z.closeRepo(O),V.broadcast("repo-closed",{id:O})}}),Y=$.followFile?new J4(K,V,$.followFile):null,X=new c$,Q=$.apiMode??"full",z={registry:K,sse:Z,daemonEvents:V,follow:Y,apiMode:Q};if(p5(X),o5(X,z),r5(X,z),t5(X,z),e5(X,z),Q==="full")$7(X,z);X7(X,z),Y7(X,z),Y?.start();let W=$.webRoot?D4($.webRoot):void 0,J=Q7.createServer((O,B)=>{for(let[j,D]of Object.entries(S4))B.setHeader(j,D);if(F4(J.address())){let j=q4(O);if(j){L(B,j.status,{error:j.message});return}}X.handle(O,B,W).catch(()=>B.end())}),U=new Set;J.on("connection",(O)=>{U.add(O),O.on("close",()=>U.delete(O))});let G=null;return{address(){return J.address()},getRepo(O){return K.getRepo(O)},async listen(O){if(O.socketPath){if(await y8(O.socketPath))throw Error(`diffstalkerd already running at ${O.socketPath}`);e.rmSync(O.socketPath,{force:!0})}return new Promise((B,j)=>{let D=(T)=>j(T);J.once("error",D);let R=()=>{if(J.removeListener("error",D),G)e.chmodSync(G,384);B()};if(O.fd!==void 0)J.listen({fd:O.fd},R);else if(O.socketPath)G=O.socketPath,process.umask(63),J.listen(O.socketPath,R);else if(O.port!==void 0)J.listen(O.port,"127.0.0.1",R);else j(Error("listen() requires a socketPath, a port, or an fd"))})},close(){Y?.dispose(),Z.destroy(),V.destroy(),K.disposeAll();for(let O of U)O.destroy();return new Promise((O,B)=>{J.close((j)=>{if(G)e.rmSync(G,{force:!0});if(j)B(j);else O()})})}}}var U7="diffstalkerd.sock",_8=3,J7=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
48
+ `);this.lastReadPath=V,this._state={path:V,lastUpdate:K,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=F8(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 u5={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class J4{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 W4(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}}import*as p5 from"node:os";function h5($){$.get("/health",({res:Z})=>{T(Z,200,{ok:!0,ready:!0,home:p5.homedir()})})}import*as k$ 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 r($,Z){let V=c($,Z);if(V.startsWith("-"))throw new H(400,`Invalid "${Z}" (must not start with "-"): ${V}`);return V}function d5($,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 U4($,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 l5($,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 t($,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 n5($,Z,V,K){let Y=$.get(Z);if(Y===null)return V;let X=Number(Y);if(!Number.isInteger(X)||X<1)throw new H(400,`Invalid "${Z}" (expected a positive integer): ${Y}`);if(K!==void 0&&X>K)throw new H(400,`Invalid "${Z}" (must be <= ${K}): ${Y}`);return X}async function h($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new H(500,"Repository status unavailable");return Z}function f5($,Z,V){let K=$.files.filter((Y)=>Y.path===Z);if(K.length===0)return null;return K.find((Y)=>Y.staged===V)??K[0]}async function P$($,Z,V){let K=await h($),Y=f5(K,Z,V);if(!Y)await $.refresh(),K=await h($),Y=f5(K,Z,V);if(!Y)throw new H(404,`File not in status: ${Z}`);return Y}function G4($,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 a5($){try{return await k$.promises.realpath($)}catch{return null}}async function O4($,Z){let V=await k$.promises.realpath(_.resolve($)),K=await a5(_.join($,Z));if(K===null)return;if(K!==V&&!K.startsWith(V+_.sep))throw new H(400,`Path escapes repository root: ${Z}`)}async function o5($,Z){let V=await k$.promises.realpath(_.resolve($)),K=[];for(let Y of Z){let X=await a5(_.join($,Y.path));if(X===null||X===V||X.startsWith(V+_.sep))K.push(Y)}return K}function M4($){return $?.code??null}function S8($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function f($,Z,V){$.clearError(),await V();let K=$.state.error;if(K){T(Z,S8(K),{error:K});return}await $.refresh(),T(Z,200,{state:l($.state)})}function E8($){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test($)?409:500}async function b($,Z,V){let K=$.manager.remote,Y=()=>new H(409,`A ${K.remoteState.operation??"remote"} operation is already in progress`);if(K.remoteState.inProgress)throw Y();let X=await V();if(X===null)throw Y();if(X.error){T(Z,E8(X.error),{error:X.error});return}let Q=$.manager.workingTree;await Q.refresh(),T(Z,200,{state:l(Q.state),result:X.lastResult})}function s5($,Z){let{registry:V}=Z;$.get("/repos",({res:K})=>{let Y=V.listRepos().map((X)=>({id:X.id,path:X.path,branch:X.manager.workingTree.state.status?.branch.current??null}));T(K,200,Y)}),$.post("/repos",async({body:K,res:Y})=>{let X=c(K,"path"),Q;try{Q=await V.openRepo(X)}catch(z){throw new H(400,z instanceof Error?z.message:String(z))}if(Q.created)Q.handle.manager.workingTree.refresh().catch(()=>{});T(Y,Q.created?201:200,{id:Q.handle.id,path:Q.handle.path})}),$.get("/repos/:id/worktrees",async({params:K,res:Y})=>{let X=C(V,K.id);T(Y,200,await z$(X.path))}),$.get("/worktrees",async({query:K,res:Y})=>{let X=K.get("path");if(!X)throw new H(400,'Missing "path" query parameter');T(Y,200,await z$(X))}),$.delete("/repos/:id",({params:K,res:Y})=>{C(V,K.id),V.closeRepo(K.id),T(Y,200,{})})}function i5($,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 r5($){return $.trim()}async function w8($){let Z=(K)=>K.filter((Y)=>Y.staged).length,V=Z((await h($)).files);if(V===0)await $.refresh(),V=Z((await h($)).files);return V}function t5($,Z){let{registry:V,sse:K}=Z;if($.get("/repos/:id/status",async({params:Y,res:X})=>{let Q=C(V,Y.id);await h(Q.manager.workingTree);let z=l(Q.manager.workingTree.state);z.operationInProgress=await g(Q.path),T(X,200,z)}),$.get("/repos/:id/diff",async({params:Y,query:X,res:Q})=>{let z=C(V,Y.id),W=X.get("path")??void 0,J=t(X,"staged",!1),U;if(W){let O=(await h(z.manager.workingTree)).files.some((M)=>M.path===W&&M.status==="untracked");if(O&&J)throw new H(400,`staged=true is meaningless for untracked file: ${W} (untracked files have no staged diff)`);U=O?await I$(z.path,W):await X$(z.path,W,J)}else U=await X$(z.path,void 0,J);z.manager.workingTree.stampDiff(U),T(Q,200,U)}),$.post("/repos/:id/stage",async({params:Y,body:X,res:Q})=>{let z=C(V,Y.id),W=c(X,"path"),J=z.manager.workingTree,U=await P$(J,W,!1);await f(J,Q,()=>J.stage(U))}),$.post("/repos/:id/unstage",async({params:Y,body:X,res:Q})=>{let z=C(V,Y.id),W=c(X,"path"),J=z.manager.workingTree,U=await P$(J,W,!0);await f(J,Q,()=>J.unstage(U))}),$.get("/repos/:id/events",({params:Y,req:X,res:Q})=>{let z=C(V,Y.id);K.subscribe(Y.id,z.manager,X,Q)}),Z.apiMode==="full")v8($,Z)}function v8($,Z){let{registry:V}=Z;$.post("/repos/:id/stage-all",async({params:K,res:Y})=>{let Q=C(V,K.id).manager.workingTree;await f(Q,Y,()=>Q.stageAll())}),$.post("/repos/:id/unstage-all",async({params:K,res:Y})=>{let Q=C(V,K.id).manager.workingTree;await f(Q,Y,()=>Q.unstageAll())}),$.post("/repos/:id/discard",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=c(Y,"path"),W=Q.manager.workingTree,J=await P$(W,z,!1);if(J.staged)throw new H(409,`Cannot discard a staged file: ${z} (unstage it first)`);await f(W,X,()=>W.discard(J))}),$.post("/repos/:id/commit",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=c(Y,"message",{allowEmpty:!0}),W=l5(Y,"amend"),J=Q.manager.workingTree,U=await w8(J),G=i5(z,U,W);if(!G.valid)throw new H(400,G.error??"Invalid commit");await f(J,X,()=>J.commit(r5(z),W))}),$.post("/repos/:id/stage-hunk",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=c(Y,"patch"),W=Q.manager.workingTree;await f(W,X,()=>W.stageHunk(z))}),$.post("/repos/:id/unstage-hunk",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=c(Y,"patch"),W=Q.manager.workingTree;await f(W,X,()=>W.unstageHunk(z))})}async function k8($){let Z=await n$($);if(Z&&await n($,Z))return Z;if(V$($)){let V=await Q$($);if(V&&await n($,V))return V}throw new H(422,"No usable base branch")}function e5($,Z){let{registry:V}=Z;if($.get("/repos/:id/history",async({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=n5(Y,"count",100,5000);T(X,200,await o4(Q.path,z))}),$.get("/repos/:id/commits/:hash/diff",async({params:K,res:Y})=>{let X=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 n(X.path,Q))throw new H(404,`Unknown commit: ${Q}`);T(Y,200,await U5(X.path,Q))}),$.get("/repos/:id/head-message",async({params:K,res:Y})=>{let X=C(V,K.id);T(Y,200,{message:await h4(X.path)})}),$.get("/repos/:id/branches",async({params:K,res:Y})=>{let X=C(V,K.id);T(Y,200,await N$(X.path))}),$.get("/repos/:id/base-branches",async({params:K,res:Y})=>{let X=C(V,K.id);T(Y,200,await l$(X.path))}),$.get("/repos/:id/compare/base",async({params:K,res:Y})=>{let X=C(V,K.id);T(Y,200,{base:await n$(X.path)})}),Z.apiMode==="full")$.put("/repos/:id/compare/base",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"branch");if(!await n(Q.path,z))throw new H(400,`Not a valid base ref: ${z}`);Q5(Q.path,z),T(X,200,{base:z})});$.get("/repos/:id/compare",async({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=t(Y,"uncommitted",!1),W=Y.get("base"),J;if(W!==null){if(!await n(Q.path,W))throw new H(400,`Unknown base ref: ${W}`);J=W}else J=await k8(Q.path);let U;try{U=z?await G5(Q.path,J):await a$(Q.path,J)}catch(G){if(G instanceof A$)throw new H(422,G.message);throw G}T(X,200,U)})}function P8($){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 $7($,Z){let{registry:V}=Z;$.get("/repos/:id/journal",({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=P8(Y);T(X,200,I4(Q.manager.journal.journalStore,z))})}function Z7($,Z){let{registry:V}=Z;$.post("/repos/:id/push",async({params:K,res:Y})=>{let X=C(V,K.id);await b(X,Y,()=>X.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:K,res:Y})=>{let X=C(V,K.id);await b(X,Y,()=>X.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:K,res:Y})=>{let X=C(V,K.id);await b(X,Y,()=>X.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=d5(Y,"message");await b(Q,X,()=>Q.manager.remote.stash(z))}),$.post("/repos/:id/stash-pop",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=U4(Y,"index",{min:0,fallback:0});await b(Q,X,()=>Q.manager.remote.stashPop(z))}),$.post("/repos/:id/switch-branch",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"name");await b(Q,X,()=>Q.manager.remote.switchBranch(z))}),$.post("/repos/:id/create-branch",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"name");await b(Q,X,()=>Q.manager.remote.createBranch(z))}),$.post("/repos/:id/soft-reset",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=U4(Y,"count",{min:1,fallback:1});if(!await n(Q.path,`HEAD~${z}`))throw new H(400,`Cannot soft-reset ${z} commit(s): HEAD~${z} does not exist`);await b(Q,X,()=>Q.manager.remote.softReset(z))}),$.post("/repos/:id/cherry-pick",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"hash");await b(Q,X,()=>Q.manager.remote.cherryPick(z))}),$.post("/repos/:id/revert",async({params:K,body:Y,res:X})=>{let Q=C(V,K.id),z=r(Y,"hash");await b(Q,X,()=>Q.manager.remote.revertCommit(z))}),$.post("/repos/:id/abort",async({params:K,res:Y})=>{let X=C(V,K.id);if(!await g(X.path))throw new H(409,"No operation in progress to abort");await b(X,Y,()=>X.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:K,res:Y})=>{let X=C(V,K.id);if(await g(X.path)!=="rebase")throw new H(409,"No rebase in progress to continue");await b(X,Y,()=>X.manager.remote.rebaseContinue())})}import*as y$ from"node:fs";import*as U$ 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("/"),Y="";for(let X=0;X<K.length-1;X++)Y=Y?`${Y}/${K[X]}`:K[X],Z.directories.add(Y);Z.directories.add("")}return Z}var y8=1048576,V7=5000;class b$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function K7($,Z,V,K){let Y=V?.hideHidden??!0,X=V?.hideGitignored??!0,Q=U$.join($,Z),z=await y$.promises.readdir(Q,{withFileTypes:!0}),W=z.map((G)=>Z?U$.join(Z,G.name):G.name),J=X?await B$($,W):new Set,U=[];for(let G of z){if(Y&&G.name.startsWith("."))continue;let O=Z?U$.join(Z,G.name):G.name;if(X&&J.has(O))continue;let M=G.isDirectory(),j={name:G.name,path:O,type:M?"dir":"file"};if(K)if(M){if(K.directories.has(O))j.hasChanges=!0}else{let D=K.files.get(O);if(D)j.gitStatus=D.status,j.staged=D.staged}U.push(j)}return U.sort((G,O)=>{if(G.type==="dir"&&O.type!=="dir")return-1;if(G.type!=="dir"&&O.type==="dir")return 1;return G.name.localeCompare(O.name)}),U}function b8($){let Z=Math.min($.length,8192);for(let V=0;V<Z;V++)if($[V]===0)return!0;return!1}async function X7($,Z){let V=U$.join($,Z),K=await y$.promises.stat(V);if(!K.isFile())throw new b$(Z);if(K.size>y8)return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:K.size,totalLines:0};let Y=await y$.promises.readFile(V);if(b8(Y))return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:K.size,totalLines:0};let X=Y.toString("utf-8"),Q=X.split(`
49
+ `),z=!1;if(Q.length>V7)X=Q.slice(0,V7).join(`
50
+ `),z=!0;return{content:X,binary:!1,truncated:z,tooLarge:!1,size:K.size,totalLines:Q.length}}function Y7($,Z){let{registry:V}=Z;$.get("/repos/:id/tree",async({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=Y.get("dir")??"",W=t(Y,"hidden",!1),J=t(Y,"ignored",!1);G4(Q.path,z),await O4(Q.path,z);let U=await h(Q.manager.workingTree),G=B4(U.files),O;try{O=await K7(Q.path,z,{hideHidden:!W,hideGitignored:!J},G)}catch(M){let j=M4(M);if(j==="ENOENT")throw new H(404,`No such directory: ${z||"/"}`);if(j==="ENOTDIR")throw new H(400,`Not a directory: ${z}`);throw M}T(X,200,await o5(Q.path,O))}),$.get("/repos/:id/file",async({params:K,query:Y,res:X})=>{let Q=C(V,K.id),z=Y.get("path");if(!z)throw new H(400,'Missing "path" query parameter');G4(Q.path,z),await O4(Q.path,z);try{T(X,200,await X7(Q.path,z))}catch(W){if(W instanceof b$)throw new H(400,W.message);let J=M4(W);if(J==="ENOENT"||J==="ENOTDIR")throw new H(404,`No such file: ${z}`);throw W}}),$.get("/repos/:id/files",async({params:K,res:Y})=>{let X=C(V,K.id);T(Y,200,await X5(X.path))})}function Q7($,Z){let{registry:V,daemonEvents:K,follow:Y}=Z;$.get("/events",({req:X,res:Q})=>{let z=V.listRepos().map((W)=>({id:W.id,path:W.path}));K.subscribe(X,Q,z)}),$.get("/follow",({res:X})=>{T(X,200,Y?Y.state:u5)})}function _8($){if(!e.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let V=W7.connect($);V.once("connect",()=>{V.destroy(),Z(!0)}),V.once("error",()=>{V.destroy(),Z(!1)})}catch{Z(!1)}})}function J7($={}){let Z=new X4,V=new Y4,K=new K4({onOpened:(O)=>V.broadcast("repo-opened",{id:O.id,path:O.path}),onClosed:(O)=>{Z.closeRepo(O),V.broadcast("repo-closed",{id:O})}}),Y=$.followFile?new J4(K,V,$.followFile):null,X=new g$,Q=$.apiMode??"full",z={registry:K,sse:Z,daemonEvents:V,follow:Y,apiMode:Q};if(h5(X),s5(X,z),t5(X,z),e5(X,z),$7(X,z),Q==="full")Z7(X,z);Y7(X,z),Q7(X,z),Y?.start();let W=$.webRoot?D4($.webRoot):void 0,J=z7.createServer((O,M)=>{for(let[j,D]of Object.entries(S4))M.setHeader(j,D);if(F4(J.address())){let j=q4(O);if(j){T(M,j.status,{error:j.message});return}}X.handle(O,M,W).catch(()=>M.end())}),U=new Set;J.on("connection",(O)=>{U.add(O),O.on("close",()=>U.delete(O))});let G=null;return{address(){return J.address()},getRepo(O){return K.getRepo(O)},async listen(O){if(O.socketPath){if(await _8(O.socketPath))throw Error(`diffstalkerd already running at ${O.socketPath}`);e.rmSync(O.socketPath,{force:!0})}return new Promise((M,j)=>{let D=(L)=>j(L);J.once("error",D);let R=()=>{if(J.removeListener("error",D),G)e.chmodSync(G,384);M()};if(O.fd!==void 0)J.listen({fd:O.fd},R);else if(O.socketPath)G=O.socketPath,process.umask(63),J.listen(O.socketPath,R);else if(O.port!==void 0)J.listen(O.port,"127.0.0.1",R);else j(Error("listen() requires a socketPath, a port, or an fd"))})},close(){Y?.dispose(),Z.destroy(),V.destroy(),K.disposeAll();for(let O of U)O.destroy();return new Promise((O,M)=>{J.close((j)=>{if(G)e.rmSync(G,{force:!0});if(j)M(j);else O()})})}}}var G7="diffstalkerd.sock",m8=3,U7=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
51
51
 
52
52
  Usage: diffstalkerd [options]
53
53
 
54
54
  Options:
55
55
  --socket PATH Bind a unix socket at PATH
56
- (default: $XDG_RUNTIME_DIR/diffstalker/${U7})
56
+ (default: $XDG_RUNTIME_DIR/diffstalker/${G7})
57
57
  --port N Bind TCP port N (loopback only) instead of a unix socket
58
58
  --follow-file PATH Hook file to follow (created when missing)
59
59
  (default: ~/.cache/diffstalker/target)
@@ -62,5 +62,5 @@ Options:
62
62
  (default: web/ next to the daemon's compiled module;
63
63
  when missing, the daemon serves the API only)
64
64
  --help, -h Show this help
65
- `;function b$($,Z,V){let K=$[Z];if(K===void 0||K.startsWith("--"))throw Error(`${V} requires a value`);return K}function x8($){let Z={};for(let V=0;V<$.length;V++){let K=$[V];switch(K){case"--help":case"-h":return"help";case"--socket":Z.socketPath=b$($,++V,"--socket");break;case"--port":if(Z.port=Number(b$($,++V,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":Z.followFile=b$($,++V,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;case"--web-root":Z.webRoot=b$($,++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 m8(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function c8($){if($.socketPath!==void 0||$.port!==void 0)return;if(m8()){$.fd=_8;return}let Z=C4();if(!Z)console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
66
- Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1);_$.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=j4.join(Z,U7)}function g8($){let Z=$??b8(new URL("web/",import.meta.url));if(_$.existsSync(Z))return Z;console.error(`diffstalkerd: web UI assets not found at ${Z}; serving API only`);return}function u8($){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${$}/`)}async function p8(){process.title="diffstalkerd";let $;try{$=x8(process.argv.slice(2))}catch(W){console.error(W instanceof Error?W.message:String(W)),console.error(J7),process.exit(2)}if($==="help"){console.log(J7);return}c8($);let Z=$.noFollow?void 0:$.followFile??j4.join(J$(),"target"),V=g8($.webRoot),K=$.port!==void 0?"web":"full",Y=W7({followFile:Z,webRoot:V,apiMode:K});if(await Y.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 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)u8($.port)}let X=!1,Q=(W)=>{if(X)return;X=!0,console.error(`Received ${W}, shutting down`),Y.close().then(()=>process.exit(0)).catch((J)=>{console.error(J instanceof Error?J.message:String(J)),process.exit(1)})};process.on("SIGINT",()=>Q("SIGINT")),process.on("SIGTERM",()=>Q("SIGTERM")),process.on("SIGHUP",()=>Q("SIGHUP"));let z=(W,J)=>{console.error(`diffstalkerd ${W}:`,J instanceof Error?J.stack??J.message:J),Y.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(W)=>z("uncaught exception",W)),process.on("unhandledRejection",(W)=>z("unhandled rejection",W))}p8().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{x8 as parseArgs};
65
+ `;function _$($,Z,V){let K=$[Z];if(K===void 0||K.startsWith("--"))throw Error(`${V} requires a value`);return K}function c8($){let Z={};for(let V=0;V<$.length;V++){let K=$[V];switch(K){case"--help":case"-h":return"help";case"--socket":Z.socketPath=_$($,++V,"--socket");break;case"--port":if(Z.port=Number(_$($,++V,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":Z.followFile=_$($,++V,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;case"--web-root":Z.webRoot=_$($,++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 g8(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function u8($){if($.socketPath!==void 0||$.port!==void 0)return;if(g8()){$.fd=m8;return}let Z=C4();if(!Z)console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
66
+ Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1);x$.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=j4.join(Z,G7)}function p8($){let Z=$??x8(new URL("web/",import.meta.url));if(x$.existsSync(Z))return Z;console.error(`diffstalkerd: web UI assets not found at ${Z}; serving API only`);return}function h8($){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${$}/`)}async function f8(){process.title="diffstalkerd";let $;try{$=c8(process.argv.slice(2))}catch(W){console.error(W instanceof Error?W.message:String(W)),console.error(U7),process.exit(2)}if($==="help"){console.log(U7);return}u8($);let Z=$.noFollow?void 0:$.followFile??j4.join(O$(),"target"),V=p8($.webRoot),K=$.port!==void 0?"web":"full",Y=J7({followFile:Z,webRoot:V,apiMode:K});if(await Y.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 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)h8($.port)}let X=!1,Q=(W)=>{if(X)return;X=!0,console.error(`Received ${W}, shutting down`),Y.close().then(()=>process.exit(0)).catch((J)=>{console.error(J instanceof Error?J.message:String(J)),process.exit(1)})};process.on("SIGINT",()=>Q("SIGINT")),process.on("SIGTERM",()=>Q("SIGTERM")),process.on("SIGHUP",()=>Q("SIGHUP"));let z=(W,J)=>{console.error(`diffstalkerd ${W}:`,J instanceof Error?J.stack??J.message:J),Y.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(W)=>z("uncaught exception",W)),process.on("unhandledRejection",(W)=>z("unhandled rejection",W))}f8().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{c8 as parseArgs};