compiler.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. 'use strict';
  2. const {
  3. VMError
  4. } = require('./bridge');
  5. let cacheCoffeeScriptCompiler;
  6. /**
  7. * Returns the cached coffee script compiler or loads it
  8. * if it is not found in the cache.
  9. *
  10. * @private
  11. * @return {compileCallback} The coffee script compiler.
  12. * @throws {VMError} If the coffee-script module can't be found.
  13. */
  14. function getCoffeeScriptCompiler() {
  15. if (!cacheCoffeeScriptCompiler) {
  16. try {
  17. // The warning generated by webpack can be disabled by setting:
  18. // ignoreWarnings[].message = /Can't resolve 'coffee-script'/
  19. /* eslint-disable-next-line global-require */
  20. const coffeeScript = require('coffee-script');
  21. cacheCoffeeScriptCompiler = (code, filename) => {
  22. return coffeeScript.compile(code, {header: false, bare: true});
  23. };
  24. } catch (e) {
  25. throw new VMError('Coffee-Script compiler is not installed.');
  26. }
  27. }
  28. return cacheCoffeeScriptCompiler;
  29. }
  30. /**
  31. * Remove the shebang from source code.
  32. *
  33. * @private
  34. * @param {string} code - Code from which to remove the shebang.
  35. * @return {string} code without the shebang.
  36. */
  37. function removeShebang(code) {
  38. if (!code.startsWith('#!')) return code;
  39. return '//' + code.substring(2);
  40. }
  41. /**
  42. * The JavaScript compiler, just a identity function.
  43. *
  44. * @private
  45. * @type {compileCallback}
  46. * @param {string} code - The JavaScript code.
  47. * @param {string} filename - Filename of this script.
  48. * @return {string} The code.
  49. */
  50. function jsCompiler(code, filename) {
  51. return removeShebang(code);
  52. }
  53. /**
  54. * Look up the compiler for a specific name.
  55. *
  56. * @private
  57. * @param {(string|compileCallback)} compiler - A compile callback or the name of the compiler.
  58. * @return {compileCallback} The resolved compiler.
  59. * @throws {VMError} If the compiler is unknown or the coffee script module was needed and couldn't be found.
  60. */
  61. function lookupCompiler(compiler) {
  62. if ('function' === typeof compiler) return compiler;
  63. switch (compiler) {
  64. case 'coffeescript':
  65. case 'coffee-script':
  66. case 'cs':
  67. case 'text/coffeescript':
  68. return getCoffeeScriptCompiler();
  69. case 'javascript':
  70. case 'java-script':
  71. case 'js':
  72. case 'text/javascript':
  73. return jsCompiler;
  74. default:
  75. throw new VMError(`Unsupported compiler '${compiler}'.`);
  76. }
  77. }
  78. exports.removeShebang = removeShebang;
  79. exports.lookupCompiler = lookupCompiler;