init.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Initialize ASAR support in fs module.
  2. import { wrapFsWithAsar } from './asar-fs-wrapper';
  3. wrapFsWithAsar(require('fs'));
  4. // Hook child_process.fork.
  5. import cp = require('child_process'); // eslint-disable-line import/first
  6. const originalFork = cp.fork;
  7. cp.fork = (modulePath, args?, options?: cp.ForkOptions) => {
  8. // Parse optional args.
  9. if (args == null) {
  10. args = [];
  11. } else if (typeof args === 'object' && !Array.isArray(args)) {
  12. options = args as cp.ForkOptions;
  13. args = [];
  14. }
  15. // Fallback to original fork to report arg type errors.
  16. if (typeof modulePath !== 'string' || !Array.isArray(args) ||
  17. (typeof options !== 'object' && typeof options !== 'undefined')) {
  18. return originalFork(modulePath, args, options);
  19. }
  20. // When forking a child script, we setup a special environment to make
  21. // the electron binary run like upstream Node.js.
  22. options = options ?? {};
  23. options.env = Object.create(options.env || process.env);
  24. options.env!.ELECTRON_RUN_AS_NODE = '1';
  25. // On mac the child script runs in helper executable.
  26. if (!options.execPath && process.platform === 'darwin') {
  27. options.execPath = process.helperExecPath;
  28. }
  29. return originalFork(modulePath, args, options);
  30. };
  31. // Prevent Node from adding paths outside this app to search paths.
  32. import path = require('path'); // eslint-disable-line import/first
  33. const Module = require('module') as NodeJS.ModuleInternal;
  34. const resourcesPathWithTrailingSlash = process.resourcesPath + path.sep;
  35. const originalNodeModulePaths = Module._nodeModulePaths;
  36. Module._nodeModulePaths = function (from) {
  37. const paths: string[] = originalNodeModulePaths(from);
  38. const fromPath = path.resolve(from) + path.sep;
  39. // If "from" is outside the app then we do nothing.
  40. if (fromPath.startsWith(resourcesPathWithTrailingSlash)) {
  41. return paths.filter(function (candidate) {
  42. return candidate.startsWith(resourcesPathWithTrailingSlash);
  43. });
  44. } else {
  45. return paths;
  46. }
  47. };