dsh-better-edit 0.1.0

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.
Files changed (82) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +188 -0
  3. package/cordis.patch.yml +8 -0
  4. package/lib/constants.js +12 -0
  5. package/lib/drift.js +98 -0
  6. package/lib/dsh-context.js +27 -0
  7. package/lib/edit-diff.js +121 -0
  8. package/lib/edit-normalize.js +9 -0
  9. package/lib/edit-pipeline.js +199 -0
  10. package/lib/edit-response.js +172 -0
  11. package/lib/file-kind.js +121 -0
  12. package/lib/file-reader.js +80 -0
  13. package/lib/fs-bridge.js +106 -0
  14. package/lib/fs-write.js +151 -0
  15. package/lib/hash-store.js +380 -0
  16. package/lib/hashline/alphabet.js +6 -0
  17. package/lib/hashline/apply.js +223 -0
  18. package/lib/hashline/hash.js +241 -0
  19. package/lib/hashline/hasher.js +23 -0
  20. package/lib/hashline/index.js +4 -0
  21. package/lib/hashline/parse.js +35 -0
  22. package/lib/hashline/resolve.js +365 -0
  23. package/lib/hashline/served.js +120 -0
  24. package/lib/index.js +91 -0
  25. package/lib/noop-guard.js +15 -0
  26. package/lib/paths.js +37 -0
  27. package/lib/prompts.js +54 -0
  28. package/lib/read-render.js +142 -0
  29. package/lib/schema.js +24 -0
  30. package/lib/served-state.js +34 -0
  31. package/lib/served-store.js +230 -0
  32. package/lib/snapshot-store.js +108 -0
  33. package/lib/tool-batch-edit.js +434 -0
  34. package/lib/tool-edit.js +152 -0
  35. package/lib/tool-read.js +86 -0
  36. package/lib/tool-undo.js +118 -0
  37. package/lib/truncate.js +98 -0
  38. package/lib/types/constants.d.ts +11 -0
  39. package/lib/types/drift.d.ts +29 -0
  40. package/lib/types/dsh-context.d.ts +23 -0
  41. package/lib/types/edit-diff.d.ts +14 -0
  42. package/lib/types/edit-normalize.d.ts +1 -0
  43. package/lib/types/edit-pipeline.d.ts +54 -0
  44. package/lib/types/edit-response.d.ts +107 -0
  45. package/lib/types/file-kind.d.ts +18 -0
  46. package/lib/types/file-reader.d.ts +47 -0
  47. package/lib/types/fs-bridge.d.ts +32 -0
  48. package/lib/types/fs-write.d.ts +2 -0
  49. package/lib/types/hash-store.d.ts +33 -0
  50. package/lib/types/hashline/alphabet.d.ts +5 -0
  51. package/lib/types/hashline/apply.d.ts +22 -0
  52. package/lib/types/hashline/hash.d.ts +19 -0
  53. package/lib/types/hashline/hasher.d.ts +8 -0
  54. package/lib/types/hashline/index.d.ts +4 -0
  55. package/lib/types/hashline/parse.d.ts +7 -0
  56. package/lib/types/hashline/resolve.d.ts +59 -0
  57. package/lib/types/hashline/served.d.ts +43 -0
  58. package/lib/types/index.d.ts +23 -0
  59. package/lib/types/noop-guard.d.ts +5 -0
  60. package/lib/types/paths.d.ts +11 -0
  61. package/lib/types/prompts.d.ts +17 -0
  62. package/lib/types/read-render.d.ts +21 -0
  63. package/lib/types/schema.d.ts +39 -0
  64. package/lib/types/served-state.d.ts +3 -0
  65. package/lib/types/served-store.d.ts +53 -0
  66. package/lib/types/snapshot-store.d.ts +14 -0
  67. package/lib/types/tool-batch-edit.d.ts +21 -0
  68. package/lib/types/tool-edit.d.ts +22 -0
  69. package/lib/types/tool-read.d.ts +21 -0
  70. package/lib/types/tool-undo.d.ts +20 -0
  71. package/lib/types/truncate.d.ts +32 -0
  72. package/lib/types/undo-edit.d.ts +32 -0
  73. package/lib/types/undo-store.d.ts +14 -0
  74. package/lib/types/utils.d.ts +13 -0
  75. package/lib/types/validation.d.ts +7 -0
  76. package/lib/types/write-hook.d.ts +21 -0
  77. package/lib/undo-edit.js +83 -0
  78. package/lib/undo-store.js +43 -0
  79. package/lib/utils.js +76 -0
  80. package/lib/validation.js +33 -0
  81. package/lib/write-hook.js +72 -0
  82. package/package.json +87 -0
