Initial commit
[yaffs-website] / node_modules / ajv / scripts / compile-dots.js
1 //compile doT templates to js functions
2
3 var glob = require('glob')
4   , fs = require('fs')
5   , path = require('path')
6   , doT = require('dot')
7   , beautify = require('js-beautify').js_beautify;
8
9 var defsRootPath = process.argv[2] || path.join(__dirname, '../lib');
10
11 var defs = {};
12 var defFiles = glob.sync('./dot/**/*.def', { cwd: defsRootPath });
13 defFiles.forEach(function (f) {
14   var name = path.basename(f, '.def');
15   defs[name] = fs.readFileSync(path.join(defsRootPath, f));
16 });
17
18 var filesRootPath = process.argv[3] || path.join(__dirname, '../lib');
19 var files = glob.sync('./dot/**/*.jst', { cwd: filesRootPath });
20
21 var dotjsPath = path.join(filesRootPath, './dotjs');
22 try { fs.mkdirSync(dotjsPath); } catch(e) {}
23
24 console.log('\n\nCompiling:');
25
26 var FUNCTION_NAME = /function\s+anonymous\s*\(it[^)]*\)\s*{/;
27 var OUT_EMPTY_STRING = /out\s*\+=\s*'\s*';/g;
28 var ISTANBUL = /\'(istanbul[^']+)\';/g;
29 var VARS = ['$errs', '$valid', '$lvl', '$data', '$dataLvl',
30             '$errorKeyword', '$closingBraces', '$schemaPath'];
31
32 files.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 });