@wirecat/cli-core 0.657.0 → 0.659.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 +35 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/calendar/index.d.ts +1 -1
- package/dist/calendar/index.js +1 -1
- package/dist/calendar/mcp/index.d.ts +12 -12
- package/dist/calendar/reads.d.ts +1 -0
- package/dist/calendar/reads.js +1 -1
- package/dist/cli/config-command.js +2 -9
- package/dist/cli/config-issues.js +1 -1
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +2 -0
- package/dist/cli/listings.d.ts +46 -0
- package/dist/cli/listings.js +188 -0
- package/dist/cli/messenger/messages-delete-command.d.ts +2 -1
- package/dist/cli/messenger/messages-delete-command.js +2 -1
- package/dist/cli/messenger/serve-relay.d.ts +1 -1
- package/dist/{cli → domain}/config-repair.d.ts +7 -0
- package/dist/{cli → domain}/config-repair.js +53 -0
- package/dist/entities/listings.d.ts +514 -0
- package/dist/entities/listings.js +154 -0
- package/dist/errors/reasons.js +4 -0
- package/dist/kit/sync-after-install.js +5 -0
- package/dist/replies/rules.d.ts +1 -1
- package/dist/replies/rules.js +1 -1
- package/dist/sends/permissions.js +5 -4
- package/dist/services/index.d.ts +1 -0
- package/dist/services/index.js +1 -0
- package/dist/services/listings.d.ts +74 -0
- package/dist/services/listings.js +285 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/index.d.ts +2 -0
- package/dist/store/index.js +2 -0
- package/dist/store/shared-config.d.ts +2 -0
- package/dist/store/shared-config.js +38 -8
- package/dist/store/sqlite/calendar-events.d.ts +10 -0
- package/dist/store/sqlite/calendar-events.js +18 -8
- package/dist/store/sqlite/document-listing.d.ts +99 -0
- package/dist/store/sqlite/document-listing.js +292 -0
- package/dist/store/sqlite/files.d.ts +2 -0
- package/dist/store/sqlite/files.js +7 -3
- package/dist/store/sqlite/meeting-listing.d.ts +108 -0
- package/dist/store/sqlite/meeting-listing.js +431 -0
- package/dist/store/store.d.ts +4 -0
- package/dist/store/store.js +6 -0
- package/package.json +1 -1
|
@@ -6,6 +6,8 @@ export type TaskCategoryEdits = Record<string, string | null>;
|
|
|
6
6
|
* A store moved by `MESSAGING_STORE` (tests, `bin/tg`) reads the one beside it, so it never reads the owner's.
|
|
7
7
|
*/
|
|
8
8
|
export declare const sharedConfigPath: (store: string, env?: NodeJS.ProcessEnv) => string;
|
|
9
|
+
/** Beside the file, so the owner finds it; a second repair in the same millisecond never replaces the first. */
|
|
10
|
+
export declare const backupPathFor: (file: string) => string;
|
|
9
11
|
/** The `task_categories` section, or `undefined` when the file or the section is missing. */
|
|
10
12
|
export declare const readTaskCategoryEdits: (path: string) => TaskCategoryEdits | undefined;
|
|
11
13
|
/** `base` with the edits applied: a text sets the category (a new one goes before `other`), `null` drops it. */
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { dirname, join, resolve } from "node:path";
|
|
3
|
-
import { CliError, resolvePaths } from "@wirecat/cli-base";
|
|
3
|
+
import { CliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
|
|
4
|
+
import { explainBrokenJson, repairConfigText, SAFE_REPAIRS } from "../domain/config-repair.js";
|
|
4
5
|
import { DEFAULT_TASK_CATEGORIES, FALLBACK_CATEGORY, taskCategoryValue, withTaskCategory, } from "../domain/task-categories.js";
|
|
5
6
|
import { storePath } from "./path.js";
|
|
6
7
|
const SECTION = "task_categories";
|
|
@@ -16,10 +17,40 @@ export const sharedConfigPath = (store, env = process.env) => {
|
|
|
16
17
|
? join(paths.config, "config.json")
|
|
17
18
|
: join(dirname(store), "config.json");
|
|
18
19
|
};
|
|
20
|
+
/** Beside the file, so the owner finds it; a second repair in the same millisecond never replaces the first. */
|
|
21
|
+
export const backupPathFor = (file) => {
|
|
22
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
23
|
+
let path = `${file}.bak-${stamp}`;
|
|
24
|
+
for (let n = 2; existsSync(path); n++)
|
|
25
|
+
path = `${file}.bak-${stamp}-${n}`;
|
|
26
|
+
return path;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* A slip with one reading (a byte-order mark, a comment, a trailing or a missing comma between lines) is mended in
|
|
30
|
+
* the file, the old one kept beside it (owner, 2026-11-14); anything else is refused with its line and likely fix.
|
|
31
|
+
*/
|
|
32
|
+
const mended = (path, bytes) => {
|
|
33
|
+
const text = bytes.toString("utf8");
|
|
34
|
+
const result = repairConfigText(text);
|
|
35
|
+
if (result.state === "repaired" && result.fixes.every((one) => SAFE_REPAIRS.has(one.kind))) {
|
|
36
|
+
try {
|
|
37
|
+
writeSecurely(backupPathFor(path), bytes, statSync(path).mode & 0o777);
|
|
38
|
+
writeSecurely(path, result.text, 0o600);
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
// A file this run cannot write is still read as mended; the next run that can write mends it.
|
|
42
|
+
}
|
|
43
|
+
return JSON.parse(result.text);
|
|
44
|
+
}
|
|
45
|
+
throw new CliError("configuration_error", `${path} is not valid JSON, ${explainBrokenJson(text, result)}`, {
|
|
46
|
+
reason: "config.invalid_json",
|
|
47
|
+
file: path,
|
|
48
|
+
});
|
|
49
|
+
};
|
|
19
50
|
const readJson = (path) => {
|
|
20
|
-
let
|
|
51
|
+
let bytes;
|
|
21
52
|
try {
|
|
22
|
-
|
|
53
|
+
bytes = readFileSync(path);
|
|
23
54
|
}
|
|
24
55
|
catch (error) {
|
|
25
56
|
if (error.code === "ENOENT")
|
|
@@ -28,11 +59,10 @@ const readJson = (path) => {
|
|
|
28
59
|
}
|
|
29
60
|
let parsed;
|
|
30
61
|
try {
|
|
31
|
-
|
|
32
|
-
parsed = JSON.parse(text.replace(/^\uFEFF/u, ""));
|
|
62
|
+
parsed = JSON.parse(bytes.toString("utf8"));
|
|
33
63
|
}
|
|
34
|
-
catch
|
|
35
|
-
|
|
64
|
+
catch {
|
|
65
|
+
parsed = mended(path, bytes);
|
|
36
66
|
}
|
|
37
67
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
38
68
|
throw new CliError("configuration_error", `${path} must hold a JSON object`);
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
import type { Event, EventFilter } from "../../meetings/index.js";
|
|
2
2
|
import type { CacheDatabase } from "../driver.js";
|
|
3
|
+
type WindowFilter = Pick<EventFilter, "from" | "fromDate" | "to" | "toDate" | "startsFrom" | "startsFromDate">;
|
|
4
|
+
/**
|
|
5
|
+
* The SQL over `events e` for a filter's time bounds: timed events by instant, all-day ones by their local days, plus
|
|
6
|
+
* bounds on `starts_at` alone so SQLite can seek its index.
|
|
7
|
+
*/
|
|
8
|
+
export declare const eventWindow: (database: CacheDatabase, filter: WindowFilter) => {
|
|
9
|
+
clauses: string[];
|
|
10
|
+
params: (string | number)[];
|
|
11
|
+
};
|
|
3
12
|
/** The events of a filter, earliest first (`EventStore.events`). */
|
|
4
13
|
export declare const listEvents: (database: CacheDatabase, filter: EventFilter) => Event[];
|
|
14
|
+
export {};
|
|
@@ -11,11 +11,15 @@ const accountsOf = (filter) => {
|
|
|
11
11
|
throw new CliError("validation_error", "accountIds names no account");
|
|
12
12
|
return filter.accountIds ?? (filter.accountId === undefined ? undefined : [filter.accountId]);
|
|
13
13
|
};
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
const longestEvent = (database) => Number(database.prepare("SELECT coalesce(max(ends_at - starts_at), 0) AS ms FROM events WHERE deleted_at IS NULL").get()
|
|
15
|
+
?.ms ?? 0);
|
|
16
|
+
/**
|
|
17
|
+
* The SQL over `events e` for a filter's time bounds: timed events by instant, all-day ones by their local days, plus
|
|
18
|
+
* bounds on `starts_at` alone so SQLite can seek its index.
|
|
19
|
+
*/
|
|
20
|
+
export const eventWindow = (database, filter) => {
|
|
21
|
+
const clauses = [];
|
|
17
22
|
const params = [];
|
|
18
|
-
const entries = (extra) => `EXISTS (SELECT 1 FROM calendar_entries ce JOIN calendars c ON c.id = ce.calendar_id WHERE ce.event_id = e.id AND ${extra})`;
|
|
19
23
|
const dated = (column, date, instant, at) => {
|
|
20
24
|
if (at === undefined)
|
|
21
25
|
return;
|
|
@@ -32,11 +36,9 @@ export const listEvents = (database, filter) => {
|
|
|
32
36
|
dated("start_date >= ?", filter.startsFromDate, "e.starts_at >= ?", filter.startsFrom);
|
|
33
37
|
// Bounds on starts_at alone let SQLite seek its index; the CASE above cannot. They are wider than the CASE: by the
|
|
34
38
|
// longest stored event back, and by a day each way for an all-day event's zone.
|
|
35
|
-
const longest = () => Number(database.prepare("SELECT coalesce(max(ends_at - starts_at), 0) AS ms FROM events WHERE deleted_at IS NULL").get()
|
|
36
|
-
?.ms ?? 0);
|
|
37
39
|
if (filter.from !== undefined) {
|
|
38
40
|
clauses.push("e.starts_at >= ?");
|
|
39
|
-
params.push(filter.from -
|
|
41
|
+
params.push(filter.from - longestEvent(database) - DAY);
|
|
40
42
|
}
|
|
41
43
|
if (filter.to !== undefined && filter.toDate !== undefined) {
|
|
42
44
|
clauses.push("e.starts_at < ?");
|
|
@@ -46,6 +48,14 @@ export const listEvents = (database, filter) => {
|
|
|
46
48
|
clauses.push("e.starts_at >= ?");
|
|
47
49
|
params.push(filter.startsFrom - DAY);
|
|
48
50
|
}
|
|
51
|
+
return { clauses, params };
|
|
52
|
+
};
|
|
53
|
+
/** The events of a filter, earliest first (`EventStore.events`). */
|
|
54
|
+
export const listEvents = (database, filter) => {
|
|
55
|
+
const window = eventWindow(database, filter);
|
|
56
|
+
const clauses = ["e.deleted_at IS NULL", ...window.clauses];
|
|
57
|
+
const params = [...window.params];
|
|
58
|
+
const entries = (extra) => `EXISTS (SELECT 1 FROM calendar_entries ce JOIN calendars c ON c.id = ce.calendar_id WHERE ce.event_id = e.id AND ${extra})`;
|
|
49
59
|
if (filter.id !== undefined) {
|
|
50
60
|
clauses.push("e.id = ?");
|
|
51
61
|
params.push(filter.id);
|
|
@@ -107,7 +117,7 @@ export const listEvents = (database, filter) => {
|
|
|
107
117
|
AND coalesce(bce.transparency, '') <> 'transparent'
|
|
108
118
|
AND coalesce(bce.event_type, '') <> 'working-location')`;
|
|
109
119
|
const own = busy("e");
|
|
110
|
-
params.push(
|
|
120
|
+
params.push(longestEvent(database));
|
|
111
121
|
const clash = `${own} AND EXISTS (SELECT 1 FROM events e2 WHERE e2.id <> e.id AND e2.starts_at < e.ends_at
|
|
112
122
|
AND e2.ends_at > e.starts_at AND e2.starts_at >= e.starts_at - ? AND ${busy("e2")})`;
|
|
113
123
|
clauses.push(filter.overlapping ? clash : `NOT (${clash})`);
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import type { QueryAst } from "@wirecat/cli-base/query";
|
|
2
|
+
import { type ListedAccount } from "./meeting-listing.js";
|
|
3
|
+
import type { StoreContext } from "./open.js";
|
|
4
|
+
/** What a document is to a person, from its MIME type and file name: the Documents page filters and shows by it. */
|
|
5
|
+
export declare const DOCUMENT_KINDS: readonly ["transcript", "doc", "sheet", "slides", "pdf", "docx", "xlsx", "pptx", "csv", "md", "txt", "html", "page", "image", "other"];
|
|
6
|
+
export type DocumentKind = (typeof DOCUMENT_KINDS)[number];
|
|
7
|
+
export declare const DOCUMENT_KIND_SQL: string;
|
|
8
|
+
export interface DocumentListFilter {
|
|
9
|
+
/** Stored account ids; every account when left out. */
|
|
10
|
+
accountIds?: readonly number[];
|
|
11
|
+
/** The rest of the list's query, over `DOCUMENT_LIST_COLUMNS`' fields. */
|
|
12
|
+
query?: QueryAst;
|
|
13
|
+
/** Only these documents, in this order: what a text search found, best first. */
|
|
14
|
+
ids?: readonly number[];
|
|
15
|
+
zone?: string;
|
|
16
|
+
now?: number;
|
|
17
|
+
limit: number;
|
|
18
|
+
offset: number;
|
|
19
|
+
}
|
|
20
|
+
export interface DocumentListRow {
|
|
21
|
+
id: number;
|
|
22
|
+
accountId: number;
|
|
23
|
+
provider: string;
|
|
24
|
+
account: string;
|
|
25
|
+
accountName: string | null;
|
|
26
|
+
title: string | null;
|
|
27
|
+
fileName: string | null;
|
|
28
|
+
kind: DocumentKind;
|
|
29
|
+
mime: string | null;
|
|
30
|
+
size: number | null;
|
|
31
|
+
url: string | null;
|
|
32
|
+
/** A copy the store keeps of an added file, or a local file's own path when the writer kept one. */
|
|
33
|
+
localPath: string | null;
|
|
34
|
+
/** Where the source keeps it, relative to the account: a Drive folder path, a notes folder's path. */
|
|
35
|
+
path: string | null;
|
|
36
|
+
folder: string | null;
|
|
37
|
+
modifiedAt: number | null;
|
|
38
|
+
storedAt: number;
|
|
39
|
+
hasText: boolean;
|
|
40
|
+
}
|
|
41
|
+
export interface DocumentFolderNode {
|
|
42
|
+
name: string;
|
|
43
|
+
path: string;
|
|
44
|
+
/** Documents in it and in every folder under it. */
|
|
45
|
+
count: number;
|
|
46
|
+
folders: DocumentFolderNode[];
|
|
47
|
+
}
|
|
48
|
+
export interface DocumentSourceNode {
|
|
49
|
+
accountId: number;
|
|
50
|
+
provider: string;
|
|
51
|
+
account: string;
|
|
52
|
+
name: string | null;
|
|
53
|
+
count: number;
|
|
54
|
+
/** Documents kept at the top, in no folder. */
|
|
55
|
+
loose: number;
|
|
56
|
+
folders: DocumentFolderNode[];
|
|
57
|
+
}
|
|
58
|
+
export interface DocumentLink {
|
|
59
|
+
ref: string;
|
|
60
|
+
title: string | null;
|
|
61
|
+
at: number | null;
|
|
62
|
+
role: string | null;
|
|
63
|
+
}
|
|
64
|
+
export interface DocumentDetail extends DocumentListRow {
|
|
65
|
+
text: string | null;
|
|
66
|
+
/** The text's length in characters, all of it, whatever part `text` holds. */
|
|
67
|
+
textLength: number;
|
|
68
|
+
extraction: string | null;
|
|
69
|
+
extractionError: string | null;
|
|
70
|
+
language: string | null;
|
|
71
|
+
tags: string[];
|
|
72
|
+
people: {
|
|
73
|
+
ref: string;
|
|
74
|
+
name: string | null;
|
|
75
|
+
kind: string;
|
|
76
|
+
}[];
|
|
77
|
+
meetings: DocumentLink[];
|
|
78
|
+
events: DocumentLink[];
|
|
79
|
+
}
|
|
80
|
+
export interface DocumentListing {
|
|
81
|
+
/** Every account holding a listed document: what a list reads when no source narrows it. */
|
|
82
|
+
documentAccounts(): Promise<ListedAccount[]>;
|
|
83
|
+
/** One page of every document the filter takes, newest change first (or in `ids`' order). */
|
|
84
|
+
documents(filter: DocumentListFilter): Promise<{
|
|
85
|
+
items: DocumentListRow[];
|
|
86
|
+
total: number;
|
|
87
|
+
}>;
|
|
88
|
+
/** Provider → account → folder, with how many documents each holds, for the accounts given or all of them. */
|
|
89
|
+
documentSources(filter: {
|
|
90
|
+
accountIds?: readonly number[];
|
|
91
|
+
depth: number;
|
|
92
|
+
}): Promise<DocumentSourceNode[]>;
|
|
93
|
+
/** One listed document with a part of its text, from `offset` for `limit` characters. */
|
|
94
|
+
document(id: number, text: {
|
|
95
|
+
offset: number;
|
|
96
|
+
limit: number;
|
|
97
|
+
}): Promise<DocumentDetail | undefined>;
|
|
98
|
+
}
|
|
99
|
+
export declare const documentListingOver: (context: StoreContext) => DocumentListing;
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { normalizeTag } from "../../domain/tags.js";
|
|
3
|
+
import { PREFERRED_FILE, subtreeOf } from "./files.js";
|
|
4
|
+
import { accountOf } from "./meeting-listing.js";
|
|
5
|
+
import { idsOf } from "./merged-persons.js";
|
|
6
|
+
import { queryFilter } from "./query-filter.js";
|
|
7
|
+
import { canonicalTagNamed } from "./tags.js";
|
|
8
|
+
import { thingOf } from "./things.js";
|
|
9
|
+
import { read } from "./transaction.js";
|
|
10
|
+
/** What a document is to a person, from its MIME type and file name: the Documents page filters and shows by it. */
|
|
11
|
+
export const DOCUMENT_KINDS = [
|
|
12
|
+
"transcript",
|
|
13
|
+
"doc",
|
|
14
|
+
"sheet",
|
|
15
|
+
"slides",
|
|
16
|
+
"pdf",
|
|
17
|
+
"docx",
|
|
18
|
+
"xlsx",
|
|
19
|
+
"pptx",
|
|
20
|
+
"csv",
|
|
21
|
+
"md",
|
|
22
|
+
"txt",
|
|
23
|
+
"html",
|
|
24
|
+
"page",
|
|
25
|
+
"image",
|
|
26
|
+
"other",
|
|
27
|
+
];
|
|
28
|
+
const ext = "lower(coalesce(d.extension, ''))";
|
|
29
|
+
const mime = "coalesce(f.mime, d.mime, '')";
|
|
30
|
+
const among = (values) => `${ext} IN (${values.map((value) => `'${value}'`).join(", ")})`;
|
|
31
|
+
/** A meeting's transcript saved as a document (a Meet transcript Drive imported) is a transcript whatever its type. */
|
|
32
|
+
const TRANSCRIPT_LINK = "EXISTS (SELECT 1 FROM links tl WHERE tl.to_type = 'document' AND tl.to_id = d.id AND tl.from_type = 'meeting' " +
|
|
33
|
+
"AND tl.kind = 'attached' AND tl.role = 'transcript')";
|
|
34
|
+
const OFFICE = "application/vnd.openxmlformats-officedocument";
|
|
35
|
+
export const DOCUMENT_KIND_SQL = `CASE
|
|
36
|
+
WHEN ${among(["vtt", "srt"])} OR ${TRANSCRIPT_LINK} THEN 'transcript'
|
|
37
|
+
WHEN ${mime} = 'application/vnd.google-apps.document' THEN 'doc'
|
|
38
|
+
WHEN ${mime} = 'application/vnd.google-apps.spreadsheet' THEN 'sheet'
|
|
39
|
+
WHEN ${mime} = 'application/vnd.google-apps.presentation' THEN 'slides'
|
|
40
|
+
WHEN ${mime} = 'application/pdf' OR ${among(["pdf"])} THEN 'pdf'
|
|
41
|
+
WHEN ${among(["docx", "doc", "odt", "rtf", "epub"])} OR ${mime} LIKE '${OFFICE}.wordprocessingml%' THEN 'docx'
|
|
42
|
+
WHEN ${among(["xlsx", "xls", "ods"])} OR ${mime} LIKE '${OFFICE}.spreadsheetml%' THEN 'xlsx'
|
|
43
|
+
WHEN ${among(["pptx", "ppt", "odp"])} OR ${mime} LIKE '${OFFICE}.presentationml%' THEN 'pptx'
|
|
44
|
+
WHEN ${among(["csv", "tsv"])} OR ${mime} IN ('text/csv', 'text/tab-separated-values') THEN 'csv'
|
|
45
|
+
WHEN ${among(["md", "markdown"])} OR ${mime} = 'text/markdown' THEN 'md'
|
|
46
|
+
WHEN ${among(["txt", "text", "log"])} OR ${mime} = 'text/plain' THEN 'txt'
|
|
47
|
+
WHEN ${among(["html", "htm"])} OR ${mime} = 'text/html' THEN 'html'
|
|
48
|
+
WHEN ${mime} LIKE 'image/%' THEN 'image'
|
|
49
|
+
WHEN d.kind = 'page' THEN 'page'
|
|
50
|
+
WHEN d.kind = 'text' THEN 'txt'
|
|
51
|
+
ELSE 'other' END`;
|
|
52
|
+
const PREFERRED = "LEFT JOIN files f ON f.id = (SELECT f.id FROM files f WHERE f.document_id = d.id AND f.kind <> 'folder' " +
|
|
53
|
+
`ORDER BY ${PREFERRED_FILE} LIMIT 1)`;
|
|
54
|
+
/** Documents a list shows: not deleted, not a folder, and still in its source's catalog. */
|
|
55
|
+
const LISTED = "d.deleted_at IS NULL AND d.kind <> 'folder' AND coalesce(json_extract(d.metadata, '$.catalog.active'), 1) = 1";
|
|
56
|
+
const MODIFIED = "coalesce(f.external_updated_at, d.external_updated_at, d.updated_at)";
|
|
57
|
+
/** A document's place: its preferred file's path, else where a folder import put it. */
|
|
58
|
+
const PATH = "coalesce(f.path, CASE WHEN d.storage = 'local' THEN d.external_id END)";
|
|
59
|
+
// lower() folds ASCII only; the files' own paths are folded in full when stored.
|
|
60
|
+
const PATH_FOLDED = "coalesce(f.path_folded, CASE WHEN d.storage = 'local' THEN lower(d.external_id) END)";
|
|
61
|
+
const COLUMNS = `d.id, d.account_id, a.provider, a.external_id AS account, a.name AS account_name, d.title, d.file_name,
|
|
62
|
+
${DOCUMENT_KIND_SQL} AS kind, coalesce(f.mime, d.mime) AS mime, coalesce(f.size, d.size) AS size,
|
|
63
|
+
coalesce(f.url, d.url) AS url, d.local_path, ${PATH} AS path, ${MODIFIED} AS modified_at, d.updated_at,
|
|
64
|
+
d.body IS NOT NULL AS has_text`;
|
|
65
|
+
const str = (value) => (value == null ? null : String(value));
|
|
66
|
+
const num = (value) => (value == null ? null : Number(value));
|
|
67
|
+
const folderOf = (path) => {
|
|
68
|
+
if (path === null)
|
|
69
|
+
return null;
|
|
70
|
+
const slash = path.lastIndexOf("/");
|
|
71
|
+
return slash <= 0 ? null : path.slice(0, slash);
|
|
72
|
+
};
|
|
73
|
+
const rowOf = (row) => {
|
|
74
|
+
const path = str(row.path);
|
|
75
|
+
return {
|
|
76
|
+
id: Number(row.id),
|
|
77
|
+
accountId: Number(row.account_id),
|
|
78
|
+
provider: String(row.provider),
|
|
79
|
+
account: String(row.account),
|
|
80
|
+
accountName: str(row.account_name),
|
|
81
|
+
title: str(row.title),
|
|
82
|
+
fileName: str(row.file_name),
|
|
83
|
+
kind: String(row.kind),
|
|
84
|
+
mime: str(row.mime),
|
|
85
|
+
size: num(row.size),
|
|
86
|
+
url: str(row.url),
|
|
87
|
+
localPath: str(row.local_path),
|
|
88
|
+
path,
|
|
89
|
+
folder: folderOf(path),
|
|
90
|
+
modifiedAt: num(row.modified_at),
|
|
91
|
+
storedAt: Number(row.updated_at),
|
|
92
|
+
hasText: Number(row.has_text) === 1,
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
const invalid = (message) => {
|
|
96
|
+
throw new CliError("validation_error", message);
|
|
97
|
+
};
|
|
98
|
+
/** The list's fields as the store answers them; `text` is searched before, and arrives as `ids`. */
|
|
99
|
+
const columns = (context) => {
|
|
100
|
+
const { database } = context;
|
|
101
|
+
return {
|
|
102
|
+
kind: { type: "enum", sql: DOCUMENT_KIND_SQL },
|
|
103
|
+
source_modified_at: { type: "time", sql: MODIFIED },
|
|
104
|
+
has_text: { type: "bool", sql: "(d.body IS NOT NULL)" },
|
|
105
|
+
folder: {
|
|
106
|
+
where: (node) => {
|
|
107
|
+
const [low, high] = subtreeOf(node.value.replace(/^\/+/u, ""));
|
|
108
|
+
return { sql: `(${PATH_FOLDED} >= ? AND ${PATH_FOLDED} < ?)`, params: [low, high], known: true };
|
|
109
|
+
},
|
|
110
|
+
},
|
|
111
|
+
tag: {
|
|
112
|
+
where: (node) => ({
|
|
113
|
+
sql: "EXISTS (SELECT 1 FROM taggings g JOIN resolved_tags t ON t.id = g.tag_id " +
|
|
114
|
+
"WHERE g.taggable_type = 'document' AND g.taggable_id = d.id AND t.name = ?)",
|
|
115
|
+
params: [canonicalTagNamed(database, node.value)?.name ?? normalizeTag(node.value)],
|
|
116
|
+
}),
|
|
117
|
+
},
|
|
118
|
+
person: {
|
|
119
|
+
where: (node) => {
|
|
120
|
+
let found;
|
|
121
|
+
try {
|
|
122
|
+
found = thingOf(database, node.value.startsWith("person:") ? node.value : `person:${node.value}`);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
found = undefined;
|
|
126
|
+
}
|
|
127
|
+
if (!found)
|
|
128
|
+
return { sql: "0", params: [], known: true };
|
|
129
|
+
return {
|
|
130
|
+
sql: "EXISTS (SELECT 1 FROM links l WHERE l.from_type = 'document' AND l.from_id = d.id AND l.to_type = ? " +
|
|
131
|
+
"AND l.to_id IN (SELECT value FROM json_each(?)))",
|
|
132
|
+
params: [found.type, idsOf(database, found.type, found.id)],
|
|
133
|
+
};
|
|
134
|
+
},
|
|
135
|
+
},
|
|
136
|
+
};
|
|
137
|
+
};
|
|
138
|
+
const scoped = (filter, where) => {
|
|
139
|
+
const clauses = [LISTED];
|
|
140
|
+
const params = [];
|
|
141
|
+
if (filter.accountIds !== undefined) {
|
|
142
|
+
if (filter.accountIds.length === 0)
|
|
143
|
+
invalid("accountIds names no account");
|
|
144
|
+
clauses.push("d.account_id IN (SELECT value FROM json_each(?))");
|
|
145
|
+
params.push(JSON.stringify(filter.accountIds));
|
|
146
|
+
}
|
|
147
|
+
if (where) {
|
|
148
|
+
clauses.push(`(${where.sql})`);
|
|
149
|
+
for (const param of where.params)
|
|
150
|
+
params.push(param);
|
|
151
|
+
}
|
|
152
|
+
return { sql: clauses.join(" AND "), params };
|
|
153
|
+
};
|
|
154
|
+
const FROM = `FROM documents d JOIN accounts a ON a.id = d.account_id ${PREFERRED}`;
|
|
155
|
+
const treeOf = (paths, depth) => {
|
|
156
|
+
const root = { name: "", path: "", count: 0, folders: [] };
|
|
157
|
+
let loose = 0;
|
|
158
|
+
for (const [folder, count] of paths) {
|
|
159
|
+
if (folder === "") {
|
|
160
|
+
loose += count;
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
let at = root;
|
|
164
|
+
const parts = folder.split("/");
|
|
165
|
+
for (const [index, name] of parts.slice(0, depth).entries()) {
|
|
166
|
+
const path = parts.slice(0, index + 1).join("/");
|
|
167
|
+
let child = at.folders.find((one) => one.path === path);
|
|
168
|
+
if (!child) {
|
|
169
|
+
child = { name, path, count: 0, folders: [] };
|
|
170
|
+
at.folders.push(child);
|
|
171
|
+
}
|
|
172
|
+
child.count += count;
|
|
173
|
+
at = child;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
const sort = (nodes) => {
|
|
177
|
+
nodes.sort((a, b) => a.name.localeCompare(b.name));
|
|
178
|
+
for (const node of nodes)
|
|
179
|
+
sort(node.folders);
|
|
180
|
+
};
|
|
181
|
+
sort(root.folders);
|
|
182
|
+
return { loose, folders: root.folders };
|
|
183
|
+
};
|
|
184
|
+
export const documentListingOver = (context) => {
|
|
185
|
+
const { database } = context;
|
|
186
|
+
const whereOf = (query, zone, now) => query && queryFilter(query, columns(context), { ...(zone ? { zone } : {}), ...(now ? { now } : {}) });
|
|
187
|
+
return {
|
|
188
|
+
documentAccounts: async () => database
|
|
189
|
+
.prepare(`SELECT id, provider, external_id, name FROM accounts WHERE id IN (SELECT d.account_id FROM documents d ` +
|
|
190
|
+
`WHERE ${LISTED}) ORDER BY provider, external_id`)
|
|
191
|
+
.all()
|
|
192
|
+
.map(accountOf),
|
|
193
|
+
documents: async (filter) => {
|
|
194
|
+
if (!Number.isInteger(filter.limit) || filter.limit < 1 || !Number.isInteger(filter.offset) || filter.offset < 0)
|
|
195
|
+
invalid("limit takes 1 or more and offset 0 or more");
|
|
196
|
+
if (filter.ids?.length === 0)
|
|
197
|
+
return { items: [], total: 0 };
|
|
198
|
+
const where = scoped(filter, whereOf(filter.query, filter.zone, filter.now));
|
|
199
|
+
// A text search's ids come ranked: joined as a table, their position orders the page.
|
|
200
|
+
const from = filter.ids ? `${FROM} JOIN json_each(?) k ON k.value = d.id` : FROM;
|
|
201
|
+
const ranked = filter.ids ? [JSON.stringify(filter.ids)] : [];
|
|
202
|
+
const order = filter.ids ? "k.key" : `${MODIFIED} DESC, d.id DESC`;
|
|
203
|
+
return read(database, () => {
|
|
204
|
+
// Counted apart: a window count would make SQLite build every row's columns before the page is cut.
|
|
205
|
+
const total = Number(database.prepare(`SELECT count(*) AS n ${from} WHERE ${where.sql}`).get(...ranked, ...where.params)?.n);
|
|
206
|
+
// The page's ids first, then its columns: SQLite would build every row's kind and path before the cut.
|
|
207
|
+
const page = database
|
|
208
|
+
.prepare(`SELECT d.id ${from} WHERE ${where.sql} ORDER BY ${order} LIMIT ? OFFSET ?`)
|
|
209
|
+
.all(...ranked, ...where.params, filter.limit, filter.offset)
|
|
210
|
+
.map(({ id }) => Number(id));
|
|
211
|
+
const found = database
|
|
212
|
+
.prepare(`SELECT ${COLUMNS} ${FROM} JOIN json_each(?) p ON p.value = d.id ORDER BY p.key`)
|
|
213
|
+
.all(JSON.stringify(page));
|
|
214
|
+
return { items: found.map(rowOf), total };
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
documentSources: async ({ accountIds, depth }) => {
|
|
218
|
+
const where = scoped({ ...(accountIds ? { accountIds } : {}) }, undefined);
|
|
219
|
+
return read(database, () => {
|
|
220
|
+
const rows = database
|
|
221
|
+
.prepare(`SELECT d.account_id, a.provider, a.external_id AS account, a.name AS account_name, ${PATH} AS path ${FROM} ` +
|
|
222
|
+
`WHERE ${where.sql}`)
|
|
223
|
+
.all(...where.params);
|
|
224
|
+
const byAccount = new Map();
|
|
225
|
+
for (const row of rows) {
|
|
226
|
+
const id = Number(row.account_id);
|
|
227
|
+
const held = byAccount.get(id) ?? { row, folders: new Map() };
|
|
228
|
+
byAccount.set(id, held);
|
|
229
|
+
const folder = folderOf(str(row.path)) ?? "";
|
|
230
|
+
held.folders.set(folder, (held.folders.get(folder) ?? 0) + 1);
|
|
231
|
+
}
|
|
232
|
+
return [...byAccount.entries()]
|
|
233
|
+
.map(([accountId, { row, folders }]) => ({
|
|
234
|
+
accountId,
|
|
235
|
+
provider: String(row.provider),
|
|
236
|
+
account: String(row.account),
|
|
237
|
+
name: str(row.account_name),
|
|
238
|
+
count: [...folders.values()].reduce((sum, count) => sum + count, 0),
|
|
239
|
+
...treeOf(folders, depth),
|
|
240
|
+
}))
|
|
241
|
+
.sort((a, b) => a.provider.localeCompare(b.provider) || a.account.localeCompare(b.account));
|
|
242
|
+
});
|
|
243
|
+
},
|
|
244
|
+
document: async (id, { offset, limit }) => read(database, () => {
|
|
245
|
+
const row = database
|
|
246
|
+
.prepare(`SELECT ${COLUMNS}, substr(d.body, ?, ?) AS text, length(d.body) AS text_length, d.extraction,
|
|
247
|
+
d.extraction_error, d.language ${FROM} WHERE d.id = ? AND ${LISTED}`)
|
|
248
|
+
.get(offset + 1, limit, id);
|
|
249
|
+
if (!row)
|
|
250
|
+
return undefined;
|
|
251
|
+
const tags = database
|
|
252
|
+
.prepare("SELECT t.name FROM taggings g JOIN resolved_tags t ON t.id = g.tag_id " +
|
|
253
|
+
"WHERE g.taggable_type = 'document' AND g.taggable_id = ? ORDER BY t.name")
|
|
254
|
+
.all(id)
|
|
255
|
+
.map((tag) => String(tag.name));
|
|
256
|
+
const people = database
|
|
257
|
+
.prepare("SELECT DISTINCT p.id, p.name, l.kind FROM links l JOIN persons p ON p.id = l.to_id " +
|
|
258
|
+
"WHERE l.from_type = 'document' AND l.from_id = ? AND l.to_type = 'person' ORDER BY p.name, p.id")
|
|
259
|
+
.all(id)
|
|
260
|
+
.map((person) => ({ ref: `person:${person.id}`, name: str(person.name), kind: String(person.kind) }));
|
|
261
|
+
const meetings = database
|
|
262
|
+
.prepare("SELECT m.id, m.account_id, m.title, m.started_at, l.role FROM links l JOIN meetings m ON m.id = l.from_id " +
|
|
263
|
+
"WHERE l.from_type = 'meeting' AND l.to_type = 'document' AND l.to_id = ? AND l.kind = 'attached' " +
|
|
264
|
+
"AND m.deleted_at IS NULL ORDER BY m.started_at DESC, m.id")
|
|
265
|
+
.all(id)
|
|
266
|
+
.map((meeting) => ({
|
|
267
|
+
ref: `meeting:${meeting.account_id}/${meeting.id}`,
|
|
268
|
+
title: str(meeting.title),
|
|
269
|
+
at: num(meeting.started_at),
|
|
270
|
+
role: str(meeting.role),
|
|
271
|
+
}));
|
|
272
|
+
const events = database
|
|
273
|
+
.prepare("SELECT DISTINCT e.id, e.title, e.starts_at FROM links l JOIN calendar_entries ce ON ce.id = l.from_id " +
|
|
274
|
+
"JOIN events e ON e.id = ce.event_id WHERE l.from_type = 'calendar_entry' AND l.to_type = 'document' " +
|
|
275
|
+
"AND l.to_id = ? AND l.kind = 'attached' AND e.deleted_at IS NULL ORDER BY e.starts_at DESC, e.id")
|
|
276
|
+
.all(id)
|
|
277
|
+
.map((event) => ({ ref: `event:${event.id}`, title: str(event.title), at: num(event.starts_at), role: null }));
|
|
278
|
+
return {
|
|
279
|
+
...rowOf(row),
|
|
280
|
+
text: str(row.text),
|
|
281
|
+
textLength: Number(row.text_length ?? 0),
|
|
282
|
+
extraction: str(row.extraction),
|
|
283
|
+
extractionError: str(row.extraction_error),
|
|
284
|
+
language: str(row.language),
|
|
285
|
+
tags,
|
|
286
|
+
people,
|
|
287
|
+
meetings,
|
|
288
|
+
events,
|
|
289
|
+
};
|
|
290
|
+
}),
|
|
291
|
+
};
|
|
292
|
+
};
|
|
@@ -90,6 +90,8 @@ export declare const fileOf: (row: Row) => StoredFile;
|
|
|
90
90
|
* Read with the document's row joined as `d`.
|
|
91
91
|
*/
|
|
92
92
|
export declare const PREFERRED_FILE = "f.deleted_at IS NOT NULL, f.id IS NOT d.pinned_file_id, coalesce(f.external_updated_at, f.updated_at) DESC, f.id DESC";
|
|
93
|
+
/** The folded paths under a folder, as one range over the index: `/` sorts just before `0`. */
|
|
94
|
+
export declare const subtreeOf: (folder: string) => [low: string, high: string];
|
|
93
95
|
export declare const filesStoreOver: ({ database, now }: {
|
|
94
96
|
database: CacheDatabase;
|
|
95
97
|
now: () => number;
|
|
@@ -256,6 +256,11 @@ export const fileOf = (row) => ({
|
|
|
256
256
|
* Read with the document's row joined as `d`.
|
|
257
257
|
*/
|
|
258
258
|
export const PREFERRED_FILE = "f.deleted_at IS NOT NULL, f.id IS NOT d.pinned_file_id, coalesce(f.external_updated_at, f.updated_at) DESC, f.id DESC";
|
|
259
|
+
/** The folded paths under a folder, as one range over the index: `/` sorts just before `0`. */
|
|
260
|
+
export const subtreeOf = (folder) => {
|
|
261
|
+
const prefix = fold(folder.replace(/\/+$/u, ""));
|
|
262
|
+
return [`${prefix}/`, `${prefix}0`];
|
|
263
|
+
};
|
|
259
264
|
export const filesStoreOver = ({ database, now }) => {
|
|
260
265
|
const account = (id) => {
|
|
261
266
|
if (!/^\d+$/.test(id) || !database.prepare("SELECT 1 FROM accounts WHERE id = ?").get(Number(id)))
|
|
@@ -276,10 +281,9 @@ export const filesStoreOver = ({ database, now }) => {
|
|
|
276
281
|
params.push(query.kind);
|
|
277
282
|
}
|
|
278
283
|
if (query.under !== undefined) {
|
|
279
|
-
const
|
|
280
|
-
// `/` sorts just before `0`, so the subtree is one range over the index.
|
|
284
|
+
const [low, high] = subtreeOf(query.under);
|
|
281
285
|
clauses.push("(f.path_folded = ? OR (f.path_folded >= ? AND f.path_folded < ?))");
|
|
282
|
-
params.push(
|
|
286
|
+
params.push(fold(query.under.replace(/\/+$/u, "")), low, high);
|
|
283
287
|
}
|
|
284
288
|
if (query.pathContains !== undefined) {
|
|
285
289
|
clauses.push("instr(f.path_folded, ?) > 0");
|