turno-cli 0.0.0-stage → 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 (83) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/README.md +334 -2
  5. package/dist/accounts/audit.js +54 -0
  6. package/dist/accounts/builtin.js +214 -0
  7. package/dist/accounts/delegate.js +185 -0
  8. package/dist/accounts/registry.js +190 -0
  9. package/dist/agents/index.js +101 -0
  10. package/dist/agents/snippets.js +64 -0
  11. package/dist/cli/args.js +47 -0
  12. package/dist/cli/commands/accounts.js +216 -0
  13. package/dist/cli/commands/auto.js +44 -0
  14. package/dist/cli/commands/available.js +18 -0
  15. package/dist/cli/commands/browser.js +175 -0
  16. package/dist/cli/commands/complete.js +112 -0
  17. package/dist/cli/commands/completion.js +57 -0
  18. package/dist/cli/commands/config.js +168 -0
  19. package/dist/cli/commands/doctor.js +324 -0
  20. package/dist/cli/commands/exhausted.js +40 -0
  21. package/dist/cli/commands/handoff.js +118 -0
  22. package/dist/cli/commands/hook.js +63 -0
  23. package/dist/cli/commands/identity.js +114 -0
  24. package/dist/cli/commands/limit.js +102 -0
  25. package/dist/cli/commands/mcp.js +350 -0
  26. package/dist/cli/commands/mcpd.js +161 -0
  27. package/dist/cli/commands/migrate.js +176 -0
  28. package/dist/cli/commands/open.js +60 -0
  29. package/dist/cli/commands/profile.js +259 -0
  30. package/dist/cli/commands/resolve.js +23 -0
  31. package/dist/cli/commands/run.js +15 -0
  32. package/dist/cli/commands/secret.js +123 -0
  33. package/dist/cli/commands/session.js +36 -0
  34. package/dist/cli/commands/sessions.js +27 -0
  35. package/dist/cli/commands/setup.js +224 -0
  36. package/dist/cli/commands/status.js +101 -0
  37. package/dist/cli/commands/statusline.js +275 -0
  38. package/dist/cli/commands/ui.js +276 -0
  39. package/dist/cli/commands/undo.js +67 -0
  40. package/dist/cli/commands/update-check.js +22 -0
  41. package/dist/cli/commands/upgrade.js +162 -0
  42. package/dist/cli/commands/usage.js +167 -0
  43. package/dist/cli/commands/version.js +27 -0
  44. package/dist/cli/commands/which.js +28 -0
  45. package/dist/cli/group.js +50 -0
  46. package/dist/cli/io.js +22 -0
  47. package/dist/cli/launch.js +98 -0
  48. package/dist/cli/launchers.js +200 -0
  49. package/dist/cli/main.js +94 -0
  50. package/dist/cli/registry.js +77 -0
  51. package/dist/core/config-edit.js +42 -0
  52. package/dist/core/config.js +137 -0
  53. package/dist/core/exhausted.js +30 -0
  54. package/dist/core/journal.js +185 -0
  55. package/dist/core/manifest.js +177 -0
  56. package/dist/core/paths.js +54 -0
  57. package/dist/core/profiles.js +61 -0
  58. package/dist/core/ratelimit.js +39 -0
  59. package/dist/core/resolve.js +78 -0
  60. package/dist/core/secrets.js +44 -0
  61. package/dist/core/sessions.js +173 -0
  62. package/dist/core/toml-edit.js +152 -0
  63. package/dist/core/update.js +102 -0
  64. package/dist/core/version.js +103 -0
  65. package/dist/mcpd/cache.js +41 -0
  66. package/dist/mcpd/connectors.js +63 -0
  67. package/dist/mcpd/daemon.js +163 -0
  68. package/dist/mcpd/gateway.js +308 -0
  69. package/dist/mcpd/importer.js +160 -0
  70. package/dist/mcpd/instances.js +303 -0
  71. package/dist/mcpd/jsonrpc.js +19 -0
  72. package/dist/mcpd/launchd.js +86 -0
  73. package/dist/mcpd/peerpid.js +25 -0
  74. package/dist/mcpd/sync.js +208 -0
  75. package/dist/mcpd/upstream.js +232 -0
  76. package/dist/statusline/cost.js +135 -0
  77. package/dist/statusline/render.js +246 -0
  78. package/dist/ui/cmap.js +57 -0
  79. package/dist/ui/fonts.js +107 -0
  80. package/dist/ui/settings.js +69 -0
  81. package/dist/ui/terminal-id.js +30 -0
  82. package/dist/ui/terminals.js +163 -0
  83. package/package.json +69 -3
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ import { realpathSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { UsageError, defaultIo } from "./io.js";
5
+ import { COMMANDS, QUIET, SECTIONS, expand } from "./registry.js";
6
+ async function help(io) {
7
+ io.out("turno: several Claude Code accounts on one machine, sharing context, with a lazy MCP gateway.\n");
8
+ io.out("Usage:");
9
+ io.out(` turno ${"<profile> [claude args]".padEnd(24)} open Claude Code with that account (turno run <profile>)`);
10
+ for (const section of SECTIONS) {
11
+ io.out(`\n${section.title}:`);
12
+ const loaded = await Promise.all(section.commands.map(async (n) => [n, (await COMMANDS[n]()).command]));
13
+ for (const [name, cmd] of loaded)
14
+ io.out(` turno ${name.padEnd(24)} ${cmd.summary}`);
15
+ }
16
+ io.out("\nRun `turno <command> --help` for details. Older names (setup, usage, exhausted, accounts, mcpd,");
17
+ io.out("and the Spanish ones) still work.");
18
+ return 0;
19
+ }
20
+ /** Print the update notice on stderr after an interactive command, at most once a day. */
21
+ async function notice(name, io) {
22
+ if (QUIET.has(name) || !io.isTty || !process.stderr.isTTY)
23
+ return;
24
+ try {
25
+ const { loadConfig } = await import("../core/config.js");
26
+ const { updateNotice } = await import("../core/update.js");
27
+ let configured = true;
28
+ try {
29
+ configured = loadConfig(io.env).updateCheck;
30
+ }
31
+ catch {
32
+ /* default */
33
+ }
34
+ const text = updateNotice(io.env, configured);
35
+ if (text)
36
+ io.err(`\n${text}`);
37
+ }
38
+ catch {
39
+ /* never fail a command over the notice */
40
+ }
41
+ }
42
+ export async function main(argv, io = defaultIo()) {
43
+ const [head, ...tail] = argv;
44
+ if (!head || head === "help" || head === "-h" || head === "--help")
45
+ return help(io);
46
+ if (head === "--version" || head === "-v") {
47
+ const { packageInfo } = await import("../core/version.js");
48
+ io.out(`turno ${packageInfo().version}`);
49
+ return 0;
50
+ }
51
+ const [first, rest] = expand(head, tail);
52
+ const load = COMMANDS[first];
53
+ try {
54
+ if (load) {
55
+ const { command } = await load();
56
+ if (!command.subcommands && (rest[0] === "--help" || rest[0] === "-h")) {
57
+ io.out(command.usage);
58
+ return 0;
59
+ }
60
+ const code = await command.run(rest, io);
61
+ await notice(first, io);
62
+ return code;
63
+ }
64
+ // Anything else is a profile name: exec its launcher.
65
+ const { launchProfile } = await import("./launch.js");
66
+ return await launchProfile(first, rest, io);
67
+ }
68
+ catch (err) {
69
+ if (err instanceof UsageError) {
70
+ io.err(`turno: ${err.message}`);
71
+ return 2;
72
+ }
73
+ const e = err;
74
+ io.err(`turno: ${e.name === "ConfigError" ? e.message : (e.stack ?? e.message)}`);
75
+ return 1;
76
+ }
77
+ }
78
+ function isEntry() {
79
+ try {
80
+ return Boolean(process.argv[1]) && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ if (isEntry()) {
87
+ main(process.argv.slice(2)).then((code) => {
88
+ process.exitCode = code;
89
+ }, (err) => {
90
+ process.stderr.write(`turno: ${err.stack ?? err}\n`);
91
+ process.exitCode = 1;
92
+ });
93
+ }
94
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Every command, loaded lazily so hot paths (`auto`, `resolve`, `statusline`) never pay for
3
+ * the MCP SDK. Order and section decide `turno help`.
4
+ */
5
+ export const SECTIONS = [
6
+ { title: "Start an agent", commands: ["run", "auto"] },
7
+ { title: "Accounts", commands: ["profile", "limit", "session", "open"] },
8
+ { title: "MCP servers and outside services", commands: ["mcp", "identity", "secret", "browser"] },
9
+ { title: "Look", commands: ["ui"] },
10
+ { title: "Maintenance", commands: ["status", "doctor", "config", "undo", "upgrade", "version", "completion", "migrate"] },
11
+ ];
12
+ export const COMMANDS = {
13
+ run: () => import("./commands/run.js"),
14
+ auto: () => import("./commands/auto.js"),
15
+ profile: () => import("./commands/profile.js"),
16
+ limit: () => import("./commands/limit.js"),
17
+ session: () => import("./commands/session.js"),
18
+ open: () => import("./commands/open.js"),
19
+ mcp: () => import("./commands/mcp.js"),
20
+ identity: () => import("./commands/identity.js"),
21
+ secret: () => import("./commands/secret.js"),
22
+ browser: () => import("./commands/browser.js"),
23
+ ui: () => import("./commands/ui.js"),
24
+ status: () => import("./commands/status.js"),
25
+ doctor: () => import("./commands/doctor.js"),
26
+ config: () => import("./commands/config.js"),
27
+ undo: () => import("./commands/undo.js"),
28
+ upgrade: () => import("./commands/upgrade.js"),
29
+ version: () => import("./commands/version.js"),
30
+ completion: () => import("./commands/completion.js"),
31
+ migrate: () => import("./commands/migrate.js"),
32
+ // Called by Claude Code, hooks, launchers and the LaunchAgent; not in the help.
33
+ statusline: () => import("./commands/statusline.js"),
34
+ hook: () => import("./commands/hook.js"),
35
+ resolve: () => import("./commands/resolve.js"),
36
+ mcpd: () => import("./commands/mcpd.js"),
37
+ __complete: () => import("./commands/complete.js"),
38
+ "__update-check": () => import("./commands/update-check.js"),
39
+ };
40
+ /**
41
+ * Earlier names: the 0.1 commands and the Spanish words of the bash script. They keep
42
+ * working so hooks, Orca, skills and muscle memory do not break; the help shows the new ones.
43
+ */
44
+ export const ALIASES = {
45
+ which: ["profile", "which"],
46
+ setup: ["profile", "repair"],
47
+ sessions: ["session", "list"],
48
+ handoff: ["session", "handoff"],
49
+ usage: ["limit", "show"],
50
+ exhausted: ["limit", "set"],
51
+ available: ["limit", "clear"],
52
+ accounts: ["identity"],
53
+ cuenta: ["profile", "which"],
54
+ resolver: ["resolve"],
55
+ sesiones: ["session", "list"],
56
+ uso: ["limit", "show"],
57
+ agotada: ["limit", "set"],
58
+ disponible: ["limit", "clear"],
59
+ limite: ["hook", "rate-limit"],
60
+ abrir: ["open"],
61
+ "sync-mcp": ["mcp", "sync"],
62
+ };
63
+ export const ALIAS_FLAGS = {
64
+ uso: { "--vigilar": "--watch" },
65
+ agotada: { hasta: "until" },
66
+ };
67
+ /** Commands that run on every prompt or launch: no update notice, no extra work. */
68
+ export const QUIET = new Set(["run", "auto", "open", "statusline", "hook", "resolve", "mcpd", "__complete", "__update-check", "completion", "upgrade", "version"]);
69
+ /** Expand an alias: the command name and the arguments it stands for. */
70
+ export function expand(first, rest) {
71
+ const alias = ALIASES[first];
72
+ if (!alias)
73
+ return [first, rest];
74
+ const flags = ALIAS_FLAGS[first] ?? {};
75
+ return [alias[0], [...alias.slice(1), ...rest.map((a) => flags[a] ?? a)]];
76
+ }
77
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1,42 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { UsageError } from "../cli/io.js";
4
+ import { parseConfig } from "./config.js";
5
+ import { paths, tildify } from "./paths.js";
6
+ export class MigrationPending extends UsageError {
7
+ constructor(env) {
8
+ super(`${tildify(paths(env).legacyConfig, env)} still holds the bash claudio config; run turno migrate first`);
9
+ }
10
+ }
11
+ /** True while the bash config is there and config.toml is not: a new config.toml would block migrate. */
12
+ export function migrationPending(env) {
13
+ const p = paths(env);
14
+ return !existsSync(p.configFile) && ["proyectos", "navegador"].some((f) => existsSync(join(p.legacyConfig, f)));
15
+ }
16
+ export function readConfigText(env) {
17
+ try {
18
+ return readFileSync(paths(env).configFile, "utf8");
19
+ }
20
+ catch (err) {
21
+ if (err.code === "ENOENT")
22
+ return "";
23
+ throw err;
24
+ }
25
+ }
26
+ /**
27
+ * Apply a text edit to config.toml: comments and layout stay, the result must parse, and the
28
+ * write goes through the journal. Returns whether anything changed.
29
+ */
30
+ export function editConfig(env, journal, edit) {
31
+ if (migrationPending(env))
32
+ throw new MigrationPending(env);
33
+ const file = paths(env).configFile;
34
+ const before = readConfigText(env);
35
+ const after = edit(before);
36
+ if (after === before)
37
+ return { changed: false, text: after };
38
+ parseConfig(after, file, env);
39
+ journal.write(file, after);
40
+ return { changed: true, text: after };
41
+ }
42
+ //# sourceMappingURL=config-edit.js.map
@@ -0,0 +1,137 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { parse } from "smol-toml";
3
+ import { AGENT_IDS, isAgentId } from "../agents/index.js";
4
+ import { expandHome, paths } from "./paths.js";
5
+ export class ConfigError extends Error {
6
+ constructor(file, message) {
7
+ super(`${file}: ${message}`);
8
+ this.name = "ConfigError";
9
+ }
10
+ }
11
+ const NAME = /^[a-z0-9][a-z0-9_-]*$/;
12
+ export function isValidProfileName(name) {
13
+ return NAME.test(name);
14
+ }
15
+ function str(v, file, key) {
16
+ if (v === undefined)
17
+ return undefined;
18
+ if (typeof v !== "string")
19
+ throw new ConfigError(file, `${key} must be a string`);
20
+ return v;
21
+ }
22
+ export function parseConfig(text, file = "config.toml", env = process.env) {
23
+ let raw;
24
+ try {
25
+ raw = parse(text);
26
+ }
27
+ catch (err) {
28
+ throw new ConfigError(file, err.message);
29
+ }
30
+ const p = paths(env);
31
+ const cfg = {
32
+ icons: "auto",
33
+ nerdTerminals: [],
34
+ updateCheck: true,
35
+ profiles: {},
36
+ agents: {},
37
+ projects: [],
38
+ open: { chromeDir: p.chromeProfilesDir },
39
+ mcpd: { port: 47821 },
40
+ };
41
+ cfg.system = str(raw.system, file, "system");
42
+ cfg.default = str(raw.default, file, "default");
43
+ cfg.fallback = str(raw.fallback, file, "fallback");
44
+ const icons = str(raw.icons, file, "icons");
45
+ if (icons !== undefined) {
46
+ if (icons !== "auto" && icons !== "nerd" && icons !== "unicode") {
47
+ throw new ConfigError(file, "icons must be auto, nerd or unicode");
48
+ }
49
+ cfg.icons = icons;
50
+ }
51
+ const nerd = raw.nerd_terminals;
52
+ if (nerd !== undefined) {
53
+ if (!Array.isArray(nerd) || nerd.some((t) => typeof t !== "string")) {
54
+ throw new ConfigError(file, "nerd_terminals must be an array of terminal names");
55
+ }
56
+ cfg.nerdTerminals = nerd;
57
+ }
58
+ if (raw.update_check !== undefined) {
59
+ if (typeof raw.update_check !== "boolean")
60
+ throw new ConfigError(file, "update_check must be true or false");
61
+ cfg.updateCheck = raw.update_check;
62
+ }
63
+ const profiles = raw.profiles ?? {};
64
+ if (typeof profiles !== "object" || Array.isArray(profiles))
65
+ throw new ConfigError(file, "[profiles] must be a table");
66
+ for (const [name, value] of Object.entries(profiles)) {
67
+ if (!isValidProfileName(name))
68
+ throw new ConfigError(file, `invalid profile name "${name}"`);
69
+ const v = (value ?? {});
70
+ const browser = str(v.browser, file, `profiles.${name}.browser`) ?? "chrome";
71
+ if (browser !== "chrome" && browser !== "default") {
72
+ throw new ConfigError(file, `profiles.${name}.browser must be chrome or default`);
73
+ }
74
+ const color = v.color;
75
+ if (color !== undefined && typeof color !== "string" && typeof color !== "number") {
76
+ throw new ConfigError(file, `profiles.${name}.color must be a name or a number`);
77
+ }
78
+ const agent = v.agent ?? "claude";
79
+ if (!isAgentId(agent))
80
+ throw new ConfigError(file, `profiles.${name}.agent must be one of ${AGENT_IDS.join(", ")}`);
81
+ cfg.profiles[name] = { agent, browser, ...(color !== undefined ? { color } : {}) };
82
+ }
83
+ const agents = raw.agents ?? {};
84
+ if (typeof agents !== "object" || Array.isArray(agents))
85
+ throw new ConfigError(file, "[agents] must be a table");
86
+ for (const [id, value] of Object.entries(agents)) {
87
+ if (!isAgentId(id) || id === "claude") {
88
+ throw new ConfigError(file, `[agents.${id}]: use one of ${AGENT_IDS.filter((a) => a !== "claude").join(", ")} (Claude Code uses the top-level default and fallback)`);
89
+ }
90
+ const v = (value ?? {});
91
+ const roles = {};
92
+ const d = str(v.default, file, `agents.${id}.default`);
93
+ const f = str(v.fallback, file, `agents.${id}.fallback`);
94
+ if (d)
95
+ roles.default = d;
96
+ if (f)
97
+ roles.fallback = f;
98
+ cfg.agents[id] = roles;
99
+ }
100
+ const projects = raw.projects ?? [];
101
+ if (!Array.isArray(projects))
102
+ throw new ConfigError(file, "projects must be an array of tables ([[projects]])");
103
+ for (const [i, item] of projects.entries()) {
104
+ const v = item;
105
+ const path = str(v.path, file, `projects[${i}].path`);
106
+ const profile = str(v.profile, file, `projects[${i}].profile`);
107
+ if (!path || !profile)
108
+ throw new ConfigError(file, `projects[${i}] needs path and profile`);
109
+ cfg.projects.push({ path: expandHome(path, env), profile });
110
+ }
111
+ const open = (raw.open ?? {});
112
+ const chromeDir = str(open.chrome_dir, file, "open.chrome_dir");
113
+ if (chromeDir)
114
+ cfg.open.chromeDir = expandHome(chromeDir, env);
115
+ const mcpd = (raw.mcpd ?? {});
116
+ if (mcpd.port !== undefined) {
117
+ if (typeof mcpd.port !== "number" || !Number.isInteger(mcpd.port) || mcpd.port < 1024 || mcpd.port > 65535) {
118
+ throw new ConfigError(file, "mcpd.port must be an integer between 1024 and 65535");
119
+ }
120
+ cfg.mcpd.port = mcpd.port;
121
+ }
122
+ return cfg;
123
+ }
124
+ /** Load ~/.config/turno/config.toml; a missing file means all defaults. */
125
+ export function loadConfig(env = process.env) {
126
+ const file = paths(env).configFile;
127
+ let text = "";
128
+ try {
129
+ text = readFileSync(file, "utf8");
130
+ }
131
+ catch (err) {
132
+ if (err.code !== "ENOENT")
133
+ throw err;
134
+ }
135
+ return parseConfig(text, file, env);
136
+ }
137
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,30 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { paths } from "./paths.js";
4
+ /** Epoch seconds until which a profile is marked exhausted, or undefined (expired marks are removed). */
5
+ export function exhaustedUntil(profile, env = process.env, now = Date.now() / 1000) {
6
+ const file = join(paths(env).exhaustedDir, profile);
7
+ let until;
8
+ try {
9
+ until = Number.parseFloat(readFileSync(file, "utf8").trim().split(/\s+/)[0] ?? "");
10
+ }
11
+ catch {
12
+ return undefined;
13
+ }
14
+ if (!Number.isFinite(until))
15
+ return undefined;
16
+ if (until < now) {
17
+ rmSync(file, { force: true });
18
+ return undefined;
19
+ }
20
+ return until;
21
+ }
22
+ export function markExhausted(profile, until, env = process.env) {
23
+ const dir = paths(env).exhaustedDir;
24
+ mkdirSync(dir, { recursive: true });
25
+ writeFileSync(join(dir, profile), `${Math.floor(until)}\n`);
26
+ }
27
+ export function clearExhausted(profile, env = process.env) {
28
+ rmSync(join(paths(env).exhaustedDir, profile), { force: true });
29
+ }
30
+ //# sourceMappingURL=exhausted.js.map
@@ -0,0 +1,185 @@
1
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
2
+ import { createHash } from "node:crypto";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { paths } from "./paths.js";
5
+ /** Local "YYYYMMDD-HHMMSS". */
6
+ export function stamp(d = new Date()) {
7
+ const p = (n) => String(n).padStart(2, "0");
8
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
9
+ }
10
+ const MANIFEST = "journal.json";
11
+ function digest(file) {
12
+ try {
13
+ return createHash("sha256").update(readFileSync(file)).digest("hex");
14
+ }
15
+ catch {
16
+ return "absent";
17
+ }
18
+ }
19
+ function real(p) {
20
+ try {
21
+ return realpathSync(p);
22
+ }
23
+ catch {
24
+ // A file that does not exist yet: resolve its folder, which may be a symlink.
25
+ try {
26
+ return join(realpathSync(dirname(p)), basename(p));
27
+ }
28
+ catch {
29
+ return p;
30
+ }
31
+ }
32
+ }
33
+ /** Write text atomically, keeping the mode of the file it replaces. */
34
+ export function atomicWrite(file, data, mode) {
35
+ mkdirSync(dirname(file), { recursive: true });
36
+ const tmp = `${file}.turno-${process.pid}.tmp`;
37
+ writeFileSync(tmp, data, mode !== undefined ? { mode } : undefined);
38
+ if (mode !== undefined)
39
+ chmodSync(tmp, mode);
40
+ renameSync(tmp, file);
41
+ }
42
+ export class Journal {
43
+ env;
44
+ dryRun;
45
+ stamp;
46
+ dir;
47
+ manifest;
48
+ seen = new Set();
49
+ constructor(env, command,
50
+ /** Dry runs record nothing and write nothing. */
51
+ dryRun = false) {
52
+ this.env = env;
53
+ this.dryRun = dryRun;
54
+ const root = paths(env).backupsDir;
55
+ let s = stamp();
56
+ for (let n = 2; existsSync(join(root, s)); n++)
57
+ s = `${stamp()}-${n}`;
58
+ this.stamp = s;
59
+ this.dir = join(root, s);
60
+ this.manifest = { version: 1, stamp: s, command, created: new Date().toISOString(), entries: [] };
61
+ }
62
+ get used() {
63
+ return this.manifest.entries.length > 0;
64
+ }
65
+ /** Record what `file` holds now (once per path). Returns the real path it resolved to. */
66
+ save(file) {
67
+ const target = real(file);
68
+ if (this.dryRun || this.seen.has(target))
69
+ return target;
70
+ this.seen.add(target);
71
+ const entry = { path: target, existed: existsSync(target) };
72
+ if (entry.existed) {
73
+ const st = statSync(target);
74
+ if (!st.isFile())
75
+ throw new Error(`${target} is not a regular file; turno only journals files`);
76
+ entry.mode = st.mode & 0o777;
77
+ entry.backup = join("files", `${this.manifest.entries.length}-${basename(target)}`);
78
+ mkdirSync(join(this.dir, "files"), { recursive: true });
79
+ copyFileSync(target, join(this.dir, entry.backup));
80
+ }
81
+ this.manifest.entries.push(entry);
82
+ this.flush();
83
+ return target;
84
+ }
85
+ /** Record what a saved file holds after the command changed it by its own means. */
86
+ settle(file) {
87
+ if (this.dryRun)
88
+ return;
89
+ const target = real(file);
90
+ const entry = this.manifest.entries.find((e) => e.path === target);
91
+ if (!entry)
92
+ return;
93
+ entry.wrote = digest(target);
94
+ this.flush();
95
+ }
96
+ flush() {
97
+ mkdirSync(this.dir, { recursive: true });
98
+ writeFileSync(join(this.dir, MANIFEST), `${JSON.stringify(this.manifest, null, 2)}\n`);
99
+ }
100
+ /** Save, then write atomically through symlinks so linked profiles keep linking. */
101
+ write(file, data, mode) {
102
+ if (this.dryRun)
103
+ return;
104
+ const target = this.save(file);
105
+ let keep = mode;
106
+ if (keep === undefined) {
107
+ try {
108
+ keep = statSync(target).mode & 0o777;
109
+ }
110
+ catch {
111
+ keep = undefined;
112
+ }
113
+ }
114
+ atomicWrite(target, data, keep);
115
+ this.settle(target);
116
+ }
117
+ remove(file) {
118
+ if (this.dryRun)
119
+ return;
120
+ const target = this.save(file);
121
+ rmSync(target, { force: true });
122
+ this.settle(target);
123
+ }
124
+ /** The `turno undo` hint to print after a command that changed something. */
125
+ hint() {
126
+ return this.used ? `undo with: turno undo ${this.stamp}` : undefined;
127
+ }
128
+ }
129
+ /** Backup folders, newest first. */
130
+ export function listJournals(env = process.env) {
131
+ const root = paths(env).backupsDir;
132
+ let names = [];
133
+ try {
134
+ names = readdirSync(root);
135
+ }
136
+ catch {
137
+ return [];
138
+ }
139
+ return names
140
+ .filter((n) => /^\d{8}-\d{6}/.test(n))
141
+ .sort()
142
+ .reverse()
143
+ .map((n) => {
144
+ const dir = join(root, n);
145
+ try {
146
+ return { stamp: n, dir, manifest: JSON.parse(readFileSync(join(dir, MANIFEST), "utf8")) };
147
+ }
148
+ catch {
149
+ return { stamp: n, dir };
150
+ }
151
+ });
152
+ }
153
+ /**
154
+ * Put back every file of a journal. The current contents are journaled first, so an undo can
155
+ * itself be undone.
156
+ */
157
+ export function undoJournal(info, env, opts = {}) {
158
+ const dryRun = Boolean(opts.dryRun);
159
+ const m = info.manifest;
160
+ if (!m)
161
+ throw new Error(`${info.stamp} was written before journals existed; restore it by hand from ${info.dir}`);
162
+ const journal = new Journal(env, `undo ${info.stamp}`, dryRun);
163
+ const steps = [];
164
+ for (const e of [...m.entries].reverse()) {
165
+ if (!opts.force && e.wrote && digest(e.path) !== e.wrote) {
166
+ steps.push({ path: e.path, action: "skip", reason: "changed since; --force puts the old copy back anyway" });
167
+ continue;
168
+ }
169
+ if (e.existed && e.backup) {
170
+ steps.push({ path: e.path, action: "restore" });
171
+ journal.write(e.path, readFileSync(join(info.dir, e.backup)), e.mode);
172
+ }
173
+ else {
174
+ steps.push({ path: e.path, action: "delete" });
175
+ if (existsSync(e.path))
176
+ journal.remove(e.path);
177
+ }
178
+ }
179
+ if (!dryRun) {
180
+ m.undoneBy = journal.stamp;
181
+ writeFileSync(join(info.dir, MANIFEST), `${JSON.stringify(m, null, 2)}\n`);
182
+ }
183
+ return { steps, journal };
184
+ }
185
+ //# sourceMappingURL=journal.js.map