示例工程 43-project-local-knowledge-base
43-project-local-knowledge-base/app/knowledge/indexer.cjs
/* eslint-disable @typescript-eslint/no-require-imports -- 独立索引器 CJS 程序 */
const fs = require("node:fs");
const path = require("node:path");
const { DatabaseSync } = require("node:sqlite");
const parentPort = process.parentPort;
function send(message) {
parentPort?.postMessage(message);
}
function chunkText(text, max = 360, overlap = 60) {
const clean = text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, "");
const chunks = [];
let start = 0;
while (start < clean.length) {
let end = Math.min(clean.length, start + max);
if (end < clean.length) {
const window = clean.slice(start, end);
const cut = Math.max(
window.lastIndexOf("\n\n"),
window.lastIndexOf("。"),
window.lastIndexOf(";"),
);
if (cut > max * 0.4) end = start + cut + 1;
}
const body = clean.slice(start, end).trim();
if (body) chunks.push(body);
if (end >= clean.length) break;
start = Math.max(start + 1, end - overlap);
}
return chunks;
}
function titleOf(text, file) {
const line = text.split("\n").find((candidate) => candidate.startsWith("# "));
return line ? line.slice(2).trim() : path.basename(file);
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function index(request) {
const started = Date.now();
const file = request.dbPath;
fs.mkdirSync(path.dirname(file), { recursive: true });
const db = new DatabaseSync(file);
db.exec("PRAGMA journal_mode = WAL;");
db.exec("PRAGMA synchronous = NORMAL;");
db.exec(`
CREATE TABLE IF NOT EXISTS docs (
id INTEGER PRIMARY KEY,
path TEXT UNIQUE NOT NULL,
title TEXT NOT NULL,
bytes INTEGER NOT NULL,
chunks INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS chunks (
id INTEGER PRIMARY KEY,
doc_id INTEGER NOT NULL,
seq INTEGER NOT NULL,
body TEXT NOT NULL
);
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
doc_id UNINDEXED,
seq UNINDEXED,
body,
tokenize = 'unicode61'
);
`);
const files = Array.isArray(request.files) ? request.files : [];
let docs = 0;
let chunks = 0;
db.exec("BEGIN IMMEDIATE;");
try {
db.exec("DELETE FROM chunks_fts; DELETE FROM chunks; DELETE FROM docs;");
for (let index = 0; index < files.length; index += 1) {
const item = files[index];
send({
type: "progress",
current: index,
total: files.length,
file: item.title ?? path.basename(item.path),
});
const text = fs.readFileSync(item.path, "utf8");
const title = item.title ?? titleOf(text, item.path);
const parts = chunkText(text);
const inserted = db
.prepare(
"INSERT INTO docs (path, title, bytes, chunks) VALUES (?, ?, ?, ?)",
)
.run(item.path, title, Buffer.byteLength(text, "utf8"), parts.length);
const docId = Number(inserted.lastInsertRowid);
const insertChunk = db.prepare(
"INSERT INTO chunks (doc_id, seq, body) VALUES (?, ?, ?)",
);
const insertFts = db.prepare(
"INSERT INTO chunks_fts (doc_id, seq, body) VALUES (?, ?, ?)",
);
for (let seq = 0; seq < parts.length; seq += 1) {
insertChunk.run(docId, seq, parts[seq]);
insertFts.run(docId, seq, parts[seq]);
}
docs += 1;
chunks += parts.length;
await sleep(300);
}
db.exec("COMMIT;");
} catch (error) {
try {
db.exec("ROLLBACK;");
} catch {
// 事务可能已回滚。
}
db.close();
send({ type: "error", message: String(error?.message ?? error) });
return;
}
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
db.close();
send({
type: "done",
docs,
chunks,
ms: Date.now() - started,
});
}
send({
type: "worker-ready",
pid: process.pid,
node: process.versions.node,
});
parentPort?.on("message", (event) => {
const message = event.data;
if (message?.type === "index") {
void index(message);
}
});