File size: 1,530 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync, rmSync } from "node:fs";
import { join } from "node:path";
import { resolveDataDir } from "../data-dir.mjs";

function sessionsDir() {
  const dir = join(resolveDataDir(), "repl-sessions");
  if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
  return dir;
}

export function saveSession(name, session) {
  const path = join(sessionsDir(), `${name}.json`);
  writeFileSync(
    path,
    JSON.stringify({ ...session, name, updatedAt: new Date().toISOString() }, null, 2)
  );
}

export function loadSession(name) {
  const path = join(sessionsDir(), `${name}.json`);
  if (!existsSync(path)) throw new Error(`session '${name}' not found`);
  return JSON.parse(readFileSync(path, "utf8"));
}

export function listSessions() {
  const dir = sessionsDir();
  return readdirSync(dir)
    .filter((f) => f.endsWith(".json"))
    .map((f) => {
      try {
        const data = JSON.parse(readFileSync(join(dir, f), "utf8"));
        return {
          name: data.name || f.replace(".json", ""),
          updatedAt: data.updatedAt,
          model: data.model,
        };
      } catch {
        return { name: f.replace(".json", ""), updatedAt: null, model: null };
      }
    });
}

export function autosave(session) {
  try {
    saveSession("autosave", session);
  } catch {
    // autosave failure is not fatal
  }
}

export function deleteSession(name) {
  const path = join(sessionsDir(), `${name}.json`);
  if (existsSync(path)) rmSync(path);
}