Open History to see the last commit
1import type {
2 Heading,
3 Link,
4 Paragraph,
5 PhrasingContent,
6 Root,
7 RootContent,
8 TableCell,
9 Text,
10} from "mdast";
11import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts";
12import { type PluggableList, type Processor, type Transformer, unified } from "unified";
13import remarkParse from "remark-parse";
14import remarkRehype from "remark-rehype";
15import { find, html } from "property-information";
16import rehypeRaw from "rehype-raw";
17import rehypeSanitize from "rehype-sanitize";
18import remarkBreaks from "remark-breaks";
19import remarkGfm from "remark-gfm";
20import { remarkGithubAlerts } from "./markdownGithubAlerts.ts";
21import { remarkNormalizeListItemIndentation } from "./markdownListIndentation.ts";
22import { remarkKeepOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
23import {
24 remarkEnableLeadingWhitespace,
25 remarkKeepLeadingWhitespace,
26} from "./markdownLeadingWhitespace.ts";
27import { remarkCodexDirectives } from "./codexMarkdownDirectives.ts";
28import { absoluteFilePathMatches } from "./markdownLinks.ts";
29import { isWindowsAbsolutePath } from "./path.ts";
30import {
31 CHAT_MARKDOWN_SANITIZE_SCHEMA,
32 chatMarkdownImageSource,
33 rehypeNormalizeLocalEditorLinks,
34 rehypePreserveImageSourceMeta,
35 type ChatMarkdownImageProperties,
36} from "./markdownHast.ts";
37
38export { chatMarkdownImageSource, type ChatMarkdownImageProperties };
39
40export { remarkEnableOrderedListNumbers } from "./markdownOrderedListNumbers.ts";
41
42type MarkdownImageHastNode = {
43 type?: string;
44 value?: string;
45 tagName?: string;
46 properties?: Record<string, unknown>;
47 children?: MarkdownImageHastNode[];
48};
49
50// Whole tags, attributes, and comments, so closing-anchor text inside them never counts as a tag.
51const RAW_HTML_TAG_PATTERN = /<!--[\s\S]*?(?:-->|$)|<\/?[A-Za-z](?:[^"'<>]|"[^"]*"|'[^']*')*>/g;
52
53function rehypePreserveBareAnchorPlaceholders() {
54 return (tree: MarkdownImageHastNode) => {
55 const anchors: Array<MarkdownImageHastNode | null> = [];
56 let rawTextTag: string | undefined;
57 const visit = (node: MarkdownImageHastNode) => {
58 if (node.type === "raw" && typeof node.value === "string") {
59 const tags = new RegExp(RAW_HTML_TAG_PATTERN);
60 let offset = 0;
61 while (rawTextTag !== "plaintext") {
62 // Raw text ends at its closing tag even inside comment-looking text.
63 const matcher = rawTextTag ? new RegExp(`</${rawTextTag}\\s*>`, "gi") : tags;
64 matcher.lastIndex = offset;
65 const match = matcher.exec(node.value);
66 if (!match) break;
67 const [tag] = match;
68 offset = matcher.lastIndex;
69 if (rawTextTag) {
70 rawTextTag = undefined;
71 continue;
72 }
73 if (tag.startsWith("<!--")) continue;
74 const closing = /^<\/([a-z]+)\s*>$/i.exec(tag)?.[1]?.toLowerCase();
75 const opening = /^<([a-z]+)(?:\s|\/?>)/i.exec(tag)?.[1]?.toLowerCase();
76 if (
77 opening &&
78 /^(?:script|style|textarea|title|xmp|iframe|noembed|noframes|plaintext)$/.test(opening)
79 ) {
80 rawTextTag = opening;
81 } else if (opening === "a") {
82 anchors.push(node.value === tag && /^<a\s*\/?>$/i.test(tag) ? node : null);
83 } else if (closing === "a") {
84 anchors.pop();
85 }
86 }
87 }
88 node.children?.forEach(visit);
89 };
90
91 visit(tree);
92 for (const anchor of anchors) {
93 if (anchor) anchor.type = "text";
94 }
95 };
96}
97
98export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [
99 remarkGfm,
100 remarkEndAutolinksAtScriptPunctuation,
101 remarkKeepAutolinkSuffixes,
102 remarkLinkAbsoluteFilePaths,
103 remarkKeepWindowsPaths,
104 remarkGithubAlerts,
105 remarkKeepOrderedListNumbers,
106 remarkNormalizeListItemIndentation,
107 remarkCodexDirectives,
108 remarkBreakAroundImageLines,
109 remarkPreserveCodeMeta,
110 remarkNormalizeLinksAndTagInlineCode,
111];
112
113// Leading whitespace is kept only where each line renders as a line.
114export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [
115 remarkGfm,
116 remarkEndAutolinksAtScriptPunctuation,
117 remarkKeepAutolinkSuffixes,
118 remarkKeepLeadingWhitespace,
119 remarkLinkAbsoluteFilePaths,
120 remarkKeepWindowsPaths,
121 remarkGithubAlerts,
122 remarkKeepOrderedListNumbers,
123 remarkNormalizeListItemIndentation,
124 remarkCodexDirectives,
125 remarkBreakAroundImageLines,
126 remarkBreaks,
127 remarkPreserveCodeMeta,
128 remarkNormalizeLinksAndTagInlineCode,
129];
130
131// Users type paths like ~/a and (~/b, which GFM's single-tilde strikethrough hides as <del>.
132// Appended after the base list, this reconfigures its remark-gfm entry; ~~double~~ still strikes.
133// Users also indent lines with spaces, which CommonMark drops from a paragraph.
134export const CHAT_USER_MARKDOWN_REMARK_PLUGINS: PluggableList = [
135 [remarkGfm, { singleTilde: false }],
136 remarkEnableLeadingWhitespace,
137];
138
139// Start tags an HTML parser closes an open `<p>` for.
140const CLOSES_PARAGRAPH = new Set(
141 "address article aside blockquote center details dialog dir div dl fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hgroup hr li listing main menu nav ol p plaintext pre search section summary table ul xmp dd dt".split(
142 " ",
143 ),
144);
145const HEADING = /^h[1-6]$/;
146
147interface HtmlScope {
148 readonly anchor: boolean;
149 readonly paragraph: boolean;
150 readonly heading: boolean;
151}
152
153/**
154 * Whether the tree needs the HTML parser: raw HTML, or nesting it repairs (a footnote call in a
155 * link label nests `<a>`). Otherwise it only rewrites properties as hast-util-to-parse5 does and
156 * drops `data`, both repeated here, and moves blank text that renders the same.
157 */
158function needsHtmlParser(node: MarkdownImageHastNode, scope: HtmlScope): boolean {
159 if (node.type === "raw") return true;
160 let inner = scope;
161 if (node.type === "element" && node.tagName) {
162 const { tagName } = node;
163 const heading = HEADING.test(tagName);
164 if (
165 (tagName === "a" && scope.anchor) ||
166 (scope.paragraph && CLOSES_PARAGRAPH.has(tagName)) ||
167 (heading && scope.heading)
168 ) {
169 return true;
170 }
171 inner = {
172 anchor: scope.anchor || tagName === "a",
173 paragraph: scope.paragraph || tagName === "p",
174 heading: scope.heading || heading,
175 };
176 const properties = node.properties ?? {};
177 for (const key of Object.keys(properties)) {
178 const value = properties[key];
179 const info = find(html, key);
180 if (
181 value === false ||
182 value === null ||
183 value === undefined ||
184 Number.isNaN(value) ||
185 (!value && info.boolean)
186 ) {
187 delete properties[key];
188 } else if (value === true && !info.boolean && !info.overloadedBoolean) {
189 properties[key] = "";
190 }
191 }
192 delete (node as { data?: unknown }).data;
193 }
194 return (node.children ?? []).some((child) => needsHtmlParser(child, inner));
195}
196
197const TOP_SCOPE: HtmlScope = { anchor: false, paragraph: false, heading: false };
198
199/** rehype-raw reparses the whole tree through an HTML parser, which most trees can skip. */
200function rehypeRawWhenPresent(this: Processor) {
201 const transform = rehypeRaw.call(this) as unknown as (
202 tree: MarkdownImageHastNode,
203 file: unknown,
204 ) => unknown;
205 return (tree: MarkdownImageHastNode, file: unknown) =>
206 needsHtmlParser(tree, TOP_SCOPE) ? transform(tree, file) : undefined;
207}
208
209export const CHAT_MARKDOWN_REHYPE_PLUGINS: PluggableList = [
210 rehypePreserveBareAnchorPlaceholders,
211 rehypeRawWhenPresent,
212 rehypePreserveImageSourceMeta,
213 rehypeNormalizeLocalEditorLinks,
214 [rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],
215];
216
217const isImageNode = (node: PhrasingContent | undefined): boolean =>
218 node?.type === "image" ||
219 node?.type === "imageReference" ||
220 ((node?.type === "link" || node?.type === "linkReference") &&
221 node.children.length === 1 &&
222 isImageNode(node.children[0]));
223const endsLine = (node: PhrasingContent | undefined) =>
224 node === undefined ||
225 node.type === "break" ||
226 (node.type === "text" && /\n[ \t]*$/.test(node.value));
227const startsLine = (node: PhrasingContent | undefined) =>
228 node === undefined ||
229 node.type === "break" ||
230 (node.type === "text" && /^[ \t]*\n/.test(node.value));
231
232function breakLinesAroundImages(paragraph: Paragraph) {
233 const children = paragraph.children;
234 if (!children.some(isImageNode)) return;
235 const ownsLine = (index: number) =>
236 isImageNode(children[index]) &&
237 endsLine(children[index - 1]) &&
238 startsLine(children[index + 1]);
239 paragraph.children = children.flatMap((child, index): PhrasingContent[] => {
240 if (child.type !== "text") return [child];
241 const afterImage = ownsLine(index - 1);
242 const beforeImage = ownsLine(index + 1);
243 if (!afterImage && !beforeImage) return [child];
244 const parts: PhrasingContent[] = [];
245 let value = child.value;
246 if (afterImage) {
247 value = value.replace(/^[ \t]*\n/, "");
248 parts.push({ type: "break" });
249 }
250 const breakAfter = beforeImage && /\n[ \t]*$/.test(value);
251 if (breakAfter) value = value.replace(/[ \t]*\n[ \t]*$/, "");
252 if (value) parts.push({ type: "text", value });
253 if (breakAfter) parts.push({ type: "break" });
254 return parts;
255 });
256}
257
258/**
259 * Agents label screenshots with a line like `**Palette**` right above the image. CommonMark
260 * joins those lines into one paragraph, which puts the image inline beside its label. An
261 * image alone on its source line keeps that line; prose and inline badges still wrap.
262 */
263function remarkBreakAroundImageLines() {
264 return (tree: Root) => {
265 const visit = (node: Root | RootContent) => {
266 if (node.type === "paragraph") breakLinesAroundImages(node);
267 else if ("children" in node) node.children.forEach(visit);
268 };
269 visit(tree);
270 };
271}
272
273type MarkdownAstNode = {
274 type?: string;
275 meta?: unknown;
276 url?: string;
277 data?: {
278 hProperties?: Record<string, unknown>;
279 };
280 children?: MarkdownAstNode[];
281};
282
283function remarkKeepAutolinkSuffixes(): Transformer<Root> {
284 return (tree, file) => {
285 const source = String(file);
286 const visit = (node: Root | RootContent) => {
287 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
288 for (let index = 0; index < node.children.length; index++) {
289 const child = node.children[index];
290 const next = node.children[index + 1];
291 if (child?.type === "link" && /^https?:\/\//i.test(child.url) && next?.type === "text") {
292 const suffix = /^[_~]+/.exec(next.value)?.[0];
293 if (!suffix) continue;
294 const label = child.children.length === 1 ? child.children[0] : undefined;
295 if (label?.type !== "text") continue;
296 if (label.value !== child.url && `http://${label.value}` !== child.url) continue;
297 const start = child.position?.start.offset;
298 const end = child.position?.end.offset;
299 const bare =
300 !child.position ||
301 (start !== undefined &&
302 end !== undefined &&
303 source.slice(start, end) === label.value &&
304 source.slice(end, end + suffix.length) === suffix);
305 if (bare) {
306 child.url += suffix;
307 label.value += suffix;
308 next.value = next.value.slice(suffix.length);
309 if (child.position && end !== undefined) {
310 const boundary = {
311 ...child.position.end,
312 column: child.position.end.column + suffix.length,
313 offset: end + suffix.length,
314 };
315 child.position.end = boundary;
316 if (label.position) label.position.end = boundary;
317 if (next.position) next.position.start = boundary;
318 }
319 if (!next.value) node.children.splice(index + 1, 1);
320 }
321 }
322 if (child) visit(child);
323 }
324 };
325 visit(tree);
326 };
327}
328
329// Punctuation and symbols from CJK Symbols and Punctuation and from Halfwidth and Fullwidth Forms,
330// plus the Arabic-script comma, semicolon, question mark, and full stop.
331const SCRIPT_PUNCTUATION = /(?=[ -〿-،؛؟۔])[\p{P}\p{S}]/u;
332
333/**
334 * GFM runs a bare URL on until whitespace, so Chinese, Japanese, and Arabic punctuation joins it,
335 * along with the rest of the sentence and any `**` that should have closed around it. A URL that is
336 * ASCII up to such a mark ends there. Unicode earlier in the URL means the mark may belong to it, so it stays.
337 */
338function scriptPunctuationIndex(link: Link): number {
339 const label = link.children.length === 1 ? link.children[0] : undefined;
340 if (label?.type !== "text" || !/^https?:\/\//i.test(link.url)) return -1;
341 if (link.url !== label.value && link.url !== `http://${label.value}`) return -1;
342 const index = label.value.search(/[^!-~]/u);
343 return index > 0 && SCRIPT_PUNCTUATION.test(label.value.charAt(index)) ? index : -1;
344}
345
346/** GFM's text pass links bare URLs without positions; its tokenizer's links span their URL. */
347function isBareLink(link: Link, source: string): boolean {
348 const start = link.position?.start.offset;
349 const end = link.position?.end.offset;
350 const label = link.children[0];
351 return (
352 !link.position ||
353 (start !== undefined &&
354 end !== undefined &&
355 label?.type === "text" &&
356 source.slice(start, end) === label.value)
357 );
358}
359
360/** Source offsets of the marks that tokenized bare URLs run past. */
361function scriptPunctuationOffsets(node: RootContent, source: string): number[] {
362 if (node.type === "link") {
363 const index = scriptPunctuationIndex(node);
364 const start = node.position?.start.offset;
365 return index > 0 && start !== undefined && isBareLink(node, source) ? [start + index] : [];
366 }
367 return "children" in node && node.type !== "linkReference"
368 ? (node.children as RootContent[]).flatMap((child) => scriptPunctuationOffsets(child, source))
369 : [];
370}
371
372const hasReference = (node: RootContent): boolean =>
373 node.type === "linkReference" ||
374 node.type === "imageReference" ||
375 node.type === "footnoteReference" ||
376 ("children" in node && (node.children as RootContent[]).some(hasReference));
377
378/** How many of the ascending numbers are below `value`. */
379function countBelow(sorted: readonly number[], value: number): number {
380 let low = 0;
381 let high = sorted.length;
382 while (low < high) {
383 const middle = (low + high) >> 1;
384 if (sorted[middle]! < value) low = middle + 1;
385 else high = middle;
386 }
387 return low;
388}
389
390/**
391 * Parses the block's text again with a tab before each mark. The tab ends the URL as a space would,
392 * so emphasis around the URL closes and later URLs and code get their own nodes. The tabs are then
393 * dropped and positions mapped back to the source. Returns false and leaves the block alone when its
394 * text would parse differently on its own, as a quote's continuation lines do.
395 */
396function reparseAtScriptPunctuation(
397 processor: Processor,
398 block: Paragraph | Heading | TableCell,
399 source: string,
400 offsets: number[],
401): boolean {
402 // A task item's paragraph starts at its checkbox; its first child starts after it.
403 const from = block.children[0]?.position?.start;
404 const to = block.children.at(-1)?.position?.end;
405 if (from?.offset === undefined || to?.offset === undefined || hasReference(block)) return false;
406 const base = from.offset;
407 const text = source.slice(base, to.offset);
408 // A tab is the marker, a quote's `>` on a later line would read as a new quote, a list's
409 // indentation would join a code span, and only a table unescapes `\|` in code.
410 if (
411 text.includes("\t") ||
412 /[\r\n][ ]*>/.test(text) ||
413 (/[\r\n] /.test(text) && text.includes("`")) ||
414 (block.type === "tableCell" && text.includes("\\|"))
415 ) {
416 return false;
417 }
418 const marks = offsets.map((offset) => offset - base);
419 // Each pass finds the next URL in a run with no spaces, like `http://a,http://b,http://c`.
420 for (let attempt = 0; attempt < 16; attempt++) {
421 marks.sort((a, b) => a - b);
422 const tabs = marks.map((mark, index) => mark + index);
423 const unmarked = (offset: number) => offset - countBelow(tabs, offset);
424 const marked = [0, ...marks]
425 .map((start, index) => text.slice(start, marks[index] ?? text.length))
426 .join("\t");
427 const [paragraph, ...rest] = (processor.parse(marked) as Root).children;
428 if (paragraph?.type !== "paragraph" || rest.length > 0) return false;
429 const more = scriptPunctuationOffsets(paragraph, marked);
430 if (more.length > 0) {
431 marks.push(...more.map(unmarked));
432 continue;
433 }
434
435 let tabCount = 0;
436 const moved = new Set<object>();
437 const restore = (node: RootContent): boolean => {
438 for (const point of node.position ? [node.position.start, node.position.end] : []) {
439 const offset = point.offset;
440 if (offset === undefined || moved.has(point)) continue;
441 moved.add(point);
442 const tabsOnLine = countBelow(tabs, offset) - countBelow(tabs, offset - point.column + 1);
443 point.column = (point.line === 1 ? from.column - 1 : 0) + point.column - tabsOnLine;
444 point.line += from.line - 1;
445 point.offset = base + unmarked(offset);
446 }
447 if (node.type === "text") {
448 tabCount += node.value.split("\t").length - 1;
449 node.value = node.value.replaceAll("\t", "");
450 } else if (
451 ("value" in node && node.value.includes("\t")) ||
452 ("url" in node && node.url.includes("\t"))
453 ) {
454 return false;
455 }
456 if (!("children" in node)) return true;
457 const children = node.children as RootContent[];
458 if (!children.every(restore)) return false;
459 node.children = children.filter(
460 (child) => child.type !== "text" || child.value !== "",
461 ) as typeof node.children;
462 return true;
463 };
464 if (!restore(paragraph) || tabCount !== tabs.length) return false;
465 block.children = paragraph.children;
466 return true;
467 }
468 return false;
469}
470
471/** Ends the bare URLs a reparse could not, and those GFM's text pass linked after emphasis. */
472function splitAtScriptPunctuation(node: RootContent, source: string) {
473 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
474 const children = node.children as RootContent[];
475 for (let index = 0; index < children.length; index++) {
476 const child = children[index]!;
477 if (child.type !== "link") {
478 splitAtScriptPunctuation(child, source);
479 continue;
480 }
481 const at = isBareLink(child, source) ? scriptPunctuationIndex(child) : -1;
482 const label = child.children[0];
483 if (at < 0 || label?.type !== "text") continue;
484 // GFM drops this punctuation from the end of a URL; remarkKeepAutolinkSuffixes restores `_` and `~`.
485 const length = label.value.slice(0, at).replace(/[!"'*,.:;?_~]+$/, "").length;
486 const tail: Text = { type: "text", value: label.value.slice(length) };
487 const start = child.position?.start;
488 if (child.position && start?.offset !== undefined) {
489 const end = {
490 line: start.line,
491 column: start.column + length,
492 offset: start.offset + length,
493 };
494 tail.position = { start: end, end: child.position.end };
495 child.position = { start, end };
496 label.position = { start, end };
497 }
498 child.url = child.url.slice(0, child.url.length - label.value.length + length);
499 label.value = label.value.slice(0, length);
500 children.splice(index + 1, 0, tail);
501 index++;
502 }
503}
504
505function remarkEndAutolinksAtScriptPunctuation(this: Processor): Transformer<Root> {
506 return (tree, file) => {
507 const source = String(file);
508 if (!SCRIPT_PUNCTUATION.test(source)) return;
509 const visit = (node: RootContent) => {
510 if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") {
511 const offsets = scriptPunctuationOffsets(node, source);
512 if (offsets.length > 0) reparseAtScriptPunctuation(this, node, source, offsets);
513 splitAtScriptPunctuation(node, source);
514 } else if ("children" in node) {
515 (node.children as RootContent[]).forEach(visit);
516 }
517 };
518 tree.children.forEach(visit);
519 };
520}
521
522function remarkLinkAbsoluteFilePaths(): Transformer<Root> {
523 return (tree) => {
524 // Raw `<a>` tags are sibling html nodes, so text inside one is not under a link node.
525 let rawAnchorDepth = 0;
526 const visit = (node: Root | RootContent) => {
527 if (!("children" in node) || node.type === "link" || node.type === "linkReference") return;
528 node.children = node.children.flatMap((child): typeof node.children => {
529 if (child.type === "html") {
530 for (const [tag] of child.value.matchAll(RAW_HTML_TAG_PATTERN)) {
531 if (/^<a[\s/>]/i.test(tag)) rawAnchorDepth += 1;
532 else if (/^<\/a[\s>]/i.test(tag)) rawAnchorDepth = Math.max(0, rawAnchorDepth - 1);
533 }
534 }
535 if (child.type !== "text" || rawAnchorDepth > 0) {
536 visit(child);
537 return [child];
538 }
539 const parts: PhrasingContent[] = [];
540 let offset = 0;
541 for (const { index, path } of absoluteFilePathMatches(child.value)) {
542 if (index > offset) parts.push({ type: "text", value: child.value.slice(offset, index) });
543 parts.push({ type: "link", url: path, children: [{ type: "text", value: path }] });
544 offset = index + path.length;
545 }
546 if (offset === 0) return [child];
547 if (offset < child.value.length)
548 parts.push({ type: "text", value: child.value.slice(offset) });
549 return parts;
550 });
551 };
552 visit(tree);
553 };
554}
555
556function remarkPreserveCodeMeta() {
557 return (tree: MarkdownAstNode) => {
558 const visit = (node: MarkdownAstNode) => {
559 if (node.type === "code" && typeof node.meta === "string" && node.meta.trim().length > 0) {
560 node.data = {
561 ...node.data,
562 hProperties: {
563 ...node.data?.hProperties,
564 dataCodeMeta: node.meta.trim(),
565 },
566 };
567 }
568 node.children?.forEach(visit);
569 };
570
571 visit(tree);
572 };
573}
574
575function remarkNormalizeLinksAndTagInlineCode() {
576 return (tree: MarkdownAstNode) => {
577 const visit = (node: MarkdownAstNode, insideLink: boolean) => {
578 if (
579 (node.type === "link" || node.type === "definition") &&
580 typeof node.url === "string" &&
581 /^[A-Za-z]:[\\/]/.test(node.url)
582 ) {
583 node.url = `file:///${node.url.replaceAll("\\", "/")}`;
584 }
585 if (node.type === "inlineCode" && !insideLink) {
586 node.data = {
587 ...node.data,
588 hProperties: {
589 ...node.data?.hProperties,
590 dataInlineCode: "",
591 },
592 };
593 }
594 const childInsideLink = insideLink || node.type === "link" || node.type === "linkReference";
595 node.children?.forEach((child) => visit(child, childInsideLink));
596 };
597
598 visit(tree, false);
599 };
600}
601
602export function remarkAssistantInsights(this: Processor) {
603 return (tree: Root, file: { value: unknown }) => {
604 const source = String(file.value);
605 if (!source.includes("★ Insight")) return;
606 const protectedRanges: { start: number; end: number; code: boolean }[] = [];
607 const inspect = (node: RootContent | PhrasingContent) => {
608 const start = node.position?.start.offset;
609 const end = node.position?.end.offset;
610 if (start !== undefined && end !== undefined) {
611 const code =
612 node.type === "code" ||
613 node.type === "html" ||
614 (node.type === "inlineCode" && node.position?.start.line !== node.position?.end.line);
615 if (code || node.type === "list" || node.type === "blockquote")
616 protectedRanges.push({ start, end, code });
617 }
618 if ("children" in node) node.children.forEach(inspect);
619 };
620 tree.children.forEach(inspect);
621 const starts = new Set<number>();
622 const offsets: { original: number; rewritten: number; prefix: number }[] = [];
623 let indent: string | undefined;
624 let original = 0;
625 let rewritten = 0;
626 const lines = source.split(/(?<=\n)|(?<=\r)(?!\n)/u).map((line, index) => {
627 const value = line.replace(/[\r\n]+$/u, "");
628 const blocked = protectedRanges.some(
629 (range) =>
630 original >= range.start && original < range.end && (indent === undefined || range.code),
631 );
632 const opening =
633 indent === undefined && !blocked
634 ? /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u.exec(value)
635 : null;
636 const closing =
637 indent !== undefined && !blocked ? /^( {0,3})(`?)─{3,}\2[ \t]*$/u.exec(value) : null;
638 let prefix = 0;
639 let output = line;
640 if (opening) {
641 indent = opening[1] ?? "";
642 starts.add(index + 1);
643 output = ">" + line.slice(value.length);
644 } else if (closing && closing[1] === indent) {
645 indent = undefined;
646 output = line.slice(value.length);
647 } else if (indent !== undefined) {
648 prefix = 2;
649 output = "> " + line;
650 }
651 offsets.push({ original, rewritten, prefix });
652 original += line.length;
653 rewritten += output.length;
654 return output;
655 });
656 if (starts.size === 0) return;
657 const parsed = this.parse(lines.join("")) as Root;
658 const restorePosition = (node: RootContent | PhrasingContent) => {
659 if (node.position) {
660 for (const point of [node.position.start, node.position.end]) {
661 const offset = offsets[point.line - 1];
662 if (!offset) continue;
663 point.column = Math.max(1, point.column - offset.prefix);
664 if (point.offset !== undefined)
665 point.offset += offset.original - offset.rewritten - offset.prefix;
666 }
667 }
668 if ("children" in node) node.children.forEach(restorePosition);
669 };
670 for (const node of parsed.children) {
671 if (node.type === "blockquote" && starts.has(node.position?.start.line ?? 0)) {
672 node.data = { ...node.data, hProperties: { dataAlert: "insight" } };
673 }
674 restorePosition(node);
675 }
676 tree.children = parsed.children;
677 };
678}
679
680const imageSourceProcessor = unified()
681 .use(remarkParse)
682 .use(CHAT_MARKDOWN_REMARK_PLUGINS)
683 .use(remarkRehype, { allowDangerousHtml: true })
684 .use(CHAT_MARKDOWN_REHYPE_PLUGINS);
685
686interface ImageSourceNode {
687 readonly type: string;
688 readonly tagName?: string;
689 readonly properties?: ChatMarkdownImageProperties;
690 readonly children?: ReadonlyArray<ImageSourceNode>;
691}
692
693/**
694 * Collect the fallback and every theme variant so images are available to all viewers.
695 */
696export function chatMarkdownImageSources(markdown: string): Array<string> {
697 const sources: Array<string> = [];
698 const visit = (node: ImageSourceNode) => {
699 if (node.type === "element" && node.tagName === "img") {
700 const properties = node.properties;
701 const fallback = chatMarkdownImageSource(properties);
702 if (fallback) sources.push(fallback.classifiedSrc);
703 for (const [theme, variant] of [
704 ["dark", properties?.dataDarkSrc],
705 ["light", properties?.dataLightSrc],
706 ] as const) {
707 if (typeof variant !== "string") continue;
708 const source = chatMarkdownImageSource(properties, theme);
709 if (source) sources.push(source.classifiedSrc);
710 }
711 }
712 node.children?.forEach(visit);
713 };
714 visit(imageSourceProcessor.runSync(imageSourceProcessor.parse(markdown)) as ImageSourceNode);
715 return sources;
716}
717
718const linkDestinationProcessor = unified().use(remarkParse).use(remarkKeepWindowsPaths);
719
720// An angle destination cannot hold an unescaped `<` or `>`, or end on a lone backslash.
721const ANGLE_DESTINATION_CONTENT = /^(?:[^\\<>]|\\.)*$/;
722
723/** Reads a destination from `extractMarkdownLinkHrefs` as the renderer's parser does. */
724export function decodeMarkdownLinkEscapes(href: string): string {
725 // Only the parser knows character references, so destinations that may have one go through it.
726 if (href.includes("&")) {
727 // The extractor drops angle brackets, and only that form keeps an unmatched `)` in the path.
728 const destination = ANGLE_DESTINATION_CONTENT.test(href) ? `<${href}>` : href;
729 const paragraph = linkDestinationProcessor.parse(`[](${destination})`).children[0];
730 const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined;
731 if (link?.type === "link") return link.url;
732 }
733 return isWindowsAbsolutePath(href) ? href : href.replace(/\\([!-/:-@[-`{-~])/g, "$1");
734}