@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 215 lines 7.53 KB
Raw
1 import { md5, sha1 } from "@noble/hashes/legacy";
2 import { sha256 } from "@noble/hashes/sha2";
3 import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils";
4
5 export interface PullRequestAnchorRange {
6 readonly start: number;
7 readonly side: "left" | "right";
8 readonly end: number;
9 readonly endSide: "left" | "right";
10 /** A GitLab line code's old-side counter: the line it names when that old line was removed. */
11 readonly oldLine?: number;
12 }
13
14 export type PullRequestAnchor =
15 | { readonly kind: "code" }
16 | { readonly kind: "commits" }
17 | { readonly kind: "checks" }
18 | {
19 readonly kind: "diff";
20 readonly digest: string;
21 readonly range: PullRequestAnchorRange | null;
22 }
23 | { readonly kind: "timeline"; readonly anchor: string }
24 | { readonly kind: "summary"; readonly anchor: string };
25
26 function pullRequestUrlHash(url: string | null | undefined): string {
27 if (!url) return "";
28 try {
29 return decodeURIComponent(new URL(url).hash.slice(1));
30 } catch {
31 return "";
32 }
33 }
34
35 function normalizePullRequestCommentAnchor(anchor: string): string {
36 return anchor.replace(
37 /^(?:r|discussion-diff-)(\d+)(?:[LR]\d+(?:-[LR]\d+)?)?$/i,
38 "discussion_r$1",
39 );
40 }
41
42 // GitHub pull request tabs and their GitLab merge request equivalents. Forgejo and Gitea spell the
43 // path `/pulls/`.
44 function pullRequestPathTab(pathname: string): PullRequestAnchor | null {
45 const tab = /\/(?:pulls?|-\/merge_requests)\/\d+\/([a-z]+)(?:\/(.*))?$/i.exec(pathname);
46 const rest = tab?.[2] ?? "";
47 switch (tab?.[1]?.toLowerCase()) {
48 case "files":
49 case "changes":
50 case "diffs":
51 return { kind: "code" };
52 case "commits":
53 if (rest === "") return { kind: "commits" };
54 return /^[a-f0-9]{40}\/?$/i.test(rest) ? { kind: "code" } : null;
55 case "checks":
56 case "pipelines":
57 return rest === "" ? { kind: "checks" } : null;
58 default:
59 return null;
60 }
61 }
62
63 const isLine = (line: number) => Number.isSafeInteger(line) && line >= 1;
64
65 function gitLabLine(
66 start: number,
67 side: "left" | "right",
68 oldLine = 0,
69 ): PullRequestAnchorRange | null {
70 if (!isLine(start)) return null;
71 return { start, side, end: start, endSide: side, ...(isLine(oldLine) ? { oldLine } : {}) };
72 }
73
74 // GitLab names a file by its path's SHA-1 and a line by `<sha1>_<old>_<new>`, which carries both
75 // sides' counters. Rapid Diffs writes `line_<sha1 prefix>_<old>` or `_A<new>`.
76 function gitLabDiffAnchor(anchor: string, file: string | null): PullRequestAnchor | null {
77 const rapid = /^line_([a-f0-9]{9})_(A?)(\d+)$/i.exec(anchor);
78 if (rapid) {
79 const line = Number(rapid[3]);
80 return {
81 kind: "diff",
82 digest: (rapid[1] ?? "").toLowerCase(),
83 range: gitLabLine(line, rapid[2] ? "right" : "left"),
84 };
85 }
86 const code = /^(?:diff-content-)?([a-f0-9]{40})(?:_(\d+)_(\d+))?$/i.exec(anchor);
87 // A comment anchor beside `?file=` names the comment.
88 const digest =
89 code?.[1] ?? (!anchor && file !== null && /^[a-f0-9]{40}$/i.test(file) ? file : null);
90 if (digest === null) return null;
91 const [oldLine, newLine] = [Number(code?.[2]), Number(code?.[3])];
92 // A deleted file has no new side, so its new counter is 0.
93 const range =
94 code?.[2] === undefined
95 ? null
96 : newLine === 0
97 ? gitLabLine(oldLine, "left")
98 : gitLabLine(newLine, "right", oldLine);
99 return { kind: "diff", digest: digest.toLowerCase(), range };
100 }
101
102 /** The range to select, once the diff shows whether a GitLab line code's old line was removed. */
103 export function resolvePullRequestAnchorRange(
104 range: PullRequestAnchorRange,
105 isRemovedLine: (oldLine: number) => boolean,
106 ): PullRequestAnchorRange {
107 return range.oldLine !== undefined && isRemovedLine(range.oldLine)
108 ? (gitLabLine(range.oldLine, "left") ?? range)
109 : range;
110 }
111
112 export function parsePullRequestAnchor(url: string | null | undefined): PullRequestAnchor | null {
113 let parsed: URL;
114 try {
115 parsed = new URL(url ?? "");
116 } catch {
117 return null;
118 }
119 const fallback = pullRequestPathTab(parsed.pathname);
120 const anchor = pullRequestUrlHash(url);
121 const gitLab = gitLabDiffAnchor(
122 anchor,
123 /\/-\/merge_requests\/\d+\/diffs\/?$/i.test(parsed.pathname)
124 ? parsed.searchParams.get("file")
125 : null,
126 );
127 if (gitLab) return gitLab;
128 if (!anchor) return fallback;
129 // GitHub line ranges may cross diff sides; file digests were MD5 before SHA-256.
130 const diff = /^diff-([a-f0-9]+)(?:([LR])(\d+)(?:-([LR])(\d+))?)?$/i.exec(anchor);
131 if (diff) {
132 const start = Number(diff[3]);
133 const end = Number(diff[5] ?? diff[3]);
134 if (
135 diff[2] &&
136 (!Number.isSafeInteger(start) || start < 1 || !Number.isSafeInteger(end) || end < 1)
137 )
138 return fallback;
139 return {
140 kind: "diff",
141 digest: (diff[1] ?? "").toLowerCase(),
142 range: diff[2]
143 ? {
144 start,
145 side: diff[2].toUpperCase() === "L" ? "left" : "right",
146 end,
147 endSide: (diff[4] ?? diff[2]).toUpperCase() === "L" ? "left" : "right",
148 }
149 : null,
150 };
151 }
152 if (
153 /^(?:(?:issuecomment-|pullrequestreview-|discussion_r|r|commitcomment-|event-|note_|comment-)\d+|discussion-diff-\d+(?:[LR]\d+(?:-[LR]\d+)?)?)$/i.test(
154 anchor,
155 )
156 ) {
157 return { kind: "timeline", anchor: normalizePullRequestCommentAnchor(anchor) };
158 }
159 return fallback ?? { kind: "summary", anchor };
160 }
161
162 export function pullRequestAnchorMatchesUrl(
163 anchor: string,
164 url: string | null | undefined,
165 ): boolean {
166 return normalizePullRequestCommentAnchor(pullRequestUrlHash(url)) === anchor;
167 }
168
169 interface AnchoredComment {
170 readonly url: string | null;
171 readonly createdAt: string;
172 readonly reviewUrl?: string | null | undefined;
173 }
174
175 /**
176 * A review with no text of its own appears only through the line comments it posted, so its link
177 * resolves to the earliest of those. Any other anchor, or a review shown in its own right, is kept.
178 */
179 export function resolvePullRequestReviewAnchor(
180 anchor: string,
181 comments: ReadonlyArray<Pick<AnchoredComment, "url">>,
182 reviewThreads: ReadonlyArray<{ readonly comments: ReadonlyArray<AnchoredComment> }>,
183 ): string {
184 if (!/^pullrequestreview-\d+$/i.test(anchor)) return anchor;
185 if (comments.some((comment) => pullRequestAnchorMatchesUrl(anchor, comment.url))) return anchor;
186 // The earliest comment the review posted; `toSorted` is missing from Hermes.
187 let posted: AnchoredComment | undefined;
188 for (const comment of reviewThreads.flatMap((thread) => thread.comments)) {
189 if (comment.url === null || !pullRequestAnchorMatchesUrl(anchor, comment.reviewUrl)) continue;
190 if (posted === undefined || comment.createdAt < posted.createdAt) posted = comment;
191 }
192 const own = posted ? normalizePullRequestCommentAnchor(pullRequestUrlHash(posted.url)) : "";
193 return own || anchor;
194 }
195
196 export function pullRequestDiffPathMatches(digest: string, path: string): boolean {
197 const bytes = utf8ToBytes(path);
198 // GitLab uses SHA-1, abbreviated to 9 characters in Rapid Diffs line anchors.
199 if (digest.length === 40 || digest.length === 9)
200 return bytesToHex(sha1(bytes)).startsWith(digest);
201 return digest === bytesToHex(digest.length === 32 ? md5(bytes) : sha256(bytes));
202 }
203
204 export function pullRequestLinkCommit(url: string | null | undefined): string | null {
205 if (!url) return null;
206 try {
207 const { pathname, searchParams } = new URL(url);
208 const commit = /\/-\/merge_requests\/\d+\/diffs\/?$/i.test(pathname)
209 ? searchParams.get("commit_id")
210 : /\/pulls?\/\d+\/commits\/([a-f0-9]{40})\/?$/i.exec(pathname)?.[1];
211 return commit && /^[a-f0-9]{40}$/i.test(commit) ? commit : null;
212 } catch {
213 return null;
214 }
215 }