Public: anyone can read this; the crew can change it.
OG designs for the map and the audit #466
torque/forge:torque/454-og-designs-for-the-map-and-the-audit → main 7 commits fork
31 files
changed +2534
−12
CLAUDE.md +8 −1
| @@ -140,7 +140,14 @@ src/ | ||
| 140 | 140 | surface, one module per concept: words (the vocabulary every |
| 141 | 141 | page says it in), asks, previews, shelf (an app as one |
| 142 | 142 | row, for any page that lists apps), home, app, change, tell, |
| 143 | run, lists, actions, style (the page sheet, assembled) | |
| 143 | run, lists, actions, style (the page sheet, assembled), | |
| 144 | and og/ — link previews: metrics (the fonts' advances), | |
| 145 | svg (palette, fonts, escaped text), card (the SVG, from | |
| 146 | plain data), graph and score (its figures), source (what a | |
| 147 | kind is handed: no viewer), kinds (what each preview says, | |
| 148 | read as nobody; map and audit in their own files), raster | |
| 149 | (resvg, spawned), cache (sha256 of the input), route | |
| 150 | (`/og/:kind/*path`) | |
| 144 | 151 | feed/ a viewer's feed (docs/FEED.md): items (candidates read through |
| 145 | 152 | the access every page uses), affinity (decayed counts), rank, |
| 146 | 153 | feed (filter, page, cursor) |
Dockerfile +18 −2
| @@ -3,14 +3,30 @@ | ||
| 3 | 3 | # npm), and chromium for the look — a picture of every green preview |
| 4 | 4 | # (docs/APPS.md). Chromium and a font to draw with add about 450 MB to the |
| 5 | 5 | # image; it is the largest thing here by far, and the only way to see a page |
| 6 | # as a browser does. package.json's dependency list is empty, so there is | |
| 7 | # nothing to install. | |
| 6 | # as a browser does. A fourth, resvg, draws the link previews (src/web/og): | |
| 7 | # one static 5 MB binary, pinned to a release and its sha256, and the | |
| 8 | # Liberation fonts it draws them in are the ones chromium already uses. | |
| 9 | # package.json's dependency list is empty, so there is nothing to install. | |
| 8 | 10 | FROM oven/bun:1.3-debian |
| 11 | ARG TARGETARCH | |
| 12 | ARG RESVG_VERSION=0.48.1 | |
| 13 | ARG RESVG_SHA256_AMD64=fa8c26495a187e592c501db15bf9e8a9fdc051d4b2b336b39703d5b59f912b9d | |
| 9 | 14 | RUN apt-get update \ |
| 10 | 15 | && apt-get install -y --no-install-recommends git ca-certificates curl bubblewrap socat nodejs npm tini chromium fonts-liberation \ |
| 11 | 16 | && rm -rf /var/lib/apt/lists/* \ |
| 12 | 17 | && npm install -g @anthropic-ai/claude-code \ |
| 13 | 18 | && npm cache clean --force |
| 19 | # resvg publishes a Linux binary for x86_64 only, so only the amd64 sha256 | |
| 20 | # is pinned; on any other TARGETARCH the PNG previews answer 503 (the SVGs | |
| 21 | # still work) until one is installed and named by FORGE_RESVG. The chart | |
| 22 | # (charts/app) pins no architecture: the image is built for whatever the | |
| 23 | # platform's builder is, and that is amd64 today. | |
| 24 | RUN if [ "${TARGETARCH:-amd64}" = "amd64" ]; then \ | |
| 25 | curl -fsSL -o /tmp/resvg.tgz "https://github.com/linebender/resvg/releases/download/v${RESVG_VERSION}/resvg-linux-x86_64.tar.gz" \ | |
| 26 | && echo "${RESVG_SHA256_AMD64} /tmp/resvg.tgz" | sha256sum -c - \ | |
| 27 | && tar -xzf /tmp/resvg.tgz -C /usr/local/bin resvg \ | |
| 28 | && rm /tmp/resvg.tgz; \ | |
| 29 | fi | |
| 14 | 30 | WORKDIR /app |
| 15 | 31 | COPY package.json tsconfig.json ./ |
| 16 | 32 | COPY src ./src |
README.md +57
| @@ -365,6 +365,63 @@ not as a crew run; AWS audits look at us-east-1 only; over-provisioned | ||
| 365 | 365 | droplets and forgotten DNS records need metrics or resolution and are not |
| 366 | 366 | attempted; Backblaze audits find nothing yet. No dependency was added. |
| 367 | 367 | |
| 368 | ## Link previews | |
| 369 | ||
| 370 | A link to the forge unfurls as a 1200 × 630 picture drawn from the page's | |
| 371 | data — the card a chat app shows before anyone clicks: | |
| 372 | ||
| 373 | ||
| 374 | /og/site/home.png the forge: what it holds in the open | |
| 375 | /og/repo/<owner>/<name>.png a repository: its description, what is open | |
| 376 | /og/map/<owner>/<name>.png a repository's map: the plan as a thumbnail | |
| 377 | /og/map/all.png the forge's map: every public repository's plan | |
| 378 | /og/audit/all.png the audit: the policy score, the top findings | |
| 379 | /og/<kind>/<path>.svg the same card, before it is rasterized | |
| 380 | ||
| 381 | ||
| 382 | The home, a public repository, its map, the forge's map and the audit name | |
| 383 | their card in the page's head (`og:image`, 1200 × 630, | |
| 384 | `summary_large_image`); every other page, and a private repository's page | |
| 385 | even to its own crew, keeps the forge's icon. | |
| 386 | ||
| 387 | Every preview reads as an anonymous viewer, whoever asks — unfurlers are | |
| 388 | anonymous, and a picture is cached and shared — so a private repository and | |
| 389 | a missing one draw the same card, one card with no name on it and | |
| 390 | "private": the bytes cannot tell them apart, and a thousand made-up names | |
| 391 | are one cached picture. The | |
| 392 | card is SVG composed from plain data in the studio's palette and rasterized | |
| 393 | by [](https://github.com/linebender/resvg), a static binary the image | |
| 394 | pins (`FORGE_RESVG` names another); it is spawned like git, so there is | |
| 395 | still no runtime dependency. PNGs are kept in memory under the sha256 of | |
| 396 | their input, which is also the ETag: unchanged data is a 304, changed data | |
| 397 | is a new picture, and nothing is ever invalidated. A cold render is about | |
| 398 | 60–130 ms. Without resvg the PNG answers 503 and says why; the SVG still | |
| 399 | works. resvg publishes a Linux binary for x86_64 only, so the image pins | |
| 400 | one for amd64 alone; built for any other architecture, the PNGs answer 503 | |
| 401 | until `FORGE_RESVG` names one. | |
| 402 | ||
| 403 | A cold render is the one cost a stranger can cause here, so it is bounded | |
| 404 | twice. Each address may cause 30 cold renders a minute; past that the next | |
| 405 | miss is 429 with `retry-after`, while a cached card, a render already under | |
| 406 | way and a 304 cost nothing and are never refused. The address is the | |
| 407 | socket's — no forwarded header is believed — so behind a proxy it is the | |
| 408 | proxy's, and the 30 are the whole forge's. And forge-wide at most 2 renders | |
| 409 | run and 16 wait; past that line the answer is 503, so a flood is refused, | |
| 410 | not queued. The previews are a URL surface, not a page action: there is no | |
| 411 | terminal twin to build. | |
| 412 | ||
| 413 | The **map** preview is the map page seen from far away: the same layout, | |
| 414 | titles left out, each card filled by its word (ready green, working the | |
| 415 | accent, blocked grey, waiting violet, parked amber, done faint) and the | |
| 416 | critical path's cards and edges in the accent, beside the counts and one | |
| 417 | sentence — how many are open, how long the chain still to go is, and what a | |
| 418 | free hand would take next. When anything is linked, only the chains are | |
| 419 | drawn and the unlinked issues are counted. The **audit** preview is the | |
| 420 | policy score as a ring — the share of public apps that *hold*: a contract | |
| 421 | that reads sound and doors that did not disagree with it when last knocked | |
| 422 | on; an app with no contract does not hold — and the top four findings, | |
| 423 | worst first: disobeying, unsound, open to anyone (most first), unread. | |
| 424 | ||
| 368 | 425 | ## Develop |
| 369 | 426 | |
| 370 | 427 | sh |
docs/APPS.md +2
| @@ -942,6 +942,8 @@ one line and a link to the asks screen is posted there (`src/crew/notify.ts`). | ||
| 942 | 942 | | `FORGE_CLAUDE` | `claude` on `PATH` | the Claude Code binary | |
| 943 | 943 | | `FORGE_CLAUDE_CONFIG_DIR` | Claude Code's own | a `CLAUDE_CONFIG_DIR` for runs, when wanted | |
| 944 | 944 | | `FORGE_CHROMIUM` | `chromium` on `PATH` | the browser the look is taken with | |
| 945 | | `FORGE_RESVG` | `resvg` on `PATH` | what draws the link previews (`/og/…png`) | | |
| 946 | | `FORGE_OG_FONTS` | where `fonts-liberation` lives | a directory holding the three Liberation faces | | |
| 945 | 947 | | `ANTHROPIC_API_KEY` | — | handed to agent runs when set | |
| 946 | 948 | | `CLAUDE_CODE_OAUTH_TOKEN` | — | handed to agent runs when set | |
| 947 | 949 | | `TYPESAFE_API_KEY` | — | TypeSafe's Jev answers fixed-choice decisions | |
scripts/gate.ts +3
| @@ -73,6 +73,9 @@ export const GATE: readonly string[] = [ | ||
| 73 | 73 | "test/board.test.ts", |
| 74 | 74 | "test/spawn-plan.test.ts", |
| 75 | 75 | "test/spawn.test.ts", |
| 76 | "test/og.test.ts", | |
| 77 | "test/og-designs.test.ts", | |
| 78 | "test/og-pages.test.ts", | |
| 76 | 79 | "test/web-apps.test.ts", |
| 77 | 80 | "test/fleet-ops.test.ts", |
| 78 | 81 | "test/meter.test.ts", |
src/http/context.ts +6
| @@ -29,6 +29,12 @@ export interface Ctx { | ||
| 29 | 29 | theme: ThemeName | undefined; |
| 30 | 30 | /** Studio or dev, from the forge_mode cookie; studio when unset. */ |
| 31 | 31 | mode: Mode; |
| 32 | /** | |
| 33 | * The address of the socket the request came in on, for a limit that has | |
| 34 | * no identity to key on (`web/og/route.ts`). No forwarded header is read: | |
| 35 | * behind a proxy this is the proxy, and the limit is the forge's whole. | |
| 36 | */ | |
| 37 | peer?: string; | |
| 32 | 38 | } |
| 33 | 39 | |
| 34 | 40 | export type Handler = (ctx: Ctx) => Response | Promise<Response>; |
src/http/server.ts +22 −2
| @@ -308,6 +308,7 @@ import { | ||
| 308 | 308 | type StoredResponse, |
| 309 | 309 | } from "../core/idempotency.ts"; |
| 310 | 310 | import { sseStream, viewerStream } from "./sse.ts"; |
| 311 | import { ogImage } from "../web/og/route.ts"; | |
| 311 | 312 | import { Router } from "./router.ts"; |
| 312 | 313 | import { getUserById } from "../core/users.ts"; |
| 313 | 314 | import { appsRuntime } from "../apps/runtime.ts"; |
| @@ -415,6 +416,8 @@ export function buildRouter(): Router<Handler> { | ||
| 415 | 416 | router.add("GET", "/sitemap.xml", sitemapXml); |
| 416 | 417 | router.add("GET", "/manifest.webmanifest", webManifest); |
| 417 | 418 | router.add("GET", "/icons/:spec.png", iconPng); |
| 419 | // Link previews: a picture of a page, drawn from its data as nobody sees it. | |
| 420 | router.add("GET", "/og/:kind/*path", ogImage); | |
| 418 | 421 | // The highlighter bundle, content-addressed. A stale hash is a 404 rather |
| 419 | 422 | // than a redirect: the page that asked for it names the hash it was built |
| 420 | 423 | // with, so a miss means an old tab, and an old tab should reload. |
| @@ -1320,7 +1323,14 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1320 | 1323 | // Everything the forge answers for itself leaves through this one |
| 1321 | 1324 | // door, so a responder added next year cannot forget the floor. |
| 1322 | 1325 | return securityFloor( |
| 1323 | await answer(app, router, apiRouter, limiter, request), | |
| 1326 | await answer( | |
| 1327 | app, | |
| 1328 | router, | |
| 1329 | apiRouter, | |
| 1330 | limiter, | |
| 1331 | request, | |
| 1332 | server.requestIP(request)?.address, | |
| 1333 | ), | |
| 1324 | 1334 | ); |
| 1325 | 1335 | }, |
| 1326 | 1336 | error(error) { |
| @@ -1370,8 +1380,16 @@ async function answer( | ||
| 1370 | 1380 | apiRouter: Router<Handler>, |
| 1371 | 1381 | limiter: RateLimiter, |
| 1372 | 1382 | request: Request, |
| 1383 | peer: string | undefined, | |
| 1373 | 1384 | ): Promise<Response> { |
| 1374 | const response = await answerGet(app, router, apiRouter, limiter, request); | |
| 1385 | const response = await answerGet( | |
| 1386 | app, | |
| 1387 | router, | |
| 1388 | apiRouter, | |
| 1389 | limiter, | |
| 1390 | request, | |
| 1391 | peer, | |
| 1392 | ); | |
| 1375 | 1393 | return request.method === "HEAD" |
| 1376 | 1394 | ? new Response(null, { status: response.status, headers: response.headers }) |
| 1377 | 1395 | : response; |
| @@ -1383,6 +1401,7 @@ async function answerGet( | ||
| 1383 | 1401 | apiRouter: Router<Handler>, |
| 1384 | 1402 | limiter: RateLimiter, |
| 1385 | 1403 | request: Request, |
| 1404 | peer: string | undefined, | |
| 1386 | 1405 | ): Promise<Response> { |
| 1387 | 1406 | const url = publicUrl(request, app.config.url); |
| 1388 | 1407 | if (url.pathname === "/healthz") return healthResponse(); |
| @@ -1453,6 +1472,7 @@ async function answerGet( | ||
| 1453 | 1472 | auth, |
| 1454 | 1473 | theme: isThemeName(themeCookie) ? themeCookie : undefined, |
| 1455 | 1474 | mode, |
| 1475 | ...(peer === undefined ? {} : { peer }), | |
| 1456 | 1476 | }); |
| 1457 | 1477 | |
| 1458 | 1478 | // A signed-in browser's outbox replays by key too (web/outbox.ts): the |
src/web/layout.ts +29 −5
| @@ -102,6 +102,14 @@ export interface PageOptions { | ||
| 102 | 102 | bare?: boolean; |
| 103 | 103 | /** The theme when the viewer has chosen none: for a page that is dark by nature. */ |
| 104 | 104 | theme?: ThemeName; |
| 105 | /** | |
| 106 | * This page's link preview: a kind and its path, as `/og/<kind>/<path>.png` | |
| 107 | * spells them (`web/og/route.ts`) — `["repo", owner, name]`. Absent, the | |
| 108 | * forge's icon stands in. A page sets it only for something an anonymous | |
| 109 | * unfurler may see (`web/og/link.ts`): the card reads as nobody, and a page | |
| 110 | * that names one for a private repository would announce it. | |
| 111 | */ | |
| 112 | og?: readonly string[] | undefined; | |
| 105 | 113 | } |
| 106 | 114 | |
| 107 | 115 | // ---- topbar pieces ---- |
| @@ -498,6 +506,26 @@ function pageDescription(options: PageOptions): string { | ||
| 498 | 506 | return line.length <= 200 ? line : `${line.slice(0, 197).trimEnd()}…`; |
| 499 | 507 | } |
| 500 | 508 | |
| 509 | /** | |
| 510 | * The head's picture: a page's own card, 1200 × 630, when it names one and | |
| 511 | * exists, else the icon. An error page never names a card, for the same | |
| 512 | * reason it never names its `og:url`. | |
| 513 | */ | |
| 514 | function ogImageMeta(ctx: Ctx, og: readonly string[] | undefined): Html { | |
| 515 | if (og === undefined || og.length === 0) | |
| 516 | return html`<meta | |
| 517 | property="og:image" | |
| 518 | content="${ctx.url.origin}/icons/forge-512.png" | |
| 519 | /> | |
| 520 | <meta name="twitter:card" content="summary" />`; | |
| 521 | const src = `${ctx.url.origin}/og/${og.map(encodeURIComponent).join("/")}.png`; | |
| 522 | return html`<meta property="og:image" content="${src}" /> | |
| 523 | <meta property="og:image:width" content="1200" /> | |
| 524 | <meta property="og:image:height" content="630" /> | |
| 525 | <meta name="twitter:card" content="summary_large_image" /> | |
| 526 | <meta name="twitter:image" content="${src}" />`; | |
| 527 | } | |
| 528 | ||
| 501 | 529 | export function page(options: PageOptions, status = 200): Response { |
| 502 | 530 | // A per-response nonce lets exactly this page's <style> and <script> run |
| 503 | 531 | // while everything else stays forbidden. |
| @@ -552,11 +580,7 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 552 | 580 | />` |
| 553 | 581 | : null |
| 554 | 582 | } |
| 555 | <meta | |
| 556 | property="og:image" | |
| 557 | content="${ctx.url.origin}/icons/forge-512.png" | |
| 558 | /> | |
| 559 | <meta name="twitter:card" content="summary" /> | |
| 583 | ${ogImageMeta(ctx, status === 200 ? options.og : undefined)} | |
| 560 | 584 | <link rel="manifest" href="/manifest.webmanifest" /> |
| 561 | 585 | <link rel="apple-touch-icon" href="/icons/forge-180.png" /> |
| 562 | 586 | <meta name="mobile-web-app-capable" content="yes" /> |
src/web/og/audit.ts added +163
| @@ -0,0 +1,163 @@ | ||
| 1 | /** | |
| 2 | * The audit's preview: the policy score as a ring, and the top findings. | |
| 3 | * | |
| 4 | * /og/audit/all.png the forge's audit (`/audit`), as nobody sees it | |
| 5 | * | |
| 6 | * It reads what the audit page reads — each app's `contract.json` at its | |
| 7 | * default branch through the evaluator the app decides with, and the last | |
| 8 | * time the forge knocked on its doors — for the public apps only, because | |
| 9 | * an unfurler is nobody (`source.ts`). | |
| 10 | * | |
| 11 | * The score is the share of apps that hold: an app holds when its contract | |
| 12 | * reads sound and its doors did not disagree with its table the last time | |
| 13 | * they were knocked on (an app never knocked on has not disagreed). An app | |
| 14 | * with no contract does not hold — it is unread, and an audit that leaves | |
| 15 | * out what it cannot read reads as a clean bill. So 3 sound apps of which | |
| 16 | * one disobeys, plus one unread, is 2 of 4: 50%. | |
| 17 | * | |
| 18 | * Findings, worst first, four at most: an app that disobeys its table; a | |
| 19 | * contract that does not read; an app with doors open to anyone, the most | |
| 20 | * open first; and the unread apps, together on one line. | |
| 21 | */ | |
| 22 | ||
| 23 | import { appsForRepos } from "../../core/apps.ts"; | |
| 24 | import { listReposVisibleTo } from "../../core/repos.ts"; | |
| 25 | import { audit } from "../../contract/audit.ts"; | |
| 26 | import { latestProbes } from "../../contract/probes.ts"; | |
| 27 | import type { Card, Note } from "./card.ts"; | |
| 28 | import { percent, type ScoreFigure } from "./score.ts"; | |
| 29 | import { plural, type Kind, type OgSource } from "./source.ts"; | |
| 30 | import type { Tone } from "./svg.ts"; | |
| 31 | ||
| 32 | /** The audit page's own bound. */ | |
| 33 | const AUDIT_LIMIT = 200; | |
| 34 | const MAX_FINDINGS = 4; | |
| 35 | ||
| 36 | /** One app as the audit read it: plain data, so the card is a pure function of these. */ | |
| 37 | export interface AuditRow { | |
| 38 | /** `owner/name`. */ | |
| 39 | readonly name: string; | |
| 40 | readonly standing: "sound" | "unsound" | "unread"; | |
| 41 | /** Doors the floor — anyone who can reach the app — may open. */ | |
| 42 | readonly open: number; | |
| 43 | /** Why an unsound contract does not read. */ | |
| 44 | readonly problems: readonly string[]; | |
| 45 | /** The last probe found the doors disagreeing with the table. */ | |
| 46 | readonly disobeys: boolean; | |
| 47 | } | |
| 48 | ||
| 49 | const holds = (r: AuditRow): boolean => r.standing === "sound" && !r.disobeys; | |
| 50 | ||
| 51 | /** The findings, worst first. */ | |
| 52 | export function findings(rows: readonly AuditRow[]): Note[] { | |
| 53 | const out: Note[] = []; | |
| 54 | for (const r of rows) | |
| 55 | if (r.standing === "sound" && r.disobeys) | |
| 56 | out.push({ text: `${r.name} disobeys its contract`, tone: "danger" }); | |
| 57 | for (const r of rows) | |
| 58 | if (r.standing === "unsound") | |
| 59 | out.push({ | |
| 60 | text: `${r.name}: unsound${r.problems[0] === undefined ? "" : ` — ${r.problems[0]}`}`, | |
| 61 | tone: "danger", | |
| 62 | }); | |
| 63 | for (const r of rows | |
| 64 | .filter((r) => r.standing === "sound" && r.open > 0) | |
| 65 | .toSorted((a, b) => b.open - a.open || a.name.localeCompare(b.name))) | |
| 66 | out.push({ | |
| 67 | text: `${r.name}: ${r.open} ${plural(r.open, "door")} open to anyone`, | |
| 68 | tone: "attn", | |
| 69 | }); | |
| 70 | const unread = rows.filter((r) => r.standing === "unread"); | |
| 71 | if (unread.length === 1) | |
| 72 | out.push({ text: `${unread[0]!.name} is unread: no contract.json`, tone: "muted" }); | |
| 73 | else if (unread.length > 1) | |
| 74 | out.push({ text: `${unread.length} apps unread: no contract.json`, tone: "muted" }); | |
| 75 | return out; | |
| 76 | } | |
| 77 | ||
| 78 | function scoreTone(held: number, of: number): Tone { | |
| 79 | const p = percent(held, of); | |
| 80 | return p === 100 ? "success" : p >= 50 ? "attn" : "danger"; | |
| 81 | } | |
| 82 | ||
| 83 | /** The audit's card from the apps as read. */ | |
| 84 | export function auditCard(host: string, rows: readonly AuditRow[]): Card { | |
| 85 | const held = rows.filter(holds).length; | |
| 86 | const of = rows.length; | |
| 87 | const sound = rows.filter((r) => r.standing === "sound").length; | |
| 88 | const unsound = rows.filter((r) => r.standing === "unsound").length; | |
| 89 | const unread = rows.filter((r) => r.standing === "unread").length; | |
| 90 | const open = rows.reduce((n, r) => n + (r.standing === "sound" ? r.open : 0), 0); | |
| 91 | const found = findings(rows); | |
| 92 | const head = { eyebrow: "forge · audit", title: "Audit", host }; | |
| 93 | if (of === 0) | |
| 94 | return { | |
| 95 | ...head, | |
| 96 | description: "No public apps to audit yet. An app's policy shows here once it has a contract.", | |
| 97 | state: { label: "nothing to read", tone: "muted" }, | |
| 98 | }; | |
| 99 | const figure: ScoreFigure = { | |
| 100 | kind: "score", | |
| 101 | held, | |
| 102 | of, | |
| 103 | caption: | |
| 104 | of === 1 | |
| 105 | ? `${held} of 1 app holds its contract` | |
| 106 | : `${held} of ${of} apps hold their contract`, | |
| 107 | tone: scoreTone(held, of), | |
| 108 | }; | |
| 109 | const worst = found[0]; | |
| 110 | return { | |
| 111 | ...head, | |
| 112 | state: | |
| 113 | worst === undefined | |
| 114 | ? { label: "holds", tone: "success" } | |
| 115 | : worst.tone === "danger" | |
| 116 | ? { label: rows.some((r) => r.disobeys) ? "disobeyed" : "unsound", tone: "danger" } | |
| 117 | : { label: "holds, with notes", tone: worst.tone }, | |
| 118 | notes: | |
| 119 | found.length === 0 | |
| 120 | ? [{ text: "Every app holds its contract.", tone: "success" }] | |
| 121 | : found.slice(0, MAX_FINDINGS), | |
| 122 | figure, | |
| 123 | stats: [ | |
| 124 | { value: String(sound), label: `${plural(sound, "contract")} read` }, | |
| 125 | { | |
| 126 | value: String(open), | |
| 127 | label: `${plural(open, "door")} open to anyone`, | |
| 128 | tone: open > 0 ? "attn" : "muted", | |
| 129 | }, | |
| 130 | { value: String(unsound), label: "unsound", tone: unsound > 0 ? "danger" : "muted" }, | |
| 131 | { value: String(unread), label: "unread", tone: "muted" }, | |
| 132 | ], | |
| 133 | }; | |
| 134 | } | |
| 135 | ||
| 136 | /** The public apps, read the way the audit page reads them. */ | |
| 137 | async function auditRows(source: OgSource): Promise<AuditRow[]> { | |
| 138 | const repos = listReposVisibleTo(source.db, undefined, { limit: AUDIT_LIMIT }); | |
| 139 | const records = appsForRepos( | |
| 140 | source.db, | |
| 141 | repos.map((r) => r.id), | |
| 142 | ); | |
| 143 | const apps = repos.filter((r) => records.has(r.id)); | |
| 144 | const audited = await Promise.all(apps.map((repo) => audit(source.reposRoot, repo))); | |
| 145 | const probed = latestProbes( | |
| 146 | source.db, | |
| 147 | audited.filter((a) => a.standing.kind === "sound").map((a) => records.get(a.repo.id)!.id), | |
| 148 | ); | |
| 149 | return audited.map((a) => ({ | |
| 150 | name: `${a.repo.ownerName}/${a.repo.name}`, | |
| 151 | standing: a.standing.kind, | |
| 152 | open: a.standing.kind === "sound" ? a.standing.open.length : 0, | |
| 153 | problems: a.standing.kind === "unsound" ? a.standing.problems : [], | |
| 154 | disobeys: | |
| 155 | a.standing.kind === "sound" && | |
| 156 | probed.get(records.get(a.repo.id)!.id)?.verdict === "mismatch", | |
| 157 | })); | |
| 158 | } | |
| 159 | ||
| 160 | export const auditKind: Kind = async (source, path) => { | |
| 161 | if (path.length !== 1 || path[0] !== "all") return undefined; | |
| 162 | return auditCard(source.host, await auditRows(source)); | |
| 163 | }; |
src/web/og/cache.ts added +99
| @@ -0,0 +1,99 @@ | ||
| 1 | /** | |
| 2 | * Rendered previews, kept by what they were rendered from. The key is the | |
| 3 | * sha256 of the card's input in canonical JSON (keys sorted) plus the | |
| 4 | * renderer's version: the same data always maps to the same PNG, changed | |
| 5 | * data is a different key, and nothing has to be invalidated — a stale | |
| 6 | * entry simply stops being asked for and falls off the end of the LRU. | |
| 7 | * | |
| 8 | * The same key is the response's ETag, so an unfurler or a browser that | |
| 9 | * already holds the picture is answered 304 without a render. | |
| 10 | * | |
| 11 | * In memory, bounded by bytes: a card is ~20–40 KB, so the default 32 MB | |
| 12 | * holds about a thousand. After a restart the first request for each pays | |
| 13 | * one cold render (≤ 300 ms is the bar; resvg does it in under 100). | |
| 14 | * Concurrent requests for one key share one render. | |
| 15 | */ | |
| 16 | ||
| 17 | import { sha256 } from "../../kernel/hash.ts"; | |
| 18 | import { ok, type Result } from "../../kernel/result.ts"; | |
| 19 | ||
| 20 | /** Bumped when the drawing changes, so an old picture is never served for new code. */ | |
| 21 | export const RENDER_VERSION = "og-1"; | |
| 22 | ||
| 23 | /** JSON with object keys sorted at every depth: equal data, equal text. */ | |
| 24 | export function canonical(value: unknown): string { | |
| 25 | if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`; | |
| 26 | if (value !== null && typeof value === "object") { | |
| 27 | const entries = Object.entries(value as Record<string, unknown>) | |
| 28 | .filter(([, v]) => v !== undefined) | |
| 29 | .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); | |
| 30 | return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`; | |
| 31 | } | |
| 32 | return JSON.stringify(value) ?? "null"; | |
| 33 | } | |
| 34 | ||
| 35 | /** The cache key of one preview's input. */ | |
| 36 | export function inputHash(kind: string, input: unknown): string { | |
| 37 | return sha256(`${RENDER_VERSION}\n${kind}\n${canonical(input)}`); | |
| 38 | } | |
| 39 | ||
| 40 | export class PngCache { | |
| 41 | private readonly entries = new Map<string, Uint8Array>(); | |
| 42 | private readonly pending = new Map< | |
| 43 | string, | |
| 44 | Promise<Result<Uint8Array, string>> | |
| 45 | >(); | |
| 46 | private bytes = 0; | |
| 47 | ||
| 48 | constructor(readonly maxBytes = 32 * 1024 * 1024) {} | |
| 49 | ||
| 50 | get size(): number { | |
| 51 | return this.entries.size; | |
| 52 | } | |
| 53 | ||
| 54 | get(key: string): Uint8Array | undefined { | |
| 55 | const hit = this.entries.get(key); | |
| 56 | if (hit === undefined) return undefined; | |
| 57 | // Re-insert: a Map iterates in insertion order, so the oldest is first. | |
| 58 | this.entries.delete(key); | |
| 59 | this.entries.set(key, hit); | |
| 60 | return hit; | |
| 61 | } | |
| 62 | ||
| 63 | set(key: string, png: Uint8Array): void { | |
| 64 | if (png.length > this.maxBytes) return; | |
| 65 | const old = this.entries.get(key); | |
| 66 | if (old !== undefined) { | |
| 67 | this.bytes -= old.length; | |
| 68 | this.entries.delete(key); | |
| 69 | } | |
| 70 | this.entries.set(key, png); | |
| 71 | this.bytes += png.length; | |
| 72 | for (const [k, v] of this.entries) { | |
| 73 | if (this.bytes <= this.maxBytes) break; | |
| 74 | this.entries.delete(k); | |
| 75 | this.bytes -= v.length; | |
| 76 | } | |
| 77 | } | |
| 78 | ||
| 79 | /** The PNG for `key`: from memory, from a render already running, or from `render`. */ | |
| 80 | async through( | |
| 81 | key: string, | |
| 82 | render: () => Promise<Result<Uint8Array, string>>, | |
| 83 | ): Promise<Result<Uint8Array, string>> { | |
| 84 | const hit = this.get(key); | |
| 85 | if (hit !== undefined) return ok(hit); | |
| 86 | const running = this.pending.get(key); | |
| 87 | if (running !== undefined) return running; | |
| 88 | const started = render().then((result) => { | |
| 89 | if (result.ok) this.set(key, result.value); | |
| 90 | return result; | |
| 91 | }); | |
| 92 | this.pending.set(key, started); | |
| 93 | try { | |
| 94 | return await started; | |
| 95 | } finally { | |
| 96 | this.pending.delete(key); | |
| 97 | } | |
| 98 | } | |
| 99 | } |
src/web/og/card.ts added +226
| @@ -0,0 +1,226 @@ | ||
| 1 | /** | |
| 2 | * The preview card: one 1200 × 630 SVG composed from plain data, in the | |
| 3 | * studio's own palette (Porcelain, `design/themes.ts`) and its mark. Every | |
| 4 | * kind of preview is a `Card` — a kind decides what to say, this file | |
| 5 | * decides how it looks — so every link the forge unfurls is one visual | |
| 6 | * system. | |
| 7 | * | |
| 8 | * ┌──────────────────────────────────────────────┐ | |
| 9 | * │ ■ eyebrow ( state ) │ y 72 | |
| 10 | * │ Title, bold, up to two lines │ y 196 | |
| 11 | * │ Description, up to three lines │ | |
| 12 | * │ │ | |
| 13 | * │ 12 3 $41 │ y 508 | |
| 14 | * │ open waiting today │ | |
| 15 | * │ host │ y 590 | |
| 16 | * └▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀┘ | |
| 17 | * | |
| 18 | * A card may carry notes — lines with a dot in a tone, the audit's | |
| 19 | * findings — under the description, and a figure (the map's graph, | |
| 20 | * `graph.ts`; the audit's score, `score.ts`) in the right-hand box | |
| 21 | * (`FIGURE_BOX`, x 648–1128, y 116–460), in which case the words keep to | |
| 22 | * the left 528 px. | |
| 23 | * | |
| 24 | * 1200 × 630 is the size every unfurler (iMessage, Slack, X, Discord) | |
| 25 | * crops least; text is placed by arithmetic (`metrics.ts`) because SVG | |
| 26 | * does not wrap. Nothing here reads a database: a card is a pure function | |
| 27 | * of its input, which is what lets the cache key be a hash of that input. | |
| 28 | */ | |
| 29 | ||
| 30 | import { graphSvg, type GraphFigure } from "./graph.ts"; | |
| 31 | import { clip, measure, wrap } from "./metrics.ts"; | |
| 32 | import { scoreSvg, type ScoreFigure } from "./score.ts"; | |
| 33 | import { MONO, P, SANS, text, tone, type Box, type Tone } from "./svg.ts"; | |
| 34 | ||
| 35 | export { MONO, SANS, xmlText, type Tone } from "./svg.ts"; | |
| 36 | ||
| 37 | export const WIDTH = 1200; | |
| 38 | export const HEIGHT = 630; | |
| 39 | ||
| 40 | export interface Stat { | |
| 41 | readonly value: string; | |
| 42 | readonly label: string; | |
| 43 | readonly tone?: Tone; | |
| 44 | } | |
| 45 | ||
| 46 | /** One line said with a coloured dot: a finding, a warning, a note. */ | |
| 47 | export interface Note { | |
| 48 | readonly text: string; | |
| 49 | readonly tone: Tone; | |
| 50 | } | |
| 51 | ||
| 52 | /** A picture beside the words: the map's graph, the audit's score. */ | |
| 53 | export type Figure = GraphFigure | ScoreFigure; | |
| 54 | ||
| 55 | /** Everything a preview says. Plain data: what is hashed is what is drawn. */ | |
| 56 | export interface Card { | |
| 57 | /** Where this is, small, above the title — `owner/name`, `forge`. */ | |
| 58 | readonly eyebrow: string; | |
| 59 | readonly title: string; | |
| 60 | readonly description?: string; | |
| 61 | /** One word for the state of the thing, in a pill at the top right. */ | |
| 62 | readonly state?: { readonly label: string; readonly tone: Tone }; | |
| 63 | /** Lines under the description, each with a dot in its tone; four at most. */ | |
| 64 | readonly notes?: readonly Note[]; | |
| 65 | /** Drawn in the right-hand box; the words take the left. */ | |
| 66 | readonly figure?: Figure; | |
| 67 | /** Up to four numbers along the bottom. */ | |
| 68 | readonly stats?: readonly Stat[]; | |
| 69 | /** The forge's host, bottom left: whose link this is. */ | |
| 70 | readonly host: string; | |
| 71 | } | |
| 72 | ||
| 73 | const PAD = 72; | |
| 74 | const INNER = WIDTH - PAD * 2; | |
| 75 | const MAX_STATS = 4; | |
| 76 | const MAX_NOTES = 4; | |
| 77 | ||
| 78 | /** Where a figure goes: the right of the card, between the pill and the numbers. */ | |
| 79 | export const FIGURE_BOX: Box = { x: 648, y: 116, w: WIDTH - PAD - 648, h: 344 }; | |
| 80 | /** How wide the words may run when a figure is beside them. */ | |
| 81 | const BESIDE = FIGURE_BOX.x - PAD - 48; | |
| 82 | ||
| 83 | /** The mark, as the favicon draws it, at `size` px with its top-left at x, y. */ | |
| 84 | function mark(x: number, y: number, size: number): string { | |
| 85 | const r = (size * 8) / 26; | |
| 86 | return `<rect x="${x}" y="${y}" width="${size}" height="${size}" rx="${r}" fill="url(#mark)"/>`; | |
| 87 | } | |
| 88 | ||
| 89 | function pill(label: string, t: Tone): string { | |
| 90 | const size = 24; | |
| 91 | const shown = clip(label, size, "bold", 360); | |
| 92 | // 22 px to the dot, 14 more to the text, 24 after it. | |
| 93 | const w = Math.ceil(measure(shown, size, "bold")) + 60; | |
| 94 | const h = 48; | |
| 95 | const x = WIDTH - PAD - w; | |
| 96 | const y = PAD - 32; | |
| 97 | const c = tone(t); | |
| 98 | return [ | |
| 99 | `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}" fill="${c}" fill-opacity="0.12"/>`, | |
| 100 | `<circle cx="${x + 22}" cy="${y + h / 2}" r="6" fill="${c}"/>`, | |
| 101 | text( | |
| 102 | x + 36, | |
| 103 | y + 32, | |
| 104 | shown, | |
| 105 | `font-family="${SANS}" font-weight="700" font-size="${size}" fill="${c}"`, | |
| 106 | ), | |
| 107 | ].join(""); | |
| 108 | } | |
| 109 | ||
| 110 | function stats(list: readonly Stat[]): string { | |
| 111 | const shown = list.slice(0, MAX_STATS); | |
| 112 | if (shown.length === 0) return ""; | |
| 113 | const cell = INNER / Math.max(3, shown.length); | |
| 114 | return shown | |
| 115 | .map((s, i) => { | |
| 116 | const x = PAD + i * cell; | |
| 117 | return [ | |
| 118 | text( | |
| 119 | x, | |
| 120 | 510, | |
| 121 | clip(s.value, 52, "bold", cell - 24), | |
| 122 | `font-family="${SANS}" font-weight="700" font-size="52" fill="${tone(s.tone)}"`, | |
| 123 | ), | |
| 124 | text( | |
| 125 | x, | |
| 126 | 546, | |
| 127 | clip(s.label, 24, "sans", cell - 24), | |
| 128 | `font-family="${SANS}" font-size="24" fill="${P["muted-fg"]}"`, | |
| 129 | ), | |
| 130 | ].join(""); | |
| 131 | }) | |
| 132 | .join(""); | |
| 133 | } | |
| 134 | ||
| 135 | function figure(f: Figure): string { | |
| 136 | switch (f.kind) { | |
| 137 | case "graph": | |
| 138 | return graphSvg(f, FIGURE_BOX); | |
| 139 | case "score": | |
| 140 | return scoreSvg(f, FIGURE_BOX); | |
| 141 | } | |
| 142 | } | |
| 143 | ||
| 144 | /** Notes from baseline `top`, 46 px apart, a dot at the x-height's middle. */ | |
| 145 | function notes(list: readonly Note[], top: number, width: number): string { | |
| 146 | return list | |
| 147 | .map((n, i) => { | |
| 148 | const y = top + i * 46; | |
| 149 | return [ | |
| 150 | `<circle cx="${PAD + 7}" cy="${y - 10}" r="7" fill="${tone(n.tone)}"/>`, | |
| 151 | text( | |
| 152 | PAD + 28, | |
| 153 | y, | |
| 154 | clip(n.text, 30, "sans", width - 28), | |
| 155 | `font-family="${SANS}" font-size="30" fill="${P.fg}"`, | |
| 156 | ), | |
| 157 | ].join(""); | |
| 158 | }) | |
| 159 | .join(""); | |
| 160 | } | |
| 161 | ||
| 162 | /** The card as an SVG document. */ | |
| 163 | export function cardSvg(card: Card): string { | |
| 164 | const pillRoom = card.state === undefined ? 0 : 420; | |
| 165 | const eyebrow = clip(card.eyebrow, 28, "mono", INNER - 64 - pillRoom); | |
| 166 | const hasStats = (card.stats ?? []).length > 0; | |
| 167 | const width = card.figure === undefined ? INNER : BESIDE; | |
| 168 | // Up to two lines of title at 68 px; the description takes the lines | |
| 169 | // left above the numbers (44 px apart, last baseline ≤ 420) or, with no | |
| 170 | // numbers, above the host — four at most — and the notes take what the | |
| 171 | // description leaves, 46 px each. | |
| 172 | const bottom = hasStats ? 420 : 560; | |
| 173 | const title = wrap(card.title, 68, "bold", width, 2); | |
| 174 | const descTop = 196 + (title.length - 1) * 80 + 72; | |
| 175 | const room = (top: number, step: number): number => | |
| 176 | Math.max(0, Math.floor((bottom - top) / step) + 1); | |
| 177 | const wanted = (card.notes ?? []).slice(0, MAX_NOTES); | |
| 178 | // Notes are the finding; the description gives way to them first. | |
| 179 | const descRoom = Math.max(0, room(descTop, 44) - Math.ceil((wanted.length * 46) / 44)); | |
| 180 | const desc = | |
| 181 | card.description === undefined | |
| 182 | ? [] | |
| 183 | : wrap(card.description, 32, "sans", width, Math.min(4, descRoom)); | |
| 184 | const notesTop = desc.length === 0 ? descTop : descTop + desc.length * 44 + 14; | |
| 185 | const shownNotes = wanted.slice(0, room(notesTop, 46)); | |
| 186 | return [ | |
| 187 | `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}">`, | |
| 188 | `<defs><linearGradient id="mark" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${P.accent}"/><stop offset="1" stop-color="${P.merged}"/></linearGradient></defs>`, | |
| 189 | `<rect width="${WIDTH}" height="${HEIGHT}" fill="${P.bg}"/>`, | |
| 190 | `<rect y="${HEIGHT - 12}" width="${WIDTH}" height="12" fill="url(#mark)"/>`, | |
| 191 | mark(PAD, PAD - 32, 44), | |
| 192 | text( | |
| 193 | PAD + 64, | |
| 194 | PAD + 2, | |
| 195 | eyebrow, | |
| 196 | `font-family="${MONO}" font-size="28" fill="${P["muted-fg"]}"`, | |
| 197 | ), | |
| 198 | card.state === undefined ? "" : pill(card.state.label, card.state.tone), | |
| 199 | card.figure === undefined ? "" : figure(card.figure), | |
| 200 | ...title.map((line, i) => | |
| 201 | text( | |
| 202 | PAD, | |
| 203 | 196 + i * 80, | |
| 204 | line, | |
| 205 | `font-family="${SANS}" font-weight="700" font-size="68" fill="${P.fg}"`, | |
| 206 | ), | |
| 207 | ), | |
| 208 | ...desc.map((line, i) => | |
| 209 | text( | |
| 210 | PAD, | |
| 211 | descTop + i * 44, | |
| 212 | line, | |
| 213 | `font-family="${SANS}" font-size="32" fill="${P["muted-fg"]}"`, | |
| 214 | ), | |
| 215 | ), | |
| 216 | notes(shownNotes, notesTop, width), | |
| 217 | stats(card.stats ?? []), | |
| 218 | text( | |
| 219 | PAD, | |
| 220 | 596, | |
| 221 | clip(card.host, 22, "mono", INNER), | |
| 222 | `font-family="${MONO}" font-size="22" fill="${P.faint}"`, | |
| 223 | ), | |
| 224 | `</svg>`, | |
| 225 | ].join(""); | |
| 226 | } |
src/web/og/graph.ts added +141
| @@ -0,0 +1,141 @@ | ||
| 1 | /** | |
| 2 | * The map as a thumbnail: the same layout the map page draws (`layout` in | |
| 3 | * `web/pages/map.ts` — a card one level below its deepest blocker, long | |
| 4 | * edges routed down the gutters), shrunk into a box, with the titles left | |
| 5 | * out because nobody reads 9 px type in a chat bubble. What is left is the | |
| 6 | * shape of the plan: each card filled by its word, and the critical path — | |
| 7 | * its cards and its edges — in the accent. | |
| 8 | * | |
| 9 | * ready success, outlined working accent, solid | |
| 10 | * blocked grey, filled waiting merged, outlined | |
| 11 | * parked attn, outlined done faint, outlined | |
| 12 | * | |
| 13 | * The proportions are the page's own (a 196 × 68 card, 28 across and 44 | |
| 14 | * down between them), so the thumbnail is the page seen from far away. | |
| 15 | * Plain data in, an SVG fragment out. | |
| 16 | */ | |
| 17 | ||
| 18 | import type { Word } from "../pages/map.ts"; | |
| 19 | import { P, px, type Box } from "./svg.ts"; | |
| 20 | ||
| 21 | export interface GraphNode { | |
| 22 | readonly level: number; | |
| 23 | readonly slot: number; | |
| 24 | readonly word: Word; | |
| 25 | readonly critical: boolean; | |
| 26 | } | |
| 27 | ||
| 28 | /** A spot a long edge passes through: a gutter at a level, shared by `lanes` lines. */ | |
| 29 | export interface GraphVia { | |
| 30 | readonly level: number; | |
| 31 | readonly gutter: number; | |
| 32 | readonly lane: number; | |
| 33 | readonly lanes: number; | |
| 34 | } | |
| 35 | ||
| 36 | export interface GraphEdge { | |
| 37 | /** Indices into `nodes`: the blocker, then what it holds up. */ | |
| 38 | readonly from: number; | |
| 39 | readonly to: number; | |
| 40 | readonly via: readonly GraphVia[]; | |
| 41 | readonly critical: boolean; | |
| 42 | /** Either end is closed: drawn faint. */ | |
| 43 | readonly done: boolean; | |
| 44 | } | |
| 45 | ||
| 46 | export interface GraphFigure { | |
| 47 | readonly kind: "graph"; | |
| 48 | /** The widest level, in slots. */ | |
| 49 | readonly width: number; | |
| 50 | readonly levels: number; | |
| 51 | readonly nodes: readonly GraphNode[]; | |
| 52 | readonly edges: readonly GraphEdge[]; | |
| 53 | } | |
| 54 | ||
| 55 | const W = 196; | |
| 56 | const H = 68; | |
| 57 | const GX = 28; | |
| 58 | const GY = 44; | |
| 59 | const LANE = 6; | |
| 60 | /** No bigger than this, so a plan of two cards is not two slabs. */ | |
| 61 | const MAX_SCALE = 0.62; | |
| 62 | ||
| 63 | /** The scale that fits a `width` × `levels` grid in the box: the smaller ratio, capped. */ | |
| 64 | export function graphScale(width: number, levels: number, box: Box): number { | |
| 65 | const w = Math.max(1, width) * (W + GX) - GX; | |
| 66 | const h = Math.max(1, levels) * (H + GY) - GY; | |
| 67 | return Math.min(box.w / w, box.h / h, MAX_SCALE); | |
| 68 | } | |
| 69 | ||
| 70 | function fill(word: Word): { fill: string; stroke: string } { | |
| 71 | switch (word) { | |
| 72 | case "ready": | |
| 73 | return { fill: P.card, stroke: P.success }; | |
| 74 | case "working": | |
| 75 | return { fill: P.accent, stroke: P.accent }; | |
| 76 | case "blocked": | |
| 77 | return { fill: P.border, stroke: P["border-strong"] }; | |
| 78 | case "waiting": | |
| 79 | return { fill: P.card, stroke: P.merged }; | |
| 80 | case "parked": | |
| 81 | return { fill: P.card, stroke: P.attn }; | |
| 82 | case "done": | |
| 83 | return { fill: P.bg, stroke: P.border }; | |
| 84 | } | |
| 85 | } | |
| 86 | ||
| 87 | export function graphSvg(fig: GraphFigure, box: Box): string { | |
| 88 | if (fig.nodes.length === 0) return ""; | |
| 89 | const s = graphScale(fig.width, fig.levels, box); | |
| 90 | const dw = (Math.max(1, fig.width) * (W + GX) - GX) * s; | |
| 91 | const dh = (Math.max(1, fig.levels) * (H + GY) - GY) * s; | |
| 92 | // Centred across, hung from the top: the plan reads downwards. | |
| 93 | const ox = box.x + (box.w - dw) / 2; | |
| 94 | const oy = box.y + Math.max(0, (box.h - dh) / 2); | |
| 95 | const x = (slot: number): number => ox + slot * (W + GX) * s; | |
| 96 | const y = (level: number): number => oy + level * (H + GY) * s; | |
| 97 | const gx = (v: GraphVia): number => | |
| 98 | x(v.gutter) - (GX / 2) * s + (v.lane - (v.lanes - 1) / 2) * LANE * s; | |
| 99 | const w = W * s; | |
| 100 | const h = H * s; | |
| 101 | const line = Math.max(1.5, Math.min(3, 4 * s)); | |
| 102 | ||
| 103 | const edges = fig.edges | |
| 104 | // The critical path last, so it is drawn over what it crosses. | |
| 105 | .toSorted((a, b) => Number(a.critical) - Number(b.critical)) | |
| 106 | .map((e) => { | |
| 107 | const from = fig.nodes[e.from]; | |
| 108 | const to = fig.nodes[e.to]; | |
| 109 | if (from === undefined || to === undefined) return ""; | |
| 110 | let cx = x(from.slot) + w / 2; | |
| 111 | let cy = y(from.level) + h; | |
| 112 | let d = `M${px(cx)} ${px(cy)}`; | |
| 113 | const hop = (nx: number, ny: number): void => { | |
| 114 | const bend = (ny - cy) / 2; | |
| 115 | d += `C${px(cx)} ${px(cy + bend)} ${px(nx)} ${px(ny - bend)} ${px(nx)} ${px(ny)}`; | |
| 116 | cx = nx; | |
| 117 | cy = ny; | |
| 118 | }; | |
| 119 | for (const v of e.via) { | |
| 120 | const vx = gx(v); | |
| 121 | hop(vx, y(v.level)); | |
| 122 | cy = y(v.level) + h; | |
| 123 | d += `L${px(vx)} ${px(cy)}`; | |
| 124 | } | |
| 125 | hop(x(to.slot) + w / 2, y(to.level)); | |
| 126 | const stroke = e.critical ? P.accent : e.done ? P.border : P["border-strong"]; | |
| 127 | return `<path d="${d}" fill="none" stroke="${stroke}" stroke-width="${px(e.critical ? line * 1.6 : line)}"/>`; | |
| 128 | }) | |
| 129 | .join(""); | |
| 130 | ||
| 131 | const nodes = fig.nodes | |
| 132 | .map((n) => { | |
| 133 | const c = fill(n.word); | |
| 134 | const stroke = n.critical && n.word !== "working" ? P.accent : c.stroke; | |
| 135 | const sw = n.critical ? line * 1.6 : line; | |
| 136 | return `<rect x="${px(x(n.slot))}" y="${px(y(n.level))}" width="${px(w)}" height="${px(h)}" rx="${px(Math.min(10, 8 * s + 1))}" fill="${c.fill}" stroke="${stroke}" stroke-width="${px(sw)}"/>`; | |
| 137 | }) | |
| 138 | .join(""); | |
| 139 | ||
| 140 | return `<g>${edges}${nodes}</g>`; | |
| 141 | } |
src/web/og/kinds.ts added +86
| @@ -0,0 +1,86 @@ | ||
| 1 | /** | |
| 2 | * What each kind of preview says: `/og/<kind>/<path>.png` names a kind and | |
| 3 | * the thing it is a picture of, and the kind reads that thing's data and | |
| 4 | * answers a `Card`. A new design (the map, the audit, an app, a change — | |
| 5 | * #454, #455) is a new entry in `KINDS`, or a richer card from an old one. | |
| 6 | * | |
| 7 | * A preview is fetched by unfurlers — iMessage, Slack, X, Discord — and | |
| 8 | * they are anonymous, so every kind reads as nobody. That is mechanical, | |
| 9 | * not a convention: a loader is handed `OgSource`, which carries the | |
| 10 | * database and the forge's host and no viewer at all, so a signed-in | |
| 11 | * person's access can never end up drawn into a cached, shareable PNG. | |
| 12 | * | |
| 13 | * A thing nobody may see and a thing that does not exist draw the same | |
| 14 | * card — one card, no name on it, "private" — the picture-shaped twin of | |
| 15 | * `not_found`'s deliberate ambiguity. | |
| 16 | */ | |
| 17 | ||
| 18 | import { canRead, countsForRepos, getRepo } from "../../core/repos.ts"; | |
| 19 | import { auditKind } from "./audit.ts"; | |
| 20 | import { mapKind } from "./map.ts"; | |
| 21 | import { NAME, plural, privateCard, type Kind } from "./source.ts"; | |
| 22 | ||
| 23 | export { privateCard, type Kind, type OgSource } from "./source.ts"; | |
| 24 | ||
| 25 | /** `/og/site/home.png` — the forge itself: what it holds in the open. */ | |
| 26 | const site: Kind = (source, path) => { | |
| 27 | if (path.length !== 1 || path[0] !== "home") return undefined; | |
| 28 | const row = source.db | |
| 29 | .query<{ repos: number; issues: number; pulls: number }, []>( | |
| 30 | `SELECT | |
| 31 | (SELECT COUNT(*) FROM repo WHERE visibility = 'public') AS repos, | |
| 32 | (SELECT COUNT(*) FROM issue JOIN repo ON repo.id = issue.repo_id | |
| 33 | WHERE repo.visibility = 'public' AND issue.state = 'open' AND issue.kind = 'issue') AS issues, | |
| 34 | (SELECT COUNT(*) FROM issue JOIN repo ON repo.id = issue.repo_id | |
| 35 | WHERE repo.visibility = 'public' AND issue.state = 'open' AND issue.kind = 'pull') AS pulls`, | |
| 36 | ) | |
| 37 | .get() ?? { repos: 0, issues: 0, pulls: 0 }; | |
| 38 | return { | |
| 39 | eyebrow: "forge", | |
| 40 | // The host's first label names the forge; the whole host is the footer. | |
| 41 | title: source.host.split(".")[0] || source.host, | |
| 42 | description: "Your code, your machine: repositories, apps and the crew that builds them.", | |
| 43 | stats: [ | |
| 44 | { value: String(row.repos), label: plural(row.repos, "public repository", "public repositories") }, | |
| 45 | { value: String(row.issues), label: `open ${plural(row.issues, "issue")}` }, | |
| 46 | { value: String(row.pulls), label: `open ${plural(row.pulls, "change")}`, tone: row.pulls > 0 ? "accent" : "muted" }, | |
| 47 | ], | |
| 48 | host: source.host, | |
| 49 | }; | |
| 50 | }; | |
| 51 | ||
| 52 | /** `/og/repo/<owner>/<name>.png` — a repository: what it is, and what is open. */ | |
| 53 | const repo: Kind = (source, path) => { | |
| 54 | const [owner, name] = path; | |
| 55 | if (path.length !== 2 || owner === undefined || name === undefined) return undefined; | |
| 56 | if (!NAME.test(owner) || !NAME.test(name)) return undefined; | |
| 57 | const found = getRepo(source.db, owner, name); | |
| 58 | if (found === undefined || !canRead(source.db, found, undefined)) | |
| 59 | return privateCard(source); | |
| 60 | const counts = countsForRepos(source.db, [found.id]).get(found.id); | |
| 61 | const issues = counts?.openIssues ?? 0; | |
| 62 | const pulls = counts?.openPulls ?? 0; | |
| 63 | return { | |
| 64 | eyebrow: `${found.ownerName}/${found.name}`, | |
| 65 | title: found.name, | |
| 66 | ...(found.description.trim() === "" ? {} : { description: found.description.trim() }), | |
| 67 | state: { label: "public", tone: "success" }, | |
| 68 | stats: [ | |
| 69 | { value: String(issues), label: `open ${plural(issues, "issue")}` }, | |
| 70 | { value: String(pulls), label: `open ${plural(pulls, "change")}`, tone: pulls > 0 ? "accent" : "muted" }, | |
| 71 | { value: found.defaultBranch, label: "default branch", tone: "muted" }, | |
| 72 | ], | |
| 73 | host: source.host, | |
| 74 | }; | |
| 75 | }; | |
| 76 | ||
| 77 | export const KINDS: Readonly<Record<string, Kind>> = { | |
| 78 | site, | |
| 79 | repo, | |
| 80 | map: mapKind, | |
| 81 | audit: auditKind, | |
| 82 | }; | |
| 83 | ||
| 84 | export function kindNamed(name: string): Kind | undefined { | |
| 85 | return Object.hasOwn(KINDS, name) ? KINDS[name] : undefined; | |
| 86 | } |
src/web/og/link.ts added +32
| @@ -0,0 +1,32 @@ | ||
| 1 | /** | |
| 2 | * Which card a page names in its head (`PageOptions.og` in `layout.ts`). | |
| 3 | * | |
| 4 | * The card is drawn as nobody (`source.ts`), so a page names one only for | |
| 5 | * what an anonymous unfurler may read. A private repository's page, seen by | |
| 6 | * its own crew, keeps the forge's icon: naming `/og/repo/<owner>/<name>.png` | |
| 7 | * would put the name into every unfurl of the link and draw "private" under | |
| 8 | * it — a preview that tells a stranger more than the 404 they would get. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { Database } from "bun:sqlite"; | |
| 12 | import { canRead, type Repo } from "../../core/repos.ts"; | |
| 13 | ||
| 14 | /** The forge's own card, for its front door. */ | |
| 15 | export const SITE_CARD: readonly string[] = ["site", "home"]; | |
| 16 | ||
| 17 | /** The audit's card: the policy score and the worst findings. */ | |
| 18 | export const AUDIT_CARD: readonly string[] = ["audit", "all"]; | |
| 19 | ||
| 20 | /** Every public plan at once, for the forge-wide map. */ | |
| 21 | export const MAP_CARD: readonly string[] = ["map", "all"]; | |
| 22 | ||
| 23 | /** A repository's card (`repo`) or its map's (`map`), when it is public. */ | |
| 24 | export function repoCard( | |
| 25 | db: Database, | |
| 26 | repo: Repo, | |
| 27 | kind: "repo" | "map", | |
| 28 | ): readonly string[] | undefined { | |
| 29 | return canRead(db, repo, undefined) | |
| 30 | ? [kind, repo.ownerName, repo.name] | |
| 31 | : undefined; | |
| 32 | } |
src/web/og/map.ts added +260
| @@ -0,0 +1,260 @@ | ||
| 1 | /** | |
| 2 | * The map's preview: the plan as a thumbnail, and the words counted. | |
| 3 | * | |
| 4 | * /og/map/<owner>/<name>.png one repository's map (`/:owner/:name/map`) | |
| 5 | * /og/map/all.png every public repository's (`/map`) | |
| 6 | * | |
| 7 | * It reads what the map page reads — the graph, the ready list, the | |
| 8 | * critical path, the crew's runs, the pulls that would close an issue — | |
| 9 | * through the same functions, so the picture and the page cannot disagree | |
| 10 | * on a word. It reads as nobody (`source.ts`): a private repository is the | |
| 11 | * private card, and the forge-wide map is only the public repositories. | |
| 12 | */ | |
| 13 | ||
| 14 | import { | |
| 15 | criticalPath, | |
| 16 | readyNow, | |
| 17 | repoGraph, | |
| 18 | type Graph, | |
| 19 | } from "../../core/dependencies.ts"; | |
| 20 | import { canRead, getRepo, listReposVisibleTo } from "../../core/repos.ts"; | |
| 21 | import { listActiveRuns } from "../../core/runs.ts"; | |
| 22 | import { | |
| 23 | countWords, | |
| 24 | layout, | |
| 25 | marksFor, | |
| 26 | wordFor, | |
| 27 | type Marks, | |
| 28 | type Word, | |
| 29 | } from "../pages/map.ts"; | |
| 30 | import { sha256 } from "../../kernel/hash.ts"; | |
| 31 | import type { Card, Stat } from "./card.ts"; | |
| 32 | import type { GraphEdge, GraphFigure, GraphNode } from "./graph.ts"; | |
| 33 | import { NAME, plural, privateCard, type Kind, type OgSource } from "./source.ts"; | |
| 34 | ||
| 35 | /** The forge-wide map draws at most this many issues, as the page's own graph does per repository. */ | |
| 36 | const ALL_MAX_ISSUES = 400; | |
| 37 | const ALL_MAX_REPOS = 50; | |
| 38 | /** Unlinked issues are drawn only when nothing is linked, and then this many rows. */ | |
| 39 | const ISLAND_ROWS = 4; | |
| 40 | ||
| 41 | /** | |
| 42 | * Thumbnails by what they are drawn from. The layout is the one costly | |
| 43 | * step (tens of ms at the page's 400-issue bound), and an unfurl storm | |
| 44 | * asks for one map many times; the key is the whole input, so an entry is | |
| 45 | * never stale, only no longer asked for. | |
| 46 | */ | |
| 47 | const FIGURES = new Map<string, GraphFigure | undefined>(); | |
| 48 | const FIGURES_MAX = 64; | |
| 49 | ||
| 50 | function figureKey( | |
| 51 | graph: Graph, | |
| 52 | words: ReadonlyMap<string, Word>, | |
| 53 | critical: readonly string[], | |
| 54 | ): string { | |
| 55 | return sha256( | |
| 56 | JSON.stringify([ | |
| 57 | graph.issues.map((i) => [i.id, words.get(i.id) ?? ""]), | |
| 58 | graph.edges.map((e) => [e.blockedById, e.issueId]), | |
| 59 | critical, | |
| 60 | ]), | |
| 61 | ); | |
| 62 | } | |
| 63 | ||
| 64 | /** `graphFigure`, remembered by its input. */ | |
| 65 | export function cachedGraphFigure( | |
| 66 | graph: Graph, | |
| 67 | words: ReadonlyMap<string, Word>, | |
| 68 | critical: readonly string[], | |
| 69 | ): GraphFigure | undefined { | |
| 70 | const key = figureKey(graph, words, critical); | |
| 71 | if (FIGURES.has(key)) { | |
| 72 | const hit = FIGURES.get(key); | |
| 73 | FIGURES.delete(key); | |
| 74 | FIGURES.set(key, hit); | |
| 75 | return hit; | |
| 76 | } | |
| 77 | const made = graphFigure(graph, words, critical); | |
| 78 | FIGURES.set(key, made); | |
| 79 | if (FIGURES.size > FIGURES_MAX) FIGURES.delete(FIGURES.keys().next().value!); | |
| 80 | return made; | |
| 81 | } | |
| 82 | ||
| 83 | /** | |
| 84 | * The thumbnail's data from a laid-out graph: the chains when there are | |
| 85 | * any (the unlinked issues are counted, not drawn — a grid of loose cards | |
| 86 | * says nothing at this size), otherwise the first few rows of loose ones. | |
| 87 | */ | |
| 88 | export function graphFigure( | |
| 89 | graph: Graph, | |
| 90 | words: ReadonlyMap<string, Word>, | |
| 91 | critical: readonly string[], | |
| 92 | ): GraphFigure | undefined { | |
| 93 | const placed = layout(graph); | |
| 94 | const chained = placed.islandFrom > 0; | |
| 95 | const drawn = placed.nodes.filter((n) => | |
| 96 | chained ? !n.island : n.level < ISLAND_ROWS, | |
| 97 | ); | |
| 98 | if (drawn.length === 0) return undefined; | |
| 99 | const index = new Map(drawn.map((n, i) => [n.issue.id, i])); | |
| 100 | const onPath = new Set(critical); | |
| 101 | const chain = new Set<string>(); | |
| 102 | for (let i = 0; i + 1 < critical.length; i++) | |
| 103 | chain.add(`${critical[i]}>${critical[i + 1]}`); | |
| 104 | const via = new Map(placed.routes.map((r) => [`${r.blockedById}>${r.issueId}`, r.via])); | |
| 105 | const nodes: GraphNode[] = drawn.map((n) => ({ | |
| 106 | level: n.level, | |
| 107 | slot: n.slot, | |
| 108 | word: words.get(n.issue.id) ?? "blocked", | |
| 109 | critical: onPath.has(n.issue.id), | |
| 110 | })); | |
| 111 | const edges: GraphEdge[] = []; | |
| 112 | for (const e of graph.edges) { | |
| 113 | const from = index.get(e.blockedById); | |
| 114 | const to = index.get(e.issueId); | |
| 115 | if (from === undefined || to === undefined) continue; | |
| 116 | const key = `${e.blockedById}>${e.issueId}`; | |
| 117 | edges.push({ | |
| 118 | from, | |
| 119 | to, | |
| 120 | via: (via.get(key) ?? []).map((v) => ({ | |
| 121 | level: v.level, | |
| 122 | gutter: v.gutter, | |
| 123 | lane: v.lane, | |
| 124 | lanes: v.lanes, | |
| 125 | })), | |
| 126 | critical: chain.has(key), | |
| 127 | done: nodes[from]!.word === "done" || nodes[to]!.word === "done", | |
| 128 | }); | |
| 129 | } | |
| 130 | return { | |
| 131 | kind: "graph", | |
| 132 | width: Math.max(...nodes.map((n) => n.slot)) + 1, | |
| 133 | levels: Math.max(...nodes.map((n) => n.level)) + 1, | |
| 134 | nodes, | |
| 135 | edges, | |
| 136 | }; | |
| 137 | } | |
| 138 | ||
| 139 | /** The sentence under the title: how much is open, how long the chain still to go is, what is next. */ | |
| 140 | export function mapSentence( | |
| 141 | open: number, | |
| 142 | path: readonly { number: number }[], | |
| 143 | next: { number: number; title: string } | undefined, | |
| 144 | ): string { | |
| 145 | if (open === 0) return "Nothing open: every issue on the map is done."; | |
| 146 | const parts = [`${open} open ${plural(open, "issue")}`]; | |
| 147 | if (path.length > 1) | |
| 148 | parts.push( | |
| 149 | `the critical path is ${path.length} issues, #${path[0]!.number} to #${path.at(-1)!.number}`, | |
| 150 | ); | |
| 151 | else parts.push("none waiting on another"); | |
| 152 | const said = `${parts.join("; ")}.`; | |
| 153 | return next === undefined ? said : `${said} Next: #${next.number} ${next.title}`; | |
| 154 | } | |
| 155 | ||
| 156 | /** A map's card, from its graph and what is known beyond it. */ | |
| 157 | export function mapCard( | |
| 158 | head: { readonly eyebrow: string; readonly title: string; readonly host: string }, | |
| 159 | graph: Graph, | |
| 160 | marks: Marks, | |
| 161 | ): Card { | |
| 162 | const ready = readyNow(graph); | |
| 163 | const path = criticalPath(graph); | |
| 164 | const readySet = new Set(ready.map((r) => r.issue.id)); | |
| 165 | const words = new Map(graph.issues.map((i) => [i.id, wordFor(i, readySet, marks)])); | |
| 166 | const counts = countWords([...words.values()]); | |
| 167 | const open = graph.issues.filter((i) => i.state === "open").length; | |
| 168 | const figure = cachedGraphFigure( | |
| 169 | graph, | |
| 170 | words, | |
| 171 | path.map((i) => i.id), | |
| 172 | ); | |
| 173 | const fourth: Stat = | |
| 174 | counts.waiting > 0 | |
| 175 | ? { value: String(counts.waiting), label: "waiting on a change", tone: "merged" } | |
| 176 | : { value: String(counts.done), label: "done", tone: "muted" }; | |
| 177 | const state: Card["state"] = | |
| 178 | open === 0 | |
| 179 | ? { label: "done", tone: "muted" } | |
| 180 | : counts.working > 0 | |
| 181 | ? { label: "working", tone: "accent" } | |
| 182 | : counts.ready > 0 | |
| 183 | ? { label: "ready", tone: "success" } | |
| 184 | : { label: "blocked", tone: "attn" }; | |
| 185 | // Next is what a free hand would take: ready, and nobody on it yet. | |
| 186 | const next = ready.find((r) => words.get(r.issue.id) === "ready")?.issue; | |
| 187 | return { | |
| 188 | eyebrow: head.eyebrow, | |
| 189 | title: head.title, | |
| 190 | description: mapSentence(open, path, next), | |
| 191 | state, | |
| 192 | ...(figure === undefined ? {} : { figure }), | |
| 193 | stats: [ | |
| 194 | { value: String(counts.ready), label: "ready", tone: "success" }, | |
| 195 | { value: String(counts.working), label: "working", tone: "accent" }, | |
| 196 | { value: String(counts.blocked), label: "blocked" }, | |
| 197 | fourth, | |
| 198 | ], | |
| 199 | host: head.host, | |
| 200 | }; | |
| 201 | } | |
| 202 | ||
| 203 | function repoMap(source: OgSource, owner: string, name: string): Card { | |
| 204 | const found = getRepo(source.db, owner, name); | |
| 205 | if (found === undefined || !canRead(source.db, found, undefined)) | |
| 206 | return privateCard(source); | |
| 207 | const graph = repoGraph(source.db, found.id); | |
| 208 | const marks = marksFor(source.db, found.id, graph, listActiveRuns(source.db, [found.id])); | |
| 209 | return mapCard( | |
| 210 | { eyebrow: `${found.ownerName}/${found.name} · map`, title: found.name, host: source.host }, | |
| 211 | graph, | |
| 212 | marks, | |
| 213 | ); | |
| 214 | } | |
| 215 | ||
| 216 | /** | |
| 217 | * Every public repository's plan as one graph. Issue ids are forge-wide | |
| 218 | * and an edge never crosses repositories, so the graphs simply concatenate | |
| 219 | * and their chains lie side by side, a level meaning the same in each. | |
| 220 | */ | |
| 221 | function forgeMap(source: OgSource): Card { | |
| 222 | const repos = listReposVisibleTo(source.db, undefined, { limit: ALL_MAX_REPOS }); | |
| 223 | const issues: Graph["issues"][number][] = []; | |
| 224 | const edges: Graph["edges"][number][] = []; | |
| 225 | const held: Graph["held"][number][] = []; | |
| 226 | const crew: Marks["crew"] = new Map(); | |
| 227 | const waiting = new Set<string>(); | |
| 228 | const parked = new Set<string>(); | |
| 229 | const why: Marks["why"] = new Map(); | |
| 230 | const runs = listActiveRuns( | |
| 231 | source.db, | |
| 232 | repos.map((r) => r.id), | |
| 233 | ); | |
| 234 | for (const repo of repos) { | |
| 235 | const graph = repoGraph(source.db, repo.id); | |
| 236 | if (graph.issues.length === 0) continue; | |
| 237 | if (issues.length + graph.issues.length > ALL_MAX_ISSUES) break; | |
| 238 | issues.push(...graph.issues); | |
| 239 | edges.push(...graph.edges); | |
| 240 | held.push(...graph.held); | |
| 241 | const marks = marksFor(source.db, repo.id, graph, runs); | |
| 242 | for (const [id, state] of marks.crew) crew.set(id, state); | |
| 243 | for (const id of marks.waiting) waiting.add(id); | |
| 244 | for (const id of marks.parked) parked.add(id); | |
| 245 | for (const [id, note] of marks.why) why.set(id, note); | |
| 246 | } | |
| 247 | return mapCard( | |
| 248 | { eyebrow: "forge · map", title: "Map", host: source.host }, | |
| 249 | { issues, edges, held }, | |
| 250 | { crew, waiting, parked, why }, | |
| 251 | ); | |
| 252 | } | |
| 253 | ||
| 254 | export const mapKind: Kind = (source, path) => { | |
| 255 | if (path.length === 1 && path[0] === "all") return forgeMap(source); | |
| 256 | const [owner, name] = path; | |
| 257 | if (path.length !== 2 || owner === undefined || name === undefined) return undefined; | |
| 258 | if (!NAME.test(owner) || !NAME.test(name)) return undefined; | |
| 259 | return repoMap(source, owner, name); | |
| 260 | }; |
src/web/og/metrics.ts added +132
| @@ -0,0 +1,132 @@ | ||
| 1 | /** | |
| 2 | * How wide a line of text is, before anything draws it. SVG has no line | |
| 3 | * wrapping, so a title that would run off a 1200 px card has to be broken | |
| 4 | * and clipped here, by arithmetic, before the rasterizer ever sees it. | |
| 5 | * | |
| 6 | * The widths are the fonts' own: the horizontal advances (`hmtx`, indexed | |
| 7 | * through `cmap` format 4) of Liberation Sans Regular and Bold for U+0020… | |
| 8 | * U+007E, in font units of a 2048-unit em, read out of the TTFs the image | |
| 9 | * ships (`fonts-liberation`). Liberation Sans is metric-compatible with | |
| 10 | * Arial by design, so the same table is exact for either. Liberation Mono | |
| 11 | * is 1229/2048 em for every glyph. | |
| 12 | * | |
| 13 | * width(px) = Σ advance(ch) × size(px) / 2048 | |
| 14 | * | |
| 15 | * Anything outside ASCII is counted at a digit's width (1139/2048 — also | |
| 16 | * the advance of `é`), and a wide (CJK) character at a full em: an | |
| 17 | * estimate that errs wide, so a line is clipped early rather than late. | |
| 18 | */ | |
| 19 | ||
| 20 | export type Face = "sans" | "bold" | "mono"; | |
| 21 | ||
| 22 | const EM = 2048; | |
| 23 | ||
| 24 | // prettier-ignore | |
| 25 | const SANS = [ | |
| 26 | 569,569,727,1139,1139,1821,1366,391,682,682,797,1196,569,682,569,569, | |
| 27 | 1139,1139,1139,1139,1139,1139,1139,1139,1139,1139,569,569,1196,1196,1196,1139, | |
| 28 | 2079,1366,1366,1479,1479,1366,1251,1593,1479,569,1024,1366,1139,1706,1479,1593, | |
| 29 | 1366,1593,1479,1366,1251,1479,1366,1933,1366,1366,1251,569,569,569,961,1139, | |
| 30 | 682,1139,1139,1024,1139,1139,569,1139,1139,455,455,1024,455,1706,1139,1139, | |
| 31 | 1139,1139,682,1024,569,1139,1024,1479,1024,1024,1024,684,532,684,1196, | |
| 32 | ]; | |
| 33 | ||
| 34 | // prettier-ignore | |
| 35 | const BOLD = [ | |
| 36 | 569,682,971,1139,1139,1821,1479,487,682,682,797,1196,569,682,569,569, | |
| 37 | 1139,1139,1139,1139,1139,1139,1139,1139,1139,1139,682,682,1196,1196,1196,1251, | |
| 38 | 1997,1479,1479,1479,1479,1366,1251,1593,1479,569,1139,1479,1251,1706,1479,1593, | |
| 39 | 1366,1593,1479,1366,1251,1479,1366,1933,1366,1366,1251,682,569,682,1196,1139, | |
| 40 | 682,1139,1251,1139,1251,1139,682,1251,1251,569,569,1139,569,1821,1251,1251, | |
| 41 | 1251,1251,797,1139,682,1251,1139,1593,1139,1139,1024,797,573,797,1196, | |
| 42 | ]; | |
| 43 | ||
| 44 | const MONO = 1229; | |
| 45 | const OTHER = 1139; | |
| 46 | /** `…` U+2026 in both sans faces; one mono cell in mono. */ | |
| 47 | const ELLIPSIS = "…"; | |
| 48 | ||
| 49 | function isWide(code: number): boolean { | |
| 50 | return ( | |
| 51 | (code >= 0x1100 && code <= 0x115f) || | |
| 52 | (code >= 0x2e80 && code <= 0xa4cf) || | |
| 53 | (code >= 0xac00 && code <= 0xd7a3) || | |
| 54 | (code >= 0xf900 && code <= 0xfaff) || | |
| 55 | (code >= 0xff00 && code <= 0xff60) || | |
| 56 | code >= 0x1f300 | |
| 57 | ); | |
| 58 | } | |
| 59 | ||
| 60 | function advance(ch: string, face: Face): number { | |
| 61 | const code = ch.codePointAt(0) ?? 0; | |
| 62 | if (face === "mono") return isWide(code) ? EM : MONO; | |
| 63 | if (code === 0x2026) return EM; | |
| 64 | if (code >= 0x20 && code <= 0x7e) { | |
| 65 | const table = face === "bold" ? BOLD : SANS; | |
| 66 | return table[code - 0x20] ?? OTHER; | |
| 67 | } | |
| 68 | return isWide(code) ? EM : OTHER; | |
| 69 | } | |
| 70 | ||
| 71 | /** The width in pixels of `text` set in `face` at `size` px. */ | |
| 72 | export function measure(text: string, size: number, face: Face): number { | |
| 73 | let units = 0; | |
| 74 | for (const ch of text) units += advance(ch, face); | |
| 75 | return (units * size) / EM; | |
| 76 | } | |
| 77 | ||
| 78 | /** `text` cut to fit `max` px, ending in `…` when anything was cut. */ | |
| 79 | export function clip( | |
| 80 | text: string, | |
| 81 | size: number, | |
| 82 | face: Face, | |
| 83 | max: number, | |
| 84 | ): string { | |
| 85 | if (measure(text, size, face) <= max) return text; | |
| 86 | const room = max - measure(ELLIPSIS, size, face); | |
| 87 | let used = 0; | |
| 88 | let out = ""; | |
| 89 | for (const ch of text) { | |
| 90 | const w = (advance(ch, face) * size) / EM; | |
| 91 | if (used + w > room) break; | |
| 92 | used += w; | |
| 93 | out += ch; | |
| 94 | } | |
| 95 | return `${out.trimEnd()}${ELLIPSIS}`; | |
| 96 | } | |
| 97 | ||
| 98 | /** | |
| 99 | * `text` broken at spaces into at most `lines` lines of at most `max` px; | |
| 100 | * the last line is clipped with `…` when the text does not fit. A word | |
| 101 | * longer than a whole line is clipped where it stands. | |
| 102 | */ | |
| 103 | export function wrap( | |
| 104 | text: string, | |
| 105 | size: number, | |
| 106 | face: Face, | |
| 107 | max: number, | |
| 108 | lines: number, | |
| 109 | ): string[] { | |
| 110 | const words = text.split(/\s+/).filter((w) => w !== ""); | |
| 111 | const out: string[] = []; | |
| 112 | let i = 0; | |
| 113 | while (i < words.length && out.length < lines) { | |
| 114 | // The last line allowed takes everything left, clipped. | |
| 115 | if (out.length === lines - 1) { | |
| 116 | out.push(clip(words.slice(i).join(" "), size, face, max)); | |
| 117 | break; | |
| 118 | } | |
| 119 | let line = words[i++]!; | |
| 120 | if (measure(line, size, face) > max) { | |
| 121 | out.push(clip(line, size, face, max)); | |
| 122 | continue; | |
| 123 | } | |
| 124 | while ( | |
| 125 | i < words.length && | |
| 126 | measure(`${line} ${words[i]}`, size, face) <= max | |
| 127 | ) | |
| 128 | line = `${line} ${words[i++]}`; | |
| 129 | out.push(line); | |
| 130 | } | |
| 131 | return out; | |
| 132 | } |
src/web/og/raster.ts added +141
| @@ -0,0 +1,141 @@ | ||
| 1 | /** | |
| 2 | * SVG → PNG, by resvg (https://github.com/linebender/resvg): a static | |
| 3 | * binary, spawned the way git and chromium are — the forge's dependency | |
| 4 | * list stays empty, and the host provides the tool (the Dockerfile pins a | |
| 5 | * release and its sha256). A cold render of a card is one spawn and about | |
| 6 | * 60–90 ms; the cache in front of it (`cache.ts`) makes the second one free. | |
| 7 | * | |
| 8 | * The fonts are handed over by file, with system fonts skipped, when the | |
| 9 | * three faces the card is measured against are on the machine | |
| 10 | * (`metrics.ts` holds their advances): what was measured is what is drawn, | |
| 11 | * and the render does not depend on whatever else fontconfig would find. | |
| 12 | * Without them resvg falls back to the system's fonts, and the text still | |
| 13 | * draws, a few pixels off the arithmetic. | |
| 14 | * | |
| 15 | * Nothing in the SVG can reach outside it: the card emits no `href`, and | |
| 16 | * `--resources-dir` points at a directory that does not exist. | |
| 17 | */ | |
| 18 | ||
| 19 | import { existsSync } from "node:fs"; | |
| 20 | import { join } from "node:path"; | |
| 21 | import { childEnv } from "../../apps/process.ts"; | |
| 22 | import { Gate } from "../../git/env.ts"; | |
| 23 | import { isPng } from "../../design/image/png.ts"; | |
| 24 | import { err, ok, type Result } from "../../kernel/result.ts"; | |
| 25 | ||
| 26 | /** The resvg binary: `FORGE_RESVG`, else `resvg` on `PATH`. */ | |
| 27 | export function findResvg(): string | undefined { | |
| 28 | const named = (process.env["FORGE_RESVG"] ?? "").trim(); | |
| 29 | if (named !== "") return existsSync(named) ? named : undefined; | |
| 30 | return Bun.which("resvg") ?? undefined; | |
| 31 | } | |
| 32 | ||
| 33 | const FACES = [ | |
| 34 | "LiberationSans-Regular.ttf", | |
| 35 | "LiberationSans-Bold.ttf", | |
| 36 | "LiberationMono-Regular.ttf", | |
| 37 | ] as const; | |
| 38 | ||
| 39 | const FONT_DIRS = [ | |
| 40 | "/usr/share/fonts/truetype/liberation", | |
| 41 | "/usr/share/fonts/truetype/liberation2", | |
| 42 | "/usr/share/fonts/liberation-sans", | |
| 43 | "/usr/share/fonts/liberation", | |
| 44 | "/opt/homebrew/share/fonts", | |
| 45 | "/usr/local/share/fonts", | |
| 46 | ]; | |
| 47 | ||
| 48 | /** | |
| 49 | * The three font files, from `FORGE_OG_FONTS` (a directory) or the places | |
| 50 | * distributions put `fonts-liberation` — or undefined when any is missing. | |
| 51 | */ | |
| 52 | export function findFonts(): readonly string[] | undefined { | |
| 53 | const named = (process.env["FORGE_OG_FONTS"] ?? "").trim(); | |
| 54 | for (const dir of named !== "" ? [named] : FONT_DIRS) { | |
| 55 | const files = FACES.map((f) => join(dir, f)); | |
| 56 | if (files.every((f) => existsSync(f))) return files; | |
| 57 | } | |
| 58 | return undefined; | |
| 59 | } | |
| 60 | ||
| 61 | /** The argv after the binary: fonts, families, then stdin → stdout. */ | |
| 62 | export function resvgArgs(fonts: readonly string[] | undefined): string[] { | |
| 63 | const args: string[] = []; | |
| 64 | if (fonts !== undefined) { | |
| 65 | args.push("--skip-system-fonts"); | |
| 66 | for (const f of fonts) args.push("--use-font-file", f); | |
| 67 | } | |
| 68 | args.push( | |
| 69 | "--sans-serif-family", | |
| 70 | "Liberation Sans", | |
| 71 | "--monospace-family", | |
| 72 | "Liberation Mono", | |
| 73 | "--resources-dir", | |
| 74 | "/nonexistent/forge-og", | |
| 75 | "-", | |
| 76 | "-c", | |
| 77 | ); | |
| 78 | return args; | |
| 79 | } | |
| 80 | ||
| 81 | /** | |
| 82 | * Two renders at once, forge-wide, and at most `MAX_WAITING` in line: an | |
| 83 | * unfurler storm queues, and a flood of made-up URLs (each one a distinct | |
| 84 | * card, so each one a cold render) is refused rather than piled up. | |
| 85 | */ | |
| 86 | const gate = new Gate(2); | |
| 87 | export const MAX_WAITING = 16; | |
| 88 | /** Renders running plus renders waiting for a permit. */ | |
| 89 | let inFlight = 0; | |
| 90 | ||
| 91 | const TIMEOUT_MS = 5_000; | |
| 92 | const MAX_SVG = 256 * 1024; | |
| 93 | ||
| 94 | /** Rasterize `svg` to PNG bytes. */ | |
| 95 | export async function rasterize( | |
| 96 | svg: string, | |
| 97 | ): Promise<Result<Uint8Array, string>> { | |
| 98 | const binary = findResvg(); | |
| 99 | if (binary === undefined) | |
| 100 | return err("no resvg on this forge: install one, or set FORGE_RESVG"); | |
| 101 | if (svg.length > MAX_SVG) return err("the SVG is larger than a card can be"); | |
| 102 | if (inFlight >= gate.limit + MAX_WAITING) | |
| 103 | return err("busy: too many previews rendering"); | |
| 104 | inFlight++; | |
| 105 | const release = await gate.acquire(); | |
| 106 | try { | |
| 107 | const proc = Bun.spawn([binary, ...resvgArgs(findFonts())], { | |
| 108 | env: childEnv({}), | |
| 109 | stdin: new TextEncoder().encode(svg), | |
| 110 | stdout: "pipe", | |
| 111 | stderr: "pipe", | |
| 112 | }); | |
| 113 | const timer = setTimeout(() => proc.kill("SIGKILL"), TIMEOUT_MS); | |
| 114 | try { | |
| 115 | // `arrayBuffer()`, not `bytes()`: Bun 1.3's `bytes()` on a spawned | |
| 116 | // pipe sometimes resolves to a bare ArrayBuffer. | |
| 117 | const [out, said, code] = await Promise.all([ | |
| 118 | new Response(proc.stdout).arrayBuffer(), | |
| 119 | new Response(proc.stderr).text(), | |
| 120 | proc.exited, | |
| 121 | ]); | |
| 122 | const png = new Uint8Array(out); | |
| 123 | if (code !== 0 || !isPng(png)) { | |
| 124 | const last = said | |
| 125 | .split("\n") | |
| 126 | .map((l) => l.trim()) | |
| 127 | .filter((l) => l !== "" && !l.startsWith("Warning")) | |
| 128 | .at(-1); | |
| 129 | return err( | |
| 130 | `resvg exited ${code}${last === undefined ? "" : `: ${last.slice(0, 300)}`}`, | |
| 131 | ); | |
| 132 | } | |
| 133 | return ok(png); | |
| 134 | } finally { | |
| 135 | clearTimeout(timer); | |
| 136 | } | |
| 137 | } finally { | |
| 138 | release(); | |
| 139 | inFlight--; | |
| 140 | } | |
| 141 | } |
src/web/og/route.ts added +126
| @@ -0,0 +1,126 @@ | ||
| 1 | /** | |
| 2 | * GET /og/:kind/*path — a link preview, 1200 × 630. | |
| 3 | * | |
| 4 | * /og/site/home.png the forge | |
| 5 | * /og/repo/<owner>/<name>.png a repository | |
| 6 | * /og/map/<owner>/<name>.png a repository's map; /og/map/all.png, the forge's | |
| 7 | * /og/audit/all.png the audit: the policy score, the top findings | |
| 8 | * …/<thing>.svg the same card before rasterizing, for | |
| 9 | * looking at and for tests | |
| 10 | * | |
| 11 | * The kind reads its data as nobody (`kinds.ts`), the card is drawn from | |
| 12 | * that data (`card.ts`), and the PNG is kept under the sha256 of the data | |
| 13 | * (`cache.ts`), which is also its ETag. `cache-control` is short: the data | |
| 14 | * is live, and a preview that is five minutes stale is still the story. | |
| 15 | * | |
| 16 | * A cold render is a resvg spawn, so it is the one thing here that is | |
| 17 | * limited per caller: `COLD_PER_MINUTE` misses an address may cause, keyed | |
| 18 | * on the socket (`Ctx.peer`). A cached card, a render already running for | |
| 19 | * someone else and a 304 cost nothing and count for nothing; past the limit | |
| 20 | * the answer is 429 with `retry-after`, so one client filling the render | |
| 21 | * line cannot turn every real unfurl into a 503. | |
| 22 | */ | |
| 23 | ||
| 24 | import type { Ctx } from "../../http/context.ts"; | |
| 25 | import { RateLimiter } from "../../core/ratelimit.ts"; | |
| 26 | import { notFound } from "../../http/respond.ts"; | |
| 27 | import { err } from "../../kernel/result.ts"; | |
| 28 | import { PngCache, inputHash } from "./cache.ts"; | |
| 29 | import { cardSvg } from "./card.ts"; | |
| 30 | import { kindNamed } from "./kinds.ts"; | |
| 31 | import { rasterize } from "./raster.ts"; | |
| 32 | ||
| 33 | const cache = new PngCache(); | |
| 34 | ||
| 35 | const MAX_AGE = 300; | |
| 36 | ||
| 37 | /** Cold renders one address may cause in a minute. */ | |
| 38 | export const COLD_PER_MINUTE = 30; | |
| 39 | ||
| 40 | /** One limiter per forge, so a test's forge never throttles another's. */ | |
| 41 | const coldLimits = new WeakMap<Ctx["app"], RateLimiter>(); | |
| 42 | ||
| 43 | function coldLimiter(ctx: Ctx): RateLimiter { | |
| 44 | let limiter = coldLimits.get(ctx.app); | |
| 45 | if (limiter === undefined) { | |
| 46 | limiter = new RateLimiter({ | |
| 47 | perMinute: COLD_PER_MINUTE, | |
| 48 | adminPerMinute: COLD_PER_MINUTE, | |
| 49 | enabled: true, | |
| 50 | }); | |
| 51 | coldLimits.set(ctx.app, limiter); | |
| 52 | } | |
| 53 | return limiter; | |
| 54 | } | |
| 55 | ||
| 56 | function etagMatches(ctx: Ctx, etag: string): boolean { | |
| 57 | const asked = ctx.request.headers.get("if-none-match"); | |
| 58 | if (asked === null) return false; | |
| 59 | return asked.split(",").some((t) => t.trim().replace(/^W\//, "") === etag); | |
| 60 | } | |
| 61 | ||
| 62 | export async function ogImage(ctx: Ctx): Promise<Response> { | |
| 63 | const kindName = ctx.params["kind"] ?? ""; | |
| 64 | const rest = ctx.params["path"] ?? ""; | |
| 65 | const m = /^(.+)\.(png|svg)$/.exec(rest); | |
| 66 | const kind = kindName === "" ? undefined : kindNamed(kindName); | |
| 67 | if (m === null || kind === undefined) return notFound(); | |
| 68 | const format = m[2] as "png" | "svg"; | |
| 69 | const card = await kind( | |
| 70 | { db: ctx.app.db, reposRoot: ctx.app.reposRoot, host: ctx.url.host }, | |
| 71 | m[1]!.split("/"), | |
| 72 | ); | |
| 73 | if (card === undefined) return notFound(); | |
| 74 | ||
| 75 | const hash = inputHash(kindName, card); | |
| 76 | const etag = `"${hash}"`; | |
| 77 | const headers = { | |
| 78 | etag, | |
| 79 | "cache-control": `public, max-age=${MAX_AGE}`, | |
| 80 | }; | |
| 81 | if (etagMatches(ctx, etag)) return new Response(null, { status: 304, headers }); | |
| 82 | ||
| 83 | if (format === "svg") | |
| 84 | return new Response(cardSvg(card), { | |
| 85 | headers: { ...headers, "content-type": "image/svg+xml; charset=utf-8" }, | |
| 86 | }); | |
| 87 | ||
| 88 | // Asked only on a real miss: `through` calls this when nothing is cached | |
| 89 | // and no one else's render of the same card is under way. | |
| 90 | let refusedFor: number | undefined; | |
| 91 | const png = await cache.through(hash, async () => { | |
| 92 | const verdict = coldLimiter(ctx).take(`peer:${ctx.peer ?? "unknown"}`, "ro"); | |
| 93 | if (!verdict.allowed) { | |
| 94 | refusedFor = verdict.retryAfter; | |
| 95 | return err("too many cold renders from this address"); | |
| 96 | } | |
| 97 | return rasterize(cardSvg(card)); | |
| 98 | }); | |
| 99 | if (refusedFor !== undefined) | |
| 100 | return new Response("too many previews drawn for this address; try again shortly\n", { | |
| 101 | status: 429, | |
| 102 | headers: { | |
| 103 | "content-type": "text/plain; charset=utf-8", | |
| 104 | "cache-control": "no-store", | |
| 105 | "retry-after": String(Math.max(1, refusedFor)), | |
| 106 | }, | |
| 107 | }); | |
| 108 | if (!png.ok) { | |
| 109 | ctx.app.log.warn("og: render failed", { kind: kindName, error: png.error }); | |
| 110 | return new Response(`preview unavailable: ${png.error}\n`, { | |
| 111 | status: 503, | |
| 112 | headers: { | |
| 113 | "content-type": "text/plain; charset=utf-8", | |
| 114 | "cache-control": "no-store", | |
| 115 | "retry-after": "60", | |
| 116 | }, | |
| 117 | }); | |
| 118 | } | |
| 119 | return new Response(png.value, { | |
| 120 | headers: { | |
| 121 | ...headers, | |
| 122 | "content-type": "image/png", | |
| 123 | "content-length": String(png.value.length), | |
| 124 | }, | |
| 125 | }); | |
| 126 | } |
src/web/og/score.ts added +61
| @@ -0,0 +1,61 @@ | ||
| 1 | /** | |
| 2 | * A score as a ring: the share of a whole, the arc filled clockwise from | |
| 3 | * twelve o'clock, the number in the middle and what it counts underneath. | |
| 4 | * The audit's preview draws its policy score with it (`audit.ts`). | |
| 5 | * | |
| 6 | * The arc is one circle with a dash as long as the share of its | |
| 7 | * circumference — no path arithmetic, so 0 and 100 are exact. | |
| 8 | */ | |
| 9 | ||
| 10 | import { clip, measure } from "./metrics.ts"; | |
| 11 | import { P, SANS, px, text, tone, type Box, type Tone } from "./svg.ts"; | |
| 12 | ||
| 13 | export interface ScoreFigure { | |
| 14 | readonly kind: "score"; | |
| 15 | /** What is counted towards the score, and out of how many. */ | |
| 16 | readonly held: number; | |
| 17 | readonly of: number; | |
| 18 | /** Under the ring: what the number counts. */ | |
| 19 | readonly caption: string; | |
| 20 | readonly tone: Tone; | |
| 21 | } | |
| 22 | ||
| 23 | /** The score as a whole percent: held / of × 100, rounded; nothing to count is 0. */ | |
| 24 | export function percent(held: number, of: number): number { | |
| 25 | if (of <= 0) return 0; | |
| 26 | return Math.round((Math.min(Math.max(held, 0), of) / of) * 100); | |
| 27 | } | |
| 28 | ||
| 29 | const STROKE = 26; | |
| 30 | const CAPTION = 26; | |
| 31 | ||
| 32 | export function scoreSvg(fig: ScoreFigure, box: Box): string { | |
| 33 | const r = Math.min(box.w, box.h - 64) / 2 - STROKE / 2; | |
| 34 | const cx = box.x + box.w / 2; | |
| 35 | const cy = box.y + r + STROKE / 2; | |
| 36 | const share = fig.of <= 0 ? 0 : Math.min(Math.max(fig.held, 0), fig.of) / fig.of; | |
| 37 | const circ = 2 * Math.PI * r; | |
| 38 | const label = fig.of <= 0 ? "—" : `${percent(fig.held, fig.of)}%`; | |
| 39 | // The number fills the ring's middle, never wider than its hole. | |
| 40 | const size = Math.min(84, Math.floor((84 * (2 * r - STROKE * 2)) / Math.max(1, measure(label, 84, "bold")))); | |
| 41 | return [ | |
| 42 | `<circle cx="${px(cx)}" cy="${px(cy)}" r="${px(r)}" fill="none" stroke="${P.border}" stroke-width="${STROKE}"/>`, | |
| 43 | share <= 0 | |
| 44 | ? "" | |
| 45 | : `<circle cx="${px(cx)}" cy="${px(cy)}" r="${px(r)}" fill="none" stroke="${tone(fig.tone)}" stroke-width="${STROKE}" stroke-dasharray="${px(circ * share)} ${px(circ)}" transform="rotate(-90 ${px(cx)} ${px(cy)})"/>`, | |
| 46 | text( | |
| 47 | cx, | |
| 48 | cy + size * 0.36, | |
| 49 | label, | |
| 50 | `font-family="${SANS}" font-weight="700" font-size="${size}" fill="${fig.of <= 0 ? P["muted-fg"] : P.fg}"`, | |
| 51 | "middle", | |
| 52 | ), | |
| 53 | text( | |
| 54 | cx, | |
| 55 | cy + r + STROKE / 2 + 44, | |
| 56 | clip(fig.caption, CAPTION, "sans", box.w), | |
| 57 | `font-family="${SANS}" font-size="${CAPTION}" fill="${P["muted-fg"]}"`, | |
| 58 | "middle", | |
| 59 | ), | |
| 60 | ].join(""); | |
| 61 | } |
src/web/og/source.ts added +49
| @@ -0,0 +1,49 @@ | ||
| 1 | /** | |
| 2 | * What a kind of preview is handed, and what it answers (`kinds.ts`). | |
| 3 | * | |
| 4 | * A loader is handed `OgSource` — the database, where the repositories | |
| 5 | * live, and the forge's host — and no viewer at all, so whatever it draws | |
| 6 | * is what an anonymous unfurler may see, whoever asked. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import type { Card } from "./card.ts"; | |
| 11 | ||
| 12 | /** All a loader may read: no request, no session, no viewer. */ | |
| 13 | export interface OgSource { | |
| 14 | readonly db: Database; | |
| 15 | /** Where the bare repositories are, for kinds that read from git. */ | |
| 16 | readonly reposRoot: string; | |
| 17 | /** The forge's public host, e.g. `forge.example.com`. */ | |
| 18 | readonly host: string; | |
| 19 | } | |
| 20 | ||
| 21 | /** A kind reads its data; `undefined` means the path is not one of its shape. */ | |
| 22 | export type Kind = ( | |
| 23 | source: OgSource, | |
| 24 | path: readonly string[], | |
| 25 | ) => Card | undefined | Promise<Card | undefined>; | |
| 26 | ||
| 27 | /** A user, org or repository name, as the forge allows them. */ | |
| 28 | export const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; | |
| 29 | ||
| 30 | export function plural(n: number, one: string, many = `${one}s`): string { | |
| 31 | return n === 1 ? one : many; | |
| 32 | } | |
| 33 | ||
| 34 | /** | |
| 35 | * The card for something an anonymous viewer may not see — or that is not | |
| 36 | * there. One card for all of them, the name left out: a private name is | |
| 37 | * not repeated into every unfurl of its link, a private thing and a missing | |
| 38 | * one are the same bytes, and a flood of made-up names is one cached | |
| 39 | * picture, not one cold render each. | |
| 40 | */ | |
| 41 | export function privateCard(source: OgSource): Card { | |
| 42 | return { | |
| 43 | eyebrow: "forge", | |
| 44 | title: "Nothing public here", | |
| 45 | description: "Private, or not here at all. Sign in on this forge to see it.", | |
| 46 | state: { label: "private", tone: "muted" }, | |
| 47 | host: source.host, | |
| 48 | }; | |
| 49 | } |
src/web/og/svg.ts added +79
| @@ -0,0 +1,79 @@ | ||
| 1 | /** | |
| 2 | * The drawing vocabulary every preview shares: the studio's palette by | |
| 3 | * role, the font families resvg is handed, and text that is safe to put in | |
| 4 | * an SVG document. The card (`card.ts`) and its figures (`graph.ts`, | |
| 5 | * `score.ts`) all draw with these, so a preview is one visual system. | |
| 6 | */ | |
| 7 | ||
| 8 | import { THEMES } from "../../design/themes.ts"; | |
| 9 | ||
| 10 | /** Porcelain, the studio's light palette (`design/themes.ts`). */ | |
| 11 | export const P = THEMES.light.tokens; | |
| 12 | ||
| 13 | /** The families resvg is handed (`raster.ts`), with a fallback for any other. */ | |
| 14 | export const SANS = "'Liberation Sans', Arial, Helvetica, sans-serif"; | |
| 15 | export const MONO = "'Liberation Mono', 'Courier New', monospace"; | |
| 16 | ||
| 17 | /** The palette roles a card may colour a state or a number with. */ | |
| 18 | export type Tone = "accent" | "success" | "attn" | "danger" | "merged" | "muted"; | |
| 19 | ||
| 20 | export function tone(t: Tone | undefined): string { | |
| 21 | switch (t) { | |
| 22 | case "accent": | |
| 23 | return P.accent; | |
| 24 | case "success": | |
| 25 | return P.success; | |
| 26 | case "attn": | |
| 27 | return P.attn; | |
| 28 | case "danger": | |
| 29 | return P.danger; | |
| 30 | case "merged": | |
| 31 | return P.merged; | |
| 32 | case "muted": | |
| 33 | return P["muted-fg"]; | |
| 34 | default: | |
| 35 | return P.fg; | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | const MAX_TEXT = 400; | |
| 40 | ||
| 41 | /** | |
| 42 | * Text as it may appear in XML: escaped, and with the C0 controls (and | |
| 43 | * U+FFFE/FFFF) XML 1.0 forbids removed — one stray byte from an issue | |
| 44 | * title would otherwise make the whole document unparseable. | |
| 45 | */ | |
| 46 | export function xmlText(s: string): string { | |
| 47 | return s | |
| 48 | .slice(0, MAX_TEXT) | |
| 49 | .toWellFormed() | |
| 50 | .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\ufffe\uffff]/g, "") | |
| 51 | .replace(/[\t\n\r]/g, " ") | |
| 52 | .replace( | |
| 53 | /[<>&'"]/g, | |
| 54 | (c) => | |
| 55 | ({ "<": "<", ">": ">", "&": "&", "'": "'", '"': """ })[c]!, | |
| 56 | ); | |
| 57 | } | |
| 58 | ||
| 59 | export function text( | |
| 60 | x: number, | |
| 61 | y: number, | |
| 62 | body: string, | |
| 63 | attrs: string, | |
| 64 | anchor: "start" | "middle" | "end" = "start", | |
| 65 | ): string { | |
| 66 | const a = anchor === "start" ? "" : ` text-anchor="${anchor}"`; | |
| 67 | return `<text x="${x}" y="${y}"${a} ${attrs}>${xmlText(body)}</text>`; | |
| 68 | } | |
| 69 | ||
| 70 | /** A coordinate to a tenth of a pixel: enough for resvg, and short. */ | |
| 71 | export const px = (n: number): string => String(Math.round(n * 10) / 10); | |
| 72 | ||
| 73 | /** Where a figure is drawn: the card hands it a box and it fits inside. */ | |
| 74 | export interface Box { | |
| 75 | readonly x: number; | |
| 76 | readonly y: number; | |
| 77 | readonly w: number; | |
| 78 | readonly h: number; | |
| 79 | } |
src/web/pages/audit.ts +2
| @@ -37,6 +37,7 @@ import { loadRepo, notFoundPage, signInFirst } from "../chrome.ts"; | ||
| 37 | 37 | import { readForm } from "../form.ts"; |
| 38 | 38 | import { html, when, type Html } from "../html.ts"; |
| 39 | 39 | import { flashTo, page } from "../layout.ts"; |
| 40 | import { AUDIT_CARD } from "../og/link.ts"; | |
| 40 | 41 | import { badge, btn, card, empty, icon, sha, time } from "../ui.ts"; |
| 41 | 42 | |
| 42 | 43 | const AUDIT_LIMIT = 200; |
| @@ -89,6 +90,7 @@ export async function auditPage(ctx: Ctx): Promise<Response> { | ||
| 89 | 90 | title: "Audit", |
| 90 | 91 | description: |
| 91 | 92 | "Who can do what, across every app, read from each one's contract.", |
| 93 | og: AUDIT_CARD, | |
| 92 | 94 | body: html`<div class="page-head"> |
| 93 | 95 | <h1>Audit</h1> |
| 94 | 96 | <span class="spacer"></span> |
src/web/pages/map.ts +3
| @@ -52,6 +52,7 @@ import { | ||
| 52 | 52 | import { liveRegionsJs } from "../client.ts"; |
| 53 | 53 | import { html, type Html } from "../html.ts"; |
| 54 | 54 | import { page } from "../layout.ts"; |
| 55 | import { MAP_CARD, repoCard } from "../og/link.ts"; | |
| 55 | 56 | import { avatar, hueOf, icon } from "../ui.ts"; |
| 56 | 57 | import { autonomyStatus, type AutonomyStatus } from "../../crew/autonomy.ts"; |
| 57 | 58 | import { struckOut } from "../../crew/parks.ts"; |
| @@ -1264,6 +1265,7 @@ export function mapPage(ctx: Ctx): Response { | ||
| 1264 | 1265 | return page({ |
| 1265 | 1266 | ctx, |
| 1266 | 1267 | title: `Map · ${repo.name}`, |
| 1268 | og: repoCard(db, repo, "map"), | |
| 1267 | 1269 | crumbs: crumbsFor(repo), |
| 1268 | 1270 | palette: repoPalette(ctx, repo), |
| 1269 | 1271 | body, |
| @@ -1505,6 +1507,7 @@ export function globalMapPage(ctx: Ctx): Response { | ||
| 1505 | 1507 | return page({ |
| 1506 | 1508 | ctx, |
| 1507 | 1509 | title: "Map", |
| 1510 | og: MAP_CARD, | |
| 1508 | 1511 | body, |
| 1509 | 1512 | styleCss: mapCss, |
| 1510 | 1513 | scriptJs: `${liveRegionsJs}\n${mapViewJs}`, |
src/web/pages/repo.ts +3
| @@ -50,6 +50,7 @@ import { getAppByRepo } from "../../core/apps.ts"; | ||
| 50 | 50 | import { field, readForm } from "../form.ts"; |
| 51 | 51 | import { html, when, type Html } from "../html.ts"; |
| 52 | 52 | import { flashTo, fragment, page } from "../layout.ts"; |
| 53 | import { repoCard } from "../og/link.ts"; | |
| 53 | 54 | import { renderMarkdown } from "../markdown.ts"; |
| 54 | 55 | import { browseBase, localScope, type RepoScope } from "../scope.ts"; |
| 55 | 56 | import { repoForkOf } from "../../core/origins.ts"; |
| @@ -921,6 +922,7 @@ export async function repoHome(ctx: Ctx): Promise<Response> { | ||
| 921 | 922 | ctx, |
| 922 | 923 | title: repo.name, |
| 923 | 924 | description: repo.description, |
| 925 | og: repoCard(ctx.app.db, repo, "repo"), | |
| 924 | 926 | feed: { |
| 925 | 927 | href: `${repoBase(repo)}/activity.atom`, |
| 926 | 928 | title: `${repo.ownerName}/${repo.name} activity`, |
| @@ -968,6 +970,7 @@ export async function repoHome(ctx: Ctx): Promise<Response> { | ||
| 968 | 970 | ctx, |
| 969 | 971 | title: repo.name, |
| 970 | 972 | description: repo.description, |
| 973 | og: repoCard(ctx.app.db, repo, "repo"), | |
| 971 | 974 | feed: { |
| 972 | 975 | href: `${repoBase(repo)}/activity.atom`, |
| 973 | 976 | title: `${repo.ownerName}/${repo.name} activity`, |
src/web/pages/site.ts +2
| @@ -56,6 +56,7 @@ import { | ||
| 56 | 56 | isTransientEvent, |
| 57 | 57 | } from "../../design/activity.ts"; |
| 58 | 58 | import { flashTo, page, redirect } from "../layout.ts"; |
| 59 | import { SITE_CARD } from "../og/link.ts"; | |
| 59 | 60 | import { liveClientJs, liveMount } from "../live.ts"; |
| 60 | 61 | import { |
| 61 | 62 | btn, |
| @@ -586,6 +587,7 @@ export async function home(ctx: Ctx): Promise<Response> { | ||
| 586 | 587 | return page({ |
| 587 | 588 | ctx, |
| 588 | 589 | title: "forge", |
| 590 | og: SITE_CARD, | |
| 589 | 591 | body: dashboard(ctx, user), |
| 590 | 592 | scriptJs: liveClientJs, |
| 591 | 593 | }); |
src/web/studio/app.ts +2
| @@ -29,6 +29,7 @@ import { crumbsFor, repoBase, repoHeader, repoPalette } from "../chrome.ts"; | ||
| 29 | 29 | import { appTailJs, liveRegionsJs } from "../client.ts"; |
| 30 | 30 | import { html, when, type Html } from "../html.ts"; |
| 31 | 31 | import { page } from "../layout.ts"; |
| 32 | import { repoCard } from "../og/link.ts"; | |
| 32 | 33 | import { liveClientJs, liveMount } from "../live.ts"; |
| 33 | 34 | import { |
| 34 | 35 | avatar, |
| @@ -441,6 +442,7 @@ export async function studioApp( | ||
| 441 | 442 | return page({ |
| 442 | 443 | ctx, |
| 443 | 444 | title: `${repo.name}`, |
| 445 | og: repoCard(db, repo, "repo"), | |
| 444 | 446 | crumbs: crumbsFor(repo), |
| 445 | 447 | palette: repoPalette(ctx, repo), |
| 446 | 448 | body, |
src/web/studio/home.ts +3 −1
| @@ -21,6 +21,7 @@ import { repoBase } from "../chrome.ts"; | ||
| 21 | 21 | import { liveRegionsJs } from "../client.ts"; |
| 22 | 22 | import { html, when, type Html } from "../html.ts"; |
| 23 | 23 | import { fragment, page } from "../layout.ts"; |
| 24 | import { SITE_CARD } from "../og/link.ts"; | |
| 24 | 25 | import { liveClientJs } from "../live.ts"; |
| 25 | 26 | import { btn, empty, envStateBadge, icon, listCard } from "../ui.ts"; |
| 26 | 27 | import { onYouCard } from "../pages/site.ts"; |
| @@ -164,6 +165,7 @@ export async function studioHome(ctx: Ctx, user: User): Promise<Response> { | ||
| 164 | 165 | return page({ |
| 165 | 166 | ctx, |
| 166 | 167 | title: "Studio", |
| 168 | og: SITE_CARD, | |
| 167 | 169 | body, |
| 168 | 170 | scriptJs: `${liveClientJs}\n${liveRegionsJs}\n${feedJs}`, |
| 169 | 171 | }); |
| @@ -292,5 +294,5 @@ export function studioDoor(ctx: Ctx): Response { | ||
| 292 | 294 | note: "Apps made public here show up on this shelf once they run.", |
| 293 | 295 | })} |
| 294 | 296 | </div>`}`; |
| 295 | return page({ ctx, title: "forge", body }); | |
| 297 | return page({ ctx, title: "forge", og: SITE_CARD, body }); | |
| 296 | 298 | } |
test/og-designs.test.ts added +306
| @@ -0,0 +1,306 @@ | ||
| 1 | /** | |
| 2 | * The map's and the audit's link previews (src/web/og/map.ts, audit.ts): | |
| 3 | * the thumbnail's scale and the policy score match a hand calculation, the | |
| 4 | * words and the critical path are the map page's own, the findings come | |
| 5 | * worst first — and over HTTP, a signed-in owner is served what nobody | |
| 6 | * sees: no private repository's plan, no private app's policy. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { newApp } from "../src/actions/apps.ts"; | |
| 14 | import { openIssue } from "../src/actions/issues.ts"; | |
| 15 | import { createRepo } from "../src/actions/repos.ts"; | |
| 16 | import { addDependency, type Graph } from "../src/core/dependencies.ts"; | |
| 17 | import type { Issue } from "../src/core/issues.ts"; | |
| 18 | import { createSession } from "../src/core/sessions.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { NO_MARKS, type Marks } from "../src/web/pages/map.ts"; | |
| 22 | import { auditCard, findings, type AuditRow } from "../src/web/og/audit.ts"; | |
| 23 | import { cardSvg, FIGURE_BOX } from "../src/web/og/card.ts"; | |
| 24 | import { graphScale, graphSvg } from "../src/web/og/graph.ts"; | |
| 25 | import { cachedGraphFigure, graphFigure, mapCard, mapSentence } from "../src/web/og/map.ts"; | |
| 26 | import { kindNamed, privateCard, type OgSource } from "../src/web/og/kinds.ts"; | |
| 27 | import { findResvg, rasterize } from "../src/web/og/raster.ts"; | |
| 28 | import { percent, scoreSvg } from "../src/web/og/score.ts"; | |
| 29 | import { pngHeader } from "../src/design/image/png.ts"; | |
| 30 | ||
| 31 | const HOST = "forge.example.com"; | |
| 32 | ||
| 33 | const issue = (n: number, state: "open" | "closed" = "open"): Issue => | |
| 34 | ({ | |
| 35 | id: `i${n}`, | |
| 36 | number: n, | |
| 37 | title: `Issue ${n}`, | |
| 38 | state, | |
| 39 | kind: "issue", | |
| 40 | createdAt: `2026-01-${String(n).padStart(2, "0")}T00:00:00.000Z`, | |
| 41 | }) as unknown as Issue; | |
| 42 | const edge = (blocker: number, blocked: number) => ({ | |
| 43 | issueId: `i${blocked}`, | |
| 44 | blockedById: `i${blocker}`, | |
| 45 | }); | |
| 46 | ||
| 47 | describe("the map's thumbnail", () => { | |
| 48 | test("its scale is the smaller of the two fits, capped", () => { | |
| 49 | // 4 slots × 5 levels at the page's proportions (196 × 68, gaps 28 / 44): | |
| 50 | // 4·224 − 28 = 868 wide, 5·112 − 44 = 516 tall. The box is 480 × 344: | |
| 51 | // 480 / 868 = 0.55300…, 344 / 516 = 0.66667 — the width decides. | |
| 52 | expect(FIGURE_BOX).toEqual({ x: 648, y: 116, w: 480, h: 344 }); | |
| 53 | expect(graphScale(4, 5, FIGURE_BOX)).toBeCloseTo(480 / 868, 9); | |
| 54 | // 1 × 9: 196 wide, 9·112 − 44 = 964 tall; 344 / 964 = 0.35685 decides. | |
| 55 | expect(graphScale(1, 9, FIGURE_BOX)).toBeCloseTo(344 / 964, 9); | |
| 56 | // One card would be 2.4× the page; it is held to 0.62. | |
| 57 | expect(graphScale(1, 1, FIGURE_BOX)).toBe(0.62); | |
| 58 | }); | |
| 59 | ||
| 60 | // 1 → 3 → 5, 2 (closed) → 3, 4 → 5, and 6 on no edge. | |
| 61 | const graph: Graph = { | |
| 62 | issues: [issue(1), issue(2, "closed"), issue(3), issue(4), issue(5), issue(6)], | |
| 63 | edges: [edge(1, 3), edge(2, 3), edge(3, 5), edge(4, 5)], | |
| 64 | held: [], | |
| 65 | }; | |
| 66 | ||
| 67 | test("the card counts the page's words and draws the chain in the accent", () => { | |
| 68 | const marks: Marks = { crew: new Map([["i1", "running"]]), waiting: new Set(["i4"]), parked: new Set(), why: new Map() }; | |
| 69 | const card = mapCard({ eyebrow: "alice/engine · map", title: "engine", host: HOST }, graph, marks); | |
| 70 | // 1 working; 4 waiting on a pull; 6 ready (on no edge); 3 and 5 blocked; 2 done. | |
| 71 | expect(card.stats).toEqual([ | |
| 72 | { value: "1", label: "ready", tone: "success" }, | |
| 73 | { value: "1", label: "working", tone: "accent" }, | |
| 74 | { value: "2", label: "blocked" }, | |
| 75 | { value: "1", label: "waiting on a change", tone: "merged" }, | |
| 76 | ]); | |
| 77 | expect(card.state).toEqual({ label: "working", tone: "accent" }); | |
| 78 | // Five open; the longest open chain is 1 → 3 → 5. Next skips 1, which | |
| 79 | // the crew is on, and 4, which a pull is for: 6 is what a free hand takes. | |
| 80 | expect(card.description).toBe("5 open issues; the critical path is 3 issues, #1 to #5. Next: #6 Issue 6"); | |
| 81 | const fig = card.figure; | |
| 82 | if (fig?.kind !== "graph") throw new Error("no graph"); | |
| 83 | // Only the chains are drawn: 6, on no edge, is counted, not drawn. | |
| 84 | expect(fig.nodes.length).toBe(5); | |
| 85 | expect(fig.levels).toBe(3); | |
| 86 | expect(fig.nodes.filter((n) => n.critical).length).toBe(3); | |
| 87 | expect(fig.edges.filter((e) => e.critical).length).toBe(2); | |
| 88 | expect(fig.edges.filter((e) => e.done).length).toBe(1); | |
| 89 | expect(fig.nodes.map((n) => n.word).toSorted()).toEqual(["blocked", "blocked", "done", "waiting", "working"]); | |
| 90 | const svg = cardSvg(card); | |
| 91 | expect(svg.match(/<rect [^>]*stroke-width/g)?.length).toBe(5); | |
| 92 | expect(svg).toContain('stroke="#2563eb"'); | |
| 93 | }); | |
| 94 | ||
| 95 | test("with nothing linked, the loose issues are drawn, four rows at most", () => { | |
| 96 | const loose: Graph = { issues: Array.from({ length: 40 }, (_, i) => issue(i + 1)), edges: [], held: [] }; | |
| 97 | const words = new Map(loose.issues.map((i) => [i.id, "ready" as const])); | |
| 98 | const fig = graphFigure(loose, words, [])!; | |
| 99 | // The page's island is as wide as the chains, three at least: with no | |
| 100 | // chains, three to a row; four rows of them is 12 cards of the 40. | |
| 101 | expect(fig.nodes.length).toBe(12); | |
| 102 | expect(fig.width).toBe(3); | |
| 103 | expect(fig.levels).toBe(4); | |
| 104 | expect(graphFigure({ issues: [], edges: [], held: [] }, new Map(), [])).toBeUndefined(); | |
| 105 | expect(graphSvg({ kind: "graph", width: 0, levels: 0, nodes: [], edges: [] }, FIGURE_BOX)).toBe(""); | |
| 106 | }); | |
| 107 | ||
| 108 | test("a thumbnail is remembered by its whole input: the same plan is not laid out twice, a changed word is", () => { | |
| 109 | const words = new Map(graph.issues.map((i) => [i.id, "blocked" as const])); | |
| 110 | const first = cachedGraphFigure(graph, words, ["i1", "i3"]); | |
| 111 | expect(cachedGraphFigure(graph, new Map(words), ["i1", "i3"])).toBe(first!); | |
| 112 | const moved = new Map([...words, ["i1", "working" as const]]); | |
| 113 | expect(cachedGraphFigure(graph, moved, ["i1", "i3"])).not.toBe(first!); | |
| 114 | expect(cachedGraphFigure(graph, words, ["i1"])).not.toBe(first!); | |
| 115 | }); | |
| 116 | ||
| 117 | test("the sentence says what is open, the chain still to go, and what is next", () => { | |
| 118 | expect(mapSentence(0, [], undefined)).toBe("Nothing open: every issue on the map is done."); | |
| 119 | expect(mapSentence(1, [], { number: 4, title: "Ship it" })).toBe("1 open issue; none waiting on another. Next: #4 Ship it"); | |
| 120 | const empty = mapCard({ eyebrow: "e", title: "t", host: HOST }, { issues: [], edges: [], held: [] }, NO_MARKS); | |
| 121 | expect(empty.figure).toBeUndefined(); | |
| 122 | expect(empty.state).toEqual({ label: "done", tone: "muted" }); | |
| 123 | }); | |
| 124 | }); | |
| 125 | ||
| 126 | describe("the audit's score and findings", () => { | |
| 127 | const row = (name: string, standing: AuditRow["standing"], more: Partial<AuditRow> = {}): AuditRow => ({ | |
| 128 | name, | |
| 129 | standing, | |
| 130 | open: 0, | |
| 131 | problems: [], | |
| 132 | disobeys: false, | |
| 133 | ...more, | |
| 134 | }); | |
| 135 | ||
| 136 | test("the score is a whole percent of the apps that hold", () => { | |
| 137 | expect(percent(2, 5)).toBe(40); | |
| 138 | expect(percent(1, 3)).toBe(33); | |
| 139 | expect(percent(2, 3)).toBe(67); | |
| 140 | expect(percent(5, 5)).toBe(100); | |
| 141 | expect(percent(0, 0)).toBe(0); | |
| 142 | expect(percent(9, 3)).toBe(100); | |
| 143 | }); | |
| 144 | ||
| 145 | const rows = [ | |
| 146 | row("a/notes", "sound", { open: 3 }), | |
| 147 | row("a/shop", "sound", { disobeys: true }), | |
| 148 | row("a/blog", "unsound", { problems: ["roles.admin is not a role", "and more"] }), | |
| 149 | row("a/wiki", "unread"), | |
| 150 | row("a/chat", "sound", { open: 5 }), | |
| 151 | row("a/docs", "unread"), | |
| 152 | ]; | |
| 153 | ||
| 154 | test("findings come worst first: disobeying, unsound, the most open, then the unread together", () => { | |
| 155 | expect(findings(rows)).toEqual([ | |
| 156 | { text: "a/shop disobeys its contract", tone: "danger" }, | |
| 157 | { text: "a/blog: unsound — roles.admin is not a role", tone: "danger" }, | |
| 158 | { text: "a/chat: 5 doors open to anyone", tone: "attn" }, | |
| 159 | { text: "a/notes: 3 doors open to anyone", tone: "attn" }, | |
| 160 | { text: "2 apps unread: no contract.json", tone: "muted" }, | |
| 161 | ]); | |
| 162 | }); | |
| 163 | ||
| 164 | test("the card: 2 of 6 hold — notes and chat; shop disobeys, blog and the unread do not", () => { | |
| 165 | const card = auditCard(HOST, rows); | |
| 166 | expect(card.figure).toEqual({ | |
| 167 | kind: "score", | |
| 168 | held: 2, | |
| 169 | of: 6, | |
| 170 | caption: "2 of 6 apps hold their contract", | |
| 171 | tone: "danger", | |
| 172 | }); | |
| 173 | expect(card.state).toEqual({ label: "disobeyed", tone: "danger" }); | |
| 174 | expect(card.notes?.length).toBe(4); | |
| 175 | expect(card.stats?.map((s) => s.value)).toEqual(["3", "8", "1", "2"]); | |
| 176 | // 2 / 6 = 33.3…% → 33%. | |
| 177 | expect(cardSvg(card)).toContain(">33%<"); | |
| 178 | }); | |
| 179 | ||
| 180 | test("all holding is said, and nothing to audit draws no score", () => { | |
| 181 | const fine = auditCard(HOST, [row("a/notes", "sound")]); | |
| 182 | expect(fine.notes).toEqual([{ text: "Every app holds its contract.", tone: "success" }]); | |
| 183 | expect(fine.state).toEqual({ label: "holds", tone: "success" }); | |
| 184 | expect(fine.figure).toMatchObject({ held: 1, of: 1, caption: "1 of 1 app holds its contract", tone: "success" }); | |
| 185 | const none = auditCard(HOST, []); | |
| 186 | expect(none.figure).toBeUndefined(); | |
| 187 | expect(none.stats).toBeUndefined(); | |
| 188 | }); | |
| 189 | ||
| 190 | test("the ring's arc is the share of its circumference", () => { | |
| 191 | const box = FIGURE_BOX; | |
| 192 | const svg = scoreSvg({ kind: "score", held: 1, of: 4, caption: "c", tone: "attn" }, box); | |
| 193 | // r = min(480, 344 − 64) / 2 − 13 = 127; 2π·127 = 797.96; a quarter is 199.49. | |
| 194 | expect(svg).toContain('stroke-dasharray="199.5 798"'); | |
| 195 | expect(scoreSvg({ kind: "score", held: 0, of: 4, caption: "c", tone: "danger" }, box)).not.toContain("dasharray"); | |
| 196 | }); | |
| 197 | }); | |
| 198 | ||
| 199 | const noResvg = findResvg() === undefined; | |
| 200 | if (noResvg) | |
| 201 | console.log("SKIPPING: resvg is not installed here (nor FORGE_RESVG set), so the map and audit cards cannot be rasterized on this machine"); | |
| 202 | describe.skipIf(noResvg)("rendered by resvg", () => { | |
| 203 | test("the map and the audit are 1200 × 630 PNGs inside the 300 ms budget", async () => { | |
| 204 | const chain: Graph = { | |
| 205 | issues: Array.from({ length: 30 }, (_, i) => issue(i + 1)), | |
| 206 | edges: Array.from({ length: 20 }, (_, i) => edge(i + 1, i + 1 + (i % 3) + 1)), | |
| 207 | held: [], | |
| 208 | }; | |
| 209 | const cards = [ | |
| 210 | mapCard({ eyebrow: "a/b · map", title: "b", host: HOST }, chain, NO_MARKS), | |
| 211 | auditCard(HOST, [ | |
| 212 | { name: "a/x", standing: "sound", open: 2, problems: [], disobeys: true }, | |
| 213 | { name: "a/y", standing: "unread", open: 0, problems: [], disobeys: false }, | |
| 214 | ]), | |
| 215 | ]; | |
| 216 | for (const card of cards) { | |
| 217 | const started = performance.now(); | |
| 218 | const png = await rasterize(cardSvg(card)); | |
| 219 | const took = performance.now() - started; | |
| 220 | if (!png.ok) throw new Error(png.error); | |
| 221 | const head = pngHeader(png.value); | |
| 222 | expect(head.ok && [head.value.width, head.value.height]).toEqual([1200, 630]); | |
| 223 | expect(took).toBeLessThan(300); | |
| 224 | } | |
| 225 | }); | |
| 226 | }); | |
| 227 | ||
| 228 | describe("over HTTP, as nobody", () => { | |
| 229 | let dataDir: string; | |
| 230 | let app: App; | |
| 231 | let servers: Servers; | |
| 232 | let alice: User; | |
| 233 | let cookie: string; | |
| 234 | let source: OgSource; | |
| 235 | ||
| 236 | beforeAll(async () => { | |
| 237 | dataDir = await mkdtemp(join(tmpdir(), "forge-og-designs-")); | |
| 238 | app = createApp({ dataDir, port: 0 }); | |
| 239 | servers = await serve(app); | |
| 240 | const made = await createUser(app.db, { | |
| 241 | username: "alice", | |
| 242 | email: "[email protected]", | |
| 243 | password: "a-good-passphrase", | |
| 244 | adminIfFirst: true, | |
| 245 | }); | |
| 246 | if (!made.ok) throw new Error(made.error); | |
| 247 | alice = made.value; | |
| 248 | cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 249 | source = { db: app.db, reposRoot: app.reposRoot, host: HOST }; | |
| 250 | for (const [name, visibility] of [["engine", "public"], ["plans", "private"]] as const) { | |
| 251 | const repo = await createRepo(app, alice, { name, visibility }); | |
| 252 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 253 | const opened = ["Extract the renderer", "Scene graph", "Launch the moon base"].map((title) => { | |
| 254 | const i = openIssue(app, alice, repo.value, { title }); | |
| 255 | if (!i.ok) throw new Error(String(i.error)); | |
| 256 | return i.value; | |
| 257 | }); | |
| 258 | expect(addDependency(app.db, opened[1]!, opened[0]!, alice.id).ok).toBe(true); | |
| 259 | } | |
| 260 | const pub = await newApp(app, alice, { name: "notes", visibility: "public" }); | |
| 261 | const priv = await newApp(app, alice, { name: "vault", visibility: "private" }); | |
| 262 | if (!pub.ok || !priv.ok) throw new Error("apps"); | |
| 263 | }, 30_000); | |
| 264 | ||
| 265 | afterAll(async () => { | |
| 266 | servers.stop(); | |
| 267 | app.close(); | |
| 268 | await rm(dataDir, { recursive: true, force: true }); | |
| 269 | }); | |
| 270 | ||
| 271 | test("a public repository's map: its words counted, its chain drawn", async () => { | |
| 272 | const card = (await kindNamed("map")!(source, ["alice", "engine"]))!; | |
| 273 | expect(card.eyebrow).toBe("alice/engine · map"); | |
| 274 | expect(card.stats?.slice(0, 3).map((s) => s.value)).toEqual(["2", "0", "1"]); | |
| 275 | expect(card.figure?.kind).toBe("graph"); | |
| 276 | }); | |
| 277 | ||
| 278 | test("a private repository's map is the private card, and the shape is checked", async () => { | |
| 279 | const map = kindNamed("map")!; | |
| 280 | expect(await map(source, ["alice", "plans"])).toEqual(privateCard(source)); | |
| 281 | expect(await map(source, ["alice"])).toBeUndefined(); | |
| 282 | expect(await map(source, ["alice", ".."])).toBeUndefined(); | |
| 283 | expect(await kindNamed("audit")!(source, ["alice"])).toBeUndefined(); | |
| 284 | }); | |
| 285 | ||
| 286 | test("the forge's map and audit hold only what is public, whoever asks", async () => { | |
| 287 | for (const path of ["/og/map/all.svg", "/og/audit/all.svg", "/og/map/alice/plans.svg"]) { | |
| 288 | const anonymous = await fetch(`${servers.url}${path}`); | |
| 289 | const owner = await fetch(`${servers.url}${path}`, { headers: { cookie } }); | |
| 290 | expect(anonymous.status).toBe(200); | |
| 291 | expect(anonymous.headers.get("content-type")).toStartWith("image/svg+xml"); | |
| 292 | const body = await owner.text(); | |
| 293 | expect(body).toBe(await anonymous.text()); | |
| 294 | expect(owner.headers.get("etag")).toBe(anonymous.headers.get("etag")); | |
| 295 | expect(body).not.toContain("moon base"); | |
| 296 | expect(body).not.toContain("vault"); | |
| 297 | } | |
| 298 | const all = (await kindNamed("map")!(source, ["all"]))!; | |
| 299 | // engine's three issues only: 1 and 3 ready, 2 blocked — none of plans'. | |
| 300 | expect(all.stats?.slice(0, 3).map((s) => s.value)).toEqual(["2", "0", "1"]); | |
| 301 | const audit = (await kindNamed("audit")!(source, ["all"]))!; | |
| 302 | // notes, scaffolded with a contract, is the one public app. | |
| 303 | expect(audit.figure).toMatchObject({ kind: "score", held: 1, of: 1 }); | |
| 304 | expect(JSON.stringify(audit)).not.toContain("vault"); | |
| 305 | }); | |
| 306 | }); |
test/og-pages.test.ts added +140
| @@ -0,0 +1,140 @@ | ||
| 1 | /** | |
| 2 | * Where the link previews meet the pages and the callers: the pages that | |
| 3 | * have a card name it in their head (and a private repository's does not), | |
| 4 | * and a cold render is limited per address while a warm one is free. | |
| 5 | * | |
| 6 | * The limit is proven without the real resvg: `FORGE_RESVG` names a stand-in | |
| 7 | * that prints a PNG signature (a warm card), then a path that is not there | |
| 8 | * (every ask a cold miss that fails, so nothing is cached between them). | |
| 9 | */ | |
| 10 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 11 | import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { createRepo } from "../src/actions/repos.ts"; | |
| 16 | import { createSession } from "../src/core/sessions.ts"; | |
| 17 | import { createUser } from "../src/core/users.ts"; | |
| 18 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 19 | import { COLD_PER_MINUTE } from "../src/web/og/route.ts"; | |
| 20 | ||
| 21 | let dataDir: string; | |
| 22 | let app: App; | |
| 23 | let servers: Servers; | |
| 24 | let cookie: string; | |
| 25 | ||
| 26 | beforeAll(async () => { | |
| 27 | dataDir = await mkdtemp(join(tmpdir(), "forge-og-pages-")); | |
| 28 | app = createApp({ dataDir, port: 0 }); | |
| 29 | servers = await serve(app); | |
| 30 | const made = await createUser(app.db, { | |
| 31 | username: "alice", | |
| 32 | email: "[email protected]", | |
| 33 | password: "a-good-passphrase", | |
| 34 | adminIfFirst: true, | |
| 35 | }); | |
| 36 | if (!made.ok) throw new Error(made.error); | |
| 37 | cookie = `forge_session=${createSession(app.db, made.value.id).token}`; | |
| 38 | const open = await createRepo(app, made.value, { name: "engine", visibility: "public" }); | |
| 39 | const secret = await createRepo(app, made.value, { name: "secret", visibility: "private" }); | |
| 40 | if (!open.ok || !secret.ok) throw new Error("repos"); | |
| 41 | }); | |
| 42 | ||
| 43 | afterAll(async () => { | |
| 44 | servers.stop(); | |
| 45 | app.close(); | |
| 46 | await rm(dataDir, { recursive: true, force: true }); | |
| 47 | }); | |
| 48 | ||
| 49 | async function head(path: string, withCookie = false): Promise<{ status: number; html: string }> { | |
| 50 | const res = await fetch(`${servers.url}${path}`, { | |
| 51 | headers: { accept: "text/html", ...(withCookie ? { cookie } : {}) }, | |
| 52 | redirect: "manual", | |
| 53 | }); | |
| 54 | const text = await res.text(); | |
| 55 | return { status: res.status, html: text.slice(0, text.indexOf("</head>")) }; | |
| 56 | } | |
| 57 | ||
| 58 | function ogImage(html: string): string | undefined { | |
| 59 | return /<meta\s+property="og:image"\s+content="([^"]*)"/.exec(html)?.[1]; | |
| 60 | } | |
| 61 | ||
| 62 | describe("pages name their card", () => { | |
| 63 | const cases: [string, string, boolean][] = [ | |
| 64 | ["/", "/og/site/home.png", false], | |
| 65 | ["/?mode=dev", "/og/site/home.png", true], | |
| 66 | ["/alice/engine", "/og/repo/alice/engine.png", false], | |
| 67 | ["/alice/engine/map", "/og/map/alice/engine.png", false], | |
| 68 | ["/map", "/og/map/all.png", true], | |
| 69 | ["/audit", "/og/audit/all.png", false], | |
| 70 | ]; | |
| 71 | for (const [path, card, signedIn] of cases) | |
| 72 | test(`${path} → ${card}`, async () => { | |
| 73 | const { status, html } = await head(path, signedIn); | |
| 74 | expect(status).toBe(200); | |
| 75 | expect(ogImage(html)).toBe(`${servers.url}${card}`); | |
| 76 | expect(html).toContain('<meta property="og:image:width" content="1200"'); | |
| 77 | expect(html).toContain('<meta property="og:image:height" content="630"'); | |
| 78 | expect(html).toContain('<meta name="twitter:card" content="summary_large_image"'); | |
| 79 | }); | |
| 80 | ||
| 81 | test("a private repository's page, seen by its owner, names no card", async () => { | |
| 82 | for (const path of ["/alice/secret", "/alice/secret/map"]) { | |
| 83 | const { status, html } = await head(path, true); | |
| 84 | expect(status).toBe(200); | |
| 85 | expect(ogImage(html)).toBe(`${servers.url}/icons/forge-512.png`); | |
| 86 | expect(html).not.toContain("/og/"); | |
| 87 | expect(html).toContain('<meta name="twitter:card" content="summary"'); | |
| 88 | } | |
| 89 | }); | |
| 90 | ||
| 91 | test("a page that is not there names no card", async () => { | |
| 92 | const { status, html } = await head("/alice/secret"); | |
| 93 | expect(status).toBe(404); | |
| 94 | expect(html).not.toContain("/og/"); | |
| 95 | }); | |
| 96 | }); | |
| 97 | ||
| 98 | describe("cold renders are limited per address", () => { | |
| 99 | const before = process.env["FORGE_RESVG"]; | |
| 100 | afterAll(() => { | |
| 101 | if (before === undefined) delete process.env["FORGE_RESVG"]; | |
| 102 | else process.env["FORGE_RESVG"] = before; | |
| 103 | }); | |
| 104 | ||
| 105 | test("a warm card is free; past the limit a miss is 429, and the warm card still answers", async () => { | |
| 106 | const fake = join(dataDir, "fake-resvg"); | |
| 107 | await writeFile(fake, "#!/bin/sh\ncat >/dev/null\nprintf '\\211PNG\\r\\n\\032\\nfake'\n"); | |
| 108 | await chmod(fake, 0o755); | |
| 109 | process.env["FORGE_RESVG"] = fake; | |
| 110 | ||
| 111 | const warm = `${servers.url}/og/site/home.png`; | |
| 112 | // One cold render, then hits: well past the limit, and none refused. | |
| 113 | for (let i = 0; i < COLD_PER_MINUTE + 5; i++) { | |
| 114 | const res = await fetch(warm); | |
| 115 | expect(res.status).toBe(200); | |
| 116 | expect(res.headers.get("content-type")).toBe("image/png"); | |
| 117 | await res.arrayBuffer(); | |
| 118 | } | |
| 119 | ||
| 120 | // Now every ask of another card is a miss that fails, so each one costs. | |
| 121 | process.env["FORGE_RESVG"] = join(dataDir, "no-such-resvg"); | |
| 122 | const cold = `${servers.url}/og/repo/alice/engine.png`; | |
| 123 | for (let i = 1; i < COLD_PER_MINUTE; i++) { | |
| 124 | const res = await fetch(cold); | |
| 125 | expect(res.status).toBe(503); | |
| 126 | await res.arrayBuffer(); | |
| 127 | } | |
| 128 | const refused = await fetch(cold); | |
| 129 | expect(refused.status).toBe(429); | |
| 130 | expect(Number(refused.headers.get("retry-after"))).toBeGreaterThan(0); | |
| 131 | expect(refused.headers.get("cache-control")).toBe("no-store"); | |
| 132 | await refused.arrayBuffer(); | |
| 133 | ||
| 134 | const still = await fetch(warm); | |
| 135 | expect(still.status).toBe(200); | |
| 136 | await still.arrayBuffer(); | |
| 137 | // The SVG is no render at all, and is never refused. | |
| 138 | expect((await fetch(`${servers.url}/og/repo/alice/engine.svg`)).status).toBe(200); | |
| 139 | }); | |
| 140 | }); |
test/og.test.ts added +330
| @@ -0,0 +1,330 @@ | ||
| 1 | /** | |
| 2 | * The link-preview renderer (src/web/og): text arithmetic that matches a | |
| 3 | * hand calculation, a card that escapes whatever it is given, a cache keyed | |
| 4 | * by the input's hash, kinds that read as nobody — proven over HTTP with a | |
| 5 | * signed-in owner — and, where resvg is installed, every kind rendered to a | |
| 6 | * 1200 × 630 PNG inside the time budget. | |
| 7 | */ | |
| 8 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 9 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { createSession } from "../src/core/sessions.ts"; | |
| 15 | import { createUser, type User } from "../src/core/users.ts"; | |
| 16 | import { pngHeader } from "../src/design/image/png.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | import { canonical, inputHash, PngCache } from "../src/web/og/cache.ts"; | |
| 19 | import { cardSvg, HEIGHT, WIDTH, xmlText, type Card } from "../src/web/og/card.ts"; | |
| 20 | import { KINDS, kindNamed, privateCard, type OgSource } from "../src/web/og/kinds.ts"; | |
| 21 | import { clip, measure, wrap } from "../src/web/og/metrics.ts"; | |
| 22 | import { findResvg, MAX_WAITING, rasterize, resvgArgs } from "../src/web/og/raster.ts"; | |
| 23 | import { err, ok } from "../src/kernel/result.ts"; | |
| 24 | ||
| 25 | describe("metrics", () => { | |
| 26 | test("a width is the sum of the font's advances, scaled from a 2048-unit em", () => { | |
| 27 | // Liberation Sans: H 1479, e 1139, l 455, l 455, o 1139 = 4667 units. | |
| 28 | expect(measure("Hello", 2048, "sans")).toBe(4667); | |
| 29 | expect(measure("Hello", 100, "sans")).toBeCloseTo((4667 * 100) / 2048, 9); | |
| 30 | // Bold: H 1479, i 569 = 2048 units — exactly one em. | |
| 31 | expect(measure("Hi", 68, "bold")).toBe(68); | |
| 32 | // Mono is 1229 units a glyph, whatever the glyph. | |
| 33 | expect(measure("abc", 28, "mono")).toBeCloseTo((3 * 1229 * 28) / 2048, 9); | |
| 34 | expect(measure("", 40, "sans")).toBe(0); | |
| 35 | }); | |
| 36 | ||
| 37 | test("clip leaves what fits, and cuts what does not to fit with an ellipsis", () => { | |
| 38 | expect(clip("short", 32, "sans", 1000)).toBe("short"); | |
| 39 | const cut = clip("a title much too long for the room it is given", 32, "sans", 200); | |
| 40 | expect(cut.endsWith("…")).toBe(true); | |
| 41 | expect(measure(cut, 32, "sans")).toBeLessThanOrEqual(200); | |
| 42 | // Only just over: still cut, never drawn past the edge. | |
| 43 | const word = "WWWWWWWWWW"; | |
| 44 | const max = measure(word, 20, "bold") - 1; | |
| 45 | expect(measure(clip(word, 20, "bold", max), 20, "bold")).toBeLessThanOrEqual(max); | |
| 46 | }); | |
| 47 | ||
| 48 | test("wrap breaks at spaces, keeps every line inside the width, and folds the rest into the last", () => { | |
| 49 | const text = "one two three four five six seven eight nine ten eleven twelve"; | |
| 50 | const lines = wrap(text, 32, "sans", 300, 2); | |
| 51 | expect(lines.length).toBe(2); | |
| 52 | for (const l of lines) expect(measure(l, 32, "sans")).toBeLessThanOrEqual(300); | |
| 53 | // "one two three four" is 16508 units = 257.9 px at 32 px; " five" | |
| 54 | // (569 + 3187 units) would take it to 316.6 px, past 300. | |
| 55 | expect(measure("one two three four", 2048, "sans")).toBe(16508); | |
| 56 | expect(lines[0]).toBe("one two three four"); | |
| 57 | expect(lines[1]!.endsWith("…")).toBe(true); | |
| 58 | // Room enough: every word, no ellipsis. | |
| 59 | expect(wrap("a b c", 32, "sans", 1000, 3)).toEqual(["a b c"]); | |
| 60 | // A word wider than a line is clipped where it stands. | |
| 61 | const long = wrap(`${"x".repeat(200)} tail`, 32, "sans", 300, 3); | |
| 62 | expect(long[0]!.endsWith("…")).toBe(true); | |
| 63 | expect(long[1]).toBe("tail"); | |
| 64 | expect(wrap(" ", 32, "sans", 300, 2)).toEqual([]); | |
| 65 | }); | |
| 66 | }); | |
| 67 | ||
| 68 | const sample: Card = { | |
| 69 | eyebrow: "acme/engine", | |
| 70 | title: "engine", | |
| 71 | description: "A tick-accurate match engine.", | |
| 72 | state: { label: "working", tone: "attn" }, | |
| 73 | stats: [ | |
| 74 | { value: "3", label: "changes waiting", tone: "accent" }, | |
| 75 | { value: "2", label: "crew working" }, | |
| 76 | { value: "$41", label: "today" }, | |
| 77 | ], | |
| 78 | host: "forge.example.com", | |
| 79 | }; | |
| 80 | ||
| 81 | describe("card", () => { | |
| 82 | test("is a 1200 × 630 SVG that says what it was given", () => { | |
| 83 | const svg = cardSvg(sample); | |
| 84 | expect(svg).toStartWith(`<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}"`); | |
| 85 | expect([WIDTH, HEIGHT]).toEqual([1200, 630]); | |
| 86 | for (const s of ["acme/engine", "engine", "A tick-accurate match engine.", "working", "changes waiting", "$41", "forge.example.com"]) | |
| 87 | expect(svg).toContain(`>${s}<`); | |
| 88 | }); | |
| 89 | ||
| 90 | test("escapes markup and drops the bytes XML forbids, so no input can change the document", () => { | |
| 91 | expect(xmlText(`</text><image href="x"/>&`)).toBe("</text><image href="x"/>&"); | |
| 92 | expect(xmlText("a\u0000b\u001bc\nd")).toBe("abc d"); | |
| 93 | expect(xmlText("lone \ud800 surrogate")).toBe("lone � surrogate"); | |
| 94 | const svg = cardSvg({ ...sample, title: `<script>alert(1)</script>`, eyebrow: `x" onload="y` }); | |
| 95 | expect(svg).not.toContain("<script"); | |
| 96 | expect(svg).not.toContain(`x" onload`); | |
| 97 | // The only elements are the ones the card draws: nothing that loads. | |
| 98 | expect(svg).not.toMatch(/<(image|script|foreignObject|use)\b|href=/); | |
| 99 | }); | |
| 100 | ||
| 101 | test("never draws more than four numbers", () => { | |
| 102 | const stats = Array.from({ length: 6 }, (_, i) => ({ value: `${i}${i}${i}`, label: `n${i}` })); | |
| 103 | const svg = cardSvg({ ...sample, stats }); | |
| 104 | expect(svg).toContain(">333<"); | |
| 105 | expect(svg).not.toContain(">444<"); | |
| 106 | }); | |
| 107 | }); | |
| 108 | ||
| 109 | describe("cache", () => { | |
| 110 | test("the key is the input's hash: key order does not matter, any change does", () => { | |
| 111 | expect(canonical({ b: 1, a: [{ d: 2, c: 3 }], u: undefined })).toBe(`{"a":[{"c":3,"d":2}],"b":1}`); | |
| 112 | const reordered = Object.fromEntries(Object.entries(sample).reverse()) as unknown as Card; | |
| 113 | expect(Object.keys(reordered)[0]).toBe("host"); | |
| 114 | expect(inputHash("repo", reordered)).toBe(inputHash("repo", sample)); | |
| 115 | expect(inputHash("repo", { ...sample, title: "engine2" })).not.toBe(inputHash("repo", sample)); | |
| 116 | expect(inputHash("site", sample)).not.toBe(inputHash("repo", sample)); | |
| 117 | expect(inputHash("repo", sample)).toMatch(/^[0-9a-f]{64}$/); | |
| 118 | }); | |
| 119 | ||
| 120 | test("evicts the least recently used by bytes", () => { | |
| 121 | const cache = new PngCache(10); | |
| 122 | cache.set("a", new Uint8Array(4)); | |
| 123 | cache.set("b", new Uint8Array(4)); | |
| 124 | expect(cache.get("a")).toBeDefined(); // a is now the most recent | |
| 125 | cache.set("c", new Uint8Array(4)); | |
| 126 | expect(cache.get("b")).toBeUndefined(); | |
| 127 | expect(cache.get("a")).toBeDefined(); | |
| 128 | expect(cache.get("c")).toBeDefined(); | |
| 129 | cache.set("huge", new Uint8Array(11)); | |
| 130 | expect(cache.get("huge")).toBeUndefined(); | |
| 131 | }); | |
| 132 | ||
| 133 | test("one render for concurrent asks; a failure is not kept", async () => { | |
| 134 | const cache = new PngCache(); | |
| 135 | let renders = 0; | |
| 136 | const render = async () => { | |
| 137 | renders++; | |
| 138 | await Bun.sleep(5); | |
| 139 | return ok(new Uint8Array([1, 2, 3])); | |
| 140 | }; | |
| 141 | const [x, y] = await Promise.all([cache.through("k", render), cache.through("k", render)]); | |
| 142 | expect(x.ok && y.ok).toBe(true); | |
| 143 | expect(renders).toBe(1); | |
| 144 | await cache.through("k", render); | |
| 145 | expect(renders).toBe(1); | |
| 146 | let failures = 0; | |
| 147 | const failing = async () => (failures++, err("no")); | |
| 148 | expect((await cache.through("f", failing)).ok).toBe(false); | |
| 149 | expect((await cache.through("f", failing)).ok).toBe(false); | |
| 150 | expect(failures).toBe(2); | |
| 151 | }); | |
| 152 | }); | |
| 153 | ||
| 154 | describe("raster arguments", () => { | |
| 155 | test("with the measured fonts, only they are used; without, the system's", () => { | |
| 156 | const fonts = ["/f/LiberationSans-Regular.ttf", "/f/LiberationSans-Bold.ttf", "/f/LiberationMono-Regular.ttf"]; | |
| 157 | const args = resvgArgs(fonts); | |
| 158 | expect(args).toContain("--skip-system-fonts"); | |
| 159 | expect(args.filter((a) => a === "--use-font-file").length).toBe(3); | |
| 160 | expect(args.slice(-2)).toEqual(["-", "-c"]); | |
| 161 | expect(resvgArgs(undefined)).not.toContain("--skip-system-fonts"); | |
| 162 | }); | |
| 163 | }); | |
| 164 | ||
| 165 | describe("kinds and the route", () => { | |
| 166 | let dataDir: string; | |
| 167 | let app: App; | |
| 168 | let servers: Servers; | |
| 169 | let alice: User; | |
| 170 | let cookie: string; | |
| 171 | let source: OgSource; | |
| 172 | ||
| 173 | beforeAll(async () => { | |
| 174 | dataDir = await mkdtemp(join(tmpdir(), "forge-og-")); | |
| 175 | app = createApp({ dataDir, port: 0 }); | |
| 176 | servers = await serve(app); | |
| 177 | const made = await createUser(app.db, { | |
| 178 | username: "alice", | |
| 179 | email: "[email protected]", | |
| 180 | password: "a-good-passphrase", | |
| 181 | adminIfFirst: true, | |
| 182 | }); | |
| 183 | if (!made.ok) throw new Error(made.error); | |
| 184 | alice = made.value; | |
| 185 | cookie = `forge_session=${createSession(app.db, alice.id).token}`; | |
| 186 | const open = await createRepo(app, alice, { name: "engine", visibility: "public", description: "A match engine." }); | |
| 187 | const secret = await createRepo(app, alice, { name: "secret", visibility: "private", description: "the launch plan" }); | |
| 188 | if (!open.ok || !secret.ok) throw new Error("repos"); | |
| 189 | source = { db: app.db, reposRoot: app.reposRoot, host: "forge.example.com" }; | |
| 190 | }); | |
| 191 | ||
| 192 | afterAll(async () => { | |
| 193 | servers.stop(); | |
| 194 | app.close(); | |
| 195 | await rm(dataDir, { recursive: true, force: true }); | |
| 196 | }); | |
| 197 | ||
| 198 | test("a public repository says what it is and what is open", async () => { | |
| 199 | const card = (await kindNamed("repo")!(source, ["alice", "engine"]))!; | |
| 200 | expect(card.eyebrow).toBe("alice/engine"); | |
| 201 | expect(card.description).toBe("A match engine."); | |
| 202 | expect(card.state).toEqual({ label: "public", tone: "success" }); | |
| 203 | expect(card.stats?.map((s) => s.value)).toEqual(["0", "0", "main"]); | |
| 204 | }); | |
| 205 | ||
| 206 | test("a private repository and a missing one draw the same card, which names neither", async () => { | |
| 207 | const repo = kindNamed("repo")!; | |
| 208 | const hidden = await repo(source, ["alice", "secret"]); | |
| 209 | const missing = await repo(source, ["alice", "nothing"]); | |
| 210 | expect(hidden).toEqual(privateCard(source)); | |
| 211 | expect(missing).toEqual(privateCard(source)); | |
| 212 | expect(JSON.stringify(hidden)).not.toContain("launch plan"); | |
| 213 | expect(JSON.stringify(hidden)).not.toContain("secret"); | |
| 214 | }); | |
| 215 | ||
| 216 | test("the forge's own card counts only what is public", async () => { | |
| 217 | const card = (await KINDS["site"]!(source, ["home"]))!; | |
| 218 | expect(card.title).toBe("forge"); | |
| 219 | expect(card.host).toBe("forge.example.com"); | |
| 220 | expect(card.stats?.[0]).toEqual({ value: "1", label: "public repository" }); | |
| 221 | }); | |
| 222 | ||
| 223 | test("a path that is not a kind's shape is no card", async () => { | |
| 224 | expect(await kindNamed("repo")!(source, ["alice"])).toBeUndefined(); | |
| 225 | expect(await kindNamed("repo")!(source, ["alice", "../etc"])).toBeUndefined(); | |
| 226 | expect(await KINDS["site"]!(source, ["elsewhere"])).toBeUndefined(); | |
| 227 | expect(kindNamed("constructor")).toBeUndefined(); | |
| 228 | expect(kindNamed("toString")).toBeUndefined(); | |
| 229 | }); | |
| 230 | ||
| 231 | test("over HTTP: the SVG, its ETag, a 304 for the same data, a 404 for no such kind", async () => { | |
| 232 | const url = `${servers.url}/og/repo/alice/engine.svg`; | |
| 233 | const res = await fetch(url); | |
| 234 | expect(res.status).toBe(200); | |
| 235 | expect(res.headers.get("content-type")).toStartWith("image/svg+xml"); | |
| 236 | expect(res.headers.get("x-content-type-options")).toBe("nosniff"); | |
| 237 | expect(res.headers.get("content-security-policy")).not.toBeNull(); | |
| 238 | const etag = res.headers.get("etag")!; | |
| 239 | expect(etag).toMatch(/^"[0-9a-f]{64}"$/); | |
| 240 | expect(await res.text()).toContain(">A match engine.<"); | |
| 241 | const again = await fetch(url, { headers: { "if-none-match": etag } }); | |
| 242 | expect(again.status).toBe(304); | |
| 243 | for (const path of ["/og/nope/x.png", "/og/repo/alice/engine.gif", "/og/repo/alice.png", "/og/site/home"]) | |
| 244 | expect((await fetch(`${servers.url}${path}`)).status).toBe(404); | |
| 245 | }); | |
| 246 | ||
| 247 | test("over HTTP, a signed-in owner is still served what nobody sees", async () => { | |
| 248 | const anonymous = await fetch(`${servers.url}/og/repo/alice/secret.svg`); | |
| 249 | const owner = await fetch(`${servers.url}/og/repo/alice/secret.svg`, { headers: { cookie } }); | |
| 250 | const body = await owner.text(); | |
| 251 | expect(body).toBe(await anonymous.text()); | |
| 252 | expect(body).toContain(">private<"); | |
| 253 | expect(body).not.toContain("launch plan"); | |
| 254 | expect(owner.headers.get("etag")).toBe(anonymous.headers.get("etag")); | |
| 255 | expect(owner.headers.get("set-cookie")).toBeNull(); | |
| 256 | }); | |
| 257 | ||
| 258 | test("over HTTP, a private repository's cards are byte for byte a missing one's", async () => { | |
| 259 | for (const kind of ["repo", "map"]) { | |
| 260 | const hidden = await fetch(`${servers.url}/og/${kind}/alice/secret.svg`, { headers: { cookie } }); | |
| 261 | const missing = await fetch(`${servers.url}/og/${kind}/alice/nothing.svg`); | |
| 262 | const made = await fetch(`${servers.url}/og/${kind}/bob/made-up-${kind}.svg`); | |
| 263 | const body = await hidden.text(); | |
| 264 | expect(await missing.text()).toBe(body); | |
| 265 | expect(await made.text()).toBe(body); | |
| 266 | expect(hidden.headers.get("etag")).toBe(missing.headers.get("etag")); | |
| 267 | expect(made.headers.get("etag")).toBe(missing.headers.get("etag")); | |
| 268 | expect(body).not.toContain("secret"); | |
| 269 | } | |
| 270 | }); | |
| 271 | ||
| 272 | // Conditional on the tool, and loud about it (test/helpers/tools.ts): | |
| 273 | // a machine without resvg skips these, and says so. | |
| 274 | const noResvg = findResvg() === undefined; | |
| 275 | if (noResvg) | |
| 276 | console.log("SKIPPING: resvg is not installed here (nor FORGE_RESVG set), so the tests that rasterize cannot run on this machine"); | |
| 277 | describe.skipIf(noResvg)("rendered by resvg", () => { | |
| 278 | const cards: Record<string, () => Promise<Card | undefined> | Card | undefined> = { | |
| 279 | site: () => KINDS["site"]!(source, ["home"]), | |
| 280 | repo: () => KINDS["repo"]!(source, ["alice", "engine"]), | |
| 281 | private: () => KINDS["repo"]!(source, ["alice", "secret"]), | |
| 282 | full: () => ({ ...sample, title: "a title long enough to need ".repeat(5) }), | |
| 283 | }; | |
| 284 | ||
| 285 | test("every kind is a 1200 × 630 PNG, cold inside the 300 ms budget", async () => { | |
| 286 | const times: number[] = []; | |
| 287 | for (const [name, card] of Object.entries(cards)) { | |
| 288 | const started = performance.now(); | |
| 289 | const png = await rasterize(cardSvg((await card())!)); | |
| 290 | times.push(performance.now() - started); | |
| 291 | if (!png.ok) throw new Error(`${name}: ${png.error}`); | |
| 292 | const head = pngHeader(png.value); | |
| 293 | expect(head.ok && [head.value.width, head.value.height]).toEqual([1200, 630]); | |
| 294 | expect(png.value.length).toBeLessThan(200 * 1024); | |
| 295 | } | |
| 296 | // The median, so one scheduler hiccup on a busy machine is not a red gate. | |
| 297 | times.sort((a, b) => a - b); | |
| 298 | expect(times[Math.floor(times.length / 2)]!).toBeLessThan(300); | |
| 299 | }); | |
| 300 | ||
| 301 | test("over HTTP: a PNG, and the second ask is served from the cache", async () => { | |
| 302 | const url = `${servers.url}/og/site/home.png`; | |
| 303 | const first = await fetch(url); | |
| 304 | expect(first.status).toBe(200); | |
| 305 | expect(first.headers.get("content-type")).toBe("image/png"); | |
| 306 | const bytes = new Uint8Array(await first.arrayBuffer()); | |
| 307 | expect(Number(first.headers.get("content-length"))).toBe(bytes.length); | |
| 308 | const started = performance.now(); | |
| 309 | const second = await fetch(url); | |
| 310 | const warm = performance.now() - started; | |
| 311 | expect(new Uint8Array(await second.arrayBuffer())).toEqual(bytes); | |
| 312 | expect(second.headers.get("etag")).toBe(first.headers.get("etag")); | |
| 313 | expect(warm).toBeLessThan(50); | |
| 314 | }); | |
| 315 | }); | |
| 316 | }); | |
| 317 | ||
| 318 | describe.skipIf(findResvg() === undefined)("the render queue", () => { | |
| 319 | test("is bounded: past the line, a render is refused, not queued", async () => { | |
| 320 | const svg = cardSvg(sample); | |
| 321 | const all = await Promise.all( | |
| 322 | Array.from({ length: 2 + MAX_WAITING + 4 }, () => rasterize(svg)), | |
| 323 | ); | |
| 324 | const refused = all.filter((r) => !r.ok); | |
| 325 | expect(refused.length).toBe(4); | |
| 326 | for (const r of refused) expect(!r.ok && r.error).toStartWith("busy"); | |
| 327 | // And the line drains: the next one renders. | |
| 328 | expect((await rasterize(svg)).ok).toBe(true); | |
| 329 | }, 30_000); | |
| 330 | }); |
test/standards.test.ts +3 −1
| @@ -154,7 +154,9 @@ describe("what the open web expects", () => { | ||
| 154 | 154 | expect(html).toContain( |
| 155 | 155 | 'rel="apple-touch-icon" href="/icons/forge-180.png"', |
| 156 | 156 | ); |
| 157 | expect(html).toContain('name="twitter:card" content="summary"'); | |
| 157 | // A public repository has its own card (`web/og`), not the icon. | |
| 158 | expect(html).toContain('name="twitter:card" content="summary_large_image"'); | |
| 159 | expect(html).toContain(`property="og:image" content="${base}/og/repo/alice/open.png"`); | |
| 158 | 160 | expect(html).toContain("viewport-fit=cover"); |
| 159 | 161 | }); |
| 160 | 162 |
new above
offline