@clarify-labs/cli 0.11.5 → 0.11.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/output/cli.cjs +1 -1
- package/output/cli.js +1 -1
- package/output/{engine-DuiJVdO8.js → engine-Cuwx3aJ2.js} +2 -2
- package/output/{engine-DuiJVdO8.js.map → engine-Cuwx3aJ2.js.map} +1 -1
- package/output/{engine-VgAP_Ms6.cjs → engine-DVw8CV5R.cjs} +2 -2
- package/output/{engine-VgAP_Ms6.cjs.map → engine-DVw8CV5R.cjs.map} +1 -1
- package/output/index.cjs +1 -1
- package/output/index.js +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine-DuiJVdO8.js","names":[],"sources":["../source/parsers/content/diagnostic.ts","../source/parsers/markdown/mdx.ts","../source/core/runtime/module-ids.ts","../source/core/plugin/hooks.ts","../source/parsers/markdown/frontmatter.ts","../source/parsers/content/content.ts","../source/parsers/markdown/markdown.ts","../source/parsers/routes/routes.ts","../source/parsers/router/dev-routes.ts","../source/parsers/theme.ts","../source/core/config/config-schema.ts","../source/core/config/config.ts","../source/core/config/user-config.ts","../source/core/project/project-info.ts","../source/core/runtime/virtual-modules.ts","../source/core/adapters.ts","../package.json","../source/cli/package.ts","../source/core/config/options.ts","../source/plugins/content-artifacts/artifacts.ts","../source/plugins/content-artifacts/server.ts","../source/plugins/content-artifacts/index.ts","../source/plugins/html-shell/index.ts","../source/plugins/mcp-search/mcp-config.ts","../source/plugins/mcp-search/orama-index.ts","../source/plugins/mcp-search/index.ts","../source/plugins/openapi/parser.ts","../source/plugins/openapi/routes.ts","../source/plugins/openapi/virtual-modules.ts","../source/plugins/openapi/state.ts","../source/plugins/openapi/index.ts","../source/core/project/temp-dir.ts","../source/plugins/page-search/search-language.ts","../source/plugins/page-search/index.ts","../source/plugins/seo/artifacts.ts","../source/plugins/seo/index.ts","../source/plugins/source-links/source-links.ts","../source/plugins/source-links/index.ts","../source/plugins/variables/index.ts","../source/core/plugin/builtin.ts","../source/core/plugin/manager.ts","../source/core/project/project-context.ts","../source/core/routing/route-analysis.ts","../source/core/routing/route-resolution.ts","../source/core/runtime/env-types.ts","../source/parsers/markdown/utils.ts","../source/core/runtime/html-template.ts","../source/core/runtime/runtime-deps.ts","../source/core/runtime/ssg.ts","../source/core/runtime/startup.ts","../source/core/engine/context.ts","../source/core/engine/phases.ts","../source/core/engine/engine.ts"],"sourcesContent":["import { isAbsolute, relative } from 'node:path'\n\nimport type { ContentDiagnostic } from '@clarify-labs/renderer'\n\ntype CreateContentDiagnosticOptions = {\n kind: ContentDiagnostic['kind']\n title: string\n message: string\n error: unknown\n filePath?: string\n projectRoot?: string\n includeStack?: boolean\n}\n\nfunction displayPath(filePath: string | undefined, projectRoot: string | undefined): string | undefined {\n if (!filePath) return undefined\n if (!projectRoot) return filePath.replace(/^[A-Za-z]:\\//, '').replace(/^\\/+/, '')\n\n const normalized = relative(projectRoot, filePath)\n return normalized && !normalized.startsWith('..') && !isAbsolute(normalized)\n ? normalized\n : filePath.replace(/^[A-Za-z]:\\//, '').replace(/^\\/+/, '')\n}\n\nexport function createContentDiagnostic(options: CreateContentDiagnosticOptions): ContentDiagnostic {\n const { error } = options\n return {\n kind: options.kind,\n title: options.title,\n message: options.message,\n filePath: displayPath(options.filePath, options.projectRoot),\n details: error instanceof Error\n ? options.includeStack ? error.stack ?? error.message : error.message\n : String(error),\n }\n}\n","import { compile, type CompileOptions } from '@mdx-js/mdx'\nimport rehypeShiki from '@shikijs/rehype'\nimport rehypeSlug from 'rehype-slug'\nimport { createCssVariablesTheme } from 'shiki'\nimport { visit } from 'unist-util-visit'\n\nimport { markdownRemarkPlugins, parseCodeMeta } from '@clarify-labs/renderer'\n\nimport type { ContentDiagnostic } from '../../types.js'\nimport { createContentDiagnostic } from '../content/diagnostic.js'\n\ntype HastNode = {\n type: string\n tagName?: string\n value?: string\n properties?: Record<string, unknown>\n children?: HastNode[]\n}\n\ntype HastParent = HastNode & {\n children: HastNode[]\n}\n\nfunction getLanguage(className: unknown): string {\n const classes = Array.isArray(className) ? className : typeof className === 'string' ? className.split(/\\s+/) : []\n const languageClass = classes.find((item): item is string => typeof item === 'string' && item.startsWith('language-'))\n return languageClass?.replace(/^language-/, '') || 'txt'\n}\n\nconst cssVariablesTheme = createCssVariablesTheme()\n\nexport function rehypeParseCodeBlocks() {\n return (tree: HastNode) => {\n visit(tree, 'element', (node: HastNode, _nodeIndex: number | undefined, parentNode: HastParent | undefined) => {\n if (node.tagName !== 'code' || !parentNode) return\n parentNode.properties = parentNode.properties ?? {}\n node.properties = node.properties ?? {}\n const language = getLanguage(node.properties.className)\n parentNode.properties.language = language\n node.properties.language = language\n\n for (const key of ['title', 'tag', 'label']) {\n if (node.properties[key] !== undefined) parentNode.properties[key] = node.properties[key]\n }\n })\n }\n}\n\nexport const remarkPlugins: unknown[] = markdownRemarkPlugins\nexport const rehypePlugins: NonNullable<CompileOptions['rehypePlugins']> = [\n rehypeSlug,\n rehypeParseCodeBlocks,\n [rehypeShiki, {\n theme: cssVariablesTheme,\n langs: [],\n lazy: true,\n addLanguageClass: true,\n fallbackLanguage: 'text',\n parseMetaString: parseCodeMeta,\n }],\n]\n\ntype ContentCompileDiagnosticOptions = {\n format: 'markdown' | 'markdown+jsx'\n phase: 'syntax' | 'compilation'\n error: unknown\n filePath?: string\n projectRoot?: string\n}\n\nexport function createContentCompileDiagnostic(options: ContentCompileDiagnosticOptions): ContentDiagnostic {\n const { format, phase, error, filePath, projectRoot } = options\n const label = format === 'markdown+jsx' ? 'MDX' : 'Markdown'\n return createContentDiagnostic({\n kind: format,\n title: `${label} ${phase} error`,\n message: phase === 'syntax'\n ? `This page could not be compiled. Fix the ${label} syntax or component usage above, then reload the route.`\n : `This page could not be compiled. Fix the ${label} syntax or plugin error below, then reload the route.`,\n error,\n filePath,\n projectRoot,\n includeStack: phase === 'compilation',\n })\n}\n\ntype CompileContentOptions = {\n filePath?: string\n projectRoot?: string\n}\n\n/**\n * Validate MDX content for diagnostics WITHOUT running the build-time rehype\n * pipeline (Shiki highlighting, slug injection, code-block parsing).\n *\n * `rehypePlugins` includes `rehypeShiki`, which loads grammar/WASM assets and\n * is expensive. The real highlighting happens at Vite build time via the\n * `@mdx-js/rollup` plugin (see `createContentCompilerPlugin` in\n * `core/adapters.ts`), which runs the full remark + rehype pipeline.\n * Re-running it here, during route discovery (Phase 3), would compile every\n * `.mdx` file twice and invoke Shiki once per file per `engine.refresh()` -\n * see ARCHITECTURE.md §2.2 which states \"不应在 core 中执行代码高亮\".\n *\n * The remark pipeline still runs (shared with the Vite plugin via\n * `remarkPlugins`), so MDX/JSX syntax errors - the only class of error this\n * diagnostic is meant to surface ahead of the Vite build - are caught. The\n * output is discarded; only the thrown error is used.\n *\n * `.md` files are handled by `compileMarkdownContent` in `markdown.ts`, which\n * mirrors the adapter's markdown compiler semantics (`format: 'md'`, raw HTML\n * allowed). Keep the two compilers separate so each format can evolve its own\n * diagnostic rules without contaminating the other.\n */\nexport async function compileMdxContent(content: string, options: CompileContentOptions = {}): Promise<{ ok: true } | { ok: false; diagnostic: ContentDiagnostic }> {\n const { filePath, projectRoot } = options\n try {\n await compile(content, {\n jsx: true,\n providerImportSource: '@clarify-labs/renderer',\n remarkPlugins: remarkPlugins as CompileOptions['remarkPlugins'],\n // NOTE: `rehypePlugins` intentionally omitted. See JSDoc above.\n })\n return { ok: true }\n } catch (error) {\n return {\n ok: false,\n diagnostic: createContentCompileDiagnostic({ format: 'markdown+jsx', phase: 'syntax', error, filePath, projectRoot }),\n }\n }\n}\n","import { isAbsolute, relative } from 'node:path'\n\nconst PAGE_PREFIX = 'virtual:clarify-page/'\nconst CONTENT_PREFIX = 'virtual:clarify-content/'\n\nexport function pageVirtualModuleId(path: string): string {\n const normalized = path\n .replace(/^\\/+/, '')\n .replace(/\\/index$/, '')\n .replace(/\\/+/g, '/')\n return `${PAGE_PREFIX}${normalized || 'index'}`\n}\n\nexport function pageVirtualModuleIdFromRef(ref: string): string {\n return pageVirtualModuleId(ref\n .replace(/\\.mdx?$/, '')\n .replace(/\\.openapi\\.(json|yaml|yml)$/, ''))\n}\n\nexport function isPageVirtualModuleId(id: string): boolean {\n return id.startsWith(PAGE_PREFIX)\n}\n\nexport function pageVirtualModulePath(id: string): string {\n return isPageVirtualModuleId(id) ? id.slice(PAGE_PREFIX.length) : id\n}\n\nexport function contentVirtualModuleId(filePath: string, contentRoot: string): string {\n const sourcePath = relative(contentRoot, filePath).replace(/\\\\/g, '/')\n if (!sourcePath || sourcePath.startsWith('../') || isAbsolute(sourcePath)) {\n throw new Error(`Content source must be inside the content root: ${filePath}`)\n }\n return `${CONTENT_PREFIX}${sourcePath}`\n}\n","import type { ViteDevServer } from 'vite'\n\nimport type { ClarifyDevServerPostHook, ClarifyEmitAsset, ClarifyHookContext, ClarifyPipelineHooks, ClarifyPlugin } from '../../types.js'\n\nexport async function runHooks<K extends keyof ClarifyPipelineHooks>(plugins: ClarifyPlugin[], hookName: K, input: Parameters<NonNullable<ClarifyPipelineHooks[K]>>[0], ctx: ClarifyHookContext): Promise<Parameters<NonNullable<ClarifyPipelineHooks[K]>>[0]> {\n let result = input\n for (const plugin of plugins) {\n const hook = plugin.hooks?.[hookName]\n if (!hook) continue\n try {\n result = await hook(result as never, ctx) as Parameters<NonNullable<ClarifyPipelineHooks[K]>>[0]\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"${hookName}\" failed: ${err}`, { cause: err })\n }\n }\n return result\n}\n\nexport async function runDevConfigureServerHooks(plugins: ClarifyPlugin[], server: ViteDevServer, ctx: ClarifyHookContext): Promise<ClarifyDevServerPostHook[]> {\n const postHooks: ClarifyDevServerPostHook[] = []\n for (const plugin of plugins) {\n const hook = plugin.hooks?.['dev:configureServer']\n if (!hook) continue\n try {\n const postHook = await hook(server, ctx)\n if (postHook) postHooks.push(postHook)\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"dev:configureServer\" failed: ${err}`, { cause: err })\n }\n }\n return postHooks\n}\n\nexport async function runBuildAssetsHooks(plugins: ClarifyPlugin[], ctx: ClarifyHookContext): Promise<ClarifyEmitAsset[]> {\n const assets: ClarifyEmitAsset[] = []\n const producerByFileName = new Map<string, string>()\n\n for (const plugin of plugins) {\n const hook = plugin.hooks?.['build:assets']\n if (!hook) continue\n\n let pluginAssets: ClarifyEmitAsset[]\n try {\n pluginAssets = await hook(ctx)\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"build:assets\" failed: ${err}`, { cause: err })\n }\n\n for (const asset of pluginAssets) {\n const fileName = asset.fileName.replace(/\\\\/g, '/').replace(/^\\/+/, '')\n const previousProducer = producerByFileName.get(fileName)\n if (previousProducer) {\n throw new Error(`[clarify] build asset \"${fileName}\" is emitted by both plugin \"${previousProducer}\" and plugin \"${plugin.name}\"`)\n }\n producerByFileName.set(fileName, plugin.name)\n assets.push({ ...asset, fileName })\n }\n }\n\n return assets\n}\n\nexport async function runBuildDoneHooks(plugins: ClarifyPlugin[], ctx: ClarifyHookContext): Promise<void> {\n for (const plugin of plugins) {\n const hook = plugin.hooks?.['build:done']\n if (!hook) continue\n try {\n await hook(ctx)\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"build:done\" failed: ${err}`, { cause: err })\n }\n }\n}\n","import matter from 'gray-matter'\n\nexport type ParsedFrontmatter = {\n frontmatter: Record<string, unknown>\n content: string\n}\n\n/**\n * 在内容入口统一解析 MDX frontmatter,并返回可供后续流程复用的标准化正文。\n */\nexport function parseFrontmatter(content: string): ParsedFrontmatter {\n const parsed = matter(content)\n return {\n frontmatter: parsed.data,\n content: parsed.content.replace(/^\\r?\\n/, ''),\n }\n}\n\n/**\n * 从 MDX 文件内容中提取 frontmatter。\n * 使用 gray-matter 支持 YAML frontmatter 的标准语法和类型解析。\n */\nexport function extractFrontmatter(content: string): Record<string, unknown> {\n return parseFrontmatter(content).frontmatter\n}\n\n/**\n * 移除 MDX 文件开头的 YAML frontmatter,保留页面正文。\n */\nexport function stripFrontmatter(content: string): string {\n return parseFrontmatter(content).content\n}\n","import { runHooks } from '../../core/plugin/hooks.js'\nimport type { ClarifyContentKind, ClarifyContentTransformInput, ClarifyHookContext, ClarifyPlugin } from '../../types.js'\nimport { parseFrontmatter } from '../markdown/frontmatter.js'\n\nexport type ProcessedMdxContent = {\n frontmatter: Record<string, unknown>\n content: string\n}\n\nexport type ContentTransform = (input: ClarifyContentTransformInput) => Promise<ClarifyContentTransformInput> | ClarifyContentTransformInput\n\nexport type ContentProcessor = {\n processMdx(source: string, filePath?: string): Promise<ProcessedMdxContent>\n processText(source: string, kind: Exclude<ClarifyContentKind, 'markdown+jsx'>, filePath?: string): Promise<string>\n}\n\nasync function transformContent(transform: ContentTransform | undefined, input: ClarifyContentTransformInput): Promise<ClarifyContentTransformInput> {\n return transform ? await transform(input) : input\n}\n\nexport function createContentProcessor(transform?: ContentTransform): ContentProcessor {\n return {\n async processMdx(source, filePath) {\n const { frontmatter, content } = parseFrontmatter(source)\n const transformed = await transformContent(transform, {\n kind: 'markdown+jsx',\n source,\n filePath,\n frontmatter,\n content,\n })\n\n return {\n frontmatter: transformed.frontmatter,\n content: transformed.content,\n }\n },\n async processText(source, kind, filePath) {\n const transformed = await transformContent(transform, {\n kind,\n source,\n filePath,\n frontmatter: {},\n content: source,\n })\n return transformed.content\n },\n }\n}\n\n/**\n * Creates a ContentProcessor that forwards each piece of content through the\n * `content:transform` pipeline hook before it is parsed.\n *\n * Plugins that need to read content (site-discovery, openapi) call this with\n * the plugins list from their hook context. There is no global registry -\n * each call produces an independent processor bound to the given plugins.\n */\nexport function createProjectContentProcessor(plugins: ClarifyPlugin[], ctx: ClarifyHookContext): ContentProcessor {\n return createContentProcessor(input => runHooks(plugins, 'content:transform', input, ctx))\n}\n","import { compile, type CompileOptions } from '@mdx-js/mdx'\n\nimport type { ContentDiagnostic } from '../../types.js'\n\nimport { createContentCompileDiagnostic, remarkPlugins } from './mdx.js'\n\ntype CompileMarkdownContentOptions = {\n filePath?: string\n projectRoot?: string\n}\n\n/**\n * Validate Markdown content for diagnostics WITHOUT running the build-time\n * rehype pipeline (Shiki highlighting, slug injection, code-block parsing).\n *\n * `rehypePlugins` includes `rehypeShiki`, which loads grammar/WASM assets and\n * is expensive. The real highlighting happens at Vite build time via the\n * `@mdx-js/rollup` plugin (see `createContentCompilerPlugin` in\n * `core/adapters.ts`), which runs the full remark + rehype pipeline.\n * Re-running it here, during route discovery (Phase 3), would compile every\n * `.md` file twice and invoke Shiki once per file per `engine.refresh()` -\n * see ARCHITECTURE.md §2.2 which states \"不应在 core 中执行代码高亮\".\n *\n * `format: 'md'` mirrors the adapter's markdown compiler semantics (no JSX,\n * raw HTML allowed via `remarkRehypeOptions`), so the same class of syntax\n * errors that would break the Vite build is surfaced as a diagnostic here\n * instead of leaking out as an opaque\n * `Failed to fetch dynamically imported module` at runtime.\n *\n * MDX files are handled by `compileMdxContent` in `mdx.ts`. Keep the two\n * compilers separate so each format can evolve its own diagnostic rules\n * without contaminating the other.\n */\nexport async function compileMarkdownContent(content: string, options: CompileMarkdownContentOptions = {}): Promise<{ ok: true } | { ok: false; diagnostic: ContentDiagnostic }> {\n const { filePath, projectRoot } = options\n try {\n await compile(content, {\n format: 'md',\n jsx: true,\n providerImportSource: '@clarify-labs/renderer',\n remarkPlugins: remarkPlugins as CompileOptions['remarkPlugins'],\n remarkRehypeOptions: { allowDangerousHtml: true },\n // NOTE: `rehypePlugins` intentionally omitted. See JSDoc above.\n })\n return { ok: true }\n } catch (error) {\n return {\n ok: false,\n diagnostic: createContentCompileDiagnostic({ format: 'markdown', phase: 'syntax', error, filePath, projectRoot }),\n }\n }\n}\n","import { readdir, readFile, stat } from 'node:fs/promises'\nimport { extname, join, relative } from 'node:path'\n\nimport GithubSlugger from 'github-slugger'\nimport { toString } from 'mdast-util-to-string'\nimport { remark } from 'remark'\nimport { visit } from 'unist-util-visit'\n\nimport { contentVirtualModuleId, pageVirtualModuleId, pageVirtualModuleIdFromRef } from '../../core/runtime/module-ids.js'\nimport type { ClarifyPage, ClarifyPageRouteIntent, ContentRoute, ContentSection, ClarifyNavigationNode, ClarifyPagesConfig, ClarifyPagesGroup, ClarifyPagesItem, ClarifyRouteIntent, ClarifyLocalizedText, ClarifyTabsConfig, LocalizedNavigation, LocalizedTabbedNavigation, MarkdownContentRoute, NavigationSection, ResolvedClarifyLocalesConfig, TabbedNavigation } from '../../types.js'\nimport { createContentProcessor, type ContentProcessor } from '../content/content.js'\nimport { compileMarkdownContent } from '../markdown/markdown.js'\nimport { compileMdxContent } from '../markdown/mdx.js'\n\nexport type FindContentRoutesOptions = {\n contentProcessor?: ContentProcessor\n}\n\nexport function kebabToTitle(str: string): string {\n return str\n .split('-')\n .map(w => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ')\n}\n\nfunction parseMdxTree(content: string) {\n return remark.parse(content)\n}\n\nasync function compileRouteDiagnostic(content: string, filePath: string, baseDir: string) {\n const compile = extname(filePath).toLowerCase() === '.md' ? compileMarkdownContent : compileMdxContent\n const result = await compile(content, { filePath, projectRoot: baseDir })\n return result.ok ? undefined : result.diagnostic\n}\n\n/** 从内容中提取第一个 H1 标题 */\nfunction extractH1(content: string): string {\n const tree = parseMdxTree(content)\n let title = ''\n visit(tree, 'heading', (node) => {\n if (!title && node.depth === 1) {\n title = toString(node)\n }\n })\n return title\n}\n\n/** 从 MDX/Markdown 内容中提取 H2/H3 章节 */\nfunction extractMdxSections(content: string): ContentSection[] {\n const sections: ContentSection[] = []\n const slugger = new GithubSlugger()\n const tree = parseMdxTree(content)\n visit(tree, 'heading', (node) => {\n if (node.depth !== 2 && node.depth !== 3) return\n const title = toString(node)\n sections.push({ id: slugger.slug(title), title, level: node.depth })\n })\n return sections\n}\n\nfunction navigationSections(sections: ContentSection[]): NavigationSection[] {\n return sections.map(section => ({ id: section.id, title: section.title, level: section.level, badge: section.badge, tags: section.tags }))\n}\n\nexport function normalizePath(path: string): string {\n const clean = '/' + path.replace(/^\\/+|\\/+$/g, '')\n return clean === '/' ? '/' : clean.replace(/\\/+/g, '/')\n}\n\nfunction pathSegmentFromOpenAPITag(tag: string): string {\n return tag\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'tag'\n}\n\nfunction openAPITagsPathSegment(tags: string[]): string {\n return tags.map(pathSegmentFromOpenAPITag).join('-')\n}\n\nexport function basePathFromRef(ref: string): string {\n const withoutExtension = ref.replace(/\\.mdx?$/, '').replace(/\\.openapi\\.(json|yaml|yml)$/, '')\n return normalizePath(withoutExtension === 'index' ? '/' : withoutExtension.replace(/\\/index$/, ''))\n}\n\nexport function openAPIPagePathFromRef(ref: string, tagFilter?: string[], explicitPath?: string): string {\n if (explicitPath) return normalizePath(explicitPath)\n const basePath = basePathFromRef(ref)\n if (!tagFilter?.length) return basePath\n return normalizePath(`${basePath}/${openAPITagsPathSegment(tagFilter)}`)\n}\n\nexport function routePathFromRef(ref: string, explicitPath?: string): string {\n return explicitPath ? normalizePath(explicitPath) : basePathFromRef(ref)\n}\n\nexport function localizedRoutePath(basePath: string, locale: string, _i18n: ResolvedClarifyLocalesConfig): string {\n const normalizedBasePath = normalizePath(basePath)\n const prefix = normalizePath(locale)\n return normalizedBasePath === '/' ? prefix : normalizePath(`${prefix}${normalizedBasePath}`)\n}\n\nfunction resolveLocalizedText(text: ClarifyLocalizedText | undefined, locale: string, fallbackLocale?: string): string | undefined {\n if (typeof text === 'string') return text\n if (text === undefined) return undefined\n return text[locale] ?? (fallbackLocale ? text[fallbackLocale] : undefined) ?? Object.values(text)[0]\n}\n\nexport async function findContentRoutes(dir: string, base: string = dir, options: FindContentRoutesOptions = {}): Promise<MarkdownContentRoute[]> {\n const routes: MarkdownContentRoute[] = []\n // Skip directories that do not exist instead of throwing; `stat` rejects for\n // missing paths, so treat that as an empty result.\n let dirStat\n try {\n dirStat = await stat(dir)\n } catch {\n return routes\n }\n if (!dirStat.isDirectory()) return routes\n\n const entries = await readdir(dir, { withFileTypes: true })\n for (const entry of entries) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n routes.push(...await findContentRoutes(fullPath, base, options))\n } else if (entry.isFile() && /\\.mdx?$/.test(entry.name)) {\n const relativePath = relative(base, fullPath)\n const pathParts = relativePath.replace(/\\.mdx?$/, '').split('/')\n const path = '/' + pathParts.map(p => p === 'index' ? '' : p).filter(Boolean).join('/')\n const cleanPath = path.replace(/\\/+/g, '/').replace(/\\/$/, '') || '/'\n\n const source = await readFile(fullPath, 'utf-8')\n const { frontmatter, content } = await (options.contentProcessor ?? createContentProcessor()).processMdx(source, fullPath)\n const page: ClarifyPage = {\n path: cleanPath,\n filePath: fullPath,\n frontmatter,\n content,\n }\n const diagnostic = await compileRouteDiagnostic(page.content, fullPath, base)\n\n let title = typeof page.frontmatter.title === 'string' ? page.frontmatter.title : ''\n if (!title) {\n const lastPart = pathParts[pathParts.length - 1] ?? ''\n const stem = lastPart === 'index'\n ? (pathParts.length >= 2 ? pathParts[pathParts.length - 2]! : extractH1(page.content))\n : lastPart\n title = kebabToTitle(stem) || 'Untitled'\n }\n\n routes.push({\n kind: entry.name.toLowerCase().endsWith('.mdx') ? 'markdown+jsx' : 'markdown',\n path: cleanPath,\n basePath: cleanPath,\n meta: {\n title,\n description: typeof page.frontmatter.description === 'string' ? page.frontmatter.description : undefined,\n keywords: frontmatterKeywords(page.frontmatter),\n sections: extractMdxSections(page.content),\n },\n module: {\n pageVirtualModuleId: pageVirtualModuleId(relativePath.replace(/\\.mdx?$/, '')),\n contentVirtualModuleId: contentVirtualModuleId(fullPath, base),\n },\n source: {\n filePath: fullPath,\n frontmatter: page.frontmatter,\n content: page.content,\n },\n diagnostic,\n })\n }\n }\n return routes\n}\n\nfunction pageVirtualModuleIdForLocalizedRoute(contentRoot: string, filePath: string): string {\n return pageVirtualModuleIdFromRef(relative(contentRoot, filePath))\n}\n\nfunction frontmatterKeywords(frontmatter: Record<string, unknown>): string[] | undefined {\n const value = frontmatter.keywords ?? frontmatter.keyword ?? frontmatter.tags\n const keywords = Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : typeof value === 'string'\n ? value.split(',').map(keyword => keyword.trim()).filter(Boolean)\n : []\n\n return keywords.length > 0 ? keywords : undefined\n}\n\nfunction withPageIdentity<T extends ContentRoute>(route: T, path: string): T {\n return {\n ...route,\n path,\n module: { ...route.module, pageVirtualModuleId: pageVirtualModuleId(path) },\n }\n}\n\nexport function withAlternates<T extends ContentRoute>(route: T, routes: ContentRoute[], locales: ResolvedClarifyLocalesConfig): T {\n const basePath = route.basePath ?? route.path\n // 排除裸路径别名,避免覆盖带 locale 前缀的路径\n const routeByLocaleAndBase = new Map(\n routes\n .filter(r => !r.locale || r.path === `/${r.locale}` || r.path.startsWith(`/${r.locale}/`))\n .map(r => [`${r.locale ?? ''}:${r.basePath ?? r.path}`, r]),\n )\n const alternates = Object.fromEntries(\n locales.locales.flatMap((locale) => {\n const alternate = routeByLocaleAndBase.get(`${locale.code}:${basePath}`)\n return alternate ? [[locale.code, alternate.path]] : []\n })\n )\n return { ...route, alternates }\n}\n\n/**\n * 为默认语言的 locale-prefixed 路由生成无前缀的\"裸路径别名\",方便不带语言\n * 前缀的 URL 也能访问。标记 `isBareAlias` 以便搜索索引生成时过滤重复索引。\n */\nfunction generateBareAliases(routes: MarkdownContentRoute[], locales: ResolvedClarifyLocalesConfig): MarkdownContentRoute[] {\n const bareRoutes: MarkdownContentRoute[] = []\n const seenBare = new Set(routes.map(r => r.path))\n for (const route of routes) {\n if (route.locale !== locales.default) continue\n const bp = route.basePath ?? route.path\n if (bp === route.path || seenBare.has(bp)) continue\n seenBare.add(bp)\n bareRoutes.push({ ...withPageIdentity(route, bp), isBareAlias: true })\n }\n return bareRoutes\n}\n\nexport async function findLocalizedContentRoutes(contentRoot: string, locales?: ResolvedClarifyLocalesConfig, options: FindContentRoutesOptions = {}): Promise<MarkdownContentRoute[]> {\n if (!locales) return findContentRoutes(contentRoot, contentRoot, options)\n\n const localizedRoutes: MarkdownContentRoute[] = []\n for (const locale of locales.locales) {\n const localeRoot = join(contentRoot, locale.code)\n const discovered = await findContentRoutes(localeRoot, localeRoot, options)\n for (const route of discovered) {\n const basePath = route.basePath ?? route.path\n localizedRoutes.push({\n ...route,\n path: localizedRoutePath(basePath, locale.code, locales),\n basePath,\n locale: locale.code,\n module: {\n ...route.module,\n pageVirtualModuleId: pageVirtualModuleIdForLocalizedRoute(contentRoot, route.source.filePath),\n contentVirtualModuleId: contentVirtualModuleId(route.source.filePath, contentRoot),\n },\n })\n }\n }\n\n if (locales.missing === 'fallback') {\n const routeByLocaleAndBase = new Map(localizedRoutes.map(route => [`${route.locale ?? ''}:${route.basePath ?? route.path}`, route]))\n const defaultRoutes = localizedRoutes.filter(route => route.locale === locales.default)\n for (const sourceRoute of defaultRoutes) {\n const basePath = sourceRoute.basePath ?? sourceRoute.path\n for (const locale of locales.locales) {\n const key = `${locale.code}:${basePath}`\n if (routeByLocaleAndBase.has(key)) continue\n const path = localizedRoutePath(basePath, locale.code, locales)\n localizedRoutes.push({\n ...withPageIdentity(sourceRoute, path),\n locale: locale.code,\n isFallback: true,\n })\n }\n }\n }\n\n const routesWithAlternates = localizedRoutes.map(route => withAlternates(route, localizedRoutes, locales))\n\n return [...routesWithAlternates, ...generateBareAliases(routesWithAlternates, locales)]\n}\n\nexport function buildNavigation(routes: ContentRoute[]): ClarifyNavigationNode[] {\n const root: ClarifyNavigationNode[] = []\n\n for (const route of routes) {\n if (route.path === '/' || (route.basePath ?? route.path) === '/404') continue // 首页和 404 不放入侧边栏\n\n const parts = route.path.replace(/^\\//, '').split('/')\n let current = root\n\n for (let i = 0; i < parts.length; i++) {\n const pathSoFar = '/' + parts.slice(0, i + 1).join('/')\n let node = current.find(n => n.path === pathSoFar)\n if (!node) {\n node = { path: pathSoFar, title: i === parts.length - 1 ? route.meta.title : kebabToTitle(parts[i]), children: [] }\n current.push(node)\n }\n if (i === parts.length - 1 && route.meta.sections) {\n node.sections = navigationSections(route.meta.sections)\n }\n if (i < parts.length - 1) {\n node.children = node.children ?? []\n current = node.children\n }\n }\n }\n\n return root\n}\n\nexport function routeIntentFromPagesItem(\n item: ClarifyPagesItem\n): ClarifyRouteIntent {\n if (typeof item === 'string') return { kind: 'page', ref: item }\n if ('group' in item) throw new Error('Navigation groups do not resolve to route intents')\n if ('openapi' in item) return { kind: 'openapi', ref: item.openapi, tagFilter: item.filter?.tags, path: item.path, title: item.title, icon: item.icon }\n return { kind: 'page', ref: item.page, path: item.path, redirect: item.redirect, title: item.title, icon: item.icon }\n}\n\nfunction firstNavigationPath(nodes: ClarifyNavigationNode[]): string {\n for (const node of nodes) {\n if (node.path) return node.path\n const childPath = node.children ? firstNavigationPath(node.children) : undefined\n if (childPath) return childPath\n }\n return '/'\n}\n\nfunction collectExplicitPagePathIntents(tabs?: ClarifyTabsConfig): Array<ClarifyPageRouteIntent & { path: string }> {\n const intents: Array<ClarifyPageRouteIntent & { path: string }> = []\n\n const collectItems = (items: ClarifyPagesItem[]) => {\n for (const item of items) {\n if (typeof item !== 'string' && 'group' in item) {\n collectItems(item.pages)\n } else if (typeof item !== 'string' && 'page' in item && item.path) {\n const intent = routeIntentFromPagesItem(item)\n if (intent.kind === 'page' && intent.path) intents.push({ ...intent, path: intent.path })\n }\n }\n }\n\n for (const tab of tabs ?? []) {\n if (!tab.pages || tab.pages === 'FileTree') continue\n for (const group of tab.pages) {\n collectItems(group.pages)\n }\n }\n\n return intents\n}\n\nexport function applyConfiguredPageRoutePaths(routes: ContentRoute[], tabs?: ClarifyTabsConfig, locales?: ResolvedClarifyLocalesConfig): ContentRoute[] {\n const pageIntents = collectExplicitPagePathIntents(tabs)\n if (!pageIntents.length) return routes\n\n const additions: MarkdownContentRoute[] = []\n const existingKeys = new Set(routes.map(route => `${route.locale ?? ''}:${route.basePath ?? route.path}`))\n\n for (const intent of pageIntents) {\n const sourceBasePath = routePathFromRef(intent.ref)\n const targetBasePath = routePathFromRef(intent.ref, intent.path)\n if (sourceBasePath === targetBasePath) continue\n\n for (const route of routes) {\n if (route.kind === 'openapi' || (route.basePath ?? route.path) !== sourceBasePath) continue\n\n const key = `${route.locale ?? ''}:${targetBasePath}`\n if (existingKeys.has(key)) continue\n existingKeys.add(key)\n\n const path = route.locale && locales ? localizedRoutePath(targetBasePath, route.locale, locales) : targetBasePath\n additions.push({\n ...withPageIdentity(route, path),\n basePath: targetBasePath,\n })\n }\n }\n\n const nextRoutes = [...routes, ...additions]\n const routesWithAlternates = locales ? nextRoutes.map(route => withAlternates(route, nextRoutes, locales)) : nextRoutes\n\n if (!locales) return routesWithAlternates\n\n const markdownRoutes = routesWithAlternates.filter((route): route is MarkdownContentRoute => route.kind !== 'openapi')\n return [...routesWithAlternates, ...generateBareAliases(markdownRoutes, locales)]\n}\n\nfunction buildNavigationFromPagesConfig(routes: ContentRoute[], config?: ClarifyPagesConfig): ClarifyNavigationNode[] {\n if (!config || config === 'FileTree') return buildNavigation(routes)\n return buildNavigationFromConfig(routes, config)\n}\n\nexport function buildNavigationFromTabsConfig(routes: ContentRoute[], tabs: ClarifyTabsConfig): TabbedNavigation {\n return {\n kind: 'tabbed',\n tabs: tabs.map(tab => {\n const children = buildNavigationFromPagesConfig(routes, tab.pages)\n return {\n type: 'tab',\n path: firstNavigationPath(children),\n title: resolveLocalizedText(tab.tab, '', '') ?? '',\n icon: tab.icon,\n children,\n }\n }),\n }\n}\n\nexport function buildNavigationFromConfig(routes: ContentRoute[], config: ClarifyPagesGroup[]): ClarifyNavigationNode[] {\n const routeMap = new Map(routes.map(r => [r.path, r]))\n\n const buildItem = (item: ClarifyPagesItem): ClarifyNavigationNode => {\n if (typeof item !== 'string' && 'group' in item) {\n const children = item.pages.map(buildItem)\n return {\n path: firstNavigationPath(children),\n title: resolveLocalizedText(item.group, '', '') ?? '',\n icon: item.icon,\n children,\n }\n }\n\n const intent = routeIntentFromPagesItem(item)\n\n if (intent.kind === 'openapi') {\n const path = openAPIPagePathFromRef(intent.ref, intent.tagFilter, intent.path)\n const route = routeMap.get(path)\n return {\n path,\n title: resolveLocalizedText(intent.title, '', '') ?? route?.meta.title ?? kebabToTitle(path.split('/').pop() ?? intent.ref),\n icon: intent.icon,\n sections: route?.meta.sections ? navigationSections(route.meta.sections) : undefined,\n }\n }\n\n const path = routePathFromRef(intent.ref, intent.path)\n const route = routeMap.get(path)\n return {\n path: intent.redirect ? normalizePath(intent.redirect) : path,\n title: resolveLocalizedText(intent.title, '', '') ?? route?.meta.title ?? kebabToTitle(path.split('/').pop() ?? intent.ref),\n icon: intent.icon,\n sections: route?.meta.sections ? navigationSections(route.meta.sections) : undefined,\n }\n }\n\n return config.map(group => {\n const children = group.pages.map(buildItem)\n\n return {\n path: children[0]?.path ?? '/',\n title: resolveLocalizedText(group.group, '', '') ?? '',\n icon: group.icon,\n children,\n }\n })\n}\n\nfunction localizeNavigationPaths(nodes: ClarifyNavigationNode[], locale: string, locales: ResolvedClarifyLocalesConfig): ClarifyNavigationNode[] {\n return nodes.map(node => ({\n ...node,\n path: localizedRoutePath(node.path, locale, locales),\n children: node.children ? localizeNavigationPaths(node.children, locale, locales) : undefined,\n }))\n}\n\nexport function buildLocalizedNavigation(routes: ContentRoute[], config: ClarifyPagesConfig | undefined, localesConfig?: ResolvedClarifyLocalesConfig): LocalizedNavigation | undefined {\n if (!localesConfig) return undefined\n\n const locales: LocalizedNavigation['locales'] = {}\n for (const locale of localesConfig.locales) {\n const localeRoutes = routes.filter(route => route.locale === locale.code)\n locales[locale.code] = buildLocalizedNavigationForLocale(localeRoutes, config, locale.code, localesConfig)\n }\n\n return { kind: 'localized', locales }\n}\n\nfunction buildLocalizedNavigationForLocale(routes: ContentRoute[], config: ClarifyPagesConfig | undefined, locale: string, locales: ResolvedClarifyLocalesConfig): ClarifyNavigationNode[] {\n if (!config || config === 'FileTree') {\n const baseNavigation = buildNavigation(routes.map(route => ({ ...route, path: route.basePath ?? route.path })))\n return localizeNavigationPaths(baseNavigation, locale, locales)\n }\n\n const routeMap = new Map(routes.map(route => [route.basePath ?? route.path, route]))\n const buildItem = (item: ClarifyPagesItem): ClarifyNavigationNode => {\n if (typeof item !== 'string' && 'group' in item) {\n const children = item.pages.map(buildItem)\n return {\n path: firstNavigationPath(children),\n title: resolveLocalizedText(item.group, locale, locales.default) ?? '',\n icon: item.icon,\n children,\n }\n }\n\n const intent = routeIntentFromPagesItem(item)\n const basePath = intent.kind === 'openapi'\n ? openAPIPagePathFromRef(intent.ref, intent.tagFilter, intent.path)\n : routePathFromRef(intent.ref, intent.path)\n const route = routeMap.get(basePath)\n const path = route?.path ?? localizedRoutePath(basePath, locale, locales)\n const redirectPath = intent.kind === 'page' && intent.redirect ? localizedRoutePath(routePathFromRef(intent.redirect), locale, locales) : undefined\n\n return {\n path: redirectPath ?? path,\n title: resolveLocalizedText(intent.title, locale, locales.default) ?? route?.meta.title ?? kebabToTitle(basePath.split('/').pop() ?? intent.ref),\n icon: intent.icon,\n sections: route?.meta.sections ? navigationSections(route.meta.sections) : undefined,\n }\n }\n\n return config.map(group => {\n const children = group.pages.map(buildItem)\n\n return {\n path: children[0]?.path ?? localizedRoutePath('/', locale, locales),\n title: resolveLocalizedText(group.group, locale, locales.default) ?? '',\n icon: group.icon,\n children,\n }\n })\n}\n\nexport function buildLocalizedNavigationFromTabsConfig(routes: ContentRoute[], tabs: ClarifyTabsConfig, localesConfig?: ResolvedClarifyLocalesConfig): LocalizedTabbedNavigation | undefined {\n if (!localesConfig) return undefined\n\n const locales: LocalizedTabbedNavigation['locales'] = {}\n for (const locale of localesConfig.locales) {\n const localeRoutes = routes.filter(route => route.locale === locale.code)\n locales[locale.code] = {\n tabs: tabs.map(tab => {\n const children = buildLocalizedNavigationForLocale(localeRoutes, tab.pages, locale.code, localesConfig)\n return {\n type: 'tab',\n path: firstNavigationPath(children),\n title: resolveLocalizedText(tab.tab, locale.code, localesConfig.default) ?? '',\n icon: tab.icon,\n children,\n }\n }),\n }\n }\n\n return { kind: 'localized-tabbed', locales }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { relative } from 'node:path'\n\nimport type { ClarifyProjectContext, ContentRoute } from '../../types.js'\nimport { basePathFromRef, localizedRoutePath, normalizePath } from '../routes/routes.js'\n\n/**\n * Dev-only HTTP endpoint that exposes the in-memory route manifest so external\n * tools (e.g. the VS Code extension) can resolve a content file path to its\n * preview URL.\n *\n * Mounted at `POST /dev/query-preview-route`:\n * - Empty body → returns the full route list (minimal fields).\n * - `{ \"file\": \"<absPath>\" }` → returns the single matching route. When the\n * project uses i18n, the route whose locale matches the file's directory is\n * preferred; otherwise the default-locale route is returned. If the file is\n * not a registered route, a best-effort preview path is derived from the\n * file path relative to the content root.\n *\n * Uses POST + JSON body (instead of GET + query string) because file paths may\n * contain characters that are awkward to encode in a URL query parameter.\n */\nexport const CLARIFY_DEV_ROUTE_ENDPOINT = '/dev/query-preview-route'\n\nexport type DevRouteEntry = {\n path: string\n filePath: string\n locale?: string\n basePath?: string\n kind: string\n title: string\n /** Whether the route was derived from the file path rather than matched in the route manifest. */\n inferred?: boolean\n}\n\nexport type DevRouteResponse = DevRouteEntry | DevRouteEntry[] | null\n\n/** Serialize a ContentRoute into the minimal shape exposed to tooling. */\nexport function toDevRouteEntry(route: ContentRoute): DevRouteEntry {\n return {\n path: route.path,\n filePath: route.source.filePath,\n locale: route.locale,\n basePath: route.basePath,\n kind: route.kind,\n title: route.meta.title,\n }\n}\n\n/**\n * Resolve a single file path to its preview route.\n *\n * Selection order:\n * 1. Routes whose `filePath` exactly matches.\n * 2. Among matches, prefer the one whose `locale` matches the file's locale\n * directory (e.g. `source/zh-CN/x.mdx` → locale `zh-CN`).\n * 3. If no locale match, fall back to the default locale (if i18n is enabled)\n * or the first match.\n */\nexport function resolveRouteForFile(filePath: string, routes: ContentRoute[], defaultLocale?: string): ContentRoute | undefined {\n const matches = routes.filter(r => r.source.filePath === filePath)\n if (matches.length === 0) return undefined\n if (matches.length === 1) return matches[0]\n\n const fileLocale = inferLocaleFromPath(filePath)\n if (fileLocale) {\n const localeMatch = matches.find(r => r.locale === fileLocale)\n if (localeMatch) return localeMatch\n }\n\n if (defaultLocale) {\n const defaultMatch = matches.find(r => r.locale === defaultLocale)\n if (defaultMatch) return defaultMatch\n }\n\n return matches[0]\n}\n\n/**\n * Derive a best-effort preview route for a file that is not in the route\n * manifest (e.g. a draft or newly created file). The path is computed from the\n * file's location relative to the content root, following the same convention\n * as route discovery (`source/{locale}/path/index.mdx` → `/{locale}/path`).\n *\n * Returns null when the file is outside the content root or is not a\n * recognized content file type.\n */\nexport function inferRouteForFile(filePath: string, contentRoot: string, defaultLocale?: string): DevRouteEntry | null {\n const ref = relative(contentRoot, filePath)\n if (!ref || ref.startsWith('..')) return null\n\n const isMdx = /\\.mdx?$/.test(filePath)\n const isOpenApi = /\\.openapi\\.(json|ya?ml)$/.test(filePath)\n if (!isMdx && !isOpenApi) return null\n\n const segments = ref.split('/')\n const fileLocale = inferLocaleFromPath(filePath)\n const localeSegmentIndex = fileLocale ? segments.indexOf(fileLocale) : -1\n const refWithoutLocale = localeSegmentIndex >= 0 ? segments.slice(localeSegmentIndex + 1).join('/') : ref\n\n const basePath = basePathFromRef(refWithoutLocale)\n const path = fileLocale && defaultLocale\n ? localizedRoutePath(basePath, fileLocale, { default: defaultLocale, missing: 'fallback', locales: [] })\n : basePath\n\n const title = segments[segments.length - 1]?.replace(/\\.(mdx?|openapi\\.(json|ya?ml))$/, '') || 'Untitled'\n\n return {\n path: normalizePath(path),\n filePath,\n locale: fileLocale,\n basePath: normalizePath(basePath),\n kind: isMdx ? 'markdown+jsx' : 'openapi',\n title,\n inferred: true,\n }\n}\n\n/** Best-effort locale inference from a file path segment like `.../zh-CN/x.mdx`. */\nfunction inferLocaleFromPath(filePath: string): string | undefined {\n const segments = filePath.split('/')\n for (const segment of segments) {\n if (/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-[A-Z]{2})?$/.test(segment)) {\n return segment\n }\n }\n return undefined\n}\n\n/** Read and parse the JSON body of an IncomingMessage. */\nfunction readJsonBody(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolveBody, reject) => {\n const chunks: Buffer[] = []\n req.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)))\n req.on('error', reject)\n req.on('end', () => {\n const raw = Buffer.concat(chunks).toString('utf-8').trim()\n if (!raw) return resolveBody({})\n try {\n resolveBody(JSON.parse(raw))\n } catch (err) {\n reject(err)\n }\n })\n })\n}\n\n/**\n * Handle a request to the dev route endpoint. Pure function — does not touch\n * the network directly, only reads the request body and writes to `res`.\n */\nexport async function handleDevRouteRequest(req: IncomingMessage, res: ServerResponse, routes: ContentRoute[], context: ClarifyProjectContext): Promise<void> {\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n\n let body: unknown\n try {\n body = await readJsonBody(req)\n } catch {\n res.statusCode = 400\n res.end(JSON.stringify({ error: 'Invalid JSON body' }))\n return\n }\n\n const file = typeof body === 'object' && body !== null ? (body as { file?: unknown }).file : undefined\n\n if (typeof file === 'string' && file.length > 0) {\n const route = resolveRouteForFile(file, routes, context.projectConfig.locales?.default)\n if (route) {\n res.end(JSON.stringify(toDevRouteEntry(route)))\n return\n }\n const inferred = inferRouteForFile(file, context.contentRoot, context.projectConfig.locales?.default)\n res.end(JSON.stringify(inferred))\n return\n }\n\n res.end(JSON.stringify(routes.map(toDevRouteEntry)))\n}\n","import { themePresets } from '@clarify-labs/renderer'\n\nimport type { ClarifyThemeConfig, ResolvedClarifyThemeConfig } from '../types.js'\n\nexport { themePresets }\n\nexport function resolveThemeConfig(theme: ClarifyThemeConfig = {}): ResolvedClarifyThemeConfig {\n const preset = theme.preset ?? 'default'\n const presetTheme = themePresets[preset] as ResolvedClarifyThemeConfig\n\n return {\n preset,\n tokens: {\n colors: {\n ...presetTheme.tokens.colors,\n ...theme.tokens?.colors,\n },\n radius: {\n ...presetTheme.tokens.radius,\n ...theme.tokens?.radius,\n },\n },\n layout: {\n ...presetTheme.layout,\n ...theme.layout,\n },\n }\n}\n","import { z } from 'zod'\n\nimport type { ClarifyVariableValue, ClarifyProjectConfig } from '../../types.js'\n\nconst clarifyLogoConfigSchema = z.union([\n z.string(),\n z.object({\n light: z.string().optional(),\n dark: z.string().optional(),\n }).strict(),\n])\n\nconst clarifyFaviconConfigSchema = z.union([\n z.string(),\n z.object({\n light: z.string().optional(),\n dark: z.string().optional(),\n }).strict(),\n])\n\nconst clarifyLocalizedTextSchema = z.union([\n z.string(),\n z.record(z.string(), z.string()),\n])\n\nconst clarifyLocaleConfigSchema = z.object({\n code: z.string(),\n label: z.string(),\n dir: z.union([z.literal('ltr'), z.literal('rtl')]).optional(),\n}).strict()\n\nconst clarifyLocalesConfigSchema = z.object({\n default: z.string().optional(),\n missing: z.union([z.literal('fallback'), z.literal('404'), z.literal('hide')]).optional(),\n locales: z.array(clarifyLocaleConfigSchema).min(1),\n}).strict().superRefine((config, ctx) => {\n const localeCodes = new Set<string>()\n for (const [index, locale] of config.locales.entries()) {\n if (localeCodes.has(locale.code)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Duplicate locale code \"${locale.code}\"`,\n path: ['locales', index, 'code'],\n })\n }\n localeCodes.add(locale.code)\n }\n\n if (config.default && !localeCodes.has(config.default)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'default must be one of locales.locales',\n path: ['default'],\n })\n }\n})\n\nconst clarifyNavbarLinkSchema = z.object({\n label: clarifyLocalizedTextSchema,\n href: z.string(),\n external: z.boolean().optional(),\n}).strict()\n\nconst clarifyBannerConfigOptionsSchema = z.object({\n content: clarifyLocalizedTextSchema,\n dismissible: z.boolean().optional(),\n link: clarifyNavbarLinkSchema.optional(),\n}).strict()\n\nconst clarifyFooterConfigSchema = z.object({\n links: z.array(clarifyNavbarLinkSchema).optional(),\n socials: z.record(z.string(), z.string()).optional(),\n copyright: clarifyLocalizedTextSchema.optional(),\n}).strict()\n\nconst clarifyVariableValueSchema: z.ZodType<ClarifyVariableValue> = z.lazy(() => z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), clarifyVariableValueSchema),\n]))\n\nconst clarifyVariablesConfigSchema = z.record(z.string(), clarifyVariableValueSchema)\n\nconst clarifyRepositoryConfigSchema = z.object({\n url: z.string().optional(),\n branch: z.string().optional(),\n directory: z.string().optional(),\n}).strict()\n\nconst clarifyPagesItemSchema: z.ZodType<\n import('../../types.js').ClarifyPagesItem,\n import('../../types.js').ClarifyPagesItem\n> = z.lazy(() => z.union([\n z.string(),\n clarifyPagesGroupSchema,\n z.object({\n page: z.string(),\n path: z.string().optional(),\n title: clarifyLocalizedTextSchema.optional(),\n icon: z.string().optional(),\n redirect: z.string().optional(),\n }).strict(),\n z.object({\n openapi: z.string(),\n path: z.string().optional(),\n icon: z.string().optional(),\n title: clarifyLocalizedTextSchema.optional(),\n filter: z.object({\n tags: z.array(z.string()).optional(),\n }).strict().optional(),\n }).strict(),\n]))\n\nconst clarifyPagesGroupSchema: z.ZodType<\n import('../../types.js').ClarifyPagesGroup,\n import('../../types.js').ClarifyPagesGroup\n> = z.lazy(() => z.object({\n group: clarifyLocalizedTextSchema,\n icon: z.string().optional(),\n pages: z.array(clarifyPagesItemSchema),\n}).strict())\n\nconst clarifyPagesConfigSchema = z.union([\n z.array(clarifyPagesGroupSchema),\n z.literal('FileTree'),\n])\n\nconst clarifyTabItemSchema = z.object({\n tab: clarifyLocalizedTextSchema,\n icon: z.string().optional(),\n pages: clarifyPagesConfigSchema.optional(),\n}).strict()\n\nconst clarifyTabsConfigSchema = z.array(clarifyTabItemSchema)\n\nconst clarifyThemePresetSchema = z.enum(['default', 'base'])\n\nconst clarifyThemeModeColorValueSchema = z.object({\n light: z.string().optional(),\n dark: z.string().optional(),\n}).strict()\n\nconst clarifyThemeColorValueSchema = z.union([z.string(), clarifyThemeModeColorValueSchema])\n\nconst clarifyThemeColorTokensConfigSchema = z.object({\n primary: clarifyThemeColorValueSchema.optional(),\n accent: clarifyThemeColorValueSchema.optional(),\n background: clarifyThemeColorValueSchema.optional(),\n foreground: clarifyThemeColorValueSchema.optional(),\n surface: clarifyThemeColorValueSchema.optional(),\n muted: clarifyThemeColorValueSchema.optional(),\n border: clarifyThemeColorValueSchema.optional(),\n codeBackground: clarifyThemeColorValueSchema.optional(),\n}).strict()\n\nconst clarifyThemeRadiusTokensConfigSchema = z.object({\n sm: z.string().optional(),\n md: z.string().optional(),\n lg: z.string().optional(),\n xl: z.string().optional(),\n}).strict()\n\nconst clarifyThemeTokensConfigSchema = z.object({\n colors: clarifyThemeColorTokensConfigSchema.optional(),\n radius: clarifyThemeRadiusTokensConfigSchema.optional(),\n}).strict()\n\nconst clarifyThemeLayoutConfigSchema = z.object({\n maxWidth: z.string().optional(),\n}).strict()\n\nconst clarifyThemeConfigSchema = z.object({\n preset: clarifyThemePresetSchema.optional(),\n tokens: clarifyThemeTokensConfigSchema.optional(),\n layout: clarifyThemeLayoutConfigSchema.optional(),\n}).strict()\n\nfunction featureSchema<Schema extends z.ZodRawShape>(shape: Schema, defaults: Record<string, unknown>, enabledByDefault = true) {\n const resolvedDefaults = { enabled: enabledByDefault, ...defaults }\n const objectSchema = z.object({ enabled: z.boolean().default(enabledByDefault), ...shape }).strict().default(resolvedDefaults as never)\n return z.union([\n z.boolean(),\n objectSchema,\n ]).default(resolvedDefaults as never).transform((value) => typeof value === 'boolean'\n ? { enabled: value, ...defaults }\n : value)\n}\n\nexport const clarifyFeaturesConfigSchema = z.object({\n search: featureSchema({ mcp: z.boolean().default(true) }, { mcp: true }),\n repository: featureSchema(clarifyRepositoryConfigSchema.shape, {}),\n themeEditor: featureSchema({}, {}, false),\n openapi: featureSchema({\n playground: z.boolean().default(true),\n }, { playground: true }),\n}).strict()\n\nexport const clarifyProjectConfigSchema = z.object({\n title: z.string().optional(),\n description: z.string().optional(),\n siteUrl: z.string().optional(),\n routePrefix: z.string().default('/'),\n assetPrefix: z.string().optional(),\n logo: clarifyLogoConfigSchema.optional(),\n homeUrl: z.string().optional(),\n favicon: clarifyFaviconConfigSchema.optional(),\n theme: clarifyThemeConfigSchema.optional(),\n navigation: z.object({\n links: z.array(clarifyNavbarLinkSchema).optional(),\n tabs: clarifyTabsConfigSchema.optional(),\n }).strict().optional(),\n banner: clarifyBannerConfigOptionsSchema.optional(),\n footer: clarifyFooterConfigSchema.optional(),\n locales: clarifyLocalesConfigSchema.optional(),\n variables: clarifyVariablesConfigSchema.optional(),\n features: clarifyFeaturesConfigSchema.optional(),\n}).strict() satisfies z.ZodType<ClarifyProjectConfig>\n\nexport type ClarifyProjectConfigInput = z.input<typeof clarifyProjectConfigSchema>\n","import type { ZodError } from 'zod'\n\nimport { resolveThemeConfig } from '../../parsers/theme.js'\nimport type { ClarifyFeaturesConfig, ClarifyLocalesConfig, ClarifyProjectConfig, ResolvedClarifyFeaturesConfig, ResolvedClarifyLocalesConfig, ResolvedProjectConfig } from '../../types.js'\n\nimport { clarifyFeaturesConfigSchema, clarifyProjectConfigSchema } from './config-schema.js'\n\nfunction formatIssuePath(path: PropertyKey[]): string {\n return path.reduce<string>((result, segment) => {\n if (typeof segment === 'number') return `${result}[${segment}]`\n const key = String(segment)\n return result ? `${result}.${key}` : key\n }, '')\n}\n\nfunction formatProjectConfigError(error: ZodError): string {\n const issue = error.issues[0]\n if (!issue) return '[clarify] config is invalid'\n\n const path = formatIssuePath(issue.path)\n if (!path) return `[clarify] config must contain an object: ${issue.message}`\n\n return `[clarify] config field \"${path}\" is invalid: ${issue.message}`\n}\n\nexport function validateProjectConfig(value: unknown): ClarifyProjectConfig {\n const result = clarifyProjectConfigSchema.safeParse(value)\n if (!result.success) {\n throw new Error(formatProjectConfigError(result.error))\n }\n return result.data\n}\n\nfunction resolveLocalesConfig(locales?: ClarifyLocalesConfig): ResolvedClarifyLocalesConfig | undefined {\n if (!locales) return undefined\n\n const firstLocale = locales.locales[0]?.code\n const defaultLocale = locales.default ?? firstLocale\n if (!defaultLocale) return undefined\n\n return {\n default: defaultLocale,\n missing: locales.missing ?? 'fallback',\n locales: locales.locales,\n }\n}\n\nexport function resolveFeaturesConfig(features: ClarifyFeaturesConfig = {}): ResolvedClarifyFeaturesConfig {\n return clarifyFeaturesConfigSchema.parse(features) as unknown as ResolvedClarifyFeaturesConfig\n}\n\nfunction resolveRoutePrefix(routePrefix?: string): string {\n const trimmed = routePrefix?.trim()\n if (!trimmed || trimmed === '/') return '/'\n\n return `/${trimmed.replace(/^\\/+|\\/+$/g, '')}/`\n}\n\nfunction resolveAssetPrefix(assetPrefix: string | undefined, routePrefix: string): string {\n const trimmed = assetPrefix?.trim()\n if (trimmed === undefined) return routePrefix\n if (trimmed === './' || trimmed === '') return trimmed || '/'\n if (!trimmed || trimmed === '/') return '/'\n if (/^[a-z][a-z\\d+.-]*:\\/\\//i.test(trimmed)) return trimmed.endsWith('/') ? trimmed : `${trimmed}/`\n if (trimmed.startsWith('./') || trimmed.startsWith('../')) return trimmed.endsWith('/') ? trimmed : `${trimmed}/`\n\n return `/${trimmed.replace(/^\\/+|\\/+$/g, '')}/`\n}\n\nexport function resolveProjectConfig(config: ClarifyProjectConfig = {}): ResolvedProjectConfig {\n const routePrefix = resolveRoutePrefix(config.routePrefix)\n\n return {\n title: config.title ?? 'Clarify Docs',\n description: config.description ?? '',\n siteUrl: config.siteUrl,\n routePrefix,\n assetPrefix: resolveAssetPrefix(config.assetPrefix, routePrefix),\n logo: config.logo,\n homeUrl: config.homeUrl,\n favicon: config.favicon,\n theme: resolveThemeConfig(config.theme),\n navigation: config.navigation,\n banner: config.banner,\n footer: config.footer,\n locales: resolveLocalesConfig(config.locales),\n variables: config.variables ?? {},\n features: resolveFeaturesConfig(config.features),\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { loadConfigFromFile } from 'vite'\nimport type { ConfigEnv } from 'vite'\n\nimport type { ClarifyProjectConfig, ClarifyPlugin } from '../../types.js'\n\nimport { validateProjectConfig } from './config.js'\n\nexport type ClarifyConfig = ClarifyProjectConfig & {\n plugins?: ClarifyPlugin[]\n}\n\nexport function defineConfig(config: ClarifyConfig): ClarifyConfig {\n return validateClarifyConfig(config)\n}\n\n/**\n * Config filenames Clarify CLI looks for at the project root, in resolution\n * order. Exported so other modules (e.g. the dev `project-info` endpoint) can\n * surface the same list to tooling without duplicating it.\n */\nexport const CONFIG_FILENAMES = [\n 'clarify.ts',\n 'clarify.js',\n 'clarify.json',\n] as const\n\nexport function findClarifyConfigFile(root: string): string | undefined {\n for (const filename of CONFIG_FILENAMES) {\n const filePath = resolve(root, filename)\n if (existsSync(filePath)) return filePath\n }\n return undefined\n}\n\nfunction assertConfigObject(config: unknown, configFile: string): Record<string, unknown> {\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error(`[clarify] ${configFile} must export a configuration object`)\n }\n return config as Record<string, unknown>\n}\n\nfunction loadJsonConfig(configFile: string): ClarifyConfig {\n const config = assertConfigObject(JSON.parse(readFileSync(configFile, 'utf-8')), configFile)\n if ('plugins' in config) {\n throw new Error('[clarify] clarify.json does not support plugins; use clarify.ts or clarify.js')\n }\n return validateClarifyConfig(config)\n}\n\nfunction validateClarifyConfig(config: ClarifyConfig | Record<string, unknown>): ClarifyConfig {\n const { plugins, ...projectConfigInput } = config\n if (plugins !== undefined && !Array.isArray(plugins)) {\n throw new Error('[clarify] config field \"plugins\" is invalid: Expected an array')\n }\n const projectConfig = validateProjectConfig(projectConfigInput)\n return plugins ? { ...projectConfig, plugins } : projectConfig\n}\n\nexport async function loadClarifyConfig(root: string, env: ConfigEnv): Promise<ClarifyConfig> {\n const configFile = findClarifyConfigFile(root)\n if (!configFile) return {}\n\n if (configFile.endsWith('.json')) {\n return loadJsonConfig(configFile)\n }\n\n const loaded = await loadConfigFromFile(env, configFile, root, 'silent')\n const config = assertConfigObject(loaded?.config, configFile)\n return validateClarifyConfig(config)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport type { ClarifyProjectContext } from '../../types.js'\nimport { CONFIG_FILENAMES } from '../config/user-config.js'\n\n/**\n * Dev-only HTTP endpoint that exposes project metadata so external tooling\n * (e.g. the VS Code extension) can discover which files Clarify recognizes\n * without hardcoding conventions that may drift between CLI versions.\n *\n * Mounted at `GET /dev/project-info`. Returns a JSON object describing:\n * - `configFilenames`: config files Clarify looks for at the project root.\n * - `contentFileExtensions`: file extensions treated as content files.\n * - `contentRoot`: the resolved content root directory name (relative to\n * the project root, e.g. `\"source\"`).\n * - `projectRoot`: the absolute project root path.\n * - `locales`: locale information when localization is configured.\n */\nexport const CLARIFY_DEV_PROJECT_INFO_ENDPOINT = '/dev/project-info'\n\n/**\n * File extensions Clarify treats as content files. Kept in sync with the\n * patterns used by route discovery in `parsers/routes.ts` and the OpenAPI\n * page generator. Exposed to tooling so the extension's \"is this a content\n * file?\" check stays accurate without duplicating the regex.\n */\nexport const CONTENT_FILE_EXTENSIONS = [\n '.md',\n '.mdx',\n '.openapi.json',\n '.openapi.yaml',\n '.openapi.yml',\n] as const\n\nexport type ProjectInfoResponse = {\n configFilenames: readonly string[]\n contentFileExtensions: readonly string[]\n contentRoot: string\n projectRoot: string\n locales?: {\n default: string\n locales: string[]\n }\n}\n\n/**\n * Build the project-info response payload from the resolved plugin state.\n */\nexport function buildProjectInfo(context: ClarifyProjectContext): ProjectInfoResponse {\n const { projectRoot, contentRoot, projectConfig } = context\n // `contentRoot` is an absolute path (join(root, rootDirectory)); expose the\n // relative directory name so tooling can reason about file locations\n // without assuming a specific absolute path.\n const contentRootName = contentRoot.startsWith(projectRoot)\n ? contentRoot.slice(projectRoot.length).replace(/^[/\\\\]+/, '')\n : contentRoot\n\n const response: ProjectInfoResponse = {\n configFilenames: CONFIG_FILENAMES,\n contentFileExtensions: CONTENT_FILE_EXTENSIONS,\n contentRoot: contentRootName || 'source',\n projectRoot,\n }\n\n if (projectConfig.locales) {\n response.locales = {\n default: projectConfig.locales.default,\n locales: projectConfig.locales.locales.map(l => l.code),\n }\n }\n\n return response\n}\n\n/**\n * Handle a request to the project-info endpoint. Responds to any method\n * (GET is typical) with the JSON payload — there is no request body to parse.\n */\nexport function handleProjectInfoRequest(_req: IncomingMessage, res: ServerResponse, context: ClarifyProjectContext): void {\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n res.end(JSON.stringify(buildProjectInfo(context)))\n}\n","import type { UISlotRegistration } from '@clarify-labs/renderer'\n\nimport type { ClarifyPlugin, ContentDiagnostic, ContentRoute, ContentSection, MarkdownContentRoute, NavigationTree, ResolvedBuildOptions, ResolvedProjectConfig } from '../../types.js'\n\n// 新的虚拟模块命名 - 更清晰的职责划分\nconst VIRTUAL_CONFIG = 'virtual:clarify/config'\nexport const VIRTUAL_ROUTES = 'virtual:clarify/routes'\nconst VIRTUAL_SERVER_ROUTES = 'virtual:clarify/routes/server'\nexport const VIRTUAL_OPENAPI = 'virtual:clarify/openapi'\nexport const VIRTUAL_OPENAPI_SERVER = 'virtual:clarify/openapi/server'\nconst VIRTUAL_SLOTS = 'virtual:clarify/slots'\nconst VIRTUAL_SLOT = 'virtual:clarify/slot'\nexport const VIRTUAL_CLIENT_ENTRY = 'virtual:clarify/entry-client'\nconst RESOLVED_CLIENT_ENTRY = '\\0' + VIRTUAL_CLIENT_ENTRY\n\nexport type VirtualModules = Map<string, string>\n\ntype BuildVirtualModulesArgs = {\n generateOptions: ResolvedBuildOptions\n projectConfig: ResolvedProjectConfig\n routes: ContentRoute[]\n version?: string\n plugins?: ClarifyPlugin[]\n navigation: NavigationTree\n themeEditor?: boolean\n}\n\ntype CreateClientEntryModuleOptions = {\n themeEditor?: boolean\n}\n\nexport function resolveVirtualId(id: string): string {\n return '\\0' + id\n}\n\nexport function stripVirtualPrefix(id: string): string {\n return id.startsWith('\\0') ? id.slice(1) : id\n}\n\nexport function virtualContentModuleId(route: MarkdownContentRoute): string {\n return route.module.contentVirtualModuleId\n}\n\n/**\n * Fixed virtual module IDs (excluding the client entry, which has a special\n * resolved form). Used to avoid hardcoding the constant list in every\n * `resolveId` implementation.\n */\nconst FIXED_VIRTUAL_IDS = [\n VIRTUAL_CONFIG,\n VIRTUAL_ROUTES,\n VIRTUAL_SERVER_ROUTES,\n VIRTUAL_OPENAPI,\n VIRTUAL_OPENAPI_SERVER,\n VIRTUAL_SLOTS,\n VIRTUAL_SLOT,\n] as const\n\n/**\n * Shared `resolveId` logic for all Clarify virtual modules. Used by both the\n * Vite core plugin (dev + build) and the SSG virtual plugin so the ID-to-\n * resolved-ID mapping has a single source of truth.\n *\n * Returns the resolved ID (with `\\0` prefix per Vite convention) or `null`\n * if the ID is not a Clarify virtual module.\n */\nexport function resolveVirtualModuleId(id: string, modules: VirtualModules, routes: readonly ContentRoute[]): string | null {\n if (id === VIRTUAL_CLIENT_ENTRY || id === RESOLVED_CLIENT_ENTRY) return RESOLVED_CLIENT_ENTRY\n\n for (const virtualId of FIXED_VIRTUAL_IDS) {\n if (id === virtualId || id === resolveVirtualId(virtualId)) return resolveVirtualId(virtualId)\n }\n\n const moduleId = stripVirtualPrefix(id)\n if (modules.has(moduleId)) return resolveVirtualId(moduleId)\n\n const contentRoute = routes.find(route => (route.kind === 'markdown' || route.kind === 'markdown+jsx') && route.module.contentVirtualModuleId === moduleId)\n if (contentRoute) return contentRoute.source.filePath\n\n const route = routes.find(route => route.module.pageVirtualModuleId === id || route.module.pageVirtualModuleId === moduleId)\n if (route) return resolveVirtualId(route.module.pageVirtualModuleId)\n\n return null\n}\n\nexport function generateConfigModule(projectConfig: ResolvedProjectConfig, version?: string): string {\n const runtimeConfig: Record<string, unknown> = {\n title: projectConfig.title,\n description: projectConfig.description,\n siteUrl: projectConfig.siteUrl,\n routePrefix: projectConfig.routePrefix,\n assetPrefix: projectConfig.assetPrefix,\n logo: projectConfig.logo,\n homeUrl: projectConfig.homeUrl,\n favicon: projectConfig.favicon,\n theme: projectConfig.theme,\n navigation: projectConfig.navigation,\n banner: projectConfig.banner,\n footer: projectConfig.footer,\n locales: projectConfig.locales,\n variables: projectConfig.variables,\n features: projectConfig.features,\n }\n if (version) {\n runtimeConfig.version = version\n }\n return `export const config = ${JSON.stringify(runtimeConfig)};`\n}\n\nfunction moduleSpecifier(value: string): string {\n return JSON.stringify(value)\n}\n\ntype RuntimeRouteComponentExpression = string\n\ntype RuntimeRouteIdentity = {\n path: string\n basePath?: string\n locale?: string\n alternates?: Record<string, string>\n isFallback?: true\n isBareAlias?: true\n}\n\ntype RuntimeRouteMetadata = {\n title: string\n description?: string\n keywords?: string[]\n sections?: ContentSection[]\n}\n\ntype RuntimeRouteContentLinks = {\n contentArtifactUrl?: string\n sourceEditUrl?: string\n}\n\ntype RuntimeRouteManifestEntry = RuntimeRouteIdentity & RuntimeRouteMetadata & RuntimeRouteContentLinks & {\n component: RuntimeRouteComponentExpression\n lazy?: true\n kind: ContentRoute['kind']\n}\n\nfunction routeToRuntimeManifestEntry(route: ContentRoute, component: RuntimeRouteComponentExpression, mode: 'client' | 'server'): RuntimeRouteManifestEntry {\n const entry: RuntimeRouteManifestEntry = {\n path: route.path,\n title: route.meta.title,\n component,\n kind: route.kind,\n }\n\n if (mode === 'client') entry.lazy = true\n if (route.basePath) entry.basePath = route.basePath\n if (route.locale) entry.locale = route.locale\n if (route.isFallback) entry.isFallback = true\n if (route.isBareAlias) entry.isBareAlias = true\n if (route.alternates) entry.alternates = route.alternates\n if (route.meta.description) entry.description = route.meta.description\n if (route.meta.keywords?.length) entry.keywords = route.meta.keywords\n if (route.artifacts?.contentArtifactUrl) entry.contentArtifactUrl = route.artifacts.contentArtifactUrl\n if (route.source?.sourceEditUrl) entry.sourceEditUrl = route.source.sourceEditUrl\n if (route.meta.sections?.length) {\n entry.sections = route.meta.sections.map(section => ({ id: section.id, title: section.title, level: section.level, badge: section.badge, tags: section.tags }))\n }\n\n return entry\n}\n\nexport function generateRoutesModule(routes: ContentRoute[], navigation: NavigationTree, mode: 'client' | 'server' = 'client'): string {\n const imports = mode === 'server'\n ? routes.map((r, i) => `import Page${i} from ${moduleSpecifier(r.module.pageVirtualModuleId)};`).join('\\n')\n : `import { createContentDiagnosticComponent } from '@clarify-labs/renderer';`\n\n // `component` is a raw JS expression (an identifier or arrow function),\n // not a JSON string. We serialize each route object with a unique placeholder\n // for the component, then replace it with the actual expression source.\n // This keeps the rest of the object fully type-checked via JSON.stringify\n // while avoiding fragile string concatenation for every field.\n const routeEntries = routes.map((r, i) => {\n const component = mode === 'server'\n ? `Page${i}`\n : `() => import(${moduleSpecifier(r.module.pageVirtualModuleId)}).catch((error) => Promise.resolve({ default: createContentDiagnosticComponent({ kind: 'route-load', title: 'This page could not be loaded', message: error instanceof Error ? error.message : String(error), details: error instanceof Error ? error.stack : undefined }) }))`\n const placeholder = `__COMPONENT_${i}__`\n const manifestEntry = routeToRuntimeManifestEntry(r, placeholder, mode)\n const json = JSON.stringify(manifestEntry, null, 0)\n // JSON.stringify quotes all keys and omits spaces after colons. Convert to\n // idiomatic JS object-literal syntax: unquote identifier keys, pad colons\n // with a single space. Non-identifier keys (none currently, but defensive)\n // keep their quotes. Replace the component placeholder first, before the\n // key-unquoting regex runs, so the placeholder (an identifier) is not\n // turned into a bare key.\n const jsObject = json\n .replace(`\"${placeholder}\"`, component)\n .replace(/\"([A-Za-z_$][\\w$]*)\":/g, '$1: ')\n return ` ${jsObject}`\n }).join(',\\n')\n\n return `${imports}\\n\\nexport const routes = [\\n${routeEntries}\\n];\\n\\nexport const navigation = ${JSON.stringify(navigation, null, 2)};\\n`\n}\n\nexport function createClientEntryModule(options: CreateClientEntryModuleOptions = {}): string {\n return `\nimport '@clarify-labs/renderer/style.css';\nimport { render } from '@clarify-labs/renderer/client';\nimport { routes, navigation } from '${VIRTUAL_ROUTES}';\nimport { config } from '${VIRTUAL_CONFIG}';\nimport { openApiSpecs } from '${VIRTUAL_OPENAPI}';\nimport { runtimeSlots } from '${VIRTUAL_SLOTS}';\nconst renderOptions = { config, routes, navigation, openApiSpecs, runtimeSlots, themeEditor: ${JSON.stringify(options.themeEditor ?? false)} };\nrender(renderOptions);\nif (import.meta.hot) {\n import.meta.hot.accept('${VIRTUAL_ROUTES}', (mod) => {\n render({ ...renderOptions, routes: mod.routes, navigation: mod.navigation });\n });\n}`\n}\n\n/**\n * Collect every plugin's `slots` declarations into a single runtime registry\n * module. Component modules are exported as lazy import factories so the\n * renderer can decide whether to code-split (client) or pre-resolve (SSR).\n *\n * Relative component paths are resolved against the project `root` so that\n * the generated `import()` call uses an absolute specifier — Vite cannot\n * resolve relative imports from virtual modules.\n *\n * Slot name validity is enforced at compile time by the `UISlotName`\n * type — no runtime validation is needed.\n */\nexport function createRuntimeSlotsModule(plugins: ClarifyPlugin[] = [], root: string = process.cwd()): string {\n const registrations: { plugin: string; slot: UISlotRegistration }[] = []\n for (const plugin of plugins) {\n for (const slot of plugin.slots ?? []) {\n registrations.push({ plugin: plugin.name, slot })\n }\n }\n\n if (registrations.length === 0) {\n return 'export const runtimeSlots = {};\\n'\n }\n\n const grouped = new Map<string, string[]>()\n for (const { plugin, slot } of registrations) {\n // Warn when multiple plugins register the same replace slot — only the\n // last one takes effect, which is almost certainly a configuration error.\n if (slot.name.endsWith('.replace')) {\n const existing = grouped.get(slot.name)\n if (existing) {\n console.warn(`[clarify] Multiple plugins register slot \"${slot.name}\": \"${plugin}\" overrides \"${existing[existing.length - 1]}\". Only the last registration is used.`)\n }\n }\n\n // Resolve `/`-prefixed paths relative to the project root so that\n // Vite can resolve the import from the virtual module.\n if (!slot.component.startsWith('/')) {\n throw new Error(`[clarify] Plugin \"${plugin}\" slot \"${slot.name}\" has an invalid component path \"${slot.component}\". Component paths must start with \"/\" to reference the project root.`)\n }\n const componentPath = root + slot.component\n const entry = `{ plugin: ${JSON.stringify(plugin)}, loadComponent: () => import(${moduleSpecifier(componentPath)}) }`\n const list = grouped.get(slot.name) ?? []\n list.push(entry)\n grouped.set(slot.name, list)\n }\n\n const entries = [...grouped.entries()]\n .map(([name, list]) => ` ${JSON.stringify(name)}: [\\n ${list.join(',\\n ')}\\n ]`)\n .join(',\\n')\n\n return `export const runtimeSlots = {\\n${entries}\\n};\\n`\n}\n\nexport function generateContentDiagnosticModule(diagnostic: ContentDiagnostic): string {\n return `import { createContentDiagnosticComponent } from '@clarify-labs/renderer';\n\nexport const contentDiagnostic = ${JSON.stringify(diagnostic)};\n\nexport default createContentDiagnosticComponent(contentDiagnostic);\n`\n}\n\nexport function buildVirtualModules(args: BuildVirtualModulesArgs): VirtualModules {\n const modules: VirtualModules = new Map()\n const clientEntryModule = createClientEntryModule({ themeEditor: args.themeEditor })\n \n // Collect all plugins\n const allPlugins: ClarifyPlugin[] = [...(args.plugins ?? [])]\n \n modules.set(VIRTUAL_CONFIG, generateConfigModule(args.projectConfig, args.version))\n modules.set(VIRTUAL_ROUTES, generateRoutesModule(args.routes, args.navigation, 'client'))\n modules.set(VIRTUAL_SERVER_ROUTES, generateRoutesModule(args.routes, args.navigation, 'server'))\n modules.set(VIRTUAL_SLOTS, createRuntimeSlotsModule(allPlugins, args.generateOptions.projectRoot))\n modules.set(VIRTUAL_SLOT, \"export { useSlot } from '@clarify-labs/renderer';\\n\")\n modules.set(VIRTUAL_OPENAPI, 'export const openApiSpecs = {};')\n modules.set(RESOLVED_CLIENT_ENTRY, clientEntryModule)\n modules.set(VIRTUAL_CLIENT_ENTRY, clientEntryModule)\n\n for (const route of args.routes) {\n const moduleContent = route.diagnostic\n ? generateContentDiagnosticModule(route.diagnostic)\n : route.kind === 'markdown' || route.kind === 'markdown+jsx'\n ? `export { default } from ${moduleSpecifier(virtualContentModuleId(route))};`\n : null\n if (moduleContent === null) continue\n modules.set(route.module.pageVirtualModuleId, moduleContent)\n }\n\n return modules\n}\n","import { isAbsolute, join, relative } from 'node:path'\n\nimport mdxPlugin, { type Options as MdxPluginOptions } from '@mdx-js/rollup'\nimport tailwindcss from '@tailwindcss/vite'\nimport react from '@vitejs/plugin-react'\nimport rehypeRaw from 'rehype-raw'\nimport type { Plugin, ResolvedConfig, ViteDevServer } from 'vite'\n\nimport { createContentCompileDiagnostic, rehypePlugins, remarkPlugins } from '../parsers/markdown/mdx.js'\nimport { CLARIFY_DEV_ROUTE_ENDPOINT, handleDevRouteRequest } from '../parsers/router/dev-routes.js'\nimport type { ContentRoute, NavigationTree } from '../types.js'\n\nimport { type ClarifyEngine } from './engine/engine.js'\nimport { CLARIFY_DEV_PROJECT_INFO_ENDPOINT, handleProjectInfoRequest } from './project/project-info.js'\nimport {\n VIRTUAL_CLIENT_ENTRY,\n VIRTUAL_ROUTES,\n generateContentDiagnosticModule,\n resolveVirtualId,\n resolveVirtualModuleId,\n} from './runtime/virtual-modules.js'\n\ntype DevStructureSnapshot = {\n routes: string\n navigation: string\n}\n\nfunction routeStructure(route: ContentRoute): ContentRoute {\n const { content: _content, ...source } = route.source\n return { ...route, source }\n}\n\nfunction createDevStructureSnapshot(routes: ContentRoute[], navigation: NavigationTree): DevStructureSnapshot {\n return {\n routes: JSON.stringify(routes.map(routeStructure)),\n navigation: JSON.stringify(navigation),\n }\n}\n\nfunction hasDevStructureChanged(before: DevStructureSnapshot, after: DevStructureSnapshot): boolean {\n return before.routes !== after.routes || before.navigation !== after.navigation\n}\n\nfunction invalidateVirtualModules(engine: ClarifyEngine, server: ViteDevServer): void {\n for (const id of engine.modules.keys()) {\n const moduleNode = server.moduleGraph.getModuleById(resolveVirtualId(id))\n if (moduleNode) server.moduleGraph.invalidateModule(moduleNode)\n }\n}\n\nasync function refreshDevServer(engine: ClarifyEngine, server: ViteDevServer): Promise<boolean> {\n const before = createDevStructureSnapshot(engine.routes, engine.navigation)\n await engine.refresh()\n invalidateVirtualModules(engine, server)\n const after = createDevStructureSnapshot(engine.routes, engine.navigation)\n return hasDevStructureChanged(before, after)\n}\n\nfunction createNormalizedContentPlugin(engine: ClarifyEngine): Plugin {\n return {\n name: 'clarify:normalized-content',\n enforce: 'pre',\n transform(_code, id) {\n if (!/\\.mdx?(?:\\?|$)/.test(id)) return null\n const filePath = id.replace(/\\?.*$/, '')\n const route = engine.routes.find(route => (route.kind === 'markdown+jsx' || route.kind === 'markdown') && route.source.filePath === filePath)\n if (!route || route.source.content === undefined) return null\n return { code: route.source.content, map: null }\n },\n }\n}\n\ntype ContentFormat = 'markdown' | 'markdown+jsx'\ntype ContentCompileErrorPolicy = 'diagnostic' | 'throw'\ntype TransformHook = NonNullable<Plugin['transform']> extends infer Hook ? Hook extends (...args: never[]) => unknown ? Hook : never : never\n\nexport function createContentCompileTransform(transform: TransformHook, format: ContentFormat, projectRoot: string, errorPolicy: () => ContentCompileErrorPolicy = () => 'diagnostic'): NonNullable<Plugin['transform']> {\n return async function contentCompileTransform(code, id) {\n try {\n return await transform.call(this, code, id)\n } catch (error) {\n if (errorPolicy() === 'throw') throw error\n const filePath = id.replace(/\\?.*$/, '')\n return {\n code: generateContentDiagnosticModule(createContentCompileDiagnostic({\n format,\n phase: 'compilation',\n error,\n filePath,\n projectRoot,\n })),\n map: null,\n }\n }\n }\n}\n\nfunction createContentCompilerPlugin(format: ContentFormat, projectRoot: string, errorPolicy: () => ContentCompileErrorPolicy): Plugin {\n const markdown = format === 'markdown'\n const plugin = mdxPlugin({\n include: [markdown ? '**/*.md' : '**/*.mdx'],\n format: markdown ? 'md' : 'mdx',\n jsxImportSource: 'react',\n providerImportSource: '@clarify-labs/renderer',\n remarkPlugins: remarkPlugins as MdxPluginOptions['remarkPlugins'],\n ...(markdown ? { remarkRehypeOptions: { allowDangerousHtml: true } } : {}),\n rehypePlugins: markdown ? [rehypeRaw, ...rehypePlugins] : rehypePlugins,\n }) as Plugin\n const transform = typeof plugin.transform === 'function' ? plugin.transform : plugin.transform?.handler\n\n if (!transform) return plugin\n\n return {\n ...plugin,\n transform: createContentCompileTransform(transform, format, projectRoot, errorPolicy),\n }\n}\n\nfunction createClarifyViteCorePlugin(engine: ClarifyEngine, normalizedContentPlugin: Plugin, markdown: Plugin, mdx: Plugin): Plugin {\n let viteConfig: ResolvedConfig\n\n return {\n name: 'clarify:core',\n async config() {\n // The engine is already prepared (initialize + discoverSite + buildModules)\n // by the caller before constructing the Vite config. The adapter only\n // contributes Vite-level settings derived from the prepared engine state.\n return {\n base: engine.projectConfig.assetPrefix,\n build: {\n ...(engine.generateOptions.outputDirectory ? { outDir: engine.generateOptions.outputDirectory } : {}),\n manifest: true,\n },\n }\n },\n configResolved(config) {\n viteConfig = config\n engine.configureRuntime({\n command: config.command,\n mode: config.mode,\n outputDirectory: config.build.outDir,\n })\n if (!engine.generateOptions.outputDirectory) {\n engine.generateOptions.outputDirectory = config.build.outDir\n }\n },\n async buildStart() {\n if (!(await engine.beginBuild())) return\n engine.writeEnvTypes()\n },\n async handleHotUpdate(ctx) {\n const changedFile = isAbsolute(ctx.file) ? ctx.file : join(engine.root, ctx.file)\n if (engine.configFilePath && changedFile === engine.configFilePath) {\n // Config file changed: force re-prepare (initialize + discoverSite +\n // buildModules) with the current runtime mode, then reload.\n await engine.prepare({ command: 'serve', mode: viteConfig.mode }, engine.options, { force: true })\n invalidateVirtualModules(engine, ctx.server)\n ctx.server.ws.send({ type: 'full-reload' })\n return []\n }\n\n const relativeContentFile = relative(engine.contentRoot, changedFile)\n const isContentFile = relativeContentFile && !relativeContentFile.startsWith('..') && !isAbsolute(relativeContentFile)\n if (!isContentFile || !engine.hasContentRouteForFile(changedFile)) return\n\n const structureChanged = await refreshDevServer(engine, ctx.server)\n if (structureChanged) {\n const routesModule = ctx.server.moduleGraph.getModuleById(resolveVirtualId(VIRTUAL_ROUTES))\n if (routesModule) return [...ctx.modules, routesModule]\n ctx.server.ws.send({ type: 'full-reload' })\n return []\n }\n return ctx.modules\n },\n resolveId(id) {\n return resolveVirtualModuleId(id, engine.modules, engine.routes)\n },\n load(id) {\n return engine.loadModule(id)\n },\n async configureServer(server) {\n server.watcher.add(engine.contentRoot)\n if (engine.configFilePath) server.watcher.add(engine.configFilePath)\n\n server.middlewares.use((req, res, next) => {\n if (req.url === CLARIFY_DEV_ROUTE_ENDPOINT && req.method === 'POST') {\n return handleDevRouteRequest(req, res, engine.routes, engine.runtimeContext())\n }\n if (req.url === CLARIFY_DEV_PROJECT_INFO_ENDPOINT && (req.method === 'GET' || req.method === 'HEAD')) {\n return handleProjectInfoRequest(req, res, engine.runtimeContext())\n }\n next()\n })\n\n const handleContentTreeChange = async (filePath: string) => {\n const changedFile = isAbsolute(filePath) ? filePath : join(engine.root, filePath)\n const relativeContentFile = relative(engine.contentRoot, changedFile)\n const isContentFile = relativeContentFile && !relativeContentFile.startsWith('..') && !isAbsolute(relativeContentFile)\n if (!isContentFile) return\n const shouldReload = await refreshDevServer(engine, server)\n if (shouldReload) server.ws.send({ type: 'full-reload' })\n }\n\n server.watcher.on('add', handleContentTreeChange)\n server.watcher.on('unlink', handleContentTreeChange)\n const postHooks = await engine.configureDevServer(server)\n if (postHooks.length > 0) {\n return () => {\n for (const postHook of postHooks) postHook()\n }\n }\n },\n transformIndexHtml: {\n order: 'pre',\n async handler(html, transformCtx) {\n const clientEntryId = transformCtx.server\n ? `/@id/${VIRTUAL_CLIENT_ENTRY}`\n : VIRTUAL_CLIENT_ENTRY\n const result = await engine.transformHtml({\n html,\n tags: [],\n clientEntryId,\n dev: Boolean(transformCtx.server),\n })\n return {\n html: result.html,\n tags: result.tags,\n }\n },\n },\n async generateBundle() {\n const assets = await engine.collectBuildAssets()\n for (const asset of assets) {\n this.emitFile({\n type: 'asset',\n fileName: asset.fileName,\n source: asset.source,\n })\n }\n await engine.endBuild()\n },\n async closeBundle() {\n if (!engine.shouldRunBuild()) return\n engine.configureRuntime({\n outputDirectory: viteConfig.build.outDir,\n ssrPlugins: [engine.createSSGVirtualPlugin(), normalizedContentPlugin, markdown, mdx],\n })\n await engine.runSSG()\n },\n }\n}\n\n/**\n * Creates the Clarify Vite plugins bound to an already-prepared engine.\n *\n * The caller is responsible for running `engine.prepare()` (initialize +\n * discoverSite + buildModules) before constructing the Vite config that\n * includes these plugins. The adapter never initializes or discovers the\n * site itself - it only bridges Vite lifecycle hooks to the engine.\n */\nexport function createViteAdapter(engine: ClarifyEngine): Plugin[] {\n let contentCompileErrorPolicy: ContentCompileErrorPolicy = 'diagnostic'\n const errorPolicy = () => contentCompileErrorPolicy\n const normalizedContentPlugin = createNormalizedContentPlugin(engine)\n const markdown = createContentCompilerPlugin('markdown', engine.root, errorPolicy)\n const mdx = createContentCompilerPlugin('markdown+jsx', engine.root, errorPolicy)\n const compilePolicyPlugin: Plugin = {\n name: 'clarify:content-compile-policy',\n configResolved(config) {\n contentCompileErrorPolicy = config.command === 'build' ? 'throw' : 'diagnostic'\n },\n }\n // `react()` returns `Plugin[]`; `tailwindcss()` returns `Plugin | Plugin[]`;\n // the rest return a single `Plugin`. Spread the array-returning results so\n // every element is a `Plugin`, avoiding the `.flat().filter(Boolean) as\n // Plugin[]` escape hatch.\n const tailwind = tailwindcss()\n return [\n ...react(),\n ...(Array.isArray(tailwind) ? tailwind : [tailwind]),\n compilePolicyPlugin,\n normalizedContentPlugin,\n createClarifyViteCorePlugin(engine, normalizedContentPlugin, markdown, mdx),\n markdown,\n mdx,\n ]\n}\n","{\n \"name\": \"@clarify-labs/cli\",\n \"version\": \"0.11.5\",\n \"license\": \"AGPL-3.0-only\",\n \"type\": \"module\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/taicode-labs/clarify\",\n \"directory\": \"packages/cli\"\n },\n \"main\": \"output/index.cjs\",\n \"module\": \"output/index.js\",\n \"types\": \"output/index.d.ts\",\n \"bin\": {\n \"clarify\": \"bin/clarify.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./output/index.d.ts\",\n \"import\": \"./output/index.js\",\n \"require\": \"./output/index.cjs\",\n \"default\": \"./output/index.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"LICENSE\",\n \"bin\",\n \"output\"\n ],\n \"scripts\": {\n \"dev\": \"vite build --watch\",\n \"build\": \"vite build\",\n \"lint\": \"eslint source/\",\n \"lint:fix\": \"eslint source/ --fix\",\n \"typecheck\": \"tsc -p tsconfig.json --noEmit\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\"\n },\n \"dependencies\": {\n \"@apidevtools/swagger-parser\": \"^12.1.0\",\n \"@clarify-labs/renderer\": \"workspace:*\",\n \"@clarify-labs/templates\": \"workspace:*\",\n \"@mdx-js/mdx\": \"^3.1.1\",\n \"@mdx-js/rollup\": \"^3.1.1\",\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"@msgpack/msgpack\": \"^3.1.3\",\n \"@orama/orama\": \"^3.1.18\",\n \"@shikijs/rehype\": \"^4.3.0\",\n \"@tailwindcss/vite\": \"^4.3.2\",\n \"@vitejs/plugin-react\": \"^6.0.3\",\n \"cac\": \"^7.0.0\",\n \"github-slugger\": \"^2.0.0\",\n \"gray-matter\": \"^4.0.3\",\n \"mdast-util-to-string\": \"^4.0.0\",\n \"mermaid\": \"^11.4.0\",\n \"openapi-types\": \"^12.1.3\",\n \"pagefind\": \"^1.5.2\",\n \"react\": \"^19.1.0\",\n \"react-dom\": \"^19.1.0\",\n \"react-router\": \"^7.0.0\",\n \"react-router-dom\": \"^7.0.0\",\n \"react-zoom-pan-pinch\": \"^4.0.3\",\n \"rehype-raw\": \"^7.0.0\",\n \"rehype-slug\": \"^6.0.0\",\n \"remark\": \"^15.0.1\",\n \"shiki\": \"4.3.0\",\n \"unist-util-visit\": \"^5.1.0\",\n \"vite\": \"^8.1.4\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^4.4.3\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^19.2.17\",\n \"typescript\": \"^6.0.3\",\n \"vite-plugin-dts\": \"^5.0.3\",\n \"vitest\": \"^4.1.10\"\n }\n}\n","import packageJson from '../../package.json' with { type: 'json' }\n\nexport const cliPackageJson = packageJson as { version?: string }\nexport const cliPackageVersion = cliPackageJson.version ?? '0.0.0'\nexport const cliPackageVersionWithCaret = `^${cliPackageVersion}`\n\nexport function readPackageVersion(): string {\n return cliPackageVersion\n}\n","import type { ClarifyPlugin, ClarifyProjectConfig } from '../../types.js'\n\nexport type ClarifyBuildOptions = ClarifyProjectConfig & {\n /** Project root directory. Defaults to the current working directory. */\n projectRoot?: string\n /** Root directory for content sources. Default: 'source' */\n rootDirectory?: string\n /** Output directory for the built docs site. When omitted, Vite's build.outDir is used. */\n outputDirectory?: string\n\n /** Clarify plugin extensions for translation, search, and other build-time features. */\n plugins?: ClarifyPlugin[]\n}\n\nexport type ResolvedBuildOptions = {\n projectRoot: string\n rootDirectory: string\n outputDirectory?: string\n}\n\nexport function resolveBuildOptions(options: ClarifyBuildOptions = {}): ResolvedBuildOptions {\n return {\n projectRoot: options.projectRoot ?? process.cwd(),\n rootDirectory: options.rootDirectory ?? 'source',\n outputDirectory: options.outputDirectory,\n }\n}\n","import type { ContentRoute, ResolvedProjectConfig } from '../../types.js'\n\nconst UTF8_SIGNATURE = '\\uFEFF'\n\nfunction normalizeBasePath(basePath: string): string {\n if (!basePath || basePath === '/') return ''\n return '/' + basePath.replace(/^\\/+|\\/+$/g, '')\n}\n\nfunction containsNonAscii(content: string): boolean {\n return [...content].some(character => character.codePointAt(0)! > 0x7F)\n}\n\nfunction withUtf8Signature(content: string): string {\n if (!containsNonAscii(content) || content.startsWith(UTF8_SIGNATURE)) return content\n return `${UTF8_SIGNATURE}${content}`\n}\n\nfunction shouldUseUtf8Signature(route: ContentRoute): boolean {\n if (route.kind === 'markdown+jsx' || route.kind === 'markdown') return true\n return false\n}\n\nfunction routeToMarkdownArtifactUrl(routePath: string): string {\n const normalizedPath = routePath === '/' ? '/index' : routePath.replace(/\\/$/, '')\n return `${normalizedPath}.md`\n}\n\nfunction routeToOpenAPIArtifactUrl(routePath: string): string {\n const normalizedPath = routePath === '/' ? '/index' : routePath.replace(/\\/$/, '')\n return `${normalizedPath}.openapi.json`\n}\n\nexport function attachContentArtifactUrls(routes: ContentRoute[]): void {\n for (const route of routes) {\n route.artifacts = {\n ...route.artifacts,\n contentArtifactUrl: route.kind === 'openapi'\n ? routeToOpenAPIArtifactUrl(route.path)\n : routeToMarkdownArtifactUrl(route.path),\n }\n }\n}\n\nexport function readRouteContent(route: ContentRoute): string {\n if (route.source.content !== undefined) return route.source.content\n throw new Error(`Route content is missing from route context: ${route.source.filePath}`)\n}\n\nexport function readRouteArtifactContent(route: ContentRoute): string {\n const content = readRouteContent(route)\n return shouldUseUtf8Signature(route) ? withUtf8Signature(content) : content\n}\n\nfunction isLlmsTxtRoute(route: ContentRoute): boolean {\n return !route.path.split('/').includes('404')\n}\n\nfunction llmsTxtDescription(route: ContentRoute): string | undefined {\n if (route.meta.description) return route.meta.description\n\n const sections = route.meta.sections?.filter(section => section.level === 2).slice(0, 3).map(section => section.title)\n if (sections?.length) return `Covers ${sections.join(', ')}.`\n\n if (route.meta.keywords?.length) return `Related topics: ${route.meta.keywords.join(', ')}.`\n\n if (route.kind === 'openapi') return 'OpenAPI artifact for machine-readable API reference data.'\n\n return undefined\n}\n\nfunction llmsTxtListItem(route: ContentRoute, basePath: string): string | undefined {\n const contentArtifactUrl = route.artifacts?.contentArtifactUrl\n if (!contentArtifactUrl) return undefined\n\n const description = llmsTxtDescription(route)\n return description\n ? `- [${route.meta.title}](${basePath}${contentArtifactUrl}): ${description}`\n : `- [${route.meta.title}](${basePath}${contentArtifactUrl})`\n}\n\nfunction llmsTxtLocaleLabel(locale: string, projectConfig: ResolvedProjectConfig): string {\n return projectConfig.locales?.locales.find(item => item.code === locale)?.label ?? locale\n}\n\nfunction groupRoutesByLocale(routes: ContentRoute[]): Map<string, ContentRoute[]> {\n const groups = new Map<string, ContentRoute[]>()\n for (const route of routes) {\n const key = route.locale ?? 'default'\n groups.set(key, [...(groups.get(key) ?? []), route])\n }\n return groups\n}\n\nfunction groupLlmsTxtRoutesByLocale(routes: ContentRoute[], projectConfig: ResolvedProjectConfig): Map<string, ContentRoute[]> {\n const routesBySource = new Map<string, ContentRoute>()\n const defaultLocale = projectConfig.locales?.default\n\n for (const route of routes) {\n const sourceKey = `${route.locale ?? defaultLocale ?? 'default'}:${route.basePath ?? route.artifacts?.contentArtifactUrl ?? route.path}`\n const previousRoute = routesBySource.get(sourceKey)\n\n if (!previousRoute || (previousRoute.locale && !route.locale)) {\n routesBySource.set(sourceKey, route)\n }\n }\n\n return groupRoutesByLocale([...routesBySource.values()].map(route => ({\n ...route,\n locale: route.locale ?? defaultLocale,\n })))\n}\n\nfunction llmsTxtDocsSectionTitle(locale: string, groupCount: number, projectConfig: ResolvedProjectConfig): string {\n if (groupCount <= 1) return 'Docs'\n return `Docs - ${locale === 'default' ? 'Default' : llmsTxtLocaleLabel(locale, projectConfig)}`\n}\n\nexport function createLlmsTxt(routes: ContentRoute[], projectConfig: ResolvedProjectConfig): string {\n const basePath = normalizeBasePath(projectConfig.routePrefix)\n const lines = [\n `# ${projectConfig.title}`,\n '',\n ]\n\n if (projectConfig.description) {\n lines.push(`> ${projectConfig.description}`, '')\n }\n\n lines.push('This file lists the source-ready Markdown and OpenAPI artifacts for this documentation site.', '')\n\n // Exclude bare alias routes (e.g., /path without language prefix) in multilingual sites\n const markdownRoutes = routes.filter(route => (route.kind === 'markdown+jsx' || route.kind === 'markdown') && isLlmsTxtRoute(route) && !route.isBareAlias)\n if (markdownRoutes.length > 0) {\n const localizedGroups = groupLlmsTxtRoutesByLocale(markdownRoutes, projectConfig)\n for (const [locale, localeRoutes] of localizedGroups) {\n lines.push(`## ${llmsTxtDocsSectionTitle(locale, localizedGroups.size, projectConfig)}`)\n\n for (const route of localeRoutes) {\n const item = llmsTxtListItem(route, basePath)\n if (item) lines.push(item)\n }\n\n lines.push('')\n }\n }\n\n // Exclude bare alias routes (e.g., /path without language prefix) in multilingual sites\n const openApiRoutes = routes.filter(route => route.kind === 'openapi' && isLlmsTxtRoute(route) && !route.isBareAlias)\n if (openApiRoutes.length > 0) {\n if (lines.at(-1) !== '') lines.push('')\n lines.push('## OpenAPI')\n for (const route of openApiRoutes) {\n const item = llmsTxtListItem(route, basePath)\n if (item) lines.push(item)\n }\n }\n\n while (lines.at(-1) === '') lines.pop()\n return `${lines.join('\\n')}\\n`\n}\n\nexport function createLlmsTxtArtifact(routes: ContentRoute[], projectConfig: ResolvedProjectConfig): string {\n return withUtf8Signature(createLlmsTxt(routes, projectConfig))\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { stringify as yamlStringify } from 'yaml'\n\nimport type { ContentRoute, ResolvedProjectConfig } from '../../types.js'\n\nimport { createLlmsTxtArtifact, readRouteArtifactContent } from './artifacts.js'\n\nfunction normalizeRoutePrefix(routePrefix: string): string {\n if (!routePrefix || routePrefix === '/') return ''\n return `/${routePrefix.replace(/^\\/+|\\/+$/g, '')}`\n}\n\nexport function resolveContentArtifactPath(url: string | undefined, projectConfig: ResolvedProjectConfig): string {\n const requestPath = url?.split('?')[0] ?? ''\n const basePath = normalizeRoutePrefix(projectConfig.routePrefix)\n return basePath && requestPath.startsWith(basePath)\n ? requestPath.slice(basePath.length) || '/'\n : requestPath\n}\n\nexport function resolveContentArtifactType(route: ContentRoute): string {\n return route.kind === 'openapi'\n ? 'application/json; charset=utf-8'\n : 'text/markdown; charset=utf-8'\n}\n\nexport function serveContentArtifacts(req: IncomingMessage, res: ServerResponse, projectConfig: ResolvedProjectConfig, routes: ContentRoute[]): boolean {\n const contentPath = resolveContentArtifactPath(req.url, projectConfig)\n\n if (contentPath === '/llms.txt') {\n res.statusCode = 200\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end(createLlmsTxtArtifact(routes, projectConfig), 'utf8')\n return true\n }\n\n // Handle YAML variant for OpenAPI routes: /api.openapi.yaml → serve YAML\n if (contentPath.endsWith('.openapi.yaml')) {\n const jsonPath = contentPath.replace(/\\.yaml$/, '.json')\n const route = routes.find(route => route.artifacts?.contentArtifactUrl === jsonPath)\n if (route?.kind === 'openapi' && route.source.content) {\n const spec = JSON.parse(route.source.content)\n res.statusCode = 200\n res.setHeader('Content-Type', 'text/yaml; charset=utf-8')\n res.end(yamlStringify(spec, { lineWidth: 0 }), 'utf8')\n return true\n }\n return false\n }\n\n const route = routes.find(route => route.artifacts?.contentArtifactUrl === contentPath)\n if (!route) return false\n\n res.statusCode = 200\n res.setHeader('Content-Type', resolveContentArtifactType(route))\n res.end(readRouteArtifactContent(route), 'utf8')\n return true\n}\n","import type { ViteDevServer } from 'vite'\nimport { stringify as yamlStringify } from 'yaml'\n\nimport type { ClarifyEmitAsset, ClarifyPlugin } from '../../types.js'\n\nimport { attachContentArtifactUrls, createLlmsTxtArtifact, readRouteArtifactContent } from './artifacts.js'\nimport { serveContentArtifacts } from './server.js'\n\nexport function createContentArtifactsPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:content-artifacts',\n hooks: {\n 'routes:resolved': (input) => {\n attachContentArtifactUrls(input.routes)\n return input\n },\n 'dev:configureServer': (server: ViteDevServer, ctx) => {\n return () => {\n server.middlewares.use((req, res, next) => {\n if (serveContentArtifacts(req, res, ctx.projectConfig, ctx.routes)) return\n next()\n })\n }\n },\n 'build:assets': (ctx) => {\n const assets: ClarifyEmitAsset[] = []\n\n for (const route of ctx.routes) {\n const contentArtifactUrl = route.artifacts?.contentArtifactUrl\n if (!contentArtifactUrl) continue\n\n assets.push({\n fileName: contentArtifactUrl.replace(/^\\//, ''),\n source: readRouteArtifactContent(route),\n })\n\n if (route.kind === 'openapi' && route.source.content) {\n const yamlFileName = contentArtifactUrl.replace(/\\.json$/, '.yaml')\n const spec = JSON.parse(route.source.content)\n assets.push({\n fileName: yamlFileName.replace(/^\\//, ''),\n source: yamlStringify(spec, { lineWidth: 0 }),\n })\n }\n }\n\n assets.push({\n fileName: 'llms.txt',\n source: createLlmsTxtArtifact(ctx.routes, ctx.projectConfig),\n })\n\n return assets\n },\n },\n }\n}\n","import type { HtmlTagDescriptor } from 'vite'\n\nimport { themeBootstrapScript } from '@clarify-labs/renderer'\n\nimport type { ClarifyFaviconConfig, ClarifyPlugin } from '../../types.js'\n\nconst REL_ICON_RE = /<link\\s+[^>]*rel=[\"'][^\"']*\\bicon\\b[^\"']*[\"'][^>]*>/i\n\nfunction inferIconType(href: string): string | undefined {\n const path = href.split(/[?#]/, 1)[0]?.toLowerCase() ?? href.toLowerCase()\n\n if (path.endsWith('.svg')) return 'image/svg+xml'\n if (path.endsWith('.png')) return 'image/png'\n if (path.endsWith('.ico')) return 'image/x-icon'\n if (path.endsWith('.webp')) return 'image/webp'\n\n return undefined\n}\n\nfunction createIconTag(href: string, media?: string): HtmlTagDescriptor {\n return {\n tag: 'link',\n attrs: {\n rel: 'icon',\n ...(inferIconType(href) ? { type: inferIconType(href) } : {}),\n href,\n ...(media ? { media } : {}),\n },\n injectTo: 'head',\n }\n}\n\nfunction createIconTags(icon?: ClarifyFaviconConfig): HtmlTagDescriptor[] {\n if (!icon) return []\n\n if (typeof icon === 'string') return [createIconTag(icon)]\n\n const lightIcon = icon.light ?? icon.dark\n const darkIcon = icon.dark ?? icon.light\n\n if (!lightIcon || !darkIcon) return []\n if (lightIcon === darkIcon) return [createIconTag(lightIcon)]\n\n return [\n createIconTag(lightIcon, '(prefers-color-scheme: light)'),\n createIconTag(darkIcon, '(prefers-color-scheme: dark)'),\n ]\n}\n\nexport function createHtmlShellPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:html-shell',\n hooks: {\n 'html:transform': (input, ctx) => ({\n html: input.html,\n tags: [\n ...input.tags,\n ...(REL_ICON_RE.test(input.html) ? [] : createIconTags(ctx.projectConfig.favicon ?? ctx.projectConfig.logo)),\n {\n tag: 'script',\n children: themeBootstrapScript(ctx.projectConfig.theme),\n injectTo: 'head-prepend',\n },\n {\n tag: 'script',\n attrs: { type: 'module', src: input.clientEntryId },\n injectTo: 'body',\n },\n ],\n clientEntryId: input.clientEntryId,\n dev: input.dev,\n }),\n },\n }\n}\n","import type { ResolvedProjectConfig } from '../../types.js'\n\n/**\n * Descriptor for a single MCP capability surfaced by a Clarify site.\n *\n * Capabilities are intentionally open-ended so future versions can add\n * `resources`, `prompts`, etc. without reshaping the top-level file. Each\n * capability carries its own metadata block; the CLI selects the block(s)\n * it understands and ignores the rest.\n */\nexport type McpCapability = McpSearchCapability\n\n/**\n * Full-text search capability backed by an Orama binary index.\n */\nexport type McpSearchCapability = {\n /** Capability discriminator. */\n type: 'search'\n /**\n * Root-relative path to the Orama binary index (`.msp`) produced at build\n * time. Always served from the site root, so it already includes the\n * routePrefix when one is configured.\n */\n indexPath: string\n /** SHA-256 hash of the index payload at indexPath, for cache freshness checks. */\n indexHash?: string\n /** Locale used when the caller does not specify one. Drives tokenizer. */\n defaultLocale?: string\n /** Number of documents stored in the index. */\n documentCount: number\n /** Locales present in the index, for surfacing in tool descriptions. */\n locales: string[]\n}\n\n/**\n * MCP server descriptor emitted to `<output>/mcp.json` during build.\n *\n * Consumed by `clarify mcp <url>` to bootstrap a local MCP server that\n * exposes site capabilities (currently full-text search) to LLM clients.\n * The descriptor points the CLI at the Orama binary index (`.msp`) written\n * alongside `mcp.json` and carries the locale metadata needed to reconstruct\n * the tokenizer at runtime.\n */\nexport type McpSiteConfig = {\n /** Schema version of this file. Bumped on breaking shape changes. */\n version: 3\n site: {\n title?: string\n description?: string\n /** Canonical public site URL, if `siteUrl` is configured. */\n url?: string\n /** Route prefix where the site is mounted. Default: '/'. */\n routePrefix: string\n }\n /**\n * Capability map keyed by capability id. The id is stable across builds so\n * clients can address a specific capability (e.g. `search`) even as new\n * ones are added. Only capabilities actually emitted by the build are\n * present; an absent key means the site does not provide that capability.\n */\n capabilities: {\n search?: McpSearchCapability\n }\n}\n\n/**\n * Normalize a route prefix into a root-relative path segment.\n *\n * `'/'` -> `''`, `'/docs'` -> `'/docs'`, `'docs/'` -> `'/docs'`.\n */\nfunction normalizePrefix(routePrefix: string | undefined): string {\n if (!routePrefix || routePrefix === '/') return ''\n return `/${routePrefix.replace(/^\\/+|\\/+$/g, '')}`\n}\n\nexport type CreateMcpSiteConfigOptions = {\n documentCount: number\n locales: string[]\n indexHash: string\n}\n\n/**\n * Assemble the MCP site config from build-time metadata.\n *\n * Unlike the previous pagefind-based descriptor, this no longer reads an\n * entry JSON file - the Orama index is a single binary blob, so the caller\n * supplies the document count and locale list directly from the build step\n * that produced the index.\n */\nexport function createMcpSiteConfig(projectConfig: ResolvedProjectConfig, options: CreateMcpSiteConfigOptions): McpSiteConfig {\n const prefix = normalizePrefix(projectConfig.routePrefix)\n return {\n version: 3,\n site: {\n title: projectConfig.title,\n description: projectConfig.description,\n url: projectConfig.siteUrl,\n routePrefix: projectConfig.routePrefix ?? '/',\n },\n capabilities: {\n search: {\n type: 'search',\n indexPath: `${prefix}/mcp-search.msp`,\n indexHash: options.indexHash,\n defaultLocale: projectConfig.locales?.default,\n documentCount: options.documentCount,\n locales: options.locales,\n },\n },\n }\n}\n","import { readFileSync, writeFileSync } from 'node:fs'\nimport { brotliCompressSync, brotliDecompressSync, constants as zlibConstants } from 'node:zlib'\n\nimport { decode, encode } from '@msgpack/msgpack'\nimport { create, insertMultiple, search, save, load } from '@orama/orama'\nimport type { AnyOrama, Results } from '@orama/orama'\n\nimport type { ContentRoute } from '../../types.js'\n\nconst MSP_MAGIC = new Uint8Array([0x43, 0x4c, 0x41, 0x52, 0x49, 0x46, 0x59, 0x4d, 0x53, 0x50, 0x01])\n\nfunction hasMspMagic(buffer: Uint8Array): boolean {\n return buffer.byteLength >= MSP_MAGIC.byteLength\n && MSP_MAGIC.every((byte, index) => buffer[index] === byte)\n}\n\n/**\n * Orama schema for the MCP search index.\n *\n * - `path`, `title`, `description`, `content` are full-text searchable strings.\n * - `locale` is an `enum` so we can use `where: { locale: { eq } }` filters at\n * query time. (`string` fields cannot be filtered in Orama.)\n * - `keywords` is a `string[]` also indexed for full-text matching.\n */\nexport const mcpSearchSchema = {\n path: 'string',\n title: 'string',\n description: 'string',\n locale: 'enum',\n content: 'string',\n keywords: 'string[]',\n} as const\n\nexport type McpSearchDocument = {\n path: string\n title: string\n description: string\n locale: string\n content: string\n keywords: string[]\n}\n\n/**\n * Intl.Segmenter cache keyed by BCP 47 tag. Segmenter construction is not\n * cheap, and the MCP server issues many queries against the same locale, so\n * we reuse instances. The cache is module-scoped: build and runtime share it\n * in the same process, and separate processes get their own - which is fine.\n */\nconst segmenterCache = new Map<string, Intl.Segmenter>()\n\nfunction getSegmenter(locale: string): Intl.Segmenter {\n let seg = segmenterCache.get(locale)\n if (!seg) {\n seg = new Intl.Segmenter(locale, { granularity: 'word' })\n segmenterCache.set(locale, seg)\n }\n return seg\n}\n\n/**\n * Map a Clarify locale code (e.g. `zh-CN`, `en-US`, `ja-JP`) to a BCP 47 tag\n * suitable for `Intl.Segmenter`. Returns `null` for locales we intentionally\n * want to tokenize with the Latin/whitespace fallback (faster, and avoids\n * forcing CJK-style word segmentation on Latin scripts).\n */\nfunction segmenterLocale(locale: string | undefined): string | null {\n if (!locale) return null\n const lower = locale.toLowerCase()\n if (lower.startsWith('zh')) return 'zh-CN'\n if (lower.startsWith('ja')) return 'ja-JP'\n if (lower.startsWith('ko')) return 'ko-KR'\n return null\n}\n\n/**\n * Tokenize text for Orama indexing and querying.\n *\n * CJK locales use `Intl.Segmenter` (word granularity), which splits\n * spaceless scripts into words and individual characters. Latin/whitespace\n * locales fall back to a Unicode-aware split on spaces and punctuation.\n *\n * All tokens are lowercased so queries match regardless of case.\n */\nexport function tokenizeForSearch(text: string, locale?: string): string[] {\n if (!text) return []\n const segLocale = segmenterLocale(locale)\n if (segLocale) {\n const seg = getSegmenter(segLocale)\n return Array.from(seg.segment(text))\n .filter((s) => s.isWordLike)\n .map((s) => s.segment.toLowerCase())\n }\n // Latin / default: split on whitespace + punctuation, drop empties.\n return text\n .toLowerCase()\n .split(/[\\s\\p{P}]+/u)\n .filter(Boolean)\n}\n\n/**\n * Build an Orama tokenizer component bound to a specific default locale.\n *\n * The tokenizer receives the raw field value and the per-field language hint\n * from Orama (which we don't set per-field, so it falls back to the default\n * language). We resolve the segmenter locale from the default locale at\n * construction time so the same tokenizer handles all documents in a\n * predominantly single-locale index.\n *\n * For multi-locale indexes, the tokenizer is also used at query time. Since\n * the query locale is not known to Orama's tokenizer callback, we use the\n * index's default locale - this is acceptable because:\n * - CJK queries get CJK segmentation (correct)\n * - Latin queries against a CJK-default index still work because Latin\n * text has no word boundaries for CJK segmenters to mis-split; the\n * segmenter passes through Latin words as-is.\n */\nexport function createMcpTokenizer(defaultLocale?: string) {\n return {\n language: defaultLocale ?? 'en',\n normalizationCache: new Map<string, string>(),\n tokenize(raw: unknown, language?: string): string[] {\n const text = typeof raw === 'string' ? raw : String(raw ?? '')\n // `language` is Orama's per-field language; fall back to the index default.\n return tokenizeForSearch(text, language ?? defaultLocale)\n },\n }\n}\n\n/**\n * Compose the searchable text for a route. Shared between the Pagefind\n * (browser) and Orama (MCP) indexing paths so both backends see the same\n * field order and content.\n */\nexport function routeSearchContent(route: ContentRoute): string {\n return [\n route.meta.title,\n route.meta.description,\n route.meta.keywords?.join(' '),\n route.meta.sections?.map((section) => section.title).join(' '),\n route.source.content,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n}\n\n/**\n * Convert a `ContentRoute` into the document shape stored in the Orama index.\n */\nexport function routeToSearchDocument(route: ContentRoute, defaultLocale?: string): McpSearchDocument | null {\n // Skip bare alias routes (e.g. `/path` that just redirects to `/locale/path`)\n // to avoid indexing duplicate content in multilingual sites.\n if (route.isBareAlias) return null\n\n const content = routeSearchContent(route)\n if (!content.trim()) return null\n\n return {\n path: route.path,\n title: route.meta.title ?? '',\n description: route.meta.description ?? '',\n locale: route.locale ?? defaultLocale ?? 'en',\n content,\n keywords: route.meta.keywords ?? [],\n }\n}\n\n/**\n * Create an Orama index pre-configured with the MCP schema and CJK-aware\n * tokenizer. Both the build step and the runtime loader use this so the\n * tokenizer is guaranteed to match between indexing and querying.\n *\n * Annotated as `AnyOrama` (Orama's exported base type) rather than inferred\n * via `ReturnType<typeof create>` because the inference would pull in\n * Orama's internal component types (`DocumentsStore`, `Index`, `Sorter`)\n * which are not exported and break `.d.ts` generation (TS2883).\n */\nexport function createMcpSearchIndex(defaultLocale?: string): McpSearchDb {\n return create({\n schema: mcpSearchSchema,\n components: { tokenizer: createMcpTokenizer(defaultLocale) },\n })\n}\n\n/** Orama index instance type for the MCP search schema. */\nexport type McpSearchDb = AnyOrama<typeof mcpSearchSchema>\n\n/**\n * Insert search documents into an Orama index.\n */\nexport function indexSearchDocuments(db: McpSearchDb, documents: McpSearchDocument[]): void {\n if (documents.length === 0) return\n insertMultiple(db, documents)\n}\n\n/**\n * Build a ready-to-search Orama index from content routes.\n *\n * Filters out bare aliases and empty routes. Returns the populated db.\n */\nexport function buildSearchIndex(routes: ContentRoute[], defaultLocale?: string): { db: McpSearchDb; documentCount: number } {\n const db = createMcpSearchIndex(defaultLocale)\n const documents: McpSearchDocument[] = []\n for (const route of routes) {\n const doc = routeToSearchDocument(route, defaultLocale)\n if (doc) documents.push(doc)\n }\n indexSearchDocuments(db, documents)\n return { db, documentCount: documents.length }\n}\n\n/**\n * Collect the distinct locale codes that will be present in the Orama index,\n * in stable insertion order. Bare aliases are skipped (they duplicate the\n * default-locale route). Locales with no code fall back to the project\n * default so single-locale sites still surface one locale.\n */\nexport function collectIndexedLocales(routes: ContentRoute[], defaultLocale?: string): string[] {\n const seen = new Set<string>()\n const locales: string[] = []\n for (const route of routes) {\n if (route.isBareAlias) continue\n const code = route.locale ?? defaultLocale ?? 'en'\n if (!seen.has(code)) {\n seen.add(code)\n locales.push(code)\n }\n }\n return locales\n}\n\nexport type McpSearchParams = {\n query: string\n locale?: string\n limit?: number\n}\n\nexport type McpSearchHit = {\n path: string\n title: string\n description: string\n locale: string\n score: number\n excerpt: string\n keywords: string[]\n}\n\nexport type McpSearchResult = {\n hits: McpSearchHit[]\n count: number\n}\n\n/**\n * Search an Orama MCP index.\n *\n * Applies an optional locale filter (via the `enum` field) and returns a\n * compact, LLM-friendly hit shape. Excerpts are derived from the matched\n * content: Orama does not return highlighted excerpts, so we synthesize a\n * short window around the first query term occurrence.\n */\nexport function searchMcpIndex(db: McpSearchDb, params: McpSearchParams): McpSearchResult {\n const limit = Math.max(1, Math.min(50, params.limit ?? 10))\n // `search` (the sync variant) returns `Results` at runtime, but its type\n // signature is `Results | Promise<Results>` to also cover `searchAsync`.\n // We assert to `Results` since we intentionally call the sync form.\n const result = search(db, {\n term: params.query,\n limit,\n where: params.locale ? { locale: { eq: params.locale } } : undefined,\n }) as Results<McpSearchDocument>\n\n const hits: McpSearchHit[] = result.hits.map((hit) => {\n const doc = hit.document as McpSearchDocument\n return {\n path: doc.path,\n title: doc.title || guessTitleFromPath(doc.path),\n description: doc.description,\n locale: doc.locale,\n score: hit.score,\n excerpt: makeExcerpt(doc.content, params.query),\n keywords: doc.keywords,\n }\n })\n\n return { hits, count: result.count }\n}\n\n/**\n * Build a short excerpt around the first occurrence of any query term in the\n * content. Falls back to the beginning of the content if no term is found.\n */\nfunction makeExcerpt(content: string, query: string, maxLen = 240): string {\n if (!content) return ''\n const terms = query\n .toLowerCase()\n .split(/[\\s\\p{P}]+/u)\n .filter(Boolean)\n const lower = content.toLowerCase()\n let pos = -1\n for (const term of terms) {\n const i = lower.indexOf(term)\n if (i >= 0 && (pos < 0 || i < pos)) pos = i\n }\n if (pos < 0) pos = 0\n // Center the window on the first match, clamped to content bounds.\n const half = Math.floor(maxLen / 2)\n const start = Math.max(0, pos - half)\n const end = Math.min(content.length, start + maxLen)\n const prefix = start > 0 ? '…' : ''\n const suffix = end < content.length ? '…' : ''\n return `${prefix}${content.slice(start, end).trim()}${suffix}`\n}\n\nfunction guessTitleFromPath(path: string): string {\n if (!path) return '(untitled)'\n const segments = path.split('/').filter(Boolean)\n if (segments.length === 0) return 'Home'\n return segments[segments.length - 1]\n .replace(/\\.(md|mdx|html)$/, '')\n .replace(/[-_]/g, ' ')\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\n/**\n * Serialize an Orama index to a versioned, Brotli-compressed binary buffer.\n *\n * Uses `save()` to extract the raw index data, MessagePack-encodes it, then\n * compresses the payload so source documents are not embedded as contiguous\n * plaintext. The leading magic bytes identify the container and its version.\n */\nexport function serializeSearchIndex(db: McpSearchDb): Uint8Array {\n const raw = save(db)\n const packed = encode(raw)\n const compressed = brotliCompressSync(packed, {\n params: {\n [zlibConstants.BROTLI_PARAM_QUALITY]: 9,\n },\n })\n const buffer = new Uint8Array(MSP_MAGIC.byteLength + compressed.byteLength)\n buffer.set(MSP_MAGIC)\n buffer.set(compressed, MSP_MAGIC.byteLength)\n return buffer\n}\n\n/**\n * Deserialize a current compressed container or legacy MessagePack buffer\n * into a ready-to-search Orama index.\n *\n * The caller must supply the same `defaultLocale` used when the index was\n * built, so the tokenizer matches. A mismatch would not corrupt data but\n * would cause CJK query terms to be tokenized incorrectly (e.g. \"文档\" left\n * as a single token instead of split into \"文\" + \"档\").\n */\nexport function deserializeSearchIndex(buffer: Uint8Array, defaultLocale?: string): McpSearchDb {\n const packed = hasMspMagic(buffer)\n ? brotliDecompressSync(buffer.subarray(MSP_MAGIC.byteLength))\n : buffer\n const raw = decode(packed) as ReturnType<typeof save>\n const db = createMcpSearchIndex(defaultLocale)\n load(db, raw)\n return db\n}\n\n/**\n * Write an Orama index to a versioned `.msp` file on disk.\n */\nexport function writeSearchIndex(db: McpSearchDb, filePath: string): void {\n writeFileSync(filePath, serializeSearchIndex(db))\n}\n\n/**\n * Read a current or legacy Orama `.msp` index from disk.\n */\nexport function readSearchIndex(filePath: string, defaultLocale?: string): McpSearchDb {\n return deserializeSearchIndex(readFileSync(filePath), defaultLocale)\n}\n","import { createHash } from 'node:crypto'\n\nimport type { ClarifyEmitAsset, ClarifyPlugin } from '../../types.js'\n\nimport { createMcpSiteConfig } from './mcp-config.js'\nimport { buildSearchIndex, collectIndexedLocales, serializeSearchIndex } from './orama-index.js'\n\n/**\n * MCP search index plugin.\n *\n * Generates the Orama binary index (`mcp-search.msp`) and the MCP site\n * descriptor (`mcp.json`) as build assets consumed by the `clarify mcp`\n * command to serve documentation search to MCP-aware clients (e.g. AI coding\n * assistants).\n *\n * This plugin is independent of `clarify:page-search` (Pagefind), which\n * powers in-browser search. The MCP server runs in Node and needs a\n * self-contained, compact index with CJK-aware tokenization that doesn't\n * depend on the browser-only Pagefind runtime.\n */\nexport function createMcpSearchPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:mcp-search',\n hooks: {\n 'build:assets'(ctx) {\n const searchConfig = ctx.projectConfig.features.search\n if (!searchConfig.enabled || !searchConfig.mcp) return []\n\n const defaultLocale = ctx.projectConfig.locales?.default\n const { db, documentCount } = buildSearchIndex(ctx.routes, defaultLocale)\n const locales = collectIndexedLocales(ctx.routes, defaultLocale)\n const indexBytes = serializeSearchIndex(db)\n const indexHash = createHash('sha256').update(indexBytes).digest('hex')\n const mcpConfig = createMcpSiteConfig(ctx.projectConfig, { documentCount, locales, indexHash })\n\n const prefix = mcpConfig.capabilities.search?.indexPath.replace(/\\/mcp-search\\.msp$/, '') ?? ''\n const assets: ClarifyEmitAsset[] = [\n {\n fileName: `${prefix}/mcp-search.msp`.replace(/^\\//, ''),\n source: indexBytes,\n },\n {\n fileName: 'mcp.json',\n source: `${JSON.stringify(mcpConfig, null, 2)}\\n`,\n },\n ]\n\n console.log(`[clarify] MCP search index (${documentCount} docs, ${locales.length} locales) written to mcp-search.msp.`)\n return assets\n },\n },\n }\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { join, relative, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport SwaggerParser from '@apidevtools/swagger-parser'\nimport { slug } from 'github-slugger'\n\nimport { pageVirtualModuleIdFromRef } from '../../core/runtime/module-ids.js'\nimport type { ContentProcessor } from '../../parsers/content/content.js'\nimport { createContentDiagnostic } from '../../parsers/content/diagnostic.js'\nimport { kebabToTitle, routePathFromRef } from '../../parsers/routes/routes.js'\nimport type { ContentDiagnostic, ContentSection, OpenAPIContentRoute, OpenAPISpec } from '../../types.js'\n\nconst OPENAPI_HTTP_METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'] as const\nconst CLARIFY_OPENAPI_SECTION_ID_EXTENSION = 'x-clarify-section-id'\n\ntype ResolverFileInfo = { url: string }\n\nexport type OpenAPIParseResult =\n | { ok: true; spec: OpenAPISpec }\n | { ok: false; diagnostic: ContentDiagnostic }\n\nfunction isSameOpenAPIFile(url: string, filePath: string): boolean {\n try {\n return resolve(fileURLToPath(url)) === resolve(filePath)\n } catch {\n return resolve(url) === resolve(filePath)\n }\n}\n\nexport function findOpenAPIRoutes(dir: string, base: string = dir): OpenAPIContentRoute[] {\n const routes: OpenAPIContentRoute[] = []\n if (!existsSync(dir)) return routes\n\n const entries = readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n routes.push(...findOpenAPIRoutes(fullPath, base))\n continue\n }\n if (!entry.isFile() || !/\\.openapi\\.(json|yaml|yml)$/.test(entry.name)) continue\n\n const ref = relative(base, fullPath)\n const cleanPath = routePathFromRef(ref)\n routes.push({\n path: cleanPath,\n basePath: cleanPath,\n kind: 'openapi',\n meta: {\n title: kebabToTitle(cleanPath.split('/').pop() ?? 'API'),\n },\n module: {\n pageVirtualModuleId: pageVirtualModuleIdFromRef(ref),\n },\n source: {\n filePath: fullPath,\n },\n })\n }\n\n return routes\n}\n\nfunction operationMatchesTags(operationTags: string[] | undefined, filterTags: string[] | undefined): boolean {\n if (!filterTags?.length) return true\n return operationTags?.some(tag => filterTags.includes(tag)) ?? false\n}\n\nfunction filterPathItemsByTags(items: Record<string, unknown>, tags: string[]): Record<string, unknown> {\n const filteredItems: Record<string, unknown> = {}\n for (const path of Object.keys(items)) {\n const pathItem = items[path] as Record<string, unknown> | undefined\n if (!pathItem) continue\n const ops = OPENAPI_HTTP_METHODS.map(method => pathItem[method])\n const hasMatch = ops.some(op => op && typeof op === 'object' && operationMatchesTags((op as Record<string, unknown>).tags as string[] | undefined, tags))\n if (hasMatch) filteredItems[path] = pathItem\n }\n return filteredItems\n}\n\nfunction createOperationSectionId(operation: Record<string, unknown>, method: string, path: string, kind: 'path' | 'webhook'): string {\n const operationId = typeof operation.operationId === 'string' ? operation.operationId.trim() : ''\n return operationId || slug(`${kind === 'webhook' ? 'webhook ' : ''}${method.toLowerCase()} ${path}`)\n}\n\nfunction operationSectionId(operation: Record<string, unknown>): string {\n const sectionId = operation[CLARIFY_OPENAPI_SECTION_ID_EXTENSION]\n return typeof sectionId === 'string' ? sectionId : ''\n}\n\nexport function normalizeOpenAPISpecSectionIds(spec: OpenAPISpec): OpenAPISpec {\n const items = [\n ...Object.entries(spec.paths ?? {}).map(([path, pathItem]) => ({ path, pathItem, kind: 'path' as const })),\n ...Object.entries(((spec as Record<string, unknown>).webhooks ?? {}) as Record<string, unknown>).map(([path, pathItem]) => ({ path, pathItem, kind: 'webhook' as const })),\n ]\n\n for (const { path, pathItem, kind } of items) {\n if (!pathItem || typeof pathItem !== 'object') continue\n const operations = pathItem as Record<string, unknown>\n for (const method of OPENAPI_HTTP_METHODS) {\n const op = operations[method] as Record<string, unknown> | undefined\n if (!op || typeof op !== 'object') continue\n op[CLARIFY_OPENAPI_SECTION_ID_EXTENSION] = createOperationSectionId(op, method, path, kind)\n }\n }\n\n return spec\n}\n\n/** Filter an OpenAPI spec to only include paths that have at least one operation matching the given tags. */\nexport function filterSpecByTags(spec: OpenAPISpec, tags: string[]): OpenAPISpec {\n const paths = (spec.paths ?? {}) as Record<string, unknown>\n const webhooks = ((spec as Record<string, unknown>).webhooks ?? {}) as Record<string, unknown>\n return { ...spec, paths: filterPathItemsByTags(paths, tags), webhooks: filterPathItemsByTags(webhooks, tags) } as OpenAPISpec\n}\n\n/** Extract endpoint operations from an OpenAPI spec as page sections. */\nexport function extractOpenAPISections(spec: OpenAPISpec, filterTags?: string[]): ContentSection[] {\n normalizeOpenAPISpecSectionIds(spec)\n\n const sections: ContentSection[] = []\n const items = [\n ...Object.entries(spec.paths ?? {}).map(([path, pathItem]) => ({ path, pathItem, kind: 'path' })),\n ...Object.entries(((spec as Record<string, unknown>).webhooks ?? {}) as Record<string, unknown>).map(([path, pathItem]) => ({ path, pathItem, kind: 'webhook' })),\n ]\n for (const { path, pathItem, kind } of items) {\n if (!pathItem) continue\n const operations = pathItem as Record<string, unknown>\n for (const method of OPENAPI_HTTP_METHODS) {\n const op = operations[method] as Record<string, unknown> | undefined\n const tags = Array.isArray(op?.tags) ? op.tags as string[] : undefined\n if (!op || !operationMatchesTags(tags, filterTags)) continue\n const title = typeof op.summary === 'string' ? op.summary : `${method.toUpperCase()} ${path}`\n sections.push({ id: operationSectionId(op), title, level: 2, badge: kind === 'webhook' ? 'WEBHOOK' : method.toUpperCase(), tags })\n }\n }\n return sections\n}\n\nexport async function readOpenAPISpec(filePath: string, contentProcessor?: ContentProcessor, projectRoot?: string): Promise<OpenAPIParseResult> {\n try {\n if (!contentProcessor) return { ok: true, spec: await SwaggerParser.dereference(filePath) as OpenAPISpec }\n\n const source = readFileSync(filePath, 'utf-8')\n const transformedSource = await contentProcessor.processText(source, 'openapi', filePath)\n if (transformedSource === source) return { ok: true, spec: await SwaggerParser.dereference(filePath) as OpenAPISpec }\n\n return {\n ok: true,\n spec: await SwaggerParser.dereference(filePath, {\n resolve: {\n transformedOpenAPISource: {\n order: 1,\n canRead: (file: ResolverFileInfo) => isSameOpenAPIFile(file.url, filePath),\n read: () => transformedSource,\n },\n },\n }) as OpenAPISpec,\n }\n } catch (error) {\n return {\n ok: false,\n diagnostic: createContentDiagnostic({\n kind: 'openapi',\n title: 'OpenAPI spec parse failed',\n message: 'Clarify could not parse this OpenAPI specification.',\n error,\n filePath,\n projectRoot,\n }),\n }\n }\n}\n","import { join } from 'node:path'\n\nimport { pageVirtualModuleId } from '../../core/runtime/module-ids.js'\nimport { localizedRoutePath, openAPIPagePathFromRef, routeIntentFromPagesItem, withAlternates } from '../../parsers/routes/routes.js'\nimport type { ClarifyOpenAPIRouteIntent, ClarifyPagesConfig, ClarifyPagesItem, ContentRoute, OpenAPIContentRoute, ResolvedClarifyLocalesConfig, ResolvedProjectConfig } from '../../types.js'\n\nimport { findOpenAPIRoutes } from './parser.js'\n\nfunction collectOpenAPIPageIntents(config: ResolvedProjectConfig): ClarifyOpenAPIRouteIntent[] {\n const intents: ClarifyOpenAPIRouteIntent[] = []\n\n function visitItems(items: ClarifyPagesItem[]) {\n for (const item of items) {\n if (typeof item !== 'string' && 'group' in item) {\n visitItems(item.pages)\n continue\n }\n const intent = routeIntentFromPagesItem(item)\n if (intent.kind === 'openapi' && (intent.path || intent.tagFilter?.length)) intents.push(intent)\n }\n }\n\n function visitPages(pages?: ClarifyPagesConfig) {\n if (!pages || pages === 'FileTree') return\n for (const group of pages) visitItems(group.pages)\n }\n\n for (const tab of config.navigation?.tabs ?? []) visitPages(tab.pages)\n return intents\n}\n\nfunction cloneOpenAPIRoute(route: OpenAPIContentRoute, overrides: Partial<OpenAPIContentRoute> = {}): OpenAPIContentRoute {\n return {\n ...route,\n meta: { ...route.meta, sections: route.meta.sections ? [...route.meta.sections] : undefined },\n module: { ...route.module },\n source: { ...route.source },\n openapi: route.openapi ? { ...route.openapi, tagFilter: route.openapi.tagFilter ? [...route.openapi.tagFilter] : undefined } : undefined,\n alternates: route.alternates ? { ...route.alternates } : undefined,\n ...overrides,\n }\n}\n\nexport function discoverOpenAPIRoutes(contentRoot: string, locales?: ResolvedClarifyLocalesConfig): OpenAPIContentRoute[] {\n if (!locales) return findOpenAPIRoutes(contentRoot)\n\n const localizedRoutes: OpenAPIContentRoute[] = []\n for (const locale of locales.locales) {\n const localeRoot = join(contentRoot, locale.code)\n for (const route of findOpenAPIRoutes(localeRoot, localeRoot)) {\n const basePath = route.basePath ?? route.path\n const path = localizedRoutePath(basePath, locale.code, locales)\n localizedRoutes.push({\n ...route,\n path,\n basePath,\n locale: locale.code,\n module: { pageVirtualModuleId: pageVirtualModuleId(path) },\n })\n }\n }\n\n if (locales.missing !== 'fallback') return localizedRoutes\n\n const routeByLocaleAndBase = new Map(localizedRoutes.map(route => [`${route.locale ?? ''}:${route.basePath ?? route.path}`, route]))\n const defaultRoutes = localizedRoutes.filter(route => route.locale === locales.default)\n for (const sourceRoute of defaultRoutes) {\n const basePath = sourceRoute.basePath ?? sourceRoute.path\n for (const locale of locales.locales) {\n const key = `${locale.code}:${basePath}`\n if (routeByLocaleAndBase.has(key)) continue\n const path = localizedRoutePath(basePath, locale.code, locales)\n localizedRoutes.push(cloneOpenAPIRoute(sourceRoute, {\n path,\n locale: locale.code,\n module: { pageVirtualModuleId: pageVirtualModuleId(path) },\n isFallback: true,\n }))\n }\n }\n\n return localizedRoutes\n}\n\nexport function expandConfiguredOpenAPIRoutes(routes: ContentRoute[], config: ResolvedProjectConfig): ContentRoute[] {\n const openAPIIntents = collectOpenAPIPageIntents(config)\n if (!openAPIIntents.length) return routes\n\n const additions: OpenAPIContentRoute[] = []\n const existingKeys = new Set(routes.map(route => `${route.locale ?? ''}:${route.basePath ?? route.path}`))\n\n for (const intent of openAPIIntents) {\n const tagFilter = intent.tagFilter?.filter(Boolean)\n const sourceBasePath = openAPIPagePathFromRef(intent.ref)\n const targetBasePath = openAPIPagePathFromRef(intent.ref, tagFilter, intent.path)\n if (sourceBasePath === targetBasePath && !tagFilter?.length) continue\n\n for (const route of routes) {\n if (route.kind !== 'openapi' || (route.basePath ?? route.path) !== sourceBasePath) continue\n const key = `${route.locale ?? ''}:${targetBasePath}`\n if (existingKeys.has(key)) continue\n existingKeys.add(key)\n\n const path = route.locale && config.locales ? localizedRoutePath(targetBasePath, route.locale, config.locales) : targetBasePath\n additions.push(cloneOpenAPIRoute(route, {\n path,\n basePath: targetBasePath,\n module: { pageVirtualModuleId: pageVirtualModuleId(path) },\n openapi: { ...route.openapi, tagFilter: tagFilter?.length ? tagFilter : undefined },\n }))\n }\n }\n\n const nextRoutes = [...routes, ...additions]\n if (!config.locales) return nextRoutes\n\n const routesWithAlternates = nextRoutes.map(route => withAlternates(route, nextRoutes, config.locales!))\n const bareAliases: OpenAPIContentRoute[] = []\n const seenBare = new Set(routesWithAlternates.map(route => route.path))\n\n for (const route of routesWithAlternates) {\n if (route.kind !== 'openapi' || route.locale !== config.locales.default) continue\n const basePath = route.basePath ?? route.path\n if (basePath === route.path || seenBare.has(basePath)) continue\n seenBare.add(basePath)\n bareAliases.push(cloneOpenAPIRoute(route, {\n path: basePath,\n module: { pageVirtualModuleId: pageVirtualModuleId(basePath) },\n isBareAlias: true,\n }))\n }\n\n return [...routesWithAlternates, ...bareAliases]\n}\n","import { VIRTUAL_OPENAPI, VIRTUAL_OPENAPI_SERVER } from '../../core/runtime/virtual-modules.js'\nimport type { OpenAPISpec } from '../../types.js'\n\nexport const openApiRegistryModuleId = VIRTUAL_OPENAPI\nexport const openApiServerRegistryModuleId = VIRTUAL_OPENAPI_SERVER\nconst OPENAPI_SPEC_PREFIX = 'virtual:clarify/openapi-spec/'\n\nexport function specVirtualModuleId(specKey: string): string {\n return `${OPENAPI_SPEC_PREFIX}${specKey}`\n}\n\nexport function generateOpenAPIRegistryModule(openApiSpecs: Record<string, string>): string {\n const entries = Object.entries(openApiSpecs)\n .map(([key, moduleId]) => ` ${JSON.stringify(key)}: () => import(${JSON.stringify(moduleId)}),`)\n .join('\\n')\n return `export const openApiSpecs = {\\n${entries}\\n};`\n}\n\nexport function generateOpenAPIServerRegistryModule(openApiSpecs: Record<string, OpenAPISpec>): string {\n return `export const openApiSpecs = ${JSON.stringify(openApiSpecs)};`\n}\n\n/** Generate a virtual module that exports a single spec as default. */\nexport function generateOpenAPISpecModule(spec: OpenAPISpec): string {\n return `export default ${JSON.stringify(spec)};`\n}\n\ntype OpenAPIPageModuleOptions = {\n specModuleId: string\n}\n\nexport function generateOpenAPIPageModule(opts: OpenAPIPageModuleOptions): string {\n return `import { createOpenApiRouteComponent } from '@clarify-labs/renderer';\nimport spec from ${JSON.stringify(opts.specModuleId)};\n\nexport const routeData = {};\n\nexport default createOpenApiRouteComponent({ ...routeData, spec });\n`\n}\n","import { relative } from 'node:path'\n\nimport { pageVirtualModuleId } from '../../core/runtime/module-ids.js'\nimport { generateContentDiagnosticModule, type VirtualModules } from '../../core/runtime/virtual-modules.js'\nimport { createProjectContentProcessor } from '../../parsers/content/content.js'\nimport type { ClarifyHookContext, ContentRoute, OpenAPISpec } from '../../types.js'\n\nimport { extractOpenAPISections, filterSpecByTags, normalizeOpenAPISpecSectionIds, readOpenAPISpec } from './parser.js'\nimport { generateOpenAPIPageModule, generateOpenAPIRegistryModule, generateOpenAPIServerRegistryModule, generateOpenAPISpecModule, openApiRegistryModuleId, openApiServerRegistryModuleId, specVirtualModuleId } from './virtual-modules.js'\n\nfunction sourceSpecIdFromPath(filePath: string, projectRoot: string): string {\n return relative(projectRoot, filePath).replace(/[^a-zA-Z0-9_-]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '')\n}\n\nfunction routeSpecModuleIdFromSourceSpecId(sourceSpecId: string, tagFilter?: string[]): string {\n if (!tagFilter?.length) return sourceSpecId\n const suffix = tagFilter.map(tag => tag.replace(/[^a-zA-Z0-9_-]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '') || 'tag').join('_')\n return `${sourceSpecId}_tags_${suffix}`\n}\n\nfunction openAPIRegistryKeys(route: ContentRoute): string[] {\n const keys = new Set<string>()\n const path = (route.path || '/').replace(/^\\//, '')\n const base = (route.basePath ?? route.path).replace(/^\\//, '')\n\n if (route.locale) keys.add(pageVirtualModuleId(`${route.locale}/${base}`))\n keys.add(pageVirtualModuleId(path))\n if (!route.locale && base) keys.add(pageVirtualModuleId(base))\n\n return [...keys]\n}\n\nexport class OpenAPIPluginState {\n private readonly specModules = new Map<string, OpenAPISpec>()\n\n async enrichRoutes(routes: ContentRoute[], ctx: ClarifyHookContext): Promise<ContentRoute[]> {\n this.specModules.clear()\n const specByFilePath = new Map<string, OpenAPISpec>()\n\n for (const route of routes) {\n if (route.kind !== 'openapi') continue\n const specFromCache = specByFilePath.get(route.source.filePath)\n const processor = createProjectContentProcessor(ctx.plugins, ctx)\n const result = specFromCache\n ? { ok: true as const, spec: specFromCache }\n : await readOpenAPISpec(route.source.filePath, processor, ctx.generateOptions.projectRoot)\n if (!result.ok) {\n route.diagnostic = result.diagnostic\n route.meta.title = route.meta.title || 'OpenAPI parse error'\n route.meta.sections = []\n continue\n }\n\n const spec = normalizeOpenAPISpecSectionIds(result.spec)\n specByFilePath.set(route.source.filePath, spec)\n const sourceSpecId = sourceSpecIdFromPath(route.source.filePath, ctx.generateOptions.projectRoot)\n route.openapi = { ...route.openapi, sourceSpecId }\n\n route.meta.title = spec.info?.title ?? route.meta.title\n route.meta.description = spec.info?.description ?? route.meta.description\n route.meta.sections = extractOpenAPISections(spec, route.openapi.tagFilter)\n\n const pageSpec = route.openapi.tagFilter?.length ? filterSpecByTags(spec, route.openapi.tagFilter) : spec\n const routeSpecModuleId = routeSpecModuleIdFromSourceSpecId(sourceSpecId, route.openapi.tagFilter)\n route.openapi.routeSpecModuleId = routeSpecModuleId\n this.specModules.set(routeSpecModuleId, pageSpec)\n route.source.content = JSON.stringify(pageSpec)\n }\n\n return routes\n }\n\n contributeModules(modules: VirtualModules, routes: ContentRoute[]): VirtualModules {\n const registryEntries: Record<string, string> = {}\n const serverRegistryEntries: Record<string, OpenAPISpec> = {}\n\n for (const route of routes) {\n if (route.kind !== 'openapi' || !route.openapi?.sourceSpecId) continue\n const routeSpecModuleId = route.openapi.routeSpecModuleId ?? route.openapi.sourceSpecId\n const spec = this.specModules.get(routeSpecModuleId)\n if (!spec) continue\n\n for (const registryKey of openAPIRegistryKeys(route)) {\n registryEntries[registryKey] = specVirtualModuleId(routeSpecModuleId)\n serverRegistryEntries[registryKey] = spec\n }\n }\n\n modules.set(openApiRegistryModuleId, generateOpenAPIRegistryModule(registryEntries))\n modules.set(openApiServerRegistryModuleId, generateOpenAPIServerRegistryModule(serverRegistryEntries))\n for (const [routeSpecModuleId, spec] of this.specModules) {\n modules.set(specVirtualModuleId(routeSpecModuleId), generateOpenAPISpecModule(spec))\n }\n\n for (const route of routes) {\n if (route.kind !== 'openapi') continue\n if (route.diagnostic) {\n modules.set(route.module.pageVirtualModuleId, generateContentDiagnosticModule(route.diagnostic))\n continue\n }\n if (!route.openapi?.sourceSpecId) continue\n const routeSpecModuleId = route.openapi.routeSpecModuleId ?? route.openapi.sourceSpecId\n if (!this.specModules.has(routeSpecModuleId)) continue\n modules.set(route.module.pageVirtualModuleId, generateOpenAPIPageModule({\n specModuleId: specVirtualModuleId(routeSpecModuleId),\n }))\n }\n\n return modules\n }\n}\n","import type { ClarifyPlugin } from '../../types.js'\n\nimport { discoverOpenAPIRoutes, expandConfiguredOpenAPIRoutes } from './routes.js'\nimport { OpenAPIPluginState } from './state.js'\n\nexport function createOpenAPIPlugin(): ClarifyPlugin {\n const state = new OpenAPIPluginState()\n\n return {\n name: 'clarify:openapi',\n hooks: {\n 'routes:discover': (input, ctx) => ({\n ...input,\n routes: [...input.routes, ...discoverOpenAPIRoutes(input.contentRoot, ctx.projectConfig.locales)],\n }),\n 'routes:discovered': async (routes, ctx) => {\n const expandedRoutes = expandConfiguredOpenAPIRoutes(routes, ctx.projectConfig)\n return state.enrichRoutes(expandedRoutes, ctx)\n },\n 'modules:before': (modules, ctx) => state.contributeModules(modules, ctx.routes),\n },\n }\n}\n","import { mkdtempSync, rmSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport function createClarifyTempDir(name: string): string {\n return mkdtempSync(join(tmpdir(), `clarify-${name}-`))\n}\n\nexport function removeClarifyTempDir(path: string | undefined): void {\n if (!path) return\n rmSync(path, { recursive: true, force: true })\n}\n","export function toPagefindLanguage(locale: string | undefined): string {\n const normalizedLocale = locale\n ?.trim()\n .replace(/_/g, '-')\n .split('-')\n .filter(Boolean)\n .join('-')\n // Pagefind's browser runtime lowercases the detected <html lang> value\n // before resolving the language-specific index. Keep Clarify's public\n // locale codes canonical (for example en-US / zh-CN), but use lowercase\n // BCP 47 tags internally so custom dev indexes match Pagefind runtime.\n .toLowerCase()\n\n return normalizedLocale || 'en'\n}\n","import { createReadStream, existsSync } from 'node:fs'\nimport { extname, join, relative, resolve } from 'node:path'\n\nimport type { ViteDevServer } from 'vite'\n\nimport { createClarifyTempDir, removeClarifyTempDir } from '../../core/project/temp-dir.js'\nimport type { ClarifyHookContext, ClarifyPlugin } from '../../types.js'\nimport { routeSearchContent } from '../mcp-search/orama-index.js'\n\nimport { toPagefindLanguage } from './search-language.js'\n\ntype PagefindModule = typeof import('pagefind')\n\ntype GeneratePagefindIndexOptions = {\n outputRoot: string\n sourceRoot?: string\n}\n\nconst pagefindContentTypes: Record<string, string> = {\n '.css': 'text/css; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.wasm': 'application/wasm',\n}\n\nfunction assertNoPagefindErrors(action: string, errors: string[] | undefined): void {\n if (!errors?.length) return\n throw new Error(`[clarify] Pagefind ${action} failed:\\n${errors.join('\\n')}`)\n}\n\nasync function generatePagefindIndex(options: GeneratePagefindIndexOptions, pagefind?: PagefindModule): Promise<number> {\n const runtime = pagefind ?? (await import('pagefind') as PagefindModule)\n const { errors, index } = await runtime.createIndex({\n excludeSelectors: [\n '[data-pagefind-ignore]',\n 'script',\n 'style',\n 'svg',\n ],\n includeCharacters: '._-/#:@',\n keepIndexUrl: false,\n verbose: false,\n writePlayground: false,\n })\n\n assertNoPagefindErrors('createIndex', errors)\n if (!index) throw new Error('[clarify] Pagefind did not create an index.')\n\n try {\n const addResult = await index.addDirectory({ path: options.sourceRoot ?? options.outputRoot, glob: '**/*.html' })\n assertNoPagefindErrors('addDirectory', addResult.errors)\n\n const writeResult = await index.writeFiles({ outputPath: join(options.outputRoot, 'pagefind') })\n assertNoPagefindErrors('writeFiles', writeResult.errors)\n\n return addResult.page_count\n } finally {\n await index.deleteIndex()\n if (!pagefind) {\n await runtime.close()\n }\n }\n}\n\nasync function generateDevSearchIndex(ctx: ClarifyHookContext, root: string, pagefind: PagefindModule): Promise<void> {\n const { errors, index } = await pagefind.createIndex({\n includeCharacters: '._-/#:@',\n keepIndexUrl: false,\n verbose: false,\n writePlayground: false,\n })\n\n assertNoPagefindErrors('createIndex', errors)\n if (!index) throw new Error('[clarify] Pagefind did not create an index.')\n\n try {\n let pageCount = 0\n for (const route of ctx.routes) {\n // Skip bare alias routes (e.g., /path) to avoid indexing duplicates in multilingual sites\n // Only index the full path with locale prefix (e.g., /locale/path)\n if (route.isBareAlias) continue\n \n const content = routeSearchContent(route)\n if (!content.trim()) continue\n const result = await index.addCustomRecord({\n url: route.path,\n content,\n language: toPagefindLanguage(route.locale ?? ctx.projectConfig.locales?.default),\n meta: {\n title: route.meta.title,\n },\n })\n assertNoPagefindErrors(`addCustomRecord ${route.path}`, result.errors)\n pageCount += 1\n }\n\n const writeResult = await index.writeFiles({ outputPath: join(root, 'pagefind') })\n assertNoPagefindErrors('writeFiles', writeResult.errors)\n console.log(`[clarify] Dev search index generated for ${pageCount} pages.`)\n } finally {\n await index.deleteIndex()\n }\n}\n\nfunction normalizeDevPagefindPath(rawUrl: string | undefined, routePrefix: string): string | undefined {\n const pathname = rawUrl?.split('?')[0]\n if (!pathname) return undefined\n\n const normalizedPrefix = routePrefix && routePrefix !== '/' ? `/${routePrefix.replace(/^\\/+|\\/+$/g, '')}` : ''\n const pagefindPath = normalizedPrefix && pathname.startsWith(`${normalizedPrefix}/pagefind/`)\n ? pathname.slice(normalizedPrefix.length)\n : pathname\n\n return pagefindPath.startsWith('/pagefind/') ? pagefindPath : undefined\n}\n\nfunction serveDevPagefind(server: ViteDevServer, getRoot: () => string | undefined, ctx: ClarifyHookContext): void {\n server.middlewares.use((req, res, next) => {\n const root = getRoot()\n const pagefindPath = normalizeDevPagefindPath(req.url, ctx.projectConfig.routePrefix)\n if (!root || !pagefindPath) {\n next()\n return\n }\n\n const filePath = join(root, pagefindPath)\n const relativePath = relative(root, filePath)\n if (relativePath.startsWith('..') || relativePath === '' || !existsSync(filePath)) {\n next()\n return\n }\n\n const contentType = pagefindContentTypes[extname(filePath)] ?? 'application/octet-stream'\n res.setHeader('Content-Type', contentType)\n createReadStream(filePath).pipe(res)\n })\n}\n\nexport function createPageSearchPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:page-search',\n hooks: {\n async 'dev:configureServer'(server, ctx) {\n if (!ctx.projectConfig.features.search.enabled) return\n const pagefind = await import('pagefind') as PagefindModule\n let currentRoot: string | undefined\n const staleRoots = new Set<string>()\n\n const replaceDevIndex = async () => {\n const nextRoot = createClarifyTempDir('pagefind')\n await generateDevSearchIndex(ctx, nextRoot, pagefind)\n const previousRoot = currentRoot\n currentRoot = nextRoot\n if (previousRoot) {\n staleRoots.add(previousRoot)\n setTimeout(() => {\n staleRoots.delete(previousRoot)\n removeClarifyTempDir(previousRoot)\n }, 30_000).unref?.()\n }\n }\n\n serveDevPagefind(server, () => currentRoot, ctx)\n await replaceDevIndex()\n\n let regenerateTimer: ReturnType<typeof setTimeout> | undefined\n const regenerate = (filePath: string) => {\n if (!/\\.(md|mdx|json|ya?ml)$/i.test(filePath)) return\n if (regenerateTimer) clearTimeout(regenerateTimer)\n regenerateTimer = setTimeout(() => {\n void replaceDevIndex().catch((err: unknown) => {\n console.error('[clarify] Failed to regenerate dev search index:', err)\n })\n }, 100)\n }\n\n server.watcher.on('add', regenerate)\n server.watcher.on('change', regenerate)\n server.watcher.on('unlink', regenerate)\n\n server.httpServer?.once('close', () => {\n if (regenerateTimer) clearTimeout(regenerateTimer)\n removeClarifyTempDir(currentRoot)\n for (const staleRoot of staleRoots) removeClarifyTempDir(staleRoot)\n void pagefind.close().catch(() => undefined)\n })\n },\n async 'build:done'(ctx) {\n if (!ctx.projectConfig.features.search.enabled) return\n const outputDirectory = ctx.generateOptions.outputDirectory\n if (!outputDirectory) return\n\n const outputRoot = resolve(ctx.generateOptions.projectRoot, outputDirectory)\n const pageCount = await generatePagefindIndex({ outputRoot })\n console.log(`[clarify] Page search index generated for ${pageCount} pages.`)\n },\n },\n }\n}\n","import type { ContentRoute, ResolvedProjectConfig } from '../../types.js'\n\nfunction trimTrailingSlash(value: string): string {\n return value.replace(/\\/+$/, '')\n}\n\nfunction normalizeRoutePrefix(routePrefix: string): string {\n if (!routePrefix || routePrefix === '/') return ''\n return `/${routePrefix.replace(/^\\/+|\\/+$/g, '')}`\n}\n\nfunction routeUrl(siteUrl: string, routePrefix: string, routePath: string): string {\n const base = trimTrailingSlash(siteUrl)\n const prefix = normalizeRoutePrefix(routePrefix)\n const path = routePath === '/' ? '' : routePath.replace(/^\\/+/, '/')\n return `${base}${prefix}${path}` || base\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''')\n}\n\nfunction publicRoutes(routes: ContentRoute[]): ContentRoute[] {\n // Exclude 404 routes and bare alias routes (e.g., /path without language prefix) in multilingual sites\n return routes.filter(route => route.path !== '/404' && !route.isBareAlias)\n}\n\nexport function createSitemapXml(routes: ContentRoute[], config: ResolvedProjectConfig): string | undefined {\n if (!config.siteUrl) return undefined\n\n const urls = publicRoutes(routes)\n .map(route => routeUrl(config.siteUrl!, config.routePrefix, route.path))\n .filter((url, index, list) => list.indexOf(url) === index)\n .sort()\n\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">',\n ...urls.map(url => ` <url><loc>${escapeXml(url)}</loc></url>`),\n '</urlset>',\n '',\n ].join('\\n')\n}\n\nexport function createRobotsTxt(config: ResolvedProjectConfig): string | undefined {\n if (!config.siteUrl) return undefined\n const sitemapUrl = routeUrl(config.siteUrl, config.routePrefix, '/sitemap.xml')\n return [\n 'User-agent: *',\n 'Allow: /',\n `Sitemap: ${sitemapUrl}`,\n '',\n ].join('\\n')\n}\n","import type { ClarifyEmitAsset, ClarifyPlugin } from '../../types.js'\n\nimport { createRobotsTxt, createSitemapXml } from './artifacts.js'\n\nexport function createSeoPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:seo',\n hooks: {\n 'build:assets'(ctx) {\n const assets: ClarifyEmitAsset[] = []\n const sitemap = createSitemapXml(ctx.routes, ctx.projectConfig)\n const robots = createRobotsTxt(ctx.projectConfig)\n if (sitemap) assets.push({ fileName: 'sitemap.xml', source: sitemap })\n if (robots) assets.push({ fileName: 'robots.txt', source: robots })\n return assets\n },\n },\n }\n}\n","import { relative } from 'node:path'\n\nimport type { ClarifyRepositoryConfig, ContentRoute } from '../../types.js'\n\nfunction trimSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, '')\n}\n\nfunction normalizeRepositoryUrl(repository: string): string {\n return repository.replace(/\\.git$/, '').replace(/\\/+$/, '')\n}\n\nfunction encodePath(path: string): string {\n return path\n .split('/')\n .filter(Boolean)\n .map(segment => encodeURIComponent(segment))\n .join('/')\n}\n\nexport function createSourceEditUrl(filePath: string, contentRoot: string, source: ClarifyRepositoryConfig): string {\n if (!source.url) return ''\n const repository = normalizeRepositoryUrl(source.url)\n const branch = source.branch ?? 'main'\n const directory = source.directory ? trimSlashes(source.directory) : ''\n const relativePath = relative(contentRoot, filePath).replaceAll('\\\\', '/')\n const sourcePath = [directory, relativePath].filter(Boolean).join('/')\n return `${repository}/edit/${encodeURIComponent(branch)}/${encodePath(sourcePath)}`\n}\n\nexport function attachSourceEditUrls(routes: ContentRoute[], contentRoot: string, source?: ClarifyRepositoryConfig): void {\n if (!source) return\n for (const route of routes) {\n route.source = {\n ...route.source,\n sourceEditUrl: createSourceEditUrl(route.source.filePath, contentRoot, source),\n }\n }\n}\n","import { join } from 'node:path'\n\nimport type { ClarifyPlugin } from '../../types.js'\n\nimport { attachSourceEditUrls } from './source-links.js'\n\nexport function createSourceLinksPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:source-links',\n hooks: {\n 'routes:discovered': (routes, ctx) => {\n if (!ctx.projectConfig.features.repository.enabled) return routes\n const contentRoot = join(ctx.generateOptions.projectRoot, ctx.generateOptions.rootDirectory)\n attachSourceEditUrls(routes, contentRoot, ctx.projectConfig.features.repository)\n return routes\n },\n },\n }\n}\n","import type { ClarifyVariablesConfig, ClarifyVariableValue, ClarifyPlugin } from '../../types.js'\n\nconst variablePattern = /{{\\s*([A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*)\\s*}}/g\n\nfunction getVariableValue(variables: ClarifyVariablesConfig, path: string): ClarifyVariableValue | undefined {\n let current: ClarifyVariableValue | undefined = variables\n for (const segment of path.split('.')) {\n if (!current || typeof current !== 'object' || Array.isArray(current)) return undefined\n current = current[segment]\n }\n return current\n}\n\nfunction stringifyVariableValue(variables: ClarifyVariablesConfig, path: string, stack: string[]): string | undefined {\n if (stack.includes(path)) {\n throw new Error(`[clarify] variable \"${path}\" contains a circular reference: ${[...stack, path].join(' -> ')}`)\n }\n\n const value = getVariableValue(variables, path)\n if (value === undefined || typeof value === 'object') return undefined\n if (typeof value !== 'string') return String(value)\n\n return value.replace(variablePattern, (match, nestedPath: string) => stringifyVariableValue(variables, nestedPath, [...stack, path]) ?? match)\n}\n\nexport function applyVariables(content: string, variables: ClarifyVariablesConfig = {}): string {\n return content.replace(variablePattern, (match, path: string) => stringifyVariableValue(variables, path, []) ?? match)\n}\n\nfunction applyVariablesToFrontmatter(frontmatter: Record<string, unknown>, variables: ClarifyVariablesConfig): Record<string, unknown> {\n const nextFrontmatter = { ...frontmatter }\n for (const key of ['title', 'description'] as const) {\n if (typeof nextFrontmatter[key] !== 'string') continue\n nextFrontmatter[key] = applyVariables(nextFrontmatter[key], variables)\n }\n return nextFrontmatter\n}\n\nexport function createVariablesPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:variables',\n hooks: {\n 'content:transform': (input, ctx) => ({\n ...input,\n frontmatter: applyVariablesToFrontmatter(input.frontmatter, ctx.projectConfig.variables),\n content: applyVariables(input.content, ctx.projectConfig.variables),\n }),\n },\n }\n}\n","import { createContentArtifactsPlugin } from '../../plugins/content-artifacts/index.js'\nimport { createHtmlShellPlugin } from '../../plugins/html-shell/index.js'\nimport { createMcpSearchPlugin } from '../../plugins/mcp-search/index.js'\nimport { createOpenAPIPlugin } from '../../plugins/openapi/index.js'\nimport { createPageSearchPlugin } from '../../plugins/page-search/index.js'\nimport { createSeoPlugin } from '../../plugins/seo/index.js'\nimport { createSourceLinksPlugin } from '../../plugins/source-links/index.js'\nimport { createVariablesPlugin } from '../../plugins/variables/index.js'\nimport type { ClarifyPlugin } from '../../types.js'\n\nexport type BuiltinPluginOptions = {\n htmlShell?: boolean\n}\n\nexport function createBuiltinPlugins(options: BuiltinPluginOptions = {}): ClarifyPlugin[] {\n // Core site discovery (content scanning, i18n fallback routes) and\n // navigation building are handled directly by the Engine, not as plugins.\n // The remaining plugins provide optional functionality (variables, OpenAPI,\n // SEO, search, etc.) and can be augmented or replaced by user plugins.\n const plugins = [\n createVariablesPlugin(),\n createOpenAPIPlugin(),\n createSourceLinksPlugin(),\n createContentArtifactsPlugin(),\n createSeoPlugin(),\n createPageSearchPlugin(),\n createMcpSearchPlugin(),\n ]\n if (options.htmlShell ?? true) plugins.push(createHtmlShellPlugin())\n return plugins\n}\n","import type { ClarifyPlugin } from '../../types.js'\nimport type { ClarifyBuildOptions } from '../config/options.js'\n\nimport { createBuiltinPlugins, type BuiltinPluginOptions } from './builtin.js'\n\nexport type LoadPluginsOptions = BuiltinPluginOptions & {\n userPlugins?: ClarifyPlugin[]\n}\n\nfunction pluginWeight(plugin: ClarifyPlugin): number {\n const enforceWeight = plugin.enforce === 'pre'\n ? 1_000_000\n : plugin.enforce === 'post'\n ? -1_000_000\n : 0\n return enforceWeight + (plugin.priority ?? 0)\n}\n\nexport function sortPlugins(plugins: ClarifyPlugin[]): ClarifyPlugin[] {\n const entries = plugins.map((plugin, index) => ({ plugin, index }))\n const byName = new Map<string, ClarifyPlugin>()\n for (const { plugin } of entries) {\n if (byName.has(plugin.name)) throw new Error(`[clarify] Duplicate plugin name: ${plugin.name}`)\n byName.set(plugin.name, plugin)\n }\n\n const sortedByWeight = [...entries].sort((left, right) => {\n const weightDiff = pluginWeight(right.plugin) - pluginWeight(left.plugin)\n return weightDiff === 0 ? left.index - right.index : weightDiff\n })\n const visitOrder = new Map(sortedByWeight.map((entry, index) => [entry.plugin.name, index]))\n const visiting = new Set<string>()\n const visited = new Set<string>()\n const sorted: ClarifyPlugin[] = []\n\n function visit(plugin: ClarifyPlugin): void {\n if (visited.has(plugin.name)) return\n if (visiting.has(plugin.name)) throw new Error(`[clarify] Circular plugin dependency detected: ${plugin.name}`)\n\n visiting.add(plugin.name)\n const dependencies = [...(plugin.dependsOn ?? [])].sort((left, right) => (visitOrder.get(left) ?? 0) - (visitOrder.get(right) ?? 0))\n for (const dependencyName of dependencies) {\n const dependency = byName.get(dependencyName)\n if (!dependency) throw new Error(`[clarify] Plugin ${plugin.name} depends on missing plugin: ${dependencyName}`)\n visit(dependency)\n }\n visiting.delete(plugin.name)\n visited.add(plugin.name)\n sorted.push(plugin)\n }\n\n for (const { plugin } of sortedByWeight) visit(plugin)\n return sorted\n}\n\nexport function loadPlugins(options: LoadPluginsOptions = {}): ClarifyPlugin[] {\n return sortPlugins([\n ...createBuiltinPlugins({ htmlShell: options.htmlShell }),\n ...(options.userPlugins ?? []),\n ])\n}\n\nexport function loadBuildPlugins(options: ClarifyBuildOptions = {}, pluginOptions: BuiltinPluginOptions = {}): ClarifyPlugin[] {\n return loadPlugins({\n ...pluginOptions,\n userPlugins: options.plugins,\n })\n}\n","import { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport type { ConfigEnv } from 'vite'\n\nimport { cliPackageVersion } from '../../cli/package.js'\nimport type { ClarifyProjectContext } from '../../types.js'\nimport { resolveProjectConfig } from '../config/config.js'\nimport { resolveBuildOptions, type ClarifyBuildOptions, type ResolvedBuildOptions } from '../config/options.js'\nimport { findClarifyConfigFile, loadClarifyConfig, type ClarifyConfig } from '../config/user-config.js'\n\nexport type ResolvedProjectContext = {\n projectRoot: string\n contentRoot: string\n config: ClarifyConfig\n configFilePath?: string\n buildOptions: ResolvedBuildOptions\n resolvedOptions: ClarifyBuildOptions\n projectContext: ClarifyProjectContext\n projectConfig: ReturnType<typeof resolveProjectConfig>\n}\n\nexport async function resolveProjectContext(options: ClarifyBuildOptions = {}, env: ConfigEnv = { command: 'build', mode: 'production' }): Promise<ResolvedProjectContext> {\n const projectRoot = resolve(options.projectRoot ?? process.cwd())\n const initialBuildOptions = resolveBuildOptions(options)\n const configFilePath = findClarifyConfigFile(projectRoot)\n const config = configFilePath && existsSync(configFilePath)\n ? await loadClarifyConfig(projectRoot, env)\n : {}\n\n const mergedOptions: ClarifyBuildOptions = {\n ...config,\n ...options,\n projectRoot,\n rootDirectory: options.rootDirectory ?? initialBuildOptions.rootDirectory,\n outputDirectory: options.outputDirectory ?? initialBuildOptions.outputDirectory,\n }\n const resolvedProjectConfig = resolveProjectConfig(mergedOptions)\n const resolvedBuildOptions = resolveBuildOptions(mergedOptions)\n const contentRoot = join(projectRoot, resolvedBuildOptions.rootDirectory)\n\n const projectContext: ClarifyProjectContext = {\n projectRoot,\n contentRoot,\n version: cliPackageVersion,\n projectConfig: resolvedProjectConfig,\n generateOptions: resolvedBuildOptions,\n }\n\n return {\n projectRoot,\n contentRoot,\n configFilePath,\n projectConfig: resolvedProjectConfig,\n buildOptions: resolvedBuildOptions,\n resolvedOptions: mergedOptions,\n config,\n projectContext,\n }\n}\n","import type { ContentRoute } from '../../types.js'\n\nexport type RouteConflictKind = 'path' | 'page-module'\n\nexport type RouteConflict = {\n kind: RouteConflictKind\n key: string\n label: string\n routes: ContentRoute[]\n}\n\nfunction routeDescription(route: ContentRoute): string {\n return `${route.kind} ${route.source.filePath}`\n}\n\nfunction collectConflicts(routes: ContentRoute[], keyOf: (route: ContentRoute) => string): Map<string, ContentRoute[]> {\n const grouped = new Map<string, ContentRoute[]>()\n for (const route of routes) {\n const key = keyOf(route)\n grouped.set(key, [...(grouped.get(key) ?? []), route])\n }\n return grouped\n}\n\nexport function describeRouteConflict(route: ContentRoute): string {\n return routeDescription(route)\n}\n\nexport function findRouteConflicts(routes: ContentRoute[]): RouteConflict[] {\n const conflicts: RouteConflict[] = []\n\n for (const [path, pathRoutes] of collectConflicts(routes, route => route.path)) {\n if (pathRoutes.length < 2) continue\n conflicts.push({ kind: 'path', key: path, label: `path ${path}`, routes: pathRoutes })\n }\n\n for (const [pageModuleId, moduleRoutes] of collectConflicts(routes, route => route.module.pageVirtualModuleId)) {\n if (moduleRoutes.length < 2) continue\n if (moduleRoutes.every(route => route.path === moduleRoutes[0]!.path)) continue\n conflicts.push({ kind: 'page-module', key: pageModuleId, label: `page module ${pageModuleId}`, routes: moduleRoutes })\n }\n\n return conflicts\n}\n\nexport function formatRouteConflicts(conflicts: RouteConflict[]): string {\n return conflicts\n .map(conflict => `- ${conflict.label}: ${conflict.routes.map(describeRouteConflict).join(', ')}`)\n .join('\\n')\n}\n","import { applyConfiguredPageRoutePaths, buildLocalizedNavigationFromTabsConfig, buildNavigation, buildNavigationFromTabsConfig } from '../../parsers/routes/routes.js'\nimport type { ClarifyHookContext, ClarifyPage, ClarifyPlugin, ContentDiagnostic, ContentRoute, NavigationTree } from '../../types.js'\nimport { runHooks } from '../plugin/hooks.js'\n\nimport { describeRouteConflict, findRouteConflicts, formatRouteConflicts, type RouteConflict } from './route-analysis.js'\n\nexport async function resolveRoutePages(routes: ContentRoute[], plugins: ClarifyPlugin[], ctx: ClarifyHookContext): Promise<ContentRoute[]> {\n const routeToken = Symbol('clarifyRouteToken')\n type RoutedPage = ClarifyPage & { [routeToken]: number }\n\n const pages = routes.map<RoutedPage>((route, routeIndex) => ({\n path: route.path,\n filePath: route.source.filePath,\n frontmatter: route.source.frontmatter ?? {},\n content: route.source.content ?? '',\n [routeToken]: routeIndex,\n }))\n const resolvedPages = await runHooks(plugins, 'pages:resolved', pages, ctx)\n const pageByRouteIndex = new Map<number, ClarifyPage>()\n\n for (const page of resolvedPages) {\n const routeIndex = (page as RoutedPage)[routeToken]\n if (!Number.isInteger(routeIndex) || routeIndex < 0 || routeIndex >= routes.length) {\n throw new Error('[clarify] pages:resolved hooks must preserve each page route identity')\n }\n if (pageByRouteIndex.has(routeIndex)) {\n throw new Error('[clarify] pages:resolved hooks returned the same page route identity more than once')\n }\n pageByRouteIndex.set(routeIndex, page)\n }\n\n if (pageByRouteIndex.size !== routes.length) {\n throw new Error('[clarify] pages:resolved hooks must return exactly one page for each route')\n }\n\n return routes.map((route, routeIndex) => {\n const page = pageByRouteIndex.get(routeIndex)!\n return {\n ...route,\n source: {\n ...route.source,\n frontmatter: page.frontmatter,\n content: page.content,\n },\n }\n })\n}\n\nfunction buildNavigationTree(routes: ContentRoute[], ctx: ClarifyHookContext): NavigationTree {\n const tabs = ctx.projectConfig.navigation?.tabs\n if (!tabs) return { kind: 'flat', nodes: buildNavigation(routes) }\n if (!ctx.projectConfig.locales) return buildNavigationFromTabsConfig(routes, tabs)\n return buildLocalizedNavigationFromTabsConfig(routes, tabs, ctx.projectConfig.locales)\n ?? { kind: 'localized-tabbed', locales: {} }\n}\n\nexport function assertNoRouteConflicts(routes: ContentRoute[]): void {\n const conflicts = findRouteConflicts(routes)\n if (conflicts.length > 0) {\n throw new Error(`[clarify] Route conflicts prevent the site from being built:\\n${formatRouteConflicts(conflicts)}`)\n }\n}\n\nfunction createRouteConflictDiagnostic(label: string, routes: ContentRoute[]): ContentDiagnostic {\n return {\n kind: 'route-load',\n title: 'Route conflict',\n message: `This page cannot be rendered because ${label} is used by multiple routes.`,\n details: routes.map(describeRouteConflict).join('\\n'),\n }\n}\n\nexport function createDevRouteConflictRoutes(routes: ContentRoute[]): ContentRoute[] {\n const conflicts = findRouteConflicts(routes)\n if (conflicts.length === 0) return routes\n\n const conflictedRoutes = new Map<ContentRoute, RouteConflict>()\n for (const conflict of conflicts) {\n for (const route of conflict.routes) conflictedRoutes.set(route, conflict)\n }\n\n function createConflictRoute<T extends ContentRoute>(route: T, conflict: RouteConflict): T {\n return {\n ...route,\n module: { ...route.module, pageVirtualModuleId: `${route.module.pageVirtualModuleId}__conflict` },\n diagnostic: createRouteConflictDiagnostic(conflict.label, conflict.routes),\n }\n }\n\n const usedPaths = new Set<string>()\n return routes.flatMap(route => {\n const conflict = conflictedRoutes.get(route)\n if (!conflict) return [route]\n if (usedPaths.has(route.path)) return []\n usedPaths.add(route.path)\n return [createConflictRoute(route, conflict)]\n })\n}\n\nfunction handleRouteConflicts(routes: ContentRoute[], development: boolean): ContentRoute[] {\n if (development) return createDevRouteConflictRoutes(routes)\n assertNoRouteConflicts(routes)\n return routes\n}\n\nexport async function resolveRouteState(routes: ContentRoute[], plugins: ClarifyPlugin[], ctx: ClarifyHookContext, development: boolean): Promise<{ routes: ContentRoute[], navigation: NavigationTree }> {\n const tabs = ctx.projectConfig.navigation?.tabs\n const configuredRoutes = applyConfiguredPageRoutePaths(routes, tabs, ctx.projectConfig.locales)\n const navigation = buildNavigationTree(configuredRoutes, ctx)\n const resolved = await runHooks(plugins, 'routes:resolved', { routes: configuredRoutes, navigation }, ctx)\n const finalRoutes = handleRouteConflicts(resolved.routes, development)\n\n return {\n routes: finalRoutes,\n navigation: finalRoutes === resolved.routes ? resolved.navigation : buildNavigationTree(finalRoutes, ctx),\n }\n}\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport type { ClarifyPlugin } from '../../types.js'\n\nconst GENERATED_FILE_NAME = 'clarify-env.d.ts'\n\n/**\n * Template for the generated `clarify-env.d.ts` file.\n * Edit this template directly if you need to change the type declarations.\n * This avoids the complexity of reading external files at runtime after bundling.\n */\nconst CLARIFY_ENV_TEMPLATE = `// This file is generated by Clarify. Do not edit it manually.\n// It provides ambient type declarations for Clarify virtual modules used in\n// plugin and slot code, so the TypeScript language service can resolve them.\n\ndeclare module 'virtual:clarify/slot' {\n import type { UISlotContext } from '@clarify-labs/cli'\n\n export function useSlot(): UISlotContext\n}\n`\n\nexport function generateClarifyEnvDts(_plugins: ClarifyPlugin[]): string {\n return CLARIFY_ENV_TEMPLATE\n}\n\n/**\n * Writes `clarify-env.d.ts` into the project root. Only rewrites when content\n * changes to avoid triggering unnecessary file watchers, and never overwrites a\n * user-authored file that does not carry the generated marker.\n */\nexport function writeClarifyEnvDts(projectRoot: string, plugins: ClarifyPlugin[]): void {\n const filePath = join(projectRoot, GENERATED_FILE_NAME)\n const next = generateClarifyEnvDts(plugins)\n\n if (existsSync(filePath)) {\n const current = readFileSync(filePath, 'utf-8')\n if (current === next) return\n // Guard against clobbering a hand-written file that happens to share the name.\n if (!current.startsWith('// This file is generated by Clarify.')) return\n }\n\n writeFileSync(filePath, next, 'utf-8')\n}\n","export function escapeHtml(text: string): string {\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n","import { escapeHtml } from '../../parsers/markdown/utils.js'\nimport type { ClarifyProjectContext, ContentRoute, ResolvedProjectConfig } from '../../types.js'\n\n/**\n * HTML template manipulation helpers used during SSG.\n *\n * The SSG renderer needs to mutate the built `index.html` per route\n * (title, description/keywords meta, canonical link, `<html lang/dir>`,\n * and the root `<div>` content). These operations are all string-based\n * because the template is a raw HTML string, not a parsed DOM. Keeping them\n * in one module centralizes every HTML-mutation regex so they can be audited\n * together and so `ssg.ts` stays focused on the render pipeline.\n */\n\nfunction resolveProjectConfigFromContext(contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig): ResolvedProjectConfig {\n return 'projectConfig' in contextOrConfig ? contextOrConfig.projectConfig : contextOrConfig\n}\n\nfunction routeTitle(contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route?: ContentRoute): string {\n const projectConfig = resolveProjectConfigFromContext(contextOrConfig)\n const title = route?.meta.title.trim()\n if (!title || title === projectConfig.title) return projectConfig.title\n return `${title} - ${projectConfig.title}`\n}\n\nfunction canonicalUrl(contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route: ContentRoute): string | undefined {\n const projectConfig = resolveProjectConfigFromContext(contextOrConfig)\n if (!projectConfig.siteUrl || !route.alternates || !route.locale) return undefined\n const prefixedPath = route.alternates[route.locale]\n if (!prefixedPath || prefixedPath === route.path) return undefined\n\n const base = projectConfig.siteUrl.replace(/\\/+$/, '')\n const prefix = (!projectConfig.routePrefix || projectConfig.routePrefix === '/')\n ? ''\n : `/${projectConfig.routePrefix.replace(/^\\/+|\\/+$/g, '')}`\n return `${base}${prefix}${prefixedPath}`\n}\n\n/** Inject `lang` (and optional `dir`) onto the `<html>` tag for the route locale. */\nfunction injectHtmlLocaleAttributes(html: string, contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route?: ContentRoute): string {\n const projectConfig = resolveProjectConfigFromContext(contextOrConfig)\n const localeCode = route?.locale ?? projectConfig.locales?.default\n if (!localeCode) return html\n\n const localeConfig = projectConfig.locales?.locales.find(locale => locale.code === localeCode)\n const dir = localeConfig?.dir\n\n return html.replace(/<html\\b([^>]*)>/i, (_match, attributes: string) => {\n let nextAttributes = attributes\n .replace(/\\s+lang=(\"[^\"]*\"|'[^']*'|[^\\s>]*)/i, '')\n .replace(/\\s+dir=(\"[^\"]*\"|'[^']*'|[^\\s>]*)/i, '')\n\n nextAttributes = `${nextAttributes} lang=\"${escapeHtml(localeCode)}\"`\n if (dir) nextAttributes = `${nextAttributes} dir=\"${escapeHtml(dir)}\"`\n return `<html${nextAttributes}>`\n })\n}\n\n/** Set, replace, or remove a `<meta name=\"...\">` tag in `<head>`. */\nfunction setNamedMeta(html: string, name: string, content: string | undefined): string {\n const metaPattern = new RegExp(`<meta\\\\b(?=[^>]*\\\\bname=[\"']${name}[\"'])[^>]*>\\\\n?`, 'i')\n if (!content) return html.replace(metaPattern, '')\n\n const meta = `<meta name=\"${name}\" content=\"${escapeHtml(content)}\" />`\n if (metaPattern.test(html)) return html.replace(metaPattern, meta)\n return html.replace('</head>', ` ${meta}\\n </head>`)\n}\n\n/** Remove any existing canonical link and (if a URL is resolved) inject a fresh one. */\nfunction injectCanonicalUrl(html: string, contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route?: ContentRoute): string {\n const url = route ? canonicalUrl(contextOrConfig, route) : undefined\n // Remove any existing canonical link\n html = html.replace(/<link\\b[^>]*\\brel=[\"']canonical[\"'][^>]*\\/?>\\n?/gi, '')\n if (!url) return html\n return html.replace('</head>', ` <link rel=\"canonical\" href=\"${escapeHtml(url)}\" />\\n </head>`)\n}\n\n/**\n * Render the SSR result into the built HTML template: set `<title>`, the\n * description/keywords meta, the canonical link, the `<html lang/dir>`, and\n * replace the `#root` content with the rendered app HTML.\n */\nexport function injectSSRIntoTemplate(template: string, appHtml: string, contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route?: ContentRoute): string {\n const projectConfig = resolveProjectConfigFromContext(contextOrConfig)\n let html = injectHtmlLocaleAttributes(template, contextOrConfig, route)\n\n // Replace <title>...</title>\n html = html.replace(/<title>.*?<\\/title>/, `<title>${escapeHtml(routeTitle(contextOrConfig, route))}</title>`)\n\n html = setNamedMeta(html, 'description', route?.meta.description ?? projectConfig.description)\n html = setNamedMeta(html, 'keywords', route?.meta.keywords?.join(', '))\n html = injectCanonicalUrl(html, contextOrConfig, route)\n\n // Replace <div id=\"root\">...</div> with SSR rendered content\n // For bare alias routes (e.g., /path) in multilingual sites, mark the root div\n // with data-pagefind-ignore to prevent Pagefind from indexing duplicates\n const dataPagefindIgnore = route?.isBareAlias ? ' data-pagefind-ignore' : ''\n html = html.replace(/<div id=\"root\">([\\s\\S]*?)<\\/div>/, `<div id=\"root\"${dataPagefindIgnore}>${appHtml}</div>`)\n\n return html\n}\n","import { readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join } from 'node:path'\n\nimport type { AliasOptions } from 'vite'\n\nconst requireFromCli = createRequire(import.meta.url)\n\nfunction resolveCliDependency(id: string): string {\n return requireFromCli.resolve(id)\n}\n\nfunction resolvePackageExport(packageName: string, subpath: string, condition: 'import' | 'require' = 'import'): string {\n const packageJsonPath = requireFromCli.resolve(`${packageName}/package.json`)\n const packageRoot = dirname(packageJsonPath)\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as {\n exports?: Record<string, string | Record<string, string>>\n }\n const exportKey = subpath ? `./${subpath}` : '.'\n const exportEntry = packageJson.exports?.[exportKey]\n const target = typeof exportEntry === 'string'\n ? exportEntry\n : exportEntry?.[condition] ?? exportEntry?.default\n\n if (!target) {\n throw new Error(`[clarify] Unable to resolve ${packageName}/${subpath}`)\n }\n\n return join(packageRoot, target)\n}\n\n/**\n * Resolve Clarify's framework/runtime dependencies from the CLI package instead\n * of from the user's documentation project. This keeps content-only projects\n * free from React, renderer, and tsconfig requirements.\n */\nexport function createClarifyRuntimeAliases(): AliasOptions {\n return [\n { find: /^@clarify-labs\\/renderer\\/style\\.css$/, replacement: resolvePackageExport('@clarify-labs/renderer', 'style.css') },\n { find: /^@clarify-labs\\/renderer\\/client$/, replacement: resolvePackageExport('@clarify-labs/renderer', 'client') },\n { find: /^@clarify-labs\\/renderer\\/server$/, replacement: resolvePackageExport('@clarify-labs/renderer', 'server') },\n { find: /^@clarify-labs\\/renderer$/, replacement: resolvePackageExport('@clarify-labs/renderer', '') },\n { find: /^react\\/jsx-dev-runtime$/, replacement: resolveCliDependency('react/jsx-dev-runtime') },\n { find: /^react\\/jsx-runtime$/, replacement: resolveCliDependency('react/jsx-runtime') },\n { find: /^react-dom\\/client$/, replacement: resolveCliDependency('react-dom/client') },\n { find: /^react-dom\\/server$/, replacement: resolveCliDependency('react-dom/server') },\n { find: /^react-dom$/, replacement: resolveCliDependency('react-dom') },\n { find: /^react-router-dom$/, replacement: resolveCliDependency('react-router-dom') },\n { find: /^react-router$/, replacement: resolveCliDependency('react-router') },\n { find: /^mermaid$/, replacement: resolveCliDependency('mermaid') },\n { find: /^react-zoom-pan-pinch$/, replacement: resolveCliDependency('react-zoom-pan-pinch') },\n { find: /^react$/, replacement: resolveCliDependency('react') },\n ]\n}\n","import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { join, dirname } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { build } from 'vite'\nimport type { Plugin } from 'vite'\n\nimport type { ClarifyProjectContext, ContentRoute, ResolvedProjectConfig } from '../../types.js'\nimport { createClarifyTempDir } from '../project/temp-dir.js'\n\nimport { injectSSRIntoTemplate } from './html-template.js'\nimport { createClarifyRuntimeAliases } from './runtime-deps.js'\n\n// Re-export the template helpers so existing callers that imported them from\n// `ssg.ts` keep working. The implementations live in `html-template.ts`.\nexport { injectSSRIntoTemplate } from './html-template.js'\n\nexport function readIndexHtml(outputDirectory: string): string | undefined {\n const indexPath = join(outputDirectory, 'index.html')\n if (!existsSync(indexPath)) return undefined\n try {\n return readFileSync(indexPath, 'utf-8')\n } catch {\n return undefined\n }\n}\n\nexport function isNotFoundRoute(route: ContentRoute): boolean {\n return (route.basePath ?? route.path) === '/404'\n}\n\nexport function routeOutputFiles(outputDirectory: string, route: ContentRoute): string[] {\n const files = [join(outputDirectory, route.path, 'index.html')]\n if (isNotFoundRoute(route) && (!route.locale || route.path === '/404')) {\n files.push(join(outputDirectory, '404.html'))\n }\n return files\n}\n\nexport const SSR_ENTRY_CODE = `import { renderToHTML } from '@clarify-labs/renderer/server';\nimport { routes, navigation } from 'virtual:clarify/routes/server';\nimport { config } from 'virtual:clarify/config';\nimport { openApiSpecs } from 'virtual:clarify/openapi/server';\nimport { runtimeSlots } from 'virtual:clarify/slots';\n\nexport async function render(url) {\n // Pre-resolve every slot component factory so renderToString can use\n // them synchronously (renderToString has no Suspense support).\n const entries = Object.values(runtimeSlots).flat()\n await Promise.all(entries.map(async (entry) => {\n const mod = await entry.loadComponent()\n entry._resolved = mod.default\n }))\n return renderToHTML({ config, routes, navigation, openApiSpecs, runtimeSlots, url, themeEditor: config.theme.editor });\n}`\n\nexport function createTempEntryFile(content: string): string {\n const tempDir = createClarifyTempDir('ssr')\n const entryPath = join(tempDir, 'entry-server.ts')\n writeFileSync(entryPath, content, 'utf-8')\n return entryPath\n}\n\nexport async function buildSSRBundle(root: string, ssrEntry: string, ssrOutDir: string, plugins: Plugin[]): Promise<void> {\n await build({\n root,\n configFile: false,\n resolve: {\n alias: createClarifyRuntimeAliases(),\n },\n ssr: {\n noExternal: true,\n },\n plugins,\n build: {\n ssr: ssrEntry,\n outDir: ssrOutDir,\n emptyOutDir: true,\n rolldownOptions: {\n input: ssrEntry,\n checks: {\n pluginTimings: false,\n },\n },\n },\n })\n}\n\nexport async function renderSSGRoutes(routes: ContentRoute[], contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, outputDirectory: string, ssrBundlePath: string): Promise<void> {\n const { render } = await import(pathToFileURL(ssrBundlePath).href)\n\n const template = readIndexHtml(outputDirectory)\n if (!template) {\n throw new Error(\n `[clarify] index.html not found in outputDirectory \"${outputDirectory}\". Make sure Vite build produces it.`\n )\n }\n\n await Promise.all(routes.map(async (route) => {\n try {\n const appHtml = await render(route.path)\n const finalHtml = injectSSRIntoTemplate(template, appHtml, contextOrConfig, route)\n\n for (const outFile of routeOutputFiles(outputDirectory, route)) {\n mkdirSync(dirname(outFile), { recursive: true })\n writeFileSync(outFile, finalHtml, 'utf-8')\n }\n } catch (err) {\n console.error(`[clarify] Failed to render route \"${route.path}\":`, err)\n throw err\n }\n }))\n}\n","import { relative } from 'node:path'\n\nexport type StartupHintOptions = {\n projectRoot: string\n contentRoot: string\n contentDirExists: boolean\n hasRoutes: boolean\n}\n\nfunction contentDirectoryLabel(projectRoot: string, contentRoot: string): string {\n const relativePath = relative(projectRoot, contentRoot)\n return relativePath && relativePath !== '.' ? relativePath : 'source'\n}\n\nfunction contentFileExampleLabel(projectRoot: string, contentRoot: string): string {\n return `${contentDirectoryLabel(projectRoot, contentRoot)}/index.mdx`\n}\n\nexport function getStartupHints(options: StartupHintOptions): string[] {\n const hints: string[] = []\n\n if (!options.contentDirExists) {\n const label = contentDirectoryLabel(options.projectRoot, options.contentRoot)\n hints.push(`Content directory \"${label}\" was not found. Create it or pass --content <dir> to point Clarify at a different directory.`)\n } else if (!options.hasRoutes) {\n const example = contentFileExampleLabel(options.projectRoot, options.contentRoot)\n hints.push(`No content pages were found yet. Add ${example} to get started.`)\n }\n\n return hints\n}\n\nexport function logStartupHints(options: StartupHintOptions): void {\n const hints = getStartupHints(options)\n if (hints.length === 0) return\n\n const message = hints.map(hint => `[clarify] ${hint}`).join('\\n')\n console.warn(message)\n}\n","import type { ClarifyHookContext, ClarifyPlugin, ContentRoute, NavigationTree, ResolvedProjectConfig } from '../../types.js'\nimport type { ResolvedBuildOptions } from '../config/options.js'\n\nexport type ClarifyContextInit = {\n projectRoot: string\n contentRoot: string\n projectConfig: ResolvedProjectConfig\n generateOptions: ResolvedBuildOptions\n version: string\n routes?: ContentRoute[]\n navigation?: NavigationTree\n plugins?: ClarifyPlugin[]\n}\n\ntype ContextListener = () => void\n\nexport type ProjectStateUpdate = {\n projectRoot?: string\n contentRoot?: string\n projectConfig?: ResolvedProjectConfig\n generateOptions?: ResolvedBuildOptions\n version?: string\n}\n\nexport class ClarifyContext implements ClarifyHookContext {\n projectRoot: string\n contentRoot: string\n projectConfig: ResolvedProjectConfig\n generateOptions: ResolvedBuildOptions\n version: string\n\n private values = new Map<string, unknown>()\n private routeListeners = new Set<ContextListener>()\n private navigationListeners = new Set<ContextListener>()\n private currentRoutes: ContentRoute[]\n private currentNavigation: NavigationTree\n private currentPlugins: ClarifyPlugin[]\n\n constructor(init: ClarifyContextInit) {\n this.projectRoot = init.projectRoot\n this.contentRoot = init.contentRoot\n this.projectConfig = init.projectConfig\n this.generateOptions = init.generateOptions\n this.version = init.version\n this.currentRoutes = init.routes ?? []\n this.currentNavigation = init.navigation ?? { kind: 'flat', nodes: [] }\n this.currentPlugins = init.plugins ?? []\n }\n\n get routes(): ContentRoute[] {\n return this.currentRoutes\n }\n\n set routes(routes: ContentRoute[]) {\n this.currentRoutes = routes\n this.notify(this.routeListeners)\n }\n\n get navigation(): NavigationTree {\n return this.currentNavigation\n }\n\n set navigation(navigation: NavigationTree) {\n this.currentNavigation = navigation\n this.notify(this.navigationListeners)\n }\n\n get plugins(): ClarifyPlugin[] {\n return this.currentPlugins\n }\n\n set plugins(plugins: ClarifyPlugin[]) {\n this.currentPlugins = plugins\n }\n\n get isI18n(): boolean {\n return Boolean(this.projectConfig.locales)\n }\n\n get defaultLocale(): string | undefined {\n return this.projectConfig.locales?.default\n }\n\n get<T>(key: string): T | undefined {\n return this.values.get(key) as T | undefined\n }\n\n set<T>(key: string, value: T): void {\n this.values.set(key, value)\n }\n\n has(key: string): boolean {\n return this.values.has(key)\n }\n\n delete(key: string): boolean {\n return this.values.delete(key)\n }\n\n onRoutesChange(listener: ContextListener): () => void {\n this.routeListeners.add(listener)\n return () => this.routeListeners.delete(listener)\n }\n\n onNavigationChange(listener: ContextListener): () => void {\n this.navigationListeners.add(listener)\n return () => this.navigationListeners.delete(listener)\n }\n\n updateProjectState(update: ProjectStateUpdate): void {\n if (update.projectRoot !== undefined) this.projectRoot = update.projectRoot\n if (update.contentRoot !== undefined) this.contentRoot = update.contentRoot\n if (update.projectConfig !== undefined) this.projectConfig = update.projectConfig\n if (update.generateOptions !== undefined) this.generateOptions = update.generateOptions\n if (update.version !== undefined) this.version = update.version\n }\n\n private notify(listeners: Set<ContextListener>): void {\n for (const listener of listeners) listener()\n }\n}\n","import type { ClarifyCollectorHook, ClarifyHookContext, ClarifyInterceptHook, ClarifyPipelineHook, ClarifyPlugin, ClarifyTapHook } from '../../types.js'\n\nexport type PhaseName =\n | 'config:load'\n | 'config:resolve'\n | 'plugins:load'\n | 'site:discover'\n | 'content:process'\n | 'modules:build'\n | 'build'\n | 'ssg'\n | 'dev:server'\n\nexport type TapPhaseName =\n | `before:${PhaseName}`\n | `after:${PhaseName}`\n\nexport type TapHook = ClarifyTapHook\nexport type InterceptHook = ClarifyInterceptHook\nexport type PipelineHook<Input> = ClarifyPipelineHook<Input>\nexport type CollectorHook<Result> = ClarifyCollectorHook<Result>\n\nexport async function runTapHooks(plugins: ClarifyPlugin[], hookName: TapPhaseName, ctx: ClarifyHookContext): Promise<void> {\n for (const plugin of plugins) {\n const hook = plugin.hooks?.[hookName]\n if (!hook) continue\n try {\n await hook(ctx)\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"${hookName}\" failed: ${err}`, { cause: err })\n }\n }\n}\n\nexport async function runInterceptHooks(plugins: ClarifyPlugin[], hookName: 'build:shouldRun' | 'ssg:shouldRun', ctx: ClarifyHookContext): Promise<boolean> {\n for (const plugin of plugins) {\n const hook = plugin.hooks?.[hookName]\n if (!hook) continue\n try {\n if (await hook(ctx) === false) return false\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"${hookName}\" failed: ${err}`, { cause: err })\n }\n }\n return true\n}\n\nexport async function runPhase<T>(plugins: ClarifyPlugin[], phase: PhaseName, ctx: ClarifyHookContext, task: () => Promise<T> | T): Promise<T> {\n await runTapHooks(plugins, `before:${phase}`, ctx)\n const result = await task()\n await runTapHooks(plugins, `after:${phase}`, ctx)\n return result\n}\n","import { existsSync, rmSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport type { ConfigEnv, Plugin } from 'vite'\n\nimport { cliPackageVersion } from '../../cli/package.js'\nimport { createProjectContentProcessor } from '../../parsers/content/content.js'\nimport { findContentRoutes, findLocalizedContentRoutes } from '../../parsers/routes/routes.js'\nimport type { ClarifyEmitAsset, ClarifyHtmlTransformInput, ClarifyPlugin, ContentRoute, NavigationTree, ClarifyProjectContext } from '../../types.js'\nimport { resolveProjectConfig } from '../config/config.js'\nimport { resolveBuildOptions, type ClarifyBuildOptions } from '../config/options.js'\nimport { findClarifyConfigFile } from '../config/user-config.js'\nimport { runBuildAssetsHooks, runBuildDoneHooks, runDevConfigureServerHooks, runHooks } from '../plugin/hooks.js'\nimport { loadBuildPlugins } from '../plugin/manager.js'\nimport { resolveProjectContext } from '../project/project-context.js'\nimport { resolveRoutePages, resolveRouteState } from '../routing/route-resolution.js'\nimport { writeClarifyEnvDts } from '../runtime/env-types.js'\nimport {\n SSR_ENTRY_CODE,\n buildSSRBundle,\n createTempEntryFile,\n renderSSGRoutes,\n} from '../runtime/ssg.js'\nimport { logStartupHints } from '../runtime/startup.js'\nimport {\n buildVirtualModules,\n resolveVirtualModuleId,\n stripVirtualPrefix,\n type VirtualModules,\n} from '../runtime/virtual-modules.js'\n\nimport { ClarifyContext } from './context.js'\nimport { runInterceptHooks, runPhase, runTapHooks } from './phases.js'\nimport type { BuildSSRBundleOptions, ClarifyEngineRuntime, PrepareOptions } from './types.js'\n\nexport type { ClarifyEngineMode, ClarifyEngineRuntime, PrepareOptions } from './types.js'\nexport { assertNoRouteConflicts, createDevRouteConflictRoutes } from '../routing/route-resolution.js'\n\nfunction loadVirtualModule(id: string, modules: VirtualModules): string | null {\n const bareId = stripVirtualPrefix(id)\n return modules.get(bareId) ?? modules.get(id) ?? null\n}\n\nexport function assertNoContentDiagnostics(routes: ContentRoute[]): void {\n const failures = routes.filter(route => route.diagnostic)\n if (failures.length === 0) return\n\n const summary = failures\n .map(route => `- ${route.path}: ${route.diagnostic?.title ?? 'Content error'}${route.diagnostic?.filePath ? ` (${route.diagnostic.filePath})` : ''}`)\n .join('\\n')\n throw new Error(`[clarify] Content diagnostics prevented the build:\\n${summary}`)\n}\n\nexport class ClarifyEngine {\n readonly options: ClarifyBuildOptions\n readonly root: string\n configFilePath?: string\n readonly ctx: ClarifyContext\n\n private runtime: ClarifyEngineRuntime = { command: 'build', mode: 'production' }\n private virtualModules: VirtualModules = new Map()\n private buildEnabled = true\n private initializedOptions?: ClarifyBuildOptions\n\n constructor(options: ClarifyBuildOptions = {}) {\n this.options = options\n this.root = resolve(options.projectRoot ?? process.cwd())\n this.configFilePath = findClarifyConfigFile(this.root) ?? undefined\n\n // Create a minimal context with placeholder values. The real config\n // resolution and plugin loading happen in initialize(), which is always\n // called before any real work. This avoids redundant work in the\n // constructor and keeps Engine construction cheap.\n const placeholderConfig = resolveProjectConfig({})\n const placeholderOptions = resolveBuildOptions(options)\n this.ctx = new ClarifyContext({\n projectRoot: this.root,\n contentRoot: join(this.root, placeholderOptions.rootDirectory),\n projectConfig: placeholderConfig,\n generateOptions: placeholderOptions,\n version: cliPackageVersion,\n routes: [],\n navigation: { kind: 'flat', nodes: [] },\n plugins: [],\n })\n }\n\n configureRuntime(runtime: Partial<ClarifyEngineRuntime>): void {\n this.runtime = { ...this.runtime, ...runtime }\n }\n\n async initialize(env: ConfigEnv = { command: this.runtime.command, mode: this.runtime.mode }, options: ClarifyBuildOptions = this.options, prepareOptions: PrepareOptions = {}): Promise<ClarifyBuildOptions> {\n if (this.initializedOptions && !prepareOptions.force) return this.initializedOptions\n\n const seedPlugins = loadBuildPlugins(options, { htmlShell: prepareOptions.htmlShell })\n this.ctx.plugins = seedPlugins\n const context = await runPhase(seedPlugins, 'config:load', this.ctx, () => resolveProjectContext(options, env))\n\n this.configFilePath = context.configFilePath\n this.ctx.updateProjectState({\n projectRoot: context.projectRoot,\n contentRoot: context.contentRoot,\n projectConfig: context.projectConfig,\n generateOptions: context.buildOptions,\n version: context.projectContext.version,\n })\n await runPhase(seedPlugins, 'config:resolve', this.ctx, () => undefined)\n\n // Reload plugins with the fully resolved options (which now include\n // plugins declared in the config file) and run the plugins:load phase.\n // The seed plugins above only carried user-supplied options.plugins so\n // that config:load/config:resolve hooks could fire before the config\n // file was read; the final plugin set replaces them here.\n const finalPlugins = loadBuildPlugins(context.resolvedOptions, { htmlShell: prepareOptions.htmlShell })\n this.ctx.plugins = finalPlugins\n await runPhase(finalPlugins, 'plugins:load', this.ctx, () => undefined)\n this.initializedOptions = context.resolvedOptions\n\n return context.resolvedOptions\n }\n\n /**\n * Runs the full pre-build/pre-dev preparation: initialize (config load +\n * resolve + plugins:load), site discovery (routes + navigation), and module\n * building. This is the single entry point that prepares the engine before\n * handing it to a Vite adapter or running a check, so callers never need to\n * call initialize/discoverSite separately.\n *\n * Options:\n * - `force`: re-run even if already prepared (config-file hot reload).\n * - `htmlShell`: toggle the HTML shell builtin plugin (default true).\n * - `skipModules`: skip `buildModules()` (check command).\n * - `skipHints`: skip `logStartupHints()` (check command).\n *\n * Idempotent: calling prepare() again with the same env is a no-op unless\n * `force` is set.\n */\n async prepare(env: ConfigEnv = { command: this.runtime.command, mode: this.runtime.mode }, options: ClarifyBuildOptions = this.options, prepareOptions: PrepareOptions = {}): Promise<ClarifyBuildOptions> {\n this.configureRuntime({ command: env.command, mode: env.mode })\n const resolvedOptions = await this.initialize(env, options, prepareOptions)\n await this.discoverSite()\n if (!prepareOptions.skipModules) await this.buildModules()\n if (!prepareOptions.skipHints) this.logStartupHints()\n return resolvedOptions\n }\n\n get projectConfig(): ClarifyContext['projectConfig'] {\n return this.ctx.projectConfig\n }\n\n get generateOptions(): ClarifyContext['generateOptions'] {\n return this.ctx.generateOptions\n }\n\n get contentRoot(): string {\n return this.ctx.contentRoot\n }\n\n get routes(): ContentRoute[] {\n return this.ctx.routes\n }\n\n get navigation(): NavigationTree {\n return this.ctx.navigation\n }\n\n get plugins(): ClarifyPlugin[] {\n return this.ctx.plugins\n }\n\n get modules(): VirtualModules {\n return this.virtualModules\n }\n\n loadModule(id: string): string | null {\n return loadVirtualModule(id, this.virtualModules)\n }\n\n async discoverSite(): Promise<void> {\n const plugins = this.ctx.plugins\n const contentRoot = this.ctx.contentRoot\n const { locales } = this.ctx.projectConfig\n\n // Phase 3: site:discover - scan content directory. The Engine provides the\n // default discovery logic (i18n-aware content scanning) directly; user\n // plugins can extend or replace it via the routes:discover pipeline hook.\n let routes = await runPhase(plugins, 'site:discover', this.ctx, async () => {\n const processor = createProjectContentProcessor(plugins, this.ctx)\n const options = { contentProcessor: processor }\n\n const discovered = locales\n ? await findLocalizedContentRoutes(contentRoot, locales, options)\n : await findContentRoutes(contentRoot, contentRoot, options)\n\n // Run routes:discover hook so plugins can augment the discovered routes.\n const result = await runHooks(plugins, 'routes:discover', { contentRoot, routes: discovered }, this.ctx)\n const routes = await runHooks(plugins, 'routes:discovered', result.routes, this.ctx)\n return routes\n })\n\n // Phase 4: content:process - post-discovery adjustments. Map routes to\n // pages, run pages:resolved pipeline, then write back any page-level\n // changes (frontmatter/content) onto the routes.\n routes = await runPhase(plugins, 'content:process', this.ctx, () => resolveRoutePages(routes, plugins, this.ctx))\n\n const resolved = await resolveRouteState(routes, plugins, this.ctx, this.runtime.command === 'serve')\n this.ctx.routes = resolved.routes\n this.ctx.navigation = resolved.navigation\n }\n\n logStartupHints(): void {\n logStartupHints({\n projectRoot: this.root,\n contentRoot: this.contentRoot,\n contentDirExists: existsSync(this.contentRoot),\n hasRoutes: this.routes.length > 0,\n })\n }\n\n async buildModules(): Promise<void> {\n await runPhase(this.plugins, 'modules:build', this.ctx, async () => {\n this.virtualModules = buildVirtualModules({\n projectConfig: this.projectConfig,\n generateOptions: this.generateOptions,\n routes: this.routes,\n navigation: this.navigation,\n plugins: this.plugins,\n themeEditor: this.runtime.command === 'serve' || this.runtime.themeEditor === true || this.projectConfig.features.themeEditor.enabled,\n version: this.ctx.version,\n })\n this.virtualModules = await runHooks(this.plugins, 'modules:before', this.virtualModules, this.ctx)\n })\n }\n\n writeEnvTypes(): void {\n writeClarifyEnvDts(this.root, this.plugins)\n }\n\n hasContentRouteForFile(filePath: string): boolean {\n return this.routes.some(route => route.source.filePath === filePath)\n }\n\n async collectBuildAssets(): Promise<ClarifyEmitAsset[]> {\n if (!this.buildEnabled) return []\n return runBuildAssetsHooks(this.plugins, this.ctx)\n }\n\n async beginBuild(): Promise<boolean> {\n this.buildEnabled = await runInterceptHooks(this.plugins, 'build:shouldRun', this.ctx)\n if (!this.buildEnabled) return false\n await runTapHooks(this.plugins, 'before:build', this.ctx)\n return true\n }\n\n async endBuild(): Promise<void> {\n if (!this.buildEnabled) return\n await runTapHooks(this.plugins, 'after:build', this.ctx)\n }\n\n shouldRunBuild(): boolean {\n return this.buildEnabled\n }\n\n async configureDevServer(server: Parameters<typeof runDevConfigureServerHooks>[1]): Promise<Awaited<ReturnType<typeof runDevConfigureServerHooks>>> {\n return runPhase(this.plugins, 'dev:server', this.ctx, () => {\n return runDevConfigureServerHooks(this.plugins, server, this.ctx)\n })\n }\n\n async runBuildDone(): Promise<void> {\n if (!this.buildEnabled) return\n await runBuildDoneHooks(this.plugins, this.ctx)\n }\n\n async runSSG(): Promise<void> {\n if (!this.buildEnabled) return\n await runPhase(this.plugins, 'ssg', this.ctx, async () => {\n if (process.env.SKIP_CLARIFY_SSG) return\n\n if (!(await runInterceptHooks(this.plugins, 'ssg:shouldRun', this.ctx))) return\n\n assertNoContentDiagnostics(this.routes)\n\n const outputDir = this.runtime.outputDirectory ?? this.generateOptions.outputDirectory\n if (!outputDir) throw new Error('[clarify] outputDirectory is required before SSG runs')\n\n const ssrOutputDir = join(outputDir, '.ssr')\n let tempEntryPath: string | undefined\n\n try {\n tempEntryPath = createTempEntryFile(SSR_ENTRY_CODE)\n const buildSSR = this.runtime.buildSSRBundle ?? ((options: BuildSSRBundleOptions) => buildSSRBundle(options.root, options.ssrEntry, options.ssrOutDir, options.plugins))\n\n await buildSSR({\n root: this.root,\n ssrEntry: tempEntryPath,\n ssrOutDir: ssrOutputDir,\n plugins: this.runtime.ssrPlugins ?? [],\n })\n\n const ssrBundlePath = join(ssrOutputDir, 'entry-server.js')\n await renderSSGRoutes(this.routes, this.runtimeContext(), outputDir, ssrBundlePath)\n } catch (err) {\n console.error('[clarify] SSG failed:', err)\n throw err\n } finally {\n if (tempEntryPath) {\n try {\n rmSync(tempEntryPath, { force: true })\n } catch {\n // ignore cleanup errors\n }\n }\n }\n\n })\n await this.runBuildDone()\n }\n\n async refresh(): Promise<void> {\n await this.discoverSite()\n await this.buildModules()\n }\n\n /**\n * Runs the `html:transform` pipeline hook and returns the transformed\n * input. Adapters call this from their `transformIndexHtml` hook instead\n * of invoking `runHooks` directly, keeping hook execution inside Engine.\n */\n async transformHtml(input: ClarifyHtmlTransformInput): Promise<ClarifyHtmlTransformInput> {\n return runHooks(this.plugins, 'html:transform', input, this.ctx)\n }\n\n runtimeContext(): ClarifyProjectContext {\n return {\n projectRoot: this.root,\n contentRoot: this.contentRoot,\n projectConfig: this.projectConfig,\n generateOptions: this.generateOptions,\n version: this.ctx.version,\n }\n }\n\n createSSGVirtualPlugin(): Plugin {\n return {\n name: 'clarify:virtual-ssg',\n resolveId: id => resolveVirtualModuleId(id, this.virtualModules, this.routes),\n load: id => this.loadModule(id),\n }\n }\n}\n\nexport function createClarifyEngine(options: ClarifyBuildOptions = {}): ClarifyEngine {\n return new ClarifyEngine(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,YAAY,UAA8B,aAAqD;CACtG,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,IAAI,CAAC,aAAa,OAAO,SAAS,QAAQ,gBAAgB,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAEhF,MAAM,aAAa,SAAS,aAAa,QAAQ;CACjD,OAAO,cAAc,CAAC,WAAW,WAAW,IAAI,KAAK,CAAC,WAAW,UAAU,IACvE,aACA,SAAS,QAAQ,gBAAgB,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC7D;AAEA,SAAgB,wBAAwB,SAA4D;CAClG,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,MAAM,QAAQ;EACd,OAAO,QAAQ;EACf,SAAS,QAAQ;EACjB,UAAU,YAAY,QAAQ,UAAU,QAAQ,WAAW;EAC3D,SAAS,iBAAiB,QACtB,QAAQ,eAAe,MAAM,SAAS,MAAM,UAAU,MAAM,UAC5D,OAAO,KAAK;CAClB;AACF;;;ACZA,SAAS,YAAY,WAA4B;CAG/C,QAFgB,MAAM,QAAQ,SAAS,IAAI,YAAY,OAAO,cAAc,WAAW,UAAU,MAAM,KAAK,IAAI,CAAC,EAAA,CACnF,MAAM,SAAyB,OAAO,SAAS,YAAY,KAAK,WAAW,WAAW,CAC7G,CAAA,EAAe,QAAQ,cAAc,EAAE,KAAK;AACrD;AAEA,IAAM,oBAAoB,wBAAwB;AAElD,S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ACR,IAAI,eACF,IAAI;KACF,OAAO,eAAe,EAAE,OAAO,KAAK,CAAC;IACvC,QAAQ,CAER;GAEJ;EAEF,CAAC;EACD,MAAM,KAAK,aAAa;CAC1B;CAEA,MAAM,UAAyB;EAC7B,MAAM,KAAK,aAAa;EACxB,MAAM,KAAK,aAAa;CAC1B;;;;;;CAOA,MAAM,cAAc,OAAsE;EACxF,OAAO,SAAS,KAAK,SAAS,kBAAkB,OAAO,KAAK,GAAG;CACjE;CAEA,iBAAwC;EACtC,OAAO;GACL,aAAa,KAAK;GAClB,aAAa,KAAK;GAClB,eAAe,KAAK;GACpB,iBAAiB,KAAK;GACtB,SAAS,KAAK,IAAI;EACpB;CACF;CAEA,yBAAiC;EAC/B,OAAO;GACL,MAAM;GACN,YAAW,OAAM,uBAAuB,IAAI,KAAK,gBAAgB,KAAK,MAAM;GAC5E,OAAM,OAAM,KAAK,WAAW,EAAE;EAChC;CACF;AACF;AAEA,SAAgB,oBAAoB,UAA+B,CAAC,GAAkB;CACpF,OAAO,IAAI,cAAc,OAAO;AAClC"}
|
|
1
|
+
{"version":3,"file":"engine-Cuwx3aJ2.js","names":[],"sources":["../source/parsers/content/diagnostic.ts","../source/parsers/markdown/mdx.ts","../source/core/runtime/module-ids.ts","../source/core/plugin/hooks.ts","../source/parsers/markdown/frontmatter.ts","../source/parsers/content/content.ts","../source/parsers/markdown/markdown.ts","../source/parsers/routes/routes.ts","../source/parsers/router/dev-routes.ts","../source/parsers/theme.ts","../source/core/config/config-schema.ts","../source/core/config/config.ts","../source/core/config/user-config.ts","../source/core/project/project-info.ts","../source/core/runtime/virtual-modules.ts","../source/core/adapters.ts","../package.json","../source/cli/package.ts","../source/core/config/options.ts","../source/plugins/content-artifacts/artifacts.ts","../source/plugins/content-artifacts/server.ts","../source/plugins/content-artifacts/index.ts","../source/plugins/html-shell/index.ts","../source/plugins/mcp-search/mcp-config.ts","../source/plugins/mcp-search/orama-index.ts","../source/plugins/mcp-search/index.ts","../source/plugins/openapi/parser.ts","../source/plugins/openapi/routes.ts","../source/plugins/openapi/virtual-modules.ts","../source/plugins/openapi/state.ts","../source/plugins/openapi/index.ts","../source/core/project/temp-dir.ts","../source/plugins/page-search/search-language.ts","../source/plugins/page-search/index.ts","../source/plugins/seo/artifacts.ts","../source/plugins/seo/index.ts","../source/plugins/source-links/source-links.ts","../source/plugins/source-links/index.ts","../source/plugins/variables/index.ts","../source/core/plugin/builtin.ts","../source/core/plugin/manager.ts","../source/core/project/project-context.ts","../source/core/routing/route-analysis.ts","../source/core/routing/route-resolution.ts","../source/core/runtime/env-types.ts","../source/parsers/markdown/utils.ts","../source/core/runtime/html-template.ts","../source/core/runtime/runtime-deps.ts","../source/core/runtime/ssg.ts","../source/core/runtime/startup.ts","../source/core/engine/context.ts","../source/core/engine/phases.ts","../source/core/engine/engine.ts"],"sourcesContent":["import { isAbsolute, relative } from 'node:path'\n\nimport type { ContentDiagnostic } from '@clarify-labs/renderer'\n\ntype CreateContentDiagnosticOptions = {\n kind: ContentDiagnostic['kind']\n title: string\n message: string\n error: unknown\n filePath?: string\n projectRoot?: string\n includeStack?: boolean\n}\n\nfunction displayPath(filePath: string | undefined, projectRoot: string | undefined): string | undefined {\n if (!filePath) return undefined\n if (!projectRoot) return filePath.replace(/^[A-Za-z]:\\//, '').replace(/^\\/+/, '')\n\n const normalized = relative(projectRoot, filePath)\n return normalized && !normalized.startsWith('..') && !isAbsolute(normalized)\n ? normalized\n : filePath.replace(/^[A-Za-z]:\\//, '').replace(/^\\/+/, '')\n}\n\nexport function createContentDiagnostic(options: CreateContentDiagnosticOptions): ContentDiagnostic {\n const { error } = options\n return {\n kind: options.kind,\n title: options.title,\n message: options.message,\n filePath: displayPath(options.filePath, options.projectRoot),\n details: error instanceof Error\n ? options.includeStack ? error.stack ?? error.message : error.message\n : String(error),\n }\n}\n","import { compile, type CompileOptions } from '@mdx-js/mdx'\nimport rehypeShiki from '@shikijs/rehype'\nimport rehypeSlug from 'rehype-slug'\nimport { createCssVariablesTheme } from 'shiki'\nimport { visit } from 'unist-util-visit'\n\nimport { markdownRemarkPlugins, parseCodeMeta } from '@clarify-labs/renderer'\n\nimport type { ContentDiagnostic } from '../../types.js'\nimport { createContentDiagnostic } from '../content/diagnostic.js'\n\ntype HastNode = {\n type: string\n tagName?: string\n value?: string\n properties?: Record<string, unknown>\n children?: HastNode[]\n}\n\ntype HastParent = HastNode & {\n children: HastNode[]\n}\n\nfunction getLanguage(className: unknown): string {\n const classes = Array.isArray(className) ? className : typeof className === 'string' ? className.split(/\\s+/) : []\n const languageClass = classes.find((item): item is string => typeof item === 'string' && item.startsWith('language-'))\n return languageClass?.replace(/^language-/, '') || 'txt'\n}\n\nconst cssVariablesTheme = createCssVariablesTheme()\n\nexport function rehypeParseCodeBlocks() {\n return (tree: HastNode) => {\n visit(tree, 'element', (node: HastNode, _nodeIndex: number | undefined, parentNode: HastParent | undefined) => {\n if (node.tagName !== 'code' || !parentNode) return\n parentNode.properties = parentNode.properties ?? {}\n node.properties = node.properties ?? {}\n const language = getLanguage(node.properties.className)\n parentNode.properties.language = language\n node.properties.language = language\n\n for (const key of ['title', 'tag', 'label']) {\n if (node.properties[key] !== undefined) parentNode.properties[key] = node.properties[key]\n }\n })\n }\n}\n\nexport const remarkPlugins: unknown[] = markdownRemarkPlugins\nexport const rehypePlugins: NonNullable<CompileOptions['rehypePlugins']> = [\n rehypeSlug,\n rehypeParseCodeBlocks,\n [rehypeShiki, {\n theme: cssVariablesTheme,\n langs: [],\n lazy: true,\n addLanguageClass: true,\n fallbackLanguage: 'text',\n parseMetaString: parseCodeMeta,\n }],\n]\n\ntype ContentCompileDiagnosticOptions = {\n format: 'markdown' | 'markdown+jsx'\n phase: 'syntax' | 'compilation'\n error: unknown\n filePath?: string\n projectRoot?: string\n}\n\nexport function createContentCompileDiagnostic(options: ContentCompileDiagnosticOptions): ContentDiagnostic {\n const { format, phase, error, filePath, projectRoot } = options\n const label = format === 'markdown+jsx' ? 'MDX' : 'Markdown'\n return createContentDiagnostic({\n kind: format,\n title: `${label} ${phase} error`,\n message: phase === 'syntax'\n ? `This page could not be compiled. Fix the ${label} syntax or component usage above, then reload the route.`\n : `This page could not be compiled. Fix the ${label} syntax or plugin error below, then reload the route.`,\n error,\n filePath,\n projectRoot,\n includeStack: phase === 'compilation',\n })\n}\n\ntype CompileContentOptions = {\n filePath?: string\n projectRoot?: string\n}\n\n/**\n * Validate MDX content for diagnostics WITHOUT running the build-time rehype\n * pipeline (Shiki highlighting, slug injection, code-block parsing).\n *\n * `rehypePlugins` includes `rehypeShiki`, which loads grammar/WASM assets and\n * is expensive. The real highlighting happens at Vite build time via the\n * `@mdx-js/rollup` plugin (see `createContentCompilerPlugin` in\n * `core/adapters.ts`), which runs the full remark + rehype pipeline.\n * Re-running it here, during route discovery (Phase 3), would compile every\n * `.mdx` file twice and invoke Shiki once per file per `engine.refresh()` -\n * see ARCHITECTURE.md §2.2 which states \"不应在 core 中执行代码高亮\".\n *\n * The remark pipeline still runs (shared with the Vite plugin via\n * `remarkPlugins`), so MDX/JSX syntax errors - the only class of error this\n * diagnostic is meant to surface ahead of the Vite build - are caught. The\n * output is discarded; only the thrown error is used.\n *\n * `.md` files are handled by `compileMarkdownContent` in `markdown.ts`, which\n * mirrors the adapter's markdown compiler semantics (`format: 'md'`, raw HTML\n * allowed). Keep the two compilers separate so each format can evolve its own\n * diagnostic rules without contaminating the other.\n */\nexport async function compileMdxContent(content: string, options: CompileContentOptions = {}): Promise<{ ok: true } | { ok: false; diagnostic: ContentDiagnostic }> {\n const { filePath, projectRoot } = options\n try {\n await compile(content, {\n jsx: true,\n providerImportSource: '@clarify-labs/renderer',\n remarkPlugins: remarkPlugins as CompileOptions['remarkPlugins'],\n // NOTE: `rehypePlugins` intentionally omitted. See JSDoc above.\n })\n return { ok: true }\n } catch (error) {\n return {\n ok: false,\n diagnostic: createContentCompileDiagnostic({ format: 'markdown+jsx', phase: 'syntax', error, filePath, projectRoot }),\n }\n }\n}\n","import { isAbsolute, relative } from 'node:path'\n\nconst PAGE_PREFIX = 'virtual:clarify-page/'\nconst CONTENT_PREFIX = 'virtual:clarify-content/'\n\nexport function pageVirtualModuleId(path: string): string {\n const normalized = path\n .replace(/^\\/+/, '')\n .replace(/\\/index$/, '')\n .replace(/\\/+/g, '/')\n return `${PAGE_PREFIX}${normalized || 'index'}`\n}\n\nexport function pageVirtualModuleIdFromRef(ref: string): string {\n return pageVirtualModuleId(ref\n .replace(/\\.mdx?$/, '')\n .replace(/\\.openapi\\.(json|yaml|yml)$/, ''))\n}\n\nexport function isPageVirtualModuleId(id: string): boolean {\n return id.startsWith(PAGE_PREFIX)\n}\n\nexport function pageVirtualModulePath(id: string): string {\n return isPageVirtualModuleId(id) ? id.slice(PAGE_PREFIX.length) : id\n}\n\nexport function contentVirtualModuleId(filePath: string, contentRoot: string): string {\n const sourcePath = relative(contentRoot, filePath).replace(/\\\\/g, '/')\n if (!sourcePath || sourcePath.startsWith('../') || isAbsolute(sourcePath)) {\n throw new Error(`Content source must be inside the content root: ${filePath}`)\n }\n return `${CONTENT_PREFIX}${sourcePath}`\n}\n","import type { ViteDevServer } from 'vite'\n\nimport type { ClarifyDevServerPostHook, ClarifyEmitAsset, ClarifyHookContext, ClarifyPipelineHooks, ClarifyPlugin } from '../../types.js'\n\nexport async function runHooks<K extends keyof ClarifyPipelineHooks>(plugins: ClarifyPlugin[], hookName: K, input: Parameters<NonNullable<ClarifyPipelineHooks[K]>>[0], ctx: ClarifyHookContext): Promise<Parameters<NonNullable<ClarifyPipelineHooks[K]>>[0]> {\n let result = input\n for (const plugin of plugins) {\n const hook = plugin.hooks?.[hookName]\n if (!hook) continue\n try {\n result = await hook(result as never, ctx) as Parameters<NonNullable<ClarifyPipelineHooks[K]>>[0]\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"${hookName}\" failed: ${err}`, { cause: err })\n }\n }\n return result\n}\n\nexport async function runDevConfigureServerHooks(plugins: ClarifyPlugin[], server: ViteDevServer, ctx: ClarifyHookContext): Promise<ClarifyDevServerPostHook[]> {\n const postHooks: ClarifyDevServerPostHook[] = []\n for (const plugin of plugins) {\n const hook = plugin.hooks?.['dev:configureServer']\n if (!hook) continue\n try {\n const postHook = await hook(server, ctx)\n if (postHook) postHooks.push(postHook)\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"dev:configureServer\" failed: ${err}`, { cause: err })\n }\n }\n return postHooks\n}\n\nexport async function runBuildAssetsHooks(plugins: ClarifyPlugin[], ctx: ClarifyHookContext): Promise<ClarifyEmitAsset[]> {\n const assets: ClarifyEmitAsset[] = []\n const producerByFileName = new Map<string, string>()\n\n for (const plugin of plugins) {\n const hook = plugin.hooks?.['build:assets']\n if (!hook) continue\n\n let pluginAssets: ClarifyEmitAsset[]\n try {\n pluginAssets = await hook(ctx)\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"build:assets\" failed: ${err}`, { cause: err })\n }\n\n for (const asset of pluginAssets) {\n const fileName = asset.fileName.replace(/\\\\/g, '/').replace(/^\\/+/, '')\n const previousProducer = producerByFileName.get(fileName)\n if (previousProducer) {\n throw new Error(`[clarify] build asset \"${fileName}\" is emitted by both plugin \"${previousProducer}\" and plugin \"${plugin.name}\"`)\n }\n producerByFileName.set(fileName, plugin.name)\n assets.push({ ...asset, fileName })\n }\n }\n\n return assets\n}\n\nexport async function runBuildDoneHooks(plugins: ClarifyPlugin[], ctx: ClarifyHookContext): Promise<void> {\n for (const plugin of plugins) {\n const hook = plugin.hooks?.['build:done']\n if (!hook) continue\n try {\n await hook(ctx)\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"build:done\" failed: ${err}`, { cause: err })\n }\n }\n}\n","import matter from 'gray-matter'\n\nexport type ParsedFrontmatter = {\n frontmatter: Record<string, unknown>\n content: string\n}\n\n/**\n * 在内容入口统一解析 MDX frontmatter,并返回可供后续流程复用的标准化正文。\n */\nexport function parseFrontmatter(content: string): ParsedFrontmatter {\n const parsed = matter(content)\n return {\n frontmatter: parsed.data,\n content: parsed.content.replace(/^\\r?\\n/, ''),\n }\n}\n\n/**\n * 从 MDX 文件内容中提取 frontmatter。\n * 使用 gray-matter 支持 YAML frontmatter 的标准语法和类型解析。\n */\nexport function extractFrontmatter(content: string): Record<string, unknown> {\n return parseFrontmatter(content).frontmatter\n}\n\n/**\n * 移除 MDX 文件开头的 YAML frontmatter,保留页面正文。\n */\nexport function stripFrontmatter(content: string): string {\n return parseFrontmatter(content).content\n}\n","import { runHooks } from '../../core/plugin/hooks.js'\nimport type { ClarifyContentKind, ClarifyContentTransformInput, ClarifyHookContext, ClarifyPlugin } from '../../types.js'\nimport { parseFrontmatter } from '../markdown/frontmatter.js'\n\nexport type ProcessedMdxContent = {\n frontmatter: Record<string, unknown>\n content: string\n}\n\nexport type ContentTransform = (input: ClarifyContentTransformInput) => Promise<ClarifyContentTransformInput> | ClarifyContentTransformInput\n\nexport type ContentProcessor = {\n processMdx(source: string, filePath?: string): Promise<ProcessedMdxContent>\n processText(source: string, kind: Exclude<ClarifyContentKind, 'markdown+jsx'>, filePath?: string): Promise<string>\n}\n\nasync function transformContent(transform: ContentTransform | undefined, input: ClarifyContentTransformInput): Promise<ClarifyContentTransformInput> {\n return transform ? await transform(input) : input\n}\n\nexport function createContentProcessor(transform?: ContentTransform): ContentProcessor {\n return {\n async processMdx(source, filePath) {\n const { frontmatter, content } = parseFrontmatter(source)\n const transformed = await transformContent(transform, {\n kind: 'markdown+jsx',\n source,\n filePath,\n frontmatter,\n content,\n })\n\n return {\n frontmatter: transformed.frontmatter,\n content: transformed.content,\n }\n },\n async processText(source, kind, filePath) {\n const transformed = await transformContent(transform, {\n kind,\n source,\n filePath,\n frontmatter: {},\n content: source,\n })\n return transformed.content\n },\n }\n}\n\n/**\n * Creates a ContentProcessor that forwards each piece of content through the\n * `content:transform` pipeline hook before it is parsed.\n *\n * Plugins that need to read content (site-discovery, openapi) call this with\n * the plugins list from their hook context. There is no global registry -\n * each call produces an independent processor bound to the given plugins.\n */\nexport function createProjectContentProcessor(plugins: ClarifyPlugin[], ctx: ClarifyHookContext): ContentProcessor {\n return createContentProcessor(input => runHooks(plugins, 'content:transform', input, ctx))\n}\n","import { compile, type CompileOptions } from '@mdx-js/mdx'\n\nimport type { ContentDiagnostic } from '../../types.js'\n\nimport { createContentCompileDiagnostic, remarkPlugins } from './mdx.js'\n\ntype CompileMarkdownContentOptions = {\n filePath?: string\n projectRoot?: string\n}\n\n/**\n * Validate Markdown content for diagnostics WITHOUT running the build-time\n * rehype pipeline (Shiki highlighting, slug injection, code-block parsing).\n *\n * `rehypePlugins` includes `rehypeShiki`, which loads grammar/WASM assets and\n * is expensive. The real highlighting happens at Vite build time via the\n * `@mdx-js/rollup` plugin (see `createContentCompilerPlugin` in\n * `core/adapters.ts`), which runs the full remark + rehype pipeline.\n * Re-running it here, during route discovery (Phase 3), would compile every\n * `.md` file twice and invoke Shiki once per file per `engine.refresh()` -\n * see ARCHITECTURE.md §2.2 which states \"不应在 core 中执行代码高亮\".\n *\n * `format: 'md'` mirrors the adapter's markdown compiler semantics (no JSX,\n * raw HTML allowed via `remarkRehypeOptions`), so the same class of syntax\n * errors that would break the Vite build is surfaced as a diagnostic here\n * instead of leaking out as an opaque\n * `Failed to fetch dynamically imported module` at runtime.\n *\n * MDX files are handled by `compileMdxContent` in `mdx.ts`. Keep the two\n * compilers separate so each format can evolve its own diagnostic rules\n * without contaminating the other.\n */\nexport async function compileMarkdownContent(content: string, options: CompileMarkdownContentOptions = {}): Promise<{ ok: true } | { ok: false; diagnostic: ContentDiagnostic }> {\n const { filePath, projectRoot } = options\n try {\n await compile(content, {\n format: 'md',\n jsx: true,\n providerImportSource: '@clarify-labs/renderer',\n remarkPlugins: remarkPlugins as CompileOptions['remarkPlugins'],\n remarkRehypeOptions: { allowDangerousHtml: true },\n // NOTE: `rehypePlugins` intentionally omitted. See JSDoc above.\n })\n return { ok: true }\n } catch (error) {\n return {\n ok: false,\n diagnostic: createContentCompileDiagnostic({ format: 'markdown', phase: 'syntax', error, filePath, projectRoot }),\n }\n }\n}\n","import { readdir, readFile, stat } from 'node:fs/promises'\nimport { extname, join, relative } from 'node:path'\n\nimport GithubSlugger from 'github-slugger'\nimport { toString } from 'mdast-util-to-string'\nimport { remark } from 'remark'\nimport { visit } from 'unist-util-visit'\n\nimport { contentVirtualModuleId, pageVirtualModuleId, pageVirtualModuleIdFromRef } from '../../core/runtime/module-ids.js'\nimport type { ClarifyPage, ClarifyPageRouteIntent, ContentRoute, ContentSection, ClarifyNavigationNode, ClarifyPagesConfig, ClarifyPagesGroup, ClarifyPagesItem, ClarifyRouteIntent, ClarifyLocalizedText, ClarifyTabsConfig, LocalizedNavigation, LocalizedTabbedNavigation, MarkdownContentRoute, NavigationSection, ResolvedClarifyLocalesConfig, TabbedNavigation } from '../../types.js'\nimport { createContentProcessor, type ContentProcessor } from '../content/content.js'\nimport { compileMarkdownContent } from '../markdown/markdown.js'\nimport { compileMdxContent } from '../markdown/mdx.js'\n\nexport type FindContentRoutesOptions = {\n contentProcessor?: ContentProcessor\n}\n\nexport function kebabToTitle(str: string): string {\n return str\n .split('-')\n .map(w => w.charAt(0).toUpperCase() + w.slice(1))\n .join(' ')\n}\n\nfunction parseMdxTree(content: string) {\n return remark.parse(content)\n}\n\nasync function compileRouteDiagnostic(content: string, filePath: string, baseDir: string) {\n const compile = extname(filePath).toLowerCase() === '.md' ? compileMarkdownContent : compileMdxContent\n const result = await compile(content, { filePath, projectRoot: baseDir })\n return result.ok ? undefined : result.diagnostic\n}\n\n/** 从内容中提取第一个 H1 标题 */\nfunction extractH1(content: string): string {\n const tree = parseMdxTree(content)\n let title = ''\n visit(tree, 'heading', (node) => {\n if (!title && node.depth === 1) {\n title = toString(node)\n }\n })\n return title\n}\n\n/** 从 MDX/Markdown 内容中提取 H2/H3 章节 */\nfunction extractMdxSections(content: string): ContentSection[] {\n const sections: ContentSection[] = []\n const slugger = new GithubSlugger()\n const tree = parseMdxTree(content)\n visit(tree, 'heading', (node) => {\n if (node.depth !== 2 && node.depth !== 3) return\n const title = toString(node)\n sections.push({ id: slugger.slug(title), title, level: node.depth })\n })\n return sections\n}\n\nfunction navigationSections(sections: ContentSection[]): NavigationSection[] {\n return sections.map(section => ({ id: section.id, title: section.title, level: section.level, badge: section.badge, tags: section.tags }))\n}\n\nexport function normalizePath(path: string): string {\n const clean = '/' + path.replace(/^\\/+|\\/+$/g, '')\n return clean === '/' ? '/' : clean.replace(/\\/+/g, '/')\n}\n\nfunction pathSegmentFromOpenAPITag(tag: string): string {\n return tag\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '') || 'tag'\n}\n\nfunction openAPITagsPathSegment(tags: string[]): string {\n return tags.map(pathSegmentFromOpenAPITag).join('-')\n}\n\nexport function basePathFromRef(ref: string): string {\n const withoutExtension = ref.replace(/\\.mdx?$/, '').replace(/\\.openapi\\.(json|yaml|yml)$/, '')\n return normalizePath(withoutExtension === 'index' ? '/' : withoutExtension.replace(/\\/index$/, ''))\n}\n\nexport function openAPIPagePathFromRef(ref: string, tagFilter?: string[], explicitPath?: string): string {\n if (explicitPath) return normalizePath(explicitPath)\n const basePath = basePathFromRef(ref)\n if (!tagFilter?.length) return basePath\n return normalizePath(`${basePath}/${openAPITagsPathSegment(tagFilter)}`)\n}\n\nexport function routePathFromRef(ref: string, explicitPath?: string): string {\n return explicitPath ? normalizePath(explicitPath) : basePathFromRef(ref)\n}\n\nexport function localizedRoutePath(basePath: string, locale: string, _i18n: ResolvedClarifyLocalesConfig): string {\n const normalizedBasePath = normalizePath(basePath)\n const prefix = normalizePath(locale)\n return normalizedBasePath === '/' ? prefix : normalizePath(`${prefix}${normalizedBasePath}`)\n}\n\nfunction resolveLocalizedText(text: ClarifyLocalizedText | undefined, locale: string, fallbackLocale?: string): string | undefined {\n if (typeof text === 'string') return text\n if (text === undefined) return undefined\n return text[locale] ?? (fallbackLocale ? text[fallbackLocale] : undefined) ?? Object.values(text)[0]\n}\n\nexport async function findContentRoutes(dir: string, base: string = dir, options: FindContentRoutesOptions = {}): Promise<MarkdownContentRoute[]> {\n const routes: MarkdownContentRoute[] = []\n // Skip directories that do not exist instead of throwing; `stat` rejects for\n // missing paths, so treat that as an empty result.\n let dirStat\n try {\n dirStat = await stat(dir)\n } catch {\n return routes\n }\n if (!dirStat.isDirectory()) return routes\n\n const entries = await readdir(dir, { withFileTypes: true })\n for (const entry of entries) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n routes.push(...await findContentRoutes(fullPath, base, options))\n } else if (entry.isFile() && /\\.mdx?$/.test(entry.name)) {\n const relativePath = relative(base, fullPath)\n const pathParts = relativePath.replace(/\\.mdx?$/, '').split('/')\n const path = '/' + pathParts.map(p => p === 'index' ? '' : p).filter(Boolean).join('/')\n const cleanPath = path.replace(/\\/+/g, '/').replace(/\\/$/, '') || '/'\n\n const source = await readFile(fullPath, 'utf-8')\n const { frontmatter, content } = await (options.contentProcessor ?? createContentProcessor()).processMdx(source, fullPath)\n const page: ClarifyPage = {\n path: cleanPath,\n filePath: fullPath,\n frontmatter,\n content,\n }\n const diagnostic = await compileRouteDiagnostic(page.content, fullPath, base)\n\n let title = typeof page.frontmatter.title === 'string' ? page.frontmatter.title : ''\n if (!title) {\n const lastPart = pathParts[pathParts.length - 1] ?? ''\n const stem = lastPart === 'index'\n ? (pathParts.length >= 2 ? pathParts[pathParts.length - 2]! : extractH1(page.content))\n : lastPart\n title = kebabToTitle(stem) || 'Untitled'\n }\n\n routes.push({\n kind: entry.name.toLowerCase().endsWith('.mdx') ? 'markdown+jsx' : 'markdown',\n path: cleanPath,\n basePath: cleanPath,\n meta: {\n title,\n description: typeof page.frontmatter.description === 'string' ? page.frontmatter.description : undefined,\n keywords: frontmatterKeywords(page.frontmatter),\n sections: extractMdxSections(page.content),\n },\n module: {\n pageVirtualModuleId: pageVirtualModuleId(relativePath.replace(/\\.mdx?$/, '')),\n contentVirtualModuleId: contentVirtualModuleId(fullPath, base),\n },\n source: {\n filePath: fullPath,\n frontmatter: page.frontmatter,\n content: page.content,\n },\n diagnostic,\n })\n }\n }\n return routes\n}\n\nfunction pageVirtualModuleIdForLocalizedRoute(contentRoot: string, filePath: string): string {\n return pageVirtualModuleIdFromRef(relative(contentRoot, filePath))\n}\n\nfunction frontmatterKeywords(frontmatter: Record<string, unknown>): string[] | undefined {\n const value = frontmatter.keywords ?? frontmatter.keyword ?? frontmatter.tags\n const keywords = Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string')\n : typeof value === 'string'\n ? value.split(',').map(keyword => keyword.trim()).filter(Boolean)\n : []\n\n return keywords.length > 0 ? keywords : undefined\n}\n\nfunction withPageIdentity<T extends ContentRoute>(route: T, path: string): T {\n return {\n ...route,\n path,\n module: { ...route.module, pageVirtualModuleId: pageVirtualModuleId(path) },\n }\n}\n\nexport function withAlternates<T extends ContentRoute>(route: T, routes: ContentRoute[], locales: ResolvedClarifyLocalesConfig): T {\n const basePath = route.basePath ?? route.path\n // 排除裸路径别名,避免覆盖带 locale 前缀的路径\n const routeByLocaleAndBase = new Map(\n routes\n .filter(r => !r.locale || r.path === `/${r.locale}` || r.path.startsWith(`/${r.locale}/`))\n .map(r => [`${r.locale ?? ''}:${r.basePath ?? r.path}`, r]),\n )\n const alternates = Object.fromEntries(\n locales.locales.flatMap((locale) => {\n const alternate = routeByLocaleAndBase.get(`${locale.code}:${basePath}`)\n return alternate ? [[locale.code, alternate.path]] : []\n })\n )\n return { ...route, alternates }\n}\n\n/**\n * 为默认语言的 locale-prefixed 路由生成无前缀的\"裸路径别名\",方便不带语言\n * 前缀的 URL 也能访问。标记 `isBareAlias` 以便搜索索引生成时过滤重复索引。\n */\nfunction generateBareAliases(routes: MarkdownContentRoute[], locales: ResolvedClarifyLocalesConfig): MarkdownContentRoute[] {\n const bareRoutes: MarkdownContentRoute[] = []\n const seenBare = new Set(routes.map(r => r.path))\n for (const route of routes) {\n if (route.locale !== locales.default) continue\n const bp = route.basePath ?? route.path\n if (bp === route.path || seenBare.has(bp)) continue\n seenBare.add(bp)\n bareRoutes.push({ ...withPageIdentity(route, bp), isBareAlias: true })\n }\n return bareRoutes\n}\n\nexport async function findLocalizedContentRoutes(contentRoot: string, locales?: ResolvedClarifyLocalesConfig, options: FindContentRoutesOptions = {}): Promise<MarkdownContentRoute[]> {\n if (!locales) return findContentRoutes(contentRoot, contentRoot, options)\n\n const localizedRoutes: MarkdownContentRoute[] = []\n for (const locale of locales.locales) {\n const localeRoot = join(contentRoot, locale.code)\n const discovered = await findContentRoutes(localeRoot, localeRoot, options)\n for (const route of discovered) {\n const basePath = route.basePath ?? route.path\n localizedRoutes.push({\n ...route,\n path: localizedRoutePath(basePath, locale.code, locales),\n basePath,\n locale: locale.code,\n module: {\n ...route.module,\n pageVirtualModuleId: pageVirtualModuleIdForLocalizedRoute(contentRoot, route.source.filePath),\n contentVirtualModuleId: contentVirtualModuleId(route.source.filePath, contentRoot),\n },\n })\n }\n }\n\n if (locales.missing === 'fallback') {\n const routeByLocaleAndBase = new Map(localizedRoutes.map(route => [`${route.locale ?? ''}:${route.basePath ?? route.path}`, route]))\n const defaultRoutes = localizedRoutes.filter(route => route.locale === locales.default)\n for (const sourceRoute of defaultRoutes) {\n const basePath = sourceRoute.basePath ?? sourceRoute.path\n for (const locale of locales.locales) {\n const key = `${locale.code}:${basePath}`\n if (routeByLocaleAndBase.has(key)) continue\n const path = localizedRoutePath(basePath, locale.code, locales)\n localizedRoutes.push({\n ...withPageIdentity(sourceRoute, path),\n locale: locale.code,\n isFallback: true,\n })\n }\n }\n }\n\n const routesWithAlternates = localizedRoutes.map(route => withAlternates(route, localizedRoutes, locales))\n\n return [...routesWithAlternates, ...generateBareAliases(routesWithAlternates, locales)]\n}\n\nexport function buildNavigation(routes: ContentRoute[]): ClarifyNavigationNode[] {\n const root: ClarifyNavigationNode[] = []\n\n for (const route of routes) {\n if (route.path === '/' || (route.basePath ?? route.path) === '/404') continue // 首页和 404 不放入侧边栏\n\n const parts = route.path.replace(/^\\//, '').split('/')\n let current = root\n\n for (let i = 0; i < parts.length; i++) {\n const pathSoFar = '/' + parts.slice(0, i + 1).join('/')\n let node = current.find(n => n.path === pathSoFar)\n if (!node) {\n node = { path: pathSoFar, title: i === parts.length - 1 ? route.meta.title : kebabToTitle(parts[i]), children: [] }\n current.push(node)\n }\n if (i === parts.length - 1 && route.meta.sections) {\n node.sections = navigationSections(route.meta.sections)\n }\n if (i < parts.length - 1) {\n node.children = node.children ?? []\n current = node.children\n }\n }\n }\n\n return root\n}\n\nexport function routeIntentFromPagesItem(\n item: ClarifyPagesItem\n): ClarifyRouteIntent {\n if (typeof item === 'string') return { kind: 'page', ref: item }\n if ('group' in item) throw new Error('Navigation groups do not resolve to route intents')\n if ('openapi' in item) return { kind: 'openapi', ref: item.openapi, tagFilter: item.filter?.tags, path: item.path, title: item.title, icon: item.icon }\n return { kind: 'page', ref: item.page, path: item.path, redirect: item.redirect, title: item.title, icon: item.icon }\n}\n\nfunction firstNavigationPath(nodes: ClarifyNavigationNode[]): string {\n for (const node of nodes) {\n if (node.path) return node.path\n const childPath = node.children ? firstNavigationPath(node.children) : undefined\n if (childPath) return childPath\n }\n return '/'\n}\n\nfunction collectExplicitPagePathIntents(tabs?: ClarifyTabsConfig): Array<ClarifyPageRouteIntent & { path: string }> {\n const intents: Array<ClarifyPageRouteIntent & { path: string }> = []\n\n const collectItems = (items: ClarifyPagesItem[]) => {\n for (const item of items) {\n if (typeof item !== 'string' && 'group' in item) {\n collectItems(item.pages)\n } else if (typeof item !== 'string' && 'page' in item && item.path) {\n const intent = routeIntentFromPagesItem(item)\n if (intent.kind === 'page' && intent.path) intents.push({ ...intent, path: intent.path })\n }\n }\n }\n\n for (const tab of tabs ?? []) {\n if (!tab.pages || tab.pages === 'FileTree') continue\n for (const group of tab.pages) {\n collectItems(group.pages)\n }\n }\n\n return intents\n}\n\nexport function applyConfiguredPageRoutePaths(routes: ContentRoute[], tabs?: ClarifyTabsConfig, locales?: ResolvedClarifyLocalesConfig): ContentRoute[] {\n const pageIntents = collectExplicitPagePathIntents(tabs)\n if (!pageIntents.length) return routes\n\n const additions: MarkdownContentRoute[] = []\n const existingKeys = new Set(routes.map(route => `${route.locale ?? ''}:${route.basePath ?? route.path}`))\n\n for (const intent of pageIntents) {\n const sourceBasePath = routePathFromRef(intent.ref)\n const targetBasePath = routePathFromRef(intent.ref, intent.path)\n if (sourceBasePath === targetBasePath) continue\n\n for (const route of routes) {\n if (route.kind === 'openapi' || (route.basePath ?? route.path) !== sourceBasePath) continue\n\n const key = `${route.locale ?? ''}:${targetBasePath}`\n if (existingKeys.has(key)) continue\n existingKeys.add(key)\n\n const path = route.locale && locales ? localizedRoutePath(targetBasePath, route.locale, locales) : targetBasePath\n additions.push({\n ...withPageIdentity(route, path),\n basePath: targetBasePath,\n })\n }\n }\n\n const nextRoutes = [...routes, ...additions]\n const routesWithAlternates = locales ? nextRoutes.map(route => withAlternates(route, nextRoutes, locales)) : nextRoutes\n\n if (!locales) return routesWithAlternates\n\n const markdownRoutes = routesWithAlternates.filter((route): route is MarkdownContentRoute => route.kind !== 'openapi')\n return [...routesWithAlternates, ...generateBareAliases(markdownRoutes, locales)]\n}\n\nfunction buildNavigationFromPagesConfig(routes: ContentRoute[], config?: ClarifyPagesConfig): ClarifyNavigationNode[] {\n if (!config || config === 'FileTree') return buildNavigation(routes)\n return buildNavigationFromConfig(routes, config)\n}\n\nexport function buildNavigationFromTabsConfig(routes: ContentRoute[], tabs: ClarifyTabsConfig): TabbedNavigation {\n return {\n kind: 'tabbed',\n tabs: tabs.map(tab => {\n const children = buildNavigationFromPagesConfig(routes, tab.pages)\n return {\n type: 'tab',\n path: firstNavigationPath(children),\n title: resolveLocalizedText(tab.tab, '', '') ?? '',\n icon: tab.icon,\n children,\n }\n }),\n }\n}\n\nexport function buildNavigationFromConfig(routes: ContentRoute[], config: ClarifyPagesGroup[]): ClarifyNavigationNode[] {\n const routeMap = new Map(routes.map(r => [r.path, r]))\n\n const buildItem = (item: ClarifyPagesItem): ClarifyNavigationNode => {\n if (typeof item !== 'string' && 'group' in item) {\n const children = item.pages.map(buildItem)\n return {\n path: firstNavigationPath(children),\n title: resolveLocalizedText(item.group, '', '') ?? '',\n icon: item.icon,\n children,\n }\n }\n\n const intent = routeIntentFromPagesItem(item)\n\n if (intent.kind === 'openapi') {\n const path = openAPIPagePathFromRef(intent.ref, intent.tagFilter, intent.path)\n const route = routeMap.get(path)\n return {\n path,\n title: resolveLocalizedText(intent.title, '', '') ?? route?.meta.title ?? kebabToTitle(path.split('/').pop() ?? intent.ref),\n icon: intent.icon,\n sections: route?.meta.sections ? navigationSections(route.meta.sections) : undefined,\n }\n }\n\n const path = routePathFromRef(intent.ref, intent.path)\n const route = routeMap.get(path)\n return {\n path: intent.redirect ? normalizePath(intent.redirect) : path,\n title: resolveLocalizedText(intent.title, '', '') ?? route?.meta.title ?? kebabToTitle(path.split('/').pop() ?? intent.ref),\n icon: intent.icon,\n sections: route?.meta.sections ? navigationSections(route.meta.sections) : undefined,\n }\n }\n\n return config.map(group => {\n const children = group.pages.map(buildItem)\n\n return {\n path: children[0]?.path ?? '/',\n title: resolveLocalizedText(group.group, '', '') ?? '',\n icon: group.icon,\n children,\n }\n })\n}\n\nfunction localizeNavigationPaths(nodes: ClarifyNavigationNode[], locale: string, locales: ResolvedClarifyLocalesConfig): ClarifyNavigationNode[] {\n return nodes.map(node => ({\n ...node,\n path: localizedRoutePath(node.path, locale, locales),\n children: node.children ? localizeNavigationPaths(node.children, locale, locales) : undefined,\n }))\n}\n\nexport function buildLocalizedNavigation(routes: ContentRoute[], config: ClarifyPagesConfig | undefined, localesConfig?: ResolvedClarifyLocalesConfig): LocalizedNavigation | undefined {\n if (!localesConfig) return undefined\n\n const locales: LocalizedNavigation['locales'] = {}\n for (const locale of localesConfig.locales) {\n const localeRoutes = routes.filter(route => route.locale === locale.code)\n locales[locale.code] = buildLocalizedNavigationForLocale(localeRoutes, config, locale.code, localesConfig)\n }\n\n return { kind: 'localized', locales }\n}\n\nfunction buildLocalizedNavigationForLocale(routes: ContentRoute[], config: ClarifyPagesConfig | undefined, locale: string, locales: ResolvedClarifyLocalesConfig): ClarifyNavigationNode[] {\n if (!config || config === 'FileTree') {\n const baseNavigation = buildNavigation(routes.map(route => ({ ...route, path: route.basePath ?? route.path })))\n return localizeNavigationPaths(baseNavigation, locale, locales)\n }\n\n const routeMap = new Map(routes.map(route => [route.basePath ?? route.path, route]))\n const buildItem = (item: ClarifyPagesItem): ClarifyNavigationNode => {\n if (typeof item !== 'string' && 'group' in item) {\n const children = item.pages.map(buildItem)\n return {\n path: firstNavigationPath(children),\n title: resolveLocalizedText(item.group, locale, locales.default) ?? '',\n icon: item.icon,\n children,\n }\n }\n\n const intent = routeIntentFromPagesItem(item)\n const basePath = intent.kind === 'openapi'\n ? openAPIPagePathFromRef(intent.ref, intent.tagFilter, intent.path)\n : routePathFromRef(intent.ref, intent.path)\n const route = routeMap.get(basePath)\n const path = route?.path ?? localizedRoutePath(basePath, locale, locales)\n const redirectPath = intent.kind === 'page' && intent.redirect ? localizedRoutePath(routePathFromRef(intent.redirect), locale, locales) : undefined\n\n return {\n path: redirectPath ?? path,\n title: resolveLocalizedText(intent.title, locale, locales.default) ?? route?.meta.title ?? kebabToTitle(basePath.split('/').pop() ?? intent.ref),\n icon: intent.icon,\n sections: route?.meta.sections ? navigationSections(route.meta.sections) : undefined,\n }\n }\n\n return config.map(group => {\n const children = group.pages.map(buildItem)\n\n return {\n path: children[0]?.path ?? localizedRoutePath('/', locale, locales),\n title: resolveLocalizedText(group.group, locale, locales.default) ?? '',\n icon: group.icon,\n children,\n }\n })\n}\n\nexport function buildLocalizedNavigationFromTabsConfig(routes: ContentRoute[], tabs: ClarifyTabsConfig, localesConfig?: ResolvedClarifyLocalesConfig): LocalizedTabbedNavigation | undefined {\n if (!localesConfig) return undefined\n\n const locales: LocalizedTabbedNavigation['locales'] = {}\n for (const locale of localesConfig.locales) {\n const localeRoutes = routes.filter(route => route.locale === locale.code)\n locales[locale.code] = {\n tabs: tabs.map(tab => {\n const children = buildLocalizedNavigationForLocale(localeRoutes, tab.pages, locale.code, localesConfig)\n return {\n type: 'tab',\n path: firstNavigationPath(children),\n title: resolveLocalizedText(tab.tab, locale.code, localesConfig.default) ?? '',\n icon: tab.icon,\n children,\n }\n }),\n }\n }\n\n return { kind: 'localized-tabbed', locales }\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\nimport { relative } from 'node:path'\n\nimport type { ClarifyProjectContext, ContentRoute } from '../../types.js'\nimport { basePathFromRef, localizedRoutePath, normalizePath } from '../routes/routes.js'\n\n/**\n * Dev-only HTTP endpoint that exposes the in-memory route manifest so external\n * tools (e.g. the VS Code extension) can resolve a content file path to its\n * preview URL.\n *\n * Mounted at `POST /dev/query-preview-route`:\n * - Empty body → returns the full route list (minimal fields).\n * - `{ \"file\": \"<absPath>\" }` → returns the single matching route. When the\n * project uses i18n, the route whose locale matches the file's directory is\n * preferred; otherwise the default-locale route is returned. If the file is\n * not a registered route, a best-effort preview path is derived from the\n * file path relative to the content root.\n *\n * Uses POST + JSON body (instead of GET + query string) because file paths may\n * contain characters that are awkward to encode in a URL query parameter.\n */\nexport const CLARIFY_DEV_ROUTE_ENDPOINT = '/dev/query-preview-route'\n\nexport type DevRouteEntry = {\n path: string\n filePath: string\n locale?: string\n basePath?: string\n kind: string\n title: string\n /** Whether the route was derived from the file path rather than matched in the route manifest. */\n inferred?: boolean\n}\n\nexport type DevRouteResponse = DevRouteEntry | DevRouteEntry[] | null\n\n/** Serialize a ContentRoute into the minimal shape exposed to tooling. */\nexport function toDevRouteEntry(route: ContentRoute): DevRouteEntry {\n return {\n path: route.path,\n filePath: route.source.filePath,\n locale: route.locale,\n basePath: route.basePath,\n kind: route.kind,\n title: route.meta.title,\n }\n}\n\n/**\n * Resolve a single file path to its preview route.\n *\n * Selection order:\n * 1. Routes whose `filePath` exactly matches.\n * 2. Among matches, prefer the one whose `locale` matches the file's locale\n * directory (e.g. `source/zh-CN/x.mdx` → locale `zh-CN`).\n * 3. If no locale match, fall back to the default locale (if i18n is enabled)\n * or the first match.\n */\nexport function resolveRouteForFile(filePath: string, routes: ContentRoute[], defaultLocale?: string): ContentRoute | undefined {\n const matches = routes.filter(r => r.source.filePath === filePath)\n if (matches.length === 0) return undefined\n if (matches.length === 1) return matches[0]\n\n const fileLocale = inferLocaleFromPath(filePath)\n if (fileLocale) {\n const localeMatch = matches.find(r => r.locale === fileLocale)\n if (localeMatch) return localeMatch\n }\n\n if (defaultLocale) {\n const defaultMatch = matches.find(r => r.locale === defaultLocale)\n if (defaultMatch) return defaultMatch\n }\n\n return matches[0]\n}\n\n/**\n * Derive a best-effort preview route for a file that is not in the route\n * manifest (e.g. a draft or newly created file). The path is computed from the\n * file's location relative to the content root, following the same convention\n * as route discovery (`source/{locale}/path/index.mdx` → `/{locale}/path`).\n *\n * Returns null when the file is outside the content root or is not a\n * recognized content file type.\n */\nexport function inferRouteForFile(filePath: string, contentRoot: string, defaultLocale?: string): DevRouteEntry | null {\n const ref = relative(contentRoot, filePath)\n if (!ref || ref.startsWith('..')) return null\n\n const isMdx = /\\.mdx?$/.test(filePath)\n const isOpenApi = /\\.openapi\\.(json|ya?ml)$/.test(filePath)\n if (!isMdx && !isOpenApi) return null\n\n const segments = ref.split('/')\n const fileLocale = inferLocaleFromPath(filePath)\n const localeSegmentIndex = fileLocale ? segments.indexOf(fileLocale) : -1\n const refWithoutLocale = localeSegmentIndex >= 0 ? segments.slice(localeSegmentIndex + 1).join('/') : ref\n\n const basePath = basePathFromRef(refWithoutLocale)\n const path = fileLocale && defaultLocale\n ? localizedRoutePath(basePath, fileLocale, { default: defaultLocale, missing: 'fallback', locales: [] })\n : basePath\n\n const title = segments[segments.length - 1]?.replace(/\\.(mdx?|openapi\\.(json|ya?ml))$/, '') || 'Untitled'\n\n return {\n path: normalizePath(path),\n filePath,\n locale: fileLocale,\n basePath: normalizePath(basePath),\n kind: isMdx ? 'markdown+jsx' : 'openapi',\n title,\n inferred: true,\n }\n}\n\n/** Best-effort locale inference from a file path segment like `.../zh-CN/x.mdx`. */\nfunction inferLocaleFromPath(filePath: string): string | undefined {\n const segments = filePath.split('/')\n for (const segment of segments) {\n if (/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-[A-Z]{2})?$/.test(segment)) {\n return segment\n }\n }\n return undefined\n}\n\n/** Read and parse the JSON body of an IncomingMessage. */\nfunction readJsonBody(req: IncomingMessage): Promise<unknown> {\n return new Promise((resolveBody, reject) => {\n const chunks: Buffer[] = []\n req.on('data', chunk => chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)))\n req.on('error', reject)\n req.on('end', () => {\n const raw = Buffer.concat(chunks).toString('utf-8').trim()\n if (!raw) return resolveBody({})\n try {\n resolveBody(JSON.parse(raw))\n } catch (err) {\n reject(err)\n }\n })\n })\n}\n\n/**\n * Handle a request to the dev route endpoint. Pure function — does not touch\n * the network directly, only reads the request body and writes to `res`.\n */\nexport async function handleDevRouteRequest(req: IncomingMessage, res: ServerResponse, routes: ContentRoute[], context: ClarifyProjectContext): Promise<void> {\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n\n let body: unknown\n try {\n body = await readJsonBody(req)\n } catch {\n res.statusCode = 400\n res.end(JSON.stringify({ error: 'Invalid JSON body' }))\n return\n }\n\n const file = typeof body === 'object' && body !== null ? (body as { file?: unknown }).file : undefined\n\n if (typeof file === 'string' && file.length > 0) {\n const route = resolveRouteForFile(file, routes, context.projectConfig.locales?.default)\n if (route) {\n res.end(JSON.stringify(toDevRouteEntry(route)))\n return\n }\n const inferred = inferRouteForFile(file, context.contentRoot, context.projectConfig.locales?.default)\n res.end(JSON.stringify(inferred))\n return\n }\n\n res.end(JSON.stringify(routes.map(toDevRouteEntry)))\n}\n","import { themePresets } from '@clarify-labs/renderer'\n\nimport type { ClarifyThemeConfig, ResolvedClarifyThemeConfig } from '../types.js'\n\nexport { themePresets }\n\nexport function resolveThemeConfig(theme: ClarifyThemeConfig = {}): ResolvedClarifyThemeConfig {\n const preset = theme.preset ?? 'default'\n const presetTheme = themePresets[preset] as ResolvedClarifyThemeConfig\n\n return {\n preset,\n tokens: {\n colors: {\n ...presetTheme.tokens.colors,\n ...theme.tokens?.colors,\n },\n radius: {\n ...presetTheme.tokens.radius,\n ...theme.tokens?.radius,\n },\n },\n layout: {\n ...presetTheme.layout,\n ...theme.layout,\n },\n }\n}\n","import { z } from 'zod'\n\nimport type { ClarifyVariableValue, ClarifyProjectConfig } from '../../types.js'\n\nconst clarifyLogoConfigSchema = z.union([\n z.string(),\n z.object({\n light: z.string().optional(),\n dark: z.string().optional(),\n }).strict(),\n])\n\nconst clarifyFaviconConfigSchema = z.union([\n z.string(),\n z.object({\n light: z.string().optional(),\n dark: z.string().optional(),\n }).strict(),\n])\n\nconst clarifyLocalizedTextSchema = z.union([\n z.string(),\n z.record(z.string(), z.string()),\n])\n\nconst clarifyLocaleConfigSchema = z.object({\n code: z.string(),\n label: z.string(),\n dir: z.union([z.literal('ltr'), z.literal('rtl')]).optional(),\n}).strict()\n\nconst clarifyLocalesConfigSchema = z.object({\n default: z.string().optional(),\n missing: z.union([z.literal('fallback'), z.literal('404'), z.literal('hide')]).optional(),\n locales: z.array(clarifyLocaleConfigSchema).min(1),\n}).strict().superRefine((config, ctx) => {\n const localeCodes = new Set<string>()\n for (const [index, locale] of config.locales.entries()) {\n if (localeCodes.has(locale.code)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: `Duplicate locale code \"${locale.code}\"`,\n path: ['locales', index, 'code'],\n })\n }\n localeCodes.add(locale.code)\n }\n\n if (config.default && !localeCodes.has(config.default)) {\n ctx.addIssue({\n code: z.ZodIssueCode.custom,\n message: 'default must be one of locales.locales',\n path: ['default'],\n })\n }\n})\n\nconst clarifyNavbarLinkSchema = z.object({\n label: clarifyLocalizedTextSchema,\n href: z.string(),\n external: z.boolean().optional(),\n}).strict()\n\nconst clarifyBannerConfigOptionsSchema = z.object({\n content: clarifyLocalizedTextSchema,\n dismissible: z.boolean().optional(),\n link: clarifyNavbarLinkSchema.optional(),\n}).strict()\n\nconst clarifyFooterConfigSchema = z.object({\n links: z.array(clarifyNavbarLinkSchema).optional(),\n socials: z.record(z.string(), z.string()).optional(),\n copyright: clarifyLocalizedTextSchema.optional(),\n}).strict()\n\nconst clarifyVariableValueSchema: z.ZodType<ClarifyVariableValue> = z.lazy(() => z.union([\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), clarifyVariableValueSchema),\n]))\n\nconst clarifyVariablesConfigSchema = z.record(z.string(), clarifyVariableValueSchema)\n\nconst clarifyRepositoryConfigSchema = z.object({\n url: z.string().optional(),\n branch: z.string().optional(),\n directory: z.string().optional(),\n}).strict()\n\nconst clarifyPagesItemSchema: z.ZodType<\n import('../../types.js').ClarifyPagesItem,\n import('../../types.js').ClarifyPagesItem\n> = z.lazy(() => z.union([\n z.string(),\n clarifyPagesGroupSchema,\n z.object({\n page: z.string(),\n path: z.string().optional(),\n title: clarifyLocalizedTextSchema.optional(),\n icon: z.string().optional(),\n redirect: z.string().optional(),\n }).strict(),\n z.object({\n openapi: z.string(),\n path: z.string().optional(),\n icon: z.string().optional(),\n title: clarifyLocalizedTextSchema.optional(),\n filter: z.object({\n tags: z.array(z.string()).optional(),\n }).strict().optional(),\n }).strict(),\n]))\n\nconst clarifyPagesGroupSchema: z.ZodType<\n import('../../types.js').ClarifyPagesGroup,\n import('../../types.js').ClarifyPagesGroup\n> = z.lazy(() => z.object({\n group: clarifyLocalizedTextSchema,\n icon: z.string().optional(),\n pages: z.array(clarifyPagesItemSchema),\n}).strict())\n\nconst clarifyPagesConfigSchema = z.union([\n z.array(clarifyPagesGroupSchema),\n z.literal('FileTree'),\n])\n\nconst clarifyTabItemSchema = z.object({\n tab: clarifyLocalizedTextSchema,\n icon: z.string().optional(),\n pages: clarifyPagesConfigSchema.optional(),\n}).strict()\n\nconst clarifyTabsConfigSchema = z.array(clarifyTabItemSchema)\n\nconst clarifyThemePresetSchema = z.enum(['default', 'base'])\n\nconst clarifyThemeModeColorValueSchema = z.object({\n light: z.string().optional(),\n dark: z.string().optional(),\n}).strict()\n\nconst clarifyThemeColorValueSchema = z.union([z.string(), clarifyThemeModeColorValueSchema])\n\nconst clarifyThemeColorTokensConfigSchema = z.object({\n primary: clarifyThemeColorValueSchema.optional(),\n accent: clarifyThemeColorValueSchema.optional(),\n background: clarifyThemeColorValueSchema.optional(),\n foreground: clarifyThemeColorValueSchema.optional(),\n surface: clarifyThemeColorValueSchema.optional(),\n muted: clarifyThemeColorValueSchema.optional(),\n border: clarifyThemeColorValueSchema.optional(),\n codeBackground: clarifyThemeColorValueSchema.optional(),\n}).strict()\n\nconst clarifyThemeRadiusTokensConfigSchema = z.object({\n sm: z.string().optional(),\n md: z.string().optional(),\n lg: z.string().optional(),\n xl: z.string().optional(),\n}).strict()\n\nconst clarifyThemeTokensConfigSchema = z.object({\n colors: clarifyThemeColorTokensConfigSchema.optional(),\n radius: clarifyThemeRadiusTokensConfigSchema.optional(),\n}).strict()\n\nconst clarifyThemeLayoutConfigSchema = z.object({\n maxWidth: z.string().optional(),\n}).strict()\n\nconst clarifyThemeConfigSchema = z.object({\n preset: clarifyThemePresetSchema.optional(),\n tokens: clarifyThemeTokensConfigSchema.optional(),\n layout: clarifyThemeLayoutConfigSchema.optional(),\n}).strict()\n\nfunction featureSchema<Schema extends z.ZodRawShape>(shape: Schema, defaults: Record<string, unknown>, enabledByDefault = true) {\n const resolvedDefaults = { enabled: enabledByDefault, ...defaults }\n const objectSchema = z.object({ enabled: z.boolean().default(enabledByDefault), ...shape }).strict().default(resolvedDefaults as never)\n return z.union([\n z.boolean(),\n objectSchema,\n ]).default(resolvedDefaults as never).transform((value) => typeof value === 'boolean'\n ? { enabled: value, ...defaults }\n : value)\n}\n\nexport const clarifyFeaturesConfigSchema = z.object({\n search: featureSchema({ mcp: z.boolean().default(true) }, { mcp: true }),\n repository: featureSchema(clarifyRepositoryConfigSchema.shape, {}),\n themeEditor: featureSchema({}, {}, false),\n openapi: featureSchema({\n playground: z.boolean().default(true),\n }, { playground: true }),\n}).strict()\n\nexport const clarifyProjectConfigSchema = z.object({\n title: z.string().optional(),\n description: z.string().optional(),\n siteUrl: z.string().optional(),\n routePrefix: z.string().default('/'),\n assetPrefix: z.string().optional(),\n logo: clarifyLogoConfigSchema.optional(),\n homeUrl: z.string().optional(),\n favicon: clarifyFaviconConfigSchema.optional(),\n theme: clarifyThemeConfigSchema.optional(),\n navigation: z.object({\n links: z.array(clarifyNavbarLinkSchema).optional(),\n tabs: clarifyTabsConfigSchema.optional(),\n }).strict().optional(),\n banner: clarifyBannerConfigOptionsSchema.optional(),\n footer: clarifyFooterConfigSchema.optional(),\n locales: clarifyLocalesConfigSchema.optional(),\n variables: clarifyVariablesConfigSchema.optional(),\n features: clarifyFeaturesConfigSchema.optional(),\n}).strict() satisfies z.ZodType<ClarifyProjectConfig>\n\nexport type ClarifyProjectConfigInput = z.input<typeof clarifyProjectConfigSchema>\n","import type { ZodError } from 'zod'\n\nimport { resolveThemeConfig } from '../../parsers/theme.js'\nimport type { ClarifyFeaturesConfig, ClarifyLocalesConfig, ClarifyProjectConfig, ResolvedClarifyFeaturesConfig, ResolvedClarifyLocalesConfig, ResolvedProjectConfig } from '../../types.js'\n\nimport { clarifyFeaturesConfigSchema, clarifyProjectConfigSchema } from './config-schema.js'\n\nfunction formatIssuePath(path: PropertyKey[]): string {\n return path.reduce<string>((result, segment) => {\n if (typeof segment === 'number') return `${result}[${segment}]`\n const key = String(segment)\n return result ? `${result}.${key}` : key\n }, '')\n}\n\nfunction formatProjectConfigError(error: ZodError): string {\n const issue = error.issues[0]\n if (!issue) return '[clarify] config is invalid'\n\n const path = formatIssuePath(issue.path)\n if (!path) return `[clarify] config must contain an object: ${issue.message}`\n\n return `[clarify] config field \"${path}\" is invalid: ${issue.message}`\n}\n\nexport function validateProjectConfig(value: unknown): ClarifyProjectConfig {\n const result = clarifyProjectConfigSchema.safeParse(value)\n if (!result.success) {\n throw new Error(formatProjectConfigError(result.error))\n }\n return result.data\n}\n\nfunction resolveLocalesConfig(locales?: ClarifyLocalesConfig): ResolvedClarifyLocalesConfig | undefined {\n if (!locales) return undefined\n\n const firstLocale = locales.locales[0]?.code\n const defaultLocale = locales.default ?? firstLocale\n if (!defaultLocale) return undefined\n\n return {\n default: defaultLocale,\n missing: locales.missing ?? 'fallback',\n locales: locales.locales,\n }\n}\n\nexport function resolveFeaturesConfig(features: ClarifyFeaturesConfig = {}): ResolvedClarifyFeaturesConfig {\n return clarifyFeaturesConfigSchema.parse(features) as unknown as ResolvedClarifyFeaturesConfig\n}\n\nfunction resolveRoutePrefix(routePrefix?: string): string {\n const trimmed = routePrefix?.trim()\n if (!trimmed || trimmed === '/') return '/'\n\n return `/${trimmed.replace(/^\\/+|\\/+$/g, '')}/`\n}\n\nfunction resolveAssetPrefix(assetPrefix: string | undefined, routePrefix: string): string {\n const trimmed = assetPrefix?.trim()\n if (trimmed === undefined) return routePrefix\n if (trimmed === './' || trimmed === '') return trimmed || '/'\n if (!trimmed || trimmed === '/') return '/'\n if (/^[a-z][a-z\\d+.-]*:\\/\\//i.test(trimmed)) return trimmed.endsWith('/') ? trimmed : `${trimmed}/`\n if (trimmed.startsWith('./') || trimmed.startsWith('../')) return trimmed.endsWith('/') ? trimmed : `${trimmed}/`\n\n return `/${trimmed.replace(/^\\/+|\\/+$/g, '')}/`\n}\n\nexport function resolveProjectConfig(config: ClarifyProjectConfig = {}): ResolvedProjectConfig {\n const routePrefix = resolveRoutePrefix(config.routePrefix)\n\n return {\n title: config.title ?? 'Clarify Docs',\n description: config.description ?? '',\n siteUrl: config.siteUrl,\n routePrefix,\n assetPrefix: resolveAssetPrefix(config.assetPrefix, routePrefix),\n logo: config.logo,\n homeUrl: config.homeUrl,\n favicon: config.favicon,\n theme: resolveThemeConfig(config.theme),\n navigation: config.navigation,\n banner: config.banner,\n footer: config.footer,\n locales: resolveLocalesConfig(config.locales),\n variables: config.variables ?? {},\n features: resolveFeaturesConfig(config.features),\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { loadConfigFromFile } from 'vite'\nimport type { ConfigEnv } from 'vite'\n\nimport type { ClarifyProjectConfig, ClarifyPlugin } from '../../types.js'\n\nimport { validateProjectConfig } from './config.js'\n\nexport type ClarifyConfig = ClarifyProjectConfig & {\n plugins?: ClarifyPlugin[]\n}\n\nexport function defineConfig(config: ClarifyConfig): ClarifyConfig {\n return validateClarifyConfig(config)\n}\n\n/**\n * Config filenames Clarify CLI looks for at the project root, in resolution\n * order. Exported so other modules (e.g. the dev `project-info` endpoint) can\n * surface the same list to tooling without duplicating it.\n */\nexport const CONFIG_FILENAMES = [\n 'clarify.ts',\n 'clarify.js',\n 'clarify.json',\n] as const\n\nexport function findClarifyConfigFile(root: string): string | undefined {\n for (const filename of CONFIG_FILENAMES) {\n const filePath = resolve(root, filename)\n if (existsSync(filePath)) return filePath\n }\n return undefined\n}\n\nfunction assertConfigObject(config: unknown, configFile: string): Record<string, unknown> {\n if (!config || typeof config !== 'object' || Array.isArray(config)) {\n throw new Error(`[clarify] ${configFile} must export a configuration object`)\n }\n return config as Record<string, unknown>\n}\n\nfunction loadJsonConfig(configFile: string): ClarifyConfig {\n const config = assertConfigObject(JSON.parse(readFileSync(configFile, 'utf-8')), configFile)\n if ('plugins' in config) {\n throw new Error('[clarify] clarify.json does not support plugins; use clarify.ts or clarify.js')\n }\n return validateClarifyConfig(config)\n}\n\nfunction validateClarifyConfig(config: ClarifyConfig | Record<string, unknown>): ClarifyConfig {\n const { plugins, ...projectConfigInput } = config\n if (plugins !== undefined && !Array.isArray(plugins)) {\n throw new Error('[clarify] config field \"plugins\" is invalid: Expected an array')\n }\n const projectConfig = validateProjectConfig(projectConfigInput)\n return plugins ? { ...projectConfig, plugins } : projectConfig\n}\n\nexport async function loadClarifyConfig(root: string, env: ConfigEnv): Promise<ClarifyConfig> {\n const configFile = findClarifyConfigFile(root)\n if (!configFile) return {}\n\n if (configFile.endsWith('.json')) {\n return loadJsonConfig(configFile)\n }\n\n const loaded = await loadConfigFromFile(env, configFile, root, 'silent')\n const config = assertConfigObject(loaded?.config, configFile)\n return validateClarifyConfig(config)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport type { ClarifyProjectContext } from '../../types.js'\nimport { CONFIG_FILENAMES } from '../config/user-config.js'\n\n/**\n * Dev-only HTTP endpoint that exposes project metadata so external tooling\n * (e.g. the VS Code extension) can discover which files Clarify recognizes\n * without hardcoding conventions that may drift between CLI versions.\n *\n * Mounted at `GET /dev/project-info`. Returns a JSON object describing:\n * - `configFilenames`: config files Clarify looks for at the project root.\n * - `contentFileExtensions`: file extensions treated as content files.\n * - `contentRoot`: the resolved content root directory name (relative to\n * the project root, e.g. `\"source\"`).\n * - `projectRoot`: the absolute project root path.\n * - `locales`: locale information when localization is configured.\n */\nexport const CLARIFY_DEV_PROJECT_INFO_ENDPOINT = '/dev/project-info'\n\n/**\n * File extensions Clarify treats as content files. Kept in sync with the\n * patterns used by route discovery in `parsers/routes.ts` and the OpenAPI\n * page generator. Exposed to tooling so the extension's \"is this a content\n * file?\" check stays accurate without duplicating the regex.\n */\nexport const CONTENT_FILE_EXTENSIONS = [\n '.md',\n '.mdx',\n '.openapi.json',\n '.openapi.yaml',\n '.openapi.yml',\n] as const\n\nexport type ProjectInfoResponse = {\n configFilenames: readonly string[]\n contentFileExtensions: readonly string[]\n contentRoot: string\n projectRoot: string\n locales?: {\n default: string\n locales: string[]\n }\n}\n\n/**\n * Build the project-info response payload from the resolved plugin state.\n */\nexport function buildProjectInfo(context: ClarifyProjectContext): ProjectInfoResponse {\n const { projectRoot, contentRoot, projectConfig } = context\n // `contentRoot` is an absolute path (join(root, rootDirectory)); expose the\n // relative directory name so tooling can reason about file locations\n // without assuming a specific absolute path.\n const contentRootName = contentRoot.startsWith(projectRoot)\n ? contentRoot.slice(projectRoot.length).replace(/^[/\\\\]+/, '')\n : contentRoot\n\n const response: ProjectInfoResponse = {\n configFilenames: CONFIG_FILENAMES,\n contentFileExtensions: CONTENT_FILE_EXTENSIONS,\n contentRoot: contentRootName || 'source',\n projectRoot,\n }\n\n if (projectConfig.locales) {\n response.locales = {\n default: projectConfig.locales.default,\n locales: projectConfig.locales.locales.map(l => l.code),\n }\n }\n\n return response\n}\n\n/**\n * Handle a request to the project-info endpoint. Responds to any method\n * (GET is typical) with the JSON payload — there is no request body to parse.\n */\nexport function handleProjectInfoRequest(_req: IncomingMessage, res: ServerResponse, context: ClarifyProjectContext): void {\n res.setHeader('Content-Type', 'application/json; charset=utf-8')\n res.end(JSON.stringify(buildProjectInfo(context)))\n}\n","import type { UISlotRegistration } from '@clarify-labs/renderer'\n\nimport type { ClarifyPlugin, ContentDiagnostic, ContentRoute, ContentSection, MarkdownContentRoute, NavigationTree, ResolvedBuildOptions, ResolvedProjectConfig } from '../../types.js'\n\n// 新的虚拟模块命名 - 更清晰的职责划分\nconst VIRTUAL_CONFIG = 'virtual:clarify/config'\nexport const VIRTUAL_ROUTES = 'virtual:clarify/routes'\nconst VIRTUAL_SERVER_ROUTES = 'virtual:clarify/routes/server'\nexport const VIRTUAL_OPENAPI = 'virtual:clarify/openapi'\nexport const VIRTUAL_OPENAPI_SERVER = 'virtual:clarify/openapi/server'\nconst VIRTUAL_SLOTS = 'virtual:clarify/slots'\nconst VIRTUAL_SLOT = 'virtual:clarify/slot'\nexport const VIRTUAL_CLIENT_ENTRY = 'virtual:clarify/entry-client'\nconst RESOLVED_CLIENT_ENTRY = '\\0' + VIRTUAL_CLIENT_ENTRY\n\nexport type VirtualModules = Map<string, string>\n\ntype BuildVirtualModulesArgs = {\n generateOptions: ResolvedBuildOptions\n projectConfig: ResolvedProjectConfig\n routes: ContentRoute[]\n version?: string\n plugins?: ClarifyPlugin[]\n navigation: NavigationTree\n themeEditor?: boolean\n}\n\ntype CreateClientEntryModuleOptions = {\n themeEditor?: boolean\n}\n\nexport function resolveVirtualId(id: string): string {\n return '\\0' + id\n}\n\nexport function stripVirtualPrefix(id: string): string {\n return id.startsWith('\\0') ? id.slice(1) : id\n}\n\nexport function virtualContentModuleId(route: MarkdownContentRoute): string {\n return route.module.contentVirtualModuleId\n}\n\n/**\n * Fixed virtual module IDs (excluding the client entry, which has a special\n * resolved form). Used to avoid hardcoding the constant list in every\n * `resolveId` implementation.\n */\nconst FIXED_VIRTUAL_IDS = [\n VIRTUAL_CONFIG,\n VIRTUAL_ROUTES,\n VIRTUAL_SERVER_ROUTES,\n VIRTUAL_OPENAPI,\n VIRTUAL_OPENAPI_SERVER,\n VIRTUAL_SLOTS,\n VIRTUAL_SLOT,\n] as const\n\n/**\n * Shared `resolveId` logic for all Clarify virtual modules. Used by both the\n * Vite core plugin (dev + build) and the SSG virtual plugin so the ID-to-\n * resolved-ID mapping has a single source of truth.\n *\n * Returns the resolved ID (with `\\0` prefix per Vite convention) or `null`\n * if the ID is not a Clarify virtual module.\n */\nexport function resolveVirtualModuleId(id: string, modules: VirtualModules, routes: readonly ContentRoute[]): string | null {\n if (id === VIRTUAL_CLIENT_ENTRY || id === RESOLVED_CLIENT_ENTRY) return RESOLVED_CLIENT_ENTRY\n\n for (const virtualId of FIXED_VIRTUAL_IDS) {\n if (id === virtualId || id === resolveVirtualId(virtualId)) return resolveVirtualId(virtualId)\n }\n\n const moduleId = stripVirtualPrefix(id)\n if (modules.has(moduleId)) return resolveVirtualId(moduleId)\n\n const contentRoute = routes.find(route => (route.kind === 'markdown' || route.kind === 'markdown+jsx') && route.module.contentVirtualModuleId === moduleId)\n if (contentRoute) return contentRoute.source.filePath\n\n const route = routes.find(route => route.module.pageVirtualModuleId === id || route.module.pageVirtualModuleId === moduleId)\n if (route) return resolveVirtualId(route.module.pageVirtualModuleId)\n\n return null\n}\n\nexport function generateConfigModule(projectConfig: ResolvedProjectConfig, version?: string): string {\n const runtimeConfig: Record<string, unknown> = {\n title: projectConfig.title,\n description: projectConfig.description,\n siteUrl: projectConfig.siteUrl,\n routePrefix: projectConfig.routePrefix,\n assetPrefix: projectConfig.assetPrefix,\n logo: projectConfig.logo,\n homeUrl: projectConfig.homeUrl,\n favicon: projectConfig.favicon,\n theme: projectConfig.theme,\n navigation: projectConfig.navigation,\n banner: projectConfig.banner,\n footer: projectConfig.footer,\n locales: projectConfig.locales,\n variables: projectConfig.variables,\n features: projectConfig.features,\n }\n if (version) {\n runtimeConfig.version = version\n }\n return `export const config = ${JSON.stringify(runtimeConfig)};`\n}\n\nfunction moduleSpecifier(value: string): string {\n return JSON.stringify(value)\n}\n\ntype RuntimeRouteComponentExpression = string\n\ntype RuntimeRouteIdentity = {\n path: string\n basePath?: string\n locale?: string\n alternates?: Record<string, string>\n isFallback?: true\n isBareAlias?: true\n}\n\ntype RuntimeRouteMetadata = {\n title: string\n description?: string\n keywords?: string[]\n sections?: ContentSection[]\n}\n\ntype RuntimeRouteContentLinks = {\n contentArtifactUrl?: string\n sourceEditUrl?: string\n}\n\ntype RuntimeRouteManifestEntry = RuntimeRouteIdentity & RuntimeRouteMetadata & RuntimeRouteContentLinks & {\n component: RuntimeRouteComponentExpression\n lazy?: true\n kind: ContentRoute['kind']\n}\n\nfunction routeToRuntimeManifestEntry(route: ContentRoute, component: RuntimeRouteComponentExpression, mode: 'client' | 'server'): RuntimeRouteManifestEntry {\n const entry: RuntimeRouteManifestEntry = {\n path: route.path,\n title: route.meta.title,\n component,\n kind: route.kind,\n }\n\n if (mode === 'client') entry.lazy = true\n if (route.basePath) entry.basePath = route.basePath\n if (route.locale) entry.locale = route.locale\n if (route.isFallback) entry.isFallback = true\n if (route.isBareAlias) entry.isBareAlias = true\n if (route.alternates) entry.alternates = route.alternates\n if (route.meta.description) entry.description = route.meta.description\n if (route.meta.keywords?.length) entry.keywords = route.meta.keywords\n if (route.artifacts?.contentArtifactUrl) entry.contentArtifactUrl = route.artifacts.contentArtifactUrl\n if (route.source?.sourceEditUrl) entry.sourceEditUrl = route.source.sourceEditUrl\n if (route.meta.sections?.length) {\n entry.sections = route.meta.sections.map(section => ({ id: section.id, title: section.title, level: section.level, badge: section.badge, tags: section.tags }))\n }\n\n return entry\n}\n\nexport function generateRoutesModule(routes: ContentRoute[], navigation: NavigationTree, mode: 'client' | 'server' = 'client'): string {\n const imports = mode === 'server'\n ? routes.map((r, i) => `import Page${i} from ${moduleSpecifier(r.module.pageVirtualModuleId)};`).join('\\n')\n : `import { createContentDiagnosticComponent } from '@clarify-labs/renderer';`\n\n // `component` is a raw JS expression (an identifier or arrow function),\n // not a JSON string. We serialize each route object with a unique placeholder\n // for the component, then replace it with the actual expression source.\n // This keeps the rest of the object fully type-checked via JSON.stringify\n // while avoiding fragile string concatenation for every field.\n const routeEntries = routes.map((r, i) => {\n const component = mode === 'server'\n ? `Page${i}`\n : `() => import(${moduleSpecifier(r.module.pageVirtualModuleId)}).catch((error) => Promise.resolve({ default: createContentDiagnosticComponent({ kind: 'route-load', title: 'This page could not be loaded', message: error instanceof Error ? error.message : String(error), details: error instanceof Error ? error.stack : undefined }) }))`\n const placeholder = `__COMPONENT_${i}__`\n const manifestEntry = routeToRuntimeManifestEntry(r, placeholder, mode)\n const json = JSON.stringify(manifestEntry, null, 0)\n // JSON.stringify quotes all keys and omits spaces after colons. Convert to\n // idiomatic JS object-literal syntax: unquote identifier keys, pad colons\n // with a single space. Non-identifier keys (none currently, but defensive)\n // keep their quotes. Replace the component placeholder first, before the\n // key-unquoting regex runs, so the placeholder (an identifier) is not\n // turned into a bare key.\n const jsObject = json\n .replace(`\"${placeholder}\"`, component)\n .replace(/\"([A-Za-z_$][\\w$]*)\":/g, '$1: ')\n return ` ${jsObject}`\n }).join(',\\n')\n\n return `${imports}\\n\\nexport const routes = [\\n${routeEntries}\\n];\\n\\nexport const navigation = ${JSON.stringify(navigation, null, 2)};\\n`\n}\n\nexport function createClientEntryModule(options: CreateClientEntryModuleOptions = {}): string {\n return `\nimport '@clarify-labs/renderer/style.css';\nimport { render } from '@clarify-labs/renderer/client';\nimport { routes, navigation } from '${VIRTUAL_ROUTES}';\nimport { config } from '${VIRTUAL_CONFIG}';\nimport { openApiSpecs } from '${VIRTUAL_OPENAPI}';\nimport { runtimeSlots } from '${VIRTUAL_SLOTS}';\nconst renderOptions = { config, routes, navigation, openApiSpecs, runtimeSlots, themeEditor: ${JSON.stringify(options.themeEditor ?? false)} };\nrender(renderOptions);\nif (import.meta.hot) {\n import.meta.hot.accept('${VIRTUAL_ROUTES}', (mod) => {\n render({ ...renderOptions, routes: mod.routes, navigation: mod.navigation });\n });\n}`\n}\n\n/**\n * Collect every plugin's `slots` declarations into a single runtime registry\n * module. Component modules are exported as lazy import factories so the\n * renderer can decide whether to code-split (client) or pre-resolve (SSR).\n *\n * Relative component paths are resolved against the project `root` so that\n * the generated `import()` call uses an absolute specifier — Vite cannot\n * resolve relative imports from virtual modules.\n *\n * Slot name validity is enforced at compile time by the `UISlotName`\n * type — no runtime validation is needed.\n */\nexport function createRuntimeSlotsModule(plugins: ClarifyPlugin[] = [], root: string = process.cwd()): string {\n const registrations: { plugin: string; slot: UISlotRegistration }[] = []\n for (const plugin of plugins) {\n for (const slot of plugin.slots ?? []) {\n registrations.push({ plugin: plugin.name, slot })\n }\n }\n\n if (registrations.length === 0) {\n return 'export const runtimeSlots = {};\\n'\n }\n\n const grouped = new Map<string, string[]>()\n for (const { plugin, slot } of registrations) {\n // Warn when multiple plugins register the same replace slot — only the\n // last one takes effect, which is almost certainly a configuration error.\n if (slot.name.endsWith('.replace')) {\n const existing = grouped.get(slot.name)\n if (existing) {\n console.warn(`[clarify] Multiple plugins register slot \"${slot.name}\": \"${plugin}\" overrides \"${existing[existing.length - 1]}\". Only the last registration is used.`)\n }\n }\n\n // Resolve `/`-prefixed paths relative to the project root so that\n // Vite can resolve the import from the virtual module.\n if (!slot.component.startsWith('/')) {\n throw new Error(`[clarify] Plugin \"${plugin}\" slot \"${slot.name}\" has an invalid component path \"${slot.component}\". Component paths must start with \"/\" to reference the project root.`)\n }\n const componentPath = root + slot.component\n const entry = `{ plugin: ${JSON.stringify(plugin)}, loadComponent: () => import(${moduleSpecifier(componentPath)}) }`\n const list = grouped.get(slot.name) ?? []\n list.push(entry)\n grouped.set(slot.name, list)\n }\n\n const entries = [...grouped.entries()]\n .map(([name, list]) => ` ${JSON.stringify(name)}: [\\n ${list.join(',\\n ')}\\n ]`)\n .join(',\\n')\n\n return `export const runtimeSlots = {\\n${entries}\\n};\\n`\n}\n\nexport function generateContentDiagnosticModule(diagnostic: ContentDiagnostic): string {\n return `import { createContentDiagnosticComponent } from '@clarify-labs/renderer';\n\nexport const contentDiagnostic = ${JSON.stringify(diagnostic)};\n\nexport default createContentDiagnosticComponent(contentDiagnostic);\n`\n}\n\nexport function buildVirtualModules(args: BuildVirtualModulesArgs): VirtualModules {\n const modules: VirtualModules = new Map()\n const clientEntryModule = createClientEntryModule({ themeEditor: args.themeEditor })\n \n // Collect all plugins\n const allPlugins: ClarifyPlugin[] = [...(args.plugins ?? [])]\n \n modules.set(VIRTUAL_CONFIG, generateConfigModule(args.projectConfig, args.version))\n modules.set(VIRTUAL_ROUTES, generateRoutesModule(args.routes, args.navigation, 'client'))\n modules.set(VIRTUAL_SERVER_ROUTES, generateRoutesModule(args.routes, args.navigation, 'server'))\n modules.set(VIRTUAL_SLOTS, createRuntimeSlotsModule(allPlugins, args.generateOptions.projectRoot))\n modules.set(VIRTUAL_SLOT, \"export { useSlot } from '@clarify-labs/renderer';\\n\")\n modules.set(VIRTUAL_OPENAPI, 'export const openApiSpecs = {};')\n modules.set(RESOLVED_CLIENT_ENTRY, clientEntryModule)\n modules.set(VIRTUAL_CLIENT_ENTRY, clientEntryModule)\n\n for (const route of args.routes) {\n const moduleContent = route.diagnostic\n ? generateContentDiagnosticModule(route.diagnostic)\n : route.kind === 'markdown' || route.kind === 'markdown+jsx'\n ? `export { default } from ${moduleSpecifier(virtualContentModuleId(route))};`\n : null\n if (moduleContent === null) continue\n modules.set(route.module.pageVirtualModuleId, moduleContent)\n }\n\n return modules\n}\n","import { isAbsolute, join, relative } from 'node:path'\n\nimport mdxPlugin, { type Options as MdxPluginOptions } from '@mdx-js/rollup'\nimport tailwindcss from '@tailwindcss/vite'\nimport react from '@vitejs/plugin-react'\nimport rehypeRaw from 'rehype-raw'\nimport type { Plugin, ResolvedConfig, ViteDevServer } from 'vite'\n\nimport { createContentCompileDiagnostic, rehypePlugins, remarkPlugins } from '../parsers/markdown/mdx.js'\nimport { CLARIFY_DEV_ROUTE_ENDPOINT, handleDevRouteRequest } from '../parsers/router/dev-routes.js'\nimport type { ContentRoute, NavigationTree } from '../types.js'\n\nimport { type ClarifyEngine } from './engine/engine.js'\nimport { CLARIFY_DEV_PROJECT_INFO_ENDPOINT, handleProjectInfoRequest } from './project/project-info.js'\nimport {\n VIRTUAL_CLIENT_ENTRY,\n VIRTUAL_ROUTES,\n generateContentDiagnosticModule,\n resolveVirtualId,\n resolveVirtualModuleId,\n} from './runtime/virtual-modules.js'\n\ntype DevStructureSnapshot = {\n routes: string\n navigation: string\n}\n\nfunction routeStructure(route: ContentRoute): ContentRoute {\n const { content: _content, ...source } = route.source\n return { ...route, source }\n}\n\nfunction createDevStructureSnapshot(routes: ContentRoute[], navigation: NavigationTree): DevStructureSnapshot {\n return {\n routes: JSON.stringify(routes.map(routeStructure)),\n navigation: JSON.stringify(navigation),\n }\n}\n\nfunction hasDevStructureChanged(before: DevStructureSnapshot, after: DevStructureSnapshot): boolean {\n return before.routes !== after.routes || before.navigation !== after.navigation\n}\n\nfunction invalidateVirtualModules(engine: ClarifyEngine, server: ViteDevServer): void {\n for (const id of engine.modules.keys()) {\n const moduleNode = server.moduleGraph.getModuleById(resolveVirtualId(id))\n if (moduleNode) server.moduleGraph.invalidateModule(moduleNode)\n }\n}\n\nasync function refreshDevServer(engine: ClarifyEngine, server: ViteDevServer): Promise<boolean> {\n const before = createDevStructureSnapshot(engine.routes, engine.navigation)\n await engine.refresh()\n invalidateVirtualModules(engine, server)\n const after = createDevStructureSnapshot(engine.routes, engine.navigation)\n return hasDevStructureChanged(before, after)\n}\n\nfunction createNormalizedContentPlugin(engine: ClarifyEngine): Plugin {\n return {\n name: 'clarify:normalized-content',\n enforce: 'pre',\n transform(_code, id) {\n if (!/\\.mdx?(?:\\?|$)/.test(id)) return null\n const filePath = id.replace(/\\?.*$/, '')\n const route = engine.routes.find(route => (route.kind === 'markdown+jsx' || route.kind === 'markdown') && route.source.filePath === filePath)\n if (!route || route.source.content === undefined) return null\n return { code: route.source.content, map: null }\n },\n }\n}\n\ntype ContentFormat = 'markdown' | 'markdown+jsx'\ntype ContentCompileErrorPolicy = 'diagnostic' | 'throw'\ntype TransformHook = NonNullable<Plugin['transform']> extends infer Hook ? Hook extends (...args: never[]) => unknown ? Hook : never : never\n\nexport function createContentCompileTransform(transform: TransformHook, format: ContentFormat, projectRoot: string, errorPolicy: () => ContentCompileErrorPolicy = () => 'diagnostic'): NonNullable<Plugin['transform']> {\n return async function contentCompileTransform(code, id) {\n try {\n return await transform.call(this, code, id)\n } catch (error) {\n if (errorPolicy() === 'throw') throw error\n const filePath = id.replace(/\\?.*$/, '')\n return {\n code: generateContentDiagnosticModule(createContentCompileDiagnostic({\n format,\n phase: 'compilation',\n error,\n filePath,\n projectRoot,\n })),\n map: null,\n }\n }\n }\n}\n\nfunction createContentCompilerPlugin(format: ContentFormat, projectRoot: string, errorPolicy: () => ContentCompileErrorPolicy): Plugin {\n const markdown = format === 'markdown'\n const plugin = mdxPlugin({\n include: [markdown ? '**/*.md' : '**/*.mdx'],\n format: markdown ? 'md' : 'mdx',\n jsxImportSource: 'react',\n providerImportSource: '@clarify-labs/renderer',\n remarkPlugins: remarkPlugins as MdxPluginOptions['remarkPlugins'],\n ...(markdown ? { remarkRehypeOptions: { allowDangerousHtml: true } } : {}),\n rehypePlugins: markdown ? [rehypeRaw, ...rehypePlugins] : rehypePlugins,\n }) as Plugin\n const transform = typeof plugin.transform === 'function' ? plugin.transform : plugin.transform?.handler\n\n if (!transform) return plugin\n\n return {\n ...plugin,\n transform: createContentCompileTransform(transform, format, projectRoot, errorPolicy),\n }\n}\n\nfunction createClarifyViteCorePlugin(engine: ClarifyEngine, normalizedContentPlugin: Plugin, markdown: Plugin, mdx: Plugin): Plugin {\n let viteConfig: ResolvedConfig\n\n return {\n name: 'clarify:core',\n async config() {\n // The engine is already prepared (initialize + discoverSite + buildModules)\n // by the caller before constructing the Vite config. The adapter only\n // contributes Vite-level settings derived from the prepared engine state.\n return {\n base: engine.projectConfig.assetPrefix,\n build: {\n ...(engine.generateOptions.outputDirectory ? { outDir: engine.generateOptions.outputDirectory } : {}),\n manifest: true,\n },\n }\n },\n configResolved(config) {\n viteConfig = config\n engine.configureRuntime({\n command: config.command,\n mode: config.mode,\n outputDirectory: config.build.outDir,\n })\n if (!engine.generateOptions.outputDirectory) {\n engine.generateOptions.outputDirectory = config.build.outDir\n }\n },\n async buildStart() {\n if (!(await engine.beginBuild())) return\n engine.writeEnvTypes()\n },\n async handleHotUpdate(ctx) {\n const changedFile = isAbsolute(ctx.file) ? ctx.file : join(engine.root, ctx.file)\n if (engine.configFilePath && changedFile === engine.configFilePath) {\n // Config file changed: force re-prepare (initialize + discoverSite +\n // buildModules) with the current runtime mode, then reload.\n await engine.prepare({ command: 'serve', mode: viteConfig.mode }, engine.options, { force: true })\n invalidateVirtualModules(engine, ctx.server)\n ctx.server.ws.send({ type: 'full-reload' })\n return []\n }\n\n const relativeContentFile = relative(engine.contentRoot, changedFile)\n const isContentFile = relativeContentFile && !relativeContentFile.startsWith('..') && !isAbsolute(relativeContentFile)\n if (!isContentFile || !engine.hasContentRouteForFile(changedFile)) return\n\n const structureChanged = await refreshDevServer(engine, ctx.server)\n if (structureChanged) {\n const routesModule = ctx.server.moduleGraph.getModuleById(resolveVirtualId(VIRTUAL_ROUTES))\n if (routesModule) return [...ctx.modules, routesModule]\n ctx.server.ws.send({ type: 'full-reload' })\n return []\n }\n return ctx.modules\n },\n resolveId(id) {\n return resolveVirtualModuleId(id, engine.modules, engine.routes)\n },\n load(id) {\n return engine.loadModule(id)\n },\n async configureServer(server) {\n server.watcher.add(engine.contentRoot)\n if (engine.configFilePath) server.watcher.add(engine.configFilePath)\n\n server.middlewares.use((req, res, next) => {\n if (req.url === CLARIFY_DEV_ROUTE_ENDPOINT && req.method === 'POST') {\n return handleDevRouteRequest(req, res, engine.routes, engine.runtimeContext())\n }\n if (req.url === CLARIFY_DEV_PROJECT_INFO_ENDPOINT && (req.method === 'GET' || req.method === 'HEAD')) {\n return handleProjectInfoRequest(req, res, engine.runtimeContext())\n }\n next()\n })\n\n const handleContentTreeChange = async (filePath: string) => {\n const changedFile = isAbsolute(filePath) ? filePath : join(engine.root, filePath)\n const relativeContentFile = relative(engine.contentRoot, changedFile)\n const isContentFile = relativeContentFile && !relativeContentFile.startsWith('..') && !isAbsolute(relativeContentFile)\n if (!isContentFile) return\n const shouldReload = await refreshDevServer(engine, server)\n if (shouldReload) server.ws.send({ type: 'full-reload' })\n }\n\n server.watcher.on('add', handleContentTreeChange)\n server.watcher.on('unlink', handleContentTreeChange)\n const postHooks = await engine.configureDevServer(server)\n if (postHooks.length > 0) {\n return () => {\n for (const postHook of postHooks) postHook()\n }\n }\n },\n transformIndexHtml: {\n order: 'pre',\n async handler(html, transformCtx) {\n const clientEntryId = transformCtx.server\n ? `/@id/${VIRTUAL_CLIENT_ENTRY}`\n : VIRTUAL_CLIENT_ENTRY\n const result = await engine.transformHtml({\n html,\n tags: [],\n clientEntryId,\n dev: Boolean(transformCtx.server),\n })\n return {\n html: result.html,\n tags: result.tags,\n }\n },\n },\n async generateBundle() {\n const assets = await engine.collectBuildAssets()\n for (const asset of assets) {\n this.emitFile({\n type: 'asset',\n fileName: asset.fileName,\n source: asset.source,\n })\n }\n await engine.endBuild()\n },\n async closeBundle() {\n if (!engine.shouldRunBuild()) return\n engine.configureRuntime({\n outputDirectory: viteConfig.build.outDir,\n ssrPlugins: [engine.createSSGVirtualPlugin(), normalizedContentPlugin, markdown, mdx],\n })\n await engine.runSSG()\n },\n }\n}\n\n/**\n * Creates the Clarify Vite plugins bound to an already-prepared engine.\n *\n * The caller is responsible for running `engine.prepare()` (initialize +\n * discoverSite + buildModules) before constructing the Vite config that\n * includes these plugins. The adapter never initializes or discovers the\n * site itself - it only bridges Vite lifecycle hooks to the engine.\n */\nexport function createViteAdapter(engine: ClarifyEngine): Plugin[] {\n let contentCompileErrorPolicy: ContentCompileErrorPolicy = 'diagnostic'\n const errorPolicy = () => contentCompileErrorPolicy\n const normalizedContentPlugin = createNormalizedContentPlugin(engine)\n const markdown = createContentCompilerPlugin('markdown', engine.root, errorPolicy)\n const mdx = createContentCompilerPlugin('markdown+jsx', engine.root, errorPolicy)\n const compilePolicyPlugin: Plugin = {\n name: 'clarify:content-compile-policy',\n configResolved(config) {\n contentCompileErrorPolicy = config.command === 'build' ? 'throw' : 'diagnostic'\n },\n }\n // `react()` returns `Plugin[]`; `tailwindcss()` returns `Plugin | Plugin[]`;\n // the rest return a single `Plugin`. Spread the array-returning results so\n // every element is a `Plugin`, avoiding the `.flat().filter(Boolean) as\n // Plugin[]` escape hatch.\n const tailwind = tailwindcss()\n return [\n ...react(),\n ...(Array.isArray(tailwind) ? tailwind : [tailwind]),\n compilePolicyPlugin,\n normalizedContentPlugin,\n createClarifyViteCorePlugin(engine, normalizedContentPlugin, markdown, mdx),\n markdown,\n mdx,\n ]\n}\n","{\n \"name\": \"@clarify-labs/cli\",\n \"version\": \"0.11.6\",\n \"license\": \"AGPL-3.0-only\",\n \"type\": \"module\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/taicode-labs/clarify\",\n \"directory\": \"packages/cli\"\n },\n \"main\": \"output/index.cjs\",\n \"module\": \"output/index.js\",\n \"types\": \"output/index.d.ts\",\n \"bin\": {\n \"clarify\": \"bin/clarify.js\"\n },\n \"exports\": {\n \".\": {\n \"types\": \"./output/index.d.ts\",\n \"import\": \"./output/index.js\",\n \"require\": \"./output/index.cjs\",\n \"default\": \"./output/index.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"files\": [\n \"LICENSE\",\n \"bin\",\n \"output\"\n ],\n \"scripts\": {\n \"dev\": \"vite build --watch\",\n \"build\": \"vite build\",\n \"lint\": \"eslint source/\",\n \"lint:fix\": \"eslint source/ --fix\",\n \"typecheck\": \"tsc -p tsconfig.json --noEmit\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\"\n },\n \"dependencies\": {\n \"@apidevtools/swagger-parser\": \"^12.1.0\",\n \"@clarify-labs/renderer\": \"workspace:*\",\n \"@clarify-labs/templates\": \"workspace:*\",\n \"@mdx-js/mdx\": \"^3.1.1\",\n \"@mdx-js/rollup\": \"^3.1.1\",\n \"@modelcontextprotocol/sdk\": \"^1.29.0\",\n \"@msgpack/msgpack\": \"^3.1.3\",\n \"@orama/orama\": \"^3.1.18\",\n \"@shikijs/rehype\": \"^4.3.0\",\n \"@tailwindcss/vite\": \"^4.3.2\",\n \"@vitejs/plugin-react\": \"^6.0.3\",\n \"cac\": \"^7.0.0\",\n \"github-slugger\": \"^2.0.0\",\n \"gray-matter\": \"^4.0.3\",\n \"mdast-util-to-string\": \"^4.0.0\",\n \"mermaid\": \"^11.4.0\",\n \"openapi-types\": \"^12.1.3\",\n \"pagefind\": \"^1.5.2\",\n \"react\": \"^19.1.0\",\n \"react-dom\": \"^19.1.0\",\n \"react-router\": \"^7.0.0\",\n \"react-router-dom\": \"^7.0.0\",\n \"react-zoom-pan-pinch\": \"^4.0.3\",\n \"rehype-raw\": \"^7.0.0\",\n \"rehype-slug\": \"^6.0.0\",\n \"remark\": \"^15.0.1\",\n \"shiki\": \"4.3.0\",\n \"unist-util-visit\": \"^5.1.0\",\n \"vite\": \"^8.1.4\",\n \"yaml\": \"^2.9.0\",\n \"zod\": \"^4.4.3\"\n },\n \"devDependencies\": {\n \"@types/react\": \"^19.2.17\",\n \"typescript\": \"^6.0.3\",\n \"vite-plugin-dts\": \"^5.0.3\",\n \"vitest\": \"^4.1.10\"\n }\n}\n","import packageJson from '../../package.json' with { type: 'json' }\n\nexport const cliPackageJson = packageJson as { version?: string }\nexport const cliPackageVersion = cliPackageJson.version ?? '0.0.0'\nexport const cliPackageVersionWithCaret = `^${cliPackageVersion}`\n\nexport function readPackageVersion(): string {\n return cliPackageVersion\n}\n","import type { ClarifyPlugin, ClarifyProjectConfig } from '../../types.js'\n\nexport type ClarifyBuildOptions = ClarifyProjectConfig & {\n /** Project root directory. Defaults to the current working directory. */\n projectRoot?: string\n /** Root directory for content sources. Default: 'source' */\n rootDirectory?: string\n /** Output directory for the built docs site. When omitted, Vite's build.outDir is used. */\n outputDirectory?: string\n\n /** Clarify plugin extensions for translation, search, and other build-time features. */\n plugins?: ClarifyPlugin[]\n}\n\nexport type ResolvedBuildOptions = {\n projectRoot: string\n rootDirectory: string\n outputDirectory?: string\n}\n\nexport function resolveBuildOptions(options: ClarifyBuildOptions = {}): ResolvedBuildOptions {\n return {\n projectRoot: options.projectRoot ?? process.cwd(),\n rootDirectory: options.rootDirectory ?? 'source',\n outputDirectory: options.outputDirectory,\n }\n}\n","import type { ContentRoute, ResolvedProjectConfig } from '../../types.js'\n\nconst UTF8_SIGNATURE = '\\uFEFF'\n\nfunction normalizeBasePath(basePath: string): string {\n if (!basePath || basePath === '/') return ''\n return '/' + basePath.replace(/^\\/+|\\/+$/g, '')\n}\n\nfunction containsNonAscii(content: string): boolean {\n return [...content].some(character => character.codePointAt(0)! > 0x7F)\n}\n\nfunction withUtf8Signature(content: string): string {\n if (!containsNonAscii(content) || content.startsWith(UTF8_SIGNATURE)) return content\n return `${UTF8_SIGNATURE}${content}`\n}\n\nfunction shouldUseUtf8Signature(route: ContentRoute): boolean {\n if (route.kind === 'markdown+jsx' || route.kind === 'markdown') return true\n return false\n}\n\nfunction routeToMarkdownArtifactUrl(routePath: string): string {\n const normalizedPath = routePath === '/' ? '/index' : routePath.replace(/\\/$/, '')\n return `${normalizedPath}.md`\n}\n\nfunction routeToOpenAPIArtifactUrl(routePath: string): string {\n const normalizedPath = routePath === '/' ? '/index' : routePath.replace(/\\/$/, '')\n return `${normalizedPath}.openapi.json`\n}\n\nexport function attachContentArtifactUrls(routes: ContentRoute[]): void {\n for (const route of routes) {\n route.artifacts = {\n ...route.artifacts,\n contentArtifactUrl: route.kind === 'openapi'\n ? routeToOpenAPIArtifactUrl(route.path)\n : routeToMarkdownArtifactUrl(route.path),\n }\n }\n}\n\nexport function readRouteContent(route: ContentRoute): string {\n if (route.source.content !== undefined) return route.source.content\n throw new Error(`Route content is missing from route context: ${route.source.filePath}`)\n}\n\nexport function readRouteArtifactContent(route: ContentRoute): string {\n const content = readRouteContent(route)\n return shouldUseUtf8Signature(route) ? withUtf8Signature(content) : content\n}\n\nfunction isLlmsTxtRoute(route: ContentRoute): boolean {\n return !route.path.split('/').includes('404')\n}\n\nfunction llmsTxtDescription(route: ContentRoute): string | undefined {\n if (route.meta.description) return route.meta.description\n\n const sections = route.meta.sections?.filter(section => section.level === 2).slice(0, 3).map(section => section.title)\n if (sections?.length) return `Covers ${sections.join(', ')}.`\n\n if (route.meta.keywords?.length) return `Related topics: ${route.meta.keywords.join(', ')}.`\n\n if (route.kind === 'openapi') return 'OpenAPI artifact for machine-readable API reference data.'\n\n return undefined\n}\n\nfunction llmsTxtListItem(route: ContentRoute, basePath: string): string | undefined {\n const contentArtifactUrl = route.artifacts?.contentArtifactUrl\n if (!contentArtifactUrl) return undefined\n\n const description = llmsTxtDescription(route)\n return description\n ? `- [${route.meta.title}](${basePath}${contentArtifactUrl}): ${description}`\n : `- [${route.meta.title}](${basePath}${contentArtifactUrl})`\n}\n\nfunction llmsTxtLocaleLabel(locale: string, projectConfig: ResolvedProjectConfig): string {\n return projectConfig.locales?.locales.find(item => item.code === locale)?.label ?? locale\n}\n\nfunction groupRoutesByLocale(routes: ContentRoute[]): Map<string, ContentRoute[]> {\n const groups = new Map<string, ContentRoute[]>()\n for (const route of routes) {\n const key = route.locale ?? 'default'\n groups.set(key, [...(groups.get(key) ?? []), route])\n }\n return groups\n}\n\nfunction groupLlmsTxtRoutesByLocale(routes: ContentRoute[], projectConfig: ResolvedProjectConfig): Map<string, ContentRoute[]> {\n const routesBySource = new Map<string, ContentRoute>()\n const defaultLocale = projectConfig.locales?.default\n\n for (const route of routes) {\n const sourceKey = `${route.locale ?? defaultLocale ?? 'default'}:${route.basePath ?? route.artifacts?.contentArtifactUrl ?? route.path}`\n const previousRoute = routesBySource.get(sourceKey)\n\n if (!previousRoute || (previousRoute.locale && !route.locale)) {\n routesBySource.set(sourceKey, route)\n }\n }\n\n return groupRoutesByLocale([...routesBySource.values()].map(route => ({\n ...route,\n locale: route.locale ?? defaultLocale,\n })))\n}\n\nfunction llmsTxtDocsSectionTitle(locale: string, groupCount: number, projectConfig: ResolvedProjectConfig): string {\n if (groupCount <= 1) return 'Docs'\n return `Docs - ${locale === 'default' ? 'Default' : llmsTxtLocaleLabel(locale, projectConfig)}`\n}\n\nexport function createLlmsTxt(routes: ContentRoute[], projectConfig: ResolvedProjectConfig): string {\n const basePath = normalizeBasePath(projectConfig.routePrefix)\n const lines = [\n `# ${projectConfig.title}`,\n '',\n ]\n\n if (projectConfig.description) {\n lines.push(`> ${projectConfig.description}`, '')\n }\n\n lines.push('This file lists the source-ready Markdown and OpenAPI artifacts for this documentation site.', '')\n\n // Exclude bare alias routes (e.g., /path without language prefix) in multilingual sites\n const markdownRoutes = routes.filter(route => (route.kind === 'markdown+jsx' || route.kind === 'markdown') && isLlmsTxtRoute(route) && !route.isBareAlias)\n if (markdownRoutes.length > 0) {\n const localizedGroups = groupLlmsTxtRoutesByLocale(markdownRoutes, projectConfig)\n for (const [locale, localeRoutes] of localizedGroups) {\n lines.push(`## ${llmsTxtDocsSectionTitle(locale, localizedGroups.size, projectConfig)}`)\n\n for (const route of localeRoutes) {\n const item = llmsTxtListItem(route, basePath)\n if (item) lines.push(item)\n }\n\n lines.push('')\n }\n }\n\n // Exclude bare alias routes (e.g., /path without language prefix) in multilingual sites\n const openApiRoutes = routes.filter(route => route.kind === 'openapi' && isLlmsTxtRoute(route) && !route.isBareAlias)\n if (openApiRoutes.length > 0) {\n if (lines.at(-1) !== '') lines.push('')\n lines.push('## OpenAPI')\n for (const route of openApiRoutes) {\n const item = llmsTxtListItem(route, basePath)\n if (item) lines.push(item)\n }\n }\n\n while (lines.at(-1) === '') lines.pop()\n return `${lines.join('\\n')}\\n`\n}\n\nexport function createLlmsTxtArtifact(routes: ContentRoute[], projectConfig: ResolvedProjectConfig): string {\n return withUtf8Signature(createLlmsTxt(routes, projectConfig))\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\nimport { stringify as yamlStringify } from 'yaml'\n\nimport type { ContentRoute, ResolvedProjectConfig } from '../../types.js'\n\nimport { createLlmsTxtArtifact, readRouteArtifactContent } from './artifacts.js'\n\nfunction normalizeRoutePrefix(routePrefix: string): string {\n if (!routePrefix || routePrefix === '/') return ''\n return `/${routePrefix.replace(/^\\/+|\\/+$/g, '')}`\n}\n\nexport function resolveContentArtifactPath(url: string | undefined, projectConfig: ResolvedProjectConfig): string {\n const requestPath = url?.split('?')[0] ?? ''\n const basePath = normalizeRoutePrefix(projectConfig.routePrefix)\n return basePath && requestPath.startsWith(basePath)\n ? requestPath.slice(basePath.length) || '/'\n : requestPath\n}\n\nexport function resolveContentArtifactType(route: ContentRoute): string {\n return route.kind === 'openapi'\n ? 'application/json; charset=utf-8'\n : 'text/markdown; charset=utf-8'\n}\n\nexport function serveContentArtifacts(req: IncomingMessage, res: ServerResponse, projectConfig: ResolvedProjectConfig, routes: ContentRoute[]): boolean {\n const contentPath = resolveContentArtifactPath(req.url, projectConfig)\n\n if (contentPath === '/llms.txt') {\n res.statusCode = 200\n res.setHeader('Content-Type', 'text/plain; charset=utf-8')\n res.end(createLlmsTxtArtifact(routes, projectConfig), 'utf8')\n return true\n }\n\n // Handle YAML variant for OpenAPI routes: /api.openapi.yaml → serve YAML\n if (contentPath.endsWith('.openapi.yaml')) {\n const jsonPath = contentPath.replace(/\\.yaml$/, '.json')\n const route = routes.find(route => route.artifacts?.contentArtifactUrl === jsonPath)\n if (route?.kind === 'openapi' && route.source.content) {\n const spec = JSON.parse(route.source.content)\n res.statusCode = 200\n res.setHeader('Content-Type', 'text/yaml; charset=utf-8')\n res.end(yamlStringify(spec, { lineWidth: 0 }), 'utf8')\n return true\n }\n return false\n }\n\n const route = routes.find(route => route.artifacts?.contentArtifactUrl === contentPath)\n if (!route) return false\n\n res.statusCode = 200\n res.setHeader('Content-Type', resolveContentArtifactType(route))\n res.end(readRouteArtifactContent(route), 'utf8')\n return true\n}\n","import type { ViteDevServer } from 'vite'\nimport { stringify as yamlStringify } from 'yaml'\n\nimport type { ClarifyEmitAsset, ClarifyPlugin } from '../../types.js'\n\nimport { attachContentArtifactUrls, createLlmsTxtArtifact, readRouteArtifactContent } from './artifacts.js'\nimport { serveContentArtifacts } from './server.js'\n\nexport function createContentArtifactsPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:content-artifacts',\n hooks: {\n 'routes:resolved': (input) => {\n attachContentArtifactUrls(input.routes)\n return input\n },\n 'dev:configureServer': (server: ViteDevServer, ctx) => {\n return () => {\n server.middlewares.use((req, res, next) => {\n if (serveContentArtifacts(req, res, ctx.projectConfig, ctx.routes)) return\n next()\n })\n }\n },\n 'build:assets': (ctx) => {\n const assets: ClarifyEmitAsset[] = []\n\n for (const route of ctx.routes) {\n const contentArtifactUrl = route.artifacts?.contentArtifactUrl\n if (!contentArtifactUrl) continue\n\n assets.push({\n fileName: contentArtifactUrl.replace(/^\\//, ''),\n source: readRouteArtifactContent(route),\n })\n\n if (route.kind === 'openapi' && route.source.content) {\n const yamlFileName = contentArtifactUrl.replace(/\\.json$/, '.yaml')\n const spec = JSON.parse(route.source.content)\n assets.push({\n fileName: yamlFileName.replace(/^\\//, ''),\n source: yamlStringify(spec, { lineWidth: 0 }),\n })\n }\n }\n\n assets.push({\n fileName: 'llms.txt',\n source: createLlmsTxtArtifact(ctx.routes, ctx.projectConfig),\n })\n\n return assets\n },\n },\n }\n}\n","import type { HtmlTagDescriptor } from 'vite'\n\nimport { themeBootstrapScript } from '@clarify-labs/renderer'\n\nimport type { ClarifyFaviconConfig, ClarifyPlugin } from '../../types.js'\n\nconst REL_ICON_RE = /<link\\s+[^>]*rel=[\"'][^\"']*\\bicon\\b[^\"']*[\"'][^>]*>/i\n\nfunction inferIconType(href: string): string | undefined {\n const path = href.split(/[?#]/, 1)[0]?.toLowerCase() ?? href.toLowerCase()\n\n if (path.endsWith('.svg')) return 'image/svg+xml'\n if (path.endsWith('.png')) return 'image/png'\n if (path.endsWith('.ico')) return 'image/x-icon'\n if (path.endsWith('.webp')) return 'image/webp'\n\n return undefined\n}\n\nfunction createIconTag(href: string, media?: string): HtmlTagDescriptor {\n return {\n tag: 'link',\n attrs: {\n rel: 'icon',\n ...(inferIconType(href) ? { type: inferIconType(href) } : {}),\n href,\n ...(media ? { media } : {}),\n },\n injectTo: 'head',\n }\n}\n\nfunction createIconTags(icon?: ClarifyFaviconConfig): HtmlTagDescriptor[] {\n if (!icon) return []\n\n if (typeof icon === 'string') return [createIconTag(icon)]\n\n const lightIcon = icon.light ?? icon.dark\n const darkIcon = icon.dark ?? icon.light\n\n if (!lightIcon || !darkIcon) return []\n if (lightIcon === darkIcon) return [createIconTag(lightIcon)]\n\n return [\n createIconTag(lightIcon, '(prefers-color-scheme: light)'),\n createIconTag(darkIcon, '(prefers-color-scheme: dark)'),\n ]\n}\n\nexport function createHtmlShellPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:html-shell',\n hooks: {\n 'html:transform': (input, ctx) => ({\n html: input.html,\n tags: [\n ...input.tags,\n ...(REL_ICON_RE.test(input.html) ? [] : createIconTags(ctx.projectConfig.favicon ?? ctx.projectConfig.logo)),\n {\n tag: 'script',\n children: themeBootstrapScript(ctx.projectConfig.theme),\n injectTo: 'head-prepend',\n },\n {\n tag: 'script',\n attrs: { type: 'module', src: input.clientEntryId },\n injectTo: 'body',\n },\n ],\n clientEntryId: input.clientEntryId,\n dev: input.dev,\n }),\n },\n }\n}\n","import type { ResolvedProjectConfig } from '../../types.js'\n\n/**\n * Descriptor for a single MCP capability surfaced by a Clarify site.\n *\n * Capabilities are intentionally open-ended so future versions can add\n * `resources`, `prompts`, etc. without reshaping the top-level file. Each\n * capability carries its own metadata block; the CLI selects the block(s)\n * it understands and ignores the rest.\n */\nexport type McpCapability = McpSearchCapability\n\n/**\n * Full-text search capability backed by an Orama binary index.\n */\nexport type McpSearchCapability = {\n /** Capability discriminator. */\n type: 'search'\n /**\n * Root-relative path to the Orama binary index (`.msp`) produced at build\n * time. Always served from the site root, so it already includes the\n * routePrefix when one is configured.\n */\n indexPath: string\n /** SHA-256 hash of the index payload at indexPath, for cache freshness checks. */\n indexHash?: string\n /** Locale used when the caller does not specify one. Drives tokenizer. */\n defaultLocale?: string\n /** Number of documents stored in the index. */\n documentCount: number\n /** Locales present in the index, for surfacing in tool descriptions. */\n locales: string[]\n}\n\n/**\n * MCP server descriptor emitted to `<output>/mcp.json` during build.\n *\n * Consumed by `clarify mcp <url>` to bootstrap a local MCP server that\n * exposes site capabilities (currently full-text search) to LLM clients.\n * The descriptor points the CLI at the Orama binary index (`.msp`) written\n * alongside `mcp.json` and carries the locale metadata needed to reconstruct\n * the tokenizer at runtime.\n */\nexport type McpSiteConfig = {\n /** Schema version of this file. Bumped on breaking shape changes. */\n version: 3\n site: {\n title?: string\n description?: string\n /** Canonical public site URL, if `siteUrl` is configured. */\n url?: string\n /** Route prefix where the site is mounted. Default: '/'. */\n routePrefix: string\n }\n /**\n * Capability map keyed by capability id. The id is stable across builds so\n * clients can address a specific capability (e.g. `search`) even as new\n * ones are added. Only capabilities actually emitted by the build are\n * present; an absent key means the site does not provide that capability.\n */\n capabilities: {\n search?: McpSearchCapability\n }\n}\n\n/**\n * Normalize a route prefix into a root-relative path segment.\n *\n * `'/'` -> `''`, `'/docs'` -> `'/docs'`, `'docs/'` -> `'/docs'`.\n */\nfunction normalizePrefix(routePrefix: string | undefined): string {\n if (!routePrefix || routePrefix === '/') return ''\n return `/${routePrefix.replace(/^\\/+|\\/+$/g, '')}`\n}\n\nexport type CreateMcpSiteConfigOptions = {\n documentCount: number\n locales: string[]\n indexHash: string\n}\n\n/**\n * Assemble the MCP site config from build-time metadata.\n *\n * Unlike the previous pagefind-based descriptor, this no longer reads an\n * entry JSON file - the Orama index is a single binary blob, so the caller\n * supplies the document count and locale list directly from the build step\n * that produced the index.\n */\nexport function createMcpSiteConfig(projectConfig: ResolvedProjectConfig, options: CreateMcpSiteConfigOptions): McpSiteConfig {\n const prefix = normalizePrefix(projectConfig.routePrefix)\n return {\n version: 3,\n site: {\n title: projectConfig.title,\n description: projectConfig.description,\n url: projectConfig.siteUrl,\n routePrefix: projectConfig.routePrefix ?? '/',\n },\n capabilities: {\n search: {\n type: 'search',\n indexPath: `${prefix}/mcp-search.msp`,\n indexHash: options.indexHash,\n defaultLocale: projectConfig.locales?.default,\n documentCount: options.documentCount,\n locales: options.locales,\n },\n },\n }\n}\n","import { readFileSync, writeFileSync } from 'node:fs'\nimport { brotliCompressSync, brotliDecompressSync, constants as zlibConstants } from 'node:zlib'\n\nimport { decode, encode } from '@msgpack/msgpack'\nimport { create, insertMultiple, search, save, load } from '@orama/orama'\nimport type { AnyOrama, Results } from '@orama/orama'\n\nimport type { ContentRoute } from '../../types.js'\n\nconst MSP_MAGIC = new Uint8Array([0x43, 0x4c, 0x41, 0x52, 0x49, 0x46, 0x59, 0x4d, 0x53, 0x50, 0x01])\n\nfunction hasMspMagic(buffer: Uint8Array): boolean {\n return buffer.byteLength >= MSP_MAGIC.byteLength\n && MSP_MAGIC.every((byte, index) => buffer[index] === byte)\n}\n\n/**\n * Orama schema for the MCP search index.\n *\n * - `path`, `title`, `description`, `content` are full-text searchable strings.\n * - `locale` is an `enum` so we can use `where: { locale: { eq } }` filters at\n * query time. (`string` fields cannot be filtered in Orama.)\n * - `keywords` is a `string[]` also indexed for full-text matching.\n */\nexport const mcpSearchSchema = {\n path: 'string',\n title: 'string',\n description: 'string',\n locale: 'enum',\n content: 'string',\n keywords: 'string[]',\n} as const\n\nexport type McpSearchDocument = {\n path: string\n title: string\n description: string\n locale: string\n content: string\n keywords: string[]\n}\n\n/**\n * Intl.Segmenter cache keyed by BCP 47 tag. Segmenter construction is not\n * cheap, and the MCP server issues many queries against the same locale, so\n * we reuse instances. The cache is module-scoped: build and runtime share it\n * in the same process, and separate processes get their own - which is fine.\n */\nconst segmenterCache = new Map<string, Intl.Segmenter>()\n\nfunction getSegmenter(locale: string): Intl.Segmenter {\n let seg = segmenterCache.get(locale)\n if (!seg) {\n seg = new Intl.Segmenter(locale, { granularity: 'word' })\n segmenterCache.set(locale, seg)\n }\n return seg\n}\n\n/**\n * Map a Clarify locale code (e.g. `zh-CN`, `en-US`, `ja-JP`) to a BCP 47 tag\n * suitable for `Intl.Segmenter`. Returns `null` for locales we intentionally\n * want to tokenize with the Latin/whitespace fallback (faster, and avoids\n * forcing CJK-style word segmentation on Latin scripts).\n */\nfunction segmenterLocale(locale: string | undefined): string | null {\n if (!locale) return null\n const lower = locale.toLowerCase()\n if (lower.startsWith('zh')) return 'zh-CN'\n if (lower.startsWith('ja')) return 'ja-JP'\n if (lower.startsWith('ko')) return 'ko-KR'\n return null\n}\n\n/**\n * Tokenize text for Orama indexing and querying.\n *\n * CJK locales use `Intl.Segmenter` (word granularity), which splits\n * spaceless scripts into words and individual characters. Latin/whitespace\n * locales fall back to a Unicode-aware split on spaces and punctuation.\n *\n * All tokens are lowercased so queries match regardless of case.\n */\nexport function tokenizeForSearch(text: string, locale?: string): string[] {\n if (!text) return []\n const segLocale = segmenterLocale(locale)\n if (segLocale) {\n const seg = getSegmenter(segLocale)\n return Array.from(seg.segment(text))\n .filter((s) => s.isWordLike)\n .map((s) => s.segment.toLowerCase())\n }\n // Latin / default: split on whitespace + punctuation, drop empties.\n return text\n .toLowerCase()\n .split(/[\\s\\p{P}]+/u)\n .filter(Boolean)\n}\n\n/**\n * Build an Orama tokenizer component bound to a specific default locale.\n *\n * The tokenizer receives the raw field value and the per-field language hint\n * from Orama (which we don't set per-field, so it falls back to the default\n * language). We resolve the segmenter locale from the default locale at\n * construction time so the same tokenizer handles all documents in a\n * predominantly single-locale index.\n *\n * For multi-locale indexes, the tokenizer is also used at query time. Since\n * the query locale is not known to Orama's tokenizer callback, we use the\n * index's default locale - this is acceptable because:\n * - CJK queries get CJK segmentation (correct)\n * - Latin queries against a CJK-default index still work because Latin\n * text has no word boundaries for CJK segmenters to mis-split; the\n * segmenter passes through Latin words as-is.\n */\nexport function createMcpTokenizer(defaultLocale?: string) {\n return {\n language: defaultLocale ?? 'en',\n normalizationCache: new Map<string, string>(),\n tokenize(raw: unknown, language?: string): string[] {\n const text = typeof raw === 'string' ? raw : String(raw ?? '')\n // `language` is Orama's per-field language; fall back to the index default.\n return tokenizeForSearch(text, language ?? defaultLocale)\n },\n }\n}\n\n/**\n * Compose the searchable text for a route. Shared between the Pagefind\n * (browser) and Orama (MCP) indexing paths so both backends see the same\n * field order and content.\n */\nexport function routeSearchContent(route: ContentRoute): string {\n return [\n route.meta.title,\n route.meta.description,\n route.meta.keywords?.join(' '),\n route.meta.sections?.map((section) => section.title).join(' '),\n route.source.content,\n ]\n .filter(Boolean)\n .join('\\n\\n')\n}\n\n/**\n * Convert a `ContentRoute` into the document shape stored in the Orama index.\n */\nexport function routeToSearchDocument(route: ContentRoute, defaultLocale?: string): McpSearchDocument | null {\n // Skip bare alias routes (e.g. `/path` that just redirects to `/locale/path`)\n // to avoid indexing duplicate content in multilingual sites.\n if (route.isBareAlias) return null\n\n const content = routeSearchContent(route)\n if (!content.trim()) return null\n\n return {\n path: route.path,\n title: route.meta.title ?? '',\n description: route.meta.description ?? '',\n locale: route.locale ?? defaultLocale ?? 'en',\n content,\n keywords: route.meta.keywords ?? [],\n }\n}\n\n/**\n * Create an Orama index pre-configured with the MCP schema and CJK-aware\n * tokenizer. Both the build step and the runtime loader use this so the\n * tokenizer is guaranteed to match between indexing and querying.\n *\n * Annotated as `AnyOrama` (Orama's exported base type) rather than inferred\n * via `ReturnType<typeof create>` because the inference would pull in\n * Orama's internal component types (`DocumentsStore`, `Index`, `Sorter`)\n * which are not exported and break `.d.ts` generation (TS2883).\n */\nexport function createMcpSearchIndex(defaultLocale?: string): McpSearchDb {\n return create({\n schema: mcpSearchSchema,\n components: { tokenizer: createMcpTokenizer(defaultLocale) },\n })\n}\n\n/** Orama index instance type for the MCP search schema. */\nexport type McpSearchDb = AnyOrama<typeof mcpSearchSchema>\n\n/**\n * Insert search documents into an Orama index.\n */\nexport function indexSearchDocuments(db: McpSearchDb, documents: McpSearchDocument[]): void {\n if (documents.length === 0) return\n insertMultiple(db, documents)\n}\n\n/**\n * Build a ready-to-search Orama index from content routes.\n *\n * Filters out bare aliases and empty routes. Returns the populated db.\n */\nexport function buildSearchIndex(routes: ContentRoute[], defaultLocale?: string): { db: McpSearchDb; documentCount: number } {\n const db = createMcpSearchIndex(defaultLocale)\n const documents: McpSearchDocument[] = []\n for (const route of routes) {\n const doc = routeToSearchDocument(route, defaultLocale)\n if (doc) documents.push(doc)\n }\n indexSearchDocuments(db, documents)\n return { db, documentCount: documents.length }\n}\n\n/**\n * Collect the distinct locale codes that will be present in the Orama index,\n * in stable insertion order. Bare aliases are skipped (they duplicate the\n * default-locale route). Locales with no code fall back to the project\n * default so single-locale sites still surface one locale.\n */\nexport function collectIndexedLocales(routes: ContentRoute[], defaultLocale?: string): string[] {\n const seen = new Set<string>()\n const locales: string[] = []\n for (const route of routes) {\n if (route.isBareAlias) continue\n const code = route.locale ?? defaultLocale ?? 'en'\n if (!seen.has(code)) {\n seen.add(code)\n locales.push(code)\n }\n }\n return locales\n}\n\nexport type McpSearchParams = {\n query: string\n locale?: string\n limit?: number\n}\n\nexport type McpSearchHit = {\n path: string\n title: string\n description: string\n locale: string\n score: number\n excerpt: string\n keywords: string[]\n}\n\nexport type McpSearchResult = {\n hits: McpSearchHit[]\n count: number\n}\n\n/**\n * Search an Orama MCP index.\n *\n * Applies an optional locale filter (via the `enum` field) and returns a\n * compact, LLM-friendly hit shape. Excerpts are derived from the matched\n * content: Orama does not return highlighted excerpts, so we synthesize a\n * short window around the first query term occurrence.\n */\nexport function searchMcpIndex(db: McpSearchDb, params: McpSearchParams): McpSearchResult {\n const limit = Math.max(1, Math.min(50, params.limit ?? 10))\n // `search` (the sync variant) returns `Results` at runtime, but its type\n // signature is `Results | Promise<Results>` to also cover `searchAsync`.\n // We assert to `Results` since we intentionally call the sync form.\n const result = search(db, {\n term: params.query,\n limit,\n where: params.locale ? { locale: { eq: params.locale } } : undefined,\n }) as Results<McpSearchDocument>\n\n const hits: McpSearchHit[] = result.hits.map((hit) => {\n const doc = hit.document as McpSearchDocument\n return {\n path: doc.path,\n title: doc.title || guessTitleFromPath(doc.path),\n description: doc.description,\n locale: doc.locale,\n score: hit.score,\n excerpt: makeExcerpt(doc.content, params.query),\n keywords: doc.keywords,\n }\n })\n\n return { hits, count: result.count }\n}\n\n/**\n * Build a short excerpt around the first occurrence of any query term in the\n * content. Falls back to the beginning of the content if no term is found.\n */\nfunction makeExcerpt(content: string, query: string, maxLen = 240): string {\n if (!content) return ''\n const terms = query\n .toLowerCase()\n .split(/[\\s\\p{P}]+/u)\n .filter(Boolean)\n const lower = content.toLowerCase()\n let pos = -1\n for (const term of terms) {\n const i = lower.indexOf(term)\n if (i >= 0 && (pos < 0 || i < pos)) pos = i\n }\n if (pos < 0) pos = 0\n // Center the window on the first match, clamped to content bounds.\n const half = Math.floor(maxLen / 2)\n const start = Math.max(0, pos - half)\n const end = Math.min(content.length, start + maxLen)\n const prefix = start > 0 ? '…' : ''\n const suffix = end < content.length ? '…' : ''\n return `${prefix}${content.slice(start, end).trim()}${suffix}`\n}\n\nfunction guessTitleFromPath(path: string): string {\n if (!path) return '(untitled)'\n const segments = path.split('/').filter(Boolean)\n if (segments.length === 0) return 'Home'\n return segments[segments.length - 1]\n .replace(/\\.(md|mdx|html)$/, '')\n .replace(/[-_]/g, ' ')\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n}\n\n/**\n * Serialize an Orama index to a versioned, Brotli-compressed binary buffer.\n *\n * Uses `save()` to extract the raw index data, MessagePack-encodes it, then\n * compresses the payload so source documents are not embedded as contiguous\n * plaintext. The leading magic bytes identify the container and its version.\n */\nexport function serializeSearchIndex(db: McpSearchDb): Uint8Array {\n const raw = save(db)\n const packed = encode(raw)\n const compressed = brotliCompressSync(packed, {\n params: {\n [zlibConstants.BROTLI_PARAM_QUALITY]: 9,\n },\n })\n const buffer = new Uint8Array(MSP_MAGIC.byteLength + compressed.byteLength)\n buffer.set(MSP_MAGIC)\n buffer.set(compressed, MSP_MAGIC.byteLength)\n return buffer\n}\n\n/**\n * Deserialize a current compressed container or legacy MessagePack buffer\n * into a ready-to-search Orama index.\n *\n * The caller must supply the same `defaultLocale` used when the index was\n * built, so the tokenizer matches. A mismatch would not corrupt data but\n * would cause CJK query terms to be tokenized incorrectly (e.g. \"文档\" left\n * as a single token instead of split into \"文\" + \"档\").\n */\nexport function deserializeSearchIndex(buffer: Uint8Array, defaultLocale?: string): McpSearchDb {\n const packed = hasMspMagic(buffer)\n ? brotliDecompressSync(buffer.subarray(MSP_MAGIC.byteLength))\n : buffer\n const raw = decode(packed) as ReturnType<typeof save>\n const db = createMcpSearchIndex(defaultLocale)\n load(db, raw)\n return db\n}\n\n/**\n * Write an Orama index to a versioned `.msp` file on disk.\n */\nexport function writeSearchIndex(db: McpSearchDb, filePath: string): void {\n writeFileSync(filePath, serializeSearchIndex(db))\n}\n\n/**\n * Read a current or legacy Orama `.msp` index from disk.\n */\nexport function readSearchIndex(filePath: string, defaultLocale?: string): McpSearchDb {\n return deserializeSearchIndex(readFileSync(filePath), defaultLocale)\n}\n","import { createHash } from 'node:crypto'\n\nimport type { ClarifyEmitAsset, ClarifyPlugin } from '../../types.js'\n\nimport { createMcpSiteConfig } from './mcp-config.js'\nimport { buildSearchIndex, collectIndexedLocales, serializeSearchIndex } from './orama-index.js'\n\n/**\n * MCP search index plugin.\n *\n * Generates the Orama binary index (`mcp-search.msp`) and the MCP site\n * descriptor (`mcp.json`) as build assets consumed by the `clarify mcp`\n * command to serve documentation search to MCP-aware clients (e.g. AI coding\n * assistants).\n *\n * This plugin is independent of `clarify:page-search` (Pagefind), which\n * powers in-browser search. The MCP server runs in Node and needs a\n * self-contained, compact index with CJK-aware tokenization that doesn't\n * depend on the browser-only Pagefind runtime.\n */\nexport function createMcpSearchPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:mcp-search',\n hooks: {\n 'build:assets'(ctx) {\n const searchConfig = ctx.projectConfig.features.search\n if (!searchConfig.enabled || !searchConfig.mcp) return []\n\n const defaultLocale = ctx.projectConfig.locales?.default\n const { db, documentCount } = buildSearchIndex(ctx.routes, defaultLocale)\n const locales = collectIndexedLocales(ctx.routes, defaultLocale)\n const indexBytes = serializeSearchIndex(db)\n const indexHash = createHash('sha256').update(indexBytes).digest('hex')\n const mcpConfig = createMcpSiteConfig(ctx.projectConfig, { documentCount, locales, indexHash })\n\n const prefix = mcpConfig.capabilities.search?.indexPath.replace(/\\/mcp-search\\.msp$/, '') ?? ''\n const assets: ClarifyEmitAsset[] = [\n {\n fileName: `${prefix}/mcp-search.msp`.replace(/^\\//, ''),\n source: indexBytes,\n },\n {\n fileName: 'mcp.json',\n source: `${JSON.stringify(mcpConfig, null, 2)}\\n`,\n },\n ]\n\n console.log(`[clarify] MCP search index (${documentCount} docs, ${locales.length} locales) written to mcp-search.msp.`)\n return assets\n },\n },\n }\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs'\nimport { join, relative, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport SwaggerParser from '@apidevtools/swagger-parser'\nimport { slug } from 'github-slugger'\n\nimport { pageVirtualModuleIdFromRef } from '../../core/runtime/module-ids.js'\nimport type { ContentProcessor } from '../../parsers/content/content.js'\nimport { createContentDiagnostic } from '../../parsers/content/diagnostic.js'\nimport { kebabToTitle, routePathFromRef } from '../../parsers/routes/routes.js'\nimport type { ContentDiagnostic, ContentSection, OpenAPIContentRoute, OpenAPISpec } from '../../types.js'\n\nconst OPENAPI_HTTP_METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'] as const\nconst CLARIFY_OPENAPI_SECTION_ID_EXTENSION = 'x-clarify-section-id'\n\ntype ResolverFileInfo = { url: string }\n\nexport type OpenAPIParseResult =\n | { ok: true; spec: OpenAPISpec }\n | { ok: false; diagnostic: ContentDiagnostic }\n\nfunction isSameOpenAPIFile(url: string, filePath: string): boolean {\n try {\n return resolve(fileURLToPath(url)) === resolve(filePath)\n } catch {\n return resolve(url) === resolve(filePath)\n }\n}\n\nexport function findOpenAPIRoutes(dir: string, base: string = dir): OpenAPIContentRoute[] {\n const routes: OpenAPIContentRoute[] = []\n if (!existsSync(dir)) return routes\n\n const entries = readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n const fullPath = join(dir, entry.name)\n if (entry.isDirectory()) {\n routes.push(...findOpenAPIRoutes(fullPath, base))\n continue\n }\n if (!entry.isFile() || !/\\.openapi\\.(json|yaml|yml)$/.test(entry.name)) continue\n\n const ref = relative(base, fullPath)\n const cleanPath = routePathFromRef(ref)\n routes.push({\n path: cleanPath,\n basePath: cleanPath,\n kind: 'openapi',\n meta: {\n title: kebabToTitle(cleanPath.split('/').pop() ?? 'API'),\n },\n module: {\n pageVirtualModuleId: pageVirtualModuleIdFromRef(ref),\n },\n source: {\n filePath: fullPath,\n },\n })\n }\n\n return routes\n}\n\nfunction operationMatchesTags(operationTags: string[] | undefined, filterTags: string[] | undefined): boolean {\n if (!filterTags?.length) return true\n return operationTags?.some(tag => filterTags.includes(tag)) ?? false\n}\n\nfunction filterPathItemsByTags(items: Record<string, unknown>, tags: string[]): Record<string, unknown> {\n const filteredItems: Record<string, unknown> = {}\n for (const path of Object.keys(items)) {\n const pathItem = items[path] as Record<string, unknown> | undefined\n if (!pathItem) continue\n const ops = OPENAPI_HTTP_METHODS.map(method => pathItem[method])\n const hasMatch = ops.some(op => op && typeof op === 'object' && operationMatchesTags((op as Record<string, unknown>).tags as string[] | undefined, tags))\n if (hasMatch) filteredItems[path] = pathItem\n }\n return filteredItems\n}\n\nfunction createOperationSectionId(operation: Record<string, unknown>, method: string, path: string, kind: 'path' | 'webhook'): string {\n const operationId = typeof operation.operationId === 'string' ? operation.operationId.trim() : ''\n return operationId || slug(`${kind === 'webhook' ? 'webhook ' : ''}${method.toLowerCase()} ${path}`)\n}\n\nfunction operationSectionId(operation: Record<string, unknown>): string {\n const sectionId = operation[CLARIFY_OPENAPI_SECTION_ID_EXTENSION]\n return typeof sectionId === 'string' ? sectionId : ''\n}\n\nexport function normalizeOpenAPISpecSectionIds(spec: OpenAPISpec): OpenAPISpec {\n const items = [\n ...Object.entries(spec.paths ?? {}).map(([path, pathItem]) => ({ path, pathItem, kind: 'path' as const })),\n ...Object.entries(((spec as Record<string, unknown>).webhooks ?? {}) as Record<string, unknown>).map(([path, pathItem]) => ({ path, pathItem, kind: 'webhook' as const })),\n ]\n\n for (const { path, pathItem, kind } of items) {\n if (!pathItem || typeof pathItem !== 'object') continue\n const operations = pathItem as Record<string, unknown>\n for (const method of OPENAPI_HTTP_METHODS) {\n const op = operations[method] as Record<string, unknown> | undefined\n if (!op || typeof op !== 'object') continue\n op[CLARIFY_OPENAPI_SECTION_ID_EXTENSION] = createOperationSectionId(op, method, path, kind)\n }\n }\n\n return spec\n}\n\n/** Filter an OpenAPI spec to only include paths that have at least one operation matching the given tags. */\nexport function filterSpecByTags(spec: OpenAPISpec, tags: string[]): OpenAPISpec {\n const paths = (spec.paths ?? {}) as Record<string, unknown>\n const webhooks = ((spec as Record<string, unknown>).webhooks ?? {}) as Record<string, unknown>\n return { ...spec, paths: filterPathItemsByTags(paths, tags), webhooks: filterPathItemsByTags(webhooks, tags) } as OpenAPISpec\n}\n\n/** Extract endpoint operations from an OpenAPI spec as page sections. */\nexport function extractOpenAPISections(spec: OpenAPISpec, filterTags?: string[]): ContentSection[] {\n normalizeOpenAPISpecSectionIds(spec)\n\n const sections: ContentSection[] = []\n const items = [\n ...Object.entries(spec.paths ?? {}).map(([path, pathItem]) => ({ path, pathItem, kind: 'path' })),\n ...Object.entries(((spec as Record<string, unknown>).webhooks ?? {}) as Record<string, unknown>).map(([path, pathItem]) => ({ path, pathItem, kind: 'webhook' })),\n ]\n for (const { path, pathItem, kind } of items) {\n if (!pathItem) continue\n const operations = pathItem as Record<string, unknown>\n for (const method of OPENAPI_HTTP_METHODS) {\n const op = operations[method] as Record<string, unknown> | undefined\n const tags = Array.isArray(op?.tags) ? op.tags as string[] : undefined\n if (!op || !operationMatchesTags(tags, filterTags)) continue\n const title = typeof op.summary === 'string' ? op.summary : `${method.toUpperCase()} ${path}`\n sections.push({ id: operationSectionId(op), title, level: 2, badge: kind === 'webhook' ? 'WEBHOOK' : method.toUpperCase(), tags })\n }\n }\n return sections\n}\n\nexport async function readOpenAPISpec(filePath: string, contentProcessor?: ContentProcessor, projectRoot?: string): Promise<OpenAPIParseResult> {\n try {\n if (!contentProcessor) return { ok: true, spec: await SwaggerParser.dereference(filePath) as OpenAPISpec }\n\n const source = readFileSync(filePath, 'utf-8')\n const transformedSource = await contentProcessor.processText(source, 'openapi', filePath)\n if (transformedSource === source) return { ok: true, spec: await SwaggerParser.dereference(filePath) as OpenAPISpec }\n\n return {\n ok: true,\n spec: await SwaggerParser.dereference(filePath, {\n resolve: {\n transformedOpenAPISource: {\n order: 1,\n canRead: (file: ResolverFileInfo) => isSameOpenAPIFile(file.url, filePath),\n read: () => transformedSource,\n },\n },\n }) as OpenAPISpec,\n }\n } catch (error) {\n return {\n ok: false,\n diagnostic: createContentDiagnostic({\n kind: 'openapi',\n title: 'OpenAPI spec parse failed',\n message: 'Clarify could not parse this OpenAPI specification.',\n error,\n filePath,\n projectRoot,\n }),\n }\n }\n}\n","import { join } from 'node:path'\n\nimport { pageVirtualModuleId } from '../../core/runtime/module-ids.js'\nimport { localizedRoutePath, openAPIPagePathFromRef, routeIntentFromPagesItem, withAlternates } from '../../parsers/routes/routes.js'\nimport type { ClarifyOpenAPIRouteIntent, ClarifyPagesConfig, ClarifyPagesItem, ContentRoute, OpenAPIContentRoute, ResolvedClarifyLocalesConfig, ResolvedProjectConfig } from '../../types.js'\n\nimport { findOpenAPIRoutes } from './parser.js'\n\nfunction collectOpenAPIPageIntents(config: ResolvedProjectConfig): ClarifyOpenAPIRouteIntent[] {\n const intents: ClarifyOpenAPIRouteIntent[] = []\n\n function visitItems(items: ClarifyPagesItem[]) {\n for (const item of items) {\n if (typeof item !== 'string' && 'group' in item) {\n visitItems(item.pages)\n continue\n }\n const intent = routeIntentFromPagesItem(item)\n if (intent.kind === 'openapi' && (intent.path || intent.tagFilter?.length)) intents.push(intent)\n }\n }\n\n function visitPages(pages?: ClarifyPagesConfig) {\n if (!pages || pages === 'FileTree') return\n for (const group of pages) visitItems(group.pages)\n }\n\n for (const tab of config.navigation?.tabs ?? []) visitPages(tab.pages)\n return intents\n}\n\nfunction cloneOpenAPIRoute(route: OpenAPIContentRoute, overrides: Partial<OpenAPIContentRoute> = {}): OpenAPIContentRoute {\n return {\n ...route,\n meta: { ...route.meta, sections: route.meta.sections ? [...route.meta.sections] : undefined },\n module: { ...route.module },\n source: { ...route.source },\n openapi: route.openapi ? { ...route.openapi, tagFilter: route.openapi.tagFilter ? [...route.openapi.tagFilter] : undefined } : undefined,\n alternates: route.alternates ? { ...route.alternates } : undefined,\n ...overrides,\n }\n}\n\nexport function discoverOpenAPIRoutes(contentRoot: string, locales?: ResolvedClarifyLocalesConfig): OpenAPIContentRoute[] {\n if (!locales) return findOpenAPIRoutes(contentRoot)\n\n const localizedRoutes: OpenAPIContentRoute[] = []\n for (const locale of locales.locales) {\n const localeRoot = join(contentRoot, locale.code)\n for (const route of findOpenAPIRoutes(localeRoot, localeRoot)) {\n const basePath = route.basePath ?? route.path\n const path = localizedRoutePath(basePath, locale.code, locales)\n localizedRoutes.push({\n ...route,\n path,\n basePath,\n locale: locale.code,\n module: { pageVirtualModuleId: pageVirtualModuleId(path) },\n })\n }\n }\n\n if (locales.missing !== 'fallback') return localizedRoutes\n\n const routeByLocaleAndBase = new Map(localizedRoutes.map(route => [`${route.locale ?? ''}:${route.basePath ?? route.path}`, route]))\n const defaultRoutes = localizedRoutes.filter(route => route.locale === locales.default)\n for (const sourceRoute of defaultRoutes) {\n const basePath = sourceRoute.basePath ?? sourceRoute.path\n for (const locale of locales.locales) {\n const key = `${locale.code}:${basePath}`\n if (routeByLocaleAndBase.has(key)) continue\n const path = localizedRoutePath(basePath, locale.code, locales)\n localizedRoutes.push(cloneOpenAPIRoute(sourceRoute, {\n path,\n locale: locale.code,\n module: { pageVirtualModuleId: pageVirtualModuleId(path) },\n isFallback: true,\n }))\n }\n }\n\n return localizedRoutes\n}\n\nexport function expandConfiguredOpenAPIRoutes(routes: ContentRoute[], config: ResolvedProjectConfig): ContentRoute[] {\n const openAPIIntents = collectOpenAPIPageIntents(config)\n if (!openAPIIntents.length) return routes\n\n const additions: OpenAPIContentRoute[] = []\n const existingKeys = new Set(routes.map(route => `${route.locale ?? ''}:${route.basePath ?? route.path}`))\n\n for (const intent of openAPIIntents) {\n const tagFilter = intent.tagFilter?.filter(Boolean)\n const sourceBasePath = openAPIPagePathFromRef(intent.ref)\n const targetBasePath = openAPIPagePathFromRef(intent.ref, tagFilter, intent.path)\n if (sourceBasePath === targetBasePath && !tagFilter?.length) continue\n\n for (const route of routes) {\n if (route.kind !== 'openapi' || (route.basePath ?? route.path) !== sourceBasePath) continue\n const key = `${route.locale ?? ''}:${targetBasePath}`\n if (existingKeys.has(key)) continue\n existingKeys.add(key)\n\n const path = route.locale && config.locales ? localizedRoutePath(targetBasePath, route.locale, config.locales) : targetBasePath\n additions.push(cloneOpenAPIRoute(route, {\n path,\n basePath: targetBasePath,\n module: { pageVirtualModuleId: pageVirtualModuleId(path) },\n openapi: { ...route.openapi, tagFilter: tagFilter?.length ? tagFilter : undefined },\n }))\n }\n }\n\n const nextRoutes = [...routes, ...additions]\n if (!config.locales) return nextRoutes\n\n const routesWithAlternates = nextRoutes.map(route => withAlternates(route, nextRoutes, config.locales!))\n const bareAliases: OpenAPIContentRoute[] = []\n const seenBare = new Set(routesWithAlternates.map(route => route.path))\n\n for (const route of routesWithAlternates) {\n if (route.kind !== 'openapi' || route.locale !== config.locales.default) continue\n const basePath = route.basePath ?? route.path\n if (basePath === route.path || seenBare.has(basePath)) continue\n seenBare.add(basePath)\n bareAliases.push(cloneOpenAPIRoute(route, {\n path: basePath,\n module: { pageVirtualModuleId: pageVirtualModuleId(basePath) },\n isBareAlias: true,\n }))\n }\n\n return [...routesWithAlternates, ...bareAliases]\n}\n","import { VIRTUAL_OPENAPI, VIRTUAL_OPENAPI_SERVER } from '../../core/runtime/virtual-modules.js'\nimport type { OpenAPISpec } from '../../types.js'\n\nexport const openApiRegistryModuleId = VIRTUAL_OPENAPI\nexport const openApiServerRegistryModuleId = VIRTUAL_OPENAPI_SERVER\nconst OPENAPI_SPEC_PREFIX = 'virtual:clarify/openapi-spec/'\n\nexport function specVirtualModuleId(specKey: string): string {\n return `${OPENAPI_SPEC_PREFIX}${specKey}`\n}\n\nexport function generateOpenAPIRegistryModule(openApiSpecs: Record<string, string>): string {\n const entries = Object.entries(openApiSpecs)\n .map(([key, moduleId]) => ` ${JSON.stringify(key)}: () => import(${JSON.stringify(moduleId)}),`)\n .join('\\n')\n return `export const openApiSpecs = {\\n${entries}\\n};`\n}\n\nexport function generateOpenAPIServerRegistryModule(openApiSpecs: Record<string, OpenAPISpec>): string {\n return `export const openApiSpecs = ${JSON.stringify(openApiSpecs)};`\n}\n\n/** Generate a virtual module that exports a single spec as default. */\nexport function generateOpenAPISpecModule(spec: OpenAPISpec): string {\n return `export default ${JSON.stringify(spec)};`\n}\n\ntype OpenAPIPageModuleOptions = {\n specModuleId: string\n}\n\nexport function generateOpenAPIPageModule(opts: OpenAPIPageModuleOptions): string {\n return `import { createOpenApiRouteComponent } from '@clarify-labs/renderer';\nimport spec from ${JSON.stringify(opts.specModuleId)};\n\nexport const routeData = {};\n\nexport default createOpenApiRouteComponent({ ...routeData, spec });\n`\n}\n","import { relative } from 'node:path'\n\nimport { pageVirtualModuleId } from '../../core/runtime/module-ids.js'\nimport { generateContentDiagnosticModule, type VirtualModules } from '../../core/runtime/virtual-modules.js'\nimport { createProjectContentProcessor } from '../../parsers/content/content.js'\nimport type { ClarifyHookContext, ContentRoute, OpenAPISpec } from '../../types.js'\n\nimport { extractOpenAPISections, filterSpecByTags, normalizeOpenAPISpecSectionIds, readOpenAPISpec } from './parser.js'\nimport { generateOpenAPIPageModule, generateOpenAPIRegistryModule, generateOpenAPIServerRegistryModule, generateOpenAPISpecModule, openApiRegistryModuleId, openApiServerRegistryModuleId, specVirtualModuleId } from './virtual-modules.js'\n\nfunction sourceSpecIdFromPath(filePath: string, projectRoot: string): string {\n return relative(projectRoot, filePath).replace(/[^a-zA-Z0-9_-]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '')\n}\n\nfunction routeSpecModuleIdFromSourceSpecId(sourceSpecId: string, tagFilter?: string[]): string {\n if (!tagFilter?.length) return sourceSpecId\n const suffix = tagFilter.map(tag => tag.replace(/[^a-zA-Z0-9_-]/g, '_').replace(/_+/g, '_').replace(/^_|_$/g, '') || 'tag').join('_')\n return `${sourceSpecId}_tags_${suffix}`\n}\n\nfunction openAPIRegistryKeys(route: ContentRoute): string[] {\n const keys = new Set<string>()\n const path = (route.path || '/').replace(/^\\//, '')\n const base = (route.basePath ?? route.path).replace(/^\\//, '')\n\n if (route.locale) keys.add(pageVirtualModuleId(`${route.locale}/${base}`))\n keys.add(pageVirtualModuleId(path))\n if (!route.locale && base) keys.add(pageVirtualModuleId(base))\n\n return [...keys]\n}\n\nexport class OpenAPIPluginState {\n private readonly specModules = new Map<string, OpenAPISpec>()\n\n async enrichRoutes(routes: ContentRoute[], ctx: ClarifyHookContext): Promise<ContentRoute[]> {\n this.specModules.clear()\n const specByFilePath = new Map<string, OpenAPISpec>()\n\n for (const route of routes) {\n if (route.kind !== 'openapi') continue\n const specFromCache = specByFilePath.get(route.source.filePath)\n const processor = createProjectContentProcessor(ctx.plugins, ctx)\n const result = specFromCache\n ? { ok: true as const, spec: specFromCache }\n : await readOpenAPISpec(route.source.filePath, processor, ctx.generateOptions.projectRoot)\n if (!result.ok) {\n route.diagnostic = result.diagnostic\n route.meta.title = route.meta.title || 'OpenAPI parse error'\n route.meta.sections = []\n continue\n }\n\n const spec = normalizeOpenAPISpecSectionIds(result.spec)\n specByFilePath.set(route.source.filePath, spec)\n const sourceSpecId = sourceSpecIdFromPath(route.source.filePath, ctx.generateOptions.projectRoot)\n route.openapi = { ...route.openapi, sourceSpecId }\n\n route.meta.title = spec.info?.title ?? route.meta.title\n route.meta.description = spec.info?.description ?? route.meta.description\n route.meta.sections = extractOpenAPISections(spec, route.openapi.tagFilter)\n\n const pageSpec = route.openapi.tagFilter?.length ? filterSpecByTags(spec, route.openapi.tagFilter) : spec\n const routeSpecModuleId = routeSpecModuleIdFromSourceSpecId(sourceSpecId, route.openapi.tagFilter)\n route.openapi.routeSpecModuleId = routeSpecModuleId\n this.specModules.set(routeSpecModuleId, pageSpec)\n route.source.content = JSON.stringify(pageSpec)\n }\n\n return routes\n }\n\n contributeModules(modules: VirtualModules, routes: ContentRoute[]): VirtualModules {\n const registryEntries: Record<string, string> = {}\n const serverRegistryEntries: Record<string, OpenAPISpec> = {}\n\n for (const route of routes) {\n if (route.kind !== 'openapi' || !route.openapi?.sourceSpecId) continue\n const routeSpecModuleId = route.openapi.routeSpecModuleId ?? route.openapi.sourceSpecId\n const spec = this.specModules.get(routeSpecModuleId)\n if (!spec) continue\n\n for (const registryKey of openAPIRegistryKeys(route)) {\n registryEntries[registryKey] = specVirtualModuleId(routeSpecModuleId)\n serverRegistryEntries[registryKey] = spec\n }\n }\n\n modules.set(openApiRegistryModuleId, generateOpenAPIRegistryModule(registryEntries))\n modules.set(openApiServerRegistryModuleId, generateOpenAPIServerRegistryModule(serverRegistryEntries))\n for (const [routeSpecModuleId, spec] of this.specModules) {\n modules.set(specVirtualModuleId(routeSpecModuleId), generateOpenAPISpecModule(spec))\n }\n\n for (const route of routes) {\n if (route.kind !== 'openapi') continue\n if (route.diagnostic) {\n modules.set(route.module.pageVirtualModuleId, generateContentDiagnosticModule(route.diagnostic))\n continue\n }\n if (!route.openapi?.sourceSpecId) continue\n const routeSpecModuleId = route.openapi.routeSpecModuleId ?? route.openapi.sourceSpecId\n if (!this.specModules.has(routeSpecModuleId)) continue\n modules.set(route.module.pageVirtualModuleId, generateOpenAPIPageModule({\n specModuleId: specVirtualModuleId(routeSpecModuleId),\n }))\n }\n\n return modules\n }\n}\n","import type { ClarifyPlugin } from '../../types.js'\n\nimport { discoverOpenAPIRoutes, expandConfiguredOpenAPIRoutes } from './routes.js'\nimport { OpenAPIPluginState } from './state.js'\n\nexport function createOpenAPIPlugin(): ClarifyPlugin {\n const state = new OpenAPIPluginState()\n\n return {\n name: 'clarify:openapi',\n hooks: {\n 'routes:discover': (input, ctx) => ({\n ...input,\n routes: [...input.routes, ...discoverOpenAPIRoutes(input.contentRoot, ctx.projectConfig.locales)],\n }),\n 'routes:discovered': async (routes, ctx) => {\n const expandedRoutes = expandConfiguredOpenAPIRoutes(routes, ctx.projectConfig)\n return state.enrichRoutes(expandedRoutes, ctx)\n },\n 'modules:before': (modules, ctx) => state.contributeModules(modules, ctx.routes),\n },\n }\n}\n","import { mkdtempSync, rmSync } from 'node:fs'\nimport { tmpdir } from 'node:os'\nimport { join } from 'node:path'\n\nexport function createClarifyTempDir(name: string): string {\n return mkdtempSync(join(tmpdir(), `clarify-${name}-`))\n}\n\nexport function removeClarifyTempDir(path: string | undefined): void {\n if (!path) return\n rmSync(path, { recursive: true, force: true })\n}\n","export function toPagefindLanguage(locale: string | undefined): string {\n const normalizedLocale = locale\n ?.trim()\n .replace(/_/g, '-')\n .split('-')\n .filter(Boolean)\n .join('-')\n // Pagefind's browser runtime lowercases the detected <html lang> value\n // before resolving the language-specific index. Keep Clarify's public\n // locale codes canonical (for example en-US / zh-CN), but use lowercase\n // BCP 47 tags internally so custom dev indexes match Pagefind runtime.\n .toLowerCase()\n\n return normalizedLocale || 'en'\n}\n","import { createReadStream, existsSync } from 'node:fs'\nimport { extname, join, relative, resolve } from 'node:path'\n\nimport type { ViteDevServer } from 'vite'\n\nimport { createClarifyTempDir, removeClarifyTempDir } from '../../core/project/temp-dir.js'\nimport type { ClarifyHookContext, ClarifyPlugin } from '../../types.js'\nimport { routeSearchContent } from '../mcp-search/orama-index.js'\n\nimport { toPagefindLanguage } from './search-language.js'\n\ntype PagefindModule = typeof import('pagefind')\n\ntype GeneratePagefindIndexOptions = {\n outputRoot: string\n sourceRoot?: string\n}\n\nconst pagefindContentTypes: Record<string, string> = {\n '.css': 'text/css; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.wasm': 'application/wasm',\n}\n\nfunction assertNoPagefindErrors(action: string, errors: string[] | undefined): void {\n if (!errors?.length) return\n throw new Error(`[clarify] Pagefind ${action} failed:\\n${errors.join('\\n')}`)\n}\n\nasync function generatePagefindIndex(options: GeneratePagefindIndexOptions, pagefind?: PagefindModule): Promise<number> {\n const runtime = pagefind ?? (await import('pagefind') as PagefindModule)\n const { errors, index } = await runtime.createIndex({\n excludeSelectors: [\n '[data-pagefind-ignore]',\n 'script',\n 'style',\n 'svg',\n ],\n includeCharacters: '._-/#:@',\n keepIndexUrl: false,\n verbose: false,\n writePlayground: false,\n })\n\n assertNoPagefindErrors('createIndex', errors)\n if (!index) throw new Error('[clarify] Pagefind did not create an index.')\n\n try {\n const addResult = await index.addDirectory({ path: options.sourceRoot ?? options.outputRoot, glob: '**/*.html' })\n assertNoPagefindErrors('addDirectory', addResult.errors)\n\n const writeResult = await index.writeFiles({ outputPath: join(options.outputRoot, 'pagefind') })\n assertNoPagefindErrors('writeFiles', writeResult.errors)\n\n return addResult.page_count\n } finally {\n await index.deleteIndex()\n if (!pagefind) {\n await runtime.close()\n }\n }\n}\n\nasync function generateDevSearchIndex(ctx: ClarifyHookContext, root: string, pagefind: PagefindModule): Promise<void> {\n const { errors, index } = await pagefind.createIndex({\n includeCharacters: '._-/#:@',\n keepIndexUrl: false,\n verbose: false,\n writePlayground: false,\n })\n\n assertNoPagefindErrors('createIndex', errors)\n if (!index) throw new Error('[clarify] Pagefind did not create an index.')\n\n try {\n let pageCount = 0\n for (const route of ctx.routes) {\n // Skip bare alias routes (e.g., /path) to avoid indexing duplicates in multilingual sites\n // Only index the full path with locale prefix (e.g., /locale/path)\n if (route.isBareAlias) continue\n \n const content = routeSearchContent(route)\n if (!content.trim()) continue\n const result = await index.addCustomRecord({\n url: route.path,\n content,\n language: toPagefindLanguage(route.locale ?? ctx.projectConfig.locales?.default),\n meta: {\n title: route.meta.title,\n },\n })\n assertNoPagefindErrors(`addCustomRecord ${route.path}`, result.errors)\n pageCount += 1\n }\n\n const writeResult = await index.writeFiles({ outputPath: join(root, 'pagefind') })\n assertNoPagefindErrors('writeFiles', writeResult.errors)\n console.log(`[clarify] Dev search index generated for ${pageCount} pages.`)\n } finally {\n await index.deleteIndex()\n }\n}\n\nfunction normalizeDevPagefindPath(rawUrl: string | undefined, routePrefix: string): string | undefined {\n const pathname = rawUrl?.split('?')[0]\n if (!pathname) return undefined\n\n const normalizedPrefix = routePrefix && routePrefix !== '/' ? `/${routePrefix.replace(/^\\/+|\\/+$/g, '')}` : ''\n const pagefindPath = normalizedPrefix && pathname.startsWith(`${normalizedPrefix}/pagefind/`)\n ? pathname.slice(normalizedPrefix.length)\n : pathname\n\n return pagefindPath.startsWith('/pagefind/') ? pagefindPath : undefined\n}\n\nfunction serveDevPagefind(server: ViteDevServer, getRoot: () => string | undefined, ctx: ClarifyHookContext): void {\n server.middlewares.use((req, res, next) => {\n const root = getRoot()\n const pagefindPath = normalizeDevPagefindPath(req.url, ctx.projectConfig.routePrefix)\n if (!root || !pagefindPath) {\n next()\n return\n }\n\n const filePath = join(root, pagefindPath)\n const relativePath = relative(root, filePath)\n if (relativePath.startsWith('..') || relativePath === '' || !existsSync(filePath)) {\n next()\n return\n }\n\n const contentType = pagefindContentTypes[extname(filePath)] ?? 'application/octet-stream'\n res.setHeader('Content-Type', contentType)\n createReadStream(filePath).pipe(res)\n })\n}\n\nexport function createPageSearchPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:page-search',\n hooks: {\n async 'dev:configureServer'(server, ctx) {\n if (!ctx.projectConfig.features.search.enabled) return\n const pagefind = await import('pagefind') as PagefindModule\n let currentRoot: string | undefined\n const staleRoots = new Set<string>()\n\n const replaceDevIndex = async () => {\n const nextRoot = createClarifyTempDir('pagefind')\n await generateDevSearchIndex(ctx, nextRoot, pagefind)\n const previousRoot = currentRoot\n currentRoot = nextRoot\n if (previousRoot) {\n staleRoots.add(previousRoot)\n setTimeout(() => {\n staleRoots.delete(previousRoot)\n removeClarifyTempDir(previousRoot)\n }, 30_000).unref?.()\n }\n }\n\n serveDevPagefind(server, () => currentRoot, ctx)\n await replaceDevIndex()\n\n let regenerateTimer: ReturnType<typeof setTimeout> | undefined\n const regenerate = (filePath: string) => {\n if (!/\\.(md|mdx|json|ya?ml)$/i.test(filePath)) return\n if (regenerateTimer) clearTimeout(regenerateTimer)\n regenerateTimer = setTimeout(() => {\n void replaceDevIndex().catch((err: unknown) => {\n console.error('[clarify] Failed to regenerate dev search index:', err)\n })\n }, 100)\n }\n\n server.watcher.on('add', regenerate)\n server.watcher.on('change', regenerate)\n server.watcher.on('unlink', regenerate)\n\n server.httpServer?.once('close', () => {\n if (regenerateTimer) clearTimeout(regenerateTimer)\n removeClarifyTempDir(currentRoot)\n for (const staleRoot of staleRoots) removeClarifyTempDir(staleRoot)\n void pagefind.close().catch(() => undefined)\n })\n },\n async 'build:done'(ctx) {\n if (!ctx.projectConfig.features.search.enabled) return\n const outputDirectory = ctx.generateOptions.outputDirectory\n if (!outputDirectory) return\n\n const outputRoot = resolve(ctx.generateOptions.projectRoot, outputDirectory)\n const pageCount = await generatePagefindIndex({ outputRoot })\n console.log(`[clarify] Page search index generated for ${pageCount} pages.`)\n },\n },\n }\n}\n","import type { ContentRoute, ResolvedProjectConfig } from '../../types.js'\n\nfunction trimTrailingSlash(value: string): string {\n return value.replace(/\\/+$/, '')\n}\n\nfunction normalizeRoutePrefix(routePrefix: string): string {\n if (!routePrefix || routePrefix === '/') return ''\n return `/${routePrefix.replace(/^\\/+|\\/+$/g, '')}`\n}\n\nfunction routeUrl(siteUrl: string, routePrefix: string, routePath: string): string {\n const base = trimTrailingSlash(siteUrl)\n const prefix = normalizeRoutePrefix(routePrefix)\n const path = routePath === '/' ? '' : routePath.replace(/^\\/+/, '/')\n return `${base}${prefix}${path}` || base\n}\n\nfunction escapeXml(value: string): string {\n return value\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''')\n}\n\nfunction publicRoutes(routes: ContentRoute[]): ContentRoute[] {\n // Exclude 404 routes and bare alias routes (e.g., /path without language prefix) in multilingual sites\n return routes.filter(route => route.path !== '/404' && !route.isBareAlias)\n}\n\nexport function createSitemapXml(routes: ContentRoute[], config: ResolvedProjectConfig): string | undefined {\n if (!config.siteUrl) return undefined\n\n const urls = publicRoutes(routes)\n .map(route => routeUrl(config.siteUrl!, config.routePrefix, route.path))\n .filter((url, index, list) => list.indexOf(url) === index)\n .sort()\n\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">',\n ...urls.map(url => ` <url><loc>${escapeXml(url)}</loc></url>`),\n '</urlset>',\n '',\n ].join('\\n')\n}\n\nexport function createRobotsTxt(config: ResolvedProjectConfig): string | undefined {\n if (!config.siteUrl) return undefined\n const sitemapUrl = routeUrl(config.siteUrl, config.routePrefix, '/sitemap.xml')\n return [\n 'User-agent: *',\n 'Allow: /',\n `Sitemap: ${sitemapUrl}`,\n '',\n ].join('\\n')\n}\n","import type { ClarifyEmitAsset, ClarifyPlugin } from '../../types.js'\n\nimport { createRobotsTxt, createSitemapXml } from './artifacts.js'\n\nexport function createSeoPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:seo',\n hooks: {\n 'build:assets'(ctx) {\n const assets: ClarifyEmitAsset[] = []\n const sitemap = createSitemapXml(ctx.routes, ctx.projectConfig)\n const robots = createRobotsTxt(ctx.projectConfig)\n if (sitemap) assets.push({ fileName: 'sitemap.xml', source: sitemap })\n if (robots) assets.push({ fileName: 'robots.txt', source: robots })\n return assets\n },\n },\n }\n}\n","import { relative } from 'node:path'\n\nimport type { ClarifyRepositoryConfig, ContentRoute } from '../../types.js'\n\nfunction trimSlashes(value: string): string {\n return value.replace(/^\\/+|\\/+$/g, '')\n}\n\nfunction normalizeRepositoryUrl(repository: string): string {\n return repository.replace(/\\.git$/, '').replace(/\\/+$/, '')\n}\n\nfunction encodePath(path: string): string {\n return path\n .split('/')\n .filter(Boolean)\n .map(segment => encodeURIComponent(segment))\n .join('/')\n}\n\nexport function createSourceEditUrl(filePath: string, contentRoot: string, source: ClarifyRepositoryConfig): string {\n if (!source.url) return ''\n const repository = normalizeRepositoryUrl(source.url)\n const branch = source.branch ?? 'main'\n const directory = source.directory ? trimSlashes(source.directory) : ''\n const relativePath = relative(contentRoot, filePath).replaceAll('\\\\', '/')\n const sourcePath = [directory, relativePath].filter(Boolean).join('/')\n return `${repository}/edit/${encodeURIComponent(branch)}/${encodePath(sourcePath)}`\n}\n\nexport function attachSourceEditUrls(routes: ContentRoute[], contentRoot: string, source?: ClarifyRepositoryConfig): void {\n if (!source) return\n for (const route of routes) {\n route.source = {\n ...route.source,\n sourceEditUrl: createSourceEditUrl(route.source.filePath, contentRoot, source),\n }\n }\n}\n","import { join } from 'node:path'\n\nimport type { ClarifyPlugin } from '../../types.js'\n\nimport { attachSourceEditUrls } from './source-links.js'\n\nexport function createSourceLinksPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:source-links',\n hooks: {\n 'routes:discovered': (routes, ctx) => {\n if (!ctx.projectConfig.features.repository.enabled) return routes\n const contentRoot = join(ctx.generateOptions.projectRoot, ctx.generateOptions.rootDirectory)\n attachSourceEditUrls(routes, contentRoot, ctx.projectConfig.features.repository)\n return routes\n },\n },\n }\n}\n","import type { ClarifyVariablesConfig, ClarifyVariableValue, ClarifyPlugin } from '../../types.js'\n\nconst variablePattern = /{{\\s*([A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*)\\s*}}/g\n\nfunction getVariableValue(variables: ClarifyVariablesConfig, path: string): ClarifyVariableValue | undefined {\n let current: ClarifyVariableValue | undefined = variables\n for (const segment of path.split('.')) {\n if (!current || typeof current !== 'object' || Array.isArray(current)) return undefined\n current = current[segment]\n }\n return current\n}\n\nfunction stringifyVariableValue(variables: ClarifyVariablesConfig, path: string, stack: string[]): string | undefined {\n if (stack.includes(path)) {\n throw new Error(`[clarify] variable \"${path}\" contains a circular reference: ${[...stack, path].join(' -> ')}`)\n }\n\n const value = getVariableValue(variables, path)\n if (value === undefined || typeof value === 'object') return undefined\n if (typeof value !== 'string') return String(value)\n\n return value.replace(variablePattern, (match, nestedPath: string) => stringifyVariableValue(variables, nestedPath, [...stack, path]) ?? match)\n}\n\nexport function applyVariables(content: string, variables: ClarifyVariablesConfig = {}): string {\n return content.replace(variablePattern, (match, path: string) => stringifyVariableValue(variables, path, []) ?? match)\n}\n\nfunction applyVariablesToFrontmatter(frontmatter: Record<string, unknown>, variables: ClarifyVariablesConfig): Record<string, unknown> {\n const nextFrontmatter = { ...frontmatter }\n for (const key of ['title', 'description'] as const) {\n if (typeof nextFrontmatter[key] !== 'string') continue\n nextFrontmatter[key] = applyVariables(nextFrontmatter[key], variables)\n }\n return nextFrontmatter\n}\n\nexport function createVariablesPlugin(): ClarifyPlugin {\n return {\n name: 'clarify:variables',\n hooks: {\n 'content:transform': (input, ctx) => ({\n ...input,\n frontmatter: applyVariablesToFrontmatter(input.frontmatter, ctx.projectConfig.variables),\n content: applyVariables(input.content, ctx.projectConfig.variables),\n }),\n },\n }\n}\n","import { createContentArtifactsPlugin } from '../../plugins/content-artifacts/index.js'\nimport { createHtmlShellPlugin } from '../../plugins/html-shell/index.js'\nimport { createMcpSearchPlugin } from '../../plugins/mcp-search/index.js'\nimport { createOpenAPIPlugin } from '../../plugins/openapi/index.js'\nimport { createPageSearchPlugin } from '../../plugins/page-search/index.js'\nimport { createSeoPlugin } from '../../plugins/seo/index.js'\nimport { createSourceLinksPlugin } from '../../plugins/source-links/index.js'\nimport { createVariablesPlugin } from '../../plugins/variables/index.js'\nimport type { ClarifyPlugin } from '../../types.js'\n\nexport type BuiltinPluginOptions = {\n htmlShell?: boolean\n}\n\nexport function createBuiltinPlugins(options: BuiltinPluginOptions = {}): ClarifyPlugin[] {\n // Core site discovery (content scanning, i18n fallback routes) and\n // navigation building are handled directly by the Engine, not as plugins.\n // The remaining plugins provide optional functionality (variables, OpenAPI,\n // SEO, search, etc.) and can be augmented or replaced by user plugins.\n const plugins = [\n createVariablesPlugin(),\n createOpenAPIPlugin(),\n createSourceLinksPlugin(),\n createContentArtifactsPlugin(),\n createSeoPlugin(),\n createPageSearchPlugin(),\n createMcpSearchPlugin(),\n ]\n if (options.htmlShell ?? true) plugins.push(createHtmlShellPlugin())\n return plugins\n}\n","import type { ClarifyPlugin } from '../../types.js'\nimport type { ClarifyBuildOptions } from '../config/options.js'\n\nimport { createBuiltinPlugins, type BuiltinPluginOptions } from './builtin.js'\n\nexport type LoadPluginsOptions = BuiltinPluginOptions & {\n userPlugins?: ClarifyPlugin[]\n}\n\nfunction pluginWeight(plugin: ClarifyPlugin): number {\n const enforceWeight = plugin.enforce === 'pre'\n ? 1_000_000\n : plugin.enforce === 'post'\n ? -1_000_000\n : 0\n return enforceWeight + (plugin.priority ?? 0)\n}\n\nexport function sortPlugins(plugins: ClarifyPlugin[]): ClarifyPlugin[] {\n const entries = plugins.map((plugin, index) => ({ plugin, index }))\n const byName = new Map<string, ClarifyPlugin>()\n for (const { plugin } of entries) {\n if (byName.has(plugin.name)) throw new Error(`[clarify] Duplicate plugin name: ${plugin.name}`)\n byName.set(plugin.name, plugin)\n }\n\n const sortedByWeight = [...entries].sort((left, right) => {\n const weightDiff = pluginWeight(right.plugin) - pluginWeight(left.plugin)\n return weightDiff === 0 ? left.index - right.index : weightDiff\n })\n const visitOrder = new Map(sortedByWeight.map((entry, index) => [entry.plugin.name, index]))\n const visiting = new Set<string>()\n const visited = new Set<string>()\n const sorted: ClarifyPlugin[] = []\n\n function visit(plugin: ClarifyPlugin): void {\n if (visited.has(plugin.name)) return\n if (visiting.has(plugin.name)) throw new Error(`[clarify] Circular plugin dependency detected: ${plugin.name}`)\n\n visiting.add(plugin.name)\n const dependencies = [...(plugin.dependsOn ?? [])].sort((left, right) => (visitOrder.get(left) ?? 0) - (visitOrder.get(right) ?? 0))\n for (const dependencyName of dependencies) {\n const dependency = byName.get(dependencyName)\n if (!dependency) throw new Error(`[clarify] Plugin ${plugin.name} depends on missing plugin: ${dependencyName}`)\n visit(dependency)\n }\n visiting.delete(plugin.name)\n visited.add(plugin.name)\n sorted.push(plugin)\n }\n\n for (const { plugin } of sortedByWeight) visit(plugin)\n return sorted\n}\n\nexport function loadPlugins(options: LoadPluginsOptions = {}): ClarifyPlugin[] {\n return sortPlugins([\n ...createBuiltinPlugins({ htmlShell: options.htmlShell }),\n ...(options.userPlugins ?? []),\n ])\n}\n\nexport function loadBuildPlugins(options: ClarifyBuildOptions = {}, pluginOptions: BuiltinPluginOptions = {}): ClarifyPlugin[] {\n return loadPlugins({\n ...pluginOptions,\n userPlugins: options.plugins,\n })\n}\n","import { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport type { ConfigEnv } from 'vite'\n\nimport { cliPackageVersion } from '../../cli/package.js'\nimport type { ClarifyProjectContext } from '../../types.js'\nimport { resolveProjectConfig } from '../config/config.js'\nimport { resolveBuildOptions, type ClarifyBuildOptions, type ResolvedBuildOptions } from '../config/options.js'\nimport { findClarifyConfigFile, loadClarifyConfig, type ClarifyConfig } from '../config/user-config.js'\n\nexport type ResolvedProjectContext = {\n projectRoot: string\n contentRoot: string\n config: ClarifyConfig\n configFilePath?: string\n buildOptions: ResolvedBuildOptions\n resolvedOptions: ClarifyBuildOptions\n projectContext: ClarifyProjectContext\n projectConfig: ReturnType<typeof resolveProjectConfig>\n}\n\nexport async function resolveProjectContext(options: ClarifyBuildOptions = {}, env: ConfigEnv = { command: 'build', mode: 'production' }): Promise<ResolvedProjectContext> {\n const projectRoot = resolve(options.projectRoot ?? process.cwd())\n const initialBuildOptions = resolveBuildOptions(options)\n const configFilePath = findClarifyConfigFile(projectRoot)\n const config = configFilePath && existsSync(configFilePath)\n ? await loadClarifyConfig(projectRoot, env)\n : {}\n\n const mergedOptions: ClarifyBuildOptions = {\n ...config,\n ...options,\n projectRoot,\n rootDirectory: options.rootDirectory ?? initialBuildOptions.rootDirectory,\n outputDirectory: options.outputDirectory ?? initialBuildOptions.outputDirectory,\n }\n const resolvedProjectConfig = resolveProjectConfig(mergedOptions)\n const resolvedBuildOptions = resolveBuildOptions(mergedOptions)\n const contentRoot = join(projectRoot, resolvedBuildOptions.rootDirectory)\n\n const projectContext: ClarifyProjectContext = {\n projectRoot,\n contentRoot,\n version: cliPackageVersion,\n projectConfig: resolvedProjectConfig,\n generateOptions: resolvedBuildOptions,\n }\n\n return {\n projectRoot,\n contentRoot,\n configFilePath,\n projectConfig: resolvedProjectConfig,\n buildOptions: resolvedBuildOptions,\n resolvedOptions: mergedOptions,\n config,\n projectContext,\n }\n}\n","import type { ContentRoute } from '../../types.js'\n\nexport type RouteConflictKind = 'path' | 'page-module'\n\nexport type RouteConflict = {\n kind: RouteConflictKind\n key: string\n label: string\n routes: ContentRoute[]\n}\n\nfunction routeDescription(route: ContentRoute): string {\n return `${route.kind} ${route.source.filePath}`\n}\n\nfunction collectConflicts(routes: ContentRoute[], keyOf: (route: ContentRoute) => string): Map<string, ContentRoute[]> {\n const grouped = new Map<string, ContentRoute[]>()\n for (const route of routes) {\n const key = keyOf(route)\n grouped.set(key, [...(grouped.get(key) ?? []), route])\n }\n return grouped\n}\n\nexport function describeRouteConflict(route: ContentRoute): string {\n return routeDescription(route)\n}\n\nexport function findRouteConflicts(routes: ContentRoute[]): RouteConflict[] {\n const conflicts: RouteConflict[] = []\n\n for (const [path, pathRoutes] of collectConflicts(routes, route => route.path)) {\n if (pathRoutes.length < 2) continue\n conflicts.push({ kind: 'path', key: path, label: `path ${path}`, routes: pathRoutes })\n }\n\n for (const [pageModuleId, moduleRoutes] of collectConflicts(routes, route => route.module.pageVirtualModuleId)) {\n if (moduleRoutes.length < 2) continue\n if (moduleRoutes.every(route => route.path === moduleRoutes[0]!.path)) continue\n conflicts.push({ kind: 'page-module', key: pageModuleId, label: `page module ${pageModuleId}`, routes: moduleRoutes })\n }\n\n return conflicts\n}\n\nexport function formatRouteConflicts(conflicts: RouteConflict[]): string {\n return conflicts\n .map(conflict => `- ${conflict.label}: ${conflict.routes.map(describeRouteConflict).join(', ')}`)\n .join('\\n')\n}\n","import { applyConfiguredPageRoutePaths, buildLocalizedNavigationFromTabsConfig, buildNavigation, buildNavigationFromTabsConfig } from '../../parsers/routes/routes.js'\nimport type { ClarifyHookContext, ClarifyPage, ClarifyPlugin, ContentDiagnostic, ContentRoute, NavigationTree } from '../../types.js'\nimport { runHooks } from '../plugin/hooks.js'\n\nimport { describeRouteConflict, findRouteConflicts, formatRouteConflicts, type RouteConflict } from './route-analysis.js'\n\nexport async function resolveRoutePages(routes: ContentRoute[], plugins: ClarifyPlugin[], ctx: ClarifyHookContext): Promise<ContentRoute[]> {\n const routeToken = Symbol('clarifyRouteToken')\n type RoutedPage = ClarifyPage & { [routeToken]: number }\n\n const pages = routes.map<RoutedPage>((route, routeIndex) => ({\n path: route.path,\n filePath: route.source.filePath,\n frontmatter: route.source.frontmatter ?? {},\n content: route.source.content ?? '',\n [routeToken]: routeIndex,\n }))\n const resolvedPages = await runHooks(plugins, 'pages:resolved', pages, ctx)\n const pageByRouteIndex = new Map<number, ClarifyPage>()\n\n for (const page of resolvedPages) {\n const routeIndex = (page as RoutedPage)[routeToken]\n if (!Number.isInteger(routeIndex) || routeIndex < 0 || routeIndex >= routes.length) {\n throw new Error('[clarify] pages:resolved hooks must preserve each page route identity')\n }\n if (pageByRouteIndex.has(routeIndex)) {\n throw new Error('[clarify] pages:resolved hooks returned the same page route identity more than once')\n }\n pageByRouteIndex.set(routeIndex, page)\n }\n\n if (pageByRouteIndex.size !== routes.length) {\n throw new Error('[clarify] pages:resolved hooks must return exactly one page for each route')\n }\n\n return routes.map((route, routeIndex) => {\n const page = pageByRouteIndex.get(routeIndex)!\n return {\n ...route,\n source: {\n ...route.source,\n frontmatter: page.frontmatter,\n content: page.content,\n },\n }\n })\n}\n\nfunction buildNavigationTree(routes: ContentRoute[], ctx: ClarifyHookContext): NavigationTree {\n const tabs = ctx.projectConfig.navigation?.tabs\n if (!tabs) return { kind: 'flat', nodes: buildNavigation(routes) }\n if (!ctx.projectConfig.locales) return buildNavigationFromTabsConfig(routes, tabs)\n return buildLocalizedNavigationFromTabsConfig(routes, tabs, ctx.projectConfig.locales)\n ?? { kind: 'localized-tabbed', locales: {} }\n}\n\nexport function assertNoRouteConflicts(routes: ContentRoute[]): void {\n const conflicts = findRouteConflicts(routes)\n if (conflicts.length > 0) {\n throw new Error(`[clarify] Route conflicts prevent the site from being built:\\n${formatRouteConflicts(conflicts)}`)\n }\n}\n\nfunction createRouteConflictDiagnostic(label: string, routes: ContentRoute[]): ContentDiagnostic {\n return {\n kind: 'route-load',\n title: 'Route conflict',\n message: `This page cannot be rendered because ${label} is used by multiple routes.`,\n details: routes.map(describeRouteConflict).join('\\n'),\n }\n}\n\nexport function createDevRouteConflictRoutes(routes: ContentRoute[]): ContentRoute[] {\n const conflicts = findRouteConflicts(routes)\n if (conflicts.length === 0) return routes\n\n const conflictedRoutes = new Map<ContentRoute, RouteConflict>()\n for (const conflict of conflicts) {\n for (const route of conflict.routes) conflictedRoutes.set(route, conflict)\n }\n\n function createConflictRoute<T extends ContentRoute>(route: T, conflict: RouteConflict): T {\n return {\n ...route,\n module: { ...route.module, pageVirtualModuleId: `${route.module.pageVirtualModuleId}__conflict` },\n diagnostic: createRouteConflictDiagnostic(conflict.label, conflict.routes),\n }\n }\n\n const usedPaths = new Set<string>()\n return routes.flatMap(route => {\n const conflict = conflictedRoutes.get(route)\n if (!conflict) return [route]\n if (usedPaths.has(route.path)) return []\n usedPaths.add(route.path)\n return [createConflictRoute(route, conflict)]\n })\n}\n\nfunction handleRouteConflicts(routes: ContentRoute[], development: boolean): ContentRoute[] {\n if (development) return createDevRouteConflictRoutes(routes)\n assertNoRouteConflicts(routes)\n return routes\n}\n\nexport async function resolveRouteState(routes: ContentRoute[], plugins: ClarifyPlugin[], ctx: ClarifyHookContext, development: boolean): Promise<{ routes: ContentRoute[], navigation: NavigationTree }> {\n const tabs = ctx.projectConfig.navigation?.tabs\n const configuredRoutes = applyConfiguredPageRoutePaths(routes, tabs, ctx.projectConfig.locales)\n const navigation = buildNavigationTree(configuredRoutes, ctx)\n const resolved = await runHooks(plugins, 'routes:resolved', { routes: configuredRoutes, navigation }, ctx)\n const finalRoutes = handleRouteConflicts(resolved.routes, development)\n\n return {\n routes: finalRoutes,\n navigation: finalRoutes === resolved.routes ? resolved.navigation : buildNavigationTree(finalRoutes, ctx),\n }\n}\n","import { existsSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport type { ClarifyPlugin } from '../../types.js'\n\nconst GENERATED_FILE_NAME = 'clarify-env.d.ts'\n\n/**\n * Template for the generated `clarify-env.d.ts` file.\n * Edit this template directly if you need to change the type declarations.\n * This avoids the complexity of reading external files at runtime after bundling.\n */\nconst CLARIFY_ENV_TEMPLATE = `// This file is generated by Clarify. Do not edit it manually.\n// It provides ambient type declarations for Clarify virtual modules used in\n// plugin and slot code, so the TypeScript language service can resolve them.\n\ndeclare module 'virtual:clarify/slot' {\n import type { UISlotContext } from '@clarify-labs/cli'\n\n export function useSlot(): UISlotContext\n}\n`\n\nexport function generateClarifyEnvDts(_plugins: ClarifyPlugin[]): string {\n return CLARIFY_ENV_TEMPLATE\n}\n\n/**\n * Writes `clarify-env.d.ts` into the project root. Only rewrites when content\n * changes to avoid triggering unnecessary file watchers, and never overwrites a\n * user-authored file that does not carry the generated marker.\n */\nexport function writeClarifyEnvDts(projectRoot: string, plugins: ClarifyPlugin[]): void {\n const filePath = join(projectRoot, GENERATED_FILE_NAME)\n const next = generateClarifyEnvDts(plugins)\n\n if (existsSync(filePath)) {\n const current = readFileSync(filePath, 'utf-8')\n if (current === next) return\n // Guard against clobbering a hand-written file that happens to share the name.\n if (!current.startsWith('// This file is generated by Clarify.')) return\n }\n\n writeFileSync(filePath, next, 'utf-8')\n}\n","export function escapeHtml(text: string): string {\n return text\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n","import { escapeHtml } from '../../parsers/markdown/utils.js'\nimport type { ClarifyProjectContext, ContentRoute, ResolvedProjectConfig } from '../../types.js'\n\n/**\n * HTML template manipulation helpers used during SSG.\n *\n * The SSG renderer needs to mutate the built `index.html` per route\n * (title, description/keywords meta, canonical link, `<html lang/dir>`,\n * and the root `<div>` content). These operations are all string-based\n * because the template is a raw HTML string, not a parsed DOM. Keeping them\n * in one module centralizes every HTML-mutation regex so they can be audited\n * together and so `ssg.ts` stays focused on the render pipeline.\n */\n\nfunction resolveProjectConfigFromContext(contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig): ResolvedProjectConfig {\n return 'projectConfig' in contextOrConfig ? contextOrConfig.projectConfig : contextOrConfig\n}\n\nfunction routeTitle(contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route?: ContentRoute): string {\n const projectConfig = resolveProjectConfigFromContext(contextOrConfig)\n const title = route?.meta.title.trim()\n if (!title || title === projectConfig.title) return projectConfig.title\n return `${title} - ${projectConfig.title}`\n}\n\nfunction canonicalUrl(contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route: ContentRoute): string | undefined {\n const projectConfig = resolveProjectConfigFromContext(contextOrConfig)\n if (!projectConfig.siteUrl || !route.alternates || !route.locale) return undefined\n const prefixedPath = route.alternates[route.locale]\n if (!prefixedPath || prefixedPath === route.path) return undefined\n\n const base = projectConfig.siteUrl.replace(/\\/+$/, '')\n const prefix = (!projectConfig.routePrefix || projectConfig.routePrefix === '/')\n ? ''\n : `/${projectConfig.routePrefix.replace(/^\\/+|\\/+$/g, '')}`\n return `${base}${prefix}${prefixedPath}`\n}\n\n/** Inject `lang` (and optional `dir`) onto the `<html>` tag for the route locale. */\nfunction injectHtmlLocaleAttributes(html: string, contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route?: ContentRoute): string {\n const projectConfig = resolveProjectConfigFromContext(contextOrConfig)\n const localeCode = route?.locale ?? projectConfig.locales?.default\n if (!localeCode) return html\n\n const localeConfig = projectConfig.locales?.locales.find(locale => locale.code === localeCode)\n const dir = localeConfig?.dir\n\n return html.replace(/<html\\b([^>]*)>/i, (_match, attributes: string) => {\n let nextAttributes = attributes\n .replace(/\\s+lang=(\"[^\"]*\"|'[^']*'|[^\\s>]*)/i, '')\n .replace(/\\s+dir=(\"[^\"]*\"|'[^']*'|[^\\s>]*)/i, '')\n\n nextAttributes = `${nextAttributes} lang=\"${escapeHtml(localeCode)}\"`\n if (dir) nextAttributes = `${nextAttributes} dir=\"${escapeHtml(dir)}\"`\n return `<html${nextAttributes}>`\n })\n}\n\n/** Set, replace, or remove a `<meta name=\"...\">` tag in `<head>`. */\nfunction setNamedMeta(html: string, name: string, content: string | undefined): string {\n const metaPattern = new RegExp(`<meta\\\\b(?=[^>]*\\\\bname=[\"']${name}[\"'])[^>]*>\\\\n?`, 'i')\n if (!content) return html.replace(metaPattern, '')\n\n const meta = `<meta name=\"${name}\" content=\"${escapeHtml(content)}\" />`\n if (metaPattern.test(html)) return html.replace(metaPattern, meta)\n return html.replace('</head>', ` ${meta}\\n </head>`)\n}\n\n/** Remove any existing canonical link and (if a URL is resolved) inject a fresh one. */\nfunction injectCanonicalUrl(html: string, contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route?: ContentRoute): string {\n const url = route ? canonicalUrl(contextOrConfig, route) : undefined\n // Remove any existing canonical link\n html = html.replace(/<link\\b[^>]*\\brel=[\"']canonical[\"'][^>]*\\/?>\\n?/gi, '')\n if (!url) return html\n return html.replace('</head>', ` <link rel=\"canonical\" href=\"${escapeHtml(url)}\" />\\n </head>`)\n}\n\n/**\n * Render the SSR result into the built HTML template: set `<title>`, the\n * description/keywords meta, the canonical link, the `<html lang/dir>`, and\n * replace the `#root` content with the rendered app HTML.\n */\nexport function injectSSRIntoTemplate(template: string, appHtml: string, contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, route?: ContentRoute): string {\n const projectConfig = resolveProjectConfigFromContext(contextOrConfig)\n let html = injectHtmlLocaleAttributes(template, contextOrConfig, route)\n\n // Replace <title>...</title>\n html = html.replace(/<title>.*?<\\/title>/, `<title>${escapeHtml(routeTitle(contextOrConfig, route))}</title>`)\n\n html = setNamedMeta(html, 'description', route?.meta.description ?? projectConfig.description)\n html = setNamedMeta(html, 'keywords', route?.meta.keywords?.join(', '))\n html = injectCanonicalUrl(html, contextOrConfig, route)\n\n // Replace <div id=\"root\">...</div> with SSR rendered content\n // For bare alias routes (e.g., /path) in multilingual sites, mark the root div\n // with data-pagefind-ignore to prevent Pagefind from indexing duplicates\n const dataPagefindIgnore = route?.isBareAlias ? ' data-pagefind-ignore' : ''\n html = html.replace(/<div id=\"root\">([\\s\\S]*?)<\\/div>/, `<div id=\"root\"${dataPagefindIgnore}>${appHtml}</div>`)\n\n return html\n}\n","import { readFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { dirname, join } from 'node:path'\n\nimport type { AliasOptions } from 'vite'\n\nconst requireFromCli = createRequire(import.meta.url)\n\nfunction resolveCliDependency(id: string): string {\n return requireFromCli.resolve(id)\n}\n\nfunction resolvePackageExport(packageName: string, subpath: string, condition: 'import' | 'require' = 'import'): string {\n const packageJsonPath = requireFromCli.resolve(`${packageName}/package.json`)\n const packageRoot = dirname(packageJsonPath)\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8')) as {\n exports?: Record<string, string | Record<string, string>>\n }\n const exportKey = subpath ? `./${subpath}` : '.'\n const exportEntry = packageJson.exports?.[exportKey]\n const target = typeof exportEntry === 'string'\n ? exportEntry\n : exportEntry?.[condition] ?? exportEntry?.default\n\n if (!target) {\n throw new Error(`[clarify] Unable to resolve ${packageName}/${subpath}`)\n }\n\n return join(packageRoot, target)\n}\n\n/**\n * Resolve Clarify's framework/runtime dependencies from the CLI package instead\n * of from the user's documentation project. This keeps content-only projects\n * free from React, renderer, and tsconfig requirements.\n */\nexport function createClarifyRuntimeAliases(): AliasOptions {\n return [\n { find: /^@clarify-labs\\/renderer\\/style\\.css$/, replacement: resolvePackageExport('@clarify-labs/renderer', 'style.css') },\n { find: /^@clarify-labs\\/renderer\\/client$/, replacement: resolvePackageExport('@clarify-labs/renderer', 'client') },\n { find: /^@clarify-labs\\/renderer\\/server$/, replacement: resolvePackageExport('@clarify-labs/renderer', 'server') },\n { find: /^@clarify-labs\\/renderer$/, replacement: resolvePackageExport('@clarify-labs/renderer', '') },\n { find: /^react\\/jsx-dev-runtime$/, replacement: resolveCliDependency('react/jsx-dev-runtime') },\n { find: /^react\\/jsx-runtime$/, replacement: resolveCliDependency('react/jsx-runtime') },\n { find: /^react-dom\\/client$/, replacement: resolveCliDependency('react-dom/client') },\n { find: /^react-dom\\/server$/, replacement: resolveCliDependency('react-dom/server') },\n { find: /^react-dom$/, replacement: resolveCliDependency('react-dom') },\n { find: /^react-router-dom$/, replacement: resolveCliDependency('react-router-dom') },\n { find: /^react-router$/, replacement: resolveCliDependency('react-router') },\n { find: /^mermaid$/, replacement: resolveCliDependency('mermaid') },\n { find: /^react-zoom-pan-pinch$/, replacement: resolveCliDependency('react-zoom-pan-pinch') },\n { find: /^react$/, replacement: resolveCliDependency('react') },\n ]\n}\n","import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs'\nimport { join, dirname } from 'node:path'\nimport { pathToFileURL } from 'node:url'\n\nimport { build } from 'vite'\nimport type { Plugin } from 'vite'\n\nimport type { ClarifyProjectContext, ContentRoute, ResolvedProjectConfig } from '../../types.js'\nimport { createClarifyTempDir } from '../project/temp-dir.js'\n\nimport { injectSSRIntoTemplate } from './html-template.js'\nimport { createClarifyRuntimeAliases } from './runtime-deps.js'\n\n// Re-export the template helpers so existing callers that imported them from\n// `ssg.ts` keep working. The implementations live in `html-template.ts`.\nexport { injectSSRIntoTemplate } from './html-template.js'\n\nexport function readIndexHtml(outputDirectory: string): string | undefined {\n const indexPath = join(outputDirectory, 'index.html')\n if (!existsSync(indexPath)) return undefined\n try {\n return readFileSync(indexPath, 'utf-8')\n } catch {\n return undefined\n }\n}\n\nexport function isNotFoundRoute(route: ContentRoute): boolean {\n return (route.basePath ?? route.path) === '/404'\n}\n\nexport function routeOutputFiles(outputDirectory: string, route: ContentRoute): string[] {\n const files = [join(outputDirectory, route.path, 'index.html')]\n if (isNotFoundRoute(route) && (!route.locale || route.path === '/404')) {\n files.push(join(outputDirectory, '404.html'))\n }\n return files\n}\n\nexport const SSR_ENTRY_CODE = `import { renderToHTML } from '@clarify-labs/renderer/server';\nimport { routes, navigation } from 'virtual:clarify/routes/server';\nimport { config } from 'virtual:clarify/config';\nimport { openApiSpecs } from 'virtual:clarify/openapi/server';\nimport { runtimeSlots } from 'virtual:clarify/slots';\n\nexport async function render(url) {\n // Pre-resolve every slot component factory so renderToString can use\n // them synchronously (renderToString has no Suspense support).\n const entries = Object.values(runtimeSlots).flat()\n await Promise.all(entries.map(async (entry) => {\n const mod = await entry.loadComponent()\n entry._resolved = mod.default\n }))\n return renderToHTML({ config, routes, navigation, openApiSpecs, runtimeSlots, url, themeEditor: config.theme.editor });\n}`\n\nexport function createTempEntryFile(content: string): string {\n const tempDir = createClarifyTempDir('ssr')\n const entryPath = join(tempDir, 'entry-server.ts')\n writeFileSync(entryPath, content, 'utf-8')\n return entryPath\n}\n\nexport async function buildSSRBundle(root: string, ssrEntry: string, ssrOutDir: string, plugins: Plugin[]): Promise<void> {\n await build({\n root,\n configFile: false,\n resolve: {\n alias: createClarifyRuntimeAliases(),\n },\n ssr: {\n noExternal: true,\n },\n plugins,\n build: {\n ssr: ssrEntry,\n outDir: ssrOutDir,\n emptyOutDir: true,\n rolldownOptions: {\n input: ssrEntry,\n checks: {\n pluginTimings: false,\n },\n },\n },\n })\n}\n\nexport async function renderSSGRoutes(routes: ContentRoute[], contextOrConfig: ClarifyProjectContext | ResolvedProjectConfig, outputDirectory: string, ssrBundlePath: string): Promise<void> {\n const { render } = await import(pathToFileURL(ssrBundlePath).href)\n\n const template = readIndexHtml(outputDirectory)\n if (!template) {\n throw new Error(\n `[clarify] index.html not found in outputDirectory \"${outputDirectory}\". Make sure Vite build produces it.`\n )\n }\n\n await Promise.all(routes.map(async (route) => {\n try {\n const appHtml = await render(route.path)\n const finalHtml = injectSSRIntoTemplate(template, appHtml, contextOrConfig, route)\n\n for (const outFile of routeOutputFiles(outputDirectory, route)) {\n mkdirSync(dirname(outFile), { recursive: true })\n writeFileSync(outFile, finalHtml, 'utf-8')\n }\n } catch (err) {\n console.error(`[clarify] Failed to render route \"${route.path}\":`, err)\n throw err\n }\n }))\n}\n","import { relative } from 'node:path'\n\nexport type StartupHintOptions = {\n projectRoot: string\n contentRoot: string\n contentDirExists: boolean\n hasRoutes: boolean\n}\n\nfunction contentDirectoryLabel(projectRoot: string, contentRoot: string): string {\n const relativePath = relative(projectRoot, contentRoot)\n return relativePath && relativePath !== '.' ? relativePath : 'source'\n}\n\nfunction contentFileExampleLabel(projectRoot: string, contentRoot: string): string {\n return `${contentDirectoryLabel(projectRoot, contentRoot)}/index.mdx`\n}\n\nexport function getStartupHints(options: StartupHintOptions): string[] {\n const hints: string[] = []\n\n if (!options.contentDirExists) {\n const label = contentDirectoryLabel(options.projectRoot, options.contentRoot)\n hints.push(`Content directory \"${label}\" was not found. Create it or pass --content <dir> to point Clarify at a different directory.`)\n } else if (!options.hasRoutes) {\n const example = contentFileExampleLabel(options.projectRoot, options.contentRoot)\n hints.push(`No content pages were found yet. Add ${example} to get started.`)\n }\n\n return hints\n}\n\nexport function logStartupHints(options: StartupHintOptions): void {\n const hints = getStartupHints(options)\n if (hints.length === 0) return\n\n const message = hints.map(hint => `[clarify] ${hint}`).join('\\n')\n console.warn(message)\n}\n","import type { ClarifyHookContext, ClarifyPlugin, ContentRoute, NavigationTree, ResolvedProjectConfig } from '../../types.js'\nimport type { ResolvedBuildOptions } from '../config/options.js'\n\nexport type ClarifyContextInit = {\n projectRoot: string\n contentRoot: string\n projectConfig: ResolvedProjectConfig\n generateOptions: ResolvedBuildOptions\n version: string\n routes?: ContentRoute[]\n navigation?: NavigationTree\n plugins?: ClarifyPlugin[]\n}\n\ntype ContextListener = () => void\n\nexport type ProjectStateUpdate = {\n projectRoot?: string\n contentRoot?: string\n projectConfig?: ResolvedProjectConfig\n generateOptions?: ResolvedBuildOptions\n version?: string\n}\n\nexport class ClarifyContext implements ClarifyHookContext {\n projectRoot: string\n contentRoot: string\n projectConfig: ResolvedProjectConfig\n generateOptions: ResolvedBuildOptions\n version: string\n\n private values = new Map<string, unknown>()\n private routeListeners = new Set<ContextListener>()\n private navigationListeners = new Set<ContextListener>()\n private currentRoutes: ContentRoute[]\n private currentNavigation: NavigationTree\n private currentPlugins: ClarifyPlugin[]\n\n constructor(init: ClarifyContextInit) {\n this.projectRoot = init.projectRoot\n this.contentRoot = init.contentRoot\n this.projectConfig = init.projectConfig\n this.generateOptions = init.generateOptions\n this.version = init.version\n this.currentRoutes = init.routes ?? []\n this.currentNavigation = init.navigation ?? { kind: 'flat', nodes: [] }\n this.currentPlugins = init.plugins ?? []\n }\n\n get routes(): ContentRoute[] {\n return this.currentRoutes\n }\n\n set routes(routes: ContentRoute[]) {\n this.currentRoutes = routes\n this.notify(this.routeListeners)\n }\n\n get navigation(): NavigationTree {\n return this.currentNavigation\n }\n\n set navigation(navigation: NavigationTree) {\n this.currentNavigation = navigation\n this.notify(this.navigationListeners)\n }\n\n get plugins(): ClarifyPlugin[] {\n return this.currentPlugins\n }\n\n set plugins(plugins: ClarifyPlugin[]) {\n this.currentPlugins = plugins\n }\n\n get isI18n(): boolean {\n return Boolean(this.projectConfig.locales)\n }\n\n get defaultLocale(): string | undefined {\n return this.projectConfig.locales?.default\n }\n\n get<T>(key: string): T | undefined {\n return this.values.get(key) as T | undefined\n }\n\n set<T>(key: string, value: T): void {\n this.values.set(key, value)\n }\n\n has(key: string): boolean {\n return this.values.has(key)\n }\n\n delete(key: string): boolean {\n return this.values.delete(key)\n }\n\n onRoutesChange(listener: ContextListener): () => void {\n this.routeListeners.add(listener)\n return () => this.routeListeners.delete(listener)\n }\n\n onNavigationChange(listener: ContextListener): () => void {\n this.navigationListeners.add(listener)\n return () => this.navigationListeners.delete(listener)\n }\n\n updateProjectState(update: ProjectStateUpdate): void {\n if (update.projectRoot !== undefined) this.projectRoot = update.projectRoot\n if (update.contentRoot !== undefined) this.contentRoot = update.contentRoot\n if (update.projectConfig !== undefined) this.projectConfig = update.projectConfig\n if (update.generateOptions !== undefined) this.generateOptions = update.generateOptions\n if (update.version !== undefined) this.version = update.version\n }\n\n private notify(listeners: Set<ContextListener>): void {\n for (const listener of listeners) listener()\n }\n}\n","import type { ClarifyCollectorHook, ClarifyHookContext, ClarifyInterceptHook, ClarifyPipelineHook, ClarifyPlugin, ClarifyTapHook } from '../../types.js'\n\nexport type PhaseName =\n | 'config:load'\n | 'config:resolve'\n | 'plugins:load'\n | 'site:discover'\n | 'content:process'\n | 'modules:build'\n | 'build'\n | 'ssg'\n | 'dev:server'\n\nexport type TapPhaseName =\n | `before:${PhaseName}`\n | `after:${PhaseName}`\n\nexport type TapHook = ClarifyTapHook\nexport type InterceptHook = ClarifyInterceptHook\nexport type PipelineHook<Input> = ClarifyPipelineHook<Input>\nexport type CollectorHook<Result> = ClarifyCollectorHook<Result>\n\nexport async function runTapHooks(plugins: ClarifyPlugin[], hookName: TapPhaseName, ctx: ClarifyHookContext): Promise<void> {\n for (const plugin of plugins) {\n const hook = plugin.hooks?.[hookName]\n if (!hook) continue\n try {\n await hook(ctx)\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"${hookName}\" failed: ${err}`, { cause: err })\n }\n }\n}\n\nexport async function runInterceptHooks(plugins: ClarifyPlugin[], hookName: 'build:shouldRun' | 'ssg:shouldRun', ctx: ClarifyHookContext): Promise<boolean> {\n for (const plugin of plugins) {\n const hook = plugin.hooks?.[hookName]\n if (!hook) continue\n try {\n if (await hook(ctx) === false) return false\n } catch (err) {\n throw new Error(`[clarify] plugin \"${plugin.name}\" hook \"${hookName}\" failed: ${err}`, { cause: err })\n }\n }\n return true\n}\n\nexport async function runPhase<T>(plugins: ClarifyPlugin[], phase: PhaseName, ctx: ClarifyHookContext, task: () => Promise<T> | T): Promise<T> {\n await runTapHooks(plugins, `before:${phase}`, ctx)\n const result = await task()\n await runTapHooks(plugins, `after:${phase}`, ctx)\n return result\n}\n","import { existsSync, rmSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport type { ConfigEnv, Plugin } from 'vite'\n\nimport { cliPackageVersion } from '../../cli/package.js'\nimport { createProjectContentProcessor } from '../../parsers/content/content.js'\nimport { findContentRoutes, findLocalizedContentRoutes } from '../../parsers/routes/routes.js'\nimport type { ClarifyEmitAsset, ClarifyHtmlTransformInput, ClarifyPlugin, ContentRoute, NavigationTree, ClarifyProjectContext } from '../../types.js'\nimport { resolveProjectConfig } from '../config/config.js'\nimport { resolveBuildOptions, type ClarifyBuildOptions } from '../config/options.js'\nimport { findClarifyConfigFile } from '../config/user-config.js'\nimport { runBuildAssetsHooks, runBuildDoneHooks, runDevConfigureServerHooks, runHooks } from '../plugin/hooks.js'\nimport { loadBuildPlugins } from '../plugin/manager.js'\nimport { resolveProjectContext } from '../project/project-context.js'\nimport { resolveRoutePages, resolveRouteState } from '../routing/route-resolution.js'\nimport { writeClarifyEnvDts } from '../runtime/env-types.js'\nimport {\n SSR_ENTRY_CODE,\n buildSSRBundle,\n createTempEntryFile,\n renderSSGRoutes,\n} from '../runtime/ssg.js'\nimport { logStartupHints } from '../runtime/startup.js'\nimport {\n buildVirtualModules,\n resolveVirtualModuleId,\n stripVirtualPrefix,\n type VirtualModules,\n} from '../runtime/virtual-modules.js'\n\nimport { ClarifyContext } from './context.js'\nimport { runInterceptHooks, runPhase, runTapHooks } from './phases.js'\nimport type { BuildSSRBundleOptions, ClarifyEngineRuntime, PrepareOptions } from './types.js'\n\nexport type { ClarifyEngineMode, ClarifyEngineRuntime, PrepareOptions } from './types.js'\nexport { assertNoRouteConflicts, createDevRouteConflictRoutes } from '../routing/route-resolution.js'\n\nfunction loadVirtualModule(id: string, modules: VirtualModules): string | null {\n const bareId = stripVirtualPrefix(id)\n return modules.get(bareId) ?? modules.get(id) ?? null\n}\n\nexport function assertNoContentDiagnostics(routes: ContentRoute[]): void {\n const failures = routes.filter(route => route.diagnostic)\n if (failures.length === 0) return\n\n const summary = failures\n .map(route => `- ${route.path}: ${route.diagnostic?.title ?? 'Content error'}${route.diagnostic?.filePath ? ` (${route.diagnostic.filePath})` : ''}`)\n .join('\\n')\n throw new Error(`[clarify] Content diagnostics prevented the build:\\n${summary}`)\n}\n\nexport class ClarifyEngine {\n readonly options: ClarifyBuildOptions\n readonly root: string\n configFilePath?: string\n readonly ctx: ClarifyContext\n\n private runtime: ClarifyEngineRuntime = { command: 'build', mode: 'production' }\n private virtualModules: VirtualModules = new Map()\n private buildEnabled = true\n private initializedOptions?: ClarifyBuildOptions\n\n constructor(options: ClarifyBuildOptions = {}) {\n this.options = options\n this.root = resolve(options.projectRoot ?? process.cwd())\n this.configFilePath = findClarifyConfigFile(this.root) ?? undefined\n\n // Create a minimal context with placeholder values. The real config\n // resolution and plugin loading happen in initialize(), which is always\n // called before any real work. This avoids redundant work in the\n // constructor and keeps Engine construction cheap.\n const placeholderConfig = resolveProjectConfig({})\n const placeholderOptions = resolveBuildOptions(options)\n this.ctx = new ClarifyContext({\n projectRoot: this.root,\n contentRoot: join(this.root, placeholderOptions.rootDirectory),\n projectConfig: placeholderConfig,\n generateOptions: placeholderOptions,\n version: cliPackageVersion,\n routes: [],\n navigation: { kind: 'flat', nodes: [] },\n plugins: [],\n })\n }\n\n configureRuntime(runtime: Partial<ClarifyEngineRuntime>): void {\n this.runtime = { ...this.runtime, ...runtime }\n }\n\n async initialize(env: ConfigEnv = { command: this.runtime.command, mode: this.runtime.mode }, options: ClarifyBuildOptions = this.options, prepareOptions: PrepareOptions = {}): Promise<ClarifyBuildOptions> {\n if (this.initializedOptions && !prepareOptions.force) return this.initializedOptions\n\n const seedPlugins = loadBuildPlugins(options, { htmlShell: prepareOptions.htmlShell })\n this.ctx.plugins = seedPlugins\n const context = await runPhase(seedPlugins, 'config:load', this.ctx, () => resolveProjectContext(options, env))\n\n this.configFilePath = context.configFilePath\n this.ctx.updateProjectState({\n projectRoot: context.projectRoot,\n contentRoot: context.contentRoot,\n projectConfig: context.projectConfig,\n generateOptions: context.buildOptions,\n version: context.projectContext.version,\n })\n await runPhase(seedPlugins, 'config:resolve', this.ctx, () => undefined)\n\n // Reload plugins with the fully resolved options (which now include\n // plugins declared in the config file) and run the plugins:load phase.\n // The seed plugins above only carried user-supplied options.plugins so\n // that config:load/config:resolve hooks could fire before the config\n // file was read; the final plugin set replaces them here.\n const finalPlugins = loadBuildPlugins(context.resolvedOptions, { htmlShell: prepareOptions.htmlShell })\n this.ctx.plugins = finalPlugins\n await runPhase(finalPlugins, 'plugins:load', this.ctx, () => undefined)\n this.initializedOptions = context.resolvedOptions\n\n return context.resolvedOptions\n }\n\n /**\n * Runs the full pre-build/pre-dev preparation: initialize (config load +\n * resolve + plugins:load), site discovery (routes + navigation), and module\n * building. This is the single entry point that prepares the engine before\n * handing it to a Vite adapter or running a check, so callers never need to\n * call initialize/discoverSite separately.\n *\n * Options:\n * - `force`: re-run even if already prepared (config-file hot reload).\n * - `htmlShell`: toggle the HTML shell builtin plugin (default true).\n * - `skipModules`: skip `buildModules()` (check command).\n * - `skipHints`: skip `logStartupHints()` (check command).\n *\n * Idempotent: calling prepare() again with the same env is a no-op unless\n * `force` is set.\n */\n async prepare(env: ConfigEnv = { command: this.runtime.command, mode: this.runtime.mode }, options: ClarifyBuildOptions = this.options, prepareOptions: PrepareOptions = {}): Promise<ClarifyBuildOptions> {\n this.configureRuntime({ command: env.command, mode: env.mode })\n const resolvedOptions = await this.initialize(env, options, prepareOptions)\n await this.discoverSite()\n if (!prepareOptions.skipModules) await this.buildModules()\n if (!prepareOptions.skipHints) this.logStartupHints()\n return resolvedOptions\n }\n\n get projectConfig(): ClarifyContext['projectConfig'] {\n return this.ctx.projectConfig\n }\n\n get generateOptions(): ClarifyContext['generateOptions'] {\n return this.ctx.generateOptions\n }\n\n get contentRoot(): string {\n return this.ctx.contentRoot\n }\n\n get routes(): ContentRoute[] {\n return this.ctx.routes\n }\n\n get navigation(): NavigationTree {\n return this.ctx.navigation\n }\n\n get plugins(): ClarifyPlugin[] {\n return this.ctx.plugins\n }\n\n get modules(): VirtualModules {\n return this.virtualModules\n }\n\n loadModule(id: string): string | null {\n return loadVirtualModule(id, this.virtualModules)\n }\n\n async discoverSite(): Promise<void> {\n const plugins = this.ctx.plugins\n const contentRoot = this.ctx.contentRoot\n const { locales } = this.ctx.projectConfig\n\n // Phase 3: site:discover - scan content directory. The Engine provides the\n // default discovery logic (i18n-aware content scanning) directly; user\n // plugins can extend or replace it via the routes:discover pipeline hook.\n let routes = await runPhase(plugins, 'site:discover', this.ctx, async () => {\n const processor = createProjectContentProcessor(plugins, this.ctx)\n const options = { contentProcessor: processor }\n\n const discovered = locales\n ? await findLocalizedContentRoutes(contentRoot, locales, options)\n : await findContentRoutes(contentRoot, contentRoot, options)\n\n // Run routes:discover hook so plugins can augment the discovered routes.\n const result = await runHooks(plugins, 'routes:discover', { contentRoot, routes: discovered }, this.ctx)\n const routes = await runHooks(plugins, 'routes:discovered', result.routes, this.ctx)\n return routes\n })\n\n // Phase 4: content:process - post-discovery adjustments. Map routes to\n // pages, run pages:resolved pipeline, then write back any page-level\n // changes (frontmatter/content) onto the routes.\n routes = await runPhase(plugins, 'content:process', this.ctx, () => resolveRoutePages(routes, plugins, this.ctx))\n\n const resolved = await resolveRouteState(routes, plugins, this.ctx, this.runtime.command === 'serve')\n this.ctx.routes = resolved.routes\n this.ctx.navigation = resolved.navigation\n }\n\n logStartupHints(): void {\n logStartupHints({\n projectRoot: this.root,\n contentRoot: this.contentRoot,\n contentDirExists: existsSync(this.contentRoot),\n hasRoutes: this.routes.length > 0,\n })\n }\n\n async buildModules(): Promise<void> {\n await runPhase(this.plugins, 'modules:build', this.ctx, async () => {\n this.virtualModules = buildVirtualModules({\n projectConfig: this.projectConfig,\n generateOptions: this.generateOptions,\n routes: this.routes,\n navigation: this.navigation,\n plugins: this.plugins,\n themeEditor: this.runtime.command === 'serve' || this.runtime.themeEditor === true || this.projectConfig.features.themeEditor.enabled,\n version: this.ctx.version,\n })\n this.virtualModules = await runHooks(this.plugins, 'modules:before', this.virtualModules, this.ctx)\n })\n }\n\n writeEnvTypes(): void {\n writeClarifyEnvDts(this.root, this.plugins)\n }\n\n hasContentRouteForFile(filePath: string): boolean {\n return this.routes.some(route => route.source.filePath === filePath)\n }\n\n async collectBuildAssets(): Promise<ClarifyEmitAsset[]> {\n if (!this.buildEnabled) return []\n return runBuildAssetsHooks(this.plugins, this.ctx)\n }\n\n async beginBuild(): Promise<boolean> {\n this.buildEnabled = await runInterceptHooks(this.plugins, 'build:shouldRun', this.ctx)\n if (!this.buildEnabled) return false\n await runTapHooks(this.plugins, 'before:build', this.ctx)\n return true\n }\n\n async endBuild(): Promise<void> {\n if (!this.buildEnabled) return\n await runTapHooks(this.plugins, 'after:build', this.ctx)\n }\n\n shouldRunBuild(): boolean {\n return this.buildEnabled\n }\n\n async configureDevServer(server: Parameters<typeof runDevConfigureServerHooks>[1]): Promise<Awaited<ReturnType<typeof runDevConfigureServerHooks>>> {\n return runPhase(this.plugins, 'dev:server', this.ctx, () => {\n return runDevConfigureServerHooks(this.plugins, server, this.ctx)\n })\n }\n\n async runBuildDone(): Promise<void> {\n if (!this.buildEnabled) return\n await runBuildDoneHooks(this.plugins, this.ctx)\n }\n\n async runSSG(): Promise<void> {\n if (!this.buildEnabled) return\n await runPhase(this.plugins, 'ssg', this.ctx, async () => {\n if (process.env.SKIP_CLARIFY_SSG) return\n\n if (!(await runInterceptHooks(this.plugins, 'ssg:shouldRun', this.ctx))) return\n\n assertNoContentDiagnostics(this.routes)\n\n const outputDir = this.runtime.outputDirectory ?? this.generateOptions.outputDirectory\n if (!outputDir) throw new Error('[clarify] outputDirectory is required before SSG runs')\n\n const ssrOutputDir = join(outputDir, '.ssr')\n let tempEntryPath: string | undefined\n\n try {\n tempEntryPath = createTempEntryFile(SSR_ENTRY_CODE)\n const buildSSR = this.runtime.buildSSRBundle ?? ((options: BuildSSRBundleOptions) => buildSSRBundle(options.root, options.ssrEntry, options.ssrOutDir, options.plugins))\n\n await buildSSR({\n root: this.root,\n ssrEntry: tempEntryPath,\n ssrOutDir: ssrOutputDir,\n plugins: this.runtime.ssrPlugins ?? [],\n })\n\n const ssrBundlePath = join(ssrOutputDir, 'entry-server.js')\n await renderSSGRoutes(this.routes, this.runtimeContext(), outputDir, ssrBundlePath)\n } catch (err) {\n console.error('[clarify] SSG failed:', err)\n throw err\n } finally {\n if (tempEntryPath) {\n try {\n rmSync(tempEntryPath, { force: true })\n } catch {\n // ignore cleanup errors\n }\n }\n }\n\n })\n await this.runBuildDone()\n }\n\n async refresh(): Promise<void> {\n await this.discoverSite()\n await this.buildModules()\n }\n\n /**\n * Runs the `html:transform` pipeline hook and returns the transformed\n * input. Adapters call this from their `transformIndexHtml` hook instead\n * of invoking `runHooks` directly, keeping hook execution inside Engine.\n */\n async transformHtml(input: ClarifyHtmlTransformInput): Promise<ClarifyHtmlTransformInput> {\n return runHooks(this.plugins, 'html:transform', input, this.ctx)\n }\n\n runtimeContext(): ClarifyProjectContext {\n return {\n projectRoot: this.root,\n contentRoot: this.contentRoot,\n projectConfig: this.projectConfig,\n generateOptions: this.generateOptions,\n version: this.ctx.version,\n }\n }\n\n createSSGVirtualPlugin(): Plugin {\n return {\n name: 'clarify:virtual-ssg',\n resolveId: id => resolveVirtualModuleId(id, this.virtualModules, this.routes),\n load: id => this.loadModule(id),\n }\n }\n}\n\nexport function createClarifyEngine(options: ClarifyBuildOptions = {}): ClarifyEngine {\n return new ClarifyEngine(options)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAcA,SAAS,YAAY,UAA8B,aAAqD;CACtG,IAAI,CAAC,UAAU,OAAO,KAAA;CACtB,IAAI,CAAC,aAAa,OAAO,SAAS,QAAQ,gBAAgB,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAEhF,MAAM,aAAa,SAAS,aAAa,QAAQ;CACjD,OAAO,cAAc,CAAC,WAAW,WAAW,IAAI,KAAK,CAAC,WAAW,UAAU,IACvE,aACA,SAAS,QAAQ,gBAAgB,EAAE,CAAC,CAAC,QAAQ,QAAQ,EAAE;AAC7D;AAEA,SAAgB,wBAAwB,SAA4D;CAClG,MAAM,EAAE,UAAU;CAClB,OAAO;EACL,MAAM,QAAQ;EACd,OAAO,QAAQ;EACf,SAAS,QAAQ;EACjB,UAAU,YAAY,QAAQ,UAAU,QAAQ,WAAW;EAC3D,SAAS,iBAAiB,QACtB,QAAQ,eAAe,MAAM,SAAS,MAAM,UAAU,MAAM,UAC5D,OAAO,KAAK;CAClB;AACF;;;ACZA,SAAS,YAAY,WAA4B;CAG/C,QAFgB,MA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