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