slides-grab 1.0.0 → 1.1.2

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,1166 @@
1
+ /**
2
+ * html2pptx - Experimental / unstable HTML-to-pptxgenjs conversion for slide exports
3
+ *
4
+ * USAGE:
5
+ * const pptx = new pptxgen();
6
+ * pptx.layout = 'LAYOUT_16x9'; // Must match HTML body dimensions
7
+ *
8
+ * const { slide, placeholders } = await html2pptx('slide.html', pptx);
9
+ * slide.addChart(pptx.charts.LINE, data, placeholders[0]);
10
+ *
11
+ * await pptx.writeFile('output.pptx');
12
+ *
13
+ * FEATURES:
14
+ * - Best-effort conversion from HTML to PowerPoint
15
+ * - Supports text, images, shapes, and bullet lists
16
+ * - Extracts placeholder elements (class="placeholder") with positions
17
+ * - Handles CSS gradients, borders, and margins
18
+ *
19
+ * VALIDATION:
20
+ * - Uses body width/height from HTML for viewport sizing
21
+ * - Throws error if HTML dimensions don't match presentation layout
22
+ * - Throws error if content overflows body (with overflow details)
23
+ *
24
+ * RETURNS:
25
+ * { slide, placeholders } where placeholders is an array of { id, x, y, w, h }
26
+ */
27
+
28
+ const { chromium } = require('playwright');
29
+ const path = require('path');
30
+ const sharp = require('sharp');
31
+
32
+ const PT_PER_PX = 0.75;
33
+ const PX_PER_IN = 96;
34
+ const EMU_PER_IN = 914400;
35
+
36
+ async function launchBrowser(tmpDir) {
37
+ const launchOptions = { env: { TMPDIR: tmpDir } };
38
+
39
+ if (process.platform !== 'darwin') {
40
+ return chromium.launch(launchOptions);
41
+ }
42
+
43
+ try {
44
+ return await chromium.launch({ ...launchOptions, channel: 'chrome' });
45
+ } catch (error) {
46
+ if (error && typeof error.message === 'string' && error.message.includes("Chromium distribution 'chrome' is not found")) {
47
+ return chromium.launch(launchOptions);
48
+ }
49
+ throw error;
50
+ }
51
+ }
52
+
53
+ async function waitForDynamicLibraryRender(page, timeout = 5000) {
54
+ await page.evaluate(async () => {
55
+ if (document.fonts?.ready) {
56
+ await document.fonts.ready;
57
+ }
58
+ });
59
+
60
+ const hasCanvas = await page.evaluate(() => document.querySelector('canvas') !== null);
61
+ if (hasCanvas) {
62
+ await page.evaluate(() => {
63
+ if (!window.Chart || !window.Chart.instances) return;
64
+ const instances = Array.isArray(window.Chart.instances)
65
+ ? window.Chart.instances
66
+ : Object.values(window.Chart.instances);
67
+
68
+ for (const chart of instances) {
69
+ if (!chart) continue;
70
+ if (chart.options) chart.options.animation = false;
71
+ if (typeof chart.update === 'function') {
72
+ try {
73
+ chart.update('none');
74
+ } catch (_) {
75
+ // noop
76
+ }
77
+ }
78
+ }
79
+ });
80
+
81
+ try {
82
+ await page.waitForFunction(() => {
83
+ const canvases = Array.from(document.querySelectorAll('canvas'));
84
+ if (canvases.length === 0) return true;
85
+
86
+ const instances = (window.Chart && window.Chart.instances)
87
+ ? (Array.isArray(window.Chart.instances) ? window.Chart.instances : Object.values(window.Chart.instances))
88
+ : [];
89
+
90
+ return canvases.every((canvas) => {
91
+ const rect = canvas.getBoundingClientRect();
92
+ if (rect.width === 0 || rect.height === 0) return false;
93
+
94
+ const matchedChart = instances.find((instance) => instance && instance.canvas === canvas);
95
+ if (!matchedChart) return true;
96
+ return matchedChart.animating === false;
97
+ });
98
+ }, null, { timeout });
99
+ } catch (_) {
100
+ // Keep conversion resilient even when chart animation state is unavailable.
101
+ }
102
+ }
103
+
104
+ const hasMermaid = await page.evaluate(() => document.querySelector('.mermaid') !== null);
105
+ if (hasMermaid) {
106
+ await page.evaluate(async () => {
107
+ if (!window.mermaid) return;
108
+
109
+ try {
110
+ if (typeof window.mermaid.run === 'function') {
111
+ await window.mermaid.run({ querySelector: '.mermaid' });
112
+ return;
113
+ }
114
+
115
+ if (typeof window.mermaid.init === 'function') {
116
+ await window.mermaid.init(undefined, document.querySelectorAll('.mermaid'));
117
+ }
118
+ } catch (_) {
119
+ // noop
120
+ }
121
+ });
122
+
123
+ try {
124
+ await page.waitForFunction(() => {
125
+ const blocks = Array.from(document.querySelectorAll('.mermaid'));
126
+ if (blocks.length === 0) return true;
127
+ return blocks.every((block) => block.querySelector('svg') !== null);
128
+ }, null, { timeout });
129
+ } catch (_) {
130
+ // Keep conversion resilient when Mermaid CDN/script is unavailable.
131
+ }
132
+ }
133
+ }
134
+
135
+ async function rasterizeDynamicVisuals(page) {
136
+ await page.evaluate(async () => {
137
+ const waitForImageLoad = (img) => new Promise((resolve) => {
138
+ if (img.complete) {
139
+ resolve();
140
+ return;
141
+ }
142
+
143
+ const done = () => resolve();
144
+ img.addEventListener('load', done, { once: true });
145
+ img.addEventListener('error', done, { once: true });
146
+ });
147
+
148
+ const canvasList = Array.from(document.querySelectorAll('canvas'));
149
+ for (const canvas of canvasList) {
150
+ try {
151
+ const rect = canvas.getBoundingClientRect();
152
+ if (rect.width === 0 || rect.height === 0) continue;
153
+
154
+ const dataUrl = canvas.toDataURL('image/png');
155
+ if (!dataUrl || dataUrl === 'data:,') continue;
156
+
157
+ const computed = window.getComputedStyle(canvas);
158
+ const img = document.createElement('img');
159
+ img.src = dataUrl;
160
+ img.alt = canvas.getAttribute('aria-label') || 'chart';
161
+ img.style.width = `${rect.width}px`;
162
+ img.style.height = `${rect.height}px`;
163
+ img.style.display = computed.display === 'inline' ? 'inline-block' : computed.display;
164
+ img.style.objectFit = 'contain';
165
+ if (canvas.className) img.className = canvas.className;
166
+ if (canvas.id) img.id = `${canvas.id}-rendered`;
167
+
168
+ canvas.replaceWith(img);
169
+ await waitForImageLoad(img);
170
+ } catch (_) {
171
+ // noop
172
+ }
173
+ }
174
+
175
+ const svgList = Array.from(document.querySelectorAll('svg'));
176
+ for (const svg of svgList) {
177
+ try {
178
+ const rect = svg.getBoundingClientRect();
179
+ if (rect.width === 0 || rect.height === 0) continue;
180
+
181
+ const clone = svg.cloneNode(true);
182
+ if (!clone.getAttribute('xmlns')) {
183
+ clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
184
+ }
185
+ if (!clone.getAttribute('xmlns:xlink')) {
186
+ clone.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink');
187
+ }
188
+ if (!clone.getAttribute('width')) {
189
+ clone.setAttribute('width', `${Math.max(1, Math.round(rect.width))}`);
190
+ }
191
+ if (!clone.getAttribute('height')) {
192
+ clone.setAttribute('height', `${Math.max(1, Math.round(rect.height))}`);
193
+ }
194
+
195
+ const serialized = new XMLSerializer().serializeToString(clone);
196
+ const base64Svg = btoa(unescape(encodeURIComponent(serialized)));
197
+ const dataUrl = `data:image/svg+xml;base64,${base64Svg}`;
198
+
199
+ const computed = window.getComputedStyle(svg);
200
+ const img = document.createElement('img');
201
+ img.src = dataUrl;
202
+ img.alt = 'diagram';
203
+ img.style.width = `${rect.width}px`;
204
+ img.style.height = `${rect.height}px`;
205
+ img.style.display = computed.display === 'inline' ? 'inline-block' : computed.display;
206
+ img.style.objectFit = 'contain';
207
+
208
+ svg.replaceWith(img);
209
+ await waitForImageLoad(img);
210
+ } catch (_) {
211
+ // noop
212
+ }
213
+ }
214
+ });
215
+ }
216
+
217
+ // Helper: Get body dimensions and check for overflow
218
+ async function getBodyDimensions(page) {
219
+ const bodyDimensions = await page.evaluate(() => {
220
+ const body = document.body;
221
+ const style = window.getComputedStyle(body);
222
+
223
+ return {
224
+ width: parseFloat(style.width),
225
+ height: parseFloat(style.height),
226
+ scrollWidth: body.scrollWidth,
227
+ scrollHeight: body.scrollHeight
228
+ };
229
+ });
230
+
231
+ const errors = [];
232
+ const widthOverflowPx = Math.max(0, bodyDimensions.scrollWidth - bodyDimensions.width - 1);
233
+ const heightOverflowPx = Math.max(0, bodyDimensions.scrollHeight - bodyDimensions.height - 1);
234
+
235
+ const widthOverflowPt = widthOverflowPx * PT_PER_PX;
236
+ const heightOverflowPt = heightOverflowPx * PT_PER_PX;
237
+
238
+ if (widthOverflowPt > 0 || heightOverflowPt > 0) {
239
+ const directions = [];
240
+ if (widthOverflowPt > 0) directions.push(`${widthOverflowPt.toFixed(1)}pt horizontally`);
241
+ if (heightOverflowPt > 0) directions.push(`${heightOverflowPt.toFixed(1)}pt vertically`);
242
+ const reminder = heightOverflowPt > 0 ? ' (Remember: leave 0.5" margin at bottom of slide)' : '';
243
+ errors.push(`HTML content overflows body by ${directions.join(' and ')}${reminder}`);
244
+ }
245
+
246
+ return { ...bodyDimensions, errors };
247
+ }
248
+
249
+ // Helper: Validate dimensions match presentation layout
250
+ function validateDimensions(bodyDimensions, pres) {
251
+ const errors = [];
252
+ const widthInches = bodyDimensions.width / PX_PER_IN;
253
+ const heightInches = bodyDimensions.height / PX_PER_IN;
254
+
255
+ if (pres.presLayout) {
256
+ const layoutWidth = pres.presLayout.width / EMU_PER_IN;
257
+ const layoutHeight = pres.presLayout.height / EMU_PER_IN;
258
+
259
+ if (Math.abs(layoutWidth - widthInches) > 0.1 || Math.abs(layoutHeight - heightInches) > 0.1) {
260
+ errors.push(
261
+ `HTML dimensions (${widthInches.toFixed(1)}" × ${heightInches.toFixed(1)}") ` +
262
+ `don't match presentation layout (${layoutWidth.toFixed(1)}" × ${layoutHeight.toFixed(1)}")`
263
+ );
264
+ }
265
+ }
266
+ return errors;
267
+ }
268
+
269
+ function validateTextBoxPosition(slideData, bodyDimensions) {
270
+ const errors = [];
271
+ const slideHeightInches = bodyDimensions.height / PX_PER_IN;
272
+ const minBottomMargin = 0.5; // 0.5 inches from bottom
273
+
274
+ for (const el of slideData.elements) {
275
+ // Check text elements (p, h1-h6, list)
276
+ if (['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'list'].includes(el.type)) {
277
+ const fontSize = el.style?.fontSize || 0;
278
+ const bottomEdge = el.position.y + el.position.h;
279
+ const distanceFromBottom = slideHeightInches - bottomEdge;
280
+
281
+ if (fontSize > 12 && distanceFromBottom < minBottomMargin) {
282
+ const getText = () => {
283
+ if (typeof el.text === 'string') return el.text;
284
+ if (Array.isArray(el.text)) return el.text.find(t => t.text)?.text || '';
285
+ if (Array.isArray(el.items)) return el.items.find(item => item.text)?.text || '';
286
+ return '';
287
+ };
288
+ const textPrefix = getText().substring(0, 50) + (getText().length > 50 ? '...' : '');
289
+
290
+ errors.push(
291
+ `Text box "${textPrefix}" ends too close to bottom edge ` +
292
+ `(${distanceFromBottom.toFixed(2)}" from bottom, minimum ${minBottomMargin}" required)`
293
+ );
294
+ }
295
+ }
296
+ }
297
+
298
+ return errors;
299
+ }
300
+
301
+ // Helper: Add background to slide
302
+ async function addBackground(slideData, targetSlide, tmpDir) {
303
+ if (slideData.background.type === 'image' && slideData.background.path) {
304
+ let imagePath = slideData.background.path.startsWith('file://')
305
+ ? slideData.background.path.replace('file://', '')
306
+ : slideData.background.path;
307
+ targetSlide.background = { path: imagePath };
308
+ } else if (slideData.background.type === 'color' && slideData.background.value) {
309
+ targetSlide.background = { color: slideData.background.value };
310
+ }
311
+ }
312
+
313
+ // Helper: Add elements to slide
314
+ function addElements(slideData, targetSlide, pres) {
315
+ for (const el of slideData.elements) {
316
+ if (el.type === 'image') {
317
+ if (el.src.startsWith('data:')) {
318
+ targetSlide.addImage({
319
+ data: el.src.replace(/^data:/, ''),
320
+ x: el.position.x,
321
+ y: el.position.y,
322
+ w: el.position.w,
323
+ h: el.position.h
324
+ });
325
+ } else {
326
+ let imagePath = el.src.startsWith('file://') ? el.src.replace('file://', '') : el.src;
327
+ targetSlide.addImage({
328
+ path: imagePath,
329
+ x: el.position.x,
330
+ y: el.position.y,
331
+ w: el.position.w,
332
+ h: el.position.h
333
+ });
334
+ }
335
+ } else if (el.type === 'line') {
336
+ targetSlide.addShape(pres.ShapeType.line, {
337
+ x: el.x1,
338
+ y: el.y1,
339
+ w: el.x2 - el.x1,
340
+ h: el.y2 - el.y1,
341
+ line: { color: el.color, width: el.width }
342
+ });
343
+ } else if (el.type === 'shape') {
344
+ const shapeOptions = {
345
+ x: el.position.x,
346
+ y: el.position.y,
347
+ w: el.position.w,
348
+ h: el.position.h,
349
+ shape: el.shape.rectRadius > 0 ? pres.ShapeType.roundRect : pres.ShapeType.rect
350
+ };
351
+
352
+ if (el.shape.fill) {
353
+ shapeOptions.fill = { color: el.shape.fill };
354
+ if (el.shape.transparency != null) shapeOptions.fill.transparency = el.shape.transparency;
355
+ }
356
+ if (el.shape.line) shapeOptions.line = el.shape.line;
357
+ if (el.shape.rectRadius > 0) shapeOptions.rectRadius = el.shape.rectRadius;
358
+ if (el.shape.shadow) shapeOptions.shadow = el.shape.shadow;
359
+
360
+ targetSlide.addText(el.text || '', shapeOptions);
361
+ } else if (el.type === 'list') {
362
+ const listOptions = {
363
+ x: el.position.x,
364
+ y: el.position.y,
365
+ w: el.position.w,
366
+ h: el.position.h,
367
+ fontSize: el.style.fontSize,
368
+ fontFace: el.style.fontFace,
369
+ color: el.style.color,
370
+ align: el.style.align,
371
+ valign: 'top',
372
+ lineSpacing: el.style.lineSpacing,
373
+ paraSpaceBefore: el.style.paraSpaceBefore,
374
+ paraSpaceAfter: el.style.paraSpaceAfter,
375
+ margin: el.style.margin
376
+ };
377
+ if (el.style.margin) listOptions.margin = el.style.margin;
378
+ targetSlide.addText(el.items, listOptions);
379
+ } else {
380
+ // Check if text is single-line (height suggests one line)
381
+ const lineHeight = el.style.lineSpacing || el.style.fontSize * 1.2;
382
+ const isSingleLine = el.position.h <= lineHeight * 1.5;
383
+
384
+ let adjustedX = el.position.x;
385
+ let adjustedW = el.position.w;
386
+
387
+ // Make single-line text 2% wider to account for underestimate
388
+ if (isSingleLine) {
389
+ const widthIncrease = el.position.w * 0.02;
390
+ const align = el.style.align;
391
+
392
+ if (align === 'center') {
393
+ // Center: expand both sides
394
+ adjustedX = el.position.x - (widthIncrease / 2);
395
+ adjustedW = el.position.w + widthIncrease;
396
+ } else if (align === 'right') {
397
+ // Right: expand to the left
398
+ adjustedX = el.position.x - widthIncrease;
399
+ adjustedW = el.position.w + widthIncrease;
400
+ } else {
401
+ // Left (default): expand to the right
402
+ adjustedW = el.position.w + widthIncrease;
403
+ }
404
+ }
405
+
406
+ const textOptions = {
407
+ x: adjustedX,
408
+ y: el.position.y,
409
+ w: adjustedW,
410
+ h: el.position.h,
411
+ fontSize: el.style.fontSize,
412
+ fontFace: el.style.fontFace,
413
+ color: el.style.color,
414
+ bold: el.style.bold,
415
+ italic: el.style.italic,
416
+ underline: el.style.underline,
417
+ valign: 'top',
418
+ lineSpacing: el.style.lineSpacing,
419
+ paraSpaceBefore: el.style.paraSpaceBefore,
420
+ paraSpaceAfter: el.style.paraSpaceAfter,
421
+ inset: 0 // Remove default PowerPoint internal padding
422
+ };
423
+
424
+ if (el.style.align) textOptions.align = el.style.align;
425
+ if (el.style.margin) textOptions.margin = el.style.margin;
426
+ if (el.style.rotate !== undefined) textOptions.rotate = el.style.rotate;
427
+ if (el.style.transparency !== null && el.style.transparency !== undefined) textOptions.transparency = el.style.transparency;
428
+
429
+ targetSlide.addText(el.text, textOptions);
430
+ }
431
+ }
432
+ }
433
+
434
+ // Helper: Extract slide data from HTML page
435
+ async function extractSlideData(page) {
436
+ return await page.evaluate(() => {
437
+ const PT_PER_PX = 0.75;
438
+ const PX_PER_IN = 96;
439
+
440
+ // Fonts that are single-weight and should not have bold applied
441
+ // (applying bold causes PowerPoint to use faux bold which makes text wider)
442
+ const SINGLE_WEIGHT_FONTS = ['impact'];
443
+
444
+ // Helper: Check if a font should skip bold formatting
445
+ const shouldSkipBold = (fontFamily) => {
446
+ if (!fontFamily) return false;
447
+ const normalizedFont = fontFamily.toLowerCase().replace(/['"]/g, '').split(',')[0].trim();
448
+ return SINGLE_WEIGHT_FONTS.includes(normalizedFont);
449
+ };
450
+
451
+ // Unit conversion helpers
452
+ const pxToInch = (px) => px / PX_PER_IN;
453
+ const pxToPoints = (pxStr) => parseFloat(pxStr) * PT_PER_PX;
454
+ const rgbToHex = (rgbStr) => {
455
+ // Handle transparent backgrounds by defaulting to white
456
+ if (rgbStr === 'rgba(0, 0, 0, 0)' || rgbStr === 'transparent') return 'FFFFFF';
457
+
458
+ const match = rgbStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);
459
+ if (!match) return 'FFFFFF';
460
+ return match.slice(1).map(n => parseInt(n).toString(16).padStart(2, '0')).join('');
461
+ };
462
+
463
+ const extractAlpha = (rgbStr) => {
464
+ const match = rgbStr.match(/rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)/);
465
+ if (!match || !match[4]) return null;
466
+ const alpha = parseFloat(match[4]);
467
+ return Math.round((1 - alpha) * 100);
468
+ };
469
+
470
+ const applyTextTransform = (text, textTransform) => {
471
+ if (textTransform === 'uppercase') return text.toUpperCase();
472
+ if (textTransform === 'lowercase') return text.toLowerCase();
473
+ if (textTransform === 'capitalize') {
474
+ return text.replace(/\b\w/g, c => c.toUpperCase());
475
+ }
476
+ return text;
477
+ };
478
+
479
+ // Extract rotation angle from CSS transform and writing-mode
480
+ const getRotation = (transform, writingMode) => {
481
+ let angle = 0;
482
+
483
+ // Handle writing-mode first
484
+ // PowerPoint: 90° = text rotated 90° clockwise (reads top to bottom, letters upright)
485
+ // PowerPoint: 270° = text rotated 270° clockwise (reads bottom to top, letters upright)
486
+ if (writingMode === 'vertical-rl') {
487
+ // vertical-rl alone = text reads top to bottom = 90° in PowerPoint
488
+ angle = 90;
489
+ } else if (writingMode === 'vertical-lr') {
490
+ // vertical-lr alone = text reads bottom to top = 270° in PowerPoint
491
+ angle = 270;
492
+ }
493
+
494
+ // Then add any transform rotation
495
+ if (transform && transform !== 'none') {
496
+ // Try to match rotate() function
497
+ const rotateMatch = transform.match(/rotate\((-?\d+(?:\.\d+)?)deg\)/);
498
+ if (rotateMatch) {
499
+ angle += parseFloat(rotateMatch[1]);
500
+ } else {
501
+ // Browser may compute as matrix - extract rotation from matrix
502
+ const matrixMatch = transform.match(/matrix\(([^)]+)\)/);
503
+ if (matrixMatch) {
504
+ const values = matrixMatch[1].split(',').map(parseFloat);
505
+ // matrix(a, b, c, d, e, f) where rotation = atan2(b, a)
506
+ const matrixAngle = Math.atan2(values[1], values[0]) * (180 / Math.PI);
507
+ angle += Math.round(matrixAngle);
508
+ }
509
+ }
510
+ }
511
+
512
+ // Normalize to 0-359 range
513
+ angle = angle % 360;
514
+ if (angle < 0) angle += 360;
515
+
516
+ return angle === 0 ? null : angle;
517
+ };
518
+
519
+ // Get position/dimensions accounting for rotation
520
+ const getPositionAndSize = (el, rect, rotation) => {
521
+ if (rotation === null) {
522
+ return { x: rect.left, y: rect.top, w: rect.width, h: rect.height };
523
+ }
524
+
525
+ // For 90° or 270° rotations, swap width and height
526
+ // because PowerPoint applies rotation to the original (unrotated) box
527
+ const isVertical = rotation === 90 || rotation === 270;
528
+
529
+ if (isVertical) {
530
+ // The browser shows us the rotated dimensions (tall box for vertical text)
531
+ // But PowerPoint needs the pre-rotation dimensions (wide box that will be rotated)
532
+ // So we swap: browser's height becomes PPT's width, browser's width becomes PPT's height
533
+ const centerX = rect.left + rect.width / 2;
534
+ const centerY = rect.top + rect.height / 2;
535
+
536
+ return {
537
+ x: centerX - rect.height / 2,
538
+ y: centerY - rect.width / 2,
539
+ w: rect.height,
540
+ h: rect.width
541
+ };
542
+ }
543
+
544
+ // For other rotations, use element's offset dimensions
545
+ const centerX = rect.left + rect.width / 2;
546
+ const centerY = rect.top + rect.height / 2;
547
+ return {
548
+ x: centerX - el.offsetWidth / 2,
549
+ y: centerY - el.offsetHeight / 2,
550
+ w: el.offsetWidth,
551
+ h: el.offsetHeight
552
+ };
553
+ };
554
+
555
+ // Parse CSS box-shadow into PptxGenJS shadow properties
556
+ const parseBoxShadow = (boxShadow) => {
557
+ if (!boxShadow || boxShadow === 'none') return null;
558
+
559
+ // Browser computed style format: "rgba(0, 0, 0, 0.3) 2px 2px 8px 0px [inset]"
560
+ // CSS format: "[inset] 2px 2px 8px 0px rgba(0, 0, 0, 0.3)"
561
+
562
+ const insetMatch = boxShadow.match(/inset/);
563
+
564
+ // IMPORTANT: PptxGenJS/PowerPoint doesn't properly support inset shadows
565
+ // Only process outer shadows to avoid file corruption
566
+ if (insetMatch) return null;
567
+
568
+ // Extract color first (rgba or rgb at start)
569
+ const colorMatch = boxShadow.match(/rgba?\([^)]+\)/);
570
+
571
+ // Extract numeric values (handles both px and pt units)
572
+ const parts = boxShadow.match(/([-\d.]+)(px|pt)/g);
573
+
574
+ if (!parts || parts.length < 2) return null;
575
+
576
+ const offsetX = parseFloat(parts[0]);
577
+ const offsetY = parseFloat(parts[1]);
578
+ const blur = parts.length > 2 ? parseFloat(parts[2]) : 0;
579
+
580
+ // Calculate angle from offsets (in degrees, 0 = right, 90 = down)
581
+ let angle = 0;
582
+ if (offsetX !== 0 || offsetY !== 0) {
583
+ angle = Math.atan2(offsetY, offsetX) * (180 / Math.PI);
584
+ if (angle < 0) angle += 360;
585
+ }
586
+
587
+ // Calculate offset distance (hypotenuse)
588
+ const offset = Math.sqrt(offsetX * offsetX + offsetY * offsetY) * PT_PER_PX;
589
+
590
+ // Extract opacity from rgba
591
+ let opacity = 0.5;
592
+ if (colorMatch) {
593
+ const opacityMatch = colorMatch[0].match(/[\d.]+\)$/);
594
+ if (opacityMatch) {
595
+ opacity = parseFloat(opacityMatch[0].replace(')', ''));
596
+ }
597
+ }
598
+
599
+ return {
600
+ type: 'outer',
601
+ angle: Math.round(angle),
602
+ blur: blur * 0.75, // Convert to points
603
+ color: colorMatch ? rgbToHex(colorMatch[0]) : '000000',
604
+ offset: offset,
605
+ opacity
606
+ };
607
+ };
608
+
609
+ // Parse inline formatting tags (<b>, <i>, <u>, <strong>, <em>, <span>) into text runs
610
+ const parseInlineFormatting = (element, baseOptions = {}, runs = [], baseTextTransform = (x) => x) => {
611
+ let prevNodeIsText = false;
612
+
613
+ element.childNodes.forEach((node) => {
614
+ let textTransform = baseTextTransform;
615
+
616
+ const isText = node.nodeType === Node.TEXT_NODE || node.tagName === 'BR';
617
+ if (isText) {
618
+ const text = node.tagName === 'BR' ? '\n' : textTransform(node.textContent.replace(/\s+/g, ' '));
619
+ const prevRun = runs[runs.length - 1];
620
+ if (prevNodeIsText && prevRun) {
621
+ prevRun.text += text;
622
+ } else {
623
+ runs.push({ text, options: { ...baseOptions } });
624
+ }
625
+
626
+ } else if (node.nodeType === Node.ELEMENT_NODE && node.textContent.trim()) {
627
+ const options = { ...baseOptions };
628
+ const computed = window.getComputedStyle(node);
629
+
630
+ // Handle inline elements with computed styles
631
+ if (node.tagName === 'SPAN' || node.tagName === 'B' || node.tagName === 'STRONG' || node.tagName === 'I' || node.tagName === 'EM' || node.tagName === 'U') {
632
+ const isBold = computed.fontWeight === 'bold' || parseInt(computed.fontWeight) >= 600;
633
+ if (isBold && !shouldSkipBold(computed.fontFamily)) options.bold = true;
634
+ if (computed.fontStyle === 'italic') options.italic = true;
635
+ if (computed.textDecoration && computed.textDecoration.includes('underline')) options.underline = true;
636
+ if (computed.color && computed.color !== 'rgb(0, 0, 0)') {
637
+ options.color = rgbToHex(computed.color);
638
+ const transparency = extractAlpha(computed.color);
639
+ if (transparency !== null) options.transparency = transparency;
640
+ }
641
+ if (computed.fontSize) options.fontSize = pxToPoints(computed.fontSize);
642
+
643
+ // Apply text-transform on the span element itself
644
+ if (computed.textTransform && computed.textTransform !== 'none') {
645
+ const transformStr = computed.textTransform;
646
+ textTransform = (text) => applyTextTransform(text, transformStr);
647
+ }
648
+
649
+ // Validate: Check for margins on inline elements
650
+ if (computed.marginLeft && parseFloat(computed.marginLeft) > 0) {
651
+ errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-left which is not supported in PowerPoint. Remove margin from inline elements.`);
652
+ }
653
+ if (computed.marginRight && parseFloat(computed.marginRight) > 0) {
654
+ errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-right which is not supported in PowerPoint. Remove margin from inline elements.`);
655
+ }
656
+ if (computed.marginTop && parseFloat(computed.marginTop) > 0) {
657
+ errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-top which is not supported in PowerPoint. Remove margin from inline elements.`);
658
+ }
659
+ if (computed.marginBottom && parseFloat(computed.marginBottom) > 0) {
660
+ errors.push(`Inline element <${node.tagName.toLowerCase()}> has margin-bottom which is not supported in PowerPoint. Remove margin from inline elements.`);
661
+ }
662
+
663
+ // Recursively process the child node. This will flatten nested spans into multiple runs.
664
+ parseInlineFormatting(node, options, runs, textTransform);
665
+ }
666
+ }
667
+
668
+ prevNodeIsText = isText;
669
+ });
670
+
671
+ // Trim leading space from first run and trailing space from last run
672
+ if (runs.length > 0) {
673
+ runs[0].text = runs[0].text.replace(/^\s+/, '');
674
+ runs[runs.length - 1].text = runs[runs.length - 1].text.replace(/\s+$/, '');
675
+ }
676
+
677
+ return runs.filter(r => r.text.length > 0);
678
+ };
679
+
680
+ // Extract background from body (image or color)
681
+ const body = document.body;
682
+ const bodyStyle = window.getComputedStyle(body);
683
+ const bgImage = bodyStyle.backgroundImage;
684
+ const bgColor = bodyStyle.backgroundColor;
685
+
686
+ // Collect validation errors
687
+ const errors = [];
688
+
689
+ // Validate: Check for CSS gradients
690
+ if (bgImage && (bgImage.includes('linear-gradient') || bgImage.includes('radial-gradient'))) {
691
+ errors.push(
692
+ 'CSS gradients are not supported. Use Sharp to rasterize gradients as PNG images first, ' +
693
+ 'then reference with background-image: url(\'gradient.png\')'
694
+ );
695
+ }
696
+
697
+ let background;
698
+ if (bgImage && bgImage !== 'none') {
699
+ // Extract URL from url("...") or url(...)
700
+ const urlMatch = bgImage.match(/url\(["']?([^"')]+)["']?\)/);
701
+ if (urlMatch) {
702
+ background = {
703
+ type: 'image',
704
+ path: urlMatch[1]
705
+ };
706
+ } else {
707
+ background = {
708
+ type: 'color',
709
+ value: rgbToHex(bgColor)
710
+ };
711
+ }
712
+ } else {
713
+ background = {
714
+ type: 'color',
715
+ value: rgbToHex(bgColor)
716
+ };
717
+ }
718
+
719
+ // Process all elements
720
+ const elements = [];
721
+ const placeholders = [];
722
+ const textTags = ['P', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'UL', 'OL', 'LI'];
723
+ const processed = new Set();
724
+
725
+ document.querySelectorAll('*').forEach((el) => {
726
+ if (processed.has(el)) return;
727
+
728
+ // Validate text elements don't have backgrounds, borders, or shadows
729
+ if (textTags.includes(el.tagName)) {
730
+ const computed = window.getComputedStyle(el);
731
+ const hasBg = computed.backgroundColor && computed.backgroundColor !== 'rgba(0, 0, 0, 0)';
732
+ const hasBorder = (computed.borderWidth && parseFloat(computed.borderWidth) > 0) ||
733
+ (computed.borderTopWidth && parseFloat(computed.borderTopWidth) > 0) ||
734
+ (computed.borderRightWidth && parseFloat(computed.borderRightWidth) > 0) ||
735
+ (computed.borderBottomWidth && parseFloat(computed.borderBottomWidth) > 0) ||
736
+ (computed.borderLeftWidth && parseFloat(computed.borderLeftWidth) > 0);
737
+ const hasShadow = computed.boxShadow && computed.boxShadow !== 'none';
738
+
739
+ if (hasBg || hasBorder || hasShadow) {
740
+ errors.push(
741
+ `Text element <${el.tagName.toLowerCase()}> has ${hasBg ? 'background' : hasBorder ? 'border' : 'shadow'}. ` +
742
+ 'Backgrounds, borders, and shadows are only supported on <div> elements, not text elements.'
743
+ );
744
+ return;
745
+ }
746
+ }
747
+
748
+ // Extract placeholder elements (for charts, etc.)
749
+ if (el.className && el.className.includes('placeholder')) {
750
+ const rect = el.getBoundingClientRect();
751
+ if (rect.width === 0 || rect.height === 0) {
752
+ errors.push(
753
+ `Placeholder "${el.id || 'unnamed'}" has ${rect.width === 0 ? 'width: 0' : 'height: 0'}. Check the layout CSS.`
754
+ );
755
+ } else {
756
+ placeholders.push({
757
+ id: el.id || `placeholder-${placeholders.length}`,
758
+ x: pxToInch(rect.left),
759
+ y: pxToInch(rect.top),
760
+ w: pxToInch(rect.width),
761
+ h: pxToInch(rect.height)
762
+ });
763
+ }
764
+ processed.add(el);
765
+ return;
766
+ }
767
+
768
+ // Extract images
769
+ if (el.tagName === 'IMG') {
770
+ const rect = el.getBoundingClientRect();
771
+ if (rect.width > 0 && rect.height > 0) {
772
+ elements.push({
773
+ type: 'image',
774
+ src: el.src,
775
+ position: {
776
+ x: pxToInch(rect.left),
777
+ y: pxToInch(rect.top),
778
+ w: pxToInch(rect.width),
779
+ h: pxToInch(rect.height)
780
+ }
781
+ });
782
+ processed.add(el);
783
+ return;
784
+ }
785
+ }
786
+
787
+ // Extract DIVs with backgrounds/borders as shapes
788
+ const isContainer = el.tagName === 'DIV' && !textTags.includes(el.tagName);
789
+ if (isContainer) {
790
+ const computed = window.getComputedStyle(el);
791
+ const hasBg = computed.backgroundColor && computed.backgroundColor !== 'rgba(0, 0, 0, 0)';
792
+
793
+ // Validate: Check for unwrapped text content in DIV
794
+ for (const node of el.childNodes) {
795
+ if (node.nodeType === Node.TEXT_NODE) {
796
+ const text = node.textContent.trim();
797
+ if (text) {
798
+ errors.push(
799
+ `DIV element contains unwrapped text "${text.substring(0, 50)}${text.length > 50 ? '...' : ''}". ` +
800
+ 'All text must be wrapped in <p>, <h1>-<h6>, <ul>, or <ol> tags to appear in PowerPoint.'
801
+ );
802
+ }
803
+ }
804
+ }
805
+
806
+ // Check for background images on shapes
807
+ const bgImage = computed.backgroundImage;
808
+ if (bgImage && bgImage !== 'none') {
809
+ errors.push(
810
+ 'Background images on DIV elements are not supported. ' +
811
+ 'Use solid colors or borders for shapes, or use slide.addImage() in PptxGenJS to layer images.'
812
+ );
813
+ return;
814
+ }
815
+
816
+ // Check for borders - both uniform and partial
817
+ const borderTop = computed.borderTopWidth;
818
+ const borderRight = computed.borderRightWidth;
819
+ const borderBottom = computed.borderBottomWidth;
820
+ const borderLeft = computed.borderLeftWidth;
821
+ const borders = [borderTop, borderRight, borderBottom, borderLeft].map(b => parseFloat(b) || 0);
822
+ const hasBorder = borders.some(b => b > 0);
823
+ const hasUniformBorder = hasBorder && borders.every(b => b === borders[0]);
824
+ const borderLines = [];
825
+
826
+ if (hasBorder && !hasUniformBorder) {
827
+ const rect = el.getBoundingClientRect();
828
+ const x = pxToInch(rect.left);
829
+ const y = pxToInch(rect.top);
830
+ const w = pxToInch(rect.width);
831
+ const h = pxToInch(rect.height);
832
+
833
+ // Collect lines to add after shape (inset by half the line width to center on edge)
834
+ if (parseFloat(borderTop) > 0) {
835
+ const widthPt = pxToPoints(borderTop);
836
+ const inset = (widthPt / 72) / 2; // Convert points to inches, then half
837
+ borderLines.push({
838
+ type: 'line',
839
+ x1: x, y1: y + inset, x2: x + w, y2: y + inset,
840
+ width: widthPt,
841
+ color: rgbToHex(computed.borderTopColor)
842
+ });
843
+ }
844
+ if (parseFloat(borderRight) > 0) {
845
+ const widthPt = pxToPoints(borderRight);
846
+ const inset = (widthPt / 72) / 2;
847
+ borderLines.push({
848
+ type: 'line',
849
+ x1: x + w - inset, y1: y, x2: x + w - inset, y2: y + h,
850
+ width: widthPt,
851
+ color: rgbToHex(computed.borderRightColor)
852
+ });
853
+ }
854
+ if (parseFloat(borderBottom) > 0) {
855
+ const widthPt = pxToPoints(borderBottom);
856
+ const inset = (widthPt / 72) / 2;
857
+ borderLines.push({
858
+ type: 'line',
859
+ x1: x, y1: y + h - inset, x2: x + w, y2: y + h - inset,
860
+ width: widthPt,
861
+ color: rgbToHex(computed.borderBottomColor)
862
+ });
863
+ }
864
+ if (parseFloat(borderLeft) > 0) {
865
+ const widthPt = pxToPoints(borderLeft);
866
+ const inset = (widthPt / 72) / 2;
867
+ borderLines.push({
868
+ type: 'line',
869
+ x1: x + inset, y1: y, x2: x + inset, y2: y + h,
870
+ width: widthPt,
871
+ color: rgbToHex(computed.borderLeftColor)
872
+ });
873
+ }
874
+ }
875
+
876
+ if (hasBg || hasBorder) {
877
+ const rect = el.getBoundingClientRect();
878
+ if (rect.width > 0 && rect.height > 0) {
879
+ const shadow = parseBoxShadow(computed.boxShadow);
880
+
881
+ // Only add shape if there's background or uniform border
882
+ if (hasBg || hasUniformBorder) {
883
+ elements.push({
884
+ type: 'shape',
885
+ text: '', // Shape only - child text elements render on top
886
+ position: {
887
+ x: pxToInch(rect.left),
888
+ y: pxToInch(rect.top),
889
+ w: pxToInch(rect.width),
890
+ h: pxToInch(rect.height)
891
+ },
892
+ shape: {
893
+ fill: hasBg ? rgbToHex(computed.backgroundColor) : null,
894
+ transparency: hasBg ? extractAlpha(computed.backgroundColor) : null,
895
+ line: hasUniformBorder ? {
896
+ color: rgbToHex(computed.borderColor),
897
+ width: pxToPoints(computed.borderWidth)
898
+ } : null,
899
+ // Convert border-radius to rectRadius (in inches)
900
+ // % values: 50%+ = circle (1), <50% = percentage of min dimension
901
+ // pt values: divide by 72 (72pt = 1 inch)
902
+ // px values: divide by 96 (96px = 1 inch)
903
+ rectRadius: (() => {
904
+ const radius = computed.borderRadius;
905
+ const radiusValue = parseFloat(radius);
906
+ if (radiusValue === 0) return 0;
907
+
908
+ if (radius.includes('%')) {
909
+ if (radiusValue >= 50) return 1;
910
+ // Calculate percentage of smaller dimension
911
+ const minDim = Math.min(rect.width, rect.height);
912
+ return (radiusValue / 100) * pxToInch(minDim);
913
+ }
914
+
915
+ if (radius.includes('pt')) return radiusValue / 72;
916
+ return radiusValue / PX_PER_IN;
917
+ })(),
918
+ shadow: shadow
919
+ }
920
+ });
921
+ }
922
+
923
+ // Add partial border lines
924
+ elements.push(...borderLines);
925
+
926
+ processed.add(el);
927
+ return;
928
+ }
929
+ }
930
+ }
931
+
932
+ // Extract bullet lists as single text block
933
+ if (el.tagName === 'UL' || el.tagName === 'OL') {
934
+ const rect = el.getBoundingClientRect();
935
+ if (rect.width === 0 || rect.height === 0) return;
936
+
937
+ const liElements = Array.from(el.querySelectorAll('li'));
938
+ const items = [];
939
+ const ulComputed = window.getComputedStyle(el);
940
+ const ulPaddingLeftPt = pxToPoints(ulComputed.paddingLeft);
941
+
942
+ // Split: margin-left for bullet position, indent for text position
943
+ // margin-left + indent = ul padding-left
944
+ const marginLeft = ulPaddingLeftPt * 0.5;
945
+ const textIndent = ulPaddingLeftPt * 0.5;
946
+
947
+ liElements.forEach((li, idx) => {
948
+ const isLast = idx === liElements.length - 1;
949
+ const runs = parseInlineFormatting(li, { breakLine: false });
950
+ // Clean manual bullets from first run
951
+ if (runs.length > 0) {
952
+ runs[0].text = runs[0].text.replace(/^[•\-\*▪▸]\s*/, '');
953
+ runs[0].options.bullet = { indent: textIndent };
954
+ }
955
+ // Set breakLine on last run
956
+ if (runs.length > 0 && !isLast) {
957
+ runs[runs.length - 1].options.breakLine = true;
958
+ }
959
+ items.push(...runs);
960
+ });
961
+
962
+ const computed = window.getComputedStyle(liElements[0] || el);
963
+
964
+ elements.push({
965
+ type: 'list',
966
+ items: items,
967
+ position: {
968
+ x: pxToInch(rect.left),
969
+ y: pxToInch(rect.top),
970
+ w: pxToInch(rect.width),
971
+ h: pxToInch(rect.height)
972
+ },
973
+ style: {
974
+ fontSize: pxToPoints(computed.fontSize),
975
+ fontFace: computed.fontFamily.split(',')[0].replace(/['"]/g, '').trim(),
976
+ color: rgbToHex(computed.color),
977
+ transparency: extractAlpha(computed.color),
978
+ align: computed.textAlign === 'start' ? 'left' : computed.textAlign,
979
+ lineSpacing: computed.lineHeight && computed.lineHeight !== 'normal' ? pxToPoints(computed.lineHeight) : null,
980
+ paraSpaceBefore: 0,
981
+ paraSpaceAfter: pxToPoints(computed.marginBottom),
982
+ // PptxGenJS margin array is [left, right, bottom, top]
983
+ margin: [marginLeft, 0, 0, 0]
984
+ }
985
+ });
986
+
987
+ liElements.forEach(li => processed.add(li));
988
+ processed.add(el);
989
+ return;
990
+ }
991
+
992
+ // Extract text elements (P, H1, H2, etc.)
993
+ if (!textTags.includes(el.tagName)) return;
994
+
995
+ const rect = el.getBoundingClientRect();
996
+ const text = el.textContent.trim();
997
+ if (rect.width === 0 || rect.height === 0 || !text) return;
998
+
999
+ // Validate: Check for manual bullet symbols in text elements (not in lists)
1000
+ if (el.tagName !== 'LI' && /^[•\-\*▪▸○●◆◇■□]\s/.test(text.trimStart())) {
1001
+ errors.push(
1002
+ `Text element <${el.tagName.toLowerCase()}> starts with bullet symbol "${text.substring(0, 20)}...". ` +
1003
+ 'Use <ul> or <ol> lists instead of manual bullet symbols.'
1004
+ );
1005
+ return;
1006
+ }
1007
+
1008
+ const computed = window.getComputedStyle(el);
1009
+ const rotation = getRotation(computed.transform, computed.writingMode);
1010
+ const { x, y, w, h } = getPositionAndSize(el, rect, rotation);
1011
+
1012
+ const baseStyle = {
1013
+ fontSize: pxToPoints(computed.fontSize),
1014
+ fontFace: computed.fontFamily.split(',')[0].replace(/['"]/g, '').trim(),
1015
+ color: rgbToHex(computed.color),
1016
+ align: computed.textAlign === 'start' ? 'left' : computed.textAlign,
1017
+ lineSpacing: pxToPoints(computed.lineHeight),
1018
+ paraSpaceBefore: pxToPoints(computed.marginTop),
1019
+ paraSpaceAfter: pxToPoints(computed.marginBottom),
1020
+ // PptxGenJS margin array is [left, right, bottom, top] (not [top, right, bottom, left] as documented)
1021
+ margin: [
1022
+ pxToPoints(computed.paddingLeft),
1023
+ pxToPoints(computed.paddingRight),
1024
+ pxToPoints(computed.paddingBottom),
1025
+ pxToPoints(computed.paddingTop)
1026
+ ]
1027
+ };
1028
+
1029
+ const transparency = extractAlpha(computed.color);
1030
+ if (transparency !== null) baseStyle.transparency = transparency;
1031
+
1032
+ if (rotation !== null) baseStyle.rotate = rotation;
1033
+
1034
+ const hasFormatting = el.querySelector('b, i, u, strong, em, span, br');
1035
+
1036
+ if (hasFormatting) {
1037
+ // Text with inline formatting
1038
+ const transformStr = computed.textTransform;
1039
+ const runs = parseInlineFormatting(el, {}, [], (str) => applyTextTransform(str, transformStr));
1040
+
1041
+ // Adjust lineSpacing based on largest fontSize in runs
1042
+ const adjustedStyle = { ...baseStyle };
1043
+ if (adjustedStyle.lineSpacing) {
1044
+ const maxFontSize = Math.max(
1045
+ adjustedStyle.fontSize,
1046
+ ...runs.map(r => r.options?.fontSize || 0)
1047
+ );
1048
+ if (maxFontSize > adjustedStyle.fontSize) {
1049
+ const lineHeightMultiplier = adjustedStyle.lineSpacing / adjustedStyle.fontSize;
1050
+ adjustedStyle.lineSpacing = maxFontSize * lineHeightMultiplier;
1051
+ }
1052
+ }
1053
+
1054
+ elements.push({
1055
+ type: el.tagName.toLowerCase(),
1056
+ text: runs,
1057
+ position: { x: pxToInch(x), y: pxToInch(y), w: pxToInch(w), h: pxToInch(h) },
1058
+ style: adjustedStyle
1059
+ });
1060
+ } else {
1061
+ // Plain text - inherit CSS formatting
1062
+ const textTransform = computed.textTransform;
1063
+ const transformedText = applyTextTransform(text, textTransform);
1064
+
1065
+ const isBold = computed.fontWeight === 'bold' || parseInt(computed.fontWeight) >= 600;
1066
+
1067
+ elements.push({
1068
+ type: el.tagName.toLowerCase(),
1069
+ text: transformedText,
1070
+ position: { x: pxToInch(x), y: pxToInch(y), w: pxToInch(w), h: pxToInch(h) },
1071
+ style: {
1072
+ ...baseStyle,
1073
+ bold: isBold && !shouldSkipBold(computed.fontFamily),
1074
+ italic: computed.fontStyle === 'italic',
1075
+ underline: computed.textDecoration.includes('underline')
1076
+ }
1077
+ });
1078
+ }
1079
+
1080
+ processed.add(el);
1081
+ });
1082
+
1083
+ return { background, elements, placeholders, errors };
1084
+ });
1085
+ }
1086
+
1087
+ async function html2pptx(htmlFile, pres, options = {}) {
1088
+ const {
1089
+ tmpDir = process.env.TMPDIR || '/tmp',
1090
+ slide = null
1091
+ } = options;
1092
+
1093
+ try {
1094
+ const browser = await launchBrowser(tmpDir);
1095
+
1096
+ let bodyDimensions;
1097
+ let slideData;
1098
+
1099
+ const filePath = path.isAbsolute(htmlFile) ? htmlFile : path.join(process.cwd(), htmlFile);
1100
+ const validationErrors = [];
1101
+
1102
+ try {
1103
+ const page = await browser.newPage();
1104
+ page.on('console', (msg) => {
1105
+ // Log the message text to your test runner's console
1106
+ console.log(`Browser console: ${msg.text()}`);
1107
+ });
1108
+
1109
+ await page.goto(`file://${filePath}`);
1110
+ await waitForDynamicLibraryRender(page);
1111
+ await rasterizeDynamicVisuals(page);
1112
+
1113
+ bodyDimensions = await getBodyDimensions(page);
1114
+
1115
+ await page.setViewportSize({
1116
+ width: Math.round(bodyDimensions.width),
1117
+ height: Math.round(bodyDimensions.height)
1118
+ });
1119
+
1120
+ slideData = await extractSlideData(page);
1121
+ } finally {
1122
+ await browser.close();
1123
+ }
1124
+
1125
+ // Collect all validation errors
1126
+ if (bodyDimensions.errors && bodyDimensions.errors.length > 0) {
1127
+ validationErrors.push(...bodyDimensions.errors);
1128
+ }
1129
+
1130
+ const dimensionErrors = validateDimensions(bodyDimensions, pres);
1131
+ if (dimensionErrors.length > 0) {
1132
+ validationErrors.push(...dimensionErrors);
1133
+ }
1134
+
1135
+ const textBoxPositionErrors = validateTextBoxPosition(slideData, bodyDimensions);
1136
+ if (textBoxPositionErrors.length > 0) {
1137
+ validationErrors.push(...textBoxPositionErrors);
1138
+ }
1139
+
1140
+ if (slideData.errors && slideData.errors.length > 0) {
1141
+ validationErrors.push(...slideData.errors);
1142
+ }
1143
+
1144
+ // Throw all errors at once if any exist
1145
+ if (validationErrors.length > 0) {
1146
+ const errorMessage = validationErrors.length === 1
1147
+ ? validationErrors[0]
1148
+ : `Multiple validation errors found:\n${validationErrors.map((e, i) => ` ${i + 1}. ${e}`).join('\n')}`;
1149
+ throw new Error(errorMessage);
1150
+ }
1151
+
1152
+ const targetSlide = slide || pres.addSlide();
1153
+
1154
+ await addBackground(slideData, targetSlide, tmpDir);
1155
+ addElements(slideData, targetSlide, pres);
1156
+
1157
+ return { slide: targetSlide, placeholders: slideData.placeholders };
1158
+ } catch (error) {
1159
+ if (!error.message.startsWith(htmlFile)) {
1160
+ throw new Error(`${htmlFile}: ${error.message}`);
1161
+ }
1162
+ throw error;
1163
+ }
1164
+ }
1165
+
1166
+ module.exports = html2pptx;