Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesPull RequestsActionsSecurityInsightsSettings
✨ AI
More
Blame · Line-by-line history

web.tsx

Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.

web.tsxBlame917 lines · 1 contributor
fc1817aClaude1/**
2 * Web UI routes — browse repositories, code, commits, diffs.
06d5ffeClaude3 * Now auth-aware with user profiles, repo creation, stars, and syntax highlighting.
fc1817aClaude4 */
5
6import { Hono } from "hono";
79136bbClaude7import { html } from "hono/html";
06d5ffeClaude8import { eq, and, desc } from "drizzle-orm";
9import { db } from "../db";
10import { users, repositories, stars } from "../db/schema";
fc1817aClaude11import { Layout } from "../views/layout";
12import {
13 RepoHeader,
14 RepoNav,
15 Breadcrumb,
16 FileTable,
17 CommitList,
18 DiffView,
06d5ffeClaude19 RepoCard,
20 BranchSwitcher,
21 HighlightedCode,
22 PlainCode,
fc1817aClaude23} from "../views/components";
24import {
25 getTree,
26 getBlob,
27 listCommits,
28 getCommit,
29 getCommitFullMessage,
30 getDiff,
31 getReadme,
32 getDefaultBranch,
33 listBranches,
34 repoExists,
06d5ffeClaude35 initBareRepo,
79136bbClaude36 getBlame,
37 getRawBlob,
38 searchCode,
fc1817aClaude39} from "../git/repository";
79136bbClaude40import { renderMarkdown, markdownCss } from "../lib/markdown";
06d5ffeClaude41import { highlightCode } from "../lib/highlight";
42import { softAuth, requireAuth } from "../middleware/auth";
43import type { AuthEnv } from "../middleware/auth";
8f50ed0Claude44import { trackByName } from "../lib/traffic";
fc1817aClaude45
06d5ffeClaude46const web = new Hono<AuthEnv>();
47
48// Soft auth on all web routes — c.get("user") available but may be null
49web.use("*", softAuth);
fc1817aClaude50
51// Home page
06d5ffeClaude52web.get("/", async (c) => {
53 const user = c.get("user");
54
55 if (user) {
3ef4c9dClaude56 const { renderDashboard } = await import("./dashboard");
57 return renderDashboard(c);
06d5ffeClaude58 }
59
fc1817aClaude60 return c.html(
06d5ffeClaude61 <Layout user={null}>
fc1817aClaude62 <div class="empty-state">
63 <h2>gluecron</h2>
64 <p>AI-native code intelligence platform</p>
06d5ffeClaude65 <div style="margin-top: 24px; display: flex; gap: 12px; justify-content: center">
66 <a href="/register" class="btn btn-primary">
67 Get started
68 </a>
69 <a href="/login" class="btn">
70 Sign in
71 </a>
72 </div>
73 <pre style="margin-top: 32px">{`# Quick start
fc1817aClaude74curl -X POST http://localhost:3000/api/setup \\
75 -H 'Content-Type: application/json' \\
76 -d '{"username":"you","email":"you@dev.com","repoName":"hello"}'
77
78git remote add gluecron http://localhost:3000/you/hello.git
79git push gluecron main`}</pre>
80 </div>
81 </Layout>
82 );
83});
84
06d5ffeClaude85// New repository form
86web.get("/new", requireAuth, (c) => {
87 const user = c.get("user")!;
88 const error = c.req.query("error");
89
90 return c.html(
91 <Layout title="New repository" user={user}>
92 <div class="new-repo-form">
93 <h2>Create a new repository</h2>
94 {error && <div class="auth-error">{decodeURIComponent(error)}</div>}
95 <form method="POST" action="/new">
96 <div class="form-group">
97 <label>Owner</label>
98 <input type="text" value={user.username} disabled class="input-disabled" />
99 </div>
100 <div class="form-group">
101 <label for="name">Repository name</label>
102 <input
103 type="text"
104 id="name"
105 name="name"
106 required
107 pattern="^[a-zA-Z0-9._-]+$"
108 placeholder="my-project"
109 autocomplete="off"
110 />
111 </div>
112 <div class="form-group">
113 <label for="description">Description (optional)</label>
114 <input
115 type="text"
116 id="description"
117 name="description"
118 placeholder="A short description of your repository"
119 />
120 </div>
121 <div class="visibility-options">
122 <label class="visibility-option">
123 <input type="radio" name="visibility" value="public" checked />
124 <div class="vis-label">Public</div>
125 <div class="vis-desc">Anyone can see this repository</div>
126 </label>
127 <label class="visibility-option">
128 <input type="radio" name="visibility" value="private" />
129 <div class="vis-label">Private</div>
130 <div class="vis-desc">Only you can see this repository</div>
131 </label>
132 </div>
133 <button type="submit" class="btn btn-primary">
134 Create repository
135 </button>
136 </form>
137 </div>
138 </Layout>
139 );
140});
141
142web.post("/new", requireAuth, async (c) => {
143 const user = c.get("user")!;
144 const body = await c.req.parseBody();
145 const name = String(body.name || "").trim();
146 const description = String(body.description || "").trim();
147 const isPrivate = body.visibility === "private";
148
149 if (!name) {
150 return c.redirect("/new?error=Repository+name+is+required");
151 }
152
153 if (!/^[a-zA-Z0-9._-]+$/.test(name)) {
154 return c.redirect("/new?error=Invalid+repository+name");
155 }
156
157 if (await repoExists(user.username, name)) {
158 return c.redirect("/new?error=Repository+already+exists");
159 }
160
161 const diskPath = await initBareRepo(user.username, name);
162
3ef4c9dClaude163 const [newRepo] = await db
164 .insert(repositories)
165 .values({
166 name,
167 ownerId: user.id,
168 description: description || null,
169 isPrivate,
170 diskPath,
171 })
172 .returning();
173
174 if (newRepo) {
175 const { bootstrapRepository } = await import("../lib/repo-bootstrap");
176 await bootstrapRepository({
177 repositoryId: newRepo.id,
178 ownerUserId: user.id,
179 defaultBranch: "main",
180 });
181 }
06d5ffeClaude182
183 return c.redirect(`/${user.username}/${name}`);
184});
185
186// User profile
fc1817aClaude187web.get("/:owner", async (c) => {
06d5ffeClaude188 const { owner: ownerName } = c.req.param();
189 const user = c.get("user");
190
191 // Avoid clashing with fixed routes
192 if (
193 ["login", "register", "logout", "new", "settings", "api"].includes(
194 ownerName
195 )
196 ) {
197 return c.notFound();
198 }
199
200 let ownerUser;
201 try {
202 const [found] = await db
203 .select()
204 .from(users)
205 .where(eq(users.username, ownerName))
206 .limit(1);
207 ownerUser = found;
208 } catch {
209 // DB not available — check if repos exist on disk
210 ownerUser = null;
211 }
212
213 // Even without DB, show repos if they exist on disk
214 let repos: any[] = [];
215 if (ownerUser) {
216 const allRepos = await db
217 .select()
218 .from(repositories)
219 .where(eq(repositories.ownerId, ownerUser.id))
220 .orderBy(desc(repositories.updatedAt));
221
222 // Show public repos to everyone, private only to owner
223 repos =
224 user?.id === ownerUser.id
225 ? allRepos
226 : allRepos.filter((r) => !r.isPrivate);
227 }
228
fc1817aClaude229 return c.html(
06d5ffeClaude230 <Layout title={ownerName} user={user}>
231 <div class="user-profile">
232 <div class="user-avatar">
233 {(ownerUser?.displayName || ownerName)[0].toUpperCase()}
234 </div>
235 <div class="user-info">
236 <h2>{ownerUser?.displayName || ownerName}</h2>
237 <div class="username">@{ownerName}</div>
238 {ownerUser?.bio && <div class="bio">{ownerUser.bio}</div>}
239 </div>
240 </div>
241 <h3 style="margin-bottom: 16px">Repositories</h3>
242 {repos.length === 0 ? (
243 <p style="color: var(--text-muted)">No repositories yet.</p>
244 ) : (
245 <div class="card-grid">
246 {repos.map((repo) => (
247 <RepoCard repo={repo} ownerName={ownerName} />
248 ))}
249 </div>
250 )}
fc1817aClaude251 </Layout>
252 );
253});
254
06d5ffeClaude255// Star/unstar a repo
256web.post("/:owner/:repo/star", requireAuth, async (c) => {
257 const { owner: ownerName, repo: repoName } = c.req.param();
258 const user = c.get("user")!;
259
260 try {
261 const [ownerUser] = await db
262 .select()
263 .from(users)
264 .where(eq(users.username, ownerName))
265 .limit(1);
266 if (!ownerUser) return c.redirect(`/${ownerName}/${repoName}`);
267
268 const [repo] = await db
269 .select()
270 .from(repositories)
271 .where(
272 and(
273 eq(repositories.ownerId, ownerUser.id),
274 eq(repositories.name, repoName)
275 )
276 )
277 .limit(1);
278 if (!repo) return c.redirect(`/${ownerName}/${repoName}`);
279
280 // Toggle star
281 const [existing] = await db
282 .select()
283 .from(stars)
284 .where(
285 and(eq(stars.userId, user.id), eq(stars.repositoryId, repo.id))
286 )
287 .limit(1);
288
289 if (existing) {
290 await db.delete(stars).where(eq(stars.id, existing.id));
291 await db
292 .update(repositories)
293 .set({ starCount: Math.max(0, repo.starCount - 1) })
294 .where(eq(repositories.id, repo.id));
295 } else {
296 await db.insert(stars).values({
297 userId: user.id,
298 repositoryId: repo.id,
299 });
300 await db
301 .update(repositories)
302 .set({ starCount: repo.starCount + 1 })
303 .where(eq(repositories.id, repo.id));
304 }
305 } catch {
306 // DB error — ignore
307 }
308
309 return c.redirect(`/${ownerName}/${repoName}`);
310});
311
fc1817aClaude312// Repository overview — file tree at HEAD
313web.get("/:owner/:repo", async (c) => {
314 const { owner, repo } = c.req.param();
06d5ffeClaude315 const user = c.get("user");
fc1817aClaude316
8f50ed0Claude317 // F1 — fire-and-forget traffic tracking. Never awaits; never throws.
318 trackByName(owner, repo, "view", {
319 userId: user?.id || null,
320 path: `/${owner}/${repo}`,
321 ip: c.req.header("x-forwarded-for") || c.req.header("x-real-ip") || null,
322 userAgent: c.req.header("user-agent") || null,
323 referer: c.req.header("referer") || null,
324 }).catch(() => {});
325
fc1817aClaude326 if (!(await repoExists(owner, repo))) {
327 return c.html(
06d5ffeClaude328 <Layout title="Not Found" user={user}>
fc1817aClaude329 <div class="empty-state">
330 <h2>Repository not found</h2>
331 <p>
332 {owner}/{repo} does not exist.
333 </p>
334 </div>
335 </Layout>,
336 404
337 );
338 }
339
05b973eClaude340 // Parallelize all independent operations
341 const [defaultBranch, branches] = await Promise.all([
342 getDefaultBranch(owner, repo).then((b) => b || "main"),
343 listBranches(owner, repo),
344 ]);
345 const [tree, starInfo] = await Promise.all([
346 getTree(owner, repo, defaultBranch),
347 // Star info fetched in parallel with tree
348 (async () => {
349 try {
350 const [ownerUser] = await db
351 .select()
352 .from(users)
353 .where(eq(users.username, owner))
354 .limit(1);
355 if (!ownerUser) return { starCount: 0, starred: false };
356 const [repoRow] = await db
357 .select()
358 .from(repositories)
359 .where(
360 and(
361 eq(repositories.ownerId, ownerUser.id),
362 eq(repositories.name, repo)
363 )
06d5ffeClaude364 )
05b973eClaude365 .limit(1);
366 if (!repoRow) return { starCount: 0, starred: false };
367 let starred = false;
06d5ffeClaude368 if (user) {
369 const [star] = await db
370 .select()
371 .from(stars)
372 .where(
373 and(
374 eq(stars.userId, user.id),
375 eq(stars.repositoryId, repoRow.id)
376 )
377 )
378 .limit(1);
379 starred = !!star;
380 }
05b973eClaude381 return { starCount: repoRow.starCount, starred };
382 } catch {
383 return { starCount: 0, starred: false };
06d5ffeClaude384 }
05b973eClaude385 })(),
386 ]);
387 const { starCount, starred } = starInfo;
06d5ffeClaude388
fc1817aClaude389 if (tree.length === 0) {
390 return c.html(
06d5ffeClaude391 <Layout title={`${owner}/${repo}`} user={user}>
392 <RepoHeader
393 owner={owner}
394 repo={repo}
395 starCount={starCount}
396 starred={starred}
397 currentUser={user?.username}
398 />
fc1817aClaude399 <RepoNav owner={owner} repo={repo} active="code" />
400 <div class="empty-state">
401 <h2>Empty repository</h2>
402 <p>Get started by pushing code:</p>
403 <pre>{`git remote add gluecron http://localhost:3000/${owner}/${repo}.git
404git push -u gluecron main`}</pre>
405 </div>
406 </Layout>
407 );
408 }
409
410 const readme = await getReadme(owner, repo, defaultBranch);
411
412 return c.html(
06d5ffeClaude413 <Layout title={`${owner}/${repo}`} user={user}>
414 <RepoHeader
415 owner={owner}
416 repo={repo}
417 starCount={starCount}
418 starred={starred}
419 currentUser={user?.username}
420 />
fc1817aClaude421 <RepoNav owner={owner} repo={repo} active="code" />
06d5ffeClaude422 <BranchSwitcher
423 owner={owner}
424 repo={repo}
425 currentRef={defaultBranch}
426 branches={branches}
427 pathType="tree"
428 />
fc1817aClaude429 <FileTable
430 entries={tree}
431 owner={owner}
432 repo={repo}
433 ref={defaultBranch}
434 path=""
435 />
79136bbClaude436 {readme && (() => {
437 const readmeHtml = renderMarkdown(readme);
438 return (
439 <div class="blob-view" style="margin-top: 20px">
440 <div class="blob-header">README.md</div>
441 <style>{markdownCss}</style>
442 <div class="markdown-body">
443 {html([readmeHtml] as unknown as TemplateStringsArray)}
444 </div>
fc1817aClaude445 </div>
79136bbClaude446 );
447 })()}
fc1817aClaude448 </Layout>
449 );
450});
451
452// Browse tree at ref/path
453web.get("/:owner/:repo/tree/:ref{.+$}", async (c) => {
454 const { owner, repo } = c.req.param();
06d5ffeClaude455 const user = c.get("user");
fc1817aClaude456 const refAndPath = c.req.param("ref");
457
458 const branches = await listBranches(owner, repo);
459 let ref = "";
460 let treePath = "";
461
462 for (const branch of branches) {
463 if (refAndPath === branch || refAndPath.startsWith(branch + "/")) {
464 ref = branch;
465 treePath = refAndPath.slice(branch.length + 1);
466 break;
467 }
468 }
469
470 if (!ref) {
471 const slashIdx = refAndPath.indexOf("/");
472 if (slashIdx === -1) {
473 ref = refAndPath;
474 } else {
475 ref = refAndPath.slice(0, slashIdx);
476 treePath = refAndPath.slice(slashIdx + 1);
477 }
478 }
479
480 const tree = await getTree(owner, repo, ref, treePath);
481
482 return c.html(
06d5ffeClaude483 <Layout title={`${treePath || "/"} — ${owner}/${repo}`} user={user}>
fc1817aClaude484 <RepoHeader owner={owner} repo={repo} />
485 <RepoNav owner={owner} repo={repo} active="code" />
06d5ffeClaude486 <BranchSwitcher
487 owner={owner}
488 repo={repo}
489 currentRef={ref}
490 branches={branches}
491 pathType="tree"
492 subPath={treePath}
493 />
fc1817aClaude494 <Breadcrumb owner={owner} repo={repo} ref={ref} path={treePath} />
495 <FileTable
496 entries={tree}
497 owner={owner}
498 repo={repo}
499 ref={ref}
500 path={treePath}
501 />
502 </Layout>
503 );
504});
505
06d5ffeClaude506// View file blob with syntax highlighting
fc1817aClaude507web.get("/:owner/:repo/blob/:ref{.+$}", async (c) => {
508 const { owner, repo } = c.req.param();
06d5ffeClaude509 const user = c.get("user");
fc1817aClaude510 const refAndPath = c.req.param("ref");
511
512 const branches = await listBranches(owner, repo);
513 let ref = "";
514 let filePath = "";
515
516 for (const branch of branches) {
517 if (refAndPath.startsWith(branch + "/")) {
518 ref = branch;
519 filePath = refAndPath.slice(branch.length + 1);
520 break;
521 }
522 }
523
524 if (!ref) {
525 const slashIdx = refAndPath.indexOf("/");
526 if (slashIdx === -1) return c.text("Not found", 404);
527 ref = refAndPath.slice(0, slashIdx);
528 filePath = refAndPath.slice(slashIdx + 1);
529 }
530
531 const blob = await getBlob(owner, repo, ref, filePath);
532 if (!blob) {
533 return c.html(
06d5ffeClaude534 <Layout title="Not Found" user={user}>
fc1817aClaude535 <div class="empty-state">
536 <h2>File not found</h2>
537 </div>
538 </Layout>,
539 404
540 );
541 }
542
06d5ffeClaude543 const fileName = filePath.split("/").pop() || filePath;
fc1817aClaude544
545 return c.html(
06d5ffeClaude546 <Layout title={`${filePath} — ${owner}/${repo}`} user={user}>
fc1817aClaude547 <RepoHeader owner={owner} repo={repo} />
548 <RepoNav owner={owner} repo={repo} active="code" />
06d5ffeClaude549 <BranchSwitcher
550 owner={owner}
551 repo={repo}
552 currentRef={ref}
553 branches={branches}
554 pathType="blob"
555 subPath={filePath}
556 />
fc1817aClaude557 <Breadcrumb owner={owner} repo={repo} ref={ref} path={filePath} />
558 <div class="blob-view">
559 <div class="blob-header">
06d5ffeClaude560 <span>{fileName} — {blob.size} bytes</span>
79136bbClaude561 <span style="display: flex; gap: 12px">
562 <a href={`/${owner}/${repo}/raw/${ref}/${filePath}`} style="font-size: 12px">
563 Raw
564 </a>
565 <a href={`/${owner}/${repo}/blame/${ref}/${filePath}`} style="font-size: 12px">
566 Blame
567 </a>
0074234Claude568 {user && (
569 <a href={`/${owner}/${repo}/edit/${ref}/${filePath}`} style="font-size: 12px">
570 Edit
571 </a>
572 )}
79136bbClaude573 </span>
fc1817aClaude574 </div>
575 {blob.isBinary ? (
576 <div style="padding: 16px; color: var(--text-muted)">
577 Binary file not shown.
578 </div>
06d5ffeClaude579 ) : (() => {
580 const { html: highlighted, language } = highlightCode(
581 blob.content,
582 fileName
583 );
584 const lineCount = blob.content.split("\n").length;
585 // Trim trailing newline from count
586 const adjustedCount =
587 blob.content.endsWith("\n") ? lineCount - 1 : lineCount;
588
589 if (language) {
590 return (
591 <HighlightedCode
592 highlightedHtml={highlighted}
593 lineCount={adjustedCount}
594 />
595 );
596 }
597 const lines = blob.content.split("\n");
598 if (lines[lines.length - 1] === "") lines.pop();
599 return <PlainCode lines={lines} />;
600 })()}
fc1817aClaude601 </div>
602 </Layout>
603 );
604});
605
606// Commit log
607web.get("/:owner/:repo/commits/:ref?", async (c) => {
608 const { owner, repo } = c.req.param();
06d5ffeClaude609 const user = c.get("user");
fc1817aClaude610 const ref =
611 c.req.param("ref") || (await getDefaultBranch(owner, repo)) || "main";
06d5ffeClaude612 const branches = await listBranches(owner, repo);
fc1817aClaude613
614 const commits = await listCommits(owner, repo, ref, 50);
615
616 return c.html(
06d5ffeClaude617 <Layout title={`Commits — ${owner}/${repo}`} user={user}>
fc1817aClaude618 <RepoHeader owner={owner} repo={repo} />
619 <RepoNav owner={owner} repo={repo} active="commits" />
06d5ffeClaude620 <BranchSwitcher
621 owner={owner}
622 repo={repo}
623 currentRef={ref}
624 branches={branches}
625 pathType="commits"
626 />
fc1817aClaude627 {commits.length === 0 ? (
628 <div class="empty-state">
629 <p>No commits yet.</p>
630 </div>
631 ) : (
632 <CommitList commits={commits} owner={owner} repo={repo} />
633 )}
634 </Layout>
635 );
636});
637
638// Single commit with diff
639web.get("/:owner/:repo/commit/:sha", async (c) => {
640 const { owner, repo, sha } = c.req.param();
06d5ffeClaude641 const user = c.get("user");
fc1817aClaude642
05b973eClaude643 // Fetch commit, full message, and diff in parallel
644 const [commit, fullMessage, diffResult] = await Promise.all([
645 getCommit(owner, repo, sha),
646 getCommitFullMessage(owner, repo, sha),
647 getDiff(owner, repo, sha),
648 ]);
fc1817aClaude649 if (!commit) {
650 return c.html(
06d5ffeClaude651 <Layout title="Not Found" user={user}>
fc1817aClaude652 <div class="empty-state">
653 <h2>Commit not found</h2>
654 </div>
655 </Layout>,
656 404
657 );
658 }
659
05b973eClaude660 const { files, raw } = diffResult;
fc1817aClaude661
662 return c.html(
06d5ffeClaude663 <Layout title={`${commit.message} — ${owner}/${repo}`} user={user}>
fc1817aClaude664 <RepoHeader owner={owner} repo={repo} />
665 <div
666 style="background: var(--bg-secondary); border: 1px solid var(--border); border-radius: var(--radius); padding: 16px; margin-bottom: 20px"
667 >
668 <div style="font-size: 18px; font-weight: 600; margin-bottom: 8px">
669 {commit.message}
670 </div>
671 {fullMessage !== commit.message && (
672 <div style="white-space: pre-wrap; color: var(--text-muted); font-size: 14px; margin-bottom: 12px">
673 {fullMessage}
674 </div>
675 )}
676 <div style="font-size: 13px; color: var(--text-muted)">
677 <strong style="color: var(--text)">{commit.author}</strong>{" "}
678 committed on{" "}
679 {new Date(commit.date).toLocaleDateString("en-US", {
680 month: "long",
681 day: "numeric",
682 year: "numeric",
683 })}
684 </div>
685 <div style="margin-top: 8px">
686 <span class="commit-sha">{commit.sha}</span>
687 {commit.parentShas.length > 0 && (
688 <span style="margin-left: 12px; font-size: 13px; color: var(--text-muted)">
689 Parent:{" "}
690 {commit.parentShas.map((p) => (
691 <a
692 href={`/${owner}/${repo}/commit/${p}`}
693 class="commit-sha"
694 style="margin-left: 4px"
695 >
696 {p.slice(0, 7)}
697 </a>
698 ))}
699 </span>
700 )}
701 </div>
702 </div>
703 <DiffView raw={raw} files={files} />
704 </Layout>
705 );
706});
707
79136bbClaude708// Raw file download
709web.get("/:owner/:repo/raw/:ref{.+$}", async (c) => {
710 const { owner, repo } = c.req.param();
711 const refAndPath = c.req.param("ref");
712
713 const branches = await listBranches(owner, repo);
714 let ref = "";
715 let filePath = "";
716
717 for (const branch of branches) {
718 if (refAndPath.startsWith(branch + "/")) {
719 ref = branch;
720 filePath = refAndPath.slice(branch.length + 1);
721 break;
722 }
723 }
724
725 if (!ref) {
726 const slashIdx = refAndPath.indexOf("/");
727 if (slashIdx === -1) return c.text("Not found", 404);
728 ref = refAndPath.slice(0, slashIdx);
729 filePath = refAndPath.slice(slashIdx + 1);
730 }
731
732 const data = await getRawBlob(owner, repo, ref, filePath);
733 if (!data) return c.text("Not found", 404);
734
735 const fileName = filePath.split("/").pop() || "file";
736 return new Response(data, {
737 headers: {
738 "Content-Type": "application/octet-stream",
739 "Content-Disposition": `attachment; filename="${fileName}"`,
05b973eClaude740 "Cache-Control": "public, max-age=300, stale-while-revalidate=60",
79136bbClaude741 },
742 });
743});
744
745// Blame view
746web.get("/:owner/:repo/blame/:ref{.+$}", async (c) => {
747 const { owner, repo } = c.req.param();
748 const user = c.get("user");
749 const refAndPath = c.req.param("ref");
750
751 const branches = await listBranches(owner, repo);
752 let ref = "";
753 let filePath = "";
754
755 for (const branch of branches) {
756 if (refAndPath.startsWith(branch + "/")) {
757 ref = branch;
758 filePath = refAndPath.slice(branch.length + 1);
759 break;
760 }
761 }
762
763 if (!ref) {
764 const slashIdx = refAndPath.indexOf("/");
765 if (slashIdx === -1) return c.text("Not found", 404);
766 ref = refAndPath.slice(0, slashIdx);
767 filePath = refAndPath.slice(slashIdx + 1);
768 }
769
770 const blameLines = await getBlame(owner, repo, ref, filePath);
771 if (blameLines.length === 0) {
772 return c.html(
773 <Layout title="Not Found" user={user}>
774 <div class="empty-state">
775 <h2>File not found</h2>
776 </div>
777 </Layout>,
778 404
779 );
780 }
781
782 const fileName = filePath.split("/").pop() || filePath;
783
784 return c.html(
785 <Layout title={`Blame: ${filePath} — ${owner}/${repo}`} user={user}>
786 <RepoHeader owner={owner} repo={repo} />
787 <RepoNav owner={owner} repo={repo} active="code" />
788 <Breadcrumb owner={owner} repo={repo} ref={ref} path={filePath} />
789 <div class="blob-view">
790 <div class="blob-header">
791 <span>{fileName} — blame</span>
792 <a href={`/${owner}/${repo}/blob/${ref}/${filePath}`} style="font-size: 12px">
793 Normal view
794 </a>
795 </div>
796 <div class="blob-code" style="overflow-x: auto">
797 <table style="width: 100%; border-collapse: collapse; font-size: 13px; font-family: var(--font-mono)">
798 <tbody>
799 {blameLines.map((line, i) => {
800 const showInfo =
801 i === 0 || blameLines[i - 1].sha !== line.sha;
802 return (
803 <tr style="border-bottom: 1px solid var(--border)">
804 <td
805 style={`width: 200px; padding: 0 8px; font-size: 11px; color: var(--text-muted); white-space: nowrap; vertical-align: top; ${showInfo ? "border-top: 1px solid var(--border)" : ""}`}
806 >
807 {showInfo && (
808 <>
809 <a
810 href={`/${owner}/${repo}/commit/${line.sha}`}
811 style="color: var(--text-link); font-family: var(--font-mono)"
812 >
813 {line.sha.slice(0, 7)}
814 </a>{" "}
815 <span>{line.author}</span>
816 </>
817 )}
818 </td>
819 <td class="line-num">{line.lineNum}</td>
820 <td class="line-content">{line.content}</td>
821 </tr>
822 );
823 })}
824 </tbody>
825 </table>
826 </div>
827 </div>
828 </Layout>
829 );
830});
831
832// Search
833web.get("/:owner/:repo/search", async (c) => {
834 const { owner, repo } = c.req.param();
835 const user = c.get("user");
836 const q = c.req.query("q") || "";
837
838 if (!(await repoExists(owner, repo))) return c.notFound();
839
840 const defaultBranch = (await getDefaultBranch(owner, repo)) || "main";
841 let results: Array<{ file: string; lineNum: number; line: string }> = [];
842
843 if (q.trim()) {
844 results = await searchCode(owner, repo, defaultBranch, q.trim());
845 }
846
847 return c.html(
848 <Layout title={`Search — ${owner}/${repo}`} user={user}>
849 <RepoHeader owner={owner} repo={repo} />
850 <RepoNav owner={owner} repo={repo} active="code" />
851 <form
852 method="GET"
853 action={`/${owner}/${repo}/search`}
854 style="margin-bottom: 20px"
855 >
856 <div style="display: flex; gap: 8px">
857 <input
858 type="text"
859 name="q"
860 value={q}
861 placeholder="Search code..."
862 style="flex: 1; padding: 8px 12px; background: var(--bg); border: 1px solid var(--border); border-radius: var(--radius); color: var(--text); font-size: 14px"
863 />
864 <button type="submit" class="btn btn-primary">
865 Search
866 </button>
867 </div>
868 </form>
869 {q && (
870 <p style="font-size: 14px; color: var(--text-muted); margin-bottom: 16px">
871 {results.length} result{results.length !== 1 ? "s" : ""} for{" "}
872 <strong style="color: var(--text)">"{q}"</strong>
873 </p>
874 )}
875 {results.length > 0 && (
876 <div class="search-results">
877 {(() => {
878 // Group by file
879 const grouped: Record<
880 string,
881 Array<{ lineNum: number; line: string }>
882 > = {};
883 for (const r of results) {
884 if (!grouped[r.file]) grouped[r.file] = [];
885 grouped[r.file].push({ lineNum: r.lineNum, line: r.line });
886 }
887 return Object.entries(grouped).map(([file, matches]) => (
888 <div class="diff-file" style="margin-bottom: 12px">
889 <div class="diff-file-header">
890 <a
891 href={`/${owner}/${repo}/blob/${defaultBranch}/${file}`}
892 >
893 {file}
894 </a>
895 </div>
896 <div class="blob-code">
897 <table>
898 <tbody>
899 {matches.map((m) => (
900 <tr>
901 <td class="line-num">{m.lineNum}</td>
902 <td class="line-content">{m.line}</td>
903 </tr>
904 ))}
905 </tbody>
906 </table>
907 </div>
908 </div>
909 ));
910 })()}
911 </div>
912 )}
913 </Layout>
914 );
915});
916
fc1817aClaude917export default web;