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/graph.ts ADDED
@@ -0,0 +1,1480 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import { dirname, join } from "node:path";
3
+ import { getAccessToken } from "./auth";
4
+ import {
5
+ isOneNoteResourceUrl,
6
+ renderHtmlForRead,
7
+ renderResourceForRead,
8
+ } from "./read-render";
9
+
10
+ const GRAPH_BASE = "https://graph.microsoft.com/v1.0";
11
+
12
+ const PKG_ROOT = dirname(import.meta.dir);
13
+ const PKG_CACHE_DIR = join(PKG_ROOT, ".onenote");
14
+ const NOTEBOOK_CACHE_PATH = join(PKG_CACHE_DIR, "notebooks.json");
15
+ const NOTEBOOK_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
16
+
17
+ type CachedNotebook = {
18
+ id: string;
19
+ displayName: string;
20
+ webUrl?: string;
21
+ lastModifiedDateTime?: string;
22
+ };
23
+
24
+ async function loadNotebookCache(): Promise<CachedNotebook[] | null> {
25
+ try {
26
+ const raw = await readFile(NOTEBOOK_CACHE_PATH, "utf8");
27
+ const parsed = JSON.parse(raw);
28
+ if (!parsed || typeof parsed !== "object") return null;
29
+ const cachedAt = typeof parsed.cachedAt === "string" ? Date.parse(parsed.cachedAt) : NaN;
30
+ if (!Number.isFinite(cachedAt) || Date.now() - cachedAt > NOTEBOOK_CACHE_TTL_MS) return null;
31
+ if (!Array.isArray(parsed.notebooks)) return null;
32
+ return parsed.notebooks as CachedNotebook[];
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ async function saveNotebookCache(notebooks: CachedNotebook[]): Promise<void> {
39
+ await mkdir(PKG_CACHE_DIR, { recursive: true });
40
+ await writeFile(
41
+ NOTEBOOK_CACHE_PATH,
42
+ JSON.stringify({ cachedAt: new Date().toISOString(), notebooks }, null, 2)
43
+ );
44
+ }
45
+
46
+ async function lookupSectionFromSyncCache(
47
+ notebookName: string,
48
+ sectionName: string
49
+ ): Promise<{ id: string; displayName: string; links?: any } | null> {
50
+ try {
51
+ const file = join(PKG_CACHE_DIR, "cache", notebookName, `${sectionName}.json`);
52
+ const raw = await readFile(file, "utf8");
53
+ const data = JSON.parse(raw);
54
+ const url: string = data.webUrl ?? "";
55
+ const m = decodeURIComponent(url).match(/sourcedoc=\{([0-9a-f-]+)\}/i);
56
+ if (!m) return null;
57
+ return { id: `0-${m[1]!.toLowerCase()}`, displayName: data.section ?? sectionName };
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+
63
+ async function lookupPageFromSyncCache(
64
+ notebookName: string,
65
+ sectionName: string,
66
+ pageTitle: string
67
+ ): Promise<{ id: string; title: string; links?: any } | null> {
68
+ try {
69
+ const file = join(PKG_CACHE_DIR, "cache", notebookName, `${sectionName}.json`);
70
+ const raw = await readFile(file, "utf8");
71
+ const data = JSON.parse(raw);
72
+ const pages = (data.officialPages ?? []) as Array<{ guid: string; title: string; webUrl?: string }>;
73
+ const matches = pages.filter((p) => p.title === pageTitle);
74
+ if (matches.length === 0) return null;
75
+ if (matches.length > 1) {
76
+ const lines = matches.map((p) => ` - ${p.guid} ${p.webUrl ?? ""}`).join("\n");
77
+ throw new Error(
78
+ `Multiple pages titled '${pageTitle}' in '${notebookName}/${sectionName}' (${matches.length} matches). Please rename for uniqueness or use URL/ID.\nCandidates:\n${lines}`
79
+ );
80
+ }
81
+ return { id: `0-${matches[0]!.guid.toLowerCase()}`, title: matches[0]!.title };
82
+ } catch (err: any) {
83
+ if (err?.message?.startsWith("Multiple pages")) throw err;
84
+ return null;
85
+ }
86
+ }
87
+
88
+ async function getCachedNotebooks(force = false): Promise<CachedNotebook[]> {
89
+ if (!force) {
90
+ const cached = await loadNotebookCache();
91
+ if (cached) return cached;
92
+ }
93
+ const fresh = await listNotebooks();
94
+ const slim: CachedNotebook[] = fresh.map((nb: any) => ({
95
+ id: nb.id,
96
+ displayName: nb.displayName,
97
+ webUrl: nb.links?.oneNoteWebUrl?.href ?? nb.links?.oneNoteClientUrl?.href,
98
+ lastModifiedDateTime: nb.lastModifiedDateTime,
99
+ }));
100
+ await saveNotebookCache(slim);
101
+ return slim;
102
+ }
103
+
104
+ interface GraphResponse<T> {
105
+ value: T[];
106
+ "@odata.nextLink"?: string;
107
+ }
108
+
109
+ async function graphFetch(path: string, init?: RequestInit): Promise<Response> {
110
+ const token = await getAccessToken();
111
+ const url = path.startsWith("http") ? path : `${GRAPH_BASE}${path}`;
112
+ const doFetch = () => fetch(url, {
113
+ ...init,
114
+ headers: {
115
+ Authorization: `Bearer ${token}`,
116
+ "Content-Type": "application/json",
117
+ ...init?.headers,
118
+ },
119
+ });
120
+ let res = await doFetch();
121
+ // Retry on 429 with Retry-After / exponential backoff
122
+ for (let attempt = 0; attempt < 5 && res.status === 429; attempt++) {
123
+ const retryAfter = parseInt(res.headers.get("retry-after") ?? "0", 10);
124
+ const delayMs = retryAfter > 0 ? retryAfter * 1000 : Math.min(2000 * 2 ** attempt, 60000);
125
+ await new Promise((r) => setTimeout(r, delayMs));
126
+ res = await doFetch();
127
+ }
128
+ if (!res.ok) {
129
+ const body = await res.text();
130
+ let code = "";
131
+ let message = "";
132
+ try {
133
+ const err = JSON.parse(body);
134
+ code = err.error?.code ?? "";
135
+ message = err.error?.message ?? body;
136
+ } catch {
137
+ message = body;
138
+ }
139
+ const error = new Error(`Graph API ${res.status}: ${message}`) as any;
140
+ error.statusCode = res.status;
141
+ error.graphCode = code;
142
+ throw error;
143
+ }
144
+ return res;
145
+ }
146
+
147
+ function is5000LimitError(err: any): boolean {
148
+ return err?.graphCode === "10008" || err?.graphCode === "20102";
149
+ }
150
+
151
+ // --- Notebook path helpers ---
152
+
153
+ function getNotebookDrivePath(notebook: any): string | null {
154
+ const webUrl = notebook.links?.oneNoteWebUrl?.href;
155
+ if (!webUrl) return null;
156
+ const match = decodeURIComponent(new URL(webUrl).pathname).match(/Documents\/(.+)/);
157
+ return match?.[1] ?? null;
158
+ }
159
+
160
+ async function listNotebookFilesViaDrive(notebook: any): Promise<any[]> {
161
+ const drivePath = getNotebookDrivePath(notebook);
162
+ if (!drivePath) return [];
163
+ const encoded = drivePath.split("/").map(s => encodeURIComponent(s)).join("/");
164
+ const res = await graphFetch(
165
+ `/me/drive/root:/${encoded}:/children?$select=name,id,file,folder,size,lastModifiedDateTime,createdDateTime`
166
+ );
167
+ const data: GraphResponse<any> = await res.json();
168
+ return data.value;
169
+ }
170
+
171
+ // --- Notebooks ---
172
+
173
+ export async function listNotebooks() {
174
+ const res = await graphFetch("/me/onenote/notebooks");
175
+ const data: GraphResponse<any> = await res.json();
176
+ return data.value;
177
+ }
178
+
179
+ export async function getNotebook(ref: string) {
180
+ const { apiBase, notebookId } = await resolveNotebookRef(ref);
181
+ const res = await graphFetch(`${apiBase}/onenote/notebooks/${notebookId}`);
182
+ return res.json();
183
+ }
184
+
185
+ async function getNotebookByRef(ref: string) {
186
+ const { apiBase, notebookId } = await resolveNotebookRef(ref);
187
+ const res = await graphFetch(`${apiBase}/onenote/notebooks/${notebookId}`);
188
+ return res.json();
189
+ }
190
+
191
+ export async function createNotebook(displayName: string) {
192
+ const res = await graphFetch("/me/onenote/notebooks", {
193
+ method: "POST",
194
+ body: JSON.stringify({ displayName }),
195
+ });
196
+ return res.json();
197
+ }
198
+
199
+ // --- Sections ---
200
+
201
+ export async function listSections(notebookId?: string) {
202
+ try {
203
+ let path = "/me/onenote/sections";
204
+ if (notebookId) {
205
+ const { apiBase, notebookId: resolvedNotebookId } = await resolveNotebookRef(notebookId);
206
+ path = `${apiBase}/onenote/notebooks/${resolvedNotebookId}/sections`;
207
+ }
208
+ const res = await graphFetch(path);
209
+ const data: GraphResponse<any> = await res.json();
210
+ return data.value;
211
+ } catch (err: any) {
212
+ if (!is5000LimitError(err) || !notebookId) throw err;
213
+ // Fallback: list .one files via OneDrive
214
+ const notebook = await getNotebookByRef(notebookId);
215
+ const files = await listNotebookFilesViaDrive(notebook);
216
+ return files
217
+ .filter((f: any) => f.name?.endsWith(".one"))
218
+ .map((f: any) => ({
219
+ id: f.id,
220
+ displayName: f.name.replace(/\.one$/, ""),
221
+ createdDateTime: f.createdDateTime,
222
+ lastModifiedDateTime: f.lastModifiedDateTime,
223
+ _source: "onedrive",
224
+ }));
225
+ }
226
+ }
227
+
228
+ export async function getSection(ref: string) {
229
+ const { apiBase, sectionId } = await resolveSectionRef(ref);
230
+ const res = await graphFetch(`${apiBase}/onenote/sections/${sectionId}`);
231
+ return res.json();
232
+ }
233
+
234
+ export async function createSection(notebookId: string, displayName: string) {
235
+ const { apiBase, notebookId: resolvedNotebookId } = await resolveNotebookRef(notebookId);
236
+ const res = await graphFetch(`${apiBase}/onenote/notebooks/${resolvedNotebookId}/sections`, {
237
+ method: "POST",
238
+ body: JSON.stringify({ displayName }),
239
+ });
240
+ return res.json();
241
+ }
242
+
243
+ // --- Section Groups ---
244
+
245
+ export async function listSectionGroups(notebookId?: string) {
246
+ try {
247
+ let path = "/me/onenote/sectionGroups";
248
+ if (notebookId) {
249
+ const { apiBase, notebookId: resolvedNotebookId } = await resolveNotebookRef(notebookId);
250
+ path = `${apiBase}/onenote/notebooks/${resolvedNotebookId}/sectionGroups`;
251
+ }
252
+ const res = await graphFetch(path);
253
+ const data: GraphResponse<any> = await res.json();
254
+ return data.value;
255
+ } catch (err: any) {
256
+ if (!is5000LimitError(err) || !notebookId) throw err;
257
+ // Fallback: list folders via OneDrive
258
+ const notebook = await getNotebookByRef(notebookId);
259
+ const files = await listNotebookFilesViaDrive(notebook);
260
+ return files
261
+ .filter((f: any) => f.folder && !f.name?.startsWith("OneNote_") && f.name !== "deletePending")
262
+ .map((f: any) => ({
263
+ id: f.id,
264
+ displayName: f.name,
265
+ createdDateTime: f.createdDateTime,
266
+ _source: "onedrive",
267
+ }));
268
+ }
269
+ }
270
+
271
+ // --- Pages ---
272
+
273
+ export async function listPages(sectionId?: string) {
274
+ let path = "/me/onenote/pages";
275
+ if (sectionId) {
276
+ const { apiBase, sectionId: resolvedSectionId } = await resolveSectionRef(sectionId);
277
+ path = `${apiBase}/onenote/sections/${resolvedSectionId}/pages`;
278
+ }
279
+ const res = await graphFetch(path);
280
+ const data: GraphResponse<any> = await res.json();
281
+ return data.value;
282
+ }
283
+
284
+ export async function getPage(id: string) {
285
+ const { apiBase, pageId } = await resolvePageRef(id);
286
+ const res = await graphFetch(`${apiBase}/onenote/pages/${pageId}`);
287
+ return res.json();
288
+ }
289
+
290
+ export async function getPageContent(id: string): Promise<string> {
291
+ const { apiBase, pageId } = await resolvePageRef(id);
292
+ const res = await graphFetch(`${apiBase}/onenote/pages/${pageId}/content`);
293
+ return res.text();
294
+ }
295
+
296
+ export type PageUpdateCommand = {
297
+ target: string; // "body", "title", or "#element-id"
298
+ action: "append" | "insert" | "prepend" | "replace";
299
+ position?: "before" | "after";
300
+ content: string;
301
+ };
302
+
303
+ /**
304
+ * Update page content via PATCH. Commands follow MS Graph OneNote page update format.
305
+ * Accepts either a page ID or a OneNote URL (SharePoint URLs use site-scoped
306
+ * endpoints to bypass the 5000-item limit on /me/onenote/*).
307
+ * @see https://learn.microsoft.com/graph/onenote-update-page
308
+ */
309
+ export async function updatePage(urlOrId: string, commands: PageUpdateCommand[]) {
310
+ const { apiBase, pageId } = await resolvePageRef(urlOrId);
311
+ const res = await graphFetch(`${apiBase}/onenote/pages/${pageId}/content`, {
312
+ method: "PATCH",
313
+ body: JSON.stringify(commands),
314
+ });
315
+ return res.ok;
316
+ }
317
+
318
+ /**
319
+ * Rename a page by replacing its title element.
320
+ */
321
+ export async function renamePage(urlOrId: string, newTitle: string) {
322
+ return updatePage(urlOrId, [
323
+ { target: "title", action: "replace", content: newTitle },
324
+ ]);
325
+ }
326
+
327
+ /**
328
+ * Append HTML content to a page's body.
329
+ */
330
+ export async function appendToPage(urlOrId: string, htmlContent: string) {
331
+ return updatePage(urlOrId, [
332
+ { target: "body", action: "append", content: htmlContent },
333
+ ]);
334
+ }
335
+
336
+ /**
337
+ * Rename a section.
338
+ */
339
+ export async function renameSection(ref: string, newName: string) {
340
+ const { apiBase, sectionId } = await resolveSectionRef(ref);
341
+ const res = await graphFetch(`${apiBase}/onenote/sections/${sectionId}`, {
342
+ method: "PATCH",
343
+ body: JSON.stringify({ displayName: newName }),
344
+ });
345
+ return res.json();
346
+ }
347
+
348
+ /**
349
+ * Rename a notebook.
350
+ */
351
+ export async function renameNotebook(ref: string, newName: string) {
352
+ const { apiBase, notebookId, displayName } = await resolveNotebookRef(ref);
353
+
354
+ // For site-scoped notebooks, the OneNote PATCH endpoint is not supported.
355
+ // Look up the DriveItem by path, then PATCH by item ID.
356
+ if (apiBase.startsWith("/sites/") && displayName) {
357
+ const siteId = apiBase.replace(/^\/sites\//, "");
358
+ const itemRes = await graphFetch(
359
+ `/sites/${siteId}/drive/root:/Notebooks/${encodeURIComponent(displayName)}:`
360
+ );
361
+ const item: any = await itemRes.json();
362
+ if (!item.id) throw new Error(`Could not find DriveItem for notebook '${displayName}'.`);
363
+ await graphFetch(`/sites/${siteId}/drive/items/${item.id}`, {
364
+ method: "PATCH",
365
+ body: JSON.stringify({ name: newName }),
366
+ });
367
+ return { displayName: newName };
368
+ }
369
+
370
+ const res = await graphFetch(`${apiBase}/onenote/notebooks/${notebookId}`, {
371
+ method: "PATCH",
372
+ body: JSON.stringify({ displayName: newName }),
373
+ });
374
+ return res.json();
375
+ }
376
+
377
+ /**
378
+ * Copy a section into a destination notebook. Returns the async operation
379
+ * URL (Operation-Location header) that Graph provides; callers can poll it.
380
+ * Source and destination must be in /me/onenote (SharePoint site-scoped
381
+ * cross-apiBase copies are not supported by Graph).
382
+ */
383
+ export async function copySectionToNotebook(
384
+ sectionRef: string,
385
+ destNotebookRef: string
386
+ ): Promise<{ operationUrl: string; sourceApiBase: string; destApiBase: string }> {
387
+ const src = await resolveSectionRef(sectionRef);
388
+ const dst = await resolveNotebookRef(destNotebookRef);
389
+ if (src.apiBase !== dst.apiBase) {
390
+ throw new Error(
391
+ `Cross-site section copy is not supported by Graph (source=${src.apiBase}, dest=${dst.apiBase}).`
392
+ );
393
+ }
394
+ const res = await graphFetch(`${src.apiBase}/onenote/sections/${src.sectionId}/copyToNotebook`, {
395
+ method: "POST",
396
+ body: JSON.stringify({ id: dst.notebookId }),
397
+ });
398
+ const operationUrl = res.headers.get("Operation-Location") ?? "";
399
+ return { operationUrl, sourceApiBase: src.apiBase, destApiBase: dst.apiBase };
400
+ }
401
+
402
+ /**
403
+ * Poll a Graph OneNote async operation until it completes or times out.
404
+ * See: https://learn.microsoft.com/graph/api/onenoteoperation-get
405
+ */
406
+ export async function waitForOperation(
407
+ operationUrl: string,
408
+ options?: { timeoutMs?: number; pollIntervalMs?: number; onProgress?: (status: string) => void }
409
+ ): Promise<{ status: string; resourceLocation?: string; error?: any }> {
410
+ const timeoutMs = options?.timeoutMs ?? 5 * 60 * 1000;
411
+ const pollIntervalMs = options?.pollIntervalMs ?? 2000;
412
+ const deadline = Date.now() + timeoutMs;
413
+ while (Date.now() < deadline) {
414
+ const res = await graphFetch(operationUrl);
415
+ const data: any = await res.json();
416
+ options?.onProgress?.(data.status);
417
+ if (data.status === "completed" || data.status === "failed") {
418
+ return { status: data.status, resourceLocation: data.resourceLocation, error: data.error };
419
+ }
420
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
421
+ }
422
+ throw new Error(`Operation did not complete within ${timeoutMs}ms: ${operationUrl}`);
423
+ }
424
+
425
+ export async function createPage(sectionId: string, title: string, htmlBody: string) {
426
+ const { apiBase, sectionId: resolvedSectionId } = await resolveSectionRef(sectionId);
427
+ const html = `
428
+ <!DOCTYPE html>
429
+ <html>
430
+ <head>
431
+ <title>${title}</title>
432
+ </head>
433
+ <body>
434
+ ${htmlBody}
435
+ </body>
436
+ </html>`;
437
+
438
+ const res = await graphFetch(`${apiBase}/onenote/sections/${resolvedSectionId}/pages`, {
439
+ method: "POST",
440
+ headers: { "Content-Type": "text/html" },
441
+ body: html,
442
+ });
443
+ return res.json();
444
+ }
445
+
446
+ export async function deletePage(urlOrId: string) {
447
+ const { apiBase, pageId } = await resolvePageRef(urlOrId);
448
+ await graphFetch(`${apiBase}/onenote/pages/${pageId}`, { method: "DELETE" });
449
+ }
450
+
451
+ // --- Search ---
452
+
453
+ async function resolveOneNoteUrl(filePath: string): Promise<string> {
454
+ // Get the driveItem to obtain the proper Doc.aspx URL with sourcedoc GUID
455
+ try {
456
+ const match = decodeURIComponent(new URL(filePath).pathname).match(/Documents\/(.+)/);
457
+ if (!match) return filePath;
458
+ const encoded = match[1].split("/").map((s) => encodeURIComponent(s)).join("/");
459
+ const res = await graphFetch(`/me/drive/root:/${encoded}?$select=webUrl`);
460
+ const item = (await res.json()) as any;
461
+ // webUrl has format: ...Doc.aspx?sourcedoc={GUID}&file=name.one&action=edit...
462
+ // Clean it up
463
+ return item.webUrl?.split("&mobileredirect")[0] ?? filePath;
464
+ } catch {
465
+ return filePath;
466
+ }
467
+ }
468
+
469
+ export async function searchPages(query: string) {
470
+ // Use Microsoft Graph Search API with listItem to search OneNote content (full-text)
471
+ const res = await graphFetch("/search/query", {
472
+ method: "POST",
473
+ body: JSON.stringify({
474
+ requests: [
475
+ {
476
+ entityTypes: ["listItem"],
477
+ query: { queryString: `${query} FileExtension:one` },
478
+ from: 0,
479
+ size: 25,
480
+ fields: ["title", "path", "parentLink", "spWebUrl"],
481
+ },
482
+ ],
483
+ }),
484
+ });
485
+ const data = (await res.json()) as any;
486
+ const hits = data.value?.[0]?.hitsContainers?.[0]?.hits ?? [];
487
+ const results = hits
488
+ .map((hit: any) => {
489
+ const r = hit.resource ?? {};
490
+ const fields = r.fields ?? {};
491
+ const rawSummary = (hit.summary ?? "")
492
+ .replace(/<c0>/g, "**")
493
+ .replace(/<\/c0>/g, "**")
494
+ .replace(/<ddd\/>/g, "...")
495
+ .replace(/<[^>]*>/g, "")
496
+ .trim();
497
+ const filePath = fields.path ?? r.webUrl ?? "";
498
+ const pathMatch = filePath.match(/Documents\/(?:Notebooks\/)?([^/]+)\//);
499
+ const notebook = pathMatch ? decodeURIComponent(pathMatch[1]) : "";
500
+ return {
501
+ id: r.id ?? hit.hitId,
502
+ section: fields.title ?? (r.name ?? "").replace(/\.one$/, ""),
503
+ notebook,
504
+ summary: rawSummary,
505
+ filePath,
506
+ url: "",
507
+ lastModifiedDateTime: r.lastModifiedDateTime ?? "",
508
+ };
509
+ })
510
+ .filter((r: any) => r.summary.length > 0);
511
+
512
+ // Resolve proper OneNote Online URLs in parallel
513
+ await Promise.all(
514
+ results.map(async (r: any) => {
515
+ r.url = await resolveOneNoteUrl(r.filePath);
516
+ })
517
+ );
518
+ return results;
519
+ }
520
+
521
+ // --- Read page by URL ---
522
+
523
+ /**
524
+ * Parse a OneNote Online URL to determine type and extract GUIDs.
525
+ */
526
+ interface ParsedOneNoteUrl {
527
+ type: "page" | "section" | "notebook" | "unknown";
528
+ sectionGuid?: string;
529
+ pageGuid?: string;
530
+ notebookId?: string;
531
+ fileName?: string; // from file= param or .one path basename
532
+ // SharePoint / business notebook resolution hints
533
+ siteRef?: string; // e.g. "host:/personal/user" for /sites endpoint lookup
534
+ notebookName?: string; // from direct notebook path basename
535
+ sectionName?: string; // from wd=target first segment (with .one stripped)
536
+ pageTitle?: string; // from wd=target second segment (unescaped)
537
+ // Direct Graph IDs derived from Doc.aspx wd* params (most reliable resolution)
538
+ graphSectionId?: string; // "1-<wdsectionfileid>"
539
+ graphPageId?: string; // "1-<wdpartid-guid-compact>!<rev>-<wdsectionfileid>"
540
+ }
541
+
542
+ function unescapeOneNoteName(s: string): string {
543
+ return s.replace(/\\(.)/g, "$1");
544
+ }
545
+
546
+ function parseOneNoteUrl(url: string): ParsedOneNoteUrl {
547
+ const decoded = decodeURIComponent(url);
548
+ let fileName: string | undefined;
549
+
550
+ const sourcedocMatch = decoded.match(/sourcedoc=\{?([0-9a-f-]+)\}?/i);
551
+ let sectionGuid = sourcedocMatch?.[1]?.toLowerCase();
552
+
553
+ // SharePoint siteRef from the URL host + /personal/{user} or /sites/{name} segment
554
+ let siteRef: string | undefined;
555
+ let notebookName: string | undefined;
556
+ try {
557
+ const u = new URL(url);
558
+ if (/sharepoint\.com$/i.test(u.hostname)) {
559
+ const p = decodeURIComponent(u.pathname);
560
+ const personal = p.match(/\/(personal\/[^/]+)/i);
561
+ const site = p.match(/\/(sites|teams)\/([^/]+)/i);
562
+ if (personal) siteRef = `${u.hostname}:/${personal[1]}:`;
563
+ else if (site) siteRef = `${u.hostname}:/${site[1]}/${site[2]}:`;
564
+
565
+ const lastSegment = p.split("/").filter(Boolean).at(-1);
566
+ if (lastSegment && !/\.aspx$/i.test(lastSegment)) {
567
+ if (/\.one$/i.test(lastSegment)) fileName = lastSegment.replace(/\.one$/i, "");
568
+ else notebookName = lastSegment;
569
+ }
570
+ }
571
+ } catch {}
572
+
573
+ // Doc.aspx URLs expose the current .one file as the `file=` query parameter.
574
+ const fileMatch = decoded.match(/[?&]file=([^&]+)/i);
575
+ if (fileMatch) {
576
+ fileName = decodeURIComponent(fileMatch[1]).replace(/\.one$/i, "");
577
+ }
578
+
579
+ // wd=target(sectionName|SECTION_GUID/pageTitle|PAGE_GUID/)
580
+ // Page titles may contain escaped ')' as '\\)' — skip those when finding the terminator.
581
+ const wdTargetMatch = decoded.match(/wd=target\(((?:[^)\\]|\\.)*)\)/i);
582
+ let pageGuid: string | undefined;
583
+ let sectionName: string | undefined;
584
+ let pageTitle: string | undefined;
585
+ if (wdTargetMatch) {
586
+ const target = wdTargetMatch[1];
587
+ // Capture "name|guid" pairs, where name may contain backslash escapes.
588
+ const pairs = [...target.matchAll(/((?:[^|\\]|\\.)+)\|([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi)];
589
+ if (pairs.length >= 1) {
590
+ sectionName = unescapeOneNoteName(pairs[0][1]).replace(/\.one$/i, "");
591
+ sectionGuid = pairs[0][2].toLowerCase();
592
+ }
593
+ if (pairs.length >= 2) {
594
+ // Second pair's name begins with "/" (segment separator) — strip it.
595
+ pageTitle = unescapeOneNoteName(pairs[1][1].replace(/^\//, ""));
596
+ pageGuid = pairs[1][2].toLowerCase();
597
+ } else if (pairs.length === 0) {
598
+ // Path-only target, e.g. target(/Home.one/) or target(/Sec.one/Page/).
599
+ // Segments ending in ".one" name the section; a trailing segment names the page.
600
+ const segs = target.split("/").map((s) => unescapeOneNoteName(s)).filter(Boolean);
601
+ const secIdx = segs.findIndex((s) => /\.one$/i.test(s));
602
+ if (secIdx >= 0) {
603
+ if (!sectionName) sectionName = segs[secIdx].replace(/\.one$/i, "");
604
+ if (segs[secIdx + 1] && !pageTitle) pageTitle = segs[secIdx + 1];
605
+ }
606
+ }
607
+ }
608
+
609
+ // Doc.aspx wd* params carry the authoritative Graph IDs. `wdsectionfileid`
610
+ // is the section's file GUID (Graph section id = "1-<guid>"); `wdpartid`
611
+ // is "{page-object-guid}{revision}" and yields the Graph page id.
612
+ const wdSectionMatch = decoded.match(
613
+ /wdsectionfileid=\{?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}?/i
614
+ );
615
+ const wdSectionFileId = wdSectionMatch?.[1]?.toLowerCase();
616
+ const wdPartMatch = decoded.match(
617
+ /wdpartid=\{?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}?\{(\d+)\}/i
618
+ );
619
+ let graphSectionId: string | undefined;
620
+ let graphPageId: string | undefined;
621
+ if (wdSectionFileId) {
622
+ graphSectionId = `1-${wdSectionFileId}`;
623
+ if (wdPartMatch) {
624
+ const compact = wdPartMatch[1].replace(/-/g, "").toLowerCase();
625
+ const rev = wdPartMatch[2];
626
+ graphPageId = `1-${compact}!${rev}-${wdSectionFileId}`;
627
+ }
628
+ }
629
+
630
+ if (!sectionName && fileName && sectionGuid) {
631
+ sectionName = fileName;
632
+ }
633
+
634
+ const nbMatch = decoded.match(/notebooks\/(1-[0-9a-f-]+)/i);
635
+ const notebookId = nbMatch?.[1];
636
+
637
+ const base = { siteRef, fileName, notebookName, sectionName, pageTitle, graphSectionId, graphPageId };
638
+ if (graphPageId || (pageGuid && sectionGuid)) {
639
+ return { type: "page", sectionGuid, pageGuid, ...base };
640
+ }
641
+ if (sectionGuid || graphSectionId) return { type: "section", sectionGuid, ...base };
642
+ if (notebookId || notebookName) return { type: "notebook", notebookId, ...base };
643
+ return { type: "unknown", ...base };
644
+ }
645
+
646
+ // --- Site-scoped resolution (bypasses 5000-item limit on /me/onenote/*) ---
647
+
648
+ const siteIdCache = new Map<string, string>();
649
+
650
+ async function resolveSiteId(siteRef: string): Promise<string> {
651
+ if (siteIdCache.has(siteRef)) return siteIdCache.get(siteRef)!;
652
+ const res = await graphFetch(`/sites/${siteRef}?$select=id`);
653
+ const site = (await res.json()) as any;
654
+ siteIdCache.set(siteRef, site.id);
655
+ return site.id;
656
+ }
657
+
658
+ function odataEscape(s: string): string {
659
+ return s.replace(/'/g, "''");
660
+ }
661
+
662
+ function extractSectionIdFromClientUrl(href: string | undefined, wantGuid?: string): boolean {
663
+ if (!href || !wantGuid) return false;
664
+ const m = decodeURIComponent(href).match(/section-id=([0-9a-f-]+)/i);
665
+ return (m?.[1]?.toLowerCase() ?? "") === wantGuid;
666
+ }
667
+
668
+ function extractPageIdFromClientUrl(href: string | undefined, wantGuid?: string): boolean {
669
+ if (!href || !wantGuid) return false;
670
+ const m = decodeURIComponent(href).match(/page-id=([0-9a-f-]+)/i);
671
+ return (m?.[1]?.toLowerCase() ?? "") === wantGuid;
672
+ }
673
+
674
+ async function resolveSharePointNotebook(
675
+ siteId: string,
676
+ notebookName: string
677
+ ): Promise<{ id: string; displayName: string } | null> {
678
+ const res = await graphFetch(
679
+ `/sites/${siteId}/onenote/notebooks?$filter=displayName eq '${odataEscape(notebookName)}'&$select=id,displayName&$top=50`
680
+ );
681
+ const data: GraphResponse<any> = await res.json();
682
+ if (!data.value?.length) return null;
683
+ if (data.value.length > 1) {
684
+ const lines = data.value.map((n: any) => ` - ${n.id}`).join("\n");
685
+ throw new Error(
686
+ `Multiple notebooks named '${notebookName}' in site (${data.value.length} matches). Please rename for uniqueness or pass a Graph ID.\nCandidates:\n${lines}`
687
+ );
688
+ }
689
+ return {
690
+ id: data.value[0].id,
691
+ displayName: data.value[0].displayName ?? notebookName,
692
+ };
693
+ }
694
+
695
+ async function resolveSharePointSection(
696
+ siteId: string,
697
+ sectionName: string,
698
+ sectionGuid?: string
699
+ ): Promise<{ id: string; displayName: string } | null> {
700
+ const res = await graphFetch(
701
+ `/sites/${siteId}/onenote/sections?$filter=displayName eq '${odataEscape(sectionName)}'&$select=id,displayName,links&$top=50`
702
+ );
703
+ const data: GraphResponse<any> = await res.json();
704
+ if (!data.value?.length) return null;
705
+ if (data.value.length === 1 || !sectionGuid) return data.value[0];
706
+ // Multiple matches — disambiguate by section-id in oneNoteClientUrl
707
+ const match = data.value.find((s: any) =>
708
+ extractSectionIdFromClientUrl(s.links?.oneNoteClientUrl?.href, sectionGuid)
709
+ );
710
+ return match ?? data.value[0];
711
+ }
712
+
713
+ async function resolveSharePointPage(
714
+ siteId: string,
715
+ sectionId: string,
716
+ pageTitle: string,
717
+ pageGuid?: string
718
+ ): Promise<{ id: string; title: string; webUrl: string } | null> {
719
+ const res = await graphFetch(
720
+ `/sites/${siteId}/onenote/sections/${sectionId}/pages?$filter=title eq '${odataEscape(pageTitle)}'&$select=id,title,links&$top=50`
721
+ );
722
+ const data: GraphResponse<any> = await res.json();
723
+ const mapOne = (p: any) => ({
724
+ id: p.id,
725
+ title: p.title ?? "(untitled)",
726
+ webUrl: p.links?.oneNoteWebUrl?.href ?? "",
727
+ });
728
+ if (!data.value?.length) return null;
729
+ if (data.value.length === 1 || !pageGuid) return mapOne(data.value[0]);
730
+ const match = data.value.find((p: any) =>
731
+ extractPageIdFromClientUrl(p.links?.oneNoteClientUrl?.href, pageGuid)
732
+ );
733
+ return mapOne(match ?? data.value[0]);
734
+ }
735
+
736
+ function looksLikeNotebookId(s: string): boolean {
737
+ return /^[0-9]-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);
738
+ }
739
+
740
+ function looksLikeGraphId(s: string): boolean {
741
+ // Single-part (`1-<hex>`) or composite page id (`1-<hex>!1-<guid>`) as emitted by Graph.
742
+ return /^[0-9]-[0-9a-f-]{10,}(?:![0-9]-[0-9a-f-]{10,})?$/i.test(s);
743
+ }
744
+
745
+ export type ResolvedPath = {
746
+ apiBase: string;
747
+ notebookId?: string;
748
+ sectionId?: string;
749
+ pageId?: string;
750
+ notebookName?: string;
751
+ sectionName?: string;
752
+ pageTitle?: string;
753
+ };
754
+
755
+ function uniqueOrThrow<T extends { id: string; displayName?: string; title?: string; links?: any }>(
756
+ items: T[],
757
+ kind: "notebook" | "section" | "page",
758
+ name: string,
759
+ parent?: string
760
+ ): T {
761
+ if (items.length === 0) {
762
+ throw new Error(`${kind} '${name}'${parent ? ` in '${parent}'` : ""} not found.`);
763
+ }
764
+ if (items.length > 1) {
765
+ const ctx = parent ? ` in '${parent}'` : "";
766
+ const lines = items.map((i) => {
767
+ const label = (i as any).displayName ?? (i as any).title ?? "(untitled)";
768
+ const url = i.links?.oneNoteWebUrl?.href ?? i.links?.oneNoteClientUrl?.href ?? "";
769
+ return ` - ${i.id}${url ? ` ${url}` : ""} [${label}]`;
770
+ });
771
+ throw new Error(
772
+ `Multiple ${kind}s named '${name}'${ctx} (${items.length} matches). Please rename for uniqueness or use URL/ID.\nCandidates:\n${lines.join("\n")}`
773
+ );
774
+ }
775
+ return items[0]!;
776
+ }
777
+
778
+ async function resolveByPath(path: string): Promise<ResolvedPath> {
779
+ const segments = path.split("/").filter((s) => s.length > 0);
780
+ if (segments.length === 0) throw new Error("Empty path.");
781
+ if (segments.length > 3) throw new Error(`Path too deep (max 3 segments): ${path}`);
782
+
783
+ // Segment 1: notebook
784
+ const nbName = segments[0]!;
785
+ const notebooks = (await getCachedNotebooks()).filter((n) => n.displayName === nbName);
786
+ if (notebooks.length === 0) {
787
+ const fresh = (await getCachedNotebooks(true)).filter((n) => n.displayName === nbName);
788
+ if (fresh.length === 0) {
789
+ throw new Error(`Notebook '${nbName}' not found. Run 'onenote notebooks list' to see available names.`);
790
+ }
791
+ notebooks.push(...fresh);
792
+ }
793
+ const nb = uniqueOrThrow(
794
+ notebooks.map((n) => ({ id: n.id, displayName: n.displayName, links: { oneNoteWebUrl: { href: n.webUrl } } })),
795
+ "notebook",
796
+ nbName
797
+ );
798
+ const nbRef = nb.links.oneNoteWebUrl.href
799
+ ? await resolveNotebookRef(nb.links.oneNoteWebUrl.href)
800
+ : { apiBase: "/me", notebookId: nb.id, displayName: nb.displayName };
801
+
802
+ if (segments.length === 1) {
803
+ return { apiBase: nbRef.apiBase, notebookId: nbRef.notebookId, notebookName: nbRef.displayName };
804
+ }
805
+
806
+ // Segment 2: section — try site-scoped filter; fall back to sync cache if 5000-limit error.
807
+ const sectionName = segments[1]!;
808
+ let section: { id: string; displayName: string; links?: any };
809
+ try {
810
+ const sectRes = await graphFetch(
811
+ `${nbRef.apiBase}/onenote/sections?$filter=displayName eq '${odataEscape(sectionName)}'&$expand=parentNotebook($select=id)&$select=id,displayName,links&$top=50`
812
+ );
813
+ const sectData: GraphResponse<any> = await sectRes.json();
814
+ const candidates = (sectData.value ?? []).filter(
815
+ (s: any) => !s.parentNotebook?.id || s.parentNotebook.id === nbRef.notebookId
816
+ );
817
+ section = uniqueOrThrow(candidates, "section", sectionName, nbName);
818
+ } catch (err: any) {
819
+ if (err?.message?.startsWith("Multiple sections") || err?.message?.startsWith("section ")) throw err;
820
+ if (!is5000LimitError(err) && err?.statusCode !== 404) throw err;
821
+ const fromCache = await lookupSectionFromSyncCache(nbName, sectionName);
822
+ if (!fromCache) {
823
+ throw new Error(
824
+ `Section '${sectionName}' in '${nbName}' not resolvable: site exceeds Graph API 5000-item limit. Run 'onenote sync' first, or pass a full URL.`
825
+ );
826
+ }
827
+ section = fromCache;
828
+ }
829
+
830
+ if (segments.length === 2) {
831
+ return {
832
+ apiBase: nbRef.apiBase,
833
+ notebookId: nbRef.notebookId,
834
+ sectionId: section.id,
835
+ notebookName: nbRef.displayName,
836
+ sectionName: section.displayName,
837
+ };
838
+ }
839
+
840
+ // Segment 3: page
841
+ const pageTitle = segments[2]!;
842
+ let page: { id: string; title: string; links?: any };
843
+ try {
844
+ const pageRes = await graphFetch(
845
+ `${nbRef.apiBase}/onenote/sections/${section.id}/pages?$filter=title eq '${odataEscape(pageTitle)}'&$select=id,title,links&$top=50`
846
+ );
847
+ const pageData: GraphResponse<any> = await pageRes.json();
848
+ page = uniqueOrThrow(pageData.value ?? [], "page", pageTitle, `${nbName}/${sectionName}`);
849
+ } catch (err: any) {
850
+ if (err?.message?.startsWith("Multiple pages") || err?.message?.startsWith("page ")) throw err;
851
+ if (!is5000LimitError(err) && err?.statusCode !== 404) throw err;
852
+ const fromCache = await lookupPageFromSyncCache(nbName, sectionName, pageTitle);
853
+ if (!fromCache) {
854
+ throw new Error(
855
+ `Page '${pageTitle}' in '${nbName}/${sectionName}' not resolvable: site exceeds Graph API 5000-item limit. Run 'onenote sync' first, or pass a full URL.`
856
+ );
857
+ }
858
+ page = fromCache;
859
+ }
860
+
861
+ return {
862
+ apiBase: nbRef.apiBase,
863
+ notebookId: nbRef.notebookId,
864
+ sectionId: section.id,
865
+ pageId: page.id,
866
+ notebookName: nbRef.displayName,
867
+ sectionName: section.displayName,
868
+ pageTitle: page.title,
869
+ };
870
+ }
871
+
872
+ async function resolveNotebookRef(
873
+ urlOrId: string
874
+ ): Promise<{ apiBase: string; notebookId: string; displayName?: string }> {
875
+ if (!/^https?:\/\//i.test(urlOrId)) {
876
+ if (looksLikeNotebookId(urlOrId)) {
877
+ return { apiBase: "/me", notebookId: urlOrId };
878
+ }
879
+ // Name or path — delegate to path resolver (handles uniqueness)
880
+ const r = await resolveByPath(urlOrId);
881
+ if (!r.notebookId) throw new Error(`Path '${urlOrId}' does not resolve to a notebook.`);
882
+ return { apiBase: r.apiBase, notebookId: r.notebookId, displayName: r.notebookName };
883
+ }
884
+
885
+ const parsed = parseOneNoteUrl(urlOrId);
886
+ if (parsed.notebookId) {
887
+ return { apiBase: "/me", notebookId: parsed.notebookId, displayName: parsed.notebookName };
888
+ }
889
+
890
+ if (!parsed.siteRef || !parsed.notebookName) {
891
+ throw new Error("URL does not point to a notebook with a resolvable name.");
892
+ }
893
+
894
+ const siteId = await resolveSiteId(parsed.siteRef);
895
+ const notebook = await resolveSharePointNotebook(siteId, parsed.notebookName);
896
+ if (!notebook) throw new Error(`Notebook '${parsed.notebookName}' not found.`);
897
+ return { apiBase: `/sites/${siteId}`, notebookId: notebook.id, displayName: notebook.displayName };
898
+ }
899
+
900
+ async function resolveSectionRef(
901
+ urlOrId: string
902
+ ): Promise<{ apiBase: string; sectionId: string; displayName?: string }> {
903
+ if (!/^https?:\/\//i.test(urlOrId)) {
904
+ if (urlOrId.includes("/") || !looksLikeGraphId(urlOrId)) {
905
+ const r = await resolveByPath(urlOrId);
906
+ if (!r.sectionId) throw new Error(`Path '${urlOrId}' does not resolve to a section (need notebook/section).`);
907
+ return { apiBase: r.apiBase, sectionId: r.sectionId, displayName: r.sectionName };
908
+ }
909
+ return { apiBase: "/me", sectionId: urlOrId };
910
+ }
911
+
912
+ const parsed = parseOneNoteUrl(urlOrId);
913
+ if (parsed.siteRef) {
914
+ const siteId = await resolveSiteId(parsed.siteRef);
915
+ const sectionName = parsed.sectionName ?? parsed.fileName;
916
+ if (sectionName) {
917
+ const section = await resolveSharePointSection(siteId, sectionName, parsed.sectionGuid);
918
+ if (section) {
919
+ return { apiBase: `/sites/${siteId}`, sectionId: section.id, displayName: section.displayName };
920
+ }
921
+ }
922
+ }
923
+
924
+ if (parsed.sectionGuid) {
925
+ return {
926
+ apiBase: "/me",
927
+ sectionId: `0-${parsed.sectionGuid}`,
928
+ displayName: parsed.sectionName ?? parsed.fileName,
929
+ };
930
+ }
931
+
932
+ throw new Error("URL does not point to a specific section.");
933
+ }
934
+
935
+ /**
936
+ * Resolve a URL-or-ID reference to the correct Graph API base + page ID.
937
+ * - If the input looks like an http(s) URL, parse it and resolve via the
938
+ * SharePoint site-scoped endpoint when applicable (bypasses 5000-item limit).
939
+ * - Otherwise, treat the input as a Graph page ID under /me/onenote/.
940
+ */
941
+ async function resolvePageRef(
942
+ urlOrId: string
943
+ ): Promise<{ apiBase: string; pageId: string; title?: string; webUrl?: string }> {
944
+ if (!/^https?:\/\//i.test(urlOrId)) {
945
+ if (urlOrId.includes("/") || !looksLikeGraphId(urlOrId)) {
946
+ const r = await resolveByPath(urlOrId);
947
+ if (!r.pageId) throw new Error(`Path '${urlOrId}' does not resolve to a page (need notebook/section/page).`);
948
+ return { apiBase: r.apiBase, pageId: r.pageId, title: r.pageTitle };
949
+ }
950
+ return { apiBase: "/me", pageId: urlOrId };
951
+ }
952
+ const parsed = parseOneNoteUrl(urlOrId);
953
+ if (!parsed.siteRef || !parsed.sectionName || !parsed.pageTitle) {
954
+ throw new Error(
955
+ "URL does not point to a specific page (need both section and page in wd=target)."
956
+ );
957
+ }
958
+ const siteId = await resolveSiteId(parsed.siteRef);
959
+ const section = await resolveSharePointSection(siteId, parsed.sectionName, parsed.sectionGuid);
960
+ if (!section) throw new Error(`Section '${parsed.sectionName}' not found.`);
961
+ const page = await resolveSharePointPage(siteId, section.id, parsed.pageTitle, parsed.pageGuid);
962
+ if (!page) throw new Error(`Page '${parsed.pageTitle}' not found in section '${section.displayName}'.`);
963
+ return { apiBase: `/sites/${siteId}`, pageId: page.id, title: page.title, webUrl: page.webUrl };
964
+ }
965
+
966
+ /**
967
+ * List pages in a section by its sourcedoc GUID.
968
+ * Returns array of { id, title, webUrl }.
969
+ */
970
+ export async function listSectionPagesByGuid(
971
+ sectionGuid: string
972
+ ): Promise<{ id: string; title: string; webUrl: string }[]> {
973
+ const res = await graphFetch(
974
+ `/me/onenote/sections/0-${sectionGuid}/pages?$select=id,title,links&$top=100`
975
+ );
976
+ const data: GraphResponse<any> = await res.json();
977
+ return (data.value ?? []).map((p: any) => ({
978
+ id: p.id,
979
+ title: p.title ?? "(untitled)",
980
+ webUrl: p.links?.oneNoteWebUrl?.href ?? "",
981
+ }));
982
+ }
983
+
984
+ /**
985
+ * Read a OneNote URL. Behavior depends on URL type:
986
+ * - Page URL → returns page content
987
+ * - Section URL → returns page list (tree view)
988
+ * - Notebook URL → returns section list
989
+ */
990
+ export async function readOneNoteUrl(
991
+ url: string,
992
+ options?: { downloadAssets?: boolean }
993
+ ): Promise<{
994
+ type: "page" | "section" | "notebook" | "resource";
995
+ title: string;
996
+ content: string; // text content or tree view
997
+ html?: string;
998
+ pageUrl?: string;
999
+ assetPath?: string;
1000
+ breadcrumb?: string;
1001
+ }> {
1002
+ if (isOneNoteResourceUrl(url)) {
1003
+ const resource = await renderResourceForRead(url);
1004
+ return {
1005
+ type: "resource",
1006
+ title: resource.title,
1007
+ content: resource.content,
1008
+ assetPath: resource.assetPath,
1009
+ };
1010
+ }
1011
+
1012
+ // Non-URL input: treat as path or Graph ID
1013
+ if (!/^https?:\/\//i.test(url)) {
1014
+ // Raw Graph IDs (no "/") — route directly via resolvePageRef to preserve ID support
1015
+ if (!url.includes("/") && looksLikeGraphId(url)) {
1016
+ try {
1017
+ const r = await resolvePageRef(url);
1018
+ const contentRes = await graphFetch(`${r.apiBase}/onenote/pages/${r.pageId}/content`);
1019
+ const html = await contentRes.text();
1020
+ return {
1021
+ type: "page",
1022
+ title: r.title ?? "(untitled)",
1023
+ content: await renderHtmlForRead(html, options),
1024
+ html,
1025
+ };
1026
+ } catch {
1027
+ // Fall through to path resolution
1028
+ }
1029
+ }
1030
+ const r = await resolveByPath(url);
1031
+ if (r.pageId) {
1032
+ const contentRes = await graphFetch(`${r.apiBase}/onenote/pages/${r.pageId}/content`);
1033
+ const html = await contentRes.text();
1034
+ const crumbs = [r.notebookName, r.sectionName, r.pageTitle].filter(Boolean);
1035
+ return {
1036
+ type: "page",
1037
+ title: r.pageTitle ?? "(untitled)",
1038
+ content: await renderHtmlForRead(html, options),
1039
+ html,
1040
+ breadcrumb: crumbs.length > 1 ? crumbs.join(" / ") : undefined,
1041
+ };
1042
+ }
1043
+ if (r.sectionId) {
1044
+ const pagesRes = await graphFetch(
1045
+ `${r.apiBase}/onenote/sections/${r.sectionId}/pages?$select=id,title&$top=100`
1046
+ );
1047
+ const pagesData: GraphResponse<any> = await pagesRes.json();
1048
+ const pageList = pagesData.value ?? [];
1049
+ const tree = pageList.map((p: any, i: number) => `${i + 1}. ${p.title ?? "(untitled)"}`).join("\n");
1050
+ return {
1051
+ type: "section",
1052
+ title: r.sectionName ?? "Section",
1053
+ content: `${r.sectionName} (${pageList.length} pages)\n\n${tree}`,
1054
+ };
1055
+ }
1056
+ if (r.notebookId) {
1057
+ const sections = await listSections(url);
1058
+ const tree = sections.map((s: any, i: number) => `${i + 1}. ${s.displayName ?? "(untitled)"}`).join("\n");
1059
+ return {
1060
+ type: "notebook",
1061
+ title: r.notebookName ?? "Notebook",
1062
+ content: `${r.notebookName} (${sections.length} sections)\n\n${tree}`,
1063
+ };
1064
+ }
1065
+ }
1066
+
1067
+ const parsed = parseOneNoteUrl(url);
1068
+
1069
+ // --- SharePoint direct-by-ID path: Doc.aspx URLs carry wdsectionfileid /
1070
+ // wdpartid, which map straight to Graph section/page IDs. Resolving by
1071
+ // ID avoids name lookups (and the 5000-item limit) entirely.
1072
+ if (parsed.siteRef && (parsed.graphPageId || parsed.graphSectionId)) {
1073
+ try {
1074
+ const siteId = await resolveSiteId(parsed.siteRef);
1075
+ if (parsed.graphPageId) {
1076
+ const pageId = encodeURIComponent(parsed.graphPageId);
1077
+ const contentRes = await graphFetch(`/sites/${siteId}/onenote/pages/${pageId}/content`);
1078
+ const html = await contentRes.text();
1079
+ let title = "(untitled)";
1080
+ let pageUrl: string | undefined;
1081
+ try {
1082
+ const metaRes = await graphFetch(`/sites/${siteId}/onenote/pages/${pageId}?$select=id,title,links`);
1083
+ const meta = (await metaRes.json()) as any;
1084
+ title = meta.title || title;
1085
+ pageUrl = meta.links?.oneNoteWebUrl?.href;
1086
+ } catch {}
1087
+ return {
1088
+ type: "page",
1089
+ title,
1090
+ content: await renderHtmlForRead(html, options),
1091
+ html,
1092
+ pageUrl,
1093
+ };
1094
+ }
1095
+ // Section-level: list pages as a tree.
1096
+ const secRes = await graphFetch(`/sites/${siteId}/onenote/sections/${parsed.graphSectionId}?$select=displayName`);
1097
+ const sec = (await secRes.json()) as any;
1098
+ const pagesRes = await graphFetch(
1099
+ `/sites/${siteId}/onenote/sections/${parsed.graphSectionId}/pages?$select=id,title&$top=100`
1100
+ );
1101
+ const pagesData: GraphResponse<any> = await pagesRes.json();
1102
+ const pageList = pagesData.value ?? [];
1103
+ const tree = pageList.map((p: any, i: number) => `${i + 1}. ${p.title ?? "(untitled)"}`).join("\n");
1104
+ return {
1105
+ type: "section",
1106
+ title: sec.displayName ?? "Section",
1107
+ content: `${sec.displayName ?? "Section"} (${pageList.length} pages)\n\n${tree}`,
1108
+ };
1109
+ } catch (err: any) {
1110
+ if (!is5000LimitError(err) && err?.statusCode !== 404) throw err;
1111
+ }
1112
+ }
1113
+
1114
+ // --- SharePoint (business) path: use site-scoped endpoints to bypass
1115
+ // the 5000-OneNote-item limit on /me/onenote/*.
1116
+ if (parsed.siteRef && parsed.sectionName) {
1117
+ try {
1118
+ const siteId = await resolveSiteId(parsed.siteRef);
1119
+ const section = await resolveSharePointSection(siteId, parsed.sectionName, parsed.sectionGuid);
1120
+ if (section) {
1121
+ // Page?
1122
+ if (parsed.pageTitle) {
1123
+ const page = await resolveSharePointPage(siteId, section.id, parsed.pageTitle, parsed.pageGuid);
1124
+ if (page) {
1125
+ const contentRes = await graphFetch(`/sites/${siteId}/onenote/pages/${page.id}/content`);
1126
+ const html = await contentRes.text();
1127
+ return {
1128
+ type: "page",
1129
+ title: page.title,
1130
+ content: await renderHtmlForRead(html, options),
1131
+ html,
1132
+ pageUrl: page.webUrl,
1133
+ };
1134
+ }
1135
+ }
1136
+ // Section tree view
1137
+ const pagesRes = await graphFetch(
1138
+ `/sites/${siteId}/onenote/sections/${section.id}/pages?$select=id,title&$top=100`
1139
+ );
1140
+ const pagesData: GraphResponse<any> = await pagesRes.json();
1141
+ const pageList = pagesData.value ?? [];
1142
+ const tree = pageList.map((p: any, i: number) => `${i + 1}. ${p.title ?? "(untitled)"}`).join("\n");
1143
+ return {
1144
+ type: "section",
1145
+ title: section.displayName,
1146
+ content: `${section.displayName} (${pageList.length} pages)\n\n${tree}`,
1147
+ };
1148
+ }
1149
+ } catch (err: any) {
1150
+ // Fall through to legacy paths; include message in final error if none match.
1151
+ if (!is5000LimitError(err) && err?.statusCode !== 404) throw err;
1152
+ }
1153
+ }
1154
+
1155
+ // --- Page ---
1156
+ if (parsed.type === "page" && parsed.sectionGuid) {
1157
+ const pages = await listSectionPagesByGuid(parsed.sectionGuid);
1158
+ // Find matching page by GUID
1159
+ let targetPage: any = null;
1160
+ for (const page of pages) {
1161
+ const urlDecoded = decodeURIComponent(page.webUrl);
1162
+ const urlGuids = urlDecoded.match(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi) ?? [];
1163
+ const lastGuid = urlGuids.length > 0 ? urlGuids[urlGuids.length - 1].toLowerCase() : "";
1164
+ if (parsed.pageGuid && lastGuid === parsed.pageGuid) {
1165
+ targetPage = page;
1166
+ break;
1167
+ }
1168
+ }
1169
+ if (!targetPage && pages.length > 0) targetPage = pages[0];
1170
+ if (targetPage) {
1171
+ const contentRes = await graphFetch(`/me/onenote/pages/${targetPage.id}/content`);
1172
+ const html = await contentRes.text();
1173
+ return {
1174
+ type: "page",
1175
+ title: targetPage.title,
1176
+ content: await renderHtmlForRead(html, options),
1177
+ html,
1178
+ pageUrl: targetPage.webUrl,
1179
+ };
1180
+ }
1181
+ }
1182
+
1183
+ // --- Section ---
1184
+ if ((parsed.type === "section" || parsed.type === "page") && parsed.sectionGuid) {
1185
+ const pages = await listSectionPagesByGuid(parsed.sectionGuid);
1186
+ // Build tree view
1187
+ const tree = pages.map((p, i) => `${i + 1}. ${p.title}`).join("\n");
1188
+ // Get section name
1189
+ let sectionName = "Section";
1190
+ try {
1191
+ const secRes = await graphFetch(`/me/onenote/sections/0-${parsed.sectionGuid}?$select=displayName`);
1192
+ const sec = await secRes.json() as any;
1193
+ sectionName = sec.displayName ?? sectionName;
1194
+ } catch {}
1195
+ return {
1196
+ type: "section",
1197
+ title: sectionName,
1198
+ content: `${sectionName} (${pages.length} pages)\n\n${tree}`,
1199
+ };
1200
+ }
1201
+
1202
+ // --- Notebook ---
1203
+ if (parsed.type === "notebook") {
1204
+ try {
1205
+ const { apiBase, notebookId } = await resolveNotebookRef(url);
1206
+ const nbRes = await graphFetch(`${apiBase}/onenote/notebooks/${notebookId}`);
1207
+ const nb = await nbRes.json() as any;
1208
+ const sections = await listSections(url);
1209
+ const tree = sections.map((s: any, i: number) => `${i + 1}. ${s.displayName ?? s.name ?? "(untitled)"}`).join("\n");
1210
+ return {
1211
+ type: "notebook",
1212
+ title: nb.displayName ?? "Notebook",
1213
+ content: `${nb.displayName} (${sections.length} sections)\n\n${tree}`,
1214
+ };
1215
+ } catch {
1216
+ // Fall through
1217
+ }
1218
+ }
1219
+
1220
+ throw new Error("Could not parse URL or access content. Supported: page, section, or notebook URLs.");
1221
+ }
1222
+
1223
+ // Keep backward compat
1224
+ export async function readPageByUrl(url: string) {
1225
+ const result = await readOneNoteUrl(url);
1226
+ return { title: result.title, html: result.html ?? "", text: result.content, pageUrl: result.pageUrl ?? url };
1227
+ }
1228
+
1229
+ // --- Export traversal ---
1230
+ // A `base` is the Graph endpoint prefix a node lives under, e.g. "/me" for a
1231
+ // consumer account or "/sites/{siteId}" for a SharePoint/business notebook.
1232
+ // All export traversal below is base-relative so one code path serves both.
1233
+
1234
+ export type ExportNode =
1235
+ | { kind: "page"; base: string; id: string; title: string; webUrl?: string }
1236
+ | { kind: "section"; base: string; id: string; title: string; webUrl?: string }
1237
+ | { kind: "sectionGroup"; base: string; id: string; title: string; drivePath?: string }
1238
+ | { kind: "notebook"; base: string; id: string; title: string; drivePath?: string };
1239
+
1240
+ /** GET a collection, following @odata.nextLink until exhausted. */
1241
+ async function graphListAll(path: string): Promise<any[]> {
1242
+ const out: any[] = [];
1243
+ let next: string | null = path;
1244
+ while (next) {
1245
+ const res = await graphFetch(next);
1246
+ const data: GraphResponse<any> = await res.json();
1247
+ out.push(...(data.value ?? []));
1248
+ next = (data["@odata.nextLink"] as string) ?? null;
1249
+ }
1250
+ return out;
1251
+ }
1252
+
1253
+ export async function listSectionPages(
1254
+ base: string,
1255
+ sectionId: string
1256
+ ): Promise<{ id: string; title: string; webUrl?: string }[]> {
1257
+ const pages = await graphListAll(
1258
+ `${base}/onenote/sections/${sectionId}/pages?$select=id,title,links&$top=100&$orderby=order`
1259
+ );
1260
+ return pages.map((p: any) => ({
1261
+ id: p.id,
1262
+ title: p.title ?? "",
1263
+ webUrl: p.links?.oneNoteWebUrl?.href,
1264
+ }));
1265
+ }
1266
+
1267
+ export async function listChildSections(
1268
+ base: string,
1269
+ parentType: "notebooks" | "sectionGroups",
1270
+ parentId: string
1271
+ ): Promise<{ id: string; displayName: string }[]> {
1272
+ const secs = await graphListAll(
1273
+ `${base}/onenote/${parentType}/${parentId}/sections?$select=id,displayName&$top=100`
1274
+ );
1275
+ return secs.map((s: any) => ({ id: s.id, displayName: s.displayName ?? "" }));
1276
+ }
1277
+
1278
+ export async function listChildSectionGroups(
1279
+ base: string,
1280
+ parentType: "notebooks" | "sectionGroups",
1281
+ parentId: string
1282
+ ): Promise<{ id: string; displayName: string }[]> {
1283
+ const groups = await graphListAll(
1284
+ `${base}/onenote/${parentType}/${parentId}/sectionGroups?$select=id,displayName&$top=100`
1285
+ );
1286
+ return groups.map((g: any) => ({ id: g.id, displayName: g.displayName ?? "" }));
1287
+ }
1288
+
1289
+ export async function fetchPageHtml(base: string, pageId: string): Promise<string> {
1290
+ const res = await graphFetch(`${base}/onenote/pages/${encodeURIComponent(pageId)}/content`);
1291
+ return res.text();
1292
+ }
1293
+
1294
+ // Re-resolve a possibly-stale link base-path (a notebook web URL) to the
1295
+ // notebook's *current* URL by matching its name, so internal links survive a
1296
+ // notebook being moved to another folder. Cached (and in-flight deduped) by name.
1297
+ const notebookBaseCache = new Map<string, Promise<string | null>>();
1298
+ export function currentNotebookBaseUrl(staleBasePath: string): Promise<string | null> {
1299
+ let name = "";
1300
+ try {
1301
+ name = decodeURIComponent(new URL(staleBasePath).pathname).split("/").filter(Boolean).pop() ?? "";
1302
+ } catch {
1303
+ return Promise.resolve(null);
1304
+ }
1305
+ if (!name) return Promise.resolve(null);
1306
+ let pending = notebookBaseCache.get(name);
1307
+ if (!pending) {
1308
+ pending = (async () => {
1309
+ try {
1310
+ const nb = (await getCachedNotebooks()).find((n) => n.displayName === name);
1311
+ if (!nb?.webUrl) return null;
1312
+ const u = new URL(nb.webUrl);
1313
+ u.search = "";
1314
+ u.hash = "";
1315
+ return u.toString();
1316
+ } catch {
1317
+ return null;
1318
+ }
1319
+ })();
1320
+ notebookBaseCache.set(name, pending);
1321
+ }
1322
+ return pending;
1323
+ }
1324
+
1325
+ // --- Drive-based enumeration (bypasses the Graph 5,000-OneNote-item limit) ---
1326
+ // The OneNote /notebooks/{id}/sections endpoint refuses to enumerate libraries
1327
+ // with >5,000 items. The OneDrive /drive tree has no such limit, so we walk it:
1328
+ // each ".one" file is a section (its Doc.aspx webUrl carries the sourcedoc GUID,
1329
+ // which lists pages via /me/onenote/sections/0-{guid}/pages) and each subfolder
1330
+ // is a section group.
1331
+
1332
+ function sourcedocGuidFromUrl(url: string | undefined): string | undefined {
1333
+ if (!url) return undefined;
1334
+ const m = decodeURIComponent(url).match(
1335
+ /sourcedoc=\{?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\}?/i
1336
+ );
1337
+ return m?.[1]?.toLowerCase();
1338
+ }
1339
+
1340
+ export type DriveSection = { name: string; sectionGuid: string };
1341
+ export type DriveGroup = { name: string; drivePath: string };
1342
+
1343
+ /** Drive path (relative to the personal OneDrive root) for a notebook node. */
1344
+ export async function notebookDrivePath(base: string, notebookId: string): Promise<string | undefined> {
1345
+ try {
1346
+ const nb = (await (await graphFetch(`${base}/onenote/notebooks/${notebookId}`)).json()) as any;
1347
+ return getNotebookDrivePath(nb) ?? undefined;
1348
+ } catch {
1349
+ return undefined;
1350
+ }
1351
+ }
1352
+
1353
+ /** List a notebook/section-group folder's sections (.one) and child groups (folders). */
1354
+ export async function listDriveContainer(
1355
+ drivePath: string
1356
+ ): Promise<{ sections: DriveSection[]; groups: DriveGroup[] }> {
1357
+ const encoded = drivePath.split("/").map((s) => encodeURIComponent(s)).join("/");
1358
+ const items = await graphListAll(
1359
+ `/me/drive/root:/${encoded}:/children?$select=name,file,folder,webUrl&$top=200`
1360
+ );
1361
+ const sections: DriveSection[] = [];
1362
+ const groups: DriveGroup[] = [];
1363
+ for (const it of items) {
1364
+ const name: string = it.name ?? "";
1365
+ if (it.folder) {
1366
+ if (/^OneNote_/i.test(name) || name === "deletePending") continue; // internal folders
1367
+ groups.push({ name, drivePath: `${drivePath}/${name}` });
1368
+ } else if (it.file && /\.one$/i.test(name)) {
1369
+ const sectionGuid = sourcedocGuidFromUrl(it.webUrl);
1370
+ if (sectionGuid) sections.push({ name: name.replace(/\.one$/i, ""), sectionGuid });
1371
+ }
1372
+ }
1373
+ return { sections, groups };
1374
+ }
1375
+
1376
+ /** List all pages of a section by its sourcedoc GUID (works past the 5,000 limit). */
1377
+ export async function listSectionPagesByGuidAll(
1378
+ sectionGuid: string
1379
+ ): Promise<{ id: string; title: string; webUrl?: string }[]> {
1380
+ const pages = await graphListAll(
1381
+ `/me/onenote/sections/0-${sectionGuid}/pages?$select=id,title,links&$top=100`
1382
+ );
1383
+ return pages.map((p: any) => ({
1384
+ id: p.id,
1385
+ title: p.title ?? "",
1386
+ webUrl: p.links?.oneNoteWebUrl?.href,
1387
+ }));
1388
+ }
1389
+
1390
+ /** Resolve any ref (path, page ID, or OneNote URL) to an exportable node. */
1391
+ export async function resolveExportNode(ref: string): Promise<ExportNode> {
1392
+ // --- Non-URL: page ID or path ---
1393
+ if (!/^https?:\/\//i.test(ref)) {
1394
+ if (!ref.includes("/") && ref.includes("!")) {
1395
+ // Page IDs contain "!". Section/notebook IDs are ambiguous, so only
1396
+ // page IDs are resolved directly; everything else goes through paths.
1397
+ const r = await resolvePageRef(ref);
1398
+ return { kind: "page", base: r.apiBase, id: r.pageId, title: r.title ?? "", webUrl: r.webUrl };
1399
+ }
1400
+ const r = await resolveByPath(ref);
1401
+ if (r.pageId) return { kind: "page", base: r.apiBase, id: r.pageId, title: r.pageTitle ?? "" };
1402
+ if (r.sectionId) return { kind: "section", base: r.apiBase, id: r.sectionId, title: r.sectionName ?? "" };
1403
+ if (r.notebookId) {
1404
+ return {
1405
+ kind: "notebook",
1406
+ base: r.apiBase,
1407
+ id: r.notebookId,
1408
+ title: r.notebookName ?? "",
1409
+ drivePath: await notebookDrivePath(r.apiBase, r.notebookId),
1410
+ };
1411
+ }
1412
+ throw new Error(`Could not resolve '${ref}' to a notebook, section, or page.`);
1413
+ }
1414
+
1415
+ // --- URL ---
1416
+ const parsed = parseOneNoteUrl(ref);
1417
+ if (parsed.siteRef) {
1418
+ const siteId = await resolveSiteId(parsed.siteRef);
1419
+ const base = `/sites/${siteId}`;
1420
+ if (parsed.graphPageId) {
1421
+ let title = "";
1422
+ let webUrl: string | undefined;
1423
+ try {
1424
+ const m = (await (await graphFetch(
1425
+ `${base}/onenote/pages/${encodeURIComponent(parsed.graphPageId)}?$select=id,title,links`
1426
+ )).json()) as any;
1427
+ title = m.title ?? "";
1428
+ webUrl = m.links?.oneNoteWebUrl?.href;
1429
+ } catch {}
1430
+ return { kind: "page", base, id: parsed.graphPageId, title, webUrl };
1431
+ }
1432
+ if (parsed.graphSectionId) {
1433
+ let title = parsed.sectionName ?? "Section";
1434
+ try {
1435
+ const s = (await (await graphFetch(
1436
+ `${base}/onenote/sections/${parsed.graphSectionId}?$select=displayName`
1437
+ )).json()) as any;
1438
+ title = s.displayName ?? title;
1439
+ } catch {}
1440
+ return { kind: "section", base, id: parsed.graphSectionId, title };
1441
+ }
1442
+ if (parsed.sectionName) {
1443
+ const section = await resolveSharePointSection(siteId, parsed.sectionName, parsed.sectionGuid);
1444
+ if (section) return { kind: "section", base, id: section.id, title: section.displayName };
1445
+ }
1446
+ if (parsed.notebookName) {
1447
+ const nb = await resolveSharePointNotebook(siteId, parsed.notebookName);
1448
+ if (nb) {
1449
+ return {
1450
+ kind: "notebook",
1451
+ base,
1452
+ id: nb.id,
1453
+ title: nb.displayName,
1454
+ drivePath: await notebookDrivePath(base, nb.id),
1455
+ };
1456
+ }
1457
+ }
1458
+ }
1459
+
1460
+ // --- Consumer (/me) fallbacks ---
1461
+ if (parsed.sectionGuid) {
1462
+ return {
1463
+ kind: "section",
1464
+ base: "/me",
1465
+ id: `0-${parsed.sectionGuid}`,
1466
+ title: parsed.sectionName ?? parsed.fileName ?? "Section",
1467
+ };
1468
+ }
1469
+ if (parsed.notebookId) {
1470
+ return {
1471
+ kind: "notebook",
1472
+ base: "/me",
1473
+ id: parsed.notebookId,
1474
+ title: parsed.notebookName ?? "Notebook",
1475
+ drivePath: await notebookDrivePath("/me", parsed.notebookId),
1476
+ };
1477
+ }
1478
+
1479
+ throw new Error(`Could not resolve '${ref}' to a notebook, section, or page.`);
1480
+ }