compiler.js
2.25 KB
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
'use strict';
const {
VMError
} = require('./bridge');
let cacheCoffeeScriptCompiler;
/**
* Returns the cached coffee script compiler or loads it
* if it is not found in the cache.
*
* @private
* @return {compileCallback} The coffee script compiler.
* @throws {VMError} If the coffee-script module can't be found.
*/
function getCoffeeScriptCompiler() {
if (!cacheCoffeeScriptCompiler) {
try {
// The warning generated by webpack can be disabled by setting:
// ignoreWarnings[].message = /Can't resolve 'coffee-script'/
/* eslint-disable-next-line global-require */
const coffeeScript = require('coffee-script');
cacheCoffeeScriptCompiler = (code, filename) => {
return coffeeScript.compile(code, {header: false, bare: true});
};
} catch (e) {
throw new VMError('Coffee-Script compiler is not installed.');
}
}
return cacheCoffeeScriptCompiler;
}
/**
* Remove the shebang from source code.
*
* @private
* @param {string} code - Code from which to remove the shebang.
* @return {string} code without the shebang.
*/
function removeShebang(code) {
if (!code.startsWith('#!')) return code;
return '//' + code.substring(2);
}
/**
* The JavaScript compiler, just a identity function.
*
* @private
* @type {compileCallback}
* @param {string} code - The JavaScript code.
* @param {string} filename - Filename of this script.
* @return {string} The code.
*/
function jsCompiler(code, filename) {
return removeShebang(code);
}
/**
* Look up the compiler for a specific name.
*
* @private
* @param {(string|compileCallback)} compiler - A compile callback or the name of the compiler.
* @return {compileCallback} The resolved compiler.
* @throws {VMError} If the compiler is unknown or the coffee script module was needed and couldn't be found.
*/
function lookupCompiler(compiler) {
if ('function' === typeof compiler) return compiler;
switch (compiler) {
case 'coffeescript':
case 'coffee-script':
case 'cs':
case 'text/coffeescript':
return getCoffeeScriptCompiler();
case 'javascript':
case 'java-script':
case 'js':
case 'text/javascript':
return jsCompiler;
default:
throw new VMError(`Unsupported compiler '${compiler}'.`);
}
}
exports.removeShebang = removeShebang;
exports.lookupCompiler = lookupCompiler;