Files
apes-sidebar/tests/markdown-images.spec.ts
T
Menghuan1918 fab329d469 fix(markdown): match GitHub's heading slug and mask ~~~ fences (#363)
Two defects the independent verification rejected, plus the test gaps they
left behind.

1. `githubHeadingSlug` was not GitHub's slugger. It trimmed and collapsed
   whitespace runs (GitHub does neither: every space becomes its own dash) and
   kept `\p{M}`, which left the variation selector of `🖼️` inside the id. The
   consequence was the issue's main scenario: the repo's OWN READMEs resolved
   **0 of 15** table-of-contents anchors, and the click was claimed yet did
   nothing (`scrollTop` stayed 0). The slug is now `toLowerCase()`, drop
   pictographs / `\uFE00-\uFE0F` / regional indicators / `\p{C}`, drop
   everything that is not a letter, digit, combining mark, space, `-` or `_`,
   then each space → `-`. Emoji are removed here because GitHub removes them
   while RENDERING the heading (to `<img>`) before its slugger runs; that is
   the one deliberate difference from `github-slugger`, and it is what turns
   `🚀 安装` into GitHub's real `-安装`.

2. Both source rewriters inlined a fence mask that only recognised ```, so a
   link or image demonstrated inside a `~~~` fence was rewritten
   (`[y](./b.md#u)` → `[y](./b.md%23u)`; the image half predates this feature:
   `rewriteLocalImageUrls('~~~\n![i](./p.png)\n~~~')` already produced a
   `/sidebar/file` URL on 58d7f71). One shared mask now lives in
   `src/client/markdown-code.ts` (CommonMark: 3+ backticks OR 3+ tildes, a
   closing fence no shorter than its opener, an unclosed fence running to the
   end of the text) and both passes use it.

Evidence (all on the merged tree, HEAD after `git merge origin/dev`):
- Real `TextEditor` + real host `MarkdownText`, every TOC anchor clicked:
  README.md `0/15 → 15/15`, README_EN.md `0/15 → 15/15` (shipped as a case in
  tests/markdown-surface.spec.tsx; the id-level counts are 0/16 → 16/16).
- Parity against the actual `github-slugger@2.0.0` regex (vendored in
  tests/helpers/github-slug-reference.ts), plus explicit emoji/VS16 cases.
- Mutation: restoring the old trim+collapse+`\p{M}` slug reddens 9 cases
  (both README cases included); dropping the tilde fence reddens the new
  fence case in BOTH the link and the image spec; forcing `scrollHostFor` to
  return the container reddens the two new ancestor-scroller cases.
- `scrollHostFor`'s ancestor branch was unreachable from the shipped suite
  (the mutation above used to leave 33/33 green): tests/markdown-surface.spec.tsx
  now injects the computed style (`overflowY: auto` + `scrollHeight`/
  `clientHeight`) and asserts the write lands on the ancestor, that neither
  `window.scrollTo` nor `scrollIntoView` is called, and that the container's
  own `scrollTop` is never written.

Also: the untrue "exactly like GitHub does" comment, four-form fence cases per
pass (``` / ```` / ~~~ / an inline span inside ~~~), a CHANGELOG entry, and the
recorded narrow edges (a destination with an escaped parenthesis or a
single-quoted title is not claimed — plain text, unchanged; `#L24` does not
jump to a line).

Gates: typecheck / lint clean, `vitest run --maxWorkers=3` 182 files, 2120
passed | 13 skipped; `pnpm build` complete; mount lane
(`DSH_CMD='npx -y --package @deepseek-ai/dsh@0.2.0-rc.1 dsh' pnpm test:mount`)
9 passed (2.0m), exit 0. The bare `pnpm test:mount` now dies in preflight
because the installed CLI is 0.2.0-rc.2 while the baseline pins 0.2.0-rc.1;
the lane count is 9 rather than the verifier's 11 because merging origin/dev
removed the two WCO/preset cases with the titleBar mechanism.
2026-10-06 00:19:11 +08:00

