-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathindex.js
executable file
·68 lines (59 loc) · 1.79 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
const { promisify } = require('util');
const read = promisify(require('fs').readFile);
const { resolve } = require('path');
const marked = promisify(require('marked'));
const paraphrase = require('paraphrase');
const DEFAULT_TEMPLATE = '{{content}}';
const phrase = paraphrase(/{{([^{}]*)}}/gm, { clean: true });
/**
* [description]
* @param {String} content Markdown content
* @param {String} [options[name]] To be replaced in the template
* @param {String} [options.template]
* @param {String} [options.content]
* @param {String} [options.preset]
* @return {String}
*
* @example
* markt('# This is a title\n`this is code`', {
* template: '<body>{{ content }}<footer>{{ something_else }}</footer></body>',
* something_else: 'This is the signature or something'
* })
*
* // <body><h1>This is a title</h1><code>this is code</code><footer>This is the signature or something</footer></body>
*/
module.exports = async function(content, options = {}) {
if (typeof options === 'string') {
options = { template: options };
}
const template = await getTemplate(options);
options.content = (await marked(content, {})).trim(); // eslint-disable-line require-atomic-updates
return phrase(template, options);
};
/**
* Get a template string (work through the hierarchy)
* @param {String} [options.template] Template string
* @param {String} [options.preset] File name
* @return {String}
*/
async function getTemplate({ template, preset }) {
if (typeof template === 'string') {
return template;
}
if (typeof preset === 'string') {
try {
return (
await read(
resolve(
__dirname,
'templates',
[ preset.toLowerCase(), 'html' ].join('.'),
),
)
).toString();
} catch (error) {
throw new Error(`Preset ${preset} not found`);
}
}
return DEFAULT_TEMPLATE;
}