electron/lib/renderer/init.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

162 lines
6.4 KiB
TypeScript
Raw Normal View History

import * as path from 'path';
feat: I guess it's esm (#37535) * fix: allow ESM loads from within ASAR files * fix: ensure that ESM entry points finish loading before app ready * fix: allow loading ESM entrypoints via default_app * fix: allow ESM loading for renderer preloads * docs: document current known limitations of esm * chore: add patches to support blending esm handlers * refactor: use SetDefersLoading instead of JoinAppCode in renderers Blink has it's own event loop so pumping the uv loop in the renderer is not enough, luckily in blink we can suspend the loading of the frame while we do additional work. * chore: add patch to expose SetDefersLoading * fix: use fileURLToPath instead of pathname * chore: update per PR feedback * fix: fs.exists/existsSync should never throw * fix: convert path to file url before importing * fix: oops * fix: oops * Update docs/tutorial/esm-limitations.md Co-authored-by: Jeremy Rose <jeremya@chromium.org> * windows... * windows... * chore: update patches * spec: fix tests and document empty body edge case * Apply suggestions from code review Co-authored-by: Daniel Scalzi <d_scalzi@yahoo.com> Co-authored-by: Jeremy Rose <jeremya@chromium.org> * spec: add tests for esm * spec: windows * chore: update per PR feedback * chore: update patches * Update shell/common/node_bindings.h Co-authored-by: Jeremy Rose <jeremya@chromium.org> * chore: update patches * rebase * use cjs loader by default for preload scripts * chore: fix lint * chore: update patches * chore: update patches * chore: fix patches * build: debug depshash * ? * Revert "build: debug depshash" This reverts commit 0de82523fb93f475226356b37418ce4b69acdcdf. * chore: allow electron as builtin protocol in esm loader * Revert "Revert "build: debug depshash"" This reverts commit ff86b1243ca6d05c9b3b38e0a6d717fb380343a4. * chore: fix esm doc * chore: update node patches --------- Co-authored-by: Jeremy Rose <jeremya@chromium.org> Co-authored-by: electron-patch-conflict-fixer[bot] <83340002+electron-patch-conflict-fixer[bot]@users.noreply.github.com> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: Daniel Scalzi <d_scalzi@yahoo.com>
2023-08-31 00:38:07 +00:00
import { pathToFileURL } from 'url';
import { IPC_MESSAGES } from '@electron/internal/common/ipc-messages';
2016-01-13 03:55:49 +00:00
import type * as ipcRendererInternalModule from '@electron/internal/renderer/ipc-renderer-internal';
import type * as ipcRendererUtilsModule from '@electron/internal/renderer/ipc-renderer-internal-utils';
const Module = require('module') as NodeJS.ModuleInternal;
2016-01-12 02:40:23 +00:00
// Make sure globals like "process" and "global" are always available in preload
// scripts even after they are deleted in "loaded" script.
//
// Note 1: We rely on a Node patch to actually pass "process" and "global" and
// other arguments to the wrapper.
//
// Note 2: Node introduced a new code path to use native code to wrap module
// code, which does not work with this hack. However by modifying the
// "Module.wrapper" we can force Node to use the old code path to wrap module
// code with JavaScript.
2019-06-02 20:03:03 +00:00
//
2019-06-20 15:11:38 +00:00
// Note 3: We provide the equivalent extra variables internally through the
2019-06-02 20:03:03 +00:00
// webpack ProvidePlugin in webpack.config.base.js. If you add any extra
// variables to this wrapper please ensure to update that plugin as well.
Module.wrapper = [
'(function (exports, require, module, __filename, __dirname, process, global, Buffer) { ' +
// By running the code in a new closure, it would be possible for the module
// code to override "process" and "Buffer" with local variables.
'return function (exports, require, module, __filename, __dirname) { ',
'\n}.call(this, exports, require, module, __filename, __dirname); });'
];
2016-01-14 19:10:12 +00:00
// We modified the original process.argv to let node.js load the
// init.js, we need to restore it here.
2016-03-25 19:57:17 +00:00
process.argv.splice(1, 1);
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Clear search paths.
2016-03-25 19:57:17 +00:00
require('../common/reset-search-paths');
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Import common settings.
require('@electron/internal/common/init');
2016-01-12 02:40:23 +00:00
const { ipcRendererInternal } = require('@electron/internal/renderer/ipc-renderer-internal') as typeof ipcRendererInternalModule;
const ipcRendererUtils = require('@electron/internal/renderer/ipc-renderer-internal-utils') as typeof ipcRendererUtilsModule;
2016-01-12 02:40:23 +00:00
process.getProcessMemoryInfo = () => {
return ipcRendererInternal.invoke<Electron.ProcessMemoryInfo>(IPC_MESSAGES.BROWSER_GET_PROCESS_MEMORY_INFO);
};
2016-01-14 18:35:29 +00:00
// Process command line arguments.
const { hasSwitch, getSwitchValue } = process._linkedBinding('electron_common_command_line');
const { mainFrame } = process._linkedBinding('electron_renderer_web_frame');
const nodeIntegration = mainFrame.getWebPreference('nodeIntegration');
const appPath = hasSwitch('app-path') ? getSwitchValue('app-path') : null;
2018-12-12 21:31:16 +00:00
// Common renderer initialization
require('@electron/internal/renderer/common-init');
if (nodeIntegration) {
2016-01-14 18:35:29 +00:00
// Export node bindings to global.
const { makeRequireFunction } = __non_webpack_require__('internal/modules/cjs/helpers');
global.module = new Module('electron/js2c/renderer_init');
global.require = makeRequireFunction(global.module);
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Set the __filename to the path of html file if it is file: protocol.
2016-01-12 02:40:23 +00:00
if (window.location.protocol === 'file:') {
const location = window.location;
let pathname = location.pathname;
if (process.platform === 'win32') {
if (pathname[0] === '/') pathname = pathname.substr(1);
const isWindowsNetworkSharePath = location.hostname.length > 0 && process.resourcesPath.startsWith('\\');
if (isWindowsNetworkSharePath) {
pathname = `//${location.host}/${pathname}`;
}
}
2016-03-25 19:57:17 +00:00
global.__filename = path.normalize(decodeURIComponent(pathname));
global.__dirname = path.dirname(global.__filename);
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Set module's filename so relative require can work as expected.
2019-06-02 20:03:03 +00:00
global.module.filename = global.__filename;
2016-01-12 02:40:23 +00:00
2016-01-14 18:35:29 +00:00
// Also search for module under the html file.
global.module.paths = Module._nodeModulePaths(global.__dirname);
2016-01-12 02:40:23 +00:00
} else {
// For backwards compatibility we fake these two paths here
global.__filename = path.join(process.resourcesPath, 'electron.asar', 'renderer', 'init.js');
global.__dirname = path.join(process.resourcesPath, 'electron.asar', 'renderer');
2017-04-04 00:36:01 +00:00
if (appPath) {
2017-04-03 13:11:29 +00:00
// Search for module under the app directory
global.module.paths = Module._nodeModulePaths(appPath);
2017-04-03 13:11:29 +00:00
}
2016-01-12 02:40:23 +00:00
}
2016-01-14 18:35:29 +00:00
// Redirect window.onerror to uncaughtException.
window.onerror = function (_message, _filename, _lineno, _colno, error) {
if (global.process.listenerCount('uncaughtException') > 0) {
// We do not want to add `uncaughtException` to our definitions
// because we don't want anyone else (anywhere) to throw that kind
// of error.
global.process.emit('uncaughtException', error as any);
2016-03-25 19:57:17 +00:00
return true;
2016-01-12 02:40:23 +00:00
} else {
2016-03-25 19:57:17 +00:00
return false;
2016-01-12 02:40:23 +00:00
}
2016-03-25 19:57:17 +00:00
};
2016-01-12 02:40:23 +00:00
} else {
// Delete Node's symbols after the Environment has been loaded in a
// non context-isolated environment
if (!process.contextIsolated) {
process.once('loaded', function () {
2020-08-24 18:23:25 +00:00
delete (global as any).process;
delete (global as any).Buffer;
delete (global as any).setImmediate;
delete (global as any).clearImmediate;
delete (global as any).global;
delete (global as any).root;
delete (global as any).GLOBAL;
});
}
2016-01-12 02:40:23 +00:00
}
feat: I guess it's esm (#37535) * fix: allow ESM loads from within ASAR files * fix: ensure that ESM entry points finish loading before app ready * fix: allow loading ESM entrypoints via default_app * fix: allow ESM loading for renderer preloads * docs: document current known limitations of esm * chore: add patches to support blending esm handlers * refactor: use SetDefersLoading instead of JoinAppCode in renderers Blink has it's own event loop so pumping the uv loop in the renderer is not enough, luckily in blink we can suspend the loading of the frame while we do additional work. * chore: add patch to expose SetDefersLoading * fix: use fileURLToPath instead of pathname * chore: update per PR feedback * fix: fs.exists/existsSync should never throw * fix: convert path to file url before importing * fix: oops * fix: oops * Update docs/tutorial/esm-limitations.md Co-authored-by: Jeremy Rose <jeremya@chromium.org> * windows... * windows... * chore: update patches * spec: fix tests and document empty body edge case * Apply suggestions from code review Co-authored-by: Daniel Scalzi <d_scalzi@yahoo.com> Co-authored-by: Jeremy Rose <jeremya@chromium.org> * spec: add tests for esm * spec: windows * chore: update per PR feedback * chore: update patches * Update shell/common/node_bindings.h Co-authored-by: Jeremy Rose <jeremya@chromium.org> * chore: update patches * rebase * use cjs loader by default for preload scripts * chore: fix lint * chore: update patches * chore: update patches * chore: fix patches * build: debug depshash * ? * Revert "build: debug depshash" This reverts commit 0de82523fb93f475226356b37418ce4b69acdcdf. * chore: allow electron as builtin protocol in esm loader * Revert "Revert "build: debug depshash"" This reverts commit ff86b1243ca6d05c9b3b38e0a6d717fb380343a4. * chore: fix esm doc * chore: update node patches --------- Co-authored-by: Jeremy Rose <jeremya@chromium.org> Co-authored-by: electron-patch-conflict-fixer[bot] <83340002+electron-patch-conflict-fixer[bot]@users.noreply.github.com> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: Daniel Scalzi <d_scalzi@yahoo.com>
2023-08-31 00:38:07 +00:00
const { appCodeLoaded } = process;
delete process.appCodeLoaded;
const { preloadPaths } = ipcRendererUtils.invokeSync<{ preloadPaths: string[] }>(IPC_MESSAGES.BROWSER_NONSANDBOX_LOAD);
const cjsPreloads = preloadPaths.filter(p => path.extname(p) !== '.mjs');
const esmPreloads = preloadPaths.filter(p => path.extname(p) === '.mjs');
if (cjsPreloads.length) {
// Load the preload scripts.
for (const preloadScript of cjsPreloads) {
try {
Module._load(preloadScript);
} catch (error) {
console.error(`Unable to load preload script: ${preloadScript}`);
console.error(error);
ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadScript, error);
}
2016-01-12 02:40:23 +00:00
}
}
feat: I guess it's esm (#37535) * fix: allow ESM loads from within ASAR files * fix: ensure that ESM entry points finish loading before app ready * fix: allow loading ESM entrypoints via default_app * fix: allow ESM loading for renderer preloads * docs: document current known limitations of esm * chore: add patches to support blending esm handlers * refactor: use SetDefersLoading instead of JoinAppCode in renderers Blink has it's own event loop so pumping the uv loop in the renderer is not enough, luckily in blink we can suspend the loading of the frame while we do additional work. * chore: add patch to expose SetDefersLoading * fix: use fileURLToPath instead of pathname * chore: update per PR feedback * fix: fs.exists/existsSync should never throw * fix: convert path to file url before importing * fix: oops * fix: oops * Update docs/tutorial/esm-limitations.md Co-authored-by: Jeremy Rose <jeremya@chromium.org> * windows... * windows... * chore: update patches * spec: fix tests and document empty body edge case * Apply suggestions from code review Co-authored-by: Daniel Scalzi <d_scalzi@yahoo.com> Co-authored-by: Jeremy Rose <jeremya@chromium.org> * spec: add tests for esm * spec: windows * chore: update per PR feedback * chore: update patches * Update shell/common/node_bindings.h Co-authored-by: Jeremy Rose <jeremya@chromium.org> * chore: update patches * rebase * use cjs loader by default for preload scripts * chore: fix lint * chore: update patches * chore: update patches * chore: fix patches * build: debug depshash * ? * Revert "build: debug depshash" This reverts commit 0de82523fb93f475226356b37418ce4b69acdcdf. * chore: allow electron as builtin protocol in esm loader * Revert "Revert "build: debug depshash"" This reverts commit ff86b1243ca6d05c9b3b38e0a6d717fb380343a4. * chore: fix esm doc * chore: update node patches --------- Co-authored-by: Jeremy Rose <jeremya@chromium.org> Co-authored-by: electron-patch-conflict-fixer[bot] <83340002+electron-patch-conflict-fixer[bot]@users.noreply.github.com> Co-authored-by: PatchUp <73610968+patchup[bot]@users.noreply.github.com> Co-authored-by: Daniel Scalzi <d_scalzi@yahoo.com>
2023-08-31 00:38:07 +00:00
if (esmPreloads.length) {
const { loadESM } = __non_webpack_require__('internal/process/esm_loader');
loadESM(async (esmLoader: any) => {
// Load the preload scripts.
for (const preloadScript of esmPreloads) {
await esmLoader.import(pathToFileURL(preloadScript).toString(), undefined, Object.create(null)).catch((err: Error) => {
console.error(`Unable to load preload script: ${preloadScript}`);
console.error(err);
ipcRendererInternal.send(IPC_MESSAGES.BROWSER_PRELOAD_ERROR, preloadScript, err);
});
}
}).finally(() => appCodeLoaded!());
} else {
appCodeLoaded!();
}