Open History to see the last commit
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 parseObsidianNavigationHref,
11} from "./markdownLinks.ts";
12import { THREAD_LINK_PROTOCOL } from "./threadLinks.ts";
13
14type MarkdownImageHastNode = {
15 type?: string;
16 value?: string;
17 tagName?: string;
18 properties?: Record<string, unknown>;
19 children?: MarkdownImageHastNode[];
20};
21
22function meaningfulHastChildren(node: MarkdownImageHastNode): MarkdownImageHastNode[] {
23 return (node.children ?? []).filter(
24 (child) => !(child.type === "text" && (child as { value?: string }).value?.trim() === ""),
25 );
26}
27
28const STANDALONE_IMAGE_BLOCKS = new Set([
29 "p",
30 "div",
31 "li",
32 "td",
33 "th",
34 "figure",
35 "center",
36 "blockquote",
37]);
38
39function soleImageDescendant(node: MarkdownImageHastNode): MarkdownImageHastNode | undefined {
40 const children = meaningfulHastChildren(node);
41 if (children.length !== 1) return undefined;
42 const only = children[0];
43 if (only?.type !== "element") return undefined;
44 if (only.tagName === "img") return only;
45 return only.tagName === "a" ||
46 only.tagName === "strong" ||
47 only.tagName === "em" ||
48 only.tagName === "picture"
49 ? soleImageDescendant(only)
50 : undefined;
51}
52
53const BLOCK_ELEMENTS = new Set([
54 ...STANDALONE_IMAGE_BLOCKS,
55 "address",
56 "article",
57 "aside",
58 "dd",
59 "details",
60 "dl",
61 "dt",
62 "figcaption",
63 "footer",
64 "h1",
65 "h2",
66 "h3",
67 "h4",
68 "h5",
69 "h6",
70 "header",
71 "hr",
72 "main",
73 "nav",
74 "ol",
75 "pre",
76 "section",
77 "summary",
78 "table",
79 "ul",
80]);
81
82const isBlockOrEdge = (node: MarkdownImageHastNode | undefined) =>
83 !node || (node.type === "element" && BLOCK_ELEMENTS.has(node.tagName ?? ""));
84
85// A raw-HTML image block between other blocks sits directly under the root, with no paragraph of
86// its own; it is standalone when nothing inline shares its line.
87function markRootImageBlocks(root: MarkdownImageHastNode) {
88 const children = meaningfulHastChildren(root).filter((child) => child.type !== "comment");
89 children.forEach((child, index) => {
90 if (isBlockOrEdge(child)) return;
91 const image = soleImageDescendant({ children: [child] });
92 if (image && isBlockOrEdge(children[index - 1]) && isBlockOrEdge(children[index + 1])) {
93 image.properties = { ...image.properties, dataStandalone: true };
94 }
95 });
96}
97
98function markStandaloneImages(node: MarkdownImageHastNode) {
99 if (node.type === "root") markRootImageBlocks(node);
100 else if (node.tagName && STANDALONE_IMAGE_BLOCKS.has(node.tagName)) {
101 const image = soleImageDescendant(node);
102 if (image) image.properties = { ...image.properties, dataStandalone: true };
103 }
104 node.children?.forEach((child) => {
105 if (child.type === "element") markStandaloneImages(child);
106 });
107}
108
109const COLOR_SCHEME_MEDIA =
110 /^[\t\n\f\r ]*\(\s*prefers-color-scheme\s*:\s*(dark|light)\s*\)[\t\n\f\r ]*$/i;
111const FIRST_SRCSET_URL = /^[\t\n\f\r ]*([^\t\n\f\r ]+)/;
112
113function normalizeUrlScheme(url: string): string {
114 return url.replace(/^(?:https?|file):/i, (scheme) => scheme.toLowerCase());
115}
116
117/**
118 * The renderer resolves an `<img>`'s `src` (workspace files, host media) but never a `<source>`'s
119 * `srcset`, which would load unresolved whenever its media matched. A color-scheme source moves
120 * onto the `<img>` for the renderer to pick by theme; every source is then dropped.
121 */
122function moveColorSchemeSourcesToImage(picture: MarkdownImageHastNode) {
123 if (!picture.children) return;
124 const image = picture.children.find((child) => child.tagName === "img");
125 for (const source of picture.children) {
126 if (source.tagName !== "source" || !image) continue;
127 const media = source.properties?.media;
128 const scheme = typeof media === "string" ? COLOR_SCHEME_MEDIA.exec(media)?.[1] : undefined;
129 const srcSet = source.properties?.srcSet;
130 const candidate = Array.isArray(srcSet) ? srcSet[0] : srcSet;
131 // HTML srcset splits URLs on ASCII whitespace only, so U+00A0 in filenames stays intact.
132 const url =
133 typeof candidate === "string"
134 ? (FIRST_SRCSET_URL.exec(candidate)?.[1]?.replace(/,+$/, "") ?? "")
135 : "";
136 const key = scheme?.toLowerCase() === "dark" ? "dataDarkSrc" : "dataLightSrc";
137 // As in a browser, the first source that matches a scheme is the one shown.
138 if (scheme && url && image.properties?.[key] === undefined) {
139 // The sanitizer reads a drive letter as a protocol; as a file URL it resolves to the same path.
140 const value = isWindowsDrivePathHref(url) ? `file:///${url.replaceAll("\\", "/")}` : url;
141 image.properties = { ...image.properties, [key]: value };
142 }
143 }
144 picture.children = picture.children.filter((child) => child.tagName !== "source");
145}
146
147export function rehypePreserveImageSourceMeta() {
148 return (tree: MarkdownImageHastNode) => {
149 const visit = (node: MarkdownImageHastNode) => {
150 const src = node.properties?.src;
151 const title = node.properties?.title;
152 if (node.type === "element" && node.tagName === "picture") {
153 moveColorSchemeSourcesToImage(node);
154 }
155 if (node.type === "element" && node.tagName === "img") {
156 node.properties = {
157 ...node.properties,
158 ...(typeof src === "string" && isWindowsDrivePathHref(src) ? { dataLocalSrc: src } : {}),
159 ...(typeof title === "string" ? { dataMarkdownTitle: title } : {}),
160 };
161 for (const key of ["src", "dataDarkSrc", "dataLightSrc"]) {
162 const value = node.properties[key];
163 if (typeof value === "string") node.properties[key] = normalizeUrlScheme(value);
164 }
165 }
166 node.children?.forEach(visit);
167 };
168
169 visit(tree);
170 markStandaloneImages(tree);
171 };
172}
173
174const IMAGE_SRC_PROTOCOLS = [...(defaultSchema.protocols?.src ?? []), "file", "t3-context"];
175const NORMALIZED_HREF_SCHEMES = new Set([...(defaultSchema.protocols?.href ?? []), "file"]);
176
177// The sanitizer compares schemes case-sensitively, so lowercase accepted link schemes first.
178function normalizeHrefScheme(href: string): string {
179 return href.replace(/^([a-z][a-z0-9+.-]*):/i, (match, scheme: string) => {
180 const lower = scheme.toLowerCase();
181 return NORMALIZED_HREF_SCHEMES.has(lower) ? `${lower}:` : match;
182 });
183}
184
185function normalizeLocalFileHref(href: string): string | undefined {
186 if (/^obsidian:/i.test(href)) return parseObsidianNavigationHref(href) ?? undefined;
187 if (/^sandbox:/i.test(href)) {
188 return parseMarkdownSandboxFileLink(href) ? href.replace(/^sandbox:/i, "sandbox:") : "";
189 }
190 try {
191 const url = new URL(href);
192 return isLocalEditorFileUrl(url) ? url.href : href;
193 } catch {
194 // Not an absolute URL; the sanitizer decides.
195 return href;
196 }
197}
198
199export function rehypeNormalizeLocalFileLinks() {
200 return (tree: MarkdownImageHastNode) => {
201 const visit = (node: MarkdownImageHastNode) => {
202 const href = node.properties?.href;
203 if (node.type === "element" && node.tagName === "a" && typeof href === "string") {
204 const normalized = normalizeLocalFileHref(normalizeHrefScheme(href));
205 if (normalized !== href) node.properties = { ...node.properties, href: normalized };
206 }
207 node.children?.forEach(visit);
208 };
209
210 visit(tree);
211 };
212}
213
214export const CHAT_MARKDOWN_SANITIZE_SCHEMA = {
215 ...defaultSchema,
216 attributes: {
217 ...defaultSchema.attributes,
218 "*": (defaultSchema.attributes?.["*"] ?? []).filter((attribute) => attribute !== "title"),
219 // Fence languages plus the two math classes the web chat's math plugin emits.
220 code: [
221 ["className", /^language-./, "math-inline", "math-display"],
222 "dataCodeMeta",
223 "dataInlineCode",
224 ],
225 blockquote: [...(defaultSchema.attributes?.blockquote ?? []), "dataAlert"],
226 // Spaces typed at the start of a user's line (keepLeadingWhitespace).
227 span: [...(defaultSchema.attributes?.span ?? []), "dataLeadingWhitespace"],
228 div: [...(defaultSchema.attributes?.div ?? []), ...CODEX_ARTIFACT_TEMPLATE_HAST_PROPERTIES],
229 a: [...(defaultSchema.attributes?.a ?? []), "dataPullRequestAutolink"],
230 img: [
231 ...(defaultSchema.attributes?.img ?? []),
232 "dataDarkSrc",
233 "dataLightSrc",
234 "dataLocalSrc",
235 "dataMarkdownTitle",
236 "dataStandalone",
237 ],
238 },
239 protocols: {
240 ...defaultSchema.protocols,
241 href: [
242 ...(defaultSchema.protocols?.href ?? []),
243 "file",
244 "sandbox",
245 "t3-citation",
246 "t3-context",
247 THREAD_LINK_PROTOCOL,
248 "obsidian",
249 // Scheme only: the renderer's URL transform checks the rest of the link shape.
250 ...LOCAL_FILE_LINK_SCHEMES,
251 ],
252 src: IMAGE_SRC_PROTOCOLS,
253 dataDarkSrc: IMAGE_SRC_PROTOCOLS,
254 dataLightSrc: IMAGE_SRC_PROTOCOLS,
255 },
256} satisfies Schema;
257
258/** Sanitizes one tree with the chat's schema, as the last rehype plugin does. */
259export const sanitizeChatHast = (tree: Root): Root =>
260 sanitize(tree, CHAT_MARKDOWN_SANITIZE_SCHEMA) as Root;
261
262export type ChatMarkdownImageProperties = {
263 readonly src?: unknown;
264 readonly dataLocalSrc?: unknown;
265 readonly dataDarkSrc?: unknown;
266 readonly dataLightSrc?: unknown;
267};
268
269/** Keep the authored path for file links and normalize Windows separators for classification. */
270export function chatMarkdownImageSource(
271 properties?: ChatMarkdownImageProperties,
272 theme?: "dark" | "light",
273) {
274 const themeSrc =
275 theme === undefined
276 ? undefined
277 : properties?.[theme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
278 const localSrc = typeof themeSrc === "string" ? undefined : properties?.dataLocalSrc;
279 const source =
280 typeof themeSrc === "string"
281 ? themeSrc
282 : typeof localSrc === "string"
283 ? localSrc
284 : properties?.src;
285 if (typeof source !== "string") return null;
286 const authoredSrc = normalizeMarkdownLinkDestination(source);
287 return {
288 authoredSrc,
289 classifiedSrc: typeof localSrc === "string" ? authoredSrc.replaceAll("\\", "/") : authoredSrc,
290 };
291}