onenote-cli 0.2.1-win32-x64 → 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.
@@ -0,0 +1,621 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdir, stat, writeFile } from "node:fs/promises";
3
+ import { dirname, join, relative, sep } from "node:path";
4
+ import { getAccessToken } from "./auth";
5
+
6
+ const PKG_ROOT = dirname(import.meta.dir);
7
+ const READ_ASSET_DIR = process.env.ONENOTE_READ_ASSET_DIR
8
+ || join(PKG_ROOT, ".onenote", "assets");
9
+
10
+ type ResourceReference = {
11
+ alt: string;
12
+ url: string;
13
+ mediaType?: string;
14
+ };
15
+
16
+ export type RenderOptions = {
17
+ /** When false, resources are not downloaded and links keep their remote URL. */
18
+ downloadAssets?: boolean;
19
+ /** Directory to write downloaded media into (default: package .onenote/assets). */
20
+ assetDir?: string;
21
+ /** Directory that emitted relative links are computed from (default: cwd). */
22
+ linkBaseDir?: string;
23
+ };
24
+
25
+ function decodeHtmlEntities(text: string): string {
26
+ return text
27
+ .replace(/ /g, " ")
28
+ .replace(/&/g, "&")
29
+ .replace(/&lt;/g, "<")
30
+ .replace(/&gt;/g, ">")
31
+ .replace(/&quot;/g, '"')
32
+ .replace(/&#39;/g, "'");
33
+ }
34
+
35
+ // Convert struck-through runs to markdown `~~…~~` before tags are stripped.
36
+ // OneNote emits both <s>/<strike>/<del> and styled spans (text-decoration:line-through).
37
+ function markStrikethrough(html: string): string {
38
+ return html
39
+ .replace(/<(?:s|strike|del)\b[^>]*>([\s\S]*?)<\/(?:s|strike|del)>/gi, "~~$1~~")
40
+ .replace(
41
+ /<span\b[^>]*text-decoration\s*:[^"';>]*line-through[^>]*>([\s\S]*?)<\/span>/gi,
42
+ "~~$1~~"
43
+ );
44
+ }
45
+
46
+ function extractAttr(tag: string, name: string): string | undefined {
47
+ const match = tag.match(new RegExp(`${name}=(["'])(.*?)\\1`, "i"));
48
+ return match?.[2];
49
+ }
50
+
51
+ function escapeMarkdownText(text: string): string {
52
+ return text.replace(/[[\]\\]/g, "\\$&");
53
+ }
54
+
55
+ export type OneNoteLinkInfo = {
56
+ basePath: string; // notebook web URL the link was authored against (may be stale)
57
+ file: string; // section ".one" filename
58
+ sectionId: string; // section object GUID
59
+ pageId: string; // page object GUID
60
+ title: string; // page title
61
+ };
62
+
63
+ /**
64
+ * A resolver that, given a parsed OneNote link, returns the page's *current*
65
+ * https URL (e.g. from the local sync cache or a fresh Graph lookup), or null to
66
+ * fall back to reconstructing it from the link's embedded base-path. Injected by
67
+ * the CLI so this module stays free of graph/cache dependencies.
68
+ */
69
+ export type LinkResolver = (info: OneNoteLinkInfo) => Promise<string | null>;
70
+
71
+ let linkResolver: LinkResolver | null = null;
72
+ export function setLinkResolver(fn: LinkResolver | null): void {
73
+ linkResolver = fn;
74
+ }
75
+
76
+ /** Parse a `onenote:` client deep-link into its parts, or null if not one. */
77
+ function parseOneNoteHref(href: string): OneNoteLinkInfo | null {
78
+ if (!/^onenote:/i.test(href)) return null;
79
+ const rest = href.replace(/^onenote:/i, "");
80
+ const hashIdx = rest.indexOf("#");
81
+ const file = decodeURIComponent(hashIdx >= 0 ? rest.slice(0, hashIdx) : rest);
82
+ const frag = hashIdx >= 0 ? rest.slice(hashIdx + 1) : "";
83
+ const params = frag.split("&");
84
+ const title = decodeURIComponent(params[0] ?? "");
85
+ const get = (k: string) => {
86
+ const p = params.find((x) => x.toLowerCase().startsWith(`${k}=`));
87
+ return p ? p.slice(k.length + 1) : "";
88
+ };
89
+ const sectionId = get("section-id").replace(/[{}]/g, "").toLowerCase();
90
+ const pageId = get("page-id").replace(/[{}]/g, "").toLowerCase();
91
+ const basePath = get("base-path");
92
+ if (!basePath || !/^https?:\/\//i.test(basePath) || !file) return null;
93
+ return { basePath, file, sectionId, pageId, title };
94
+ }
95
+
96
+ /**
97
+ * Build the equivalent https OneNote Online URL
98
+ * (`{base-path}?wd=target(file|section-guid/title|page-guid/)`) from parsed link
99
+ * info. This is the same form Graph's oneNoteWebUrl uses; browsers and web
100
+ * Markdown renderers can open it. Returns null without a section GUID.
101
+ */
102
+ export function buildOneNoteWebUrl(info: OneNoteLinkInfo): string | null {
103
+ // OneNote's own web URLs percent-encode the whole target(...) argument,
104
+ // including parentheses (which encodeURIComponent leaves untouched).
105
+ const pct = (s: string) =>
106
+ encodeURIComponent(s).replace(/[()!*'~]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
107
+ let inner: string;
108
+ if (info.sectionId && info.pageId) inner = `${info.file}|${info.sectionId}/${info.title}|${info.pageId}/`;
109
+ else if (info.sectionId) inner = `${info.file}|${info.sectionId}/`;
110
+ else return null;
111
+ return `${info.basePath}?wd=target${pct(`(${inner})`)}`;
112
+ }
113
+
114
+ /** Resolve an anchor href to its best https/onenote URL for markdown output. */
115
+ async function resolveLinkHref(href: string): Promise<string> {
116
+ if (/^https?:\/\//i.test(href)) return href;
117
+ const info = parseOneNoteHref(href);
118
+ if (!info) return href;
119
+ if (linkResolver) {
120
+ try {
121
+ const resolved = await linkResolver(info);
122
+ if (resolved) return resolved;
123
+ } catch {}
124
+ }
125
+ return buildOneNoteWebUrl(info) ?? href;
126
+ }
127
+
128
+ function sanitizeStem(text: string): string {
129
+ return text
130
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
131
+ .replace(/-+/g, "-")
132
+ .replace(/^-|-$/g, "")
133
+ .slice(0, 120);
134
+ }
135
+
136
+ function toDisplayPath(path: string, baseDir: string = process.cwd()): string {
137
+ const rel = relative(baseDir, path).split(sep).join("/");
138
+ if (!rel || rel === "") return ".";
139
+ if (rel.startsWith("../") || rel.startsWith("./")) return rel;
140
+ if (rel.startsWith(".")) return `./${rel}`;
141
+ return `./${rel}`;
142
+ }
143
+
144
+ function extensionFromMediaType(mediaType?: string): string {
145
+ switch ((mediaType ?? "").toLowerCase()) {
146
+ case "image/jpeg":
147
+ case "image/jpg":
148
+ return "jpg";
149
+ case "image/png":
150
+ return "png";
151
+ case "image/gif":
152
+ return "gif";
153
+ case "image/webp":
154
+ return "webp";
155
+ case "image/bmp":
156
+ return "bmp";
157
+ case "image/tiff":
158
+ return "tiff";
159
+ case "image/svg+xml":
160
+ return "svg";
161
+ case "application/pdf":
162
+ return "pdf";
163
+ default: {
164
+ const subtype = mediaType?.split("/")[1]?.split(";")[0];
165
+ return subtype ? subtype.replace(/[^a-z0-9]/gi, "").toLowerCase() : "bin";
166
+ }
167
+ }
168
+ }
169
+
170
+ function getResourceId(resourceUrl: string): string {
171
+ try {
172
+ const { pathname } = new URL(resourceUrl);
173
+ const match = pathname.match(/\/onenote\/resources\/([^/]+)\/(?:\$value|content)$/i);
174
+ if (match?.[1]) return match[1];
175
+ } catch {}
176
+ return createHash("sha1").update(resourceUrl).digest("hex");
177
+ }
178
+
179
+ function sniffMediaType(buf: Buffer): string | undefined {
180
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) {
181
+ return "image/jpeg";
182
+ }
183
+ if (
184
+ buf.length >= 8
185
+ && buf[0] === 0x89
186
+ && buf[1] === 0x50
187
+ && buf[2] === 0x4e
188
+ && buf[3] === 0x47
189
+ ) {
190
+ return "image/png";
191
+ }
192
+ if (buf.length >= 6 && buf.subarray(0, 6).toString("ascii") === "GIF87a") return "image/gif";
193
+ if (buf.length >= 6 && buf.subarray(0, 6).toString("ascii") === "GIF89a") return "image/gif";
194
+ if (buf.length >= 12 && buf.subarray(0, 4).toString("ascii") === "RIFF" && buf.subarray(8, 12).toString("ascii") === "WEBP") {
195
+ return "image/webp";
196
+ }
197
+ if (buf.length >= 4 && buf.subarray(0, 4).toString("ascii") === "%PDF") return "application/pdf";
198
+ return undefined;
199
+ }
200
+
201
+ async function fetchAuthed(resourceUrl: string): Promise<Response> {
202
+ const token = await getAccessToken();
203
+ const url = normalizeOneNoteResourceUrl(resourceUrl);
204
+ const doFetch = () => fetch(url, { headers: { Authorization: `Bearer ${token}` } });
205
+ let res = await doFetch();
206
+ // Retry on throttling/transient errors with Retry-After / exponential backoff,
207
+ // mirroring graphFetch so media downloads survive rate-limit windows.
208
+ for (let attempt = 0; attempt < 6 && (res.status === 429 || res.status === 503 || res.status === 504); attempt++) {
209
+ const retryAfter = parseInt(res.headers.get("retry-after") ?? "0", 10);
210
+ const delayMs = retryAfter > 0 ? retryAfter * 1000 : Math.min(2000 * 2 ** attempt, 60000);
211
+ await new Promise((r) => setTimeout(r, delayMs));
212
+ res = await doFetch();
213
+ }
214
+ if (!res.ok) {
215
+ const body = await res.text();
216
+ throw new Error(`Graph API ${res.status}: ${body}`);
217
+ }
218
+ return res;
219
+ }
220
+
221
+ export function isOneNoteResourceUrl(url: string): boolean {
222
+ try {
223
+ const parsed = new URL(url);
224
+ return /(^|\.)graph\.microsoft\.com$/i.test(parsed.hostname)
225
+ && /\/onenote\/resources\/[^/]+\/(?:\$value|content)$/i.test(parsed.pathname);
226
+ } catch {
227
+ return false;
228
+ }
229
+ }
230
+
231
+ function normalizeOneNoteResourceUrl(resourceUrl: string): string {
232
+ try {
233
+ const parsed = new URL(resourceUrl);
234
+ if (!/(^|\.)graph\.microsoft\.com$/i.test(parsed.hostname)) return resourceUrl;
235
+
236
+ parsed.pathname = parsed.pathname
237
+ .replace(
238
+ /^\/v1\.0\/siteCollections\/([^/]+)\/onenote\/resources\/([^/]+)\/\$value$/i,
239
+ "/v1.0/sites/$1/onenote/resources/$2/content"
240
+ )
241
+ .replace(
242
+ /(\/v1\.0\/(?:me|users\/[^/]+|groups\/[^/]+|sites\/[^/]+)\/onenote\/resources\/[^/]+)\/\$value$/i,
243
+ "$1/content"
244
+ );
245
+
246
+ parsed.search = "";
247
+ return parsed.toString();
248
+ } catch {
249
+ return resourceUrl;
250
+ }
251
+ }
252
+
253
+ export async function cacheOneNoteResource(
254
+ resourceUrl: string,
255
+ mediaTypeHint?: string,
256
+ opts?: { assetDir?: string; linkBaseDir?: string }
257
+ ): Promise<{ absolutePath: string; displayPath: string; mediaType: string }> {
258
+ const assetDir = opts?.assetDir ?? READ_ASSET_DIR;
259
+ const baseDir = opts?.linkBaseDir;
260
+ await mkdir(assetDir, { recursive: true });
261
+
262
+ const canonicalUrl = normalizeOneNoteResourceUrl(resourceUrl);
263
+ const resourceId = getResourceId(canonicalUrl);
264
+ const hash = createHash("sha1").update(canonicalUrl).digest("hex").slice(0, 10);
265
+ const baseName = sanitizeStem(`${resourceId}-${hash}`) || hash;
266
+ let mediaType = mediaTypeHint ?? "";
267
+ let ext = extensionFromMediaType(mediaTypeHint);
268
+ let absolutePath = join(assetDir, `${baseName}.${ext}`);
269
+
270
+ try {
271
+ await stat(absolutePath);
272
+ return { absolutePath, displayPath: toDisplayPath(absolutePath, baseDir), mediaType };
273
+ } catch {}
274
+
275
+ const res = await fetchAuthed(resourceUrl);
276
+ const buf = Buffer.from(await res.arrayBuffer());
277
+ const headerMediaType = res.headers.get("content-type") || "";
278
+ const sniffedMediaType = sniffMediaType(buf);
279
+ mediaType = mediaType
280
+ || (headerMediaType && headerMediaType !== "application/octet-stream" ? headerMediaType : "")
281
+ || sniffedMediaType
282
+ || headerMediaType
283
+ || "application/octet-stream";
284
+ ext = extensionFromMediaType(mediaType);
285
+ absolutePath = join(assetDir, `${baseName}.${ext}`);
286
+
287
+ try {
288
+ await stat(absolutePath);
289
+ return { absolutePath, displayPath: toDisplayPath(absolutePath, baseDir), mediaType };
290
+ } catch {}
291
+
292
+ await writeFile(absolutePath, buf);
293
+ return { absolutePath, displayPath: toDisplayPath(absolutePath, baseDir), mediaType };
294
+ }
295
+
296
+ function normalizeResourceReferences(html: string): ResourceReference[] {
297
+ const tags = [...html.matchAll(/<(img|object)\b[^>]*>/gi)].map((match) => match[0]);
298
+ return tags.flatMap((tag) => {
299
+ if (/^<img\b/i.test(tag)) {
300
+ const url = extractAttr(tag, "data-fullres-src") || extractAttr(tag, "src");
301
+ if (!url) return [];
302
+ return [{
303
+ alt: decodeHtmlEntities(extractAttr(tag, "alt")?.trim() || "image"),
304
+ url,
305
+ mediaType: extractAttr(tag, "data-fullres-src-type") || extractAttr(tag, "data-src-type"),
306
+ }];
307
+ }
308
+
309
+ const url = extractAttr(tag, "data");
310
+ if (!url) return [];
311
+ return [{
312
+ alt: decodeHtmlEntities(extractAttr(tag, "data-attachment")?.trim() || "attachment"),
313
+ url,
314
+ mediaType: extractAttr(tag, "type"),
315
+ }];
316
+ });
317
+ }
318
+
319
+ async function resolveResourceTargets(
320
+ html: string,
321
+ opts?: { assetDir?: string; linkBaseDir?: string }
322
+ ) {
323
+ const refs = normalizeResourceReferences(html);
324
+ const byUrl = new Map<string, { displayPath: string; mediaType?: string }>();
325
+
326
+ await Promise.all(
327
+ refs.map(async (ref) => {
328
+ if (byUrl.has(ref.url)) return;
329
+ if (!isOneNoteResourceUrl(ref.url)) {
330
+ byUrl.set(ref.url, { displayPath: ref.url, mediaType: ref.mediaType });
331
+ return;
332
+ }
333
+ try {
334
+ const cached = await cacheOneNoteResource(ref.url, ref.mediaType, opts);
335
+ byUrl.set(ref.url, { displayPath: cached.displayPath, mediaType: cached.mediaType });
336
+ } catch {
337
+ byUrl.set(ref.url, { displayPath: ref.url, mediaType: ref.mediaType });
338
+ }
339
+ })
340
+ );
341
+
342
+ return byUrl;
343
+ }
344
+
345
+ function stripTagsInline(html: string): string {
346
+ return decodeHtmlEntities(
347
+ markStrikethrough(html)
348
+ .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "")
349
+ .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "")
350
+ .replace(/<br\s*\/?>/gi, " ")
351
+ .replace(/<\/(p|div|li|h[1-6])>/gi, " ")
352
+ .replace(/<[^>]+>/g, "")
353
+ .replace(/\s+/g, " ")
354
+ .trim()
355
+ );
356
+ }
357
+
358
+ function maskNestedTables(html: string): { masked: string; slots: string[] } {
359
+ const slots: string[] = [];
360
+ let out = "";
361
+ let i = 0;
362
+ while (i < html.length) {
363
+ const start = html.toLowerCase().indexOf("<table", i);
364
+ if (start === -1) { out += html.slice(i); break; }
365
+ out += html.slice(i, start);
366
+ let depth = 0;
367
+ let j = start;
368
+ while (j < html.length) {
369
+ const lower = html.slice(j).toLowerCase();
370
+ if (lower.startsWith("<table")) {
371
+ depth++;
372
+ const close = html.indexOf(">", j);
373
+ if (close === -1) { j = html.length; break; }
374
+ j = close + 1;
375
+ } else if (lower.startsWith("</table>")) {
376
+ depth--;
377
+ j += 8;
378
+ if (depth === 0) break;
379
+ } else {
380
+ j++;
381
+ }
382
+ }
383
+ const idx = slots.length;
384
+ slots.push(html.slice(start, j));
385
+ out += `\uE000TABLE${idx}\uE000`;
386
+ i = j;
387
+ }
388
+ return { masked: out, slots };
389
+ }
390
+
391
+ function parseRowCells(rowHtml: string): string[] {
392
+ return [...rowHtml.matchAll(/<t[hd]\b[^>]*>([\s\S]*?)<\/t[hd]>/gi)].map((m) => m[1] ?? "");
393
+ }
394
+
395
+ function renderCell(cellHtml: string): string {
396
+ const { masked, slots } = maskNestedTables(cellHtml);
397
+ const flattened = slots.map((t) => {
398
+ const stripped = t.replace(/^<table\b[^>]*>/i, "").replace(/<\/table>\s*$/i, "");
399
+ const inner = maskNestedTables(stripped);
400
+ const rows = [...inner.masked.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)].map((m) => m[1] ?? "");
401
+ return rows.map((r) => parseRowCells(r).map((c) => renderCell(c.replace(/\uE000TABLE(\d+)\uE000/g, (_, n) => inner.slots[Number(n)] ?? ""))).filter(Boolean).join(" / ")).filter(Boolean).join(" ; ");
402
+ });
403
+ let text = stripTagsInline(masked);
404
+ text = text.replace(/\uE000TABLE(\d+)\uE000/g, (_, n) => ` ${flattened[Number(n)] ?? ""} `);
405
+ return text.replace(/\|/g, "\\|").replace(/\s+/g, " ").trim();
406
+ }
407
+
408
+ function renderTable(tableHtml: string): string {
409
+ const stripped = tableHtml.replace(/^<table\b[^>]*>/i, "").replace(/<\/table>\s*$/i, "");
410
+ const { masked, slots } = maskNestedTables(stripped);
411
+ const rowHtmls = [...masked.matchAll(/<tr\b[^>]*>([\s\S]*?)<\/tr>/gi)].map((m) => m[1] ?? "");
412
+ const rows = rowHtmls.map((rowMasked) =>
413
+ parseRowCells(rowMasked).map((c) => renderCell(c.replace(/\uE000TABLE(\d+)\uE000/g, (_, n) => slots[Number(n)] ?? ""))),
414
+ );
415
+ if (rows.length === 0) return "";
416
+ const width = Math.max(...rows.map((r) => r.length));
417
+ const padded = rows.map((r) => [...r, ...Array(width - r.length).fill("")]);
418
+ // OneNote tables have no header semantics (all <td>), so emit an empty header
419
+ // row by default; only promote the first row when it is made of real <th> cells.
420
+ const firstRowIsHeader = /<th\b/i.test(rowHtmls[0] ?? "") && !/<td\b/i.test(rowHtmls[0] ?? "");
421
+ const header = firstRowIsHeader ? padded[0]!.map((c) => c || " ") : Array(width).fill(" ");
422
+ const body = firstRowIsHeader ? padded.slice(1) : padded;
423
+ const lines = [
424
+ `| ${header.join(" | ")} |`,
425
+ `| ${header.map(() => "---").join(" | ")} |`,
426
+ ...body.map((r) => `| ${r.map((c) => c || " ").join(" | ")} |`),
427
+ ];
428
+ return `\n\n${lines.join("\n")}\n\n`;
429
+ }
430
+
431
+ function replaceTopLevelTables(html: string): string {
432
+ let out = "";
433
+ let i = 0;
434
+ while (i < html.length) {
435
+ const start = html.toLowerCase().indexOf("<table", i);
436
+ if (start === -1) {
437
+ out += html.slice(i);
438
+ break;
439
+ }
440
+ out += html.slice(i, start);
441
+ let depth = 0;
442
+ let j = start;
443
+ while (j < html.length) {
444
+ const lower = html.slice(j).toLowerCase();
445
+ if (lower.startsWith("<table")) {
446
+ depth++;
447
+ const close = html.indexOf(">", j);
448
+ if (close === -1) { j = html.length; break; }
449
+ j = close + 1;
450
+ } else if (lower.startsWith("</table>")) {
451
+ depth--;
452
+ j += 8;
453
+ if (depth === 0) break;
454
+ } else {
455
+ j++;
456
+ }
457
+ }
458
+ out += renderTable(html.slice(start, j));
459
+ i = j;
460
+ }
461
+ return out;
462
+ }
463
+
464
+ export async function renderHtmlForRead(
465
+ html: string,
466
+ options?: RenderOptions
467
+ ): Promise<string> {
468
+ const replacements = options?.downloadAssets === false
469
+ ? new Map<string, { displayPath: string; mediaType?: string }>()
470
+ : await resolveResourceTargets(html, options);
471
+
472
+ // Convert <img>/<object> to markdown BEFORE table rendering so assets inside
473
+ // table cells survive stripTagsInline() during cell flattening.
474
+ let rendered = html.replace(/<img\b[^>]*>/gi, (tag) => {
475
+ const url = extractAttr(tag, "data-fullres-src") || extractAttr(tag, "src");
476
+ if (!url) return "";
477
+ const alt = escapeMarkdownText(decodeHtmlEntities(extractAttr(tag, "alt")?.trim() || "image"));
478
+ const target = replacements.get(url)?.displayPath || url;
479
+ return `\n\n![${alt}](${target})\n\n`;
480
+ });
481
+
482
+ rendered = rendered.replace(/<object\b[^>]*>/gi, (tag) => {
483
+ const url = extractAttr(tag, "data");
484
+ if (!url) return "";
485
+ const label = escapeMarkdownText(
486
+ decodeHtmlEntities(extractAttr(tag, "data-attachment")?.trim() || "attachment")
487
+ );
488
+ const target = replacements.get(url)?.displayPath || url;
489
+ return `\n\n[${label}](${target})\n\n`;
490
+ });
491
+
492
+ // Convert <a href> links to markdown. Mask each as a placeholder so its URL
493
+ // (which may contain parens/spaces and thus need <angle-bracket> form) is not
494
+ // eaten by the final tag-strip below; restored at the very end.
495
+ const linkMark = String.fromCharCode(0xe001);
496
+ const linkSlots: { text: string; href: string }[] = [];
497
+ rendered = rendered.replace(/<a\b[^>]*>[\s\S]*?<\/a>/gi, (whole) => {
498
+ const open = whole.match(/<a\b[^>]*>/i)?.[0] ?? "";
499
+ const href = extractAttr(open, "href");
500
+ const inner = whole.replace(/^<a\b[^>]*>/i, "").replace(/<\/a>\s*$/i, "");
501
+ const text = decodeHtmlEntities(inner.replace(/<[^>]+>/g, "")).replace(/\s+/g, " ").trim();
502
+ if (!href) return text;
503
+ const idx = linkSlots.length;
504
+ linkSlots.push({ text, href: decodeHtmlEntities(href).trim() });
505
+ return `${linkMark}${idx}${linkMark}`;
506
+ });
507
+
508
+ rendered = replaceTopLevelTables(rendered);
509
+
510
+ const text = decodeHtmlEntities(
511
+ markStrikethrough(rendered)
512
+ // Drop document <head> (title/meta) so the page title isn't re-emitted as body text.
513
+ .replace(/<head\b[^>]*>[\s\S]*?<\/head>/gi, "")
514
+ .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "")
515
+ .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "")
516
+ .replace(/<br\s*\/?>/gi, "\n")
517
+ .replace(/<\/p>/gi, "\n\n")
518
+ .replace(/<\/div>/gi, "\n")
519
+ .replace(/<\/h[1-6]>/gi, "\n\n")
520
+ .replace(/<\/li>/gi, "\n")
521
+ .replace(/<li[^>]*>/gi, "- ")
522
+ .replace(/<[^>]+>/g, "")
523
+ );
524
+
525
+ // OneNote's HTML is pretty-printed with tab indentation; once tags are gone
526
+ // that inter-tag whitespace survives as leading tabs and blank-but-not-empty
527
+ // lines. Trim each line and collapse blank runs to keep the output readable.
528
+ const collapsed = text
529
+ .split("\n")
530
+ .map((line) => line.replace(/^[ \t]+/, "").replace(/\s+$/, ""))
531
+ .join("\n")
532
+ .replace(/\n{3,}/g, "\n\n")
533
+ .trim();
534
+
535
+ // Resolve each link to its best current URL (may hit the sync cache / Graph),
536
+ // then restore as markdown. URLs with parens/whitespace use the <angle-bracket>
537
+ // form so they don't terminate the link early.
538
+ const urls = await Promise.all(linkSlots.map((s) => resolveLinkHref(s.href)));
539
+ const linkRe = new RegExp(`${linkMark}(\\d+)${linkMark}`, "g");
540
+ return collapsed.replace(linkRe, (_, n: string) => {
541
+ const slot = linkSlots[Number(n)];
542
+ if (!slot) return "";
543
+ const url = urls[Number(n)]!;
544
+ const label = escapeMarkdownText(slot.text || url);
545
+ const safe = /[()\s]/.test(url) ? `<${url}>` : url;
546
+ return `[${label}](${safe})`;
547
+ });
548
+ }
549
+
550
+ /**
551
+ * Rewrite a page's HTML so that OneNote resource references (img/object) point
552
+ * at locally-downloaded copies. Returns the (still complete) HTML document with
553
+ * remote resource URLs replaced by relative paths, for `onenote export *.html`.
554
+ */
555
+ export async function renderHtmlForExport(
556
+ html: string,
557
+ opts?: { assetDir?: string; linkBaseDir?: string }
558
+ ): Promise<string> {
559
+ const replacements = await resolveResourceTargets(html, opts);
560
+ const localFor = (u?: string) => (u ? replacements.get(u)?.displayPath : undefined);
561
+ const swapAttr = (tag: string, from: string | undefined, to: string): string => {
562
+ if (!from) return tag;
563
+ return tag.replace(`"${from}"`, `"${to}"`).replace(`'${from}'`, `'${to}'`);
564
+ };
565
+
566
+ let out = html.replace(/<img\b[^>]*>/gi, (tag) => {
567
+ const full = extractAttr(tag, "data-fullres-src");
568
+ const src = extractAttr(tag, "src");
569
+ const target = localFor(full ?? src);
570
+ if (!target) return tag;
571
+ let t = tag;
572
+ if (src) t = swapAttr(t, src, target);
573
+ else t = t.replace(/<img\b/i, `<img src="${target}"`);
574
+ if (full) t = swapAttr(t, full, target);
575
+ return t;
576
+ });
577
+
578
+ out = out.replace(/<object\b[^>]*>/gi, (tag) => {
579
+ const data = extractAttr(tag, "data");
580
+ const target = localFor(data);
581
+ return target ? swapAttr(tag, data, target) : tag;
582
+ });
583
+
584
+ // Rewrite <a href> links to their current https URL (same policy as markdown:
585
+ // sync cache → notebook re-resolution → embedded base-path).
586
+ const anchorHrefs = new Set<string>();
587
+ for (const m of out.matchAll(/<a\b[^>]*>/gi)) {
588
+ const raw = extractAttr(m[0], "href");
589
+ if (raw) anchorHrefs.add(raw);
590
+ }
591
+ const resolvedByRaw = new Map<string, string>();
592
+ await Promise.all(
593
+ [...anchorHrefs].map(async (raw) => {
594
+ resolvedByRaw.set(raw, await resolveLinkHref(decodeHtmlEntities(raw).trim()));
595
+ })
596
+ );
597
+ const escapeHtmlAttr = (v: string) =>
598
+ v.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
599
+ out = out.replace(/<a\b[^>]*>/gi, (tag) => {
600
+ const raw = extractAttr(tag, "href");
601
+ if (!raw) return tag;
602
+ const resolved = resolvedByRaw.get(raw);
603
+ return resolved ? swapAttr(tag, raw, escapeHtmlAttr(resolved)) : tag;
604
+ });
605
+
606
+ return out;
607
+ }
608
+
609
+ export async function renderResourceForRead(resourceUrl: string): Promise<{
610
+ title: string;
611
+ content: string;
612
+ assetPath: string;
613
+ }> {
614
+ const cached = await cacheOneNoteResource(resourceUrl);
615
+ const title = cached.absolutePath.split(sep).at(-1) ?? "resource";
616
+ return {
617
+ title,
618
+ content: `![${escapeMarkdownText(title)}](${cached.displayPath})`,
619
+ assetPath: cached.displayPath,
620
+ };
621
+ }