-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
557 lines (459 loc) · 12.3 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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
'use strict';
var events = require('events'),
recache = require('recache');
// SimpleT prototype constructor
var simplet = function (directory, options, callback) {
var close = '%>',
debug = false,
extension = 'ejs',
globals = {},
open = '<%',
that = this;
// Set default arguments
if (typeof directory === 'string') {
if (typeof options === 'function') {
callback = options;
options = {};
}
} else if (typeof directory === 'object') {
if (typeof options === 'function') {
callback = options;
}
options = directory;
directory = '';
} else if (typeof directory === 'function') {
callback = directory;
options = {};
directory = '';
} else if (!options || typeof options !== 'object') {
options = {};
}
// Get a valid opening template separator
if (options.open && typeof options.open === 'string') {
open = options.open;
}
// Get a valid closing template separator
if (options.close && typeof options.close === 'string') {
close = options.close;
}
// Get a valid extension
if (options.extension && typeof options.extension === 'string') {
extension = options.extension;
}
// Get debug option value
if (options.debug === true) {
debug = true;
}
// Copy global values
if (options.globals && typeof options.globals === 'object') {
Object.keys(options.globals).forEach(function (key) {
globals[key] = options.globals[key];
});
}
// Set options for the engine
Object.defineProperties(this, {
close: {
value: close
},
container: {
value: {}
},
debug: {
value: debug
},
extension: {
value: extension
},
globals: {
value: globals
},
open: {
value: open
}
});
// Check for cache
if (directory && typeof directory === 'string') {
recache(directory, {
files: RegExp('^.+\\.' + extension + '$')
}).on('error', function (error) {
that.emit('error', error);
}).on('ready', function () {
if (typeof callback === 'function') {
callback(that);
}
}).on('file', function (file) {
that.template(file.location, file.content.toString());
}).on('change', function (element) {
if (element.stats.isFile()) {
that.template(element.location, element.content.toString());
}
}).on('unlink', function (element) {
if (element.stats.isFile()) {
that.clear(element.location);
}
});
} else if (typeof callback === 'function') {
callback(this);
}
};
// The list of XML characters that must be escaped
simplet.escapeXMLChars = {
'"': '"',
'&': '&',
'\'': ''',
'<': '<',
'>': '>'
};
// Regular expression to match escaped XML characters
simplet.escapeXMLRe = /[&<>'"]/g;
// Escapes XML characters from the provided string
simplet.escapeXML = function (string) {
return string.replace(simplet.escapeXMLRe, function (chr) {
return simplet.escapeXMLChars[chr];
});
};
// Catch error and prepare an expanded result if in debug mode
simplet.catchError = function (template, debug, error) {
var end = 0,
original = template.original,
result = 'Template Error\n',
start = 0;
// Prepare final result structure
if (debug) {
result += template.location + ':' + (error.line + 1) + '\n\n';
// Check for runtime errors to prepare expanded result
if (!(error instanceof SyntaxError)) {
// Prepare the start and the end position of the template fragment
start = Math.max(0, Math.min(error.line - 2, original.length - 5));
end = Math.min(start + 5, original.length);
// Get the template fragment and mark the error line
result += original.slice(start, end).map(function (line, index) {
var current = start + index,
count = String(current + 1);
// Check for the length of the line index to align it
if (count.length < String(end).length) {
count = ' ' + count;
}
// Add the indicator of the error line
if (current === error.line) {
count = '> ' + count;
} else {
count = ' ' + count;
}
return count + ' | ' + line.slice(0, 80 - count.length);
}).join('\n') + '\n\n';
}
// Check if there is a stack defined for this error to add it
if (error.stack) {
result += error.stack;
} else {
result += error.name + ': ' + error.message;
}
} else {
result += 'enable debug mode for expanded result';
}
return result;
};
// Normalize location path to be used in the internal cache
simplet.normalizePath = function (location, extension) {
var isAbsolute = (location[0] === '/'),
index = 0,
parts = location.split('/'),
part = parts[0],
length = parts.length,
result = [],
trailingSlash = (location && (location[location.length - 1] === '/'));
// Loop through location parts
while (index < length) {
// Skip empty or dir parts
if (part && part !== '.') {
if (part === '..') {
if (result.length && result[result.length - 1] !== '..') {
result.pop();
} else if (!isAbsolute) {
result.push('..');
}
} else {
result.push(part);
}
}
// Get the index of the next part
index++;
// Get the next part
part = parts[index];
}
// Join the parts to form the normalized location
location = result.join('/');
// Check for absolute location or empty location
if (!location && !isAbsolute) {
location = '.';
}
// Add the trailing slash if needed
if (location && trailingSlash) {
location += '/';
}
// Add the root slash for absolute location
if (isAbsolute) {
location = '/' + location;
}
// Add extension to the location string
if (location.substr(- extension.length - 1) !== '.' + extension) {
location += '.' + extension;
}
return location;
};
// Inherit from events.EventEmitter
simplet.prototype = Object.create(events.EventEmitter.prototype, {
constructor: {
value: simplet
}
});
// Remove the template from the provided location
simplet.prototype.clear = function (location) {
if (location && typeof location === 'string') {
delete this.container[location];
}
};
// Render templates from files
simplet.prototype.render = function (source, imports) {
var args = [],
context = {},
extension = this.extension,
globals = this.globals,
key = null,
result = '',
template = null,
that = this,
values = [];
// Includes content from other sources
context.include = function (location) {
// Check for relative location
if (location[0] !== '/') {
location = source.substr(0, source.lastIndexOf('/') + 1) + location;
}
// Normalize location and add extension
location = simplet.normalizePath(location, extension);
// Render the template from the provided location
result += that.render(location, imports);
};
// Adds values to the result
context.print = function () {
var index = 0,
length = arguments.length;
// Loop through all arguments
while (index < length) {
// Stingify non-string arguments and concatenate all arguments
if (typeof arguments[index] === 'string') {
result += arguments[index];
} else if (arguments[index] === undefined) {
result += '';
} else {
result += JSON.stringify(arguments[index]);
}
// Get the index of the next argument
index++;
}
};
// Adds values to the result but escapes XML characters
context.printx = function () {
var index = 0,
length = arguments.length;
// Loop through all arguments
while (index < length) {
// Stingify non-string arguments and concatenate all arguments
if (typeof arguments[index] === 'string') {
result += simplet.escapeXML(arguments[index]);
} else if (arguments[index] === undefined) {
result += '';
} else {
result += simplet.escapeXML(JSON.stringify(arguments[index]));
}
// Get the index of the next argument
index++;
}
};
// Set imports default object
if (!imports || typeof imports !== 'object') {
imports = {};
}
// Add the global values to the context
for (key in globals) {
if (!imports[key] && !context[key]) {
if (typeof globals[key] === 'function') {
context[key] = globals[key].bind(context);
} else {
context[key] = globals[key];
}
}
}
// Add the imported values to the context
for (key in imports) {
if (!context[key]) {
if (typeof imports[key] === 'function') {
context[key] = imports[key].bind(context);
} else {
context[key] = imports[key];
}
}
}
// Prepare the arguments and their values
for (key in context) {
args.push(key);
values.push(context[key]);
}
// Get the template object
template = this.container[simplet.normalizePath(source, extension)];
// Execute the template body
if (template) {
try {
Function(args, template.compiled).apply(context, values);
} catch (error) {
result = simplet.catchError(template, this.debug, error);
}
} else if (this.debug) {
result = 'Template "' + source + '" was not found';
} else {
result = 'Template not found';
}
return result;
};
// Create a new template
simplet.prototype.template = function (location, content) {
var buffer = '',
close = this.close,
csize = close.length,
current = content[0],
index = 0,
line = 0,
open = this.open,
osize = open.length,
result = '',
skip = false,
statement = false;
// Add the line index at the beginning for error handling in debug mode
if (this.debug) {
result += 'var _l_=0;try{';
}
// Parse char by char
while (current) {
// Found code delimiter
if (content.substr(index, osize) === open) {
// Skip open delimiter and get the next character
index += osize;
current = content[index];
// Concatenate the buffer if it exists
if (buffer) {
result += 'print(\'' + buffer + '\');';
buffer = '';
}
// Add the line index before the code block
if (this.debug && line > 0) {
result += '_l_=' + line + ';';
}
// Check for include and print statements
if (current === '-' || current === '=' || current === '@') {
// Prepare the print expression
if (current === '-') {
result += 'print(';
} else if (current === '=') {
result += 'printx(';
} else if (current === '@') {
result += 'include(';
}
// Set statement flag and get next character
statement = true;
index++;
current = content[index];
} else if (current === '#') {
skip = true;
index++;
current = content[index];
}
// Get the characterss of the code
while (current && content.substr(index, csize) !== close) {
// Check for end of line
if (['\n', '\r', '\u2028', '\u2029'].indexOf(current) >= 0) {
// Increment line index in debug mode
if (this.debug) {
line++;
}
// Check for DOS end of line
if (current === '\r' && content[index + 1] === '\n') {
index++;
}
// Use only Unix end of line
if (!skip) {
buffer += '\n';
}
} else if (!skip) {
buffer += current;
}
// Get the next character
index++;
current = content[index];
}
// Remove redundant whitespace
result += buffer.trim();
// Close current statement
if (statement) {
result += ');';
statement = false;
} else if (skip) {
skip = false;
} else {
result += '\n';
}
// Skip the close delimiter and remove whitespace
index += csize;
buffer = '';
} else {
// Get all non-code characters
if (['\n', '\r', '\u2028', '\u2029'].indexOf(current) >= 0) {
// Increment line index in debug mode
if (this.debug) {
line++;
}
// Use only Unix end of line
buffer += '\\n';
// Check for DOS end of line
if (current === '\r' && content[index + 1] === '\n') {
index++;
}
} else {
// Escape for quote and backslash
if (current === '\'' || current === '\\') {
buffer += '\\';
}
// Add current character to the buffer
buffer += current;
}
// Get next index
index++;
}
// Get next character
current = content[index];
}
// Concatenate the buffer if it exists
if (buffer) {
result += 'print(\'' + buffer + '\');';
buffer = '';
}
// Remove redundant whitespace
result = result.trim();
// Add the ending for the error handling in debug mode
if (this.debug) {
result += '}catch(e){e.line=_l_;throw e}';
}
// Normalize location
location = simplet.normalizePath(location, this.extension);
// Save the original and the compiled content of the template
this.container[location] = {
compiled: result,
location: location,
original: content.split(/\r\n|\n|\r|\u2028|\u2029/)
};
};
// Export a new simpleT instance
module.exports = function (directory, options, callback) {
return new simplet(directory, options, callback);
};