onenote-cli 0.2.0 → 0.2.1-darwin-arm64

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/src/cache.ts DELETED
@@ -1,1709 +0,0 @@
1
- import prettyBytes from "pretty-bytes";
2
- import { getAccessToken, listAccounts, setCurrentAccount } from "./auth";
3
- import { listNotebooks } from "./graph";
4
- import { readFile, writeFile, mkdir, readdir, stat } from "node:fs/promises";
5
- import { join } from "node:path";
6
- import { Database } from "bun:sqlite";
7
-
8
- import { homedir } from "node:os";
9
- import { dirname } from "node:path";
10
-
11
- // Cache directory: use package root (../.onenote/cache relative to src/) so that
12
- // the cache lives alongside .env.local. Fall back to ~/.onenote-cli/cache if the
13
- // package root is not writable (e.g. installed via npm).
14
- const PKG_ROOT = dirname(import.meta.dir);
15
- const CACHE_DIR = process.env.ONENOTE_CACHE_DIR
16
- || join(PKG_ROOT, ".onenote", "cache");
17
-
18
- interface CachedPage {
19
- title: string;
20
- body: string;
21
- section: string;
22
- notebook: string;
23
- webUrl: string; // OneNote Online URL for this page (section + page GUID)
24
- pageGuid?: string;
25
- account?: string | null; // which signed-in account this page came from
26
- lastModified?: string | null; // ISO 8601 from OneNote (section or page level)
27
- tagLines?: Array<{ tag: string; text: string }>; // text content of tagged elements
28
- }
29
-
30
- interface CacheIndex {
31
- updatedAt: string;
32
- notebooks: {
33
- id: string;
34
- displayName: string;
35
- sections: {
36
- driveItemId: string;
37
- displayName: string;
38
- webUrl: string;
39
- drivePath: string;
40
- cachedAt: string;
41
- }[];
42
- }[];
43
- }
44
-
45
- function getNotebookDrivePath(notebook: any): string | null {
46
- const webUrl = notebook.links?.oneNoteWebUrl?.href;
47
- if (!webUrl) return null;
48
- const match = decodeURIComponent(new URL(webUrl).pathname).match(/Documents\/(.+)/);
49
- return match?.[1] ?? null;
50
- }
51
-
52
- async function graphFetchRaw(path: string): Promise<Response> {
53
- const token = await getAccessToken();
54
- const url = path.startsWith("http")
55
- ? path
56
- : `https://graph.microsoft.com/v1.0${path}`;
57
- // Retry on 429 with bounded backoff. Total max wait: ~3 min before giving up so the
58
- // calling section moves on rather than blocking the whole sync.
59
- for (let attempt = 0; attempt < 3; attempt++) {
60
- const res = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
61
- if (res.status !== 429) return res;
62
- const retryAfter = parseInt(res.headers.get("retry-after") ?? "0", 10);
63
- const delayMs = retryAfter > 0 ? Math.min(retryAfter * 1000, 60000) : Math.min(10000 * 2 ** attempt, 60000);
64
- await new Promise((r) => setTimeout(r, delayMs));
65
- }
66
- return fetch(url, { headers: { Authorization: `Bearer ${token}` } });
67
- }
68
-
69
- function isReadableChar(code: number): boolean {
70
- return (
71
- (code >= 0x20 && code <= 0x7e) || // ASCII printable
72
- code === 0x0a || code === 0x0d || code === 0x09 || // whitespace
73
- (code >= 0xa0 && code <= 0x024f) || // Latin Extended
74
- (code >= 0x0370 && code <= 0x058f) || // Greek, Cyrillic, Armenian
75
- (code >= 0x0600 && code <= 0x06ff) || // Arabic
76
- (code >= 0x0900 && code <= 0x097f) || // Devanagari
77
- (code >= 0x0e00 && code <= 0x0e7f) || // Thai
78
- (code >= 0x1100 && code <= 0x11ff) || // Hangul Jamo
79
- (code >= 0x2000 && code <= 0x206f) || // General Punctuation
80
- (code >= 0x2100 && code <= 0x214f) || // Letterlike Symbols
81
- (code >= 0x2190 && code <= 0x21ff) || // Arrows
82
- (code >= 0x2200 && code <= 0x22ff) || // Mathematical Operators
83
- (code >= 0x2500 && code <= 0x257f) || // Box Drawing
84
- (code >= 0x3000 && code <= 0x303f) || // CJK Symbols and Punctuation
85
- (code >= 0x3040 && code <= 0x309f) || // Hiragana
86
- (code >= 0x30a0 && code <= 0x30ff) || // Katakana
87
- (code >= 0x3100 && code <= 0x312f) || // Bopomofo
88
- (code >= 0x3400 && code <= 0x4dbf) || // CJK Extension A
89
- (code >= 0x4e00 && code <= 0x9fff) || // CJK Unified Ideographs
90
- (code >= 0xac00 && code <= 0xd7af) || // Hangul Syllables
91
- (code >= 0xf900 && code <= 0xfaff) || // CJK Compatibility Ideographs
92
- (code >= 0xfe30 && code <= 0xfe4f) || // CJK Compatibility Forms
93
- (code >= 0xff00 && code <= 0xffef) // Fullwidth Forms
94
- );
95
- }
96
-
97
- function extractTextBlocks(buf: Buffer): { offset: number; text: string }[] {
98
- const blocks: { offset: number; text: string }[] = [];
99
-
100
- // Extract UTF-8 text blocks
101
- const utf8 = buf.toString("utf-8");
102
- let start = -1;
103
- let chars = "";
104
- for (let i = 0; i < utf8.length; i++) {
105
- if (isReadableChar(utf8.charCodeAt(i))) {
106
- if (start < 0) start = i;
107
- chars += utf8[i];
108
- } else {
109
- if (chars.trim().length >= 6) blocks.push({ offset: start, text: chars.trim() });
110
- chars = "";
111
- start = -1;
112
- }
113
- }
114
- if (chars.trim().length >= 6) blocks.push({ offset: start, text: chars.trim() });
115
-
116
- // Extract UTF-16LE text blocks at both even and odd byte alignments
117
- // (OneNote may have UTF-16LE strings starting at either alignment)
118
- for (const startOffset of [0, 1]) {
119
- start = -1;
120
- chars = "";
121
- for (let i = startOffset; i < buf.length - 1; i += 2) {
122
- const code = buf[i] | (buf[i + 1] << 8);
123
- if (isReadableChar(code)) {
124
- if (start < 0) start = i;
125
- chars += String.fromCharCode(code);
126
- } else {
127
- if (chars.trim().length >= 4) blocks.push({ offset: start, text: chars.trim() });
128
- chars = "";
129
- start = -1;
130
- }
131
- }
132
- if (chars.trim().length >= 4) blocks.push({ offset: start, text: chars.trim() });
133
- }
134
-
135
- // Sort by offset
136
- blocks.sort((a, b) => a.offset - b.offset);
137
-
138
- // Filter noise: require blocks to have a reasonable ratio of common characters
139
- return blocks.filter((b) => {
140
- const common = b.text.replace(
141
- /[^a-zA-Z0-9\u3040-\u30ff\u4e00-\u9fff\u3000-\u303f\uff00-\uffef\s.,;:!?@#\-_()[\]{}'"/\\]/g,
142
- ""
143
- );
144
- if (common.length / b.text.length <= 0.6 || b.text.length < 4) return false;
145
-
146
- // Detect misaligned UTF-16LE reading of ASCII: characters where low byte = 0x00
147
- // and code is in the "shifted ASCII" range (0x2000-0x7E00 typically)
148
- let shiftedAsciiCount = 0;
149
- let cjkCount = 0;
150
- for (const ch of b.text) {
151
- const code = ch.charCodeAt(0);
152
- if ((code & 0xff) === 0 && code >= 0x2000 && code <= 0x7f00) {
153
- shiftedAsciiCount++;
154
- }
155
- if (code >= 0x4e00 && code <= 0x9fff) cjkCount++;
156
- }
157
- // If most characters look like shifted-ASCII garbage, reject
158
- if (shiftedAsciiCount > 3 && shiftedAsciiCount / b.text.length > 0.5) return false;
159
- return true;
160
- });
161
- }
162
-
163
- function groupIntoPages(blocks: { offset: number; text: string }[]): { title: string; body: string }[] {
164
- const pages: { title: string; body: string }[] = [];
165
- let group: typeof blocks = [];
166
-
167
- for (const block of blocks) {
168
- if (group.length > 0) {
169
- const prevEnd = group[group.length - 1].offset + group[group.length - 1].text.length * 2;
170
- const gap = block.offset - prevEnd;
171
- if (gap > 500) {
172
- const body = group.map((b) => b.text).join("\n");
173
- if (body.length > 10) {
174
- const lines = body.split("\n").filter((l) => l.trim().length > 0);
175
- pages.push({ title: lines[0]?.slice(0, 200) || "(untitled)", body });
176
- }
177
- group = [];
178
- }
179
- }
180
- group.push(block);
181
- }
182
- if (group.length > 0) {
183
- const body = group.map((b) => b.text).join("\n");
184
- if (body.length > 10) {
185
- const lines = body.split("\n").filter((l) => l.trim().length > 0);
186
- pages.push({ title: lines[0]?.slice(0, 200) || "(untitled)", body });
187
- }
188
- }
189
-
190
- return pages;
191
- }
192
-
193
- function bufToGuid(b: Buffer, off: number): string {
194
- return [
195
- b.readUInt32LE(off).toString(16).padStart(8, "0"),
196
- b.readUInt16LE(off + 4).toString(16).padStart(4, "0"),
197
- b.readUInt16LE(off + 6).toString(16).padStart(4, "0"),
198
- b.slice(off + 8, off + 10).toString("hex"),
199
- b.slice(off + 10, off + 16).toString("hex"),
200
- ].join("-");
201
- }
202
-
203
- function guidToBuf(guid: string): Buffer {
204
- const p = guid.replace(/-/g, "");
205
- const b = Buffer.alloc(16);
206
- b.writeUInt32LE(parseInt(p.slice(0, 8), 16), 0);
207
- b.writeUInt16LE(parseInt(p.slice(8, 12), 16), 4);
208
- b.writeUInt16LE(parseInt(p.slice(12, 16), 16), 6);
209
- Buffer.from(p.slice(16, 32), "hex").copy(b, 8);
210
- return b;
211
- }
212
-
213
- /**
214
- * Expand first-occurrence anchors to include ALL binary occurrences of each known GUID.
215
- * The .one format stores page objects non-contiguously; using only first occurrences as
216
- * boundaries causes NTP/AIS pairs from later chunks of page A to be attributed to page B.
217
- */
218
- function expandAnchorsToAllOccurrences(
219
- buf: Buffer,
220
- anchors: { offset: number; guid: string }[]
221
- ): { offset: number; guid: string }[] {
222
- const guidHexToGuid = new Map<string, string>();
223
- for (const { guid } of anchors) {
224
- guidHexToGuid.set(guidToBuf(guid).toString("hex"), guid);
225
- }
226
- const SIZE_MARKER = Buffer.from([0x10, 0x00, 0x00, 0x00]);
227
- const result: { offset: number; guid: string }[] = [];
228
- let pos = 0;
229
- while (pos < buf.length - 20) {
230
- const markerPos = buf.indexOf(SIZE_MARKER, pos);
231
- if (markerPos < 0) break;
232
- const guidHex = buf.slice(markerPos + 4, markerPos + 20).toString("hex");
233
- const guid = guidHexToGuid.get(guidHex);
234
- if (guid) result.push({ offset: markerPos, guid });
235
- pos = markerPos + 1;
236
- }
237
- return result;
238
- }
239
-
240
- /**
241
- * Extract (pageGuid, title, offset) tuples from .one binary.
242
- * Pattern: [UTF-16LE title] 00 00 [10 00 00 00] [16-byte GUID]
243
- */
244
- export function extractPageGuids(
245
- buf: Buffer
246
- ): { guid: string; title: string; offset: number }[] {
247
- const results: { guid: string; title: string; offset: number }[] = [];
248
- const seen = new Set<string>();
249
-
250
- for (let i = 0; i < buf.length - 20; i++) {
251
- // Size marker 10 00 00 00 (uint32 LE = 16)
252
- if (buf[i] !== 0x10 || buf[i + 1] !== 0 || buf[i + 2] !== 0 || buf[i + 3] !== 0) continue;
253
-
254
- // Check GUID validity (UUIDv4: version=4, variant=8-B)
255
- const v = (buf[i + 4 + 7] >> 4) & 0xf;
256
- const vr = (buf[i + 4 + 8] >> 4) & 0xf;
257
- if (v !== 4 || vr < 8 || vr > 0xb) continue;
258
-
259
- const guid = bufToGuid(buf, i + 4);
260
- if (seen.has(guid)) continue;
261
-
262
- // Walk backwards from i to find UTF-16LE title
263
- let j = i - 2;
264
- if (j >= 0 && buf[j] === 0 && buf[j + 1] === 0) j -= 2; // skip terminator
265
- let chars = "";
266
- while (j >= 0 && chars.length < 200) {
267
- const code = buf[j] | (buf[j + 1] << 8);
268
- if ((code >= 0x20 && code <= 0x7e) || (code >= 0xa0 && code <= 0xffef)) {
269
- chars = String.fromCharCode(code) + chars;
270
- j -= 2;
271
- } else {
272
- break;
273
- }
274
- }
275
-
276
- if (chars.length >= 3 && chars.length < 200) {
277
- // Filter out garbage titles: must contain a meaningful ratio of "real" characters
278
- // (ASCII letters/digits, common CJK ideographs, hiragana/katakana, punctuation)
279
- const meaningful = chars.replace(
280
- /[^a-zA-Z0-9\u3040-\u30ff\u4e00-\u9fff\u3000-\u303f\uff00-\uffef\s.,;:!?@#\-_()[\]{}'"/\\]/g,
281
- ""
282
- );
283
- if (meaningful.length / chars.length < 0.7) continue;
284
-
285
- // Reject titles where most CJK chars are likely shifted-ASCII garbage
286
- let shiftedCount = 0;
287
- for (const ch of chars) {
288
- const code = ch.charCodeAt(0);
289
- if ((code & 0xff) === 0 && code >= 0x2000) shiftedCount++;
290
- }
291
- if (shiftedCount > 2 && shiftedCount / chars.length > 0.3) continue;
292
-
293
- // Reject embedded object titles like ".jpg", ".png", ".pdf" that are
294
- // attachment GUIDs, not page GUIDs
295
- const trimmed = chars.trim();
296
- if (/^\.[a-z0-9]{2,5}$/i.test(trimmed)) continue;
297
-
298
- seen.add(guid);
299
- results.push({ guid, title: trimmed, offset: i });
300
- }
301
- }
302
-
303
- return results;
304
- }
305
-
306
- export function extractPages(
307
- buf: Buffer
308
- ): { title: string; body: string; pageGuid?: string }[] {
309
- const blocks = extractTextBlocks(buf);
310
- const guidEntries = extractPageGuids(buf);
311
-
312
- if (guidEntries.length === 0) {
313
- return groupIntoPages(blocks).map((p) => ({ ...p, pageGuid: undefined }));
314
- }
315
-
316
- // Sort guid entries by offset and dedupe to get unique pages with their FIRST offset
317
- guidEntries.sort((a, b) => a.offset - b.offset);
318
- const firstOffsetByGuid = new Map<string, { title: string; offset: number }>();
319
- const titleByGuid = new Map<string, string>();
320
- for (const e of guidEntries) {
321
- if (!firstOffsetByGuid.has(e.guid)) {
322
- firstOffsetByGuid.set(e.guid, { title: e.title.trim(), offset: e.offset });
323
- titleByGuid.set(e.guid, e.title.trim());
324
- }
325
- }
326
-
327
- // Build sorted list of (offset, guid) anchors using ALL occurrences
328
- const anchors = guidEntries
329
- .map((e) => ({ offset: e.offset, guid: e.guid }))
330
- .sort((a, b) => a.offset - b.offset);
331
-
332
- // Build a title -> guid map for boundary detection
333
- const titleToGuidMap = new Map<string, string>();
334
- for (const [guid, title] of titleByGuid) {
335
- if (title.length >= 4) titleToGuidMap.set(title, guid);
336
- }
337
- // Sort known titles by length desc for greedy match
338
- const knownTitlesSorted = [...titleToGuidMap.keys()].sort((a, b) => b.length - a.length);
339
-
340
- // For each text block:
341
- // - If it matches a known page title, switch to that page's GUID
342
- // - Otherwise, append to the current page's body
343
- const bodiesByGuid = new Map<string, string[]>();
344
- let anchorIdx = 0;
345
- let currentGuid: string | undefined;
346
- for (const block of blocks) {
347
- // Check if this block IS a known page title (boundary)
348
- let titleMatch: string | undefined;
349
- for (const t of knownTitlesSorted) {
350
- if (block.text === t || block.text.startsWith(t)) {
351
- titleMatch = t;
352
- break;
353
- }
354
- }
355
- if (titleMatch) {
356
- currentGuid = titleToGuidMap.get(titleMatch);
357
- // Skip pushing the title text into the body to avoid noise
358
- continue;
359
- }
360
-
361
- // Otherwise advance anchor by offset
362
- while (anchorIdx < anchors.length && anchors[anchorIdx].offset <= block.offset) {
363
- currentGuid = anchors[anchorIdx].guid;
364
- anchorIdx++;
365
- }
366
- if (!currentGuid) continue;
367
- const arr = bodiesByGuid.get(currentGuid) || [];
368
- arr.push(block.text);
369
- bodiesByGuid.set(currentGuid, arr);
370
- }
371
-
372
- // Build final pages
373
- const pages: { title: string; body: string; pageGuid?: string }[] = [];
374
- for (const [guid, info] of firstOffsetByGuid) {
375
- const body = (bodiesByGuid.get(guid) || []).join("\n");
376
- if (body.length < 5 && info.title.length < 3) continue;
377
- pages.push({ title: info.title || "(untitled)", body: body || info.title, pageGuid: guid });
378
- }
379
- return pages;
380
- }
381
-
382
- async function ensureDir(dir: string) {
383
- await mkdir(dir, { recursive: true });
384
- }
385
-
386
- async function downloadSection(
387
- drivePath: string
388
- ): Promise<Buffer | null> {
389
- const encoded = drivePath
390
- .split("/")
391
- .map((s) => encodeURIComponent(s))
392
- .join("/");
393
- const res = await graphFetchRaw(`/me/drive/root:/${encoded}:/content`);
394
- if (!res.ok) return null;
395
- return Buffer.from(await res.arrayBuffer());
396
- }
397
-
398
- async function getSectionWebUrl(drivePath: string): Promise<string> {
399
- const encoded = drivePath
400
- .split("/")
401
- .map((s) => encodeURIComponent(s))
402
- .join("/");
403
- try {
404
- const res = await graphFetchRaw(
405
- `/me/drive/root:/${encoded}?$select=webUrl`
406
- );
407
- if (res.ok) {
408
- const item = (await res.json()) as any;
409
- return item.webUrl?.split("&mobileredirect")[0] ?? "";
410
- }
411
- } catch {}
412
- return "";
413
- }
414
-
415
- /**
416
- * Get OneNote pages for a section via Graph API.
417
- * Uses the `0-{guid}` ID prefix which works even when the 5,000-item limit
418
- * blocks listing endpoints.
419
- */
420
- async function getOneNotePagesForSection(
421
- sectionGuid: string
422
- ): Promise<{ id: string; title: string; webUrl: string }[]> {
423
- const results: { id: string; title: string; webUrl: string }[] = [];
424
- let url: string | null = `/me/onenote/sections/0-${sectionGuid}/pages?$select=id,title,links&$top=100`;
425
- try {
426
- while (url) {
427
- const res = await graphFetchRaw(url);
428
- if (!res.ok) break;
429
- const data = (await res.json()) as any;
430
- for (const p of data.value ?? []) {
431
- results.push({ id: p.id, title: p.title ?? "", webUrl: p.links?.oneNoteWebUrl?.href ?? "" });
432
- }
433
- url = data["@odata.nextLink"] ?? null;
434
- }
435
- } catch {}
436
- return results;
437
- }
438
-
439
- /**
440
- * Extract the page navigation GUID from the OneNote oneNoteWebUrl.
441
- * The webUrl contains `wd=target(...|{lastGuid}/)` where lastGuid is the page GUID
442
- * used for navigation (matches what we extract from the binary).
443
- */
444
- function pageGuidFromWebUrl(webUrl: string): string | null {
445
- if (!webUrl) return null;
446
- // Find the LAST GUID in the URL (the page-level one, after the section group)
447
- // Pattern: ...{guid1}/{title}|{pageGuid}/)
448
- const decoded = decodeURIComponent(webUrl);
449
- const matches = decoded.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi);
450
- if (!matches || matches.length === 0) return null;
451
- return matches[matches.length - 1].toLowerCase();
452
- }
453
-
454
- async function listSectionFiles(
455
- notebook: any
456
- ): Promise<{ name: string; drivePath: string; lastModified: string; size: number; apiOnly?: boolean; sectionId?: string }[]> {
457
- const nbPath = getNotebookDrivePath(notebook);
458
- if (nbPath) {
459
- const encoded = nbPath.split("/").map((s) => encodeURIComponent(s)).join("/");
460
- try {
461
- const res = await graphFetchRaw(
462
- `/me/drive/root:/${encoded}:/children?$select=name,id,file,size,lastModifiedDateTime&$top=200`
463
- );
464
- if (res.ok) {
465
- const data = (await res.json()) as any;
466
- const files = (data.value ?? [])
467
- .filter((f: any) => f.name?.endsWith(".one"))
468
- .map((f: any) => ({
469
- name: f.name.replace(/\.one$/, ""),
470
- drivePath: `${nbPath}/${f.name}`,
471
- lastModified: f.lastModifiedDateTime ?? "",
472
- size: f.size ?? 0,
473
- }));
474
- if (files.length > 0) return files;
475
- }
476
- } catch {}
477
- }
478
-
479
- // Fallback: personal OneDrive / unresolvable path → use OneNote API to list sections.
480
- // These sections are synced HTML-only (no .one binary download).
481
- try {
482
- const res = await graphFetchRaw(
483
- `/me/onenote/notebooks/${notebook.id}/sections?$select=id,displayName,lastModifiedDateTime&$top=100`
484
- );
485
- if (!res.ok) return [];
486
- const data = (await res.json()) as any;
487
- return (data.value ?? []).map((s: any) => ({
488
- name: s.displayName ?? "unnamed",
489
- drivePath: "",
490
- lastModified: s.lastModifiedDateTime ?? "",
491
- size: 0,
492
- apiOnly: true,
493
- sectionId: s.id,
494
- }));
495
- } catch {
496
- return [];
497
- }
498
- }
499
-
500
- export const SEARCH_DB_PATH = join(PKG_ROOT, ".onenote", "search.db");
501
-
502
- // Maps #alias → OneNote data-tag value(s). Multiple values = OR match.
503
- export const TAG_ALIASES: Record<string, string[]> = {
504
- star: ["star"],
505
- question: ["question"],
506
- important: ["important"],
507
- critical: ["critical"],
508
- definition: ["definition"],
509
- idea: ["idea"],
510
- contact: ["contact"],
511
- address: ["address"],
512
- phone: ["phone-number"],
513
- website: ["web-site-to-visit"],
514
- password: ["password"],
515
- remember: ["remember-for-later"],
516
- book: ["book-to-read"],
517
- music: ["music-to-listen-to"],
518
- movie: ["movie-to-see"],
519
- highlight: ["highlight"],
520
- meeting: ["schedule-meeting"],
521
- email: ["send-in-email"],
522
- callback: ["call-back"],
523
- discuss: ["discuss-with-person-a", "discuss-with-person-b", "discuss-with-manager"],
524
- priority1: ["to-do-priority-1"],
525
- priority2: ["to-do-priority-2"],
526
- client: ["client-request"],
527
- };
528
-
529
- function openSearchDb(): Database {
530
- const db = new Database(SEARCH_DB_PATH, { create: true });
531
- db.run("PRAGMA journal_mode=WAL");
532
- db.run(`
533
- CREATE TABLE IF NOT EXISTS pages (
534
- id INTEGER PRIMARY KEY,
535
- section TEXT NOT NULL,
536
- notebook TEXT NOT NULL,
537
- title TEXT,
538
- body TEXT,
539
- web_url TEXT,
540
- page_guid TEXT,
541
- has_todo INTEGER DEFAULT NULL,
542
- has_done INTEGER DEFAULT NULL,
543
- tags TEXT DEFAULT NULL,
544
- tag_lines TEXT DEFAULT NULL,
545
- account TEXT DEFAULT NULL,
546
- last_modified TEXT DEFAULT NULL
547
- )
548
- `);
549
- // Migrate existing DBs that lack these columns
550
- try { db.run("ALTER TABLE pages ADD COLUMN has_todo INTEGER DEFAULT NULL"); } catch {}
551
- try { db.run("ALTER TABLE pages ADD COLUMN has_done INTEGER DEFAULT NULL"); } catch {}
552
- try { db.run("ALTER TABLE pages ADD COLUMN tags TEXT DEFAULT NULL"); } catch {}
553
- try { db.run("ALTER TABLE pages ADD COLUMN tag_lines TEXT DEFAULT NULL"); } catch {}
554
- try { db.run("ALTER TABLE pages ADD COLUMN account TEXT DEFAULT NULL"); } catch {}
555
- try { db.run("ALTER TABLE pages ADD COLUMN last_modified TEXT DEFAULT NULL"); } catch {}
556
- db.run("CREATE INDEX IF NOT EXISTS pages_section ON pages(section, notebook)");
557
- db.run(`
558
- CREATE VIRTUAL TABLE IF NOT EXISTS pages_fts USING fts5(
559
- title, body,
560
- content="",
561
- tokenize="unicode61"
562
- )
563
- `);
564
- return db;
565
- }
566
-
567
- /** Parse tag filters out of a query string. Returns text-only FTS query and extracted tags.
568
- * Recognizes: #todo tag:todo #done tag:done
569
- */
570
- /**
571
- * Build an FTS5 MATCH parameter from a user query string.
572
- * - Explicit boolean operators (AND/OR/NOT, case-insensitive) are normalized to uppercase.
573
- * - Otherwise each space-separated token is quoted for exact-term matching (implicit AND).
574
- * - User-supplied "quoted phrases" are preserved as-is.
575
- */
576
- export function buildFtsParam(query: string): string {
577
- if (/\b(AND|OR|NOT)\b/i.test(query)) {
578
- // Normalize operators to uppercase; preserve user-quoted phrases
579
- return query.replace(/\b(AND|OR|NOT)\b/gi, (m) => m.toUpperCase());
580
- }
581
- // Split preserving quoted phrases, then quote individual bare terms
582
- const tokens = query.match(/(?:"[^"]*"|[^\s]+)/g) ?? [];
583
- return tokens
584
- .map((t) => (t.startsWith('"') ? t : `"${t.replace(/"/g, '""')}"`))
585
- .join(" ");
586
- }
587
-
588
- export function parseTagsFromQuery(query: string): {
589
- ftsQuery: string;
590
- hasTodo: boolean;
591
- hasDone: boolean;
592
- hasCheckbox: boolean;
593
- tagFilters: string[]; // OneNote data-tag values to filter by (OR within each alias group, AND across groups)
594
- } {
595
- let hasTodo = false;
596
- let hasDone = false;
597
- let hasCheckbox = false;
598
- const tagFilters: string[] = [];
599
-
600
- let ftsQuery = query
601
- .replace(/#checkbox\b/gi, () => { hasCheckbox = true; return ""; })
602
- .replace(/\btag:checkbox\b/gi, () => { hasCheckbox = true; return ""; })
603
- .replace(/#todo\b/gi, () => { hasTodo = true; return ""; })
604
- .replace(/\btag:todo\b/gi, () => { hasTodo = true; return ""; })
605
- .replace(/#done\b/gi, () => { hasDone = true; return ""; })
606
- .replace(/\btag:done\b/gi, () => { hasDone = true; return ""; });
607
-
608
- // Replace all known #alias and tag:alias patterns
609
- for (const [alias, tagValues] of Object.entries(TAG_ALIASES)) {
610
- const escaped = alias.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
611
- ftsQuery = ftsQuery
612
- .replace(new RegExp(`#${escaped}\\b`, "gi"), () => { tagFilters.push(...tagValues); return ""; })
613
- .replace(new RegExp(`\\btag:${escaped}\\b`, "gi"), () => { tagFilters.push(...tagValues); return ""; });
614
- }
615
-
616
- ftsQuery = ftsQuery.replace(/\s+/g, " ").trim();
617
- return { ftsQuery, hasTodo, hasDone, hasCheckbox, tagFilters };
618
- }
619
-
620
- const BINARY_BODY_LIMIT = 50_000; // chars extracted from .one binary per anchor range
621
-
622
- function asciiRatio(s: string): number {
623
- if (!s.length) return 0;
624
- const printable = s.split("").filter((c) => c >= "\x20" && c <= "\x7E").length;
625
- return printable / s.length;
626
- }
627
-
628
- function cleanBodyForIndex(body: string): string {
629
- // Strip binary garbage lines before FTS indexing to keep the posting list small.
630
- // A line is kept if it has reasonable ASCII ratio OR contains meaningful CJK text.
631
- const lines = body
632
- .replace(/[\x00-\x09\x0B-\x1F\x7F]/g, " ")
633
- .split(/\n+/)
634
- .map((l) => l.replace(/\s+/g, " ").trim())
635
- .filter((l) => {
636
- if (l.length < 2) return false;
637
- const ratio = asciiRatio(l);
638
- // Keep lines with decent ASCII ratio or meaningful non-ASCII (CJK etc)
639
- if (ratio >= 0.3) return true;
640
- // Count CJK/Hiragana/Katakana characters (U+3000-U+9FFF, U+AC00-U+D7AF)
641
- const cjk = (l.match(/[\u3000-\u9FFF\uAC00-\uD7AF]/g) ?? []).length;
642
- return cjk / l.length >= 0.2;
643
- });
644
- return lines.join("\n");
645
- }
646
-
647
- // MS-ONESTORE property markers for note tags
648
- const NOTE_TAGS_PROP = Buffer.from([0x89, 0x34, 0x00, 0x40]); // 0x40003489: NoteTags property
649
- const ACTION_ITEM_STATUS = Buffer.from([0x70, 0x34, 0x00, 0x10]); // 0x10003470: ActionItemStatus
650
-
651
- /**
652
- * Extract page GUIDs that have at least one uncompleted action-item tag (To Do, Remember for later, etc.)
653
- * directly from the .one binary without any API calls.
654
- *
655
- * Detection: find NoteTags property (89 34 00 40) followed within 300 bytes by
656
- * ActionItemStatus (70 34 00 10) where the 2-byte status value has bit0=0 (not completed).
657
- * Map each match to the nearest preceding page anchor.
658
- *
659
- * Note: this catches ALL uncompleted action tags, not only pure To-Do checkboxes.
660
- * Shape-based discrimination (shape=1 = checkbox) requires full OID resolution from the
661
- * PropertySet graph and is not implemented here.
662
- */
663
- export function extractTodoPageGuids(
664
- buf: Buffer,
665
- anchors: { offset: number; guid: string }[]
666
- ): { todo: Set<string>; done: Set<string> } {
667
- const sorted = expandAnchorsToAllOccurrences(buf, anchors).sort((a, b) => a.offset - b.offset);
668
- const todo = new Set<string>();
669
- const done = new Set<string>();
670
-
671
- let pos = 0;
672
- while (true) {
673
- const idx = buf.indexOf(NOTE_TAGS_PROP, pos);
674
- if (idx < 0) break;
675
-
676
- const window = buf.slice(idx, idx + 300);
677
- const aisRel = window.indexOf(ACTION_ITEM_STATUS);
678
- if (aisRel >= 0) {
679
- const aisAbs = idx + aisRel;
680
- // ActionItemStatus is a uint16 at AIS_prid_pos + 12.
681
- // The 8 bytes at +4..+11 are the FILETIME data for the preceding property (0x1400346f).
682
- // Empirically verified: status=0=unchecked, status=1=completed.
683
- if (aisAbs + 14 <= buf.length) {
684
- const status = buf.readUInt16LE(aisAbs + 12);
685
- if (status === 0 || status === 1) {
686
- // find nearest anchor (preceding, or following if very close)
687
- // MS-ONESTORE stores page content before the page GUID marker, so a NTP that falls
688
- // just before the next anchor likely belongs to that next page.
689
- let preceding: { offset: number; guid: string } | null = null;
690
- let following: { offset: number; guid: string } | null = null;
691
- for (const a of sorted) {
692
- if (a.offset <= idx) preceding = a;
693
- else { following = a; break; }
694
- }
695
- const LOOKAHEAD = 1000; // bytes: prefer following anchor if it's this close
696
- const nearest =
697
- following && following.offset - idx < LOOKAHEAD ? following.guid : preceding?.guid ?? null;
698
- if (nearest) {
699
- if (status === 0) todo.add(nearest);
700
- else done.add(nearest);
701
- }
702
- }
703
- }
704
- }
705
- pos = idx + 1;
706
- }
707
- return { todo, done };
708
- }
709
-
710
- export type PageTagInfo = {
711
- tags: string[]; // unique sorted tag values
712
- lines: Array<{ tag: string; text: string }>; // text of each tagged element
713
- };
714
-
715
- function stripHtml(s: string): string {
716
- return s
717
- .replace(/<[^>]+>/g, " ")
718
- .replace(/&nbsp;/g, " ")
719
- .replace(/&amp;/g, "&")
720
- .replace(/&lt;/g, "<")
721
- .replace(/&gt;/g, ">")
722
- .replace(/&quot;/g, '"')
723
- .replace(/&#(\d+);/g, (_, n) => String.fromCharCode(parseInt(n, 10)))
724
- .replace(/\s+/g, " ")
725
- .trim();
726
- }
727
-
728
- /** Extract text of each tagged element from OneNote HTML */
729
- export function extractTagLines(html: string): Array<{ tag: string; text: string }> {
730
- const lines: Array<{ tag: string; text: string }> = [];
731
- // Matches elements with data-tag attribute and captures content up to closing tag.
732
- // Uses non-greedy match; OneNote generally doesn't nest tagged elements.
733
- const re = /<(\w+)([^>]*?)\s+data-tag="([^"]+)"([^>]*)>([\s\S]*?)<\/\1>/gi;
734
- for (const m of html.matchAll(re)) {
735
- const tagValues = m[3].split(/[\s,]+/).filter(Boolean);
736
- const text = stripHtml(m[5]).slice(0, 200);
737
- if (text.length > 0) {
738
- for (const t of tagValues) lines.push({ tag: t, text });
739
- }
740
- }
741
- return lines;
742
- }
743
-
744
- /**
745
- * Fetch page HTML content from OneNote API and collect all data-tag values + text per page.
746
- */
747
- async function fetchTagsFromHtml(
748
- pages: Array<{ apiId: string; guid: string }>,
749
- onProgress?: (msg: string) => void
750
- ): Promise<Map<string, PageTagInfo>> {
751
- const result = new Map<string, PageTagInfo>();
752
- for (const page of pages) {
753
- try {
754
- const res = await graphFetchRaw(`/me/onenote/pages/${page.apiId}/content`);
755
- if (!res.ok) continue;
756
- const html = await res.text();
757
- const found = new Set<string>();
758
- for (const m of html.matchAll(/data-tag="([^"]+)"/g)) {
759
- for (const tag of m[1].split(/[\s,]+/)) {
760
- if (tag) found.add(tag);
761
- }
762
- }
763
- const lines = extractTagLines(html);
764
- if (found.size > 0) {
765
- const sorted = [...found].sort();
766
- result.set(page.guid, { tags: sorted, lines });
767
- onProgress?.(` [tags:${sorted.join(",")}] ${page.guid}`);
768
- }
769
- } catch {}
770
- }
771
- return result;
772
- }
773
-
774
- function extractBinaryPageText(buf: Buffer, startOffset: number, endOffset: number): string {
775
- const segment = buf.slice(startOffset, Math.min(endOffset, startOffset + BINARY_BODY_LIMIT * 3));
776
- const clean = (s: string) =>
777
- s.replace(/[\x00-\x1F\x7F\uFFFD]/g, " ").replace(/\s+/g, " ").trim();
778
- const utf8 = clean(segment.toString("utf-8"));
779
- const utf16 = clean(segment.toString("utf16le"));
780
- const best = asciiRatio(utf8) >= asciiRatio(utf16) ? utf8 : utf16;
781
- return best.slice(0, BINARY_BODY_LIMIT);
782
- }
783
-
784
- function upsertSectionToIndex(
785
- db: Database,
786
- section: string,
787
- notebook: string,
788
- pages: Array<{ title: string; body?: string; pageGuid?: string; officialUrl?: string }>,
789
- webUrl: string,
790
- binBuf?: Buffer,
791
- anchors?: Array<{ offset: number; guid: string; title: string }>,
792
- officialPages?: Array<{ guid: string | null; title: string; webUrl?: string; apiId?: string }>,
793
- htmlTags?: Map<string, PageTagInfo>,
794
- accountEmail?: string,
795
- sectionLastModified?: string
796
- ): void {
797
- // Build lookup maps
798
- const officialUrlByGuid = new Map<string, { url: string; title: string }>();
799
- for (const op of officialPages ?? []) {
800
- if (op.guid && op.webUrl) officialUrlByGuid.set(op.guid, { url: op.webUrl, title: op.title });
801
- }
802
-
803
- // Binary detection as fallback for pages not covered by HTML fetch
804
- const binaryGuids = binBuf && anchors?.length
805
- ? extractTodoPageGuids(binBuf, anchors)
806
- : { todo: new Set<string>(), done: new Set<string>() };
807
-
808
- // Pages checked via HTML: use HTML result (accurate). Others: use binary (fallback).
809
- const officialGuidSet = new Set(officialUrlByGuid.keys());
810
- const getHasTodo = (guid: string): 0 | 1 => {
811
- if (htmlTags && officialGuidSet.has(guid)) return (htmlTags.get(guid)?.tags ?? []).includes("to-do") ? 1 : 0;
812
- return binaryGuids.todo.has(guid) ? 1 : 0;
813
- };
814
- const getHasDone = (guid: string): 0 | 1 => {
815
- if (htmlTags && officialGuidSet.has(guid)) return (htmlTags.get(guid)?.tags ?? []).includes("to-do:completed") ? 1 : 0;
816
- return binaryGuids.done.has(guid) ? 1 : 0;
817
- };
818
- // tags column: pipe-delimited tag list, e.g. "|star|to-do|" for LIKE '%|star|%' matching
819
- const getTagsStr = (guid: string): string | null => {
820
- const t = htmlTags?.get(guid);
821
- if (!t || t.tags.length === 0) return null;
822
- return `|${t.tags.join("|")}|`;
823
- };
824
- // tag_lines column: JSON-encoded array of {tag, text} for display
825
- const getTagLinesStr = (guid: string): string | null => {
826
- const t = htmlTags?.get(guid);
827
- if (!t || t.lines.length === 0) return null;
828
- return JSON.stringify(t.lines);
829
- };
830
-
831
- db.transaction(() => {
832
- // Remove old FTS entries first (content table requires explicit delete)
833
- db.run(
834
- `INSERT INTO pages_fts(pages_fts, rowid, title, body)
835
- SELECT 'delete', id, title, body FROM pages WHERE section=? AND notebook=?`,
836
- [section, notebook]
837
- );
838
- db.run("DELETE FROM pages WHERE section=? AND notebook=?", [section, notebook]);
839
-
840
- const insert = db.prepare(
841
- "INSERT INTO pages(section, notebook, title, body, web_url, page_guid, has_todo, has_done, tags, tag_lines, account, last_modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
842
- );
843
-
844
- if (binBuf && anchors && anchors.length > 0) {
845
- const sorted = [...anchors].sort((a, b) => a.offset - b.offset);
846
- const jsonBodyByGuid = new Map(pages.map((p) => [p.pageGuid, p.body]));
847
- for (let i = 0; i < sorted.length; i++) {
848
- const anchor = sorted[i]!;
849
- const nextOffset = sorted[i + 1]?.offset ?? binBuf.length;
850
- const binBody = extractBinaryPageText(binBuf, anchor.offset, nextOffset);
851
- const jsonBody = jsonBodyByGuid.get(anchor.guid) ?? "";
852
- const body = cleanBodyForIndex((jsonBody + " " + binBody).slice(0, BINARY_BODY_LIMIT));
853
- const official = officialUrlByGuid.get(anchor.guid);
854
- const url = official?.url ?? buildPageUrl(webUrl, anchor.title, anchor.guid);
855
- insert.run(section, notebook, official?.title ?? anchor.title, body, url, anchor.guid, getHasTodo(anchor.guid), getHasDone(anchor.guid), getTagsStr(anchor.guid), getTagLinesStr(anchor.guid), accountEmail ?? null, sectionLastModified ?? null);
856
- }
857
- } else {
858
- for (const p of pages) {
859
- const url = p.officialUrl ?? buildPageUrl(webUrl, p.title, p.pageGuid);
860
- insert.run(section, notebook, p.title ?? "", cleanBodyForIndex(p.body ?? ""), url, p.pageGuid ?? "", null, null, null, null, accountEmail ?? null, sectionLastModified ?? null);
861
- }
862
- }
863
-
864
- // Rebuild FTS for this section from the pages table
865
- db.run(
866
- `INSERT INTO pages_fts(rowid, title, body)
867
- SELECT id, title, body FROM pages WHERE section=? AND notebook=?`,
868
- [section, notebook]
869
- );
870
- })();
871
- }
872
-
873
- export type SyncEmit = (ev: import("./sync-ui").SyncEvent) => void;
874
-
875
- /** Optional scoping for `onenote sync`. Each field is a case-insensitive substring match. */
876
- export type SyncFilter = { account?: string; notebook?: string; section?: string };
877
-
878
- function matchesFilter(value: string, filter?: string): boolean {
879
- return !filter || value.toLowerCase().includes(filter.toLowerCase());
880
- }
881
-
882
- /** Sanitize email for filesystem path usage (replace @ and any other unsafe chars). */
883
- function accountDirName(email: string): string {
884
- return email.replace(/[^a-zA-Z0-9._-]/g, "_");
885
- }
886
-
887
- /** Move legacy .onenote/cache/<notebook>/ entries into .onenote/cache/<account>/<notebook>/ on first multi-account sync. */
888
- async function migrateLegacyCacheToAccount(accountEmail: string, log: (msg: string) => void): Promise<void> {
889
- const { rename } = await import("node:fs/promises");
890
- const accountDir = join(CACHE_DIR, accountDirName(accountEmail));
891
- let entries: string[];
892
- try { entries = await readdir(CACHE_DIR); } catch { return; }
893
- const legacy = entries.filter((e) => !e.startsWith(".") && e !== accountDirName(accountEmail));
894
- if (legacy.length === 0) return;
895
-
896
- // Only migrate entries that look like notebook dirs (contain .json or .one files)
897
- const toMove: string[] = [];
898
- for (const name of legacy) {
899
- const p = join(CACHE_DIR, name);
900
- try {
901
- const s = await stat(p);
902
- if (!s.isDirectory()) continue;
903
- const files = await readdir(p);
904
- if (files.some((f) => f.endsWith(".json") || f.endsWith(".one"))) {
905
- // Skip if this dir itself looks like an account dir (contains subdirs that look like notebooks)
906
- const hasSubdirs = await Promise.all(files.map(async (f) => {
907
- try { return (await stat(join(p, f))).isDirectory(); } catch { return false; }
908
- }));
909
- if (hasSubdirs.some((x) => x)) continue; // already account-style
910
- toMove.push(name);
911
- }
912
- } catch {}
913
- }
914
- if (toMove.length === 0) return;
915
-
916
- log(`Migrating ${toMove.length} legacy notebook cache dir(s) to ${accountEmail}/...`);
917
- await ensureDir(accountDir);
918
- for (const name of toMove) {
919
- try { await rename(join(CACHE_DIR, name), join(accountDir, name)); } catch {}
920
- }
921
- }
922
-
923
- export async function syncCache(
924
- onProgress?: (msg: string) => void,
925
- emit?: SyncEmit,
926
- filter?: SyncFilter
927
- ): Promise<void> {
928
- await ensureDir(CACHE_DIR);
929
- await ensureDir(join(PKG_ROOT, ".onenote"));
930
- const log = onProgress ?? console.log;
931
-
932
- const allAccounts = await listAccounts();
933
- if (allAccounts.length === 0) {
934
- log("No accounts logged in. Run `onenote auth login` first.");
935
- return;
936
- }
937
-
938
- // One-time migration: move legacy caches (.onenote/cache/<nb>/) into the first account's namespace
939
- await migrateLegacyCacheToAccount(allAccounts[0]!.username, log);
940
-
941
- const accounts = allAccounts.filter((a) => matchesFilter(a.username, filter?.account));
942
- if (accounts.length === 0) {
943
- const msg = `No account matches --account=${filter?.account}. Available: ${allAccounts.map((a) => a.username).join(", ")}`;
944
- log(msg);
945
- emit?.({ type: "hint", text: msg });
946
- return;
947
- }
948
-
949
- // Progressively hint how to narrow the run (useful in non-TTY / agent contexts).
950
- if (!filter?.account && allAccounts.length > 1) {
951
- emit?.({ type: "hint", text: `${allAccounts.length} accounts — limit with --account=<email>` });
952
- }
953
-
954
- log(`Syncing ${accounts.length} account${accounts.length > 1 ? "s" : ""}: ${accounts.map((a) => a.username).join(", ")}`);
955
-
956
- let idx = 0;
957
- for (const account of accounts) {
958
- idx++;
959
- setCurrentAccount(account);
960
- emit?.({ type: "account", email: account.username, index: idx, total: accounts.length });
961
- log(`\n=== ${account.username} ===`);
962
- try {
963
- await syncAccountCache(account.username, log, emit, filter);
964
- } catch (err) {
965
- log(` [error] ${account.username}: ${(err as Error).message}`);
966
- }
967
- }
968
- setCurrentAccount(undefined);
969
- }
970
-
971
- /** HTML-only sync for personal OneDrive accounts (no .one binary access).
972
- * Lists pages via OneNote API, fetches each page's HTML, stores tags + text in DB. */
973
- async function syncApiOnlySection(
974
- db: Database,
975
- notebookName: string,
976
- sectionName: string,
977
- sectionId: string,
978
- accountEmail: string,
979
- log: (msg: string) => void,
980
- emit?: SyncEmit
981
- ): Promise<number> {
982
- const pagesForHtml: { guid: string; apiId: string; title: string; webUrl: string; lastModified: string | null }[] = [];
983
- let url: string | null = `/me/onenote/sections/${sectionId}/pages?$select=id,title,links,lastModifiedDateTime&$top=100`;
984
- while (url) {
985
- const res = await graphFetchRaw(url);
986
- if (!res.ok) break;
987
- const data = (await res.json()) as any;
988
- for (const p of data.value ?? []) {
989
- const webUrl = p.links?.oneNoteWebUrl?.href ?? "";
990
- const guid = pageGuidFromWebUrl(webUrl) ?? p.id;
991
- pagesForHtml.push({ guid, apiId: p.id, title: p.title ?? "", webUrl, lastModified: p.lastModifiedDateTime ?? null });
992
- }
993
- url = data["@odata.nextLink"] ?? null;
994
- }
995
- if (pagesForHtml.length === 0) return 0;
996
-
997
- emit?.({ type: "tags", count: 0 });
998
- const htmlTags = await fetchTagsFromHtml(
999
- pagesForHtml.map((p) => ({ guid: p.guid, apiId: p.apiId })),
1000
- log
1001
- );
1002
-
1003
- // Also fetch HTML body text for search (separate pass to reuse fetchTagsFromHtml would double fetch; do combined)
1004
- // Simpler: refetch HTML for the page body. But that doubles requests. Instead, extend fetchTagsFromHtml
1005
- // to return bodies too. For now keep it simple — we already have tag_lines which contain the tagged text.
1006
- db.transaction(() => {
1007
- const insert = db.prepare(
1008
- "INSERT INTO pages(section, notebook, title, body, web_url, page_guid, has_todo, has_done, tags, tag_lines, account, last_modified) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT DO NOTHING"
1009
- );
1010
- // Delete existing entries for this section first
1011
- db.run(
1012
- `INSERT INTO pages_fts(pages_fts, rowid, title, body)
1013
- SELECT 'delete', id, title, body FROM pages WHERE section=? AND notebook=? AND account=?`,
1014
- [sectionName, notebookName, accountEmail]
1015
- );
1016
- db.run("DELETE FROM pages WHERE section=? AND notebook=? AND account=?", [sectionName, notebookName, accountEmail]);
1017
-
1018
- for (const p of pagesForHtml) {
1019
- const info = htmlTags.get(p.guid);
1020
- const tags = info?.tags ?? [];
1021
- const lines = info?.lines ?? [];
1022
- const tagsStr = tags.length > 0 ? `|${tags.join("|")}|` : null;
1023
- const linesStr = lines.length > 0 ? JSON.stringify(lines) : null;
1024
- const hasTodo = tags.includes("to-do") ? 1 : 0;
1025
- const hasDone = tags.includes("to-do:completed") ? 1 : 0;
1026
- // Body = concatenation of tag line texts (used for search when no binary body available)
1027
- const body = lines.map((l) => l.text).join(" ").slice(0, 5000);
1028
- insert.run(sectionName, notebookName, p.title, body, p.webUrl, p.guid, hasTodo, hasDone, tagsStr, linesStr, accountEmail, p.lastModified);
1029
- }
1030
- // Rebuild FTS entries
1031
- db.run(
1032
- `INSERT INTO pages_fts(rowid, title, body)
1033
- SELECT id, title, body FROM pages WHERE section=? AND notebook=? AND account=?`,
1034
- [sectionName, notebookName, accountEmail]
1035
- );
1036
- })();
1037
-
1038
- return pagesForHtml.length;
1039
- }
1040
-
1041
- async function syncAccountCache(
1042
- accountEmail: string,
1043
- log: (msg: string) => void,
1044
- emit?: SyncEmit,
1045
- filter?: SyncFilter
1046
- ): Promise<void> {
1047
- const accountCacheDir = join(CACHE_DIR, accountDirName(accountEmail));
1048
- await ensureDir(accountCacheDir);
1049
- const db = openSearchDb();
1050
-
1051
- const allNotebooks = await listNotebooks();
1052
- const notebooks = allNotebooks.filter((nb) => matchesFilter(nb.displayName, filter?.notebook));
1053
- if (notebooks.length === 0) {
1054
- const msg = `No notebook matches --notebook=${filter?.notebook}. Available: ${allNotebooks.map((nb) => nb.displayName).join(", ")}`;
1055
- log(msg);
1056
- emit?.({ type: "hint", text: msg });
1057
- return;
1058
- }
1059
- if (!filter?.notebook && allNotebooks.length > 1) {
1060
- emit?.({ type: "hint", text: `${allNotebooks.length} notebooks — limit with --notebook=<name>` });
1061
- }
1062
- log(`Found ${notebooks.length} notebooks`);
1063
- emit?.({ type: "total", total: 0, notebooks: notebooks.length });
1064
-
1065
- // Collect all sections across notebooks for progress tracking.
1066
- // Sync smaller sections first so quick wins land early and huge sections
1067
- // don't block progress.
1068
- const sectionsByNotebook = await Promise.all(
1069
- notebooks.map(async (nb) => {
1070
- const nbDir = join(accountCacheDir, nb.displayName);
1071
- await ensureDir(nbDir);
1072
- const sections = await listSectionFiles(nb);
1073
- return sections.map((sec) => ({
1074
- nb,
1075
- sec,
1076
- nbDir,
1077
- cachePath: join(nbDir, `${sec.name}.json`),
1078
- }));
1079
- })
1080
- );
1081
- const allSections = sectionsByNotebook
1082
- .flat()
1083
- .filter(({ sec }) => matchesFilter(sec.name, filter?.section))
1084
- .toSorted((a, b) => (a.sec.size ?? 0) - (b.sec.size ?? 0));
1085
-
1086
- let downloaded = 0;
1087
- let skipped = 0;
1088
- let retagged = 0;
1089
- const total = allSections.length;
1090
- if (total === 0 && filter?.section) {
1091
- const msg = `No section matches --section=${filter.section} in the selected notebooks.`;
1092
- log(msg);
1093
- emit?.({ type: "hint", text: msg });
1094
- return;
1095
- }
1096
- if (!filter?.section && total > 20) {
1097
- emit?.({ type: "hint", text: `${total} sections — limit with --section=<name>` });
1098
- }
1099
- log(`${total} sections across ${notebooks.length} notebooks`);
1100
- emit?.({ type: "total", total, notebooks: notebooks.length });
1101
-
1102
- // Query for sections that already have tag_lines populated (to skip retagging them)
1103
- const taggedSectionsStmt = db.prepare(
1104
- "SELECT COUNT(*) as c FROM pages WHERE section=? AND notebook=? AND tag_lines IS NOT NULL"
1105
- );
1106
- const hasTagLines = (section: string, notebook: string): boolean =>
1107
- ((taggedSectionsStmt.get(section, notebook) as { c: number } | null)?.c ?? 0) > 0;
1108
-
1109
- for (const { nb, sec, nbDir, cachePath } of allSections) {
1110
- // Personal account / API-only sections: HTML-only sync (no binary download)
1111
- if (sec.apiOnly && sec.sectionId) {
1112
- const idx = downloaded + skipped + retagged + 1;
1113
- log(` [${idx}/${total}] ${nb.displayName}/${sec.name} (api-only)`);
1114
- emit?.({ type: "section", index: idx, notebook: nb.displayName, section: sec.name });
1115
- try {
1116
- const pageCount = await syncApiOnlySection(
1117
- db, nb.displayName, sec.name, sec.sectionId, accountEmail, log, emit
1118
- );
1119
- emit?.({ type: "done", notebook: nb.displayName, section: sec.name, pages: pageCount, status: "ok" });
1120
- downloaded++;
1121
- } catch (err) {
1122
- log(` [failed] ${sec.name}: ${(err as Error).message}`);
1123
- emit?.({ type: "done", notebook: nb.displayName, section: sec.name, pages: 0, status: "failed" });
1124
- skipped++;
1125
- }
1126
- continue;
1127
- }
1128
-
1129
- // Incremental sync: skip if cache is fresh AND source hasn't changed
1130
- let cacheIsFresh = false;
1131
- try {
1132
- const raw = await readFile(cachePath, "utf-8");
1133
- const cached = JSON.parse(raw);
1134
- if (cached.lastModified && sec.lastModified && cached.lastModified >= sec.lastModified) {
1135
- cacheIsFresh = true;
1136
- }
1137
- } catch {}
1138
-
1139
- if (cacheIsFresh) {
1140
- // Still run a light-weight tag refresh if DB doesn't have tag_lines for this section
1141
- if (!hasTagLines(sec.name, nb.displayName)) {
1142
- const webUrl = await getSectionWebUrl(sec.drivePath);
1143
- const sourcedocMatch = webUrl.match(/sourcedoc=%7B([0-9a-f-]+)%7D/i);
1144
- const sectionGuid = sourcedocMatch?.[1]?.toLowerCase();
1145
- if (sectionGuid) {
1146
- const officialPages = await getOneNotePagesForSection(sectionGuid);
1147
- const pagesForHtml = officialPages
1148
- .map((p) => { const g = pageGuidFromWebUrl(p.webUrl); return g ? { guid: g, apiId: p.id } : null; })
1149
- .filter(Boolean) as { guid: string; apiId: string }[];
1150
- if (pagesForHtml.length > 0) {
1151
- log(` [${retagged + downloaded + skipped + 1}/${total}] ${nb.displayName}/${sec.name} (retag only)`);
1152
- emit?.({ type: "retag", index: retagged + downloaded + skipped + 1, notebook: nb.displayName, section: sec.name });
1153
- const htmlTags = await fetchTagsFromHtml(pagesForHtml, log);
1154
- if (htmlTags.size > 0) {
1155
- emit?.({ type: "tags", count: htmlTags.size });
1156
- const updateStmt = db.prepare(
1157
- "UPDATE pages SET tags=?, tag_lines=?, has_todo=?, has_done=?, account=COALESCE(account, ?), last_modified=COALESCE(last_modified, ?) WHERE page_guid=? AND section=? AND notebook=?"
1158
- );
1159
- db.transaction(() => {
1160
- for (const [guid, info] of htmlTags) {
1161
- const tagsStr = `|${info.tags.join("|")}|`;
1162
- const linesStr = info.lines.length > 0 ? JSON.stringify(info.lines) : null;
1163
- const hasTodo = info.tags.includes("to-do") ? 1 : 0;
1164
- const hasDone = info.tags.includes("to-do:completed") ? 1 : 0;
1165
- updateStmt.run(tagsStr, linesStr, hasTodo, hasDone, accountEmail, sec.lastModified ?? null, guid, sec.name, nb.displayName);
1166
- }
1167
- })();
1168
- }
1169
- retagged++;
1170
- emit?.({ type: "done", notebook: nb.displayName, section: sec.name, pages: 0, status: "skipped" });
1171
- continue;
1172
- }
1173
- }
1174
- }
1175
- skipped++;
1176
- emit?.({ type: "done", notebook: nb.displayName, section: sec.name, pages: 0, status: "skipped" });
1177
- continue;
1178
- }
1179
-
1180
- const idx = downloaded + skipped + retagged + 1;
1181
- const sizeStr = sec.size ? prettyBytes(sec.size, { binary: true }) : undefined;
1182
- log(` [${idx}/${total}] ${nb.displayName}/${sec.name}${sizeStr ? ` (${sizeStr})` : ""}`);
1183
- emit?.({ type: "section", index: idx, notebook: nb.displayName, section: sec.name, size: sizeStr });
1184
- const buf = await downloadSection(sec.drivePath);
1185
- if (!buf) {
1186
- log(` [failed] ${sec.name}`);
1187
- skipped++;
1188
- emit?.({ type: "done", notebook: nb.displayName, section: sec.name, pages: 0, status: "failed" });
1189
- continue;
1190
- }
1191
- downloaded++;
1192
-
1193
- const pages = extractPages(buf);
1194
- const guidEntries = extractPageGuids(buf).sort((a, b) => a.offset - b.offset);
1195
- const webUrl = await getSectionWebUrl(sec.drivePath);
1196
-
1197
- // Extract section's sourcedoc GUID from webUrl, then fetch official page list via OneNote API
1198
- const sourcedocMatch = webUrl.match(/sourcedoc=%7B([0-9a-f-]+)%7D/i);
1199
- const sectionGuid = sourcedocMatch?.[1]?.toLowerCase();
1200
- const officialPages = sectionGuid
1201
- ? await getOneNotePagesForSection(sectionGuid)
1202
- : [];
1203
- // Map: pageGuid -> official webUrl (extract GUID from webUrl, not from id)
1204
- const officialUrlByGuid = new Map<string, { url: string; title: string }>();
1205
- const officialApiIdByGuid = new Map<string, string>();
1206
- for (const op of officialPages) {
1207
- const guid = pageGuidFromWebUrl(op.webUrl);
1208
- if (guid && op.webUrl) {
1209
- officialUrlByGuid.set(guid, { url: op.webUrl, title: op.title });
1210
- officialApiIdByGuid.set(guid, op.id);
1211
- }
1212
- }
1213
-
1214
- // Fetch HTML for each official page to collect all tag types
1215
- const pagesForHtml = [...officialApiIdByGuid.entries()].map(([guid, apiId]) => ({ guid, apiId }));
1216
- if (pagesForHtml.length > 0) log(` fetching tags (${pagesForHtml.length} pages)...`);
1217
- const htmlTags = await fetchTagsFromHtml(pagesForHtml, log);
1218
-
1219
- // Save the binary as base64 for accurate position-based search
1220
- // Limit raw cache to <50MB sections to control disk usage
1221
- const includeRaw = buf.length < 50 * 1024 * 1024;
1222
-
1223
- const cacheData = {
1224
- section: sec.name,
1225
- notebook: nb.displayName,
1226
- webUrl,
1227
- lastModified: sec.lastModified,
1228
- pages: pages.map((p: any) => ({
1229
- title: p.title,
1230
- body: p.body,
1231
- pageGuid: p.pageGuid,
1232
- officialUrl: p.pageGuid ? officialUrlByGuid.get(p.pageGuid)?.url : undefined,
1233
- })),
1234
- // Use OneNote API page list as authoritative anchor list (with official URLs)
1235
- officialPages: officialPages.map((p) => ({
1236
- guid: pageGuidFromWebUrl(p.webUrl),
1237
- title: p.title,
1238
- webUrl: p.webUrl,
1239
- apiId: p.id,
1240
- })),
1241
- anchors: guidEntries.map((e) => ({ offset: e.offset, guid: e.guid, title: e.title })),
1242
- rawSize: buf.length,
1243
- cachedAt: new Date().toISOString(),
1244
- };
1245
-
1246
- // Save raw .one file alongside JSON for binary search
1247
- if (includeRaw) {
1248
- const binPath = cachePath.replace(/\.json$/, ".one");
1249
- await writeFile(binPath, buf);
1250
- }
1251
-
1252
- await writeFile(cachePath, JSON.stringify(cacheData));
1253
- upsertSectionToIndex(
1254
- db, sec.name, nb.displayName, cacheData.pages, webUrl,
1255
- buf, // always pass buf to FTS (even >50MB sections); only disk save is gated on includeRaw
1256
- cacheData.anchors,
1257
- cacheData.officialPages,
1258
- htmlTags,
1259
- accountEmail,
1260
- sec.lastModified
1261
- );
1262
- log(` [ok] ${sec.name} (${pages.length} pages)`);
1263
- emit?.({ type: "done", notebook: nb.displayName, section: sec.name, pages: pages.length, status: "ok" });
1264
- }
1265
- db.close();
1266
- log(`Sync complete. ${downloaded} downloaded, ${retagged} retagged, ${skipped} up-to-date.`);
1267
- emit?.({ type: "complete", downloaded, retagged, skipped });
1268
- }
1269
-
1270
- /**
1271
- * Build a page-level OneNote Online URL.
1272
- * Format: {sectionUrl}&wd=target({escapedTitle}|{pageGuid}/)
1273
- *
1274
- * Note: OneNote Online caches the user's last-viewed page within a section.
1275
- * When opened in a session that has previously viewed the section, OneNote may
1276
- * redirect to the cached page instead of honoring the wd=target parameter.
1277
- * The URL is still a correct page-level permalink.
1278
- */
1279
- function buildPageUrl(
1280
- sectionUrl: string,
1281
- pageTitle: string,
1282
- pageGuid?: string
1283
- ): string {
1284
- if (!pageGuid || !sectionUrl) return sectionUrl;
1285
- // OneNote escapes only `)` and `|` in titles with `\`
1286
- const escapedTitle = pageTitle
1287
- .replace(/\\/g, "\\\\")
1288
- .replace(/\)/g, "\\)")
1289
- .replace(/\|/g, "\\|");
1290
- const wd = `target(${escapedTitle}|${pageGuid}/)`;
1291
- // Strict encoding (also encode parens) to match OneNote's own URL format
1292
- const encoded = encodeURIComponent(wd).replace(
1293
- /[!'()*]/g,
1294
- (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase()
1295
- );
1296
- const separator = sectionUrl.includes("?") ? "&" : "?";
1297
- return `${sectionUrl}${separator}wd=${encoded}`;
1298
- }
1299
-
1300
- // Lazily-opened read-only handle for fast page_guid -> web_url lookups, used to
1301
- // re-resolve OneNote internal links to their current URL (surviving notebook
1302
- // moves/renames). Undefined = not yet opened, null = unavailable (no cache).
1303
- let linkLookupDb: Database | null | undefined;
1304
- let linkLookupStmt: ReturnType<Database["query"]> | null = null;
1305
-
1306
- /** Current web URL for a synced page by its page GUID, or null if not cached. */
1307
- export function lookupPageUrlByGuid(guid: string): string | null {
1308
- if (!guid) return null;
1309
- try {
1310
- if (linkLookupDb === undefined) {
1311
- linkLookupDb = new Database(SEARCH_DB_PATH, { readonly: true });
1312
- linkLookupStmt = linkLookupDb.query(
1313
- "SELECT web_url FROM pages WHERE page_guid = ? AND web_url IS NOT NULL LIMIT 1"
1314
- );
1315
- }
1316
- if (!linkLookupStmt) return null;
1317
- const row = linkLookupStmt.get(guid.toLowerCase()) as { web_url?: string } | null;
1318
- return row?.web_url ?? null;
1319
- } catch {
1320
- linkLookupDb = null;
1321
- linkLookupStmt = null;
1322
- return null;
1323
- }
1324
- }
1325
-
1326
- export async function isCacheEmpty(): Promise<boolean> {
1327
- // Also treat DB as authoritative: if there are any indexed pages, cache is not empty
1328
- try {
1329
- const db = new Database(SEARCH_DB_PATH, { readonly: true });
1330
- const r = db.query("SELECT COUNT(*) as c FROM pages").get() as { c: number } | null;
1331
- db.close();
1332
- if ((r?.c ?? 0) > 0) return false;
1333
- } catch {}
1334
- // Walk the filesystem: look for .json files up to 2 levels deep
1335
- // (legacy: .onenote/cache/<nb>/*.json; new: .onenote/cache/<account>/<nb>/*.json)
1336
- try {
1337
- const top = await readdir(CACHE_DIR);
1338
- for (const a of top) {
1339
- const aPath = join(CACHE_DIR, a);
1340
- const s = await stat(aPath);
1341
- if (!s.isDirectory()) continue;
1342
- const level1 = await readdir(aPath);
1343
- if (level1.some((f) => f.endsWith(".json"))) return false;
1344
- for (const b of level1) {
1345
- const bPath = join(aPath, b);
1346
- try {
1347
- const bs = await stat(bPath);
1348
- if (!bs.isDirectory()) continue;
1349
- const level2 = await readdir(bPath);
1350
- if (level2.some((f) => f.endsWith(".json"))) return false;
1351
- } catch {}
1352
- }
1353
- }
1354
- } catch {}
1355
- return true;
1356
- }
1357
-
1358
- /**
1359
- * Find all binary positions where `needle` appears in `buf`.
1360
- * Searches for both UTF-8 and UTF-16LE encodings.
1361
- */
1362
- function findAllInBinary(buf: Buffer, needle: string): number[] {
1363
- const results: number[] = [];
1364
- const utf8 = Buffer.from(needle, "utf-8");
1365
- let pos = 0;
1366
- while ((pos = buf.indexOf(utf8, pos)) !== -1) { results.push(pos); pos++; }
1367
- const utf16 = Buffer.from(needle, "utf16le");
1368
- pos = 0;
1369
- while ((pos = buf.indexOf(utf16, pos)) !== -1) { results.push(pos); pos += 2; }
1370
- return results;
1371
- }
1372
-
1373
- function getNearestPrecedingAnchor(
1374
- anchors: { offset: number; guid: string; title: string }[],
1375
- pos: number
1376
- ): { guid: string; title: string } | null {
1377
- let best: { guid: string; title: string } | null = null;
1378
- for (const a of anchors) {
1379
- if (a.offset <= pos) best = { guid: a.guid, title: a.title };
1380
- else break;
1381
- }
1382
- return best;
1383
- }
1384
-
1385
- /**
1386
- * Find the page that owns this binary position by checking which page title
1387
- * appears in the surrounding context. Falls back to nearest preceding anchor.
1388
- */
1389
- function findOwnerPage(
1390
- buf: Buffer,
1391
- anchors: { offset: number; guid: string; title: string }[],
1392
- pos: number
1393
- ): { guid: string; title: string } | null {
1394
- // Get a 20KB context around the match
1395
- const ctxStart = Math.max(0, pos - 10000);
1396
- const ctxEnd = Math.min(buf.length, pos + 10000);
1397
- const ctx = buf.slice(ctxStart, ctxEnd);
1398
- // Decode as both UTF-8 and UTF-16LE to catch all titles
1399
- const ctxUtf8 = ctx.toString("utf-8");
1400
- const ctxUtf16 = ctx.toString("utf16le");
1401
-
1402
- // For each known anchor, check if its title appears in context.
1403
- // Prefer the longest matching title (more specific = more likely correct).
1404
- const candidates: { anchor: typeof anchors[number]; matchLen: number }[] = [];
1405
- for (const a of anchors) {
1406
- const t = a.title.trim();
1407
- if (t.length < 4) continue;
1408
- // Use a substring of the title (first 30 chars) for matching
1409
- const probe = t.slice(0, 30);
1410
- if (ctxUtf8.includes(probe) || ctxUtf16.includes(probe)) {
1411
- candidates.push({ anchor: a, matchLen: probe.length });
1412
- }
1413
- }
1414
-
1415
- if (candidates.length > 0) {
1416
- // Return the candidate with the longest matched title
1417
- candidates.sort((a, b) => b.matchLen - a.matchLen);
1418
- return { guid: candidates[0].anchor.guid, title: candidates[0].anchor.title };
1419
- }
1420
-
1421
- // Fallback: nearest preceding anchor
1422
- return getNearestPrecedingAnchor(anchors, pos);
1423
- }
1424
-
1425
- function extractContextFromBinary(
1426
- buf: Buffer,
1427
- pos: number,
1428
- query: string
1429
- ): string {
1430
- // Try both UTF-8 and UTF-16LE; pick the one that contains the query
1431
- // Use a wider context to be sure
1432
- const queryByteLen = Math.max(
1433
- Buffer.byteLength(query, "utf-8"),
1434
- Buffer.byteLength(query, "utf16le")
1435
- );
1436
- const start = Math.max(0, pos - 200);
1437
- const end = Math.min(buf.length, pos + queryByteLen + 200);
1438
- const segment = buf.slice(start, end);
1439
-
1440
- const cleanText = (s: string): string =>
1441
- s.replace(/[\x00-\x1F\x7F\uFFFD]/g, " ").replace(/\s+/g, " ").trim();
1442
-
1443
- // Try UTF-8
1444
- const utf8Text = cleanText(segment.toString("utf-8"));
1445
- if (utf8Text.includes(query)) return utf8Text;
1446
-
1447
- // Try UTF-16LE at this offset and offset+1
1448
- const utf16Text = cleanText(segment.toString("utf16le"));
1449
- if (utf16Text.includes(query)) return utf16Text;
1450
-
1451
- // Try UTF-16LE with shifted alignment
1452
- if (segment.length > 1) {
1453
- const shifted = cleanText(segment.slice(1).toString("utf16le"));
1454
- if (shifted.includes(query)) return shifted;
1455
- }
1456
-
1457
- // Fallback: return UTF-8 even if it doesn't contain the query
1458
- return utf8Text || utf16Text;
1459
- }
1460
-
1461
- function cleanSnippet(raw: string, query: string): string {
1462
- const stripped = raw
1463
- .replace(/<[^>]{0,300}>/g, " ")
1464
- .replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&nbsp;/g, " ")
1465
- .replace(/[\x00-\x09\x0B-\x1F\x7F]/g, " "); // keep \x0A (LF) so split(/\n+/) works
1466
- const lq = query.toLowerCase();
1467
- // Split into lines, find lines that contain the query
1468
- const lines = stripped.split(/\n+/).map((l) => l.replace(/\s+/g, " ").trim()).filter(Boolean);
1469
- const matchingLines = lines.filter((l) => l.toLowerCase().includes(lq));
1470
- if (matchingLines.length === 0) return "";
1471
- // Prefer lines with better ASCII ratio (less binary garbage)
1472
- const best = matchingLines.sort((a, b) => asciiRatio(b) - asciiRatio(a))[0]!;
1473
- // If the best line is still mostly garbage, say so
1474
- if (asciiRatio(best) < 0.15) return "[binary content, no clean preview]";
1475
- // Trim to a window around the query
1476
- const idx = best.toLowerCase().indexOf(lq);
1477
- const start = Math.max(0, idx - 30);
1478
- const end = Math.min(best.length, idx + query.length + 30);
1479
- const excerpt = best.slice(start, end).trim();
1480
- return (start > 0 ? "..." : "") + excerpt + (end < best.length ? "..." : "");
1481
- }
1482
-
1483
- async function searchSection(jsonPath: string, query: string): Promise<CachedPage[]> {
1484
- const results: CachedPage[] = [];
1485
- try {
1486
- const raw = await readFile(jsonPath, "utf-8");
1487
- const data = JSON.parse(raw);
1488
-
1489
- const binPath = jsonPath.replace(/\.json$/, ".one");
1490
- let binBuf: Buffer | null = null;
1491
- try {
1492
- binBuf = await readFile(binPath);
1493
- } catch {}
1494
-
1495
- if (binBuf && data.anchors) {
1496
- const positions = findAllInBinary(binBuf, query);
1497
- const byGuid = new Map<string, { title: string; positions: number[] }>();
1498
- for (const pos of positions) {
1499
- const anchor = findOwnerPage(binBuf, data.anchors, pos);
1500
- if (!anchor) continue;
1501
- const existing = byGuid.get(anchor.guid);
1502
- if (existing) existing.positions.push(pos);
1503
- else byGuid.set(anchor.guid, { title: anchor.title, positions: [pos] });
1504
- }
1505
- const officialByGuid = new Map<string, { url: string; title: string }>();
1506
- for (const op of data.officialPages ?? []) {
1507
- if (op.guid && op.webUrl) officialByGuid.set(op.guid, { url: op.webUrl, title: op.title });
1508
- }
1509
- const bodyByGuid = new Map<string, string>();
1510
- for (const p of data.pages ?? []) {
1511
- if (p.pageGuid && p.body) bodyByGuid.set(p.pageGuid, p.body);
1512
- }
1513
- for (const [guid, info] of byGuid) {
1514
- const firstPos = info.positions[0]!;
1515
- const cleanBody = bodyByGuid.get(guid);
1516
- const rawContext = cleanBody ?? extractContextFromBinary(binBuf, firstPos, query);
1517
- const official = officialByGuid.get(guid);
1518
- const pageUrl = official?.url ?? buildPageUrl(data.webUrl, info.title, guid);
1519
- results.push({
1520
- title: official?.title ?? info.title,
1521
- body: cleanSnippet(rawContext, query),
1522
- section: data.section,
1523
- notebook: data.notebook,
1524
- webUrl: pageUrl,
1525
- pageGuid: guid,
1526
- });
1527
- }
1528
- } else {
1529
- const lowerQuery = query.toLowerCase();
1530
- for (const page of data.pages ?? []) {
1531
- if (page.body?.toLowerCase().includes(lowerQuery)) {
1532
- const pageUrl = page.officialUrl ?? buildPageUrl(data.webUrl, page.title, page.pageGuid);
1533
- results.push({
1534
- title: page.title,
1535
- body: cleanSnippet(page.body, query),
1536
- section: data.section,
1537
- notebook: data.notebook,
1538
- webUrl: pageUrl,
1539
- pageGuid: page.pageGuid,
1540
- });
1541
- }
1542
- }
1543
- }
1544
- } catch {}
1545
- return results;
1546
- }
1547
-
1548
- export async function searchLocal(
1549
- query: string,
1550
- { offset = 0, limit = 100, notebook, section, account, since }: { offset?: number; limit?: number; notebook?: string; section?: string; account?: string; since?: string } = {}
1551
- ): Promise<CachedPage[]> {
1552
- const { ftsQuery, hasTodo, hasDone, hasCheckbox, tagFilters } = parseTagsFromQuery(query);
1553
- // Use FTS5 index if available (built during sync)
1554
- try {
1555
- const db = new Database(SEARCH_DB_PATH, { readonly: true });
1556
-
1557
- type Row = { section: string; notebook: string; title: string; body: string; web_url: string; page_guid: string; tag_lines: string | null; account: string | null; last_modified: string | null };
1558
- let rows: Row[];
1559
-
1560
- // Build tag filter SQL: each tagFilter value needs tags LIKE '%|value|%'
1561
- const addTagConditions = (conditions: string[], params: (string | number | null)[], prefix = "") => {
1562
- if (hasTodo) conditions.push(`${prefix}has_todo = 1`);
1563
- if (hasDone) conditions.push(`${prefix}has_done = 1`);
1564
- if (hasCheckbox) conditions.push(`(${prefix}has_todo = 1 OR ${prefix}has_done = 1)`);
1565
- for (const tagVal of tagFilters) {
1566
- conditions.push(`${prefix}tags LIKE ?`);
1567
- params.push(`%|${tagVal}|%`);
1568
- }
1569
- if (since) {
1570
- conditions.push(`${prefix}last_modified >= ?`);
1571
- params.push(since);
1572
- }
1573
- };
1574
-
1575
- if (ftsQuery) {
1576
- const ftsParam = buildFtsParam(ftsQuery);
1577
- const conditions: string[] = ["pages_fts MATCH ?"];
1578
- const params: (string | number | null)[] = [ftsParam];
1579
- if (notebook) { conditions.push("p.notebook LIKE ?"); params.push(`%${notebook}%`); }
1580
- if (section) { conditions.push("p.section LIKE ?"); params.push(`%${section}%`); }
1581
- if (account) { conditions.push("p.account = ?"); params.push(account); }
1582
- addTagConditions(conditions, params, "p.");
1583
- params.push(limit, offset);
1584
- rows = db.query<Row, (string | number | null)[]>(
1585
- `SELECT p.section, p.notebook, p.title, p.body, p.web_url, p.page_guid, p.tag_lines, p.account, p.last_modified
1586
- FROM pages_fts f JOIN pages p ON f.rowid = p.id
1587
- WHERE ${conditions.join(" AND ")}
1588
- ORDER BY rank, (p.account IS NULL), p.account, p.last_modified DESC, p.notebook, p.section, p.title
1589
- LIMIT ? OFFSET ?`
1590
- ).all(...params);
1591
- } else {
1592
- const conditions: string[] = [];
1593
- const params: (string | number | null)[] = [];
1594
- if (notebook) { conditions.push("notebook LIKE ?"); params.push(`%${notebook}%`); }
1595
- if (section) { conditions.push("section LIKE ?"); params.push(`%${section}%`); }
1596
- if (account) { conditions.push("account = ?"); params.push(account); }
1597
- addTagConditions(conditions, params);
1598
- const where = conditions.length ? `WHERE ${conditions.join(" AND ")}` : "";
1599
- params.push(limit, offset);
1600
- // Tag-only queries: prefer pages with tag_lines, then recent non-null accounts first
1601
- rows = db.query<Row, (string | number | null)[]>(
1602
- `SELECT section, notebook, title, body, web_url, page_guid, tag_lines, account, last_modified FROM pages ${where}
1603
- ORDER BY (tag_lines IS NOT NULL) DESC, (account IS NULL), account, last_modified DESC, notebook, section, title
1604
- LIMIT ? OFFSET ?`
1605
- ).all(...params);
1606
- }
1607
-
1608
- db.close();
1609
- return rows.map((r) => {
1610
- let tagLines: Array<{ tag: string; text: string }> | undefined;
1611
- if (r.tag_lines) { try { tagLines = JSON.parse(r.tag_lines); } catch {} }
1612
- return {
1613
- title: r.title,
1614
- body: ftsQuery ? cleanSnippet(r.body, ftsQuery) : r.body?.split("\n")[0] ?? "",
1615
- section: r.section,
1616
- notebook: r.notebook,
1617
- webUrl: r.web_url,
1618
- pageGuid: r.page_guid,
1619
- account: r.account,
1620
- lastModified: r.last_modified,
1621
- tagLines,
1622
- };
1623
- });
1624
- } catch {
1625
- // DB not found or FTS error — fall back to file scan
1626
- }
1627
-
1628
- // File-scan fallback (used before first sync or if DB is missing)
1629
- let nbDirs: string[];
1630
- try {
1631
- nbDirs = await readdir(CACHE_DIR);
1632
- } catch {
1633
- return [];
1634
- }
1635
-
1636
- const jsonPaths: string[] = [];
1637
- for (const nbName of nbDirs) {
1638
- const nbDir = join(CACHE_DIR, nbName);
1639
- try {
1640
- const s = await stat(nbDir);
1641
- if (!s.isDirectory()) continue;
1642
- const files = await readdir(nbDir);
1643
- for (const file of files) {
1644
- if (file.endsWith(".json")) jsonPaths.push(join(nbDir, file));
1645
- }
1646
- } catch {
1647
- continue;
1648
- }
1649
- }
1650
-
1651
- const CONCURRENCY = 20;
1652
- const allResults: CachedPage[] = [];
1653
- for (let i = 0; i < jsonPaths.length; i += CONCURRENCY) {
1654
- const chunk = jsonPaths.slice(i, i + CONCURRENCY);
1655
- const chunkResults = await Promise.all(chunk.map((p) => searchSection(p, query)));
1656
- for (const r of chunkResults) allResults.push(...r);
1657
- }
1658
-
1659
- return allResults;
1660
- }
1661
-
1662
- export async function rebuildSearchIndex(onProgress?: (msg: string) => void): Promise<void> {
1663
- const log = onProgress ?? console.log;
1664
- await ensureDir(join(PKG_ROOT, ".onenote"));
1665
- // Drop and recreate: contentless FTS5 DELETE has no effect on the posting list,
1666
- // and pages table truncation doesn't sync to FTS shadow tables.
1667
- const { unlink } = await import("node:fs/promises");
1668
- for (const ext of ["", "-shm", "-wal"]) {
1669
- try { await unlink(SEARCH_DB_PATH + ext); } catch {}
1670
- }
1671
- const db = openSearchDb();
1672
-
1673
- let nbDirs: string[];
1674
- try {
1675
- nbDirs = await readdir(CACHE_DIR);
1676
- } catch {
1677
- db.close();
1678
- return;
1679
- }
1680
-
1681
- let count = 0;
1682
- for (const nbName of nbDirs) {
1683
- const nbDir = join(CACHE_DIR, nbName);
1684
- try {
1685
- const s = await stat(nbDir);
1686
- if (!s.isDirectory()) continue;
1687
- const files = await readdir(nbDir);
1688
- for (const file of files) {
1689
- if (!file.endsWith(".json")) continue;
1690
- try {
1691
- const jsonPath = join(nbDir, file);
1692
- const raw = await readFile(jsonPath, "utf-8");
1693
- const data = JSON.parse(raw);
1694
- let binBuf: Buffer | undefined;
1695
- try { binBuf = await readFile(jsonPath.replace(/\.json$/, ".one")); } catch {}
1696
- upsertSectionToIndex(
1697
- db, data.section, data.notebook, data.pages ?? [], data.webUrl ?? "",
1698
- binBuf, data.anchors, data.officialPages,
1699
- undefined, data.account ?? undefined, data.lastModified ?? undefined
1700
- );
1701
- count++;
1702
- } catch {}
1703
- }
1704
- } catch {}
1705
- }
1706
-
1707
- db.close();
1708
- log(`Search index rebuilt: ${count} sections indexed.`);
1709
- }