init.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { EventEmitter } from 'events';
  2. import { pathToFileURL } from 'url';
  3. import { ParentPort } from '@electron/internal/utility/parent-port';
  4. const v8Util = process._linkedBinding('electron_common_v8_util');
  5. const entryScript: string = v8Util.getHiddenValue(process, '_serviceStartupScript');
  6. // We modified the original process.argv to let node.js load the init.js,
  7. // we need to restore it here.
  8. process.argv.splice(1, 1, entryScript);
  9. // Import common settings.
  10. require('@electron/internal/common/init');
  11. process._linkedBinding('electron_browser_event_emitter').setEventEmitterPrototype(EventEmitter.prototype);
  12. const parentPort: ParentPort = new ParentPort();
  13. Object.defineProperty(process, 'parentPort', {
  14. enumerable: true,
  15. writable: false,
  16. value: parentPort
  17. });
  18. // Based on third_party/electron_node/lib/internal/worker/io.js
  19. parentPort.on('newListener', (name: string) => {
  20. if (name === 'message' && parentPort.listenerCount('message') === 0) {
  21. parentPort.start();
  22. }
  23. });
  24. parentPort.on('removeListener', (name: string) => {
  25. if (name === 'message' && parentPort.listenerCount('message') === 0) {
  26. parentPort.pause();
  27. }
  28. });
  29. // Finally load entry script.
  30. const { loadESM } = __non_webpack_require__('internal/process/esm_loader');
  31. const mainEntry = pathToFileURL(entryScript);
  32. loadESM(async (esmLoader: any) => {
  33. try {
  34. await esmLoader.import(mainEntry.toString(), undefined, Object.create(null));
  35. } catch (err) {
  36. // @ts-ignore internalBinding is a secret internal global that we shouldn't
  37. // really be using, so we ignore the type error instead of declaring it in types
  38. internalBinding('errors').triggerUncaughtException(err);
  39. }
  40. });