v4: what the server and the client both state is declared once — several rules were written out in two or more files, some already drifting apart. A link's site name (its host without www.) was computed in five places, now shared/url.ts's siteHost; dumpFileVersion, which the frontend and the server had to keep equal by hand, is one function in shared/dump.ts; the Markdown flattening of the chat's reply previews and the digest's quotes is shared/markdown.ts's markdownToPlainText, so the digest also keeps an image's alt text; an attachment's URL and how to find one in a text are shared/attachment.ts, which the editor, Markdown and attachment-service read, its id pattern the new UUID_RE that the file and thumbnail routes check ids with. On the server, the Bandcamp, YouTube playlist and link preview caches use one TtlCache (api/lib/ttl-cache.ts) instead of three copies of the same expiry and eviction; the link previews' theme-color and the emails' theme tokens read colours with one parser (api/lib/css-color.ts), and a transparent theme-color now gives no tint; the WebSocket route sends through ws-service's send, the welcome included, so it is type-checked; fetch.ts strips an IPv6 literal's brackets with public-address's bareHostname; and a category's slug is checked by the same validateSlug as a dump's, with its own length. The migrations keep their frozen copies, as they document. 272 backend tests and 677 frontend tests pass, and deno check, tsc, eslint and doc:lint are clean.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-10-09 13:10:07 +00:00
parent 134d1a0b97
commit c3594e4c27
39 changed files with 445 additions and 360 deletions

View File

@@ -12,6 +12,7 @@ import remarkGfm from "remark-gfm";
import { useAuth } from "../../hooks/auth/useAuth.ts";
import { userPath } from "../../../shared/paths.ts";
import { EVERYONE } from "../../../shared/mention.ts";
import { isAttachmentUrl } from "../../../shared/attachment.ts";
/** Passed to {@link Markdown} by any component that shows a user's text. */
export interface MarkdownProps {
@@ -154,8 +155,6 @@ function internalPath(href: string | undefined): string | null {
type Components = React.ComponentProps<typeof ReactMarkdown>["components"];
const ATTACHMENT_PATH_RE = /\/api\/attachments\/[0-9a-f-]{36}$/;
/**
* Renders an image of the text. An attachment gets the viewer's media token,
* which the server asks for when the text linking it is private; any other
@@ -166,7 +165,7 @@ function MarkdownImage(
): React.JSX.Element {
const { mediaToken } = useAuth();
let url = typeof src === "string" ? src : undefined;
if (url && mediaToken && ATTACHMENT_PATH_RE.test(url)) {
if (url && mediaToken && isAttachmentUrl(url)) {
url = `${url}?token=${encodeURIComponent(mediaToken)}`;
}
return <img src={url} alt={alt ?? ""} loading="lazy" decoding="async" />;

View File

@@ -27,6 +27,7 @@ import { useEmojiTrigger } from "../../hooks/editor/useEmojiTrigger.ts";
import { useAnchoredFloat } from "../../hooks/shared/useAnchoredFloat.ts";
import { useAuth } from "../../hooks/auth/useAuth.ts";
import { API_URL } from "../../config/api.ts";
import { attachmentPath } from "../../../shared/attachment.ts";
/**
* Exposed through the ref of {@link TextEditor}, so that the component that
@@ -342,7 +343,7 @@ export const TextEditor: React.ForwardRefExoticComponent<
});
const json = await res.json();
if (!json.success) throw new Error(json.error?.message);
images.push(`![](${API_URL}/api/attachments/${json.data.id})`);
images.push(`![](${API_URL}${attachmentPath(json.data.id)})`);
} catch {
setNotice(
files.length > 1

View File

@@ -4,11 +4,8 @@ import { userEvent } from "@testing-library/user-event";
import { FilePreview } from "../../../components/dump/FilePreview.tsx";
import { makeDump, makeSession } from "../../fixtures.ts";
import { renderWithContexts } from "../../render.tsx";
import {
dumpFileUrl,
dumpFileVersion,
dumpThumbnailUrl,
} from "../../../utils/shared/urls.ts";
import { dumpFileUrl, dumpThumbnailUrl } from "../../../utils/shared/urls.ts";
import { dumpFileVersion } from "../../../../shared/dump.ts";
describe("FilePreview", () => {
const session = makeSession();

View File

@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import { markdownToPlainText, mentionsUser } from "../../../utils/chat/text.ts";
import { mentionsUser } from "../../../utils/chat/text.ts";
describe("mentionsUser", () => {
test("case-insensitive whole-word match", () => {
@@ -15,33 +15,3 @@ describe("mentionsUser", () => {
expect(mentionsUser("@bob @carol @alice", "alice")).toBe(true);
});
});
describe("markdownToPlainText", () => {
test("links become their text, images their alt or a label", () => {
expect(markdownToPlainText("see [this](https://x.y) now", "img")).toBe(
"see this now",
);
expect(markdownToPlainText("![cat](a.png)", "Image")).toBe("cat");
expect(markdownToPlainText("![](a.png)", "Image")).toBe("Image");
});
test("markup characters and block markers go", () => {
expect(markdownToPlainText("# Title\n> quote\n- **bold** `code`", "")).toBe(
"Title quote bold code",
);
});
test("a body cut off mid-link doesn't show a half URL", () => {
expect(markdownToPlainText("look [here](https://exa", "img")).toBe(
"look here",
);
expect(markdownToPlainText("pic ![alt](https://exa", "Image")).toBe(
"pic alt",
);
expect(markdownToPlainText("pic ![](https://exa", "Image")).toBe(
"pic Image",
);
expect(markdownToPlainText("pic ![unfinished", "Image")).toBe("pic");
});
test("whitespace collapses to one line", () => {
expect(markdownToPlainText("a\n\n b\tc", "")).toBe("a b c");
});
});

View File

@@ -6,7 +6,7 @@
*/
import { t } from "@lingui/core/macro";
import { markdownToPlainText } from "./text.ts";
import { markdownToPlainText } from "../../../shared/markdown.ts";
import { isEmojiOnly } from "../editor/text.ts";
import { VALIDATION } from "../../../shared/validation.ts";

View File

@@ -1,6 +1,5 @@
/**
* Finds the mentions in a chat message, and flattens its Markdown into reply
* previews.
* Finds the mentions of the signed-in user in a chat message.
*
* @module
*/
@@ -15,24 +14,3 @@ import { mentionedUsernames } from "../../../shared/mention.ts";
export function mentionsUser(body: string, username: string): boolean {
return mentionedUsernames(body).includes(username.toLowerCase());
}
/**
* Returns the Markdown `md` as one line of plain text. Images become their alt
* text, or `imageLabel` without one, and links their text. It takes a
* `replyToBody`, which the server cuts short, possibly inside a link: the
* unfinished link then shows as its text, without half a URL. `snippet` calls
* it.
*/
export function markdownToPlainText(md: string, imageLabel: string): string {
return md
// An image or link cut short at the end loses its unfinished target.
.replace(/!\[([^\]]*)\]\([^)]*$/, (_, alt: string) => alt || imageLabel)
.replace(/(^|[^!])\[([^\]]*)\]\([^)]*$/, "$1$2")
.replace(/!\[[^\]]*$/, "")
.replace(/!\[([^\]]*)\]\([^)]*\)/g, (_, alt: string) => alt || imageLabel)
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/^\s{0,3}(#{1,6}|>|[-*+]|\d+\.)\s+/gm, "")
.replace(/```\w*|\*\*|__|~~|[*`]/g, "")
.replace(/\s+/g, " ")
.trim();
}

