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