git / pages.tsmain at 517348b
// pages.ts — THE PAGES A PERSON READS A REPO WITH, as plain HTML. app.ts says who may read and
// calls one function here for each page. Each one reads the repo through the mind's own `itx`
// and is whole with no script: the names, the lists, a file's text, a pull's conversation.
// public/page.js then draws in their places what wants a script: the file tree, a file or a diff
// with its colours, markdown, and for a member the boxes that write (a comment, a pull, a merge).
//
// WHAT A PULL IS, and where its events are, is pulls.ts; what a release is, releases.ts. A page
// here only reads.
//
// THE DIFFERENCE BETWEEN TWO COMMITS COSTS TWO READS OF A WHOLE TREE: a repo answers with files,
// never with changes. Two commits never change, so the app keeps what it worked out in the
// mind's kv, and the next reader costs one kv read.
//
// Only `main` and the branches of open pulls are shown, and a file as text. A page shows people
// by the name before the `@` of their address, and no address.
//
// A MEMBER EDITS A FILE on `/repos/<name>/edit/main/<path>`, GitHub's address for it: the file's
// text in a box, and under it the box that commits. The page here only reads, as every page: the
// commit is the member's own, made by the script (public/page.js says how, for main and for a
// new branch with a pull).
import type { RepoLogEntry } from "iterate/api";
import type { IterateConfigEntrypoint } from "iterate/sdk";
import { z } from "zod";
import { plainDiff } from "./plain-diff.ts";
import { type LinePlace, type Pull, pullsIn, type Standing, standingOf } from "./pulls.ts";
import { type Release, type Remote, releasesIn } from "./releases.ts";
type Host = Pick<IterateConfigEntrypoint, "getItx" | "auth">;
export type Itx = ReturnType<Host["getItx"]>;
export type Repo = ReturnType<Itx["repos"]["get"]>;
/** What every page of a repo is drawn with: the request's address, the repo's path, whether
* anyone may read it, and `me`: the member who asks, as a page shows them. `me` is null for
* anyone else, who reads and writes nothing. */
export type View = { url: URL; repo: string; isPublic: boolean; me: string | null };
/** A repo's pages: its name, then what of it. */
export const PAGE_PATH =
/^\/repos\/([A-Za-z0-9._-]+)(?:\/(tree|edit|commits|commit|branches|releases|pulls|pull|compare)(?:\/(.*))?)?$/;
/** How many commits the list shows, and how far back a short oid is looked for. */
const COMMITS_SHOWN = 100;
const COMMITS_SEARCHED = 300;
/** The most text a page of diffs carries, both sides of every file together. The files past it
* are named with no diff. */
const DIFF_CHARACTERS_SHOWN = 600_000;
/** The largest file that the edit page offers, in characters: a box in a page holds no more well. */
const EDIT_CHARACTERS = 1_000_000;
/** One file that differs between two commits. `sides` is its text before and after; null when
* the page shows no diff, and `note` says why. */
const Change = z.object({
path: z.string(),
status: z.enum(["added", "deleted", "modified"]),
sides: z.object({ before: z.string(), after: z.string() }).nullable(),
note: z.string().nullable(),
});
type Change = z.infer<typeof Change>;
/** What the app keeps of a commit, under `git-app:commit:<repo>:<oid>`: what its page shows. */
const KeptCommit = z.object({
oid: z.string(),
parents: z.array(z.string()),
message: z.string(),
author: z.string(),
timestamp: z.number(),
changes: z.array(Change),
});
type KeptCommit = z.infer<typeof KeptCommit>;
// ── THE REPOS, A REPO'S FILES, ITS COMMITS ──
/** `/`: the repos, each with the command that clones it. Anyone sees the public ones, with no
* question to the mind. A member sees every repo. */
export async function reposPage(
request: Request,
url: URL,
host: Host,
publicRepos: string[],
): Promise<Response> {
const isMember = host.auth.require(request) === null;
let repos = publicRepos;
if (isMember) {
using itx = host.getItx();
const all = (await itx.repos.list()).map(({ path }) => path);
repos = all.filter((path) => PAGE_PATH.test(path)).sort();
}
const rows = repos.map((repo) => {
const tag = publicRepos.includes(repo) ? "" : ` <span class="tag">private</span>`;
return `<li><a href="${esc(repo)}"><b>${esc(nameOf(repo))}</b></a>${tag} <code class="clone">git clone ${esc(url.origin + repo)}</code></li>`;
});
const signIn = isMember
? ""
: `<p class="note"><a href="/sign-in">Sign in</a> to see the repos that are not public.</p>`;
const zone = zoneOf(url);
const main = `<h1>The repos of ${esc(zone)}</h1><ul class="repos">${rows.join("")}</ul>${signIn}`;
const view = { url, repo: null, isPublic: true, me: isMember ? "member" : null };
return page(view, 200, null, `The repos of ${zone}`, main, {});
}
/** A folder of the repo at `main`, with its README, or a file. The file tree stands beside it. */
export async function codePage(view: View, handle: Repo, path: string, plain: boolean) {
const { repo } = view;
const { commitOid, paths } = await handle.listFiles();
if (!commitOid)
return page(view, 200, "code", nameOf(repo), note("This repo has no commit yet."), {});
const isFile = paths.includes(path);
const under = path ? `${path}/` : "";
const within = paths.filter((file) => file.startsWith(under));
if (!isFile && within.length === 0) {
const missing = note(`${nameOf(repo)} has no file or folder ${path} on main.`);
return page(view, 404, "code", "Not found", missing, {});
}
// the way here: the repo, each folder above, then this file or folder
const segments = path ? path.split("/") : [];
const crumbs = segments.map((segment, index) =>
index === segments.length - 1
? `<b>${esc(segment)}</b>`
: `<a href="${treeHref(repo, segments.slice(0, index + 1).join("/"))}">${esc(segment)}</a>`,
);
const top = `<a href="${esc(repo)}">${esc(nameOf(repo))}</a>`;
const at = `<span class="at">main at <a href="${esc(repo)}/commit/${commitOid}"><code>${commitOid.slice(0, 7)}</code></a></span>`;
const file = isFile ? await fileContent(view, handle, path, plain) : null;
// a file's actions stand on the row of its name, at the right, and take no row of their own
const way = `<p class="crumbs">${[top, ...crumbs].join(" / ")}${at}${file?.acts || ""}</p>`;
const content = file ? file.body : await folderContent(view, handle, under, within);
const main = `<div class="code"><nav id="tree" aria-label="Files"></nav><div id="content">${way}${content}</div></div>`;
const title = path ? `${path} · ${nameOf(repo)}` : nameOf(repo);
return page(view, 200, "code", title, main, { paths, path });
}
/** The folder's own entries, folders first, and its README under them. */
async function folderContent(view: View, handle: Repo, under: string, within: string[]) {
const folders = new Set<string>();
const files: string[] = [];
for (const file of within) {
const rest = file.slice(under.length);
const slash = rest.indexOf("/");
if (slash < 0) files.push(rest);
else folders.add(rest.slice(0, slash));
}
const row = (name: string, shown: string) =>
`<li><a href="${treeHref(view.repo, under + name)}">${esc(shown)}</a></li>`;
const entries = [
...[...folders].sort().map((name) => row(name, `${name}/`)),
...files.sort().map((name) => row(name, name)),
];
const readme = files.find((name) => /^readme(\.(md|markdown|txt))?$/i.test(name));
const text = readme ? await handle.readFile(under + readme) : null;
const shown =
readme && text !== null
? `<article class="readme"><h2>${esc(readme)}</h2>${fileText(under + readme, text, false)}</article>`
: "";
return `<ul class="entries">${entries.join("")}</ul>${shown}`;
}
/** The file's text, and its actions for the row of its name: each an icon that is a link, with
* its name for a reader that sees no icon. A markdown file is shown as it reads, and `?plain`
* shows its source. */
async function fileContent(view: View, handle: Repo, path: string, plain: boolean) {
let text: string | null;
try {
text = await handle.readFile(path);
} catch (error) {
// the repo's own refusal of a file that is not text (an image, a font)
if (/is not text/.test(error instanceof Error ? error.message : "")) text = null;
else throw error;
}
if (text === null)
return { acts: "", body: note("This file is not text, so it is not shown. A clone has it.") };
const here = treeHref(view.repo, path);
const other = isMarkdown(path)
? plain
? `<a href="${here}" title="As it reads" aria-label="As it reads">${EYE}</a>`
: `<a href="${here}?plain" title="Its source" aria-label="Its source">${CODE}</a>`
: "";
// the pencil, for a member: GitHub's address for the page that edits this file
const pencil = view.me
? `<a class="pencil" href="${editHref(view.repo, path)}" title="Edit this file" aria-label="Edit this file">${PENCIL}</a>`
: "";
const acts = other || pencil ? `<span class="acts">${other}${pencil}</span>` : "";
return { acts, body: fileText(path, text, plain) };
}
/** `/repos/<name>/edit/main/<path>`, for a member: the file's text in a box that the member
* changes, and the place where the script draws the box that commits. `email` is the member's
* address, which a commit on a new branch names as its author; the page shows it to nobody else. */
export async function editPage(view: View, handle: Repo, rest: string, email: string | null) {
const { repo } = view;
const [branch, ...segments] = rest.split("/");
if (branch !== "main")
return page(view, 404, "code", "Not found", note("Only main is edited here."), {});
const path = segments.filter(Boolean).map(decodeURIComponent).join("/");
const { commitOid, paths } = await handle.listFiles();
if (!commitOid || !paths.includes(path)) {
const missing = note(`${nameOf(repo)} has no file ${path} on main.`);
return page(view, 404, "code", "Not found", missing, {});
}
let text: string | null;
try {
text = await handle.readFile(path, { commitOid });
} catch (error) {
if (/is not text/.test(error instanceof Error ? error.message : "")) text = null;
else throw error;
}
const file = `<a href="${treeHref(repo, path)}">${esc(path)}</a>`;
const title = `Edit ${path} · ${nameOf(repo)}`;
// A box in a page reads every line ending as a line feed. A file that ends every line with
// CR LF gets them back at the commit; one that mixes the two would be changed whole.
const lineFeeds = text === null ? 0 : text.split("\n").length - 1;
const returns = text === null ? 0 : text.split("\r").length - 1;
const crlf = returns > 0 && returns === lineFeeds && returns === text!.split("\r\n").length - 1;
const refusal =
text === null
? "This file is not text, so it is not edited here. Change it in a clone."
: text.length > EDIT_CHARACTERS
? "This file is too large to edit here. Change it in a clone."
: returns > 0 && !crlf
? "This file mixes line endings, so it is not edited here. Change it in a clone."
: null;
const at = `<span class="at">main at <a href="${esc(repo)}/commit/${commitOid}"><code>${commitOid.slice(0, 7)}</code></a></span>`;
const head = `<p class="crumbs">Edit ${file}${at}</p>`;
if (refusal !== null || text === null)
return page(view, 200, "code", title, `<article class="edit">${head}${note(refusal || "")}</article>`, {});
const shown = crlf ? text.replace(/\r\n/g, "\n") : text;
const main = [
`<article class="edit">${head}`,
// a line break right after the tag is not part of a textarea's text: the file's own first
// line break would be lost without it
`<textarea id="edit-text" spellcheck="false" autocapitalize="off" autocomplete="off" aria-label="${esc(path)}">\n${esc(shown)}</textarea>`,
`<div id="commit"><p class="note">The box that commits is drawn by this page's script.</p></div></article>`,
].join("");
// a name for the branch that no branch has yet: the member's name, then the file's
const taken = new Set((await handle.branches()).map(({ name }) => name));
const slug = (words: string) => words.replace(/[^A-Za-z0-9]+/g, "-").replace(/^-+|-+$/g, "").toLowerCase();
const stem = `${slug(view.me || "") || "member"}/edit-${slug(path.split("/").at(-1)!) || "file"}`;
let suggested = stem;
for (let count = 2; taken.has(suggested); count += 1) suggested = `${stem}-${count}`;
const edit = {
path,
commitOid,
crlf,
branch: suggested,
// as a squash names a pull's author (pulls.ts): the name before the `@`, and the address
author: email ? { name: view.me || email, email } : null,
};
return page(view, 200, "code", title, main, { edit });
}
/** A file's text as a `<pre>`, marked for the script: `data-markdown` is drawn as markdown (its
* links are read against `data-dir`, the file's folder), `data-file` with the file's colours. */
function fileText(path: string, text: string, plain: boolean) {
const dir = path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : "";
const mark =
isMarkdown(path) && !plain ? `data-markdown data-dir="${esc(dir)}"` : `data-file="${esc(path)}"`;
return `<pre ${mark}>${esc(text)}</pre>`;
}
/** The newest commits on `main`: each one's oid, the first line of its message, who and when. */
export async function commitsPage(view: View, handle: Repo) {
const commits = await handle.log({ limit: COMMITS_SHOWN });
const more = commits.length === COMMITS_SHOWN ? note(`The newest ${COMMITS_SHOWN} commits.`) : "";
const list = commits.length ? commitRows(view, commits) : note("No commit yet.");
const main = `<h1>Commits on main</h1>${list}${more}`;
return page(view, 200, "commits", `Commits · ${nameOf(view.repo)}`, main, {});
}
/** Commits as a list, newest first: each one's oid, the first line of its message, who and when. */
function commitRows(view: View, commits: RepoLogEntry[]) {
const rows = commits.map(
(commit) =>
`<li><a href="${esc(view.repo)}/commit/${commit.oid}"><code>${commit.oid.slice(0, 7)}</code></a> ${esc(subjectOf(commit.message))} <span class="by">${esc(commit.author.name)}, ${utcStamp(commit.timestamp)}</span></li>`,
);
return `<ul class="commits">${rows.join("")}</ul>`;
}
/** One commit: its message, and each file it changed against its first parent, as a diff that
* folds away under the file's name. */
export async function commitPage(view: View, handle: Repo, itx: Itx, wanted: string) {
const { repo } = view;
if (!/^[0-9a-f]{7,40}$/.test(wanted))
return page(view, 404, "commits", "Not found", note("That is no commit's oid."), {});
// A commit never changes, so what the app worked out of it is kept under its whole oid. A
// whole oid names a commit on any branch; a shorter one is looked for on main.
const whole = wanted.length === 40;
const keptOf = async (oid: string) => {
const text = await itx.kv.get(`git-app:commit:${repo}:${oid}`);
return text ? KeptCommit.parse(JSON.parse(text)) : null;
};
let commit = whole ? await keptOf(wanted) : null;
if (!commit) {
const found = whole
? await commitAt(handle, wanted)
: (await handle.log({ limit: COMMITS_SEARCHED })).find(({ oid }) => oid.startsWith(wanted));
if (!found) {
const where = whole ? "" : ` among the newest ${COMMITS_SEARCHED} of main`;
const missing = note(`${nameOf(repo)} has no commit ${wanted}${where}.`);
return page(view, 404, "commits", "Not found", missing, {});
}
commit = whole ? null : await keptOf(found.oid);
if (!commit) {
commit = {
oid: found.oid,
parents: found.parents,
message: found.message,
author: found.author.name,
timestamp: found.timestamp,
changes: await changesOf(handle, found.parents[0] || null, found.oid),
};
await itx.kv.put(`git-app:commit:${repo}:${commit.oid}`, JSON.stringify(commit));
}
}
const [subject, ...rest] = commit.message.trim().split("\n");
const body = rest.join("\n").trim();
const parents = commit.parents.map(
(oid) => `<a href="${esc(repo)}/commit/${oid}"><code>${oid.slice(0, 7)}</code></a>`,
);
const from =
parents.length === 0
? "the first commit"
: parents.length === 1
? `parent ${parents[0]}`
: `a merge of ${parents.join(" and ")}, shown against ${parents[0]}`;
const main = [
`<article class="commit"><h1>${esc(subject || "")}</h1>`,
body ? `<pre class="message">${esc(body)}</pre>` : "",
`<p class="by">${esc(commit.author)}, ${utcStamp(commit.timestamp)} · <code>${commit.oid}</code> · ${from}</p>`,
`${filesHtml(commit.changes)}</article>`,
].join("");
const title = `${subject} · ${nameOf(repo)}`;
return page(view, 200, "commits", title, main, { diffs: diffsOf(commit.changes) });
}
/** One commit by its whole oid, on any branch; undefined when the repo has no such commit. */
async function commitAt(handle: Repo, oid: string) {
try {
return (await handle.log({ limit: 1, from: oid }))[0];
} catch (error) {
// git's own words for an oid that names nothing here; any other failure is a failure
const words = error instanceof Error ? error.message : String(error);
if (/not our ref|bad object|unknown revision|not a valid object|upload-pack/i.test(words))
return undefined;
throw error;
}
}
// ── PULLS ──
/** The repo's releases, newest first: each one's tag, the commit it stands on, who cut it and
* when, and its notes. A release is a tag of git (releases.ts), so the page says how git gets
* one. `remote` is where the tags are read, with the app's kept read token (app.ts): anyone may
* ask for a public repo's page, and a page mints nothing of its own. */
export async function releasesPage(view: View, itx: Itx, remote: Remote) {
const { repo, url } = view;
const releases = await releasesIn(itx, repo, remote);
const row = (release: Release) => {
const commit = `<a href="${esc(repo)}/commit/${release.commitOid}"><code>${release.commitOid.slice(0, 7)}</code></a>`;
const cut = release.at
? `, cut${release.by ? ` by ${esc(release.by)}` : ""}, ${utcStamp(Date.parse(release.at))}`
: ", a tag with no release notes";
const notes = release.notes ? `<pre class="notes">${esc(release.notes)}</pre>` : "";
return `<li id="${esc(release.tag)}"><b>${esc(release.tag)}</b> <span class="by">at ${commit}${cut}</span>${notes}</li>`;
};
const newest = releases[0];
const main = [
`<h1>Releases</h1>`,
newest
? `<ul class="releases">${releases.map(row).join("")}</ul>`
: note("No release yet."),
`<p class="note">A release is a tag of git on a commit of main. To see the tags: <code>git ls-remote --tags ${esc(url.origin + repo)}</code>${
newest
? `. To get one: <code>git clone --branch ${esc(newest.tag)} ${esc(url.origin + repo)}</code>`
: ""
}</p>`,
].join("");
return page(view, 200, "releases", `Releases · ${nameOf(repo)}`, main, {});
}
/** The repo's pulls: the open ones, then the ones that are merged or closed. */
export async function pullsPage(view: View, handle: Repo, itx: Itx) {
const { repo } = view;
const pulls = (await pullsIn(itx, repo)).toReversed();
const row = (pull: Pull) => {
const comments = pull.threads.reduce((count, thread) => count + thread.comments.length, 0);
const said = comments ? `, ${comments} comment${comments === 1 ? "" : "s"}` : "";
const status = pull.status === "open" ? "" : `, ${pull.status}`;
return `<li><a href="${esc(repo)}/pull/${pull.number}">${esc(pull.title)}</a> <span class="by">#${pull.number}${status}, <code>${esc(pull.branch)}</code>, ${esc(pull.by)}, ${utcStamp(Date.parse(pull.openedAt))}${said}</span></li>`;
};
const open = pulls.filter((pull) => pull.status === "open");
const done = pulls.filter((pull) => pull.status !== "open");
const main = [
`<h1>Pulls</h1>`,
open.length ? `<ul class="pulls">${open.map(row).join("")}</ul>` : note("No pull is open."),
done.length
? `<details class="done"><summary>Merged and closed (${done.length})</summary><ul class="pulls">${done.map(row).join("")}</ul></details>`
: "",
`<p class="note">To propose a change: push a branch, then open it from <a href="${esc(repo)}/branches">Branches</a>.</p>`,
].join("");
return page(view, 200, "pulls", `Pulls · ${nameOf(repo)}`, main, {});
}
/** The repo's branches, main first. Main is what the mind runs. Any other is somebody's
* proposal: its row has the pull that it is, or the page that compares it with main. */
export async function branchesPage(view: View, handle: Repo, itx: Itx) {
const { repo } = view;
const branches = await handle.branches();
// the newest pull of each branch: a later one of the same branch takes the earlier one's place
const pullOf = new Map((await pullsIn(itx, repo)).map((pull) => [pull.branch, pull]));
const row = ({ name, commitOid }: { name: string; commitOid: string }) => {
const pull = pullOf.get(name);
const tip = `<a href="${esc(repo)}/commit/${commitOid}"><code>${commitOid.slice(0, 7)}</code></a>`;
// A closed pull leaves its branch free to be proposed again. A merged one does not: what
// the branch had is on main, under another commit.
const what =
name === "main"
? "what the mind runs"
: pull && pull.status !== "closed"
? `${pull.status} as <a href="${esc(repo)}/pull/${pull.number}">#${pull.number} ${esc(pull.title)}</a>`
: `<a href="${compareHref(repo, name)}">compare with main</a>`;
return `<li><code>${esc(name)}</code> <span class="by">at ${tip}, ${what}</span></li>`;
};
const rows = [
...branches.filter(({ name }) => name === "main"),
...branches.filter(({ name }) => name !== "main"),
].map(row);
const main = [
`<h1>Branches</h1>`,
rows.length ? `<ul class="branches">${rows.join("")}</ul>` : note("No branch yet."),
`<p class="note">A push to main is what the mind runs a few seconds later. A push to any other branch changes nothing that runs.</p>`,
].join("");
return page(view, 200, "branches", `Branches · ${nameOf(repo)}`, main, {});
}
/** A branch against main, before it is a pull: its commits and what it changes, and for a member
* the box that opens the pull. A branch that has an open pull goes to the pull's page. */
export async function comparePage(view: View, handle: Repo, itx: Itx, rest: string) {
const { repo, url } = view;
const branch = decodeURIComponent(rest);
const open = (await pullsIn(itx, repo)).find(
(pull) => pull.status === "open" && pull.branch === branch,
);
if (open) return Response.redirect(`${url.origin}${repo}/pull/${open.number}`, 302);
const stand = await standingOf(handle, branch);
const missing = !stand.head
? `${nameOf(repo)} has no branch ${branch}.`
: !stand.base
? `${branch} and main share no commit in the history read.`
: stand.own.length === 0
? `${branch} has nothing that main has not.`
: null;
if (missing || !stand.head)
return page(view, stand.head ? 200 : 404, "branches", "Compare", note(missing || ""), {});
const changes = await keptChanges(view, handle, itx, stand.base, stand.head);
// the branch's first commit names the pull, as a start
const [subject, ...body] = stand.own.at(-1)!.message.trim().split("\n");
const opener = view.me
? `<div id="open-pull"></div>`
: `<p class="note"><a href="${signInHref(view)}">Sign in</a> to open a pull.</p>`;
const main = [
`<article class="pull"><h1><code>${esc(branch)}</code> into <code>main</code></h1>`,
standingNote(stand, branch),
opener,
`<h2>Commits</h2>${commitRows(view, stand.own)}`,
`<h2>Files</h2>${filesHtml(changes)}</article>`,
].join("");
const data = {
compare: { branch, title: subject || branch, body: body.join("\n").trim() },
diffs: diffsOf(changes),
};
return page(view, 200, "branches", `${branch} · ${nameOf(repo)}`, main, data);
}
/** One pull: what it asks, its conversation, its commits and what it changes, with the comments
* that were made on lines. */
export async function pullPage(view: View, handle: Repo, itx: Itx, rest: string) {
const { repo } = view;
const pull = /^[1-9][0-9]*$/.test(rest)
? (await pullsIn(itx, repo)).find((pull) => pull.number === Number(rest))
: undefined;
if (!pull)
return page(view, 404, "pulls", "Not found", note(`${nameOf(repo)} has no pull #${rest}.`), {});
// WHAT THE PULL CHANGES. A merged one: the commit it became, against that commit's parent. Any
// other: its branch against where the branch stands on main, while the repo has the branch.
let stand: Standing | null = null;
let changes: Change[] = [];
if (pull.status === "merged" && pull.commitOid) {
const commit = await commitAt(handle, pull.commitOid);
if (commit)
changes = await keptChanges(view, handle, itx, commit.parents[0] || null, commit.oid);
} else {
stand = await standingOf(handle, pull.branch);
if (stand.head && stand.base)
changes = await keptChanges(view, handle, itx, stand.base, stand.head);
}
// A comment on lines stays on them while they still read as they did.
const threads = pull.threads.map((thread) => {
const now = thread.place ? lineNow(changes, thread.place) : null;
const outdated = Boolean(thread.place && now?.text !== thread.place.quote);
return { ...thread, diff: now ? now.diff : null, outdated };
});
// In the conversation a thread that is read elsewhere is folded under one line that says what
// it is: a thread on lines, which the script shows under its lines in the diff, and a resolved
// one. A thread whose lines have changed is nowhere in the diff, so it is open here.
const conversation = threads.map((thread) => {
const { place } = thread;
const comments = thread.comments
.map(
(comment) =>
`<div class="comment"><p class="by">${esc(comment.by)}, ${utcStamp(Date.parse(comment.at))}</p><pre>${esc(comment.body)}</pre></div>`,
)
.join("");
const look = `class="thread${thread.resolved ? " resolved" : ""}" id="comment-${thread.id}"`;
if (!place && !thread.resolved) return `<article ${look}>${comments}</article>`;
const first = thread.comments[0]!;
const path = place ? `<code>${esc(place.path)}</code>` : "";
const what = place
? `${thread.diff === null ? path : `<a href="#diff-${thread.diff}">${path}</a>`} ${linesOf(place)}`
: esc(`${first.by}: ${first.body.split("\n")[0]}`);
const count = `${thread.comments.length} comment${thread.comments.length === 1 ? "" : "s"}`;
const open = place && thread.outdated && !thread.resolved ? " open" : "";
const summary = `<summary class="place">${what}${thread.outdated ? ", changed since" : ""}${thread.resolved ? ", resolved" : ""} <span class="count">${count}</span></summary>`;
const quote = place ? `<code class="quote">${esc(place.quote)}</code>` : "";
return `<details ${look}${open}>${summary}${quote}${comments}</details>`;
});
// What the pull is, in one line: what it asks while it is open, and then what became of it,
// when, and by whom.
const branch = `<code>${esc(pull.branch)}</code>`;
const opened = `${esc(pull.by)} opened it ${utcStamp(Date.parse(pull.openedAt))}`;
const done = `${pull.doneBy ? ` by ${esc(pull.doneBy)}` : ""}, ${utcStamp(Date.parse(pull.doneAt || pull.openedAt))}`;
const is =
pull.status === "open"
? `${esc(pull.by)} wants ${branch} squashed into <code>main</code>, ${utcStamp(Date.parse(pull.openedAt))}`
: pull.status === "merged"
? `${branch} was squashed into <code>main</code> as <a href="${esc(repo)}/commit/${pull.commitOid}"><code>${(pull.commitOid || "").slice(0, 7)}</code></a>${done}. ${opened}.`
: `${branch} was closed without merging${done}. ${opened}.`;
const standing =
pull.status !== "open" || !stand
? ""
: !stand.head
? note(`The branch ${pull.branch} is gone.`)
: standingNote(stand, pull.branch);
const writes = view.me
? `<div id="merge"></div>`
: `<p class="note"><a href="${signInHref(view)}">Sign in</a> to comment or to merge.</p>`;
const main = [
`<article class="pull"><h1>${esc(pull.title)} <span class="by">#${pull.number}</span></h1>`,
`<p class="by"><span class="tag ${pull.status}">${pull.status}</span> ${is}</p>`,
pull.body.trim() ? `<div class="body"><pre data-markdown data-dir="">${esc(pull.body)}</pre></div>` : "",
standing,
`<h2>Conversation</h2><section id="conversation">${conversation.join("") || note("Nobody has said anything yet.")}</section>`,
writes,
stand && stand.own.length ? `<h2>Commits</h2>${commitRows(view, stand.own)}` : "",
`<h2>Files</h2>${filesHtml(changes)}</article>`,
].join("");
const data = {
pull: { number: pull.number, title: pull.title, branch: pull.branch, status: pull.status },
// what a squash asks for: the branch has main's newest commit, and changes something
mergeable: Boolean(stand?.upToDate && changes.length),
threads,
diffs: diffsOf(changes),
};
return page(view, 200, "pulls", `${pull.title} #${pull.number} · ${nameOf(repo)}`, main, data);
}
/** How a branch stands on main, in words: what it adds, and whether main has moved past what
* the branch has, which stops a squash. */
function standingNote(stand: Standing, branch: string) {
const adds = `${stand.own.length} commit${stand.own.length === 1 ? "" : "s"}`;
const moved = stand.upToDate
? ""
: note(`main has moved since ${branch} last had it. To merge: merge main into ${branch}, and push.`);
return `<p class="by"><code>${esc(branch)}</code> adds ${adds} to <code>main</code>.</p>${moved}`;
}
/** The text now on the lines a comment was made on, and which file of the page they are in;
* null when the page shows no such file. */
function lineNow(changes: Change[], place: LinePlace) {
const diff = changes.findIndex(({ path }) => path === place.path);
const sides = diff < 0 ? null : changes[diff]!.sides;
if (!sides) return null;
const lines = (place.side === "additions" ? sides.after : sides.before).split("\n");
return { diff, text: lines.slice(place.line - 1, place.endLine).join("\n") };
}
// ── THE DIFFERENCE BETWEEN TWO COMMITS ──
/** The files that differ between two commits, kept in the mind's kv under
* `git-app:changes:<repo>:<before>:<after>`: neither commit ever changes. */
async function keptChanges(
view: View,
handle: Repo,
itx: Itx,
before: string | null,
after: string,
): Promise<Change[]> {
const key = `git-app:changes:${view.repo}:${before || "nothing"}:${after}`;
const kept = await itx.kv.get(key);
if (kept) return z.array(Change).parse(JSON.parse(kept));
const changes = await changesOf(handle, before, after);
await itx.kv.put(key, JSON.stringify(changes));
return changes;
}
/** The files that differ between the commit `beforeOid` (null: no files) and `afterOid`, each
* with both texts while the page has room for them. */
async function changesOf(handle: Repo, beforeOid: string | null, afterOid: string) {
// The older one first: a repo holds the files of the commit it read last, and the newer one
// is the likelier next read.
const before = beforeOid ? await handle.files({ commitOid: beforeOid }) : {};
const after = await handle.files({ commitOid: afterOid });
let room = DIFF_CHARACTERS_SHOWN;
const changes: Change[] = [];
for (const path of Object.keys({ ...before, ...after }).sort()) {
const was = Object.hasOwn(before, path) ? before[path]! : null;
const is = Object.hasOwn(after, path) ? after[path]! : null;
// a file that is not text comes as `{ base64 }`: the same bytes are the same file
const same =
typeof was === "string" || typeof is === "string"
? was === is
: was !== null && is !== null && was.base64 === is.base64;
if (same) continue;
const status = was === null ? "added" : is === null ? "deleted" : "modified";
if ((was !== null && typeof was !== "string") || (is !== null && typeof is !== "string")) {
changes.push({ path, status, sides: null, note: "Not text, so no diff is shown." });
continue;
}
const sides = { before: was || "", after: is || "" };
const characters = sides.before.length + sides.after.length;
if (characters > room) {
const large = "Not shown: the change is larger than this page shows. A clone has it.";
changes.push({ path, status, sides: null, note: large });
continue;
}
room -= characters;
changes.push({ path, status, sides, note: null });
}
return changes;
}
/** A diff as plain text, which needs no script: the lines that went and came, as `git diff`
* shows them. It is what a reader sees until the script has drawn the diff, and all that a
* reader sees when the script did not load. */
function plainHtml(sides: { before: string; after: string }) {
const look = { " ": "", "-": ` class="went"`, "+": ` class="came"`, "@": ` class="part"` };
const lines = plainDiff(sides.before, sides.after).map(
({ kind, text }) => `<span${look[kind]}>${esc(kind === "@" ? text : kind + text)}</span>`,
);
return `<pre class="plain">${lines.join("\n")}</pre>`;
}
/** The files that changed: how many, their names, then each one under a name that folds it. Each
* diff is there as plain text; the script draws it again in its `data-diff`, from the two texts
* (`diffsOf`), and then takes the plain text away. */
function filesHtml(changes: Change[]) {
const letter = { added: "A", deleted: "D", modified: "M" };
const names = changes.map(
(change, index) =>
`<li><span class="status ${change.status}">${letter[change.status]}</span> <a href="#diff-${index}">${esc(change.path)}</a></li>`,
);
const diffs = changes.map((change, index) => {
const shown = change.sides
? `<div class="diff" data-diff="${index}">${plainHtml(change.sides)}</div>`
: note(change.note || "");
// each file folds: the reader closes the ones they have read
return `<details class="changed" id="diff-${index}" open><summary><span class="status ${change.status}">${letter[change.status]}</span> ${esc(change.path)}</summary>${shown}</details>`;
});
const count = `${changes.length} file${changes.length === 1 ? "" : "s"} changed`;
return `<p>${count}</p><ul class="changes">${names.join("")}</ul>${diffs.join("")}`;
}
/** What the script draws the page's diffs from: each file's path and its two texts, or null
* where the page shows no diff. */
const diffsOf = (changes: Change[]) =>
changes.map(({ path, sides }) => (sides ? { path, ...sides } : null));
// ── WHAT EVERY PAGE IS MADE OF ──
/** One page: the head, the row that says where the reader is, `main`, and `data`, what the
* script draws from (with the repo's path and the member's name beside it). `tab` is the row's
* link that is marked as the one shown. */
export function page(
view: { url: URL; repo: string | null; isPublic: boolean; me: string | null },
status: number,
tab: "code" | "commits" | "branches" | "releases" | "pulls" | null,
title: string,
main: string,
data: Record<string, unknown>,
): Response {
const { url, repo } = view;
const zone = zoneOf(url);
const current = (name: string) => (tab === name ? ` aria-current="page"` : "");
const where = repo
? [
`<p><a href="/">${esc(zone)}</a> / <a href="${esc(repo)}"><b>${esc(nameOf(repo))}</b></a>`,
view.isPublic ? "" : ` <span class="tag">private</span>`,
`</p><nav><a href="${esc(repo)}"${current("code")}>Code</a>`,
`<a href="${esc(repo)}/commits"${current("commits")}>Commits</a>`,
`<a href="${esc(repo)}/branches"${current("branches")}>Branches</a>`,
`<a href="${esc(repo)}/releases"${current("releases")}>Releases</a>`,
`<a href="${esc(repo)}/pulls"${current("pulls")}>Pulls</a></nav>`,
`<code class="clone">git clone ${esc(url.origin + repo)}</code>`,
].join("")
: `<p><a href="/">${esc(zone)}</a></p>`;
const forScript = JSON.stringify({ repo, me: view.me, ...data }).replace(/</g, "\\u003c");
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>${esc(title)} · ${esc(zone)}</title>
<link rel="icon" href="/icon.svg" type="image/svg+xml" />
<link rel="preconnect" href="https://esm-sh.iterate.com" crossorigin />
<script type="importmap">${IMPORT_MAP}</script>
<link rel="stylesheet" crossorigin href="${UI}/dist/styles.css" />
<link rel="stylesheet" href="/theme.css" />
<script>
if (getComputedStyle(document.documentElement).colorScheme === "dark")
document.documentElement.classList.add("dark");
</script>
<link rel="stylesheet" href="/page.css" />
</head>
<body>
<header class="where">${where}</header>
<main>${main}</main>
<script type="application/json" id="data">${forScript}</script>
<script type="module" src="/page.js" onerror="document.documentElement.classList.add('unloaded')"></script>
</body>
</html>
`;
return new Response(html, {
status,
headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache" },
});
}
const ESCAPES: Record<string, string> = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
const esc = (text: string) => text.replace(/[&<>"']/g, (character) => ESCAPES[character]!);
export const note = (text: string) => `<p class="note">${esc(text)}</p>`;
export const nameOf = (repo: string) => repo.slice("/repos/".length);
/** The zone the app is on: its hostname is one label under it. */
const zoneOf = (url: URL) => url.hostname.split(".").slice(1).join(".");
const isMarkdown = (path: string) => /\.(md|markdown)$/i.test(path);
const subjectOf = (message: string) => message.trim().split("\n")[0] || "";
/** The page of a file or a folder; the repo's own page for its root. */
const treeHref = (repo: string, path: string) =>
esc(path ? `${repo}/tree/main/${path.split("/").map(encodeURIComponent).join("/")}` : repo);
/** The page that edits a file of main. */
const editHref = (repo: string, path: string) =>
esc(`${repo}/edit/main/${path.split("/").map(encodeURIComponent).join("/")}`);
/** An icon (lucide's), drawn in the text's colour. */
const icon = (paths: string) =>
`<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths}</svg>`;
const PENCIL = icon(`<path d="M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"/><path d="m15 5 4 4"/>`);
const CODE = icon(`<path d="m16 18 6-6-6-6"/><path d="m8 6-6 6 6 6"/>`);
const EYE = icon(
`<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/>`,
);
/** A moment as `2026-11-24 15:39 UTC`: the same for every reader. */
const utcStamp = (timestamp: number) =>
`${new Date(timestamp).toISOString().slice(0, 16).replace("T", " ")} UTC`;
/** `line 4`, or `lines 4 to 6`. */
const linesOf = (place: LinePlace) =>
place.endLine > place.line ? `lines ${place.line} to ${place.endLine}` : `line ${place.line}`;
/** The page that compares a branch with main. */
const compareHref = (repo: string, branch: string) =>
esc(`${repo}/compare/${branch.split("/").map(encodeURIComponent).join("/")}`);
/** The mind's sign-in, and then back to this page. */
const signInHref = (view: View) => esc(`/sign-in?to=${encodeURIComponent(view.url.pathname)}`);
/** iterate's components, pinned to one commit of the kit's main as the esm app built it: the one the Dash pins. */
const UI = "https://esm-sh.iterate.com/repos/ui@ceceae6e052ee8c76c25106872ee4c6010327a42";
const IMPORT_MAP = JSON.stringify({
imports: {
"@iterate-com/ui/": `${UI}/`,
react: `${UI}/react`,
"react/": `${UI}/react/`,
"react-dom": `${UI}/react-dom`,
"react-dom/": `${UI}/react-dom/`,
"lucide-react": "https://esm-sh.iterate.com/lucide-react@1.48.0?external=react,react-dom",
"@pierre/trees/react": "https://esm-sh.iterate.com/@pierre/trees@1.0.0/react?external=react,react-dom",
"@pierre/diffs/react": "https://esm-sh.iterate.com/@pierre/diffs@1.7.1/react?external=react,react-dom",
// git in the browser, for a member's commit on a new branch (public/branch-commit.js)
"isomorphic-git": "https://esm-sh.iterate.com/isomorphic-git@1.44.19",
"isomorphic-git/http/web": "https://esm-sh.iterate.com/isomorphic-git@1.44.19/http/web",
},
});