View File

@@ -6,6 +6,8 @@
* @module
*/
import { siteHost } from "../../../shared/url.ts";
/**
* Checks whether `value` is a lowercase `#rrggbb` colour. An `accentColor`
* comes from a dumped page's `theme-color`, which anyone controls, and a custom
@@ -37,15 +39,6 @@ function hueFromString(seed: string): string {
return `hsl(${hashString(seed) % 360} 55% 55%)`;
}
function hostnameOf(url: string | undefined): string | undefined {
if (!url) return undefined;
try {
return new URL(url).hostname.replace(/^www\./, "");
} catch {
return undefined;
}
}
/**
* Returns the page's own colour when it declared a valid one, or else a hue
* drawn from `seed` or the hostname of `url`, so that every card gets a tint,
@@ -59,7 +52,7 @@ export function tintFor(
},
): string {
if (isSafeHex(accentColor)) return accentColor;
return hueFromString(seed ?? hostnameOf(url) ?? url ?? "");
return hueFromString(seed ?? (url && siteHost(url)) ?? url ?? "");
}
/**
@@ -70,7 +63,7 @@ export function initialsFor(
siteName: string | undefined,
url: string | undefined,
): string {
const source = siteName?.trim() || hostnameOf(url) || url || "";
const source = siteName?.trim() || (url && siteHost(url)) || url || "";
const letter = [...source].find((ch) => /\p{L}|\p{N}/u.test(ch));
return (letter ?? "?").toUpperCase();
}

View File

@@ -13,6 +13,7 @@ import {
type OwnedItem,
playlistPath,
} from "../../../shared/paths.ts";
import { dumpFileVersion } from "../../../shared/dump.ts";
/**
* Passed to {@link dumpFileUrl} and {@link dumpThumbnailUrl}, usually as a
@@ -26,18 +27,6 @@ export type VersionedDump = {
updatedAt?: Date;
};
/**
* Returns a file dump's version, as `dumpFileVersion` in
* api/services/dump-service.ts computes it, so the two must change together.
* It changes whenever the file can have. The server lets the browser cache a
* URL that carries the current version for good, and has it revalidate any
* other.
*/
export function dumpFileVersion(dump: Omit<VersionedDump, "id">): string {
const at = dump.updatedAt ?? dump.createdAt;
return `${dump.fileSize ?? 0}-${at ? at.getTime() : 0}`;
}
/**
* Returns the URL of the uploaded file of `dump`. The caller passes the
* session's media token (`useAuth`'s `mediaToken`) as `token`, which goes in