markdown-maker 1.9.2 → 1.10.0

Sign up to get free protection for your applications and to get access to all the features.
package/build/parse.js ADDED
@@ -0,0 +1,281 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.splice = void 0;
4
+ var fs = require("fs"); /* for handling reading of files */
5
+ var path = require("path"); /* for handling file paths */
6
+ var Colors = require("colors.ts"); /* for adding colours to strings */
7
+ Colors.enable();
8
+ var marked = require("marked");
9
+ var commands_1 = require("./commands");
10
+ var TargetType;
11
+ (function (TargetType) {
12
+ TargetType[TargetType["HTML"] = 0] = "HTML";
13
+ TargetType[TargetType["MARKDOWN"] = 1] = "MARKDOWN";
14
+ })(TargetType || (TargetType = {}));
15
+ /* parse some md
16
+ * recursively with extra options */
17
+ var Parser = /** @class */ (function () {
18
+ function Parser(filename, clargs, opts) {
19
+ /* this.working_directory */
20
+ this.file = filename;
21
+ if (!opts)
22
+ opts = {};
23
+ /* the parent parser */
24
+ this.parent = opts.parent;
25
+ this.line_num = 0;
26
+ this.wd = path.dirname(filename);
27
+ this.wd_full = path.resolve(this.wd);
28
+ /* finished blob */
29
+ this.blobs = {};
30
+ /* all options */
31
+ this.opts = {
32
+ defs: {},
33
+ secs: [],
34
+ args: [],
35
+ depth: 0,
36
+ verbose: false,
37
+ debug: false,
38
+ max_depth: 5,
39
+ use_underscore: false,
40
+ toc_level: 3,
41
+ allow_undefined: false,
42
+ html: false,
43
+ watch: false,
44
+ targetType: undefined,
45
+ only_warn: false,
46
+ parent: undefined,
47
+ isFileCallback: function (f) {
48
+ if (!fs.existsSync(f))
49
+ return false;
50
+ return fs.readFileSync(f, "utf-8") + "\n";
51
+ },
52
+ };
53
+ if (!clargs) {
54
+ clargs = {};
55
+ }
56
+ /* append all commandline arguments to this */
57
+ Object.assign(this.opts, clargs);
58
+ Object.assign(this.opts, opts);
59
+ this.raw = this.opts.isFileCallback(filename) || filename;
60
+ }
61
+ /**
62
+ * parse wrapper for handling
63
+ * preprocessing, parsing and postprocess
64
+ **/
65
+ Parser.prototype.parse = function () {
66
+ (0, commands_1.load_extensions)(this);
67
+ if (this.opts.verbose || this.opts.debug) {
68
+ console.log(Colors.colors("magenta", "parsing " + this.file + ": depth=" + this.opts.depth));
69
+ }
70
+ if (this.opts.debug) {
71
+ console.log("Parsing options:");
72
+ console.log(this.opts);
73
+ }
74
+ /* reset sections for beginning parse */
75
+ if (this.opts.depth === 0)
76
+ this.opts.secs = [];
77
+ var __blob;
78
+ /* apply preproccessing to raw file */
79
+ __blob = this.preprocess(this.raw);
80
+ /* main parser instance call */
81
+ __blob = this.mainparse(__blob);
82
+ /**
83
+ * apply postprocessing after */
84
+ __blob = this.postprocess(__blob);
85
+ return __blob;
86
+ };
87
+ Parser.prototype.mainparse = function (blob) {
88
+ var _this = this;
89
+ if (this.opts.verbose || this.opts.debug) {
90
+ console.debug("beginning mainparse of '".concat(this.file, "'").blue);
91
+ }
92
+ /* main parser instance loop */
93
+ blob.split("\n").forEach(function (line, lnum) {
94
+ _this.line_num = lnum;
95
+ /* if line looks like a title */
96
+ var titleMatch = line.trim().match(/^(#+) (.+)$/);
97
+ if (titleMatch) {
98
+ if (_this.opts.verbose || _this.opts.debug)
99
+ console.log("found toc element: " + line);
100
+ /* implement toc level */
101
+ var level = titleMatch[1].length;
102
+ var title = titleMatch[2];
103
+ _this.opts.secs.push({ level: level, title: title });
104
+ if (_this.opts.debug) {
105
+ console.log("updated sections:", { level: level, title: title });
106
+ }
107
+ }
108
+ });
109
+ return this.parse_commands(blob, commands_1.commands.parse);
110
+ };
111
+ Parser.prototype.preprocess = function (blob) {
112
+ if (this.opts.verbose || this.opts.debug) {
113
+ console.debug("beginning preprocess of '".concat(this.file, "'").blue);
114
+ }
115
+ return this.parse_commands(blob, commands_1.commands.preparse);
116
+ };
117
+ Parser.prototype.postprocess = function (blob) {
118
+ if (this.opts.verbose || this.opts.debug) {
119
+ console.debug("beginning postprocess of '".concat(this.file, "'").blue);
120
+ }
121
+ blob = this.parse_commands(blob, commands_1.commands.postparse);
122
+ /* remove double empty lines */
123
+ blob = this.remove_double_blank_lines(blob);
124
+ blob = blob.trimEnd() + "\n\n";
125
+ return blob;
126
+ };
127
+ Parser.prototype.parse_commands = function (blob, commands) {
128
+ var _this = this;
129
+ commands.forEach(function (command) {
130
+ /* Add global flag to RegExp */
131
+ var re = new RegExp(command.validator.source, (command.validator.flags || "") + "g");
132
+ blob = blob.replace(re, function () {
133
+ var args = [];
134
+ for (var _i = 0; _i < arguments.length; _i++) {
135
+ args[_i] = arguments[_i];
136
+ }
137
+ return command.act(args, _this) || "";
138
+ });
139
+ });
140
+ return blob;
141
+ };
142
+ Parser.prototype.parse_all_commands = function (blob, commands) {
143
+ var _this = this;
144
+ Object.keys(commands).forEach(function (key) {
145
+ blob = _this.parse_commands(blob, commands[key]);
146
+ });
147
+ return blob;
148
+ };
149
+ Parser.prototype.titleId = function (title) {
150
+ var sep = this.opts.use_underscore ? "_" : "-";
151
+ title = title
152
+ .toLowerCase()
153
+ .replace(/[^\w\s]+/g, "")
154
+ .replace(/[\s_]+/g, sep);
155
+ return title;
156
+ };
157
+ Parser.prototype.gen_toc = function () {
158
+ var _this = this;
159
+ var __blob = [];
160
+ var tabSize = 2;
161
+ var beg = "* ";
162
+ var hor = " ".repeat(tabSize);
163
+ this.opts.secs.forEach(function (sec) {
164
+ if (sec.level > _this.opts.toc_level)
165
+ return;
166
+ var title = sec.title.replace(/_/g, " ");
167
+ title = _this.parse_all_commands(title, commands_1.commands);
168
+ var link = _this.titleId(title);
169
+ var __line = hor.repeat(Math.max(sec.level - 1, 0)) + beg + "[".concat(title, "](#").concat(link, ")");
170
+ __blob.push(__line);
171
+ });
172
+ return __blob.join("\n");
173
+ };
174
+ Parser.prototype.line_num_from_index = function (index) {
175
+ return this.raw.substring(0, index).split("\n").length + 1;
176
+ };
177
+ Parser.prototype.remove_double_blank_lines = function (blob) {
178
+ /* replace all triple newlines, and EOF by double newline */
179
+ blob = blob.replace(/(\r\n|\n){3,}/g, "\n\n");
180
+ return blob;
181
+ };
182
+ /* output the parsed document to bundle */
183
+ Parser.prototype.to = function (bundleName, callback) {
184
+ var dir = path.dirname(bundleName);
185
+ if (callback === undefined)
186
+ callback = function () { };
187
+ if (!fs.existsSync(dir)) {
188
+ fs.mkdirSync(dir, { recursive: true });
189
+ }
190
+ if (!this.opts.html) {
191
+ this.get(TargetType.MARKDOWN, function (blob) {
192
+ fs.writeFile(bundleName, blob, function () { return callback(bundleName); });
193
+ });
194
+ }
195
+ else {
196
+ var htmlFileName_1 = bundleName.replace(".md", ".html");
197
+ fs.writeFile(htmlFileName_1, this.html(), function () { return callback(htmlFileName_1); });
198
+ }
199
+ };
200
+ Parser.prototype.html = function () {
201
+ var htmlFormatted = marked(this.get(TargetType.HTML));
202
+ if (this.opts.watch) {
203
+ return ("<script>w=new WebSocket(\"ws:localhost:7788\");w.addEventListener(\"message\",(e)=>{if(e.data==\"refresh\")location.reload();});</script>\n" +
204
+ htmlFormatted);
205
+ }
206
+ return htmlFormatted;
207
+ };
208
+ Parser.prototype.get = function (targetType, callback) {
209
+ /* If target type is undefined, markdown is the default */
210
+ if (targetType === undefined)
211
+ targetType = TargetType.MARKDOWN;
212
+ if (this.blobs[targetType]) {
213
+ if (callback) {
214
+ callback(this.blobs[targetType]);
215
+ }
216
+ return this.blobs[targetType];
217
+ }
218
+ else {
219
+ try {
220
+ this.opts.targetType = targetType;
221
+ var blob = this.parse();
222
+ this.opts.targetType = undefined;
223
+ if (callback)
224
+ callback(blob);
225
+ return blob;
226
+ }
227
+ catch (error) {
228
+ /* Compile a traceback of error */
229
+ var traceback = "";
230
+ var p = this;
231
+ do {
232
+ if (error instanceof commands_1.MDMError)
233
+ traceback += "\n...on line ".concat(p.line_num_from_index(error.match.index), " in ").concat(p.file).grey(15);
234
+ else
235
+ traceback += "\n...on line ".concat(p.line_num, " in ").concat(p.file).grey(15);
236
+ if (p.parent)
237
+ p = p.parent;
238
+ } while (p.parent);
239
+ error.message += traceback;
240
+ /* only interested in node stacktrace when debugging */
241
+ if (!this.opts.debug)
242
+ error.stack = "";
243
+ if (this.opts.only_warn)
244
+ console.error(error);
245
+ else
246
+ throw error;
247
+ }
248
+ }
249
+ };
250
+ Parser.TOKEN = "#md";
251
+ return Parser;
252
+ }());
253
+ function splice(str, startIndex, width, newSubStr) {
254
+ var start = str.slice(0, startIndex);
255
+ var end = str.slice(startIndex + width);
256
+ return start + newSubStr + end;
257
+ }
258
+ exports.splice = splice;
259
+ /* add extention to marked for classed blockquotes*/
260
+ marked.use({
261
+ renderer: {
262
+ blockquote: function (quote) {
263
+ /* find the ending, and if not, return the default */
264
+ var ending = quote.match(/\{(.+)\}\s*<\/p>/);
265
+ if (!ending)
266
+ return "<blockquote>".concat(quote, "</blockquote>");
267
+ var args = ending[1].split(" ");
268
+ var classes = args.filter(function (arg) { return arg.startsWith("."); });
269
+ var id = args.filter(function (arg) { return arg.startsWith("#"); });
270
+ var classNames = classes.map(function (c) { return c.slice(1); });
271
+ var classText = classes.length > 0 ? "class=\"".concat(classNames.join(" "), "\"") : "";
272
+ var idText = id.length > 0 ? "id=\"".concat(id[0].slice(1), "\"") : "";
273
+ /* remove the ending from the quote */
274
+ quote = quote.replace(/\{(.+)\}\s*<\/p>/, "</p>");
275
+ return "<blockquote ".concat(classText, " ").concat(idText, ">\n").concat(quote.trim(), "</blockquote>");
276
+ },
277
+ },
278
+ });
279
+ module.exports = Parser;
280
+ exports.default = Parser;
281
+ //# sourceMappingURL=parse.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parse.js","sourceRoot":"","sources":["../src/parse.ts"],"names":[],"mappings":";;;AAAA,IAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,mCAAmC;AAC7D,IAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,6BAA6B;AAE3D,kCAAqC,CAAC,mCAAmC;AACzE,MAAM,CAAC,MAAM,EAAE,CAAC;AAChB,IAAM,MAAM,GAAG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AAe,MAAM,CAAC"}
@@ -0,0 +1,10 @@
1
+ declare const templates: {
2
+ [key: string]: string;
3
+ };
4
+ /**
5
+ * Function to add a template to the templates object. Similar to definitions and variables, but reside as an extension.
6
+ * @param name The name of the template
7
+ * @param content The replacement string
8
+ */
9
+ export declare function new_template(name: string, content: string): void;
10
+ export default templates;
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.new_template = void 0;
4
+ var templates = {};
5
+ /**
6
+ * Function to add a template to the templates object. Similar to definitions and variables, but reside as an extension.
7
+ * @param name The name of the template
8
+ * @param content The replacement string
9
+ */
10
+ function new_template(name, content) {
11
+ templates[name] = content;
12
+ }
13
+ exports.new_template = new_template;
14
+ /* initialize default templates */
15
+ var presentation_template = require("../src/templates/presentation.js");
16
+ var mathjax_template = require("../src/templates/mathjax.js");
17
+ new_template("presentation", presentation_template);
18
+ new_template("mathjax", mathjax_template);
19
+ exports.default = templates;
20
+ //# sourceMappingURL=templates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templates.js","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":";;;AAAA,IAAM,SAAS,GAA8B,EAAE,CAAC;AAEhD;;;;GAIG;AACH,SAAgB,YAAY,CAAC,IAAY,EAAE,OAAe;IACtD,SAAS,CAAC,IAAI,CAAC,GAAG,OAAO,CAAC;AAC9B,CAAC;AAFD,oCAEC;AAED,kCAAkC;AAClC,IAAM,qBAAqB,GAAG,OAAO,CAAC,kCAAkC,CAAC,CAAC;AAC1E,IAAM,gBAAgB,GAAG,OAAO,CAAC,6BAA6B,CAAC,CAAC;AAChE,YAAY,CAAC,cAAc,EAAE,qBAAqB,CAAC,CAAC;AACpD,YAAY,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;AAE1C,kBAAe,SAAS,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "markdown-maker",
3
- "version": "1.9.2",
3
+ "version": "1.10.0",
4
4
  "description": "",
5
5
  "main": "src/cltool.ts",
6
6
  "bin": {
@@ -23,7 +23,7 @@
23
23
  ]
24
24
  },
25
25
  "scripts": {
26
- "test": "mocha",
26
+ "test": "mocha --require test/hooks.js",
27
27
  "test:yarn": "mocha",
28
28
  "bundle": "tsc --project tsconfig.json",
29
29
  "main": "node build/cltool.js document/main.md -o dist/bundle.md --debug",
package/src/cltool.ts CHANGED
@@ -11,7 +11,7 @@ const { version } = require("../package.json"); /* package version number */
11
11
  const choki = require("chokidar");
12
12
 
13
13
  export const argParser = new ArgumentParser({
14
- description: "Markdown bundler, with extra options",
14
+ description: "Markdown bundler, with extra options. Extension file is loaded from ./extensions.js, if it exists",
15
15
  prog: "mdparse",
16
16
  });
17
17
 
@@ -92,6 +92,14 @@ function main() {
92
92
  clargs = argParser.parse_args();
93
93
  }
94
94
 
95
+ /* if src is init, create config file and exit */
96
+ if (clargs.src == "init") {
97
+ const template = fs.readFileSync(path.join(__dirname, "..", "src", "templates", "configTemplate.json"));
98
+ fs.writeFileSync(configFileName, template);
99
+ fs.writeFileSync("main.md", "# Main\n");
100
+ return;
101
+ }
102
+
95
103
  /* helper method for calling parser */
96
104
  const compile = (source, output, cb?) => {
97
105
  /* load data from file, if it exists,
@@ -140,9 +148,8 @@ function main() {
140
148
 
141
149
  /* compile once */
142
150
  if (!clargs.watch) compile(clargs.src, clargs.output);
143
-
144
151
  /* watch the folder and recompile on change */
145
- if (clargs.watch) {
152
+ else {
146
153
  const srcDirName = path.dirname(clargs.src);
147
154
  console.log(`Watching ${srcDirName} for changes...`.yellow);
148
155
  server = new WebSocketServer({ port: 7788 });
@@ -154,6 +161,7 @@ function main() {
154
161
  console.log(e.message);
155
162
  }
156
163
  }
164
+
157
165
  }
158
166
 
159
167
  /* main entrypoint */
package/src/commands.ts CHANGED
@@ -42,7 +42,7 @@ export class Command {
42
42
  constructor(
43
43
  validator: RegExp,
44
44
  acter: (match: RegExpMatchArray, parser: Parser) => string | void,
45
- type: CommandType,
45
+ type: CommandType
46
46
  ) {
47
47
  this.type = type;
48
48
  this.validator = validator;
@@ -71,7 +71,7 @@ export class Command {
71
71
  new Command(
72
72
  /(\s|^)<(.+)>/,
73
73
  (match, parser) => `${match[1]}#mdvar<${match[2]}>`,
74
- CommandType.PREPARSE,
74
+ CommandType.PREPARSE
75
75
  );
76
76
 
77
77
  /* mddef */
@@ -80,7 +80,7 @@ new Command(
80
80
  (match, parser) => {
81
81
  parser.opts.defs[match[1]] = match[2].replace("_", " ");
82
82
  },
83
- CommandType.PARSE,
83
+ CommandType.PARSE
84
84
  );
85
85
 
86
86
  /* mdvar */
@@ -92,7 +92,7 @@ new Command(
92
92
  throw new Error(`Undefined variable: ${match[1]}`);
93
93
  return (value = value || `<${match[1]}>`);
94
94
  },
95
- CommandType.PARSE,
95
+ CommandType.PARSE
96
96
  );
97
97
 
98
98
  /** mdinclude */
@@ -107,17 +107,31 @@ new Command(
107
107
  }
108
108
 
109
109
  /* get the matching group */
110
- const [_, name, condition] = match;
110
+ let [_, name, condition] = match;
111
111
 
112
112
  /* implement conditional imports */
113
113
  if (condition && !parser.opts.args.includes(condition)) return;
114
114
 
115
+ const fsstat = fs.lstatSync(path.join(parser.wd, name));
116
+ if (fsstat.isDirectory()) {
117
+ /* check if a file with the same name of the
118
+ * exists in the folder */
119
+
120
+ if (fs.existsSync(path.join(parser.wd, name, `${name}.md`))) {
121
+ name = path.join(name, `${name}.md`);
122
+ } else {
123
+ throw new Error(
124
+ `No entry file found in folder "${name}". Looking for "${name}.md"`
125
+ );
126
+ }
127
+ }
128
+
115
129
  const recursiveParser = new Parser(
116
130
  path.join(parser.wd, name),
117
131
  parser.opts,
118
132
  {
119
133
  parent: parser,
120
- },
134
+ }
121
135
  );
122
136
 
123
137
  /* keep the options the same */
@@ -134,7 +148,7 @@ new Command(
134
148
  parser.opts.depth--;
135
149
  return blob;
136
150
  },
137
- CommandType.PARSE,
151
+ CommandType.PARSE
138
152
  );
139
153
 
140
154
  /* mdlabel */
@@ -149,7 +163,7 @@ new Command(
149
163
  parser.opts.secs.push({ level, title });
150
164
  return `<span id="${link}"></span>`;
151
165
  },
152
- CommandType.PREPARSE,
166
+ CommandType.PREPARSE
153
167
  );
154
168
 
155
169
  /* mdref */
@@ -163,7 +177,7 @@ new Command(
163
177
 
164
178
  if (i === parser.opts.secs.length - 1)
165
179
  throw new Error(
166
- `Reference to [${match[1]}] could not be resolved!`,
180
+ `Reference to [${match[1]}] could not be resolved!`
167
181
  );
168
182
  }
169
183
 
@@ -174,12 +188,12 @@ new Command(
174
188
  else if (parser.opts.targetType === TargetType.MARKDOWN)
175
189
  return `[${match[1]}](#${link})`;
176
190
  },
177
- CommandType.PARSE,
191
+ CommandType.PARSE
178
192
  );
179
193
 
180
194
  /* mdtemplate */
181
195
  new Command(
182
- /#mdtemplate<([\w\W]+)>/,
196
+ /#mdtemplate<(\w+?)>/,
183
197
  (match, parser) => {
184
198
  const template = match[1];
185
199
  const replacement = templates[template];
@@ -190,49 +204,39 @@ new Command(
190
204
  throw new MDMError(`Template \"${template}\" not found!`, match);
191
205
  }
192
206
  },
193
- CommandType.PARSE,
207
+ CommandType.PARSE
194
208
  );
195
209
 
196
210
  new Command(
197
211
  /#mdmaketoc(?:<>)?/,
198
212
  (match, parser) => parser.gen_toc(),
199
- CommandType.POSTPARSE,
213
+ CommandType.POSTPARSE
200
214
  );
201
215
 
202
- export function load_extensions(parser: Parser) {
203
- /* global extention */
204
- const global_extensions_path = path.join(process.cwd(), "extensions.js");
205
- if (fs.existsSync(global_extensions_path)) {
206
- const extensions = requireRuntime(global_extensions_path);
216
+ const loaded_extentions: fs.PathLike[] = [];
217
+
218
+ function load_extension(parser: Parser, file: fs.PathLike) {
219
+ if (loaded_extentions.includes(file)) return;
220
+ if (fs.existsSync(file)) {
221
+ const extensions = requireRuntime(file);
222
+ loaded_extentions.push(file);
207
223
  extensions.main(new_template, new_command);
208
224
 
209
225
  if (parser.opts.verbose)
210
- console.log(
211
- `Loaded global extensions from ${global_extensions_path}`
212
- .yellow,
213
- );
226
+ console.log(`Loaded extensions from ${file}`.yellow);
214
227
  } else if (parser.opts.debug) {
215
- console.log(
216
- `No global extensions found at ${global_extensions_path}`.red,
217
- );
228
+ console.log(`No extensions found at ${file}`.red);
218
229
  }
230
+ }
231
+
232
+ export function load_extensions(parser: Parser) {
233
+ /* global extention */
234
+ const global_extensions_path = path.join(__dirname, "extensions.js");
235
+ load_extension(parser, global_extensions_path);
219
236
 
220
237
  /* project extention */
221
238
  const project_extensions_path = path.join(parser.wd_full, "extensions.js");
222
- if (fs.existsSync(project_extensions_path)) {
223
- const extensions = requireRuntime(project_extensions_path);
224
- extensions.main(new_template, new_command);
225
-
226
- if (parser.opts.verbose)
227
- console.log(
228
- `Loaded project extensions from ${project_extensions_path}`
229
- .yellow,
230
- );
231
- } else if (parser.opts.debug) {
232
- console.log(
233
- `No project extensions found at ${project_extensions_path}!`.red,
234
- );
235
- }
239
+ load_extension(parser, project_extensions_path);
236
240
  }
237
241
 
238
242
  /**
@@ -244,7 +248,7 @@ export function load_extensions(parser: Parser) {
244
248
  export function new_command(
245
249
  regex: RegExp,
246
250
  acter: (match: RegExpMatchArray, parser: Parser) => string,
247
- type?: CommandType,
251
+ type?: CommandType
248
252
  ) {
249
253
  new Command(regex, acter, type || CommandType.PARSE);
250
254
  }
package/src/parse.ts CHANGED
@@ -258,27 +258,21 @@ class Parser {
258
258
  /* output the parsed document to bundle */
259
259
  to(bundleName: string, callback: (fileName: string) => void) {
260
260
  const dir = path.dirname(bundleName);
261
- var called = false;
262
- if (callback === undefined) callback = () => {};
261
+ if (callback === undefined) callback = () => { };
263
262
 
264
263
  if (!fs.existsSync(dir)) {
265
264
  fs.mkdirSync(dir, { recursive: true });
266
265
  }
267
- this.get(TargetType.MARKDOWN, (blob) => {
268
- fs.writeFile(bundleName, blob, () => {
269
- if (!this.opts.html) {
270
- callback(bundleName);
271
- called = true;
272
- }
266
+
267
+ if (!this.opts.html) {
268
+ this.get(TargetType.MARKDOWN, (blob) => {
269
+ fs.writeFile(bundleName, blob, () => callback(bundleName));
273
270
  });
274
- });
271
+ }
275
272
 
276
- if (this.opts.html) {
273
+ else {
277
274
  const htmlFileName = bundleName.replace(".md", ".html");
278
- fs.writeFile(htmlFileName, this.html(), () => {
279
- if (!called) callback(htmlFileName);
280
- called = true;
281
- });
275
+ fs.writeFile(htmlFileName, this.html(), () => callback(htmlFileName));
282
276
  }
283
277
  }
284
278
 
@@ -293,7 +287,7 @@ class Parser {
293
287
  return htmlFormatted;
294
288
  }
295
289
 
296
- get(targetType?: TargetType, callback?) {
290
+ get(targetType?: TargetType, callback?: (blob: string) => void): string {
297
291
  /* If target type is undefined, markdown is the default */
298
292
  if (targetType === undefined) targetType = TargetType.MARKDOWN;
299
293
  if (this.blobs[targetType]) {
@@ -307,10 +301,10 @@ class Parser {
307
301
  let blob = this.parse();
308
302
  this.opts.targetType = undefined;
309
303
  if (callback) callback(blob);
310
- return blob;
304
+ return blob
311
305
  } catch (error) {
306
+ /* Compile a traceback of error */
312
307
  let traceback = "";
313
-
314
308
  let p: Parser = this;
315
309
 
316
310
  do {
@@ -324,7 +318,7 @@ class Parser {
324
318
 
325
319
  error.message += traceback;
326
320
 
327
- /* only interested in stacktrace, when debugging */
321
+ /* only interested in node stacktrace when debugging */
328
322
  if (!this.opts.debug) error.stack = "";
329
323
 
330
324
  if (this.opts.only_warn) console.error(error);
@@ -345,7 +339,7 @@ export function splice(
345
339
  return start + newSubStr + end;
346
340
  }
347
341
 
348
- /* add extention to marked */
342
+ /* add extention to marked for classed blockquotes*/
349
343
  marked.use({
350
344
  renderer: {
351
345
  blockquote(quote) {
@@ -0,0 +1,13 @@
1
+ {
2
+ "opts": {
3
+ "src": "main.md",
4
+ "verbose": false,
5
+ "debug": false,
6
+ "output": "dist/bundle.md",
7
+ "max-depth": 3,
8
+ "toc-level": 3,
9
+ "watch": false,
10
+ "html": false,
11
+ "allow-undefined": false
12
+ }
13
+ }