nemu-cli 1.6.1 → 1.8.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.
package/dist/index.js CHANGED
@@ -62,115 +62,119 @@ const COMMANDS = {
62
62
  vault,
63
63
  sync,
64
64
  };
65
- const HELP = `
66
- ${bold("nemu")} ${dim(VERSION)}
67
-
68
- ${bold("Context for coding agents")}
69
- setup <claude|codex> [--hooks|--no-hooks] [--yes]
70
- Connect Claude Code (aliases cc, claude-code) or Codex
71
- setup <cursor|vscode|gemini|windsurf|zed|opencode>
72
- Add the Nemu MCP server to that editor's config
73
- claude [-- <claude args>] Set up if needed, then start Claude Code
74
- codex [-- <codex args>] Set up if needed, then start Codex
75
- claude load memories [--all] [--yes]
76
- Import Claude Code's saved memories
77
- claude load sessions [--limit n] Have Claude read past sessions and save what matters
78
- codex load sessions [--limit n] The same for Codex
79
- mcp Run the MCP bridge (what clients start)
80
- mcp config <client> Print config for cursor, gemini, vscode, windsurf,
81
- zed, opencode, claude, codex or remote
82
- context [load] Show what an agent sees for this folder
83
- context search <words> Search this project's saved notes
84
- context projects | export [--out f] List projects or export everything
85
- status Sign in, device, global install, client setup
86
- uninstall [client|all] Remove what setup added
87
- token [--header] Print a fresh access token
88
- config get | set reports on|off Error reports sent after a failure
89
- update [--yes] Check for a new version and install it
90
- repair Bring hooks and editor entries up to date
91
-
92
- ${bold("Vaults")}
93
- vault list Vaults in this workspace
94
- vault link <folder> [--vault <name|id>] [--create] [--obsidian]
95
- Link a folder to a vault (writes <folder>/.nemu/vault.json)
96
- vault unlink [folder] Stop syncing a folder; its files stay
97
- vault status [folder] Last sync, settings and open conflicts
98
- sync [folder] [--watch] [--dry-run] [--conflicts=merge|file] [--allow-deletes]
99
- Sync a linked folder with its vault
100
-
101
- ${bold("Account")}
102
- login [--force] [--no-browser] Sign in with the device flow
103
- login key Sign in with a workspace API key (asked for, or NEMU_API_KEY)
104
- logout Delete the stored token
105
- whoami Show the signed in account
106
- user Full account record
107
- scopes Every scope and its actions
108
-
109
- ${bold("Workspaces")}
110
- workspaces list [--stats]
111
- workspaces get <id>
112
- workspaces create <name>
113
- workspaces rename <id> <name>
114
- workspaces delete <id> --yes
115
- workspaces budget [id]
116
- workspaces set-budget <id> <amount>
117
-
118
- ${bold("Members")}
119
- members list [-w <workspace>]
120
- members invite [--email a,b] [--max-uses n] [--expires-in-days n]
121
- members role <member-id> <ADMIN|MEMBER>
122
- members remove <member-id>
123
-
124
- ${bold("Providers")}
125
- providers list [--name] [--compatibility]
126
- providers get <id>
127
- providers create <name> --priority 1 [--base-url] [--api-key]
128
- [--compatibility OPENAI_COMPATIBLE|ANTHROPIC|OPENAI_RESPONSES]
129
- providers update <id> [--name] [--priority] [--base-url] [--api-key] [--enabled]
130
- providers delete <id> --yes
131
-
132
- ${bold("Models")}
133
- models list [--provider <id>] [--type chat] [--name]
134
- models get <id>
135
- models create --name --display-name --provider <id> --type chat
136
- --input-cost --output-cost --context-window
137
- [--api-name] [--max-output] [--cache-read-cost] [--cache-write-cost]
138
- models update <id> [--display-name] [--input-cost] [--output-cost] [--enabled]
139
- models delete <id> --yes
140
-
141
- ${bold("Prompts")}
142
- prompts list [--name] [--type] [--environment]
143
- prompts get <id>
144
- prompts create --name --content [--type SYSTEM] [--model <id>] [--position n]
145
- prompts update <id> [--name] [--content] [--enabled]
146
- prompts delete <id> --yes
147
-
148
- ${bold("Mappings")}
149
- mappings list [--source] [--target]
150
- mappings get <id>
151
- mappings create --source <name> --target <model> [--priority n] [--pattern true]
152
- mappings update <id> [--source] [--target] [--priority] [--enabled]
153
- mappings delete <id> --yes
154
-
155
- ${bold("Read only")}
156
- workflows list | get <id>
157
- metrics list [--page n] [--limit n] [--key <id>] [--start <iso>] [--end <iso>]
158
- metrics get <request-id>
159
- indexes list | get <id> | create <url> [--max-pages n] | delete <id> --yes
160
- quotas list | get <id> | update <id> [--limit n] | delete <id> --yes
161
- health
162
- api-version
163
-
164
- ${bold("Escape hatch")}
165
- api <METHOD> <path> [--data '<json>'] Call any endpoint directly
166
-
167
- ${bold("Global")}
168
- --json Machine readable output on every command
169
- -w, --workspace Workspace id or name, defaults to the first
170
- --version, -v Print the CLI version
171
- --help, -h Print this message
172
-
173
- ${dim("Docs https://docs.nemu.cc")}
65
+ const HELP = `
66
+ ${bold("nemu")} ${dim(VERSION)}
67
+
68
+ ${bold("Context for coding agents")}
69
+ setup <claude|codex> [--hooks|--no-hooks] [--yes]
70
+ Connect Claude Code (aliases cc, claude-code) or Codex
71
+ setup <cursor|vscode|gemini|windsurf|zed|opencode>
72
+ Add the Nemu MCP server to that editor's config
73
+ claude [-- <claude args>] Set up if needed, then start Claude Code
74
+ codex [-- <codex args>] Set up if needed, then start Codex
75
+ claude load memories [--all] [--yes]
76
+ Import Claude Code's saved memories
77
+ claude load sessions [--limit n] Have Claude read past sessions and save what matters
78
+ codex load sessions [--limit n] The same for Codex
79
+ mcp Run the MCP bridge (what clients start)
80
+ mcp config <client> Print config for cursor, gemini, vscode, windsurf,
81
+ zed, opencode, claude, codex or remote
82
+ context [load] Show what an agent sees for this folder
83
+ context search <words> Search this project's saved notes
84
+ context projects | export [--out f] List projects or export everything
85
+ status Sign in, device, global install, client setup
86
+ uninstall [client|all] Remove what setup added
87
+ token [--header] Print a fresh access token
88
+ config get | set reports on|off Error reports sent after a failure
89
+ update [--yes] Check for a new version and install it
90
+ repair Bring hooks and editor entries up to date
91
+
92
+ ${bold("Vaults")}
93
+ vault list Vaults in this workspace
94
+ vault link <folder> [--vault <name|id>] [--create [--private]] [--obsidian]
95
+ Link a folder to a vault (writes <folder>/.nemu/vault.json)
96
+ vault unlink [folder] Stop syncing a folder; its files stay
97
+ vault status [folder] Last sync, settings and open conflicts
98
+ vault unlock [folder] Open a private vault on this computer (password, recovery key, or approval)
99
+ vault approve [folder] Let another device open a private vault, after comparing its code
100
+ vault forget [folder] Lock a private vault on this computer again
101
+ sync [folder] [--watch] [--dry-run] [--conflicts=merge|file] [--allow-deletes]
102
+ [--obsidian on|off] [--obsidian-plugins on|off]
103
+ Sync a linked folder with its vault
104
+
105
+ ${bold("Account")}
106
+ login [--force] [--no-browser] Sign in with the device flow
107
+ login key Sign in with a workspace API key (asked for, or NEMU_API_KEY)
108
+ logout Delete the stored token
109
+ whoami Show the signed in account
110
+ user Full account record
111
+ scopes Every scope and its actions
112
+
113
+ ${bold("Workspaces")}
114
+ workspaces list [--stats]
115
+ workspaces get <id>
116
+ workspaces create <name>
117
+ workspaces rename <id> <name>
118
+ workspaces delete <id> --yes
119
+ workspaces budget [id]
120
+ workspaces set-budget <id> <amount>
121
+
122
+ ${bold("Members")}
123
+ members list [-w <workspace>]
124
+ members invite [--email a,b] [--max-uses n] [--expires-in-days n]
125
+ members role <member-id> <ADMIN|MEMBER>
126
+ members remove <member-id>
127
+
128
+ ${bold("Providers")}
129
+ providers list [--name] [--compatibility]
130
+ providers get <id>
131
+ providers create <name> --priority 1 [--base-url] [--api-key]
132
+ [--compatibility OPENAI_COMPATIBLE|ANTHROPIC|OPENAI_RESPONSES]
133
+ providers update <id> [--name] [--priority] [--base-url] [--api-key] [--enabled]
134
+ providers delete <id> --yes
135
+
136
+ ${bold("Models")}
137
+ models list [--provider <id>] [--type chat] [--name]
138
+ models get <id>
139
+ models create --name --display-name --provider <id> --type chat
140
+ --input-cost --output-cost --context-window
141
+ [--api-name] [--max-output] [--cache-read-cost] [--cache-write-cost]
142
+ models update <id> [--display-name] [--input-cost] [--output-cost] [--enabled]
143
+ models delete <id> --yes
144
+
145
+ ${bold("Prompts")}
146
+ prompts list [--name] [--type] [--environment]
147
+ prompts get <id>
148
+ prompts create --name --content [--type SYSTEM] [--model <id>] [--position n]
149
+ prompts update <id> [--name] [--content] [--enabled]
150
+ prompts delete <id> --yes
151
+
152
+ ${bold("Mappings")}
153
+ mappings list [--source] [--target]
154
+ mappings get <id>
155
+ mappings create --source <name> --target <model> [--priority n] [--pattern true]
156
+ mappings update <id> [--source] [--target] [--priority] [--enabled]
157
+ mappings delete <id> --yes
158
+
159
+ ${bold("Read only")}
160
+ workflows list | get <id>
161
+ metrics list [--page n] [--limit n] [--key <id>] [--start <iso>] [--end <iso>]
162
+ metrics get <request-id>
163
+ indexes list | get <id> | create <url> [--max-pages n] | delete <id> --yes
164
+ quotas list | get <id> | update <id> [--limit n] | delete <id> --yes
165
+ health
166
+ api-version
167
+
168
+ ${bold("Escape hatch")}
169
+ api <METHOD> <path> [--data '<json>'] Call any endpoint directly
170
+
171
+ ${bold("Global")}
172
+ --json Machine readable output on every command
173
+ -w, --workspace Workspace id or name, defaults to the first
174
+ --version, -v Print the CLI version
175
+ --help, -h Print this message
176
+
177
+ ${dim("Docs https://docs.nemu.cc")}
174
178
  `;
175
179
  function usage() {
176
180
  out(HELP);
package/dist/vault/api.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { hash_of } from "./files.js";
1
2
  import { z } from "zod";
2
3
  import { CliError } from "../errors.js";
3
4
  const note_schema = z.object({
@@ -9,10 +10,12 @@ const note_schema = z.object({
9
10
  size: z.number(),
10
11
  revision: z.number(),
11
12
  deleted: z.boolean(),
13
+ sealed_path: z.string().optional(),
12
14
  });
13
15
  const vault_schema = z.object({
14
16
  id: z.string(),
15
17
  name: z.string(),
18
+ mode: z.enum(["standard", "private"]).optional(),
16
19
  revision: z.number(),
17
20
  notes: z.number().optional(),
18
21
  stored_bytes: z.number().optional(),
@@ -32,6 +35,7 @@ const info_schema = z.object({
32
35
  const version_schema = z.object({
33
36
  version: z.number().int(),
34
37
  path: z.string(),
38
+ sealed_path: z.string().optional(),
35
39
  hash: z.string(),
36
40
  size: z.number(),
37
41
  deleted: z.boolean(),
@@ -98,6 +102,9 @@ export class VaultApi {
98
102
  await wait(retry_delay(response, attempt));
99
103
  }
100
104
  }
105
+ hash(content) {
106
+ return hash_of(content);
107
+ }
101
108
  base() {
102
109
  return `/api/v1/vaults/${encodeURIComponent(this.vault_id)}`;
103
110
  }
@@ -133,13 +140,16 @@ export class VaultApi {
133
140
  }
134
141
  return { content, id, version, hash };
135
142
  }
136
- async write(path, content, base_version) {
143
+ async write(path, content, base_version, sealed) {
137
144
  const response = await this.call("PUT", `${this.base()}/files`, {
138
145
  query: { path },
139
146
  headers: {
140
147
  "content-type": "application/octet-stream",
141
148
  "x-nemu-client": this.client_label,
142
149
  ...(base_version === null ? { "if-none-match": "*" } : { "if-match": `"${base_version}"` }),
150
+ ...(sealed === undefined
151
+ ? {}
152
+ : { "x-nemu-sealed-path": sealed.sealed_path, "x-nemu-content-mac": sealed.content_hash }),
143
153
  },
144
154
  body: content,
145
155
  timeout_ms: 120_000,
@@ -153,10 +163,21 @@ export class VaultApi {
153
163
  });
154
164
  return parse(z.object({ data: note_schema }), await response.json()).data;
155
165
  }
156
- async move(from, to, base_version) {
166
+ async move(from, to, base_version, sealed) {
157
167
  const response = await this.call("POST", `${this.base()}/files/move`, {
158
168
  headers: { "content-type": "application/json", "x-nemu-client": this.client_label },
159
- body: JSON.stringify({ from, to, base_version }),
169
+ body: JSON.stringify({
170
+ from,
171
+ to,
172
+ base_version,
173
+ ...(sealed === undefined
174
+ ? {}
175
+ : {
176
+ sealed_path: sealed.sealed_path,
177
+ content_hash: sealed.content_hash,
178
+ content: Buffer.from(sealed.content).toString("base64url"),
179
+ }),
180
+ }),
160
181
  });
161
182
  return parse(z.object({ data: note_schema }), await response.json()).data;
162
183
  }
@@ -187,16 +208,91 @@ export class VaultApi {
187
208
  return parse(z.object({ data: z.array(version_schema) }), await response.json()).data;
188
209
  }
189
210
  }
211
+ const lock_schema = z.object({
212
+ id: z.string(),
213
+ kind: z.string(),
214
+ label: z.string(),
215
+ params: z.record(z.string(), z.union([z.string(), z.number()])),
216
+ created_at: z.string(),
217
+ last_used_at: z.string().nullable(),
218
+ });
219
+ const key_request_schema = z.object({
220
+ id: z.string(),
221
+ label: z.string(),
222
+ commitment: z.string(),
223
+ approver_key: z.string().nullable(),
224
+ public_key: z.string().nullable(),
225
+ nonce: z.string().nullable(),
226
+ created_at: z.string(),
227
+ expires_at: z.string(),
228
+ });
229
+ export class LockApi {
230
+ transport;
231
+ vault_id;
232
+ constructor(transport, vault_id) {
233
+ this.transport = transport;
234
+ this.vault_id = vault_id;
235
+ }
236
+ async call(method, path, body) {
237
+ const response = await this.transport(method, `/api/v1/vaults/${encodeURIComponent(this.vault_id)}${path}`, {
238
+ ...(body === undefined
239
+ ? {}
240
+ : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) }),
241
+ });
242
+ if (!response.ok)
243
+ throw await error_of(response);
244
+ return response.json();
245
+ }
246
+ async locks() {
247
+ return parse(z.object({ data: z.array(lock_schema) }), await this.call("GET", "/locks")).data;
248
+ }
249
+ async wrapped(lock_id) {
250
+ return parse(z.object({ data: z.object({ wrapped: z.string() }) }), await this.call("GET", `/locks/${encodeURIComponent(lock_id)}`)).data.wrapped;
251
+ }
252
+ async add(lock) {
253
+ return parse(z.object({ data: z.object({ id: z.string() }) }), await this.call("POST", "/locks", lock)).data.id;
254
+ }
255
+ async remove(lock_id) {
256
+ await this.call("DELETE", `/locks/${encodeURIComponent(lock_id)}`);
257
+ }
258
+ async requests() {
259
+ return parse(z.object({ data: z.array(key_request_schema) }), await this.call("GET", "/requests")).data;
260
+ }
261
+ async ask(commitment, label) {
262
+ return parse(z.object({ data: z.object({ id: z.string(), expires_at: z.string() }) }), await this.call("POST", "/requests", { commitment, label })).data;
263
+ }
264
+ async answer_of(request_id) {
265
+ return parse(z.object({
266
+ data: z.object({
267
+ status: z.string(),
268
+ approver_key: z.string().optional(),
269
+ wrapped: z.string().optional(),
270
+ }),
271
+ }), await this.call("GET", `/requests/${encodeURIComponent(request_id)}`)).data;
272
+ }
273
+ async reveal(request_id, public_key, nonce) {
274
+ await this.call("POST", `/requests/${encodeURIComponent(request_id)}/reveal`, { public_key, nonce });
275
+ }
276
+ async offer(request_id, approver_key) {
277
+ await this.call("POST", `/requests/${encodeURIComponent(request_id)}/offer`, { approver_key });
278
+ }
279
+ async request(request_id) {
280
+ return (await this.requests()).find((entry) => entry.id === request_id) ?? null;
281
+ }
282
+ async answer(request_id, wrapped) {
283
+ await this.call("POST", `/requests/${encodeURIComponent(request_id)}`, { wrapped });
284
+ }
285
+ }
190
286
  export async function list_vaults(transport) {
191
287
  const response = await transport("GET", "/api/v1/vaults", {});
192
288
  if (!response.ok)
193
289
  throw await error_of(response);
194
290
  return parse(z.object({ data: z.array(vault_schema) }), await response.json()).data;
195
291
  }
196
- export async function create_vault(transport, name) {
292
+ export async function create_vault(transport, name, privacy) {
197
293
  const response = await transport("POST", "/api/v1/vaults", {
198
294
  headers: { "content-type": "application/json" },
199
- body: JSON.stringify({ name }),
295
+ body: JSON.stringify(privacy === undefined ? { name } : { name, id: privacy.id, mode: "private", locks: privacy.locks }),
200
296
  });
201
297
  if (!response.ok)
202
298
  throw await error_of(response);
@@ -4,6 +4,9 @@ import { CliError } from "../errors.js";
4
4
  import { send } from "../http.js";
5
5
  import { VERSION } from "../version.js";
6
6
  import { VaultApi } from "./api.js";
7
+ import { vault_keys } from "./private/crypto.js";
8
+ import { PrivateVaultApi } from "./private/api.js";
9
+ import { load_vault_key } from "./private/keystore.js";
7
10
  import { state_path_for } from "./state.js";
8
11
  export function cli_transport(workspace) {
9
12
  return async (method, path, options) => {
@@ -34,8 +37,23 @@ export async function open_linked(marker) {
34
37
  credentials.workspace.id !== marker.workspace_id) {
35
38
  throw new CliError(`This folder belongs to another workspace than the API key you signed in with (${credentials.workspace.name}). Nothing was synced.`, "workspace_mismatch");
36
39
  }
40
+ const api = new VaultApi(cli_transport(marker.workspace_id), marker.vault_id, client_label());
41
+ const info = await api.info();
42
+ const vault_key = await load_vault_key(marker.vault_id);
43
+ const is_pinned_private = marker.mode === "private" || vault_key !== null;
44
+ const says_private = info.data.mode === "private";
45
+ if (is_pinned_private !== says_private && (marker.mode !== undefined || vault_key !== null)) {
46
+ throw new CliError(`Nemu now reports "${marker.vault_name}" as ${says_private ? "private" : "not private"}, but it was ${is_pinned_private ? "private" : "not private"} when this folder was linked. A vault never changes this, so nothing was synced. Check the vault in the console.`, "vault_mode_changed");
47
+ }
48
+ if (!says_private) {
49
+ return { api, state_path: state_path_for(marker.vault_id), is_private: false };
50
+ }
51
+ if (vault_key === null) {
52
+ throw new CliError(`"${marker.vault_name}" is a private vault and is locked on this computer. Run nemu vault unlock first. Nothing was synced.`, "vault_locked");
53
+ }
37
54
  return {
38
- api: new VaultApi(cli_transport(marker.workspace_id), marker.vault_id, client_label()),
55
+ api: new PrivateVaultApi(api, vault_keys(marker.vault_id, vault_key)),
39
56
  state_path: state_path_for(marker.vault_id),
57
+ is_private: true,
40
58
  };
41
59
  }
@@ -3,7 +3,7 @@ import { readFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
4
  import { CliError } from "../errors.js";
5
5
  import { RemoteError } from "./api.js";
6
- import { delete_local, hash_of, read_if, rename_local, scan_folder, write_atomic_file, } from "./files.js";
6
+ import { delete_local, read_if, rename_local, scan_folder, write_atomic_file, } from "./files.js";
7
7
  import { ignore_fingerprint, is_ignored, parse_ignore } from "./ignore.js";
8
8
  import { acquire_lock } from "./lock.js";
9
9
  import { merge_text } from "./merge.js";
@@ -108,7 +108,11 @@ function linked_groups(actions) {
108
108
  }
109
109
  async function load_ignore(root, settings) {
110
110
  const source = await readFile(join(root, ".nemuignore"), "utf-8").catch(() => "");
111
- const options = { obsidian: settings.obsidian, rules: parse_ignore(source) };
111
+ const options = {
112
+ obsidian: settings.obsidian,
113
+ obsidian_plugins: settings.obsidian_plugins,
114
+ rules: parse_ignore(source),
115
+ };
112
116
  return { options, fingerprint: ignore_fingerprint(options, source) };
113
117
  }
114
118
  function entry_of(note) {
@@ -207,6 +211,7 @@ export async function run_sync(options) {
207
211
  }
208
212
  }
209
213
  async function sync_locked(options) {
214
+ const hasher = (content) => options.api.hash(content);
210
215
  const dry_run = options.dry_run === true;
211
216
  const report = new_report(options.api.vault_id, dry_run);
212
217
  const emit = (event) => options.on_event?.(event);
@@ -221,6 +226,9 @@ async function sync_locked(options) {
221
226
  state.settings.conflicts = options.settings.conflicts;
222
227
  if (options.settings?.obsidian !== undefined)
223
228
  state.settings.obsidian = options.settings.obsidian;
229
+ if (options.settings?.obsidian_plugins !== undefined) {
230
+ state.settings.obsidian_plugins = options.settings.obsidian_plugins;
231
+ }
224
232
  const ignore = await load_ignore(options.root, state.settings);
225
233
  if (ignore.fingerprint !== state.ignore_fingerprint)
226
234
  state.full_next = true;
@@ -269,7 +277,7 @@ async function sync_locked(options) {
269
277
  continue;
270
278
  base.set(path_key(entry.path), entry);
271
279
  }
272
- const scan = await scan_folder(options.root, ignore.options, max_file_bytes, (key) => base.get(key)?.path);
280
+ const scan = await scan_folder(options.root, ignore.options, max_file_bytes, (key) => base.get(key)?.path, hasher);
273
281
  if (cycle === 1) {
274
282
  report.skipped.push(...scan.skipped);
275
283
  for (const skipped of scan.skipped)
@@ -332,7 +340,7 @@ async function sync_locked(options) {
332
340
  const ready_at = scan_started + quiet_ms;
333
341
  if (Date.now() < ready_at)
334
342
  await wait(ready_at - Date.now());
335
- const content = await read_if(options.root, local.disk, local.hash);
343
+ const content = await read_if(options.root, local.disk, local.hash, hasher);
336
344
  if (content === null) {
337
345
  if (!report.waiting.includes(local.path))
338
346
  report.waiting.push(local.path);
@@ -363,7 +371,7 @@ async function sync_locked(options) {
363
371
  catch (error) {
364
372
  if (error instanceof RemoteError && error.status === 409) {
365
373
  const current = error.current;
366
- if (current !== null && current !== undefined && !current.deleted && current.hash === hash_of(content)) {
374
+ if (current !== null && current !== undefined && !current.deleted && current.hash === hasher(content)) {
367
375
  record_note(current);
368
376
  return current;
369
377
  }
@@ -387,7 +395,7 @@ async function sync_locked(options) {
387
395
  const fetch_remote = async (path, note_id) => {
388
396
  try {
389
397
  const fetched = await options.api.read(path);
390
- if (fetched.id !== note_id || hash_of(fetched.content) !== fetched.hash) {
398
+ if (fetched.id !== note_id || hasher(fetched.content) !== fetched.hash) {
391
399
  stale = true;
392
400
  throw new GroupFailed(true);
393
401
  }
@@ -402,13 +410,10 @@ async function sync_locked(options) {
402
410
  }
403
411
  };
404
412
  const keep_both = async (remote_entry, local, copy_path, local_content, remote_content) => {
405
- if (!(await write_atomic_file(options.root, copy_path, local_content, null)))
413
+ if (!(await write_atomic_file(options.root, copy_path, local_content, null, hasher)))
406
414
  throw new GroupFailed(true);
407
415
  const fetched = remote_content ?? (await fetch_remote(remote_entry.path, remote_entry.note_id));
408
- if (!(await write_atomic_file(options.root, remote_entry.path, fetched.content, {
409
- disk: local.disk,
410
- hash: local.hash,
411
- }))) {
416
+ if (!(await write_atomic_file(options.root, remote_entry.path, fetched.content, { disk: local.disk, hash: local.hash }, hasher))) {
412
417
  throw new GroupFailed(true);
413
418
  }
414
419
  record({ path: remote_entry.path, note_id: fetched.id, version: fetched.version, hash: fetched.hash });
@@ -425,7 +430,7 @@ async function sync_locked(options) {
425
430
  const execute = async (action) => {
426
431
  switch (action.kind) {
427
432
  case "delete_local": {
428
- if (!(await delete_local(options.root, action.disk, action.hash)))
433
+ if (!(await delete_local(options.root, action.disk, action.hash, hasher)))
429
434
  throw new GroupFailed(true);
430
435
  report.deleted_local.push(action.disk);
431
436
  emit({ kind: "deleted_local", path: action.disk });
@@ -472,7 +477,7 @@ async function sync_locked(options) {
472
477
  }
473
478
  case "pull": {
474
479
  const fetched = await fetch_remote(action.path, action.note_id);
475
- const written = await write_atomic_file(options.root, action.path, fetched.content, action.replace === null ? null : { disk: action.replace.disk, hash: action.replace.hash });
480
+ const written = await write_atomic_file(options.root, action.path, fetched.content, action.replace === null ? null : { disk: action.replace.disk, hash: action.replace.hash }, hasher);
476
481
  if (!written)
477
482
  throw new GroupFailed(true);
478
483
  record({ path: action.path, note_id: fetched.id, version: fetched.version, hash: fetched.hash });
@@ -518,7 +523,7 @@ async function sync_locked(options) {
518
523
  throw error;
519
524
  }
520
525
  const texts = [base_content, local_content, fetched.content].map((value) => value === null ? null : decode(value));
521
- const merged = base_content !== null && hash_of(base_content) === action.base.hash && texts.every((text) => text !== null)
526
+ const merged = base_content !== null && hasher(base_content) === action.base.hash && texts.every((text) => text !== null)
522
527
  ? merge_text(texts[0], texts[1], texts[2])
523
528
  : { kind: "conflict" };
524
529
  if (merged.kind === "conflict") {
@@ -528,14 +533,11 @@ async function sync_locked(options) {
528
533
  return;
529
534
  }
530
535
  const bytes = Buffer.from(merged.text, "utf-8");
531
- if (!(await write_atomic_file(options.root, action.remote.path, bytes, {
532
- disk: action.local.disk,
533
- hash: action.local.hash,
534
- }))) {
536
+ if (!(await write_atomic_file(options.root, action.remote.path, bytes, { disk: action.local.disk, hash: action.local.hash }, hasher))) {
535
537
  throw new GroupFailed(true);
536
538
  }
537
539
  known.set(fetched.id, fetched.version);
538
- if (hash_of(bytes) === fetched.hash) {
540
+ if (hasher(bytes) === fetched.hash) {
539
541
  record({ path: action.remote.path, note_id: fetched.id, version: fetched.version, hash: fetched.hash });
540
542
  }
541
543
  else {
@@ -12,7 +12,7 @@ export function disk_path(root, relative) {
12
12
  function megabytes(bytes) {
13
13
  return `${(bytes / 1024 / 1024).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
14
14
  }
