summaryrefslogtreecommitdiffstats
path: root/lib/precompiler.js
blob: 2809b1b50f502776b93f476ba6524b5630ae8e84 (plain)
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
/*eslint-disable no-console */
import fs from 'fs';
import * as Handlebars from './handlebars';
import {basename} from 'path';
import {SourceMapConsumer, SourceNode} from 'source-map';
import uglify from 'uglify-js';

module.exports.loadTemplates = function(opts) {
  // Build file extension pattern
  let extension = (opts.extension || 'handlebars').replace(/[\\^$*+?.():=!|{}\-\[\]]/g, function(arg) { return '\\' + arg; });
  extension = new RegExp('\\.' + extension + '$');

  let ret = [];
  function processTemplate(template, root) {
    let path = template,
        stat;
    try {
      stat = fs.statSync(template);
    } catch (err) {
      throw new Handlebars.Exception(`Unable to open template file "${template}"`);
    }

    if (stat.isDirectory()) {
      opts.hasDirectory = true;

      fs.readdirSync(template).map(function(file) {
        let childPath = template + '/' + file;

        if (extension.test(childPath) || fs.statSync(childPath).isDirectory()) {
          processTemplate(childPath, root || template);
        }
      });
    } else {
      let data = fs.readFileSync(path, 'utf8');

      if (opts.bom && data.indexOf('\uFEFF') === 0) {
        data = data.substring(1);
      }

      // Clean the template name
      if (!root) {
        template = basename(template);
      } else if (template.indexOf(root) === 0) {
        template = template.substring(root.length + 1);
      }
      template = template.replace(extension, '');

      ret.push({
        path: path,
        name: template,
        source: data
      });
    }
  }
  opts.templates.forEach(function(template) {
    processTemplate(template, opts.root);
  });
  opts.templates = ret;
};

module.exports.cli = function(opts) {
  if (opts.version) {
    console.log(Handlebars.VERSION);
    return;
  }

  if (!opts.templates.length && !opts.hasDirectory) {
    throw new Handlebars.Exception('Must define at least one template or directory.');
  }

  if (opts.simple && opts.min) {
    throw new Handlebars.Exception('Unable to minimize simple output');
  }
  if (opts.simple && (opts.templates.length !== 1 || opts.hasDirectory)) {
    throw new Handlebars.Exception('Unable to output multiple templates in simple mode');
  }

  // Convert the known list into a hash
  let known = {};
  if (opts.known && !Array.isArray(opts.known)) {
    opts.known = [opts.known];
  }
  if (opts.known) {
    for (let i = 0, len = opts.known.length; i < len; i++) {
      known[opts.known[i]] = true;
    }
  }

  let output = new SourceNode();
  if (!opts.simple) {
    if (opts.amd) {
      output.add('define([\'' + opts.handlebarPath + 'handlebars.runtime\'], function(Handlebars) {\n  Handlebars = Handlebars["default"];');
    } else if (opts.commonjs) {
      output.add('var Handlebars = require("' + opts.commonjs + '");');
    } else {
      output.add('(function() {\n');
    }
    output.add('  var template = Handlebars.template, templates = ');
    if (opts.namespace) {
      output.add(opts.namespace);
      output.add(' = ');
      output.add(opts.namespace);
      output.add(' || ');
    }
    output.add('{};\n');
  }

  opts.templates.forEach(function(template) {
    let options = {
      knownHelpers: known,
      knownHelpersOnly: opts.o
    };

    if (opts.map) {
      options.srcName = template.path;
    }
    if (opts.data) {
      options.data = true;
    }

    let precompiled = Handlebars.precompile(template.source, options);

    // If we are generating a source map, we have to reconstruct the SourceNode object
    if (opts.map) {
      let consumer = new SourceMapConsumer(precompiled.map);
      precompiled = SourceNode.fromStringWithSourceMap(precompiled.code, consumer);
    }

    if (opts.simple) {
      output.add([precompiled, '\n']);
    } else if (opts.partial) {
      if (opts.amd && (opts.templates.length == 1 && !opts.hasDirectory)) {
        output.add('return ');
      }
      output.add(['Handlebars.partials[\'', template.name, '\'] = template(', precompiled, ');\n']);
    } else {
      if (opts.amd && (opts.templates.length == 1 && !opts.hasDirectory)) {
        output.add('return ');
      }
      output.add(['templates[\'', template.name, '\'] = template(', precompiled, ');\n']);
    }
  });

  // Output the content
  if (!opts.simple) {
    if (opts.amd) {
      if (opts.templates.length > 1 || (opts.templates.length == 1 && opts.hasDirectory)) {
        if (opts.partial) {
          output.add('return Handlebars.partials;\n');
        } else {
          output.add('return templates;\n');
        }
      }
      output.add('});');
    } else if (!opts.commonjs) {
      output.add('})();');
    }
  }


  if (opts.map) {
    output.add('\n//# sourceMappingURL=' + opts.map + '\n');
  }

  output = output.toStringWithSourceMap();
  output.map = output.map + '';

  if (opts.min) {
    output = uglify.minify(output.code, {
      fromString: true,

      outSourceMap: opts.map,
      inSourceMap: JSON.parse(output.map)
    });
    if (opts.map) {
      output.code += '\n//# sourceMappingURL=' + opts.map + '\n';
    }
  }

  if (opts.map) {
    fs.writeFileSync(opts.map, output.map, 'utf8');
  }
  output = output.code;

  if (opts.output) {
    fs.writeFileSync(opts.output, output, 'utf8');
  } else {
    console.log(output);
  }
};