project-doc-site.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /**
  2. * Build-time projection from canonical repository Markdown into VitePress.
  3. *
  4. * The generated tree is disposable: sources stay in their owning `docs/`
  5. * tier, while this adapter rewrites cross-source links for the public site.
  6. */
  7. import {
  8. copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync,
  9. } from 'node:fs'
  10. import { basename, dirname, extname, posix, relative, resolve, sep } from 'node:path'
  11. import { fromMarkdown } from 'mdast-util-from-markdown'
  12. import { gfmFromMarkdown } from 'mdast-util-gfm'
  13. import { gfm } from 'micromark-extension-gfm'
  14. import type { Nodes } from 'mdast'
  15. import { docsPages, type DocsLocale, type DocsPage } from '../website/docs.ts'
  16. const REPOSITORY_URL = 'https://github.com/deepseek-ai/deepseek-harness'
  17. const root = resolve(import.meta.dirname, '..')
  18. const generatedRoot = resolve(root, 'website/.generated')
  19. interface Replacement {
  20. start: number
  21. end: number
  22. value: string
  23. }
  24. interface DestinationRange {
  25. start: number
  26. end: number
  27. }
  28. type RewritableNode = Extract<Nodes, { type: 'link' | 'image' | 'definition' }>
  29. /** Inputs for rewriting one canonical Markdown page. */
  30. export interface RewriteMarkdownOptions {
  31. locale: DocsLocale
  32. sourcePath: string
  33. route: string
  34. pages: DocsPage[]
  35. repoRoot: string
  36. repositoryRef: string
  37. /**
  38. * Place one referenced image beside the projected page and return the URL to
  39. * reach it from that page. A GitHub raw URL cannot serve this repository —
  40. * `raw.githubusercontent.com` answers 404 for a private one, and no reader of
  41. * the site is authenticated to it — so an image travels into the generated
  42. * tree and Vite bundles it like any other site asset. Omitted by callers that
  43. * only rewrite text, which then leave images pointing at the repository.
  44. */
  45. placeImage?: (absPath: string) => string
  46. }
  47. function repoPath(absPath: string, repoRoot: string): string {
  48. return relative(repoRoot, absPath).split(sep).join('/')
  49. }
  50. function isExternalOrSiteAbsolute(url: string): boolean {
  51. return url.startsWith('#')
  52. || url.startsWith('//')
  53. || url.startsWith('/')
  54. || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(url)
  55. }
  56. function skipWhitespace(source: string, start: number): number {
  57. let index = start
  58. while (/\s/.test(source[index] ?? '')) index += 1
  59. return index
  60. }
  61. function labelEnd(source: string): number {
  62. const first = source.indexOf('[')
  63. if (first === -1) return -1
  64. let depth = 0
  65. for (let index = first; index < source.length; index += 1) {
  66. const char = source[index]
  67. if (char === '\\') {
  68. index += 1
  69. } else if (char === '[') {
  70. depth += 1
  71. } else if (char === ']') {
  72. depth -= 1
  73. if (depth === 0) return index
  74. }
  75. }
  76. return -1
  77. }
  78. function destinationRange(rawNode: string, type: 'link' | 'image' | 'definition'): DestinationRange {
  79. const endOfLabel = labelEnd(rawNode)
  80. if (endOfLabel === -1) {
  81. throw new Error(`project-doc-site: cannot locate label end in ${JSON.stringify(rawNode)}.`)
  82. }
  83. let start: number
  84. if (type === 'definition') {
  85. const colon = rawNode.indexOf(':', endOfLabel + 1)
  86. if (colon === -1) {
  87. throw new Error(`project-doc-site: cannot locate definition separator in ${JSON.stringify(rawNode)}.`)
  88. }
  89. start = skipWhitespace(rawNode, colon + 1)
  90. } else {
  91. if (rawNode[endOfLabel + 1] !== '(') {
  92. throw new Error(`project-doc-site: cannot locate inline destination in ${JSON.stringify(rawNode)}.`)
  93. }
  94. start = skipWhitespace(rawNode, endOfLabel + 2)
  95. }
  96. if (rawNode[start] === '<') {
  97. for (let index = start + 1; index < rawNode.length; index += 1) {
  98. if (rawNode[index] === '\\') index += 1
  99. else if (rawNode[index] === '>') return { start: start + 1, end: index }
  100. }
  101. throw new Error(`project-doc-site: cannot locate angle-bracket destination end in ${JSON.stringify(rawNode)}.`)
  102. }
  103. let depth = 0
  104. for (let index = start; index < rawNode.length; index += 1) {
  105. const char = rawNode[index]
  106. if (char === '\\') {
  107. index += 1
  108. } else if (char === '(') {
  109. depth += 1
  110. } else if (char === ')') {
  111. if (depth === 0) return { start, end: index }
  112. depth -= 1
  113. } else if (/\s/.test(char ?? '') && depth === 0) {
  114. return { start, end: index }
  115. }
  116. }
  117. return { start, end: rawNode.length }
  118. }
  119. // `#fragment` suffixes pass through verbatim. Generated cordis-surface
  120. // headings carry explicit `<a id>` anchors with the GitHub slug, so those
  121. // fragments resolve on the published site too; hand-written headings rely on
  122. // VitePress's own slugger, which differs from GitHub's for punctuation-heavy
  123. // text — hand-authored cross-page fragments should prefer plain-text headings
  124. // or explicit anchors.
  125. function splitTarget(url: string): { path: string; suffix: string } {
  126. const boundary = url.search(/[?#]/)
  127. if (boundary === -1) return { path: url, suffix: '' }
  128. return { path: url.slice(0, boundary), suffix: url.slice(boundary) }
  129. }
  130. function decodePath(path: string): string {
  131. try {
  132. return decodeURIComponent(path)
  133. } catch {
  134. throw new Error(`project-doc-site: malformed percent escape in ${JSON.stringify(path)}.`)
  135. }
  136. }
  137. function routeTarget(fromRoute: string, toRoute: string, suffix: string): string {
  138. const target = posix.relative(posix.dirname(fromRoute), toRoute)
  139. return `${target.startsWith('.') ? target : `./${target}`}${suffix}`
  140. }
  141. function sourceMap(pages: DocsPage[]): Map<string, Map<DocsLocale, DocsPage>> {
  142. const map = new Map<string, Map<DocsLocale, DocsPage>>()
  143. for (const page of pages) {
  144. for (const source of [page.source, ...(page.sourceAliases ?? [])]) {
  145. const localized = map.get(source) ?? new Map<DocsLocale, DocsPage>()
  146. if (localized.has(page.locale)) {
  147. throw new Error(`project-doc-site: duplicate source or alias ${JSON.stringify(source)} for locale ${JSON.stringify(page.locale)}.`)
  148. }
  149. localized.set(page.locale, page)
  150. map.set(source, localized)
  151. }
  152. }
  153. return map
  154. }
  155. function counterpartSource(source: string): string {
  156. return source.endsWith('.zh.md')
  157. ? source.replace(/\.zh\.md$/, '.md')
  158. : source.replace(/\.md$/, '.zh.md')
  159. }
  160. function resolveRepositoryTarget(sourceAbs: string, rawPath: string, repoRoot: string): { absPath: string; line?: number } {
  161. const decoded = decodePath(rawPath)
  162. let absPath = resolve(dirname(sourceAbs), decoded)
  163. if (existsSync(absPath)) return { absPath }
  164. const lineMatch = decoded.match(/:(\d+)$/)
  165. if (lineMatch !== null) {
  166. const lineText = lineMatch[1]
  167. if (lineText === undefined) throw new Error('project-doc-site: line suffix matched without a line number.')
  168. absPath = resolve(dirname(sourceAbs), decoded.slice(0, -lineMatch[0].length))
  169. if (existsSync(absPath)) return { absPath, line: Number.parseInt(lineText, 10) }
  170. }
  171. if (extname(decoded) === '') {
  172. const markdown = resolve(dirname(sourceAbs), `${decoded}.md`)
  173. if (existsSync(markdown)) return { absPath: markdown }
  174. const index = resolve(dirname(sourceAbs), decoded, 'index.md')
  175. if (existsSync(index)) return { absPath: index }
  176. }
  177. throw new Error(`project-doc-site: ${repoPath(sourceAbs, repoRoot)} links to missing path ${JSON.stringify(rawPath)}.`)
  178. }
  179. function githubTarget(
  180. absPath: string,
  181. line: number | undefined,
  182. suffix: string,
  183. repositoryRef: string,
  184. repoRoot: string,
  185. image: boolean,
  186. ): string {
  187. const path = repoPath(absPath, repoRoot)
  188. if (image) return `https://raw.githubusercontent.com/deepseek-ai/deepseek-harness/${repositoryRef}/${path}${suffix}`
  189. const kind = lstatSync(absPath).isDirectory() ? 'tree' : 'blob'
  190. const lineSuffix = line === undefined ? suffix : `#L${line}`
  191. return `${REPOSITORY_URL}/${kind}/${repositoryRef}/${path}${lineSuffix}`
  192. }
  193. /**
  194. * Rewrite repository-relative links without reserializing Markdown.
  195. *
  196. * @param source Markdown text from the canonical file.
  197. * @param options Source, route, manifest, and repository context.
  198. * @returns Markdown whose published links resolve inside the site or to GitHub.
  199. */
  200. export function rewriteMarkdown(source: string, options: RewriteMarkdownOptions): string {
  201. const sourceAbs = resolve(options.repoRoot, options.sourcePath)
  202. const published = sourceMap(options.pages)
  203. const tree = fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  204. const replacements: Replacement[] = []
  205. const rewrite = (node: RewritableNode): void => {
  206. if (isExternalOrSiteAbsolute(node.url)) return
  207. const { path, suffix } = splitTarget(node.url)
  208. if (path === '') return
  209. const { absPath, line } = resolveRepositoryTarget(sourceAbs, path, options.repoRoot)
  210. const targetPath = repoPath(absPath, options.repoRoot)
  211. const isLanguageSwitcher = targetPath === counterpartSource(options.sourcePath)
  212. const targetLocale: DocsLocale = isLanguageSwitcher
  213. ? options.locale === 'root' ? 'en' : 'root'
  214. : options.locale
  215. const page = published.get(targetPath)?.get(targetLocale)
  216. const nextUrl = page !== undefined
  217. ? routeTarget(options.route, page.route, suffix)
  218. : node.type === 'image' && options.placeImage !== undefined
  219. // The suffix rides along exactly as the GitHub branch keeps it: an SVG
  220. // view fragment or a Vite query changes what the reference means.
  221. ? `${options.placeImage(absPath)}${suffix}`
  222. : githubTarget(absPath, line, suffix, options.repositoryRef, options.repoRoot, node.type === 'image')
  223. const start = node.position?.start.offset
  224. const end = node.position?.end.offset
  225. if (start === undefined || end === undefined) {
  226. throw new Error(`project-doc-site: link ${JSON.stringify(node.url)} has no source offsets.`)
  227. }
  228. const rawNode = source.slice(start, end)
  229. const rawDestination = destinationRange(rawNode, node.type)
  230. replacements.push({
  231. start: start + rawDestination.start,
  232. end: start + rawDestination.end,
  233. value: nextUrl,
  234. })
  235. }
  236. const visit = (node: Nodes): void => {
  237. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) rewrite(node)
  238. if ('children' in node) {
  239. for (const child of node.children) visit(child)
  240. }
  241. }
  242. visit(tree)
  243. let projected = source
  244. for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
  245. projected = projected.slice(0, replacement.start) + replacement.value + projected.slice(replacement.end)
  246. }
  247. return projected
  248. }
  249. /**
  250. * Record the canonical edit target in VitePress frontmatter.
  251. *
  252. * @param markdown Projected Markdown content.
  253. * @param page Publication manifest entry for the content.
  254. * @returns Markdown with projection-owned frontmatter fields.
  255. */
  256. export function addProjectionFrontmatter(markdown: string, page: Pick<DocsPage, 'source' | 'outline'>): string {
  257. const fields = [
  258. `editSource: ${JSON.stringify(page.source)}`,
  259. ...(page.outline === undefined ? [] : [`outline: ${JSON.stringify(page.outline)}`]),
  260. ].join('\n')
  261. if (markdown.startsWith('---\n')) return markdown.replace('---\n', `---\n${fields}\n`)
  262. return `---\n${fields}\n---\n\n${markdown}`
  263. }
  264. /**
  265. * Select the Markdown rendered for one published page.
  266. *
  267. * @param markdown Rewritten canonical Markdown content.
  268. * @param page Publication manifest entry for the content.
  269. * @returns Full Markdown for ordinary pages or frontmatter-only Markdown for a locale home page.
  270. */
  271. export function projectedPageContent(markdown: string, page: DocsPage): string {
  272. if (page.sidebar !== null) return markdown
  273. if (!markdown.startsWith('---\n')) {
  274. throw new Error(`project-doc-site: locale home source ${JSON.stringify(page.source)} must start with YAML frontmatter.`)
  275. }
  276. const closingDelimiter = '\n---\n'
  277. const closing = markdown.indexOf(closingDelimiter, 4)
  278. if (closing === -1) {
  279. throw new Error(`project-doc-site: locale home source ${JSON.stringify(page.source)} has unclosed YAML frontmatter.`)
  280. }
  281. return markdown.slice(0, closing + closingDelimiter.length)
  282. }
  283. /**
  284. * The repository file one image reference resolves to, or `undefined` when the
  285. * target is not a local file this build may publish.
  286. * @param absPath - resolved image target.
  287. * @param repoRoot - repository root every published image must stay inside.
  288. * @returns the file's real path, or `undefined` when it must not be copied.
  289. *
  290. * Only a regular file whose real path stays inside the repository qualifies.
  291. * Publication copies the bytes into the site, so a reference escaping the
  292. * repository — `../../.ssh/id_rsa`, or a symlink pointing out of the tree —
  293. * would put a build-machine file on the site; `existsSync` alone, which is all
  294. * link resolution needs, does not answer that.
  295. */
  296. export function publishableImage(absPath: string, repoRoot: string): string | undefined {
  297. const real = realpathSync(absPath)
  298. const inside = real === repoRoot || real.startsWith(`${repoRoot}${sep}`)
  299. return inside && statSync(real).isFile() ? real : undefined
  300. }
  301. /** Every local image a published page references, resolved to its repository file. */
  302. function referencedImages(): string[] {
  303. const found = new Set<string>()
  304. for (const page of docsPages) {
  305. const sourceAbs = resolve(root, page.source)
  306. if (!existsSync(sourceAbs)) continue
  307. rewriteMarkdown(readFileSync(sourceAbs, 'utf8'), {
  308. sourcePath: page.source,
  309. locale: page.locale,
  310. route: page.route,
  311. pages: docsPages,
  312. repoRoot: root,
  313. repositoryRef: 'master',
  314. placeImage: (absPath) => {
  315. const real = publishableImage(absPath, root)
  316. if (real !== undefined) found.add(real)
  317. return ''
  318. },
  319. })
  320. }
  321. return [...found]
  322. }
  323. /**
  324. * Files watched by the local VitePress dev server: every canonical Markdown
  325. * source, plus the images they publish. Without the images, replacing a
  326. * screenshot leaves the previous copy in the generated tree until something
  327. * touches the Markdown beside it.
  328. */
  329. export function docsSourceFiles(): string[] {
  330. return [...new Set([...docsPages.map(page => resolve(root, page.source)), ...referencedImages()])]
  331. }
  332. /** Rebuild the disposable VitePress source tree from the publication manifest. */
  333. export function projectDocs(): void {
  334. const routes = new Set<string>()
  335. /** Projected path to the repository file that claimed it, pages and images alike. */
  336. const claimed = new Map<string, string>()
  337. const repositoryRef = process.env.GITHUB_SHA ?? 'master'
  338. rmSync(generatedRoot, { recursive: true, force: true })
  339. /** Reserve one projected path, refusing a second source for it. */
  340. const claim = (target: string, sourceAbs: string): void => {
  341. const holder = claimed.get(target)
  342. if (holder !== undefined && holder !== sourceAbs) {
  343. throw new Error(
  344. `project-doc-site: ${repoPath(sourceAbs, root)} and ${repoPath(holder, root)}`
  345. + ` both project to ${relative(generatedRoot, target).split(sep).join('/')}.`,
  346. )
  347. }
  348. claimed.set(target, sourceAbs)
  349. }
  350. for (const page of docsPages) {
  351. if (routes.has(page.route)) throw new Error(`project-doc-site: duplicate route ${JSON.stringify(page.route)}.`)
  352. routes.add(page.route)
  353. const sourceAbs = resolve(root, page.source)
  354. if (!existsSync(sourceAbs) || !lstatSync(sourceAbs).isFile()) {
  355. throw new Error(`project-doc-site: source ${JSON.stringify(page.source)} does not exist or is not a file.`)
  356. }
  357. const output = resolve(generatedRoot, page.route)
  358. // Claimed before the images are placed: a page and an image landing on one
  359. // path would otherwise overwrite each other in whichever order they ran.
  360. claim(output, sourceAbs)
  361. mkdirSync(dirname(output), { recursive: true })
  362. const markdown = readFileSync(sourceAbs, 'utf8')
  363. const projected = rewriteMarkdown(markdown, {
  364. sourcePath: page.source,
  365. locale: page.locale,
  366. route: page.route,
  367. pages: docsPages,
  368. repoRoot: root,
  369. repositoryRef,
  370. placeImage: (absPath) => {
  371. const real = publishableImage(absPath, root)
  372. if (real === undefined) {
  373. throw new Error(
  374. `project-doc-site: ${page.source} references image ${repoPath(absPath, root)},`
  375. + ' which is not a regular file inside the repository.',
  376. )
  377. }
  378. // Beside the page that references it, under its own basename: each
  379. // locale's route tree gets its own copy, so one relative URL is correct
  380. // from both.
  381. const name = basename(real)
  382. const target = resolve(dirname(output), name)
  383. claim(target, real)
  384. copyFileSync(real, target)
  385. // Encoded because the destination is a Markdown inline target, where an
  386. // unescaped space would end it early.
  387. return `./${encodeURI(name)}`
  388. },
  389. })
  390. writeFileSync(output, addProjectionFrontmatter(projectedPageContent(projected, page), page))
  391. }
  392. }