summaryrefslogtreecommitdiffstats
path: root/spec/source-map.js
blob: 54e5e4d91d73f89756cef4b8740f9abbb713945f (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
try {
  if (typeof define !== 'function' || !define.amd) {
    var SourceMap = require('source-map'),
         SourceMapConsumer = SourceMap.SourceMapConsumer;
  }
} catch (err) {
  /* NOP for in browser */
}

describe('source-map', function() {
  if (!Handlebars.precompile || !SourceMap) {
    return;
  }

  it('should safely include source map info', function() {
    var template = Handlebars.precompile('{{hello}}', {destName: 'dest.js', srcName: 'src.hbs'});

    equal(!!template.code, true);
    equal(!!template.map, !CompilerContext.browser);
  });
  it('should map source properly', function() {
    var templateSource = '  b{{hello}}  \n  {{bar}}a {{#block arg hash=(subex 1 subval)}}{{/block}}',
        template = Handlebars.precompile(templateSource, {destName: 'dest.js', srcName: 'src.hbs'});

    if (template.map) {
      var consumer = new SourceMapConsumer(template.map),
          lines = template.code.split('\n'),
          srcLines = templateSource.split('\n'),

          generated = grepLine('"  b"', lines),
          source = grepLine('  b', srcLines);

      var mapped = consumer.originalPositionFor(generated);
      equal(mapped.line, source.line);
      equal(mapped.column, source.column);
    }
  });
});

function grepLine(token, lines) {
  for (var i = 0; i < lines.length; i++) {
    var column = lines[i].indexOf(token);
    if (column >= 0) {
      return {
        line: i + 1,
        column: column
      };
    }
  }
}