Skip to content
Myr

resolve.ts

This file

Path

apps/web/src/features/markdown/resolve.ts

63 lines · 1.5 KiB · TypeScript

Last changed by

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

History of this file

Take it

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

line 1why, one step back
1/**

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 2–3why, one step back
2 * The result always names the SHA, never `main`, so it reads the same tree
3 * forever.

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 4–13why, one step back
4 */
5import type { CommitSha, ProjectName } from "@repo/protocol/ids";67export interface RepoUrlContext {8 readonly dir: string;9 readonly kind: "link" | "media";10 readonly project: ProjectName;11 readonly sha: CommitSha;12}13

Merge build/comments-web-features into mainoscabrielbefore adoption74bfc72

lines 14–17why, one step back
14/**
15 * A URL scheme (`https:`, `mailto:`, `javascript:` …): the URL leaves the repo,16 * and the sanitizer judges it.17 */

Merge branch 'build/905-readme-markdown'oscabrielbefore adoption958650a

lines 18–63why, one step back
18const scheme = /^[a-z][a-z0-9+.-]*:/iu;
1920const base = "https://repo.invalid/";2122const edgeSlashes = /^\/+|\/+$/gu;2324const routeOf = (kind: RepoUrlContext["kind"], pathname: string) => {25 if (kind === "media") {26 return "raw";27 }2829 return pathname.endsWith("/") ? "tree" : "blob";30};3132/**33 * Only the parsed path is kept, so a URL the parser reads as another host34 * (`/\host/x`) still lands inside the project.35 */36export const resolveRepoUrl = (url: string, at: RepoUrlContext): string => {37 if (38 url === "" ||39 url.startsWith("#") ||40 url.startsWith("//") ||41 scheme.test(url)42 ) {43 return url;44 }4546 const folder = at.dir47 .split("/")48 .filter((segment) => segment !== "")49 .map((segment) => encodeURIComponent(segment))50 .join("/");5152 const resolved = URL.parse(url, folder === "" ? base : `${base}${folder}/`);5354 if (resolved === null) {55 return "";56 }5758 const path = resolved.pathname.replaceAll(edgeSlashes, "");5960 const route = routeOf(at.kind, resolved.pathname);6162 return `/${at.project}/${route}/${at.sha}${path === "" ? "" : `/${path}`}${resolved.search}${resolved.hash}`;63};