init.ts 2.3 KB

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