docgen-tool 3.0.3 → 3.0.5

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.
@@ -1,891 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- var rsvp = require('rsvp');
4
- var fs = require('fs-extra');
5
- var path = require('path');
6
- var cheerio = require('cheerio');
7
- var markdown = require('markdown-it')('commonmark').enable('table');
8
- var moment = require('moment');
9
- var child_process_1 = require("child_process");
10
- var schemaValidator = require('z-schema');
11
- var chalk = require('chalk');
12
- var spawnArgs = require('spawn-args');
13
- var cliSpinner = require('cli-spinner').Spinner;
14
- var imageSizeOf = require('image-size');
15
- //Allow CommonMark links that use other protocols, such as file:///
16
- //The markdown-it implementation is more restrictive than the CommonMark spec
17
- //See https://github.com/markdown-it/markdown-it/issues/108
18
- markdown.validateLink = function () {
19
- return true;
20
- };
21
- /**
22
- * DocGen class
23
- */
24
- function DocGen(process) {
25
- var mainProcess = process;
26
- var version = '3.0.2';
27
- var wkhtmltopdfVersion = 'wkhtmltopdf 0.12.6 (with patched qt)'; //output from wkhtmltopdf -V
28
- var options;
29
- var templates = {};
30
- var meta = {};
31
- var pages = {};
32
- var sortedPages = {};
33
- this.getVersion = function () {
34
- return version;
35
- };
36
- this.setOptions = function (userOptions) {
37
- options = userOptions;
38
- //all user-specified paths must be normalized
39
- if (options.input) {
40
- options.input = path.normalize(options.input + '/');
41
- }
42
- if (options.output) {
43
- options.output = path.normalize(options.output + '/');
44
- }
45
- //wkhtmltopdf path does not need a trailing slash
46
- if (options.wkhtmltopdfPath && options.wkhtmltopdfPath !== '') {
47
- options.wkhtmltopdfPath = path.normalize(options.wkhtmltopdfPath);
48
- }
49
- };
50
- /*
51
- copy the example source files (template) to any directory, when scaffold command is invoked
52
- */
53
- this.scaffold = function () {
54
- console.log(chalk.green('Creating scaffold template directory'));
55
- copyDirSync(__dirname + '/example', options.output);
56
- };
57
- this.run = function () {
58
- console.log(chalk.green.bold('DocGen version ' + version));
59
- //delete and recreate the output directory
60
- remakeDirSync(options.output);
61
- loadTemplates();
62
- };
63
- /*
64
- read any file (async)
65
- */
66
- var readFile = function (path) {
67
- return new rsvp.Promise(function (resolve, reject) {
68
- fs.readFile(path, 'utf8', function (error, data) {
69
- if (error) {
70
- console.log(chalk.red('Error reading file: ' + path));
71
- reject(error);
72
- }
73
- else {
74
- data = data.replace(/^\uFEFF/, ''); //remove the BOM (byte-order-mark) from UTF-8 files, if present
75
- resolve(data);
76
- }
77
- });
78
- });
79
- };
80
- /*
81
- write any file (async)
82
- */
83
- var writeFile = function (path, data) {
84
- return new rsvp.Promise(function (resolve, reject) {
85
- fs.writeFile(path, data, function (error) {
86
- if (error) {
87
- console.log(chalk.red('Error writing file: ' + path));
88
- reject(error);
89
- }
90
- else {
91
- resolve(true);
92
- }
93
- });
94
- });
95
- };
96
- /*
97
- copy any directory (sync)
98
- */
99
- var copyDirSync = function (source, destination) {
100
- try {
101
- fs.copySync(source, destination);
102
- }
103
- catch (error) {
104
- console.log(chalk.red('Error copying directory: ' + source + ' to ' + destination));
105
- if (options.verbose === true) {
106
- console.log(chalk.red(error));
107
- mainProcess.exit(1);
108
- }
109
- }
110
- };
111
- /*
112
- remake a directory (sync) ... remove and then mkdir in one operation
113
- */
114
- var remakeDirSync = function (path) {
115
- try {
116
- fs.removeSync(path);
117
- fs.mkdirpSync(path);
118
- }
119
- catch (error) {
120
- console.log(chalk.red('Error recreating directory: ' + path));
121
- if (options.verbose === true) {
122
- console.log(chalk.red(error));
123
- mainProcess.exit(1);
124
- }
125
- }
126
- };
127
- /*
128
- remove any directory (sync)
129
- */
130
- var removeDirSync = function (path) {
131
- try {
132
- fs.removeSync(path);
133
- }
134
- catch (error) {
135
- console.log(chalk.red('Error removing directory: ' + path));
136
- if (options.verbose === true) {
137
- console.log(chalk.red(error));
138
- mainProcess.exit(1);
139
- }
140
- }
141
- };
142
- /*
143
- load all HTML template files
144
- */
145
- var loadTemplates = function () {
146
- console.log(chalk.green('Loading templates'));
147
- var files = {
148
- main: readFile(__dirname + '/templates/main.html'),
149
- redirect: readFile(__dirname + '/templates/redirect.html'),
150
- webCover: readFile(__dirname + '/templates/webCover.html'),
151
- pdfCover: readFile(__dirname + '/templates/pdfCover.html'),
152
- pdfHeader: readFile(__dirname + '/templates/pdfHeader.html'),
153
- pdfFooter: readFile(__dirname + '/templates/pdfFooter.html'),
154
- };
155
- rsvp
156
- .hash(files)
157
- .then(function (files) {
158
- for (var key in files) {
159
- if (files.hasOwnProperty(key)) {
160
- var file = files[key];
161
- var dom = cheerio.load(file);
162
- templates[key] = dom;
163
- }
164
- }
165
- loadMeta();
166
- })
167
- .catch(function (error) {
168
- console.log(chalk.red('Error loading templates'));
169
- if (options.verbose === true) {
170
- console.log(chalk.red(error));
171
- }
172
- mainProcess.exit(1);
173
- });
174
- };
175
- /*
176
- JSON schema validation
177
- */
178
- var schemas = {
179
- parameters: {
180
- title: 'DocGen Parameters Schema',
181
- type: 'object',
182
- required: [
183
- 'title',
184
- 'name',
185
- 'version',
186
- 'date',
187
- 'organization',
188
- 'author',
189
- 'owner',
190
- 'contributors',
191
- 'website',
192
- 'module',
193
- 'id',
194
- 'summary',
195
- 'marking',
196
- 'legalese',
197
- ],
198
- properties: {
199
- title: { type: 'string' },
200
- name: { type: 'string' },
201
- version: { type: 'string' },
202
- date: { type: 'string' },
203
- organization: {
204
- type: 'object',
205
- required: ['name', 'url'],
206
- properties: {
207
- name: { type: 'string' },
208
- url: { type: 'string' },
209
- },
210
- },
211
- author: {
212
- type: 'object',
213
- required: ['name', 'url'],
214
- properties: {
215
- name: { type: 'string' },
216
- url: { type: 'string' },
217
- },
218
- },
219
- owner: {
220
- type: 'object',
221
- required: ['name', 'url'],
222
- properties: {
223
- name: { type: 'string' },
224
- url: { type: 'string' },
225
- },
226
- },
227
- contributors: {
228
- type: 'array',
229
- items: {
230
- oneOf: [
231
- {
232
- type: 'object',
233
- required: ['name', 'url'],
234
- properties: {
235
- name: { type: 'string' },
236
- url: { type: 'string' },
237
- },
238
- },
239
- ],
240
- },
241
- },
242
- website: {
243
- type: 'object',
244
- required: ['name', 'url'],
245
- properties: {
246
- name: { type: 'string' },
247
- url: { type: 'string' },
248
- },
249
- },
250
- backlink: {
251
- type: 'object',
252
- required: ['name', 'url'],
253
- properties: {
254
- name: { type: 'string' },
255
- url: { type: 'string' },
256
- },
257
- },
258
- module: { type: 'string' },
259
- id: { type: 'string' },
260
- summary: { type: 'string' },
261
- marking: { type: 'string' },
262
- legalese: { type: 'string' },
263
- },
264
- },
265
- contents: {
266
- title: 'DocGen Table of Contents Schema',
267
- type: 'array',
268
- items: {
269
- oneOf: [
270
- {
271
- type: 'object',
272
- required: ['heading', 'column', 'pages'],
273
- properties: {
274
- name: { type: 'string' },
275
- column: { type: 'integer', minimum: 1, maximum: 4 },
276
- pages: {
277
- type: 'array',
278
- items: {
279
- oneOf: [
280
- {
281
- type: 'object',
282
- required: ['title', 'source'],
283
- properties: {
284
- title: { type: 'string' },
285
- source: { type: 'string' },
286
- html: { type: 'boolean' },
287
- },
288
- },
289
- ],
290
- },
291
- },
292
- },
293
- },
294
- ],
295
- },
296
- },
297
- };
298
- var validateJSON = function (key, data) {
299
- var schema = schemas[key];
300
- var validator = new schemaValidator();
301
- var valid = validator.validate(data, schema);
302
- if (!valid) {
303
- console.log(chalk.red('Error parsing required file: ' +
304
- key +
305
- '.json (failed schema validation)'));
306
- if (options.verbose === true) {
307
- console.log(chalk.red(validator.getLastError()));
308
- }
309
- }
310
- return valid;
311
- };
312
- /*
313
- load all metadata files (JSON)
314
- */
315
- var loadMeta = function () {
316
- console.log(chalk.green('Loading required JSON metadata files'));
317
- var files = {
318
- parameters: readFile(options.input + '/parameters.json'),
319
- contents: readFile(options.input + '/contents.json'),
320
- };
321
- rsvp
322
- .hash(files)
323
- .then(function (files) {
324
- for (var key in files) {
325
- if (files.hasOwnProperty(key)) {
326
- //ignore prototype
327
- try {
328
- var file = JSON.parse(files[key]);
329
- if (validateJSON(key, file)) {
330
- meta[key] = file;
331
- }
332
- else {
333
- mainProcess.exit(1);
334
- }
335
- }
336
- catch (error) {
337
- console.log(chalk.red('Error parsing required file: ' +
338
- key +
339
- '.json (invalid JSON)'));
340
- if (options.verbose === true) {
341
- console.log(chalk.red(error));
342
- }
343
- mainProcess.exit(1);
344
- }
345
- }
346
- }
347
- //add the release notes to the contents list
348
- var extra = {
349
- heading: 'Extra',
350
- column: 5,
351
- pages: [{ title: 'Release notes', source: 'release-notes.txt' }],
352
- };
353
- meta.contents.push(extra);
354
- loadMarkdown();
355
- })
356
- .catch(function (error) {
357
- console.log(chalk.red('Error loading required JSON metadata files'));
358
- if (options.verbose === true) {
359
- console.log(chalk.red(error));
360
- }
361
- mainProcess.exit(1);
362
- });
363
- };
364
- /*
365
- load all markdown files (source)
366
- */
367
- var loadMarkdown = function () {
368
- console.log(chalk.green('Loading source files'));
369
- var keys = [];
370
- var files = [];
371
- meta.contents.forEach(function (section) {
372
- section.pages.forEach(function (page) {
373
- keys.push(page);
374
- files.push(options.input + '/' + page.source);
375
- });
376
- });
377
- //add the release notes page
378
- keys.push('ownership');
379
- files.push(options.input + '/release-notes.txt');
380
- rsvp
381
- .all(files.map(readFile))
382
- .then(function (files) {
383
- files.forEach(function (page, index) {
384
- try {
385
- var key = keys[index];
386
- if (key.html === true) {
387
- //allow raw HTML input pages
388
- pages[key.source] = page;
389
- }
390
- else {
391
- //otherwise parse input from Markdown into HTML
392
- var html = markdown.render(page);
393
- pages[key.source] = html;
394
- }
395
- }
396
- catch (error) {
397
- console.log(chalk.red('Error parsing Markdown file: ' + file.source));
398
- if (options.verbose === true) {
399
- console.log(chalk.red(error));
400
- }
401
- mainProcess.exit(1);
402
- }
403
- });
404
- processContent();
405
- })
406
- .catch(function (error) {
407
- console.log(error);
408
- console.log(chalk.red('Error loading source files'));
409
- if (options.verbose === true) {
410
- console.log(chalk.red(error));
411
- }
412
- mainProcess.exit(1);
413
- });
414
- };
415
- var sortPages = function () {
416
- //sort the contents by heading
417
- var headings = { 1: [], 2: [], 3: [], 4: [], 5: [] };
418
- meta.contents.forEach(function (section) {
419
- if (headings.hasOwnProperty(section.column)) {
420
- headings[section.column].push(section);
421
- }
422
- });
423
- sortedPages = headings;
424
- };
425
- /*
426
- build the HTML for the table of contents
427
- */
428
- var webToc = function () {
429
- sortPages();
430
- var pdfName = meta.parameters.name.toLowerCase() + '.pdf';
431
- var $ = templates.main;
432
- var html = [], i = -1;
433
- html[++i] = '<div><table class="unstyled"><tr>';
434
- //build the contents HTML
435
- for (var key in sortedPages) {
436
- if (sortedPages.hasOwnProperty(key)) {
437
- if (key != 5) {
438
- //skip the extra column
439
- html[++i] = '<td class="dg-tocGroup">';
440
- sortedPages[key].forEach(function (section) {
441
- html[++i] =
442
- '<ul><li class="dg-tocHeading">' + section.heading + '</li>';
443
- section.pages.forEach(function (page) {
444
- var name = page.source.substr(0, page.source.lastIndexOf('.'));
445
- var path = name + '.html';
446
- html[++i] =
447
- '<li><a href="' + path + '">' + page.title + '</a></li>';
448
- });
449
- html[++i] = '</li></ul>';
450
- });
451
- html[++i] = '</td>';
452
- }
453
- }
454
- }
455
- //fixed-width column at end
456
- html[++i] = '<td class="dg-tocGroup" id="dg-tocFixedColumn"><ul>';
457
- html[++i] =
458
- '<li><span class="w-icon dg-tocIcon" data-name="person_group" title="archive"></span><a href="ownership.html">Ownership</a></li>';
459
- html[++i] =
460
- '<li><span class="w-icon dg-tocIcon" data-name="refresh" title="archive"></span><a href="release-notes.html">Release Notes</a></li>';
461
- html[++i] = '</ul><div>';
462
- if (options.pdf) {
463
- html[++i] =
464
- '<button class="w-icon-button" onclick="window.location=\'' +
465
- pdfName +
466
- '\';">';
467
- html[++i] = '<span class="w-icon" data-name="document"></span>';
468
- html[++i] = '<span>PDF copy</span>';
469
- html[++i] = '</button>';
470
- }
471
- html[++i] = '</div></td>';
472
- html[++i] = '</tr></table></div>';
473
- $('#dg-toc').html(html.join(''));
474
- templates.main = $;
475
- };
476
- /*
477
- insert the parameters into all templates
478
- */
479
- var insertParameters = function () {
480
- //------------------------------------------------------------------------------------------------------
481
- //logo dimensions
482
- var hasLogo = false;
483
- var logoWidth = 0;
484
- var logoHeight = 0;
485
- try {
486
- var logo = imageSizeOf(options.input + '/files/images/logo.png');
487
- logoWidth = logo.width;
488
- logoHeight = logo.height;
489
- hasLogo = true;
490
- }
491
- catch (error) {
492
- //do nothing. If logo file cannot be read, logo is simply not shown
493
- }
494
- //------------------------------------------------------------------------------------------------------
495
- //the homepage is the first link in the first heading
496
- var homelink = meta.contents[0].pages[0];
497
- homelink =
498
- homelink.source.substr(0, homelink.source.lastIndexOf('.')) + '.html';
499
- var date = moment().format('DD/MM/YYYY');
500
- var time = moment().format('HH:mm:ss');
501
- var year = moment().format('YYYY');
502
- var attribution = 'Created by DocGen ' + version + ' on ' + date + ' at ' + time + '.';
503
- var releaseVersion = meta.parameters.version;
504
- if (options.setVersion !== false) {
505
- releaseVersion = options.setVersion;
506
- }
507
- var releaseDate = meta.parameters.date;
508
- if (options.setReleaseDate !== false) {
509
- releaseDate = options.setReleaseDate;
510
- }
511
- var author = '';
512
- if (meta.parameters.author.url !== '') {
513
- author +=
514
- '<a href="' +
515
- meta.parameters.author.url +
516
- '">' +
517
- meta.parameters.author.name +
518
- '</a>';
519
- }
520
- else {
521
- author += meta.parameters.author.name;
522
- }
523
- var owner = '';
524
- if (meta.parameters.owner.url !== '') {
525
- owner +=
526
- '<a href="' +
527
- meta.parameters.owner.url +
528
- '">' +
529
- meta.parameters.owner.name +
530
- '</a>';
531
- }
532
- else {
533
- owner += meta.parameters.owner.name;
534
- }
535
- var organization = '';
536
- if (meta.parameters.organization.url !== '') {
537
- organization +=
538
- '<a href="' +
539
- meta.parameters.organization.url +
540
- '">' +
541
- meta.parameters.organization.name +
542
- '</a>';
543
- }
544
- else {
545
- organization += meta.parameters.organization.name;
546
- }
547
- var website = '';
548
- if (meta.parameters.website.url !== '') {
549
- website +=
550
- '<a href="' +
551
- meta.parameters.website.url +
552
- '">' +
553
- meta.parameters.website.name +
554
- '</a>';
555
- }
556
- else {
557
- website += meta.parameters.website.name;
558
- }
559
- var backlink = '';
560
- if (meta.parameters.backlink.url !== '') {
561
- backlink +=
562
- '<a href="' +
563
- meta.parameters.backlink.url +
564
- '">' +
565
- meta.parameters.backlink.name +
566
- '</a>';
567
- }
568
- else {
569
- backlink += meta.parameters.backlink.name;
570
- }
571
- var contributors = '';
572
- meta.parameters.contributors.forEach(function (contributor) {
573
- if (contributor.url !== '') {
574
- contributors +=
575
- '<a href="' + contributor.url + '">' + contributor.name + '</a>, ';
576
- }
577
- else {
578
- contributors += contributor.name + ', ';
579
- }
580
- });
581
- contributors = contributors.replace(/,\s*$/, ''); //remove trailing commas
582
- var copyright = '&copy; ' + year + ' ' + organization;
583
- var webTitle = meta.parameters.title;
584
- var webFooter = 'Version ' + releaseVersion + ' released on ' + releaseDate + '.';
585
- for (var key in templates) {
586
- if (templates.hasOwnProperty(key)) {
587
- var $ = templates[key];
588
- //logo
589
- if (hasLogo === true) {
590
- var logoUrl = 'files/images/logo.png';
591
- $('#dg-logo').css('background-image', 'url(' + logoUrl + ')');
592
- $('#dg-logo').css('height', logoHeight + 'px');
593
- $('#dg-logo').css('line-height', logoHeight + 'px');
594
- $('#dg-logo').css('padding-left', logoWidth + 25 + 'px');
595
- }
596
- else {
597
- $('#dg-logo').css('padding-left', '0');
598
- }
599
- //parameters
600
- $('title').text(meta.parameters.title);
601
- $('#dg-homelink').attr('href', homelink);
602
- $('#dg-title').text(meta.parameters.title);
603
- $('#dg-owner').html(owner);
604
- $('#dg-version').text(releaseVersion);
605
- $('#dg-web-title-version').text('(' + releaseVersion + ')');
606
- $('#dg-release-date').text(releaseDate);
607
- $('#dg-web-footer').text(webFooter);
608
- $('#dg-author').html(author);
609
- $('#dg-contributors').html(contributors);
610
- $('#dg-module').text(meta.parameters.module);
611
- $('#dg-id').html(meta.parameters.id);
612
- $('#dg-website').html(website);
613
- $('#dg-backlink').html(backlink);
614
- $('#dg-summary').text(meta.parameters.summary);
615
- $('#dg-copyright').html(copyright);
616
- $('#dg-marking').text(meta.parameters.marking);
617
- $('#dg-legalese').text(meta.parameters.legalese);
618
- $('#dg-attribution').text(attribution);
619
- }
620
- }
621
- if (options.mathKatex === true) {
622
- var $ = templates.main;
623
- //support for KaTeX (bundled with DocGen)
624
- $('head').append('<link rel="stylesheet" href="require/katex/katex.min.css" type="text/css">');
625
- $('head').append('<script type="text/javascript" src="require/katex/katex.min.js"></script>');
626
- $('head').append('<script type="text/javascript" src="require/katexInjector.js"></script>');
627
- }
628
- if (options.mathMathjax === true) {
629
- //support for MathJax (only supported via CDN due to very large size)
630
- //MathJax configuration is the same as used by math.stackexchange.com
631
- //Note - wkhtmlpdf //cdn urls - see https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1634
632
- $('head').append('<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML-full"></script>');
633
- }
634
- };
635
- /*
636
- process each input into an output
637
- */
638
- var processContent = function () {
639
- console.log(chalk.green('Generating the static web content'));
640
- webToc();
641
- insertParameters();
642
- meta.contents.forEach(function (section) {
643
- section.pages.forEach(function (page) {
644
- var $ = cheerio.load(templates.main.html()); //clone
645
- var key = page.source;
646
- var content = pages[key];
647
- //add relevant container
648
- if (page.html === true) {
649
- //raw HTML pages should not be confined to the fixed width
650
- $('#dg-content').html('<div id="dg-innerContent"></div>');
651
- }
652
- else {
653
- //Markdown pages should be confined to the fixed width
654
- $('#dg-content').html('<div class="w-fixed-width"><div id="dg-innerContent"></div></div>');
655
- }
656
- $('#dg-innerContent').html(content);
657
- //------------------------------------------------------------------------------------------------------
658
- //insert permalinks for every page heading
659
- //when pageToc is enabled, also insert a page-level table of contents
660
- var html = [], i = -1;
661
- var headings = $('h1, h2, h3, h4, h5, h6');
662
- if (headings.length > 0) {
663
- html[++i] = '<ul class="dg-pageToc">';
664
- }
665
- headings.each(function () {
666
- var label = $(this).text();
667
- var anchor = label.toLowerCase().replace(/\s+/g, '-');
668
- $(this).attr('id', anchor);
669
- html[++i] = '<li><a href="#' + anchor + '">' + label + '</a></li>';
670
- });
671
- if (headings.length > 0) {
672
- html[++i] = '</ul>';
673
- }
674
- if (options.pageToc === true && page.html !== true) {
675
- $('#dg-innerContent').prepend(html.join(''));
676
- }
677
- //------------------------------------------------------------------------------------------------------
678
- //prepend the auto heading (which makes the PDF table of contents match the web TOC)
679
- $('#dg-innerContent').prepend('<h1 id="dg-autoTitle">' + page.title + '</h1>');
680
- if (page.html === true) {
681
- $('#dg-autoTitle').addClass('dg-hiddenTitle');
682
- }
683
- //------------------------------------------------------------------------------------------------------
684
- //apply the w-table class
685
- $('table:not(.unstyled)').addClass('w-table w-fixed w-stripe');
686
- //------------------------------------------------------------------------------------------------------
687
- pages[key] = $;
688
- });
689
- });
690
- //add web ownership page
691
- var $ = cheerio.load(templates.main.html()); //clone
692
- $('#dg-content').html('<div class="w-fixed-width"><div id="dg-innerContent"></div></div>');
693
- $('#dg-innerContent').html(templates.webCover.html());
694
- templates.webCover = $;
695
- writePages();
696
- };
697
- /*
698
- write each html page
699
- */
700
- var writePages = function () {
701
- console.log(chalk.green('Writing the web page files'));
702
- var promises = {};
703
- meta.contents.forEach(function (section) {
704
- section.pages.forEach(function (page) {
705
- var key = page.source;
706
- var name = key.substr(0, page.source.lastIndexOf('.'));
707
- var path = options.output + name + '.html';
708
- var html = pages[key].html();
709
- promises[key] = writeFile(path, html);
710
- });
711
- });
712
- //add extra files
713
- promises['ownership'] = writeFile(options.output + 'ownership.html', templates.webCover.html());
714
- if (options.pdf === true) {
715
- var pdfTempDir = options.output + 'temp/';
716
- fs.mkdirsSync(pdfTempDir);
717
- promises['docgenPdfCover'] = writeFile(pdfTempDir + 'pdfCover.html', templates.pdfCover.html());
718
- promises['docgenPdfHeader'] = writeFile(pdfTempDir + 'pdfHeader.html', templates.pdfHeader.html());
719
- promises['docgenPdfFooter'] = writeFile(pdfTempDir + 'pdfFooter.html', templates.pdfFooter.html());
720
- }
721
- rsvp
722
- .hash(promises)
723
- .then(function () {
724
- copyDirSync(__dirname + '/require', options.output + 'require'); //CSS, JavaScript
725
- copyDirSync(options.input + '/files', options.output + 'files'); //user-attached files and images
726
- if (options.mathKatex === true) {
727
- copyDirSync(__dirname + '/optional/katex', options.output + 'require/katex');
728
- }
729
- checkPdfVersion();
730
- })
731
- .catch(function (error) {
732
- console.log(chalk.red('Error writing the web page files'));
733
- if (options.verbose === true) {
734
- console.log(chalk.red(error));
735
- }
736
- mainProcess.exit(1);
737
- });
738
- };
739
- /*
740
- wkthmltopdf options
741
- */
742
- var pdfOptions = [
743
- ' --zoom 1.0',
744
- ' --image-quality 100',
745
- ' --print-media-type',
746
- ' --orientation portrait',
747
- ' --page-size A4',
748
- ' --margin-top 25',
749
- ' --margin-right 15',
750
- ' --margin-bottom 16',
751
- ' --margin-left 15',
752
- ' --header-spacing 5',
753
- ' --footer-spacing 5',
754
- ' --no-stop-slow-scripts',
755
- ];
756
- var getPdfArguments = function () {
757
- var pdfName = meta.parameters.name.toLowerCase() + '.pdf';
758
- pdfOptions.push(' --enable-local-file-access');
759
- pdfOptions.push(' --javascript-delay ' + options.pdfDelay); //code syntax highlight in wkhtmltopdf 0.12.2.1 fails without a delay (but why doesn't --no-stop-slow-scripts work?)
760
- pdfOptions.push(' --user-style-sheet ' + __dirname + '/pdf-stylesheet.css');
761
- pdfOptions.push(' --header-html ' + options.output + 'temp/pdfHeader.html');
762
- pdfOptions.push(' --footer-html ' + options.output + 'temp/pdfFooter.html');
763
- pdfOptions.push(' cover ' + options.output + 'temp/pdfCover.html');
764
- pdfOptions.push(' toc --xsl-style-sheet ' + __dirname + '/pdf-contents.xsl');
765
- var allPages = '';
766
- for (var key in sortedPages) {
767
- if (sortedPages.hasOwnProperty(key)) {
768
- sortedPages[key].forEach(function (section) {
769
- section.pages.forEach(function (page) {
770
- var key = page.source;
771
- var name = key.substr(0, page.source.lastIndexOf('.'));
772
- var path = options.output + name + '.html';
773
- allPages += ' ' + path;
774
- });
775
- });
776
- }
777
- }
778
- var args = pdfOptions.join('');
779
- args += allPages;
780
- args += ' ' + options.output + pdfName;
781
- return spawnArgs(args);
782
- };
783
- var checkPdfVersion = function () {
784
- if (options.pdf === true) {
785
- //first check that wkhtmltopdf is installed
786
- (0, child_process_1.exec)(options.wkhtmltopdfPath + ' -V', function (error, stdout, stderr) {
787
- if (error) {
788
- console.log(chalk.red('Unable to call wkhtmltopdf. Is it installed and in path? See http://wkhtmltopdf.org'));
789
- if (options.verbose === true) {
790
- console.log(chalk.red(error));
791
- }
792
- mainProcess.exit(1);
793
- }
794
- else {
795
- //warn if the version of wkhtmltopdf is not an expected version
796
- var actualWkhtmltopdfVersion = stdout.trim();
797
- if (actualWkhtmltopdfVersion !== wkhtmltopdfVersion) {
798
- var warning = 'Warning: unexpected version of wkhtmltopdf, which may work but is not tested or supported';
799
- var expectedVersion = ' expected version: ' + wkhtmltopdfVersion;
800
- var detectedVersion = ' detected version: ' + actualWkhtmltopdfVersion;
801
- console.log(chalk.yellow(warning));
802
- console.log(chalk.yellow(expectedVersion));
803
- console.log(chalk.yellow(detectedVersion));
804
- }
805
- generatePdf();
806
- }
807
- });
808
- }
809
- else {
810
- cleanUp();
811
- }
812
- };
813
- /*
814
- call wkhtmltopdf as an external executable
815
- */
816
- var generatePdf = function () {
817
- console.log(chalk.green('Creating the PDF copy (may take some time)'));
818
- var args = getPdfArguments();
819
- var wkhtmltopdf = (0, child_process_1.spawn)(options.wkhtmltopdfPath, args);
820
- var spinner = new cliSpinner(chalk.green(' Processing... %s'));
821
- spinner.setSpinnerString('|/-\\');
822
- wkhtmltopdf.on('error', function (error) {
823
- console.log(chalk.red('Error calling wkhtmltopdf to generate the PDF'));
824
- if (options.verbose === true) {
825
- console.log(chalk.red(error));
826
- }
827
- });
828
- if (options.verbose !== true) {
829
- spinner.start(); //only show spinner when verbose is off (otherwise show raw wkhtmltopdf output)
830
- }
831
- else {
832
- //pipe the output from wkhtmltopdf back to stdout
833
- //however, wkhtmltpdf outputs to stderr, not stdout. See:
834
- //https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1980
835
- wkhtmltopdf.stderr.pipe(mainProcess.stdout);
836
- }
837
- wkhtmltopdf.stdout.on('data', function (data) {
838
- //do nothing
839
- });
840
- wkhtmltopdf.stderr.on('data', function (data) {
841
- //do nothing
842
- });
843
- wkhtmltopdf.on('close', function (code) {
844
- if (options.verbose !== true) {
845
- spinner.stop();
846
- console.log(''); //newline after spinner stops
847
- }
848
- if (code !== 0) {
849
- var warning = 'wkhtmltopdf exited with a warning or error: try the -v option for details';
850
- console.log(chalk.yellow(warning));
851
- }
852
- cleanUp();
853
- });
854
- };
855
- var createRedirect = function () {
856
- if (options.redirect) {
857
- var parent_1 = options.output.replace(/\/$/, ''); //trim any trailing slash
858
- parent_1 = parent_1.split(path.sep).slice(-1).pop(); //get name of final directory in the path
859
- var homepage = meta.contents[0].pages[0];
860
- homepage =
861
- homepage.source.substr(0, homepage.source.lastIndexOf('.')) + '.html';
862
- var redirectLink = parent_1 + '/' + homepage;
863
- var $ = templates.redirect;
864
- $('a').attr('href', redirectLink);
865
- $('meta[http-equiv=REFRESH]').attr('content', '0;url=' + redirectLink);
866
- var file = options.output + '../' + 'index.html';
867
- try {
868
- fs.outputFileSync(file, $.html(), 'utf-8');
869
- }
870
- catch (error) {
871
- console.log(chalk.red('Error writing redirect file: ' + file));
872
- if (options.verbose === true) {
873
- console.log(chalk.red(error));
874
- }
875
- //don't exit because redirect error is not a fatal error
876
- }
877
- }
878
- };
879
- /*
880
- cleanup
881
- */
882
- var cleanUp = function () {
883
- createRedirect();
884
- //remove temp files
885
- if (options.pdf === true) {
886
- removeDirSync(options.output + 'temp');
887
- }
888
- console.log(chalk.green.bold('Done!'));
889
- };
890
- }
891
- module.exports = DocGen;