Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 20 additions & 27 deletions app/scripts/app-init.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
// This file is used only for manifest version 3

// We don't usually `import` files into `app-init.js` because we need to load
// "chunks" via `importScripts`; but in this case `promise-with-resolvers` file
// "chunks" via `importScripts`; but in this case `extension-lazy-listener` file
// is so small we won't ever have a problem with these two files being "split".
import { withResolvers } from '../../shared/lib/promise-with-resolvers';
import { ExtensionLazyListener } from './lib/extension-lazy-listener/extension-lazy-listener';

// Represents if importAllScripts has been run
// eslint-disable-next-line
let scriptsLoadInitiated = false;
const { chrome } = globalThis;
const testMode = process.env.IN_TEST;

// this needs to be run early we can begin listening to these browser events
// as soon as possible
const listener = new ExtensionLazyListener(chrome, {
runtime: [
'onInstalled',
'onConnect',
'onConnectExternal',
'onUpdateAvailable',
],
});

/**
* @type {import('../../types/global').StateHooks}
*/
globalThis.stateHooks = globalThis.stateHooks || {};

globalThis.stateHooks.lazyListener = listener;

// Represents if importAllScripts has been run
// eslint-disable-next-line
let scriptsLoadInitiated = false;
const testMode = process.env.IN_TEST;

const loadTimeLogs = [];
// eslint-disable-next-line import/unambiguous
function tryImport(...fileNames) {
Expand Down Expand Up @@ -194,25 +208,4 @@ const registerInPageContentScript = async () => {
}
};

/**
* A promise that resolves when the `onInstalled` event is fired.
*
* @type {PromiseWithResolvers<chrome.runtime.InstalledDetails>}
*/
const deferredOnInstalledListener = withResolvers();
globalThis.stateHooks.onInstalledListener = deferredOnInstalledListener.promise;

/**
* `onInstalled` event handler.
*
* On MV3 builds we must listen for this event in `app-init`, otherwise we found
* that the listener is never called.
* For MV2 builds, the listener is added in `background.js` instead.
*/
chrome.runtime.onInstalled.addListener(function listener(details) {
chrome.runtime.onInstalled.removeListener(listener);
deferredOnInstalledListener.resolve(details);
delete globalThis.stateHooks.onInstalledListener;
});

registerInPageContentScript();
118 changes: 65 additions & 53 deletions app/scripts/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import { NotificationServicesController } from '@metamask/notification-services-controller';
import { withResolvers } from '../../shared/lib/promise-with-resolvers';
import { FirstTimeFlowType } from '../../shared/constants/onboarding';

