Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownHast.ts

219 lines7.9 KB

1import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts";
2import type { Root } from "hast";
3import { defaultSchema, sanitize, type Schema } from "hast-util-sanitize";
4​
5import { CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES } from "./codexArtifactTemplates.ts";
6import {
7 isWindowsDrivePathHref,
8 normalizeMarkdownLinkDestination,
9 parseMarkdownSandboxFileLink,
10} from "./markdownLinks.ts";
11import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
12​
13type MarkdownImageHastNode = {
14 type?: string;
15 value?: string;
16 tagName?: string;
17 properties?: Record<string, unknown>;
18 children?: MarkdownImageHastNode[];
19};
20​
21function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
22 return (node.children ?? []).filter(
23 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
24 );
26​
27const STANDALONE_IMAGE_BLOCKS = new Set([
28 "p",
29 "div",
30 "li",
31 "td",
32 "th",
33 "figure",
34 "center",
35 "blockquote",
36]);
37​
38function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
39 const children = meaningfulHastChildren(node);
40 if (children.length !== 1) return undefined;
41 const only = children[0];
42 if (only?.type !== "element") return undefined;
43 if (only.tagName === "img") return only;
44 return only.tagName === "a" || only.tagName === "strong" || only.tagName === "em"
45 ? soleImageDescendant(only)
46 : undefined;
48​
49function markStandaloneImages(node: MarkdownImageHastNode) {
50 if (node.type === "root" || (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName))) {
51 const image = soleImageDescendant(node);
52 if (image) image.properties = { ...image.properties, dataStandalone: true };
53 }
54 node.children?.forEach((child) => {
55 if (child.type === "element") markStandaloneImages(child);
56 });
58​
59const COLOR_SCHEME_MEDIA = /^\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)$/i;
60​
61/**
62 * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
63 * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
64 * onto the `<img>` for the renderer to pick by theme; every source is then dropped.
65 */
66function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
67 if (!picture.children) return;
68 const image = picture.children.find((child) => child.tagName === "img");
69 for (const source of picture.children) {
70 if (source.tagName !== "source" || !image) continue;
71 const media = source.properties?.media;
72 const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
73 const srcSet = source.properties?.srcSet;
74 const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
75 // A candidate's URL runs to the first space (a descriptor such as `2x` may follow).
76 const url =
77 typeof candidate === "string" ? candidate.trim().split(/\s/, 1)[0]?.replace(/,+$/, "") : "";
78 const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
79 // As in a browser, the first source that matches a scheme is the one shown.
80 if (scheme && url && image.properties?.[key] === undefined) {
81 // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.
82 const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;
83 image.properties = { ...image.properties, [key]: value };
84 }
85 }
86 picture.children = picture.children.filter((child) => child.tagName !== "source");
88​
89export function rehypePreserveImageSourceMeta() {
90 return (tree: MarkdownImageHastNode) => {
91 const visit = (node: MarkdownImageHastNode) => {
92 const src = node.properties?.src;
93 const title = node.properties?.title;
94 if (node.type === "element" && node.tagName === "picture") {
95 moveColorSchemeSourcesToImage(node);
96 }
97 if (node.type === "element" && node.tagName === "img") {
98 node.properties = {
99 ...node.properties,
100 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
101 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
102 };
103 }
104 node.children?.forEach(visit);
105 };
106​
107 visit(tree);
108 markStandaloneImages(tree);
109 };
111​
112const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
113​
114// The sanitizer compares schemes case-sensitively, so lowercase accepted file link schemes first.
115function normalizeLocalFileHref(href: string): string {
116 if (/^sandbox:/i.test(href)) {
117 return parseMarkdownSandboxFileLink(href) ? href.replace(/^sandbox:/i, "sandbox:") : "";
118 }
119 try {
120 const url = new URL(href);
121 return isLocalEditorFileUrl(url) ? url.href : href;
122 } catch {
123 // Not an absolute URL; the sanitizer decides.
124 return href;
125 }
127​
128export function rehypeNormalizeLocalFileLinks() {
129 return (tree: MarkdownImageHastNode) => {
130 const visit = (node: MarkdownImageHastNode) => {
131 const href = node.properties?.href;
132 if (node.type === "element" && node.tagName === "a" && typeof href === "string") {
133 const normalized = normalizeLocalFileHref(href);
134 if (normalized !== href) node.properties = { ...node.properties, href: normalized };
135 }
136 node.children?.forEach(visit);
137 };
138​
139 visit(tree);
140 };
142​
143export const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
144 ...defaultSchema,
145 attributes: {
146 ...defaultSchema.attributes,
147 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
148 // Fence languages plus the two math classes the web chat's math plugin emits.
149 code: [
150 ["className", /^language-./, "math-inline", "math-display"],
151 "dataCodeMeta",
152 "dataInlineCode",
153 ],
154 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
155 // Spaces typed at the start of a user's line (keepLeadingWhitespace).
156 span: [...(defaultSchema.attributes?.span ?? []), "dataLeadingWhitespace"],
157 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
158 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
159 img: [
160 ...(defaultSchema.attributes?.img ?? []),
161 "dataDarkSrc",
162 "dataLightSrc",
163 "dataLocalSrc",
164 "dataMarkdownTitle",
165 "dataStandalone",
166 ],
167 },
168 protocols: {
169 ...defaultSchema.protocols,
170 href: [
171 ...(defaultSchema.protocols?.href ?? []),
172 "file",
173 "sandbox",
174 "t3-citation",
175 "t3-context",
176 THREAD_LINK_PROTOCOL,
177 // Scheme only: the renderer's URL transform checks the rest of the link shape.
178 ...LOCAL_FILE_LINK_SCHEMES,
179 ],
180 src: IMAGE_SRC_PROTOCOLS,
181 dataDarkSrc: IMAGE_SRC_PROTOCOLS,
182 dataLightSrc: IMAGE_SRC_PROTOCOLS,
183 },
184} satisfies Schema;
185​
186/** Sanitizes one tree with the chat's schema, as the last rehype plugin does. */
187export const sanitizeChatHast = (tree: Root): Root =>
188 sanitize(tree, CHAT_MARKDOWN_SANITIZE_SCHEMA) as Root;
189​
190export type ChatMarkdownImageProperties = {
191 readonly src?: unknown;
192 readonly dataLocalSrc?: unknown;
193 readonly dataDarkSrc?: unknown;
194 readonly dataLightSrc?: unknown;
195};
196​
197/** Keep the authored path for file links and normalize Windows separators for classification. */
198export function chatMarkdownImageSource(
199 properties?: ChatMarkdownImageProperties,
200 theme?: "dark" | "light",
201) {
202 const themeSrc =
203 theme === undefined
204 ? undefined
205 : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
206 const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc;
207 const source =
208 typeof themeSrc === "string"
209 ? themeSrc
210 : typeof localSrc === "string"
211 ? localSrc
212 : properties?.src;
213 if (typeof source !== "string") return null;
214 const authoredSrc = normalizeMarkdownLinkDestination(source);
215 return {
216 authoredSrc,
217 classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc,
218 };