UNPKG

2 kBJavaScriptView Raw
1//compile doT templates to js functions
2
3var glob = require('glob')
4 , fs = require('fs')
5 , path = require('path')
6 , doT = require('dot')
7 , beautify = require('js-beautify').js_beautify;
8
9var defsRootPath = process.argv[2] || path.join(__dirname, '../lib');
10
11var defs = {};
12var defFiles = glob.sync('./dot/**/*.def', { cwd: defsRootPath });
13defFiles.forEach(function (f) {
14 var name = path.basename(f, '.def');
15 defs[name] = fs.readFileSync(path.join(defsRootPath, f));
16});
17
18var filesRootPath = process.argv[3] || path.join(__dirname, '../lib');
19var files = glob.sync('./dot/**/*.jst', { cwd: filesRootPath });
20
21var dotjsPath = path.join(filesRootPath, './dotjs');
22try { fs.mkdirSync(dotjsPath); } catch(e) {}
23
24console.log('\n\nCompiling:');
25
26var FUNCTION_NAME = /function\s+anonymous\s*\(it[^)]*\)\s*{/;
27var OUT_EMPTY_STRING = /out\s*\+=\s*'\s*';/g;
28var ISTANBUL = /\'(istanbul[^']+)\';/g;
29var VARS = ['$errs', '$valid', '$lvl', '$data', '$dataLvl',
30 '$errorKeyword', '$closingBraces', '$schemaPath'];
31
32files.forEach(function (f) {
33 var keyword = path.basename(f, '.jst');
34 var targetPath = path.join(dotjsPath, keyword + '.js');
35 var template = fs.readFileSync(path.join(filesRootPath, f));
36 var code = doT.compile(template, defs);
37 code = code.toString()
38 .replace(OUT_EMPTY_STRING, '')
39 .replace(FUNCTION_NAME, 'function generate_' + keyword + '(it, $keyword) {')
40 .replace(ISTANBUL, '/* $1 */');
41 VARS.forEach(removeUnusedVar);
42 code = "'use strict';\nmodule.exports = " + code;
43 code = beautify(code, { indent_size: 2 }) + '\n';
44 fs.writeFileSync(targetPath, code);
45 console.log('compiled', keyword);
46
47 function removeUnusedVar(v) {
48 v = v.replace(/\$/g, '\\$$');
49 var regexp = new RegExp(v + '[^A-Za-z0-9_$]', 'g');
50 var count = (code.match(regexp) || []).length;
51 if (count == 1) {
52 regexp = new RegExp('var\\s+' + v + '\\s*=[^;]+;|var\\s+' + v + ';');
53 code = code.replace(regexp, '');
54 }
55 }
56});