import { createHash, randomUUID } from 'node:crypto'; import { mkdir, readFile, writeFile, rename, unlink } from 'node:fs/promises'; import { join } from 'node:path'; import { sessionRuntimeDir, type RuntimeIdentity } from '../../session/runtimeStore.js'; /** Immutable, session-local source. Preview limits never truncate this copy. */ export interface PageSnapshot { url: string; text: string; format: string; fetchedAt: number } function directory(identity: RuntimeIdentity) { return join(sessionRuntimeDir(identity), 'web-pages'); } export function pageSnapshotPath(id: string, identity: RuntimeIdentity) { if (!/^[a-f0-9]{64}$/.test(id)) throw new Error('无效的 snapshot_id'); return join(directory(identity), `${id}.txt`); } export async function savePageSnapshot(page: PageSnapshot, identity: RuntimeIdentity) { const id = createHash('sha256').update(JSON.stringify(page)).digest('hex'); const dir = directory(identity); await mkdir(dir, { recursive: true, mode: 0o700 }); // Publish the metadata last. Readers never observe a half-written snapshot. const path = join(dir, `${id}.txt`); const temp = join(dir, `.${randomUUID()}.tmp`); try { await writeFile(temp, page.text, { mode: 0o600 }); await rename(temp, path); const { text, ...metadata } = page; await writeFile(temp, JSON.stringify(metadata), { mode: 0o600 }); await rename(temp, join(dir, `${id}.json`)); } finally { await unlink(temp).catch(() => undefined); } return { id, path }; } export async function loadPageSnapshot(id: string, url: string, identity: RuntimeIdentity): Promise { if (!/^[a-f0-9]{64}$/.test(id)) throw new Error('无效的 snapshot_id'); const page = JSON.parse(await readFile(join(directory(identity), `${id}.json`), 'utf8')) as PageSnapshot; if (page.url !== url) throw new Error('快照 URL 不匹配'); page.text = await readFile(join(directory(identity), `${id}.txt`), 'utf8'); if (createHash('sha256').update(JSON.stringify({ url: page.url, text: page.text, format: page.format, fetchedAt: page.fetchedAt })).digest('hex') !== id) throw new Error('快照完整性检查失败,请重新抓取'); return page; } /** UTF-16 offsets match JS slicing and Read.column; never split a surrogate pair. */ export function pageWindow(text: string, offset: number, budget: number, query?: string) { let start = Math.min(offset, text.length); if (query) { const hit = text.indexOf(query, start); if (hit < 0) return { text: '', start, end: start, next: null, found: false }; start = hit; } if (start > 0 && /[\uDC00-\uDFFF]/.test(text[start] ?? '') && /[\uD800-\uDBFF]/.test(text[start - 1]!)) start--; let end = Math.min(text.length, start + budget); if (end < text.length && /[\uD800-\uDBFF]/.test(text[end - 1] ?? '')) end--; return { text: text.slice(start, end), start, end, next: end < text.length ? end : null, found: true }; }