Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

138 linesCodeBlameRaw
1/**
2 * g1t's additions to GitHub flavoured markdown. They run on the HTML tree
3 * after it has been sanitized, so what they add is trusted and what the
4 * author wrote never is.
5 */
6
7import { type RefContext, parseRef, refHref } from "./refs.ts";
8
9type Text = { type: "text"; value: string };
10type Element = {
11 type: "element";
12 tagName: string;
13 properties: Record<string, unknown>;
14 children: Node[];
15};
16/** A node of the HTML tree, loosely: only what these plugins read. */
17type Node = { type: string; value?: string; tagName?: string; properties?: Record<string, unknown>; children?: Node[] };
18
19/** The repository a document belongs to, so `#12` is read in it. */
20export type MarkdownRepo = { namespace: string; name: string };
21
22/** The repository a site path like `/acme/web` names. */
23export function repoAt(base?: string): MarkdownRepo | undefined {
24 const [namespace, name] = (base ?? "").split("/").filter(Boolean);
25 return namespace && name ? { namespace, name } : undefined;
26}
27
28export const ALERTS = ["note", "tip", "important", "warning", "caution"] as const;
29export type AlertKind = (typeof ALERTS)[number];
30
31const ALERT_MARKER = /^\s*\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*\n?/i;
32
33function isElement(node: Node, tag?: string): node is Element {
34 return node.type === "element" && (tag == null || (node as Element).tagName === tag);
35}
36
37/**
38 * GitHub's alerts: a quote that starts with `[!NOTE]`, `[!TIP]`,
39 * `[!IMPORTANT]`, `[!WARNING]` or `[!CAUTION]` becomes a callout.
40 */
41export function rehypeAlerts() {
42 return (tree: Node) => {
43 const walk = (node: Node) => {
44 for (const child of node.children ?? []) {
45 if (isElement(child, "blockquote")) {
46 const first = child.children.find((c): c is Element => isElement(c, "p"));
47 const text = first?.children[0];
48 const match = text?.type === "text" ? ALERT_MARKER.exec((text as Text).value) : null;
49 if (first && text && match) {
50 (text as Text).value = (text as Text).value.slice(match[0].length);
51 // A marker on a line of its own leaves an empty paragraph behind.
52 if (first.children.length === 1 && !(text as Text).value.trim()) {
53 child.children = child.children.filter((c) => c !== first);
54 }
55 child.properties = { ...child.properties, dataAlert: match[1]!.toLowerCase() };
56 }
57 }
58 walk(child);
59 }
60 };
61 walk(tree);
62 };
63}
64
65/**
66 * Where `@g1t` leads: g1t's own agent, which has no profile. Never `/g1t`,
67 * which staff made an alias of Flagon, Inc.'s workspace: mentioning g1t
68 * always means the agent.
69 */
70export const G1T_MENTION_HREF = "https://docs.g1t.sh/";
71
72/** `owner/repo#12`, `workspace#12`, `#12`, `@workspace/team`, `@name` and commit hashes, in one pass. */
73const REFERENCE =
74 /(?<![\w/@#])(?:(?:([a-z0-9][a-z0-9-]*)(?:\/([a-z0-9._-]+))?)?#(\d+)|@([a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38})\/([a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,59})|@([a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38})|([0-9a-f]{7,40}))(?![\w-])/gi;
75
76function link(href: string, text: string, kind: string): Element {
77 return {
78 type: "element",
79 tagName: "a",
80 properties: { href, dataRef: kind },
81 children: [{ type: "text", value: text }],
82 };
83}
84
85/**
86 * Links what a forge's text refers to: `#12`, `owner/repo#12` and
87 * `workspace#12` to the work item or pull request they name, read as
88 * lib/refs.ts says (in the document's repository, else its workspace),
89 * `@name` to a person or workspace (`@g1t` to how g1t's agent works), and
90 * a commit hash to its commit. Nothing inside code or a link changes.
91 */
92export function rehypeReferences(options: { repo?: MarkdownRepo; workspace?: string }) {
93 const { repo, workspace: here } = options;
94 const context: RefContext | null = repo ? { repo } : here ? { workspace: here } : null;
95 return (tree: Node) => {
96 const walk = (node: Node) => {
97 const children = node.children;
98 if (!children) return;
99 for (let index = 0; index < children.length; index++) {
100 const child = children[index]!;
101 if (isElement(child)) {
102 if (child.tagName === "a" || child.tagName === "code" || child.tagName === "pre") continue;
103 walk(child);
104 continue;
105 }
106 if (child.type !== "text") continue;
107 const value = (child as Text).value;
108 const parts: Node[] = [];
109 let last = 0;
110 for (const match of value.matchAll(REFERENCE)) {
111 const [whole, owner, otherName, number, workspace, team, name, hash] = match;
112 let replacement: Element | null = null;
113 if (number) {
114 const ref = parseRef(owner, otherName, number);
115 const href = ref ? refHref(ref, context) : null;
116 if (href) replacement = link(href, whole, "ref");
117 } else if (workspace && team) {
118 replacement = link(`/${workspace.toLowerCase()}/-/teams/${team.toLowerCase()}`, whole, "team");
119 } else if (name) {
120 const href = name.toLowerCase() === "g1t" ? G1T_MENTION_HREF : `/${name.toLowerCase()}`;
121 replacement = link(href, whole, "mention");
122 } else if (hash && repo && /\d/.test(hash) && /[a-f]/i.test(hash)) {
123 replacement = link(`/${repo.namespace}/${repo.name}/commit/${hash}`, hash.slice(0, 7), "commit");
124 }
125 if (!replacement) continue;
126 if (match.index! > last) parts.push({ type: "text", value: value.slice(last, match.index) });
127 parts.push(replacement);
128 last = match.index! + whole.length;
129 }
130 if (parts.length === 0) continue;
131 if (last < value.length) parts.push({ type: "text", value: value.slice(last) });
132 children.splice(index, 1, ...parts);
133 index += parts.length - 1;
134 }
135 };
136 walk(tree);
137 };
138}