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