diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts index d0d39f126620a..862c1eba65ccc 100644 --- a/apps/mobile/src/lib/markdownDocument.ts +++ b/apps/mobile/src/lib/markdownDocument.ts @@ -2,6 +2,7 @@ import type { Root, RootContent } from "mdast"; import { unified, type Processor } from "unified"; import remarkParse from "remark-parse"; import remarkGfm from "remark-gfm"; +import { markdownWithSpacedFilePaths } from "@t3tools/shared/markdownSpacedFilePaths"; import { remarkKeepWindowsProsePaths } from "@t3tools/shared/markdownWindowsPaths"; import { isBareLink, @@ -563,7 +564,10 @@ function markdownWithImageParagraphs(markdown: string): string { // HTML wrappers can expose Markdown that wasn't in the first AST, so normalize them first. function normalizedMarkdown(markdown: string): string { - return markdownWithWindowsPathDestinations(markdownWithHtml(markdown)); + const content = markdownWithHtml(markdown); + return markdownWithWindowsPathDestinations( + markdownWithSpacedFilePaths(content, (markdown) => parser.parse(markdown)), + ); } const autolinkParser = unified() diff --git a/apps/mobile/src/lib/markdownHtml.test.ts b/apps/mobile/src/lib/markdownHtml.test.ts index 383a43d0dcfc8..4124c249a23ec 100644 --- a/apps/mobile/src/lib/markdownHtml.test.ts +++ b/apps/mobile/src/lib/markdownHtml.test.ts @@ -15,6 +15,27 @@ import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation"; import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown"; +it("renders bare Windows and POSIX spaced media and file paths in native Markdown", () => { + const winSlash = "Z:/Projects/Demo App/Output Shots/bust.jpg"; + const winBackslash = String.raw`C:\Users\First Last\.t3\shot.png`; + const mac = "/Users/test/Mobile Documents/shot.png"; + const markdown = [ + `![Bust](${winSlash})`, + `![Win](${winBackslash})`, + `![Mac](${mac})`, + `[File](C:/Users/First Last/src/app.ts:10)`, + ].join("\n\n"); + expect(markdownImageSources(markdown)).toEqual([winSlash, winBackslash, mac]); + const rendered = markdownForNativeRendering(markdown, ENRICHED_INLINE_FILE_LINK_REGEX); + expect(rendered).toContain(`![Bust](<${winSlash}>)`); + expect(rendered).toContain(String.raw`![Win]()`); + expect(rendered).toContain(`![Mac](<${mac}>)`); + expect(rendered).toContain(`[File]()`); + expect( + markdownForNativeRendering(`\uFEFF![Mac](${mac})`, ENRICHED_INLINE_FILE_LINK_REGEX), + ).toContain(`![Mac](<${mac}>)`); +}); + describe("HTML in native Markdown", () => { it("preserves screenshot URLs and captions from GitHub HTML image embeds", () => { expect( diff --git a/apps/web/src/markdown/wordsHast.test.ts b/apps/web/src/markdown/wordsHast.test.ts index d3c48b463c542..ac8868896365a 100644 --- a/apps/web/src/markdown/wordsHast.test.ts +++ b/apps/web/src/markdown/wordsHast.test.ts @@ -627,6 +627,86 @@ describe("wordsHast", () => { expect(isMarkdownFileLinkLabel(basename, String(anchor.properties.href))).toBe(true); }); + it("renders bare Windows and POSIX media embeds and file links with spaces while leaving code literal", () => { + const winSlash = "Z:/Projects/Demo App/Output Shots/final-bust.jpg"; + const winBackslash = String.raw`C:\Users\First Last\.t3\design-review\r6-1.png`; + const macIcloud = "/Users/test/Mobile Documents/iCloud~md~notes/cover photo.png"; + const winFileLink = "C:/Users/First Last/Downloads GC/project/src/DetailsTab.tsx:42"; + const markdown = [ + `![Bust](${winSlash})`, + "", + `![Round 6](${winBackslash})`, + "", + `![Cover](${macIcloud})`, + "", + `[DetailsTab.tsx:42](${winFileLink})`, + "", + `\`![Inline](${winSlash})\``, + "", + "```md", + `![Fence](${macIcloud})`, + "```", + ].join("\n"); + const html = wordsHtml(markdown); + expect(html).toContain(`data-local-src="Z:/Projects/Demo%20App/Output%20Shots/final-bust.jpg"`); + expect(html).toContain( + String.raw`data-local-src="C:\Users\First%20Last\.t3\design-review\r6-1.png"`, + ); + expect(html).toContain( + `src="/Users/test/Mobile%20Documents/iCloud~md~notes/cover%20photo.png"`, + ); + expect(html).toContain( + `href="file:///C:/Users/First%20Last/Downloads%20GC/project/src/DetailsTab.tsx:42"`, + ); + expect(html).toContain(`![Inline](${winSlash})`); + expect(html).toContain(`![Fence](${macIcloud})\n`); + + // Backticks inside a fenced block must not pair with prose backticks after an image. + expect(wordsHtml("~~~\n`unclosed\n~~~\n![real](/tmp/a b.png)\n`tail`")).toContain( + `src="/tmp/a%20b.png"`, + ); + expect(wordsHtml("[Open `README.md`](/tmp/My Project/README.md)")).toContain( + `href="/tmp/My%20Project/README.md"`, + ); + expect(wordsHtml("[Open `README\n.md`](/tmp/My Project/README.md)")).toContain( + `href="/tmp/My%20Project/README.md"`, + ); + expect(wordsHtml("![a](./img !32.png)\n\n![b](screenshots/my shot (1).png)")).toContain( + `src="./img%20!32.png"`, + ); + expect(wordsHtml("![b](screenshots/my shot (1).png)")).toContain( + `src="screenshots/my%20shot%20(1).png"`, + ); + }); + + it("leaves spaced paths alone where they would not become a link or image", () => { + for (const [markdown, options] of [ + ["
\n[x](/tmp/a b.png)\n
", {}], + ['hi', { escapeHtml: true }], + ["`a` \\``` ![x](/tmp/a b.png) ``", {}], + ["[label\n# heading\n](/tmp/a b.ts)", {}], + ["[label\n---\n](/tmp/a b.ts)", {}], + ["[unclosed\\\n\nfoo](/tmp/a b.png)", {}], + ] as const) { + expect(wordsHtml(markdown, options)).not.toContain("</tmp/"); + } + expect(wordsHtml("![x](/tmp/a b.png)")).toContain(`src="/tmp/a%20b.png"`); + // A failed candidate does not stop a later one from repairing. + expect(wordsHtml("[label\n# heading\n](/tmp/a b.ts) ![ok](/tmp/c d.png)")).toContain( + `src="/tmp/c%20d.png"`, + ); + + // Existing links keep their labels and autolinks, and an image inside one still repairs. + expect(wordsHtml("[![Shot](/tmp/my shot.png)](https://example.test)")).toContain( + `Shot`, + ); + expect(wordsHtml("[a c](/tmp/My Folder/a.ts)")).not.toContain( + "My%20Folder", + ); + + expect(wordsHtml(String.raw`![x](.\My Folder\(1)\a.png)`)).not.toContain(String.raw`)\a.png`); + }); + it("supports chunked footnote modes (omit, omit-seeded, only)", () => { const chunk0 = toHtml( wordsHast("[^a]: .\n[^b]: .\n\nFirst[^a].", { diff --git a/apps/web/src/markdown/wordsHast.ts b/apps/web/src/markdown/wordsHast.ts index d09e0a1763283..64e83393746f8 100644 --- a/apps/web/src/markdown/wordsHast.ts +++ b/apps/web/src/markdown/wordsHast.ts @@ -15,6 +15,12 @@ import { resolveChangeRequestMediaUrl } from "@t3tools/client-runtime/pull-reque import { expandIndentedCodeTabs } from "@t3tools/shared/markdownListIndentation"; import { GITHUB_ALERT_MARKER } from "@t3tools/shared/markdownGithubAlerts"; import { absoluteFilePathMatches } from "@t3tools/shared/markdownLinks"; +import { + countSpacedFilePathInsertionsBefore, + hasSpacedFilePathCandidate, + wrapSpacedFilePathsInProtectedRanges, + wrapSpacedFilePathsThatRender, +} from "@t3tools/shared/markdownSpacedFilePaths"; import { rehypeNormalizeLocalFileLinks, rehypePreserveImageSourceMeta, @@ -1193,6 +1199,74 @@ function makeInert(node: Root | Element) { } } +const SPACED_PATH_PROTECTED_TAGS = new Set(["pre", "img", "svg", "script", "style"]); + +function hastLinkStarts(tree: Root): ReadonlySet { + const starts = new Set(); + const visit = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + const start = child.position?.start.offset; + if ((child.tagName === "a" || child.tagName === "img") && start !== undefined) { + starts.add(start); + } + visit(child); + } + }; + visit(tree); + return starts; +} + +function repairSpacedFilePaths( + source: string, + tree: Root, + options: RenderOptions, +): { + readonly source: string; + readonly tree: Root; + readonly toOriginal: (offset: number) => number; +} | null { + if (!hasSpacedFilePathCandidate(source)) return null; + const protectedRanges: Array = markdownHtmlComments(source).map( + ({ start, end }) => [start, end] as const, + ); + // Existing links keep their labels; an image inside one can still be repaired. + const linkRanges: Array = []; + const collectProtected = (node: Root | Element) => { + for (const child of node.children) { + if (child.type !== "element") continue; + if (child.tagName === "a" && child.position) { + linkRanges.push([child.position.start.offset!, child.position.end.offset!]); + } else if (SPACED_PATH_PROTECTED_TAGS.has(child.tagName) && child.position) { + protectedRanges.push([child.position.start.offset!, child.position.end.offset!]); + continue; + } + collectProtected(child); + } + }; + collectProtected(tree); + const repaired = wrapSpacedFilePathsThatRender( + (skipOpeners) => + wrapSpacedFilePathsInProtectedRanges( + source, + protectedRanges, + undefined, + linkRanges, + undefined, + skipOpeners, + ), + (markdown) => parse(markdown, options), + hastLinkStarts, + ); + if (!repaired) return null; + const { markdown, insertions } = repaired; + return { + source: markdown, + tree: repaired.tree, + toOriginal: (offset) => offset - countSpacedFilePathInsertionsBefore(insertions, offset), + }; +} + function isFootnotesSection(node: Root["children"][number]): boolean { return ( node.type === "element" && @@ -1270,8 +1344,11 @@ export function wordsHast(text: string, options: WordsHastOptions): Root { : { escapeHtml: options.escapeHtml }), }; const insights = options.insights ? insightSource(text, renderOptions) : null; - const source = insights?.source ?? text; - const tree = insights?.tree ?? parse(source, renderOptions); + const initialSource = insights?.source ?? text; + const initialTree = insights?.tree ?? parse(initialSource, renderOptions); + const spaced = repairSpacedFilePaths(initialSource, initialTree, renderOptions); + const source = spaced?.source ?? initialSource; + const tree = spaced?.tree ?? initialTree; let documentDefinitions: string[] | undefined; const walk: Walk = { definitions: (markdown) => @@ -1297,6 +1374,7 @@ export function wordsHast(text: string, options: WordsHastOptions): Root { normalizeLocalFileLinks(tree as never); const hast = sanitizeChatHast(tree); if (walk.math.size > 0) restoreMath(hast, walk.math); + if (spaced) restorePositions(hast, spaced.toOriginal); if (insights) restorePositions(hast, insights.toOriginal); if (extensions.footnotes) applyFootnoteMode(hast, extensions.footnotes); if (extensions.inert) makeInert(hast); diff --git a/packages/shared/package.json b/packages/shared/package.json index 4df64da75835a..f37db1e0da4a5 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -575,6 +575,10 @@ "types": "./src/proposedPlanText.ts", "import": "./src/proposedPlanText.ts" }, + "./markdownSpacedFilePaths": { + "types": "./src/markdownSpacedFilePaths.ts", + "import": "./src/markdownSpacedFilePaths.ts" + }, "./markdownWindowsPaths": { "types": "./src/markdownWindowsPaths.ts", "import": "./src/markdownWindowsPaths.ts" diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index fc8b5aec5d3ed..0ccd618a473c1 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -416,6 +416,28 @@ describe("extractMarkdownLinkHrefs", () => { ["[a](unclosed(paren) [b](ok)", ["ok"]], ["[a](" + "(".repeat(32) + "x" + ")".repeat(32) + ")", ["(".repeat(32) + "x" + ")".repeat(32)]], ["[a](" + "(".repeat(33) + "x" + ")".repeat(33) + ") [b](ok)", ["ok"]], + [ + String.raw`![Bust](Z:/Projects/Demo App/Output Shots/bust.jpg) [Details](C:\Users\First Last\src\Details.tsx:12) [Notes](/Users/me/Mobile Documents/notes.md) ![Shot](./img !32.png) ![Rel](screenshots/my shot (1).png)`, + [ + "Z:/Projects/Demo App/Output Shots/bust.jpg", + String.raw`C:\Users\First Last\src\Details.tsx:12`, + "/Users/me/Mobile Documents/notes.md", + "./img !32.png", + "screenshots/my shot (1).png", + ], + ], + [ + String.raw`[a](/home/u/My Folder/a.pdf "Title") [b](C:\My Drive\b.html 'it\'s') [c](/tmp/x y.md "Revision )") [d](/home/u/Bob's Files/d.md)`, + [ + "/home/u/My Folder/a.pdf", + String.raw`C:\My Drive\b.html`, + "/tmp/x y.md", + "/home/u/Bob's Files/d.md", + ], + ], + [`[a](/tmp/x y.md "unclosed) [b](ok)`, ["ok"]], + [`[a](/tmp/x y.md 'unclosed) [b](ok)`, ["ok"]], + [`[a](/tmp/Rock 'n' Roll/a.md)`, ["/tmp/Rock 'n' Roll/a.md"]], ])("keeps balanced parentheses in a destination like the parser: %s", (markdown, hrefs) => { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); }); diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 830bf71436a24..7f3eecc232884 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -869,6 +869,113 @@ function markdownLinkTailScanner(markdown: string) { // link's opening parenthesis while that parenthesis counts toward this depth. const MAX_BARE_DESTINATION_PAREN_DEPTH = 32; +const EXPLICIT_SPACED_PATH_PREFIX = /^(?:\/(?![/\\])|~[\\/]|[A-Za-z]:[\\/]|\.\.?[\\/])/; + +function hasTrailingUnescapedBackslash(value: string): boolean { + let count = 0; + for (let index = value.length - 1; index >= 0 && value[index] === "\\"; index -= 1) { + count += 1; + } + return count % 2 !== 0; +} + +/** The title's closing `)`, `"unclosed"` when the quote never closes, or null when it closes mid-path. */ +function quotedTitleCloseParen(markdown: string, quoteIndex: number): number | "unclosed" | null { + const quote = markdown[quoteIndex]; + for (let index = quoteIndex + 1; index < markdown.length; index += 1) { + const char = markdown[index]!; + if (char === "\r" || char === "\n") return "unclosed"; + if (char === "]" && markdown[index + 1] === "(") return "unclosed"; + if (char === "\\") { + index += 1; + continue; + } + if (char !== quote) continue; + let close = index + 1; + while (markdown[close] === " " || markdown[close] === "\t") close += 1; + return markdown[close] === ")" ? close : null; + } + return "unclosed"; +} + +/** + * Scans a bare Markdown link destination starting at `start` (after `(` and optional horizontal + * whitespace) for a local file path containing spaces (absolute, home, or relative). + */ +export function spacedFilePathDestinationEnd( + markdown: string, + start: number, +): { readonly hrefEnd: number; readonly end: number } | null { + if (markdown[start] === "<" || markdown[start] === "#") return null; + const prefix = EXPLICIT_SPACED_PATH_PREFIX.exec(markdown.slice(start, start + 3))?.[0]; + // Backslashes after `C:`, `.\` or `~\` are separators, not escapes. + const isWindows = + prefix !== undefined && (prefix.endsWith("\\") || (prefix.length === 3 && prefix[1] === ":")); + let parenDepth = 0; + let closeParen = -1; + let pathEnd = -1; + for (let index = start; index < markdown.length; index += 1) { + const char = markdown[index]!; + const previous = markdown[index - 1]; + if ( + (char === '"' || char === "'") && + parenDepth === 0 && + index > start && + (previous === " " || previous === "\t") + ) { + const titleClose = quotedTitleCloseParen(markdown, index); + if (titleClose === "unclosed") return null; + if (titleClose !== null) { + pathEnd = index; + closeParen = titleClose; + break; + } + } + if (char === "\r" || char === "\n" || char === "<" || char === ">" || char === "`") { + return null; + } + if (char === '"') return null; + // A later `](` is scanned as its own candidate, so giving up here keeps scans linear. + if (char === "]" && markdown[index + 1] === "(") return null; + if (char === "\\" && !isWindows) { + const next = markdown[index + 1]; + if (next === undefined || next === "\r" || next === "\n") return null; + index += 1; + continue; + } + if (char === "(") { + if (parenDepth === MAX_BARE_DESTINATION_PAREN_DEPTH) return null; + parenDepth += 1; + } else if (char === ")") { + if (parenDepth === 0) { + closeParen = index; + break; + } + parenDepth -= 1; + } + } + if (closeParen < 0) return null; + let hrefEnd = pathEnd < 0 ? closeParen : pathEnd; + while (hrefEnd > start && (markdown[hrefEnd - 1] === " " || markdown[hrefEnd - 1] === "\t")) { + hrefEnd -= 1; + } + const path = markdown.slice(start, hrefEnd); + if (!/[ \t]/.test(path) || hasTrailingUnescapedBackslash(path) || isNetworkPath(path)) { + return null; + } + const parsed = parseMarkdownFileLink(path); + if (!parsed) return null; + if (!prefix) { + // Unprefixed relative paths require a slash and a file-shaped basename so prose like `(a/b c)` stays text. + if (!PATH_SEPARATOR_PATTERN.test(parsed.path)) return null; + const basename = parsed.path.split(PATH_SEPARATOR_PATTERN).at(-1) ?? ""; + if (!FILE_EXTENSION_PATTERN.test(basename) && !EXTENSIONLESS_FILE_NAMES.has(basename)) { + return null; + } + } + return { hrefEnd, end: closeParen + 1 }; +} + function bareMarkdownLinkDestinationEnd(markdown: string, start: number): number | null { // Destinations end at ASCII spaces and controls but not NUL, which micromark reads as U+FFFD. const delimiter = /[\x01-\x20\x7f()\\]/g; @@ -907,9 +1014,12 @@ export function markdownLinkDestinationScanner(markdown: string) { } } const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart); - if (hrefEnd === null) return null; - const end = bareTail(hrefEnd); - return end === null ? null : { hrefStart, hrefEnd, end }; + if (hrefEnd !== null) { + const end = bareTail(hrefEnd); + if (end !== null) return { hrefStart, hrefEnd, end }; + } + const spaced = spacedFilePathDestinationEnd(markdown, hrefStart); + return spaced === null ? null : { hrefStart, hrefEnd: spaced.hrefEnd, end: spaced.end }; }; } diff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.ts index 5d4b31ec98a2d..3cb2733fb0277 100644 --- a/packages/shared/src/markdownPipeline.test.ts +++ b/packages/shared/src/markdownPipeline.test.ts @@ -5,6 +5,7 @@ import remarkGfm from "remark-gfm"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import type { Link, Root, RootContent } from "mdast"; +import { markdownWithSpacedFilePaths } from "./markdownSpacedFilePaths.ts"; import { CHAT_MARKDOWN_REHYPE_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS, @@ -1153,3 +1154,149 @@ it.each([ expect(links(`\`\`\`\n${path}\n\`\`\``)).toEqual([]); }, ); + +it("repairs bare local media embeds and file links with spaces across Windows, POSIX, and relative paths", () => { + const winSlash = "Z:/Projects/Demo App/Output Shots/final-bust.jpg"; + const winBackslash = String.raw`C:\Users\First Last\.t3\design-review\r6-1.png`; + const winFileLink = "C:/Users/First Last/Downloads GC/project/src/DetailsTab.tsx:42"; + const macIcloud = "/Users/test/Mobile Documents/iCloud~md~notes/cover photo.png"; + const wslParens = "/mnt/c/Project (demo)/screen shot.webp"; + const homePath = "~/My Documents/notes.md"; + const relBang = "./img !32.png"; + const relParens = "screenshots/my shot (1).png"; + const relDoc = "../my docs/spec.md:12"; + const wrapped = "/work/Already wrapped.png"; + const authored = [ + `**Compare** ![Bust](${winSlash}) ![Round 6](${winBackslash})`, + `![Cover](${macIcloud}) ![Screenshot](${wslParens})`, + `![Bang](${relBang}) ![RelParens](${relParens})`, + `![Wrapped](<${wrapped}> "Title")`, + `Files: [DetailsTab.tsx:42](${winFileLink}), [notes.md](${homePath}), [spec](${relDoc})`, + "", + `\`![Inline code](${winSlash})\``, + "", + "```md", + `![Fence](${macIcloud})`, + "```", + "", + String.raw`\![Escaped](${wslParens})`, + "[Prose](see section 1/2)", + "![Network](//example.test/a b.png)", + "![External](https://example.test/a b.png)", + "![Partial](/work/a b.png", + ].join("\n"); + + expect(chatMarkdownImageSources(authored).map(decodeURI)).toEqual([ + winSlash, + winBackslash, + macIcloud, + wslParens, + relBang, + relParens, + wrapped, + ]); + + const processor = unified().use(remarkParse).use(CHAT_MARKDOWN_REMARK_PLUGINS); + const linkUrlsOf = (markdown: string) => { + const urls: string[] = []; + const visit = (node: Root | RootContent) => { + if (node.type === "link") urls.push(decodeURI(node.url)); + if ("children" in node) node.children.forEach(visit); + }; + visit(processor.runSync(processor.parse(markdown), markdown) as Root); + return urls; + }; + const linkUrls = linkUrlsOf(authored); + expect(linkUrls).toContain(`file:///${winFileLink}`); + expect(linkUrls).toContain(homePath); + expect(linkUrls).toContain(relDoc); + expect(linkUrls).not.toContain("see section 1/2"); + + const codeSpan = "![`label](/work/c d.png)`"; + expect( + markdownWithSpacedFilePaths(codeSpan, (markdown) => unified().use(remarkParse).parse(markdown)), + ).toBe(codeSpan); + + // Backticks inside a fenced code block must not pair with later prose backticks. + const fencedBacktick = "~~~\n`unclosed\n~~~\n![real](/tmp/a b.png)\n`tail`"; + expect(chatMarkdownImageSources(fencedBacktick).map(decodeURI)).toEqual(["/tmp/a b.png"]); + + // A spaced link inside an existing link label must not break the outer link, while a linked image still repairs. + const nestedLink = "[outer [inner](/tmp/a b.ts)](https://example.test)"; + expect(linkUrlsOf(nestedLink)).toEqual(["https://example.test"]); + + const linkedImage = "[![Shot](/tmp/my shot.png)](https://example.test)"; + expect(chatMarkdownImageSources(linkedImage).map(decodeURI)).toEqual(["/tmp/my shot.png"]); + + // Inline code (including multiline) inside a link label must not block spaced-path repair. + for (const codeLabelLink of [ + "[Open `README.md`](/tmp/My Project/README.md)", + "[Open `README\n.md`](/tmp/My Project/README.md)", + ]) { + expect(linkUrlsOf(codeLabelLink)).toEqual(["/tmp/My Project/README.md"]); + } + + // A spaced image inside a link label must not stop the enclosing spaced file link from repairing. + const linkedSpacedImage = "[![Shot](/tmp/my shot.png)](/tmp/my report.pdf)"; + expect(linkUrlsOf(linkedSpacedImage)).toEqual(["/tmp/my report.pdf"]); + expect(chatMarkdownImageSources(linkedSpacedImage).map(decodeURI)).toEqual(["/tmp/my shot.png"]); + + // An escaped `)` before the first space must not hide the destination from the quick pre-check. + expect(chatMarkdownImageSources(String.raw`![x](./a\) b.png)`).map(decodeURI)).toEqual([ + "./a) b.png", + ]); + + // A quoted title after a spaced path stays the link's title, even when it contains `)`. + const titled = `[Report](/tmp/My Project/report.pdf "Revision )") ![Shot](C:/My Shots/a.png 'Shot')`; + expect(linkUrlsOf(titled)).toEqual(["/tmp/My Project/report.pdf"]); + expect(chatMarkdownImageSources(titled).map(decodeURI)).toEqual(["C:/My Shots/a.png"]); + expect( + markdownWithSpacedFilePaths(titled, (markdown) => unified().use(remarkParse).parse(markdown)), + ).toBe(`[Report]( "Revision )") ![Shot]( 'Shot')`); + + // A label broken by a block never becomes a link, so its destination keeps its authored text. + const parseMarkdown = (markdown: string) => unified().use(remarkParse).parse(markdown); + for (const broken of [ + "[label\n# heading\n](/tmp/a b.ts)", + "[label\n---\n](/tmp/a b.ts)", + "[unclosed\\\n\nfoo](/tmp/a b.png)", + ]) { + expect(markdownWithSpacedFilePaths(broken, parseMarkdown)).toBe(broken); + } + expect( + markdownWithSpacedFilePaths( + "[label\n# heading\n](/tmp/a b.ts) ![ok](/tmp/c d.png)", + parseMarkdown, + ), + ).toBe("[label\n# heading\n](/tmp/a b.ts) ![ok]()"); + + expect(chatMarkdownImageSources("![x](/tmp/a b.png)").map(decodeURI)).toEqual(["/tmp/a b.png"]); + + // Backslashes in a relative Windows path are separators, so `\(` does not end the path early. + expect(markdownWithSpacedFilePaths(String.raw`![x](.\My Folder\(1)\a.png)`, parseMarkdown)).toBe( + String.raw`![x](<.\My Folder\(1)\a.png>)`, + ); +}); + +it("keeps authored offsets after repairing multiple spaced file paths", () => { + const markdown = + "![One](Z:/Demo Dir/one a.png)\t[Two](/tmp/two b.ts) [link](https://example.test)\n\nNext."; + const processor = unified().use(remarkParse).use(CHAT_MARKDOWN_REMARK_PLUGINS); + const [paragraph, next] = processor.parse(markdown).children; + if (paragraph?.type !== "paragraph") throw new Error("Expected a paragraph"); + + const sources = paragraph.children + .filter((node) => node.type === "image" || node.type === "link") + .map((node) => { + const { start, end } = node.position!; + expect(start.column).toBe(start.offset! + 1); + expect(end.column).toBe(end.offset! + 1); + return markdown.slice(start.offset, end.offset); + }); + expect(sources).toEqual([ + "![One](Z:/Demo Dir/one a.png)", + "[Two](/tmp/two b.ts)", + "[link](https://example.test)", + ]); + expect(next?.position?.start).toEqual({ line: 3, column: 1, offset: markdown.indexOf("Next.") }); +}); diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index c5283988b5f0c..a0d120e8de930 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,4 +1,5 @@ import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast"; +import { remarkSpacedFilePaths } from "./markdownSpacedFilePaths.ts"; import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts"; import { type PluggableList, type Processor, type Transformer, unified } from "unified"; import remarkParse from "remark-parse"; @@ -112,6 +113,7 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkGfm, remarkCjkFriendly, remarkCjkFriendlyGfmStrikethrough, + remarkSpacedFilePaths, remarkEndAutolinksAtScriptPunctuation, remarkKeepAutolinkSuffixes, remarkKeepWindowsPaths, @@ -130,6 +132,7 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [ remarkGfm, remarkCjkFriendly, remarkCjkFriendlyGfmStrikethrough, + remarkSpacedFilePaths, remarkEndAutolinksAtScriptPunctuation, remarkKeepAutolinkSuffixes, remarkKeepLeadingWhitespace, diff --git a/packages/shared/src/markdownSpacedFilePaths.ts b/packages/shared/src/markdownSpacedFilePaths.ts new file mode 100644 index 0000000000000..1aefce77cc39b --- /dev/null +++ b/packages/shared/src/markdownSpacedFilePaths.ts @@ -0,0 +1,430 @@ +import type { Root, RootContent } from "mdast"; +import type { Plugin } from "unified"; +import { spacedFilePathDestinationEnd } from "./markdownLinks.ts"; + +function hasSpacedDestinationAfterBracket(source: string): boolean { + let pos = source.indexOf("]("); + while (pos >= 0) { + let index = pos + 2; + while (source[index] === " " || source[index] === "\t") index += 1; + const first = source[index]; + if (first !== undefined && first !== "<" && first !== "#") { + let sawSpace = false; + let parenDepth = 0; + for (; index < source.length; index += 1) { + const ch = source[index]!; + if (ch === "\r" || ch === "\n") break; + // The next `](` starts its own candidate; stopping here keeps the scan linear. + if (ch === "]" && source[index + 1] === "(") break; + if (ch === " " || ch === "\t") { + sawSpace = true; + } else if (sawSpace && (ch === '"' || ch === "'")) { + return true; + } else if (ch === "(") { + parenDepth += 1; + } else if (ch === ")") { + // Permissive pre-check: any `)` after a space is enough to run the real scan. + if (sawSpace) return true; + if (source[index - 1] === "\\") continue; + if (parenDepth === 0) break; + parenDepth -= 1; + } + } + } + pos = source.indexOf("](", pos + 2); + } + return false; +} + +type OffsetRange = readonly [number, number]; + +function isEscaped(source: string, offset: number): boolean { + let start = offset; + while (source[start - 1] === "\\") start -= 1; + return (offset - start) % 2 !== 0; +} + +function mergeRanges(ranges: ReadonlyArray): OffsetRange[] { + if (ranges.length <= 1) return ranges.filter(([from, to]) => from < to); + const sorted = ranges + .filter(([from, to]) => from < to) + .sort((a, b) => a[0] - b[0] || a[1] - b[1]); + const merged: OffsetRange[] = []; + for (const [from, to] of sorted) { + const previous = merged.at(-1); + if (previous && from <= previous[1]) { + merged[merged.length - 1] = [previous[0], Math.max(previous[1], to)]; + } else { + merged.push([from, to]); + } + } + return merged; +} + +/** Returns the index of the first merged range with `to > offset`, or `ranges.length`. */ +function firstRangeEndingAfter(ranges: ReadonlyArray, offset: number): number { + let low = 0; + let high = ranges.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (ranges[middle]![1] <= offset) low = middle + 1; + else high = middle; + } + return low; +} + +function overlapsMergedRanges( + ranges: ReadonlyArray, + start: number, + end: number, +): boolean { + const index = firstRangeEndingAfter(ranges, start); + return index < ranges.length && ranges[index]![0] < end; +} + +function containsMergedOffset(ranges: ReadonlyArray, offset: number): boolean { + const index = firstRangeEndingAfter(ranges, offset); + return index < ranges.length && ranges[index]![0] <= offset; +} + +function findNextBlankLine(source: string, from: number, limit: number): number { + for (let index = from; index < limit; index += 1) { + if (source[index] !== "\n") continue; + let next = index + 1; + while ( + next < limit && + (source[next] === " " || source[next] === "\t" || source[next] === "\r") + ) { + next += 1; + } + if (next < limit && source[next] === "\n") return index; + } + return limit; +} + +/** + * Indexes backtick runs per contiguous non-protected paragraph in linear time so unmatched + * backtick runs never rescan the remaining paragraph. + */ +function createInlineCodeSpanFinder(source: string, protectedRanges: ReadonlyArray) { + let segmentEnd = -1; + let runsByLength = new Map(); + + const indexSegment = (from: number) => { + const nextProtectedIndex = firstRangeEndingAfter(protectedRanges, from); + const nextProtectedStart = + nextProtectedIndex < protectedRanges.length + ? protectedRanges[nextProtectedIndex]![0] + : source.length; + segmentEnd = findNextBlankLine(source, from, Math.min(source.length, nextProtectedStart)); + runsByLength = new Map(); + for (let index = from; index < segmentEnd;) { + if (source[index] !== "`") { + index += 1; + continue; + } + let runEnd = index + 1; + while (runEnd < segmentEnd && source[runEnd] === "`") runEnd += 1; + const length = runEnd - index; + let list = runsByLength.get(length); + if (!list) { + list = []; + runsByLength.set(length, list); + } + list.push(index); + index = runEnd; + } + }; + + return (openStart: number): number => { + if (openStart >= segmentEnd) indexSegment(openStart); + let runEnd = openStart + 1; + while (runEnd < segmentEnd && source[runEnd] === "`") runEnd += 1; + const tickCount = runEnd - openStart; + const starts = runsByLength.get(tickCount); + if (!starts || starts.length < 2) return -1; + let low = 0; + let high = starts.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (starts[middle]! <= openStart) low = middle + 1; + else high = middle; + } + return low < starts.length ? starts[low]! + tickCount : -1; + }; +} + +interface SpacedFilePathCandidate { + readonly isImage: boolean; + readonly opener: number; + readonly start: number; + readonly end: number; +} + +function* spacedFilePathCandidates( + source: string, + protectedRanges: ReadonlyArray, +): Generator { + if (!hasSpacedDestinationAfterBracket(source)) return; + const inlineCodeSpanEnd = createInlineCodeSpanFinder(source, protectedRanges); + const openBrackets: number[] = []; + const token = /[[\]\\`]|\n[ \t\r]*\n/g; + for (let match = token.exec(source); match; match = token.exec(source)) { + const protectedIndex = firstRangeEndingAfter(protectedRanges, match.index); + if ( + protectedIndex < protectedRanges.length && + protectedRanges[protectedIndex]![0] <= match.index + ) { + openBrackets.length = 0; + token.lastIndex = protectedRanges[protectedIndex]![1]; + continue; + } + const ch = match[0]; + if (ch === "\\") { + token.lastIndex = match.index + 2; + continue; + } + if (ch === "`") { + const codeEnd = inlineCodeSpanEnd(match.index); + if (codeEnd > 0) { + token.lastIndex = codeEnd; + } else { + let runEnd = match.index + 1; + while (source[runEnd] === "`") runEnd += 1; + token.lastIndex = runEnd; + } + continue; + } + if (ch.startsWith("\n")) { + openBrackets.length = 0; + continue; + } + if (ch === "[") { + openBrackets.push(match.index); + continue; + } + const bracketStart = openBrackets.pop(); + if (bracketStart === undefined || source[match.index + 1] !== "(") continue; + let start = match.index + 2; + while (source[start] === " " || source[start] === "\t") start += 1; + const destination = spacedFilePathDestinationEnd(source, start); + if (!destination) continue; + const isImage = + bracketStart > 0 && source[bracketStart - 1] === "!" && !isEscaped(source, bracketStart - 1); + const opener = isImage ? bracketStart - 1 : bracketStart; + yield { isImage, opener, start, end: destination.hrefEnd }; + // Links cannot nest, but an image can sit inside an enclosing link's label. + if (!isImage) openBrackets.length = 0; + token.lastIndex = destination.end; + } +} + +export interface WrappedSpacedFilePaths { + readonly markdown: string; + readonly insertions: readonly number[]; + /** Each wrapped candidate's `[` or `!` offset in the original source. */ + readonly openers: readonly number[]; +} + +export function hasSpacedFilePathCandidate(source: string): boolean { + return hasSpacedDestinationAfterBracket(source); +} + +/** + * Wraps bare local file/media destinations containing spaces in `<...>`, skipping any candidate + * whose opener or destination overlaps a protected range (such as code blocks, HTML comments, or + * already-parsed links/images). + */ +export function wrapSpacedFilePathsInProtectedRanges( + source: string, + protectedRanges: ReadonlyArray, + allowedOpenerRanges?: ReadonlyArray, + protectedLinkRanges?: ReadonlyArray, + inlineProtectedRanges?: ReadonlyArray, + skipOpeners?: ReadonlySet, +): WrappedSpacedFilePaths | undefined { + const mergedProtected = mergeRanges(protectedRanges); + const mergedInlineProtected = inlineProtectedRanges + ? mergeRanges(inlineProtectedRanges) + : undefined; + const mergedAllowed = allowedOpenerRanges ? mergeRanges(allowedOpenerRanges) : undefined; + const mergedProtectedLinks = protectedLinkRanges ? mergeRanges(protectedLinkRanges) : undefined; + const candidates = [...spacedFilePathCandidates(source, mergedProtected)]; + if (candidates.length === 0) return undefined; + + const parts: string[] = []; + const insertions: number[] = []; + const openers: number[] = []; + let writtenTo = 0; + for (const { isImage, opener, start, end } of candidates) { + if ( + start < writtenTo || + skipOpeners?.has(opener) || + (mergedAllowed !== undefined && !containsMergedOffset(mergedAllowed, opener)) || + containsMergedOffset(mergedProtected, opener) || + overlapsMergedRanges(mergedProtected, start, end) || + (mergedInlineProtected !== undefined && + (containsMergedOffset(mergedInlineProtected, opener) || + overlapsMergedRanges(mergedInlineProtected, start, end))) || + (!isImage && + mergedProtectedLinks !== undefined && + overlapsMergedRanges(mergedProtectedLinks, opener, end)) + ) { + continue; + } + parts.push(source.slice(writtenTo, start), "<", source.slice(start, end), ">"); + insertions.push(start + insertions.length, end + insertions.length + 1); + openers.push(opener); + writtenTo = end; + } + if (insertions.length === 0) return undefined; + parts.push(source.slice(writtenTo)); + return { markdown: parts.join(""), insertions, openers }; +} + +/** + * Wraps, reparses, and keeps only wraps that became a link or image, so input the scanner misreads + * (raw HTML, code, or a label broken across blocks) renders as it would without the repair. + */ +export function wrapSpacedFilePathsThatRender( + wrap: (skipOpeners?: ReadonlySet) => WrappedSpacedFilePaths | undefined, + parse: (markdown: string) => T, + renderedStarts: (tree: T) => ReadonlySet, +): (WrappedSpacedFilePaths & { readonly tree: T }) | undefined { + const wrapped = wrap(); + if (!wrapped) return undefined; + const tree = parse(wrapped.markdown); + const starts = renderedStarts(tree); + const original = wrapped.insertions.map((offset, index) => offset - index); + const failed = wrapped.openers.filter((opener) => { + let low = 0; + let high = original.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (original[middle]! <= opener) low = middle + 1; + else high = middle; + } + return !starts.has(opener + low); + }); + if (failed.length === 0) return { ...wrapped, tree }; + const retried = wrap(new Set(failed)); + return retried && { ...retried, tree: parse(retried.markdown) }; +} + +function mdastLinkStarts(tree: Root): ReadonlySet { + const starts = new Set(); + const visit = (node: Root | RootContent) => { + if ( + (node.type === "link" || node.type === "image") && + node.position?.start.offset !== undefined + ) { + starts.add(node.position.start.offset); + } + if ("children" in node) node.children.forEach(visit); + }; + visit(tree); + return starts; +} + +function wrapSpacedFilePaths(source: string, tree: Root, parse: (markdown: string) => Root) { + if (!hasSpacedFilePathCandidate(source)) return undefined; + + const textRanges: OffsetRange[] = []; + const literalRanges: OffsetRange[] = []; + const inlineCodeRanges: OffsetRange[] = []; + const linkRanges: OffsetRange[] = []; + const visit = (node: Root | RootContent) => { + const start = node.position?.start.offset; + const end = node.position?.end.offset; + if ("children" in node) { + if ( + (node.type === "link" || node.type === "linkReference") && + start !== undefined && + end !== undefined + ) { + linkRanges.push([start, end]); + const labelEnd = node.children.at(-1)?.position?.end.offset; + if (labelEnd !== undefined && labelEnd < end) { + literalRanges.push([labelEnd, end]); + } + } + node.children.forEach(visit); + } else if (start !== undefined && end !== undefined) { + if (node.type === "text") textRanges.push([start, end]); + else if (node.type === "inlineCode") inlineCodeRanges.push([start, end]); + else literalRanges.push([start, end]); + } + }; + visit(tree); + + // remark leaves a leading BOM out of its offsets, so scan the text after it. + const bom = source.startsWith("") ? "" : ""; + const body = source.slice(bom.length); + const wrapped = wrapSpacedFilePathsThatRender( + (skipOpeners) => + wrapSpacedFilePathsInProtectedRanges( + body, + literalRanges, + textRanges, + linkRanges, + inlineCodeRanges, + skipOpeners, + ), + (markdown) => parse(bom + markdown), + mdastLinkStarts, + ); + return wrapped && { ...wrapped, markdown: bom + wrapped.markdown }; +} + +export function markdownWithSpacedFilePaths( + source: string, + parse: (markdown: string) => Root, +): string { + if (!hasSpacedFilePathCandidate(source)) return source; + return wrapSpacedFilePaths(source, parse(source), parse)?.markdown ?? source; +} + +export function countSpacedFilePathInsertionsBefore( + insertions: readonly number[], + offset: number, +): number { + let low = 0; + let high = insertions.length; + while (low < high) { + const middle = (low + high) >>> 1; + if (insertions[middle]! < offset) low = middle + 1; + else high = middle; + } + return low; +} + +/** Reparse only when a bare local file/media path needs angle brackets, keeping authored positions. */ +export const remarkSpacedFilePaths: Plugin<[], Root> = function () { + const parse = this.parser; + if (!parse) return; + this.parser = (source, file) => { + const tree = parse(source, file) as Root; + const repaired = wrapSpacedFilePaths(source, tree, (markdown) => parse(markdown, file) as Root); + if (!repaired) return tree; + const { insertions, tree: parsed } = repaired; + const moved = new Set(); + const restorePositions = (node: Root | RootContent) => { + if (node.position) { + for (const point of [node.position.start, node.position.end]) { + if (point.offset === undefined || moved.has(point)) continue; + moved.add(point); + const before = countSpacedFilePathInsertionsBefore(insertions, point.offset); + const beforeLine = countSpacedFilePathInsertionsBefore( + insertions, + point.offset - point.column + 1, + ); + point.offset -= before; + point.column -= before - beforeLine; + } + } + if ("children" in node) node.children.forEach(restorePositions); + }; + restorePositions(parsed); + return parsed; + }; +};