130 lines
6.5 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { rewriteLocalImageUrls } from '../src/client/markdown-images.ts'
import type { SessionScope } from '../src/client/api.ts'
const ORIGIN = 'http://127.0.0.1:3080'
const scope: SessionScope = { sessionId: 'abc', cwd: '/repo' }
describe('rewriteLocalImageUrls', () => {
it('resolves relative destinations against the opened file directory', () => {
const md = '![a](./img.png)\n![b](images/b.jpg)'
const out = rewriteLocalImageUrls(md, scope, '/repo/docs/readme.md', ORIGIN)
expect(out).toContain(`![a](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fimg.png&cwd=%2Frepo)`)
expect(out).toContain(`![b](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fimages%2Fb.jpg&cwd=%2Frepo)`)
})
it('expects the rewritten destination to be an absolute http URL MarkdownText accepts', () => {
const out = rewriteLocalImageUrls('![a](./img.png)', scope, '/repo/readme.md', ORIGIN)
const url = out.match(/\]\((http[^)]+)\)/)?.[1]
expect(url).toBeDefined()
expect(new URL(url as string).protocol).toBe('http:')
})
it('passes absolute local paths through unchanged', () => {
const md = '![a](/repo/assets/b.png)'
const out = rewriteLocalImageUrls(md, scope, '/repo/docs/readme.md', ORIGIN)
expect(out).toContain(`![a](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fassets%2Fb.png&cwd=%2Frepo)`)
})
it('keeps remote http(s)/data/mailto destinations untouched', () => {
const md = '![a](https://example.com/x.jpg)\n![b](http://e.com/y.png)\n![c](data:image/png;base64,AAA)'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain('![a](https://example.com/x.jpg)')
expect(out).toContain('![b](http://e.com/y.png)')
expect(out).toContain('![c](data:image/png;base64,AAA)')
})
it('leaves in-page anchors untouched', () => {
const md = '![a](#section)\n\n[link](#top)'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain('![a](#section)')
})
it('rewrites reference-style image definitions', () => {
const md = '![logo][logo]\n\n[logo]: ./logo.svg'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain(`[logo]: ${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Flogo.svg&cwd=%2Frepo`)
// The inline reference itself is left for MarkdownText to combine.
expect(out).toContain('![logo][logo]')
})
it('normalizes `.`/`..` segments in relative destinations', () => {
const md = '![a](./img.png)\n![b](../assets/b.png)'
const out = rewriteLocalImageUrls(md, scope, '/repo/docs/sub/readme.md', ORIGIN)
expect(out).toContain(`![a](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fsub%2Fimg.png&cwd=%2Frepo)`)
expect(out).toContain(`![b](${ORIGIN}/sidebar/file?sessionId=abc&path=%2Frepo%2Fdocs%2Fassets%2Fb.png&cwd=%2Frepo)`)
expect(out).not.toContain('/.')
})
it('drops the cwd param when the scope has no cwd', () => {
const out = rewriteLocalImageUrls('![a](./img.png)', { sessionId: 'abc' }, '/repo/readme.md', ORIGIN)
expect(out).toContain(`sessionId=abc&path=%2Frepo%2Fimg.png`)
expect(out).not.toContain('cwd=')
})
it('handles windows absolute paths as local (not remote)', () => {
const md = '![a](C:\\repo\\img.png)'
const out = rewriteLocalImageUrls(md, scope, 'C:\\repo\\docs\\readme.md', ORIGIN)
// A Windows drive path is absolute (not a remote scheme) → rewritten.
const url = out.match(/\]\(([^)]+)\)/)?.[1] as string
expect(url).toContain('/sidebar/file?')
expect(decodeURIComponent(url)).toContain('C:\\repo\\img.png')
})
it('does not rewrite image-looking text inside fenced code blocks', () => {
const md = '```\n![alt](./img.png)\n```\n![real](./real.png)'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
// The fenced example must be preserved verbatim; only the real image is rewritten.
expect(out).toContain('```\n![alt](./img.png)\n```')
expect(out).toContain('/sidebar/file?')
})
it('does not rewrite image-looking text inside inline code spans', () => {
const md = 'Use `![alt](./img.png)` syntax.\n![real](./real.png)'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain('`![alt](./img.png)`')
expect(out).toContain('/sidebar/file?')
})
it('leaves every code-region form alone, tilde fences included', () => {
// The image pass had the SAME `~~~` blind spot as the link pass, and it
// predates this feature: on the 58d7f71 baseline
// `rewriteLocalImageUrls('~~~\n![i](./p.png)\n~~~')` already produced a
// `/sidebar/file` URL. Both passes now share one fence mask
// (`markdown-code.ts`).
const forms = [
'```\n![i](./p.png)\n```',
'````\n```\n![i](./p.png)\n```\n````',
'~~~\n![i](./p.png)\n~~~',
'~~~\nuse `![i](./p.png)` here\n~~~',
]
for (const form of forms) {
const out = rewriteLocalImageUrls(form, scope, '/repo/readme.md', ORIGIN)
expect(out, form).toBe(form)
expect(out, form).not.toContain('/sidebar/file')
}
// A longer closing fence closes, and a real image after it is rewritten.
const after = rewriteLocalImageUrls('~~~\n![i](./p.png)\n~~~~\n\n![real](./real.png)', scope, '/repo/readme.md', ORIGIN)
expect(after).toContain('~~~\n![i](./p.png)\n~~~~')
expect(after).toMatch(/\[real\]\(.*\/sidebar\/file/)
// An unclosed fence runs to the end of the document.
expect(rewriteLocalImageUrls('~~~\n![i](./p.png)', scope, '/repo/readme.md', ORIGIN))
.toBe('~~~\n![i](./p.png)')
// A reference definition inside the fence is not harvested either.
const ref = rewriteLocalImageUrls('~~~\n![i][r]\n\n[r]: ./p.png\n~~~', scope, '/repo/readme.md', ORIGIN)
expect(ref).toBe('~~~\n![i][r]\n\n[r]: ./p.png\n~~~')
})
it('does not rewrite a reference definition used only by a plain link', () => {
// The `[manual][docs]` link references `[docs]: ./docs.md`, but that
// definition must NOT be redirected to /sidebar/file because it is not
// referenced by any image. Only image-referenced definitions are rewritten.
const md = '[manual][docs]\n\n![pic][pic-def]\n\n[docs]: ./docs.md\n[pic-def]: ./pic.png'
const out = rewriteLocalImageUrls(md, scope, '/repo/readme.md', ORIGIN)
expect(out).toContain('[docs]: ./docs.md')
expect(out).not.toMatch(/\[docs\]:.*\/sidebar\/file/)
// The image-referenced definition IS rewritten.
expect(out).toMatch(/\[pic-def\]:.*\/sidebar\/file/)
})
})