UNPKG

2.15 kBJavaScriptView Raw
1/**
2 * @license
3 * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
4 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
5 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
6 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
7 * Code distributed by Google as part of the polymer project is also
8 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
9 */
10
11// jshint node: true
12'use strict';
13
14var dom5 = require('dom5');
15var pred = dom5.predicates;
16
17var inlineScriptFinder = pred.AND(
18 pred.hasTagName('script'),
19 pred.OR(
20 pred.NOT(
21 pred.hasAttr('type')
22 ),
23 pred.hasAttrValue('type', 'application/javascript'),
24 pred.hasAttrValue('type', 'text/javascript')
25 ),
26 pred.NOT(
27 pred.hasAttr('src')
28 )
29);
30
31var noSemiColonInsertion = /\/\/|;\s*$|\*\/\s*$/;
32
33function split(source, jsFileName) {
34 var doc = dom5.parse(source);
35 var head = dom5.query(doc, pred.hasTagName('head'));
36 var body = dom5.query(doc, pred.hasTagName('body'));
37 var scripts = dom5.queryAll(doc, inlineScriptFinder);
38
39 var contents = [];
40 scripts.forEach(function(sn) {
41 var nidx = sn.parentNode.childNodes.indexOf(sn) + 1;
42 var next = sn.parentNode.childNodes[nidx];
43 dom5.remove(sn);
44 // remove newline after script to get rid of nasty whitespace
45 if (next && dom5.isTextNode(next) && !/\S/.test(dom5.getTextContent(next))) {
46 dom5.remove(next);
47 }
48 var content = dom5.getTextContent(sn).trim();
49 var lines = content.split('\n');
50 var lastline = lines[lines.length - 1];
51 if (!noSemiColonInsertion.test(lastline)) {
52 content += ';';
53 }
54 contents.push(content);
55 });
56
57 var newScript = dom5.constructors.element('script');
58 dom5.setAttribute(newScript, 'src', jsFileName);
59 dom5.append(body, newScript);
60
61 var html = dom5.serialize(doc);
62 // newline + semicolon should be enough to capture all cases of concat
63 var js = contents.join('\n');
64
65 return {
66 html: html,
67 js: js
68 };
69}
70
71module.exports = {
72 split: split
73};