extract.ts

Raw source
import fs from 'node:fs/promises'
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import MarkdownIt from 'markdown-it'
import { allNavigationItems } from './docs/.vitepress/navigation'
import { languageDefinitions, localeFromPath, localeNames } from './packages/common-locale/src/languages'

interface EnhancedEntry {
  id: string
  title: string
  url: string
  headings: string[]
  anchors: { title: string; url: string }[]
  body: string
}

interface ExtractedHeading {
  title: string
  slug: string
}

async function markdownFiles(dir: string): Promise<string[]> {
  const entries = await fs.readdir(dir, { withFileTypes: true })
  const nested = await Promise.all(entries.map(async (entry) => {
    const absolute = path.join(dir, entry.name)
    if (entry.isDirectory()) {
      if (entry.name === '.vitepress' || entry.name === 'public') return []
      return markdownFiles(absolute)
    }
    return entry.name.endsWith('.md') ? [absolute] : []
  }))
  return nested.flat()
}

function extractTitle(markdown: string, fallback: string): string {
  const frontmatter = markdown.match(/^---[\s\S]*?\ntitle:\s*(.+?)\n[\s\S]*?---/)
  return frontmatter?.[1]?.trim() || markdown.match(/^#\s+(.+)$/m)?.[1]?.replace(/\s+\{#.+\}$/, '') || fallback
}

function slugify(title: string): string {
  return title
    .toLocaleLowerCase()
    .replace(/`+/g, '')
    .replace(/[^\p{Letter}\p{Number}\s-]/gu, '')
    .trim()
    .replace(/\s+/g, '-')
}

function extractHeadings(markdown: string): ExtractedHeading[] {
  // Parse real headings so shell comments and nested Markdown examples do not
  // become search links to anchors that the rendered document never creates.
  const tokens = new MarkdownIt({ html: true }).parse(markdown.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n/, ''), {})
  return tokens.flatMap((token, index) => {
    if (token.type !== 'heading_open') return []
    const raw = tokens[index + 1].content
    const explicit = raw.match(/\s*\{#([^}]+)\}$/)?.[1]
    const title = raw.replace(/\s*\{#[^}]+\}$/, '').replace(/`+/g, '').trim()
    return [{ title, slug: explicit || slugify(title) }]
  })
}

export async function extractDocumentation(root = process.cwd()): Promise<void> {
  const docsRoot = path.join(root, 'docs')
  const publicRoot = path.join(docsRoot, 'public')
  const files = await markdownFiles(docsRoot)
  const legacy: Record<string, string[]> = {}
  const enhanced: EnhancedEntry[] = []

  for (const file of files.sort()) {
    const markdown = await fs.readFile(file, 'utf8')
    const relative = path.relative(docsRoot, file).replace(/\\/g, '/')
    const id = relative.endsWith('/index.md') ? path.basename(path.dirname(file)) : path.basename(file, '.md')
    const url = path.basename(file) === 'index.md'
      ? `/${relative.slice(0, -'index.md'.length)}`
      : `/${relative.replace(/\.md$/, '')}`
    const headings = extractHeadings(markdown)
    // Keep the original Chinese legacy index contract; localized entries belong
    // in the enhanced index, with distinct IDs and real localized URLs.
    const locale = localeFromPath(relative)
    const prefix = languageDefinitions[locale].path
    if (!prefix) legacy[id] = headings.map((heading) => heading.title)
    enhanced.push({
      id: prefix ? `${prefix}/${id}` : id,
      title: extractTitle(markdown, id),
      url,
      headings: headings.map((heading) => heading.title),
      anchors: headings.map((heading) => ({
        title: heading.title,
        url: `${url}#${heading.slug}`,
      })),
      body: markdown
        .replace(/^---[\s\S]*?---/, '')
        .replace(/```[\s\S]*?```/g, '')
        .replace(/[#>*`|_-]/g, ' ')
        .replace(/\s+/g, ' ')
        .trim(),
    })
  }

  const pageUrls = new Set(enhanced.map((entry) => entry.url))
  for (const item of localeNames.flatMap((locale) => allNavigationItems.filter((item) => !/^https?:\/\//.test(item.link)).map((item) => ({ ...item, link: `${languageDefinitions[locale].path ? '/' + languageDefinitions[locale].path : ''}${item.link}` })))) {
    const [pageUrl, slug] = item.link.split('#')
    if (!pageUrls.has(pageUrl)) {
      throw new Error(`Navigation target does not exist: ${item.link}`)
    }
    if (slug && !enhanced.find((entry) => entry.url === pageUrl)?.anchors.some((anchor) => anchor.url === item.link)) {
      throw new Error(`Navigation anchor does not exist: ${item.link}`)
    }
  }
  for (const entry of enhanced) {
    const seen = new Set<string>()
    for (const anchor of entry.anchors) {
      if (seen.has(anchor.url)) {
        throw new Error(`Duplicate documentation anchor: ${anchor.url}`)
      }
      seen.add(anchor.url)
    }
  }

  await fs.mkdir(publicRoot, { recursive: true })
  for (const [name, data] of [
    ['doc-search.json', legacy],
    ['doc-search.enhanced.json', enhanced],
  ] as const) {
    const json = `${JSON.stringify(data, null, 2)}\n`
    await fs.writeFile(path.join(root, name), json)
    await fs.writeFile(path.join(publicRoot, name), json)
  }

  console.log(`Indexed ${files.length} documentation pages.`)
}

if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
  await extractDocumentation()
}