@hilvana/office 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/layout.js ADDED
@@ -0,0 +1,525 @@
1
+ import { rgb } from 'pdf-lib';
2
+ const color = (hex) => {
3
+ const n = parseInt(hex && /^[0-9a-f]{6}$/i.test(hex) ? hex : '000000', 16);
4
+ return rgb(((n >> 16) & 255) / 255, ((n >> 8) & 255) / 255, (n & 255) / 255);
5
+ };
6
+ export class LayoutEngine {
7
+ doc;
8
+ fonts;
9
+ model;
10
+ images = new Map();
11
+ warnings = new Set();
12
+ constructor(doc, fonts, model) {
13
+ this.doc = doc;
14
+ this.fonts = fonts;
15
+ this.model = model;
16
+ }
17
+ /* --------------------------------------------- preparation (async) */
18
+ async prepare() {
19
+ const uses = [];
20
+ const imgs = [];
21
+ const visit = (blocks) => {
22
+ for (const b of blocks ?? []) {
23
+ if (b.type === 'paragraph') {
24
+ if (b.label)
25
+ uses.push({ style: b.label.style, text: b.label.text });
26
+ for (const i of b.inlines) {
27
+ if (i.kind === 'text')
28
+ uses.push({ style: i.style, text: i.text.includes('\u0001') ? '0123456789' : i.text });
29
+ else if (i.kind === 'image')
30
+ imgs.push(i);
31
+ else
32
+ uses.push({ style: i.style, text: ' ' });
33
+ }
34
+ }
35
+ else if (b.type === 'table') {
36
+ for (const r of b.rows)
37
+ for (const c of r.cells)
38
+ visit(c.blocks);
39
+ }
40
+ }
41
+ };
42
+ visit(this.model.blocks);
43
+ visit(this.model.header);
44
+ visit(this.model.footer);
45
+ await this.fonts.prepare(uses);
46
+ for (const img of imgs) {
47
+ if (this.images.has(img.bytes))
48
+ continue;
49
+ try {
50
+ this.images.set(img.bytes, img.format === 'png' ? await this.doc.embedPng(img.bytes) : await this.doc.embedJpg(img.bytes));
51
+ }
52
+ catch {
53
+ this.warnings.add('UNSUPPORTED_IMAGE_FORMAT');
54
+ }
55
+ }
56
+ }
57
+ /* --------------------------------------------- paragraphs */
58
+ textAtoms(text, style, out) {
59
+ const size = style.vertAlign ? style.size * 0.65 : style.size;
60
+ for (const token of text.split(/(\s+)/)) {
61
+ if (!token)
62
+ continue;
63
+ const space = /^\s+$/.test(token);
64
+ const t = space ? token.replace(/[\t\n\r]/g, ' ') : token;
65
+ const segs = this.fonts.segment(t, style);
66
+ const width = segs.reduce((w, s) => w + s.font.widthOfTextAtSize(s.text, size), 0);
67
+ out.push({ t: 'text', segs, style, size, width, space });
68
+ }
69
+ }
70
+ atoms(p, fields) {
71
+ const out = [];
72
+ for (const i of p.inlines) {
73
+ if (i.kind === 'text') {
74
+ let text = i.text;
75
+ if (text.includes('\u0001')) {
76
+ text = text.replace(/\u0001(PAGE|NUMPAGES)\u0001/g, (_, f) => {
77
+ const v = f === 'PAGE' ? fields.page : fields.total;
78
+ if (v === undefined)
79
+ this.warnings.add('PAGE_FIELD_IN_BODY');
80
+ return v === undefined ? '' : String(v);
81
+ });
82
+ }
83
+ this.textAtoms(text, i.style, out);
84
+ }
85
+ else if (i.kind === 'tab')
86
+ out.push({ t: 'tab', style: i.style });
87
+ else if (i.kind === 'break')
88
+ out.push({ t: 'break', page: i.style.size === -1, style: i.style });
89
+ else if (this.images.has(i.bytes))
90
+ out.push({ t: 'image', image: i, width: i.width, height: i.height });
91
+ }
92
+ return out;
93
+ }
94
+ lineMetrics(line, p, fallback) {
95
+ let ascent = 0, descent = 0, gap = 0;
96
+ const consider = (style) => {
97
+ const m = this.fonts.metrics(style);
98
+ ascent = Math.max(ascent, m.ascent * style.size);
99
+ descent = Math.max(descent, m.descent * style.size);
100
+ gap = Math.max(gap, m.lineGap * style.size);
101
+ };
102
+ for (const it of line.items) {
103
+ if (it.kind === 'text')
104
+ consider(it.style);
105
+ else
106
+ ascent = Math.max(ascent, it.height);
107
+ }
108
+ // The list label never makes the line taller (Word sizes the line from the text).
109
+ if (ascent === 0)
110
+ consider(line.label && !line.items.length ? line.label.style : fallback);
111
+ const natural = ascent + descent + gap;
112
+ const rule = p.style.line;
113
+ let height;
114
+ let baseline;
115
+ if (rule.rule === 'auto') {
116
+ height = natural * rule.value;
117
+ baseline = ascent + (height - natural);
118
+ }
119
+ else if (rule.rule === 'exact') {
120
+ height = rule.value;
121
+ baseline = Math.max(0, height - descent - gap);
122
+ }
123
+ else {
124
+ height = Math.max(rule.value, natural);
125
+ baseline = height - descent - gap;
126
+ }
127
+ Object.assign(line, { ascent, descent, gap, height, baseline });
128
+ }
129
+ layoutParagraph(p, width, fields) {
130
+ const s = p.style;
131
+ const atoms = this.atoms(p, fields);
132
+ const fallback = p.inlines.find((i) => i.kind === 'text')?.style
133
+ ?? p.label?.style ?? { font: 'Calibri', size: 11, bold: false, italic: false, underline: false, strike: false, color: '000000', caps: false };
134
+ const lines = [];
135
+ const tab = this.model.defaultTab || 36;
136
+ const newLine = (first) => {
137
+ const start = first ? s.indentLeft + s.firstLine : s.indentLeft;
138
+ const avail = Math.max(10, width - s.indentRight - start);
139
+ return { items: [], width: 0, start, avail, ascent: 0, descent: 0, gap: 0, height: 0, baseline: 0, forcedEnd: false, pageBreakAfter: false };
140
+ };
141
+ let line = newLine(true);
142
+ if (p.label) {
143
+ // The label sits at the hanging position; text starts at the left indent (or after the label).
144
+ const segs = this.fonts.segment(p.label.text, p.label.style);
145
+ const lw = segs.reduce((w, sg) => w + sg.font.widthOfTextAtSize(sg.text, p.label.style.size), 0);
146
+ line.label = { segs, style: p.label.style, x: 0 };
147
+ const textStart = Math.max(s.indentLeft, line.start + lw + 3);
148
+ const offset = textStart - line.start;
149
+ line.width = offset;
150
+ }
151
+ let pendingSpaces = [];
152
+ const finish = (forced, pageBreak = false) => {
153
+ // Trailing spaces never count toward the line width.
154
+ while (line.items.length && line.items[line.items.length - 1].kind === 'text' && line.items[line.items.length - 1].space) {
155
+ const sp = line.items.pop();
156
+ line.width -= sp.width;
157
+ }
158
+ line.forcedEnd = forced;
159
+ line.pageBreakAfter = pageBreak;
160
+ this.lineMetrics(line, p, fallback);
161
+ lines.push(line);
162
+ line = newLine(false);
163
+ pendingSpaces = [];
164
+ };
165
+ const place = (a) => {
166
+ if (a.t === 'text') {
167
+ line.items.push({ kind: 'text', segs: a.segs, style: a.style, size: a.size, x: line.width, width: a.width, space: a.space });
168
+ line.width += a.width;
169
+ }
170
+ else if (a.t === 'image') {
171
+ line.items.push({ kind: 'image', image: a.image, x: line.width, width: a.width, height: a.height });
172
+ line.width += a.width;
173
+ }
174
+ };
175
+ // Group atoms into words (consecutive non-space text or images) separated by spaces, tabs and breaks.
176
+ let i = 0;
177
+ while (i < atoms.length) {
178
+ const a = atoms[i];
179
+ if (a.t === 'break') {
180
+ finish(true, a.page);
181
+ i++;
182
+ continue;
183
+ }
184
+ if (a.t === 'tab') {
185
+ const pos = line.start + line.width;
186
+ const next = (Math.floor((pos - s.indentLeft) / tab + 1e-6) + 1) * tab + s.indentLeft;
187
+ const w = Math.max(next - pos, 2);
188
+ if (line.width + w > line.avail && line.items.length)
189
+ finish(false);
190
+ line.items.push({ kind: 'text', segs: [], style: a.style, size: a.style.size, x: line.width, width: w, space: false });
191
+ line.width += w;
192
+ pendingSpaces = [];
193
+ i++;
194
+ continue;
195
+ }
196
+ if (a.t === 'text' && a.space) {
197
+ pendingSpaces.push(a);
198
+ i++;
199
+ continue;
200
+ }
201
+ const word = [];
202
+ while (i < atoms.length) {
203
+ const b = atoms[i];
204
+ if ((b.t === 'text' && !b.space) || b.t === 'image') {
205
+ word.push(b);
206
+ i++;
207
+ }
208
+ else
209
+ break;
210
+ }
211
+ // Images wider than the column are scaled down to fit.
212
+ for (const w of word) {
213
+ if (w.t === 'image' && w.width > line.avail) {
214
+ const k = line.avail / w.width;
215
+ w.width *= k;
216
+ w.height *= k;
217
+ }
218
+ }
219
+ const spaceW = pendingSpaces.reduce((acc, sp) => acc + sp.width, 0);
220
+ const wordW = word.reduce((acc, w) => acc + w.width, 0);
221
+ if (line.items.length > 0 && line.width + spaceW + wordW > line.avail) {
222
+ finish(false);
223
+ }
224
+ else {
225
+ pendingSpaces.forEach(place);
226
+ }
227
+ pendingSpaces = [];
228
+ if (wordW > line.avail && word.length) {
229
+ // A single word longer than the line: break it by characters.
230
+ for (const w of word) {
231
+ if (w.t !== 'text') {
232
+ const ww = w.t === 'image' ? w.width : 0;
233
+ if (line.width + ww > line.avail && line.items.length)
234
+ finish(false);
235
+ place(w);
236
+ continue;
237
+ }
238
+ for (const seg of w.segs) {
239
+ for (const ch of seg.text) {
240
+ const cw = seg.font.widthOfTextAtSize(ch, w.size);
241
+ if (line.width + cw > line.avail && line.items.length)
242
+ finish(false);
243
+ place({ ...w, segs: [{ text: ch, font: seg.font }], width: cw });
244
+ }
245
+ }
246
+ }
247
+ }
248
+ else
249
+ word.forEach(place);
250
+ }
251
+ finish(true);
252
+ return lines;
253
+ }
254
+ drawLine(page, line, p, x0, top, width) {
255
+ const s = p.style;
256
+ let offset = 0;
257
+ let extraPerSpace = 0;
258
+ const free = line.avail - line.width;
259
+ if (s.align === 'center')
260
+ offset = free / 2;
261
+ else if (s.align === 'right')
262
+ offset = free;
263
+ else if (s.align === 'justify' && !line.forcedEnd) {
264
+ const spaces = line.items.filter((it) => it.kind === 'text' && it.space).length;
265
+ if (spaces > 0 && free > 0)
266
+ extraPerSpace = free / spaces;
267
+ }
268
+ if (s.shading)
269
+ page.drawRectangle({ x: x0 + s.indentLeft, y: top - line.height, width: width - s.indentLeft - s.indentRight, height: line.height, color: color(s.shading) });
270
+ const baseY = top - line.baseline;
271
+ if (line.label) {
272
+ let lx = x0 + line.start;
273
+ for (const sg of line.label.segs) {
274
+ page.drawText(sg.text, { x: lx, y: baseY, size: line.label.style.size, font: sg.font, color: color(line.label.style.color) });
275
+ lx += sg.font.widthOfTextAtSize(sg.text, line.label.style.size);
276
+ }
277
+ }
278
+ let shift = 0;
279
+ for (const it of line.items) {
280
+ const x = x0 + line.start + offset + it.x + shift;
281
+ if (it.kind === 'image') {
282
+ const img = this.images.get(it.image.bytes);
283
+ if (img)
284
+ page.drawImage(img, { x, y: baseY, width: it.width, height: it.height });
285
+ continue;
286
+ }
287
+ const w = it.width + (it.space ? extraPerSpace : 0);
288
+ if (it.space)
289
+ shift += extraPerSpace;
290
+ const st = it.style;
291
+ const rise = st.vertAlign === 'superscript' ? st.size * 0.33 : st.vertAlign === 'subscript' ? -st.size * 0.14 : 0;
292
+ if (st.highlight) {
293
+ const m = this.fonts.metrics(st);
294
+ page.drawRectangle({ x, y: baseY - m.descent * st.size, width: w, height: (m.ascent + m.descent) * st.size, color: color(st.highlight) });
295
+ }
296
+ let tx = x;
297
+ if (!it.space) {
298
+ for (const sg of it.segs) {
299
+ if (sg.text)
300
+ page.drawText(sg.text, { x: tx, y: baseY + rise, size: it.size, font: sg.font, color: color(st.color) });
301
+ tx += sg.font.widthOfTextAtSize(sg.text, it.size);
302
+ }
303
+ }
304
+ if (st.underline && it.width > 0)
305
+ page.drawLine({ start: { x, y: baseY - st.size * 0.12 }, end: { x: x + w, y: baseY - st.size * 0.12 }, thickness: Math.max(0.5, st.size * 0.05), color: color(st.color) });
306
+ if (st.strike && it.width > 0)
307
+ page.drawLine({ start: { x, y: baseY + st.size * 0.28 }, end: { x: x + w, y: baseY + st.size * 0.28 }, thickness: Math.max(0.5, st.size * 0.05), color: color(st.color) });
308
+ }
309
+ }
310
+ paragraphSlices(p, width, fields, prev, next) {
311
+ const s = p.style;
312
+ const lines = this.layoutParagraph(p, width, fields);
313
+ const slices = [];
314
+ // "Don't add space between paragraphs of the same style" applies on both sides.
315
+ const sameStyleAsPrev = s.contextualSpacing && prev?.type === 'paragraph' && prev.style.styleId === s.styleId;
316
+ const sameStyleAsNext = s.contextualSpacing && next?.type === 'paragraph' && next.style.styleId === s.styleId;
317
+ if (s.spaceBefore > 0 && !sameStyleAsPrev)
318
+ slices.push({ height: s.spaceBefore, draw: () => { }, spacer: true });
319
+ lines.forEach((line, idx) => {
320
+ slices.push({
321
+ height: line.height,
322
+ draw: (page, x, top) => this.drawLine(page, line, p, x, top, width),
323
+ breakBefore: idx === 0 && s.pageBreakBefore,
324
+ keepWithNext: s.keepNext || idx < lines.length - 1 && lines.length <= 3,
325
+ });
326
+ if (line.pageBreakAfter)
327
+ slices.push({ height: 0, draw: () => { }, breakBefore: false, spacer: false, keepWithNext: false, ...{ pageBreak: true } });
328
+ });
329
+ if (s.borderBottom) {
330
+ const bb = s.borderBottom;
331
+ slices.push({ height: bb.width + 2, draw: (page, x, top) => page.drawLine({ start: { x: x + s.indentLeft, y: top - 1 }, end: { x: x + width - s.indentRight, y: top - 1 }, thickness: bb.width, color: color(bb.color) }) });
332
+ }
333
+ if (s.spaceAfter > 0 && !sameStyleAsNext)
334
+ slices.push({ height: s.spaceAfter, draw: () => { }, spacer: true });
335
+ return slices;
336
+ }
337
+ /* --------------------------------------------- tables */
338
+ tableSlices(t, width, fields) {
339
+ let cols = t.columns.length ? [...t.columns] : [];
340
+ const gridCount = Math.max(cols.length, ...t.rows.map((r) => r.cells.reduce((n, c) => n + c.span, 0)));
341
+ if (cols.length < gridCount) {
342
+ const rest = Math.max(0, width - cols.reduce((a, b) => a + b, 0));
343
+ const add = gridCount - cols.length;
344
+ cols = [...cols, ...Array(add).fill(rest / add || width / gridCount)];
345
+ }
346
+ const total = cols.reduce((a, b) => a + b, 0) || width;
347
+ const avail = width - t.indent;
348
+ if (total > avail)
349
+ cols = cols.map((c) => (c * avail) / total);
350
+ const xs = cols.reduce((acc, c) => [...acc, acc[acc.length - 1] + c], [0]);
351
+ const pad = t.cellPadding;
352
+ return t.rows.map((row, rowIndex) => {
353
+ let gi = 0;
354
+ const cells = row.cells.map((cell) => {
355
+ const x = xs[gi] ?? 0;
356
+ const w = (xs[Math.min(gi + cell.span, xs.length - 1)] ?? width) - x;
357
+ gi += cell.span;
358
+ const content = cell.vMerge === 'continue' ? [] : this.measureBlocks(cell.blocks, Math.max(10, w - pad.left - pad.right), fields);
359
+ const h = content.reduce((a, s) => a + s.height, 0);
360
+ return { cell, x, w, content, h, gridIndex: gi - cell.span };
361
+ });
362
+ const height = Math.max(row.minHeight, ...cells.map((c) => c.h + pad.top + pad.bottom), 6);
363
+ const next = t.rows[rowIndex + 1];
364
+ return {
365
+ height,
366
+ header: row.header,
367
+ keepWithNext: row.header,
368
+ draw: (page, x0, top) => {
369
+ const left = x0 + t.indent;
370
+ for (const c of cells) {
371
+ if (c.cell.shading)
372
+ page.drawRectangle({ x: left + c.x, y: top - height, width: c.w, height, color: color(c.cell.shading) });
373
+ }
374
+ for (const c of cells) {
375
+ let y = top - pad.top;
376
+ if (c.cell.vAlign === 'center')
377
+ y -= (height - pad.top - pad.bottom - c.h) / 2;
378
+ else if (c.cell.vAlign === 'bottom')
379
+ y -= height - pad.top - pad.bottom - c.h;
380
+ for (const s of c.content) {
381
+ s.draw(page, left + c.x + pad.left, y);
382
+ y -= s.height;
383
+ }
384
+ }
385
+ const tableEdge = t.borders ? { width: 0.5, color: t.borderColor } : null;
386
+ for (const c of cells) {
387
+ const xL = left + c.x;
388
+ const xR = xL + c.w;
389
+ const continuesBelow = !!next?.cells.find((n, idx) => {
390
+ let g = 0;
391
+ for (let k = 0; k < idx; k++)
392
+ g += next.cells[k].span;
393
+ return g === c.gridIndex && n.vMerge === 'continue';
394
+ });
395
+ // A side drawn on the cell wins; otherwise the table's borders apply.
396
+ const side = (k) => {
397
+ const own = c.cell.borders?.[k];
398
+ return own === undefined ? tableEdge : own;
399
+ };
400
+ const line = (b, x1, y1, x2, y2) => {
401
+ if (b)
402
+ page.drawLine({ start: { x: x1, y: y1 }, end: { x: x2, y: y2 }, thickness: b.width, color: color(b.color) });
403
+ };
404
+ if (c.cell.vMerge !== 'continue')
405
+ line(side('top'), xL, top, xR, top);
406
+ if (!continuesBelow)
407
+ line(side('bottom'), xL, top - height, xR, top - height);
408
+ line(side('left'), xL, top, xL, top - height);
409
+ line(side('right'), xR, top, xR, top - height);
410
+ }
411
+ },
412
+ };
413
+ }).map((slice, i, all) => {
414
+ // Rows marked as header repeat at the top of each page the table continues on.
415
+ if (!slice.header) {
416
+ const headers = all.slice(0, all.findIndex((x) => !x.header));
417
+ if (headers.length && i >= headers.length)
418
+ return { ...slice, repeat: headers };
419
+ }
420
+ return slice;
421
+ });
422
+ }
423
+ /* --------------------------------------------- blocks and pages */
424
+ measureBlocks(blocks, width, fields = {}) {
425
+ const out = [];
426
+ let prev;
427
+ blocks.forEach((b, idx) => {
428
+ if (b.type === 'paragraph')
429
+ out.push(...this.paragraphSlices(b, width, fields, prev, blocks[idx + 1]));
430
+ else if (b.type === 'table') {
431
+ // Space between a table and the next paragraph comes from that paragraph.
432
+ out.push(...this.tableSlices(b, width, fields));
433
+ }
434
+ else
435
+ out.push({ height: 0, draw: () => { }, ...{ pageBreak: true } });
436
+ prev = b;
437
+ });
438
+ return out;
439
+ }
440
+ /** Lays out the whole document into new pages of `doc` and returns the page count. */
441
+ render() {
442
+ const pages = [];
443
+ for (const section of this.model.sections) {
444
+ const setup = section.page;
445
+ const contentWidth = setup.width - setup.margin.left - setup.margin.right;
446
+ const top = setup.height - setup.margin.top;
447
+ const bottom = setup.margin.bottom;
448
+ const slices = this.measureBlocks(section.blocks, contentWidth);
449
+ let page = this.doc.addPage([setup.width, setup.height]);
450
+ pages.push({ page, setup });
451
+ let y = top;
452
+ const atTop = () => y === top;
453
+ const newPage = () => {
454
+ page = this.doc.addPage([setup.width, setup.height]);
455
+ pages.push({ page, setup });
456
+ y = top;
457
+ };
458
+ const drawSlice = (s) => {
459
+ if (s.height > top - bottom)
460
+ this.warnings.add('CONTENT_TALLER_THAN_PAGE');
461
+ s.draw(page, setup.margin.left, y);
462
+ y -= s.height;
463
+ };
464
+ for (let k = 0; k < slices.length; k++) {
465
+ const s = slices[k];
466
+ if (s.pageBreak) {
467
+ if (!atTop())
468
+ newPage();
469
+ continue;
470
+ }
471
+ if (s.breakBefore && !atTop())
472
+ newPage();
473
+ if (s.spacer && atTop())
474
+ continue;
475
+ let broke = false;
476
+ // Keep headings (and short paragraphs) with what follows when it would not fit.
477
+ if (s.keepWithNext && !atTop()) {
478
+ let need = s.height;
479
+ for (let j = k + 1; j < slices.length && j < k + 6; j++) {
480
+ const n = slices[j];
481
+ need += n.height;
482
+ if (!n.spacer && !n.keepWithNext)
483
+ break;
484
+ }
485
+ if (y - need < bottom && need < top - bottom) {
486
+ newPage();
487
+ broke = true;
488
+ }
489
+ }
490
+ if (y - s.height < bottom - 0.01 && !atTop()) {
491
+ newPage();
492
+ broke = true;
493
+ if (s.spacer)
494
+ continue;
495
+ }
496
+ if (broke && s.repeat)
497
+ s.repeat.forEach(drawSlice);
498
+ drawSlice(s);
499
+ }
500
+ }
501
+ // Headers and footers, now that the page count is known.
502
+ const total = pages.length;
503
+ pages.forEach(({ page: pg, setup }, idx) => {
504
+ const contentWidth = setup.width - setup.margin.left - setup.margin.right;
505
+ const fields = { page: idx + 1, total };
506
+ if (this.model.header) {
507
+ let hy = setup.height - this.model.headerDistance;
508
+ for (const s of this.measureBlocks(this.model.header, contentWidth, fields)) {
509
+ s.draw(pg, setup.margin.left, hy);
510
+ hy -= s.height;
511
+ }
512
+ }
513
+ if (this.model.footer) {
514
+ const fs = this.measureBlocks(this.model.footer, contentWidth, fields).filter((s, i, arr) => !(s.spacer && i === arr.length - 1));
515
+ let fy = this.model.footerDistance + fs.reduce((a, s) => a + s.height, 0);
516
+ for (const s of fs) {
517
+ s.draw(pg, setup.margin.left, fy);
518
+ fy -= s.height;
519
+ }
520
+ }
521
+ });
522
+ return total;
523
+ }
524
+ }
525
+ //# sourceMappingURL=layout.js.map
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Optional high-fidelity engine: uses a LibreOffice installation on the same machine.
3
+ * Still fully local (no network). Node only; import lazily.
4
+ */
5
+ /** Finds the LibreOffice binary: HILVANA_SOFFICE, then the usual install locations, then PATH. */
6
+ export declare function findLibreOffice(): Promise<string | undefined>;
7
+ /** Converts .docx bytes to PDF with LibreOffice in a private temporary profile and folder. */
8
+ export declare function libreOfficeToPdf(docx: Uint8Array, opts?: {
9
+ timeoutMs?: number;
10
+ }): Promise<Uint8Array>;
11
+ //# sourceMappingURL=libreoffice.d.ts.map
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Optional high-fidelity engine: uses a LibreOffice installation on the same machine.
3
+ * Still fully local (no network). Node only; import lazily.
4
+ */
5
+ const CANDIDATES = {
6
+ win32: [
7
+ 'C:\\Program Files\\LibreOffice\\program\\soffice.exe',
8
+ 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe',
9
+ ],
10
+ darwin: ['/Applications/LibreOffice.app/Contents/MacOS/soffice'],
11
+ linux: ['/usr/bin/soffice', '/usr/bin/libreoffice', '/usr/lib/libreoffice/program/soffice', '/snap/bin/libreoffice', '/opt/libreoffice/program/soffice'],
12
+ };
13
+ let cached;
14
+ /** Finds the LibreOffice binary: HILVANA_SOFFICE, then the usual install locations, then PATH. */
15
+ export function findLibreOffice() {
16
+ cached ??= (async () => {
17
+ const { access } = await import('node:fs/promises');
18
+ const { constants } = await import('node:fs');
19
+ const path = await import('node:path');
20
+ const exists = async (p) => access(p, constants.X_OK).then(() => true, () => false);
21
+ const fromEnv = process.env.HILVANA_SOFFICE;
22
+ if (fromEnv)
23
+ return (await exists(fromEnv)) ? fromEnv : undefined;
24
+ for (const c of CANDIDATES[process.platform] ?? [])
25
+ if (await exists(c))
26
+ return c;
27
+ const names = process.platform === 'win32' ? ['soffice.exe'] : ['soffice', 'libreoffice'];
28
+ for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
29
+ for (const n of names) {
30
+ const full = path.join(dir, n);
31
+ if (dir && (await exists(full)))
32
+ return full;
33
+ }
34
+ }
35
+ return undefined;
36
+ })();
37
+ return cached;
38
+ }
39
+ /** Converts .docx bytes to PDF with LibreOffice in a private temporary profile and folder. */
40
+ export async function libreOfficeToPdf(docx, opts = {}) {
41
+ const soffice = await findLibreOffice();
42
+ if (!soffice)
43
+ throw new Error('LIBREOFFICE_NOT_FOUND');
44
+ const { mkdtemp, writeFile, readFile, rm } = await import('node:fs/promises');
45
+ const os = await import('node:os');
46
+ const path = await import('node:path');
47
+ const { pathToFileURL } = await import('node:url');
48
+ const { execFile } = await import('node:child_process');
49
+ const dir = await mkdtemp(path.join(os.tmpdir(), 'hilvana-lo-'));
50
+ try {
51
+ const input = path.join(dir, 'input.docx');
52
+ await writeFile(input, docx);
53
+ const profile = pathToFileURL(path.join(dir, 'profile')).href;
54
+ await new Promise((resolve, reject) => {
55
+ execFile(soffice, [`-env:UserInstallation=${profile}`, '--headless', '--norestore', '--convert-to', 'pdf', '--outdir', dir, input], { timeout: opts.timeoutMs ?? 90_000, env: { ...process.env, SAL_USE_VCLPLUGIN: process.env.SAL_USE_VCLPLUGIN ?? 'svp' } }, (err) => (err ? reject(new Error(`LIBREOFFICE_FAILED: ${err.message.slice(0, 200)}`)) : resolve()));
56
+ });
57
+ return new Uint8Array(await readFile(path.join(dir, 'input.pdf')));
58
+ }
59
+ finally {
60
+ await rm(dir, { recursive: true, force: true });
61
+ }
62
+ }
63
+ //# sourceMappingURL=libreoffice.js.map