nemu-cli 1.5.0 → 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.
@@ -0,0 +1,99 @@
1
+ export const MAX_PATH_LENGTH = 240;
2
+ export const MAX_SEGMENT_LENGTH = 200;
3
+ const FORBIDDEN_CHARACTERS = /[<>:"|?*\\\u0000-\u001f\u007f]/;
4
+ const RESERVED_NAMES = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\.[^.]*)?$/i;
5
+ const RESERVED_ROOTS = new Set([".nemu"]);
6
+ export function normalize_path(raw) {
7
+ return raw
8
+ .normalize("NFC")
9
+ .replace(/^\.\/+/, "")
10
+ .replace(/^\/+/, "");
11
+ }
12
+ function check_segment(segment) {
13
+ if (segment.length === 0)
14
+ return "a folder name is empty";
15
+ if (segment === "." || segment === "..")
16
+ return "it contains . or ..";
17
+ if (segment.length > MAX_SEGMENT_LENGTH) {
18
+ return `a name is longer than ${MAX_SEGMENT_LENGTH} characters`;
19
+ }
20
+ if (FORBIDDEN_CHARACTERS.test(segment)) {
21
+ return `"${segment}" has a character Windows cannot store (< > : " | ? * \\ or a control character)`;
22
+ }
23
+ if (/[. ]$/.test(segment))
24
+ return `"${segment}" ends with a dot or a space, which Windows cannot store`;
25
+ if (RESERVED_NAMES.test(segment))
26
+ return `"${segment}" is a name Windows reserves`;
27
+ return null;
28
+ }
29
+ export function check_path(raw) {
30
+ const path = normalize_path(raw);
31
+ if (path.length === 0)
32
+ return { ok: false, error: "the path is empty" };
33
+ if (path.length > MAX_PATH_LENGTH) {
34
+ return { ok: false, error: `the path is longer than ${MAX_PATH_LENGTH} characters` };
35
+ }
36
+ const segments = path.split("/");
37
+ if (RESERVED_ROOTS.has(segments[0].toLowerCase())) {
38
+ return { ok: false, error: "the .nemu folder is reserved for sync" };
39
+ }
40
+ for (const segment of segments) {
41
+ const problem = check_segment(segment);
42
+ if (problem !== null)
43
+ return { ok: false, error: problem };
44
+ }
45
+ return { ok: true, path };
46
+ }
47
+ export function path_key(path) {
48
+ return normalize_path(path).toLowerCase();
49
+ }
50
+ export function is_markdown(path) {
51
+ return /\.md$/i.test(path);
52
+ }
53
+ function split_name(path) {
54
+ const slash = path.lastIndexOf("/");
55
+ const folder = slash === -1 ? "" : path.slice(0, slash + 1);
56
+ const name = path.slice(slash + 1);
57
+ const dot = name.lastIndexOf(".");
58
+ return dot > 0
59
+ ? { folder, stem: name.slice(0, dot), extension: name.slice(dot) }
60
+ : { folder, stem: name, extension: "" };
61
+ }
62
+ function two(value) {
63
+ return String(value).padStart(2, "0");
64
+ }
65
+ export function conflict_stamp(date) {
66
+ return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} ${two(date.getHours())}-${two(date.getMinutes())}`;
67
+ }
68
+ export function safe_device_name(raw) {
69
+ const cleaned = raw
70
+ .normalize("NFC")
71
+ .replace(/[<>:"|?*\\/\u0000-\u001f\u007f(),]/g, "")
72
+ .replace(/\s+/g, " ")
73
+ .trim()
74
+ .replace(/[. ]+$/, "")
75
+ .slice(0, 40);
76
+ return cleaned.length > 0 ? cleaned : "this device";
77
+ }
78
+ function free_name(candidates, taken) {
79
+ for (let index = 1; index < 10_000; index += 1) {
80
+ const candidate = candidates(index);
81
+ if (!taken(path_key(candidate)))
82
+ return candidate;
83
+ }
84
+ throw new Error("No free file name was found.");
85
+ }
86
+ export function conflict_path(path, device, date, taken) {
87
+ const { folder, stem, extension } = split_name(path);
88
+ const label = `conflict, ${safe_device_name(device)}, ${conflict_stamp(date)}`;
89
+ return free_name((index) => index === 1
90
+ ? `${folder}${stem} (${label})${extension}`
91
+ : `${folder}${stem} (${label} ${index})${extension}`, taken);
92
+ }
93
+ export function numbered_path(path, taken) {
94
+ const { folder, stem, extension } = split_name(path);
95
+ return free_name((index) => `${folder}${stem} (${index + 1})${extension}`, taken);
96
+ }
97
+ export function is_conflict_copy(path) {
98
+ return /\(conflict, [^()]*, \d{4}-\d{2}-\d{2} \d{2}-\d{2}( \d+)?\)(\.[^./]*)?$/.test(path);
99
+ }
@@ -0,0 +1,279 @@
1
+ import { conflict_path, is_markdown, numbered_path, path_key } from "./paths.js";
2
+ const PHASES = {
3
+ delete_local: 0,
4
+ rename_local: 1,
5
+ forget: 2,
6
+ move_remote: 3,
7
+ pull: 4,
8
+ adopt: 4,
9
+ merge: 4,
10
+ keep_both: 4,
11
+ push: 5,
12
+ delete_remote: 6,
13
+ };
14
+ function order_renames(renames) {
15
+ const pending = [...renames];
16
+ const ordered = [];
17
+ while (pending.length > 0) {
18
+ const sources = new Set(pending.map((rename) => path_key(rename.from)));
19
+ const ready = pending.findIndex((rename) => !sources.has(path_key(rename.to)) || path_key(rename.to) === path_key(rename.from));
20
+ const index = ready === -1 ? 0 : ready;
21
+ ordered.push(pending.splice(index, 1)[0]);
22
+ }
23
+ return ordered;
24
+ }
25
+ function sort_actions(actions) {
26
+ const renames = actions.filter((action) => action.kind === "rename_local");
27
+ const others = actions.filter((action) => action.kind !== "rename_local");
28
+ const ordered_renames = order_renames(renames);
29
+ return [...others, ...ordered_renames]
30
+ .map((action, index) => ({ action, index }))
31
+ .sort((left, right) => PHASES[left.action.kind] - PHASES[right.action.kind] || left.index - right.index)
32
+ .map(({ action }) => action);
33
+ }
34
+ export function plan_sync(input) {
35
+ const { base, local, remote } = input;
36
+ const actions = [];
37
+ const notices = [];
38
+ let deferred = false;
39
+ const reserved = new Set([...base.keys(), ...local.keys(), ...remote.keys(), ...input.skipped]);
40
+ const taken = (key) => reserved.has(key);
41
+ const claim = (path) => {
42
+ reserved.add(path_key(path));
43
+ return path;
44
+ };
45
+ const remote_by_id = new Map();
46
+ for (const entry of remote.values())
47
+ remote_by_id.set(entry.note_id, entry);
48
+ const associated = new Map();
49
+ const used = new Set();
50
+ const missing = [];
51
+ for (const [key, entry] of base) {
52
+ if (input.skipped.has(key))
53
+ continue;
54
+ const found = local.get(key);
55
+ if (found !== undefined) {
56
+ associated.set(key, found);
57
+ used.add(key);
58
+ continue;
59
+ }
60
+ missing.push([key, entry]);
61
+ }
62
+ const by_hash = new Map();
63
+ for (const [local_key, candidate] of local) {
64
+ if (base.has(local_key))
65
+ continue;
66
+ const keys = by_hash.get(candidate.hash) ?? [];
67
+ keys.push(local_key);
68
+ by_hash.set(candidate.hash, keys);
69
+ }
70
+ for (const [key, entry] of missing) {
71
+ const moved = (by_hash.get(entry.hash) ?? []).find((local_key) => !used.has(local_key) && is_markdown(local.get(local_key).path) === is_markdown(entry.path));
72
+ if (moved === undefined)
73
+ continue;
74
+ associated.set(key, local.get(moved));
75
+ used.add(moved);
76
+ }
77
+ const handled_remote = new Set();
78
+ const vacated = new Set();
79
+ const replaceable = new Map();
80
+ const move_aside = (entry, reason, copy) => {
81
+ const local_key = path_key(entry.path);
82
+ used.add(local_key);
83
+ vacated.add(local_key);
84
+ actions.push({ kind: "rename_local", from: entry.disk, to: copy, hash: entry.hash, reason });
85
+ actions.push({ kind: "push", note_id: null, local: { path: copy, disk: copy, hash: entry.hash }, reason: reason === "conflict" ? "conflict" : "renamed" });
86
+ };
87
+ const unassociated_at = (key) => {
88
+ const entry = local.get(key);
89
+ if (entry === undefined || used.has(key) || base.has(key))
90
+ return undefined;
91
+ return entry;
92
+ };
93
+ const conflict_copy = (path) => claim(conflict_path(path, input.device, input.now, taken));
94
+ for (const [key, entry] of base) {
95
+ if (input.skipped.has(key))
96
+ continue;
97
+ const mine = associated.get(key) ?? null;
98
+ const theirs = remote_by_id.get(entry.note_id) ?? null;
99
+ if (theirs !== null)
100
+ handled_remote.add(theirs.note_id);
101
+ const local_changed = mine !== null && mine.hash !== entry.hash;
102
+ const ref = (value) => ({ path: value.path, disk: value.disk, hash: value.hash });
103
+ if (theirs === null) {
104
+ if (mine === null) {
105
+ actions.push({ kind: "forget", key });
106
+ continue;
107
+ }
108
+ const occupant = remote.get(path_key(mine.path));
109
+ if (!local_changed) {
110
+ if (occupant !== undefined && occupant.note_id !== entry.note_id) {
111
+ replaceable.set(path_key(mine.path), ref(mine));
112
+ actions.push({ kind: "forget", key });
113
+ continue;
114
+ }
115
+ actions.push({ kind: "delete_local", key: path_key(mine.path), disk: mine.disk, hash: mine.hash });
116
+ vacated.add(path_key(mine.path));
117
+ actions.push({ kind: "forget", key });
118
+ continue;
119
+ }
120
+ actions.push({ kind: "forget", key });
121
+ if (occupant !== undefined && occupant.note_id !== entry.note_id) {
122
+ move_aside(mine, "conflict", conflict_copy(mine.path));
123
+ notices.push(`"${mine.path}" was deleted elsewhere and replaced; your edits are kept as a conflict copy.`);
124
+ continue;
125
+ }
126
+ actions.push({ kind: "push", note_id: null, local: ref(mine), reason: "restore" });
127
+ notices.push(`"${mine.path}" was deleted elsewhere, but you edited it here, so it is restored.`);
128
+ continue;
129
+ }
130
+ const remote_moved = theirs.path !== entry.path;
131
+ const remote_changed = theirs.hash !== entry.hash;
132
+ if (mine === null) {
133
+ if (!remote_moved && !remote_changed) {
134
+ actions.push({ kind: "delete_remote", note_id: entry.note_id, path: theirs.path, counted: true });
135
+ actions.push({ kind: "forget", key });
136
+ continue;
137
+ }
138
+ if (path_key(theirs.path) !== key)
139
+ actions.push({ kind: "forget", key });
140
+ const squatter = unassociated_at(path_key(theirs.path));
141
+ if (squatter !== undefined) {
142
+ used.add(path_key(squatter.path));
143
+ if (squatter.hash === theirs.hash) {
144
+ actions.push({ kind: "adopt", remote: theirs });
145
+ continue;
146
+ }
147
+ actions.push({ kind: "keep_both", remote: theirs, local: ref(squatter), copy_path: conflict_copy(theirs.path) });
148
+ continue;
149
+ }
150
+ actions.push({ kind: "pull", note_id: theirs.note_id, path: theirs.path, hash: theirs.hash, replace: null });
151
+ if (remote_changed)
152
+ notices.push(`"${theirs.path}" was deleted here but edited elsewhere, so it is restored.`);
153
+ continue;
154
+ }
155
+ const local_moved = mine.path !== entry.path;
156
+ let target = mine.path;
157
+ let disk = mine.disk;
158
+ if (remote_moved) {
159
+ target = theirs.path;
160
+ if (mine.path !== theirs.path) {
161
+ const target_key = path_key(theirs.path);
162
+ const squatter = target_key === path_key(mine.path) ? undefined : unassociated_at(target_key);
163
+ if (squatter !== undefined) {
164
+ const aside = claim(numbered_path(squatter.path, taken));
165
+ move_aside(squatter, "collision", aside);
166
+ notices.push(`"${squatter.path}" was new here, but another note moved onto that name; yours is now "${aside}".`);
167
+ }
168
+ actions.push({ kind: "rename_local", from: mine.disk, to: theirs.path, hash: mine.hash, reason: "remote_move" });
169
+ vacated.add(path_key(mine.path));
170
+ disk = theirs.path;
171
+ if (local_moved && path_key(mine.path) !== key) {
172
+ notices.push(`"${entry.path}" was renamed here and elsewhere; it keeps the other name, "${theirs.path}".`);
173
+ }
174
+ }
175
+ }
176
+ else if (local_moved) {
177
+ const target_key = path_key(mine.path);
178
+ const occupant = remote.get(target_key);
179
+ if (is_markdown(mine.path) !== is_markdown(entry.path)) {
180
+ actions.push({ kind: "push", note_id: null, local: ref(mine), reason: "renamed" });
181
+ actions.push({ kind: "delete_remote", note_id: entry.note_id, path: theirs.path, counted: false });
182
+ actions.push({ kind: "forget", key });
183
+ continue;
184
+ }
185
+ if (occupant !== undefined && occupant.note_id !== entry.note_id) {
186
+ const aside = claim(numbered_path(mine.path, taken));
187
+ actions.push({ kind: "rename_local", from: mine.disk, to: aside, hash: mine.hash, reason: "collision" });
188
+ vacated.add(target_key);
189
+ notices.push(`"${mine.path}" is taken by another note, so this one is now "${aside}".`);
190
+ target = aside;
191
+ disk = aside;
192
+ }
193
+ actions.push({ kind: "move_remote", note_id: entry.note_id, from: theirs.path, to: target });
194
+ }
195
+ if (path_key(target) !== key)
196
+ actions.push({ kind: "forget", key });
197
+ const here = { path: target, disk, hash: mine.hash };
198
+ if (local_changed && remote_changed) {
199
+ if (mine.hash === theirs.hash) {
200
+ actions.push({ kind: "adopt", remote: { ...theirs, path: target } });
201
+ continue;
202
+ }
203
+ if (is_markdown(target) && input.conflicts === "merge") {
204
+ actions.push({ kind: "merge", base: entry, remote: { ...theirs, path: target }, local: here });
205
+ continue;
206
+ }
207
+ actions.push({
208
+ kind: "keep_both",
209
+ remote: { ...theirs, path: target },
210
+ local: here,
211
+ copy_path: conflict_copy(target),
212
+ });
213
+ continue;
214
+ }
215
+ if (local_changed) {
216
+ actions.push({ kind: "push", note_id: entry.note_id, local: here, reason: "edit" });
217
+ continue;
218
+ }
219
+ if (remote_changed) {
220
+ actions.push({ kind: "pull", note_id: theirs.note_id, path: target, hash: theirs.hash, replace: here });
221
+ continue;
222
+ }
223
+ if (theirs.version !== entry.version || remote_moved || local_moved) {
224
+ actions.push({ kind: "adopt", remote: { ...theirs, path: target } });
225
+ }
226
+ }
227
+ for (const [key, entry] of remote) {
228
+ if (handled_remote.has(entry.note_id))
229
+ continue;
230
+ if (input.skipped.has(key))
231
+ continue;
232
+ const here = local.get(key);
233
+ if (here === undefined || vacated.has(key)) {
234
+ actions.push({ kind: "pull", note_id: entry.note_id, path: entry.path, hash: entry.hash, replace: null });
235
+ continue;
236
+ }
237
+ if (!used.has(key) && !base.has(key)) {
238
+ used.add(key);
239
+ if (here.hash === entry.hash) {
240
+ actions.push({ kind: "adopt", remote: entry });
241
+ continue;
242
+ }
243
+ actions.push({
244
+ kind: "keep_both",
245
+ remote: entry,
246
+ local: { path: here.path, disk: here.disk, hash: here.hash },
247
+ copy_path: conflict_copy(entry.path),
248
+ });
249
+ continue;
250
+ }
251
+ const replace = replaceable.get(key);
252
+ if (replace !== undefined) {
253
+ actions.push({ kind: "pull", note_id: entry.note_id, path: entry.path, hash: entry.hash, replace });
254
+ continue;
255
+ }
256
+ deferred = true;
257
+ notices.push(`"${entry.path}" waits for the next run, because a file here is still in its way.`);
258
+ }
259
+ for (const [key, entry] of local) {
260
+ if (used.has(key) || base.has(key))
261
+ continue;
262
+ if (remote.has(key))
263
+ continue;
264
+ actions.push({ kind: "push", note_id: null, local: { path: entry.path, disk: entry.disk, hash: entry.hash }, reason: "new" });
265
+ }
266
+ return { actions: sort_actions(actions), notices, deferred };
267
+ }
268
+ export function counted_deletes(plan) {
269
+ return plan.actions.filter((action) => action.kind === "delete_remote" && action.counted).length;
270
+ }
271
+ export function mass_delete_blocked(deletes, tracked) {
272
+ if (deletes === 0)
273
+ return false;
274
+ if (deletes > 10)
275
+ return true;
276
+ if (tracked >= 2 && deletes >= tracked)
277
+ return true;
278
+ return deletes >= 3 && deletes > tracked * 0.1;
279
+ }
@@ -0,0 +1,110 @@
1
+ import { CliError } from "../../errors.js";
2
+ import { RemoteError, } from "../api.js";
3
+ import { content_mac, open_content, open_path, remote_path, seal_content, seal_path, } from "./crypto.js";
4
+ function unreadable() {
5
+ return new CliError("A note in this private vault did not open with the key on this computer. Nothing was changed. Run nemu vault forget, then nemu vault unlock again.", "private_key_mismatch");
6
+ }
7
+ export class PrivateVaultApi {
8
+ inner;
9
+ keys;
10
+ vault_id;
11
+ constructor(inner, keys) {
12
+ this.inner = inner;
13
+ this.keys = keys;
14
+ this.vault_id = inner.vault_id;
15
+ }
16
+ hash(content) {
17
+ return content_mac(this.keys, content);
18
+ }
19
+ plain_path(remote, sealed) {
20
+ if (sealed === undefined)
21
+ throw unreadable();
22
+ try {
23
+ return open_path(this.keys, remote, sealed);
24
+ }
25
+ catch {
26
+ throw unreadable();
27
+ }
28
+ }
29
+ plain(note) {
30
+ const { sealed_path, ...rest } = note;
31
+ return { ...rest, path: this.plain_path(note.path, sealed_path) };
32
+ }
33
+ async guard(action) {
34
+ try {
35
+ return await action();
36
+ }
37
+ catch (error) {
38
+ if (error instanceof RemoteError && error.current !== undefined && error.current !== null) {
39
+ throw new RemoteError(error.message, error.code, error.status ?? 0, this.plain(error.current), error.reference);
40
+ }
41
+ throw error;
42
+ }
43
+ }
44
+ async info() {
45
+ return this.inner.info();
46
+ }
47
+ async notes(trash = false) {
48
+ const listed = await this.inner.notes(trash);
49
+ return { revision: listed.revision, notes: listed.notes.map((note) => this.plain(note)) };
50
+ }
51
+ async changes(since) {
52
+ const page = await this.inner.changes(since);
53
+ return { ...page, notes: page.notes.map((note) => this.plain(note)) };
54
+ }
55
+ async read(path) {
56
+ const remote = remote_path(this.keys, path);
57
+ const fetched = await this.guard(() => this.inner.read(remote));
58
+ try {
59
+ return { ...fetched, content: open_content(this.keys, remote, fetched.content) };
60
+ }
61
+ catch {
62
+ throw unreadable();
63
+ }
64
+ }
65
+ async write(path, content, base_version) {
66
+ const remote = remote_path(this.keys, path);
67
+ const written = await this.guard(() => this.inner.write(remote, seal_content(this.keys, path, content), base_version, {
68
+ sealed_path: seal_path(this.keys, path),
69
+ content_hash: content_mac(this.keys, content),
70
+ }));
71
+ return this.plain(written);
72
+ }
73
+ async remove(path, version) {
74
+ const removed = await this.guard(() => this.inner.remove(remote_path(this.keys, path), version));
75
+ return this.plain(removed);
76
+ }
77
+ async move(from, to, base_version) {
78
+ const current = await this.read(from);
79
+ const moved = await this.guard(() => this.inner.move(remote_path(this.keys, from), remote_path(this.keys, to), base_version, {
80
+ sealed_path: seal_path(this.keys, to),
81
+ content_hash: content_mac(this.keys, current.content),
82
+ content: seal_content(this.keys, to, current.content),
83
+ }));
84
+ return this.plain(moved);
85
+ }
86
+ async record_merge() {
87
+ return;
88
+ }
89
+ async read_version(note_id, version) {
90
+ const versions = await this.inner.history(note_id);
91
+ const found = versions.find((entry) => entry.version === version);
92
+ if (found === undefined) {
93
+ throw new RemoteError("That version is not in the history any more.", "version_not_found", 404, undefined, undefined);
94
+ }
95
+ const sealed = await this.inner.read_version(note_id, version);
96
+ try {
97
+ return open_content(this.keys, found.path, sealed);
98
+ }
99
+ catch {
100
+ throw unreadable();
101
+ }
102
+ }
103
+ async history(note_id, limit = 200) {
104
+ const versions = await this.inner.history(note_id, limit);
105
+ return versions.map((version) => {
106
+ const { sealed_path, ...rest } = version;
107
+ return { ...rest, path: this.plain_path(version.path, sealed_path) };
108
+ });
109
+ }
110
+ }