@@ -0,0 +1,151 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, open, readdir, readlink, rename, rm, stat, writeFile, } from "fs/promises";
3
+ import { dirname, join, parse, resolve, sep } from "node:path";
4
+ import { errCode } from "./utils.js";
5
+ export async function resolveTarget(path) {
6
+ const absolutePath = resolve(path);
7
+ const { root } = parse(absolutePath);
8
+ const parts = absolutePath
9
+ .slice(root.length)
10
+ .split(sep)
11
+ .filter((part) => part.length > 0);
12
+ const visitedSymlinks = new Set();
13
+ async function resParts(currentPath, remainingParts) {
14
+ if (remainingParts.length === 0) {
15
+ return currentPath;
16
+ }
17
+ const [nextPart, ...tail] = remainingParts;
18
+ const candidatePath = join(currentPath, nextPart);
19
+ try {
20
+ const candidateStats = await lstat(candidatePath);
21
+ if (!candidateStats.isSymbolicLink()) {
22
+ return resParts(candidatePath, tail);
23
+ }
24
+ if (visitedSymlinks.has(candidatePath)) {
25
+ const error = new Error(`Too many symbolic links while resolving ${path}`);
26
+ error.code = "ELOOP";
27
+ throw error;
28
+ }
29
+ visitedSymlinks.add(candidatePath);
30
+ const linkTargetPath = resolve(dirname(candidatePath), await readlink(candidatePath));
31
+ const targetParts = linkTargetPath
32
+ .slice(parse(linkTargetPath).root.length)
33
+ .split(sep)
34
+ .filter((part) => part.length > 0);
35
+ return resParts(parse(linkTargetPath).root, [
36
+ ...targetParts,
37
+ ...tail,
38
+ ]);
39
+ }
40
+ catch (error) {
41
+ if (errCode(error) === "ENOENT") {
42
+ return join(candidatePath, ...tail);
43
+ }
44
+ throw error;
45
+ }
46
+ }
47
+ return resParts(root, parts);
48
+ }
49
+ const TEMP_PREFIX = ".tmp-";
50
+ const TEMP_UUID_RE = /^\.tmp-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
51
+ const STALE_TEMP_MS = 60 * 60 * 1000;
52
+ const sweptDirs = new Set();
53
+ async function sweepStaleTemps(dir) {
54
+ if (sweptDirs.has(dir))
55
+ return;
56
+ sweptDirs.add(dir);
57
+ try {
58
+ const entries = await readdir(dir, { withFileTypes: true });
59
+ const now = Date.now();
60
+ for (const entry of entries) {
61
+ if (!entry.isFile() || !TEMP_UUID_RE.test(entry.name))
62
+ continue;
63
+ const tempPath = join(dir, entry.name);
64
+ try {
65
+ const stats = await stat(tempPath);
66
+ if (now - stats.mtimeMs > STALE_TEMP_MS) {
67
+ await rm(tempPath, { force: true });
68
+ }
69
+ }
70
+ catch {
71
+ }
72
+ }
73
+ }
74
+ catch {
75
+ }
76
+ }
77
+ async function syncDir(dir) {
78
+ if (process.platform === "win32")
79
+ return;
80
+ try {
81
+ const handle = await open(dir, "r");
82
+ try {
83
+ await handle.sync();
84
+ }
85
+ finally {
86
+ await handle.close();
87
+ }
88
+ }
89
+ catch {
90
+ }
91
+ }
92
+ export async function writeAtomic(path, content) {
93
+ const targetPath = await resolveTarget(path);
94
+ let existingStats = null;
95
+ try {
96
+ existingStats = await stat(targetPath);
97
+ }
98
+ catch (error) {
99
+ if (errCode(error) !== "ENOENT") {
100
+ throw error;
101
+ }
102
+ }
103
+ if (existingStats && existingStats.nlink > 1) {
104
+ await writeFile(targetPath, content, "utf-8");
105
+ return;
106
+ }
107
+ const dir = dirname(targetPath);
108
+ await sweepStaleTemps(dir);
109
+ const tempPath = join(dir, `${TEMP_PREFIX}${randomUUID()}`);
110
+ await mkdir(dir, { recursive: true });
111
+ const tempHandle = await open(tempPath, "wx", 0o600);
112
+ try {
113
+ await tempHandle.writeFile(content, "utf-8");
114
+ if (existingStats) {
115
+ await tempHandle.chmod(existingStats.mode & 0o7777);
116
+ }
117
+ await tempHandle.sync();
118
+ }
119
+ catch (error) {
120
+ await tempHandle.close();
121
+ try {
122
+ await rm(tempPath, { force: true });
123
+ }
124
+ catch { }
125
+ throw error;
126
+ }
127
+ try {
128
+ await tempHandle.close();
129
+ await rename(tempPath, targetPath);
130
+ await syncDir(dir);
131
+ }
132
+ catch (error) {
133
+ if (process.platform === "win32" && errCode(error) === "EPERM") {
134
+ try {
135
+ await writeFile(targetPath, content, "utf-8");
136
+ return;
137
+ }
138
+ finally {
139
+ try {
140
+ await rm(tempPath, { force: true });
141
+ }
142
+ catch { }
143
+ }
144
+ }
145
+ try {
146
+ await rm(tempPath, { force: true });
147
+ }
148
+ catch { }
149
+ throw error;
150
+ }
151
+ }
@@ -0,0 +1,380 @@
1
+ import { existsSync } from "node:fs";
2
+ import { readFile, rename, mkdir } from "fs/promises";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ import { hashStorePath, hashStoreDir, legacyHashStorePath } from "./paths.js";
5
+ import { errCode, splitLines } from "./utils.js";
6
+ import { initHasher, contentChecksum } from "./hashline/hasher.js";
7
+ import { HASH_STORE_VERSION, HASH_STORE_BUSY_TIMEOUT, SERVED_TTL_MS } from "./constants.js";
8
+ import { isValidSnapshot } from "./snapshot-store.js";
9
+ export function isCorruptionError(error) {
10
+ if (error && typeof error === "object") {
11
+ const errcode = error.errcode;
12
+ if (typeof errcode === "number") {
13
+ return errcode === 11 || errcode === 24 || errcode === 26;
14
+ }
15
+ const code = error.code;
16
+ if (typeof code === "string" && /NOTADB|CORRUPT/.test(code))
17
+ return true;
18
+ }
19
+ return (error instanceof Error &&
20
+ /corrupt|not a database|malformed|database disk image/i.test(error.message));
21
+ }
22
+ function isBusyError(error) {
23
+ if (error && typeof error === "object") {
24
+ const errcode = error.errcode;
25
+ if (typeof errcode === "number")
26
+ return errcode === 5 || errcode === 6;
27
+ }
28
+ return error instanceof Error && /busy|locked/i.test(error.message);
29
+ }
30
+ function sleepSync(ms) {
31
+ const sab = new Int32Array(new SharedArrayBuffer(4));
32
+ Atomics.wait(sab, 0, 0, ms);
33
+ }
34
+ const BUSY_RETRIES = 3;
35
+ const BUSY_RETRY_DELAY_MS = 100;
36
+ function withBusyRetry(fn) {
37
+ let lastError;
38
+ for (let attempt = 0; attempt <= BUSY_RETRIES; attempt++) {
39
+ try {
40
+ return fn();
41
+ }
42
+ catch (error) {
43
+ lastError = error;
44
+ if (!isBusyError(error) || attempt === BUSY_RETRIES)
45
+ throw error;
46
+ sleepSync(BUSY_RETRY_DELAY_MS);
47
+ }
48
+ }
49
+ throw lastError;
50
+ }
51
+ function openDbWithBusyRetry(storePath) {
52
+ return withBusyRetry(() => openDb(storePath));
53
+ }
54
+ let cachedDb = null;
55
+ let opening = null;
56
+ let exitHandlerRegistered = false;
57
+ function openDb(storePath) {
58
+ const db = new DatabaseSync(storePath, {
59
+ timeout: HASH_STORE_BUSY_TIMEOUT,
60
+ });
61
+ try {
62
+ return buildStore(db);
63
+ }
64
+ catch (error) {
65
+ try {
66
+ db.close();
67
+ }
68
+ catch { }
69
+ throw error;
70
+ }
71
+ }
72
+ function buildStore(db) {
73
+ db.exec("PRAGMA journal_mode = WAL");
74
+ db.exec("PRAGMA synchronous = NORMAL");
75
+ db.exec("CREATE TABLE IF NOT EXISTS snapshots (" +
76
+ "path TEXT PRIMARY KEY, " +
77
+ "checksum TEXT NOT NULL, " +
78
+ "line_count INTEGER NOT NULL, " +
79
+ "hashes TEXT NOT NULL, " +
80
+ "updated_at INTEGER NOT NULL" +
81
+ ")");
82
+ db.exec("CREATE TABLE IF NOT EXISTS meta (" +
83
+ "key TEXT PRIMARY KEY, " +
84
+ "value TEXT NOT NULL" +
85
+ ")");
86
+ db.exec("CREATE TABLE IF NOT EXISTS undo (" +
87
+ "path TEXT PRIMARY KEY, " +
88
+ "content TEXT NOT NULL, " +
89
+ "bom TEXT NOT NULL, " +
90
+ "ending TEXT NOT NULL, " +
91
+ "hashes TEXT NOT NULL, " +
92
+ "result_content TEXT NOT NULL, " +
93
+ "updated_at INTEGER NOT NULL" +
94
+ ")");
95
+ const versionRow = db
96
+ .prepare("SELECT value FROM meta WHERE key = 'version'")
97
+ .get();
98
+ const versionChanged = versionRow !== undefined &&
99
+ versionRow.value !== String(HASH_STORE_VERSION);
100
+ if (versionChanged) {
101
+ db.exec("DELETE FROM snapshots");
102
+ db.exec("DELETE FROM undo");
103
+ }
104
+ const servedColumns = db.prepare("PRAGMA table_info(served)").all();
105
+ if (versionChanged ||
106
+ !servedColumns.some((column) => column.name === "session_id")) {
107
+ db.exec("DROP TABLE IF EXISTS served");
108
+ }
109
+ db.exec("CREATE TABLE IF NOT EXISTS served (" +
110
+ "session_id TEXT NOT NULL, " +
111
+ "path TEXT NOT NULL, " +
112
+ "hashes TEXT NOT NULL, " +
113
+ "reported TEXT, " +
114
+ "updated_at INTEGER NOT NULL, " +
115
+ "PRIMARY KEY (session_id, path)" +
116
+ ")");
117
+ db.prepare("INSERT INTO meta (key, value) VALUES ('version', ?) " +
118
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(String(HASH_STORE_VERSION));
119
+ const getStmt = db.prepare("SELECT hashes FROM snapshots WHERE path = ? AND checksum = ? AND line_count = ?");
120
+ const allStmt = db.prepare("SELECT path FROM snapshots UNION SELECT path FROM undo UNION SELECT path FROM served");
121
+ const allHashesStmt = db.prepare("SELECT path, hashes FROM snapshots");
122
+ const delStmt = db.prepare("DELETE FROM snapshots WHERE path = ?");
123
+ const upsertStmt = db.prepare("INSERT INTO snapshots (path, checksum, line_count, hashes, updated_at) VALUES (?, ?, ?, ?, ?) " +
124
+ "ON CONFLICT(path) DO UPDATE SET checksum = excluded.checksum, line_count = excluded.line_count, hashes = excluded.hashes, updated_at = excluded.updated_at");
125
+ const undoUpsertStmt = db.prepare("INSERT INTO undo (path, content, bom, ending, hashes, result_content, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) " +
126
+ "ON CONFLICT(path) DO UPDATE SET content = excluded.content, bom = excluded.bom, ending = excluded.ending, hashes = excluded.hashes, result_content = excluded.result_content, updated_at = excluded.updated_at");
127
+ const undoGetStmt = db.prepare("SELECT content, bom, ending, hashes, result_content FROM undo WHERE path = ?");
128
+ const undoDelStmt = db.prepare("DELETE FROM undo WHERE path = ?");
129
+ const servedGetStmt = db.prepare("SELECT hashes, reported FROM served WHERE session_id = ? AND path = ?");
130
+ const servedUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, updated_at) VALUES (?, ?, ?, ?) " +
131
+ "ON CONFLICT(session_id, path) DO UPDATE SET hashes = excluded.hashes, updated_at = excluded.updated_at");
132
+ const servedReportedUpsertStmt = db.prepare("INSERT INTO served (session_id, path, hashes, reported, updated_at) VALUES (?, ?, '[]', ?, ?) " +
133
+ "ON CONFLICT(session_id, path) DO UPDATE SET reported = excluded.reported, updated_at = excluded.updated_at");
134
+ const servedReportedClearStmt = db.prepare("UPDATE served SET reported = NULL, updated_at = ? WHERE session_id = ? AND path = ?");
135
+ const servedDeleteStmt = db.prepare("DELETE FROM served WHERE session_id = ? AND path = ?");
136
+ const servedDeletePathStmt = db.prepare("DELETE FROM served WHERE path = ?");
137
+ const servedWipeStmt = db.prepare("DELETE FROM served WHERE session_id = ?");
138
+ const servedPruneOlderThanStmt = db.prepare("DELETE FROM served WHERE updated_at < ?");
139
+ const stmts = {
140
+ get: (...params) => getStmt.get(...params),
141
+ allPaths: (...params) => allStmt.all(...params),
142
+ allHashes: (...params) => allHashesStmt.all(...params),
143
+ deleteOne: (...params) => {
144
+ withBusyRetry(() => {
145
+ delStmt.run(...params);
146
+ });
147
+ },
148
+ upsert: (...params) => {
149
+ withBusyRetry(() => {
150
+ upsertStmt.run(...params);
151
+ });
152
+ },
153
+ undoUpsert: (...params) => {
154
+ withBusyRetry(() => {
155
+ undoUpsertStmt.run(...params);
156
+ });
157
+ },
158
+ undoGet: (...params) => undoGetStmt.get(...params),
159
+ undoDelete: (...params) => {
160
+ withBusyRetry(() => {
161
+ undoDelStmt.run(...params);
162
+ });
163
+ },
164
+ servedGet: (...params) => servedGetStmt.get(...params),
165
+ servedUpsert: (...params) => {
166
+ withBusyRetry(() => {
167
+ servedUpsertStmt.run(...params);
168
+ });
169
+ },
170
+ servedReportedUpsert: (...params) => {
171
+ withBusyRetry(() => {
172
+ servedReportedUpsertStmt.run(...params);
173
+ });
174
+ },
175
+ servedReportedClear: (...params) => {
176
+ withBusyRetry(() => {
177
+ servedReportedClearStmt.run(params[1], params[0], params[2]);
178
+ });
179
+ },
180
+ servedDelete: (...params) => {
181
+ withBusyRetry(() => {
182
+ servedDeleteStmt.run(...params);
183
+ });
184
+ },
185
+ servedDeletePath: (...params) => {
186
+ withBusyRetry(() => {
187
+ servedDeletePathStmt.run(...params);
188
+ });
189
+ },
190
+ servedWipe: (...params) => {
191
+ withBusyRetry(() => {
192
+ servedWipeStmt.run(...params);
193
+ });
194
+ },
195
+ servedPruneOlderThan: (...params) => {
196
+ withBusyRetry(() => {
197
+ servedPruneOlderThanStmt.run(...params);
198
+ });
199
+ },
200
+ };
201
+ return { db, stmts };
202
+ }
203
+ function isHealthy(db) {
204
+ try {
205
+ const row = db.prepare("PRAGMA quick_check").get();
206
+ return row?.quick_check === "ok";
207
+ }
208
+ catch (error) {
209
+ if (isCorruptionError(error))
210
+ return false;
211
+ return true;
212
+ }
213
+ }
214
+ async function quarantineStore(storePath) {
215
+ const suffix = `.corrupt-${Date.now()}`;
216
+ for (const candidate of [storePath, `${storePath}-wal`, `${storePath}-shm`]) {
217
+ try {
218
+ await rename(candidate, `${candidate}${suffix}`);
219
+ }
220
+ catch (error) {
221
+ if (errCode(error) !== "ENOENT") {
222
+ console.error("Failed to quarantine corrupt hash store file:", error);
223
+ }
224
+ }
225
+ }
226
+ }
227
+ function shutdownDb(db) {
228
+ try {
229
+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
230
+ }
231
+ catch { }
232
+ db.close();
233
+ }
234
+ async function openStore(storePath) {
235
+ shutdownHashStore();
236
+ await initHasher();
237
+ await mkdir(hashStoreDir(), { recursive: true });
238
+ let existed = existsSync(storePath);
239
+ let opened;
240
+ try {
241
+ opened = openDbWithBusyRetry(storePath);
242
+ }
243
+ catch (error) {
244
+ if (!isCorruptionError(error))
245
+ throw error;
246
+ console.error("Hash store failed to open, rebuilding:", error);
247
+ await quarantineStore(storePath);
248
+ existed = false;
249
+ opened = openDbWithBusyRetry(storePath);
250
+ }
251
+ if (!isHealthy(opened.db)) {
252
+ shutdownDb(opened.db);
253
+ await quarantineStore(storePath);
254
+ existed = false;
255
+ opened = openDbWithBusyRetry(storePath);
256
+ }
257
+ const { db, stmts } = opened;
258
+ if (!existed) {
259
+ await migrateLegacy(db);
260
+ }
261
+ withBusyRetry(() => {
262
+ stmts.servedPruneOlderThan(Date.now() - SERVED_TTL_MS);
263
+ });
264
+ cachedDb = { path: storePath, db, stmts };
265
+ if (!exitHandlerRegistered) {
266
+ exitHandlerRegistered = true;
267
+ process.once("exit", () => shutdownHashStore());
268
+ for (const sig of ["SIGINT", "SIGTERM"]) {
269
+ process.once(sig, () => {
270
+ shutdownHashStore();
271
+ process.kill(process.pid, sig);
272
+ });
273
+ }
274
+ }
275
+ return { stmts, engine: "node:sqlite" };
276
+ }
277
+ export function loadHashStore() {
278
+ const storePath = hashStorePath();
279
+ if (cachedDb && cachedDb.path === storePath && cachedDb.db.isOpen) {
280
+ return Promise.resolve({ stmts: cachedDb.stmts, engine: "node:sqlite" });
281
+ }
282
+ if (opening && opening.path === storePath) {
283
+ return opening.promise;
284
+ }
285
+ const promise = openStore(storePath).finally(() => {
286
+ if (opening?.path === storePath)
287
+ opening = null;
288
+ });
289
+ opening = { path: storePath, promise };
290
+ return promise;
291
+ }
292
+ export function shutdownHashStore() {
293
+ if (cachedDb) {
294
+ shutdownDb(cachedDb.db);
295
+ cachedDb = null;
296
+ }
297
+ }
298
+ export function withStore(fn) {
299
+ if (cachedDb) {
300
+ withBusyRetry(() => {
301
+ cachedDb.db.exec("BEGIN IMMEDIATE");
302
+ try {
303
+ fn();
304
+ cachedDb.db.exec("COMMIT");
305
+ }
306
+ catch (e) {
307
+ try {
308
+ cachedDb.db.exec("ROLLBACK");
309
+ }
310
+ catch { }
311
+ throw e;
312
+ }
313
+ });
314
+ }
315
+ else {
316
+ fn();
317
+ }
318
+ }
319
+ async function migrateLegacy(db) {
320
+ const legacyPath = legacyHashStorePath();
321
+ let content;
322
+ try {
323
+ content = await readFile(legacyPath, "utf-8");
324
+ }
325
+ catch (error) {
326
+ if (errCode(error) === "ENOENT")
327
+ return;
328
+ console.error("Failed to read legacy hash store for migration:", error);
329
+ return;
330
+ }
331
+ let parsed;
332
+ try {
333
+ parsed = JSON.parse(content);
334
+ }
335
+ catch (error) {
336
+ console.error("Failed to parse legacy hash store, skipping migration:", error);
337
+ return;
338
+ }
339
+ const raw = parsed.snapshots;
340
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
341
+ return;
342
+ const rows = [];
343
+ for (const [key, value] of Object.entries(raw)) {
344
+ if (!isValidSnapshot(value))
345
+ continue;
346
+ if (new Set(value.hashes).size !== value.hashes.length) {
347
+ console.warn(`Skipped legacy snapshot with duplicate hashes for ${key}; it will be re-hashed on next read.`);
348
+ continue;
349
+ }
350
+ rows.push([
351
+ key,
352
+ contentChecksum(value.content),
353
+ splitLines(value.content).length,
354
+ JSON.stringify(value.hashes),
355
+ Date.now(),
356
+ ]);
357
+ }
358
+ if (rows.length > 0) {
359
+ db.exec("BEGIN IMMEDIATE");
360
+ try {
361
+ const stmt = db.prepare("INSERT OR REPLACE INTO snapshots (path, checksum, line_count, hashes, updated_at) VALUES (?, ?, ?, ?, ?)");
362
+ for (const row of rows)
363
+ stmt.run(...row);
364
+ db.exec("COMMIT");
365
+ }
366
+ catch (e) {
367
+ db.exec("ROLLBACK");
368
+ throw e;
369
+ }
370
+ }
371
+ try {
372
+ await rename(legacyPath, `${legacyPath}.bak`);
373
+ }
374
+ catch (error) {
375
+ console.error("Failed to rename legacy hash store after migration:", error);
376
+ }
377
+ }
378
+ export { getSnapshot, upsertSnapshot, findSnapshotPaths, pruneMissing, isValidHashList, isValidSnapshot, } from "./snapshot-store.js";
379
+ export { getServed, upsertServed, recordServes, getReported, addReported, clearReported, deleteServed, wipeServed, } from "./served-store.js";
380
+ export { upsertUndo, getUndoEntry, deleteUndo, } from "./undo-store.js";
@@ -0,0 +1,6 @@
1
+ export const HASH_LEN = 3;
2
+ export const ALPH = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
3
+ const ALPH_SAFE = ALPH.replace(/-/g, "\\-");
4
+ export const ALPH_RE = new RegExp(`^[${ALPH_SAFE}]+$`);
5
+ export const HASH_CLASS = `[${ALPH_SAFE}]{${HASH_LEN}}`;
6
+ export const HASH_RE = new RegExp(`^${HASH_CLASS}$`);