-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
166 lines (156 loc) · 6.95 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
const tags = /\{\{|\}\}/;
const escapedChars = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
const escape = s => s.toString().replace(/[&<>\"']/g, m => escapedChars[m]);
const get = (c, p) => (p === "." ? c : p.split(".").reduce((x, k) => x?.[k], c)) ?? "";
// @description parse string arguments
const parseArgs = (argString = "", context = {}, vars = {}) => {
const [t, ...args] = argString.trim().match(/(?:[^\s"]+|"[^"]*")+/g);
const argv = args.filter(a => !a.includes("=")).map(a => parse(a, context, vars));
const opt = Object.fromEntries(args.filter(a => a.includes("=")).map(a => {
const [k, v] = a.split("=");
return [k, parse(v, context, vars)];
}));
return [t, argv, opt];
};
// @description parse a string value to a native type
const parse = (v, context = {}, vars = {}) => {
if ((v.startsWith(`"`) && v.endsWith(`"`)) || /^-?\d+\.?\d*$/.test(v) || v === "true" || v === "false" || v === "null") {
return JSON.parse(v);
}
return (v || "").startsWith("@") ? get(vars, v.slice(1)) : get(context, v || ".");
};
// @description tiny front-matter parser
const frontmatter = (str = "", parser = null) => {
let body = (str || "").trim(), data = {};
const matches = Array.from(body.matchAll(/^(--- *)/gm))
if (matches?.length === 2 && matches[0].index === 0) {
const front = body.substring(0 + matches[0][1].length, matches[1].index).trim();
body = body.substring(matches[1].index + matches[1][1].length).trim();
data = typeof parser === "function" ? parser(front) : front;
}
return {body, data};
};
// @description default helpers
const defaultHelpers = {
"each": p => {
const items = typeof p.args[0] === "object" ? Object.entries(p.args[0] || {}) : [];
const limit = Math.min(items.length - (p.opt.skip || 0), p.opt.limit || items.length);
return items.slice(p.opt.skip || 0, (p.opt.skip || 0) + limit)
.map((item, index) => p.fn(item[1], {index: index, key: item[0], value: item[1], first: index === 0, last: index === items.length - 1}))
.join("");
},
"if": p => !!p.args[0] ? p.fn(p.context) : "",
"unless": p => !!!p.args[0] ? p.fn(p.context) : "",
"eq": p => p.args[0] === p.args[1] ? p.fn(p.context) : "",
"ne": p => p.args[0] !== p.args[1] ? p.fn(p.context) : "",
"with": p => p.fn(p.args[0]),
};
// @description create a new instance of mikel
const create = (template = "", options = {}) => {
// initialize internal context
const helpers = Object.assign({}, defaultHelpers, options?.helpers || {});
const partials = options?.partials || {};
const functions = options?.functions || {};
// internal method to compile the template
const compile = (tokens, output, context, vars, index = 0, section = "") => {
let i = index;
while (i < tokens.length) {
if (i % 2 === 0) {
output.push(tokens[i]);
}
else if (tokens[i].startsWith("@")) {
output.push(get(vars, tokens[i].slice(1).trim() ?? "_") ?? "");
}
else if (tokens[i].startsWith("!")) {
output.push(get(context, tokens[i].slice(1).trim()));
}
else if (tokens[i].startsWith("#") && typeof helpers[tokens[i].slice(1).trim().split(" ")[0]] === "function") {
const [t, args, opt] = parseArgs(tokens[i].slice(1), context, vars);
const j = i + 1;
output.push(helpers[t]({
args: args,
opt: opt,
context: context,
fn: (blockContext = {}, blockVars = {}, blockOutput = []) => {
i = compile(tokens, blockOutput, blockContext, {...vars, ...blockVars, root: vars.root}, j, t);
return blockOutput.join("");
},
}));
// Make sure that this block is executed at least once
if (i + 1 === j) {
i = compile(tokens, [], {}, {}, j, t);
}
}
else if (tokens[i].startsWith("#") || tokens[i].startsWith("^")) {
const t = tokens[i].slice(1).trim();
const value = get(context, t);
const negate = tokens[i].startsWith("^");
if (!negate && value && Array.isArray(value)) {
const j = i + 1;
(value.length > 0 ? value : [""]).forEach(item => {
i = compile(tokens, value.length > 0 ? output : [], item, vars, j, t);
});
}
else {
const includeOutput = (!negate && !!value) || (negate && !!!value);
i = compile(tokens, includeOutput ? output : [], context, vars, i + 1, t);
}
}
else if (tokens[i].startsWith(">")) {
const [t, args, opt] = parseArgs(tokens[i].slice(1), context, vars);
if (typeof partials[t] === "string") {
const newCtx = args.length > 0 ? args[0] : (Object.keys(opt).length > 0 ? opt : context);
compile(partials[t].split(tags), output, newCtx, vars, 0, "");
}
}
else if (tokens[i].startsWith("=")) {
const [t, args, opt] = parseArgs(tokens[i].slice(1), context, vars);
if (typeof functions[t] === "function") {
output.push(functions[t]({args, opt, context}) || "");
}
}
else if (tokens[i].startsWith("/")) {
if (tokens[i].slice(1).trim() !== section) {
throw new Error(`Unmatched section end: {{${tokens[i]}}}`);
}
break;
}
else {
output.push(escape(get(context, tokens[i].trim())));
}
i = i + 1;
}
return i;
};
// entry method to compile the template with the provided data object
const compileTemplate = (data = {}, output = []) => {
compile(template.split(tags), output, data, {root: data}, 0, "");
return output.join("");
};
// assign api methods and return method to compile the template
return Object.assign(compileTemplate, {
addHelper: (name, fn) => helpers[name] = fn,
removeHelper: name => delete helpers[name],
addFunction: (name, fn) => functions[name] = fn,
removeFunction: name => delete functions[name],
addPartial: (name, partial) => partials[name] = partial,
removePartial: name => delete partials[name],
});
};
// @description main compiler function
const mikel = (template = "", data = {}, options = {}) => {
return create(template, options)(data);
};
// @description assign utilities
mikel.create = create;
mikel.escape = escape;
mikel.get = get;
mikel.parse = parse;
mikel.frontmatter = frontmatter;
export default mikel;