-
Notifications
You must be signed in to change notification settings - Fork 2
/
Crafter.js
60 lines (53 loc) · 1.76 KB
/
Crafter.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
const fs = require('fs');
const path = require('path');
const Context = require('./Context');
const parsersList = require('./Parsers');
const utils = require('./utils');
const Parsers = {};
let prevPendingParsers = [];
function getOptions(options, defaultOptions) {
return options === null || options === undefined || typeof options === 'function'
? defaultOptions
: options;
}
/**
* @param {string} source
* @param {ContextOptions} contextOptions
* @returns {array}
*/
async function parse(source, contextOptions) {
const ast = utils.markdownSourceToAST(source);
const context = new Context(source, Parsers, getOptions(contextOptions, {}));
const result = await Parsers.BlueprintParser.parse(ast.firstChild, context);
return result.slice(1);
}
async function parseFile(file, contextOptions) {
const options = { ...getOptions(contextOptions, {}), entryDir: path.dirname(file), currentFile: file };
return parse(await fs.promises.readFile(file, { encoding: 'utf-8' }), options);
}
function defineParsers(parsers) {
const pendingParsers = [];
parsers.forEach((parser) => {
if (typeof parser === 'function') {
const isDefined = parser(Parsers);
if (typeof isDefined !== 'boolean') {
throw new Error(`Expect parser function to return "true" or "false", but it returned ${isDefined}.`);
}
if (!isDefined) {
pendingParsers.push(parser);
}
}
});
if (pendingParsers.length > 0) {
if (prevPendingParsers.length && !(pendingParsers.length < prevPendingParsers.length)) {
throw new Error('Something went wrong during parsers definition process');
}
prevPendingParsers = pendingParsers;
defineParsers(pendingParsers);
}
}
defineParsers(parsersList);
module.exports = {
parse,
parseFile,
};