15
- export async function scan_folder(root, ignore, max_file_bytes, preferred = () => undefined) {
15
+ export async function scan_folder(root, ignore, max_file_bytes, preferred = () => undefined, hasher = hash_of) {
16
16
  const files = new Map();
17
17
  const skipped = [];
18
18
  const clashes = new Map();
@@ -58,7 +58,7 @@ export async function scan_folder(root, ignore, max_file_bytes, preferred = () =
58
58
  const content = await readFile(disk_path(root, disk)).catch(() => null);
59
59
  if (content === null)
60
60
  continue;
61
- const local = { path, disk, hash: hash_of(content), size: content.length };
61
+ const local = { path, disk, hash: hasher(content), size: content.length };
62
62
  const key = path_key(path);
63
63
  const group = clashes.get(key) ?? [];
64
64
  group.push(local);
@@ -85,13 +85,13 @@ export async function scan_folder(root, ignore, max_file_bytes, preferred = () =
85
85
  }
86
86
  return { files, skipped };
87
87
  }
88
- export async function read_hash(root, disk) {
88
+ export async function read_hash(root, disk, hasher = hash_of) {
89
89
  const content = await readFile(disk_path(root, disk)).catch(() => null);
90
- return content === null ? null : hash_of(content);
90
+ return content === null ? null : hasher(content);
91
91
  }
92
- export async function read_if(root, disk, expected_hash) {
92
+ export async function read_if(root, disk, expected_hash, hasher = hash_of) {
93
93
  const content = await readFile(disk_path(root, disk)).catch(() => null);
94
- if (content === null || hash_of(content) !== expected_hash)
94
+ if (content === null || hasher(content) !== expected_hash)
95
95
  return null;
96
96
  return content;
97
97
  }
@@ -113,7 +113,7 @@ export async function stays_inside(root, target) {
113
113
  return false;
114
114
  return real_folder === real_root || real_folder.startsWith(real_root.endsWith(sep) ? real_root : `${real_root}${sep}`);
115
115
  }
116
- export async function write_atomic_file(root, relative, content, expected) {
116
+ export async function write_atomic_file(root, relative, content, expected, hasher = hash_of) {
117
117
  const target = disk_path(root, relative);
118
118
  if (!(await stays_inside(root, target)))
119
119
  return false;
@@ -122,7 +122,7 @@ export async function write_atomic_file(root, relative, content, expected) {
122
122
  if (exists)
123
123
  return false;
124
124
  }
125
- else if ((await read_hash(root, expected.disk)) !== expected.hash) {
125
+ else if ((await read_hash(root, expected.disk, hasher)) !== expected.hash) {
126
126
  return false;
127
127
  }
128
128
  await mkdir(dirname(target), { recursive: true });
@@ -161,10 +161,10 @@ export async function rename_local(root, from, to) {
161
161
  await prune_folders(root, dirname(from));
162
162
  return true;
163
163
  }
164
- export async function delete_local(root, disk, expected_hash) {
164
+ export async function delete_local(root, disk, expected_hash, hasher = hash_of) {
165
165
  if (!(await stays_inside(root, disk_path(root, disk))))
166
166
  return false;
167
- if ((await read_hash(root, disk)) !== expected_hash)
167
+ if ((await read_hash(root, disk, hasher)) !== expected_hash)
168
168
  return false;
169
169
  await unlink(disk_path(root, disk));
170
170
  await prune_folders(root, dirname(disk));