@bendyline/squisq-formats 1.2.0 → 1.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.
Files changed (40) hide show
  1. package/README.md +14 -0
  2. package/dist/__tests__/epub.test.d.ts +8 -0
  3. package/dist/__tests__/epub.test.d.ts.map +1 -0
  4. package/dist/__tests__/epub.test.js +472 -0
  5. package/dist/__tests__/epub.test.js.map +1 -0
  6. package/dist/chunk-2FPJKJ6I.js +621 -0
  7. package/dist/chunk-2FPJKJ6I.js.map +1 -0
  8. package/dist/{chunk-BHHEDPRB.js → chunk-7DEUGIOO.js} +6 -41
  9. package/dist/chunk-7DEUGIOO.js.map +1 -0
  10. package/dist/chunk-A3FHLTY5.js +42 -0
  11. package/dist/chunk-A3FHLTY5.js.map +1 -0
  12. package/dist/{chunk-CLGUOVYR.js → chunk-MEZF76JA.js} +6 -4
  13. package/dist/{chunk-CLGUOVYR.js.map → chunk-MEZF76JA.js.map} +1 -1
  14. package/dist/{chunk-FIFCQN3W.js → chunk-NGWHV77G.js} +5 -3
  15. package/dist/{chunk-FIFCQN3W.js.map → chunk-NGWHV77G.js.map} +1 -1
  16. package/dist/chunk-U4MRIFKL.js +43 -0
  17. package/dist/chunk-U4MRIFKL.js.map +1 -0
  18. package/dist/{chunk-743COJWQ.js → chunk-UM5V2XZG.js} +7 -40
  19. package/dist/chunk-UM5V2XZG.js.map +1 -0
  20. package/dist/{chunk-KJ4NS4DX.js → chunk-YN5HFCEW.js} +2 -2
  21. package/dist/epub/export.d.ts +72 -0
  22. package/dist/epub/export.d.ts.map +1 -0
  23. package/dist/epub/export.js +674 -0
  24. package/dist/epub/export.js.map +1 -0
  25. package/dist/epub/index.d.ts +20 -0
  26. package/dist/epub/index.d.ts.map +1 -0
  27. package/dist/epub/index.js +19 -0
  28. package/dist/epub/index.js.map +1 -0
  29. package/dist/index.d.ts +2 -0
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -0
  32. package/dist/index.js.map +1 -1
  33. package/package.json +13 -7
  34. package/src/__tests__/epub.test.ts +548 -0
  35. package/src/epub/export.ts +891 -0
  36. package/src/epub/index.ts +20 -0
  37. package/src/index.ts +4 -0
  38. package/dist/chunk-743COJWQ.js.map +0 -1
  39. package/dist/chunk-BHHEDPRB.js.map +0 -1
  40. /package/dist/{chunk-KJ4NS4DX.js.map → chunk-YN5HFCEW.js.map} +0 -0
