onenote-cli 0.2.1-win32-arm64 → 0.2.1

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/index.ts ADDED
@@ -0,0 +1,1176 @@
1
+ #!/usr/bin/env bun
2
+ import { createHash } from "node:crypto";
3
+ import yargs from "yargs";
4
+ import { hideBin } from "yargs/helpers";
5
+ import * as graph from "./graph";
6
+ import { login, logout, logoutAll, whoami, listAccounts } from "./auth";
7
+ import { syncCache, searchLocal, isCacheEmpty, rebuildSearchIndex, SEARCH_DB_PATH, parseTagsFromQuery, TAG_ALIASES, lookupPageUrlByGuid } from "./cache";
8
+ import { stat } from "node:fs/promises";
9
+ import { markdownToHtml } from "./markdown";
10
+ import { setLinkResolver, buildOneNoteWebUrl } from "./read-render";
11
+
12
+ const isTTY = process.stdout.isTTY ?? false;
13
+
14
+ // Re-resolve OneNote internal links to their *current* URL before rendering:
15
+ // 1) the local sync cache maps the page GUID → the URL Graph last reported
16
+ // (survives the notebook being moved or renamed), then
17
+ // 2) fall back to re-resolving just the notebook's base URL by name via Graph.
18
+ // Returning null lets read-render rebuild the URL from the link's own base-path.
19
+ setLinkResolver(async (info) => {
20
+ const cached = info.pageId ? lookupPageUrlByGuid(info.pageId) : null;
21
+ if (cached) return cached;
22
+ const currentBase = await graph.currentNotebookBaseUrl(info.basePath);
23
+ if (currentBase && currentBase !== info.basePath) {
24
+ return buildOneNoteWebUrl({ ...info, basePath: currentBase });
25
+ }
26
+ return null;
27
+ });
28
+
29
+ // ANSI color helpers (only when TTY)
30
+ const bold = (s: string) => (isTTY ? `\x1b[1m${s}\x1b[0m` : s);
31
+ const dim = (s: string) => (isTTY ? `\x1b[2m${s}\x1b[0m` : s);
32
+ const yellow = (s: string) => (isTTY ? `\x1b[33m${s}\x1b[0m` : s);
33
+ const cyan = (s: string) => (isTTY ? `\x1b[36m${s}\x1b[0m` : s);
34
+ const green = (s: string) => (isTTY ? `\x1b[32m${s}\x1b[0m` : s);
35
+ const magenta = (s: string) => (isTTY ? `\x1b[35m${s}\x1b[0m` : s);
36
+ const pageUpdateActions = ["append", "insert", "prepend", "replace"] as const;
37
+ const pageInsertPositions = ["before", "after"] as const;
38
+
39
+ // OSC 8 hyperlink (clickable in supported terminals), markdown in non-TTY
40
+ function link(url: string, text: string): string {
41
+ if (!isTTY) return `[${text}](${url})`;
42
+ return `\x1b]8;;${url}\x1b\\${text}\x1b]8;;\x1b\\`;
43
+ }
44
+
45
+ function contentSha4(html: string): string {
46
+ return createHash("sha256").update(html).digest("hex").slice(0, 4);
47
+ }
48
+
49
+ async function confirmPageSha(ref: string, providedSha: string | undefined, verb: string) {
50
+ const result = await graph.readOneNoteUrl(ref, { downloadAssets: false });
51
+ if (result.type !== "page" || !result.html) {
52
+ throw new Error(`'${ref}' is not a page — ${verb} only operates on pages.`);
53
+ }
54
+ const sha = contentSha4(result.html);
55
+
56
+ if (!providedSha) {
57
+ console.log(bold(cyan(result.title)));
58
+ if (result.breadcrumb) console.log(dim(result.breadcrumb));
59
+ console.log(dim("─".repeat(Math.min(result.title.length + 10, 60))));
60
+ console.log(result.content);
61
+ console.error("");
62
+ console.error(yellow(`Dry run. To ${verb}, re-run with --sha=${sha}`));
63
+ return { confirmed: false as const, sha };
64
+ }
65
+ if (providedSha !== sha) {
66
+ throw new Error(
67
+ `sha mismatch: expected '${sha}', got '${providedSha}'. Re-read the page — content may have changed.`
68
+ );
69
+ }
70
+ return { confirmed: true as const, sha };
71
+ }
72
+
73
+ type ListItem = { name: string; url?: string; subtitle?: string };
74
+
75
+ function printList(items: ListItem[]) {
76
+ if (!items || items.length === 0) {
77
+ console.log("No results found.");
78
+ return;
79
+ }
80
+ for (const it of items) {
81
+ const main = it.url ? link(it.url, it.name) : it.name;
82
+ const sub = it.subtitle ? ` ${dim(it.subtitle)}` : "";
83
+ console.log(`- ${main}${sub}`);
84
+ }
85
+ }
86
+
87
+ function toListItem(raw: any, type?: "notebook" | "section" | "page"): ListItem {
88
+ const url =
89
+ raw?.links?.oneNoteWebUrl?.href
90
+ ?? raw?.links?.oneNoteClientUrl?.href
91
+ ?? raw?.webUrl
92
+ ?? "";
93
+ const name = raw?.displayName ?? raw?.title ?? "(untitled)";
94
+ const date = raw?.lastModifiedDateTime ?? raw?.createdDateTime;
95
+ const typeSuffix = type ? dim(` .${type}`) : "";
96
+ let locationHint: string | undefined;
97
+ if (type === "notebook" && url) {
98
+ try {
99
+ const pathname = decodeURIComponent(new URL(url).pathname.replace(/\/$/, ""));
100
+ // Strip /personal/{user}/Documents/ prefix, then show parent folder only if non-standard
101
+ const afterDocuments = pathname.replace(/^\/[^/]+\/[^/]+\/Documents\//, "");
102
+ const segments = afterDocuments.split("/");
103
+ // Standard path: Notebooks/{name} — hide, not informative
104
+ if (segments[0] !== "Notebooks") {
105
+ // Show parent folder(s) only (everything except the last segment)
106
+ const parent = segments.slice(0, -1).join("/");
107
+ locationHint = parent ? `${parent}/` : "Documents/";
108
+ }
109
+ } catch {}
110
+ }
111
+ const parts = [locationHint, date ? String(date).slice(0, 10) : undefined].filter(Boolean);
112
+ return { name: `${name}${typeSuffix}`, url, subtitle: parts.length ? parts.join(" ") : undefined };
113
+ }
114
+
115
+ function outputList(items: any[], argv: { json?: boolean; limit?: number }, type?: "notebook" | "section" | "page") {
116
+ const limited = typeof argv.limit === "number" ? items.slice(0, argv.limit) : items;
117
+ if (argv.json) {
118
+ console.log(JSON.stringify(limited, null, 2));
119
+ return;
120
+ }
121
+ printList(limited.map((r) => toListItem(r, type)));
122
+ }
123
+
124
+ function formatTable(items: any[], columns: { key: string; label: string }[]) {
125
+ if (!items || items.length === 0) {
126
+ console.log("No results found.");
127
+ return;
128
+ }
129
+ const widths = columns.map((col) =>
130
+ Math.max(col.label.length, ...items.map((item) => String(item[col.key] ?? "").length))
131
+ );
132
+ const header = columns.map((col, i) => col.label.padEnd(widths[i])).join(" ");
133
+ const separator = widths.map((w) => "-".repeat(w)).join(" ");
134
+ console.log(header);
135
+ console.log(separator);
136
+ for (const item of items) {
137
+ const row = columns.map((col, i) => String(item[col.key] ?? "").padEnd(widths[i])).join(" ");
138
+ console.log(row);
139
+ }
140
+ }
141
+
142
+ function normalizeRef(value: string | undefined): string | undefined {
143
+ if (typeof value !== "string") return undefined;
144
+ return value.replace(/^["']|["']$/g, "");
145
+ }
146
+
147
+ function renderHtmlContent(content: string, markdown?: boolean): string {
148
+ return markdown ? markdownToHtml(content) : content;
149
+ }
150
+
151
+ function renderHtmlBody(content: string | undefined, markdown?: boolean): string {
152
+ if (!content || content.trim() === "") return "<p></p>";
153
+ return renderHtmlContent(content, markdown);
154
+ }
155
+
156
+ yargs(hideBin(process.argv))
157
+ .scriptName("onenote")
158
+ .usage("$0 <command> [options]")
159
+ .demandCommand(1)
160
+
161
+ // --- top-level ls (auto-detects depth by path segments) ---
162
+ .command(
163
+ ["ls [path]", "list [path]"],
164
+ "List notebooks, sections, or pages based on path depth",
165
+ (y) =>
166
+ y.positional("path", {
167
+ type: "string",
168
+ describe: "Path: empty=notebooks, 'nb'=sections, 'nb/sec'=pages",
169
+ }),
170
+ async (argv) => {
171
+ const path = normalizeRef(argv.path as string | undefined);
172
+ const segments = path ? path.split("/").filter(Boolean) : [];
173
+ if (segments.length === 0) {
174
+ const notebooks = await graph.listNotebooks();
175
+ printList((notebooks ?? []).map((r) => toListItem(r, "notebook")));
176
+ } else if (segments.length === 1) {
177
+ const sections = await graph.listSections(path);
178
+ printList((sections ?? []).map((r) => toListItem(r, "section")));
179
+ } else if (segments.length === 2) {
180
+ const pages = await graph.listPages(path);
181
+ printList((pages ?? []).map((r) => toListItem(r, "page")));
182
+ } else {
183
+ throw new Error(
184
+ `Path '${path}' points to a page, not a listable container. Use 'onenote read ${path}' to view it.`
185
+ );
186
+ }
187
+ }
188
+ )
189
+
190
+ // --- notebooks ---
191
+ .command(
192
+ "notebooks",
193
+ "Manage notebooks",
194
+ (yargs) =>
195
+ yargs
196
+ .command(
197
+ ["list", "ls"],
198
+ "List all notebooks",
199
+ (y) =>
200
+ y
201
+ .option("json", { type: "boolean", describe: "Output JSON" })
202
+ .option("limit", { type: "number", describe: "Max items (default: all)" }),
203
+ async (argv) => {
204
+ const notebooks = await graph.listNotebooks();
205
+ outputList(notebooks ?? [], argv, "notebook");
206
+ }
207
+ )
208
+ .command(
209
+ "get <ref>",
210
+ "Get a notebook by name, path, ID, or URL",
211
+ (y) => y.positional("ref", { type: "string", demandOption: true }),
212
+ async (argv) => {
213
+ const nb = await graph.getNotebook(normalizeRef(argv.ref as string)!);
214
+ console.log(JSON.stringify(nb, null, 2));
215
+ }
216
+ )
217
+ .command(
218
+ "create <name>",
219
+ "Create a new notebook",
220
+ (y) => y.positional("name", { type: "string", demandOption: true }),
221
+ async (argv) => {
222
+ const nb = await graph.createNotebook(argv.name as string);
223
+ console.log("Created notebook:", nb.displayName);
224
+ console.log("ID:", nb.id);
225
+ }
226
+ )
227
+ .command(
228
+ "rename <ref> <name>",
229
+ "Rename a notebook",
230
+ (y) =>
231
+ y
232
+ .positional("ref", { type: "string", demandOption: true })
233
+ .positional("name", { type: "string", demandOption: true }),
234
+ async (argv) => {
235
+ const nb = await graph.renameNotebook(normalizeRef(argv.ref as string)!, argv.name as string);
236
+ console.log("Notebook renamed to:", nb.displayName);
237
+ }
238
+ )
239
+ .demandCommand(1),
240
+ () => {}
241
+ )
242
+
243
+ // --- sections ---
244
+ .command(
245
+ "sections",
246
+ "Manage sections",
247
+ (yargs) =>
248
+ yargs
249
+ .command(
250
+ ["list [ref]", "ls [ref]"],
251
+ "List sections",
252
+ (y) =>
253
+ y
254
+ .positional("ref", { type: "string", describe: "Notebook name, path, ID, or URL" })
255
+ .option("notebook", { type: "string", alias: ["n", "notebook-id"], describe: "Filter by notebook name, path, ID, or URL" })
256
+ .option("json", { type: "boolean", describe: "Output JSON" })
257
+ .option("limit", { type: "number", describe: "Max items (default: all)" }),
258
+ async (argv) => {
259
+ const notebookRef = normalizeRef((argv.ref as string | undefined) ?? (argv.notebook as string | undefined));
260
+ const sections = await graph.listSections(notebookRef);
261
+ outputList(sections ?? [], argv, "section");
262
+ }
263
+ )
264
+ .command(
265
+ "get <ref>",
266
+ "Get a section by path, ID, or URL",
267
+ (y) => y.positional("ref", { type: "string", demandOption: true }),
268
+ async (argv) => {
269
+ const section = await graph.getSection(normalizeRef(argv.ref as string)!);
270
+ console.log(JSON.stringify(section, null, 2));
271
+ }
272
+ )
273
+ .command(
274
+ "create",
275
+ "Create a new section in a notebook",
276
+ (y) =>
277
+ y
278
+ .option("notebook", { type: "string", alias: ["n", "notebook-id"], demandOption: true, describe: "Notebook name, path, ID, or URL" })
279
+ .option("name", { type: "string", demandOption: true, describe: "Section name" }),
280
+ async (argv) => {
281
+ const section = await graph.createSection(
282
+ normalizeRef(argv.notebook as string)!,
283
+ argv.name as string
284
+ );
285
+ console.log("Created section:", section.displayName);
286
+ console.log("ID:", section.id);
287
+ }
288
+ )
289
+ .command(
290
+ "rename <ref> <name>",
291
+ "Rename a section",
292
+ (y) =>
293
+ y
294
+ .positional("ref", { type: "string", demandOption: true })
295
+ .positional("name", { type: "string", demandOption: true }),
296
+ async (argv) => {
297
+ const section = await graph.renameSection(normalizeRef(argv.ref as string)!, argv.name as string);
298
+ console.log("Section renamed to:", section.displayName);
299
+ }
300
+ )
301
+ .demandCommand(1),
302
+ () => {}
303
+ )
304
+
305
+ // --- section-groups ---
306
+ .command(
307
+ "section-groups",
308
+ "Manage section groups",
309
+ (yargs) =>
310
+ yargs
311
+ .command(
312
+ ["list [ref]", "ls [ref]"],
313
+ "List section groups",
314
+ (y) =>
315
+ y
316
+ .positional("ref", { type: "string", describe: "Notebook name, path, ID, or URL" })
317
+ .option("notebook", { type: "string", alias: ["n", "notebook-id"], describe: "Filter by notebook name, path, ID, or URL" })
318
+ .option("json", { type: "boolean", describe: "Output JSON" })
319
+ .option("limit", { type: "number", describe: "Max items (default: all)" }),
320
+ async (argv) => {
321
+ const notebookRef = normalizeRef((argv.ref as string | undefined) ?? (argv.notebook as string | undefined));
322
+ const groups = await graph.listSectionGroups(notebookRef);
323
+ outputList(groups ?? [], argv);
324
+ }
325
+ )
326
+ .demandCommand(1),
327
+ () => {}
328
+ )
329
+
330
+ // --- pages ---
331
+ .command(
332
+ "pages",
333
+ "Manage pages",
334
+ (yargs) =>
335
+ yargs
336
+ .command(
337
+ ["list [ref]", "ls [ref]"],
338
+ "List pages",
339
+ (y) =>
340
+ y
341
+ .positional("ref", { type: "string", describe: "Section name, path (notebook/section), ID, or URL" })
342
+ .option("section", { type: "string", alias: ["s", "section-id"], describe: "Filter by section name, path, ID, or URL" })
343
+ .option("json", { type: "boolean", describe: "Output JSON" })
344
+ .option("limit", { type: "number", describe: "Max items (default: all)" }),
345
+ async (argv) => {
346
+ const sectionRef = normalizeRef((argv.ref as string | undefined) ?? (argv.section as string | undefined));
347
+ const pages = await graph.listPages(sectionRef);
348
+ outputList(pages ?? [], argv, "page");
349
+ }
350
+ )
351
+ .command(
352
+ "get <ref>",
353
+ "Get page metadata (accepts path, page ID, or OneNote URL)",
354
+ (y) => y.positional("ref", { type: "string", demandOption: true }),
355
+ async (argv) => {
356
+ const page = await graph.getPage(normalizeRef(argv.ref as string)!);
357
+ console.log(JSON.stringify(page, null, 2));
358
+ }
359
+ )
360
+ .command(
361
+ "content <ref>",
362
+ "Get page HTML content (deprecated: use 'onenote read <ref> --html')",
363
+ (y) => y.positional("ref", { type: "string", demandOption: true }),
364
+ async (argv) => {
365
+ console.error(dim("[deprecated] Use 'onenote read <ref> --html' instead."));
366
+ const html = await graph.getPageContent(normalizeRef(argv.ref as string)!);
367
+ console.log(html);
368
+ }
369
+ )
370
+ .command(
371
+ "create",
372
+ "Create a new page",
373
+ (y) =>
374
+ y
375
+ .option("section", { type: "string", alias: ["s", "section-id"], demandOption: true, describe: "Section name, path, ID, or URL" })
376
+ .option("title", { type: "string", alias: "t", demandOption: true, describe: "Page title" })
377
+ .option("body", { type: "string", alias: "b", describe: "HTML body content. Use data-tag to add OneNote tags: data-tag=\"to-do\" (checkbox), data-tag=\"star\", data-tag=\"question\", data-tag=\"important\", data-tag=\"critical\", data-tag=\"idea\", data-tag=\"contact\", data-tag=\"definition\", data-tag=\"highlight\", data-tag=\"password\", data-tag=\"remember-for-later\", data-tag=\"to-do:completed\" (checked)" })
378
+ .option("md", { type: "boolean", describe: "Treat --body as Markdown and convert it to HTML" }),
379
+ async (argv) => {
380
+ const page = await graph.createPage(
381
+ normalizeRef(argv.section as string)!,
382
+ argv.title as string,
383
+ renderHtmlBody(argv.body as string | undefined, argv.md as boolean | undefined)
384
+ );
385
+ console.log("Created page:", page.title);
386
+ console.log("ID:", page.id);
387
+ }
388
+ )
389
+ .command(
390
+ "delete <ref>",
391
+ "Delete a page. Without --sha, dry-runs and prints content + sha.",
392
+ (y) =>
393
+ y
394
+ .positional("ref", { type: "string", demandOption: true })
395
+ .option("sha", {
396
+ type: "string",
397
+ describe: "4-char content sha from 'onenote read' to confirm deletion",
398
+ }),
399
+ async (argv) => {
400
+ const ref = normalizeRef(argv.ref as string)!;
401
+ const { confirmed } = await confirmPageSha(ref, argv.sha as string | undefined, "delete");
402
+ if (!confirmed) return;
403
+ await graph.deletePage(ref);
404
+ console.log(green("Page deleted."));
405
+ }
406
+ )
407
+ .command(
408
+ "rename <ref> <title>",
409
+ "Rename a page (accepts path, page ID, or OneNote URL)",
410
+ (y) =>
411
+ y
412
+ .positional("ref", { type: "string", demandOption: true })
413
+ .positional("title", { type: "string", demandOption: true }),
414
+ async (argv) => {
415
+ await graph.renamePage(
416
+ normalizeRef(argv.ref as string)!,
417
+ argv.title as string
418
+ );
419
+ console.log("Page renamed to:", argv.title);
420
+ }
421
+ )
422
+ .command(
423
+ "append <ref>",
424
+ "Append HTML content to a page's body (accepts path, page ID, or OneNote URL). WARNING: the Microsoft Graph append API re-parses the whole page and may reformat or strip styles from existing content.",
425
+ (y) =>
426
+ y
427
+ .positional("ref", { type: "string", demandOption: true })
428
+ .option("content", { type: "string", alias: "c", demandOption: true, describe: "HTML content to append" })
429
+ .option("md", { type: "boolean", describe: "Treat --content as Markdown and convert it to HTML" }),
430
+ async (argv) => {
431
+ await graph.appendToPage(
432
+ normalizeRef(argv.ref as string)!,
433
+ renderHtmlContent(argv.content as string, argv.md as boolean | undefined)
434
+ );
435
+ console.log("Appended to page.");
436
+ }
437
+ )
438
+ .command(
439
+ "update <ref>",
440
+ "Apply a raw Graph page PATCH command (accepts path, page ID, or OneNote URL)",
441
+ (y) =>
442
+ y
443
+ .positional("ref", { type: "string", demandOption: true })
444
+ .option("target", {
445
+ type: "string",
446
+ alias: "t",
447
+ demandOption: true,
448
+ describe: 'Target selector: "body", "title", or "#element-id"',
449
+ })
450
+ .option("action", {
451
+ type: "string",
452
+ alias: "a",
453
+ choices: pageUpdateActions,
454
+ demandOption: true,
455
+ describe: "Patch action",
456
+ })
457
+ .option("position", {
458
+ type: "string",
459
+ alias: "p",
460
+ choices: pageInsertPositions,
461
+ describe: "Required when --action=insert",
462
+ })
463
+ .option("content", {
464
+ type: "string",
465
+ alias: "c",
466
+ demandOption: true,
467
+ describe: "HTML content to apply",
468
+ })
469
+ .option("md", { type: "boolean", describe: "Treat --content as Markdown and convert it to HTML" })
470
+ .option("sha", {
471
+ type: "string",
472
+ describe: "4-char content sha from 'onenote read' (required for --action=replace)",
473
+ })
474
+ .check((argv) => {
475
+ if (argv.action === "insert" && !argv.position) {
476
+ throw new Error("--position is required when --action=insert.");
477
+ }
478
+ if (argv.action !== "insert" && argv.position) {
479
+ throw new Error("--position can only be used when --action=insert.");
480
+ }
481
+ if (argv.md && argv.target === "title") {
482
+ throw new Error("--md cannot be used with --target=title (titles are plain text).");
483
+ }
484
+ return true;
485
+ }),
486
+ async (argv) => {
487
+ const ref = normalizeRef(argv.ref as string)!;
488
+ if (argv.action === "replace") {
489
+ const { confirmed } = await confirmPageSha(ref, argv.sha as string | undefined, "replace");
490
+ if (!confirmed) return;
491
+ }
492
+ const command: graph.PageUpdateCommand = {
493
+ target: argv.target as string,
494
+ action: argv.action as graph.PageUpdateCommand["action"],
495
+ content: renderHtmlContent(argv.content as string, argv.md as boolean | undefined),
496
+ };
497
+ if (argv.position) {
498
+ command.position = argv.position as graph.PageUpdateCommand["position"];
499
+ }
500
+ await graph.updatePage(ref, [command]);
501
+ console.log(green("Page updated."));
502
+ }
503
+ )
504
+ .demandCommand(1),
505
+ () => {}
506
+ )
507
+
508
+ // --- rm (delete page by ref; requires --sha confirmation) ---
509
+ .command(
510
+ ["rm <ref>", "delete <ref>"],
511
+ "Delete a page. Without --sha, dry-runs and prints content + sha.",
512
+ (y) =>
513
+ y
514
+ .positional("ref", { type: "string", demandOption: true })
515
+ .option("sha", {
516
+ type: "string",
517
+ describe: "4-char content sha from 'onenote read' to confirm deletion",
518
+ }),
519
+ async (argv) => {
520
+ const ref = normalizeRef(argv.ref as string)!;
521
+ const { confirmed } = await confirmPageSha(ref, argv.sha as string | undefined, "delete");
522
+ if (!confirmed) return;
523
+ await graph.deletePage(ref);
524
+ console.log(green("Page deleted."));
525
+ }
526
+ )
527
+
528
+ // --- cp (copy section into another notebook; non-destructive) ---
529
+ .command(
530
+ "cp <src> <dst>",
531
+ "Copy a section into another notebook (non-destructive; source remains)",
532
+ (y) =>
533
+ y
534
+ .positional("src", { type: "string", demandOption: true, describe: "Source section (path/ID/URL)" })
535
+ .positional("dst", { type: "string", demandOption: true, describe: "Destination notebook (path/ID/URL)" }),
536
+ async (argv) => {
537
+ const src = normalizeRef(argv.src as string)!;
538
+ const dst = normalizeRef(argv.dst as string)!;
539
+ const { operationUrl } = await graph.copySectionToNotebook(src, dst);
540
+ console.log(dim(`Operation: ${operationUrl}`));
541
+ const result = await graph.waitForOperation(operationUrl, {
542
+ onProgress: (s) => console.log(dim(` status: ${s}`)),
543
+ });
544
+ if (result.status === "failed") {
545
+ throw new Error(`Copy failed: ${JSON.stringify(result.error)}`);
546
+ }
547
+ console.log(green("Copy completed."));
548
+ if (result.resourceLocation) console.log(`New section: ${result.resourceLocation}`);
549
+ console.log(
550
+ dim("Source section was NOT deleted. Verify the copy, then 'onenote rm' the source manually if desired.")
551
+ );
552
+ }
553
+ )
554
+
555
+ // --- rename (by ref; depth-dispatched) ---
556
+ .command(
557
+ "rename <ref> <name>",
558
+ "Rename a notebook, section, or page (depth inferred from path)",
559
+ (y) =>
560
+ y
561
+ .positional("ref", { type: "string", demandOption: true })
562
+ .positional("name", { type: "string", demandOption: true }),
563
+ async (argv) => {
564
+ const ref = normalizeRef(argv.ref as string)!;
565
+ const name = argv.name as string;
566
+ const isUrl = ref.includes("://");
567
+ const segments = isUrl ? [] : ref.split("/").filter(Boolean);
568
+ const isGraphId = !isUrl && /^[0-9]-[0-9a-f-]{10,}$/i.test(ref);
569
+ if (isUrl || isGraphId) {
570
+ throw new Error(
571
+ "rename with a raw ID/URL is ambiguous. Use 'notebooks rename', 'sections rename', or 'pages rename' instead."
572
+ );
573
+ }
574
+ if (segments.length === 1) {
575
+ const nb = await graph.renameNotebook(ref, name);
576
+ console.log("Notebook renamed to:", nb.displayName);
577
+ } else if (segments.length === 2) {
578
+ const sec = await graph.renameSection(ref, name);
579
+ console.log("Section renamed to:", sec.displayName);
580
+ } else {
581
+ await graph.renamePage(ref, name);
582
+ console.log("Page renamed to:", name);
583
+ }
584
+ }
585
+ )
586
+
587
+ // --- open (launch in browser) ---
588
+ .command(
589
+ "open <ref>",
590
+ "Open a notebook, section, or page in the browser",
591
+ (y) => y.positional("ref", { type: "string", demandOption: true }),
592
+ async (argv) => {
593
+ const ref = normalizeRef(argv.ref as string)!;
594
+ const isUrl = ref.includes("://");
595
+ const segments = isUrl ? [] : ref.split("/").filter(Boolean);
596
+ const isGraphId = !isUrl && /^[0-9]-[0-9a-f-]{10,}$/i.test(ref);
597
+ let url: string | undefined;
598
+ if (isUrl) {
599
+ url = ref;
600
+ } else if (isGraphId) {
601
+ // Page IDs start with "1-"; notebook/section IDs start with "0-" (ambiguous).
602
+ if (ref.startsWith("1-")) {
603
+ const page = await graph.getPage(ref);
604
+ url = page?.links?.oneNoteWebUrl?.href ?? page?.links?.oneNoteClientUrl?.href;
605
+ } else {
606
+ throw new Error(
607
+ "open with a raw 0-* ID is ambiguous (notebook or section). Use 'notebooks get' / 'sections get' to fetch the URL, or pass a path."
608
+ );
609
+ }
610
+ } else if (segments.length === 1) {
611
+ const nb = await graph.getNotebook(ref);
612
+ url = nb?.links?.oneNoteWebUrl?.href ?? nb?.links?.oneNoteClientUrl?.href;
613
+ } else if (segments.length === 2) {
614
+ const sec = await graph.getSection(ref);
615
+ url = sec?.links?.oneNoteWebUrl?.href ?? sec?.links?.oneNoteClientUrl?.href;
616
+ } else {
617
+ const page = await graph.getPage(ref);
618
+ url = page?.links?.oneNoteWebUrl?.href ?? page?.links?.oneNoteClientUrl?.href;
619
+ }
620
+ if (!url) throw new Error(`Could not resolve URL for '${ref}'.`);
621
+ const openerArgs =
622
+ process.platform === "darwin"
623
+ ? ["open", url]
624
+ : process.platform === "win32"
625
+ ? ["cmd", "/c", "start", "", url]
626
+ : ["xdg-open", url];
627
+ const proc = Bun.spawn(openerArgs, { stdout: "inherit", stderr: "inherit" });
628
+ await proc.exited;
629
+ console.log(url);
630
+ }
631
+ )
632
+
633
+ // --- read ---
634
+ .command(
635
+ "read <url>",
636
+ "Read a OneNote page, section, or notebook by path (nb/sec/page), ID, or URL",
637
+ (y) =>
638
+ y
639
+ .positional("url", { type: "string", demandOption: true })
640
+ .option("html", { type: "boolean", describe: "Output raw HTML instead of text" }),
641
+ async (argv) => {
642
+ const url = (argv.url as string).replace(/^["']|["']$/g, "");
643
+ const result = await graph.readOneNoteUrl(url, {
644
+ downloadAssets: !argv.html,
645
+ });
646
+
647
+ if (argv.html && result.html) {
648
+ console.log(result.html);
649
+ if (result.type === "page") console.error(dim(`sha: ${contentSha4(result.html)}`));
650
+ return;
651
+ }
652
+
653
+ console.log(bold(cyan(result.title)));
654
+ if (result.breadcrumb) console.log(dim(result.breadcrumb));
655
+ console.log(dim("─".repeat(Math.min(result.title.length + 10, 60))));
656
+ console.log(result.content);
657
+ if (result.type === "page" && result.html) {
658
+ console.error(dim(`sha: ${contentSha4(result.html)}`));
659
+ }
660
+ }
661
+ )
662
+
663
+ // --- export ---
664
+ .command(
665
+ "export <ref> <output>",
666
+ "Export a page (to a .md/.html file) or a section/section group/notebook (to a directory), with media",
667
+ (y) =>
668
+ y
669
+ .positional("ref", { type: "string", demandOption: true, describe: "OneNote page/section/notebook path, ID, or URL" })
670
+ .positional("output", {
671
+ type: "string",
672
+ demandOption: true,
673
+ describe: "Output file (page) or directory (section/notebook). [date] expands to today (YYYY-MM-DD).",
674
+ })
675
+ .option("assets-dir", {
676
+ type: "string",
677
+ describe: "Directory for downloaded media (default: alongside each file, in ./assets)",
678
+ })
679
+ .option("format", {
680
+ type: "string",
681
+ choices: ["md", "html"],
682
+ describe: "Output format (default: page → from extension; directory → md)",
683
+ }),
684
+ async (argv) => {
685
+ const ref = normalizeRef(argv.ref as string)!;
686
+ const { exportRef } = await import("./export");
687
+ const res = await exportRef(ref, argv.output as string, {
688
+ assetsDir: argv["assets-dir"] as string | undefined,
689
+ format: argv.format as string | undefined,
690
+ log: (msg) => console.error(dim(msg)),
691
+ });
692
+ if (res.kind === "page") {
693
+ console.log(green(`Exported ${res.format.toUpperCase()}: ${res.rootPath}`));
694
+ console.log(dim(`Title: ${res.title}`));
695
+ } else {
696
+ console.log(green(`Exported ${res.kind} "${res.title}" → ${res.rootPath}`));
697
+ console.log(dim(`Pages: ${res.pageCount} ${res.format.toUpperCase()} file(s)`));
698
+ }
699
+ console.log(dim(`Media: ${res.assetCount} file(s)`));
700
+ }
701
+ )
702
+
703
+ // --- sync ---
704
+ .command(
705
+ "sync",
706
+ "Download and cache all OneNote sections for local search",
707
+ (y) =>
708
+ y
709
+ .option("account", { type: "string", alias: "a", describe: "Limit to accounts matching this email (substring)" })
710
+ .option("notebook", { type: "string", alias: "n", describe: "Limit to notebooks matching this name (substring)" })
711
+ .option("section", { type: "string", alias: "s", describe: "Limit to sections matching this name (substring)" }),
712
+ async (argv) => {
713
+ const filter = {
714
+ account: argv.account as string | undefined,
715
+ notebook: argv.notebook as string | undefined,
716
+ section: argv.section as string | undefined,
717
+ };
718
+ const { runSyncUI } = await import("./sync-ui");
719
+ await runSyncUI((emit) => syncCache(() => {}, emit, filter));
720
+ }
721
+ )
722
+
723
+ // --- reindex ---
724
+ .command(
725
+ "reindex",
726
+ "Rebuild FTS search index from existing cache (no network needed)",
727
+ () => {},
728
+ async () => {
729
+ await rebuildSearchIndex(console.log);
730
+ }
731
+ )
732
+
733
+ // --- search ---
734
+ .command(
735
+ "search <query>",
736
+ "Full-text search across OneNote pages (uses local cache)",
737
+ (y) =>
738
+ y
739
+ .positional("query", { type: "string", demandOption: true })
740
+ .option("online", { type: "boolean", alias: "o", describe: "Use online Graph Search API (section-level)" })
741
+ .option("notebook", { type: "string", alias: "n", describe: "Limit to a notebook name" })
742
+ .option("section", { type: "string", alias: "s", describe: "Limit to a section name" })
743
+ .option("limit", { type: "number", alias: "l", default: 100, describe: "Max results per page" })
744
+ .option("offset", { type: "number", alias: "p", default: 0, describe: "Skip first N results (for pagination)" })
745
+ .option("account", { type: "string", alias: "a", describe: "Limit to a specific account email (e.g. snomiao@gmail.com)" })
746
+ .option("group", { type: "boolean", alias: "g", describe: "Group results hierarchically by account > notebook > section" })
747
+ .option("compact", { type: "boolean", alias: "c", describe: "One line per page: [count] title — section | notebook" })
748
+ .option("max-lines", { type: "number", alias: "m", default: 5, describe: "Max tag lines to show per page (default 5)" })
749
+ .option("since", { type: "string", describe: "Only pages modified after this date (YYYY-MM-DD or '30d' / '3m' / '1y')" })
750
+ .epilog(
751
+ [
752
+ "Query syntax:",
753
+ " term1 term2 pages containing both terms (AND)",
754
+ " term1 OR term2 pages containing either term",
755
+ " term1 NOT term2 pages with term1 but not term2",
756
+ " \"phrase\" exact phrase match",
757
+ " #todo pages with unchecked checkboxes (requires: onenote sync)",
758
+ " #done pages with completed (checked) checkboxes",
759
+ " #checkbox pages with any checkbox (#todo OR #done)",
760
+ " #star pages tagged with Star",
761
+ " #question pages tagged with Question",
762
+ " #important pages tagged Important",
763
+ " #critical pages tagged Critical",
764
+ " #idea pages tagged Idea",
765
+ " #contact pages tagged Contact",
766
+ " #definition pages tagged Definition",
767
+ " #highlight pages with Highlight tag",
768
+ " #remember pages tagged Remember for Later",
769
+ " #book #music #movie #website #phone #address #password",
770
+ " #meeting #email #callback #discuss #priority1 #priority2 #client",
771
+ " tag:<name> alias for #<name> (e.g. tag:star = #star)",
772
+ "",
773
+ "Examples:",
774
+ " onenote search meeting",
775
+ " onenote search \"project plan\" --notebook Work",
776
+ " onenote search \"python OR javascript\"",
777
+ " onenote search \"#todo buy OR groceries\"",
778
+ " onenote search \"#todo\" --notebook Work",
779
+ " onenote search \"#done\"",
780
+ " onenote search meeting --online",
781
+ " onenote search meeting --limit 20 --offset 20",
782
+ ].join("\n")
783
+ ),
784
+ async (argv) => {
785
+ if (argv.online) {
786
+ const results = await graph.searchPages(argv.query as string);
787
+ if (!results || results.length === 0) {
788
+ console.log("No results found.");
789
+ return;
790
+ }
791
+ for (const r of results) {
792
+ const heading = r.notebook ? `${r.section} (${r.notebook})` : r.section;
793
+ console.log(`# ${heading}`);
794
+ if (r.summary) console.log(` ${r.summary}`);
795
+ if (r.url) console.log(` ${r.url}`);
796
+ console.log();
797
+ }
798
+ console.log(`${results.length} results found.`);
799
+ return;
800
+ }
801
+
802
+ // Auto-sync if cache is empty
803
+ if (await isCacheEmpty()) {
804
+ console.log("Cache is empty. Syncing notebooks...");
805
+ await syncCache();
806
+ }
807
+
808
+ // Local page-level search
809
+ // Strip surrounding quotes from query (shell may pass "word" or 'word')
810
+ const query = (argv.query as string).replace(/^["']|["']$/g, "");
811
+ const limit = argv.limit as number;
812
+ const offset = argv.offset as number;
813
+ const nbFilter = normalizeRef(argv.notebook as string | undefined);
814
+ const secFilter = normalizeRef(argv.section as string | undefined);
815
+ const accountFilter = normalizeRef(argv.account as string | undefined);
816
+ const groupMode = argv.group as boolean | undefined;
817
+ const compactMode = argv.compact as boolean | undefined;
818
+ const maxLines = (argv["max-lines"] as number | undefined) ?? 5;
819
+
820
+ // Parse --since: accepts "YYYY-MM-DD", "30d", "3m", "1y", or full ISO
821
+ const parseSince = (s: string | undefined): string | undefined => {
822
+ if (!s) return undefined;
823
+ const rel = s.match(/^(\d+)([dmy])$/i);
824
+ if (rel) {
825
+ const n = parseInt(rel[1], 10);
826
+ const unit = rel[2].toLowerCase();
827
+ const d = new Date();
828
+ if (unit === "d") d.setDate(d.getDate() - n);
829
+ else if (unit === "m") d.setMonth(d.getMonth() - n);
830
+ else if (unit === "y") d.setFullYear(d.getFullYear() - n);
831
+ return d.toISOString();
832
+ }
833
+ // YYYY-MM-DD → to ISO start of day
834
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return new Date(s + "T00:00:00Z").toISOString();
835
+ return s; // assume already ISO
836
+ };
837
+ const sinceIso = parseSince(argv.since as string | undefined);
838
+ const results = await searchLocal(query, { offset, limit, notebook: nbFilter, section: secFilter, account: accountFilter, since: sinceIso });
839
+ if (results.length === 0) {
840
+ console.log("No results found.");
841
+ return;
842
+ }
843
+ // Strip binary noise, then pick lines with sufficient real content for display.
844
+ // Higher threshold than indexing: requires ≥50% quality chars (ASCII printable or CJK).
845
+ const cleanSnippet = (s: string): string => {
846
+ const lines = s
847
+ .replace(/[\u0000-\u001F\u007F-\u009F]/g, " ")
848
+ .split(/[\n\r]+/)
849
+ .map((l) => l.replace(/\s+/g, " ").trim())
850
+ .filter((l) => {
851
+ if (l.length < 3) return false;
852
+ const ascii = (l.match(/[\x20-\x7E]/g) ?? []).length;
853
+ const cjk = (l.match(/[\u4E00-\u9FFF\u3000-\u30FF\uAC00-\uD7AF]/g) ?? []).length;
854
+ const quality = ascii + cjk;
855
+ if (quality / l.length < 0.5) return false;
856
+ // Require either decent ASCII ratio or meaningful CJK (≥3 chars)
857
+ return ascii / l.length >= 0.4 || (cjk >= 3 && cjk / l.length >= 0.4);
858
+ });
859
+ return lines.join(" ").replace(/\s+/g, " ").trim();
860
+ };
861
+
862
+ const { ftsQuery, hasTodo, hasDone, hasCheckbox, tagFilters } = parseTagsFromQuery(query);
863
+
864
+ // Tag display prefix: emoji per filter active
865
+ const TAG_EMOJI: Record<string, string> = {
866
+ star: "★", question: "?", important: "❗", critical: "🔴", definition: "📖",
867
+ idea: "💡", contact: "👤", address: "🏠", "phone-number": "📞",
868
+ "web-site-to-visit": "🌐", password: "🔑", "remember-for-later": "🔔",
869
+ "book-to-read": "📚", "music-to-listen-to": "🎵", "movie-to-see": "🎬",
870
+ highlight: "🖍", "schedule-meeting": "📅", "send-in-email": "📧",
871
+ "call-back": "📲", "to-do-priority-1": "P1", "to-do-priority-2": "P2",
872
+ "client-request": "👔",
873
+ };
874
+ const tagPrefix = (() => {
875
+ if (hasTodo) return yellow(bold("☐ "));
876
+ if (hasDone) return green(bold("☑ "));
877
+ if (hasCheckbox) return yellow(bold("☐")) + green(bold("☑ "));
878
+ if (tagFilters.length > 0) {
879
+ const icons = [...new Set(tagFilters.map((t) => TAG_EMOJI[t] ?? t))].join("");
880
+ return bold(icons + " ");
881
+ }
882
+ return "";
883
+ })();
884
+
885
+ const lowerQuery = ftsQuery.toLowerCase();
886
+ const cleanResults = results.filter((r) => {
887
+ if (/^\.[a-z0-9]{2,5}$/i.test(r.title.trim())) return false;
888
+ const printable = r.title.replace(/[^\x20-\x7E\u3000-\u30FF\u4E00-\u9FFF\uAC00-\uD7AF\uFF00-\uFFEF\u00A0-\u024F]/g, "");
889
+ return printable.length >= 3 && printable.length / r.title.length >= 0.4;
890
+ });
891
+
892
+ type R = typeof results[0];
893
+ const getMatchingLines = (r: R) => {
894
+ const tagLines = r.tagLines ?? [];
895
+ if (hasTodo) return tagLines.filter((l) => l.tag === "to-do");
896
+ if (hasDone) return tagLines.filter((l) => l.tag === "to-do:completed");
897
+ if (hasCheckbox) return tagLines.filter((l) => l.tag === "to-do" || l.tag === "to-do:completed");
898
+ if (tagFilters.length > 0) return tagLines.filter((l) => tagFilters.includes(l.tag));
899
+ return [];
900
+ };
901
+
902
+ const fmtDate = (iso: string | null | undefined): string => {
903
+ if (!iso) return "";
904
+ const d = new Date(iso);
905
+ if (isNaN(d.getTime())) return "";
906
+ return d.toISOString().slice(0, 10);
907
+ };
908
+
909
+ const renderPageBody = (r: R, indent: string = " ") => {
910
+ const matchingLines = getMatchingLines(r);
911
+ const body = cleanSnippet(r.body);
912
+ const idx = lowerQuery ? body.toLowerCase().indexOf(lowerQuery) : -1;
913
+ if (idx >= 0) {
914
+ const start = Math.max(0, idx - 40);
915
+ const end = Math.min(body.length, idx + ftsQuery.length + 80);
916
+ const before = body.slice(start, idx);
917
+ const match = body.slice(idx, idx + ftsQuery.length);
918
+ const after = body.slice(idx + ftsQuery.length, end);
919
+ const snippet = (start > 0 ? "..." : "") + before + yellow(bold(match)) + after + (end < body.length ? "..." : "");
920
+ console.log(`${indent}${tagPrefix}${snippet}`);
921
+ } else if (matchingLines.length > 0) {
922
+ for (const line of matchingLines.slice(0, maxLines)) {
923
+ const lineIcon = line.tag === "to-do" ? yellow(bold("☐")) :
924
+ line.tag === "to-do:completed" ? green(bold("☑")) :
925
+ bold(TAG_EMOJI[line.tag] ?? line.tag);
926
+ console.log(`${indent}${lineIcon} ${line.text}`);
927
+ }
928
+ if (matchingLines.length > maxLines) console.log(`${indent}${dim(`... and ${matchingLines.length - maxLines} more`)}`);
929
+ } else {
930
+ const snippet = body.length >= 20 ? body.slice(0, 120) : null;
931
+ if (tagPrefix) {
932
+ const label = hasTodo ? "(unchecked items)" : hasDone ? "(completed items)" : hasCheckbox ? "(checkbox items)" : `(${tagFilters.join(",")})`;
933
+ console.log(`${indent}${tagPrefix}${snippet ?? label}`);
934
+ } else if (snippet) {
935
+ console.log(`${indent}${snippet}`);
936
+ }
937
+ }
938
+ };
939
+
940
+ // Show account info only when results span multiple accounts (null counts as distinct)
941
+ const uniqueAccounts = new Set(cleanResults.map((r) => r.account ?? ""));
942
+ const showAccounts = uniqueAccounts.size > 1;
943
+
944
+ if (groupMode) {
945
+ const byAccount = new Map<string, Map<string, Map<string, R[]>>>();
946
+ for (const r of cleanResults) {
947
+ const acct = r.account ?? "(local)";
948
+ if (!byAccount.has(acct)) byAccount.set(acct, new Map());
949
+ const nbMap = byAccount.get(acct)!;
950
+ if (!nbMap.has(r.notebook)) nbMap.set(r.notebook, new Map());
951
+ const secMap = nbMap.get(r.notebook)!;
952
+ if (!secMap.has(r.section)) secMap.set(r.section, []);
953
+ secMap.get(r.section)!.push(r);
954
+ }
955
+
956
+ const renderNotebook = (nbMap: Map<string, Map<string, R[]>>, nbIndent: string, pageIndent: string, bodyIndent: string) => {
957
+ for (const [nb, secMap] of nbMap) {
958
+ console.log(`${nbIndent}${bold(nb)}`);
959
+ for (const [sec, pages] of secMap) {
960
+ console.log(`${nbIndent} ${dim(sec)}`);
961
+ for (const r of pages) {
962
+ const title = r.webUrl ? link(r.webUrl, bold(r.title)) : bold(r.title);
963
+ console.log(`${pageIndent}${title}`);
964
+ renderPageBody(r, bodyIndent);
965
+ }
966
+ }
967
+ }
968
+ };
969
+
970
+ if (showAccounts) {
971
+ for (const [acct, nbMap] of byAccount) {
972
+ const acctTotal = [...nbMap.values()].reduce((s, m) => s + [...m.values()].reduce((a, b) => a + b.length, 0), 0);
973
+ console.log(bold(cyan(`📘 ${acct}`)) + dim(` (${acctTotal} page${acctTotal === 1 ? "" : "s"})`));
974
+ renderNotebook(nbMap, " ", " ", " ");
975
+ console.log();
976
+ }
977
+ } else {
978
+ // Single account (or all null) — skip account header, flatten one level
979
+ const merged = new Map<string, Map<string, R[]>>();
980
+ for (const nbMap of byAccount.values()) {
981
+ for (const [nb, secMap] of nbMap) {
982
+ if (!merged.has(nb)) merged.set(nb, new Map());
983
+ const m = merged.get(nb)!;
984
+ for (const [sec, pages] of secMap) {
985
+ if (!m.has(sec)) m.set(sec, []);
986
+ m.get(sec)!.push(...pages);
987
+ }
988
+ }
989
+ }
990
+ renderNotebook(merged, "", " ", " ");
991
+ }
992
+ } else if (compactMode) {
993
+ // Compact: one line per page, [count] title — section | notebook [date]
994
+ for (const r of cleanResults) {
995
+ const matchingLines = getMatchingLines(r);
996
+ const countStr = matchingLines.length > 0 ? `${yellow(bold(`[${matchingLines.length}]`))} ` : "";
997
+ const titleStr = r.webUrl ? link(r.webUrl, bold(cyan(r.title))) : bold(cyan(r.title));
998
+ const locStr = dim(`${r.section} | ${r.notebook}`);
999
+ const acctStr = showAccounts && r.account ? dim(` | ${r.account}`) : "";
1000
+ const dateStr = r.lastModified ? dim(` [${fmtDate(r.lastModified)}]`) : "";
1001
+ console.log(`${countStr}${titleStr} ${dim("—")} ${locStr}${acctStr}${dateStr}`);
1002
+ }
1003
+ } else {
1004
+ // Flat: collapse consecutive same (account, notebook, section) header into one line
1005
+ let lastHeader = "";
1006
+ for (const r of cleanResults) {
1007
+ const header = `${r.section}|${r.notebook}|${r.account ?? ""}`;
1008
+ if (header !== lastHeader) {
1009
+ if (lastHeader !== "") console.log();
1010
+ const acctStr = showAccounts && r.account ? ` ${dim("|")} ${dim(r.account)}` : "";
1011
+ console.log(`${bold(r.notebook)} ${dim("›")} ${dim(r.section)}${acctStr}`);
1012
+ lastHeader = header;
1013
+ }
1014
+ const displayTitle = r.webUrl ? link(r.webUrl, bold(cyan(r.title))) : bold(cyan(r.title));
1015
+ const dateStr = r.lastModified ? dim(` [${fmtDate(r.lastModified)}]`) : "";
1016
+ console.log(` ${displayTitle}${dateStr}`);
1017
+ renderPageBody(r, " ");
1018
+ }
1019
+ }
1020
+ let syncedStr = "";
1021
+ try {
1022
+ const s = await stat(SEARCH_DB_PATH);
1023
+ syncedStr = ` • last synced: ${s.mtime.toLocaleString()}`;
1024
+ } catch {}
1025
+ const pageInfo = offset > 0 ? ` (offset ${offset})` : results.length === limit ? ` • use --offset ${offset + limit} for more` : "";
1026
+ console.log(green(`${results.length} page-level results found${pageInfo}${syncedStr}.`));
1027
+ }
1028
+ )
1029
+
1030
+ // --- init ---
1031
+ .command(
1032
+ "init",
1033
+ "First-run setup: verify client ID and login",
1034
+ () => {},
1035
+ async () => {
1036
+ // getAccessToken reads ONENOTE_CLIENT_ID from env OR ~/.onenote-cli/config.json
1037
+ // and prints a setup guide if the clientId is missing/placeholder.
1038
+ const { getAccessToken } = await import("./auth");
1039
+ await getAccessToken();
1040
+ await whoami();
1041
+ console.log(green("\nReady. Try: onenote ls"));
1042
+ }
1043
+ )
1044
+
1045
+ // --- auth ---
1046
+ .command(
1047
+ "auth",
1048
+ "Manage authentication",
1049
+ (yargs) =>
1050
+ yargs
1051
+ .command(
1052
+ "login",
1053
+ "Login to Microsoft account (browser sign-in; on a remote host, paste the redirect URL). Run multiple times to add more accounts.",
1054
+ () => {},
1055
+ async () => {
1056
+ const existing = await listAccounts();
1057
+ if (existing.length > 0) {
1058
+ console.log(`Already logged in (${existing.length} account${existing.length > 1 ? "s" : ""}):`);
1059
+ for (const a of existing) console.log(` - ${a.username}`);
1060
+ console.log("Adding another account...\n");
1061
+ }
1062
+ const username = await login();
1063
+ console.log(`\nLogged in as ${username}`);
1064
+ }
1065
+ )
1066
+ .command(
1067
+ "logout [email]",
1068
+ "Logout an account. With no args: logout if only one account, else show list. Use --all to logout all.",
1069
+ (y) => y
1070
+ .positional("email", { type: "string", describe: "Account email to logout" })
1071
+ .option("all", { type: "boolean", describe: "Logout all accounts" }),
1072
+ async (argv) => {
1073
+ if (argv.all) {
1074
+ await logoutAll();
1075
+ } else {
1076
+ await logout(argv.email as string | undefined);
1077
+ }
1078
+ }
1079
+ )
1080
+ .command(
1081
+ ["list", "ls"],
1082
+ "List all logged-in accounts",
1083
+ () => {},
1084
+ async () => {
1085
+ const accounts = await listAccounts();
1086
+ if (accounts.length === 0) {
1087
+ console.log("No accounts logged in. Run `onenote auth login` to authenticate.");
1088
+ return;
1089
+ }
1090
+ for (const a of accounts) {
1091
+ console.log(`${a.username} (${a.name ?? ""})`);
1092
+ }
1093
+ }
1094
+ )
1095
+ .command(
1096
+ "whoami",
1097
+ "Show all authenticated accounts",
1098
+ () => {},
1099
+ async () => {
1100
+ await whoami();
1101
+ }
1102
+ )
1103
+ .command(
1104
+ "setup",
1105
+ "Guide for setting up OAuth client credentials",
1106
+ () => {},
1107
+ async () => {
1108
+ console.log(`
1109
+ === onenote-cli OAuth Setup ===
1110
+
1111
+ 1. Register an Azure AD app:
1112
+ https://entra.microsoft.com/#view/Microsoft_AAD_RegisteredApps
1113
+
1114
+ - Click "New registration"
1115
+ - Name: onenote-cli
1116
+ - Supported account types: "Accounts in any organizational directory and personal Microsoft accounts"
1117
+ - Click "Register"
1118
+
1119
+ 2. Configure authentication:
1120
+ - Go to "Authentication" > "Add a platform" > "Mobile and desktop applications"
1121
+ - Check: https://login.microsoftonline.com/common/oauth2/nativeclient
1122
+ - Enable "Allow public client flows" in Settings tab
1123
+ - Click "Save"
1124
+
1125
+ 3. Add API permissions:
1126
+ - Go to "API permissions" > "Add a permission" > "Microsoft Graph" > "Delegated permissions"
1127
+ - Add: Notes.Read, Notes.ReadWrite, Notes.ReadWrite.All
1128
+ - Click "Add permissions"
1129
+
1130
+ 4. Copy your Application (client) ID and set it:
1131
+
1132
+ Option A — .env.local:
1133
+ ONENOTE_CLIENT_ID=<your-client-id>
1134
+ ONENOTE_AUTHORITY=https://login.microsoftonline.com/common
1135
+
1136
+ Option B — ~/.onenote-cli/config.json:
1137
+ { "clientId": "<your-client-id>", "authority": "https://login.microsoftonline.com/common" }
1138
+
1139
+ 5. Login:
1140
+ onenote auth login
1141
+ `);
1142
+ }
1143
+ )
1144
+ .demandCommand(1),
1145
+ () => {}
1146
+ )
1147
+
1148
+ .epilogue(
1149
+ [
1150
+ "<ref> accepts any of:",
1151
+ " - path e.g. 'NotebookA', 'NotebookA/SectionB', 'NotebookA/SectionB/PageC'",
1152
+ " - Graph ID e.g. '1-abc123...' (page) or '0-abc123...' (notebook/section)",
1153
+ " - OneNote URL e.g. https://onedrive.live.com/redir?...",
1154
+ "",
1155
+ "Note: path segments must be unique — duplicates throw; rename or use ID/URL.",
1156
+ ].join("\n")
1157
+ )
1158
+ .strict()
1159
+ .help()
1160
+ .alias("h", "help")
1161
+ .version()
1162
+ .alias("v", "version")
1163
+ .showHelpOnFail(true)
1164
+ .fail((msg, err, yargs) => {
1165
+ if (err) {
1166
+ yargs.showHelp();
1167
+ console.error("\nError:", err.message);
1168
+ process.exit(1);
1169
+ }
1170
+ if (msg) {
1171
+ yargs.showHelp();
1172
+ console.error("\n" + msg);
1173
+ process.exit(1);
1174
+ }
1175
+ })
1176
+ .parse();