The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { describe, expect, it } from "vite-plus/test"; |
| 2 | import { unified } from "unified"; |
| 3 | import remarkParse from "remark-parse"; |
| 4 | import remarkGfm from "remark-gfm"; |
| 5 | import type { Root, RootContent } from "mdast"; |
| 6 | import { ENRICHED_INLINE_FILE_LINK_REGEX } from "./enrichedLinkPresentation"; |
| 7 | import { |
| 8 | markdownForNativeRendering, |
| 9 | markdownWithInlineFileLinks, |
| 10 | markdownWithHtml, |
| 11 | } from "./markdownDocument"; |
| 12 | |
| 13 | const rewrite = (markdown: string) => |
| 14 | markdownWithInlineFileLinks(markdown, ENRICHED_INLINE_FILE_LINK_REGEX); |
| 15 | |
| 16 | describe("absolute paths in prose", () => { |
| 17 | it("become links without corrupting the source around them", () => { |
| 18 | const path = |
| 19 | "/tmp/claude-1000/-home-user--t3-worktrees-app-t3-abc123/session/scratchpad/notes.md"; |
| 20 | expect(rewrite(`Saved to ${path}.`)).toBe(`Saved to [${path}](<${path}>).`); |
| 21 | expect( |
| 22 | markdownForNativeRendering( |
| 23 | "Intro /tmp/notes.md\n| a | c |\n|---|---|\n| `./a\\|b.ts` | b |", |
| 24 | ENRICHED_INLINE_FILE_LINK_REGEX, |
| 25 | ), |
| 26 | ).toContain("[/tmp/notes.md](</tmp/notes.md>)"); |
| 27 | expect(rewrite(String.raw`See \* and /tmp/notes.md.`)).toBe( |
| 28 | String.raw`See \* and [/tmp/notes.md](</tmp/notes.md>).`, |
| 29 | ); |
| 30 | for (const decoded of [String.raw`See /tmp/a\_b.md.`, "See /tmp/a©.md."]) |
| 31 | expect(rewrite(decoded)).toBe(decoded); |
| 32 | }); |
| 33 | }); |
| 34 | |
| 35 | describe("inline code that names a file", () => { |
| 36 | it.each([ |
| 37 | [ |
| 38 | "file links", |
| 39 | "See `src/math.ts:2`, `C:\\repo\\a.ts`, `./src/a©.ts`, and [`./README.md`](readme).", |
| 40 | ], |
| 41 | [ |
| 42 | "tables", |
| 43 | "Intro `src/math.ts:2`\n| `./README.md` | Fit |\n|---|---|\n| `./a.ts` | A |\n\nMore\n| a |\n|---|\n| b |", |
| 44 | ], |
| 45 | ["escaped pipe in file header", "Intro text\n| `./a\\|b.ts` | c |\n|---|---|\n| a | b |"], |
| 46 | ["escaped pipe in file body", "Intro text\n| a | c |\n|---|---|\n| `./a\\|b.ts` | b |"], |
| 47 | [ |
| 48 | "escaped pipe after a normal file span", |
| 49 | "Intro `./normal.ts`\n| `./a\\|b.ts` | c |\n|---|---|\n| a | b |", |
| 50 | ], |
| 51 | [ |
| 52 | "unmatched delimiter before escaped pipe in header", |
| 53 | "Intro `./normal.ts`\n| `x``./a\\|b.ts`` | c |\n|---|---|\n|a|b|", |
| 54 | ], |
| 55 | [ |
| 56 | "unmatched delimiter before escaped pipe in body", |
| 57 | "Intro `./normal.ts`\n| a | c |\n|---|---|\n| `x``./a\\|b.ts`` | b |", |
| 58 | ], |
| 59 | ["tabbed quote header", ">\tIntro `./a.ts`\n>\t| `./b.ts` | c |\n>\t|---|---|\n>\t| a | b |"], |
| 60 | ["lazy quote header", "> Intro\n`./README.md` | file\n> | - | - |\n> | ok | yes |"], |
| 61 | ["lazy list header", "- Intro\n`./README.md` | file\n | - | - |\n | ok | yes |"], |
| 62 | [ |
| 63 | "HTML", |
| 64 | '<details>\n<summary>Files</summary>\n\nSee `src/math.ts:2`\n| `./README.md` |\n|---|\n| ok |\n<img alt="A & B" src="https://example.com/a.png?a=1&b=2">\n</details>', |
| 65 | ], |
| 66 | [ |
| 67 | "nested fences", |
| 68 | '> - Example\n> ````md\n> ```ts\n> `src/math.ts:2`\n> <img src="literal.png">\n> | a |\n> |---|\n> ```\n> ````\n\nSee `./README.md`.', |
| 69 | ], |
| 70 | [ |
| 71 | "HTML fences", |
| 72 | '<details>\n<summary>Example</summary>\n\n````md\n```html\n<img src="literal.png">\n```\n`src/math.ts`\n````\n\nSee `./README.md`\n</details>', |
| 73 | ], |
| 74 | ])("preserves the two-pass output for every streamed prefix: %s", (_name, fixture) => { |
| 75 | for (const ending of ["\n", "\r\n", "\r"]) { |
| 76 | const document = fixture.replaceAll("\n", ending); |
| 77 | for (let length = 0; length <= document.length; length++) { |
| 78 | const prefix = document.slice(0, length); |
| 79 | const expected = previousTableBreaks( |
| 80 | previousFileLinks(markdownWithHtml(prefix), ENRICHED_INLINE_FILE_LINK_REGEX), |
| 81 | ); |
| 82 | expect( |
| 83 | markdownForNativeRendering(prefix, ENRICHED_INLINE_FILE_LINK_REGEX), |
| 84 | JSON.stringify(prefix), |
| 85 | ).toBe(expected); |
| 86 | } |
| 87 | } |
| 88 | }); |
| 89 | |
| 90 | it("becomes a link to the same path", () => { |
| 91 | expect(rewrite("See `/tmp/claude-1000/...`.")).toBe("See `/tmp/claude-1000/...`."); |
| 92 | expect(rewrite("See `bin/python3.12`.")).toBe("See [bin/python3.12](<bin/python3.12>)."); |
| 93 | expect(rewrite("See `src/math.ts:2` and `./README.md`.")).toBe( |
| 94 | "See [src/math.ts:2](<src/math.ts:2>) and [./README.md](<./README.md>).", |
| 95 | ); |
| 96 | for (const path of [ |
| 97 | "src/數學.ts:2", |
| 98 | "數學/math.ts:2", |
| 99 | "數學.ts:2", |
| 100 | "src/數學.ts:2-4", |
| 101 | "docker/Dockerfile", |
| 102 | "/Users/me/Path Test/notes with spaces.md", |
| 103 | "~/Library/Mobile Documents/notes.md", |
| 104 | ]) { |
| 105 | expect(rewrite(`See \`${path}\`.`), path).toBe(`See [${path}](<${path}>).`); |
| 106 | } |
| 107 | }); |
| 108 | |
| 109 | it("keeps commands, identifiers and URLs as code", () => { |
| 110 | const markdown = |
| 111 | "Run `vp test run`, `/usr/bin/python3 -m venv .venv`, call `useMemo`, open `https://example.com/a.ts`."; |
| 112 | expect(rewrite(markdown)).toBe(markdown); |
| 113 | }); |
| 114 | |
| 115 | it("leaves fenced code blocks and code already inside a link alone", () => { |
| 116 | const markdown = "```\nsrc/math.ts:2\n```\n\n[`src/math.ts`](src/math.ts)"; |
| 117 | expect(rewrite(markdown)).toBe(markdown); |
| 118 | }); |
| 119 | |
| 120 | it("links to the exact path when it holds backslashes or ampersands", () => { |
| 121 | for (const path of ["C:\\repo\\_private\\file.ts", "./src/a©.ts", "./src/[id].ts"]) { |
| 122 | const paragraph = parser.parse(rewrite(`\`${path}\``)).children[0]; |
| 123 | const link = paragraph?.type === "paragraph" ? paragraph.children[0] : undefined; |
| 124 | expect(link?.type === "link" && link.url).toBe(path); |
| 125 | expect( |
| 126 | link?.type === "link" && link.children[0]?.type === "text" && link.children[0].value, |
| 127 | ).toBe(path); |
| 128 | } |
| 129 | }); |
| 130 | }); |
| 131 | |
| 132 | // Freeze the pre-optimization passes so shared transform regressions cannot change the oracle. |
| 133 | const parser = unified().use(remarkParse).use(remarkGfm); |
| 134 | type MarkdownNode = Root | RootContent; |
| 135 | const INLINE_CODE_SPAN = /`+([^`\r\n]+)`+/g; |
| 136 | |
| 137 | function previousFileLinks(markdown: string, fileLink: RegExp): string { |
| 138 | if (![...markdown.matchAll(INLINE_CODE_SPAN)].some(([, code]) => fileLink.test(code!.trim()))) |
| 139 | return markdown; |
| 140 | const edits: Array<{ start: number; end: number; content: string }> = []; |
| 141 | const visit = (node: MarkdownNode) => { |
| 142 | if (node.type === "inlineCode") { |
| 143 | const start = node.position?.start.offset; |
| 144 | const end = node.position?.end.offset; |
| 145 | const escaped = node.value.replace(/[\\[\]&]/g, "\\$&"); |
| 146 | if ( |
| 147 | start !== undefined && |
| 148 | end !== undefined && |
| 149 | fileLink.test(node.value) && |
| 150 | !/[<>]/.test(node.value) |
| 151 | ) |
| 152 | edits.push({ |
| 153 | start, |
| 154 | end, |
| 155 | content: `[${escaped}](<${escaped}>)`, |
| 156 | }); |
| 157 | } else if (node.type !== "link" && node.type !== "linkReference" && "children" in node) |
| 158 | node.children.forEach(visit); |
| 159 | }; |
| 160 | visit(parser.parse(markdown)); |
| 161 | for (const edit of edits.toReversed()) |
| 162 | markdown = markdown.slice(0, edit.start) + edit.content + markdown.slice(edit.end); |
| 163 | return markdown; |
| 164 | } |
| 165 | |
| 166 | // A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item. |
| 167 | function isTableDelimiterRow(line: string): boolean { |
| 168 | if (!line.includes("-")) return false; |
| 169 | const row = line.replace(/^[ \t>]+/, "").trim(); |
| 170 | return row |
| 171 | .replace(/^\||\|$/g, "") |
| 172 | .split("|") |
| 173 | .every((cell) => /^:?-+:?$/.test(cell.trim())); |
| 174 | } |
| 175 | |
| 176 | // Cheap pre-check for a delimiter row two lines below text, so most messages skip the parse. |
| 177 | function mayHaveTableUnderText(markdown: string): boolean { |
| 178 | if (!markdown.includes("|")) return false; |
| 179 | const lines = markdown.split(/\r\n|\r|\n/); |
| 180 | for (let index = 2; index < lines.length; index += 1) { |
| 181 | if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true; |
| 182 | } |
| 183 | return false; |
| 184 | } |
| 185 | |
| 186 | /** |
| 187 | * GFM lets a table interrupt a paragraph, but the native parser (md4c) only starts a table |
| 188 | * on a paragraph's first line, so a table right under a line of text renders as one |
| 189 | * run-on paragraph. Insert the blank line md4c needs before each such table. |
| 190 | */ |
| 191 | function previousTableBreaks(markdown: string): string { |
| 192 | if (!mayHaveTableUnderText(markdown)) return markdown; |
| 193 | const lineStarts: number[] = []; |
| 194 | const visit = (node: MarkdownNode) => { |
| 195 | if (!("children" in node)) return; |
| 196 | node.children.forEach((child, index) => { |
| 197 | const previous = node.children[index - 1]; |
| 198 | const start = child.position?.start; |
| 199 | if ( |
| 200 | child.type === "table" && |
| 201 | previous?.type === "paragraph" && |
| 202 | start?.offset !== undefined && |
| 203 | previous.position?.end.line === start.line - 1 |
| 204 | ) |
| 205 | lineStarts.push( |
| 206 | Math.max( |
| 207 | markdown.lastIndexOf("\n", start.offset - 1), |
| 208 | markdown.lastIndexOf("\r", start.offset - 1), |
| 209 | ) + 1, |
| 210 | ); |
| 211 | visit(child); |
| 212 | }); |
| 213 | }; |
| 214 | visit(parser.parse(markdown)); |
| 215 | for (const lineStart of lineStarts.toReversed()) { |
| 216 | // The header row may be a lazy line without its container markers (`>` or list indent), |
| 217 | // so copy the delimiter row's markers onto the blank line and the header row. |
| 218 | const [, header = "", cells = "", ending = "\n", markers = ""] = |
| 219 | /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? []; |
| 220 | markdown = |
| 221 | markdown.slice(0, lineStart) + |
| 222 | `${markers.trimEnd()}${ending}${markers}${cells}` + |
| 223 | markdown.slice(lineStart + header.length + cells.length); |
| 224 | } |
| 225 | return markdown; |
| 226 | } |