This repository was archived by the owner on Jul 9, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.js
More file actions
88 lines (66 loc) · 2.52 KB
/
Copy pathparser.js
File metadata and controls
88 lines (66 loc) · 2.52 KB
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
'use strict';
const commonmark = require('commonmark');
const mdParser = new commonmark.Parser();
const htmlWriter = new commonmark.HtmlRenderer({safe: false});
const entities = new (require('html-entities').AllHtmlEntities)();
class Parser {
constructor() {
this.parsers = {};
this.fileExtensions = {
'.md': 'markdown',
'.html': 'html',
'.txt': 'text',
'.apib': 'api-blueprint'
};
this.defaultParser = 'markdown';
// simple parsers
this.addParser('markdown', content => {
const ast = mdParser.parse(content);
return htmlWriter.render(ast);
});
this.addParser('html', content => {
return content;
});
this.addParser('text', (content,options) => {
return options.pre
? "<pre>" + entities.encode(content) + "</pre>"
: entities.encode(content).replace("\n", "<br>");
});
// extended parsers
this.addParser('api-blueprint', require(__dirname + '/parser/api-blueprint'));
}
parse(fileExt, content, config = {}) {
let parser = config.parser || this.fileExtensions[fileExt] || this.defaultParser;
return this.loadParser(parser)(content, config);
}
addParser(key, parsingClass) {
if(typeof(parsingClass) === 'function') {
if(parsingClass.prototype && typeof(parsingClass.prototype.parse) === 'function') {
this.parsers[key] = {
class: parsingClass
}
} else {
this.parsers[key] = parsingClass;
}
return;
}
return console.warn('WARN: The parsing class ' + parsingClass.constructor.name + " has no method parse, omitting");
}
loadParser(parser) {
if(!this.parsers[parser]) {
return function(content) {
console.warn('WARN: The requested parser "' + parser + '" could not be found. Be sure to register it!');
return entities.encode(content);
};
}
if(typeof(this.parsers[parser]) === 'function') {
return this.parsers[parser];
}
if(!this.parsers[parser].instance) {
this.parsers[parser].instance = Object.create(this.parsers[parser].class.prototype);
this.parsers[parser].instance.init(this.assembler);
}
return this.parsers[parser].instance.parse;
}
}
module.exports = new Parser;