// Export helpers: wikitext source as HTML for PDF and Word, and the Word (.docx) writer. 'use strict'; const HTMLtoDOCX = require('html-to-docx'); const PAPER = { Letter: { w: 12240, h: 15840 }, A4: { w: 11906, h: 16838 } }; function esc(s) { return String(s).replace(/&/g, '&').replace(//g, '>'); } // Full page for the PDF of the wikitext source. function markupPage(title, text) { return '' + esc(title) + '

' + esc(title) + '

' + esc(text.replace(/\r\n?/g, '\n')) + '
'; } // Body markup for Word: one paragraph per line so spacing and line breaks survive. function markupBody(title, text) { const lines = text.replace(/\r\n?/g, '\n').split('\n').map((l) => { const lead = /^ */.exec(l)[0].length; const body = ' '.repeat(lead) + esc(l.slice(lead)).replace(/\t/g, '    '); return '

' + (body || ' ') + '

'; }); return '

' + esc(title) + '

' + lines.join(''); } function wrapDoc(title, body) { return '' + esc(title) + '' + body + ''; } // The Word writer drops a lone space between two inline elements, so make those spaces non-breaking. function fixSpaces(html) { const inl = 'b|i|u|s|em|strong|span|a|code|sup|sub|small|big|cite|abbr|q|mark|del|ins'; const re = new RegExp('()\\s+(<(?:' + inl + '|img)[\\s>])', 'gi'); let prev; do { prev = html; html = html.replace(re, '$1 $2'); } while (html !== prev); return html; } async function toDocx(title, body, paper) { body = fixSpaces(body); const p = PAPER[paper] || PAPER.Letter; const opts = { title, pageSize: { width: p.w, height: p.h }, table: { row: { cantSplit: true } }, footer: false, pageNumber: false }; let out; try { out = await HTMLtoDOCX(wrapDoc(title, body), null, opts); } catch (e) { // Pictures that cannot be fetched can sink the whole file, so try again without them. out = await HTMLtoDOCX(wrapDoc(title, body.replace(/]*>/gi, '')), null, opts); } return Buffer.isBuffer(out) ? out : Buffer.from(await out.arrayBuffer ? await out.arrayBuffer() : out); } module.exports = { markupPage, markupBody, toDocx, fixSpaces, PAPER };