@wirecat/cli-core 0.719.0 → 0.721.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/CHANGELOG.md +69 -0
- package/dist/attachments/documents.d.ts +5 -0
- package/dist/attachments/documents.js +2 -2
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/config-command.js +8 -2
- package/dist/cli/config-issues.d.ts +3 -1
- package/dist/cli/config-issues.js +9 -2
- package/dist/cli/documents/file-conflicts.d.ts +25 -0
- package/dist/cli/documents/file-conflicts.js +102 -0
- package/dist/cli/documents/file-edit.d.ts +29 -0
- package/dist/cli/documents/file-edit.js +352 -0
- package/dist/cli/documents/file-update.d.ts +43 -0
- package/dist/cli/documents/file-update.js +95 -0
- package/dist/cli/documents/history.d.ts +34 -0
- package/dist/cli/documents/history.js +89 -0
- package/dist/cli/documents/index.d.ts +9 -2
- package/dist/cli/documents/index.js +9 -2
- package/dist/cli/documents/library.js +10 -0
- package/dist/cli/permission-keys.d.ts +6 -0
- package/dist/cli/permission-keys.js +15 -3
- package/dist/cli/service-api.d.ts +1 -1
- package/dist/cli/service-api.js +16 -34
- package/dist/documents/file-mirror-model.d.ts +32 -1
- package/dist/documents/index.d.ts +7 -4
- package/dist/documents/index.js +4 -1
- package/dist/documents/model.d.ts +16 -1
- package/dist/errors/reasons.js +6 -1
- package/dist/office/docx.d.ts +43 -0
- package/dist/office/docx.js +349 -0
- package/dist/office/index.d.ts +2 -0
- package/dist/office/index.js +2 -0
- package/dist/office/package.d.ts +39 -0
- package/dist/office/package.js +98 -0
- package/dist/office/xlsx.d.ts +55 -0
- package/dist/office/xlsx.js +550 -0
- package/dist/office/xml.d.ts +34 -0
- package/dist/office/xml.js +186 -0
- package/dist/office/zip.d.ts +10 -0
- package/dist/office/zip.js +116 -0
- package/dist/services/documents/block-diff.d.ts +13 -3
- package/dist/services/documents/block-diff.js +13 -7
- package/dist/services/documents/ingestion.d.ts +21 -2
- package/dist/services/documents/ingestion.js +29 -2
- package/dist/services/documents/plan.js +16 -7
- package/dist/services/documents/ports.d.ts +2 -0
- package/dist/services/documents/sync.d.ts +1 -0
- package/dist/services/documents/sync.js +9 -4
- package/dist/services/files/conflicts.d.ts +78 -0
- package/dist/services/files/conflicts.js +183 -0
- package/dist/services/files/guarded-write.d.ts +34 -0
- package/dist/services/files/guarded-write.js +42 -0
- package/dist/services/files/listing.d.ts +36 -0
- package/dist/services/files/listing.js +47 -0
- package/dist/services/files/local-files.d.ts +54 -0
- package/dist/services/files/local-files.js +143 -0
- package/dist/services/files/mirror-state.d.ts +14 -0
- package/dist/services/files/mirror-state.js +65 -0
- package/dist/services/files/mirror.d.ts +4 -14
- package/dist/services/files/mirror.js +177 -204
- package/dist/services/files/text-merge.d.ts +27 -0
- package/dist/services/files/text-merge.js +134 -0
- package/dist/services/files/versions.d.ts +36 -9
- package/dist/services/files/versions.js +40 -12
- package/dist/store/index.d.ts +2 -0
- package/dist/store/index.js +1 -0
- package/dist/store/people.d.ts +8 -0
- package/dist/store/people.js +2 -0
- package/dist/store/sqlite/account-purge.js +3 -0
- package/dist/store/sqlite/document-history.d.ts +84 -0
- package/dist/store/sqlite/document-history.js +158 -0
- package/dist/store/sqlite/manifest.js +2 -0
- package/dist/store/sqlite/migrations.generated.js +17 -0
- package/dist/store/sqlite/notes.d.ts +9 -10
- package/dist/store/sqlite/notes.js +33 -21
- package/dist/store/sqlite/person-erase.d.ts +39 -0
- package/dist/store/sqlite/person-erase.js +152 -0
- package/dist/store/sqlite/schema/document-changes.d.ts +136 -0
- package/dist/store/sqlite/schema/document-changes.js +11 -0
- package/dist/store/sqlite/schema.d.ts +65 -0
- package/dist/store/sqlite/schema.js +5 -0
- package/package.json +6 -2
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { posix } from "node:path";
|
|
2
|
+
import { markdownBlocks } from "../../documents/markdown-blocks.js";
|
|
3
|
+
import { adjoins, applied, diffSequence, mergeBlocks } from "../documents/block-diff.js";
|
|
4
|
+
import { spliceMarkdown } from "../documents/markdown-splice.js";
|
|
5
|
+
const MERGEABLE = new Set([".md", ".markdown", ".txt", ".csv", ".tsv"]);
|
|
6
|
+
/** Above this a text file is merged no more than a binary one: three copies are read whole into memory. */
|
|
7
|
+
export const MAX_MERGE_BYTES = 1024 * 1024;
|
|
8
|
+
const MARKDOWN = new Set([".md", ".markdown"]);
|
|
9
|
+
/** Whether a file both sides changed is merged line by line rather than reported as a conflict. */
|
|
10
|
+
export const mergeable = (path, ...sizes) => MERGEABLE.has(posix.extname(path).toLowerCase()) && sizes.every((size) => size <= MAX_MERGE_BYTES);
|
|
11
|
+
/** Lines with their own endings, so `\r\n`, a byte-order mark and a missing last newline come back byte for byte. */
|
|
12
|
+
const linesOf = (text) => text.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
13
|
+
const same = (line) => line;
|
|
14
|
+
/**
|
|
15
|
+
* A three-way merge of line arrays, diff3 style: stretches both sides changed, unless changed the same, conflict.
|
|
16
|
+
* Edits on neighbouring lines conflict too, as in Git: two edits can read fine alone and wrong together.
|
|
17
|
+
*/
|
|
18
|
+
const mergeLines = (base, local, remote) => {
|
|
19
|
+
const tagged = [
|
|
20
|
+
...diffSequence(base, local, same).map((hunk) => ({ ...hunk, side: "local" })),
|
|
21
|
+
...diffSequence(base, remote, same).map((hunk) => ({ ...hunk, side: "remote" })),
|
|
22
|
+
].sort((a, b) => a.from - b.from || a.to - b.to);
|
|
23
|
+
const clusters = [];
|
|
24
|
+
for (const hunk of tagged) {
|
|
25
|
+
const last = clusters.at(-1);
|
|
26
|
+
if (last?.some((other) => adjoins(other, hunk)))
|
|
27
|
+
last.push(hunk);
|
|
28
|
+
else
|
|
29
|
+
clusters.push([hunk]);
|
|
30
|
+
}
|
|
31
|
+
const segments = [];
|
|
32
|
+
const unchanged = (from, to) => {
|
|
33
|
+
if (to <= from)
|
|
34
|
+
return;
|
|
35
|
+
const text = base.slice(from, to).join("");
|
|
36
|
+
segments.push({ kind: "same", line: from + 1, base: text, local: text, remote: text });
|
|
37
|
+
};
|
|
38
|
+
let at = 0;
|
|
39
|
+
for (const cluster of clusters) {
|
|
40
|
+
const from = cluster.reduce((low, hunk) => Math.min(low, hunk.from), Number.POSITIVE_INFINITY);
|
|
41
|
+
const to = cluster.reduce((high, hunk) => Math.max(high, hunk.to), 0);
|
|
42
|
+
unchanged(at, from);
|
|
43
|
+
at = Math.max(at, to);
|
|
44
|
+
const side = (name) => applied(base, from, to, cluster.filter((hunk) => hunk.side === name)).join("");
|
|
45
|
+
const original = base.slice(from, to).join("");
|
|
46
|
+
const mine = side("local");
|
|
47
|
+
const theirs = side("remote");
|
|
48
|
+
const kind = mine === original ? "remote" : theirs === original ? "local" : mine === theirs ? "both" : "conflict";
|
|
49
|
+
segments.push({ kind, line: from + 1, base: original, local: mine, remote: theirs });
|
|
50
|
+
}
|
|
51
|
+
unchanged(at, base.length);
|
|
52
|
+
return segments;
|
|
53
|
+
};
|
|
54
|
+
const decoded = (text) => Buffer.from(text, "latin1").toString("utf8");
|
|
55
|
+
/** The merge's bytes, and its segments as UTF-8 text a person reads. */
|
|
56
|
+
const resultOf = (lines) => {
|
|
57
|
+
const segments = lines.map((segment) => ({
|
|
58
|
+
...segment,
|
|
59
|
+
base: decoded(segment.base),
|
|
60
|
+
local: decoded(segment.local),
|
|
61
|
+
remote: decoded(segment.remote),
|
|
62
|
+
}));
|
|
63
|
+
const conflicts = segments.filter((segment) => segment.kind === "conflict");
|
|
64
|
+
if (conflicts.length)
|
|
65
|
+
return { conflicts, segments };
|
|
66
|
+
const text = lines.map((segment) => (segment.kind === "remote" ? segment.remote : segment.local)).join("");
|
|
67
|
+
return { merged: Buffer.from(text, "latin1"), segments };
|
|
68
|
+
};
|
|
69
|
+
const utf8 = (bytes) => {
|
|
70
|
+
const text = bytes.toString("utf8");
|
|
71
|
+
return Buffer.from(text, "utf8").equals(bytes) ? text : undefined;
|
|
72
|
+
};
|
|
73
|
+
const BOM = "";
|
|
74
|
+
const plain = (text) => (text.startsWith(BOM) ? text.slice(1) : text).replace(/\r\n/g, "\n");
|
|
75
|
+
/**
|
|
76
|
+
* Markdown that the line merge could not settle, merged by blocks: a checklist tick and a text edit on the same item
|
|
77
|
+
* no longer collide. Taken only when the remote's text is exactly what its blocks write over the base, so a change the
|
|
78
|
+
* blocks cannot see (front matter, a link definition, `_` for `*`) is never dropped; anything else stays a conflict.
|
|
79
|
+
*/
|
|
80
|
+
const mergeMarkdown = async (base, local, remote) => {
|
|
81
|
+
const [baseText, localText, remoteText] = [utf8(base), utf8(local), utf8(remote)];
|
|
82
|
+
if (baseText === undefined || localText === undefined || remoteText === undefined)
|
|
83
|
+
return undefined;
|
|
84
|
+
// The splice writes every line ending as CRLF once the file has one, which would change lines nobody edited.
|
|
85
|
+
if (/\r\n/.test(localText) && /(^|[^\r])\n/.test(localText))
|
|
86
|
+
return undefined;
|
|
87
|
+
const [baseBlocks, localBlocks, remoteBlocks] = await Promise.all([baseText, localText, remoteText].map((text) => markdownBlocks(plain(text))));
|
|
88
|
+
if (!baseBlocks || !localBlocks || !remoteBlocks)
|
|
89
|
+
return undefined;
|
|
90
|
+
if ((await spliceMarkdown(baseText, remoteBlocks)) !== remoteText)
|
|
91
|
+
return undefined;
|
|
92
|
+
const merged = mergeBlocks(baseBlocks, baseBlocks, localBlocks, remoteBlocks, undefined, adjoins);
|
|
93
|
+
if (merged.status !== "clean")
|
|
94
|
+
return undefined;
|
|
95
|
+
const text = await spliceMarkdown(localText, merged.blocks);
|
|
96
|
+
return text === undefined ? undefined : Buffer.from(text, "utf8");
|
|
97
|
+
};
|
|
98
|
+
/** Bytes that are no text a line merge can handle: a NUL, or a UTF-16 byte-order mark. */
|
|
99
|
+
const binary = (bytes) => bytes.includes(0) ||
|
|
100
|
+
(bytes.length >= 2 && ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff)));
|
|
101
|
+
/**
|
|
102
|
+
* Merges a text file both sides changed since `base`, the content of the last sync. Lines are compared as bytes
|
|
103
|
+
* (read as latin1, which maps each byte to one character), so any 8-bit encoding, line endings and a byte-order mark
|
|
104
|
+
* pass through unchanged. Markdown that conflicts by lines gets a second try by blocks. `segments` always describe the
|
|
105
|
+
* line merge, so a conflict can be shown.
|
|
106
|
+
*/
|
|
107
|
+
export const mergeText = async (path, base, local, remote) => {
|
|
108
|
+
if ([base, local, remote].some(binary)) {
|
|
109
|
+
const segment = {
|
|
110
|
+
kind: "conflict",
|
|
111
|
+
line: 1,
|
|
112
|
+
base: base.toString("utf8"),
|
|
113
|
+
local: local.toString("utf8"),
|
|
114
|
+
remote: remote.toString("utf8"),
|
|
115
|
+
};
|
|
116
|
+
return { conflicts: [segment], segments: [segment] };
|
|
117
|
+
}
|
|
118
|
+
const lines = (bytes) => linesOf(bytes.toString("latin1"));
|
|
119
|
+
const result = resultOf(mergeLines(lines(base), lines(local), lines(remote)));
|
|
120
|
+
if ("merged" in result || !MARKDOWN.has(posix.extname(path).toLowerCase()))
|
|
121
|
+
return result;
|
|
122
|
+
const merged = await mergeMarkdown(base, local, remote);
|
|
123
|
+
return merged ? { merged, segments: result.segments } : result;
|
|
124
|
+
};
|
|
125
|
+
/** The segments' text as one file, with Git's markers around each conflict; `remote` names the other side. */
|
|
126
|
+
export const conflictText = (segments, remote) => segments
|
|
127
|
+
.map((segment) => {
|
|
128
|
+
if (segment.kind !== "conflict")
|
|
129
|
+
return segment.kind === "remote" ? segment.remote : segment.local;
|
|
130
|
+
const block = (part) => (part && !part.endsWith("\n") ? `${part}\n` : part);
|
|
131
|
+
return (`<<<<<<< local\n${block(segment.local)}||||||| base\n${block(segment.base)}=======\n` +
|
|
132
|
+
`${block(segment.remote)}>>>>>>> ${remote}\n`);
|
|
133
|
+
})
|
|
134
|
+
.join("");
|
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
import { type HeldLock } from "../documents/mirrors.js";
|
|
2
|
-
/** Which way a sync moved a change. */
|
|
3
|
-
export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored";
|
|
2
|
+
/** Which way a sync moved a change; `both` is a merge or a conflict's resolution, written to both sides. */
|
|
3
|
+
export type VersionDirection = "local-to-remote" | "remote-to-local" | "restored" | "both";
|
|
4
|
+
/** The contents a merge, a conflict or its resolution worked from: the last sync's, and each side's. */
|
|
5
|
+
export interface VersionParts {
|
|
6
|
+
base?: string;
|
|
7
|
+
local?: string;
|
|
8
|
+
remote?: string;
|
|
9
|
+
}
|
|
4
10
|
/** One line of a mirror's version log: what a sync did to a path, with the content's hash before and after. */
|
|
5
11
|
export interface VersionEvent {
|
|
6
12
|
at: string;
|
|
7
13
|
path: string;
|
|
8
|
-
|
|
14
|
+
/**
|
|
15
|
+
* `merged`: both sides' changes merged into `new`. `conflict`: they could not be, and `parts` were kept. `resolved`:
|
|
16
|
+
* the owner settled the conflict with `new`, as `resolution` says.
|
|
17
|
+
*/
|
|
18
|
+
event: "created" | "changed" | "deleted" | "renamed" | "merged" | "conflict" | "resolved";
|
|
9
19
|
direction: VersionDirection;
|
|
10
20
|
/** The content the change replaced: the local file kept before a pull or deletion, the remote version an upload replaced. */
|
|
11
21
|
old?: string;
|
|
@@ -17,10 +27,22 @@ export interface VersionEvent {
|
|
|
17
27
|
size?: number;
|
|
18
28
|
/** A rename's new path. */
|
|
19
29
|
to?: string;
|
|
30
|
+
/** A merge's, a conflict's or a resolution's contents; with `new`, kept for good. */
|
|
31
|
+
parts?: VersionParts;
|
|
32
|
+
/** How the owner resolved a conflict: kept one side, both, or gave the final file. */
|
|
33
|
+
resolution?: "local" | "remote" | "both" | "file";
|
|
20
34
|
}
|
|
35
|
+
/** Which content of a merge or a conflict a kept version is; `result` is the merge's or the resolution's. */
|
|
36
|
+
export type VersionRole = "base" | "local" | "remote" | "result";
|
|
21
37
|
/** A version of a path, and whether its bytes are still in the store. */
|
|
22
38
|
export interface FileVersion extends VersionEvent {
|
|
23
39
|
available: boolean;
|
|
40
|
+
/** Each content of a merge, a conflict or a resolution, and whether the store still has it. */
|
|
41
|
+
versions?: {
|
|
42
|
+
role: VersionRole;
|
|
43
|
+
sha256: string;
|
|
44
|
+
available: boolean;
|
|
45
|
+
}[];
|
|
24
46
|
}
|
|
25
47
|
export interface FileVersions {
|
|
26
48
|
/** The folder the store keeps its copies in, when it is on disk: a sync checks its free space first. */
|
|
@@ -34,6 +56,8 @@ export interface FileVersions {
|
|
|
34
56
|
keep(source: string | ((temp: string) => Promise<void>)): Promise<string>;
|
|
35
57
|
/** Whether the store holds this content. */
|
|
36
58
|
has(sha256: string): boolean;
|
|
59
|
+
/** A kept content's bytes, or undefined when the store does not hold it. Meant for text a merge reads whole. */
|
|
60
|
+
read(sha256: string): Promise<Buffer | undefined>;
|
|
37
61
|
log(event: Omit<VersionEvent, "at">): void;
|
|
38
62
|
/** Every event of `path`, oldest first, including renames to or from it. */
|
|
39
63
|
list(path: string): FileVersion[];
|
|
@@ -42,15 +66,18 @@ export interface FileVersions {
|
|
|
42
66
|
* undefined. False when the store no longer has the version or the file was not as `over` said.
|
|
43
67
|
*/
|
|
44
68
|
write(sha256: string, into: string, over?: string): Promise<boolean>;
|
|
45
|
-
/**
|
|
46
|
-
|
|
69
|
+
/**
|
|
70
|
+
* Applies the retention rule; see `fileVersions`. `pinned` stay too: a mirror's last synced contents, the base of
|
|
71
|
+
* its next merge. A sync runs it under its lock; call it only under that lock.
|
|
72
|
+
*/
|
|
73
|
+
prune(pinned?: Iterable<string>): Promise<void>;
|
|
47
74
|
}
|
|
48
75
|
/**
|
|
49
76
|
* A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
|
|
50
|
-
* append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
* between keeping a file and logging the change loses nothing.
|
|
77
|
+
* append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention: a
|
|
78
|
+
* content stays while an event newer than 30 days names it; the last content of a path whose newest event is a
|
|
79
|
+
* deletion, and every content a merge, a conflict or a resolution names, stay for good. A content no event names stays
|
|
80
|
+
* 30 days after it was last kept, so a crash between keeping a file and logging the change loses nothing.
|
|
54
81
|
*/
|
|
55
82
|
export declare const fileVersions: (dir: string, now?: () => number) => FileVersions;
|
|
56
83
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createHash, randomUUID } from "node:crypto";
|
|
2
2
|
import { appendFileSync, createReadStream, createWriteStream, existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
3
|
-
import { mkdir, readdir, rename, rm, stat, utimes } from "node:fs/promises";
|
|
3
|
+
import { mkdir, readdir, readFile, rename, rm, stat, utimes } from "node:fs/promises";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { Transform } from "node:stream";
|
|
6
6
|
import { pipeline } from "node:stream/promises";
|
|
@@ -36,12 +36,23 @@ const copyHashed = async (from, into) => {
|
|
|
36
36
|
}), createWriteStream(into, { flags: "wx", mode: 0o600 }));
|
|
37
37
|
return hash.digest("hex");
|
|
38
38
|
};
|
|
39
|
+
const rolesOf = (event) => {
|
|
40
|
+
if (!event.parts)
|
|
41
|
+
return [];
|
|
42
|
+
const { base, local, remote } = event.parts;
|
|
43
|
+
return [
|
|
44
|
+
...(base ? [{ role: "base", sha256: base }] : []),
|
|
45
|
+
...(local ? [{ role: "local", sha256: local }] : []),
|
|
46
|
+
...(remote ? [{ role: "remote", sha256: remote }] : []),
|
|
47
|
+
...(event.new ? [{ role: "result", sha256: event.new }] : []),
|
|
48
|
+
];
|
|
49
|
+
};
|
|
39
50
|
/**
|
|
40
51
|
* A mirror's local version store: `<dir>/objects/<sha256>` holds each kept content once, `<dir>/log.jsonl` is
|
|
41
|
-
* append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention
|
|
42
|
-
*
|
|
43
|
-
*
|
|
44
|
-
* between keeping a file and logging the change loses nothing.
|
|
52
|
+
* append-only. The store lives under the profile's state folder, never inside the mirrored folder. Retention: a
|
|
53
|
+
* content stays while an event newer than 30 days names it; the last content of a path whose newest event is a
|
|
54
|
+
* deletion, and every content a merge, a conflict or a resolution names, stay for good. A content no event names stays
|
|
55
|
+
* 30 days after it was last kept, so a crash between keeping a file and logging the change loses nothing.
|
|
45
56
|
*/
|
|
46
57
|
export const fileVersions = (dir, now = Date.now) => {
|
|
47
58
|
const objects = join(dir, "objects");
|
|
@@ -59,7 +70,7 @@ export const fileVersions = (dir, now = Date.now) => {
|
|
|
59
70
|
throw error;
|
|
60
71
|
}
|
|
61
72
|
};
|
|
62
|
-
const has = (sha256) => existsSync(join(objects, sha256));
|
|
73
|
+
const has = (sha256) => /^[0-9a-f]{64}$/.test(sha256) && existsSync(join(objects, sha256));
|
|
63
74
|
return {
|
|
64
75
|
dir,
|
|
65
76
|
keep: async (source) => {
|
|
@@ -91,16 +102,31 @@ export const fileVersions = (dir, now = Date.now) => {
|
|
|
91
102
|
}
|
|
92
103
|
},
|
|
93
104
|
has,
|
|
105
|
+
read: async (sha256) => {
|
|
106
|
+
if (!has(sha256))
|
|
107
|
+
return undefined;
|
|
108
|
+
return readFile(join(objects, sha256)).catch((error) => {
|
|
109
|
+
if (error.code === "ENOENT")
|
|
110
|
+
return undefined;
|
|
111
|
+
throw error;
|
|
112
|
+
});
|
|
113
|
+
},
|
|
94
114
|
log: (event) => {
|
|
95
115
|
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
96
116
|
appendFileSync(logPath, `${JSON.stringify({ at: new Date(now()).toISOString(), ...event })}\n`, { mode: 0o600 });
|
|
97
117
|
},
|
|
98
118
|
list: (path) => {
|
|
99
119
|
const found = events().filter((event) => event.path === path || event.to === path);
|
|
100
|
-
return found.map((event) =>
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
120
|
+
return found.map((event) => {
|
|
121
|
+
const roles = rolesOf(event);
|
|
122
|
+
return {
|
|
123
|
+
...event,
|
|
124
|
+
available: roles.length
|
|
125
|
+
? roles.every(({ sha256 }) => has(sha256))
|
|
126
|
+
: event.old !== undefined && has(event.old),
|
|
127
|
+
...(roles.length ? { versions: roles.map((role) => ({ ...role, available: has(role.sha256) })) } : {}),
|
|
128
|
+
};
|
|
129
|
+
});
|
|
104
130
|
},
|
|
105
131
|
write: async (sha256, into, over) => {
|
|
106
132
|
if (!has(sha256))
|
|
@@ -108,9 +134,9 @@ export const fileVersions = (dir, now = Date.now) => {
|
|
|
108
134
|
const copy = (temp) => pipeline(createReadStream(join(objects, sha256)), createWriteStream(temp, { flags: "wx" }));
|
|
109
135
|
return (await replaceLocal(into, over, copy, { sha256 })) !== undefined;
|
|
110
136
|
},
|
|
111
|
-
prune: async () => {
|
|
137
|
+
prune: async (pinned = []) => {
|
|
112
138
|
const all = events();
|
|
113
|
-
const keep = new Set();
|
|
139
|
+
const keep = new Set(pinned);
|
|
114
140
|
const last = new Map();
|
|
115
141
|
for (const event of all) {
|
|
116
142
|
last.set(event.path, event);
|
|
@@ -118,6 +144,8 @@ export const fileVersions = (dir, now = Date.now) => {
|
|
|
118
144
|
for (const hash of [event.old, event.new])
|
|
119
145
|
if (hash)
|
|
120
146
|
keep.add(hash);
|
|
147
|
+
for (const { sha256 } of rolesOf(event))
|
|
148
|
+
keep.add(sha256);
|
|
121
149
|
}
|
|
122
150
|
for (const event of last.values())
|
|
123
151
|
if (event.event === "deleted" && event.old)
|
package/dist/store/index.d.ts
CHANGED
|
@@ -56,6 +56,7 @@ export { type ChangeFilter, CRM_CHANGES, type CrmChange, type CrmChangeKind } fr
|
|
|
56
56
|
export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, type CrmStageMove, type CrmStageTasks, crmSettingKey, type StageTaskRule, } from "./sqlite/crm-settings.js";
|
|
57
57
|
export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
|
|
58
58
|
export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
|
|
59
|
+
export { DOCUMENT_EVENTS, DOCUMENT_REMOVALS, type DocumentChange, type DocumentEvent, type DocumentHistoryAnswer, type DocumentHistoryStore, type DocumentRemoval, type DocumentVersion, type DocumentVersionText, type VersionReason, } from "./sqlite/document-history.js";
|
|
59
60
|
export { DOCUMENT_KINDS, type DocumentDetail, type DocumentFolderNode, type DocumentKind, type DocumentLink, type DocumentListFilter, type DocumentListing, type DocumentListRow, type DocumentSourceNode, } from "./sqlite/document-listing.js";
|
|
60
61
|
export type { Email, EmailAddress, EmailAttachment, EmailFacts, EmailFilter, EmailInput, EmailInThread, EmailLocationInput, EmailRecipient, EmailRef, EmailThread, EmailVectorHit, FolderEmail, Mailbox, MailboxInput, MailFilter, MailStore, PartialEmail, SenderScore, ThreadDetails, ThreadSave, } from "./sqlite/emails.js";
|
|
61
62
|
export { EVENT_FIELDS, type EventChunkToEmbed, type EventHit, type EventQuery, type EventSearch, type NearestEvent, } from "./sqlite/event-search.js";
|
|
@@ -87,6 +88,7 @@ export type { OrganizationFilter } from "./sqlite/organization-categories.js";
|
|
|
87
88
|
export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
|
|
88
89
|
export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
|
|
89
90
|
export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, type TestDataPerson, } from "./sqlite/person-doubts.js";
|
|
91
|
+
export type { PersonErasure } from "./sqlite/person-erase.js";
|
|
90
92
|
export { mergeId, type PersonMerge, parseMergeId } from "./sqlite/person-merges.js";
|
|
91
93
|
export { ALWAYS_SHOWN, PERSON_TIES, type PersonTie, type ShownBecause, SMALL_GROUP_MEMBERS, } from "./sqlite/person-ties.js";
|
|
92
94
|
export type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
|
package/dist/store/index.js
CHANGED
|
@@ -36,6 +36,7 @@ export { CATALOG_QUERY } from "./sqlite/catalog.js";
|
|
|
36
36
|
export { crmIdentityId, } from "./sqlite/crm.js";
|
|
37
37
|
export { CRM_CHANGES } from "./sqlite/crm-changes.js";
|
|
38
38
|
export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
|
|
39
|
+
export { DOCUMENT_EVENTS, DOCUMENT_REMOVALS, } from "./sqlite/document-history.js";
|
|
39
40
|
export { DOCUMENT_KINDS, } from "./sqlite/document-listing.js";
|
|
40
41
|
export { EVENT_FIELDS, } from "./sqlite/event-search.js";
|
|
41
42
|
export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
|
package/dist/store/people.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ import { type IdentityRekey, type IdentityRekeys } from "./sqlite/identity-rekey
|
|
|
9
9
|
import type { StoreContext } from "./sqlite/open.js";
|
|
10
10
|
import { type PeopleList, type PeopleListOptions, type SimilarPerson } from "./sqlite/people-list.js";
|
|
11
11
|
import { type KeptPerson, type PersonDoubts, type TestDataPerson } from "./sqlite/person-doubts.js";
|
|
12
|
+
import { type PersonErasure } from "./sqlite/person-erase.js";
|
|
12
13
|
import type { PersonMerge } from "./sqlite/person-merges.js";
|
|
13
14
|
import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
|
|
14
15
|
import { type ShownBecause } from "./sqlite/person-ties.js";
|
|
@@ -177,6 +178,13 @@ export interface PeopleStore extends AccountPeople {
|
|
|
177
178
|
* The owner's alone; refused for the owner's own person.
|
|
178
179
|
*/
|
|
179
180
|
markTestData(person: string, by: Decider): Promise<TestDataPerson>;
|
|
181
|
+
/**
|
|
182
|
+
* Deletes a person and what memo knows of them alone; see `erasePerson`. `apply: false` answers what would go and
|
|
183
|
+
* changes nothing. The owner's alone; refused for the owner's own person.
|
|
184
|
+
*/
|
|
185
|
+
erase(person: string, by: Decider, options: {
|
|
186
|
+
apply: boolean;
|
|
187
|
+
}): Promise<PersonErasure>;
|
|
180
188
|
/** The identity, and everyone linked with it, is the owner. */
|
|
181
189
|
linkToOwner(identity: IdentityRef): Promise<PersonRecord>;
|
|
182
190
|
/** A person known by name only, with no identity yet: someone to assign a task to before any message names them. */
|
package/dist/store/people.js
CHANGED
|
@@ -9,6 +9,7 @@ import * as identitySplits from "./sqlite/identity-split-proposals.js";
|
|
|
9
9
|
import { linkToOwner } from "./sqlite/own-identities.js";
|
|
10
10
|
import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
|
|
11
11
|
import { keepPerson, markTestData, personDoubts, } from "./sqlite/person-doubts.js";
|
|
12
|
+
import { erasePerson } from "./sqlite/person-erase.js";
|
|
12
13
|
import * as personLinks from "./sqlite/person-links.js";
|
|
13
14
|
import { linkPhones, PROPOSAL_SCORE, RULE, scanMatches } from "./sqlite/person-match-scan.js";
|
|
14
15
|
import * as personMerges from "./sqlite/person-merges.js";
|
|
@@ -155,6 +156,7 @@ export const peopleStoreOver = (context, keyed) => {
|
|
|
155
156
|
doubts: async (page) => personDoubts(context, page),
|
|
156
157
|
keep: async (person, by) => write(database, () => keepPerson(context, person, by)),
|
|
157
158
|
markTestData: async (person, by) => write(database, () => markTestData(context, person, by)),
|
|
159
|
+
erase: async (person, by, { apply }) => write(database, () => erasePerson(context, person, by, apply)),
|
|
158
160
|
linkToOwner: async (identity) => linkToOwner(context, identity),
|
|
159
161
|
list: async (options) => listPeople(database, options),
|
|
160
162
|
counts: async (query) => countPeople(database, query),
|
|
@@ -3,12 +3,14 @@ import { calendarCursorKey, calendarWritesOver } from "./calendar.js";
|
|
|
3
3
|
import { forgetCalendarRows } from "./calendar-forget.js";
|
|
4
4
|
import { eq, inArray, sql } from "./drizzle/core.js";
|
|
5
5
|
import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
|
|
6
|
+
import { eraseImportedPeople, importedPeople } from "./person-erase.js";
|
|
6
7
|
import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
|
|
7
8
|
import { dropUnusedVectors } from "./vector-index.js";
|
|
8
9
|
/** Everything the account holds, children before parents: the foreign keys are enforced. */
|
|
9
10
|
export const purgeAccount = (context, accountKey) => {
|
|
10
11
|
const { orm, database, now } = context;
|
|
11
12
|
const unseenBefore = unreferenced(database, "identities");
|
|
13
|
+
const imported = importedPeople(database, accountKey);
|
|
12
14
|
const at = now();
|
|
13
15
|
const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
|
|
14
16
|
const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
|
|
@@ -111,6 +113,7 @@ export const purgeAccount = (context, accountKey) => {
|
|
|
111
113
|
orm.run(sql `DELETE FROM records WHERE account_id = ${accountKey}`);
|
|
112
114
|
orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
|
|
113
115
|
dropOrphanPeople(database, unseenBefore);
|
|
116
|
+
eraseImportedPeople(context, imported);
|
|
114
117
|
forgetDanglingEvidence(database, at);
|
|
115
118
|
dropUnusedVectors(database, hashes);
|
|
116
119
|
// The links' delete trigger writes a revision naming the account it is purging; the history goes with the links.
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import type { CacheDatabase } from "../driver.js";
|
|
2
|
+
import type { StoreContext } from "./open.js";
|
|
3
|
+
type Row = Record<string, unknown>;
|
|
4
|
+
/** Why a sync took a document out of its copy. Only `deleted` is a deletion the source reported. */
|
|
5
|
+
export declare const DOCUMENT_REMOVALS: readonly ["deleted", "unavailable", "unsynced"];
|
|
6
|
+
export type DocumentRemoval = (typeof DOCUMENT_REMOVALS)[number];
|
|
7
|
+
/** What replaced a kept version: an edit, or one of the removals. */
|
|
8
|
+
export type VersionReason = "edited" | DocumentRemoval;
|
|
9
|
+
export declare const DOCUMENT_EVENTS: readonly ["added", "changed", "restored", "deleted", "unavailable", "unsynced"];
|
|
10
|
+
export type DocumentEvent = (typeof DOCUMENT_EVENTS)[number];
|
|
11
|
+
/** One earlier version of a document, as the store kept it before something replaced it. */
|
|
12
|
+
export interface DocumentVersion {
|
|
13
|
+
revision: number;
|
|
14
|
+
title: string | null;
|
|
15
|
+
reason: VersionReason;
|
|
16
|
+
/** When this version was replaced or removed; the current version's is when it was written. */
|
|
17
|
+
replacedAt: string | null;
|
|
18
|
+
current: boolean;
|
|
19
|
+
characters: number;
|
|
20
|
+
}
|
|
21
|
+
export interface DocumentVersionText extends DocumentVersion {
|
|
22
|
+
text: string;
|
|
23
|
+
frontMatter: unknown;
|
|
24
|
+
}
|
|
25
|
+
export interface DocumentHistoryAnswer {
|
|
26
|
+
ref: string;
|
|
27
|
+
title: string | null;
|
|
28
|
+
path: string;
|
|
29
|
+
revision: number;
|
|
30
|
+
deletedAt: string | null;
|
|
31
|
+
removal: DocumentRemoval | null;
|
|
32
|
+
/** Newest first, the current version at the top. */
|
|
33
|
+
versions: DocumentVersion[];
|
|
34
|
+
}
|
|
35
|
+
export interface DocumentChange {
|
|
36
|
+
ref: string;
|
|
37
|
+
path: string;
|
|
38
|
+
title: string | null;
|
|
39
|
+
event: DocumentEvent;
|
|
40
|
+
revision: number;
|
|
41
|
+
at: string;
|
|
42
|
+
}
|
|
43
|
+
export interface DocumentHistoryStore {
|
|
44
|
+
/** The document at this path of a documents account, a removed one too, as `document:<n>`. */
|
|
45
|
+
documentAt(folderId: string, path: string): Promise<string | undefined>;
|
|
46
|
+
documentHistory(reference: string): Promise<DocumentHistoryAnswer>;
|
|
47
|
+
documentVersion(reference: string, revision: number): Promise<DocumentVersionText>;
|
|
48
|
+
/** What changed in the account at or after `since` (ISO 8601), newest first. */
|
|
49
|
+
documentChanges(folderId: string, options: {
|
|
50
|
+
since: string;
|
|
51
|
+
until?: string;
|
|
52
|
+
events?: readonly DocumentEvent[];
|
|
53
|
+
limit: number;
|
|
54
|
+
offset: number;
|
|
55
|
+
}): Promise<{
|
|
56
|
+
items: DocumentChange[];
|
|
57
|
+
hasMore: boolean;
|
|
58
|
+
}>;
|
|
59
|
+
/**
|
|
60
|
+
* Drops the versions and the change log of the account older than `before` (ISO 8601), and the text of a document
|
|
61
|
+
* that has been unavailable since before then. Answers what it dropped.
|
|
62
|
+
*/
|
|
63
|
+
pruneDocumentHistory(folderId: string, before: string): Promise<{
|
|
64
|
+
versions: number;
|
|
65
|
+
changes: number;
|
|
66
|
+
texts: number;
|
|
67
|
+
}>;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* Keeps a document's text, title and front matter under its current revision before the caller replaces or removes
|
|
71
|
+
* them with `revision + 1`, so a citation reads back the words it cited and the history shows what was there.
|
|
72
|
+
*/
|
|
73
|
+
export declare const keepRevision: (database: CacheDatabase, row: Row, at: number, reason?: VersionReason) => {
|
|
74
|
+
changes: number;
|
|
75
|
+
};
|
|
76
|
+
/** One line of the change log, from the document row as it is after the change. */
|
|
77
|
+
export declare const logDocumentChange: (database: CacheDatabase, id: number, event: DocumentEvent, at: number) => void;
|
|
78
|
+
/**
|
|
79
|
+
* Takes a document out of the live copy for `reason`. An unavailable one keeps its text, since the source may show it
|
|
80
|
+
* again; a deleted or unsynced one keeps its last text as a version and its body is blanked.
|
|
81
|
+
*/
|
|
82
|
+
export declare const removeDocument: (database: CacheDatabase, id: number, at: number, reason: DocumentRemoval) => boolean;
|
|
83
|
+
export declare const documentHistoryOver: ({ database }: StoreContext) => DocumentHistoryStore;
|
|
84
|
+
export {};
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { thingOf } from "./things.js";
|
|
3
|
+
import { write } from "./transaction.js";
|
|
4
|
+
/** Why a sync took a document out of its copy. Only `deleted` is a deletion the source reported. */
|
|
5
|
+
export const DOCUMENT_REMOVALS = ["deleted", "unavailable", "unsynced"];
|
|
6
|
+
export const DOCUMENT_EVENTS = ["added", "changed", "restored", ...DOCUMENT_REMOVALS];
|
|
7
|
+
const iso = (value) => (value == null ? null : new Date(Number(value)).toISOString());
|
|
8
|
+
const json = (value) => (value == null ? null : JSON.parse(String(value)));
|
|
9
|
+
/**
|
|
10
|
+
* Keeps a document's text, title and front matter under its current revision before the caller replaces or removes
|
|
11
|
+
* them with `revision + 1`, so a citation reads back the words it cited and the history shows what was there.
|
|
12
|
+
*/
|
|
13
|
+
export const keepRevision = (database, row, at, reason = "edited") => database
|
|
14
|
+
.prepare("INSERT INTO document_revisions (document_id, body, revision, created_at, title, front_matter, reason) " +
|
|
15
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
16
|
+
.run(Number(row.id), String(row.body ?? ""), Number(row.revision), at, row.title == null ? null : String(row.title), row.front_matter == null ? null : String(row.front_matter), reason);
|
|
17
|
+
/** One line of the change log, from the document row as it is after the change. */
|
|
18
|
+
export const logDocumentChange = (database, id, event, at) => {
|
|
19
|
+
const row = database.prepare("SELECT account_id, external_id, title, revision FROM documents WHERE id = ?").get(id);
|
|
20
|
+
if (!row)
|
|
21
|
+
return;
|
|
22
|
+
database
|
|
23
|
+
.prepare("INSERT INTO document_changes (account_id, document_id, path, title, event, revision, at) " +
|
|
24
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
25
|
+
.run(Number(row.account_id), id, String(row.external_id), row.title == null ? null : String(row.title), event, Number(row.revision), at);
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Takes a document out of the live copy for `reason`. An unavailable one keeps its text, since the source may show it
|
|
29
|
+
* again; a deleted or unsynced one keeps its last text as a version and its body is blanked.
|
|
30
|
+
*/
|
|
31
|
+
export const removeDocument = (database, id, at, reason) => {
|
|
32
|
+
const row = database.prepare("SELECT * FROM documents WHERE id = ? AND deleted_at IS NULL").get(id);
|
|
33
|
+
if (!row)
|
|
34
|
+
return false;
|
|
35
|
+
if (reason === "unavailable")
|
|
36
|
+
database.prepare("UPDATE documents SET deleted_at = ?, removal = ? WHERE id = ?").run(at, reason, id);
|
|
37
|
+
else {
|
|
38
|
+
if (row.body != null)
|
|
39
|
+
keepRevision(database, row, at, reason);
|
|
40
|
+
database
|
|
41
|
+
.prepare("UPDATE documents SET deleted_at = ?, removal = ?, body = '', revision = revision + 1 WHERE id = ?")
|
|
42
|
+
.run(at, reason, id);
|
|
43
|
+
}
|
|
44
|
+
logDocumentChange(database, id, reason, at);
|
|
45
|
+
return true;
|
|
46
|
+
};
|
|
47
|
+
const removalOf = (value) => DOCUMENT_REMOVALS.includes(value) ? value : null;
|
|
48
|
+
export const documentHistoryOver = ({ database }) => {
|
|
49
|
+
const account = (folderId) => {
|
|
50
|
+
const row = /^\d+$/.test(folderId)
|
|
51
|
+
? database.prepare("SELECT id FROM accounts WHERE id = ?").get(Number(folderId))
|
|
52
|
+
: undefined;
|
|
53
|
+
if (!row)
|
|
54
|
+
throw new CliError("not_found", `no documents account ${folderId} in the local store`);
|
|
55
|
+
return Number(row.id);
|
|
56
|
+
};
|
|
57
|
+
const documentRow = (reference) => {
|
|
58
|
+
const thing = thingOf(database, reference);
|
|
59
|
+
const row = thing?.type === "document" ? database.prepare("SELECT * FROM documents WHERE id = ?").get(thing.id) : undefined;
|
|
60
|
+
if (!row)
|
|
61
|
+
throw new CliError("not_found", `document ${reference} is not in the local store`);
|
|
62
|
+
return row;
|
|
63
|
+
};
|
|
64
|
+
const kept = (id) => database
|
|
65
|
+
.prepare("SELECT revision, title, front_matter, reason, body, created_at FROM document_revisions " +
|
|
66
|
+
"WHERE document_id = ? ORDER BY revision DESC, id DESC")
|
|
67
|
+
.all(id);
|
|
68
|
+
const keptVersion = (row, current = false) => ({
|
|
69
|
+
revision: Number(row.revision),
|
|
70
|
+
title: row.title == null ? null : String(row.title),
|
|
71
|
+
reason: current ? "edited" : (row.reason ?? "edited"),
|
|
72
|
+
replacedAt: current ? null : iso(row.created_at),
|
|
73
|
+
current,
|
|
74
|
+
characters: String(row.body ?? "").length,
|
|
75
|
+
});
|
|
76
|
+
// A removed document's row holds no text of its own once its last version was kept: it is not a version then.
|
|
77
|
+
const currentShown = (row) => row.deleted_at == null || String(row.body ?? "") !== "";
|
|
78
|
+
return {
|
|
79
|
+
documentAt: async (folderId, path) => {
|
|
80
|
+
const row = database
|
|
81
|
+
.prepare("SELECT id FROM documents WHERE account_id = ? AND external_id = ?")
|
|
82
|
+
.get(account(folderId), path);
|
|
83
|
+
return row ? `document:${row.id}` : undefined;
|
|
84
|
+
},
|
|
85
|
+
documentHistory: async (reference) => {
|
|
86
|
+
const row = documentRow(reference);
|
|
87
|
+
const id = Number(row.id);
|
|
88
|
+
return {
|
|
89
|
+
ref: `document:${id}`,
|
|
90
|
+
title: row.title == null ? null : String(row.title),
|
|
91
|
+
path: String(row.external_id),
|
|
92
|
+
revision: Number(row.revision),
|
|
93
|
+
deletedAt: iso(row.deleted_at),
|
|
94
|
+
removal: row.deleted_at == null ? null : removalOf(row.removal),
|
|
95
|
+
versions: [
|
|
96
|
+
...(currentShown(row) ? [{ ...keptVersion(row, true), replacedAt: iso(row.updated_at) }] : []),
|
|
97
|
+
...kept(id).map((one) => keptVersion(one)),
|
|
98
|
+
],
|
|
99
|
+
};
|
|
100
|
+
},
|
|
101
|
+
documentVersion: async (reference, revision) => {
|
|
102
|
+
const row = documentRow(reference);
|
|
103
|
+
if (Number(row.revision) === revision && currentShown(row))
|
|
104
|
+
return {
|
|
105
|
+
...keptVersion(row, true),
|
|
106
|
+
replacedAt: iso(row.updated_at),
|
|
107
|
+
text: String(row.body ?? ""),
|
|
108
|
+
frontMatter: json(row.front_matter),
|
|
109
|
+
};
|
|
110
|
+
const found = kept(Number(row.id)).find((one) => Number(one.revision) === revision);
|
|
111
|
+
if (!found)
|
|
112
|
+
throw new CliError("not_found", `document ${reference} has no version ${revision} in the local store`, {
|
|
113
|
+
reason: "document.version-missing",
|
|
114
|
+
});
|
|
115
|
+
return { ...keptVersion(found), text: String(found.body ?? ""), frontMatter: json(found.front_matter) };
|
|
116
|
+
},
|
|
117
|
+
documentChanges: async (folderId, { since, until, events, limit, offset }) => {
|
|
118
|
+
const from = Date.parse(since);
|
|
119
|
+
const to = until === undefined ? Number.MAX_SAFE_INTEGER : Date.parse(until);
|
|
120
|
+
if (Number.isNaN(from) || Number.isNaN(to))
|
|
121
|
+
throw new CliError("validation_error", "since and until take an ISO 8601 time");
|
|
122
|
+
const kinds = events?.length ? events : DOCUMENT_EVENTS;
|
|
123
|
+
const rows = database
|
|
124
|
+
.prepare("SELECT * FROM document_changes WHERE account_id = ? AND at >= ? AND at <= ? " +
|
|
125
|
+
`AND event IN (${kinds.map(() => "?").join(", ")}) ORDER BY at DESC, id DESC LIMIT ? OFFSET ?`)
|
|
126
|
+
.all(account(folderId), from, to, ...kinds, limit + 1, offset);
|
|
127
|
+
return {
|
|
128
|
+
items: rows.slice(0, limit).map((row) => ({
|
|
129
|
+
ref: `document:${row.document_id}`,
|
|
130
|
+
path: String(row.path),
|
|
131
|
+
title: row.title == null ? null : String(row.title),
|
|
132
|
+
event: row.event,
|
|
133
|
+
revision: Number(row.revision),
|
|
134
|
+
at: iso(row.at),
|
|
135
|
+
})),
|
|
136
|
+
hasMore: rows.length > limit,
|
|
137
|
+
};
|
|
138
|
+
},
|
|
139
|
+
pruneDocumentHistory: async (folderId, before) => write(database, () => {
|
|
140
|
+
const id = account(folderId);
|
|
141
|
+
const cut = Date.parse(before);
|
|
142
|
+
if (Number.isNaN(cut))
|
|
143
|
+
throw new CliError("validation_error", "before takes an ISO 8601 time");
|
|
144
|
+
const versions = database
|
|
145
|
+
.prepare("DELETE FROM document_revisions WHERE created_at < ? " +
|
|
146
|
+
"AND document_id IN (SELECT id FROM documents WHERE account_id = ?)")
|
|
147
|
+
.run(cut, id).changes;
|
|
148
|
+
const changes = database
|
|
149
|
+
.prepare("DELETE FROM document_changes WHERE account_id = ? AND at < ?")
|
|
150
|
+
.run(id, cut).changes;
|
|
151
|
+
const texts = database
|
|
152
|
+
.prepare("UPDATE documents SET body = '', revision = revision + 1 WHERE account_id = ? AND removal = 'unavailable' " +
|
|
153
|
+
"AND deleted_at IS NOT NULL AND deleted_at < ? AND body <> ''")
|
|
154
|
+
.run(id, cut).changes;
|
|
155
|
+
return { versions, changes, texts };
|
|
156
|
+
}),
|
|
157
|
+
};
|
|
158
|
+
};
|