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