diffstalkerd 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,54 +1,73 @@
1
- var q7=Object.create;var{getPrototypeOf:R7,defineProperty:I4,getOwnPropertyNames:F7}=Object;var S7=Object.prototype.hasOwnProperty;function E7($){return this[$]}var w7,v7,P7=($,Z,K)=>{var V=$!=null&&typeof $==="object";if(V){var X=Z?w7??=new WeakMap:v7??=new WeakMap,Y=X.get($);if(Y)return Y}K=$!=null?q7(R7($)):{};let Q=Z||!$||!$.__esModule?I4(K,"default",{value:$,enumerable:!0}):K;for(let z of F7($))if(!S7.call(Q,z))I4(Q,z,{get:E7.bind($,z),enumerable:!0});if(V)X.set($,Q);return Q};var k7=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var m5=k7((o9,x5)=>{var y=-1,P=1,w=0;function U$($,Z,K,V,X){if($===Z){if($)return[[w,$]];return[]}if(K!=null){var Y=j8($,Z,K);if(Y)return Y}var Q=Z4($,Z),z=$.substring(0,Q);$=$.substring(Q),Z=Z.substring(Q),Q=R$($,Z);var W=$.substring($.length-Q);$=$.substring(0,$.length-Q),Z=Z.substring(0,Z.length-Q);var J=z8($,Z);if(z)J.unshift([w,z]);if(W)J.push([w,W]);if(K4(J,X),V)U8(J);return J}function z8($,Z){var K;if(!$)return[[P,Z]];if(!Z)return[[y,$]];var V=$.length>Z.length?$:Z,X=$.length>Z.length?Z:$,Y=V.indexOf(X);if(Y!==-1){if(K=[[P,V.substring(0,Y)],[w,X],[P,V.substring(Y+X.length)]],$.length>Z.length)K[0][0]=K[2][0]=y;return K}if(X.length===1)return[[y,$],[P,Z]];var Q=J8($,Z);if(Q){var z=Q[0],W=Q[1],J=Q[2],U=Q[3],O=Q[4],B=U$(z,J),G=U$(W,U);return B.concat([[w,O]],G)}return W8($,Z)}function W8($,Z){var K=$.length,V=Z.length,X=Math.ceil((K+V)/2),Y=X,Q=2*X,z=Array(Q),W=Array(Q);for(var J=0;J<Q;J++)z[J]=-1,W[J]=-1;z[Y+1]=0,W[Y+1]=0;var U=K-V,O=U%2!==0,B=0,G=0,j=0,T=0;for(var q=0;q<X;q++){for(var D=-q+B;D<=q-G;D+=2){var R=Y+D,F;if(D===-q||D!==q&&z[R-1]<z[R+1])F=z[R+1];else F=z[R-1]+1;var M=F-D;while(F<K&&M<V&&$.charAt(F)===Z.charAt(M))F++,M++;if(z[R]=F,F>K)G+=2;else if(M>V)B+=2;else if(O){var N=Y+U-D;if(N>=0&&N<Q&&W[N]!==-1){var A=K-W[N];if(F>=A)return S5($,Z,F,M)}}}for(var E=-q+j;E<=q-T;E+=2){var N=Y+E,A;if(E===-q||E!==q&&W[N-1]<W[N+1])A=W[N+1];else A=W[N-1]+1;var S=A-E;while(A<K&&S<V&&$.charAt(K-A-1)===Z.charAt(V-S-1))A++,S++;if(W[N]=A,A>K)T+=2;else if(S>V)j+=2;else if(!O){var R=Y+U-E;if(R>=0&&R<Q&&z[R]!==-1){var F=z[R],M=Y+F-R;if(A=K-A,F>=A)return S5($,Z,F,M)}}}}return[[y,$],[P,Z]]}function S5($,Z,K,V){var X=$.substring(0,K),Y=Z.substring(0,V),Q=$.substring(K),z=Z.substring(V),W=U$(X,Y),J=U$(Q,z);return W.concat(J)}function Z4($,Z){if(!$||!Z||$.charAt(0)!==Z.charAt(0))return 0;var K=0,V=Math.min($.length,Z.length),X=V,Y=0;while(K<X){if($.substring(Y,X)==Z.substring(Y,X))K=X,Y=K;else V=X;X=Math.floor((V-K)/2+K)}if(k5($.charCodeAt(X-1)))X--;return X}function E5($,Z){var K=$.length,V=Z.length;if(K==0||V==0)return 0;if(K>V)$=$.substring(K-V);else if(K<V)Z=Z.substring(0,K);var X=Math.min(K,V);if($==Z)return X;var Y=0,Q=1;while(!0){var z=$.substring(X-Q),W=Z.indexOf(z);if(W==-1)return Y;if(Q+=W,W==0||$.substring(X-Q)==Z.substring(0,Q))Y=Q,Q++}}function R$($,Z){if(!$||!Z||$.slice(-1)!==Z.slice(-1))return 0;var K=0,V=Math.min($.length,Z.length),X=V,Y=0;while(K<X){if($.substring($.length-X,$.length-Y)==Z.substring(Z.length-X,Z.length-Y))K=X,Y=K;else V=X;X=Math.floor((V-K)/2+K)}if(y5($.charCodeAt($.length-X)))X--;return X}function J8($,Z){var K=$.length>Z.length?$:Z,V=$.length>Z.length?Z:$;if(K.length<4||V.length*2<K.length)return null;function X(G,j,T){var q=G.substring(T,T+Math.floor(G.length/4)),D=-1,R="",F,M,N,A;while((D=j.indexOf(q,D+1))!==-1){var E=Z4(G.substring(T),j.substring(D)),S=R$(G.substring(0,T),j.substring(0,D));if(R.length<S+E)R=j.substring(D-S,D)+j.substring(D,D+E),F=G.substring(0,T-S),M=G.substring(T+E),N=j.substring(0,D-S),A=j.substring(D+E)}if(R.length*2>=G.length)return[F,M,N,A,R];else return null}var Y=X(K,V,Math.ceil(K.length/4)),Q=X(K,V,Math.ceil(K.length/2)),z;if(!Y&&!Q)return null;else if(!Q)z=Y;else if(!Y)z=Q;else z=Y[4].length>Q[4].length?Y:Q;var W,J,U,O;if($.length>Z.length)W=z[0],J=z[1],U=z[2],O=z[3];else U=z[0],O=z[1],W=z[2],J=z[3];var B=z[4];return[W,J,U,O,B]}function U8($){var Z=!1,K=[],V=0,X=null,Y=0,Q=0,z=0,W=0,J=0;while(Y<$.length){if($[Y][0]==w)K[V++]=Y,Q=W,z=J,W=0,J=0,X=$[Y][1];else{if($[Y][0]==P)W+=$[Y][1].length;else J+=$[Y][1].length;if(X&&X.length<=Math.max(Q,z)&&X.length<=Math.max(W,J))$.splice(K[V-1],0,[y,X]),$[K[V-1]+1][0]=P,V--,V--,Y=V>0?K[V-1]:-1,Q=0,z=0,W=0,J=0,X=null,Z=!0}Y++}if(Z)K4($);B8($),Y=1;while(Y<$.length){if($[Y-1][0]==y&&$[Y][0]==P){var U=$[Y-1][1],O=$[Y][1],B=E5(U,O),G=E5(O,U);if(B>=G){if(B>=U.length/2||B>=O.length/2)$.splice(Y,0,[w,O.substring(0,B)]),$[Y-1][1]=U.substring(0,U.length-B),$[Y+1][1]=O.substring(B),Y++}else if(G>=U.length/2||G>=O.length/2)$.splice(Y,0,[w,U.substring(0,G)]),$[Y-1][0]=P,$[Y-1][1]=O.substring(0,O.length-G),$[Y+1][0]=y,$[Y+1][1]=U.substring(G),Y++;Y++}Y++}}var w5=/[^a-zA-Z0-9]/,v5=/\s/,P5=/[\r\n]/,G8=/\n\r?\n$/,O8=/^\r?\n\r?\n/;function B8($){function Z(G,j){if(!G||!j)return 6;var T=G.charAt(G.length-1),q=j.charAt(0),D=T.match(w5),R=q.match(w5),F=D&&T.match(v5),M=R&&q.match(v5),N=F&&T.match(P5),A=M&&q.match(P5),E=N&&G.match(G8),S=A&&j.match(O8);if(E||S)return 5;else if(N||A)return 4;else if(D&&!F&&M)return 3;else if(F||M)return 2;else if(D||R)return 1;return 0}var K=1;while(K<$.length-1){if($[K-1][0]==w&&$[K+1][0]==w){var V=$[K-1][1],X=$[K][1],Y=$[K+1][1],Q=R$(V,X);if(Q){var z=X.substring(X.length-Q);V=V.substring(0,V.length-Q),X=z+X.substring(0,X.length-Q),Y=z+Y}var W=V,J=X,U=Y,O=Z(V,X)+Z(X,Y);while(X.charAt(0)===Y.charAt(0)){V+=X.charAt(0),X=X.substring(1)+Y.charAt(0),Y=Y.substring(1);var B=Z(V,X)+Z(X,Y);if(B>=O)O=B,W=V,J=X,U=Y}if($[K-1][1]!=W){if(W)$[K-1][1]=W;else $.splice(K-1,1),K--;if($[K][1]=J,U)$[K+1][1]=U;else $.splice(K+1,1),K--}}K++}}function K4($,Z){$.push([w,""]);var K=0,V=0,X=0,Y="",Q="",z;while(K<$.length){if(K<$.length-1&&!$[K][1]){$.splice(K,1);continue}switch($[K][0]){case P:X++,Q+=$[K][1],K++;break;case y:V++,Y+=$[K][1],K++;break;case w:var W=K-X-V-1;if(Z){if(W>=0&&_5($[W][1])){var J=$[W][1].slice(-1);if($[W][1]=$[W][1].slice(0,-1),Y=J+Y,Q=J+Q,!$[W][1]){$.splice(W,1),K--;var U=W-1;if($[U]&&$[U][0]===P)X++,Q=$[U][1]+Q,U--;if($[U]&&$[U][0]===y)V++,Y=$[U][1]+Y,U--;W=U}}if(b5($[K][1])){var J=$[K][1].charAt(0);$[K][1]=$[K][1].slice(1),Y+=J,Q+=J}}if(K<$.length-1&&!$[K][1]){$.splice(K,1);break}if(Y.length>0||Q.length>0){if(Y.length>0&&Q.length>0){if(z=Z4(Q,Y),z!==0){if(W>=0)$[W][1]+=Q.substring(0,z);else $.splice(0,0,[w,Q.substring(0,z)]),K++;Q=Q.substring(z),Y=Y.substring(z)}if(z=R$(Q,Y),z!==0)$[K][1]=Q.substring(Q.length-z)+$[K][1],Q=Q.substring(0,Q.length-z),Y=Y.substring(0,Y.length-z)}var O=X+V;if(Y.length===0&&Q.length===0)$.splice(K-O,O),K=K-O;else if(Y.length===0)$.splice(K-O,O,[P,Q]),K=K-O+1;else if(Q.length===0)$.splice(K-O,O,[y,Y]),K=K-O+1;else $.splice(K-O,O,[y,Y],[P,Q]),K=K-O+2}if(K!==0&&$[K-1][0]===w)$[K-1][1]+=$[K][1],$.splice(K,1);else K++;X=0,V=0,Y="",Q="";break}}if($[$.length-1][1]==="")$.pop();var B=!1;K=1;while(K<$.length-1){if($[K-1][0]===w&&$[K+1][0]===w){if($[K][1].substring($[K][1].length-$[K-1][1].length)===$[K-1][1])$[K][1]=$[K-1][1]+$[K][1].substring(0,$[K][1].length-$[K-1][1].length),$[K+1][1]=$[K-1][1]+$[K+1][1],$.splice(K-1,1),B=!0;else if($[K][1].substring(0,$[K+1][1].length)==$[K+1][1])$[K-1][1]+=$[K+1][1],$[K][1]=$[K][1].substring($[K+1][1].length)+$[K+1][1],$.splice(K+1,1),B=!0}K++}if(B)K4($,Z)}function k5($){return $>=55296&&$<=56319}function y5($){return $>=56320&&$<=57343}function b5($){return y5($.charCodeAt(0))}function _5($){return k5($.charCodeAt($.length-1))}function M8($){var Z=[];for(var K=0;K<$.length;K++)if($[K][1].length>0)Z.push($[K]);return Z}function $4($,Z,K,V){if(_5($)||b5(V))return null;return M8([[w,$],[y,Z],[P,K],[w,V]])}function j8($,Z,K){var V=typeof K==="number"?{index:K,length:0}:K.oldRange,X=typeof K==="number"?null:K.newRange,Y=$.length,Q=Z.length;if(V.length===0&&(X===null||X.length===0)){var z=V.index,W=$.slice(0,z),J=$.slice(z),U=X?X.index:null;$:{var O=z+Q-Y;if(U!==null&&U!==O)break $;if(O<0||O>Q)break $;var B=Z.slice(0,O),G=Z.slice(O);if(G!==J)break $;var j=Math.min(z,O),T=W.slice(0,j),q=B.slice(0,j);if(T!==q)break $;var D=W.slice(j),R=B.slice(j);return $4(T,D,R,J)}$:{if(U!==null&&U!==z)break $;var F=z,B=Z.slice(0,F),G=Z.slice(F);if(B!==W)break $;var M=Math.min(Y-F,Q-F),N=J.slice(J.length-M),A=G.slice(G.length-M);if(N!==A)break $;var D=J.slice(0,J.length-M),R=G.slice(0,G.length-M);return $4(W,D,R,N)}}if(V.length>0&&X&&X.length===0)$:{var T=$.slice(0,V.index),N=$.slice(V.index+V.length),j=T.length,M=N.length;if(Q<j+M)break $;var q=Z.slice(0,j),A=Z.slice(Q-M);if(T!==q||N!==A)break $;var D=$.slice(j,Y-M),R=Z.slice(j,Q-M);return $4(T,D,R,N)}return null}function F$($,Z,K,V){return U$($,Z,K,V,!0)}F$.INSERT=P;F$.DELETE=y;F$.EQUAL=w;x5.exports=F$});import*as g$ from"node:fs";import*as C4 from"node:path";import{fileURLToPath as X9}from"node:url";import*as T4 from"node:os";import*as B$ from"node:path";var L4="diffstalker";function M$(){return B$.join(process.env.XDG_CACHE_HOME||B$.join(T4.homedir(),".cache"),L4)}function D4(){return process.env.XDG_RUNTIME_DIR?B$.join(process.env.XDG_RUNTIME_DIR,L4):null}import*as C7 from"node:http";import*as $$ from"node:fs";import*as I7 from"node:net";function u$($){let Z={};for(let[K,V]of $)Z[K]=V;return Z}function y7($){if(!$)return null;return{staged:u$($.staged),unstaged:u$($.unstaged)}}function l($){return{status:$.status,hunkCounts:y7($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress,mtimes:$.mtimes?u$($.mtimes):null}}function p$($){return $}function b7($){return $.entries.length>0?$.entries[0].seq-1:$.nextSeq-1}function q4($,Z){let K=Z>0?$.entries.filter((V)=>V.seq>Z):$.entries;return{epoch:$.epoch,prunedBefore:b7($),entries:p$(K)}}function z$($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[K,V]of $)Z[String(K)]=z$(V);return Z}if(Array.isArray($))return $.map(z$);if($!==null&&typeof $==="object"){let Z={};for(let[K,V]of Object.entries($))Z[K]=z$(V);return Z}return $}var _7=1048576;class H extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function L($,Z,K){let V=JSON.stringify(z$(K));$.writeHead(Z,{"content-type":"application/json"}),$.end(V)}function x7($,Z){if($.segments.length!==Z.length)return null;let K={};for(let V=0;V<$.segments.length;V++){let X=$.segments[V];if(X.startsWith(":"))try{K[X.slice(1)]=decodeURIComponent(Z[V])}catch{throw new H(400,`Malformed percent-encoding in path: ${Z[V]}`)}else if(X!==Z[V])return null}return K}async function m7($){if($.method!=="POST"&&$.method!=="PUT"&&$.method!=="PATCH")return;let Z=[],K=0;for await(let X of $){let Y=X;if(K+=Y.length,K>_7)throw new H(413,"Request body too large");Z.push(Y)}let V=Buffer.concat(Z).toString("utf-8");if(!V.trim())return;try{return JSON.parse(V)}catch{throw new H(400,"Invalid JSON body")}}class h${routes=[];get($,Z){this.add("GET",$,Z)}post($,Z){this.add("POST",$,Z)}put($,Z){this.add("PUT",$,Z)}delete($,Z){this.add("DELETE",$,Z)}add($,Z,K){this.routes.push({method:$,segments:Z.split("/").filter(Boolean),handler:K})}match($,Z){for(let K of this.routes){if(K.method!==$)continue;let V=x7(K,Z);if(V)return{handler:K.handler,params:V}}return null}async handle($,Z,K){try{let V=new URL($.url??"/","http://localhost"),X=V.pathname.split("/").filter(Boolean),Y=$.method??"GET",Q=this.match(Y,X);if(!Q){if(K&&Y==="GET"){await K($,Z,V.pathname);return}throw new H(404,`Unknown route: ${Y} ${V.pathname}`)}let z=await m7($);await Q.handler({req:$,res:Z,params:Q.params,query:V.searchParams,body:z})}catch(V){if(Z.headersSent){Z.end();return}let X=V instanceof H?V.status:500,Y=V instanceof Error?V.message:String(V);L(Z,X,{error:Y})}}}import*as f$ from"node:fs";import*as x from"node:path";var c7=new Set(["health","repos","events","follow"]),g7={".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"},R4="no-cache",u7="public, max-age=31536000, immutable";async function F4($,Z,K){let V;try{V=await f$.promises.readFile(Z)}catch{throw new H(404,`Not found: ${x.basename(Z)}`)}$.writeHead(200,{"content-type":g7[x.extname(Z)]??"application/octet-stream","cache-control":K,"content-length":V.length}),$.end(V)}function S4($){let Z=x.resolve($);return async(K,V,X)=>{let Y;try{Y=decodeURIComponent(X)}catch{throw new H(400,`Malformed percent-encoding in path: ${X}`)}if(Y.includes("\x00"))throw new H(400,"Invalid path");let Q=Y.split("/").filter(Boolean);if(Q.length>0&&c7.has(Q[0]))throw new H(404,`Unknown route: GET ${X}`);let z=Q.length>0?x.resolve(Z,Q.join("/")):Z;if(z!==Z&&!z.startsWith(Z+x.sep))throw new H(403,"Forbidden");if((await f$.promises.stat(z).catch(()=>null))?.isFile()){await F4(V,z,Q[0]==="assets"?u7:R4);return}await F4(V,x.join(Z,"index.html"),R4)}}function p7($){try{let Z=new URL(`http://${$}`).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function h7($){try{let Z=new URL($).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function E4($){return $==="localhost"||$==="::1"||$.endsWith(".localhost")||$.startsWith("127.")}function f7($){return $==="127.0.0.1"||$==="::1"||$.startsWith("127.")}function w4($){if($===null)return!1;if(typeof $==="string")return!0;return f7($.address)}function v4($){let Z=$.headers.host;if(Z!==void 0){let Q=p7(Z);if(Q===null||!E4(Q))return{status:421,message:"Host not allowed (loopback only)"}}let K=$.method??"GET";if(!(K!=="GET"&&K!=="HEAD"&&K!=="OPTIONS"))return null;let X=$.headers["sec-fetch-site"];if(X&&X!=="same-origin"&&X!=="none")return{status:403,message:"Cross-site request blocked"};let Y=$.headers.origin;if(Y!==void 0&&Y!==""){let Q=h7(Y);if(Q===null||!E4(Q))return{status:403,message:"Cross-origin request blocked"}}return null}var P4={"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 c8}from"node:crypto";class k4{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue($){return new Promise((Z,K)=>{this.queue.push({execute:$,resolve:Z,reject:K}),this.processNext()})}enqueueMutation($){return this.pendingMutations++,this.enqueue($).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh($){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await $()}).catch(()=>{this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let $=this.queue.shift();try{let Z=await $.execute();$.resolve(Z)}catch(Z){$.reject(Z instanceof Error?Z:Error(String(Z)))}finally{this.isProcessing=!1,this.processNext()}}}var d$=new Map;function y4($){let Z=d$.get($);if(!Z)Z=new k4,d$.set($,Z);return Z}function b4($){d$.delete($)}import*as v from"node:path";import*as m from"node:fs";import{execFileSync as A8}from"node:child_process";import{watch as g5}from"chokidar";import{EventEmitter as C8}from"node:events";import u5 from"ignore";function j$($){process.stderr.write(`[diffstalker warn] ${$}
2
- `)}import{simpleGit as d7}from"simple-git";function Z$(){return{...process.env,LC_ALL:"C",LANG:"C"}}var l7={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0};function I($){return d7({baseDir:$,unsafe:l7}).env(Z$())}import{execFileSync as c4}from"node:child_process";import*as K$ from"node:fs";import*as l$ from"node:path";async function N$($,Z){if(Z.length===0)return new Set;let K=I($),V=new Set,X=100;for(let Y=0;Y<Z.length;Y+=X){let Q=Z.slice(Y,Y+X);try{let W=(await K.raw(["check-ignore","--",...Q])).trim().split(`
3
- `).filter((J)=>J.length>0);for(let J of W)V.add(J)}catch{}}return V}function x4($){let Z=new Map;for(let K of $.trim().split(`
4
- `)){if(!K)continue;let V=K.split("\t");if(V.length>=3){let X=V[0]==="-"?0:parseInt(V[0],10),Y=V[1]==="-"?0:parseInt(V[1],10),Q=V.slice(2).join("\t");Z.set(Q,{insertions:X,deletions:Y})}}return Z}async function o7($,Z){try{let K=l$.join($,Z);if(!(await K$.promises.stat(K)).isFile())return 0;return(await K$.promises.readFile(K,"utf-8")).split(`
5
- `).filter((Y)=>Y.length>0).length}catch{return 0}}function m4($){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 o$($){let Z=I($);if(!await Z.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let V=await Z.status(),X=[],Y=new Set,Q=V.files.filter((G)=>G.working_dir==="?").map((G)=>G.path),z=await N$($,Q);for(let G of V.files){if(G.index==="!"||G.working_dir==="!"||z.has(G.path))continue;let j=`${G.path}-${G.index!==" "&&G.index!=="?"}`;if(Y.has(j))continue;if(Y.add(j),G.index&&G.index!==" "&&G.index!=="?")X.push({path:G.path,status:m4(G.index),staged:!0});if(G.working_dir&&G.working_dir!==" ")X.push({path:G.path,status:G.working_dir==="?"?"untracked":m4(G.working_dir),staged:!1})}let[W,J]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),U=x4(W),O=x4(J);for(let G of X){let j=G.staged?U.get(G.path):O.get(G.path);if(j)G.insertions=j.insertions,G.deletions=j.deletions}let B=X.filter((G)=>G.status==="untracked");if(B.length>0){let G=await Promise.all(B.map((j)=>o7($,j.path)));for(let j=0;j<B.length;j++)B[j].insertions=G[j],B[j].deletions=0}return{files:X,branch:{current:V.current||"HEAD",tracking:V.tracking||void 0,ahead:V.ahead,behind:V.behind},isRepo:!0}}async function g4($,Z){await I($).add(["--",Z])}async function u4($,Z){await I($).reset(["HEAD","--",Z])}async function p4($){await I($).add("-A")}async function h4($){await I($).reset(["HEAD"])}async function f4($,Z){await I($).checkout(["--",Z])}async function d4($,Z){await I($).clean("f",["--",Z])}async function l4($,Z,K=!1){if(!(await I($).commit(Z,void 0,K?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function o4($){let Z=I($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function a4($,Z){c4("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:Z$()})}function n4($,Z){c4("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:Z$()})}async function s4($){let V=(await I($).push()).pushed;if(V.length===0)return"Everything up-to-date";return V.map((X)=>`${X.local} → ${X.remote}`).join(", ")}async function i4($){return await I($).fetch(),"Fetch complete"}async function r4($){let K=await I($).pull(["--rebase"]);if(K.summary.changes===0&&K.summary.insertions===0&&K.summary.deletions===0)return"Already up-to-date";return`${K.summary.changes} file(s) changed`}async function t4($,Z=50){let K=I($);try{return(await K.log({n:Z})).all.map((X)=>({hash:X.hash,shortHash:X.hash.slice(0,7),message:X.message.split(`
6
- `)[0],author:X.author_name,date:new Date(X.date),refs:X.refs||""}))}catch{return[]}}async function H$($){let Z=I($);try{return(await Z.stashList()).all.map((V,X)=>({index:X,message:V.message}))}catch{return[]}}async function e4($,Z){let K=I($),V=["push"];if(Z)V.push("-m",Z);return await K.stash(V),"Stashed"}async function $5($,Z=0){let K=I($);await K.stash(["pop",`stash@{${Z}}`]);let V=(await K.raw(["diff","--name-only","--diff-filter=U"])).trim();if(V)throw Error(`Stash pop hit conflicts in: ${V.split(`
7
- `).join(", ")}`);return"Stash popped"}async function A$($){let K=await I($).branchLocal();return K.all.map((V)=>({name:V,current:V===K.current,tracking:K.branches[V]?.label||void 0}))}async function Z5($,Z){return await I($).raw(["switch","--",Z]),`Switched to ${Z}`}async function K5($,Z){return await I($).raw(["switch","-c",Z]),`Created ${Z}`}async function V5($,Z=1){return await I($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function Y5($,Z){return await I($).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function X5($,Z){return await I($).raw(["revert","--no-edit","--end-of-options",Z]),"Reverted"}async function g($){let Z=I($),K;try{K=(await Z.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let V=(X)=>K$.existsSync(l$.join(K,X));if(V("rebase-merge")||V("rebase-apply"))return"rebase";if(V("CHERRY_PICK_HEAD"))return"cherry-pick";if(V("REVERT_HEAD"))return"revert";if(V("MERGE_HEAD"))return"merge";return null}async function Q5($){let Z=await g($);if(!Z)throw Error("No operation in progress to abort");return await I($).raw([Z,"--abort"]),`Aborted ${Z}`}async function z5($){return await I($).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function W5($){return(await I($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((V)=>V.length>0)}import*as i from"node:fs";import*as X$ from"node:path";import*as u from"node:fs";import*as n from"node:path";function a$(){return n.join(M$(),"base-branches.json")}function a7(){let $=n.dirname(a$());if(!u.existsSync($))u.mkdirSync($,{recursive:!0})}function J5(){try{let $=a$();if(u.existsSync($))return JSON.parse(u.readFileSync($,"utf-8"))}catch{}return{}}function n7($){a7(),u.writeFileSync(a$(),JSON.stringify($,null,2)+`
8
- `)}function V$($){let Z=J5(),K=n.resolve($);return Z[K]}function U5($,Z){let K=J5(),V=n.resolve($);K[V]=Z,n7(K)}function s($){if($.length===0)return"";return $.map((Z)=>Z.content).join(`
1
+ var V5=Object.create;var{getPrototypeOf:Q5,defineProperty:Y6,getOwnPropertyNames:X5}=Object;var Y5=Object.prototype.hasOwnProperty;function W5($){return this[$]}var J5,z5,U5=($,Z,K)=>{var V=$!=null&&typeof $==="object";if(V){var Q=Z?J5??=new WeakMap:z5??=new WeakMap,X=Q.get($);if(X)return X}K=$!=null?V5(Q5($)):{};let Y=Z||!$||!$.__esModule?Y6(K,"default",{value:$,enumerable:!0}):K;for(let W of X5($))if(!Y5.call(Y,W))Y6(Y,W,{get:W5.bind($,W),enumerable:!0});if(V)Q.set($,Y);return Y};var j5=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var _8=j5((P9,k8)=>{var y=-1,P=1,E=0;function m$($,Z,K,V,Q){if($===Z){if($)return[[E,$]];return[]}if(K!=null){var X=j0($,Z,K);if(X)return X}var Y=bZ($,Z),W=$.substring(0,Y);$=$.substring(Y),Z=Z.substring(Y),Y=VZ($,Z);var J=$.substring($.length-Y);$=$.substring(0,$.length-Y),Z=Z.substring(0,Z.length-Y);var z=V0($,Z);if(W)z.unshift([E,W]);if(J)z.push([E,J]);if(yZ(z,Q),V)Y0(z);return z}function V0($,Z){var K;if(!$)return[[P,Z]];if(!Z)return[[y,$]];var V=$.length>Z.length?$:Z,Q=$.length>Z.length?Z:$,X=V.indexOf(Q);if(X!==-1){if(K=[[P,V.substring(0,X)],[E,Q],[P,V.substring(X+Q.length)]],$.length>Z.length)K[0][0]=K[2][0]=y;return K}if(Q.length===1)return[[y,$],[P,Z]];var Y=X0($,Z);if(Y){var W=Y[0],J=Y[1],z=Y[2],U=Y[3],j=Y[4],O=m$(W,z),M=m$(J,U);return O.concat([[E,j]],M)}return Q0($,Z)}function Q0($,Z){var K=$.length,V=Z.length,Q=Math.ceil((K+V)/2),X=Q,Y=2*Q,W=Array(Y),J=Array(Y);for(var z=0;z<Y;z++)W[z]=-1,J[z]=-1;W[X+1]=0,J[X+1]=0;var U=K-V,j=U%2!==0,O=0,M=0,B=0,I=0;for(var T=0;T<Q;T++){for(var D=-T+O;D<=T-M;D+=2){var C=X+D,A;if(D===-T||D!==T&&W[C-1]<W[C+1])A=W[C+1];else A=W[C-1]+1;var G=A-D;while(A<K&&G<V&&$.charAt(A)===Z.charAt(G))A++,G++;if(W[C]=A,A>K)M+=2;else if(G>V)O+=2;else if(j){var H=X+U-D;if(H>=0&&H<Y&&J[H]!==-1){var L=K-J[H];if(A>=L)return T8($,Z,A,G)}}}for(var v=-T+B;v<=T-I;v+=2){var H=X+v,L;if(v===-T||v!==T&&J[H-1]<J[H+1])L=J[H+1];else L=J[H-1]+1;var R=L-v;while(L<K&&R<V&&$.charAt(K-L-1)===Z.charAt(V-R-1))L++,R++;if(J[H]=L,L>K)I+=2;else if(R>V)B+=2;else if(!j){var C=X+U-v;if(C>=0&&C<Y&&W[C]!==-1){var A=W[C],G=X+A-C;if(L=K-L,A>=L)return T8($,Z,A,G)}}}}return[[y,$],[P,Z]]}function T8($,Z,K,V){var Q=$.substring(0,K),X=Z.substring(0,V),Y=$.substring(K),W=Z.substring(V),J=m$(Q,X),z=m$(Y,W);return J.concat(z)}function bZ($,Z){if(!$||!Z||$.charAt(0)!==Z.charAt(0))return 0;var K=0,V=Math.min($.length,Z.length),Q=V,X=0;while(K<Q){if($.substring(X,Q)==Z.substring(X,Q))K=Q,X=K;else V=Q;Q=Math.floor((V-K)/2+K)}if(R8($.charCodeAt(Q-1)))Q--;return Q}function D8($,Z){var K=$.length,V=Z.length;if(K==0||V==0)return 0;if(K>V)$=$.substring(K-V);else if(K<V)Z=Z.substring(0,K);var Q=Math.min(K,V);if($==Z)return Q;var X=0,Y=1;while(!0){var W=$.substring(Q-Y),J=Z.indexOf(W);if(J==-1)return X;if(Y+=J,J==0||$.substring(Q-Y)==Z.substring(0,Y))X=Y,Y++}}function VZ($,Z){if(!$||!Z||$.slice(-1)!==Z.slice(-1))return 0;var K=0,V=Math.min($.length,Z.length),Q=V,X=0;while(K<Q){if($.substring($.length-Q,$.length-X)==Z.substring(Z.length-Q,Z.length-X))K=Q,X=K;else V=Q;Q=Math.floor((V-K)/2+K)}if(v8($.charCodeAt($.length-Q)))Q--;return Q}function X0($,Z){var K=$.length>Z.length?$:Z,V=$.length>Z.length?Z:$;if(K.length<4||V.length*2<K.length)return null;function Q(M,B,I){var T=M.substring(I,I+Math.floor(M.length/4)),D=-1,C="",A,G,H,L;while((D=B.indexOf(T,D+1))!==-1){var v=bZ(M.substring(I),B.substring(D)),R=VZ(M.substring(0,I),B.substring(0,D));if(C.length<R+v)C=B.substring(D-R,D)+B.substring(D,D+v),A=M.substring(0,I-R),G=M.substring(I+v),H=B.substring(0,D-R),L=B.substring(D+v)}if(C.length*2>=M.length)return[A,G,H,L,C];else return null}var X=Q(K,V,Math.ceil(K.length/4)),Y=Q(K,V,Math.ceil(K.length/2)),W;if(!X&&!Y)return null;else if(!Y)W=X;else if(!X)W=Y;else W=X[4].length>Y[4].length?X:Y;var J,z,U,j;if($.length>Z.length)J=W[0],z=W[1],U=W[2],j=W[3];else U=W[0],j=W[1],J=W[2],z=W[3];var O=W[4];return[J,z,U,j,O]}function Y0($){var Z=!1,K=[],V=0,Q=null,X=0,Y=0,W=0,J=0,z=0;while(X<$.length){if($[X][0]==E)K[V++]=X,Y=J,W=z,J=0,z=0,Q=$[X][1];else{if($[X][0]==P)J+=$[X][1].length;else z+=$[X][1].length;if(Q&&Q.length<=Math.max(Y,W)&&Q.length<=Math.max(J,z))$.splice(K[V-1],0,[y,Q]),$[K[V-1]+1][0]=P,V--,V--,X=V>0?K[V-1]:-1,Y=0,W=0,J=0,z=0,Q=null,Z=!0}X++}if(Z)yZ($);z0($),X=1;while(X<$.length){if($[X-1][0]==y&&$[X][0]==P){var U=$[X-1][1],j=$[X][1],O=D8(U,j),M=D8(j,U);if(O>=M){if(O>=U.length/2||O>=j.length/2)$.splice(X,0,[E,j.substring(0,O)]),$[X-1][1]=U.substring(0,U.length-O),$[X+1][1]=j.substring(O),X++}else if(M>=U.length/2||M>=j.length/2)$.splice(X,0,[E,U.substring(0,M)]),$[X-1][0]=P,$[X-1][1]=j.substring(0,j.length-M),$[X+1][0]=y,$[X+1][1]=U.substring(M),X++;X++}X++}}var q8=/[^a-zA-Z0-9]/,F8=/\s/,S8=/[\r\n]/,W0=/\n\r?\n$/,J0=/^\r?\n\r?\n/;function z0($){function Z(M,B){if(!M||!B)return 6;var I=M.charAt(M.length-1),T=B.charAt(0),D=I.match(q8),C=T.match(q8),A=D&&I.match(F8),G=C&&T.match(F8),H=A&&I.match(S8),L=G&&T.match(S8),v=H&&M.match(W0),R=L&&B.match(J0);if(v||R)return 5;else if(H||L)return 4;else if(D&&!A&&G)return 3;else if(A||G)return 2;else if(D||C)return 1;return 0}var K=1;while(K<$.length-1){if($[K-1][0]==E&&$[K+1][0]==E){var V=$[K-1][1],Q=$[K][1],X=$[K+1][1],Y=VZ(V,Q);if(Y){var W=Q.substring(Q.length-Y);V=V.substring(0,V.length-Y),Q=W+Q.substring(0,Q.length-Y),X=W+X}var J=V,z=Q,U=X,j=Z(V,Q)+Z(Q,X);while(Q.charAt(0)===X.charAt(0)){V+=Q.charAt(0),Q=Q.substring(1)+X.charAt(0),X=X.substring(1);var O=Z(V,Q)+Z(Q,X);if(O>=j)j=O,J=V,z=Q,U=X}if($[K-1][1]!=J){if(J)$[K-1][1]=J;else $.splice(K-1,1),K--;if($[K][1]=z,U)$[K+1][1]=U;else $.splice(K+1,1),K--}}K++}}function yZ($,Z){$.push([E,""]);var K=0,V=0,Q=0,X="",Y="",W;while(K<$.length){if(K<$.length-1&&!$[K][1]){$.splice(K,1);continue}switch($[K][0]){case P:Q++,Y+=$[K][1],K++;break;case y:V++,X+=$[K][1],K++;break;case E:var J=K-Q-V-1;if(Z){if(J>=0&&E8($[J][1])){var z=$[J][1].slice(-1);if($[J][1]=$[J][1].slice(0,-1),X=z+X,Y=z+Y,!$[J][1]){$.splice(J,1),K--;var U=J-1;if($[U]&&$[U][0]===P)Q++,Y=$[U][1]+Y,U--;if($[U]&&$[U][0]===y)V++,X=$[U][1]+X,U--;J=U}}if(w8($[K][1])){var z=$[K][1].charAt(0);$[K][1]=$[K][1].slice(1),X+=z,Y+=z}}if(K<$.length-1&&!$[K][1]){$.splice(K,1);break}if(X.length>0||Y.length>0){if(X.length>0&&Y.length>0){if(W=bZ(Y,X),W!==0){if(J>=0)$[J][1]+=Y.substring(0,W);else $.splice(0,0,[E,Y.substring(0,W)]),K++;Y=Y.substring(W),X=X.substring(W)}if(W=VZ(Y,X),W!==0)$[K][1]=Y.substring(Y.length-W)+$[K][1],Y=Y.substring(0,Y.length-W),X=X.substring(0,X.length-W)}var j=Q+V;if(X.length===0&&Y.length===0)$.splice(K-j,j),K=K-j;else if(X.length===0)$.splice(K-j,j,[P,Y]),K=K-j+1;else if(Y.length===0)$.splice(K-j,j,[y,X]),K=K-j+1;else $.splice(K-j,j,[y,X],[P,Y]),K=K-j+2}if(K!==0&&$[K-1][0]===E)$[K-1][1]+=$[K][1],$.splice(K,1);else K++;Q=0,V=0,X="",Y="";break}}if($[$.length-1][1]==="")$.pop();var O=!1;K=1;while(K<$.length-1){if($[K-1][0]===E&&$[K+1][0]===E){if($[K][1].substring($[K][1].length-$[K-1][1].length)===$[K-1][1])$[K][1]=$[K-1][1]+$[K][1].substring(0,$[K][1].length-$[K-1][1].length),$[K+1][1]=$[K-1][1]+$[K+1][1],$.splice(K-1,1),O=!0;else if($[K][1].substring(0,$[K+1][1].length)==$[K+1][1])$[K-1][1]+=$[K+1][1],$[K][1]=$[K][1].substring($[K+1][1].length)+$[K+1][1],$.splice(K+1,1),O=!0}K++}if(O)yZ($,Z)}function R8($){return $>=55296&&$<=56319}function v8($){return $>=56320&&$<=57343}function w8($){return v8($.charCodeAt(0))}function E8($){return R8($.charCodeAt($.length-1))}function U0($){var Z=[];for(var K=0;K<$.length;K++)if($[K][1].length>0)Z.push($[K]);return Z}function xZ($,Z,K,V){if(E8($)||w8(V))return null;return U0([[E,$],[y,Z],[P,K],[E,V]])}function j0($,Z,K){var V=typeof K==="number"?{index:K,length:0}:K.oldRange,Q=typeof K==="number"?null:K.newRange,X=$.length,Y=Z.length;if(V.length===0&&(Q===null||Q.length===0)){var W=V.index,J=$.slice(0,W),z=$.slice(W),U=Q?Q.index:null;$:{var j=W+Y-X;if(U!==null&&U!==j)break $;if(j<0||j>Y)break $;var O=Z.slice(0,j),M=Z.slice(j);if(M!==z)break $;var B=Math.min(W,j),I=J.slice(0,B),T=O.slice(0,B);if(I!==T)break $;var D=J.slice(B),C=O.slice(B);return xZ(I,D,C,z)}$:{if(U!==null&&U!==W)break $;var A=W,O=Z.slice(0,A),M=Z.slice(A);if(O!==J)break $;var G=Math.min(X-A,Y-A),H=z.slice(z.length-G),L=M.slice(M.length-G);if(H!==L)break $;var D=z.slice(0,z.length-G),C=M.slice(0,M.length-G);return xZ(J,D,C,H)}}if(V.length>0&&Q&&Q.length===0)$:{var I=$.slice(0,V.index),H=$.slice(V.index+V.length),B=I.length,G=H.length;if(Y<B+G)break $;var T=Z.slice(0,B),L=Z.slice(Y-G);if(I!==T||H!==L)break $;var D=$.slice(B,X-G),C=Z.slice(B,Y-G);return xZ(I,D,C,H)}return null}function QZ($,Z,K,V){return m$($,Z,K,V,!0)}QZ.INSERT=P;QZ.DELETE=y;QZ.EQUAL=E;k8.exports=QZ});import*as BZ from"node:fs";import*as d$ from"node:path";import{fileURLToPath as x7}from"node:url";import*as W6 from"node:os";import*as l$ from"node:path";var J6="diffstalker";function j$(){return l$.join(process.env.XDG_CACHE_HOME||l$.join(W6.homedir(),".cache"),J6)}function z6(){return process.env.XDG_RUNTIME_DIR?l$.join(process.env.XDG_RUNTIME_DIR,J6):null}import*as n$ from"node:fs";import*as o$ from"node:path";import*as IZ from"node:os";function O$($){if($.startsWith("~/"))return o$.join(IZ.homedir(),$.slice(2));if($==="~")return IZ.homedir();return $}function U6($){let Z=o$.dirname($);if(!n$.existsSync(Z))n$.mkdirSync(Z,{recursive:!0})}function AZ($){let Z=$.split(`
2
+ `);for(let K=Z.length-1;K>=0;K--){let V=Z[K].trim();if(V)return V}return""}import*as d4 from"node:http";import*as U$ from"node:fs";import*as l4 from"node:net";function a$($){process.stderr.write(`[diffstalker warn] ${$}
3
+ `)}function O5($){if($ instanceof Error)return $.message;if($)return String($);return""}function j6($,Z){let K=Z?`: ${O5(Z)}`:"";process.stderr.write(`[diffstalker error] ${$}${K}
4
+ `)}function LZ($){let Z={};for(let[K,V]of $)Z[K]=V;return Z}function G5($){if(!$)return null;return{staged:LZ($.staged),unstaged:LZ($.unstaged)}}function s($){return{status:$.status,hunkCounts:G5($.hunkCounts),error:$.error,stashList:$.stashList,operationInProgress:$.operationInProgress,mtimes:$.mtimes?LZ($.mtimes):null}}function TZ($){return $}function M5($){return $.entries.length>0?$.entries[0].seq-1:$.nextSeq-1}function G6($,Z){let K=Z>0?$.entries.filter((V)=>V.seq>Z):$.entries;return{epoch:$.epoch,prunedBefore:M5($),entries:TZ(K)}}function E$($){if($ instanceof Date)return $.toISOString();if($ instanceof Map){let Z={};for(let[K,V]of $)Z[String(K)]=E$(V);return Z}if(Array.isArray($))return $.map(E$);if($!==null&&typeof $==="object"){let Z={};for(let[K,V]of Object.entries($))Z[K]=E$(V);return Z}return $}var H5=1048576;class N extends Error{status;constructor($,Z){super(Z);this.status=$,this.name="HttpError"}}function S($,Z,K){let V=JSON.stringify(E$(K));$.writeHead(Z,{"content-type":"application/json"}),$.end(V)}function M6($,Z,K,V){$.writeHead(Z,{...V,"content-length":String(K.byteLength)}),$.end(K)}function N5($,Z){if($.segments.length!==Z.length)return null;let K={};for(let V=0;V<$.segments.length;V++){let Q=$.segments[V];if(Q.startsWith(":"))try{K[Q.slice(1)]=decodeURIComponent(Z[V])}catch{throw new N(400,`Malformed percent-encoding in path: ${Z[V]}`)}else if(Q!==Z[V])return null}return K}async function C5($){if($.method!=="POST"&&$.method!=="PUT"&&$.method!=="PATCH")return;let Z=[],K=0;for await(let Q of $){let X=Q;if(K+=X.length,K>H5)throw new N(413,"Request body too large");Z.push(X)}let V=Buffer.concat(Z).toString("utf-8");if(!V.trim())return;try{return JSON.parse(V)}catch{throw new N(400,"Invalid JSON body")}}class DZ{routes=[];get($,Z){this.add("GET",$,Z)}post($,Z){this.add("POST",$,Z)}put($,Z){this.add("PUT",$,Z)}delete($,Z){this.add("DELETE",$,Z)}add($,Z,K){this.routes.push({method:$,segments:Z.split("/").filter(Boolean),handler:K})}match($,Z){for(let K of this.routes){if(K.method!==$)continue;let V=N5(K,Z);if(V)return{handler:K.handler,params:V}}return null}async handle($,Z,K){try{let V=new URL($.url??"/","http://localhost"),Q=V.pathname.split("/").filter(Boolean),X=$.method??"GET",Y=this.match(X,Q);if(!Y){if(K&&X==="GET"){await K($,Z,V.pathname);return}throw new N(404,`Unknown route: ${X} ${V.pathname}`)}let W=await C5($);await Y.handler({req:$,res:Z,params:Y.params,query:V.searchParams,body:W})}catch(V){if(Z.headersSent){Z.end();return}if(V instanceof N){S(Z,V.status,{error:V.message});return}j6(`${$.method??"GET"} ${$.url??"/"}`,V),S(Z,500,{error:"Internal server error"})}}}import*as qZ from"node:fs";import*as u from"node:path";var B5=new Set(["health","repos","events","follow"]),I5={".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"},H6="no-cache",A5="public, max-age=31536000, immutable";async function N6($,Z,K){let V;try{V=await qZ.promises.readFile(Z)}catch{throw new N(404,`Not found: ${u.basename(Z)}`)}$.writeHead(200,{"content-type":I5[u.extname(Z)]??"application/octet-stream","cache-control":K,"content-length":V.length}),$.end(V)}function C6($){let Z=u.resolve($);return async(K,V,Q)=>{let X;try{X=decodeURIComponent(Q)}catch{throw new N(400,`Malformed percent-encoding in path: ${Q}`)}if(X.includes("\x00"))throw new N(400,"Invalid path");let Y=X.split("/").filter(Boolean);if(Y.length>0&&B5.has(Y[0]))throw new N(404,`Unknown route: GET ${Q}`);let W=Y.length>0?u.resolve(Z,Y.join("/")):Z;if(W!==Z&&!W.startsWith(Z+u.sep))throw new N(403,"Forbidden");if((await qZ.promises.stat(W).catch(()=>null))?.isFile()){await N6(V,W,Y[0]==="assets"?A5:H6);return}await N6(V,u.join(Z,"index.html"),H6)}}function L5($){try{let Z=new URL(`http://${$}`).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function T5($){try{let Z=new URL($).hostname.toLowerCase();return Z.startsWith("[")&&Z.endsWith("]")?Z.slice(1,-1):Z}catch{return null}}function I6($){let Z=$.split(".");if(Z.length!==4)return!1;if(!Z.every((K)=>/^\d{1,3}$/.test(K)&&Number(K)<=255))return!1;return Z[0]==="127"}function D5($){return $.length>10&&$.endsWith(".localhost")}function B6($){return $==="localhost"||$==="::1"||D5($)||I6($)}function q5($){return $==="::1"||I6($)}function A6($){if($===null)return!1;if(typeof $==="string")return!0;return q5($.address)}function L6($){let Z=$.headers.host;if(Z!==void 0){let Y=L5(Z);if(Y===null||!B6(Y))return{status:421,message:"Host not allowed (loopback only)"}}let K=$.method??"GET";if(!(K!=="GET"&&K!=="HEAD"&&K!=="OPTIONS"))return null;let Q=$.headers["sec-fetch-site"];if(Q&&Q!=="same-origin"&&Q!=="none")return{status:403,message:"Cross-site request blocked"};let X=$.headers.origin;if(X!==void 0&&X!==""){let Y=T5(X);if(Y===null||!B6(Y))return{status:403,message:"Cross-origin request blocked"}}return null}function T6($){let Z=$.headers["sec-fetch-site"];if(Z&&Z!=="same-origin"&&Z!=="none")return{status:403,message:"Cross-site request blocked"};let K=$.headers["sec-fetch-dest"];if(K&&K!=="image")return{status:403,message:"Request destination must be an image"};return null}var D6={"X-Content-Type-Options":"nosniff","X-Frame-Options":"DENY","Referrer-Policy":"no-referrer","Cross-Origin-Resource-Policy":"same-origin","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'","frame-src 'none'","child-src 'none'","media-src 'none'","worker-src 'none'","form-action 'none'","base-uri 'self'","frame-ancestors 'none'"].join("; ")};import{createHash as b0}from"node:crypto";import*as c8 from"node:path";class q6{queue=[];isProcessing=!1;pendingMutations=0;refreshScheduled=!1;enqueue($){return new Promise((Z,K)=>{this.queue.push({execute:$,resolve:Z,reject:K}),this.processNext()})}enqueueMutation($){return this.pendingMutations++,this.enqueue($).finally(()=>{this.pendingMutations--})}hasPendingMutations(){return this.pendingMutations>0}scheduleRefresh($){if(this.pendingMutations>0)return;if(this.refreshScheduled)return;this.refreshScheduled=!0,this.enqueue(async()=>{this.refreshScheduled=!1,await $()}).catch(()=>{this.refreshScheduled=!1})}isBusy(){return this.isProcessing||this.queue.length>0}async processNext(){if(this.isProcessing||this.queue.length===0)return;this.isProcessing=!0;let $=this.queue.shift();try{let Z=await $.execute();$.resolve(Z)}catch(Z){$.reject(Z instanceof Error?Z:Error(String(Z)))}finally{this.isProcessing=!1,this.processNext()}}}var FZ=new Map;function F6($){let Z=FZ.get($);if(!Z)Z=new q6,FZ.set($,Z);return Z}function S6($){FZ.delete($)}import*as k from"node:path";import*as g from"node:fs";import{execFileSync as M0}from"node:child_process";import{watch as x8}from"chokidar";import{EventEmitter as H0}from"node:events";import b8 from"ignore";import{simpleGit as E5}from"simple-git";import*as f from"node:fs";import*as R6 from"node:os";import*as G$ from"node:path";import{execFileSync as F5}from"node:child_process";var S5=[["*.ada","ada"],["*.adb","ada"],["*.ads","ada"],["*.sh","bash"],["*.bash","bash"],["*.bib","bibtex"],["*.c","cpp"],["*.h","cpp"],["*.cc","cpp"],["*.cpp","cpp"],["*.cxx","cpp"],["*.hpp","cpp"],["*.hh","cpp"],["*.cs","csharp"],["*.css","css"],["*.scss","css"],["*.dts","dts"],["*.ex","elixir"],["*.exs","elixir"],["*.f","fortran"],["*.f90","fortran"],["*.go","golang"],["*.html","html"],["*.htm","html"],["*.java","java"],["*.kt","kotlin"],["*.kts","kotlin"],["*.md","markdown"],["*.m","objc"],["*.pas","pascal"],["*.pl","perl"],["*.pm","perl"],["*.php","php"],["*.py","python"],["*.rb","ruby"],["*.rs","rust"],["*.scm","scheme"],["*.tex","tex"]];function R5(){return`# Generated by diffstalker: turns on git's built-in funcname drivers.
5
+ `+`# Lowest-priority attributes source — a repo's own .gitattributes wins.
6
+ `+S5.map(([Z,K])=>`${Z} diff=${K}`).join(`
9
7
  `)+`
10
- `}function C$($){let Z=0;for(let K of $)Z+=K.content.length+1;return Z}var s7=5000,n$=262144,B5="Large file — diff not shown";function i7($){return String($).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function r7($){let Z=$/1048576;if(Z>=1)return`${Z.toFixed(1)} MB`;return`${Math.round($/1024)} KB`}function s$($,Z){let K=r7($),V=Z===void 0?K:`${K}, ${i7(Z)} lines`;return`${B5} (${V})`}function G5($){if($.length===0)return 0;let Z=1,K=-1;while((K=$.indexOf(`
11
- `,K+1))!==-1)Z++;return Z}function O5($,Z,K){let V=$.split(`
12
- `),X=V.findIndex((Q)=>Q.startsWith("@@"));return`${[...V.slice(0,X===-1?4:X),s$(Z,K)].join(`
8
+ `}var k$=null,$$=null;function v5(){if($$!==null)return $$;try{if(F5("git",["config","--get","core.attributesFile"],{encoding:"utf8",stdio:["ignore","pipe","ignore"],env:process.env}).trim()!=="")return $$=!0,!0}catch(Z){if(Z.status!==1)return $$=!0,!0}let $=process.env.XDG_CONFIG_HOME||G$.join(R6.homedir(),".config");return $$=f.existsSync(G$.join($,"git","attributes")),$$}function v6(){if(k$!==null)return k$;if(v5())return null;let $=G$.join(j$(),"funcname.gitattributes"),Z=R5();try{let K=null;try{K=f.readFileSync($,"utf8")}catch{K=null}if(K!==Z)f.mkdirSync(G$.dirname($),{recursive:!0}),w5($,Z);return k$=$,k$}catch{return k$=null,$$=!0,null}}function w5($,Z){let K=`${$}.${process.pid}.tmp`;f.writeFileSync(K,Z,"utf8"),f.renameSync(K,$)}function p(){return{...process.env,LC_ALL:"C",LANG:"C"}}var k5={allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigPaths:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeDiffExternal:!0,allowUnsafePager:!0,allowUnsafeGitProxy:!0,allowUnsafeTemplateDir:!0,allowUnsafeSshCommand:!0},_5=1e4,P5=600000;function F($,Z={}){let K=v6(),V=K===null?[]:[`core.attributesFile=${K}`];return E5({baseDir:$,unsafe:k5,timeout:{block:Z.longRunning===!0?P5:_5},config:V}).env(p())}import{execFileSync as b6}from"node:child_process";import*as P$ from"node:fs";import*as RZ from"node:path";async function i$($,Z){if(Z.length===0)return new Set;let K=F($),V=new Set,Q=100;for(let X=0;X<Z.length;X+=Q){let Y=Z.slice(X,X+Q);try{let J=(await K.raw(["check-ignore","--",...Y])).trim().split(`
9
+ `).filter((z)=>z.length>0);for(let z of J)V.add(z)}catch{}}return V}function Z$($){if($.length===0)return"";return $.map((Z)=>Z.content).join(`
10
+ `)+`
11
+ `}function s$($){let Z=0;for(let K of $)Z+=K.content.length+1;return Z}var x5=5000,_$=262144,k6="Large file — diff not shown";function b5($){return String($).replace(/\B(?=(\d{3})+(?!\d))/g,",")}function y5($){let Z=$/1048576;if(Z>=1)return`${Z.toFixed(1)} MB`;return`${Math.round($/1024)} KB`}function SZ($,Z){let K=y5($),V=Z===void 0?K:`${K}, ${b5(Z)} lines`;return`${k6} (${V})`}function w6($){if($.length===0)return 0;let Z=1,K=-1;while((K=$.indexOf(`
12
+ `,K+1))!==-1)Z++;return Z}function E6($,Z,K){let V=$.split(`
13
+ `),Q=V.findIndex((Y)=>Y.startsWith("@@"));return`${[...V.slice(0,Q===-1?4:Q),SZ(Z,K)].join(`
13
14
  `)}
14
- `}function Y$($){if($.length===0)return $;let Z=$.split(/(?=^diff --git )/m),K=!1,V=Z.map((X)=>{let Y=X.length;if(Y<=n$){let Q=G5(X);if(Q<=s7)return X;return K=!0,O5(X,Y,Q)}return K=!0,O5(X,Y,G5(X))});return K?V.join(""):$}function M5($){let Z=$.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(Z)return{oldStart:parseInt(Z[1],10),newStart:parseInt(Z[2],10)};return null}function o($){if($==="")return[];let Z=$.split(`
15
- `);if(Z.length>1&&Z[Z.length-1]==="")Z.pop();let K=[],V=0,X=0;for(let Y of Z)if(Y.startsWith("diff --git")||Y.startsWith("index ")||Y.startsWith("---")||Y.startsWith("+++")||Y.startsWith("new file")||Y.startsWith("deleted file")||Y.startsWith("Binary files")||Y.startsWith(B5)||Y.startsWith("similarity index")||Y.startsWith("rename from")||Y.startsWith("rename to"))K.push({type:"header",content:Y});else if(Y.startsWith("@@")){let Q=M5(Y);if(Q)V=Q.oldStart,X=Q.newStart;K.push({type:"hunk",content:Y})}else if(Y.startsWith("+"))K.push({type:"addition",content:Y,newLineNum:X++});else if(Y.startsWith("-"))K.push({type:"deletion",content:Y,oldLineNum:V++});else K.push({type:"context",content:Y,oldLineNum:V++,newLineNum:X++});return K}function I$($){let Z=new Map;if(!$)return Z;let K=null;for(let V of $.split(`
16
- `))if(V.startsWith("diff --git")){let X=V.match(/^diff --git a\/.+ b\/(.+)$/);if(X){if(K=X[1],!Z.has(K))Z.set(K,0)}}else if(V.startsWith("@@")&&K)Z.set(K,(Z.get(K)??0)+1);return Z}class T$ extends Error{constructor($){super(`No common history with ${$}`);this.name="NoCommonHistoryError"}}async function Q$($,Z,K=!1){let V=I($);try{let X=[];if(K)X.push("--cached");if(Z)X.push("--",Z);let Y=Y$(await V.diff(X));return{lines:o(Y)}}catch{return{lines:[]}}}var t7="4b825dc642cb6eb9a060e54bf8d69288fbee4904",j5="(unborn)",e7=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function L$($){let Z=I($);try{return(await Z.raw(["rev-parse","HEAD"])).trim()}catch(K){let V=K instanceof Error?K.message:String(K);if(e7.test(V))return j5;throw K}}async function N5($){let Z=I($),V=await L$($)===j5?t7:"HEAD",X=Y$(await Z.raw(["diff","-U3",V,"--"]));return{lines:o(X)}}var $8=n$;function Z8($,Z){return{lines:[{type:"header",content:`diff --git a/${$} b/${$}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${$}`},{type:"header",content:s$(Z)}]}}async function D$($,Z){try{let K=X$.resolve($),V=X$.resolve(K,Z);if(V!==K&&!V.startsWith(K+X$.sep))return{lines:[]};let X,Y;try{X=i.realpathSync(V),Y=i.realpathSync(K)}catch{return{lines:[]}}if(X!==Y&&!X.startsWith(Y+X$.sep))return{lines:[]};let Q=i.statSync(X);if(!Q.isFile())return{lines:[]};if(Q.size>$8)return Z8(Z,Q.size);let z=i.readFileSync(V,"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(`
17
- `),U=z.split(`
18
- `);if(J)U.pop();if(z.length>0){W.push({type:"hunk",content:`@@ -0,0 +1,${U.length} @@`});let G=1;for(let j of U)W.push({type:"addition",content:"+"+j,newLineNum:G++});if(!J)W.push({type:"context",content:"\"})}let O=s(W),B=Y$(O);if(B!==O)return{lines:o(B)};return{lines:W}}catch{return{lines:[]}}}async function i$($){let Z=I($),K=new Set,V=[];try{let X=await Z.raw(["log","--oneline","--decorate=short","--all","-n","200"]),Y=/\(([^)]+)\)/g;for(let Q of X.split(`
19
- `)){let z=Y.exec(Q);if(z){let W=z[1].split(",").map((J)=>J.trim());for(let J of W){if(J.startsWith("HEAD")||J.startsWith("tag:")||!J.includes("/"))continue;let U=J.replace(/^.*-> /,"");if(U.includes("/")&&!K.has(U))K.add(U),V.push(U)}}Y.lastIndex=0}if(V.length>0)V.sort((Q,z)=>{let W=Q.split("/").slice(1).join("/"),J=z.split("/").slice(1).join("/"),U=W==="main"||W==="master",O=J==="main"||J==="master";if(U&&!O)return-1;if(!U&&O)return 1;if(U&&O){let B=Q.startsWith("origin/"),G=z.startsWith("origin/");if(B&&!G)return 1;if(!B&&G)return-1}return 0})}catch{}return[...new Set(V)]}async function W$($){return(await i$($))[0]??null}async function r$($){return V$($)??await W$($)}async function a($,Z){let K=I($);try{return await K.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}async function t$($,Z){let K=I($),X=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!X)throw new T$(Z);let Y=await K.raw(["diff","--numstat",`${X}...HEAD`]),Q=await K.raw(["diff","--name-status",`${X}...HEAD`]),z=Y$(await K.raw(["diff",`${X}...HEAD`])),W=Y.trim().split(`
20
- `).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),S=N.slice(2).join("\t");J.set(S,{additions:A,deletions:E})}}let U=Q.trim().split(`
21
- `).filter((M)=>M),O=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],S;switch(A){case"A":S="added";break;case"D":S="deleted";break;case"R":S="renamed";break;default:S="modified"}O.set(E,S)}}let B=[],G=z.split(/(?=^diff --git )/m).filter((M)=>M.trim());for(let M of G){let N=M.match(/^diff --git a\/.+ b\/(.+)$/m);if(!N)continue;let A=N[1],E=o(M),S=J.get(A)||{additions:0,deletions:0},d=O.get(A)||"modified";B.push({path:A,status:d,additions:S.additions,deletions:S.deletions,diff:{lines:E}})}let j=0,T=0;for(let M of B)j+=M.additions,T+=M.deletions;let D=(await K.status()).files.length,F=(await K.log({from:X,to:"HEAD"})).all.map((M)=>({hash:M.hash,shortHash:M.hash.slice(0,7),message:M.message.split(`
22
- `)[0],author:M.author_name,date:new Date(M.date),refs:M.refs||""}));return B.sort((M,N)=>M.path.localeCompare(N.path)),{baseBranch:Z,stats:{filesChanged:B.length,additions:j,deletions:T},files:B,commits:F,uncommittedCount:D}}async function H5($,Z){let K=I($);try{let V=Y$(await K.raw(["show","--format=","--end-of-options",Z]));return{lines:o(V)}}catch{return{lines:[]}}}async function A5($,Z){let K=I($),V=await t$($,Z),X=await K.diff(["--cached","--numstat"]),Y=await K.diff(["--numstat"]),Q=await K.diff(["--cached"]),z=await K.diff([]),W=new Map;for(let M of X.trim().split(`
23
- `).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),S=N.slice(2).join("\t");W.set(S,{additions:A,deletions:E,staged:!0,unstaged:!1})}}for(let M of Y.trim().split(`
24
- `).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),S=N.slice(2).join("\t"),d=W.get(S);if(d)d.additions+=A,d.deletions+=E,d.unstaged=!0;else W.set(S,{additions:A,deletions:E,staged:!1,unstaged:!0})}}let J=await K.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 O=[],G=(Q+z).split(/(?=^diff --git )/m).filter((M)=>M.trim()),j=new Set;for(let M of G){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),S=W.get(A)||{additions:0,deletions:0},d=U.get(A)||"modified";O.push({path:A,status:d,additions:S.additions,deletions:S.deletions,diff:{lines:E},isUncommitted:!0})}let T=new Set(V.files.map((M)=>M.path)),q=[];for(let M of V.files){let N=O.find((A)=>A.path===M.path);if(N)q.push(M),q.push(N);else q.push(M)}for(let M of O)if(!T.has(M.path))q.push(M);let D=0,R=0,F=new Set;for(let M of q)F.add(M.path),D+=M.additions,R+=M.deletions;return q.sort((M,N)=>M.path.localeCompare(N.path)),{baseBranch:V.baseBranch,stats:{filesChanged:F.size,additions:D,deletions:R},files:q,commits:V.commits,uncommittedCount:V.uncommittedCount}}import*as C5 from"node:fs";import*as I5 from"node:path";var K8=/^diff --git a\/.+ b\/(.+)$/;function q$($){let Z=5381;for(let K of $){for(let V=0;V<K.length;V++)Z=(Z<<5)+Z+K.charCodeAt(V)|0;Z=(Z<<5)+Z+10|0}return(Z>>>0).toString(36)}function V8($){let Z=[],K="",V=null,X=()=>{if(V&&K)Z.push({file:K,key:`${K}\x00${q$(V.body)}`,headerLine:V.headerLine});V=null};for(let Y of $.lines)if(Y.type==="header"){X();let Q=Y.content.match(K8);if(Q)K=Q[1]}else if(Y.type==="hunk")X(),V={headerLine:Y,body:[]};else if(V&&(Y.type==="addition"||Y.type==="deletion"))V.body.push(Y.content);return X(),Z}class e${repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let K of V8($)){let V=this.stamps.get(K.key);if(V===void 0){let X=Z.get(K.file);if(X===void 0)X=this.mtimeOf(K.file),Z.set(K.file,X);V=X,this.stamps.set(K.key,V)}K.headerLine.editedAt=V}}prune($){for(let Z of this.stamps.keys()){let K=Z.slice(0,Z.indexOf("\x00"));if(!$.has(K))this.stamps.delete(Z)}}mtimeOf($){try{return C5.statSync(I5.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}import*as p from"node:fs";import*as k from"node:path";async function T5($){let Z=F5($);if(!Z)return null;try{let K=I(Z);if((await K.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await K.raw(["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function J$($){let Z=F5($);if(!Z)return[];try{let V=await I(Z).raw(["worktree","list","--porcelain"]),X=Q8(V),Y=await X8(X,Z);return X.map((Q)=>({...Q,lastActivity:Q.isBare?null:Y8(D5(Q.path)),aheadOfBase:Y.get(Q.path)??null}))}catch{return[]}}function Y8($){return Number.isFinite($)?$:null}async function X8($,Z){let K=$.filter((Y)=>!Y.isBare);if(K.length===0)return new Map;let V=await W$(Z).catch(()=>null),X=await Promise.all(K.map(async(Y)=>{let Q=V$(Y.path)??V;if(!Q)return null;try{let W=await I(Y.path).raw(["rev-list","--count","--end-of-options",`${Q}..HEAD`]);return[Y.path,parseInt(W.trim(),10)]}catch{return null}}));return new Map(X.filter((Y)=>Y!==null))}function L5($){let Z=null,K=-1/0;for(let V of $){if(V.isBare)continue;let X=D5(V.path);if(X>K)K=X,Z=V}return Z}function D5($){let Z=q5($),K=Z?[k.join(Z,"index"),k.join(Z,"HEAD")]:[$],V=-1/0;for(let X of K)try{let Y=p.statSync(X).mtimeMs;if(Y>V)V=Y}catch{}return V}function q5($){let Z=k.join($,".git");try{if(p.statSync(Z).isDirectory())return Z;let K=p.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!K)return null;let V=K[1].trim();return k.isAbsolute(V)?V:k.resolve($,V)}catch{return null}}function R5($){let Z=q5($);if(Z===null)return null;let K=Z;try{let V=p.readFileSync(k.join(Z,"commondir"),"utf8").trim();if(V)K=k.isAbsolute(V)?V:k.resolve(Z,V)}catch{}return{gitDir:Z,commonDir:K}}function Q8($){let Z=[],K=null;for(let V of $.split(`
25
- `))if(V.startsWith("worktree ")){if(K)Z.push(K);K={path:V.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:Z.length===0}}else if(!K)continue;else if(V.startsWith("HEAD "))K.head=V.slice(5).trim();else if(V.startsWith("branch "))K.branch=V.slice(7).trim().replace(/^refs\/heads\//,"");else if(V==="bare")K.isBare=!0;if(K)Z.push(K);return Z}function F5($){try{if(p.statSync($).isDirectory())return $;return k.dirname($)}catch{let Z=k.dirname($);return Z!==$&&p.existsSync(Z)?Z:null}}var N8=P7(m5(),1);var H8=/^diff --git a\/.+ b\/(.+)$/;function c5($){return H8.exec($)?.[1]??null}function S$($){let Z=new Map,K=null;for(let X of $.lines){if(X.type==="header"){let Y=c5(X.content);if(Y!==null)K=Z.get(Y)??[],Z.set(Y,K)}K?.push(X)}let V=new Map;for(let[X,Y]of Z)V.set(X,{lines:Y});return V}var E$="diffstalker-journal: oversize untracked snapshot omitted";var I8=262144;class w$ extends C8{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 e$($)}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=u5();Z.add(".git");let K=v.join(this.repoPath,".gitignore");if(m.existsSync(K))Z.add(m.readFileSync(K,"utf-8"));let V=v.join(this.repoPath,".git","info","exclude");if(m.existsSync(V))Z.add(m.readFileSync(V,"utf-8"));$.set("",Z);try{let X=A8("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:Z$()});for(let Y of X.split("\x00")){if(!Y||Y===".gitignore")continue;if(!Y.endsWith(".gitignore"))continue;let Q=v.dirname(Y),z=v.join(this.repoPath,Y);try{let W=m.readFileSync(z,"utf-8"),J=u5();J.add(W),$.set(Q,J)}catch(W){j$(`Failed to read ${z}: ${W instanceof Error?W.message:W}`)}}}catch{}return $}startWatching(){let $=R5(this.repoPath);if($===null)return;let Z=v.join($.gitDir,"index"),K=v.join($.gitDir,"HEAD"),V=v.join($.commonDir,"refs"),X=v.join($.commonDir,"packed-refs"),Y=v.join(this.repoPath,".gitignore");this.gitWatcher=g5([Z,K,V,X,Y],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=g5(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 O=U===0?"":J.slice(0,U).join("/"),B=this.ignorers.get(O);if(B){let G=U===0?W:J.slice(U).join("/");if(B.ignores(G))return!0}}return!1},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let Q=()=>this.scheduleRefresh();this.gitWatcher.on("change",(z)=>{if(z===Y)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 K of $.files){if(Z.has(K.path))continue;try{Z.set(K.path,m.statSync(v.join(this.repoPath,K.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 o$(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 L$(this.repoPath).catch(()=>null);try{let K=await o$(this.repoPath);if(!K.isRepo){this.updateState({status:K,isLoading:!1,error:"Not a git repository"});return}let[V,X,Y,Q,z]=await Promise.all([Q$(this.repoPath,void 0,!1),Q$(this.repoPath,void 0,!0),H$(this.repoPath),g(this.repoPath),this.gatherJournalInputs(K,Z,$)]),W={unstaged:I$(s(V.lines)),staged:I$(s(X.lines))};this.hunkTimes.stamp(V),this.hunkTimes.stamp(X),this.hunkTimes.prune(new Set(K.files.map((U)=>U.path)));let J=this.statMtimes(K);if(this.updateState({status:K,hunkCounts:W,stashList:Y,operationInProgress:Q,mtimes:J,isLoading:!1}),z!==null)this.emit("journal-observation",{status:K,headDiff:z.headDiff,headOid:z.headOid,stashCount:z.stashCount,operationInProgress:z.operationInProgress,mtimes:z.mtimes,at:Date.now()})}catch(K){this.updateState({isLoading:!1,error:K instanceof Error?K.message:"Unknown error"})}}async snapshotJournalGuard($){let[Z,K]=await Promise.all([g(this.repoPath),H$(this.repoPath)]);return{operation:Z,stashCount:K.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[K,V]of $.mtimes)if(Z.mtimes.get(K)!==V)return!0;return!1}sectionWrittenDuringGather($,Z,K){let V=new Set(Z);for(let X of $.files)if(X.status==="untracked")V.add(X.path);for(let X of V)try{let Y=m.statSync(v.join(this.repoPath,X));if(Math.floor(Y.mtimeMs)>K)return!0}catch{}return!1}async gatherJournalInputs($,Z,K){if(Z===null)return null;try{let V=await this.snapshotJournalGuard($),X=await N5(this.repoPath),Y=new Set(S$(X).keys()),Q=[...X.lines];await this.appendUntrackedSections($,Y,Q);let z=await L$(this.repoPath);if(Z!==z)return null;let W=await this.snapshotJournalGuard($);if(w$.journalGuardMoved(V,W))return null;if(this.sectionWrittenDuringGather($,Y,K))return null;return{headDiff:{lines:Q},headOid:z,stashCount:W.stashCount,operationInProgress:W.operation,mtimes:W.mtimes}}catch{return null}}async appendUntrackedSections($,Z,K){let V=new Set;for(let X of $.files){if(X.status!=="untracked"||V.has(X.path)||Z.has(X.path))continue;V.add(X.path);let Y;try{Y=m.statSync(v.join(this.repoPath,X.path))}catch{continue}if(!Y.isFile())continue;if(Y.size>I8){this.appendOversizeSection(X.path,Y,K);continue}let Q=await D$(this.repoPath,X.path);if(Q.lines.length===0)continue;K.push(...Q.lines)}}appendOversizeSection($,Z,K){let V=[`diff --git a/${$} b/${$}`,"new file mode 100644",`${E$} size=${Z.size} mtime=${Math.round(Z.mtimeMs)}`];K.push(...V.map((X)=>({type:"header",content:X})))}async stage($){try{await this.queue.enqueueMutation(()=>g4(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(()=>u4(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()=>a4(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()=>n4(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"?()=>d4(this.repoPath,$.path):()=>f4(this.repoPath,$.path);try{await this.queue.enqueueMutation(Z),await this.refresh()}catch(K){this.updateState({error:`Failed to discard ${$.path}: ${K instanceof Error?K.message:String(K)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>p4(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>h4(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(()=>l4(this.repoPath,$,Z)),await this.refresh()}catch(K){this.updateState({error:`Failed to commit: ${K instanceof Error?K.message:String(K)}`})}}async loadStashList(){try{let $=await this.queue.enqueue(()=>H$(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as T8}from"node:events";class V4 extends T8{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor($,Z,K){super();this.repoPath=$,this.queue=Z,this.callbacks=K}get remoteState(){return this._remoteState}updateRemoteState($){this._remoteState={...this._remoteState,...$},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation($,Z){this.updateRemoteState({operation:$,inProgress:!0,error:null,lastResult:null});try{let K=await this.queue.enqueue(Z);this.updateRemoteState({inProgress:!1,lastResult:K}),this.callbacks.scheduleRefresh()}catch(K){let V=K instanceof Error?K.message:String(K);this.updateRemoteState({inProgress:!1,error:V})}return this._remoteState}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>s4(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>i4(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>r4(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>e4(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>$5(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>A$(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>Z5(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>K5(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>V5(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>Y5(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>X5(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>Q5(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>z5(this.repoPath))}}import{EventEmitter as L8}from"node:events";import{randomBytes as D8}from"node:crypto";var q8=262144,R8=500,F8=16777216,f5=Number.MAX_SAFE_INTEGER,S8=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function E8($){let Z=S8.exec($);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldCount:Z[2]!==void 0?parseInt(Z[2],10):1}}function w8($,Z){let K=E8(Z);if(!K)return[];let V=K.oldCount===0?K.oldStart+1:K.oldStart,X=[],Y=null;for(let Q of $){let z=Q.content[0];if(z==="\\")continue;if(z==="-")Y=v8(Y,V),V++;else if(z==="+")Y=Y??{hasDel:!1,delStart:0,delEnd:0,anchor:V-1};else p5(X,Y),Y=null,V++}return p5(X,Y),X}function v8($,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 Y4($){if($.length===0)return{start:0,count:0};let Z=1/0,K=-1/0;for(let[Y,Q]of $){if(Y<Z)Z=Y;if(Q>K)K=Q}if(K>=f5)return{start:0,count:0};let V=Math.ceil(Z/2),X=Math.floor(K/2);return{start:V,count:X-V+1}}function P8($){let Z=[],K=null,V=[],X=null;for(let Q of $.lines)if(Q.type==="hunk")X={header:Q,body:[]},V.push(X);else if(X)X.body.push(Q);else if(Z.push(Q),Q.content.startsWith("rename from "))K=Q.content.slice(12);if(V.length===0){let Q=Z.some((z)=>z.content.startsWith(E$));return{hunks:[{runs:[[0,f5]],bodyHash:q$([s($.lines)]),ins:0,del:0,span:{start:0,count:0},diff:$,oversize:Q}],renamedFrom:K,hunkless:!0}}return{hunks:V.map(({header:Q,body:z})=>{let W=w8(z,Q.content),J=[],U=0,O=0;for(let G of z){let j=G.content[0];if(j==="\\")continue;if(j==="+")U++,J.push(G.content);else if(j==="-")O++,J.push(G.content)}let B=[...Z,Q,...z];return{runs:W,bodyHash:q$(J),ins:U,del:O,span:Y4(W),diff:{lines:B}}}),renamedFrom:K,hunkless:!1}}function k8($){if($.oversize===!0)return null;return C$($.diff.lines)>q8?null:$.diff}function y8($,Z,K){if($===0&&Z>0)return"shrunk";let V=$+Z;if(V>K)return"expanded";if(V<K)return"shrunk";return"edited"}function h5($,Z){let K=[];return $.forEach((V,X)=>{for(let[Y,Q]of V.runs)K.push({lo:Y,hi:Q,node:Z+X})}),K.sort((V,X)=>V.lo-X.lo),K}function b8($,Z){let K=Array.from({length:$.length+Z.length},(W,J)=>J),V=(W)=>{while(K[W]!==W)K[W]=K[K[W]],W=K[W];return W},X=(W,J)=>{let U=V(W),O=V(J);if(U!==O)K[U]=O},Y=h5($,0),Q=h5(Z,$.length),z=0;for(let W of Y){while(z<Q.length&&Q[z].hi<W.lo)z++;for(let J=z;J<Q.length&&Q[J].lo<=W.hi;J++)X(W.node,Q[J].node)}return K.map((W,J)=>V(J))}function _8($,Z){let K=b8($,Z),V=new Map,X=(Y)=>{let Q=V.get(Y);if(!Q)Q={prevIdx:[],nextIdx:[],minLo:1/0},V.set(Y,Q);return Q};return $.forEach((Y,Q)=>{let z=X(K[Q]);z.prevIdx.push(Q);for(let[W]of Y.runs)if(W<z.minLo)z.minLo=W}),Z.forEach((Y,Q)=>{let z=X(K[$.length+Q]);z.nextIdx.push(Q);for(let[W]of Y.runs)if(W<z.minLo)z.minLo=W}),[...V.values()].sort((Y,Q)=>Y.minLo-Q.minLo)}function x8($,Z,K){let V=[],X=Z.map(()=>null),Y=K;for(let Q of _8($,Z)){let z=Q.prevIdx.map((O)=>$[O]),W=Q.nextIdx.map((O)=>Z[O]);if(z.length===1&&W.length===1&&z[0].bodyHash===W[0].bodyHash){let O=W[0];X[Q.nextIdx[0]]={seq:z[0].seq,runs:O.runs,bodyHash:O.bodyHash,ins:O.ins,del:O.del};continue}if(W.length===0){for(let O of z)V.push({seq:Y++,kind:"reverted",span:Y4(O.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[O.seq],siblings:1});continue}let J=z.map((O)=>O.seq),U=z.reduce((O,B)=>O+B.ins+B.del,0);for(let O of Q.nextIdx){let B=Z[O],G={seq:Y++,kind:z.length===0?"created":y8(B.ins,B.del,U),span:B.span,stats:{insertions:B.ins,deletions:B.del},diff:k8(B),supersedes:[...J],siblings:W.length};V.push(G),X[O]={seq:G.seq,runs:B.runs,bodyHash:B.bodyHash,ins:B.ins,del:B.del}}}return{entries:V,nextLive:X.filter((Q)=>Q!==null)}}function m8($,Z){let K=Array($.length).fill(!1),V=Array(Z.length).fill(null);for(let z=0;z<Z.length;z++){let W=$.findIndex((J,U)=>!K[U]&&J.bodyHash===Z[z].bodyHash);if(W!==-1)K[W]=!0,V[z]=$[W].seq}for(let z=0;z<Z.length;z++){if(V[z]!==null)continue;let W=K.findIndex((J)=>!J);if(W!==-1)K[W]=!0,V[z]=$[W].seq}let X=$[$.length-1].seq,Y=Z.map((z,W)=>{return{seq:V[W]??X,runs:z.runs,bodyHash:z.bodyHash,ins:z.ins,del:z.del}}),Q=$.filter((z,W)=>!K[W]).map((z)=>z.seq);return{carried:Y,retired:Q}}function v$(){return{entries:[],epoch:`${Date.now().toString(36)}-${D8(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class X4 extends L8{store;constructor($){super();this.store=$}get journalStore(){return this.store}observe($){try{this.doObserve($)}catch(Z){j$(`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 K of Z)$.add(K.seq);this.pruneBodies($),this.pruneEntries($)}pruneBodies($){let Z=0;for(let K of this.store.entries)if(K.type==="hunk"&&K.diff!==null)Z+=C$(K.diff.lines);for(let K of this.store.entries){if(Z<=F8)return;if(K.type!=="hunk"||K.diff===null||$.has(K.seq))continue;Z-=C$(K.diff.lines),K.diff=null}}pruneEntries($){let Z=this.store.entries,K=0;while(Z.length-K>R8&&(Z[K].type==="boundary"||!$.has(Z[K].seq)))K++;if(K>0)Z.splice(0,K)}handleOperations($,Z){let K=this.store.lastOperation;if($.operationInProgress!==null){if(K===null)Z.push(this.boundary("op-start",$.operationInProgress,[],$.at)),this.store.lastOperation=$.operationInProgress;return!0}if(K!==null)Z.push(this.boundary("op-end",K,[],$.at)),this.store.lastOperation=null;return!1}seed($,Z){Z.push(this.boundary("journal-start",$.status.branch.current,[],$.at));let{files:K}=this.parseObservation($),V=[...K.keys()].sort((X,Y)=>this.tsFor($,X)-this.tsFor($,Y));for(let X of V)this.classifyPath(X,[],K.get(X).hunks,$,!0,Z);this.store.lastHeadOid=$.headOid,this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount,this.store.lastOperation=null}rebaseline($,Z){let{files:K,deferred:V}=this.parseObservation($),X=$.status.branch.current===this.store.lastBranch,Y=X?"commit":"checkout",Q=X?$.headOid.slice(0,7):$.status.branch.current,{resolves:z,newLive:W}=this.carrySurvivors(K,V);Z.push(this.boundary(Y,Q,z,$.at)),this.store.live=W;for(let[J,{hunks:U}]of K){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 K=[],V=new Map;for(let[X,Y]of this.store.live){if(Z.has(X)){V.set(X,Y);continue}let Q=$.get(X);if(!Q){K.push(...Y.map((J)=>J.seq));continue}let{carried:z,retired:W}=m8(Y,Q.hunks);K.push(...W),V.set(X,z)}return{resolves:K,newLive:V}}classify($,Z){let{files:K,deferred:V}=this.parseObservation($);this.handleRenames($,K,Z),this.handleDisappearances($,K,V,Z);for(let[X,{hunks:Y,renamedFrom:Q,hunkless:z}]of K){let W=this.store.live.get(X)??[];if(z&&Q!==null&&W.length>0)continue;this.classifyPath(X,W,Y,$,!1,Z)}this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}handleRenames($,Z,K){for(let[V,X]of Z){let Y=X.renamedFrom;if(Y===null||Y===V)continue;if(!this.store.live.has(Y)||Z.has(Y))continue;let Q=(this.store.live.get(V)??[]).map((z)=>z.seq);this.store.live.set(V,this.store.live.get(Y)),this.store.live.delete(Y),K.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,V),path:V,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:Q,siblings:1,seeded:!1})}}handleDisappearances($,Z,K,V){let X=[...this.store.live.keys()].filter((Y)=>!Z.has(Y)&&!K.has(Y));if(X.length===0)return;if($.stashCount>this.store.lastStashCount){let Y=X.flatMap((Q)=>this.store.live.get(Q).map((z)=>z.seq));V.push(this.boundary("stash","stash",Y,$.at));for(let Q of X)this.store.live.delete(Q);return}for(let Y of X){let Q=this.store.live.get(Y);V.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,Y),path:Y,status:this.statusOf($,Y),kind:"reverted",span:Y4(Q.flatMap((z)=>z.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:Q.map((z)=>z.seq),siblings:1,seeded:!1}),this.store.live.delete(Y)}}classifyPath($,Z,K,V,X,Y){let{entries:Q,nextLive:z}=x8(Z,K,this.store.nextSeq);this.store.nextSeq+=Q.length;let W=this.tsFor(V,$),J=this.statusOf(V,$);for(let U of Q){let O={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:X};Y.push(O)}if(z.length>0)this.store.live.set($,z);else this.store.live.delete($)}parseObservation($){let Z=new Map;for(let[V,X]of S$($.headDiff))Z.set(V,P8(X));let K=new Set;for(let V of $.status.files)if(V.status==="untracked"&&!Z.has(V.path))K.add(V.path);return{files:Z,deferred:K}}boundary($,Z,K,V){return{type:"boundary",seq:this.store.nextSeq++,ts:V,kind:$,label:Z,resolves:K}}tsFor($,Z){let K=$.mtimes?.get(Z);return K===void 0?$.at:Math.min(K,$.at)}statusOf($,Z){return $.status.files.find((K)=>K.path===Z)?.status??"modified"}}class Q4{workingTree;remote;journal;repoPath;constructor($,Z){this.repoPath=$;let K=y4($);this.workingTree=new w$($,K),this.remote=new V4($,K,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new X4(Z??v$()),this.workingTree.on("journal-observation",(V)=>this.journal.observe(V))}dispose(){this.workingTree.dispose(),b4(this.repoPath)}}function g8($){return c8("sha256").update($).digest("hex").slice(0,12)}var u8=32;class d5{cap;stores=new Map;constructor($=u8){this.cap=$}acquire($){let Z=this.stores.get($);if(Z)this.stores.delete($);else Z=v$();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 z4{events;byId=new Map;byPath=new Map;journalStores=new d5;constructor($={}){this.events=$}async openRepo($){let Z=await T5($);if(!Z){let Q=L5(await J$($));if(!Q)throw Error(`Not a git repository: ${$}`);Z=Q.path}let K=this.byPath.get(Z);if(K)return K.refCount++,{handle:K,created:!1};let V=g8(Z),X=new Q4(Z,this.journalStores.acquire(V));X.workingTree.startWatching();let Y={id:V,path:Z,manager:X,refCount:1};return this.byId.set(Y.id,Y),this.byPath.set(Z,Y),this.journalStores.prune((Q)=>this.byId.has(Q)),this.events.onOpened?.(Y),{handle:Y,created:!0}}getRepo($){return this.byId.get($)}listRepos(){return[...this.byId.values()]}closeRepo($){let Z=this.byId.get($);if(!Z)return!1;if(Z.refCount--,Z.refCount>0)return!1;return this.byId.delete(Z.id),this.byPath.delete(Z.path),Z.manager.dispose(),this.events.onClosed?.(Z.id),!0}disposeAll(){for(let $ of this.byId.values())$.manager.dispose();this.byId.clear(),this.byPath.clear()}}var l5=25000;function G$($,Z,K){$.write(`event: ${Z}
15
+ `}function M$($){if($.length===0)return $;let Z=$.split(/(?=^diff --git )/m),K=!1,V=Z.map((Q)=>{let X=Q.length;if(X<=_$){let Y=w6(Q);if(Y<=x5)return Q;return K=!0,E6(Q,X,Y)}return K=!0,E6(Q,X,w6(Q))});return K?V.join(""):$}function m5($){return $.startsWith("diff --git")||$.startsWith("index ")||$.startsWith("---")||$.startsWith("+++")||$.startsWith("old mode")||$.startsWith("new mode")||$.startsWith("new file")||$.startsWith("deleted file")||$.startsWith("similarity index")||$.startsWith("dissimilarity index")||$.startsWith("rename from")||$.startsWith("rename to")||$.startsWith("copy from")||$.startsWith("copy to")||$.startsWith("Binary files")||$.startsWith(k6)}function g5($){return $.startsWith("\\ ")}function _6($){let Z=$.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);if(Z)return{oldStart:parseInt(Z[1],10),newStart:parseInt(Z[2],10)};return null}function r($){if($==="")return[];let Z=$.split(`
16
+ `);if(Z.length>1&&Z[Z.length-1]==="")Z.pop();let K=[],V=0,Q=0;for(let X of Z)if(m5(X))K.push({type:"header",content:X});else if(g5(X))K.push({type:"context",content:X});else if(X.startsWith("@@")){let Y=_6(X);if(Y)V=Y.oldStart,Q=Y.newStart;K.push({type:"hunk",content:X})}else if(X.startsWith("+"))K.push({type:"addition",content:X,newLineNum:Q++});else if(X.startsWith("-"))K.push({type:"deletion",content:X,oldLineNum:V++});else K.push({type:"context",content:X,oldLineNum:V++,newLineNum:Q++});return K}function r$($){let Z=new Map;if(!$)return Z;let K=null;for(let V of $.split(`
17
+ `))if(V.startsWith("diff --git")){let Q=V.match(/^diff --git a\/.+ b\/(.+)$/);if(Q){if(K=Q[1],!Z.has(K))Z.set(K,0)}}else if(V.startsWith("@@")&&K)Z.set(K,(Z.get(K)??0)+1);return Z}function P6($){let Z=new Map;for(let K of $.trim().split(`
18
+ `)){if(!K)continue;let V=K.split("\t");if(V.length>=3){let Q=V[0]==="-"?0:parseInt(V[0],10),X=V[1]==="-"?0:parseInt(V[1],10),Y=V.slice(2).join("\t");Z.set(Y,{insertions:Q,deletions:X})}}return Z}var c5=_$;async function u5($,Z){try{let K=RZ.join($,Z),V=await P$.promises.stat(K);if(!V.isFile())return null;if(V.size>c5)return null;return(await P$.promises.readFile(K,"utf-8")).split(`
19
+ `).filter((X)=>X.length>0).length}catch{return null}}var p5=new Set(["DD","AU","UD","UA","DU","AA","UU"]);function h5($,Z){return p5.has(`${$}${Z}`)}function x6($,Z){return Z?"conflicted":f5($)}function f5($){switch($){case"M":return"modified";case"A":return"added";case"D":return"deleted";case"?":return"untracked";case"R":return"renamed";case"C":return"copied";case"U":return"conflicted";default:return"modified"}}async function vZ($){let Z=F($);if(!await Z.checkIsRepo())return{files:[],branch:{current:"",ahead:0,behind:0},isRepo:!1};let V=await Z.status(),Q=[],X=new Set,Y=V.files.filter((M)=>M.working_dir==="?").map((M)=>M.path),W=await i$($,Y);for(let M of V.files){if(M.index==="!"||M.working_dir==="!"||W.has(M.path))continue;let B=`${M.path}-${M.index!==" "&&M.index!=="?"}`;if(X.has(B))continue;X.add(B);let I=h5(M.index,M.working_dir);if(M.index&&M.index!==" "&&M.index!=="?"){let T=x6(M.index,I);Q.push({path:M.path,status:T,staged:!0,...M.from&&(T==="renamed"||T==="copied")?{originalPath:M.from}:{}})}if(M.working_dir&&M.working_dir!==" ")Q.push({path:M.path,status:x6(M.working_dir,I),staged:!1})}let[J,z]=await Promise.all([Z.diff(["--cached","--numstat"]).catch(()=>""),Z.diff(["--numstat"]).catch(()=>"")]),U=P6(J),j=P6(z);for(let M of Q){let B=M.staged?U.get(M.path):j.get(M.path);if(B)M.insertions=B.insertions,M.deletions=B.deletions}let O=Q.filter((M)=>M.status==="untracked");if(O.length>0){let M=await Promise.all(O.map((B)=>u5($,B.path)));for(let B=0;B<O.length;B++){let I=M[B];if(I===null)continue;O[B].insertions=I,O[B].deletions=0}}return{files:Q,branch:{current:V.current||"HEAD",tracking:V.tracking||void 0,ahead:V.ahead,behind:V.behind},isRepo:!0}}async function y6($,Z){await F($).add(["--",Z])}async function m6($,Z){await F($).reset(["HEAD","--",Z])}async function g6($){await F($).add("-A")}async function c6($){await F($).reset(["HEAD"])}async function u6($,Z){await F($).checkout(["--",Z])}async function p6($,Z){await F($).clean("f",["--",Z])}async function h6($,Z,K=!1){if(!(await F($,{longRunning:!0}).commit(Z,void 0,K?{"--amend":null}:void 0)).commit)throw Error("Nothing to commit: no staged changes")}async function f6($){let Z=F($);try{return(await Z.log({n:1})).latest?.message||""}catch{return""}}function d6($,Z){b6("git",["apply","--cached","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:p()})}function l6($,Z){b6("git",["apply","--cached","--reverse","--unidiff-zero"],{cwd:$,input:Z,encoding:"utf-8",env:p()})}async function n6($){let V=(await F($,{longRunning:!0}).push()).pushed;if(V.length===0)return"Everything up-to-date";return V.map((Q)=>`${Q.local} → ${Q.remote}`).join(", ")}async function o6($){return await F($,{longRunning:!0}).fetch(),"Fetch complete"}async function a6($){let K=await F($,{longRunning:!0}).pull(["--rebase"]);if(K.summary.changes===0&&K.summary.insertions===0&&K.summary.deletions===0)return"Already up-to-date";return`${K.summary.changes} file(s) changed`}async function i6($,Z=50){let K=F($);try{return(await K.log({n:Z})).all.map((Q)=>({hash:Q.hash,shortHash:Q.hash.slice(0,7),message:Q.message.split(`
20
+ `)[0],author:Q.author_name,date:new Date(Q.date),refs:Q.refs||""}))}catch{return[]}}async function s6($,Z){let K=F($);try{let Q=(await K.log(["--no-walk",Z])).all[0];if(!Q)return null;return{hash:Q.hash,shortHash:Q.hash.slice(0,7),message:Q.message.split(`
21
+ `)[0],author:Q.author_name,date:new Date(Q.date),refs:Q.refs||""}}catch{return null}}async function t$($){let Z=F($);try{return(await Z.stashList()).all.map((V,Q)=>({index:Q,message:V.message}))}catch{return[]}}async function r6($,Z){let K=F($),V=["push"];if(Z)V.push("-m",Z);return await K.stash(V),"Stashed"}async function t6($,Z=0){let K=F($);await K.stash(["pop",`stash@{${Z}}`]);let V=(await K.raw(["diff","--name-only","--diff-filter=U"])).trim();if(V)throw Error(`Stash pop hit conflicts in: ${V.split(`
22
+ `).join(", ")}`);return"Stash popped"}async function e$($){let K=await F($).branchLocal();return K.all.map((V)=>({name:V,current:V===K.current,tracking:K.branches[V]?.label||void 0}))}async function e6($,Z){return await F($).raw(["switch","--",Z]),`Switched to ${Z}`}async function $8($,Z){return await F($).raw(["switch","-c",Z]),`Created ${Z}`}async function Z8($,Z=1){return await F($).reset(["--soft",`HEAD~${Z}`]),"Reset done"}async function K8($,Z){return await F($,{longRunning:!0}).raw(["cherry-pick","--end-of-options",Z]),"Cherry-picked"}async function V8($,Z){return await F($,{longRunning:!0}).raw(["revert","--no-edit","--end-of-options",Z]),"Reverted"}async function l($){let Z=F($),K;try{K=(await Z.raw(["rev-parse","--absolute-git-dir"])).trim()}catch{return null}let V=(Q)=>P$.existsSync(RZ.join(K,Q));if(V("rebase-merge")||V("rebase-apply"))return"rebase";if(V("CHERRY_PICK_HEAD"))return"cherry-pick";if(V("REVERT_HEAD"))return"revert";if(V("MERGE_HEAD"))return"merge";return null}async function Q8($){let Z=await l($);if(!Z)throw Error("No operation in progress to abort");return await F($).raw([Z,"--abort"]),`Aborted ${Z}`}async function X8($){return await F($,{longRunning:!0}).raw(["-c","core.editor=true","rebase","--continue"]),"Rebase continued"}async function Y8($){return(await F($).raw(["ls-files","-z","--cached","--others","--exclude-standard"])).split("\x00").filter((V)=>V.length>0)}import*as V$ from"node:fs";import*as N$ from"node:path";import*as n from"node:fs";import*as K$ from"node:path";function wZ(){return K$.join(j$(),"base-branches.json")}function d5(){let $=K$.dirname(wZ());if(!n.existsSync($))n.mkdirSync($,{recursive:!0})}function W8(){try{let $=wZ();if(n.existsSync($))return JSON.parse(n.readFileSync($,"utf-8"))}catch{}return{}}function l5($){d5(),n.writeFileSync(wZ(),JSON.stringify($,null,2)+`
23
+ `)}function H$($){let Z=W8(),K=K$.resolve($);return Z[K]}function J8($,Z){let K=W8(),V=K$.resolve($);K[V]=Z,l5(K)}function x$($){let Z=Math.min($.length,8192);for(let K=0;K<Z;K++)if($[K]===0)return!0;return!1}class C$ extends Error{constructor($){super(`No common history with ${$}`);this.name="NoCommonHistoryError"}}async function B$($,Z,K=!1){let V=F($);try{let Q=[];if(K)Q.push("--cached");if(Z)Q.push("--",Z);let X=M$(await V.diff(Q));return{lines:r(X)}}catch{return{lines:[]}}}var n5="4b825dc642cb6eb9a060e54bf8d69288fbee4904",z8="(unborn)",o5=/unknown revision|ambiguous argument 'HEAD'|needed a single revision/i;async function $Z($){let Z=F($);try{return(await Z.raw(["rev-parse","HEAD"])).trim()}catch(K){let V=K instanceof Error?K.message:String(K);if(o5.test(V))return z8;throw K}}async function U8($){let Z=F($),V=await $Z($)===z8?n5:"HEAD",Q=M$(await Z.raw(["diff","-U3",V,"--"]));return{lines:r(Q)}}var a5=_$;function i5($,Z){return{lines:[{type:"header",content:`diff --git a/${$} b/${$}`},{type:"header",content:"new file mode 100644"},{type:"header",content:"--- /dev/null"},{type:"header",content:`+++ b/${$}`},{type:"header",content:SZ(Z)}]}}function s5($){return{lines:[{type:"header",content:`diff --git a/${$} b/${$}`},{type:"header",content:"new file mode 100644"},{type:"header",content:`Binary files /dev/null and b/${$} differ`}]}}function r5($,Z){let K=N$.resolve($),V=N$.resolve(K,Z);if(V!==K&&!V.startsWith(K+N$.sep))return null;let Q,X;try{Q=V$.realpathSync(V),X=V$.realpathSync(K)}catch{return null}if(Q!==X&&!Q.startsWith(X+N$.sep))return null;let Y=V$.statSync(Q);if(!Y.isFile())return null;return{path:V,size:Y.size}}async function ZZ($,Z){try{let K=r5($,Z);if(K===null)return{lines:[]};if(K.size>a5)return i5(Z,K.size);let V=V$.readFileSync(K.path);if(x$(V))return s5(Z);let Q=V.toString("utf-8"),X=[{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}`}],Y=Q.endsWith(`
24
+ `),W=Q.split(`
25
+ `);if(Y)W.pop();if(Q.length>0){X.push({type:"hunk",content:`@@ -0,0 +1,${W.length} @@`});let U=1;for(let j of W)X.push({type:"addition",content:"+"+j,newLineNum:U++});if(!Y)X.push({type:"context",content:"\"})}let J=Z$(X),z=M$(J);if(z!==J)return{lines:r(z)};return{lines:X}}catch{return{lines:[]}}}async function EZ($){let Z=F($),K=new Set,V=[];try{let Q=await Z.raw(["log","--oneline","--decorate=short","--all","-n","200"]),X=/\(([^)]+)\)/g;for(let Y of Q.split(`
26
+ `)){let W=X.exec(Y);if(W){let J=W[1].split(",").map((z)=>z.trim());for(let z of J){if(z.startsWith("HEAD")||z.startsWith("tag:")||!z.includes("/"))continue;let U=z.replace(/^.*-> /,"");if(U.includes("/")&&!K.has(U))K.add(U),V.push(U)}}X.lastIndex=0}if(V.length>0)V.sort((Y,W)=>{let J=Y.split("/").slice(1).join("/"),z=W.split("/").slice(1).join("/"),U=J==="main"||J==="master",j=z==="main"||z==="master";if(U&&!j)return-1;if(!U&&j)return 1;if(U&&j){let O=Y.startsWith("origin/"),M=W.startsWith("origin/");if(O&&!M)return 1;if(!O&&M)return-1}return 0})}catch{}return[...new Set(V)]}async function b$($){return(await EZ($))[0]??null}async function kZ($){return H$($)??await b$($)}async function t($,Z){let K=F($);try{return await K.raw(["cat-file","-e","--end-of-options",`${Z}^{commit}`]),!0}catch{return!1}}async function _Z($,Z){let K=F($),Q=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Q)throw new C$(Z);let X=await K.raw(["diff","--numstat",`${Q}...HEAD`]),Y=await K.raw(["diff","--name-status",`${Q}...HEAD`]),W=M$(await K.raw(["diff",`${Q}...HEAD`])),J=X.trim().split(`
27
+ `).filter((G)=>G),z=new Map;for(let G of J){let H=G.split("\t");if(H.length>=3){let L=H[0]==="-"?0:parseInt(H[0],10),v=H[1]==="-"?0:parseInt(H[1],10),R=H.slice(2).join("\t");z.set(R,{additions:L,deletions:v})}}let U=Y.trim().split(`
28
+ `).filter((G)=>G),j=new Map;for(let G of U){let H=G.split("\t");if(H.length>=2){let L=H[0][0],v=H[H.length-1],R;switch(L){case"A":R="added";break;case"D":R="deleted";break;case"R":R="renamed";break;default:R="modified"}j.set(v,R)}}let O=[],M=W.split(/(?=^diff --git )/m).filter((G)=>G.trim());for(let G of M){let H=G.match(/^diff --git a\/.+ b\/(.+)$/m);if(!H)continue;let L=H[1],v=r(G),R=z.get(L)||{additions:0,deletions:0},x=j.get(L)||"modified";O.push({path:L,status:x,additions:R.additions,deletions:R.deletions,diff:{lines:v}})}let B=0,I=0;for(let G of O)B+=G.additions,I+=G.deletions;let D=(await K.status()).files.length,A=(await K.log({from:Q,to:"HEAD"})).all.map((G)=>({hash:G.hash,shortHash:G.hash.slice(0,7),message:G.message.split(`
29
+ `)[0],author:G.author_name,date:new Date(G.date),refs:G.refs||""}));return O.sort((G,H)=>G.path.localeCompare(H.path)),{baseBranch:Z,stats:{filesChanged:O.length,additions:B,deletions:I},files:O,commits:A,uncommittedCount:D}}async function j8($,Z){let K=F($),Q=(await K.raw(["merge-base","--end-of-options",Z,"HEAD"])).trim();if(!Q)throw new C$(Z);let X=await K.raw(["rev-list","--count","--end-of-options",`${Q}..HEAD`]);return Number.parseInt(X.trim(),10)}async function O8($,Z){let K=F($);try{let V=M$(await K.raw(["show","--format=","--end-of-options",Z]));return{lines:r(V)}}catch{return{lines:[]}}}async function G8($,Z){let K=F($),V=await _Z($,Z),Q=await K.diff(["--cached","--numstat"]),X=await K.diff(["--numstat"]),Y=await K.diff(["--cached"]),W=await K.diff([]),J=new Map;for(let G of Q.trim().split(`
30
+ `).filter((H)=>H)){let H=G.split("\t");if(H.length>=3){let L=H[0]==="-"?0:parseInt(H[0],10),v=H[1]==="-"?0:parseInt(H[1],10),R=H.slice(2).join("\t");J.set(R,{additions:L,deletions:v,staged:!0,unstaged:!1})}}for(let G of X.trim().split(`
31
+ `).filter((H)=>H)){let H=G.split("\t");if(H.length>=3){let L=H[0]==="-"?0:parseInt(H[0],10),v=H[1]==="-"?0:parseInt(H[1],10),R=H.slice(2).join("\t"),x=J.get(R);if(x)x.additions+=L,x.deletions+=v,x.unstaged=!0;else J.set(R,{additions:L,deletions:v,staged:!1,unstaged:!0})}}let z=await K.status(),U=new Map;for(let G of z.files)if(G.index==="A"||G.working_dir==="?")U.set(G.path,"added");else if(G.index==="D"||G.working_dir==="D")U.set(G.path,"deleted");else if(G.index==="R")U.set(G.path,"renamed");else U.set(G.path,"modified");let j=[],M=(Y+W).split(/(?=^diff --git )/m).filter((G)=>G.trim()),B=new Set;for(let G of M){let H=G.match(/^diff --git a\/.+ b\/(.+)$/m);if(!H)continue;let L=H[1];if(B.has(L))continue;B.add(L);let v=r(G),R=J.get(L)||{additions:0,deletions:0},x=U.get(L)||"modified";j.push({path:L,status:x,additions:R.additions,deletions:R.deletions,diff:{lines:v},isUncommitted:!0})}let I=new Set(V.files.map((G)=>G.path)),T=[];for(let G of V.files){let H=j.find((L)=>L.path===G.path);if(H)T.push(G),T.push(H);else T.push(G)}for(let G of j)if(!I.has(G.path))T.push(G);let D=0,C=0,A=new Set;for(let G of T)A.add(G.path),D+=G.additions,C+=G.deletions;return T.sort((G,H)=>G.path.localeCompare(H.path)),{baseBranch:V.baseBranch,stats:{filesChanged:A.size,additions:D,deletions:C},files:T,commits:V.commits,uncommittedCount:V.uncommittedCount}}import*as M8 from"node:fs";import*as H8 from"node:path";var t5=/^diff --git a\/.+ b\/(.+)$/;function KZ($){let Z=5381;for(let K of $){for(let V=0;V<K.length;V++)Z=(Z<<5)+Z+K.charCodeAt(V)|0;Z=(Z<<5)+Z+10|0}return(Z>>>0).toString(36)}function e5($){let Z=[],K="",V=null,Q=()=>{if(V&&K)Z.push({file:K,key:`${K}\x00${KZ(V.body)}`,headerLine:V.headerLine});V=null};for(let X of $.lines)if(X.type==="header"){Q();let Y=X.content.match(t5);if(Y)K=Y[1]}else if(X.type==="hunk")Q(),V={headerLine:X,body:[]};else if(V&&(X.type==="addition"||X.type==="deletion"))V.body.push(X.content);return Q(),Z}class PZ{repoPath;stamps=new Map;constructor($){this.repoPath=$}stamp($){if(!$)return;let Z=new Map;for(let K of e5($)){let V=this.stamps.get(K.key);if(V===void 0){let Q=Z.get(K.file);if(Q===void 0)Q=this.mtimeOf(K.file),Z.set(K.file,Q);V=Q,this.stamps.set(K.key,V)}K.headerLine.editedAt=V}}prune($){for(let Z of this.stamps.keys()){let K=Z.slice(0,Z.indexOf("\x00"));if(!$.has(K))this.stamps.delete(Z)}}mtimeOf($){try{return M8.statSync(H8.join(this.repoPath,$)).mtimeMs}catch{return Date.now()}}}import*as o from"node:fs";import*as b from"node:path";async function N8($){let Z=L8($);if(!Z)return null;try{let K=F(Z);if((await K.raw(["rev-parse","--is-bare-repository"])).trim()==="true")return null;return(await K.raw(["rev-parse","--show-toplevel"])).trim()||null}catch{return null}}async function y$($){let Z=L8($);if(!Z)return[];try{let V=await F(Z).raw(["worktree","list","--porcelain"]),Q=K0(V),X=await Z0(Q,Z);return Q.map((Y)=>({...Y,lastActivity:Y.isBare?null:$0(B8(Y.path)),aheadOfBase:X.get(Y.path)??null}))}catch{return[]}}function $0($){return Number.isFinite($)?$:null}async function Z0($,Z){let K=$.filter((X)=>!X.isBare);if(K.length===0)return new Map;let V=await b$(Z).catch(()=>null),Q=await Promise.all(K.map(async(X)=>{let Y=H$(X.path)??V;if(!Y)return null;try{let J=await F(X.path).raw(["rev-list","--count","--end-of-options",`${Y}..HEAD`]);return[X.path,parseInt(J.trim(),10)]}catch{return null}}));return new Map(Q.filter((X)=>X!==null))}function C8($){let Z=null,K=-1/0;for(let V of $){if(V.isBare)continue;let Q=B8(V.path);if(Q>K)K=Q,Z=V}return Z}function B8($){let Z=I8($),K=Z?[b.join(Z,"index"),b.join(Z,"HEAD")]:[$],V=-1/0;for(let Q of K)try{let X=o.statSync(Q).mtimeMs;if(X>V)V=X}catch{}return V}function I8($){let Z=b.join($,".git");try{if(o.statSync(Z).isDirectory())return Z;let K=o.readFileSync(Z,"utf8").match(/^gitdir:\s*(.+)$/m);if(!K)return null;let V=K[1].trim();return b.isAbsolute(V)?V:b.resolve($,V)}catch{return null}}function A8($){let Z=I8($);if(Z===null)return null;let K=Z;try{let V=o.readFileSync(b.join(Z,"commondir"),"utf8").trim();if(V)K=b.isAbsolute(V)?V:b.resolve(Z,V)}catch{}return{gitDir:Z,commonDir:K}}function K0($){let Z=[],K=null;for(let V of $.split(`
32
+ `))if(V.startsWith("worktree ")){if(K)Z.push(K);K={path:V.slice(9).trim(),branch:null,head:null,isBare:!1,isMain:Z.length===0}}else if(!K)continue;else if(V.startsWith("HEAD "))K.head=V.slice(5).trim();else if(V.startsWith("branch "))K.branch=V.slice(7).trim().replace(/^refs\/heads\//,"");else if(V==="bare")K.isBare=!0;if(K)Z.push(K);return Z}function L8($){try{if(o.statSync($).isDirectory())return $;return b.dirname($)}catch{let Z=b.dirname($);return Z!==$&&o.existsSync(Z)?Z:null}}var O0=U5(_8(),1);var G0=/^diff --git a\/.+ b\/(.+)$/;function P8($){return G0.exec($)?.[1]??null}function XZ($){let Z=new Map,K=null;for(let Q of $.lines){if(Q.type==="header"){let X=P8(Q.content);if(X!==null)K=Z.get(X)??[],Z.set(X,K)}K?.push(Q)}let V=new Map;for(let[Q,X]of Z)V.set(Q,{lines:X});return V}var YZ="diffstalker-journal: oversize untracked snapshot omitted";var N0=262144;function C0($,Z){let K=Z;if(!K||K.isSymbolicLink())try{K=g.statSync($)}catch{return!1}return!K.isFile()&&!K.isDirectory()}class WZ extends H0{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 PZ($)}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=b8();Z.add(".git");let K=k.join(this.repoPath,".gitignore");if(g.existsSync(K))Z.add(g.readFileSync(K,"utf-8"));let V=k.join(this.repoPath,".git","info","exclude");if(g.existsSync(V))Z.add(g.readFileSync(V,"utf-8"));$.set("",Z);try{let Q=M0("git",["ls-files","-z","--cached","--others","**/.gitignore"],{cwd:this.repoPath,encoding:"utf-8",env:p()});for(let X of Q.split("\x00")){if(!X||X===".gitignore")continue;if(!X.endsWith(".gitignore"))continue;let Y=k.dirname(X),W=k.join(this.repoPath,X);try{let J=g.readFileSync(W,"utf-8"),z=b8();z.add(J),$.set(Y,z)}catch(J){a$(`Failed to read ${W}: ${J instanceof Error?J.message:J}`)}}}catch{}return $}startWatching(){let $=A8(this.repoPath);if($===null)return;let Z=k.join($.gitDir,"index"),K=k.join($.gitDir,"HEAD"),V=k.join($.commonDir,"refs"),Q=k.join($.commonDir,"packed-refs"),X=k.join(this.repoPath,".gitignore");this.gitWatcher=x8([Z,K,V,Q,X],{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100}),this.ignorers=this.loadGitignores(),this.workingDirWatcher=x8(this.repoPath,{persistent:!0,ignoreInitial:!0,ignored:(W,J)=>{let z=k.relative(this.repoPath,W);if(!z)return!1;let U=z.split("/");for(let j=0;j<U.length;j++){let O=j===0?"":U.slice(0,j).join("/"),M=this.ignorers.get(O);if(M){let B=j===0?z:U.slice(j).join("/");if(M.ignores(B))return!0}}return C0(W,J)},awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}});let Y=()=>this.scheduleRefresh();this.gitWatcher.on("change",(W)=>{if(W===X)this.ignorers=this.loadGitignores();Y()}),this.gitWatcher.on("add",Y),this.gitWatcher.on("unlink",Y),this.gitWatcher.on("error",(W)=>{let J=W instanceof Error?W.message:String(W);this.setError(`Git watcher error: ${J}`)}),this.workingDirWatcher.on("change",Y),this.workingDirWatcher.on("add",Y),this.workingDirWatcher.on("unlink",Y),this.workingDirWatcher.on("error",(W)=>{let J=W instanceof Error?W.message:String(W);this.setError(`Working dir watcher error: ${J}`)})}dispose(){this.gitWatcher?.close(),this.workingDirWatcher?.close()}statMtimes($){let Z=new Map;for(let K of $.files){if(Z.has(K.path))continue;try{Z.set(K.path,g.statSync(k.join(this.repoPath,K.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 vZ(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 $Z(this.repoPath).catch(()=>null);try{let K=await vZ(this.repoPath);if(!K.isRepo){this.updateState({status:K,isLoading:!1,error:"Not a git repository"});return}let[V,Q,X,Y,W]=await Promise.all([B$(this.repoPath,void 0,!1),B$(this.repoPath,void 0,!0),t$(this.repoPath),l(this.repoPath),this.gatherJournalInputs(K,Z,$)]),J={unstaged:r$(Z$(V.lines)),staged:r$(Z$(Q.lines))};this.hunkTimes.stamp(V),this.hunkTimes.stamp(Q),this.hunkTimes.prune(new Set(K.files.map((U)=>U.path)));let z=this.statMtimes(K);if(this.updateState({status:K,hunkCounts:J,stashList:X,operationInProgress:Y,mtimes:z,isLoading:!1}),W!==null)this.emit("journal-observation",{status:K,headDiff:W.headDiff,headOid:W.headOid,stashCount:W.stashCount,operationInProgress:W.operationInProgress,mtimes:W.mtimes,at:Date.now()})}catch(K){this.updateState({isLoading:!1,error:K instanceof Error?K.message:"Unknown error"})}}async snapshotJournalGuard($){let[Z,K]=await Promise.all([l(this.repoPath),t$(this.repoPath)]);return{operation:Z,stashCount:K.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[K,V]of $.mtimes)if(Z.mtimes.get(K)!==V)return!0;return!1}sectionWrittenDuringGather($,Z,K){let V=new Set(Z);for(let Q of $.files)if(Q.status==="untracked")V.add(Q.path);for(let Q of V)try{let X=g.statSync(k.join(this.repoPath,Q));if(Math.floor(X.mtimeMs)>K)return!0}catch{}return!1}async gatherJournalInputs($,Z,K){if(Z===null)return null;try{let V=await this.snapshotJournalGuard($),Q=await U8(this.repoPath),X=new Set(XZ(Q).keys()),Y=[...Q.lines];await this.appendUntrackedSections($,X,Y);let W=await $Z(this.repoPath);if(Z!==W)return null;let J=await this.snapshotJournalGuard($);if(WZ.journalGuardMoved(V,J))return null;if(this.sectionWrittenDuringGather($,X,K))return null;return{headDiff:{lines:Y},headOid:W,stashCount:J.stashCount,operationInProgress:J.operation,mtimes:J.mtimes}}catch{return null}}async appendUntrackedSections($,Z,K){let V=new Set;for(let Q of $.files){if(Q.status!=="untracked"||V.has(Q.path)||Z.has(Q.path))continue;V.add(Q.path);let X;try{X=g.statSync(k.join(this.repoPath,Q.path))}catch{continue}if(!X.isFile())continue;if(X.size>N0){this.appendOversizeSection(Q.path,X,K);continue}let Y=await ZZ(this.repoPath,Q.path);if(Y.lines.length===0)continue;K.push(...Y.lines)}}appendOversizeSection($,Z,K){let V=[`diff --git a/${$} b/${$}`,"new file mode 100644",`${YZ} size=${Z.size} mtime=${Math.round(Z.mtimeMs)}`];K.push(...V.map((Q)=>({type:"header",content:Q})))}async stage($){try{await this.queue.enqueueMutation(()=>y6(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(()=>m6(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()=>d6(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()=>l6(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"?()=>p6(this.repoPath,$.path):()=>u6(this.repoPath,$.path);try{await this.queue.enqueueMutation(Z),await this.refresh()}catch(K){this.updateState({error:`Failed to discard ${$.path}: ${K instanceof Error?K.message:String(K)}`})}}async stageAll(){try{await this.queue.enqueueMutation(()=>g6(this.repoPath)),await this.refresh()}catch($){this.updateState({error:`Failed to stage all: ${$ instanceof Error?$.message:String($)}`})}}async unstageAll(){try{await this.queue.enqueueMutation(()=>c6(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(()=>h6(this.repoPath,$,Z)),await this.refresh()}catch(K){this.updateState({error:`Failed to commit: ${K instanceof Error?K.message:String(K)}`})}}async loadStashList(){try{let $=await this.queue.enqueue(()=>t$(this.repoPath));this.updateState({stashList:$})}catch{}}}import{EventEmitter as B0}from"node:events";class mZ extends B0{repoPath;queue;callbacks;_remoteState={operation:null,inProgress:!1,error:null,lastResult:null};constructor($,Z,K){super();this.repoPath=$,this.queue=Z,this.callbacks=K}get remoteState(){return this._remoteState}updateRemoteState($){this._remoteState={...this._remoteState,...$},this.emit("remote-state-change",this._remoteState)}async runRemoteOperation($,Z){this.updateRemoteState({operation:$,inProgress:!0,error:null,lastResult:null});try{let K=await this.queue.enqueue(Z);this.updateRemoteState({inProgress:!1,lastResult:K}),this.callbacks.scheduleRefresh()}catch(K){let V=K instanceof Error?K.message:String(K);this.updateRemoteState({inProgress:!1,error:V})}return this._remoteState}clearRemoteState(){this.updateRemoteState({operation:null,error:null,lastResult:null})}async push(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("push",()=>n6(this.repoPath))}async fetchRemote(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("fetch",()=>o6(this.repoPath))}async pullRebase(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("pull",()=>a6(this.repoPath))}async stash($){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stash",()=>r6(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async stashPop($=0){if(this._remoteState.inProgress)return null;let Z=await this.runRemoteOperation("stashPop",()=>t6(this.repoPath,$));return await this.callbacks.loadStashList(),Z}async getLocalBranches(){return this.queue.enqueue(()=>e$(this.repoPath))}async switchBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchSwitch",()=>e6(this.repoPath,$))}async createBranch($){if(this._remoteState.inProgress)return null;return await this.runRemoteOperation("branchCreate",()=>$8(this.repoPath,$))}async softReset($=1){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("softReset",()=>Z8(this.repoPath,$))}async cherryPick($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("cherryPick",()=>K8(this.repoPath,$))}async revertCommit($){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("revert",()=>V8(this.repoPath,$))}async abortOperation(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("abort",()=>Q8(this.repoPath))}async rebaseContinue(){if(this._remoteState.inProgress)return null;return this.runRemoteOperation("rebaseContinue",()=>X8(this.repoPath))}}import{EventEmitter as I0}from"node:events";import{randomBytes as A0}from"node:crypto";var L0=262144,T0=500,D0=16777216,g8=Number.MAX_SAFE_INTEGER,q0=/^@@ -(\d+)(?:,(\d+))? \+\d+(?:,\d+)? @@/;function F0($){let Z=q0.exec($);if(!Z)return null;return{oldStart:parseInt(Z[1],10),oldCount:Z[2]!==void 0?parseInt(Z[2],10):1}}function S0($,Z){let K=F0(Z);if(!K)return[];let V=K.oldCount===0?K.oldStart+1:K.oldStart,Q=[],X=null;for(let Y of $){let W=Y.content[0];if(W==="\\")continue;if(W==="-")X=R0(X,V),V++;else if(W==="+")X=X??{hasDel:!1,delStart:0,delEnd:0,anchor:V-1};else y8(Q,X),X=null,V++}return y8(Q,X),Q}function R0($,Z){if(!$)return{hasDel:!0,delStart:Z,delEnd:Z,anchor:Z-1};if(!$.hasDel)$.hasDel=!0,$.delStart=Z;return $.delEnd=Z,$}function y8($,Z){if(!Z)return;$.push(Z.hasDel?[2*Z.delStart,2*Z.delEnd]:[2*Z.anchor,2*Z.anchor+2])}function gZ($){if($.length===0)return{start:0,count:0};let Z=1/0,K=-1/0;for(let[X,Y]of $){if(X<Z)Z=X;if(Y>K)K=Y}if(K>=g8)return{start:0,count:0};let V=Math.ceil(Z/2),Q=Math.floor(K/2);return{start:V,count:Q-V+1}}function v0($){let Z=[],K=null,V=[],Q=null;for(let Y of $.lines)if(Y.type==="hunk")Q={header:Y,body:[]},V.push(Q);else if(Q)Q.body.push(Y);else if(Z.push(Y),Y.content.startsWith("rename from "))K=Y.content.slice(12);if(V.length===0){let Y=Z.some((W)=>W.content.startsWith(YZ));return{hunks:[{runs:[[0,g8]],bodyHash:KZ([Z$($.lines)]),ins:0,del:0,span:{start:0,count:0},diff:$,oversize:Y}],renamedFrom:K,hunkless:!0}}return{hunks:V.map(({header:Y,body:W})=>{let J=S0(W,Y.content),z=[],U=0,j=0;for(let M of W){let B=M.content[0];if(B==="\\")continue;if(B==="+")U++,z.push(M.content);else if(B==="-")j++,z.push(M.content)}let O=[...Z,Y,...W];return{runs:J,bodyHash:KZ(z),ins:U,del:j,span:gZ(J),diff:{lines:O}}}),renamedFrom:K,hunkless:!1}}function w0($){if($.oversize===!0)return null;return s$($.diff.lines)>L0?null:$.diff}function E0($,Z,K){if($===0&&Z>0)return"shrunk";let V=$+Z;if(V>K)return"expanded";if(V<K)return"shrunk";return"edited"}function m8($,Z){let K=[];return $.forEach((V,Q)=>{for(let[X,Y]of V.runs)K.push({lo:X,hi:Y,node:Z+Q})}),K.sort((V,Q)=>V.lo-Q.lo),K}function k0($,Z){let K=Array.from({length:$.length+Z.length},(J,z)=>z),V=(J)=>{while(K[J]!==J)K[J]=K[K[J]],J=K[J];return J},Q=(J,z)=>{let U=V(J),j=V(z);if(U!==j)K[U]=j},X=m8($,0),Y=m8(Z,$.length),W=0;for(let J of X){while(W<Y.length&&Y[W].hi<J.lo)W++;for(let z=W;z<Y.length&&Y[z].lo<=J.hi;z++)Q(J.node,Y[z].node)}return K.map((J,z)=>V(z))}function _0($,Z){let K=k0($,Z),V=new Map,Q=(X)=>{let Y=V.get(X);if(!Y)Y={prevIdx:[],nextIdx:[],minLo:1/0},V.set(X,Y);return Y};return $.forEach((X,Y)=>{let W=Q(K[Y]);W.prevIdx.push(Y);for(let[J]of X.runs)if(J<W.minLo)W.minLo=J}),Z.forEach((X,Y)=>{let W=Q(K[$.length+Y]);W.nextIdx.push(Y);for(let[J]of X.runs)if(J<W.minLo)W.minLo=J}),[...V.values()].sort((X,Y)=>X.minLo-Y.minLo)}function P0($,Z,K){let V=[],Q=Z.map(()=>null),X=K;for(let Y of _0($,Z)){let W=Y.prevIdx.map((j)=>$[j]),J=Y.nextIdx.map((j)=>Z[j]);if(W.length===1&&J.length===1&&W[0].bodyHash===J[0].bodyHash){let j=J[0];Q[Y.nextIdx[0]]={seq:W[0].seq,runs:j.runs,bodyHash:j.bodyHash,ins:j.ins,del:j.del};continue}if(J.length===0){for(let j of W)V.push({seq:X++,kind:"reverted",span:gZ(j.runs),stats:{insertions:0,deletions:0},diff:null,supersedes:[j.seq],siblings:1});continue}let z=W.map((j)=>j.seq),U=W.reduce((j,O)=>j+O.ins+O.del,0);for(let j of Y.nextIdx){let O=Z[j],M={seq:X++,kind:W.length===0?"created":E0(O.ins,O.del,U),span:O.span,stats:{insertions:O.ins,deletions:O.del},diff:w0(O),supersedes:[...z],siblings:J.length};V.push(M),Q[j]={seq:M.seq,runs:O.runs,bodyHash:O.bodyHash,ins:O.ins,del:O.del}}}return{entries:V,nextLive:Q.filter((Y)=>Y!==null)}}function x0($,Z){let K=Array($.length).fill(!1),V=Array(Z.length).fill(null);for(let W=0;W<Z.length;W++){let J=$.findIndex((z,U)=>!K[U]&&z.bodyHash===Z[W].bodyHash);if(J!==-1)K[J]=!0,V[W]=$[J].seq}for(let W=0;W<Z.length;W++){if(V[W]!==null)continue;let J=K.findIndex((z)=>!z);if(J!==-1)K[J]=!0,V[W]=$[J].seq}let Q=$[$.length-1].seq,X=Z.map((W,J)=>{return{seq:V[J]??Q,runs:W.runs,bodyHash:W.bodyHash,ins:W.ins,del:W.del}}),Y=$.filter((W,J)=>!K[J]).map((W)=>W.seq);return{carried:X,retired:Y}}function JZ(){return{entries:[],epoch:`${Date.now().toString(36)}-${A0(4).toString("hex")}`,nextSeq:1,live:new Map,lastHeadOid:null,lastBranch:null,lastStashCount:0,lastOperation:null}}class cZ extends I0{store;constructor($){super();this.store=$}get journalStore(){return this.store}observe($){try{this.doObserve($)}catch(Z){a$(`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 K of Z)$.add(K.seq);this.pruneBodies($),this.pruneEntries($)}pruneBodies($){let Z=0;for(let K of this.store.entries)if(K.type==="hunk"&&K.diff!==null)Z+=s$(K.diff.lines);for(let K of this.store.entries){if(Z<=D0)return;if(K.type!=="hunk"||K.diff===null||$.has(K.seq))continue;Z-=s$(K.diff.lines),K.diff=null}}pruneEntries($){let Z=this.store.entries,K=0;while(Z.length-K>T0&&(Z[K].type==="boundary"||!$.has(Z[K].seq)))K++;if(K>0)Z.splice(0,K)}handleOperations($,Z){let K=this.store.lastOperation;if($.operationInProgress!==null){if(K===null)Z.push(this.boundary("op-start",$.operationInProgress,[],$.at)),this.store.lastOperation=$.operationInProgress;return!0}if(K!==null)Z.push(this.boundary("op-end",K,[],$.at)),this.store.lastOperation=null;return!1}seed($,Z){Z.push(this.boundary("journal-start",$.status.branch.current,[],$.at));let{files:K}=this.parseObservation($),V=[...K.keys()].sort((Q,X)=>this.tsFor($,Q)-this.tsFor($,X));for(let Q of V)this.classifyPath(Q,[],K.get(Q).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:K,deferred:V}=this.parseObservation($),Q=$.status.branch.current===this.store.lastBranch,X=Q?"commit":"checkout",Y=Q?$.headOid.slice(0,7):$.status.branch.current,{resolves:W,newLive:J}=this.carrySurvivors(K,V);Z.push(this.boundary(X,Y,W,$.at)),this.store.live=J;for(let[z,{hunks:U}]of K){if(J.has(z))continue;this.classifyPath(z,[],U,$,!1,Z)}this.store.lastHeadOid=$.headOid,this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}carrySurvivors($,Z){let K=[],V=new Map;for(let[Q,X]of this.store.live){if(Z.has(Q)){V.set(Q,X);continue}let Y=$.get(Q);if(!Y){K.push(...X.map((z)=>z.seq));continue}let{carried:W,retired:J}=x0(X,Y.hunks);K.push(...J),V.set(Q,W)}return{resolves:K,newLive:V}}classify($,Z){let{files:K,deferred:V}=this.parseObservation($);this.handleRenames($,K,Z),this.handleDisappearances($,K,V,Z);for(let[Q,{hunks:X,renamedFrom:Y,hunkless:W}]of K){let J=this.store.live.get(Q)??[];if(W&&Y!==null&&J.length>0)continue;this.classifyPath(Q,J,X,$,!1,Z)}this.store.lastBranch=$.status.branch.current,this.store.lastStashCount=$.stashCount}handleRenames($,Z,K){for(let[V,Q]of Z){let X=Q.renamedFrom;if(X===null||X===V)continue;if(!this.store.live.has(X)||Z.has(X))continue;let Y=(this.store.live.get(V)??[]).map((W)=>W.seq);this.store.live.set(V,this.store.live.get(X)),this.store.live.delete(X),K.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,V),path:V,status:"renamed",kind:"renamed",span:{start:0,count:0},stats:{insertions:0,deletions:0},diff:null,supersedes:Y,siblings:1,seeded:!1})}}handleDisappearances($,Z,K,V){let Q=[...this.store.live.keys()].filter((X)=>!Z.has(X)&&!K.has(X));if(Q.length===0)return;if($.stashCount>this.store.lastStashCount){let X=Q.flatMap((Y)=>this.store.live.get(Y).map((W)=>W.seq));V.push(this.boundary("stash","stash",X,$.at));for(let Y of Q)this.store.live.delete(Y);return}for(let X of Q){let Y=this.store.live.get(X);V.push({type:"hunk",seq:this.store.nextSeq++,ts:this.tsFor($,X),path:X,status:this.statusOf($,X),kind:"reverted",span:gZ(Y.flatMap((W)=>W.runs)),stats:{insertions:0,deletions:0},diff:null,supersedes:Y.map((W)=>W.seq),siblings:1,seeded:!1}),this.store.live.delete(X)}}classifyPath($,Z,K,V,Q,X){let{entries:Y,nextLive:W}=P0(Z,K,this.store.nextSeq);this.store.nextSeq+=Y.length;let J=this.tsFor(V,$),z=this.statusOf(V,$);for(let U of Y){let j={type:"hunk",seq:U.seq,ts:J,path:$,status:z,kind:U.kind==="created"&&z==="renamed"?"renamed":U.kind,span:U.span,stats:U.stats,diff:U.diff,supersedes:U.supersedes,siblings:U.siblings,seeded:Q};X.push(j)}if(W.length>0)this.store.live.set($,W);else this.store.live.delete($)}parseObservation($){let Z=new Map;for(let[V,Q]of XZ($.headDiff))Z.set(V,v0(Q));let K=new Set;for(let V of $.status.files)if(V.status==="untracked"&&!Z.has(V.path))K.add(V.path);return{files:Z,deferred:K}}boundary($,Z,K,V){return{type:"boundary",seq:this.store.nextSeq++,ts:V,kind:$,label:Z,resolves:K}}tsFor($,Z){let K=$.mtimes?.get(Z);return K===void 0?$.at:Math.min(K,$.at)}statusOf($,Z){return $.status.files.find((K)=>K.path===Z)?.status??"modified"}}class uZ{workingTree;remote;journal;repoPath;constructor($,Z){this.repoPath=$;let K=F6($);this.workingTree=new WZ($,K),this.remote=new mZ($,K,{scheduleRefresh:()=>this.workingTree.scheduleRefresh(),loadStashList:()=>this.workingTree.loadStashList()}),this.journal=new cZ(Z??JZ()),this.workingTree.on("journal-observation",(V)=>this.journal.observe(V))}dispose(){this.workingTree.dispose(),S6(this.repoPath)}}function y0($){return b0("sha256").update($).digest("hex").slice(0,12)}var m0=32;class u8{cap;stores=new Map;constructor($=m0){this.cap=$}acquire($){let Z=this.stores.get($);if(Z)this.stores.delete($);else Z=JZ();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 pZ{events;byId=new Map;byPath=new Map;journalStores=new u8;constructor($={}){this.events=$}async openRepo($){let Z=O$($);if(!c8.isAbsolute(Z))throw Error(`Repo path must be absolute: ${$}`);let K=await N8(Z);if(!K){let W=C8(await y$(Z));if(!W)throw Error(`Not a git repository: ${Z}`);K=W.path}let V=this.byPath.get(K);if(V)return V.refCount++,{handle:V,created:!1};let Q=y0(K),X=new uZ(K,this.journalStores.acquire(Q));X.workingTree.startWatching();let Y={id:Q,path:K,manager:X,refCount:1};return this.byId.set(Y.id,Y),this.byPath.set(K,Y),this.journalStores.prune((W)=>this.byId.has(W)),this.events.onOpened?.(Y),{handle:Y,created:!0}}getRepo($){return this.byId.get($)}listRepos(){return[...this.byId.values()]}closeRepo($){let Z=this.byId.get($);if(!Z)return!1;if(Z.refCount--,Z.refCount>0)return!1;return this.byId.delete(Z.id),this.byPath.delete(Z.path),Z.manager.dispose(),this.events.onClosed?.(Z.id),!0}disposeAll(){for(let $ of this.byId.values())$.manager.dispose();this.byId.clear(),this.byPath.clear()}}async function zZ($,Z){let K=await $.openRepo(Z);if(K.created)K.handle.manager.workingTree.refresh().catch(()=>{});return K}var p8=25000;function g$($,Z,K){$.write(`event: ${Z}
26
33
  data: ${K}
27
34
 
28
- `)}class W4{channels=new Map;subscribe($,Z,K,V){V.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let X=this.channels.get($);if(!X){let Q=new Set,z={manager:Z,subscribers:Q,listener:(W)=>{let J=JSON.stringify(l(W));if(J===z.lastData)return;z.lastData=J;for(let U of Q)G$(U,"state-change",J)},journalListener:(W)=>{let J=JSON.stringify({epoch:Z.journal.journalStore.epoch,entries:p$(W)});for(let U of Q)G$(U,"journal-append",J)},keepAlive:setInterval(()=>{for(let W of Q)W.write(`: ping
35
+ `)}class hZ{channels=new Map;subscribe($,Z,K,V){V.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"});let Q=this.channels.get($);if(!Q){let Y=new Set,W={manager:Z,subscribers:Y,listener:(J)=>{let z=JSON.stringify(s(J));if(z===W.lastData)return;W.lastData=z;for(let U of Y)g$(U,"state-change",z)},journalListener:(J)=>{let z=JSON.stringify({epoch:Z.journal.journalStore.epoch,entries:TZ(J)});for(let U of Y)g$(U,"journal-append",z)},keepAlive:setInterval(()=>{for(let J of Y)J.write(`: ping
29
36
 
30
- `)},l5),lastData:null};Z.workingTree.on("state-change",z.listener),Z.journal.on("append",z.journalListener),z.keepAlive.unref(),X=z,this.channels.set($,X)}X.subscribers.add(V),K.on("close",()=>this.unsubscribe($,V));let Y=JSON.stringify(l(Z.workingTree.state));G$(V,"snapshot",Y)}unsubscribe($,Z){let K=this.channels.get($);if(!K)return;if(K.subscribers.delete(Z),K.subscribers.size===0)this.teardown($,K)}teardown($,Z){Z.manager.workingTree.off("state-change",Z.listener),Z.manager.journal.off("append",Z.journalListener),clearInterval(Z.keepAlive);for(let K of Z.subscribers)K.end();Z.subscribers.clear(),this.channels.delete($)}closeRepo($){let Z=this.channels.get($);if(Z)this.teardown($,Z)}destroy(){for(let[$,Z]of this.channels)this.teardown($,Z)}}class J4{subscribers=new Set;keepAlive=null;subscribe($,Z,K){if(Z.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),this.subscribers.add(Z),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let V of this.subscribers)V.write(`: ping
37
+ `)},p8),lastData:null};Z.workingTree.on("state-change",W.listener),Z.journal.on("append",W.journalListener),W.keepAlive.unref(),Q=W,this.channels.set($,Q)}Q.subscribers.add(V),K.on("close",()=>this.unsubscribe($,V));let X=JSON.stringify(s(Z.workingTree.state));g$(V,"snapshot",X)}unsubscribe($,Z){let K=this.channels.get($);if(!K)return;if(K.subscribers.delete(Z),K.subscribers.size===0)this.teardown($,K)}teardown($,Z){Z.manager.workingTree.off("state-change",Z.listener),Z.manager.journal.off("append",Z.journalListener),clearInterval(Z.keepAlive);for(let K of Z.subscribers)K.end();Z.subscribers.clear(),this.channels.delete($)}closeRepo($){let Z=this.channels.get($);if(Z)this.teardown($,Z)}destroy(){for(let[$,Z]of this.channels)this.teardown($,Z)}}class fZ{subscribers=new Set;keepAlive=null;subscribe($,Z,K){if(Z.writeHead(200,{"content-type":"text/event-stream","cache-control":"no-cache",connection:"keep-alive"}),this.subscribers.add(Z),!this.keepAlive)this.keepAlive=setInterval(()=>{for(let V of this.subscribers)V.write(`: ping
31
38
 
32
- `)},l5),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),G$(Z,"snapshot",JSON.stringify(K))}broadcast($,Z){let K=JSON.stringify(Z);for(let V of this.subscribers)G$(V,$,K)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as r from"node:fs";import*as y$ from"node:path";import{watch as p8}from"chokidar";import{EventEmitter as h8}from"node:events";import*as P$ from"node:fs";import*as k$ from"node:path";import*as U4 from"node:os";function o5($){if($.startsWith("~/"))return k$.join(U4.homedir(),$.slice(2));if($==="~")return U4.homedir();return $}function a5($){let Z=k$.dirname($);if(!P$.existsSync(Z))P$.mkdirSync(Z,{recursive:!0})}function G4($){let Z=$.split(`
33
- `);for(let K=Z.length-1;K>=0;K--){let V=Z[K].trim();if(V)return V}return""}class O4 extends h8{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=o5($);return y$.isAbsolute(Z)?Z:y$.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=r.readFileSync(this.targetFile,"utf-8"),Z=G4($);if(Z&&Z!==this.lastReadPath){let K=this.processContent(Z),V=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${V.toISOString()}] Path change detected
39
+ `)},p8),this.keepAlive.unref();$.on("close",()=>{if(this.subscribers.delete(Z),this.subscribers.size===0&&this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null}),g$(Z,"snapshot",JSON.stringify(K))}broadcast($,Z){let K=JSON.stringify(Z);for(let V of this.subscribers)g$(V,$,K)}destroy(){if(this.keepAlive)clearInterval(this.keepAlive),this.keepAlive=null;for(let $ of this.subscribers)$.end();this.subscribers.clear()}}import*as Q$ from"node:fs";import*as UZ from"node:path";import{watch as g0}from"chokidar";import{EventEmitter as c0}from"node:events";class dZ extends c0{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=O$($);return UZ.isAbsolute(Z)?Z:UZ.resolve(Z)}readTargetDebounced(){if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{this.readTarget()},100)}readTarget(){try{let $=Q$.readFileSync(this.targetFile,"utf-8"),Z=AZ($);if(Z&&Z!==this.lastReadPath){let K=this.processContent(Z),V=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${V.toISOString()}] Path change detected
34
40
  `),process.stderr.write(` Source file: ${this.targetFile}
35
41
  `),process.stderr.write(` Raw content: "${Z}"
36
42
  `),process.stderr.write(` Previous: "${this.lastReadPath??"(none)"}"
37
43
  `),process.stderr.write(` Resolved: "${K}"
38
- `);this.lastReadPath=K,this.updateState({path:K,lastUpdate:V,rawContent:Z})}}catch{}}start(){if(a5(this.targetFile),!r.existsSync(this.targetFile))r.writeFileSync(this.targetFile,"");try{let $=r.readFileSync(this.targetFile,"utf-8"),Z=G4($);if(Z){let K=this.processContent(Z),V=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${V.toISOString()}] Initial path read
44
+ `);this.lastReadPath=K,this.updateState({path:K,lastUpdate:V,rawContent:Z})}}catch{}}start(){if(U6(this.targetFile),!Q$.existsSync(this.targetFile))Q$.writeFileSync(this.targetFile,"");try{let $=Q$.readFileSync(this.targetFile,"utf-8"),Z=AZ($);if(Z){let K=this.processContent(Z),V=new Date;if(this.debug&&K)process.stderr.write(`[diffstalker ${V.toISOString()}] Initial path read
39
45
  `),process.stderr.write(` Source file: ${this.targetFile}
40
46
  `),process.stderr.write(` Raw content: "${Z}"
41
47
  `),process.stderr.write(` Resolved: "${K}"
42
- `);this.lastReadPath=K,this._state={path:K,lastUpdate:V,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=p8(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 n5={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class B4{registry;hub;targetFile;watcher;followedRepoId=null;followedPath=null;disposed=!1;queue=Promise.resolve();constructor($,Z,K){this.registry=$,this.hub=Z,this.targetFile=K,this.watcher=new O4(K)}get state(){return{targetFile:this.targetFile,enabled:!0,followedRepoId:this.followedRepoId,followedPath:this.followedPath}}start(){if(this.watcher.on("path-change",($)=>this.enqueue($)),this.watcher.start(),this.watcher.state.path)this.enqueue(this.watcher.state)}enqueue($){this.queue=this.queue.then(()=>this.follow($)).catch(()=>{})}async follow($){if(this.disposed||!$.path)return;let Z;try{Z=await this.registry.openRepo($.path)}catch{return}if(this.disposed){this.registry.closeRepo(Z.handle.id);return}if(Z.created)Z.handle.manager.workingTree.refresh().catch(()=>{});if(Z.handle.id===this.followedRepoId)this.registry.closeRepo(Z.handle.id);else{let K=this.followedRepoId;if(this.followedRepoId=Z.handle.id,this.followedPath=Z.handle.path,K)this.registry.closeRepo(K)}this.hub.broadcast("follow-change",{repoId:Z.handle.id,path:$.path,rawContent:$.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}import*as i5 from"node:fs";var f8="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",d8=21600000,l8=300000,o8=5000;function a8(){try{let $=i5.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),Z=JSON.parse($);return typeof Z.version==="string"?Z.version:null}catch{return null}}async function n8(){let $=await fetch(f8,{headers:{accept:"application/json"},signal:AbortSignal.timeout(o8)});if(!$.ok)return null;let Z=await $.json();return typeof Z.latest==="string"?Z.latest:null}function s5($){let Z=/^(\d+)\.(\d+)\.(\d+)/.exec($.trim());if(!Z)return null;return[Number(Z[1]),Number(Z[2]),Number(Z[3])]}function s8($,Z){if($===null||Z===null)return"unknown";let K=s5($),V=s5(Z);if(!K||!V)return"unknown";for(let X=0;X<K.length;X++){if(K[X]<V[X])return"outdated";if(K[X]>V[X])return"ahead"}return"current"}function r5($=n8,Z=a8()){let K=null,V=null;function X(){if(K&&Date.now()<K.expiresAt)return Promise.resolve(K.value);if(V)return V;return V=$().catch(()=>null).then((Y)=>{let Q=Y===null?l8:d8;return K={value:Y,expiresAt:Date.now()+Q},V=null,Y}),V}return{async state(){let Y=await X();return{current:Z,latest:Y,status:s8(Z,Y)}}}}import*as t5 from"node:os";function e5($){$.get("/health",({res:Z})=>{L(Z,200,{ok:!0,ready:!0,home:t5.homedir()})})}function $7($,Z){$.get("/version",async({res:K})=>{L(K,200,await Z.version.state())})}import*as b$ from"node:fs";import*as _ from"node:path";function C($,Z){let K=$.getRepo(Z);if(!K)throw new H(404,`Unknown repo id: ${Z}`);return K}function c($,Z,K){if(typeof $!=="object"||$===null)throw new H(400,`Expected a JSON body with "${Z}"`);let V=$[Z];if(typeof V!=="string"||!K?.allowEmpty&&V.length===0)throw new H(400,`Missing "${Z}" (string) in body`);return V}function t($,Z){let K=c($,Z);if(K.startsWith("-"))throw new H(400,`Invalid "${Z}" (must not start with "-"): ${K}`);return K}function K7($,Z){if(typeof $!=="object"||$===null)return;let K=$[Z];if(K===void 0)return;if(typeof K!=="string"||K.length===0)throw new H(400,`Invalid "${Z}" (expected a non-empty string)`);return K}function M4($,Z,K){if(typeof $!=="object"||$===null)return K.fallback;let V=$[Z];if(V===void 0)return K.fallback;if(typeof V!=="number"||!Number.isInteger(V)||V<K.min)throw new H(400,`Invalid "${Z}" (expected an integer >= ${K.min})`);return V}function V7($,Z){if(typeof $!=="object"||$===null)return!1;let K=$[Z];if(K===void 0)return!1;if(typeof K!=="boolean")throw new H(400,`Invalid "${Z}" (expected a boolean)`);return K}function e($,Z,K){let V=$.get(Z);if(V===null)return K;if(V==="true")return!0;if(V==="false")return!1;throw new H(400,`Invalid "${Z}" (expected true or false): ${V}`)}function Y7($,Z,K,V){let X=$.get(Z);if(X===null)return K;let Y=Number(X);if(!Number.isInteger(Y)||Y<1)throw new H(400,`Invalid "${Z}" (expected a positive integer): ${X}`);if(V!==void 0&&Y>V)throw new H(400,`Invalid "${Z}" (must be <= ${V}): ${X}`);return Y}async function h($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new H(500,"Repository status unavailable");return Z}function Z7($,Z,K){let V=$.files.filter((X)=>X.path===Z);if(V.length===0)return null;return V.find((X)=>X.staged===K)??V[0]}async function _$($,Z,K){let V=await h($),X=Z7(V,Z,K);if(!X)await $.refresh(),V=await h($),X=Z7(V,Z,K);if(!X)throw new H(404,`File not in status: ${Z}`);return X}function j4($,Z){let K=_.resolve($),V=_.resolve(K,Z);if(V!==K&&!V.startsWith(K+_.sep))throw new H(400,`Path escapes repository root: ${Z}`)}async function X7($){try{return await b$.promises.realpath($)}catch{return null}}async function N4($,Z){let K=await b$.promises.realpath(_.resolve($)),V=await X7(_.join($,Z));if(V===null)return;if(V!==K&&!V.startsWith(K+_.sep))throw new H(400,`Path escapes repository root: ${Z}`)}async function Q7($,Z){let K=await b$.promises.realpath(_.resolve($)),V=[];for(let X of Z){let Y=await X7(_.join($,X.path));if(Y===null||Y===K||Y.startsWith(K+_.sep))V.push(X)}return V}function H4($){return $?.code??null}function i8($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function f($,Z,K){$.clearError(),await K();let V=$.state.error;if(V){L(Z,i8(V),{error:V});return}await $.refresh(),L(Z,200,{state:l($.state)})}function r8($){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test($)?409:500}async function b($,Z,K){let V=$.manager.remote,X=()=>new H(409,`A ${V.remoteState.operation??"remote"} operation is already in progress`);if(V.remoteState.inProgress)throw X();let Y=await K();if(Y===null)throw X();if(Y.error){L(Z,r8(Y.error),{error:Y.error});return}let Q=$.manager.workingTree;await Q.refresh(),L(Z,200,{state:l(Q.state),result:Y.lastResult})}function z7($,Z){let{registry:K}=Z;$.get("/repos",({res:V})=>{let X=K.listRepos().map((Y)=>({id:Y.id,path:Y.path,branch:Y.manager.workingTree.state.status?.branch.current??null}));L(V,200,X)}),$.post("/repos",async({body:V,res:X})=>{let Y=c(V,"path"),Q;try{Q=await K.openRepo(Y)}catch(z){throw new H(400,z instanceof Error?z.message:String(z))}if(Q.created)Q.handle.manager.workingTree.refresh().catch(()=>{});L(X,Q.created?201:200,{id:Q.handle.id,path:Q.handle.path})}),$.get("/repos/:id/worktrees",async({params:V,res:X})=>{let Y=C(K,V.id);L(X,200,await J$(Y.path))}),$.get("/worktrees",async({query:V,res:X})=>{let Y=V.get("path");if(!Y)throw new H(400,'Missing "path" query parameter');L(X,200,await J$(Y))}),$.delete("/repos/:id",({params:V,res:X})=>{C(K,V.id),K.closeRepo(V.id),L(X,200,{})})}function W7($,Z,K){if(!$.trim())return{valid:!1,error:"Commit message cannot be empty"};if(Z===0&&!K)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function J7($){return $.trim()}async function t8($){let Z=(V)=>V.filter((X)=>X.staged).length,K=Z((await h($)).files);if(K===0)await $.refresh(),K=Z((await h($)).files);return K}function U7($,Z){let{registry:K,sse:V}=Z;if($.get("/repos/:id/status",async({params:X,res:Y})=>{let Q=C(K,X.id);await h(Q.manager.workingTree);let z=l(Q.manager.workingTree.state);z.operationInProgress=await g(Q.path),L(Y,200,z)}),$.get("/repos/:id/diff",async({params:X,query:Y,res:Q})=>{let z=C(K,X.id),W=Y.get("path")??void 0,J=e(Y,"staged",!1),U;if(W){let B=(await h(z.manager.workingTree)).files.some((G)=>G.path===W&&G.status==="untracked");if(B&&J)throw new H(400,`staged=true is meaningless for untracked file: ${W} (untracked files have no staged diff)`);U=B?await D$(z.path,W):await Q$(z.path,W,J)}else U=await Q$(z.path,void 0,J);z.manager.workingTree.stampDiff(U),L(Q,200,U)}),$.post("/repos/:id/stage",async({params:X,body:Y,res:Q})=>{let z=C(K,X.id),W=c(Y,"path"),J=z.manager.workingTree,U=await _$(J,W,!1);await f(J,Q,()=>J.stage(U))}),$.post("/repos/:id/unstage",async({params:X,body:Y,res:Q})=>{let z=C(K,X.id),W=c(Y,"path"),J=z.manager.workingTree,U=await _$(J,W,!0);await f(J,Q,()=>J.unstage(U))}),$.get("/repos/:id/events",({params:X,req:Y,res:Q})=>{let z=C(K,X.id);V.subscribe(X.id,z.manager,Y,Q)}),Z.apiMode==="full")e8($,Z)}function e8($,Z){let{registry:K}=Z;$.post("/repos/:id/stage-all",async({params:V,res:X})=>{let Q=C(K,V.id).manager.workingTree;await f(Q,X,()=>Q.stageAll())}),$.post("/repos/:id/unstage-all",async({params:V,res:X})=>{let Q=C(K,V.id).manager.workingTree;await f(Q,X,()=>Q.unstageAll())}),$.post("/repos/:id/discard",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=c(X,"path"),W=Q.manager.workingTree,J=await _$(W,z,!1);if(J.staged)throw new H(409,`Cannot discard a staged file: ${z} (unstage it first)`);await f(W,Y,()=>W.discard(J))}),$.post("/repos/:id/commit",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=c(X,"message",{allowEmpty:!0}),W=V7(X,"amend"),J=Q.manager.workingTree,U=await t8(J),O=W7(z,U,W);if(!O.valid)throw new H(400,O.error??"Invalid commit");await f(J,Y,()=>J.commit(J7(z),W))}),$.post("/repos/:id/stage-hunk",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=c(X,"patch"),W=Q.manager.workingTree;await f(W,Y,()=>W.stageHunk(z))}),$.post("/repos/:id/unstage-hunk",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=c(X,"patch"),W=Q.manager.workingTree;await f(W,Y,()=>W.unstageHunk(z))})}async function $9($){let Z=await r$($);if(Z&&await a($,Z))return Z;if(V$($)){let K=await W$($);if(K&&await a($,K))return K}throw new H(422,"No usable base branch")}function G7($,Z){let{registry:K}=Z;if($.get("/repos/:id/history",async({params:V,query:X,res:Y})=>{let Q=C(K,V.id),z=Y7(X,"count",100,5000);L(Y,200,await t4(Q.path,z))}),$.get("/repos/:id/commits/:hash/diff",async({params:V,res:X})=>{let Y=C(K,V.id),Q=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(Q))throw new H(400,`Invalid commit hash: ${Q}`);if(!await a(Y.path,Q))throw new H(404,`Unknown commit: ${Q}`);L(X,200,await H5(Y.path,Q))}),$.get("/repos/:id/head-message",async({params:V,res:X})=>{let Y=C(K,V.id);L(X,200,{message:await o4(Y.path)})}),$.get("/repos/:id/branches",async({params:V,res:X})=>{let Y=C(K,V.id);L(X,200,await A$(Y.path))}),$.get("/repos/:id/base-branches",async({params:V,res:X})=>{let Y=C(K,V.id);L(X,200,await i$(Y.path))}),$.get("/repos/:id/compare/base",async({params:V,res:X})=>{let Y=C(K,V.id);L(X,200,{base:await r$(Y.path)})}),Z.apiMode==="full")$.put("/repos/:id/compare/base",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=t(X,"branch");if(!await a(Q.path,z))throw new H(400,`Not a valid base ref: ${z}`);U5(Q.path,z),L(Y,200,{base:z})});$.get("/repos/:id/compare",async({params:V,query:X,res:Y})=>{let Q=C(K,V.id),z=e(X,"uncommitted",!1),W=X.get("base"),J;if(W!==null){if(!await a(Q.path,W))throw new H(400,`Unknown base ref: ${W}`);J=W}else J=await $9(Q.path);let U;try{U=z?await A5(Q.path,J):await t$(Q.path,J)}catch(O){if(O instanceof T$)throw new H(422,O.message);throw O}L(Y,200,U)})}function Z9($){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 O7($,Z){let{registry:K}=Z;$.get("/repos/:id/journal",({params:V,query:X,res:Y})=>{let Q=C(K,V.id),z=Z9(X);L(Y,200,q4(Q.manager.journal.journalStore,z))})}function B7($,Z){let{registry:K}=Z;$.post("/repos/:id/push",async({params:V,res:X})=>{let Y=C(K,V.id);await b(Y,X,()=>Y.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:V,res:X})=>{let Y=C(K,V.id);await b(Y,X,()=>Y.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:V,res:X})=>{let Y=C(K,V.id);await b(Y,X,()=>Y.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=K7(X,"message");await b(Q,Y,()=>Q.manager.remote.stash(z))}),$.post("/repos/:id/stash-pop",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=M4(X,"index",{min:0,fallback:0});await b(Q,Y,()=>Q.manager.remote.stashPop(z))}),$.post("/repos/:id/switch-branch",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=t(X,"name");await b(Q,Y,()=>Q.manager.remote.switchBranch(z))}),$.post("/repos/:id/create-branch",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=t(X,"name");await b(Q,Y,()=>Q.manager.remote.createBranch(z))}),$.post("/repos/:id/soft-reset",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=M4(X,"count",{min:1,fallback:1});if(!await a(Q.path,`HEAD~${z}`))throw new H(400,`Cannot soft-reset ${z} commit(s): HEAD~${z} does not exist`);await b(Q,Y,()=>Q.manager.remote.softReset(z))}),$.post("/repos/:id/cherry-pick",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=t(X,"hash");await b(Q,Y,()=>Q.manager.remote.cherryPick(z))}),$.post("/repos/:id/revert",async({params:V,body:X,res:Y})=>{let Q=C(K,V.id),z=t(X,"hash");await b(Q,Y,()=>Q.manager.remote.revertCommit(z))}),$.post("/repos/:id/abort",async({params:V,res:X})=>{let Y=C(K,V.id);if(!await g(Y.path))throw new H(409,"No operation in progress to abort");await b(Y,X,()=>Y.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:V,res:X})=>{let Y=C(K,V.id);if(await g(Y.path)!=="rebase")throw new H(409,"No rebase in progress to continue");await b(Y,X,()=>Y.manager.remote.rebaseContinue())})}import*as x$ from"node:fs";import*as O$ from"node:path";function A4($){let Z={files:new Map,directories:new Set};for(let K of $){Z.files.set(K.path,{status:K.status,staged:K.staged});let V=K.path.split("/"),X="";for(let Y=0;Y<V.length-1;Y++)X=X?`${X}/${V[Y]}`:V[Y],Z.directories.add(X);Z.directories.add("")}return Z}var K9=1048576,M7=5000;class m$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function j7($,Z,K,V){let X=K?.hideHidden??!0,Y=K?.hideGitignored??!0,Q=O$.join($,Z),z=await x$.promises.readdir(Q,{withFileTypes:!0}),W=z.map((O)=>Z?O$.join(Z,O.name):O.name),J=Y?await N$($,W):new Set,U=[];for(let O of z){if(X&&O.name.startsWith("."))continue;let B=Z?O$.join(Z,O.name):O.name;if(Y&&J.has(B))continue;let G=O.isDirectory(),j={name:O.name,path:B,type:G?"dir":"file"};if(V)if(G){if(V.directories.has(B))j.hasChanges=!0}else{let T=V.files.get(B);if(T)j.gitStatus=T.status,j.staged=T.staged}U.push(j)}return U.sort((O,B)=>{if(O.type==="dir"&&B.type!=="dir")return-1;if(O.type!=="dir"&&B.type==="dir")return 1;return O.name.localeCompare(B.name)}),U}function V9($){let Z=Math.min($.length,8192);for(let K=0;K<Z;K++)if($[K]===0)return!0;return!1}async function N7($,Z){let K=O$.join($,Z),V=await x$.promises.stat(K);if(!V.isFile())throw new m$(Z);if(V.size>K9)return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:V.size,totalLines:0};let X=await x$.promises.readFile(K);if(V9(X))return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:V.size,totalLines:0};let Y=X.toString("utf-8"),Q=Y.split(`
43
- `),z=!1;if(Q.length>M7)Y=Q.slice(0,M7).join(`
44
- `),z=!0;return{content:Y,binary:!1,truncated:z,tooLarge:!1,size:V.size,totalLines:Q.length}}function H7($,Z){let{registry:K}=Z;$.get("/repos/:id/tree",async({params:V,query:X,res:Y})=>{let Q=C(K,V.id),z=X.get("dir")??"",W=e(X,"hidden",!1),J=e(X,"ignored",!1);j4(Q.path,z),await N4(Q.path,z);let U=await h(Q.manager.workingTree),O=A4(U.files),B;try{B=await j7(Q.path,z,{hideHidden:!W,hideGitignored:!J},O)}catch(G){let j=H4(G);if(j==="ENOENT")throw new H(404,`No such directory: ${z||"/"}`);if(j==="ENOTDIR")throw new H(400,`Not a directory: ${z}`);throw G}L(Y,200,await Q7(Q.path,B))}),$.get("/repos/:id/file",async({params:V,query:X,res:Y})=>{let Q=C(K,V.id),z=X.get("path");if(!z)throw new H(400,'Missing "path" query parameter');j4(Q.path,z),await N4(Q.path,z);try{L(Y,200,await N7(Q.path,z))}catch(W){if(W instanceof m$)throw new H(400,W.message);let J=H4(W);if(J==="ENOENT"||J==="ENOTDIR")throw new H(404,`No such file: ${z}`);throw W}}),$.get("/repos/:id/files",async({params:V,res:X})=>{let Y=C(K,V.id);L(X,200,await W5(Y.path))})}function A7($,Z){let{registry:K,daemonEvents:V,follow:X}=Z;$.get("/events",({req:Y,res:Q})=>{let z=K.listRepos().map((W)=>({id:W.id,path:W.path}));V.subscribe(Y,Q,z)}),$.get("/follow",({res:Y})=>{L(Y,200,X?X.state:n5)})}function Y9($){if(!$$.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let K=I7.connect($);K.once("connect",()=>{K.destroy(),Z(!0)}),K.once("error",()=>{K.destroy(),Z(!1)})}catch{Z(!1)}})}function T7($={}){let Z=new W4,K=new J4,V=new z4({onOpened:(G)=>K.broadcast("repo-opened",{id:G.id,path:G.path}),onClosed:(G)=>{Z.closeRepo(G),K.broadcast("repo-closed",{id:G})}}),X=$.followFile?new B4(V,K,$.followFile):null,Y=new h$,Q=$.apiMode??"full",z=r5($.updateCheck===!1?()=>Promise.resolve(null):$.fetchLatestVersion),W={registry:V,sse:Z,daemonEvents:K,follow:X,apiMode:Q,version:z};if(e5(Y),$7(Y,W),z7(Y,W),U7(Y,W),G7(Y,W),O7(Y,W),Q==="full")B7(Y,W);H7(Y,W),A7(Y,W),X?.start();let J=$.webRoot?S4($.webRoot):void 0,U=C7.createServer((G,j)=>{for(let[T,q]of Object.entries(P4))j.setHeader(T,q);if(w4(U.address())){let T=v4(G);if(T){L(j,T.status,{error:T.message});return}}Y.handle(G,j,J).catch(()=>j.end())}),O=new Set;U.on("connection",(G)=>{O.add(G),G.on("close",()=>O.delete(G))});let B=null;return{address(){return U.address()},getRepo(G){return V.getRepo(G)},async listen(G){if(G.socketPath){if(await Y9(G.socketPath))throw Error(`diffstalkerd already running at ${G.socketPath}`);$$.rmSync(G.socketPath,{force:!0})}return new Promise((j,T)=>{let q=(R)=>T(R);U.once("error",q);let D=()=>{if(U.removeListener("error",q),B)$$.chmodSync(B,384);j()};if(G.fd!==void 0)U.listen({fd:G.fd},D);else if(G.socketPath)B=G.socketPath,process.umask(63),U.listen(G.socketPath,D);else if(G.port!==void 0)U.listen(G.port,"127.0.0.1",D);else T(Error("listen() requires a socketPath, a port, or an fd"))})},close(){X?.dispose(),Z.destroy(),K.destroy(),V.disposeAll();for(let G of O)G.destroy();return new Promise((G,j)=>{U.close((T)=>{if(B)$$.rmSync(B,{force:!0});if(T)j(T);else G()})})}}}var D7="diffstalkerd.sock",Q9=3,L7=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
48
+ `);this.lastReadPath=K,this._state={path:K,lastUpdate:V,rawContent:Z,sourceFile:this.targetFile}}}catch{}this.watcher=g0(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 h8={targetFile:null,enabled:!1,followedRepoId:null,followedPath:null};class lZ{registry;hub;targetFile;watcher;followedRepoId=null;followedPath=null;disposed=!1;queue=Promise.resolve();constructor($,Z,K){this.registry=$,this.hub=Z,this.targetFile=K,this.watcher=new dZ(K)}get state(){return{targetFile:this.targetFile,enabled:!0,followedRepoId:this.followedRepoId,followedPath:this.followedPath}}start(){if(this.watcher.on("path-change",($)=>this.enqueue($)),this.watcher.start(),this.watcher.state.path)this.enqueue(this.watcher.state)}enqueue($){this.queue=this.queue.then(()=>this.follow($)).catch(()=>{})}async follow($){if(this.disposed||!$.path)return;let Z;try{Z=await this.registry.openRepo($.path)}catch{return}if(this.disposed){this.registry.closeRepo(Z.handle.id);return}if(Z.created)Z.handle.manager.workingTree.refresh().catch(()=>{});if(Z.handle.id===this.followedRepoId)this.registry.closeRepo(Z.handle.id);else{let K=this.followedRepoId;if(this.followedRepoId=Z.handle.id,this.followedPath=Z.handle.path,K)this.registry.closeRepo(K)}this.hub.broadcast("follow-change",{repoId:Z.handle.id,path:$.path,rawContent:$.rawContent})}dispose(){if(this.disposed)return;if(this.disposed=!0,this.watcher.stop(),this.followedRepoId)this.registry.closeRepo(this.followedRepoId),this.followedRepoId=null,this.followedPath=null}}import*as d8 from"node:fs";var u0="https://registry.npmjs.org/-/package/diffstalkerd/dist-tags",p0=21600000,h0=300000,f0=5000;function nZ(){try{let $=d8.readFileSync(new URL("../package.json",import.meta.url),"utf-8"),Z=JSON.parse($);return typeof Z.version==="string"?Z.version:null}catch{return null}}async function d0(){let $=await fetch(u0,{headers:{accept:"application/json"},signal:AbortSignal.timeout(f0)});if(!$.ok)return null;let Z=await $.json();return typeof Z.latest==="string"?Z.latest:null}function f8($){let Z=/^(\d+)\.(\d+)\.(\d+)/.exec($.trim());if(!Z)return null;return[Number(Z[1]),Number(Z[2]),Number(Z[3])]}function l0($,Z){if($===null||Z===null)return"unknown";let K=f8($),V=f8(Z);if(!K||!V)return"unknown";for(let Q=0;Q<K.length;Q++){if(K[Q]<V[Q])return"outdated";if(K[Q]>V[Q])return"ahead"}return"current"}function l8($=d0,Z=nZ()){let K=null,V=null;function Q(){if(K&&Date.now()<K.expiresAt)return Promise.resolve(K.value);if(V)return V;return V=$().catch(()=>null).then((X)=>{let Y=X===null?h0:p0;return K={value:X,expiresAt:Date.now()+Y},V=null,X}),V}return{async state(){let X=await Q();return{current:Z,latest:X,status:l0(Z,X)}}}}import*as n8 from"node:os";function o8($,Z){$.get("/health",({res:K})=>{S(K,200,{ok:!0,ready:!0,home:n8.homedir(),symbols:{extensions:Z.symbols?.extensions??[]}})})}function a8($,Z){$.get("/version",async({res:K})=>{S(K,200,await Z.version.state())})}import*as c$ from"node:fs";import*as _ from"node:path";function q($,Z){let K=$.getRepo(Z);if(!K)throw new N(404,`Unknown repo id: ${Z}`);return K}function c($,Z,K){if(typeof $!=="object"||$===null)throw new N(400,`Expected a JSON body with "${Z}"`);let V=$[Z];if(typeof V!=="string"||!K?.allowEmpty&&V.length===0)throw new N(400,`Missing "${Z}" (string) in body`);return V}function X$($,Z){let K=c($,Z);if(K.startsWith("-"))throw new N(400,`Invalid "${Z}" (must not start with "-"): ${K}`);return K}function s8($,Z){if(typeof $!=="object"||$===null)return;let K=$[Z];if(K===void 0)return;if(typeof K!=="string"||K.length===0)throw new N(400,`Invalid "${Z}" (expected a non-empty string)`);return K}function iZ($,Z,K){if(typeof $!=="object"||$===null)return K.fallback;let V=$[Z];if(V===void 0)return K.fallback;if(typeof V!=="number"||!Number.isInteger(V)||V<K.min)throw new N(400,`Invalid "${Z}" (expected an integer >= ${K.min})`);return V}function r8($,Z){if(typeof $!=="object"||$===null)return!1;let K=$[Z];if(K===void 0)return!1;if(typeof K!=="boolean")throw new N(400,`Invalid "${Z}" (expected a boolean)`);return K}function e($,Z,K){let V=$.get(Z);if(V===null)return K;if(V==="true")return!0;if(V==="false")return!1;throw new N(400,`Invalid "${Z}" (expected true or false): ${V}`)}function t8($,Z,K,V){let Q=$.get(Z);if(Q===null)return K;let X=Number(Q);if(!Number.isInteger(X)||X<1)throw new N(400,`Invalid "${Z}" (expected a positive integer): ${Q}`);if(V!==void 0&&X>V)throw new N(400,`Invalid "${Z}" (must be <= ${V}): ${Q}`);return X}async function a($){if(!$.state.status)await $.refresh();let Z=$.state.status;if(!Z)throw new N(500,"Repository status unavailable");return Z}function i8($,Z,K){let V=$.files.filter((Q)=>Q.path===Z);if(V.length===0)return null;return V.find((Q)=>Q.staged===K)??V[0]}async function I$($,Z,K){let V=await a($),Q=i8(V,Z,K);if(!Q)await $.refresh(),V=await a($),Q=i8(V,Z,K);if(!Q)throw new N(404,`File not in status: ${Z}`);return Q}function aZ($,Z){return $===Z||$.startsWith(Z+_.sep)}function sZ($){return $.replace(/[. ]+$/,"").toLowerCase()===".git"}function Y$($,Z){if(Z.length===0)throw new N(400,"Empty path");if(Z.includes("\x00"))throw new N(400,"Path contains a NUL byte");let K=_.resolve($),V=_.relative(K,_.resolve(K,Z));if(V==="")throw new N(400,`Path resolves to the repository root: ${Z}`);if(_.isAbsolute(V)||V===".."||V.startsWith(`..${_.sep}`))throw new N(400,`Path escapes repository root: ${Z}`);if(V.startsWith("-"))throw new N(400,`Path must not start with "-": ${Z}`);if(V.startsWith(":"))throw new N(400,`Path must not start with ":": ${Z}`);if(V.split(_.sep).some(sZ))throw new N(400,`Path addresses the git directory: ${Z}`);return V}async function e8($){try{return await c$.promises.realpath($)}catch{return null}}var oZ=new WeakMap;async function n0($){let Z=oZ.get($);if(!Z)Z=(async()=>{let K=await F($.path).raw(["rev-parse","--absolute-git-dir"]);return await c$.promises.realpath(K.trim())})(),oZ.set($,Z),Z.catch(()=>oZ.delete($));try{return await Z}catch{throw new N(500,"Cannot resolve the git directory for this repository")}}async function W$($,Z){let K=await c$.promises.realpath(_.resolve($.path)),V=await e8(_.join($.path,Z));if(V===null)return;if(!aZ(V,K))throw new N(400,`Path escapes repository root: ${Z}`);if(aZ(V,await n0($)))throw new N(400,`Path addresses the git directory: ${Z}`)}async function $4($,Z){let K=await c$.promises.realpath(_.resolve($)),V=[];for(let Q of Z){let X=await e8(_.join($,Q.path));if(X===null||aZ(X,K))V.push(Q)}return V}function rZ($){return $?.code??null}function o0($){return/index\.lock|did not match|conflict|apply|nothing to commit/i.test($)?409:500}async function i($,Z,K){$.clearError(),await K();let V=$.state.error;if(V){S(Z,o0(V),{error:V});return}await $.refresh(),S(Z,200,{state:s($.state)})}function a0($){return/conflict|rejected|non-fast-forward|would be overwritten|merge|unmerged/i.test($)?409:500}async function m($,Z,K){let V=$.manager.remote,Q=()=>new N(409,`A ${V.remoteState.operation??"remote"} operation is already in progress`);if(V.remoteState.inProgress)throw Q();let X=await K();if(X===null)throw Q();if(X.error){S(Z,a0(X.error),{error:X.error});return}let Y=$.manager.workingTree;await Y.refresh(),S(Z,200,{state:s(Y.state),result:X.lastResult})}function Z4($,Z){let{registry:K}=Z;$.get("/repos",({res:V})=>{let Q=K.listRepos().map((X)=>({id:X.id,path:X.path,branch:X.manager.workingTree.state.status?.branch.current??null}));S(V,200,Q)}),$.post("/repos",async({body:V,res:Q})=>{let X=c(V,"path"),Y;try{Y=await zZ(K,X)}catch(W){throw new N(400,W instanceof Error?W.message:String(W))}S(Q,Y.created?201:200,{id:Y.handle.id,path:Y.handle.path})}),$.get("/repos/:id/worktrees",async({params:V,res:Q})=>{let X=q(K,V.id);S(Q,200,await y$(X.path))}),$.get("/worktrees",async({query:V,res:Q})=>{let X=V.get("path");if(!X)throw new N(400,'Missing "path" query parameter');S(Q,200,await y$(X))}),$.delete("/repos/:id",({params:V,res:Q})=>{q(K,V.id),K.closeRepo(V.id),S(Q,200,{})})}function K4($,Z,K){if(!$.trim())return{valid:!1,error:"Commit message cannot be empty"};if(Z===0&&!K)return{valid:!1,error:"No changes staged for commit"};return{valid:!0,error:null}}function V4($){return $.trim()}async function i0($){let Z=(V)=>V.filter((Q)=>Q.staged).length,K=Z((await a($)).files);if(K===0)await $.refresh(),K=Z((await a($)).files);return K}function Q4($,Z){let{registry:K,sse:V}=Z;if($.get("/repos/:id/status",async({params:Q,res:X})=>{let Y=q(K,Q.id);await a(Y.manager.workingTree);let W=s(Y.manager.workingTree.state);W.operationInProgress=await l(Y.path),S(X,200,W)}),$.get("/repos/:id/diff",async({params:Q,query:X,res:Y})=>{let W=q(K,Q.id),J=X.get("path")??void 0,z=e(X,"staged",!1),U;if(J){let O=(await a(W.manager.workingTree)).files.some((M)=>M.path===J&&M.status==="untracked");if(O&&z)throw new N(400,`staged=true is meaningless for untracked file: ${J} (untracked files have no staged diff)`);U=O?await ZZ(W.path,J):await B$(W.path,J,z)}else U=await B$(W.path,void 0,z);W.manager.workingTree.stampDiff(U),S(Y,200,U)}),$.post("/repos/:id/stage",async({params:Q,body:X,res:Y})=>{let W=q(K,Q.id),J=c(X,"path"),z=W.manager.workingTree,U=await I$(z,J,!1);await i(z,Y,()=>z.stage(U))}),$.post("/repos/:id/unstage",async({params:Q,body:X,res:Y})=>{let W=q(K,Q.id),J=c(X,"path"),z=W.manager.workingTree,U=await I$(z,J,!0);await i(z,Y,()=>z.unstage(U))}),$.get("/repos/:id/events",({params:Q,req:X,res:Y})=>{let W=q(K,Q.id);V.subscribe(Q.id,W.manager,X,Y)}),Z.apiMode==="full")s0($,Z)}function s0($,Z){let{registry:K}=Z;$.post("/repos/:id/stage-all",async({params:V,res:Q})=>{let Y=q(K,V.id).manager.workingTree;await i(Y,Q,()=>Y.stageAll())}),$.post("/repos/:id/unstage-all",async({params:V,res:Q})=>{let Y=q(K,V.id).manager.workingTree;await i(Y,Q,()=>Y.unstageAll())}),$.post("/repos/:id/discard",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=c(Q,"path"),J=Y.manager.workingTree,z=await I$(J,W,!1);if(z.staged)throw new N(409,`Cannot discard a staged file: ${W} (unstage it first)`);await i(J,X,()=>J.discard(z))}),$.post("/repos/:id/commit",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=c(Q,"message",{allowEmpty:!0}),J=r8(Q,"amend"),z=Y.manager.workingTree,U=await i0(z),j=K4(W,U,J);if(!j.valid)throw new N(400,j.error??"Invalid commit");await i(z,X,()=>z.commit(V4(W),J))}),$.post("/repos/:id/stage-hunk",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=c(Q,"patch"),J=Y.manager.workingTree;await i(J,X,()=>J.stageHunk(W))}),$.post("/repos/:id/unstage-hunk",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=c(Q,"patch"),J=Y.manager.workingTree;await i(J,X,()=>J.unstageHunk(W))})}async function r0($){let Z=await kZ($);if(Z&&await t($,Z))return Z;if(H$($)){let K=await b$($);if(K&&await t($,K))return K}throw new N(422,"No usable base branch")}async function X4($,Z){let K=Z.get("base");if(K===null)return r0($);if(!await t($,K))throw new N(400,`Unknown base ref: ${K}`);return K}function Y4($,Z){let{registry:K}=Z;if($.get("/repos/:id/history",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=t8(Q,"count",100,5000);S(X,200,await i6(Y.path,W))}),$.get("/repos/:id/commits/:hash",async({params:V,res:Q})=>{let X=q(K,V.id),Y=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(Y))throw new N(400,`Invalid commit hash: ${Y}`);let W=await s6(X.path,Y);if(W===null)throw new N(404,`Unknown commit: ${Y}`);S(Q,200,W)}),$.get("/repos/:id/commits/:hash/diff",async({params:V,res:Q})=>{let X=q(K,V.id),Y=V.hash;if(!/^[0-9a-f]{4,40}$/i.test(Y))throw new N(400,`Invalid commit hash: ${Y}`);if(!await t(X.path,Y))throw new N(404,`Unknown commit: ${Y}`);S(Q,200,await O8(X.path,Y))}),$.get("/repos/:id/head-message",async({params:V,res:Q})=>{let X=q(K,V.id);S(Q,200,{message:await f6(X.path)})}),$.get("/repos/:id/branches",async({params:V,res:Q})=>{let X=q(K,V.id);S(Q,200,await e$(X.path))}),$.get("/repos/:id/base-branches",async({params:V,res:Q})=>{let X=q(K,V.id);S(Q,200,await EZ(X.path))}),$.get("/repos/:id/compare/base",async({params:V,res:Q})=>{let X=q(K,V.id);S(Q,200,{base:await kZ(X.path)})}),Z.apiMode==="full")$.put("/repos/:id/compare/base",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=X$(Q,"branch");if(!await t(Y.path,W))throw new N(400,`Not a valid base ref: ${W}`);J8(Y.path,W),S(X,200,{base:W})});$.get("/repos/:id/compare/count",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=await X4(Y.path,Q);try{S(X,200,{baseBranch:W,commits:await j8(Y.path,W)})}catch(J){if(J instanceof C$)throw new N(422,J.message);throw J}}),$.get("/repos/:id/compare",async({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=e(Q,"uncommitted",!1),J=await X4(Y.path,Q),z;try{z=W?await G8(Y.path,J):await _Z(Y.path,J)}catch(U){if(U instanceof C$)throw new N(422,U.message);throw U}S(X,200,z)})}function t0($){let Z=$.get("since");if(Z===null)return 0;if(!/^\d+$/.test(Z))throw new N(400,`Invalid "since" (expected a non-negative integer): ${Z}`);return Number(Z)}function W4($,Z){let{registry:K}=Z;$.get("/repos/:id/journal",({params:V,query:Q,res:X})=>{let Y=q(K,V.id),W=t0(Q);S(X,200,G6(Y.manager.journal.journalStore,W))})}function J4($,Z){let{registry:K}=Z;$.post("/repos/:id/push",async({params:V,res:Q})=>{let X=q(K,V.id);await m(X,Q,()=>X.manager.remote.push())}),$.post("/repos/:id/fetch",async({params:V,res:Q})=>{let X=q(K,V.id);await m(X,Q,()=>X.manager.remote.fetchRemote())}),$.post("/repos/:id/pull",async({params:V,res:Q})=>{let X=q(K,V.id);await m(X,Q,()=>X.manager.remote.pullRebase())}),$.post("/repos/:id/stash",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=s8(Q,"message");await m(Y,X,()=>Y.manager.remote.stash(W))}),$.post("/repos/:id/stash-pop",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=iZ(Q,"index",{min:0,fallback:0});await m(Y,X,()=>Y.manager.remote.stashPop(W))}),$.post("/repos/:id/switch-branch",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=X$(Q,"name");await m(Y,X,()=>Y.manager.remote.switchBranch(W))}),$.post("/repos/:id/create-branch",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=X$(Q,"name");await m(Y,X,()=>Y.manager.remote.createBranch(W))}),$.post("/repos/:id/soft-reset",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=iZ(Q,"count",{min:1,fallback:1});if(!await t(Y.path,`HEAD~${W}`))throw new N(400,`Cannot soft-reset ${W} commit(s): HEAD~${W} does not exist`);await m(Y,X,()=>Y.manager.remote.softReset(W))}),$.post("/repos/:id/cherry-pick",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=X$(Q,"hash");await m(Y,X,()=>Y.manager.remote.cherryPick(W))}),$.post("/repos/:id/revert",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=X$(Q,"hash");await m(Y,X,()=>Y.manager.remote.revertCommit(W))}),$.post("/repos/:id/abort",async({params:V,res:Q})=>{let X=q(K,V.id);if(!await l(X.path))throw new N(409,"No operation in progress to abort");await m(X,Q,()=>X.manager.remote.abortOperation())}),$.post("/repos/:id/rebase-continue",async({params:V,res:Q})=>{let X=q(K,V.id);if(await l(X.path)!=="rebase")throw new N(409,"No rebase in progress to continue");await m(X,Q,()=>X.manager.remote.rebaseContinue())})}import*as J$ from"node:fs";import*as u$ from"node:path";var T$=8388608;var z4=65536;function A$($){return Array.from($,(Z)=>Z.charCodeAt(0))}function L$($,Z,K){if(Z+K.length>$.length)return!1;for(let V=0;V<K.length;V++)if($[Z+V]!==K[V])return!1;return!0}function jZ($,Z){return $[Z]*16777216+($[Z+1]<<16)+($[Z+2]<<8)+$[Z+3]}function tZ($,Z){return($[Z]<<8)+$[Z+1]}function OZ($,Z){return $[Z]+($[Z+1]<<8)}function U4($,Z){return String.fromCharCode($[Z],$[Z+1],$[Z+2],$[Z+3])}function w($){return{ok:!1,refusal:$}}function D$($){return w($?"malformed":"header-not-found")}function eZ($,Z){if($<1||Z<1)return"malformed";if($>8192||Z>8192)return"too-many-pixels";if($*Z>16777216)return"too-many-pixels";return null}var e0=[137,80,78,71,13,10,26,10],$1=[255,216,255],Z1=A$("GIF87a"),K1=A$("GIF89a"),d=A$("ftyp");function h($){return{offset:8,bytes:A$($)}}var V1=[{label:"webp",offset:0,bytes:A$("RIFF"),brand:h("WEBP")},{label:"avif",offset:4,bytes:d,brand:h("avif")},{label:"avis",offset:4,bytes:d,brand:h("avis")},{label:"heic",offset:4,bytes:d,brand:h("heic")},{label:"heix",offset:4,bytes:d,brand:h("heix")},{label:"heim",offset:4,bytes:d,brand:h("heim")},{label:"heis",offset:4,bytes:d,brand:h("heis")},{label:"hevc",offset:4,bytes:d,brand:h("hevc")},{label:"hevx",offset:4,bytes:d,brand:h("hevx")},{label:"mif1",offset:4,bytes:d,brand:h("mif1")},{label:"msf1",offset:4,bytes:d,brand:h("msf1")},{label:"tiff-le",offset:0,bytes:[73,73,42,0]},{label:"tiff-be",offset:0,bytes:[77,77,0,42]},{label:"bmp",offset:0,bytes:A$("BM")},{label:"ico",offset:0,bytes:[0,0,1,0]},{label:"cur",offset:0,bytes:[0,0,2,0]},{label:"jxl-codestream",offset:0,bytes:[255,10]},{label:"jxl-container",offset:0,bytes:[0,0,0,12,74,88,76,32,13,10,135,10]}];function Q1($){return V1.some((Z)=>L$($,Z.offset,Z.bytes)&&(Z.brand===void 0||L$($,Z.brand.offset,Z.brand.bytes)))}var X1={0:[1,2,4,8,16],2:[8,16],3:[1,2,4,8],4:[8,16],6:[8,16]},Y1=26;function W1($,Z,K){if($.length<Y1)return D$(K);if(jZ($,8)!==13)return w("malformed");if(U4($,12)!=="IHDR")return w("malformed");let V=jZ($,16),Q=jZ($,20),X=eZ(V,Q);if(X)return w(X);let Y=X1[$[25]];if(!Y||!Y.includes($[24]))return w("malformed");let W=J1($,K);if(W)return W;return{ok:!0,info:{format:"png",mime:"image/png",width:V,height:Q,bytes:Z}}}function J1($,Z){let K=8;for(let V=0;V<256;V++){if(K+8>$.length)return D$(Z);let Q=jZ($,K),X=U4($,K+4);if(X==="IDAT")return null;if(X==="acTL")return w("animation");if(X==="iCCP"&&Q>65536)return w("malformed");let Y=K+12+Q;if(Y<=K||!Number.isSafeInteger(Y))return w("malformed");K=Y}return w("malformed")}var z1=218,U1=226,j1=new Set([219,238,192,193,194,196]);function O1($){return $>=224&&$<=239||j1.has($)}function G1($){return $===1||$>=208&&$<=217}function M1($){return $>=192&&$<=207&&$!==196&&$!==200&&$!==204}var H1=new Set([192,193,194]);function N1($,Z,K){if($.length<4)return D$(K);if(!O1($[3]))return w("malformed");return I1($,Z,K)}function C1($,Z,K,V,Q){if(!H1.has(K))return w("malformed");if(Z+9>$.length)return D$(Q);let X=tZ($,Z+5),Y=tZ($,Z+7),W=eZ(Y,X);if(W)return w(W);return{ok:!0,info:{format:"jpeg",mime:"image/jpeg",width:Y,height:X,bytes:V}}}function B1($,Z){if(Z+1>=$.length)return{kind:"ran-out"};if($[Z]!==255)return{kind:"malformed"};let K=$[Z+1];if(K===255)return{kind:"skip",next:Z+1};if(G1(K))return{kind:"skip",next:Z+2};if(K===z1)return{kind:"malformed"};if(Z+4>$.length)return{kind:"ran-out"};let V=tZ($,Z+2);if(V<2)return{kind:"malformed"};if(M1(K))return{kind:"sof",marker:K};return{kind:"segment",marker:K,length:V}}function I1($,Z,K){let V=2,Q=0;for(let X=0;X<1024;X++){let Y=B1($,V);if(Y.kind==="ran-out")return D$(K);if(Y.kind==="malformed")return w("malformed");if(Y.kind==="sof")return C1($,V,Y.marker,Z,K);if(Y.kind==="skip"){V=Y.next;continue}if(Y.marker===U1){if(Q+=Y.length-2,Q>65536)return w("malformed")}V+=2+Y.length}return w("malformed")}var A1=59,L1=44,T1=33;function j4($){return($&128)===0?0:3*(1<<($&7)+1)}function D1($,Z,K){if(Z>2097152)return w("too-large");if(!K)return w("header-not-found");if($.length<13)return D$(K);let V=OZ($,6),Q=OZ($,8),X=eZ(V,Q);if(X)return w(X);let Y={pos:13+j4($[10]),left:8192,pixels:0,overBudget:!1},W=q1($,Y);if(W===null)return w("malformed");if(W<1)return w("malformed");if(W>256)return w("too-many-pixels");if(Y.overBudget)return w("too-many-pixels");if(W*V*Q>33554432)return w("too-many-pixels");let J={format:"gif",mime:"image/gif",width:V,height:Q,bytes:Z};if(W>1)J.frames=W;return{ok:!0,info:J}}function q1($,Z){let K=0;while(Z.left-- >0){if(Z.pos>=$.length)return null;let V=$[Z.pos];if(V===A1)return K;let Q=V===L1;if(!(Q?S1($,Z):F1($,Z,V)))return null;if(Q&&++K>256)return K;if(Z.overBudget)return K}return null}function F1($,Z,K){if(K!==T1)return!1;return Z.pos+=2,O4($,Z)}function S1($,Z){if(Z.pos+10>$.length)return!1;R1(Z,OZ($,Z.pos+5),OZ($,Z.pos+7));let K=$[Z.pos+9];return Z.pos+=10+j4(K)+1,O4($,Z)}function R1($,Z,K){let V=Z*K;if(Z>8192||K>8192||V>16777216){$.overBudget=!0;return}if($.pixels+=V,$.pixels>33554432)$.overBudget=!0}function O4($,Z){while(Z.left-- >0){if(Z.pos>=$.length)return!1;let K=$[Z.pos];if(Z.pos+=1+K,K===0)return Z.pos<=$.length}return!1}function G4($){return L$($,0,Z1)||L$($,0,K1)}function q$($,Z,K){if(Z>8388608)return w("too-large");if(L$($,0,e0))return W1($,Z,K);if(L$($,0,$1))return N1($,Z,K);if(G4($))return D1($,Z,K);if(Q1($))return w("unsupported-format");return w("not-an-image")}function GZ($,Z){return G4($)?Math.min(Z,2097152):65536}function $6($){let Z={files:new Map,directories:new Set};for(let K of $){Z.files.set(K.path,{status:K.status,staged:K.staged});let V=K.path.split("/"),Q="";for(let X=0;X<V.length-1;X++)Q=Q?`${Q}/${V[X]}`:V[X],Z.directories.add(Q);Z.directories.add("")}return Z}var v1=1048576,M4=5000;class p$ extends Error{constructor($){super(`Not a regular file: ${$}`);this.name="NotRegularFileError"}}async function N4($,Z,K,V){let Q=K?.hideHidden??!0,X=K?.hideGitignored??!0,Y=u$.join($,Z),W=await J$.promises.readdir(Y,{withFileTypes:!0}),J=W.map((j)=>Z?u$.join(Z,j.name):j.name),z=X?await i$($,J):new Set,U=[];for(let j of W){if(Q&&j.name.startsWith("."))continue;let O=Z?u$.join(Z,j.name):j.name;if(X&&z.has(O))continue;let M=j.isDirectory(),B={name:j.name,path:O,type:M?"dir":"file"};if(V)if(M){if(V.directories.has(O))B.hasChanges=!0}else{let I=V.files.get(O);if(I)B.gitStatus=I.status,B.staged=I.staged}U.push(B)}return U.sort((j,O)=>{if(j.type==="dir"&&O.type!=="dir")return-1;if(j.type!=="dir"&&O.type==="dir")return 1;return j.name.localeCompare(O.name)}),U}var w1=16,E1=J$.constants.O_RDONLY|(J$.constants.O_NONBLOCK??0);async function Z6($,Z,K){let V=Buffer.alloc(Z),Q=0;while(Q<Z){let{bytesRead:X}=await $.read(V,Q,Z-Q,K+Q);if(X===0)break;Q+=X}return Q===Z?V:V.subarray(0,Q)}async function k1($,Z){let K=await Z6($,Math.min(w1,Z),0),V=q$(K,Z,K.length>=Z);if(!V.ok&&V.refusal==="too-large")return{head:K,result:V};let Q=Math.min(GZ(K,Z),Z),X=Q<=K.length?K.subarray(0,Q):Buffer.concat([K,await Z6($,Q-K.length,K.length)]);return{head:X,result:q$(X,Z,X.length>=Z)}}function _1($,Z){return $.ok?{image:$.info,refusal:null,version:Z}:{image:null,refusal:$.refusal,version:Z}}function H4($,Z){return{content:"",binary:!0,truncated:!1,tooLarge:!1,size:$,totalLines:0,media:Z}}function K6($,Z){return{content:"",binary:!1,truncated:!1,tooLarge:!0,size:$,totalLines:0,media:Z}}function P1($,Z){let K=$.toString("utf-8"),V=K.split(`
49
+ `),Q=!1;if(V.length>M4)K=V.slice(0,M4).join(`
50
+ `),Q=!0;return{content:K,binary:!1,truncated:Q,tooLarge:!1,size:Z,totalLines:V.length}}async function x1($,Z){let K=await $.stat();if(!K.isFile())throw new p$(Z);let V=K.size;if(V>T$)return K6(V);let{head:Q,result:X}=await k1($,V),Y=_1(X,`${V}-${K.mtimeMs}`);if(X.ok)return H4(V,Y);if(V>v1)return K6(V,x$(Q)?Y:void 0);let W=Q.length>=V?Q:Buffer.concat([Q,await Z6($,V-Q.length,Q.length)]);return x$(W)?H4(V,Y):P1(W,V)}async function C4($,Z){let K=u$.join($,Z),V=await J$.promises.stat(K);if(!V.isFile())throw new p$(Z);if(V.size>T$)return K6(V.size);let Q=await J$.promises.open(K,E1);try{return await x1(Q,Z)}finally{await Q.close()}}function B4($,Z){let{registry:K,symbols:V}=Z;async function Q(X,Y,W){if(!W)return X;if(X.binary||X.tooLarge)return X;if(V===null)return{...X,symbols:{status:"unavailable",reason:"error"}};if(!V.pool.supported(Y))return{...X,symbols:{status:"unsupported",reason:"language"}};let J=V.gate.acquire();if(J===null)throw new N(503,"Symbol extraction busy");try{return{...X,symbols:await V.pool.extract(Y,X.content)}}finally{(await J)()}}$.get("/repos/:id/tree",async({params:X,query:Y,res:W})=>{let J=q(K,X.id),z=Y.get("dir")??"",U=e(Y,"hidden",!1),j=e(Y,"ignored",!1),O=z===""?"":Y$(J.path,z);await W$(J,O);let M=await a(J.manager.workingTree),B=$6(M.files),I;try{I=await N4(J.path,O,{hideHidden:!U,hideGitignored:!j},B)}catch(D){let C=rZ(D);if(C==="ENOENT")throw new N(404,`No such directory: ${z||"/"}`);if(C==="ENOTDIR")throw new N(400,`Not a directory: ${z}`);throw D}let T=I.filter((D)=>!sZ(D.name));S(W,200,await $4(J.path,T))}),$.get("/repos/:id/file",async({params:X,query:Y,res:W})=>{let J=q(K,X.id),z=Y.get("path");if(!z)throw new N(400,'Missing "path" query parameter');let U=Y$(J.path,z);await W$(J,U);try{let j=await C4(J.path,U);S(W,200,await Q(j,U,e(Y,"symbols",!1)))}catch(j){if(j instanceof p$)throw new N(400,j.message);let O=rZ(j);if(O==="ENOENT"||O==="ENOTDIR")throw new N(404,`No such file: ${z}`);throw j}}),$.get("/repos/:id/files",async({params:X,res:Y})=>{let W=q(K,X.id);S(Y,200,await Y8(W.path))})}import{execFile as b1}from"node:child_process";import{promisify as y1}from"node:util";var m1=y1(b1),MZ=3,g1=20,I4=500,c1=500,u1=4194304,p1=5000,A4=400,h1=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"];class HZ extends Error{constructor(){super(`Query must be at least ${MZ} characters`);this.name="GrepQueryTooShortError"}}class F$ extends Error{constructor($){super($);this.name="GrepQueryInvalidError"}}var L4={matches:[],capped:!1,incomplete:!1,binarySkipped:0};function f1($){return $===$.toLowerCase()}function V6($){return Buffer.from($).toString("utf8")}function d1($,Z){let K=$.indexOf(0,Z);if(K===-1)return null;let V=$.indexOf(0,K+1);if(V===-1)return null;let Q=$.indexOf(10,V+1);if(Q===-1)Q=$.length;return{pathBytes:$.subarray(Z,K),lineBytes:$.subarray(K+1,V),contentBytes:$.subarray(V+1,Q),next:Q+1}}function T4($,Z=c1){let K=[],V=new Map,Q=0,X=!1,Y=0;while(Y<$.length){let W=d1($,Y);if(W===null)break;if(Y=W.next,W.contentBytes.includes(0)){Q+=1;continue}let J=Number.parseInt(V6(W.lineBytes),10);if(!Number.isSafeInteger(J)||J<1)continue;if(K.length>=Z){X=!0;break}let z=V6(W.pathBytes),U=V.get(z)??0;if(U>=g1){X=!0;continue}V.set(z,U+1);let j=V6(W.contentBytes),O=j.length>A4;K.push({path:z,line:J,text:O?j.slice(0,A4):j,truncated:O})}return{matches:K,capped:X,incomplete:!1,binarySkipped:Q}}function l1($){return[...h1,"grep","--no-textconv","--no-recurse-submodules","--full-name","--no-color","--no-column","-I","-n","-z","-F",...f1($)?["-i"]:[],"-e",$,"--untracked","--","."]}async function D4($,Z){if(Z.length<MZ)throw new HZ;if(Z.length>I4)throw new F$(`Query must be at most ${I4} characters`);if(Z.includes("\x00"))throw new F$("Query cannot contain a NUL byte");if(Z.includes(`
51
+ `))throw new F$("Query cannot span lines — this searches for literal text");try{let{stdout:K}=await m1("git",l1(Z),{cwd:$,env:p(),encoding:"buffer",maxBuffer:u1,timeout:p1,windowsHide:!0});return T4(K)}catch(K){let V=K;if(V.code===1)return L4;if(V.killed===!0||V.code==="ERR_CHILD_PROCESS_STDIO_MAXBUFFER")return{...V.stdout?T4(V.stdout):L4,incomplete:!0};throw K}}function q4($,Z){let{registry:K}=Z;$.post("/repos/:id/search",async({params:V,body:Q,res:X})=>{let Y=q(K,V.id),W=c(Q,"query");try{let J=await D4(Y.path,W);S(X,200,J)}catch(J){if(J instanceof HZ)throw new N(400,`Query must be at least ${MZ} characters`);if(J instanceof F$)throw new N(400,J.message);throw J}})}import{Worker as n1}from"node:worker_threads";var o1=1000,a1=64,i1={status:"unavailable",reason:"deadline"},h$={status:"unavailable",reason:"error"};function s1(){let $=import.meta.url;return $.endsWith(".ts")?new URL("./symbolWorker.ts",$):new URL("./symbolWorker.js",$)}function F4($){let Z=$.timeoutMs??o1,K=new Set($.extensions),V=null,Q=0,X=Promise.resolve(),Y=!1,W=new Map;function J(O,M){W.delete(O),W.set(O,M);while(W.size>a1){let B=W.keys().next().value;if(B===void 0)break;W.delete(B)}}function z(){let O=V;if(V=null,O!==null)O.terminate()}function U(){let O=new n1(s1(),{workerData:{grammarDir:$.grammarDir,queryDir:$.queryDir}});return O.unref(),O}function j(O,M){return new Promise((B)=>{if(V===null)try{V=U()}catch{B(h$);return}let I=V,T=++Q,D=!1,C=(R,x)=>{if(D)return;if(D=!0,clearTimeout(L),I.off("message",A),I.off("error",G),I.off("exit",H),x)z();B(R)},A=(R)=>{if(R.seq!==T)return;C(R.outcome,!1)},G=()=>C(h$,!0),H=()=>C(h$,!0),L=setTimeout(()=>C(i1,!0),Z);L.unref?.(),I.on("message",A),I.on("error",G),I.on("exit",H);let v={seq:T,relPath:O,content:M};try{I.postMessage(v)}catch{C(h$,!0)}})}return{supported(O){let M=O.lastIndexOf(".");if(M<=O.lastIndexOf("/"))return!1;return K.has(O.slice(M).toLowerCase())},async extract(O,M){if(Y)return h$;let B=`${O}\x00${M}`,I=W.get(B);if(I!==void 0)return J(B,I),I;let T=X.then(()=>j(O,M));X=T.catch(()=>{return});let D=await T;return J(B,D),D},async dispose(){Y=!0;let O=V;if(V=null,W.clear(),O!==null)await O.terminate()}}}import{execFile as r1,spawn as t1}from"node:child_process";import*as f$ from"node:fs";import*as R4 from"node:path";import{promisify as e1}from"node:util";var $7=e1(r1);class S$ extends Error{constructor($){super(`Not a regular blob: ${$}`);this.name="NotRegularBlobError"}}class R$ extends Error{size;constructor($,Z){super(`Blob too large: ${$} (${Z} bytes)`);this.name="BlobTooLargeError",this.size=Z}}class z$ extends Error{constructor($){super(`Unsafe blob path: ${$}`);this.name="UnsafeBlobPathError"}}var v4=["-c","core.fsmonitor=","-c","core.pager=cat","-c","core.hooksPath=/dev/null","--literal-pathspecs"],w4=5000,NZ=65536,E4=/^[0-9a-f]{40}([0-9a-f]{24})?$/,Z7=new Set(["100644","100755"]);function K7($){if($==="")throw new z$("empty");if($.includes("\x00"))throw new z$("contains NUL");if($.startsWith("-"))throw new z$('starts with "-"');if($.startsWith(":"))throw new z$('starts with ":"')}async function CZ($,Z,K){let{stdout:V}=await $7("git",[...v4,...Z],{cwd:$,env:p(),encoding:"buffer",maxBuffer:K,timeout:w4,windowsHide:!0});return V}function k4($){let Z=[],K=0;for(let V=0;V<$.length;V++){if($[V]!==0)continue;if(V>K)Z.push($.subarray(K,V));K=V+1}if(K<$.length)Z.push($.subarray(K));return Z}function _4($,Z){let K=Buffer.from(Z,"utf8");for(let V of $){let Q=V.indexOf(9);if(Q<0)continue;if(!V.subarray(Q+1).equals(K))continue;return V.subarray(0,Q).toString("utf8").trim().split(/\s+/)}return null}var V7=1;async function Q7($){let Z;try{Z=(await CZ($,["rev-parse","--verify","--quiet","--end-of-options","HEAD^{commit}"],NZ)).toString("utf8").trim()}catch(K){if(K?.code===V7)return null;throw K}return E4.test(Z)?Z:null}async function X7($,Z){let K=await Q7($);if(K===null)return null;let V=await CZ($,["ls-tree","-z","--full-tree","-l",K,"--",Z],NZ),Q=_4(k4(V),Z);if(Q===null||Q.length!==4)return null;return{mode:Q[0],oid:Q[2],sizeText:Q[3]}}async function Y7($,Z){let K=await CZ($,["ls-files","--stage","-z","--",Z],NZ),V=_4(k4(K),Z);if(V===null||V.length!==3)return null;if(V[2]!=="0")return null;return{mode:V[0],oid:V[1],sizeText:null}}function P4($,Z){let K=Number.parseInt($,10);if(!Number.isSafeInteger(K)||K<0)throw Error(`git reported a malformed size for ${Z}`);return K}async function W7($,Z,K){let V=await CZ($,["cat-file","-s",Z],NZ);return P4(V.toString("utf8").trim(),K)}var S4=Buffer.alloc(0);async function J7($,Z,K){let V=Buffer.alloc(K),Q=0;while(Q<K){let{bytesRead:X}=await $.read(V,Q,K-Q,Z+Q);if(X===0)break;Q+=X}return Q===K?V:V.subarray(0,Q)}function x4($,Z){let K=S4,V=!1;return{async read(Q){let X=Math.max(0,Math.min(Q,$));if(X>K.length&&!V){let Y=await Z(X,K);V=Y.length<X,K=Y}return K.subarray(0,Math.min(X,K.length))},release(){K=S4,V=!1}}}function z7($,Z){let K=null,V=[],Q=0,X=!1,Y=null,W=null,J=!1,z=null,U=()=>X&&Y!==null,j=()=>{if(V.length!==1){let I=Buffer.concat(V,Q);V.length=0,V.push(I)}return V[0]};function O(){if(z===null)return;if(W===null&&U()&&Y?.signal===null&&Y.code!==0)W=Error(`git cat-file blob failed for ${Z} (exit ${Y.code??"null"})`);if(W===null&&Q<z.want&&!U())return;let I=z;if(z=null,clearTimeout(I.timer),K?.stdout?.pause(),W!==null)I.reject(W);else I.resolve(j().subarray(0,Math.min(I.want,Q)))}function M(I){W??=I,O()}function B(){let I=t1("git",[...v4,"cat-file","blob",Z],{cwd:$,env:p(),stdio:["ignore","pipe","ignore"],windowsHide:!0});K=I,I.stdout?.on("data",(T)=>{if(J)return;V.push(T),Q+=T.length,O()}),I.stdout?.on("end",()=>{X=!0,O()}),I.stdout?.on("error",M),I.on("error",M),I.on("close",(T,D)=>{Y={code:T,signal:D},O()})}return{read(I){if(W!==null)return Promise.reject(W);if(J)return Promise.reject(Error(`read after close for ${Z}`));if(I<=Q||U())return Promise.resolve(j().subarray(0,Math.min(I,Q)));if(z!==null)return Promise.reject(Error(`concurrent read of ${Z}`));return new Promise((T,D)=>{let C=setTimeout(()=>{K?.kill("SIGKILL"),M(Error(`git cat-file blob timed out for ${Z}`))},w4);if(z={want:I,resolve:T,reject:D,timer:C},K===null)B();else K.stdout?.resume()})},release(){if(J=!0,z!==null)M(Error(`git cat-file blob closed while reading ${Z}`));V.length=0,Q=0,K?.kill("SIGKILL"),K=null}}}function U7($){let Z=$?.code;return Z==="ENOENT"||Z==="ENOTDIR"}async function j7($,Z,K){let V=R4.join($,Z),Q;try{Q=await f$.promises.open(V,f$.constants.O_RDONLY|(f$.constants.O_NONBLOCK??0))}catch(X){if(U7(X))return null;throw X}try{let X=await Q.stat();if(!X.isFile())throw new S$(Z);if(X.size>K)throw new R$(Z,X.size);let Y=X.size,W=x4(Y,async(J,z)=>{let U=await J7(Q,z.length,J-z.length);return z.length===0?U:Buffer.concat([z,U])});return{oid:null,size:Y,version:`${Y}-${X.mtimeMs}`,read:(J)=>W.read(J),close:()=>{return W.release(),Q.close()}}}catch(X){try{await Q.close()}catch{}throw X}}async function O7($,Z,K,V){let Q=Z==="head"?await X7($,K):await Y7($,K);if(Q===null)return null;if(!Z7.has(Q.mode))throw new S$(K);if(!E4.test(Q.oid))throw Error(`git reported a malformed object id for ${K}`);let X=Q.oid,Y=Q.sizeText===null?await W7($,X,K):P4(Q.sizeText,K);if(Y>V)throw new R$(K,Y);let W=z7($,X),J=x4(Y,(z)=>W.read(z));return{oid:X,size:Y,version:X,read:(z)=>J.read(z),close(){return J.release(),W.release(),Promise.resolve()}}}async function b4($,Z,K,V){if(K7(K),Z==="worktree")return j7($,K,V);return O7($,Z,K,V)}var G7=["worktree","index","head"],M7=16,H7=z4,N7=T$,C7=["too-large","too-many-pixels"];function y4($){let Z=$.get("path");if(Z===null)throw new N(400,'Missing "path" query parameter');return Z}function B7($){let Z=$.get("side");if(Z===null||!G7.includes(Z))throw new N(400,'Invalid "side" (expected worktree, index or head)');return Z}function I7($){let Z=$.get("staged");if(Z==="1")return!0;if(Z==="0")return!1;throw new N(400,'Invalid "staged" (expected 0 or 1)')}function u4($){if($ instanceof S$)throw new N(400,$.message);if($ instanceof z$)throw new N(400,$.message);if($ instanceof R$)throw new N(413,$.message);throw $}async function m4($,Z){let K=await $.read(Z);return{bytes:K,sniff:q$(K,$.size,K.length>=$.size)}}async function A7($,Z){let{size:K}=$,V=await $.read(M7),Q=q$(V,K,V.length>=K);if(!Q.ok&&Q.refusal==="too-large")return{bytes:V,sniff:Q};let X=Math.min(GZ(V,K),K),Y=await m4($,Math.max(X,Math.min(Z,K)));if(Y.sniff.ok||Y.sniff.refusal!=="header-not-found")return Y;if(Y.bytes.length>=K)return Y;return m4($,K)}async function p4($,Z,K,V){let Q=await b4($,Z,K,T$);if(Q===null)return null;try{let{bytes:X,sniff:Y}=await A7(Q,V);return{bytes:X,size:Q.size,oid:Q.oid,version:Q.version,sniff:Y}}finally{await Q.close()}}function L7($,Z,K){let V={"content-type":Z,"content-disposition":"inline","x-content-type-options":"nosniff","cross-origin-resource-policy":"same-origin",vary:"sec-fetch-site, sec-fetch-dest","cache-control":$==="worktree"?"no-store":"private, no-cache"};if($!=="worktree"&&K!==null)V.etag=`"${K}"`;return V}function T7($){let Z=C7.includes($)?413:415;return new N(Z,`Image not served: ${$}`)}function D7($,Z){let K=$.originalPath??$.path;switch($.status){case"untracked":return{old:null,new:{side:"worktree",path:$.path}};case"added":return{old:null,new:{side:Z?"index":"worktree",path:$.path}};case"deleted":return{old:{side:Z?"head":"index",path:K},new:null};default:return Z?{old:{side:"head",path:K},new:{side:"index",path:$.path}}:{old:{side:"index",path:K},new:{side:"worktree",path:$.path}}}}function q7($,Z,K){return{path:$.path,side:$.side,bytes:Z,oid:null,image:null,refusal:K,version:""}}async function g4($,Z){let K=Y$($.path,Z.path);await W$($,K);let V;try{V=await p4($.path,Z.side,K,H7)}catch(Q){if(Q instanceof R$)return q7(Z,Q.size,"too-large");if(Q instanceof S$)return null;u4(Q)}if(V===null)return null;return{path:Z.path,side:Z.side,bytes:V.size,oid:V.oid,version:V.version,image:V.sniff.ok?V.sniff.info:null,refusal:V.sniff.ok?null:V.sniff.refusal}}function F7($,Z){return Z.writableEnded||Z.destroyed===!0||$.destroyed===!0}async function c4($,Z,K){let V=$.acquire();if(V===null)throw new N(503,"Too many image requests in flight");let Q=await V;if(K.once("finish",Q),K.once("close",Q),Z.once("close",Q),F7(Z,K))return Q(),!1;return!0}function h4($,Z,K){let{registry:V}=Z;$.get("/repos/:id/media",async({params:Q,query:X,req:Y,res:W})=>{let J=q(V,Q.id),z=I7(X),U=Y$(J.path,y4(X));if(await W$(J,U),!await c4(K,Y,W))return;let j=await I$(J.manager.workingTree,U,z),O=D7(j,z),M={old:O.old===null?null:await g4(J,O.old),new:O.new===null?null:await g4(J,O.new)};S(W,200,M)}),$.get("/repos/:id/blob",async({params:Q,query:X,req:Y,res:W})=>{let J=q(V,Q.id),z=T6(Y);if(z)throw new N(z.status,z.message);let U=B7(X),j=Y$(J.path,y4(X));if(await W$(J,j),!await c4(K,Y,W))return;let O;try{O=await p4(J.path,U,j,N7)}catch(B){u4(B)}if(O===null)throw new N(404,`No such blob on side ${U}: ${j}`);if(!O.sniff.ok)throw T7(O.sniff.refusal);let M=L7(U,O.sniff.info.mime,O.oid);M6(W,200,O.bytes,M)})}function f4($,Z){let{registry:K,daemonEvents:V,follow:Q}=Z;$.get("/events",({req:X,res:Y})=>{let W=K.listRepos().map((J)=>({id:J.id,path:J.path}));V.subscribe(X,Y,W)}),$.get("/follow",({res:X})=>{S(X,200,Q?Q.state:h8)})}function Q6($=4,Z=64){let K=0,V=[];function Q(){let X=!1;return()=>{if(X)return;X=!0;let Y=V.shift();if(Y)Y(Q());else K--}}return{acquire(){if(K<$)return K++,Promise.resolve(Q());if(V.length>=Z)return null;return new Promise((X)=>{V.push(X)})},get active(){return K},get queued(){return V.length}}}function S7($){if(!U$.existsSync($))return Promise.resolve(!1);return new Promise((Z)=>{try{let K=l4.connect($);K.once("connect",()=>{K.destroy(),Z(!0)}),K.once("error",()=>{K.destroy(),Z(!1)})}catch{Z(!1)}})}function n4($={}){let Z=new hZ,K=new fZ,V=new pZ({onOpened:(C)=>K.broadcast("repo-opened",{id:C.id,path:C.path}),onClosed:(C)=>{Z.closeRepo(C),K.broadcast("repo-closed",{id:C})}}),Q=$.followFile?new lZ(V,K,$.followFile):null,X=l8($.updateCheck===!1?()=>Promise.resolve(null):$.fetchLatestVersion),Y=new Map,W=Q6(),J=$.symbols??null,z=J===null?null:{pool:F4(J),gate:Q6(1,4),extensions:J.extensions};function U(C){let A=Y.get(C);if(A)return A;let G=new DZ,H={registry:V,sse:Z,daemonEvents:K,follow:Q,apiMode:C,version:X,symbols:z};if(o8(G,H),a8(G,H),Z4(G,H),Q4(G,H),Y4(G,H),W4(G,H),C==="full")J4(G,H);return B4(G,H),q4(G,H),h4(G,H,W),f4(G,H),Y.set(C,G),G}let j=(C)=>$.apiMode??(C==="tcp"?"web":"full");Q?.start();let O=$.webRoot?C6($.webRoot):void 0,M=new Set,B=[];function I(C){let A=U(C),G=d4.createServer((H,L)=>{for(let[v,R]of Object.entries(D6))L.setHeader(v,R);if(A6(G.address())){let v=L6(H);if(v){S(L,v.status,{error:v.message});return}}A.handle(H,L,O).catch(()=>L.end())});return G.on("connection",(H)=>{M.add(H),H.on("close",()=>M.delete(H))}),G}async function T(C,A){let G=C==="unix"?A.socketPath??null:null;if(G){if(await S7(G))throw Error(`diffstalkerd already running at ${G}`);U$.rmSync(G,{force:!0})}let H={server:I(j(C)),socketPath:G};B.push(H),await new Promise((L,v)=>{let R=(K5)=>v(K5);H.server.once("error",R);let x=()=>{if(H.server.removeListener("error",R),G)U$.chmodSync(G,384);L()};if(C==="fd")H.server.listen({fd:A.fd},x);else if(G)process.umask(63),H.server.listen(G,x);else H.server.listen(A.port,"127.0.0.1",x)})}function D(C){return new Promise((A,G)=>{C.server.close((H)=>{if(C.socketPath)U$.rmSync(C.socketPath,{force:!0});if(H&&H.code!=="ERR_SERVER_NOT_RUNNING")G(H);else A()})})}return{address(){return B[0]?.server.address()??null},addresses(){return B.map((C)=>C.server.address()).filter((C)=>C!==null)},getRepo(C){return V.getRepo(C)},async openRepo(C){let{handle:A}=await zZ(V,C);return{id:A.id,path:A.path}},async listen(C){let A=[];if(C.fd!==void 0)A.push("fd");if(C.socketPath)A.push("unix");if(C.port!==void 0)A.push("tcp");if(A.length===0)throw Error("listen() requires a socketPath, a port, or an fd");for(let G of A)await T(G,C)},close(){Q?.dispose(),Z.destroy(),K.destroy(),V.disposeAll();for(let A of M)A.destroy();let C=z?.pool.dispose()??Promise.resolve();return Promise.all([C,...B.splice(0).map(D)]).then(()=>{})}}}import*as X6 from"node:fs";import*as v$ from"node:path";import*as t4 from"node:crypto";import{createRequire as v7}from"node:module";var o4=new Map([[".ts",{grammar:"typescript",container:null}],[".mts",{grammar:"typescript",container:null}],[".cts",{grammar:"typescript",container:null}],[".vue",{grammar:"typescript",container:"vue"}],[".js",{grammar:"javascript",container:null}],[".mjs",{grammar:"javascript",container:null}],[".cjs",{grammar:"javascript",container:null}],[".jsx",{grammar:"javascript",container:null}],[".java",{grammar:"java",container:null}]]);function a4(){return[...o4.keys()]}function R7($){let Z=$.slice($.lastIndexOf("/")+1),K=Z.lastIndexOf(".");if(K<=0)return"";return Z.slice(K).toLowerCase()}function i4($){return o4.get(R7($))??null}var w7="diffstalkerd-grammars";function E7($){return t4.createHash("sha256").update($).digest("hex")}function k7($){try{let Z=JSON.parse(X6.readFileSync(v$.join($,"checksums.json"),"utf8"));if(typeof Z.webTreeSitterVersion!=="string"||typeof Z.files!=="object")return null;return Z}catch{return null}}var s4="0.26.11";function _7($,Z,K){for(let[V,Q]of Object.entries(Z.files)){let X;try{X=X6.readFileSync(v$.join($,V))}catch{return K(`grammars: missing ${V}`),!1}if(E7(X)!==Q)return K(`grammars: checksum mismatch for ${V}`),!1}return!0}function P7($){let Z=new Set;for(let K of Object.keys($.files)){let V=/^tree-sitter-(.+)\.wasm$/.exec(K);if(V!==null&&$.files[`queries/${V[1]}.scm`]!==void 0)Z.add(V[1])}return Z}function r4($,Z=()=>{}){let K=k7($);if(K===null)return Z(`grammars: no readable checksums.json in ${$}`),null;if(K.webTreeSitterVersion!==s4)return Z(`grammars: built for web-tree-sitter ${K.webTreeSitterVersion}, this daemon bundles ${s4} — symbols disabled`),null;if(!_7($,K,Z))return null;let V=P7(K),Q=a4().filter((X)=>{let Y=i4(`x${X}`);return Y!==null&&V.has(Y.grammar)});if(Q.length===0)return Z("grammars: no usable grammar found"),null;return{grammarDir:$,queryDir:v$.join($,"queries"),extensions:Q}}function e4($,Z=()=>{}){if($!==null)return r4($,Z);try{let V=v7(import.meta.url).resolve(`${w7}/checksums.json`);return r4(v$.dirname(V),Z)}catch{return null}}var Z5="diffstalkerd.sock";function b7($){return $===void 0?Z5:`${$}.sock`}var y7=3,$5=`diffstalkerd — diffstalker daemon (REST API + SSE over @diffstalker/core)
52
+
53
+ Usage: diffstalkerd [options] [REPO_PATH...]
45
54
 
46
- Usage: diffstalkerd [options]
55
+ Arguments:
56
+ REPO_PATH Repository to open on startup, so a client finds it
57
+ already there. Relative paths resolve against the
58
+ current directory and ~ expands; no path means no
59
+ repo is opened
47
60
 
48
61
  Options:
49
62
  --socket PATH Bind a unix socket at PATH
50
- (default: $XDG_RUNTIME_DIR/diffstalker/${D7})
51
- --port N Bind TCP port N (loopback only) instead of a unix socket
63
+ (default: $XDG_RUNTIME_DIR/diffstalker/${Z5})
64
+ --instance NAME Bind <NAME>.sock in the runtime dir, so several
65
+ daemons can run side by side (default: the shared
66
+ socket every client looks for first)
67
+ --no-socket Do not bind a unix socket (requires --port)
68
+ --port N Also bind TCP port N (loopback only) for the web UI.
69
+ The port serves the web API subset; the unix socket
70
+ keeps the full API
52
71
  --follow-file PATH Hook file to follow (created when missing)
53
72
  (default: ~/.cache/diffstalker/target)
54
73
  --no-follow Disable follow mode (no hook-file watcher)
@@ -57,6 +76,8 @@ Options:
57
76
  when missing, the daemon serves the API only)
58
77
  --no-update-check Never ask npm which version is latest; GET /version
59
78
  then reports the running version only
79
+ --version, -v Print the running version and exit
60
80
  --help, -h Show this help
61
- `;function c$($,Z,K){let V=$[Z];if(V===void 0||V.startsWith("--"))throw Error(`${K} requires a value`);return V}function z9($){let Z={};for(let K=0;K<$.length;K++){let V=$[K];switch(V){case"--help":case"-h":return"help";case"--socket":Z.socketPath=c$($,++K,"--socket");break;case"--port":if(Z.port=Number(c$($,++K,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":Z.followFile=c$($,++K,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;case"--web-root":Z.webRoot=c$($,++K,"--web-root");break;case"--no-update-check":Z.noUpdateCheck=!0;break;default:throw Error(`Unknown argument: ${V}`)}}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 W9(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function J9($){if($.socketPath!==void 0||$.port!==void 0)return;if(W9()){$.fd=Q9;return}let Z=D4();if(!Z)console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
62
- Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1);g$.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=C4.join(Z,D7)}function U9($){let Z=$??X9(new URL("web/",import.meta.url));if(g$.existsSync(Z))return Z;console.error(`diffstalkerd: web UI assets not found at ${Z}; serving API only`);return}function G9($){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${$}/`)}async function O9(){process.title="diffstalkerd";let $;try{$=z9(process.argv.slice(2))}catch(W){console.error(W instanceof Error?W.message:String(W)),console.error(L7),process.exit(2)}if($==="help"){console.log(L7);return}J9($);let Z=$.noFollow?void 0:$.followFile??C4.join(M$(),"target"),K=U9($.webRoot),V=$.port!==void 0?"web":"full",X=T7({followFile:Z,webRoot:K,apiMode:V,updateCheck:!$.noUpdateCheck});if(await X.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(K){if(console.error(`diffstalkerd serving web UI from ${K}`),$.port!==void 0)G9($.port)}let Y=!1,Q=(W)=>{if(Y)return;Y=!0,console.error(`Received ${W}, shutting down`),X.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),X.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(W)=>z("uncaught exception",W)),process.on("unhandledRejection",(W)=>z("unhandled rejection",W))}O9().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{z9 as parseArgs};
81
+ `;function w$($,Z,K){let V=$[Z];if(V===void 0||V.startsWith("--"))throw Error(`${K} requires a value`);return V}function m7($,Z){if(Z.startsWith("-"))throw Error(`Unknown argument: ${Z}`);if(Z==="")throw Error("Empty repo path argument");$.repoPaths??=[],$.repoPaths.push(Z)}function g7($){let Z={};for(let K=0;K<$.length;K++){let V=$[K];switch(V){case"--help":case"-h":return"help";case"--version":case"-v":return"version";case"--socket":Z.socketPath=w$($,++K,"--socket");break;case"--instance":Z.instance=w$($,++K,"--instance");break;case"--no-socket":Z.noSocket=!0;break;case"--port":if(Z.port=Number(w$($,++K,"--port")),!Number.isInteger(Z.port)||Z.port<0)throw Error("--port requires a non-negative integer");break;case"--follow-file":Z.followFile=w$($,++K,"--follow-file");break;case"--no-follow":Z.noFollow=!0;break;case"--web-root":Z.webRoot=w$($,++K,"--web-root");break;case"--grammars":Z.grammarsDir=w$($,++K,"--grammars");break;case"--no-update-check":Z.noUpdateCheck=!0;break;default:m7(Z,V);break}}if(Z.socketPath!==void 0&&Z.noSocket)throw Error("--socket and --no-socket are mutually exclusive");if(Z.noSocket&&Z.port===void 0)throw Error("--no-socket requires --port (nothing would be listening)");if(Z.followFile!==void 0&&Z.noFollow)throw Error("--follow-file and --no-follow are mutually exclusive");return Z}function c7(){return process.env.LISTEN_PID===String(process.pid)&&Number(process.env.LISTEN_FDS)>=1}function u7($){if($.noSocket||$.socketPath!==void 0)return;if(c7()){$.fd=y7;return}let Z=z6();if(!Z){if($.port!==void 0){console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set; binding the TCP port only.
82
+ Pass --socket PATH to also accept CLI connections.`);return}console.error(`diffstalkerd: XDG_RUNTIME_DIR is not set and no --socket/--port given.
83
+ Refusing to guess a socket location; pass --socket PATH or set XDG_RUNTIME_DIR.`),process.exit(1)}BZ.mkdirSync(Z,{recursive:!0,mode:448}),$.socketPath=d$.join(Z,b7($.instance))}function p7($){let Z=$??x7(new URL("web/",import.meta.url));if(BZ.existsSync(Z))return Z;console.error(`diffstalkerd: web UI assets not found at ${Z}; serving API only`);return}function h7($){console.error(`diffstalkerd: web UI at http://diffstalker.localhost:${$}/`)}async function f7($,Z){for(let K of Z){let V=d$.resolve(O$(K));try{let Q=await $.openRepo(V);console.error(`diffstalkerd opened ${Q.path}`)}catch(Q){console.error(`diffstalkerd: cannot open ${V}: ${Q instanceof Error?Q.message:String(Q)}`),await $.close().catch(()=>{}),process.exit(1)}}}async function d7(){process.title="diffstalkerd";let $;try{$=g7(process.argv.slice(2))}catch(U){console.error(U instanceof Error?U.message:String(U)),console.error($5),process.exit(2)}if($==="help"){console.log($5);return}if($==="version"){let U=nZ();if(U===null)console.error("diffstalkerd: version unknown (package.json unreadable)"),process.exit(1);console.log(U);return}u7($);let Z=$.noFollow?void 0:$.followFile??d$.join(j$(),"target"),K=p7($.webRoot),V=e4($.grammarsDir??process.env.DIFFSTALKER_GRAMMARS_DIR??null,(U)=>console.error(`diffstalkerd: ${U}`)),Q=n4({followFile:Z,webRoot:K,symbols:V,updateCheck:!$.noUpdateCheck});await f7(Q,$.repoPaths??[]),await Q.listen($);let Y=Q.addresses().find((U)=>typeof U!=="string")?.port??$.port;if($.fd!==void 0)console.error(`diffstalkerd listening on inherited socket (fd ${$.fd})`);if($.socketPath)console.error(`diffstalkerd listening on unix socket ${$.socketPath}`);if(Y!==void 0)console.error(`diffstalkerd listening on 127.0.0.1:${Y}`);if(Z)console.error(`diffstalkerd following ${Z}`);if(K){if(console.error(`diffstalkerd serving web UI from ${K}`),Y!==void 0)h7(Y)}let W=!1,J=(U)=>{if(W)return;W=!0,console.error(`Received ${U}, shutting down`),Q.close().then(()=>process.exit(0)).catch((j)=>{console.error(j instanceof Error?j.message:String(j)),process.exit(1)})};process.on("SIGINT",()=>J("SIGINT")),process.on("SIGTERM",()=>J("SIGTERM")),process.on("SIGHUP",()=>J("SIGHUP"));let z=(U,j)=>{console.error(`diffstalkerd ${U}:`,j instanceof Error?j.stack??j.message:j),Q.close().catch(()=>{}).finally(()=>process.exit(1))};process.on("uncaughtException",(U)=>z("uncaught exception",U)),process.on("unhandledRejection",(U)=>z("unhandled rejection",U))}d7().catch(($)=>{console.error($ instanceof Error?$.message:String($)),process.exit(1)});export{g7 as parseArgs};