@creator-notes/cnotes 0.112.0 → 0.113.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/.claude-plugin/plugin.json +1 -1
- package/README.md +15 -0
- package/dist/commands/query.js +233 -0
- package/dist/lib/auth-store.js +4 -0
- package/dist/lib/local-db-store.js +200 -0
- package/dist/local-db/apply.js +166 -0
- package/dist/local-db/ops.js +102 -0
- package/dist/local-db/protocol.js +10 -0
- package/dist/local-db/query.js +184 -0
- package/dist/local-db/schema.js +83 -0
- package/dist/local-db/sync.js +270 -0
- package/dist/local-db/types.js +8 -0
- package/dist/mcp-server.js +32 -0
- package/dist/program.js +2 -0
- package/package.json +4 -3
- package/skills/cnotes/references/more-commands.md +22 -0
package/README.md
CHANGED
|
@@ -50,6 +50,7 @@ cnotes search semantic "onboarding flow"
|
|
|
50
50
|
| `cnotes draft open\|status\|propose\|edits\|ask\|checkout\|dismiss` | | Private drafts: build many notes and canvases out of sight, propose edits to shared notes, and branch a shared board (`open --from-canvas CANVAS-n`) to rework your own copy of it. Run `status` until no check blocks, then `ask --reviewer <person>` and stop: only that person accepts it, in the browser; no key can merge it |
|
|
51
51
|
| `cnotes focus plan\|list\|cancel` | | Plan protected focus blocks; `--canvas` + `--target` land a block on the exact card it works on |
|
|
52
52
|
| `cnotes search semantic` | `cnotes s` | Semantic search across notes |
|
|
53
|
+
| `cnotes query` | `cnotes q` | Filter, group or run a SELECT over every note's metadata from a local SQLite copy of the workspace, synced on each call |
|
|
53
54
|
| `cnotes timeline` | `cnotes tl` | Recent activity feed |
|
|
54
55
|
| `cnotes relationships list` | `cnotes rel` | Note relationships |
|
|
55
56
|
| `cnotes types list\|create\|update` | `cnotes t` | Manage note types (supertags) |
|
|
@@ -326,6 +327,20 @@ mkdir -p .claude/skills/cnotes
|
|
|
326
327
|
cp $(npm root -g)/@creator-notes/cnotes/skills/cnotes/SKILL.md .claude/skills/cnotes/SKILL.md
|
|
327
328
|
```
|
|
328
329
|
|
|
330
|
+
## Query the local copy (`cnotes query`)
|
|
331
|
+
|
|
332
|
+
`cnotes query` keeps a SQLite copy of the workspace's note metadata (titles, types, tags, canvases, who made each note, judged answers; never a note body) under `~/.cnotes/local-db/`, syncs what changed since the last call, and answers from the copy in milliseconds. The web app's Query panel uses the same copy format, so the two never disagree.
|
|
333
|
+
|
|
334
|
+
```bash
|
|
335
|
+
cnotes query pricing --type Decision,Insight # words in the title, AND across fields
|
|
336
|
+
cnotes query --canvas CANVAS-12 --group-by tag # notes on one canvas, grouped by tag
|
|
337
|
+
cnotes query --made-by agent --group-by month # what agents wrote, by month
|
|
338
|
+
cnotes query --sql "SELECT type, COUNT(*) AS n FROM notes GROUP BY type ORDER BY n DESC"
|
|
339
|
+
cnotes query --rebuild # drop this workspace's copy and copy it again
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
`--group-by` takes `type`, `canvas`, `tag`, `month`, `person`, `made-by`, `none`, or `<Type>:<dimension>` for a judged dimension. `--sql` runs one read-only SELECT (`--sql tables` prints the tables). Needs Node.js 22.13 or newer.
|
|
343
|
+
|
|
329
344
|
## Scripting
|
|
330
345
|
|
|
331
346
|
```bash
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { ApiClient } from "../lib/api-client.js";
|
|
2
|
+
import { resolveConfig } from "../lib/config.js";
|
|
3
|
+
import { ValidationError, handleError } from "../lib/errors.js";
|
|
4
|
+
import { outputJson, timeAgo, truncate } from "../lib/output.js";
|
|
5
|
+
import { openLocalCopy } from "../lib/local-db-store.js";
|
|
6
|
+
import { SCHEMA_HINT } from "../local-db/schema.js";
|
|
7
|
+
import { UNJUDGED } from "../local-db/query.js";
|
|
8
|
+
const GROUPS = {
|
|
9
|
+
type: "type",
|
|
10
|
+
canvas: "canvas",
|
|
11
|
+
tag: "tag",
|
|
12
|
+
month: "month",
|
|
13
|
+
person: "author",
|
|
14
|
+
author: "author",
|
|
15
|
+
"made-by": "source",
|
|
16
|
+
source: "source",
|
|
17
|
+
none: "none",
|
|
18
|
+
};
|
|
19
|
+
const SOURCES = new Set(["human", "agent", "import", "api"]);
|
|
20
|
+
const list = (value) => value
|
|
21
|
+
?.split(",")
|
|
22
|
+
.map((v) => v.trim())
|
|
23
|
+
.filter(Boolean);
|
|
24
|
+
/** A canvas by display id (CANVAS-12), by name, or by Convex id. */
|
|
25
|
+
function resolveCanvas(ref, head) {
|
|
26
|
+
const lower = ref.toLowerCase();
|
|
27
|
+
const hit = head.canvases.find((c) => c.id === ref || c.displayId?.toLowerCase() === lower || c.name.toLowerCase() === lower);
|
|
28
|
+
if (!hit) {
|
|
29
|
+
throw new ValidationError(`No canvas "${ref}" in this workspace.`, "Pass a CANVAS-<n> display id or the canvas name; `cnotes canvas list` shows both.");
|
|
30
|
+
}
|
|
31
|
+
return hit.id;
|
|
32
|
+
}
|
|
33
|
+
/** Members whose name contains the text, case-insensitively. */
|
|
34
|
+
function resolveAuthors(text, head) {
|
|
35
|
+
const lower = text.toLowerCase();
|
|
36
|
+
const ids = head.members.filter((m) => (m.name ?? "").toLowerCase().includes(lower)).map((m) => m.userId);
|
|
37
|
+
if (ids.length === 0)
|
|
38
|
+
throw new ValidationError(`No member named "${text}" in this workspace.`);
|
|
39
|
+
return ids;
|
|
40
|
+
}
|
|
41
|
+
/** Turn the command's words and flags into the shared filter and grouping. */
|
|
42
|
+
export function parseQuery(words, opts, head) {
|
|
43
|
+
const filter = {};
|
|
44
|
+
const text = words.join(" ").trim();
|
|
45
|
+
if (text)
|
|
46
|
+
filter.text = text;
|
|
47
|
+
const types = list(opts.type);
|
|
48
|
+
if (types?.length)
|
|
49
|
+
filter.types = types;
|
|
50
|
+
const canvases = list(opts.canvas);
|
|
51
|
+
if (canvases?.length)
|
|
52
|
+
filter.canvasIds = canvases.map((c) => resolveCanvas(c, head));
|
|
53
|
+
const tags = list(opts.tag);
|
|
54
|
+
if (tags?.length)
|
|
55
|
+
filter.tags = tags;
|
|
56
|
+
const sources = list(opts.madeBy);
|
|
57
|
+
if (sources?.length) {
|
|
58
|
+
const bad = sources.find((s) => !SOURCES.has(s));
|
|
59
|
+
if (bad)
|
|
60
|
+
throw new ValidationError(`--made-by takes human, agent, api or import, not "${bad}".`);
|
|
61
|
+
filter.sources = sources;
|
|
62
|
+
}
|
|
63
|
+
if (opts.by)
|
|
64
|
+
filter.authors = resolveAuthors(opts.by, head);
|
|
65
|
+
const groupBy = parseGroupBy(opts.groupBy, head);
|
|
66
|
+
const limit = opts.limit ? parseInt(opts.limit, 10) : 100;
|
|
67
|
+
if (!Number.isFinite(limit) || limit < 1)
|
|
68
|
+
throw new ValidationError("--limit must be a positive number.");
|
|
69
|
+
return { filter, groupBy, limit };
|
|
70
|
+
}
|
|
71
|
+
export function parseGroupBy(value, head) {
|
|
72
|
+
if (!value)
|
|
73
|
+
return "type";
|
|
74
|
+
const known = GROUPS[value.toLowerCase()];
|
|
75
|
+
if (known)
|
|
76
|
+
return known;
|
|
77
|
+
// "<Type>:<dimension>" names a judged dimension, by its key or its label.
|
|
78
|
+
const [type, dim] = value.split(":");
|
|
79
|
+
const match = head.dimensions.find((d) => d.type.toLowerCase() === type?.toLowerCase() && (d.key.toLowerCase() === dim?.toLowerCase() || d.label.toLowerCase() === dim?.toLowerCase()));
|
|
80
|
+
if (match)
|
|
81
|
+
return `dimension:${match.type}:${match.key}`;
|
|
82
|
+
const choices = [...Object.keys(GROUPS).filter((k) => k !== "author" && k !== "source"), ...head.dimensions.map((d) => `${d.type}:${d.key}`)];
|
|
83
|
+
throw new ValidationError(`Unknown --group-by "${value}".`, `One of: ${choices.join(", ")}.`);
|
|
84
|
+
}
|
|
85
|
+
/** The JSON shape `--json` prints. */
|
|
86
|
+
export function toJsonResult(result, head, status) {
|
|
87
|
+
const canvasNames = new Map(head.canvases.map((c) => [c.id, c.displayId ?? c.name]));
|
|
88
|
+
return {
|
|
89
|
+
total: result.total,
|
|
90
|
+
groups: result.groups.map((g) => ({ value: g.value, label: g.label, count: g.count })),
|
|
91
|
+
rows: result.rows.map((r) => ({
|
|
92
|
+
id: r.id,
|
|
93
|
+
displayId: r.display_id,
|
|
94
|
+
title: r.title,
|
|
95
|
+
type: r.type,
|
|
96
|
+
updatedAt: r.updated_at,
|
|
97
|
+
group: r.group_label,
|
|
98
|
+
})),
|
|
99
|
+
shown: result.rows.length,
|
|
100
|
+
ms: Math.round(result.ms * 10) / 10,
|
|
101
|
+
sync: syncSummary(status),
|
|
102
|
+
canvases: Object.fromEntries(canvasNames),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
export function syncSummary(status) {
|
|
106
|
+
return {
|
|
107
|
+
notes: status.counts.notes,
|
|
108
|
+
canvases: status.counts.canvases,
|
|
109
|
+
bytes: status.counts.bytes,
|
|
110
|
+
firstCopy: status.firstPassMs != null && status.firstPassMs === status.lastPassMs,
|
|
111
|
+
ms: status.lastPassMs == null ? null : Math.round(status.lastPassMs),
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
/** Lines for the terminal: a heading per group, then `ID title when` rows. */
|
|
115
|
+
export function renderResult(result, groupBy) {
|
|
116
|
+
const lines = [];
|
|
117
|
+
if (result.total === 0)
|
|
118
|
+
return ["No notes match."];
|
|
119
|
+
let current = null;
|
|
120
|
+
for (const row of result.rows) {
|
|
121
|
+
if (groupBy !== "none" && row.group_key !== current) {
|
|
122
|
+
current = row.group_key;
|
|
123
|
+
const count = result.groups.find((g) => `${g.value}` === row.group_key)?.count ?? 0;
|
|
124
|
+
if (lines.length)
|
|
125
|
+
lines.push("");
|
|
126
|
+
lines.push(`${row.group_label} (${count})`);
|
|
127
|
+
}
|
|
128
|
+
const when = row.updated_at ? timeAgo(row.updated_at) : "";
|
|
129
|
+
lines.push(` ${row.display_id.padEnd(16)} ${truncate(row.title || "Untitled", 60).padEnd(60)} ${when}`);
|
|
130
|
+
}
|
|
131
|
+
const shown = new Set(result.rows.map((r) => r.id)).size;
|
|
132
|
+
lines.push("");
|
|
133
|
+
lines.push(`${result.total} ${result.total === 1 ? "note" : "notes"}` +
|
|
134
|
+
(shown < result.total ? ` · showing ${shown}; raise --limit for more` : "") +
|
|
135
|
+
` · ${result.ms < 10 ? result.ms.toFixed(1) : Math.round(result.ms)} ms`);
|
|
136
|
+
return lines;
|
|
137
|
+
}
|
|
138
|
+
export function renderSql(out) {
|
|
139
|
+
const lines = [];
|
|
140
|
+
if (out.columns.length === 0)
|
|
141
|
+
return ["No rows."];
|
|
142
|
+
const widths = out.columns.map((c, i) => Math.max(c.length, ...out.rows.map((r) => String(r[i] ?? "").length)));
|
|
143
|
+
lines.push(out.columns.map((c, i) => c.padEnd(widths[i])).join(" "));
|
|
144
|
+
lines.push(widths.map((w) => "-".repeat(w)).join(" "));
|
|
145
|
+
for (const row of out.rows)
|
|
146
|
+
lines.push(row.map((cell, i) => String(cell ?? "").padEnd(widths[i])).join(" "));
|
|
147
|
+
lines.push("");
|
|
148
|
+
lines.push(`${out.rows.length}${out.truncated ? "+" : ""} rows · ${out.ms < 10 ? out.ms.toFixed(1) : Math.round(out.ms)} ms`);
|
|
149
|
+
return lines;
|
|
150
|
+
}
|
|
151
|
+
const SQL_MAX_ROWS = 500;
|
|
152
|
+
/** Everything `cnotes query` and the MCP tool share: sync, ask, shape the answer. */
|
|
153
|
+
export async function runQuery(api, workspaceId, words, opts, directory) {
|
|
154
|
+
const opened = await openLocalCopy({ api, workspaceId, rebuild: opts.rebuild, directory });
|
|
155
|
+
try {
|
|
156
|
+
if (opts.sql !== undefined) {
|
|
157
|
+
if (opts.sql.trim().toLowerCase() === "tables") {
|
|
158
|
+
return { kind: "tables", tables: SCHEMA_HINT, sync: syncSummary(opened.status) };
|
|
159
|
+
}
|
|
160
|
+
const out = opened.store.db.sql({ sql: opts.sql, maxRows: SQL_MAX_ROWS });
|
|
161
|
+
return { kind: "sql", ...out, sync: syncSummary(opened.status) };
|
|
162
|
+
}
|
|
163
|
+
const { filter, groupBy, limit } = parseQuery(words, opts, opened.head);
|
|
164
|
+
const result = opened.store.db.query({ filter, groupBy, limit });
|
|
165
|
+
return { kind: "notes", result, groupBy, json: toJsonResult(result, opened.head, opened.status) };
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
opened.store.close();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
export function registerQueryCommands(program) {
|
|
172
|
+
program
|
|
173
|
+
.command("query")
|
|
174
|
+
.alias("q")
|
|
175
|
+
.description("Filter, group or run a SELECT over every note's metadata, from a local copy of the workspace")
|
|
176
|
+
.argument("[words...]", "Words that must all appear in the title or display id")
|
|
177
|
+
.option("--type <types>", "Note types, comma-separated (Decision,Insight)")
|
|
178
|
+
.option("--canvas <refs>", "Canvases by CANVAS-<n> or name, comma-separated")
|
|
179
|
+
.option("--tag <tags>", "Tags, comma-separated")
|
|
180
|
+
.option("--made-by <sources>", "human, agent, api or import, comma-separated")
|
|
181
|
+
.option("--by <name>", "Notes made by a member whose name contains this")
|
|
182
|
+
.option("--group-by <field>", "type (default), canvas, tag, month, person, made-by, none, or <Type>:<dimension>")
|
|
183
|
+
.option("--limit <n>", "Rows to return (default 100)")
|
|
184
|
+
.option("--sql <select>", "Run one read-only SELECT against the copy; `tables` lists the tables")
|
|
185
|
+
.option("--rebuild", "Drop this workspace's copy and copy it again")
|
|
186
|
+
.addHelpText("after", `
|
|
187
|
+
The copy holds every note's metadata (title, type, tags, canvases, who made it,
|
|
188
|
+
judged answers), never a note body. The first call copies the workspace; later
|
|
189
|
+
calls sync only what changed, then answer in milliseconds.
|
|
190
|
+
|
|
191
|
+
Examples:
|
|
192
|
+
$ cnotes query pricing --type Decision,Insight
|
|
193
|
+
$ cnotes query --canvas CANVAS-12 --group-by tag
|
|
194
|
+
$ cnotes query --made-by agent --group-by month --json
|
|
195
|
+
$ cnotes query --group-by Risk:status # the state '${UNJUDGED}' is a group too
|
|
196
|
+
$ cnotes query --sql "SELECT type, COUNT(*) AS n FROM notes GROUP BY type ORDER BY n DESC"
|
|
197
|
+
$ cnotes query --sql tables
|
|
198
|
+
`)
|
|
199
|
+
.action(async (words, opts) => {
|
|
200
|
+
const cfg = resolveConfig(program.opts());
|
|
201
|
+
const api = new ApiClient(cfg.serverUrl, cfg.token, cfg.workspaceId);
|
|
202
|
+
try {
|
|
203
|
+
const answer = await runQuery(api, cfg.workspaceId, words, opts);
|
|
204
|
+
if (answer.kind === "tables") {
|
|
205
|
+
if (cfg.json)
|
|
206
|
+
outputJson({ tables: answer.tables, sync: answer.sync }, cfg.fields);
|
|
207
|
+
else
|
|
208
|
+
for (const line of answer.tables)
|
|
209
|
+
console.log(line);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (answer.kind === "sql") {
|
|
213
|
+
if (cfg.json) {
|
|
214
|
+
const { kind: _kind, ...rest } = answer;
|
|
215
|
+
outputJson(rest, cfg.fields);
|
|
216
|
+
}
|
|
217
|
+
else
|
|
218
|
+
for (const line of renderSql(answer))
|
|
219
|
+
console.log(line);
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
if (cfg.json) {
|
|
223
|
+
outputJson(answer.json, cfg.fields);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
for (const line of renderResult(answer.result, answer.groupBy))
|
|
227
|
+
console.log(line);
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
handleError(error, cfg.json);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
package/dist/lib/auth-store.js
CHANGED
|
@@ -7,6 +7,10 @@ import { BRAND } from "./brand.js";
|
|
|
7
7
|
// multi-profile setups). Unset in normal use, which is the homedir default.
|
|
8
8
|
const CONFIG_DIR = process.env.CNOTES_CONFIG_DIR || join(homedir(), BRAND.configDir);
|
|
9
9
|
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
|
10
|
+
/** The directory everything the CLI keeps on disk lives under (config, local workspace copies). */
|
|
11
|
+
export function getConfigDir() {
|
|
12
|
+
return CONFIG_DIR;
|
|
13
|
+
}
|
|
10
14
|
/**
|
|
11
15
|
* One-time migration of the pre-rename config dir (`~/.creatornotes`) to the
|
|
12
16
|
* current one (`~/.cnotes`). Best-effort and idempotent: it only acts when the
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* The CLI's local copy of a workspace's note metadata: the same SQLite
|
|
11
|
+
* database the web app's Query panel keeps (src/local-db/, copied from
|
|
12
|
+
* lib/local-db/), held in a file under the config directory and filled
|
|
13
|
+
* through `POST /api/local-db` with the caller's key.
|
|
14
|
+
*
|
|
15
|
+
* The web app runs the database in a worker over SQLite-wasm; here it is
|
|
16
|
+
* `node:sqlite` (or `bun:sqlite` in the compiled binary) in-process, so a
|
|
17
|
+
* "call" is a direct function call. Everything else (schema, sync loop, query
|
|
18
|
+
* builder) is the shared code.
|
|
19
|
+
*/
|
|
20
|
+
import { existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
|
|
21
|
+
import { join } from "node:path";
|
|
22
|
+
import { getConfigDir } from "./auth-store.js";
|
|
23
|
+
import { CliError, NotFoundError } from "./errors.js";
|
|
24
|
+
import { createLocalDbOps, openCopy } from "../local-db/ops.js";
|
|
25
|
+
import { workspaceFilePrefix } from "../local-db/protocol.js";
|
|
26
|
+
import { IDLE_STATUS, WorkspaceSync } from "../local-db/sync.js";
|
|
27
|
+
/** Where the copies live: one file per member per workspace. */
|
|
28
|
+
export function localDbDirectory() {
|
|
29
|
+
return join(getConfigDir(), "local-db");
|
|
30
|
+
}
|
|
31
|
+
export const NODE_SQLITE_HINT = "cnotes query keeps the workspace copy in node:sqlite, which needs Node.js 22.13 or newer. " +
|
|
32
|
+
"Upgrade Node (https://nodejs.org), or use the cnotes binary, which carries its own runtime.";
|
|
33
|
+
async function loadDatabase() {
|
|
34
|
+
try {
|
|
35
|
+
const mod = (await import(__rewriteRelativeImportExtension("node:sqlite")));
|
|
36
|
+
return mod.DatabaseSync;
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
// Not Node 22.13+, or the module is behind a flag.
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const mod = (await import(__rewriteRelativeImportExtension("bun:sqlite")));
|
|
43
|
+
return mod.Database;
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
throw new CliError(NODE_SQLITE_HINT);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** The handle the shared code needs, over one open database. */
|
|
50
|
+
function wrap(handle) {
|
|
51
|
+
return {
|
|
52
|
+
run: (sql, params = []) => {
|
|
53
|
+
if (params.length)
|
|
54
|
+
handle.prepare(sql).run(...params);
|
|
55
|
+
else
|
|
56
|
+
handle.exec(sql);
|
|
57
|
+
},
|
|
58
|
+
all: (sql, params = []) => handle.prepare(sql).all(...params),
|
|
59
|
+
transaction: (fn) => {
|
|
60
|
+
handle.exec("BEGIN");
|
|
61
|
+
try {
|
|
62
|
+
const result = fn();
|
|
63
|
+
handle.exec("COMMIT");
|
|
64
|
+
return result;
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
handle.exec("ROLLBACK");
|
|
68
|
+
throw err;
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
rows: (sql, params = []) => {
|
|
72
|
+
// query_only makes SQLite itself refuse any write, whatever the text says.
|
|
73
|
+
handle.exec("PRAGMA query_only = 1");
|
|
74
|
+
try {
|
|
75
|
+
const stmt = handle.prepare(sql);
|
|
76
|
+
const columns = stmt.columns ? stmt.columns().map((c) => c.name) : (stmt.columnNames ?? []);
|
|
77
|
+
const objects = stmt.all(...params);
|
|
78
|
+
const names = columns.length ? columns : Object.keys(objects[0] ?? {});
|
|
79
|
+
return { columns: names, rows: objects.map((o) => names.map((c) => o[c] ?? null)) };
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
handle.exec("PRAGMA query_only = 0");
|
|
83
|
+
}
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
// The database as the sync loop sees it: an open file plus the shared ops.
|
|
89
|
+
// ---------------------------------------------------------------------------
|
|
90
|
+
export class LocalCopyStore {
|
|
91
|
+
Database;
|
|
92
|
+
directory;
|
|
93
|
+
handle = null;
|
|
94
|
+
ops = null;
|
|
95
|
+
openPath = null;
|
|
96
|
+
constructor(Database, directory) {
|
|
97
|
+
this.Database = Database;
|
|
98
|
+
this.directory = directory;
|
|
99
|
+
}
|
|
100
|
+
/** Query, facets and SQL over the open copy; throws until a sync has opened it. */
|
|
101
|
+
get db() {
|
|
102
|
+
if (!this.ops)
|
|
103
|
+
throw new CliError("The local copy is not open yet.");
|
|
104
|
+
return this.ops;
|
|
105
|
+
}
|
|
106
|
+
get path() {
|
|
107
|
+
return this.openPath;
|
|
108
|
+
}
|
|
109
|
+
close() {
|
|
110
|
+
this.handle?.close();
|
|
111
|
+
this.handle = null;
|
|
112
|
+
this.ops = null;
|
|
113
|
+
this.openPath = null;
|
|
114
|
+
}
|
|
115
|
+
async call(op, args) {
|
|
116
|
+
switch (op) {
|
|
117
|
+
case "open": {
|
|
118
|
+
const { fileName, wipeFirst } = args;
|
|
119
|
+
this.close();
|
|
120
|
+
if (wipeFirst)
|
|
121
|
+
this.wipeAll();
|
|
122
|
+
mkdirSync(this.directory, { recursive: true, mode: 0o700 });
|
|
123
|
+
// The shared name is an OPFS path with a leading slash.
|
|
124
|
+
const path = join(this.directory, fileName.replace(/^\//, ""));
|
|
125
|
+
this.handle = new this.Database(path);
|
|
126
|
+
this.openPath = path;
|
|
127
|
+
const db = wrap(this.handle);
|
|
128
|
+
this.ops = createLocalDbOps(db);
|
|
129
|
+
return openCopy(db, true);
|
|
130
|
+
}
|
|
131
|
+
case "forget": {
|
|
132
|
+
const { workspaceId } = args;
|
|
133
|
+
const prefix = workspaceFilePrefix(workspaceId).replace(/^\//, "");
|
|
134
|
+
if (this.openPath && this.openPath.includes(prefix))
|
|
135
|
+
this.close();
|
|
136
|
+
this.removeFiles((name) => name.startsWith(prefix));
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
case "wipe":
|
|
140
|
+
this.close();
|
|
141
|
+
this.wipeAll();
|
|
142
|
+
return null;
|
|
143
|
+
default: {
|
|
144
|
+
const handler = this.db[op];
|
|
145
|
+
return handler(args);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
wipeAll() {
|
|
150
|
+
this.removeFiles(() => true);
|
|
151
|
+
}
|
|
152
|
+
removeFiles(match) {
|
|
153
|
+
if (!existsSync(this.directory))
|
|
154
|
+
return;
|
|
155
|
+
for (const name of readdirSync(this.directory)) {
|
|
156
|
+
if (match(name))
|
|
157
|
+
rmSync(join(this.directory, name), { force: true });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
export function restSyncSource(api, workspaceId) {
|
|
162
|
+
const call = (body) => api.post("/api/local-db", { workspaceId, ...body });
|
|
163
|
+
return {
|
|
164
|
+
noteIds: (cursor, numItems) => call({ op: "noteIds", cursor, numItems }),
|
|
165
|
+
notesChangedSince: (since, cursor, numItems) => call({ op: "changedSince", since, cursor, numItems }),
|
|
166
|
+
notesByIds: (ids) => call({ op: "notesByIds", ids }),
|
|
167
|
+
placements: (canvasIds) => call({ op: "placements", canvasIds }),
|
|
168
|
+
dimensionAnswers: (supertagId, dimensionKey, cursor, numItems) => call({ op: "answers", supertagId, dimensionKey, cursor, numItems }),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
export function fetchSyncHead(api, workspaceId) {
|
|
172
|
+
return api.post("/api/local-db", { op: "head", workspaceId });
|
|
173
|
+
}
|
|
174
|
+
// ---------------------------------------------------------------------------
|
|
175
|
+
// One call: open the copy, bring it up to date, hand it back.
|
|
176
|
+
// ---------------------------------------------------------------------------
|
|
177
|
+
/** Inside this window a call pulls only what changed; past it, every note id is compared again. */
|
|
178
|
+
export const RECONCILE_EVERY_MS = 60 * 60 * 1000;
|
|
179
|
+
export async function openLocalCopy(options) {
|
|
180
|
+
const Database = await loadDatabase();
|
|
181
|
+
const directory = options.directory ?? localDbDirectory();
|
|
182
|
+
const store = new LocalCopyStore(Database, directory);
|
|
183
|
+
const head = await fetchSyncHead(options.api, options.workspaceId);
|
|
184
|
+
if (!head) {
|
|
185
|
+
// Not a member any more, or the key is pinned to another workspace: the copy goes too.
|
|
186
|
+
await store.call("forget", { workspaceId: options.workspaceId });
|
|
187
|
+
throw new NotFoundError("This workspace is not readable with your key.", "Run `cnotes workspace list` to see the workspaces your key reaches.");
|
|
188
|
+
}
|
|
189
|
+
let status = IDLE_STATUS;
|
|
190
|
+
const sync = new WorkspaceSync(restSyncSource(options.api, options.workspaceId), store, options.workspaceId, (s) => {
|
|
191
|
+
status = s;
|
|
192
|
+
options.onStatus?.(s);
|
|
193
|
+
}, { reconcileEvery: RECONCILE_EVERY_MS });
|
|
194
|
+
await (options.rebuild ? sync.rebuild(head) : sync.onHead(head));
|
|
195
|
+
if (status.phase === "error") {
|
|
196
|
+
store.close();
|
|
197
|
+
throw new CliError(`The local copy could not be synced: ${status.error ?? "unknown error"}`);
|
|
198
|
+
}
|
|
199
|
+
return { store, head, status };
|
|
200
|
+
}
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
function deleteNote(db, id) {
|
|
2
|
+
db.run("DELETE FROM notes WHERE id = ?", [id]);
|
|
3
|
+
db.run("DELETE FROM note_tags WHERE note_id = ?", [id]);
|
|
4
|
+
db.run("DELETE FROM answers WHERE note_id = ?", [id]);
|
|
5
|
+
}
|
|
6
|
+
/** Upsert notes and drop removals. Returns the newest `updatedAt` seen. */
|
|
7
|
+
export function applyNotes(db, rows) {
|
|
8
|
+
let upserted = 0;
|
|
9
|
+
let removed = 0;
|
|
10
|
+
let newest = 0;
|
|
11
|
+
db.transaction(() => {
|
|
12
|
+
for (const row of rows) {
|
|
13
|
+
newest = Math.max(newest, row.updatedAt ?? 0);
|
|
14
|
+
if (row.removed) {
|
|
15
|
+
deleteNote(db, row.id);
|
|
16
|
+
removed++;
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
db.run(`INSERT INTO notes (id, display_id, title, type, created_by, source, created_at, updated_at)
|
|
20
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
21
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
22
|
+
display_id = excluded.display_id, title = excluded.title, type = excluded.type,
|
|
23
|
+
created_by = excluded.created_by, source = excluded.source,
|
|
24
|
+
created_at = excluded.created_at, updated_at = excluded.updated_at`, [row.id, row.displayId, row.title, row.type, row.createdBy, row.createdBySource, row.createdAt, row.updatedAt]);
|
|
25
|
+
db.run("DELETE FROM note_tags WHERE note_id = ?", [row.id]);
|
|
26
|
+
for (const tag of new Set(row.tags))
|
|
27
|
+
db.run("INSERT INTO note_tags (note_id, tag) VALUES (?, ?)", [row.id, tag]);
|
|
28
|
+
upserted++;
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
return { upserted, removed, newest };
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Members, dimensions and boards from the sync head. Boards no longer in the
|
|
35
|
+
* head lose their placements. Returns the boards whose placements must be
|
|
36
|
+
* read again (new ones, and ones whose `changedAt` or note count moved since
|
|
37
|
+
* their placements were read) and the dimensions whose newest answer moved
|
|
38
|
+
* since their answers were read.
|
|
39
|
+
*/
|
|
40
|
+
export function applyHead(db, head) {
|
|
41
|
+
const canvasesToRefresh = [];
|
|
42
|
+
const dimensionsToRefresh = [];
|
|
43
|
+
db.transaction(() => {
|
|
44
|
+
db.run("DELETE FROM members");
|
|
45
|
+
for (const m of head.members)
|
|
46
|
+
db.run("INSERT INTO members (user_id, name) VALUES (?, ?)", [m.userId, m.name]);
|
|
47
|
+
// `answers_at` is when each dimension's answers were last read; it survives
|
|
48
|
+
// the replace so the next pass knows whether a judgment landed since.
|
|
49
|
+
const answersAt = new Map(db.all("SELECT type, key, answers_at FROM dimensions").map((d) => [
|
|
50
|
+
`${d.type}\u0000${d.key}`,
|
|
51
|
+
d.answers_at,
|
|
52
|
+
]));
|
|
53
|
+
db.run("DELETE FROM dimensions");
|
|
54
|
+
for (const d of head.dimensions) {
|
|
55
|
+
const prior = answersAt.get(`${d.type}\u0000${d.key}`) ?? null;
|
|
56
|
+
db.run("INSERT OR REPLACE INTO dimensions (type, key, label, kind, options, supertag_id, answers_at) VALUES (?, ?, ?, ?, ?, ?, ?)", [d.type, d.key, d.label, d.kind, JSON.stringify(d.options), d.supertagId, prior]);
|
|
57
|
+
if (prior !== d.newestAnswerAt)
|
|
58
|
+
dimensionsToRefresh.push({ type: d.type, key: d.key });
|
|
59
|
+
}
|
|
60
|
+
// Answers to a dimension that was removed from its type go with it.
|
|
61
|
+
db.run("DELETE FROM answers WHERE NOT EXISTS (SELECT 1 FROM dimensions d WHERE d.type = answers.type AND d.key = answers.key)");
|
|
62
|
+
const known = new Map(db
|
|
63
|
+
.all("SELECT id, placements_changed_at, placements_note_count FROM canvases")
|
|
64
|
+
.map((c) => [c.id, c]));
|
|
65
|
+
const live = new Set();
|
|
66
|
+
for (const c of head.canvases) {
|
|
67
|
+
live.add(c.id);
|
|
68
|
+
db.run(`INSERT INTO canvases (id, display_id, name, updated_at, note_count, is_default, branch_of)
|
|
69
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
70
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
71
|
+
display_id = excluded.display_id, name = excluded.name, updated_at = excluded.updated_at,
|
|
72
|
+
note_count = excluded.note_count, is_default = excluded.is_default, branch_of = excluded.branch_of`, [c.id, c.displayId, c.name, c.updatedAt, c.noteCount, c.isDefault ? 1 : 0, c.branchOf]);
|
|
73
|
+
const prior = known.get(c.id);
|
|
74
|
+
if (!prior || prior.placements_changed_at !== c.changedAt || prior.placements_note_count !== c.noteCount) {
|
|
75
|
+
canvasesToRefresh.push(c.id);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
for (const id of known.keys()) {
|
|
79
|
+
if (live.has(id))
|
|
80
|
+
continue;
|
|
81
|
+
db.run("DELETE FROM canvases WHERE id = ?", [id]);
|
|
82
|
+
db.run("DELETE FROM placements WHERE canvas_id = ?", [id]);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
return { canvasesToRefresh, dimensionsToRefresh };
|
|
86
|
+
}
|
|
87
|
+
/** Replace each board's placements, and remember the board fields they were read at. */
|
|
88
|
+
export function applyPlacements(db, rows) {
|
|
89
|
+
db.transaction(() => {
|
|
90
|
+
for (const row of rows) {
|
|
91
|
+
db.run("DELETE FROM placements WHERE canvas_id = ?", [row.canvasId]);
|
|
92
|
+
if (row.removed) {
|
|
93
|
+
db.run("DELETE FROM canvases WHERE id = ?", [row.canvasId]);
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
for (const noteId of row.cards) {
|
|
97
|
+
db.run("INSERT OR IGNORE INTO placements (canvas_id, note_id, via) VALUES (?, ?, 'card')", [row.canvasId, noteId]);
|
|
98
|
+
}
|
|
99
|
+
for (const noteId of row.listItems) {
|
|
100
|
+
db.run("INSERT OR IGNORE INTO placements (canvas_id, note_id, via) VALUES (?, ?, 'list')", [row.canvasId, noteId]);
|
|
101
|
+
}
|
|
102
|
+
db.run("UPDATE canvases SET placements_changed_at = ?, placements_note_count = ? WHERE id = ?", [
|
|
103
|
+
row.changedAt,
|
|
104
|
+
row.noteCount,
|
|
105
|
+
row.canvasId,
|
|
106
|
+
]);
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* One page of a dimension's answers. The first page of a pass clears that
|
|
112
|
+
* dimension, so answers the server no longer holds disappear. A note can hold
|
|
113
|
+
* several stored answers; the newest judgment wins. `answersAt` is the head's
|
|
114
|
+
* `newestAnswerAt` these pages were read for; the next head compares it.
|
|
115
|
+
*/
|
|
116
|
+
export function applyAnswers(db, type, key, rows, firstPage, answersAt) {
|
|
117
|
+
db.transaction(() => {
|
|
118
|
+
if (firstPage)
|
|
119
|
+
db.run("DELETE FROM answers WHERE type = ? AND key = ?", [type, key]);
|
|
120
|
+
db.run("UPDATE dimensions SET answers_at = ? WHERE type = ? AND key = ?", [answersAt, type, key]);
|
|
121
|
+
for (const row of rows) {
|
|
122
|
+
db.run(`INSERT INTO answers (note_id, type, key, state, value, judged_at) VALUES (?, ?, ?, ?, ?, ?)
|
|
123
|
+
ON CONFLICT (note_id, type, key) DO UPDATE SET
|
|
124
|
+
state = excluded.state, value = excluded.value, judged_at = excluded.judged_at
|
|
125
|
+
WHERE excluded.judged_at >= answers.judged_at`, [row.noteId, type, key, row.state, row.value, row.judgedAt]);
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Compare every note id the server holds with the copy. Local notes the server
|
|
131
|
+
* no longer lists, or now lists as removed, are deleted; ids that are missing
|
|
132
|
+
* locally or carry a different `updatedAt` are returned for fetching.
|
|
133
|
+
*/
|
|
134
|
+
export function reconcileNotes(db, server) {
|
|
135
|
+
const local = new Map(db.all("SELECT id, updated_at FROM notes").map((n) => [n.id, n.updated_at]));
|
|
136
|
+
const toFetch = [];
|
|
137
|
+
const keep = new Set();
|
|
138
|
+
for (const row of server) {
|
|
139
|
+
if (row.removed)
|
|
140
|
+
continue;
|
|
141
|
+
keep.add(row.id);
|
|
142
|
+
if (!local.has(row.id) || local.get(row.id) !== row.updatedAt)
|
|
143
|
+
toFetch.push(row.id);
|
|
144
|
+
}
|
|
145
|
+
let deleted = 0;
|
|
146
|
+
db.transaction(() => {
|
|
147
|
+
for (const id of local.keys()) {
|
|
148
|
+
if (keep.has(id))
|
|
149
|
+
continue;
|
|
150
|
+
deleteNote(db, id);
|
|
151
|
+
deleted++;
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
return { deleted, toFetch };
|
|
155
|
+
}
|
|
156
|
+
export function getMeta(db, key) {
|
|
157
|
+
const row = db.all("SELECT value FROM meta WHERE key = ?", [key])[0];
|
|
158
|
+
return row ? row.value : null;
|
|
159
|
+
}
|
|
160
|
+
export function setMeta(db, key, value) {
|
|
161
|
+
db.run("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", [key, value]);
|
|
162
|
+
}
|
|
163
|
+
export function countRows(db) {
|
|
164
|
+
const count = (table) => Number(db.all(`SELECT COUNT(*) AS n FROM ${table}`)[0]?.n ?? 0);
|
|
165
|
+
return { notes: count("notes"), canvases: count("canvases"), placements: count("placements"), answers: count("answers") };
|
|
166
|
+
}
|