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

markdownDocument.ts

564 lines21.9 KB

1import type { Root, RootContent } from "mdast";
2import { unified, type Processor } from "unified";
3import remarkParse from "remark-parse";
4import remarkGfm from "remark-gfm";
5import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths";
6import {
7 absoluteFilePathMatches,
8 inlineCodeFilePathCandidate,
9 parseMarkdownFileLink,
10} from "@t3tools/shared/markdownLinks";
11import { isWindowsAbsolutePath } from "@t3tools/shared/path";
12​
13const parser = unified().use(remarkParse).use(remarkGfm).use(remarkKeepWindowsProsePaths);
14export type MarkdownNode = Root | RootContent;
15​
16interface MarkdownEdit {
17 readonly start: number;
18 readonly end: number;
19 readonly content: string;
21​
22function applyMarkdownEdits(markdown: string, edits: MarkdownEdit[]): string {
23 if (edits.length === 0) return markdown;
24 const parts: string[] = [];
25 let offset = 0;
26 // AST traversal emits disjoint edits in source order.
27 for (const edit of edits) {
28 parts.push(markdown.slice(offset, edit.start), edit.content);
29 offset = edit.end;
30 }
31 parts.push(markdown.slice(offset));
32 return parts.join("");
34​
35function decodeCodePoint(codePoint: number, entity: string): string {
36 if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
37 return entity;
38 }
39 return String.fromCodePoint(codePoint);
41​
42export function decodeHtmlEntities(value: string): string {
43 return value.replace(
44 /&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
45 (entity, decimal: string | undefined, hexadecimal: string | undefined) => {
46 if (decimal) {
47 return decodeCodePoint(Number.parseInt(decimal, 10), entity);
48 }
49 if (hexadecimal) {
50 return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
51 }
52 switch (entity.toLowerCase()) {
53 case "&amp;":
54 return "&";
55 case "&apos;":
56 return "'";
57 case "&gt;":
58 return ">";
59 case "&lt;":
60 return "<";
61 case "&nbsp;":
62 return "\u00a0";
63 case "&quot;":
64 return '"';
65 default:
66 return entity;
67 }
68 },
69 );
71​
72const HTML_TAG = /<!--[\s\S]*?-->|<\/?[a-z](?:[^>"']|"[^"]*"|'[^']*')*>/gi;
73​
74function attribute(tag: string, name: string): string | null {
75 const attributes = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g;
76 for (const match of tag.matchAll(attributes)) {
77 if (match[1]?.toLowerCase() === name) {
78 return decodeHtmlEntities(match[2] ?? match[3] ?? match[4] ?? "");
79 }
80 }
81 return null;
83​
84function markdownDestination(url: string): string {
85 return `<${url.replace(/&/g, "\\&").replace(/</g, "%3C").replace(/>/g, "%3E").replace(/\|/g, "%7C").replace(/\n/g, "")}>`;
87​
88const ANCHOR_TAG = /^<\/?a[\s/>]/i;
89​
90/** Replacements for the anchor tags still ahead, and how many emitted links are open. */
91type AnchorState = { readonly pending: string[]; open: number };
92​
93// Code spans keep their text; an odd trailing backslash would escape the closing "]".
94function escapeLinkLabel(text: string): string {
95 return text
96 .replace(/(`+)[\s\S]*?\1|\\*[[\]]/g, (match) =>
97 match.startsWith("`") || match.length % 2 === 0
98 ? match
99 : `${match.slice(0, -1)}\\${match.slice(-1)}`,
100 )
101 .replace(/\\+$/, (slashes) => (slashes.length % 2 ? `${slashes}\\` : slashes));
103​
104// An unescaped "!" before the inserted "[" would turn the link into an image.
105function bangBefore(text: string, index: number): boolean {
106 if (text[index - 1] !== "!") return false;
107 let backslashes = 0;
108 while (text[index - 2 - backslashes] === "\\") backslashes += 1;
109 return backslashes % 2 === 0;
111​
112/**
113 * Pairs `<a>` tags in order. Only a closed anchor with an http(s) or mailto href becomes a
114 * Markdown link; any other anchor keeps its text unlinked.
115 */
116function anchorMarkdown(tags: readonly string[]): AnchorState {
117 const replacements = tags.map(() => "");
118 const open: Array<{ index: number; href: string | undefined }> = [];
119 tags.forEach((tag, index) => {
120 if (tag[1] !== "/") {
121 const href = attribute(tag, "href")?.trim();
122 open.push({ index, href: href && /^(?:https?|mailto):/i.test(href) ? href : undefined });
123 return;
124 }
125 const opening = open.pop();
126 if (!opening?.href) return;
127 replacements[opening.index] = "[";
128 replacements[index] = `](${markdownDestination(opening.href)})`;
129 });
130 return { pending: replacements, open: 0 };
132​
133export function markdownHtmlTags(content: string): RegExpExecArray[] {
134 // An HTML block such as <details> can also contain Markdown fences and code spans.
135 const codeRanges: Array<{ start: number; end: number }> = [];
136 const tags = [...content.matchAll(HTML_TAG)];
137 let tagIndex = 0;
138 const delimiters = [...content.matchAll(/`+|~{3,}/g)].filter((delimiter) => {
139 while (tags[tagIndex] && tags[tagIndex]!.index + tags[tagIndex]![0].length <= delimiter.index)
140 tagIndex += 1;
141 const tag = tags[tagIndex];
142 return !tag || delimiter.index < tag.index;
143 });
144 for (let index = 0; index < delimiters.length; index += 1) {
145 const opening = delimiters[index]!;
146 const lineStart = content.lastIndexOf("\n", opening.index - 1) + 1;
147 const fenced =
148 opening[0].length >= 3 && /^ {0,3}$/.test(content.slice(lineStart, opening.index));
149 if (opening[0][0] === "~" && !fenced) continue;
150 let closingIndex = -1;
151 for (let candidate = index + 1; candidate < delimiters.length; candidate += 1) {
152 const closing = delimiters[candidate]!;
153 if (!fenced && closing[0] === opening[0]) {
154 closingIndex = candidate;
155 break;
156 }
157 if (!fenced || closing[0][0] !== opening[0][0] || closing[0].length < opening[0].length)
158 continue;
159 const start = content.lastIndexOf("\n", closing.index - 1) + 1;
160 const nextLine = content.indexOf("\n", closing.index);
161 const end = nextLine === -1 ? content.length : nextLine;
162 if (
163 /^ {0,3}$/.test(content.slice(start, closing.index)) &&
164 /^\s*$/.test(content.slice(closing.index + closing[0].length, end))
165 ) {
166 closingIndex = candidate;
167 break;
168 }
169 }
170 if (closingIndex === -1) {
171 if (!fenced) continue;
172 // An unclosed fence runs to the end of the content, so no later opener matters.
173 codeRanges.push({ start: opening.index, end: content.length });
174 break;
175 }
176 const closing = delimiters[closingIndex]!;
177 codeRanges.push({ start: opening.index, end: closing.index + closing[0].length });
178 index = closingIndex;
179 }
180 return tags.filter(
181 (tag) => !codeRanges.some((range) => tag.index >= range.start && tag.index < range.end),
182 );
184​
185/**
186 * Called only for parsed HTML nodes, so Markdown code examples keep their literal tags.
187 * `anchors` is shared across sibling inline HTML nodes because each of those carries a single tag.
188 */
189export function markdownHtmlContent(
190 content: string,
191 options: { readonly anchors?: AnchorState; readonly inTableCell?: boolean } = {},
192): string {
193 const tags = markdownHtmlTags(content);
194 const anchors =
195 options.anchors ??
196 anchorMarkdown(tags.map((tag) => tag[0]).filter((tag) => ANCHOR_TAG.test(tag)));
197 let result = "";
198 let end = 0;
199 for (const match of tags) {
200 const text = content.slice(end, match.index);
201 result += anchors.open > 0 ? escapeLinkLabel(text) : text;
202 const replacement = htmlTagMarkdown(match[0], anchors, options);
203 if (replacement === "[" && bangBefore(result, result.length))
204 result = `${result.slice(0, -1)}\\!`;
205 result +=
206 anchors.open > 0 && /[\s[]/.test(result.at(-1) ?? "")
207 ? replacement.replace(/^ /, "")
208 : replacement;
209 end = match.index + match[0].length;
210 }
211 const text = content.slice(end);
212 return result + (anchors.open > 0 ? escapeLinkLabel(text) : text);
214​
215function htmlTagMarkdown(
216 tag: string,
217 anchors: AnchorState,
218 options: { readonly inTableCell?: boolean },
219): string {
220 if (tag.startsWith("<!--")) return "";
221 if (ANCHOR_TAG.test(tag)) {
222 const replacement = anchors.pending.shift() ?? "";
223 if (replacement === "[") anchors.open += 1;
224 else if (replacement) anchors.open -= 1;
225 return replacement;
226 }
227 if (/^<img\b/i.test(tag)) {
228 const src = attribute(tag, "src");
229 if (!src) return "";
230 const alt = (attribute(tag, "alt") ?? "").replace(/[\\[\]&]/g, "\\$&");
231 return `![${alt}](${markdownDestination(src)})`;
232 }
233 // A raw newline would end the table row; both parsers decode this reference to one inside the cell.
234 const cellBreak = "&#10;";
235 // A blank line inside an open link label would end the paragraph before its "]".
236 const blockBreak = anchors.open > 0 ? " " : options.inTableCell ? cellBreak : "\n\n";
237 if (/^<summary\b/i.test(tag)) return `${blockBreak}**`;
238 if (/^<\/summary\s*>/i.test(tag)) return `**${blockBreak}`;
239 if (/^<br\b/i.test(tag)) return options.inTableCell ? cellBreak : " \n";
240 if (/^<\/?(?:p|div|details)\b/i.test(tag)) return blockBreak;
241 return "";
243​
244export function markdownWithHtml(markdown: string): string {
245 if (!/<(?:!--|\/?[a-z])/i.test(markdown)) return markdown;
246 const edits: Array<{ start: number; end: number; content: string }> = [];
247 const visit = (node: MarkdownNode, inTableCell: boolean, inLink: boolean) => {
248 if (!("children" in node)) return;
249 inTableCell ||= node.type === "tableCell";
250 const children: readonly MarkdownNode[] = node.children;
251 // Inline HTML arrives one tag per node, so anchors pair across phrasing siblings.
252 const anchors =
253 node.type === "root" || node.type === "blockquote" || node.type === "listItem"
254 ? undefined
255 : anchorMarkdown(
256 children.flatMap((child) =>
257 child.type === "html"
258 ? markdownHtmlTags(child.value)
259 .map((tag) => tag[0])
260 .filter((tag) => ANCHOR_TAG.test(tag))
261 : [],
262 ),
263 );
264 for (const child of children) {
265 const start = child.position?.start.offset;
266 const end = child.position?.end.offset;
267 const linkLabel = inLink || (anchors?.open ?? 0) > 0;
268 if (child.type === "text") {
269 if (linkLabel && start !== undefined && end !== undefined) {
270 const content = escapeLinkLabel(markdown.slice(start, end));
271 if (content !== markdown.slice(start, end)) edits.push({ start, end, content });
272 }
273 continue;
274 }
275 if (child.type !== "html") {
276 visit(child, inTableCell, linkLabel);
277 continue;
278 }
279 const content = markdownHtmlContent(child.value, { anchors, inTableCell });
280 if (start === undefined || end === undefined) continue;
281 // Text before an outermost link is never edited, so this edit cannot overlap another.
282 if (content.startsWith("[") && !linkLabel && bangBefore(markdown, start))
283 edits.push({ start: start - 1, end: start, content: "\\!" });
284 edits.push({ start, end, content });
285 }
286 };
287 visit(parser.parse(markdown), false, false);
288 return applyMarkdownEdits(markdown, edits);
290​
291/** Reference definitions as authored, one line each, so a Windows destination keeps its backslashes. */
292export function markdownReferenceDefinitions(markdown: string): string[] {
293 if (!markdown.includes("]:")) return [];
294 // Flattened as the renderer does it: a raw HTML block hides the definitions inside it.
295 const flattened = markdownWithHtml(markdown);
296 const definitions: string[] = [];
297 const visit = (node: MarkdownNode, quotes: number) => {
298 if (node.type === "definition") {
299 // A wrapped definition drops its indent and the enclosing quotes' markers, not a literal ">".
300 const wrap = new RegExp(`(?:\\r\\n|\\r|\\n)(?:[ \\t]*>){0,${quotes}}[ \\t]*`, "g");
301 definitions.push(
302 flattened.slice(node.position?.start.offset, node.position?.end.offset).replace(wrap, " "),
303 );
304 }
305 if (!("children" in node)) return;
306 for (const child of node.children) visit(child, quotes + (node.type === "blockquote" ? 1 : 0));
307 };
308 visit(parser.parse(flattened), 0);
309 return definitions;
311​
312/**
313 * A reply split into folds and cards renders each fragment as its own document, so each one
314 * carries the reply's definitions. The first definition of a label wins, so the fragment's own
315 * lead: the renderer then prefers them by its own label matching, with none reimplemented here.
316 */
317export function withReferenceDefinitions(
318 fragment: string,
319 replyDefinitions: ReadonlyArray<string>,
320): string {
321 if (replyDefinitions.length === 0 || !fragment.includes("[")) return fragment;
322 const definitions = new Set([...markdownReferenceDefinitions(fragment), ...replyDefinitions]);
323 return `${[...definitions].join("\n")}\n\n${fragment}`;
325​
326// Start only at the beginning of a backtick run to avoid retrying every suffix.
327const INLINE_CODE_SPAN = /(?<!`)`+([^`\r\n]+)`+/g;
328​
329// The native regex stops at whitespace; the shared classifier decides paths with spaces.
330function isInlineCodeFileLink(code: string, fileLink: RegExp): boolean {
331 return fileLink.test(code) || (/\s/.test(code) && inlineCodeFilePathCandidate(code) !== null);
333​
334export function markdownWithInlineFileLinks(markdown: string, fileLink: RegExp): string {
335 return transformNativeMarkdown(markdown, fileLink, false);
337​
338function transformNativeMarkdown(
339 markdown: string,
340 fileLink: RegExp | undefined,
341 tableBreaks: boolean,
342): string {
343 const breakTables = tableBreaks && mayHaveTableUnderText(markdown);
344 let linkFiles = false;
345 if (fileLink) {
346 for (const [, code] of markdown.matchAll(INLINE_CODE_SPAN)) {
347 if (isInlineCodeFileLink(code!.trim(), fileLink)) {
348 linkFiles = true;
349 break;
350 }
351 }
352 }
353 const linkProseFiles = fileLink !== undefined && absoluteFilePathMatches(markdown).length > 0;
354 if (!linkFiles && !linkProseFiles && !breakTables) return markdown;
355 const edits: MarkdownEdit[] = [];
356 const fileEdits: MarkdownEdit[] = [];
357 let rewritesPipe = false;
358 const visit = (node: MarkdownNode) => {
359 if (linkFiles && node.type === "inlineCode") {
360 const start = node.position?.start.offset;
361 const end = node.position?.end.offset;
362 const escaped = node.value.replace(/[\\[\]&]/g, "\\$&");
363 if (
364 start !== undefined &&
365 end !== undefined &&
366 fileLink !== undefined &&
367 isInlineCodeFileLink(node.value, fileLink) &&
368 parseMarkdownFileLink(node.value) !== null &&
369 !/[<>]/.test(node.value)
370 ) {
371 const edit = {
372 start,
373 end,
374 content: `[${escaped}](<${escaped}>)`,
375 };
376 edits.push(edit);
377 fileEdits.push(edit);
378 if (node.value.includes("|")) rewritesPipe = true;
379 }
380 } else if (
381 linkProseFiles &&
382 node.type === "text" &&
383 node.position?.start.offset !== undefined
384 ) {
385 const start = node.position.start.offset;
386 const raw = markdown.slice(start, node.position.end.offset);
387 for (const { index, path } of absoluteFilePathMatches(raw)) {
388 // Source offsets stay valid for paths whose own text needs no Markdown decoding.
389 if (raw !== node.value && /[\\&]/.test(path)) continue;
390 const escaped = path.replace(/[\\[\]&]/g, "\\$&");
391 const edit = {
392 start: start + index,
393 end: start + index + path.length,
394 content: `[${escaped}](<${escaped}>)`,
395 };
396 edits.push(edit);
397 fileEdits.push(edit);
398 }
399 } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node)
400 node.children.forEach((child, index) => {
401 const previous = node.children[index - 1];
402 const start = child.position?.start;
403 if (
404 breakTables &&
405 child.type === "table" &&
406 previous?.type === "paragraph" &&
407 start?.offset !== undefined &&
408 previous.position?.end.line === start.line - 1
409 ) {
410 let lineStart = start.offset;
411 while (lineStart > 0 && !/[\r\n]/.test(markdown[lineStart - 1]!)) lineStart -= 1;
412 // Replace only the container prefix, leaving cell edits disjoint from the table break.
413 const [, header = "", , ending = "\n", markers = ""] =
414 /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
415 edits.push({
416 start: lineStart,
417 end: lineStart + header.length,
418 content: `${markers.trimEnd()}${ending}${markers}`,
419 });
420 }
421 visit(child);
422 });
423 };
424 visit(parser.parse(markdown));
425 // Rewritten pipes can change table structure, so preserve the original pass ordering.
426 if (breakTables && rewritesPipe)
427 return markdownWithTableBreaks(applyMarkdownEdits(markdown, fileEdits));
428 return applyMarkdownEdits(markdown, edits);
430​
431// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
432function isTableDelimiterRow(line: string): boolean {
433 if (!line.includes("-")) return false;
434 const row = line.replace(/^[ \t>]+/, "").trim();
435 return row
436 .replace(/^\||\|$/g, "")
437 .split("|")
438 .every((cell) => /^:?-+:?$/.test(cell.trim()));
440​
441function mayHaveTableUnderText(markdown: string): boolean {
442 if (!markdown.includes("|")) return false;
443 const lines = markdown.split(/\r\n|\r|\n/);
444 for (let index = 2; index < lines.length; index += 1) {
445 if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
446 }
447 return false;
449​
450/** md4c starts tables only at paragraph starts; insert breaks to match GFM. */
451export function markdownWithTableBreaks(markdown: string): string {
452 return transformNativeMarkdown(markdown, undefined, true);
454​
455// `>` covers a destination continued on a blockquote line.
456const WINDOWS_DESTINATION = /\](?:\(|:)[\s>]*<?(?:[A-Za-z]:[\\/]|\\\\)/;
457​
458interface DestinationToken {
459 readonly start: { readonly offset: number };
460 readonly end: { readonly offset: number };
462​
463/**
464 * Markdown reads `C:\work\.t3` as `C:\work.t3`. Web keeps authored Windows destinations
465 * literally (see `remarkKeepWindowsPaths` in shared), so escape their backslashes to give
466 * both parsers here the same path. `\&` stays an escape, as `markdownWithHtml` emits it.
467 * Expects authored Markdown: already escaped output would be escaped twice.
468 */
469function markdownWithWindowsPathDestinations(markdown: string): string {
470 // Skips the extra parse for the common message that has no Windows destination.
471 if (!WINDOWS_DESTINATION.test(markdown)) return markdown;
472 const edits: MarkdownEdit[] = [];
473 function record(
474 this: { resume(): string; sliceSerialize(token: DestinationToken): string },
475 token: DestinationToken,
476 ) {
477 this.resume();
478 const authored = this.sliceSerialize(token);
479 if (!isWindowsAbsolutePath(authored) || !authored.includes("\\") || /[<>]/.test(authored))
480 return;
481 const start = token.start.offset;
482 const end = token.end.offset;
483 const escaped = authored.replace(/\\(?!&)/g, "\\\\");
484 // A bare destination ends at an unescaped `)`, so wrap it to keep `\)` inside.
485 const angled = markdown[start - 1] === "<";
486 edits.push({ start, end, content: angled ? escaped : `<${escaped}>` });
487 }
488 unified()
489 .use(remarkParse)
490 .use(remarkGfm)
491 .use(function (this: Processor) {
492 (this.data().fromMarkdownExtensions ??= []).push({
493 exit: { resourceDestinationString: record, definitionDestinationString: record },
494 });
495 })
496 .parse(markdown);
497 return applyMarkdownEdits(markdown, edits);
499​
500// HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first.
501export function markdownForNativeParsing(markdown: string): string {
502 return markdownWithWindowsPathDestinations(markdownWithHtml(markdown));
504​
505export function parseMarkdownDocument(markdown: string): Root {
506 return parser.parse(markdownForNativeParsing(markdown));
508​
509export function markdownForNativeRendering(markdown: string, fileLink: RegExp): string {
510 return transformNativeMarkdown(markdownForNativeParsing(markdown), fileLink, true);
512​
513/** Native media slots only cover standalone images; nested file embeds must become links. */
514export function markdownWithFileEmbeds(
515 markdown: string,
516 label: (href: string, standalone: boolean) => string | null,
517): { markdown: string; fileHrefs: ReadonlySet<string> } {
518 const fileHrefs = new Set<string>();
519 if (!markdown.includes("![")) return { markdown, fileHrefs };
520 const root = parser.parse(markdown);
521 const topLevelBlocks = new Set<MarkdownNode>(root.children);
522 const definitions = new Map<string, string>();
523 const collect = (node: MarkdownNode) => {
524 if (node.type === "definition") {
525 const identifier = node.identifier.toUpperCase();
526 if (!definitions.has(identifier)) definitions.set(identifier, node.url);
527 }
528 if ("children" in node) node.children.forEach(collect);
529 };
530 collect(root);
531 const edits: Array<{ start: number; end: number; content: string }> = [];
532 const visit = (node: MarkdownNode, standalone = false, insideLink = false) => {
533 if (node.type === "image" || node.type === "imageReference") {
534 const href =
535 node.type === "image" ? node.url : definitions.get(node.identifier.toUpperCase());
536 const name = href === undefined ? null : label(href, standalone);
537 const start = node.position?.start.offset;
538 const end = node.position?.end.offset;
539 if (href !== undefined && name !== null && start !== undefined && end !== undefined) {
540 const text = name.replace(/[\\[\]`*_~|&<>]/g, "\\$&");
541 const url = href.replace(/[\\&]/g, "\\$&").replace(/</g, "%3C").replace(/>/g, "%3E");
542 edits.push({ start, end, content: insideLink ? text : `[${text}](<${url}>)` });
543 fileHrefs.add(href);
544 }
545 }
546 if ("children" in node)
547 node.children.forEach((child) =>
548 visit(
549 child,
550 node.type === "paragraph" && node.children.length === 1 && topLevelBlocks.has(node),
551 insideLink || node.type === "link" || node.type === "linkReference",
552 ),
553 );
554 };
555 visit(root);
556 const parts: string[] = [];
557 let offset = 0;
558 for (const edit of edits) {
559 parts.push(markdown.slice(offset, edit.start), edit.content);
560 offset = edit.end;
561 }
562 parts.push(markdown.slice(offset));
563 return { markdown: parts.join(""), fileHrefs };