-
Notifications
You must be signed in to change notification settings - Fork 323
Expand file tree
/
Copy pathdraft.ts
More file actions
64 lines (58 loc) · 1.7 KB
/
draft.ts
File metadata and controls
64 lines (58 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Draft Storage
*
* Persists annotation drafts to the plannotator state directory so they
* survive server crashes. Each draft is keyed by a content hash of the
* plan/diff it was created against.
*
* Runtime-agnostic: uses only node:fs, node:path, node:os, node:crypto.
*/
import { join } from "path";
import { mkdirSync, writeFileSync, readFileSync, unlinkSync, existsSync } from "fs";
import { createHash } from "crypto";
import { getStateBase } from "./paths";
/**
* Get the drafts directory, creating it if needed.
*/
export function getDraftDir(): string {
const dir = join(getStateBase(), "drafts");
mkdirSync(dir, { recursive: true });
return dir;
}
/**
* Generate a stable key from content using truncated SHA-256.
* Same content always produces the same key across server restarts.
*/
export function contentHash(content: string): string {
return createHash("sha256").update(content).digest("hex").slice(0, 16);
}
/**
* Save a draft to disk.
*/
export function saveDraft(key: string, data: object): void {
const dir = getDraftDir();
writeFileSync(join(dir, `${key}.json`), JSON.stringify(data), "utf-8");
}
/**
* Load a draft from disk. Returns null if not found.
*/
export function loadDraft(key: string): object | null {
const filePath = join(getDraftDir(), `${key}.json`);
try {
if (!existsSync(filePath)) return null;
return JSON.parse(readFileSync(filePath, "utf-8"));
} catch {
return null;
}
}
/**
* Delete a draft from disk. No-op if not found.
*/
export function deleteDraft(key: string): void {
const filePath = join(getDraftDir(), `${key}.json`);
try {
if (existsSync(filePath)) unlinkSync(filePath);
} catch {
// Ignore delete failures
}
}