import {
ENVIRONMENT_TYPE_POPUP,
ENVIRONMENT_TYPE_NOTIFICATION,
Expand Down Expand Up @@ -98,6 +97,8 @@
* @typedef {import('./lib/stores/persistence-manager').Backup} Backup
*/

const { lazyListener } = globalThis.stateHooks;

// eslint-disable-next-line @metamask/design-tokens/color-no-hex
const BADGE_COLOR_APPROVAL = '#0376C9';
// eslint-disable-next-line @metamask/design-tokens/color-no-hex
Expand Down Expand Up @@ -167,15 +168,7 @@
// Timeout for initializing phishing warning page.
const PHISHING_WARNING_PAGE_TIMEOUT = ONE_SECOND_IN_MILLISECONDS;

// In MV3 onInstalled must be installed in the entry file
if (globalThis.stateHooks.onInstalledListener) {
globalThis.stateHooks.onInstalledListener.then(handleOnInstalled);
} else {
browser.runtime.onInstalled.addListener(function listener(details) {
browser.runtime.onInstalled.removeListener(listener);
handleOnInstalled(details);
});
}
lazyListener.once('runtime', 'onInstalled').then(handleOnInstalled);

/**
* This deferred Promise is used to track whether initialization has finished.
Expand Down Expand Up @@ -447,13 +440,19 @@
let connectCaipMultichain;

const corruptionHandler = new CorruptionHandler();
browser.runtime.onConnect.addListener(async (port) => {
const handleOnConnect = async (port) => {
if (
inTest &&
getManifestFlags().testing?.simulateUnresponsiveBackground === true
) {
return;
}
// `handleOnConnect` can be called asynchronously, well after the `onConnect`
// event was emitted, due to the lazy listener setup uip app-init.
if (port.disconnected) {
// window already closed, no need to do anything else.
return;
}

port.postMessage({
data: {
Expand Down Expand Up @@ -503,24 +502,37 @@
} else {
const errorLike = isObject(error)
? {
message: error.message ?? 'Unknown error',
name: error.name ?? 'UnknownError',
stack: error.stack,
}
message: error.message ?? 'Unknown error',

Check failure on line 505 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
name: error.name ?? 'UnknownError',

Check failure on line 506 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
stack: error.stack,

Check failure on line 507 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
}

Check failure on line 508 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
: {
message: String(error),
name: 'UnknownError',
stack: '',
};
message: String(error),

Check failure on line 510 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
name: 'UnknownError',

Check failure on line 511 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
stack: '',

Check failure on line 512 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
};

Check failure on line 513 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
// general errors
tryPostMessage(port, DISPLAY_GENERAL_STARTUP_ERROR, {
error: errorLike,
currentLocale: controller?.preferencesController?.state?.currentLocale,
});
}
}
});
browser.runtime.onConnectExternal.addListener(async (...args) => {
};
const installOnConnectListener = () => {
lazyListener.addListener('runtime', 'onConnect', handleOnConnect);
};
if (
inTest &&
getManifestFlags().testing?.simulatedSlowBackgroundLoadingTimeout
) {
const { simulatedSlowBackgroundLoadingTimeout } = getManifestFlags().testing;
setTimeout(installOnConnectListener, simulatedSlowBackgroundLoadingTimeout);
} else {
installOnConnectListener();
}

lazyListener.addListener('runtime', 'onConnectExternal', async (...args) => {
// Queue up connection attempts here, waiting until after initialization
await isInitialized;
// This is set in `setupController`, which is called as part of initialization
Expand Down Expand Up @@ -631,20 +643,20 @@

const overrides = inTest
? {
keyrings: {
// Use `require` to make it easier to exclude this test code from the Browserify build.
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require
trezorBridge: require('../../test/stub/keyring-bridge')
.FakeTrezorBridge,
// Use `require` to make it easier to exclude this test code from the Browserify build.
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require
ledgerBridge: require('../../test/stub/keyring-bridge')
.FakeLedgerBridge,
// Use `require` to make it easier to exclude this test code from the Browserify build.
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require
qrBridge: require('../../test/stub/keyring-bridge').FakeQrBridge,
},
}
keyrings: {

Check failure on line 646 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
// Use `require` to make it easier to exclude this test code from the Browserify build.

Check failure on line 647 in app/scripts/background.js

View workflow job for this annotation

GitHub Actions / test-lint / Test lint

Insert `··`
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require
trezorBridge: require('../../test/stub/keyring-bridge')
.FakeTrezorBridge,
// Use `require` to make it easier to exclude this test code from the Browserify build.
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require
ledgerBridge: require('../../test/stub/keyring-bridge')
.FakeLedgerBridge,
// Use `require` to make it easier to exclude this test code from the Browserify build.
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require
qrBridge: require('../../test/stub/keyring-bridge').FakeQrBridge,
},
}
: {};

const preinstalledSnaps = await loadPreinstalledSnaps();
Expand Down Expand Up @@ -843,7 +855,7 @@
migrations,
defaultVersion: process.env.WITH_STATE
? // eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires, node/global-require
require('../../test/e2e/default-fixture').FIXTURE_STATE_METADATA_VERSION
require('../../test/e2e/default-fixture').FIXTURE_STATE_METADATA_VERSION
: null,
});

Expand Down Expand Up @@ -1407,30 +1419,30 @@
).filter(
(notification) =>
notification.type ===
NotificationServicesController.Constants.TRIGGER_TYPES.SNAP &&
NotificationServicesController.Constants.TRIGGER_TYPES.SNAP &&
notification.readDate === null,
).length;

const featureAnnouncementCount = isFeatureAnnouncementsEnabled
? controller.notificationServicesController.state.metamaskNotificationsList.filter(
(notification) =>
!notification.isRead &&
notification.type ===
NotificationServicesController.Constants.TRIGGER_TYPES
.FEATURES_ANNOUNCEMENT,
).length
(notification) =>
!notification.isRead &&
notification.type ===
NotificationServicesController.Constants.TRIGGER_TYPES
.FEATURES_ANNOUNCEMENT,
).length
: 0;

const walletNotificationCount = isNotificationServicesEnabled
? controller.notificationServicesController.state.metamaskNotificationsList.filter(
(notification) =>
!notification.isRead &&
notification.type !==
NotificationServicesController.Constants.TRIGGER_TYPES
.FEATURES_ANNOUNCEMENT &&
notification.type !==
NotificationServicesController.Constants.TRIGGER_TYPES.SNAP,
).length
(notification) =>
!notification.isRead &&
notification.type !==
NotificationServicesController.Constants.TRIGGER_TYPES
.FEATURES_ANNOUNCEMENT &&
notification.type !==
NotificationServicesController.Constants.TRIGGER_TYPES.SNAP,
).length
: 0;

const unreadNotificationsCount =
Expand Down Expand Up @@ -1545,7 +1557,7 @@
*
* @param {chrome.runtime.InstalledDetails} details
*/
function handleOnInstalled(details) {
function handleOnInstalled([details]) {
if (details.reason === 'install') {
onInstall();
} else if (
Expand Down Expand Up @@ -1586,7 +1598,7 @@
controller.appStateController.setIsUpdateAvailable(true);
}

browser.runtime.onUpdateAvailable.addListener(onUpdateAvailable);
lazyListener.addListener('runtime', 'onUpdateAvailable', onUpdateAvailable);

function onNavigateToTab() {
browser.tabs.onActivated.addListener((onActivatedTab) => {
Expand Down
Loading
Loading