project-doc-site.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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-harness/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. function splitTarget(url: string): { path: string; suffix: string } {
  120. const boundary = url.search(/[?#]/)
  121. if (boundary === -1) return { path: url, suffix: '' }
  122. return { path: url.slice(0, boundary), suffix: url.slice(boundary) }
  123. }
  124. function decodePath(path: string): string {
  125. try {
  126. return decodeURIComponent(path)
  127. } catch {
  128. throw new Error(`project-doc-site: malformed percent escape in ${JSON.stringify(path)}.`)
  129. }
  130. }
  131. function routeTarget(fromRoute: string, toRoute: string, suffix: string): string {
  132. const target = posix.relative(posix.dirname(fromRoute), toRoute)
  133. return `${target.startsWith('.') ? target : `./${target}`}${suffix}`
  134. }
  135. function sourceMap(pages: DocsPage[]): Map<string, Map<DocsLocale, DocsPage>> {
  136. const map = new Map<string, Map<DocsLocale, DocsPage>>()
  137. for (const page of pages) {
  138. for (const source of [page.source, ...(page.sourceAliases ?? [])]) {
  139. const localized = map.get(source) ?? new Map<DocsLocale, DocsPage>()
  140. if (localized.has(page.locale)) {
  141. throw new Error(`project-doc-site: duplicate source or alias ${JSON.stringify(source)} for locale ${JSON.stringify(page.locale)}.`)
  142. }
  143. localized.set(page.locale, page)
  144. map.set(source, localized)
  145. }
  146. }
  147. return map
  148. }
  149. function counterpartSource(source: string): string {
  150. return source.endsWith('.zh.md')
  151. ? source.replace(/\.zh\.md$/, '.md')
  152. : source.replace(/\.md$/, '.zh.md')
  153. }
  154. function resolveRepositoryTarget(sourceAbs: string, rawPath: string, repoRoot: string): { absPath: string; line?: number } {
  155. const decoded = decodePath(rawPath)
  156. let absPath = resolve(dirname(sourceAbs), decoded)
  157. if (existsSync(absPath)) return { absPath }
  158. const lineMatch = decoded.match(/:(\d+)$/)
  159. if (lineMatch !== null) {
  160. const lineText = lineMatch[1]
  161. if (lineText === undefined) throw new Error('project-doc-site: line suffix matched without a line number.')
  162. absPath = resolve(dirname(sourceAbs), decoded.slice(0, -lineMatch[0].length))
  163. if (existsSync(absPath)) return { absPath, line: Number.parseInt(lineText, 10) }
  164. }
  165. if (extname(decoded) === '') {
  166. const markdown = resolve(dirname(sourceAbs), `${decoded}.md`)
  167. if (existsSync(markdown)) return { absPath: markdown }
  168. const index = resolve(dirname(sourceAbs), decoded, 'index.md')
  169. if (existsSync(index)) return { absPath: index }
  170. }
  171. throw new Error(`project-doc-site: ${repoPath(sourceAbs, repoRoot)} links to missing path ${JSON.stringify(rawPath)}.`)
  172. }
  173. function githubTarget(
  174. absPath: string,
  175. line: number | undefined,
  176. suffix: string,
  177. repositoryRef: string,
  178. repoRoot: string,
  179. image: boolean,
  180. ): string {
  181. const path = repoPath(absPath, repoRoot)
  182. if (image) return `https://raw.githubusercontent.com/deepseek-harness/deepseek-harness/${repositoryRef}/${path}${suffix}`
  183. const kind = lstatSync(absPath).isDirectory() ? 'tree' : 'blob'
  184. const lineSuffix = line === undefined ? suffix : `#L${line}`
  185. return `${REPOSITORY_URL}/${kind}/${repositoryRef}/${path}${lineSuffix}`
  186. }
  187. /**
  188. * Rewrite repository-relative links without reserializing Markdown.
  189. *
  190. * @param source Markdown text from the canonical file.
  191. * @param options Source, route, manifest, and repository context.
  192. * @returns Markdown whose published links resolve inside the site or to GitHub.
  193. */
  194. export function rewriteMarkdown(source: string, options: RewriteMarkdownOptions): string {
  195. const sourceAbs = resolve(options.repoRoot, options.sourcePath)
  196. const published = sourceMap(options.pages)
  197. const tree = fromMarkdown(source, { extensions: [gfm()], mdastExtensions: [gfmFromMarkdown()] })
  198. const replacements: Replacement[] = []
  199. const rewrite = (node: RewritableNode): void => {
  200. if (isExternalOrSiteAbsolute(node.url)) return
  201. const { path, suffix } = splitTarget(node.url)
  202. if (path === '') return
  203. const { absPath, line } = resolveRepositoryTarget(sourceAbs, path, options.repoRoot)
  204. const targetPath = repoPath(absPath, options.repoRoot)
  205. const isLanguageSwitcher = targetPath === counterpartSource(options.sourcePath)
  206. const targetLocale: DocsLocale = isLanguageSwitcher
  207. ? options.locale === 'root' ? 'en' : 'root'
  208. : options.locale
  209. const page = published.get(targetPath)?.get(targetLocale)
  210. const nextUrl = page !== undefined
  211. ? routeTarget(options.route, page.route, suffix)
  212. : node.type === 'image' && options.placeImage !== undefined
  213. // The suffix rides along exactly as the GitHub branch keeps it: an SVG
  214. // view fragment or a Vite query changes what the reference means.
  215. ? `${options.placeImage(absPath)}${suffix}`
  216. : githubTarget(absPath, line, suffix, options.repositoryRef, options.repoRoot, node.type === 'image')
  217. const start = node.position?.start.offset
  218. const end = node.position?.end.offset
  219. if (start === undefined || end === undefined) {
  220. throw new Error(`project-doc-site: link ${JSON.stringify(node.url)} has no source offsets.`)
  221. }
  222. const rawNode = source.slice(start, end)
  223. const rawDestination = destinationRange(rawNode, node.type)
  224. replacements.push({
  225. start: start + rawDestination.start,
  226. end: start + rawDestination.end,
  227. value: nextUrl,
  228. })
  229. }
  230. const visit = (node: Nodes): void => {
  231. if ((node.type === 'link' || node.type === 'image' || node.type === 'definition') && 'url' in node) rewrite(node)
  232. if ('children' in node) {
  233. for (const child of node.children) visit(child)
  234. }
  235. }
  236. visit(tree)
  237. let projected = source
  238. for (const replacement of replacements.sort((a, b) => b.start - a.start)) {
  239. projected = projected.slice(0, replacement.start) + replacement.value + projected.slice(replacement.end)
  240. }
  241. return projected
  242. }
  243. /**
  244. * Record the canonical edit target in VitePress frontmatter.
  245. *
  246. * @param markdown Projected Markdown content.
  247. * @param page Publication manifest entry for the content.
  248. * @returns Markdown with projection-owned frontmatter fields.
  249. */
  250. export function addProjectionFrontmatter(markdown: string, page: Pick<DocsPage, 'source' | 'outline'>): string {
  251. const fields = [
  252. `editSource: ${JSON.stringify(page.source)}`,
  253. ...(page.outline === undefined ? [] : [`outline: ${JSON.stringify(page.outline)}`]),
  254. ].join('\n')
  255. if (markdown.startsWith('---\n')) return markdown.replace('---\n', `---\n${fields}\n`)
  256. return `---\n${fields}\n---\n\n${markdown}`
  257. }
  258. /**
  259. * Select the Markdown rendered for one published page.
  260. *
  261. * @param markdown Rewritten canonical Markdown content.
  262. * @param page Publication manifest entry for the content.
  263. * @returns Full Markdown for ordinary pages or frontmatter-only Markdown for a locale home page.
  264. */
  265. export function projectedPageContent(markdown: string, page: DocsPage): string {
  266. if (page.sidebar !== null) return markdown
  267. if (!markdown.startsWith('---\n')) {
  268. throw new Error(`project-doc-site: locale home source ${JSON.stringify(page.source)} must start with YAML frontmatter.`)
  269. }
  270. const closingDelimiter = '\n---\n'
  271. const closing = markdown.indexOf(closingDelimiter, 4)
  272. if (closing === -1) {
  273. throw new Error(`project-doc-site: locale home source ${JSON.stringify(page.source)} has unclosed YAML frontmatter.`)
  274. }
  275. return markdown.slice(0, closing + closingDelimiter.length)
  276. }
  277. /**
  278. * The repository file one image reference resolves to, or `undefined` when the
  279. * target is not a local file this build may publish.
  280. * @param absPath - resolved image target.
  281. * @param repoRoot - repository root every published image must stay inside.
  282. * @returns the file's real path, or `undefined` when it must not be copied.
  283. *
  284. * Only a regular file whose real path stays inside the repository qualifies.
  285. * Publication copies the bytes into the site, so a reference escaping the
  286. * repository — `../../.ssh/id_rsa`, or a symlink pointing out of the tree —
  287. * would put a build-machine file on the site; `existsSync` alone, which is all
  288. * link resolution needs, does not answer that.
  289. */
  290. export function publishableImage(absPath: string, repoRoot: string): string | undefined {
  291. const real = realpathSync(absPath)
  292. const inside = real === repoRoot || real.startsWith(`${repoRoot}${sep}`)
  293. return inside && statSync(real).isFile() ? real : undefined
  294. }
  295. /** Every local image a published page references, resolved to its repository file. */
  296. function referencedImages(): string[] {
  297. const found = new Set<string>()
  298. for (const page of docsPages) {
  299. const sourceAbs = resolve(root, page.source)
  300. if (!existsSync(sourceAbs)) continue
  301. rewriteMarkdown(readFileSync(sourceAbs, 'utf8'), {
  302. sourcePath: page.source,
  303. locale: page.locale,
  304. route: page.route,
  305. pages: docsPages,
  306. repoRoot: root,
  307. repositoryRef: 'master',
  308. placeImage: (absPath) => {
  309. const real = publishableImage(absPath, root)
  310. if (real !== undefined) found.add(real)
  311. return ''
  312. },
  313. })
  314. }
  315. return [...found]
  316. }
  317. /**
  318. * Files watched by the local VitePress dev server: every canonical Markdown
  319. * source, plus the images they publish. Without the images, replacing a
  320. * screenshot leaves the previous copy in the generated tree until something
  321. * touches the Markdown beside it.
  322. */
  323. export function docsSourceFiles(): string[] {
  324. return [...new Set([...docsPages.map(page => resolve(root, page.source)), ...referencedImages()])]
  325. }
  326. /** Rebuild the disposable VitePress source tree from the publication manifest. */
  327. export function projectDocs(): void {
  328. const routes = new Set<string>()
  329. /** Projected path to the repository file that claimed it, pages and images alike. */
  330. const claimed = new Map<string, string>()
  331. const repositoryRef = process.env.GITHUB_SHA ?? 'master'
  332. rmSync(generatedRoot, { recursive: true, force: true })
  333. /** Reserve one projected path, refusing a second source for it. */
  334. const claim = (target: string, sourceAbs: string): void => {
  335. const holder = claimed.get(target)
  336. if (holder !== undefined && holder !== sourceAbs) {
  337. throw new Error(
  338. `project-doc-site: ${repoPath(sourceAbs, root)} and ${repoPath(holder, root)}`
  339. + ` both project to ${relative(generatedRoot, target).split(sep).join('/')}.`,
  340. )
  341. }
  342. claimed.set(target, sourceAbs)
  343. }
  344. for (const page of docsPages) {
  345. if (routes.has(page.route)) throw new Error(`project-doc-site: duplicate route ${JSON.stringify(page.route)}.`)
  346. routes.add(page.route)
  347. const sourceAbs = resolve(root, page.source)
  348. if (!existsSync(sourceAbs) || !lstatSync(sourceAbs).isFile()) {
  349. throw new Error(`project-doc-site: source ${JSON.stringify(page.source)} does not exist or is not a file.`)
  350. }
  351. const output = resolve(generatedRoot, page.route)
  352. // Claimed before the images are placed: a page and an image landing on one
  353. // path would otherwise overwrite each other in whichever order they ran.
  354. claim(output, sourceAbs)
  355. mkdirSync(dirname(output), { recursive: true })
  356. const markdown = readFileSync(sourceAbs, 'utf8')
  357. const projected = rewriteMarkdown(markdown, {
  358. sourcePath: page.source,
  359. locale: page.locale,
  360. route: page.route,
  361. pages: docsPages,
  362. repoRoot: root,
  363. repositoryRef,
  364. placeImage: (absPath) => {
  365. const real = publishableImage(absPath, root)
  366. if (real === undefined) {
  367. throw new Error(
  368. `project-doc-site: ${page.source} references image ${repoPath(absPath, root)},`
  369. + ' which is not a regular file inside the repository.',
  370. )
  371. }
  372. // Beside the page that references it, under its own basename: each
  373. // locale's route tree gets its own copy, so one relative URL is correct
  374. // from both.
  375. const name = basename(real)
  376. const target = resolve(dirname(output), name)
  377. claim(target, real)
  378. copyFileSync(real, target)
  379. // Encoded because the destination is a Markdown inline target, where an
  380. // unescaped space would end it early.
  381. return `./${encodeURI(name)}`
  382. },
  383. })
  384. writeFileSync(output, addProjectionFrontmatter(projectedPageContent(projected, page), page))
  385. }
  386. }