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

wordsHast.ts

1,342 lines51.5 KB

1import type { Element, ElementContent, Root, Text } from "hast";
2import {
3 init as initWords,
4 renderToHtml as wordsRenderToHtml,
5 type RenderOptions as WordsRenderOptions,
6} from "@pierre/words/core";
7import wordsWasm from "@pierre/words/wasm";
8import { decodeHTML, decodeHTMLAttribute } from "entities";
9import { find, html as htmlSchema, svg as svgSchema } from "property-information";
10import { resolveCodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
11import { resolveCodexFileCitationLink } from "@t3tools/shared/codexFileCitations";
12import type { ReferenceAutolink } from "@t3tools/client-runtime/source-control-clients";
13import { expandGithubEmojiAliases } from "@t3tools/client-runtime/pull-request-markdown";
14import { resolveChangeRequestMediaUrl } from "@t3tools/client-runtime/pull-request-references";
15import { GITHUB_ALERT_MARKER } from "@t3tools/shared/markdownGithubAlerts";
16import { absoluteFilePathMatches } from "@t3tools/shared/markdownLinks";
17import {
18 rehypeNormalizeLocalEditorLinks,
19 rehypePreserveImageSourceMeta,
20 sanitizeChatHast,
21} from "@t3tools/shared/markdownHast";
22​
23import { rehypeChipPunctuation } from "../components/chat/markdownChipPunctuation";
24import { rehypeHeadingIds } from "../components/chat/markdownFragments";
25import { rehypeTextDirection } from "../components/chat/markdownTextDirection";
26​
27/** What a kind of message adds to chat Markdown. Pass a stable object: renderers cache by it. */
28export interface MarkdownExtensions {
29 /**
30 * A sent user message: a single `~` stays text, and a written list number that breaks the
31 * sequence stays, so the bubble shows what the composer showed.
32 */
33 readonly userMessage?: boolean;
34 /** Spaces typed at the start of a line show, as the composer showed them (keepLeadingWhitespace). */
35 readonly leadingWhitespace?: boolean;
36 /** A saved file's Markdown, which must not load URLs or act: links, images and HTML are text. */
37 readonly inert?: boolean;
38 /** The whole message flattened to one line of text and math, or `fallback` when empty. */
39 readonly preview?: { readonly fallback: string; readonly maxLength: number };
40 /** A change request's body: root-relative media resolve on its host, and references link. */
41 readonly changeRequest?: {
42 readonly repositoryUrl: string;
43 readonly autolinks: ((text: string) => ReadonlyArray<ReferenceAutolink>) | null;
44 };
45 /** Expand GitHub `:alias:` emoji shortcodes in prose outside code. */
46 readonly githubEmoji?: boolean;
48​
49export interface WordsHastOptions {
50 /** `$…$`, `$$…$$` and `math` code blocks render as SVG. */
51 readonly math: boolean;
52 /** Soft line breaks render as `<br>`, as remark-breaks does. */
53 readonly breaks: boolean;
54 /** Raw HTML shows as the text it was written as. */
55 readonly escapeHtml: boolean;
56 /** `★ Insight ───` blocks render as insight callouts. */
57 readonly insights: boolean;
58 readonly extensions: MarkdownExtensions;
60​
61const CODEX_DIRECTIVES = ["codex-file-citation", "codex-followup", "artifact-template"];
62​
63const VOID = new Set("area base br col embed hr img input link meta source track wbr".split(" "));
64​
65const TAG =
66 /<(\/?)([a-zA-Z][\w:-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|<!--(?:-?>|[\s\S]*?-->)|<![^>]*>|<\?[\s\S]*?\?>/g;
67const ATTRIBUTE = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
68​
69// Start tags an HTML parser closes an open `<p>` for, and the elements that scope that search.
70const CLOSES_PARAGRAPH = new Set(
71 "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(
72 " ",
73 ),
74);
75const PARAGRAPH_SCOPE = new Set([
76 "applet",
77 "caption",
78 "table",
79 "td",
80 "th",
81 "marquee",
82 "object",
83 "template",
84 "button",
85]);
86​
87type RenderOptions = Omit<WordsRenderOptions, "frontmatter">;
88​
89const decoder = new TextDecoder();
90const encoder = new TextEncoder();
91​
92// Browsers can disable WebAssembly (JIT off by policy, CSP); renderToHtml then falls back below.
93try {
94 initWords(new WebAssembly.Module(wordsWasm));
95} catch {}
96​
97function renderToHtml(markdown: string, options: RenderOptions): Uint8Array {
98 try {
99 return wordsRenderToHtml(markdown, options);
100 } catch {
101 return encoder.encode(
102 `<p>${markdown.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll("\n", "<br>")}</p>`,
103 );
104 }
106​
107const decode = (value: string) => (value.includes("&") ? decodeHTML(value) : value);
108​
109function properties(source: string | undefined, inSvg: boolean): Element["properties"] {
110 const result: Element["properties"] = {};
111 if (!source) return result;
112 for (const match of source.matchAll(ATTRIBUTE)) {
113 const name = match[1]!;
114 const info = find(inSvg ? svgSchema : htmlSchema, inSvg ? name : name.toLowerCase());
115 const raw = match[2] ?? match[3] ?? match[4];
116 if (raw === undefined) {
117 result[info.property] = info.boolean || info.overloadedBoolean ? true : "";
118 continue;
119 }
120 // Attribute values decode as attributes: `&copy=` in a query stays as written.
121 const value = raw.includes("&") ? decodeHTMLAttribute(raw) : raw;
122 result[info.property] =
123 info.spaceSeparated || info.commaSeparated
124 ? value.split(info.commaSeparated ? "," : /\s+/).filter(Boolean)
125 : info.boolean
126 ? true
127 : value;
128 }
129 return result;
131​
132interface Tokenized {
133 readonly root: Root;
134 /** Elements with a `data-sourcepos`, which raw HTML can write too. */
135 readonly positioned: Element[];
137​
138/**
139 * Hast for Words' HTML. Its own markup is well formed; raw HTML closes where its end tags say,
140 * and is sanitized afterwards, so a misnested tag can only change structure, never safety.
141 */
142function tokenize(html: string, offsetOf: (byte: number) => number): Tokenized {
143 const root: Root = { type: "root", children: [] };
144 const positioned: Element[] = [];
145 const stack: Array<Root | Element> = [root];
146 let svgDepth = 0;
147 let last = 0;
148 // rehypePreserveBareAnchorPlaceholders: an `<a>` with no attributes that never closes is text.
149 const anchors: Array<{ element: Element; parent: Root | Element; tag: string } | null> = [];
150 const text = (end: number) => {
151 if (end <= last) return;
152 const parent = stack.at(-1)!;
153 const value = decode(html.slice(last, end));
154 const previous = parent.children.at(-1);
155 if (previous?.type === "text") previous.value += value;
156 else parent.children.push({ type: "text", value } as Text);
157 };
158 for (const match of html.matchAll(TAG)) {
159 text(match.index);
160 last = match.index + match[0].length;
161 const tagName = match[2]?.toLowerCase();
162 if (!tagName) continue;
163 if (match[1]) {
164 if (tagName === "a") anchors.pop();
165 if (tagName === "p" && openParagraph(stack) < 0) {
166 // A stray `</p>` is an empty paragraph to an HTML parser.
167 (stack.at(-1)!.children as ElementContent[]).push({
168 type: "element",
169 tagName: "p",
170 properties: {},
171 children: [],
172 });
173 continue;
174 }
175 const at = stack.findLastIndex((node) => node.type === "element" && node.tagName === tagName);
176 if (at > 0) {
177 for (let index = at; index < stack.length; index++) {
178 if ((stack[index] as Element).tagName === "svg") svgDepth--;
179 }
180 stack.length = at;
181 }
182 continue;
183 }
184 const inSvg = svgDepth > 0 || tagName === "svg";
185 if (!inSvg && CLOSES_PARAGRAPH.has(tagName)) {
186 const paragraph = openParagraph(stack);
187 if (paragraph > 0) stack.length = paragraph;
188 }
189 const element: Element = {
190 type: "element",
191 tagName: inSvg ? match[2]! : tagName,
192 properties: properties(match[3], inSvg),
193 children: [],
194 };
195 const sourcepos = element.properties.dataSourcepos;
196 if (typeof sourcepos === "string") {
197 delete element.properties.dataSourcepos;
198 const [start, end] = sourcepos.split("-").map((byte) => offsetOf(Number(byte)));
199 element.position = {
200 start: { line: 1, column: start! + 1, offset: start! },
201 end: { line: 1, column: end! + 1, offset: end! },
202 };
203 positioned.push(element);
204 }
205 const parent = stack.at(-1)!;
206 (parent.children as ElementContent[]).push(element);
207 if (tagName === "a") {
208 anchors.push(match[3]?.trim() ? null : { element, parent, tag: match[0] });
209 }
210 // The HTML parser ignores `/>` on elements that are not void, such as `<a/>`.
211 if (!VOID.has(tagName) && (!match[4] || !inSvg)) {
212 stack.push(element);
213 if (tagName === "svg") svgDepth++;
214 }
215 }
216 text(html.length);
217 for (const anchor of anchors) {
218 if (!anchor) continue;
219 const siblings = anchor.parent.children as ElementContent[];
220 const at = siblings.indexOf(anchor.element);
221 if (at >= 0)
222 siblings.splice(at, 1, { type: "text", value: anchor.tag }, ...anchor.element.children);
223 }
224 normalizeRawTables(root);
225 // Words ends each block with a newline; hast from remark has none after the last.
226 const end = root.children.at(-1);
227 if (end?.type === "text") {
228 end.value = end.value.replace(/\n$/, "");
229 if (end.value.trim() === "") root.children.pop();
230 }
231 return { root, positioned };
233​
234const positionKey = (node: Element) =>
235 `${node.tagName.toLowerCase()}:${node.position!.start.offset}-${node.position!.end.offset}`;
236​
237/**
238 * Words' HTML for `markdown` as hast. A position marks what Words generated, so raw HTML that
239 * writes its own `data-sourcepos` keeps none: Words' elements are those it also writes with raw
240 * HTML escaped, and a range claimed more often than that is trusted for none of its claimants.
241 */
242function parse(markdown: string, options: RenderOptions): Root {
243 const offsetOf = utf16Offsets(markdown);
244 const render = (escapeHtml?: true) =>
245 tokenize(
246 decoder.decode(
247 renderToHtml(markdown, {
248 ...options,
249 ...(escapeHtml ? { escapeHtml } : {}),
250 sourcePositions: true,
251 }),
252 ),
253 offsetOf,
254 );
255 const { root, positioned } = render();
256 if (options.escapeHtml || options.skipHtml || !/data-sourcepos/i.test(markdown)) return root;
257 const generated = new Map<string, number>();
258 for (const node of render(true).positioned) {
259 const key = positionKey(node);
260 generated.set(key, (generated.get(key) ?? 0) + 1);
261 }
262 const claimed = new Map<string, number>();
263 for (const node of positioned) {
264 const key = positionKey(node);
265 claimed.set(key, (claimed.get(key) ?? 0) + 1);
266 }
267 for (const node of positioned) {
268 const key = positionKey(node);
269 if (claimed.get(key)! > (generated.get(key) ?? 0)) delete node.position;
270 }
271 return root;
273​
274/** The stack index of the `<p>` an HTML parser would close, or -1 when none is in scope. */
275function openParagraph(stack: ReadonlyArray<Root | Element>): number {
276 for (let index = stack.length - 1; index > 0; index--) {
277 const tagName = (stack[index] as Element).tagName;
278 if (tagName === "p") return index;
279 if (PARAGRAPH_SCOPE.has(tagName)) return -1;
280 }
281 return -1;
283​
284/** parse5 puts a raw HTML table's rows in a `<tbody>`; Words' own tables start with `<thead>`. */
285function normalizeRawTables(node: Root | Element) {
286 for (const child of node.children) {
287 if (child.type === "element") normalizeRawTables(child);
288 }
289 if (node.type !== "element" || node.tagName !== "table") return;
290 const first = node.children.findIndex((child) => isElement(child, "tr"));
291 if (first < 0) return;
292 node.children = [
293 ...node.children.slice(0, first),
294 { type: "element", tagName: "tbody", properties: {}, children: node.children.slice(first) },
295 ];
297​
298// Words leaves these raw in Markdown destinations, where micromark percent-encodes them.
299const UNSAFE_URL_CHARACTERS = /[\\[\]`{}|^"<> ]/g;
300const normalizeUri = (value: string) =>
301 value.replace(UNSAFE_URL_CHARACTERS, (character) => encodeURIComponent(character));
302​
303const windowsPath = (url: string) => {
304 const path = url.replace(/%5C/gi, "\\");
305 return /^[A-Za-z]:[\\/]/.test(path) ? path : undefined;
306};
307​
308const isElement = (node: unknown, tagName?: string): node is Element =>
309 (node as Element | undefined)?.type === "element" &&
310 (tagName === undefined || (node as Element).tagName === tagName);
311​
312const isElementNode = (node: ElementContent): node is Element => node.type === "element";
313​
314const isMarkdownImage = (node: unknown): boolean =>
315 (isElement(node, "img") && node.position !== undefined) ||
316 (isElement(node, "a") &&
317 node.position !== undefined &&
318 node.children.length === 1 &&
319 isMarkdownImage(node.children[0]));
320​
321const BREAK: ElementContent = { type: "element", tagName: "br", properties: {}, children: [] };
322​
323// Words' math: these elements and presentation attributes, and no links or handlers.
324const MATH_ELEMENTS = new Set(["svg", "g", "text", "tspan", "rect", "path"]);
325const MATH_PROPERTIES = new Set([
326 "xmlns",
327 "width",
328 "height",
329 "viewBox",
330 "fill",
331 "fontFamily",
332 "fontSize",
333 "fontStyle",
334 "fontWeight",
335 "role",
336 "ariaLabel",
337 "x",
338 "y",
339 "dx",
340 "dy",
341 "d",
342 "transform",
343 "stroke",
344 "strokeWidth",
345 "textAnchor",
346]);
347const MATH_STYLE = /^(?:display|vertical-align|overflow|margin|white-space)$/;
348​
349function sanitizeMath(node: Element): Element | null {
350 if (!MATH_ELEMENTS.has(node.tagName)) return null;
351 const properties: Element["properties"] = {};
352 for (const [key, value] of Object.entries(node.properties)) {
353 if (MATH_PROPERTIES.has(key)) properties[key] = value;
354 }
355 if (typeof node.properties.style === "string") {
356 const style = node.properties.style
357 .split(";")
358 .filter((rule) => MATH_STYLE.test(rule.split(":")[0]!.trim()))
359 .join(";");
360 if (style) properties.style = style;
361 }
362 const children: ElementContent[] = [];
363 for (const child of node.children) {
364 if (child.type === "text") children.push(child);
365 else if (child.type === "element") {
366 const clean = sanitizeMath(child);
367 if (clean) children.push(clean);
368 }
369 }
370 return { ...node, properties, children };
372​
373interface Walk {
374 /** Words' hast for more Markdown, rendered with the same options; `indent` as leadingWhitespace's. */
375 readonly render: (markdown: string, indent: number) => Root;
376 readonly source: string;
377 readonly options: WordsHastOptions;
378 readonly math: Map<string, Element>;
379 /** A per-render id prefix for math placeholders, which authored ids cannot share. */
380 readonly mathKey: string;
381 /** What insightSource opened each insight block with, when it opened any. */
382 readonly insightMarker: RegExp | null;
384​
385/** UTF-16 offsets for the UTF-8 byte offsets in Words' `data-sourcepos`. */
386function utf16Offsets(source: string): (byte: number) => number {
387 if (!/[^\x00-\x7f]/.test(source)) return (byte) => byte;
388 const offsets: number[] = [];
389 for (let index = 0; index < source.length; index++) {
390 const code = source.codePointAt(index)!;
391 const bytes = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4;
392 for (let byte = 0; byte < bytes; byte++) offsets.push(index);
393 if (code >= 0x10000) index++;
394 }
395 offsets.push(source.length);
396 return (byte) => offsets[byte] ?? source.length;
398​
399const sourceOf = (node: Element, source: string) =>
400 node.position ? source.slice(node.position.start.offset, node.position.end.offset) : "";
401​
402const textOf = (node: ElementContent): string =>
403 node.type === "text"
404 ? node.value
405 : node.type === "element"
406 ? node.children.map(textOf).join("")
407 : "";
408​
409/** A directive's attributes, as strings; anything else Words would never write reads as none. */
410function directiveAttributes(node: Element): Record<string, string> {
411 let parsed: unknown;
412 try {
413 parsed = JSON.parse(String(node.properties.dataAttributes ?? "{}"));
414 } catch {
415 return {};
416 }
417 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};
418 return Object.fromEntries(
419 Object.entries(parsed).filter(
420 (entry): entry is [string, string] => typeof entry[1] === "string",
421 ),
422 );
424​
425/** remarkCodexDirectives: what a directive Words parsed becomes, as the remark plugin builds it. */
426function codexDirective(node: Element, walk: Walk, inLink: boolean): ElementContent {
427 const name = node.properties.dataDirective;
428 const attributes = directiveAttributes(node);
429 const asText = (): ElementContent => {
430 const value: ElementContent = { type: "text", value: sourceOf(node, walk.source) };
431 return node.tagName === "div"
432 ? { type: "element", tagName: "p", properties: {}, children: [value] }
433 : value;
434 };
435 if (name === "codex-file-citation") {
436 const citation = resolveCodexFileCitationLink(attributes);
437 if (!citation || inLink) return asText();
438 return {
439 type: "element",
440 tagName: "a",
441 properties: { href: citation.href },
442 children: [{ type: "text", value: citation.label }],
443 ...(node.position ? { position: node.position } : {}),
444 };
445 }
446 if (name === "codex-followup") {
447 if (!attributes.prompt?.trim() || !node.children.map(textOf).join("").trim()) return asText();
448 return { type: "element", tagName: "span", properties: {}, children: node.children };
449 }
450 const template = resolveCodexArtifactTemplate(attributes);
451 if (!template) return asText();
452 return {
453 type: "element",
454 tagName: "div",
455 properties: {
456 dataCodexArtifactTemplate: "true",
457 dataArtifactKind: template.artifactKind,
458 dataDisplayName: template.displayName,
459 ...(template.galleryKind === undefined ? {} : { dataGalleryKind: template.galleryKind }),
460 dataSkillDirectory: template.skillDirectory,
461 dataSkillName: template.skillName,
462 },
463 children: [],
464 };
466​
467const INLINE_PREFIX = "t3-markdown-inline-prefix:";
468​
469function stripPositions(node: ElementContent) {
470 delete node.position;
471 if (node.type === "element") node.children.forEach(stripPositions);
473​
474/**
475 * remarkNormalizeListItemIndentation: four spaces after a list marker make indented code, but
476 * agents mean wide indentation, so code starting on the marker's line is Markdown again. True
477 * when it recovered the item, whose children it then has transformed.
478 */
479function recoverIndentedCode(
480 item: Element,
481 list: Root | Element,
482 walk: Walk,
483 inLink: boolean,
484 inCode: boolean,
485): boolean {
486 const code = item.children.find((child) => child.type === "element");
487 const start = code?.position?.start.offset;
488 const itemStart = item.position?.start.offset;
489 if (!isElement(code, "pre") || start === undefined || itemStart === undefined) return false;
490 const value = textOf(code);
491 if (!/^[\t ]/.test(value)) return false;
492 if (walk.source.slice(itemStart, start).includes("\n") || /[`~]/.test(walk.source[start]!)) {
493 return false;
494 }
495 // The trimmed first line sets where the item's content starts.
496 const indent = [.../^[\t ]*/.exec(value)![0]].reduce(
497 (column, character) => (character === "\t" ? (Math.floor(column / 4) + 1) * 4 : column + 1),
498 0,
499 );
500 // The prefix keeps block syntax at the start, such as `#`, from opening a block.
501 const source = `${INLINE_PREFIX}${value.trim()}`;
502 const recovered = walk.render(source, indent);
503 const paragraph = recovered.children.find((child) => child.type === "element");
504 const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
505 if (first?.type !== "text" || !first.value.startsWith(INLINE_PREFIX)) return false;
506 first.value = first.value.slice(INLINE_PREFIX.length);
507 if (first.value === "") paragraph!.children.shift();
508 transform(recovered, { ...walk, source }, inLink, inCode);
509 transform(item, walk, inLink, inCode);
510 let blocks = recovered.children.filter(
511 (child) => !(child.type === "text" && child.value.trim() === ""),
512 ) as ElementContent[];
513 // Their positions point into `source`, not the message.
514 blocks.forEach(stripPositions);
515 let at = item.children.indexOf(code);
516 let remove = 1;
517 if (!isLooseList(list, walk.source)) {
518 // A tight item shows its text bare, as remark-rehype unwraps its paragraphs.
519 blocks = blocks.flatMap((block, index) => [
520 ...(index > 0 ? [{ type: "text", value: "\n" } as Text] : []),
521 ...(isElement(block, "p") ? block.children : [block]),
522 ]);
523 const isBlank = (node: ElementContent | undefined) =>
524 node?.type === "text" && node.value.trim() === "";
525 if (at === 1 && isBlank(item.children[0])) [at, remove] = [0, 2];
526 if (at + remove === item.children.length - 1 && isBlank(item.children.at(-1))) remove++;
527 }
528 item.children.splice(at, remove, ...blocks);
529 return true;
531​
532/** remark-rehype's listLoose: a blank line between items, or an item Words wrote as paragraphs. */
533function isLooseList(list: Root | Element, source: string): boolean {
534 const items = (list.children as ElementContent[]).filter((child): child is Element =>
535 isElement(child, "li"),
536 );
537 return items.some(
538 (item, index) =>
539 item.children.some((child) => isElement(child, "p")) ||
540 (index > 0 &&
541 /\n[ \t>]*\n/.test(
542 source.slice(
543 items[index - 1]!.position?.end.offset ?? 0,
544 item.position?.start.offset ?? 0,
545 ),
546 )),
547 );
549​
550const WRITTEN_NUMBER = /[ \t]*(\d{1,9})[.)]/y;
551​
552function keepListNumbers(list: Element, source: string) {
553 let expected = Number(list.properties.start ?? 1);
554 for (const item of list.children) {
555 if (!isElement(item, "li")) continue;
556 const offset = item.position?.start.offset;
557 WRITTEN_NUMBER.lastIndex = offset ?? 0;
558 const digits = offset === undefined ? undefined : WRITTEN_NUMBER.exec(source)?.[1];
559 const value = digits === undefined ? expected : Number(digits);
560 if (value !== expected) item.properties.value = String(value);
561 expected = value + 1;
562 }
564​
565/** What the chat's remark plugins add that Words does not. */
566const link = (href: string, label: string, properties: Element["properties"] = {}): Element => ({
567 type: "element",
568 tagName: "a",
569 properties: { href, ...properties },
570 children: [{ type: "text", value: label }],
571});
572​
573/** Links in text: absolute file paths (remarkLinkAbsoluteFilePaths), then a change request's references. */
574function linkText(value: string, walk: Walk): ElementContent[] | null {
575 let parts: ElementContent[] = [];
576 let offset = 0;
577 for (const { index, path } of absoluteFilePathMatches(value)) {
578 if (index > offset) parts.push({ type: "text", value: value.slice(offset, index) });
579 parts.push(link(path, path));
580 offset = index + path.length;
581 }
582 if (offset < value.length) parts.push({ type: "text", value: value.slice(offset) });
583 const autolinks = walk.options.extensions.changeRequest?.autolinks;
584 if (autolinks) {
585 parts = parts.flatMap((part) => {
586 if (part.type !== "text") return [part];
587 const found = autolinks(part.value);
588 if (found.length === 0) return [part];
589 const linked: ElementContent[] = [];
590 let start = 0;
591 for (const reference of found) {
592 if (start < reference.index) {
593 linked.push({ type: "text", value: part.value.slice(start, reference.index) });
594 }
595 linked.push(
596 link(reference.url, reference.label, { dataPullRequestAutolink: reference.kind }),
597 );
598 start = reference.index + reference.text.length;
599 }
600 if (start < part.value.length) linked.push({ type: "text", value: part.value.slice(start) });
601 return linked;
602 });
603 }
604 return parts.length === 1 && parts[0]!.type === "text" ? null : parts;
606​
607function transform(node: Root | Element, walk: Walk, inLink: boolean, inCode: boolean) {
608 const children = node.children as ElementContent[];
609 for (let index = 0; index < children.length; index++) {
610 const child = children[index]!;
611 if (child.type === "text") {
612 if (inCode) continue;
613 if (walk.options.extensions.githubEmoji && child.value.includes(":")) {
614 child.value = expandGithubEmojiAliases(child.value);
615 }
616 if (inLink) continue;
617 const parts = linkText(child.value, walk);
618 if (!parts) continue;
619 children.splice(index, 1, ...parts);
620 index += parts.length - 1;
621 continue;
622 }
623 if (child.type !== "element") continue;
624 // Words gives what it generates a source position; raw HTML that copies its attributes has none.
625 if (child.properties.dataDirective !== undefined && child.position) {
626 children[index] = codexDirective(child, walk, inLink);
627 index--;
628 continue;
629 }
630 const { tagName, properties: props } = child;
631 if (tagName === "svg") {
632 // Sanitizing drops SVG, so math waits under a placeholder until after it.
633 const clean = walk.options.math && child.position ? sanitizeMath(child) : null;
634 if (clean) {
635 const key = `${walk.mathKey}-${walk.math.size}`;
636 walk.math.set(key, clean);
637 children[index] = {
638 type: "element",
639 tagName: "span",
640 properties: { id: key },
641 children: [],
642 };
643 }
644 continue;
645 }
646 if (tagName === "a" && props.dataFootnoteRef !== undefined) {
647 // remark-rehype's footnote markup, before rehype-sanitize prefixes ids again.
648 props.href = `#user-content-${String(props.href).slice(1)}`;
649 props.id = `user-content-${String(props.id)}`;
650 props.ariaDescribedBy = ["footnote-label"];
651 } else if (tagName === "a" && props.dataFootnoteBackref !== undefined) {
652 const { href, ariaLabel } = props;
653 child.properties = {
654 href: `#user-content-${String(href).slice(1)}`,
655 dataFootnoteBackref: "",
656 ariaLabel,
657 className: ["data-footnote-backref"],
658 };
659 } else if (tagName === "li" && typeof props.id === "string" && props.id.startsWith("fn-")) {
660 props.id = `user-content-${props.id}`;
661 } else if (tagName === "section" && props.dataFootnotes !== undefined) {
662 child.properties = { dataFootnotes: "", className: ["footnotes"] };
663 child.children.unshift({
664 type: "element",
665 tagName: "h2",
666 properties: { className: ["sr-only"], id: "footnote-label" },
667 children: [{ type: "text", value: "Footnotes" }],
668 });
669 } else if (tagName === "a" && typeof props.href === "string") {
670 // remarkNormalizeLinksAndTagInlineCode: a Windows drive path links as a file URL.
671 const path = windowsPath(props.href);
672 props.href = path ? `file:///${path.replaceAll("\\", "/")}` : normalizeUri(props.href);
673 } else if (tagName === "img" && typeof props.src === "string") {
674 const changeRequest = walk.options.extensions.changeRequest;
675 const src = changeRequest
676 ? resolveChangeRequestMediaUrl(props.src, changeRequest.repositoryUrl)
677 : props.src;
678 props.src = windowsPath(src) ?? normalizeUri(src);
679 } else if (tagName === "code" && isElement(node, "pre")) {
680 if (props.dataMeta !== undefined) {
681 props.dataCodeMeta = props.dataMeta;
682 delete props.dataMeta;
683 }
684 } else if (tagName === "code" && !inLink) {
685 props.dataInlineCode = "";
686 } else if (tagName === "ol" && walk.options.extensions.userMessage) {
687 keepListNumbers(child, walk.source);
688 } else if (tagName === "li") {
689 const firstBlock = child.children.find(isElementNode);
690 if (isElement(firstBlock, "pre") && recoverIndentedCode(child, node, walk, inLink, inCode)) {
691 continue;
692 }
693 // Tight items put the checkbox directly in `<li>`, loose ones inside its first `<p>`.
694 const checkbox = isElement(child.children[0], "input")
695 ? child.children[0]
696 : isElement(firstBlock, "p") && isElement(firstBlock.children[0], "input")
697 ? firstBlock.children[0]
698 : undefined;
699 if (checkbox) {
700 props.className = ["task-list-item"];
701 const { checked } = checkbox.properties;
702 checkbox.properties = { type: "checkbox", checked, disabled: true };
703 if (node.type === "element") node.properties.className = ["contains-task-list"];
704 }
705 if (child.position) breakLines(child, walk.options.breaks);
706 } else if (tagName === "p" && Object.keys(child.properties).length === 0) {
707 // Words writes a Markdown paragraph bare; one with attributes is raw HTML, which keeps its
708 // lines as written, as remark-breaks never touched raw HTML.
709 breakLines(child, walk.options.breaks);
710 } else if (tagName === "blockquote") {
711 // remarkGithubAlerts
712 const paragraph = child.children.find((item) => item.type === "element");
713 const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
714 const text = first?.type === "text" ? first.value : "";
715 const insight = walk.insightMarker?.exec(text);
716 const alert = GITHUB_ALERT_MARKER.exec(text);
717 // An alert marker followed by more inline content on its line is text, as remarkGithubAlerts reads it.
718 const match = insight
719 ? ([insight[0], "insight"] as const)
720 : alert && (alert[0].endsWith("\n") || (paragraph as Element).children.length === 1)
721 ? alert
722 : null;
723 if (match && first?.type === "text" && isElement(paragraph, "p")) {
724 first.value = first.value.slice(match[0].length);
725 if (first.value === "") paragraph.children.shift();
726 if (paragraph.children.length === 0) {
727 const at = child.children.indexOf(paragraph);
728 const next = child.children[at + 1];
729 // The line ending after it goes too, as remark leaves none for a removed paragraph.
730 const blank = next?.type === "text" && next.value.trim() === "" ? 2 : 1;
731 child.children.splice(at, blank);
732 }
733 props.dataAlert = match[1]!.toLowerCase();
734 }
735 }
736 transform(
737 child,
738 walk,
739 inLink || tagName === "a",
740 inCode || tagName === "code" || tagName === "pre",
741 );
742 }
744​
745/**
746 * remark-breaks puts a `<br>` before every soft line ending, and remarkBreakAroundImageLines
747 * before those next to a Markdown image. Both keep the line ending after it.
748 */
749/** A Markdown image alone on its line: nothing but a line ending (or the paragraph's edge) around it. */
750function imageOwnsLine(items: ElementContent[], at: number): boolean {
751 if (!isMarkdownImage(items[at])) return false;
752 const before = items[at - 1];
753 const after = items[at + 1];
754 const startsLine =
755 before === undefined ||
756 (before.type === "text" && /\n[ \t]*$/.test(before.value)) ||
757 isElement(before, "br");
758 const endsLine = after === undefined || (after.type === "text" && /^[ \t]*\n/.test(after.value));
759 return startsLine && endsLine;
761​
762const isBlockElement = (node: ElementContent | undefined) =>
763 node?.type === "element" && CLOSES_PARAGRAPH.has(node.tagName);
764​
765/** Where the images that end a paragraph after its text start: a caption, then its screenshots. */
766function trailingImagesStart(items: ElementContent[]): number | undefined {
767 let start: number | undefined;
768 for (let at = items.length - 1; at >= 0; at--) {
769 const item = items[at]!;
770 if (isMarkdownImage(item)) start = at;
771 else if (!isElement(item, "br") && !(item.type === "text" && !item.value.trim())) return start;
772 }
773 return undefined;
775​
776function breakLines(paragraph: Element, breaks: boolean) {
777 const items = paragraph.children;
778 // Inline elements recurse here under `breaks`; only a paragraph's own end is a caption's end.
779 const trailing =
780 paragraph.tagName === "p" || paragraph.tagName === "li"
781 ? trailingImagesStart(items)
782 : undefined;
783 const trailingImage = trailing === undefined ? undefined : items[trailing];
784 const beforeTrailing = trailing === undefined ? undefined : items[trailing - 1];
785 // A line ending before the images breaks below; kept indentation already starts a line.
786 if (
787 trailing !== undefined &&
788 beforeTrailing &&
789 !(
790 beforeTrailing.type === "element" &&
791 (beforeTrailing.tagName === "br" ||
792 (beforeTrailing.tagName === "span" && "dataLeadingWhitespace" in beforeTrailing.properties))
793 ) &&
794 !(beforeTrailing.type === "text" && /\n[ \t]*$/.test(beforeTrailing.value))
795 ) {
796 items.splice(trailing, 0, BREAK, { type: "text", value: "\n" });
797 if (beforeTrailing.type === "text") {
798 beforeTrailing.value = beforeTrailing.value.replace(/[ \t]+$/, "");
799 if (!beforeTrailing.value) items.splice(trailing - 1, 1);
800 }
801 }
802 for (let at = 0; at < items.length; at++) {
803 const item = items[at]!;
804 if (
805 item.type === "element" &&
806 breaks &&
807 item.tagName !== "code" &&
808 !CLOSES_PARAGRAPH.has(item.tagName)
809 ) {
810 breakLines(item, breaks);
811 }
812 if (item.type !== "text" || !item.value.includes("\n")) continue;
813 const afterImage = imageOwnsLine(items, at - 1);
814 const beforeImage =
815 imageOwnsLine(items, at + 1) ||
816 (trailingImage !== undefined && items[at + 1] === trailingImage);
817 const afterBlock = isBlockElement(items[at - 1]) || (at === 0 && paragraph.tagName === "li");
818 const beforeBlock =
819 isBlockElement(items[at + 1]) || (at === items.length - 1 && paragraph.tagName === "li");
820 const lines = item.value.split("\n");
821 const parts: ElementContent[] = [];
822 lines.forEach((line, index) => {
823 // A hard break's own line ending follows its <br>, and adds no second one;
824 // structural line endings around a list item's block children stay breaks between blocks.
825 const afterHardBreak = index === 1 && isElement(items[at - 1], "br");
826 const blockBoundary =
827 (index === 1 && lines[0] === "" && afterBlock) ||
828 (index === lines.length - 1 && line === "" && beforeBlock);
829 const breaksHere =
830 index > 0 &&
831 !afterHardBreak &&
832 !blockBoundary &&
833 (breaks || (index === 1 && afterImage) || (index === lines.length - 1 && beforeImage));
834 if (index > 0) {
835 if (breaksHere) {
836 const previous = parts.at(-1);
837 if (previous?.type === "text") previous.value = previous.value.replace(/[ \t]+$/, "");
838 parts.push(BREAK);
839 }
840 parts.push({ type: "text", value: `\n${line}` });
841 } else if (line) {
842 parts.push({ type: "text", value: line });
843 }
844 });
845 // Rejoin text that did not break, so the tree matches remark's text nodes.
846 const merged: ElementContent[] = [];
847 for (const part of parts) {
848 const previous = merged.at(-1);
849 if (part.type === "text" && previous?.type === "text") previous.value += part.value;
850 else merged.push(part);
851 }
852 items.splice(at, 1, ...merged);
853 at += merged.length - 1;
854 }
856​
857/**
858 * The wrapper copying reads (markdown-clipboard's MATH_SELECTOR): the formula's TeX, as the source
859 * Words drew it from, so copying any part of a formula copies the whole of it.
860 */
861// A formula wider than its block scrolls, with room for the glyphs that reach past its box; in a
862// table it keeps its width and the table scrolls.
863const MATH_SCROLL = [
864 "max-w-full",
865 "overflow-x-auto",
866 "overflow-y-hidden",
867 "px-0.5",
868 "py-0.75",
869 "in-[.chat-markdown-table-container]:max-w-none",
870 "in-[.chat-markdown-table-container]:overflow-visible",
871];
872​
873function mathWrapper(svg: Element): Element {
874 const tex = String(svg.properties.ariaLabel ?? "").trim();
875 const display = /display:\s*block/.test(String(svg.properties.style ?? ""));
876 return {
877 type: "element",
878 tagName: "span",
879 properties: display
880 ? {
881 className: ["chat-markdown-math-display", "block", ...MATH_SCROLL],
882 dataMarkdownMath: "display",
883 dataMarkdownCopy: `\\[\n${tex}\n\\]\n\n`,
884 }
885 : {
886 className: ["inline-block", "align-middle", ...MATH_SCROLL],
887 dataMarkdownMath: "inline",
888 dataMarkdownCopy: `\\(${tex}\\)`,
889 },
890 children: [svg],
891 };
893​
894function restoreMath(node: Root | Element, math: Map<string, Element>) {
895 const children = node.children as ElementContent[];
896 for (let index = 0; index < children.length; index++) {
897 const child = children[index]!;
898 if (child.type !== "element") continue;
899 const id = child.properties.id;
900 const svg = typeof id === "string" ? math.get(id.replace(/^user-content-/, "")) : undefined;
901 if (svg) children[index] = mathWrapper(svg);
902 else restoreMath(child, math);
903 }
905​
906const addHeadingIds = rehypeHeadingIds();
907const addTextDirection = rehypeTextDirection();
908const preserveImageSourceMeta = rehypePreserveImageSourceMeta();
909const normalizeLocalEditorLinks = rehypeNormalizeLocalEditorLinks();
910const groupChipPunctuation = rehypeChipPunctuation();
911​
912const INSIGHT_OPENING = /^( {0,3})(`?)★ Insight[ \t]+─{3,}\2[ \t]*$/u;
913const INSIGHT_CLOSING = /^( {0,3})(`?)─{3,}\2[ \t]*$/u;
914​
915interface InsightSource {
916 readonly source: string;
917 readonly tree: Root;
918 readonly marker: RegExp;
919 /** The offset in the message for an offset in `source`. */
920 readonly toOriginal: (offset: number) => number;
922​
923/**
924 * remarkAssistantInsights: a `★ Insight ───` line opens a quoted insight block, which a `───` line
925 * at the same indentation closes; the end of the text closes one that never does. Lines in code
926 * neither open nor close one, and an opening Words does not read as a quote's first line, as in
927 * an HTML block or a quote's lazy line, stays text.
928 */
929function insightSource(text: string, options: RenderOptions): InsightSource | null {
930 if (!text.includes("★ Insight")) return null;
931 const code: Array<readonly [number, number]> = [];
932 const findCode = (node: Root | Element) => {
933 for (const child of node.children) {
934 if (child.type !== "element") continue;
935 if (child.tagName === "pre" && child.position) {
936 code.push([child.position.start.offset!, child.position.end.offset!]);
937 } else findCode(child);
938 }
939 };
940 findCode(parse(text, options));
941 const nonce = Math.random().toString(36).slice(2);
942 const marker = new RegExp(String.raw`^\[!T3-INSIGHT-${nonce}-(\d+)\](?:\r?\n)?`);
943 const anywhere = new RegExp(String.raw`\[!T3-INSIGHT-${nonce}-(\d+)\]`, "g");
944 const lines = text.split(/(?<=\n)/u);
945 const skipped = new Set<number>();
946 for (;;) {
947 // Each line's offset in the message and in the source, and how much longer it got.
948 const offsets: Array<{ original: number; source: number; length: number; delta: number }> = [];
949 let original = 0;
950 let rewritten = 0;
951 let opened = 0;
952 let indent: string | undefined;
953 const source = lines
954 .map((line, lineIndex) => {
955 const value = line.replace(/[\r\n]+$/u, "");
956 const ending = line.slice(value.length);
957 const inCode = code.some(([start, end]) => original >= start && original < end);
958 let output = line;
959 if (indent === undefined) {
960 const opening = inCode ? null : INSIGHT_OPENING.exec(value);
961 if (opening && !skipped.has(lineIndex)) {
962 indent = opening[1] ?? "";
963 opened++;
964 output = `> [!T3-INSIGHT-${nonce}-${lineIndex}]${ending}`;
965 }
966 } else {
967 const closing = inCode ? null : INSIGHT_CLOSING.exec(value);
968 if (closing && closing[1] === indent) {
969 indent = undefined;
970 output = ending;
971 } else output = `> ${line}`;
972 }
973 offsets.push({
974 original,
975 source: rewritten,
976 length: line.length,
977 delta: output.length - line.length,
978 });
979 original += line.length;
980 rewritten += output.length;
981 return output;
982 })
983 .join("");
984 if (opened === 0) return null;
985 const tree = parse(source, options);
986 let stranded = false;
987 const visit = (node: Root | Element, quoteStart: Text | undefined) => {
988 for (const child of node.children) {
989 if (child.type === "text") {
990 for (const found of child.value.matchAll(anywhere)) {
991 if (child === quoteStart && found.index === 0) continue;
992 skipped.add(Number(found[1]));
993 stranded = true;
994 }
995 } else if (child.type === "element") {
996 const paragraph =
997 child.tagName === "blockquote" ? child.children.find(isElementNode) : undefined;
998 const first = isElement(paragraph, "p") ? paragraph.children[0] : undefined;
999 visit(child, first?.type === "text" ? first : quoteStart);
1002 };
1003 visit(tree, undefined);
1004 if (stranded) continue;
1005 return {
1006 source,
1007 tree,
1008 marker,
1009 toOriginal: (offset) => {
1010 const line = offsets.findLast((entry) => entry.source <= offset) ?? offsets[0]!;
1011 return (
1012 line.original + Math.min(Math.max(offset - line.source - line.delta, 0), line.length)
1013 );
1014 },
1015 };
1018​
1019/** Positions that point into an insight's rewritten source, moved back into the message. */
1020function restorePositions(node: Root | Element, toOriginal: (offset: number) => number) {
1021 for (const child of node.children) {
1022 if (child.type !== "element") continue;
1023 if (child.position) {
1024 const start = toOriginal(child.position.start.offset!);
1025 const end = toOriginal(child.position.end.offset!);
1026 child.position = {
1027 start: { line: 1, column: start + 1, offset: start },
1028 end: { line: 1, column: end + 1, offset: end },
1029 };
1031 restorePositions(child, toOriginal);
1034​
1035const PREVIEW_SEPARATED = new Set([
1036 "blockquote",
1037 "ul",
1038 "ol",
1039 "li",
1040 "table",
1041 "thead",
1042 "tbody",
1043 "tr",
1044]);
1045​
1046/** remarkThoughtPreview: the message as one line of text, keeping math, cut at `maxLength`. */
1047function flattenPreview(tree: Root, preview: NonNullable<MarkdownExtensions["preview"]>): Root {
1048 const children: ElementContent[] = [];
1049 let remaining = preview.maxLength;
1050 let fragments: string[] = [];
1051 const flush = () => {
1052 if (fragments.length === 0) return;
1053 children.push({ type: "text", value: fragments.join("").replace(/\s+/g, " ") });
1054 fragments = [];
1055 };
1056 const take = (value: string) => {
1057 const text = value.slice(0, remaining);
1058 remaining = text.length < value.length ? 0 : remaining - text.length;
1059 // A cut must not leave half a surrogate pair.
1060 return text.replace(/[\uD800-\uDBFF]$/, "");
1061 };
1062 const visit = (node: Root | ElementContent) => {
1063 if (remaining === 0) return;
1064 if (node.type === "text") {
1065 fragments.push(take(node.value));
1066 return;
1068 if (node.type === "element" && node.properties.dataMarkdownMath !== undefined) {
1069 flush();
1070 // One line has no room for display math, which a preview shows inline.
1071 const svg = node.children[0];
1072 children.push(
1073 node.properties.dataMarkdownMath === "display" && svg?.type === "element"
1074 ? mathWrapper({
1075 ...svg,
1076 properties: {
1077 ...svg.properties,
1078 style: "display:inline;vertical-align:middle;overflow:visible",
1079 },
1080 })
1081 : node,
1082 );
1083 return;
1085 if (node.type === "element" && node.tagName === "img") {
1086 fragments.push(take(String(node.properties.alt ?? "")));
1087 return;
1089 if (node.type === "element" && node.tagName === "br") {
1090 fragments.push(take(" "));
1091 return;
1093 if (node.type !== "root" && node.type !== "element") return;
1094 const separates = node.type === "root" || PREVIEW_SEPARATED.has(node.tagName);
1095 let first = true;
1096 for (const child of node.children as ElementContent[]) {
1097 if (remaining === 0) break;
1098 if (child.type === "text" && child.value.trim() === "" && separates) continue;
1099 if (!first && separates) fragments.push(take(" "));
1100 first = false;
1101 visit(child);
1103 };
1104 visit(tree);
1105 flush();
1106 const head = children[0];
1107 const tail = children.at(-1);
1108 if (head?.type === "text") head.value = head.value.trimStart();
1109 if (tail?.type === "text") tail.value = tail.value.trimEnd();
1110 const visible = children.some((child) => child.type !== "text" || child.value);
1111 return {
1112 type: "root",
1113 children: visible ? children : [{ type: "text", value: preview.fallback }],
1114 };
1116​
1117/** Links become their text, images their alt text, inline code plain text, Mermaid plain code. */
1118function makeInert(node: Root | Element) {
1119 const children = node.children as ElementContent[];
1120 for (let index = 0; index < children.length; index++) {
1121 const child = children[index]!;
1122 if (child.type !== "element") continue;
1123 if (child.tagName === "a") {
1124 children.splice(index, 1, ...child.children);
1125 index--;
1126 continue;
1128 if (child.tagName === "img") {
1129 children[index] = { type: "text", value: String(child.properties.alt ?? "") };
1130 continue;
1132 if (child.tagName === "code" && child.properties.dataInlineCode !== undefined) {
1133 children[index] = { type: "text", value: textOf(child) };
1134 continue;
1136 if (
1137 child.tagName === "code" &&
1138 String(child.properties.className ?? "").includes("language-mermaid")
1139 ) {
1140 child.properties.className = ["language-text"];
1142 makeInert(child);
1145​
1146/** ChatMarkdown's sanitized hast for `text`, rendered by Words. */
1147export function wordsHast(text: string, options: WordsHastOptions): Root {
1148 const { extensions } = options;
1149 const renderOptions: RenderOptions = {
1150 math: options.math,
1151 // llm-math's `\(…\)` and `\[…\]`, which agents write as often as `$`.
1152 texDelimiters: options.math,
1153 autolinkBoundaries: true,
1154 singleTilde: !extensions.userMessage,
1155 leadingWhitespace: extensions.leadingWhitespace === true,
1156 windowsPaths: true,
1157 codeMeta: true,
1158 directives: CODEX_DIRECTIVES,
1159 // Previews and inert Markdown drop raw HTML, as their remark plugins dropped html nodes.
1160 ...(extensions.preview || extensions.inert
1161 ? { skipHtml: true }
1162 : { escapeHtml: options.escapeHtml }),
1163 };
1164 const insights = options.insights ? insightSource(text, renderOptions) : null;
1165 const source = insights?.source ?? text;
1166 const tree = insights?.tree ?? parse(source, renderOptions);
1167 const walk: Walk = {
1168 render: (markdown, indent) =>
1169 parse(markdown, {
1170 ...renderOptions,
1171 leadingWhitespace: extensions.leadingWhitespace === true && { indent },
1172 }),
1173 source,
1174 options,
1175 math: new Map(),
1176 mathKey: `t3-math-${Math.random().toString(36).slice(2)}`,
1177 insightMarker: insights?.marker ?? null,
1178 };
1179 transform(tree, walk, false, false);
1180 preserveImageSourceMeta(tree as never);
1181 normalizeLocalEditorLinks(tree as never);
1182 const hast = sanitizeChatHast(tree);
1183 if (walk.math.size > 0) restoreMath(hast, walk.math);
1184 if (insights) restorePositions(hast, insights.toOriginal);
1185 if (extensions.inert) makeInert(hast);
1186 if (extensions.preview) return flattenPreview(hast, extensions.preview);
1187 addHeadingIds(hast);
1188 addTextDirection(hast as never);
1189 groupChipPunctuation(hast as never);
1190 return hast;
1192​
1193export interface CodexDirectiveSource {
1194 readonly name: string;
1195 readonly attributes: Record<string, string>;
1196 /** UTF-16 offsets of the whole directive in the source. */
1197 readonly start: number;
1198 readonly end: number;
1199 /** The label's text as written. */
1200 readonly label: string;
1201 /** Inside a link, where a file citation stays text. */
1202 readonly inLink: boolean;
1204​
1205/** The Codex directives in `markdown`, as Words reads them. */
1206export function codexDirectiveSources(markdown: string): CodexDirectiveSource[] {
1207 const found: CodexDirectiveSource[] = [];
1208 const visit = (node: Root | Element, inLink: boolean) => {
1209 for (const child of node.children) {
1210 if (child.type !== "element") continue;
1211 const name = child.properties.dataDirective;
1212 if (typeof name === "string" && child.position) {
1213 const { start, end } = child.position;
1214 found.push({
1215 name,
1216 attributes: directiveAttributes(child),
1217 start: start.offset!,
1218 end: end.offset!,
1219 label: directiveLabel(markdown.slice(start.offset, end.offset)),
1220 inLink,
1221 });
1223 visit(child, inLink || child.tagName === "a");
1225 };
1226 visit(
1227 parse(markdown, {
1228 windowsPaths: true,
1229 autolinkBoundaries: true,
1230 directives: CODEX_DIRECTIVES,
1231 }),
1232 false,
1233 );
1234 return found;
1236​
1237/** The label of a directive as written, `:name[label]{…}`: brackets nest in it, and `\` escapes. */
1238function directiveLabel(written: string): string {
1239 const open = written.indexOf("[");
1240 if (open < 0) return "";
1241 let depth = 0;
1242 for (let index = open; index < written.length; index++) {
1243 const character = written[index];
1244 if (character === "\\") index++;
1245 else if (character === "[") depth++;
1246 else if (character === "]" && --depth === 0) return written.slice(open + 1, index);
1248 return "";
1250​
1251/**
1252 * Words' HTML for `markdown` as hast, unsanitized and without the chat's additions. Code blocks,
1253 * links, list items and math carry source positions.
1254 */
1255export function markdownTree(
1256 markdown: string,
1257 options: { skipHtml?: boolean; singleTilde?: boolean; math?: boolean } = {},
1258): Root {
1259 return parse(markdown, {
1260 windowsPaths: true,
1261 autolinkBoundaries: true,
1262 skipHtml: options.skipHtml === true,
1263 singleTilde: options.singleTilde !== false,
1264 math: options.math === true,
1265 texDelimiters: options.math === true,
1266 });
1268​
1269/** The formulas Words reads in `text`, as source offsets, for editors that keep math as source. */
1270export function markdownMathRanges(text: string): Array<{ start: number; end: number }> {
1271 if (!/[$\\]|(?:`{3,}|~{3,})[ \t]*math\b/.test(text)) return [];
1272 const ranges: Array<{ start: number; end: number }> = [];
1273 const visit = (node: Root | Element) => {
1274 for (const child of node.children) {
1275 if (child.type !== "element") continue;
1276 if (child.tagName === "svg") {
1277 if (child.position) {
1278 ranges.push({ start: child.position.start.offset!, end: child.position.end.offset! });
1280 continue;
1282 visit(child);
1284 };
1285 visit(parse(text, { math: true, texDelimiters: true }));
1286 return ranges;
1288​
1289/** The HTML comments Words reads as raw HTML in `markdown`, not as code or text, as source offsets. */
1290export function markdownHtmlComments(markdown: string): Array<{ start: number; end: number }> {
1291 const openers = [...markdown.matchAll(/<!--(?!-?>)/g)].map((match) => match.index);
1292 if (openers.length === 0) return [];
1293 // A mark after each opener keeps a comment a comment; Words writes only real ones unescaped.
1294 let marked = "";
1295 let from = 0;
1296 for (const [index, at] of openers.entries()) {
1297 marked += `${markdown.slice(from, at + 4)}\uE000${index}\uE001`;
1298 from = at + 4;
1300 const html = decoder.decode(renderToHtml(marked + markdown.slice(from), { windowsPaths: true }));
1301 return [...html.matchAll(/<!--\uE000(\d+)\uE001/g)].map((match) => {
1302 const start = openers[Number(match[1])]!;
1303 const close = markdown.indexOf("-->", start + 4);
1304 return { start, end: close < 0 ? markdown.length : close + 3 };
1305 });
1307​
1308/**
1309 * The first definition of each label in `markdown`, as one line of Markdown. Words decides which
1310 * `[label]:` text defines one: each label is looked up again after the text.
1311 */
1312export function markdownReferenceDefinitions(markdown: string): string[] {
1313 const labels = new Map<string, string>();
1314 for (const match of markdown.matchAll(/\[((?:[^\\[\]]|\\.){1,999})\]:/g)) {
1315 const key = match[1]!.replace(/\s+/g, " ").trim().toLowerCase();
1316 // `[^1]:` is a footnote.
1317 if (key !== "" && !key.startsWith("^") && !labels.has(key)) labels.set(key, match[1]!);
1319 if (labels.size === 0) return [];
1320 let probe = `${markdown}\n\n`;
1321 const lookups = new Map<number, string>();
1322 for (const label of labels.values()) {
1323 lookups.set(probe.length, label);
1324 probe += `[${label}]\n\n`;
1326 const definitions: string[] = [];
1327 const visit = (node: Root | Element) => {
1328 for (const child of node.children) {
1329 if (child.type !== "element") continue;
1330 const label = lookups.get(child.position?.start.offset ?? -1);
1331 if (child.tagName === "a" && label !== undefined) {
1332 const href = String(child.properties.href ?? "").replace(/[<>\\\n]/g, encodeURIComponent);
1333 const title = child.properties.title;
1334 definitions.push(
1335 `[${label}]: <${href}>${typeof title === "string" ? ` "${title.replace(/\s+/g, " ").replace(/["\\]/g, "\\$&")}"` : ""}`,
1336 );
1337 } else visit(child);
1339 };
1340 visit(parse(probe, { windowsPaths: true }));
1341 return definitions;