ts.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. var childProcess = require('child_process');
  3. var fs = require('fs');
  4. var path = require('path');
  5. read(function(err, fileNames) {
  6. clean(fileNames, function() {
  7. var hasLintError = false;
  8. compile(fileNames, function(err) {
  9. if (err) {
  10. console.error(err);
  11. return process.exit(1);
  12. }
  13. lint(fileNames, function(message) {
  14. process.stdout.write(message);
  15. hasLintError = true;
  16. }, function() {
  17. process.exit(Number(hasLintError));
  18. });
  19. });
  20. });
  21. });
  22. /**
  23. * Clean the files.
  24. * @param {Array.<string>} filePaths
  25. * @param {function()} done
  26. */
  27. function clean(filePaths, done) {
  28. var i = -1;
  29. (function next() {
  30. i += 1;
  31. if (i >= filePaths.length) return done();
  32. var filePath = filePaths[i];
  33. if (/\.d\.ts$/.test(filePath)) return next();
  34. var mapName = filePath.substring(4, filePath.length - 2) + 'js.map';
  35. var mapPath = path.join('dist', mapName);
  36. if (fs.existsSync(mapPath)) fs.unlinkSync(mapPath);
  37. next();
  38. })();
  39. }
  40. /**
  41. * Compile the files.
  42. * @param {Array.<string>} filePaths
  43. * @param {function(Error)} done
  44. */
  45. function compile(filePaths, done) {
  46. var execPath = path.join(__dirname, 'node_modules/.bin/tsc');
  47. var options = '--declaration --module CommonJS --noImplicitAny --outDir dist';
  48. childProcess.exec([execPath, options].concat(filePaths).join(' '), function(err, stdout) {
  49. if (stdout) return done(new Error(stdout));
  50. done(null);
  51. });
  52. }
  53. /**
  54. * Lint the files.
  55. * @param {Array.<string>} filePaths
  56. * @param {function(string)} handler
  57. * @param {function()} done
  58. */
  59. function lint(filePaths, handler, done) {
  60. var i = -1;
  61. var execPath = path.join(__dirname, 'node_modules/.bin/tslint');
  62. (function next() {
  63. i += 1;
  64. if (i >= filePaths.length) return done();
  65. var filePath = filePaths[i];
  66. if (/\.d\.ts$/.test(filePath)) return next();
  67. childProcess.exec(execPath + ' -f ' + filePath, function(err, stdout) {
  68. if (stdout) handler(stdout);
  69. next();
  70. });
  71. })();
  72. }
  73. /**
  74. * Read the files from the project file.
  75. * @param {function(Error, Array.<string>)} done
  76. */
  77. function read(done) {
  78. var contents = fs.readFileSync('crunchyroll.js.njsproj', 'utf8');
  79. var expression = /<TypeScriptCompile\s+Include="([\w\W]+?\.ts)" \/>/g;
  80. var matches;
  81. var filePaths = [];
  82. while ((matches = expression.exec(contents))) filePaths.push(matches[1]);
  83. done(null, filePaths);
  84. }