refactor(cli): centralize content registry building

Extract buildRegistryFromIndex and normalizePathKey from the CLI serve
command and the browser completions module into the shared
content-registry module. This ensures both paths produce identical
pathIndex/docContent, including the spark-injection pass that was
previously only applied in the CLI.
This commit is contained in:
hyper
2026-08-07 12:46:08 +08:00
parent e8aa7165cb
commit 0a68122efd
3 changed files with 63 additions and 33 deletions
+7 -24
View File
@@ -2,15 +2,15 @@ import type { ServeCommandHandler } from "../types.js";
import { createServer, Server, IncomingMessage, ServerResponse } from "http";
import { readdirSync, statSync, readFileSync, existsSync } from "fs";
import { createReadStream } from "fs";
import { join, resolve, extname, sep, relative, dirname } from "path";
import { join, resolve, extname, relative, dirname } from "path";
import { watch } from "chokidar";
import { networkInterfaces } from "os";
import { fileURLToPath } from "url";
import { createJournalServer } from "../journal.js";
import {
scanDoc,
buildRegistryFromIndex,
normalizePathKey,
deriveCompletions,
injectSparkDirectives,
type ContentRegistry,
} from "../content-registry.js";
import type { CompletionsPayload } from "../completions/types.js";
@@ -86,7 +86,7 @@ function getBestIP(): string {
* 扫描目录内的 .md 等文件,构建内容注册表(路径索引 + 每文档内联内容)
*/
export function buildRegistry(dir: string): ContentRegistry {
const registry: ContentRegistry = { pathIndex: {}, docContent: {} };
const index: Record<string, string> = {};
function scan(currentPath: string, relativePath: string) {
const entries = readdirSync(currentPath);
@@ -96,7 +96,7 @@ export function buildRegistry(dir: string): ContentRegistry {
const fullPath = join(currentPath, entry);
const relPath = relativePath ? join(relativePath, entry) : entry;
const normalizedRelPath = "/" + relPath.split(sep).join("/");
const normalizedRelPath = normalizePathKey(relPath);
const stats = statSync(fullPath);
if (stats.isDirectory()) {
@@ -108,14 +108,7 @@ export function buildRegistry(dir: string): ContentRegistry {
entry.endsWith(".svg")
) {
try {
const content = readFileSync(fullPath, "utf-8");
if (entry.endsWith(".md")) {
const result = scanDoc(content, normalizedRelPath);
registry.pathIndex[normalizedRelPath] = result.stripped;
registry.docContent[normalizedRelPath] = result.content;
} else {
registry.pathIndex[normalizedRelPath] = content;
}
index[normalizedRelPath] = readFileSync(fullPath, "utf-8");
} catch (e) {
console.error(`读取文件失败:${fullPath}`, e);
}
@@ -125,17 +118,7 @@ export function buildRegistry(dir: string): ContentRegistry {
scan(dir, "");
// ---- Inject data-spark into real-file spark table directives ----
for (const [relPath, content] of Object.entries(registry.pathIndex)) {
if (!relPath.endsWith(".md")) continue;
registry.pathIndex[relPath] = injectSparkDirectives(
content,
relPath,
registry,
);
}
return registry;
return buildRegistryFromIndex(index);
}
/**