Skip to content

Commit

Permalink
fix(karma): load scripts in strict mode
Browse files Browse the repository at this point in the history
Replace the eval() with <script> tags for each script, so that they still create global variables

Similar to g3 cl/198411444

Fixes bazel-contrib#922
  • Loading branch information
alexeagle committed Oct 28, 2019
1 parent 3b74e29 commit b9e95de
Showing 1 changed file with 41 additions and 16 deletions.
57 changes: 41 additions & 16 deletions packages/karma/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,25 +36,50 @@ function initConcatJs(logger, emitter, basePath, hostname, port) {
content: '',
encodings: {},
} as any;
const included = [];
// Preserve all non-JS that were there in the included list.
const included = files.included.filter(f => path.extname(f.originalPath) !== '.js');
const bundledFiles =
files.included.filter(f => path.extname(f.originalPath) === '.js').map((file) => {
const relativePath = path.relative(basePath, file.originalPath).replace(/\\/g, '/');

files.included.forEach(file => {
if (path.extname(file.originalPath) !== '.js') {
// Preserve all non-JS that were there in the included list.
included.push(file);
} else {
const relativePath = path.relative(basePath, file.originalPath).replace(/\\/g, '/');
let content = file.content + `\n//# sourceURL=http://${hostname}:${port}/base/` +
relativePath + '\n';

// Remove 'use strict'.
let content = file.content.replace(/('use strict'|"use strict");?/, '');
content = JSON.stringify(
`${content}\n//# sourceURL=http://${hostname}:${port}/base/` +
`${relativePath}\n`);
content = `//${relativePath}\neval(${content});\n`;
bundleFile.content += content;
}
});
return `
loadFile(
${JSON.stringify(relativePath)},
${JSON.stringify(content)});`;
});

// Execute each file by putting it in a <script> tag. This makes them create
// global variables, even with 'use strict'; (unlike eval).
bundleFile.content = `
(function() { // Hide local variables
// IE 8 and below do not support document.head.
var parent = document.getElementsByTagName('head')[0] ||
document.documentElement;
function loadFile(path, src) {
try {
var script = document.createElement('script');
if ('textContent' in script) {
script.textContent = src;
} else {
// This is for IE 8 and below.
script.text = src;
}
parent.appendChild(script);
// Don't pollute the DOM with hundreds of <script> tags.
parent.removeChild(script);
} catch(err) {
window.__karma__ && window.__karma__.error(
'An error occurred while loading ' + path + ':\\n' +
(err.stack || err.message || err.toString()));
console.error('An error occurred while loading ' + path, err);
throw err;
}
}
${bundledFiles.join('')}
})();`;
bundleFile.sha = sha1(Buffer.from(bundleFile.content));
bundleFile.mtime = new Date();
included.unshift(bundleFile);
Expand Down

0 comments on commit b9e95de

Please sign in to comment.