@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.
@@ -0,0 +1,102 @@
1
+ // GENERATED from lib/local-db in the repository root: do not edit here.
2
+ // Change the source and run `npm --prefix cli run sync:local-db`.
3
+ /**
4
+ * The local workspace database's operations over an open SQLite handle: what
5
+ * the sync loop writes (head, notes, placements, answers, reconcile) and what
6
+ * the panel and the CLI ask (filtered query, facets, a read-only SELECT).
7
+ *
8
+ * Storage-neutral: the browser worker (workers/localDb.worker.ts) runs these
9
+ * on a SQLite-wasm file in the origin private file system, the `cnotes` CLI
10
+ * on `node:sqlite` under its config directory. Opening, forgetting and wiping
11
+ * files stay with the storage, so they are not here.
12
+ */
13
+ import { applyAnswers, applyHead, applyNotes, applyPlacements, countRows, getMeta, reconcileNotes, setMeta } from "./apply.js";
14
+ import { buildCountQuery, buildFacetQuery, buildGroupCountsQuery, buildResultsQuery, checkReadOnlySql } from "./query.js";
15
+ import { ensureSchema } from "./schema.js";
16
+ export const NEWEST_KEY = "newest_note_updated_at";
17
+ export const RECONCILED_KEY = "last_reconciled_at";
18
+ const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
19
+ /** Bytes the database takes, from its page count and size (works for a file and for memory). */
20
+ export function fileBytes(db) {
21
+ const pages = Number(db.all("PRAGMA page_count")[0]?.page_count ?? 0);
22
+ const size = Number(db.all("PRAGMA page_size")[0]?.page_size ?? 0);
23
+ return pages * size;
24
+ }
25
+ /** Prepare a freshly opened handle: tables present, and what the copy already holds. */
26
+ export function openCopy(db, persistent) {
27
+ const fresh = ensureSchema(db);
28
+ return {
29
+ counts: countRows(db),
30
+ persistent,
31
+ fresh,
32
+ newestNoteUpdatedAt: Number(getMeta(db, NEWEST_KEY) ?? 0),
33
+ reconciledAt: Number(getMeta(db, RECONCILED_KEY) ?? 0),
34
+ };
35
+ }
36
+ /**
37
+ * Run one SELECT (or WITH ... SELECT) and return rows as arrays. The caller
38
+ * wraps it in `PRAGMA query_only` where the handle supports it; the text check
39
+ * here is for a readable error, not the guarantee.
40
+ */
41
+ export function runReadOnlySql(db, sql, maxRows) {
42
+ const checked = checkReadOnlySql(sql);
43
+ if (!checked.ok)
44
+ throw new Error(checked.reason);
45
+ const start = now();
46
+ const wrapped = `SELECT * FROM (${checked.sql}) LIMIT ${maxRows + 1}`;
47
+ let columns;
48
+ let rows;
49
+ if (db.rows) {
50
+ ({ columns, rows } = db.rows(wrapped));
51
+ }
52
+ else {
53
+ const objects = db.all(wrapped);
54
+ columns = Object.keys(objects[0] ?? {});
55
+ rows = objects.map((o) => columns.map((c) => o[c] ?? null));
56
+ }
57
+ return { columns, rows: rows.slice(0, maxRows), truncated: rows.length > maxRows, ms: now() - start };
58
+ }
59
+ export function createLocalDbOps(db) {
60
+ return {
61
+ applyHead: (head) => applyHead(db, head),
62
+ applyNotes: (rows) => applyNotes(db, rows),
63
+ applyPlacements: (rows) => {
64
+ applyPlacements(db, rows);
65
+ return null;
66
+ },
67
+ applyAnswers: ({ type, key, rows, firstPage, answersAt }) => {
68
+ applyAnswers(db, type, key, rows, firstPage, answersAt);
69
+ return null;
70
+ },
71
+ reconcile: (rows) => reconcileNotes(db, rows),
72
+ setNewest: (newest) => {
73
+ setMeta(db, NEWEST_KEY, String(newest));
74
+ return null;
75
+ },
76
+ markReconciled: (at) => {
77
+ setMeta(db, RECONCILED_KEY, String(at));
78
+ return null;
79
+ },
80
+ counts: () => ({ ...countRows(db), bytes: fileBytes(db) }),
81
+ query: ({ filter, groupBy, limit }) => {
82
+ const start = now();
83
+ const results = buildResultsQuery(filter, groupBy, limit);
84
+ const rows = db.all(results.sql, results.params);
85
+ const count = buildCountQuery(filter);
86
+ const total = Number(db.all(count.sql, count.params)[0]?.count ?? 0);
87
+ const groupsQuery = buildGroupCountsQuery(filter, groupBy);
88
+ const groups = groupBy === "none" ? [] : db.all(groupsQuery.sql, groupsQuery.params);
89
+ return { rows, total, groups, ms: now() - start };
90
+ },
91
+ facets: ({ filter, fields, limit }) => {
92
+ const start = now();
93
+ const facets = {};
94
+ for (const field of fields) {
95
+ const q = buildFacetQuery(filter, field, limit);
96
+ facets[field] = db.all(q.sql, q.params);
97
+ }
98
+ return { facets, ms: now() - start };
99
+ },
100
+ sql: ({ sql, maxRows }) => runReadOnlySql(db, sql, maxRows),
101
+ };
102
+ }
@@ -0,0 +1,10 @@
1
+ /** Where the SAH pool keeps its files in the origin private file system. */
2
+ export const LOCAL_DB_DIRECTORY = "/cn-local-db";
3
+ export const LOCAL_DB_VFS = "cn-local-db";
4
+ /** One file per member and workspace, so one person's copy never opens for another. */
5
+ export function localDbFileName(userId, workspaceId) {
6
+ return `${workspaceFilePrefix(workspaceId)}${userId}.sqlite3`;
7
+ }
8
+ export function workspaceFilePrefix(workspaceId) {
9
+ return `/ws-${workspaceId}-u-`;
10
+ }
@@ -0,0 +1,184 @@
1
+ export const UNJUDGED = "unjudged";
2
+ export const NO_CANVAS = "Not on a canvas";
3
+ export const NO_TAG = "No tag";
4
+ const placeholders = (n) => Array.from({ length: n }, () => "?").join(", ");
5
+ function escapeLike(word) {
6
+ return word.replace(/[\\%_]/g, (c) => `\\${c}`);
7
+ }
8
+ export function buildWhere(filter) {
9
+ const clauses = [];
10
+ const params = [];
11
+ const words = (filter.text ?? "").trim().split(/\s+/).filter(Boolean);
12
+ for (const word of words) {
13
+ clauses.push(`(n.title LIKE ? ESCAPE '\\' OR n.display_id LIKE ? ESCAPE '\\')`);
14
+ const pattern = `%${escapeLike(word)}%`;
15
+ params.push(pattern, pattern);
16
+ }
17
+ if (filter.types?.length) {
18
+ clauses.push(`n.type IN (${placeholders(filter.types.length)})`);
19
+ params.push(...filter.types);
20
+ }
21
+ if (filter.sources?.length) {
22
+ clauses.push(`n.source IN (${placeholders(filter.sources.length)})`);
23
+ params.push(...filter.sources);
24
+ }
25
+ if (filter.authors?.length) {
26
+ clauses.push(`n.created_by IN (${placeholders(filter.authors.length)})`);
27
+ params.push(...filter.authors);
28
+ }
29
+ if (filter.canvasIds?.length) {
30
+ clauses.push(`EXISTS (SELECT 1 FROM placements p WHERE p.note_id = n.id AND p.canvas_id IN (${placeholders(filter.canvasIds.length)}))`);
31
+ params.push(...filter.canvasIds);
32
+ }
33
+ if (filter.tags?.length) {
34
+ clauses.push(`EXISTS (SELECT 1 FROM note_tags t WHERE t.note_id = n.id AND t.tag IN (${placeholders(filter.tags.length)}))`);
35
+ params.push(...filter.tags);
36
+ }
37
+ if (filter.createdFrom != null) {
38
+ clauses.push("n.created_at >= ?");
39
+ params.push(filter.createdFrom);
40
+ }
41
+ if (filter.createdTo != null) {
42
+ clauses.push("n.created_at <= ?");
43
+ params.push(filter.createdTo);
44
+ }
45
+ for (const dim of filter.dimensions ?? []) {
46
+ if (dim.states.length === 0)
47
+ continue;
48
+ const judged = dim.states.filter((s) => s !== UNJUDGED);
49
+ const parts = [];
50
+ // A dimension belongs to one type, so filtering on it keeps that type only.
51
+ const scope = "n.type = ?";
52
+ if (judged.length) {
53
+ parts.push(`EXISTS (SELECT 1 FROM answers a WHERE a.note_id = n.id AND a.type = n.type AND a.key = ? AND a.state IN (${placeholders(judged.length)}))`);
54
+ }
55
+ if (judged.length !== dim.states.length) {
56
+ parts.push(`NOT EXISTS (SELECT 1 FROM answers a WHERE a.note_id = n.id AND a.type = n.type AND a.key = ?)`);
57
+ }
58
+ clauses.push(`(${scope} AND (${parts.join(" OR ")}))`);
59
+ params.push(dim.type);
60
+ if (judged.length)
61
+ params.push(dim.key, ...judged);
62
+ if (judged.length !== dim.states.length)
63
+ params.push(dim.key);
64
+ }
65
+ return { sql: clauses.length ? `WHERE ${clauses.join(" AND ")}` : "", params };
66
+ }
67
+ /** The join and the key/label expressions for one grouping. */
68
+ function grouping(groupBy) {
69
+ switch (groupBy) {
70
+ case "type":
71
+ return { join: "", key: "n.type", label: "n.type", params: [] };
72
+ case "canvas":
73
+ return {
74
+ join: "LEFT JOIN placements p ON p.note_id = n.id LEFT JOIN canvases c ON c.id = p.canvas_id",
75
+ key: "COALESCE(c.id, '')",
76
+ label: `COALESCE(c.name, '${NO_CANVAS}')`,
77
+ params: [],
78
+ };
79
+ case "tag":
80
+ return {
81
+ join: "LEFT JOIN note_tags t ON t.note_id = n.id",
82
+ key: "COALESCE(t.tag, '')",
83
+ label: `COALESCE(t.tag, '${NO_TAG}')`,
84
+ params: [],
85
+ };
86
+ case "month":
87
+ return {
88
+ join: "",
89
+ key: "COALESCE(strftime('%Y-%m', n.created_at / 1000, 'unixepoch'), '')",
90
+ label: "COALESCE(strftime('%Y-%m', n.created_at / 1000, 'unixepoch'), 'No date')",
91
+ params: [],
92
+ };
93
+ case "source":
94
+ return { join: "", key: "COALESCE(n.source, '')", label: "COALESCE(n.source, 'unknown')", params: [] };
95
+ case "author":
96
+ return {
97
+ join: "LEFT JOIN members m ON m.user_id = n.created_by",
98
+ key: "COALESCE(n.created_by, '')",
99
+ label: "COALESCE(m.name, 'Unnamed member')",
100
+ params: [],
101
+ };
102
+ case "none":
103
+ return { join: "", key: "''", label: "''", params: [] };
104
+ default: {
105
+ const [, type, key] = groupBy.split(":");
106
+ return {
107
+ join: "LEFT JOIN answers a ON a.note_id = n.id AND a.type = n.type AND a.type = ? AND a.key = ?",
108
+ key: `COALESCE(a.state, '${UNJUDGED}')`,
109
+ label: `COALESCE(a.state, '${UNJUDGED}')`,
110
+ params: [type ?? "", key ?? ""],
111
+ };
112
+ }
113
+ }
114
+ }
115
+ /**
116
+ * Matching notes with the group each falls in. Groups come largest first (the
117
+ * order the facet chips use, so the list opens on the group the chips say
118
+ * dominates), months newest first, and inside a group the most recently
119
+ * written note leads. A note on two canvases (or with two tags) appears once
120
+ * per group when grouped by that field, and once in a group however many
121
+ * times it is placed there (DISTINCT: a card and a list item on one canvas
122
+ * join as two rows). Groups that share a label (two canvases both called
123
+ * "Untitled") still come out contiguous: the key breaks the tie, and the
124
+ * panel folds rows into groups by consecutive key.
125
+ */
126
+ export function buildResultsQuery(filter, groupBy, limit) {
127
+ const where = buildWhere(filter);
128
+ const g = grouping(groupBy);
129
+ const order = groupBy === "month" ? "group_label DESC" : "sizes.group_size DESC, group_label COLLATE NOCASE";
130
+ const sql = `WITH matched AS (
131
+ SELECT DISTINCT n.id, n.display_id, n.title, n.type, n.updated_at, ${g.key} AS group_key, ${g.label} AS group_label
132
+ FROM notes n ${g.join} ${where.sql}
133
+ ), sizes AS (SELECT group_key, COUNT(*) AS group_size FROM matched GROUP BY group_key)
134
+ SELECT matched.* FROM matched JOIN sizes USING (group_key)
135
+ ORDER BY ${order}, group_key, matched.updated_at DESC
136
+ LIMIT ?`;
137
+ return { sql, params: [...g.params, ...where.params, limit] };
138
+ }
139
+ /** How many notes match, each counted once. */
140
+ export function buildCountQuery(filter) {
141
+ const where = buildWhere(filter);
142
+ return { sql: `SELECT COUNT(*) AS count FROM notes n ${where.sql}`, params: where.params };
143
+ }
144
+ /** Group sizes, each note counted once per group. */
145
+ export function buildGroupCountsQuery(filter, groupBy) {
146
+ const where = buildWhere(filter);
147
+ const g = grouping(groupBy);
148
+ return {
149
+ sql: `SELECT ${g.key} AS value, ${g.label} AS label, COUNT(DISTINCT n.id) AS count
150
+ FROM notes n ${g.join} ${where.sql}
151
+ GROUP BY value, label ORDER BY label COLLATE NOCASE`,
152
+ params: [...g.params, ...where.params],
153
+ };
154
+ }
155
+ const FACET_GROUP = {
156
+ types: "type",
157
+ canvasIds: "canvas",
158
+ tags: "tag",
159
+ sources: "source",
160
+ };
161
+ /** Counts for one facet's chips, leaving that facet's own filter out. Largest first. */
162
+ export function buildFacetQuery(filter, field, limit) {
163
+ const rest = { ...filter, [field]: undefined };
164
+ const counts = buildGroupCountsQuery(rest, FACET_GROUP[field]);
165
+ return {
166
+ sql: `SELECT * FROM (${counts.sql}) WHERE value != '' ORDER BY count DESC, label COLLATE NOCASE LIMIT ?`,
167
+ params: [...counts.params, limit],
168
+ };
169
+ }
170
+ /**
171
+ * The SQL box runs one SELECT (or WITH ... SELECT) statement. The worker also
172
+ * runs it with `PRAGMA query_only` on, so this check is for a readable error,
173
+ * not the guarantee.
174
+ */
175
+ export function checkReadOnlySql(sql) {
176
+ const trimmed = sql.trim().replace(/;\s*$/, "");
177
+ if (!trimmed)
178
+ return { ok: false, reason: "Type a SELECT statement." };
179
+ if (!/^(select|with)\b/i.test(trimmed))
180
+ return { ok: false, reason: "Only SELECT statements run here." };
181
+ if (/;/.test(trimmed.replace(/'(?:[^']|'')*'/g, "''")))
182
+ return { ok: false, reason: "Run one statement at a time." };
183
+ return { ok: true, sql: trimmed };
184
+ }
@@ -0,0 +1,83 @@
1
+ export const SCHEMA_VERSION = 2;
2
+ const TABLES = ["notes", "note_tags", "canvases", "placements", "members", "dimensions", "answers", "meta"];
3
+ const CREATE = [
4
+ `CREATE TABLE notes (
5
+ id TEXT PRIMARY KEY,
6
+ display_id TEXT NOT NULL,
7
+ title TEXT,
8
+ type TEXT NOT NULL,
9
+ created_by TEXT,
10
+ source TEXT,
11
+ created_at INTEGER,
12
+ updated_at INTEGER
13
+ )`,
14
+ `CREATE TABLE note_tags (note_id TEXT NOT NULL, tag TEXT NOT NULL, PRIMARY KEY (note_id, tag)) WITHOUT ROWID`,
15
+ `CREATE TABLE canvases (
16
+ id TEXT PRIMARY KEY,
17
+ display_id TEXT,
18
+ name TEXT NOT NULL,
19
+ updated_at INTEGER,
20
+ note_count INTEGER,
21
+ is_default INTEGER NOT NULL DEFAULT 0,
22
+ branch_of TEXT,
23
+ placements_changed_at INTEGER,
24
+ placements_note_count INTEGER
25
+ )`,
26
+ `CREATE TABLE placements (
27
+ canvas_id TEXT NOT NULL,
28
+ note_id TEXT NOT NULL,
29
+ via TEXT NOT NULL,
30
+ PRIMARY KEY (canvas_id, note_id, via)
31
+ ) WITHOUT ROWID`,
32
+ `CREATE TABLE members (user_id TEXT PRIMARY KEY, name TEXT)`,
33
+ `CREATE TABLE dimensions (
34
+ type TEXT NOT NULL,
35
+ key TEXT NOT NULL,
36
+ label TEXT,
37
+ kind TEXT,
38
+ options TEXT,
39
+ supertag_id TEXT,
40
+ answers_at INTEGER,
41
+ PRIMARY KEY (type, key)
42
+ )`,
43
+ `CREATE TABLE answers (
44
+ note_id TEXT NOT NULL,
45
+ type TEXT NOT NULL,
46
+ key TEXT NOT NULL,
47
+ state TEXT NOT NULL,
48
+ value REAL,
49
+ judged_at INTEGER,
50
+ PRIMARY KEY (note_id, type, key)
51
+ ) WITHOUT ROWID`,
52
+ `CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)`,
53
+ `CREATE INDEX notes_by_type ON notes (type)`,
54
+ `CREATE INDEX notes_by_updated ON notes (updated_at)`,
55
+ `CREATE INDEX notes_by_created ON notes (created_at)`,
56
+ `CREATE INDEX placements_by_note ON placements (note_id)`,
57
+ `CREATE INDEX tags_by_tag ON note_tags (tag)`,
58
+ `CREATE INDEX answers_by_key ON answers (type, key, state)`,
59
+ ];
60
+ /** Create the tables, or drop and recreate them when the schema moved. Returns true when it (re)created. */
61
+ export function ensureSchema(db) {
62
+ const version = Number(db.all("PRAGMA user_version")[0]?.user_version ?? 0);
63
+ if (version === SCHEMA_VERSION)
64
+ return false;
65
+ db.transaction(() => {
66
+ for (const table of TABLES)
67
+ db.run(`DROP TABLE IF EXISTS ${table}`);
68
+ for (const statement of CREATE)
69
+ db.run(statement);
70
+ db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);
71
+ });
72
+ return true;
73
+ }
74
+ /** What the SQL box shows as the tables a reader can query. */
75
+ export const SCHEMA_HINT = [
76
+ "notes(id, display_id, title, type, created_by, source, created_at, updated_at)",
77
+ "note_tags(note_id, tag)",
78
+ "canvases(id, display_id, name, updated_at, note_count, is_default, branch_of)",
79
+ "placements(canvas_id, note_id, via) -- via: card | list",
80
+ "members(user_id, name)",
81
+ "dimensions(type, key, label, kind, options)",
82
+ "answers(note_id, type, key, state, value, judged_at)",
83
+ ];
@@ -0,0 +1,270 @@
1
+ // GENERATED from lib/local-db in the repository root: do not edit here.
2
+ // Change the source and run `npm --prefix cli run sync:local-db`.
3
+ /**
4
+ * Keeps the local workspace database in step with the server (PLAN-6KP3
5
+ * step 4).
6
+ *
7
+ * The caller hands every head it receives to `onHead`: the page from its
8
+ * `localDb.syncHead` subscription, the CLI from one `POST /api/local-db`
9
+ * read. The first head of a session opens the member's file and reconciles
10
+ * every note id (which also fills an empty copy); later heads pull only
11
+ * notes written since the newest one the copy holds. Canvases whose
12
+ * `changedAt` or note count moved have their placements read again, and a
13
+ * judged dimension's answers are read again when notes of its type changed
14
+ * or a judgment landed since they were read.
15
+ *
16
+ * Heads that arrive while a pass runs are coalesced: the latest one runs next.
17
+ *
18
+ * The database holds ONE open file. A disposed sync (the page moved to
19
+ * another workspace) must never write again, or its rows land in whichever
20
+ * file the next sync opened: every database call goes through `call`, which
21
+ * refuses once disposed.
22
+ *
23
+ * Runtime-neutral: nothing here touches the DOM, Convex or Node. The `cnotes`
24
+ * CLI runs a copy of this file (cli/src/local-db/, kept in step by
25
+ * `npm --prefix cli run sync:local-db`).
26
+ */
27
+ import { localDbFileName } from "./protocol.js";
28
+ export const IDLE_STATUS = {
29
+ phase: "idle",
30
+ persistent: false,
31
+ counts: { notes: 0, canvases: 0, placements: 0, answers: 0, bytes: 0 },
32
+ copied: 0,
33
+ syncedAt: null,
34
+ lastPassMs: null,
35
+ firstPassMs: null,
36
+ error: null,
37
+ };
38
+ /** Thrown by a pass whose sync was disposed mid-flight; never reaches the status. */
39
+ export class SyncDisposedError extends Error {
40
+ constructor() {
41
+ super("The sync was disposed.");
42
+ this.name = "SyncDisposedError";
43
+ }
44
+ }
45
+ const ID_PAGE = 1000;
46
+ const CHANGED_PAGE = 200;
47
+ const FETCH_CHUNK = 200;
48
+ /**
49
+ * Canvases per `placements` call. A canvas can hold thousands of cards, list
50
+ * nodes and list items, and one Convex query reads at most 16,384 documents,
51
+ * so a small batch keeps a workspace of large canvases syncable.
52
+ */
53
+ const PLACEMENT_CHUNK = 5;
54
+ const ANSWER_PAGE = 500;
55
+ /** Parallel note fetches during a reconcile. */
56
+ const FETCH_PARALLEL = 4;
57
+ const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
58
+ const chunks = (items, size) => {
59
+ const out = [];
60
+ for (let i = 0; i < items.length; i += size)
61
+ out.push(items.slice(i, i + size));
62
+ return out;
63
+ };
64
+ const dimensionKey = (d) => `${d.type}\u0000${d.key}`;
65
+ export class WorkspaceSync {
66
+ source;
67
+ db;
68
+ workspaceId;
69
+ onStatus;
70
+ options;
71
+ opened = false;
72
+ /** False until a pass has compared every note id this session. */
73
+ reconciled = false;
74
+ forgetOnOpen = false;
75
+ newest = 0;
76
+ running = false;
77
+ nextHead = null;
78
+ disposed = false;
79
+ status = IDLE_STATUS;
80
+ constructor(source, db, workspaceId, onStatus, options = {}) {
81
+ this.source = source;
82
+ this.db = db;
83
+ this.workspaceId = workspaceId;
84
+ this.onStatus = onStatus;
85
+ this.options = options;
86
+ }
87
+ dispose() {
88
+ this.disposed = true;
89
+ }
90
+ /** Throw away this workspace's copy and sync it again from scratch. */
91
+ rebuild(head) {
92
+ this.opened = false;
93
+ this.reconciled = false;
94
+ this.forgetOnOpen = true;
95
+ return this.onHead(head);
96
+ }
97
+ onHead(head) {
98
+ this.nextHead = head;
99
+ if (this.running)
100
+ return Promise.resolve();
101
+ return this.drain();
102
+ }
103
+ async drain() {
104
+ this.running = true;
105
+ try {
106
+ while (this.nextHead && !this.disposed) {
107
+ const head = this.nextHead;
108
+ this.nextHead = null;
109
+ await this.pass(head);
110
+ }
111
+ }
112
+ finally {
113
+ this.running = false;
114
+ }
115
+ }
116
+ emit(patch) {
117
+ if (this.disposed)
118
+ return;
119
+ this.status = { ...this.status, ...patch };
120
+ this.onStatus(this.status);
121
+ }
122
+ /** Every database call: refused once disposed, so no row of this workspace reaches another's file. */
123
+ call(op, args) {
124
+ if (this.disposed)
125
+ return Promise.reject(new SyncDisposedError());
126
+ return this.db.call(op, args);
127
+ }
128
+ async open(head) {
129
+ this.emit({ phase: "opening", error: null });
130
+ if (this.forgetOnOpen) {
131
+ // A rebuild drops this workspace's files only; other workspaces' copies stay.
132
+ await this.call("forget", { workspaceId: this.workspaceId });
133
+ this.forgetOnOpen = false;
134
+ }
135
+ const opened = await this.call("open", {
136
+ fileName: localDbFileName(head.userId, this.workspaceId),
137
+ wipeFirst: this.options.wipePending?.() ?? false,
138
+ });
139
+ this.options.clearWipePending?.();
140
+ this.opened = true;
141
+ this.newest = opened.fresh ? 0 : opened.newestNoteUpdatedAt;
142
+ const every = this.options.reconcileEvery;
143
+ if (every !== undefined && !opened.fresh && Date.now() - opened.reconciledAt < every)
144
+ this.reconciled = true;
145
+ this.emit({ persistent: opened.persistent });
146
+ }
147
+ async pass(head) {
148
+ const start = now();
149
+ try {
150
+ if (!this.opened)
151
+ await this.open(head);
152
+ this.emit({ phase: "syncing", copied: 0 });
153
+ const full = !this.reconciled;
154
+ const { canvasesToRefresh, dimensionsToRefresh } = await this.call("applyHead", head);
155
+ const changedTypes = full ? await this.reconcile() : await this.pullChanged(head);
156
+ this.reconciled = true;
157
+ await this.pullPlacements(canvasesToRefresh);
158
+ await this.pullAnswers(head, full ? null : changedTypes, dimensionsToRefresh);
159
+ await this.call("setNewest", this.newest);
160
+ const counts = await this.call("counts", null);
161
+ const ms = now() - start;
162
+ this.emit({
163
+ phase: "ready",
164
+ counts,
165
+ syncedAt: Date.now(),
166
+ lastPassMs: ms,
167
+ firstPassMs: this.status.firstPassMs ?? ms,
168
+ error: null,
169
+ });
170
+ }
171
+ catch (err) {
172
+ if (err instanceof SyncDisposedError)
173
+ return;
174
+ this.emit({ phase: "error", error: err instanceof Error ? err.message : String(err) });
175
+ }
176
+ }
177
+ track(rows, types) {
178
+ let copied = this.status.copied;
179
+ for (const row of rows) {
180
+ this.newest = Math.max(this.newest, row.updatedAt ?? 0);
181
+ if (!row.removed) {
182
+ types.add(row.type);
183
+ copied += 1;
184
+ }
185
+ }
186
+ if (copied !== this.status.copied)
187
+ this.emit({ copied });
188
+ }
189
+ /** Every note id against the copy: drops what the server no longer holds, fetches what changed. */
190
+ async reconcile() {
191
+ const ids = [];
192
+ let cursor = null;
193
+ for (;;) {
194
+ const page = await this.source.noteIds(cursor, ID_PAGE);
195
+ ids.push(...page.page);
196
+ if (page.isDone)
197
+ break;
198
+ cursor = page.continueCursor;
199
+ }
200
+ for (const row of ids)
201
+ this.newest = Math.max(this.newest, row.updatedAt ?? 0);
202
+ const { toFetch } = await this.call("reconcile", ids);
203
+ await this.call("markReconciled", Date.now());
204
+ const types = new Set();
205
+ const batches = chunks(toFetch, FETCH_CHUNK);
206
+ for (const group of chunks(batches, FETCH_PARALLEL)) {
207
+ const results = await Promise.all(group.map((batch) => this.source.notesByIds(batch)));
208
+ for (const rows of results) {
209
+ this.track(rows, types);
210
+ await this.call("applyNotes", rows);
211
+ }
212
+ }
213
+ return types;
214
+ }
215
+ /**
216
+ * Notes written since the newest one the copy holds. The mark is inclusive
217
+ * (`gte` on the server): a note committed with the same millisecond
218
+ * `updatedAt` as the one the last pass ended on, after that pass read, must
219
+ * not be skipped. The boundary note is upserted again, which is idempotent.
220
+ */
221
+ async pullChanged(head) {
222
+ const types = new Set();
223
+ if (head.newestNoteUpdatedAt < this.newest)
224
+ return types;
225
+ const since = this.newest;
226
+ let cursor = null;
227
+ for (;;) {
228
+ const page = await this.source.notesChangedSince(since, cursor, CHANGED_PAGE);
229
+ this.track(page.page, types);
230
+ await this.call("applyNotes", page.page);
231
+ if (page.isDone)
232
+ break;
233
+ cursor = page.continueCursor;
234
+ }
235
+ return types;
236
+ }
237
+ async pullPlacements(canvasIds) {
238
+ for (const batch of chunks(canvasIds, PLACEMENT_CHUNK)) {
239
+ const rows = await this.source.placements(batch);
240
+ await this.call("applyPlacements", rows);
241
+ }
242
+ }
243
+ /**
244
+ * Every dimension on the first pass; afterwards, those whose type had notes
245
+ * change and those the head says gained a judgment since they were read.
246
+ */
247
+ async pullAnswers(head, changedTypes, toRefresh) {
248
+ const refresh = new Set(toRefresh.map(dimensionKey));
249
+ for (const dim of head.dimensions) {
250
+ if (changedTypes && !changedTypes.has(dim.type) && !refresh.has(dimensionKey(dim)))
251
+ continue;
252
+ let cursor = null;
253
+ let firstPage = true;
254
+ for (;;) {
255
+ const page = await this.source.dimensionAnswers(dim.supertagId, dim.key, cursor, ANSWER_PAGE);
256
+ await this.call("applyAnswers", {
257
+ type: dim.type,
258
+ key: dim.key,
259
+ rows: page.page,
260
+ firstPage,
261
+ answersAt: dim.newestAnswerAt,
262
+ });
263
+ firstPage = false;
264
+ if (page.isDone)
265
+ break;
266
+ cursor = page.continueCursor;
267
+ }
268
+ }
269
+ }
270
+ }
@@ -0,0 +1,8 @@
1
+ // GENERATED from lib/local-db in the repository root: do not edit here.
2
+ // Change the source and run `npm --prefix cli run sync:local-db`.
3
+ /**
4
+ * Shapes shared by the local workspace database's worker, sync loop and UI
5
+ * (experiment `workspaceQuery`). Server rows mirror convex/localDb.ts with ids
6
+ * as plain strings, so the worker never imports Convex.
7
+ */
8
+ export {};