-
Notifications
You must be signed in to change notification settings - Fork 167
/
Copy pathindex.js
executable file
·1000 lines (869 loc) · 23.1 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import fs from 'node:fs';
import stream from 'node:stream';
import path from 'node:path';
import { randomUUID as uuid } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import pup from 'puppeteer';
import archiver from 'archiver';
import fetch from 'node-fetch';
import { JSDOM } from 'jsdom';
import validateNames from 'jsdom/lib/jsdom/living/helpers/validate-names.js';
import nunjucks from 'nunjucks';
import css from 'css';
import { Readability } from '@mozilla/readability';
import createDOMPurify from 'dompurify';
import MimeType from 'whatwg-mimetype';
/*
Markdown functions
*/
import { fromDom } from 'hast-util-from-dom';
import { toMdast } from 'hast-util-to-mdast';
import { gfmToMarkdown } from 'mdast-util-gfm';
import { toMarkdown } from 'mdast-util-to-markdown';
import {
AVAILABLE_MARKDOWN_OPTIONS,
DEFAULT_MARKDOWN_OPTIONS
} from './src/constants/markdown.js';
import slurp from './src/util/slurp.js';
import { lookupMimetype } from './src/util/file-mimetype.js';
import epubDate from './src/util/epub-date.js';
import humanDate from './src/util/human-date.js';
import outputPath from './src/util/output-path.js';
import getCssPageFormat from './src/util/get-css-page-format.js';
import { resolveSequence, resolveParallel } from './src/util/promises.js';
import { getUrlOrigin } from './src/util/url-origin.js';
import addExif from './src/exif.js';
import { hyphenateDom } from './src/hyphenate.js';
import { textToIso6391, getLanguageAttribute } from './src/util/language.js';
import { setIdsAndReturnHeadings, nestHeadings } from './src/headings.js';
import {
ampToHtml,
fixLazyLoadedImages,
imagesAtFullSize,
wikipediaSpecific,
noUselessHref,
relativeToAbsoluteURIs,
singleImgToFigure,
expandDetailsElements,
githubSpecific,
wrapPreBlocks
} from './src/enhancements.js';
import mapRemoteResources from './src/remote-resources.js';
import inlineImages from './src/inline-images.js';
import get_style_attribute_value from './src/get-style-attribute-value.js';
const out = process.stdout;
const err = process.stderr;
const { readFile, writeFile } = fs.promises;
const pkg = JSON.parse(
fs.readFileSync(new URL('./package.json', import.meta.url))
);
let UA = `percollate/${pkg.version}`;
const JUSTIFY_CSS = `
.article__content p {
text-align: justify;
}
`;
const enhancePage = function (dom) {
// Note: the order of the enhancements matters!
[
ampToHtml,
fixLazyLoadedImages,
relativeToAbsoluteURIs,
imagesAtFullSize,
singleImgToFigure,
noUselessHref,
expandDetailsElements,
wikipediaSpecific,
githubSpecific,
wrapPreBlocks
].forEach(enhancement => {
enhancement(dom.window.document);
});
};
/*
Some setup
----------
*/
let configured = false;
function configure() {
if (!configured) {
nunjucks.configure({ autoescape: false, noCache: true });
configured = true;
}
}
function launch(options, size) {
/*
Produce tagged PDFs, better for accessibility;
Hopefully will also produce an Outline (ToC) eventually.
See: https://github.com/danburzo/percollate/issues/47
*/
let args = ['--export-tagged-pdf'];
/*
Allow running with no sandbox
See: https://github.com/danburzo/percollate/issues/26
*/
if (options.sandbox === false) {
args = args.concat(['--no-sandbox', '--disable-setuid-sandbox']);
}
return pup.launch({
headless: 'new',
product: options.browser || 'chrome',
args,
defaultViewport: {
// Emulate retina display (@2x)...
deviceScaleFactor: 2,
// ...but then we need to provide the other
// viewport parameters as well
width: 1920,
height: 1080,
...size
}
});
}
/*
Fetch a web page and clean the HTML
-----------------------------------
*/
function isURL(ref) {
try {
new URL(ref);
return true;
} catch (err) {
// no-op
}
return false;
}
async function fetchContent(ref, fetchOptions = {}) {
if (ref instanceof stream.Readable) {
return {
buffer: await slurp(ref),
contentType: undefined
};
}
let url;
try {
url = new URL(ref);
} catch (err) {
// no-op
}
if (!url) {
return {
buffer: await readFile(ref),
contentType: lookupMimetype(ref)
};
}
if (url && url.protocol === 'file:') {
url = decodeURI(url.href.replace(/^file:\/\//, ''));
return {
buffer: await readFile(url),
contentType: lookupMimetype(url)
};
}
/*
Must ensure that the URL is properly encoded.
See: https://github.com/danburzo/percollate/pull/83
*/
return fetch(url.href, {
...fetchOptions,
headers: {
...fetchOptions.headers,
'user-agent': UA
}
}).then(async response => {
let contentType = response.headers.get('Content-Type');
let mt = new MimeType(contentType);
if (!mt.isHTML() && !mt.isXML()) {
throw new Error(
`URL ${url.href} has unsupported content type: ${contentType}`
);
}
return {
buffer: await response.arrayBuffer(),
contentType
};
});
}
async function cleanup(url, options) {
if (!url) {
return null;
}
try {
err.write(`Fetching: ${url}`);
const { buffer, contentType } = await fetchContent(
url === '-' ? process.stdin : url,
options.fetch || {}
);
err.write(' ✓\n');
const final_url =
options.preferred_url !== undefined
? options.preferred_url
: url === '-'
? undefined
: isURL(url)
? url
: 'file://' + path.resolve(url);
/*
Disable some validations in JSDOM to allow
some invalid HTML files to be processed correctly.
Currently done via monkey-patching. See:
https://github.com/danburzo/percollate/issues/177
*/
if (options.unsafe) {
// make no-op
validateNames.name = () => {};
}
const dom = new JSDOM(buffer, {
contentType,
url: final_url
});
// Force relative URL resolution
dom.window.document.body.setAttribute(null, null);
const sanitizer = createDOMPurify(dom.window);
const amp = dom.window.document.querySelector('link[rel~=amphtml]');
if (amp && options.amp) {
err.write('\nFound AMP version (use `--no-amp` to ignore)\n');
return cleanup(amp.href, options, amp.href);
}
err.write(`Enhancing web page: ${url}`);
/*
Run enhancements
----------------
*/
enhancePage(dom);
// Run through readability and return
const R = new Readability(dom.window.document, {
classesToPreserve: [
'no-href',
/*
Placed on some <a> elements
as in-page anchors
*/
'anchor'
],
/*
Change Readability's serialization to return
a DOM element (instead of a HTML string)
as the `.content` property returned from `.parse()`
This makes it easier for us to run subsequent
transformations (sanitization, hyphenation, etc.)
without having to parse/serialize the HTML repeatedly.
*/
serializer: el => el
});
// TODO: find better solution to prevent Readability from
// making img srcs relative.
if (options.mapRemoteResources || options.inline) {
R._fixRelativeUris = () => {};
}
const parsed = R.parse() || {};
let remoteResources;
if (options.mapRemoteResources) {
remoteResources = mapRemoteResources(parsed.content);
}
// Hyphenate the text
const textContent = sanitizer.sanitize(parsed.textContent);
const lang =
getLanguageAttribute(dom.window.document) ||
textToIso6391(textContent);
err.write(' ✓\n');
if (options.inline) {
await inlineImages(
parsed.content,
{
headers: {
'user-agent': UA
},
/*
Send the referrer as the browser would
when fetching the image to render it.
The referrer policy would take care of
stripping the URL down to its origin,
but just in case, let’s strip it ourselves.
*/
referrer: getUrlOrigin(final_url),
referrerPolicy: 'strict-origin-when-cross-origin',
timeout: 10 * 1000
},
options.debug ? out : undefined
);
}
/*
Select the appropriate serialization method
based on the bundle target. EPUBs need the
content to be XHTML (produced by a XML serializer),
rather than normal HTML.
*/
const serializer = options.xhtml
? arr => {
const xs = new dom.window.XMLSerializer();
return arr.map(el => xs.serializeToString(el)).join('');
}
: arr => arr.map(el => el.innerHTML).join('');
/*
When dompurify returns a DOM node, it always wraps it
in a HTMLBodyElement. We only need its children.
*/
const sanitize_to_dom = dirty =>
Array.from(
sanitizer.sanitize(dirty, { RETURN_DOM: true }).children
);
const content_els = sanitize_to_dom(parsed.content);
// `--toc-level` implies `--toc`, unless disabled with `--no-toc`.
let headings = [];
if (options['toc-level'] > 1 && options.toc !== false) {
headings = setIdsAndReturnHeadings(
content_els,
options['toc-level']
).map(heading => {
return {
id: heading.id,
level: heading.level,
// Plain text used in EPUB
text: heading.node.textContent.trim(),
// Sanitized marked-up text used in HTML/PDF
content: serializer([heading.node])
};
});
}
return {
id: `percollate-page-${uuid()}`,
url: final_url,
title: sanitizer.sanitize(parsed.title),
byline: sanitizer.sanitize(parsed.byline),
dir: sanitizer.sanitize(parsed.dir),
excerpt: serializer(sanitize_to_dom(parsed.excerpt)),
content: serializer(
options.hyphenate === true
? content_els.map(el => hyphenateDom(el, lang))
: content_els
),
lang,
textContent,
toc: nestHeadings(headings || []),
length: parsed.length,
siteName: sanitizer.sanitize(parsed.siteName),
remoteResources,
originalContent: {
buffer,
contentType
}
};
} catch (error) {
console.error(`${url}:`, error.message);
throw error;
}
}
/*
Bundle the HTML files into a PDF
--------------------------------
*/
async function bundlePdf(items, options) {
const DEFAULT_STYLESHEET = new URL(
'templates/default.css',
import.meta.url
);
const DEFAULT_TEMPLATE = new URL('templates/default.html', import.meta.url);
const style =
(await readFile(options.style || DEFAULT_STYLESHEET, 'utf8')) +
(options.hyphenate === true ? JUSTIFY_CSS : '') +
(options.css || '');
const title =
options.title || (items.length === 1 ? items[0].title : 'Untitled');
const author =
options.author || (items.length === 1 ? items[0].byline : undefined);
// either explicit `--toc` or implicit ToC in the absence of `--no-toc`.
const use_toc =
options.toc ||
((items.length > 1 || options['toc-level'] > 1) &&
options.toc !== false);
const html = nunjucks.renderString(
await readFile(options.template || DEFAULT_TEMPLATE, 'utf8'),
{
filetype: 'pdf',
title,
author,
date: humanDate(new Date()),
items,
style,
options: {
use_toc,
use_cover:
options.cover ||
(options.cover !== false &&
(options.title || items.length > 1))
}
}
);
const doc = new JSDOM(html).window.document;
const headerTemplate = doc.querySelector('.header-template');
const footerTemplate = doc.querySelector('.footer-template');
const header = new JSDOM(
headerTemplate ? headerTemplate.innerHTML : '<span></span>'
).window.document;
const footer = new JSDOM(
footerTemplate ? footerTemplate.innerHTML : '<span></span>'
).window.document;
const css_ast = css.parse(style);
const header_style = get_style_attribute_value(css_ast, '.header-template');
const header_div = header.querySelector('body :first-child');
if (header_div && header_style) {
header_div.setAttribute(
'style',
`
${header_style};
${header_div.getAttribute('style') || ''}
`
);
}
const footer_style = get_style_attribute_value(css_ast, '.footer-template');
const footer_div = footer.querySelector('body :first-child');
if (footer_div && footer_style) {
footer_div.setAttribute(
'style',
`
${footer_style};
${footer_div.getAttribute('style') || ''}
`
);
}
if (options.debug) {
err.write('Generating temporary HTML file... ');
const temp_file = path.resolve(process.cwd(), `${uuid()}.html`);
await writeFile(temp_file, html);
err.write('✓\n');
err.write(`Temporary HTML file: file://${temp_file}\n`);
}
const browser = await launch(options);
const page = await browser.newPage();
/*
Increase the navigation timeout to 2 minutes
See: https://github.com/danburzo/percollate/issues/80
*/
page.setDefaultNavigationTimeout(120 * 1000);
if (options.debug) {
page.on('response', response => {
err.write(`Fetched: ${response.url()}\n`);
});
}
await page.setContent(html, { waitUntil: 'load' });
const output_path = outputPath(items, options, '.pdf', options.slugCache);
const pdfOptions = {
preferCSSPageSize: true,
displayHeaderFooter: options.browser !== 'firefox',
headerTemplate: header.body.innerHTML,
footerTemplate: footer.body.innerHTML,
printBackground: true
};
/*
Currently, Firefox does not produce PDFs
with the page format specified by the author
with the `@page/size` CSS declaration.
We need to extract that value ourselves and produce
the appropriate Puppeteer config.
Once these tasks get done in Firefox,
the EXPLICIT_PAGE_SIZE_FROM_CSS code path can be removed:
https://bugzilla.mozilla.org/show_bug.cgi?id=1793220
https://bugzilla.mozilla.org/show_bug.cgi?id=1815565
*/
const EXPLICIT_PAGE_SIZE_FROM_CSS = options.browser === 'firefox';
let buffer = await page.pdf(
EXPLICIT_PAGE_SIZE_FROM_CSS
? {
...pdfOptions,
...getCssPageFormat(doc)
}
: pdfOptions
);
await browser.close();
let pdf = await addExif(buffer, {
Title: title,
Author: author
});
await writeFile(output_path, pdf);
err.write(`Saved PDF: `);
out.write(String(output_path));
}
/*
Bundle the HTML files into a EPUB
---------------------------------
*/
async function bundleEpub(items, options) {
const DEFAULT_STYLESHEET = new URL(
'templates/default.css',
import.meta.url
);
const style =
(await readFile(options.style || DEFAULT_STYLESHEET, 'utf8')) +
(options.hyphenate === true ? JUSTIFY_CSS : '') +
(options.css || '');
err.write('Saving EPUB...\n');
const output_path = outputPath(items, options, '.epub', options.slugCache);
const title =
options.title || (items.length === 1 ? items[0].title : 'Untitled');
const author =
options.author || (items.length === 1 ? items[0].byline : undefined);
await epubgen(
{
filetype: 'epub',
title,
author,
date: epubDate(new Date()),
cover:
options.cover ||
(options.cover !== false &&
(options.title || items.length > 1)),
uuid: uuid(),
items,
style
},
output_path,
options
);
err.write(`Saved EPUB: `);
out.write(String(output_path));
}
/*
Bundle the HTML files into a HTML
---------------------------------
*/
async function bundleHtml(items, options) {
const DEFAULT_STYLESHEET = new URL(
'templates/default.css',
import.meta.url
);
const DEFAULT_TEMPLATE = new URL('templates/default.html', import.meta.url);
const style =
(await readFile(options.style || DEFAULT_STYLESHEET, 'utf8')) +
(options.hyphenate === true ? JUSTIFY_CSS : '') +
(options.css || '');
// either explicit `--toc` or implicit ToC in the absence of `--no-toc`.
const use_toc =
options.toc ||
((items.length > 1 || options['toc-level'] > 1) &&
options.toc !== false);
const html = nunjucks.renderString(
await readFile(options.template || DEFAULT_TEMPLATE, 'utf8'),
{
filetype: 'html',
title:
options.title ||
(items.length === 1 ? items[0].title : 'Untitled'),
date: humanDate(new Date()),
items,
style,
options: {
use_toc,
use_cover:
options.cover ||
(options.cover !== false &&
(options.title || items.length > 1))
}
}
);
if (options.output === '-') {
out.write(html);
return;
}
err.write('Saving HTML...\n');
const output_path = outputPath(items, options, '.html', options.slugCache);
await writeFile(output_path, html);
err.write(`Saved HTML: `);
out.write(String(output_path));
}
/*
Bundle the HTML files into a Markdown
-------------------------------------
*/
async function bundleMd(items, options) {
const DEFAULT_STYLESHEET = new URL(
'templates/default.css',
import.meta.url
);
const DEFAULT_TEMPLATE = new URL('templates/default.html', import.meta.url);
const style =
(await readFile(options.style || DEFAULT_STYLESHEET, 'utf8')) +
(options.hyphenate === true ? JUSTIFY_CSS : '') +
(options.css || '');
// either explicit `--toc` or implicit ToC in the absence of `--no-toc`.
const use_toc =
options.toc ||
((items.length > 1 || options['toc-level'] > 1) &&
options.toc !== false);
const html = nunjucks.renderString(
await readFile(options.template || DEFAULT_TEMPLATE, 'utf8'),
{
filetype: 'html',
title:
options.title ||
(items.length === 1 ? items[0].title : 'Untitled'),
date: humanDate(new Date()),
items,
style,
options: {
use_toc,
use_cover:
options.cover ||
(options.cover !== false &&
(options.title || items.length > 1))
}
}
);
const md = toMarkdown(toMdast(fromDom(new JSDOM(html).window.document)), {
...DEFAULT_MARKDOWN_OPTIONS,
...Object.fromEntries(
Object.entries(options.markdownOptions).filter(entry =>
AVAILABLE_MARKDOWN_OPTIONS.has(entry[0])
)
),
extensions: [gfmToMarkdown()]
});
if (options.output === '-') {
out.write(md);
return;
}
err.write('Saving MD...\n');
const output_path = outputPath(items, options, '.md', options.slugCache);
await writeFile(output_path, md);
err.write(`Saved MD: `);
out.write(String(output_path));
}
async function generate(fn, urls, options = {}) {
if (!configured) {
configure();
}
if (!urls.length) {
return null;
}
let w = options.wait * 1000;
if (options.debug && w) {
if (Number.isFinite(w) && w >= 0) {
err.write(
`Processing URLs sequentially, waiting ${options.wait} seconds in-between.\n`
);
} else {
err.write(
`Invalid --wait: expecting positive number, got ${options.wait}. Processing URLs in parallel.\n`
);
}
}
let resolve =
Number.isFinite(w) && w >= 0 ? resolveSequence : resolveParallel;
let items = (
await resolve(
urls,
(url, i) => {
return cleanup(url, {
...options,
preferred_url: options.url ? options.url[i] : undefined
}).catch(err => {
console.error(err);
console.error('Ignoring item');
return null;
});
},
w
)
).filter(it => it);
if (options.individual) {
await Promise.all(items.map(item => fn([item], options)));
} else {
await fn(items, options);
}
return {
items,
options
};
}
/*
Generate PDF
*/
async function pdf(urls, options) {
return await generate(bundlePdf, urls, {
...options,
// Hyphenate by default
hyphenate: options.hyphenate !== undefined ? options.hyphenate : true,
slugCache: {}
});
}
/*
Generate EPUB
*/
async function epub(urls, options) {
return await generate(bundleEpub, urls, {
...options,
xhtml: true,
mapRemoteResources: !options.inline,
hyphenate: options.hyphenate !== undefined ? options.hyphenate : false,
slugCache: {}
});
}
/*
Generate HTML
*/
async function html(urls, options) {
return await generate(bundleHtml, urls, {
...options,
hyphenate: options.hyphenate !== undefined ? options.hyphenate : false,
slugCache: {}
});
}
/*
Generate Markdown
*/
async function md(urls, options) {
return await generate(bundleMd, urls, {
...options,
hyphenate: options.hyphenate !== undefined ? options.hyphenate : false,
slugCache: {}
});
}
/*
Produce an EPUB file
--------------------
Reference:
https://www.ibm.com/developerworks/xml/tutorials/x-epubtut/index.html
*/
async function epubgen(data, output_path, options) {
const wrapAsync = inner => {
return new Promise((resolve, reject) => {
inner(resolve, reject).catch(reject);
});
};
return wrapAsync(async (resolve, reject) => {
const template_base = fileURLToPath(
new URL('templates/epub/', import.meta.url)
);
const output = fs.createWriteStream(output_path);
const archive = archiver('zip', {
zlib: {
// Best DEFLATE compression level
level: 9
}
});
output
.on('finish', () => {
err.write(`${archive.pointer()} total bytes, archive closed\n`);
resolve();
})
.on('error', reject);
archive.on('warning', reject).on('error', reject).pipe(output);
// mimetype file must be first
archive.append('application/epub+zip', {
name: 'mimetype',
// don’t compress the mimetype file as per EPUB spec
store: true
});
// static files from META-INF
archive.directory(path.join(template_base, 'META-INF'), 'META-INF');
const contentTemplate = await readFile(
path.join(template_base, 'OEBPS/content.xhtml'),
'utf8'
);
const navTemplate = await readFile(
path.join(template_base, 'OEBPS/nav.xhtml'),
'utf8'
);
const tocTemplate = await readFile(
path.join(template_base, 'OEBPS/toc.ncx'),
'utf8'
);
const opfTemplate = await readFile(
path.join(template_base, 'OEBPS/content.opf'),
'utf8'
);
archive.append(data.style || '', { name: 'OEBPS/style.css' });
let remoteResources = [];
data.items.forEach(item => {
remoteResources = remoteResources.concat(
item.remoteResources || []
);
let item_content = nunjucks.renderString(contentTemplate, {
...data,
item
});
archive.append(item_content, { name: `OEBPS/${item.id}.xhtml` });
});
for (let i = 0; i < remoteResources.length; i++) {
let entry = remoteResources[i];
try {
if (options.debug) {
err.write(`Fetching: ${entry.original}\n`);
}
let stream = (
await fetch(entry.original, {
headers: {
'user-agent': UA
},
/*
Send the referrer as the browser would
when fetching the image to render it.
*/
referrer: entry.origin,
referrerPolicy: 'strict-origin-when-cross-origin',
timeout: 10 * 1000
})
).body;
archive.append(stream, { name: `OEBPS/${entry.mapped}` });
} catch (err) {
console.error(err);
}
}
const assets = [
{
id: 'style',
href: 'style.css',
mimetype: 'text/css'
}
];
if (data.cover) {
const COVER_TEMPLATE = new URL(
'templates/cover.html',
import.meta.url
);
const cover_html = nunjucks.renderString(
await readFile(COVER_TEMPLATE, 'utf8'),
data
);
const browser = await launch(options, {
width: 400,
height: 565
});
const page = await browser.newPage();
await page.setUserAgent(UA);
await page.setContent(cover_html, { waitUntil: 'load' });
let buff = await page.screenshot({
type: 'png',
fullPage: true
});
archive.append(buff, { name: 'OEBPS/cover.png' });
await browser.close();
}
const nav = nunjucks.renderString(navTemplate, data);
const opf = nunjucks.renderString(opfTemplate, {
...data,
assets,
cover: data.cover
? {
id: 'cover',
href: 'cover.png',
mimetype: 'image/png'
}
: undefined,
remoteResources: remoteResources.map(entry => ({
id: entry.mapped.replace(/[^a-z0-9]/gi, ''),
href: entry.mapped,
mimetype: entry.mimetype
}))
});
const toc = nunjucks.renderString(tocTemplate, data);
archive.append(nav, { name: 'OEBPS/nav.xhtml' });
archive.append(opf, { name: 'OEBPS/content.opf' });
archive.append(toc, { name: 'OEBPS/toc.ncx' });
archive.finalize();
});
}
export { configure, pdf, epub, html, md };
export const __test__ = {
fetchContent,
isURL
};