-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathinjector-transform.js
82 lines (67 loc) · 2.73 KB
/
injector-transform.js
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
/*!
* Module dependencies.
*/
var fs = require('fs'),
archiver = require('archiver'),
path = require('path'),
util = require('util'),
cspParser = require('../util/csp-parser'),
cspBuilder = require('../util/csp-builder'),
scripts = require('../util/scripts-to-inject');
/**
* Util function to help inject scripts using a stream Transform object
*
* Options:
*
* - `options` {Object}
*/
module.exports = function(options) {
options.isBrowser = false;
options.isDevmode = options.isDevmode || false;
var injectScript;
// make sure to only inject scripts for older versions of the PhoneGap Developer App
// ie: before devmode plugin
if(!options.isDevmode) {
injectScript = scripts.getScripts(options);
} else {
injectScript = '';
}
function InjectHTML(options) {
if (!(this instanceof InjectHTML)) {
return new InjectHTML(options);
}
Transform.call(this, options);
};
var Transform = require('stream').Transform;
util.inherits(InjectHTML, Transform);
var replaceText = '<script type=\"text/javascript\" src=\"cordova.js\"></script>';
InjectHTML.prototype._transform = function (chunk, encoding, callback) {
// Inject our scripts at the bottom of the body tag
var newChunk = chunk.toString().replace(replaceText, replaceText + injectScript + '\n');
var cspRegex = /<meta.+Content-Security-Policy.+content.+"(.+)".*>/i;
var cspObject, cspString, cspTag;
// if we find an existing csp - warn the user about their csp being modified
// this is a little weird to parse the exact portion of the meta head that we need
var result = cspRegex.exec(newChunk);
if(result != null && result.length>=2) {
cspObject = cspParser(result[1]);
cspString = cspBuilder(cspObject);
cspTag = '<meta http-equiv="Content-Security-Policy" content="' + cspString + '">';
newChunk = newChunk.replace(cspRegex, cspTag);
if(options.emitter) {
options.emitter.emit('log', '[console.warn]'.yellow + ' Content Security Policy has been modified to be:', cspTag);
}
} else if(result == null) {
cspObject = {};
cspString = cspBuilder(cspObject);
cspTag = '<meta http-equiv="Content-Security-Policy" content="' + cspString + '">';
newChunk = newChunk.replace('</head>', cspTag + '\n</head>');
if(options.emitter) {
options.emitter.emit('log', '[console.warn]'.yellow + ' Content Security Policy has been added:', cspTag);
}
}
this.push(newChunk);
callback();
};
return new InjectHTML(options);
};