-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
190 lines (162 loc) · 4.92 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
#! /usr/bin/env node
import path from 'path';
import { URL } from 'url';
import fs from 'fs';
import cp from 'child_process';
import puppeteer from 'puppeteer';
import { unified } from 'unified';
import remarkParse from 'remark-parse';
import remarkFrontmatter from 'remark-frontmatter';
import remarkRehype from 'remark-rehype';
import rehypeDocument from 'rehype-document';
import rehypeFormat from 'rehype-format';
import rehypeStringify from 'rehype-stringify';
import { visit } from 'unist-util-visit';
import yaml from 'yaml';
const __dirname = new URL('.', import.meta.url).pathname;
const CWD = process.cwd();
const TEMP_PATH = path.join(__dirname, 'temp');
const startServer = () => new Promise((resolve, _) => {
const server = cp.spawn('npx', ['http-server', TEMP_PATH, '-c-1', '--no-color']);
// server.on('exit', (code) => console.log('Server exited with code', code));
server.stderr.on('data', (chunkBuffer) => {
const serverMessage = chunkBuffer.toString('utf-8');
if (serverMessage.includes('OutgoingMessage.prototype._headers is deprecated')) {
return;
}
console.log('Server error:', serverMessage);
});
server.stdout.on('data', (chunkBuffer) => {
const serverMessage = chunkBuffer.toString('utf-8');
// console.log(`Server output:`,chunkBuffer.toString('utf-8'));
if (serverMessage.includes('Available on')) {
const [targetUrl] = serverMessage.match(/http[s]*:\/\/[\d|\.]+:\d+/g);
resolve({server, targetUrl});
}
});
});
async function spinBrowserAndPrint({ fileName, targetUrl }) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(
targetUrl,
{
waitUntil: 'networkidle0',
},
);
await page.pdf({
path: `${fileName}.pdf`,
format: 'a4',
margin: {
top: '20px',
left: '20px',
right: '20px',
bottom: '20px',
},
});
await browser.close();
}
async function convertMarkdownAndCreateTempFiles(fileName) {
const linkNode = {
type: 'element',
tagName: 'link',
properties: {
rel: 'stylesheet',
href: 'styles.css',
},
children: [],
};
const getGoogleFontsNodes = (fontList) => {
const familySlug = fontList.map((fontName) => {
let slug = 'family=';
slug += fontName.replace(' ', '+');
slug += ':wght@100;200;300;400;500;600;700;800;900';
return slug;
}).join('&');
const nodes = [
{
type: 'element',
tagName: 'link',
properties: {
rel: 'preconnect',
href: 'https://fonts.googleapis.com',
},
},
{
type: 'element',
tagName: 'link',
properties: {
rel: 'preconnect',
href: 'https://fonts.gstatic.com',
crossorigin: '',
},
},
{
type: 'element',
tagName: 'link',
properties: {
rel: 'stylesheet',
href: `https://fonts.googleapis.com/css2?${familySlug}&display=swap`,
},
},
];
return nodes;
};
let yamlConfigs = {};
const processor = unified()
.use(remarkParse)
.use(remarkFrontmatter)
.use(() => tree => {
visit(
tree,
(node) => node.type ==='yaml',
(yamlNode) => {
yamlConfigs = yaml.parse(yamlNode.value);
});
})
.use(remarkRehype)
.use(rehypeDocument)
.use(rehypeFormat)
.use(() => (tree) => {
visit(tree,
(node) => node.tagName === 'head',
(head) => {
if (yamlConfigs.stylesheet) {
head.children.push(linkNode);
}
if (yamlConfigs.google_fonts) {
head.children = [...head.children, ...getGoogleFontsNodes(yamlConfigs.google_fonts)];
}
});
})
.use(() => tree => {
// visit(tree, null, node => console.log(JSON.stringify(node)));
})
.use(rehypeStringify);
const markdownContent = await fs.promises.readFile(path.join(CWD, `${fileName}.md`), 'utf-8');
const htmlFile = await processor.process(markdownContent);
await fs.promises.mkdir(TEMP_PATH);
await fs.promises.writeFile(path.join(TEMP_PATH, 'index.html'), htmlFile.toString());
if (yamlConfigs.stylesheet) {
await fs.promises.copyFile(path.join(CWD, yamlConfigs.stylesheet), path.join(TEMP_PATH, 'styles.css'));
}
}
async function clearTempFolder() {
const files = await fs.promises.readdir(TEMP_PATH);
files.forEach(async (fileName) => {
await fs.promises.unlink(path.join(TEMP_PATH, fileName));
});
await fs.promises.rmdir(TEMP_PATH);
}
(async () => {
const fileName = process.argv[2];
if (!fileName) {
throw new Error ('Must inform the name of the markdown file');
}
await convertMarkdownAndCreateTempFiles(fileName);
const { server, targetUrl } = await startServer();
await spinBrowserAndPrint({ fileName, targetUrl });
await clearTempFolder();
console.log(`Successfully converted ${fileName}.md to ${fileName}.pdf`);
server.kill();
})();