index.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/usr/bin/env ts-node
  2. import spawn from 'cross-spawn';
  3. import {resolve} from 'path';
  4. import {getSWTEnv} from '../config/env.ts';
  5. import {__dirname} from '../config/paths.ts';
  6. process.on('unhandledRejection', function(err) {
  7. throw err;
  8. });
  9. const args = process.argv.slice(2);
  10. const scriptIndex = args.findIndex(
  11. x => x === 'build' || x === 'test' || x === 'dev',
  12. );
  13. const script = scriptIndex === -1 ? args[0] : args[scriptIndex];
  14. const nodeArgs = scriptIndex > 0 ? args.slice(0, scriptIndex) : [];
  15. type CanWrite<T> = {
  16. -readonly [K in keyof T]: T[K];
  17. };
  18. function setEnv(name: string) {
  19. switch (name) {
  20. case 'dev':
  21. (process.env as CanWrite<NodeJS.ProcessEnv>).NODE_ENV = 'development';
  22. break;
  23. case 'build':
  24. (process.env as CanWrite<NodeJS.ProcessEnv>).NODE_ENV = 'production';
  25. break;
  26. }
  27. const env = getSWTEnv();
  28. Object.assign(process.env, env);
  29. }
  30. function runScript() {
  31. const result = spawn.sync(
  32. 'pnpm',
  33. nodeArgs
  34. .concat('ts-node')
  35. .concat(resolve(__dirname, `../scripts/${script}.ts`)),
  36. {stdio: 'inherit'},
  37. );
  38. if (result.signal) {
  39. if (result.signal === 'SIGKILL') {
  40. console.log(
  41. 'The build failed because the process exited too early. '
  42. + 'This probably means the system ran out of memory or someone called '
  43. + '`kill -9` on the process.',
  44. );
  45. } else if (result.signal === 'SIGTERM') {
  46. console.log(
  47. 'The build failed because the process exited too early. '
  48. + 'Someone might have called `kill` or `killall`, or the system could '
  49. + 'be shutting down.',
  50. );
  51. }
  52. process.exit(1);
  53. }
  54. return result;
  55. }
  56. function start() {
  57. if (['build', 'dev'].includes(script)) {
  58. setEnv(script);
  59. const {status} = runScript();
  60. process.exit(status ?? 1);
  61. } else {
  62. console.log('Unknown script "' + script + '".');
  63. }
  64. }
  65. start();