@@ -0,0 +1,891 @@
1
+ /**
2
+ * EPUB 3 Export
3
+ *
4
+ * Converts a MarkdownDocument (or Doc) to an EPUB 3 file (.epub).
5
+ *
6
+ * An EPUB is a ZIP archive containing XHTML chapter files, images,
7
+ * a package manifest (content.opf), and a navigation document (toc.xhtml).
8
+ * Content is split into chapters at H1/H2 heading boundaries.
9
+ *
10
+ * Uses JSZip for packaging (already a dependency), escapeXml from the
11
+ * OOXML utils, and image utilities from the HTML exporter.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * import { markdownDocToEpub } from '@bendyline/squisq-formats/epub';
16
+ *
17
+ * const epub = await markdownDocToEpub(markdownDoc, {
18
+ * title: 'My Book',
19
+ * author: 'Jane Doe',
20
+ * });
21
+ * ```
22
+ */
23
+
24
+ import JSZip from 'jszip';
25
+ import type { Doc, AudioSegment } from '@bendyline/squisq/schemas';
26
+ import { resolveTheme } from '@bendyline/squisq/schemas';
27
+ import type {
28
+ MarkdownDocument,
29
+ MarkdownBlockNode,
30
+ MarkdownInlineNode,
31
+ MarkdownHeading,
32
+ MarkdownParagraph,
33
+ MarkdownListItem,
34
+ MarkdownTable,
35
+ MarkdownTableRow,
36
+ MarkdownTableCell,
37
+ } from '@bendyline/squisq/markdown';
38
+ import { escapeXml } from '../ooxml/xmlUtils.js';
39
+ import { inferMimeType, extractFilename } from '../html/imageUtils.js';
40
+
41
+ // ── Public API ────────────────────────────────────────────────────
42
+
43
+ export interface EpubExportOptions {
44
+ /** Book title (default: 'Untitled') */
45
+ title?: string;
46
+ /** Author name */
47
+ author?: string;
48
+ /** Book description / summary */
49
+ description?: string;
50
+ /** BCP-47 language code (default: 'en') */
51
+ language?: string;
52
+ /** Publisher name */
53
+ publisher?: string;
54
+ /** Squisq theme ID for CSS styling */
55
+ themeId?: string;
56
+ /** Pre-resolved image data keyed by relative path as it appears in the markdown */
57
+ images?: Map<string, ArrayBuffer>;
58
+ /** Cover image data (JPEG or PNG) */
59
+ coverImage?: ArrayBuffer;
60
+ /**
61
+ * Audio narration data keyed by segment src/name.
62
+ * When provided alongside audioSegments, EPUB 3 Media Overlays (SMIL)
63
+ * are generated for synchronized audio playback.
64
+ */
65
+ audio?: Map<string, ArrayBuffer>;
66
+ /**
67
+ * Audio segment metadata (from Doc.audio.segments).
68
+ * Required together with `audio` to generate Media Overlays.
69
+ * Each segment's duration and startTime are used to build SMIL timing.
70
+ */
71
+ audioSegments?: AudioSegment[];
72
+ /** Total document duration in seconds (used for Media Overlay metadata) */
73
+ totalDuration?: number;
74
+ }
75
+
76
+ /**
77
+ * Convert a MarkdownDocument to an EPUB 3 file.
78
+ *
79
+ * Chapters are split at H1/H2 heading boundaries. All referenced images
80
+ * (provided via `options.images`) are embedded in the archive.
81
+ */
82
+ export async function markdownDocToEpub(
83
+ doc: MarkdownDocument,
84
+ options: EpubExportOptions = {},
85
+ ): Promise<ArrayBuffer> {
86
+ const fmTitle = doc.frontmatter?.title;
87
+ const fmAuthor = doc.frontmatter?.author;
88
+ const title = options.title ?? (typeof fmTitle === 'string' ? fmTitle : 'Untitled');
89
+ const author = options.author ?? (typeof fmAuthor === 'string' ? fmAuthor : '');
90
+ const language = options.language ?? 'en';
91
+ const description = options.description ?? '';
92
+ const publisher = options.publisher ?? '';
93
+ const uuid = crypto.randomUUID();
94
+
95
+ // Split document into chapters
96
+ const chapters = splitIntoChapters(doc.children);
97
+
98
+ // Collect images referenced in the document, deduplicating filenames
99
+ const imageEntries = collectDocImages(doc.children);
100
+ const resolvedImages = new Map<string, { data: ArrayBuffer; mime: string; filename: string }>();
101
+ if (options.images) {
102
+ const usedNames = new Set<string>();
103
+ for (const src of imageEntries) {
104
+ const data = options.images.get(src);
105
+ if (data) {
106
+ let filename = extractFilename(src);
107
+ // Deduplicate: if two paths share a basename (e.g. a/hero.png and b/hero.png)
108
+ if (usedNames.has(filename)) {
109
+ const dot = filename.lastIndexOf('.');
110
+ const base = dot > 0 ? filename.slice(0, dot) : filename;
111
+ const ext = dot > 0 ? filename.slice(dot) : '';
112
+ let counter = 2;
113
+ while (usedNames.has(`${base}-${counter}${ext}`)) counter++;
114
+ filename = `${base}-${counter}${ext}`;
115
+ }
116
+ usedNames.add(filename);
117
+ resolvedImages.set(src, { data, mime: inferMimeType(filename), filename });
118
+ }
119
+ }
120
+ }
121
+
122
+ // Generate theme CSS
123
+ const css = generateStylesheet(options.themeId);
124
+
125
+ // Build the ZIP
126
+ const zip = new JSZip();
127
+
128
+ // mimetype must be first entry, stored (not compressed)
129
+ zip.file('mimetype', 'application/epub+zip', { compression: 'STORE' });
130
+
131
+ // META-INF/container.xml
132
+ zip.file('META-INF/container.xml', CONTAINER_XML);
133
+
134
+ // OEBPS/styles.css
135
+ zip.file('OEBPS/styles.css', css);
136
+
137
+ // OEBPS/images/*
138
+ for (const [, img] of resolvedImages) {
139
+ zip.file(`OEBPS/images/${img.filename}`, img.data);
140
+ }
141
+
142
+ // Cover image — detect PNG vs JPEG from magic bytes
143
+ let coverFilename: string | undefined;
144
+ if (options.coverImage) {
145
+ const bytes = new Uint8Array(options.coverImage);
146
+ const isPng =
147
+ bytes.length >= 4 &&
148
+ bytes[0] === 0x89 &&
149
+ bytes[1] === 0x50 &&
150
+ bytes[2] === 0x4e &&
151
+ bytes[3] === 0x47;
152
+ coverFilename = isPng ? 'cover.png' : 'cover.jpg';
153
+ zip.file(`OEBPS/images/${coverFilename}`, options.coverImage);
154
+ }
155
+
156
+ // ── Audio narration ──────────────────────────────────────────────
157
+ const audioMap = options.audio;
158
+ const audioSegments = options.audioSegments;
159
+ const hasAudio = audioMap && audioSegments && audioSegments.length > 0;
160
+ // Per-segment audio file info, indexed by segment index (null if data missing)
161
+ const segmentAudioFiles: ({ filename: string; mime: string } | null)[] = [];
162
+ const allAudioFiles: { filename: string; mime: string }[] = [];
163
+
164
+ if (hasAudio) {
165
+ for (const seg of audioSegments) {
166
+ const data = audioMap.get(seg.src) ?? audioMap.get(seg.name);
167
+ if (data) {
168
+ const filename = extractFilename(seg.src);
169
+ const finalName = filename.includes('.') ? filename : `${filename}.mp3`;
170
+ zip.file(`OEBPS/audio/${finalName}`, data);
171
+ const info = { filename: finalName, mime: inferMimeType(finalName) };
172
+ segmentAudioFiles.push(info);
173
+ allAudioFiles.push(info);
174
+ } else {
175
+ segmentAudioFiles.push(null);
176
+ }
177
+ }
178
+ }
179
+
180
+ // Build chapter-to-audio mapping for SMIL overlays
181
+ const chapterAudio: (ChapterAudioInfo | null)[] = [];
182
+ if (hasAudio && allAudioFiles.length > 0) {
183
+ if (chapters.length !== audioSegments.length) {
184
+ console.warn(
185
+ `EPUB: ${chapters.length} chapters but ${audioSegments.length} audio segments — ` +
186
+ `extra chapters will reuse the last segment's audio`,
187
+ );
188
+ }
189
+ for (let i = 0; i < chapters.length; i++) {
190
+ const segIdx = Math.min(i, audioSegments.length - 1);
191
+ const seg = audioSegments[segIdx];
192
+ const audioFile = segmentAudioFiles[segIdx];
193
+ if (audioFile) {
194
+ chapterAudio.push({
195
+ audioFilename: audioFile.filename,
196
+ clipStart: 0,
197
+ clipEnd: seg.duration,
198
+ duration: seg.duration,
199
+ });
200
+ } else {
201
+ chapterAudio.push(null);
202
+ }
203
+ }
204
+ }
205
+
206
+ // OEBPS/chapters/*.xhtml + optional SMIL overlays
207
+ const chapterFiles: ChapterFileInfo[] = [];
208
+ for (let i = 0; i < chapters.length; i++) {
209
+ const chap = chapters[i];
210
+ const num = String(i + 1).padStart(3, '0');
211
+ const id = `chapter-${num}`;
212
+ const filename = `${id}.xhtml`;
213
+ const audioInfo = chapterAudio[i] ?? null;
214
+
215
+ // Render XHTML with element IDs for SMIL references when audio is present
216
+ const xhtml = renderChapterXhtml(chap.nodes, title, resolvedImages, audioInfo !== null);
217
+ zip.file(`OEBPS/chapters/${filename}`, xhtml);
218
+
219
+ let smilFilename: string | undefined;
220
+ if (audioInfo) {
221
+ smilFilename = `${id}.smil`;
222
+ const smil = generateSmil(filename, audioInfo, chap.nodes);
223
+ zip.file(`OEBPS/chapters/${smilFilename}`, smil);
224
+ }
225
+
226
+ chapterFiles.push({
227
+ id,
228
+ filename,
229
+ title: chap.title,
230
+ smilFilename,
231
+ duration: audioInfo?.duration,
232
+ });
233
+ }
234
+
235
+ // OEBPS/toc.xhtml (EPUB 3 nav)
236
+ zip.file('OEBPS/toc.xhtml', generateTocXhtml(chapterFiles, title));
237
+
238
+ // OEBPS/content.opf
239
+ zip.file(
240
+ 'OEBPS/content.opf',
241
+ generateContentOpf({
242
+ uuid,
243
+ title,
244
+ author,
245
+ language,
246
+ description,
247
+ publisher,
248
+ chapters: chapterFiles,
249
+ images: resolvedImages,
250
+ coverFilename,
251
+ audioFiles: allAudioFiles,
252
+ totalDuration: options.totalDuration,
253
+ }),
254
+ );
255
+
256
+ const blob = await zip.generateAsync({
257
+ type: 'arraybuffer',
258
+ compression: 'DEFLATE',
259
+ compressionOptions: { level: 6 },
260
+ // mimetype was already set to STORE above; JSZip respects per-file options
261
+ });
262
+
263
+ return blob;
264
+ }
265
+
266
+ /**
267
+ * Convert a squisq Doc to an EPUB 3 file.
268
+ *
269
+ * Convenience wrapper: Doc → MarkdownDocument → EPUB.
270
+ * When the Doc has audio segments and `options.audio` is provided,
271
+ * EPUB 3 Media Overlays are generated for narrated playback.
272
+ */
273
+ export async function docToEpub(doc: Doc, options: EpubExportOptions = {}): Promise<ArrayBuffer> {
274
+ const { docToMarkdown } = await import('@bendyline/squisq/doc');
275
+ const markdownDoc = docToMarkdown(doc);
276
+
277
+ // Thread audio segment metadata from the Doc into options
278
+ const epubOptions: EpubExportOptions = { ...options };
279
+ if (doc.audio?.segments?.length && !epubOptions.audioSegments) {
280
+ epubOptions.audioSegments = doc.audio.segments;
281
+ }
282
+ if (doc.duration && !epubOptions.totalDuration) {
283
+ epubOptions.totalDuration = doc.duration;
284
+ }
285
+
286
+ return markdownDocToEpub(markdownDoc, epubOptions);
287
+ }
288
+
289
+ // ── Chapter Splitting ─────────────────────────────────────────────
290
+
291
+ interface Chapter {
292
+ title: string;
293
+ nodes: MarkdownBlockNode[];
294
+ }
295
+
296
+ interface ChapterFileInfo {
297
+ id: string;
298
+ filename: string;
299
+ title: string;
300
+ smilFilename?: string;
301
+ duration?: number;
302
+ }
303
+
304
+ interface ChapterAudioInfo {
305
+ audioFilename: string;
306
+ clipStart: number;
307
+ clipEnd: number;
308
+ duration: number;
309
+ }
310
+
311
+ function splitIntoChapters(nodes: MarkdownBlockNode[]): Chapter[] {
312
+ const chapters: Chapter[] = [];
313
+ let currentNodes: MarkdownBlockNode[] = [];
314
+ let currentTitle = 'Untitled';
315
+
316
+ for (const node of nodes) {
317
+ if (node.type === 'heading' && node.depth <= 2) {
318
+ // Flush previous chapter
319
+ if (currentNodes.length > 0) {
320
+ chapters.push({ title: currentTitle, nodes: currentNodes });
321
+ }
322
+ currentTitle = extractHeadingText(node);
323
+ currentNodes = [node];
324
+ } else {
325
+ currentNodes.push(node);
326
+ }
327
+ }
328
+
329
+ // Flush remaining
330
+ if (currentNodes.length > 0) {
331
+ chapters.push({ title: currentTitle, nodes: currentNodes });
332
+ }
333
+
334
+ // If no chapters were created, wrap everything as one
335
+ if (chapters.length === 0) {
336
+ chapters.push({ title: 'Untitled', nodes: [] });
337
+ }
338
+
339
+ return chapters;
340
+ }
341
+
342
+ function extractHeadingText(heading: MarkdownHeading): string {
343
+ return heading.children.map(inlineToText).join('');
344
+ }
345
+
346
+ function inlineToText(node: MarkdownInlineNode): string {
347
+ switch (node.type) {
348
+ case 'text':
349
+ return node.value;
350
+ case 'emphasis':
351
+ case 'strong':
352
+ case 'delete':
353
+ return node.children.map(inlineToText).join('');
354
+ case 'inlineCode':
355
+ return node.value;
356
+ case 'link':
357
+ return node.children.map(inlineToText).join('');
358
+ case 'image':
359
+ return node.alt ?? '';
360
+ case 'break':
361
+ return ' ';
362
+ default:
363
+ return '';
364
+ }
365
+ }
366
+
367
+ // ── Image Collection ──────────────────────────────────────────────
368
+
369
+ function collectDocImages(nodes: MarkdownBlockNode[]): Set<string> {
370
+ const images = new Set<string>();
371
+
372
+ function walkBlock(node: MarkdownBlockNode): void {
373
+ switch (node.type) {
374
+ case 'paragraph':
375
+ case 'heading':
376
+ node.children.forEach(walkInline);
377
+ break;
378
+ case 'blockquote':
379
+ node.children.forEach(walkBlock);
380
+ break;
381
+ case 'list':
382
+ node.children.forEach((item) => item.children.forEach(walkBlock));
383
+ break;
384
+ case 'table':
385
+ node.children.forEach((row) =>
386
+ row.children.forEach((cell) => cell.children.forEach(walkInline)),
387
+ );
388
+ break;
389
+ default:
390
+ break;
391
+ }
392
+ }
393
+
394
+ function walkInline(node: MarkdownInlineNode): void {
395
+ if (
396
+ node.type === 'image' &&
397
+ node.url &&
398
+ !node.url.startsWith('data:') &&
399
+ !node.url.startsWith('http')
400
+ ) {
401
+ images.add(node.url);
402
+ }
403
+ if ('children' in node && Array.isArray(node.children)) {
404
+ (node.children as MarkdownInlineNode[]).forEach(walkInline);
405
+ }
406
+ }
407
+
408
+ nodes.forEach(walkBlock);
409
+ return images;
410
+ }
411
+
412
+ // ── XHTML Rendering ───────────────────────────────────────────────
413
+
414
+ type ImageMap = Map<string, { data: ArrayBuffer; mime: string; filename: string }>;
415
+
416
+ function renderChapterXhtml(
417
+ nodes: MarkdownBlockNode[],
418
+ bookTitle: string,
419
+ images: ImageMap,
420
+ addIds = false,
421
+ ): string {
422
+ let elementCounter = 0;
423
+ const nextId = () => `p${++elementCounter}`;
424
+ const body = nodes.map((n) => blockToXhtml(n, images, addIds ? nextId : undefined)).join('\n');
425
+ return `<?xml version="1.0" encoding="UTF-8"?>
426
+ <!DOCTYPE html>
427
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
428
+ <head>
429
+ <meta charset="UTF-8"/>
430
+ <title>${escapeXml(bookTitle)}</title>
431
+ <link rel="stylesheet" type="text/css" href="../styles.css"/>
432
+ </head>
433
+ <body>
434
+ ${body}
435
+ </body>
436
+ </html>`;
437
+ }
438
+
439
+ function blockToXhtml(node: MarkdownBlockNode, images: ImageMap, nextId?: () => string): string {
440
+ const idAttr = nextId ? ` id="${nextId()}"` : '';
441
+
442
+ switch (node.type) {
443
+ case 'heading': {
444
+ const tag = `h${node.depth}`;
445
+ return `<${tag}${idAttr}>${inlinesToXhtml(node.children, images)}</${tag}>`;
446
+ }
447
+
448
+ case 'paragraph':
449
+ return `<p${idAttr}>${inlinesToXhtml(node.children, images)}</p>`;
450
+
451
+ case 'blockquote':
452
+ return `<blockquote${idAttr}>\n${node.children.map((c) => blockToXhtml(c, images, nextId)).join('\n')}\n</blockquote>`;
453
+
454
+ case 'list': {
455
+ const tag = node.ordered ? 'ol' : 'ul';
456
+ const startAttr =
457
+ node.ordered && node.start && node.start !== 1 ? ` start="${node.start}"` : '';
458
+ const items = node.children.map((item) => listItemToXhtml(item, images)).join('\n');
459
+ return `<${tag}${idAttr}${startAttr}>\n${items}\n</${tag}>`;
460
+ }
461
+
462
+ case 'code': {
463
+ const langAttr = node.lang ? ` class="language-${escapeXml(node.lang)}"` : '';
464
+ return `<pre${idAttr}><code${langAttr}>${escapeXml(node.value)}</code></pre>`;
465
+ }
466
+
467
+ case 'thematicBreak':
468
+ return `<hr${idAttr}/>`;
469
+
470
+ case 'table':
471
+ return tableToXhtml(node as MarkdownTable, images, idAttr);
472
+
473
+ case 'htmlBlock':
474
+ // Strip HTML tags for XHTML safety — raw HTML may not be well-formed XML
475
+ return `<p${idAttr}>${escapeXml(node.rawHtml.replace(/<[^>]+>/g, ''))}</p>`;
476
+
477
+ case 'math':
478
+ return `<p${idAttr} class="math">${escapeXml(node.value)}</p>`;
479
+
480
+ default:
481
+ return '';
482
+ }
483
+ }
484
+
485
+ function listItemToXhtml(item: MarkdownListItem, images: ImageMap): string {
486
+ const content = item.children.map((c) => blockToXhtml(c, images)).join('\n');
487
+ // Unwrap single <p> inside <li> for cleaner output
488
+ const unwrapped =
489
+ item.children.length === 1 && item.children[0].type === 'paragraph'
490
+ ? inlinesToXhtml((item.children[0] as MarkdownParagraph).children, images)
491
+ : content;
492
+ return `<li>${unwrapped}</li>`;
493
+ }
494
+
495
+ function tableToXhtml(table: MarkdownTable, images: ImageMap, idAttr = ''): string {
496
+ const rows = table.children;
497
+ if (rows.length === 0) return `<table${idAttr}></table>`;
498
+
499
+ const headerRow = rows[0];
500
+ const bodyRows = rows.slice(1);
501
+ const align = table.align ?? [];
502
+
503
+ function cellToXhtml(cell: MarkdownTableCell, tag: 'th' | 'td', colIndex: number): string {
504
+ const a = align[colIndex];
505
+ const style = a ? ` style="text-align: ${a}"` : '';
506
+ return `<${tag}${style}>${inlinesToXhtml(cell.children, images)}</${tag}>`;
507
+ }
508
+
509
+ const thead = `<thead><tr>${headerRow.children.map((c, i) => cellToXhtml(c, 'th', i)).join('')}</tr></thead>`;
510
+ const tbody =
511
+ bodyRows.length > 0
512
+ ? `<tbody>${bodyRows.map((row: MarkdownTableRow) => `<tr>${row.children.map((c, i) => cellToXhtml(c, 'td', i)).join('')}</tr>`).join('')}</tbody>`
513
+ : '';
514
+
515
+ return `<table${idAttr}>${thead}${tbody}</table>`;
516
+ }
517
+
518
+ function inlinesToXhtml(nodes: MarkdownInlineNode[], images: ImageMap): string {
519
+ return nodes.map((n) => inlineToXhtml(n, images)).join('');
520
+ }
521
+
522
+ function inlineToXhtml(node: MarkdownInlineNode, images: ImageMap): string {
523
+ switch (node.type) {
524
+ case 'text':
525
+ return escapeXml(node.value);
526
+
527
+ case 'strong':
528
+ return `<strong>${inlinesToXhtml(node.children, images)}</strong>`;
529
+
530
+ case 'emphasis':
531
+ return `<em>${inlinesToXhtml(node.children, images)}</em>`;
532
+
533
+ case 'delete':
534
+ return `<del>${inlinesToXhtml(node.children, images)}</del>`;
535
+
536
+ case 'inlineCode':
537
+ return `<code>${escapeXml(node.value)}</code>`;
538
+
539
+ case 'link': {
540
+ const titleAttr = node.title ? ` title="${escapeXml(node.title)}"` : '';
541
+ return `<a href="${escapeXml(node.url)}"${titleAttr}>${inlinesToXhtml(node.children, images)}</a>`;
542
+ }
543
+
544
+ case 'image': {
545
+ const alt = escapeXml(node.alt ?? '');
546
+ const resolved = images.get(node.url);
547
+ const src = resolved ? `../images/${resolved.filename}` : escapeXml(node.url);
548
+ return `<img src="${src}" alt="${alt}"/>`;
549
+ }
550
+
551
+ case 'break':
552
+ return '<br/>';
553
+
554
+ case 'inlineMath':
555
+ return `<span class="math">${escapeXml(node.value)}</span>`;
556
+
557
+ case 'htmlInline':
558
+ // Strip tags for XHTML safety
559
+ return escapeXml(node.rawHtml.replace(/<[^>]+>/g, ''));
560
+
561
+ default:
562
+ return '';
563
+ }
564
+ }
565
+
566
+ // ── SMIL Media Overlays ───────────────────────────────────────────
567
+
568
+ /**
569
+ * Generate an EPUB 3 Media Overlay (SMIL) file for a chapter.
570
+ * Maps block-level elements to audio clip ranges for synchronized narration.
571
+ */
572
+ function generateSmil(
573
+ chapterFilename: string,
574
+ audioInfo: ChapterAudioInfo,
575
+ nodes: MarkdownBlockNode[],
576
+ ): string {
577
+ // Count block elements to match the IDs generated by blockToXhtml.
578
+ // Must mirror blockToXhtml's recursion: each block gets an ID,
579
+ // blockquote children recurse (they pass nextId), but list items do not.
580
+ let elementCount = 0;
581
+ function countBlocks(node: MarkdownBlockNode): void {
582
+ elementCount++;
583
+ if (node.type === 'blockquote') node.children.forEach(countBlocks);
584
+ }
585
+ nodes.forEach(countBlocks);
586
+
587
+ if (elementCount === 0) elementCount = 1;
588
+
589
+ // Distribute audio duration evenly across elements (best effort without word-level timing)
590
+ const clipDuration = audioInfo.duration / elementCount;
591
+ const pars: string[] = [];
592
+
593
+ for (let i = 0; i < elementCount; i++) {
594
+ const clipStart = formatTime(audioInfo.clipStart + i * clipDuration, true);
595
+ const clipEnd = formatTime(audioInfo.clipStart + (i + 1) * clipDuration, true);
596
+ pars.push(
597
+ ` <par id="par-${i + 1}">` +
598
+ `\n <text src="${chapterFilename}#p${i + 1}"/>` +
599
+ `\n <audio src="../audio/${escapeXml(audioInfo.audioFilename)}" clipBegin="${clipStart}" clipEnd="${clipEnd}"/>` +
600
+ `\n </par>`,
601
+ );
602
+ }
603
+
604
+ return `<?xml version="1.0" encoding="UTF-8"?>
605
+ <smil xmlns="http://www.w3.org/ns/SMIL" xmlns:epub="http://www.idpf.org/2007/ops" version="3.0">
606
+ <body>
607
+ <seq id="seq-1" epub:textref="${chapterFilename}">
608
+ ${pars.join('\n')}
609
+ </seq>
610
+ </body>
611
+ </smil>`;
612
+ }
613
+
614
+ function formatTime(seconds: number, fractional = false): string {
615
+ const h = Math.floor(seconds / 3600);
616
+ const m = Math.floor((seconds % 3600) / 60);
617
+ const s = seconds % 60;
618
+ const sPart = fractional ? s.toFixed(3).padStart(6, '0') : String(Math.floor(s)).padStart(2, '0');
619
+ return `${h}:${String(m).padStart(2, '0')}:${sPart}`;
620
+ }
621
+
622
+ // ── Package Documents ─────────────────────────────────────────────
623
+
624
+ const CONTAINER_XML = `<?xml version="1.0" encoding="UTF-8"?>
625
+ <container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
626
+ <rootfiles>
627
+ <rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
628
+ </rootfiles>
629
+ </container>`;
630
+
631
+ interface OpfParams {
632
+ uuid: string;
633
+ title: string;
634
+ author: string;
635
+ language: string;
636
+ description: string;
637
+ publisher: string;
638
+ chapters: ChapterFileInfo[];
639
+ images: ImageMap;
640
+ coverFilename?: string;
641
+ audioFiles?: { filename: string; mime: string }[];
642
+ totalDuration?: number;
643
+ }
644
+
645
+ function generateContentOpf(params: OpfParams): string {
646
+ const {
647
+ uuid,
648
+ title,
649
+ author,
650
+ language,
651
+ description,
652
+ publisher,
653
+ chapters,
654
+ images,
655
+ coverFilename,
656
+ audioFiles,
657
+ totalDuration,
658
+ } = params;
659
+ const modified = new Date().toISOString().replace(/\.\d+Z$/, 'Z');
660
+ const hasOverlays = chapters.some((c) => c.smilFilename);
661
+
662
+ // Manifest items
663
+ const manifestItems: string[] = [
664
+ ' <item id="toc" href="toc.xhtml" media-type="application/xhtml+xml" properties="nav"/>',
665
+ ' <item id="css" href="styles.css" media-type="text/css"/>',
666
+ ];
667
+
668
+ if (coverFilename) {
669
+ const mime = inferMimeType(coverFilename);
670
+ manifestItems.push(
671
+ ` <item id="cover-image" href="images/${escapeXml(coverFilename)}" media-type="${mime}" properties="cover-image"/>`,
672
+ );
673
+ }
674
+
675
+ for (const chap of chapters) {
676
+ const overlayAttr = chap.smilFilename ? ` media-overlay="${chap.id}-overlay"` : '';
677
+ manifestItems.push(
678
+ ` <item id="${chap.id}" href="chapters/${escapeXml(chap.filename)}" media-type="application/xhtml+xml"${overlayAttr}/>`,
679
+ );
680
+ if (chap.smilFilename) {
681
+ manifestItems.push(
682
+ ` <item id="${chap.id}-overlay" href="chapters/${escapeXml(chap.smilFilename)}" media-type="application/smil+xml"/>`,
683
+ );
684
+ }
685
+ }
686
+
687
+ // Audio files in manifest
688
+ if (audioFiles) {
689
+ const usedAudioNames = new Set<string>();
690
+ for (const af of audioFiles) {
691
+ if (usedAudioNames.has(af.filename)) continue;
692
+ usedAudioNames.add(af.filename);
693
+ const audioId = `audio-${af.filename.replace(/[^a-zA-Z0-9]/g, '-')}`;
694
+ manifestItems.push(
695
+ ` <item id="${audioId}" href="audio/${escapeXml(af.filename)}" media-type="${af.mime}"/>`,
696
+ );
697
+ }
698
+ }
699
+
700
+ const usedFilenames = new Set<string>();
701
+ for (const [, img] of images) {
702
+ if (usedFilenames.has(img.filename)) continue;
703
+ usedFilenames.add(img.filename);
704
+ const imgId = `img-${img.filename.replace(/[^a-zA-Z0-9]/g, '-')}`;
705
+ manifestItems.push(
706
+ ` <item id="${imgId}" href="images/${escapeXml(img.filename)}" media-type="${img.mime}"/>`,
707
+ );
708
+ }
709
+
710
+ // Spine
711
+ const spineItems = chapters.map((chap) => ` <itemref idref="${chap.id}"/>`).join('\n');
712
+
713
+ // Metadata
714
+ const metaParts = [
715
+ ` <dc:identifier id="uid">urn:uuid:${uuid}</dc:identifier>`,
716
+ ` <dc:title>${escapeXml(title)}</dc:title>`,
717
+ ` <dc:language>${escapeXml(language)}</dc:language>`,
718
+ ` <meta property="dcterms:modified">${modified}</meta>`,
719
+ ];
720
+ if (author) metaParts.push(` <dc:creator>${escapeXml(author)}</dc:creator>`);
721
+ if (description) metaParts.push(` <dc:description>${escapeXml(description)}</dc:description>`);
722
+ if (publisher) metaParts.push(` <dc:publisher>${escapeXml(publisher)}</dc:publisher>`);
723
+
724
+ // Media Overlay metadata
725
+ if (hasOverlays && totalDuration) {
726
+ metaParts.push(` <meta property="media:duration">${formatTime(totalDuration)}</meta>`);
727
+ metaParts.push(' <meta property="media:active-class">epub-media-overlay-active</meta>');
728
+ }
729
+
730
+ return `<?xml version="1.0" encoding="UTF-8"?>
731
+ <package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="uid">
732
+ <metadata xmlns:dc="http://purl.org/dc/elements/1.1/">
733
+ ${metaParts.join('\n')}
734
+ </metadata>
735
+ <manifest>
736
+ ${manifestItems.join('\n')}
737
+ </manifest>
738
+ <spine>
739
+ ${spineItems}
740
+ </spine>
741
+ </package>`;
742
+ }
743
+
744
+ function generateTocXhtml(chapters: ChapterFileInfo[], bookTitle: string): string {
745
+ const navItems = chapters
746
+ .map(
747
+ (chap) =>
748
+ ` <li><a href="chapters/${escapeXml(chap.filename)}">${escapeXml(chap.title)}</a></li>`,
749
+ )
750
+ .join('\n');
751
+
752
+ return `<?xml version="1.0" encoding="UTF-8"?>
753
+ <!DOCTYPE html>
754
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
755
+ <head>
756
+ <meta charset="UTF-8"/>
757
+ <title>${escapeXml(bookTitle)}</title>
758
+ <link rel="stylesheet" type="text/css" href="styles.css"/>
759
+ </head>
760
+ <body>
761
+ <nav epub:type="toc">
762
+ <h1>Table of Contents</h1>
763
+ <ol>
764
+ ${navItems}
765
+ </ol>
766
+ </nav>
767
+ </body>
768
+ </html>`;
769
+ }
770
+
771
+ // ── Stylesheet ────────────────────────────────────────────────────
772
+
773
+ function generateStylesheet(themeId?: string): string {
774
+ let themeVars = '';
775
+ if (themeId) {
776
+ const theme = resolveTheme(themeId);
777
+ themeVars = `
778
+ --epub-bg: ${theme.colors.background};
779
+ --epub-text: ${theme.colors.text};
780
+ --epub-primary: ${theme.colors.primary};
781
+ --epub-heading-font: ${theme.typography.titleFontFamily};
782
+ --epub-body-font: ${theme.typography.bodyFontFamily};`;
783
+ }
784
+
785
+ return `/* Squisq EPUB Stylesheet */
786
+ :root {${themeVars}
787
+ }
788
+
789
+ body {
790
+ font-family: var(--epub-body-font, Georgia, 'Times New Roman', serif);
791
+ color: var(--epub-text, #1a1a1a);
792
+ line-height: 1.7;
793
+ margin: 1em 2em;
794
+ max-width: 40em;
795
+ }
796
+
797
+ h1, h2, h3, h4, h5, h6 {
798
+ font-family: var(--epub-heading-font, system-ui, sans-serif);
799
+ color: var(--epub-primary, #1a1a1a);
800
+ margin-top: 1.5em;
801
+ margin-bottom: 0.5em;
802
+ line-height: 1.3;
803
+ }
804
+
805
+ h1 { font-size: 2em; }
806
+ h2 { font-size: 1.5em; }
807
+ h3 { font-size: 1.25em; }
808
+
809
+ p {
810
+ margin: 0.8em 0;
811
+ }
812
+
813
+ a {
814
+ color: var(--epub-primary, #2563eb);
815
+ }
816
+
817
+ img {
818
+ max-width: 100%;
819
+ height: auto;
820
+ }
821
+
822
+ pre {
823
+ background: #f5f5f5;
824
+ padding: 1em;
825
+ overflow-x: auto;
826
+ border-radius: 4px;
827
+ font-size: 0.9em;
828
+ line-height: 1.4;
829
+ }
830
+
831
+ code {
832
+ font-family: 'Courier New', Courier, monospace;
833
+ font-size: 0.9em;
834
+ }
835
+
836
+ p > code, li > code {
837
+ background: #f0f0f0;
838
+ padding: 0.1em 0.3em;
839
+ border-radius: 3px;
840
+ }
841
+
842
+ blockquote {
843
+ border-left: 3px solid var(--epub-primary, #d1d5db);
844
+ margin: 1em 0;
845
+ padding: 0.5em 1em;
846
+ color: #4b5563;
847
+ }
848
+
849
+ table {
850
+ border-collapse: collapse;
851
+ width: 100%;
852
+ margin: 1em 0;
853
+ }
854
+
855
+ th, td {
856
+ border: 1px solid #d1d5db;
857
+ padding: 0.5em 0.75em;
858
+ text-align: left;
859
+ }
860
+
861
+ th {
862
+ background: #f3f4f6;
863
+ font-weight: 600;
864
+ }
865
+
866
+ hr {
867
+ border: none;
868
+ border-top: 1px solid #d1d5db;
869
+ margin: 2em 0;
870
+ }
871
+
872
+ ul, ol {
873
+ margin: 0.8em 0;
874
+ padding-left: 1.5em;
875
+ }
876
+
877
+ li {
878
+ margin: 0.3em 0;
879
+ }
880
+
881
+ .math {
882
+ font-family: 'Courier New', Courier, monospace;
883
+ font-style: italic;
884
+ }
885
+
886
+ /* Media Overlay active highlight (narration sync) */
887
+ .epub-media-overlay-active {
888
+ background-color: rgba(37, 99, 235, 0.12);
889
+ }
890
+ `;
891
+ }