From 5e5127564cfe8ee171ba80dcd34a240f3ae2eabd Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Wed, 14 Jan 2026 13:13:22 +0100 Subject: [PATCH 1/6] feat: add new ConnectivityController --- .github/CODEOWNERS | 1 + README.md | 4 + packages/connectivity-controller/CHANGELOG.md | 14 ++ packages/connectivity-controller/LICENSE | 20 +++ packages/connectivity-controller/README.md | 15 ++ .../connectivity-controller/jest.config.js | 26 +++ packages/connectivity-controller/package.json | 72 ++++++++ .../src/ConnectivityController.test.ts | 160 ++++++++++++++++++ .../src/ConnectivityController.ts | 158 +++++++++++++++++ packages/connectivity-controller/src/index.ts | 12 ++ .../tsconfig.build.json | 13 ++ .../connectivity-controller/tsconfig.json | 8 + packages/connectivity-controller/typedoc.json | 7 + teams.json | 1 + tsconfig.build.json | 1 + tsconfig.json | 1 + yarn.lock | 18 ++ 17 files changed, 531 insertions(+) create mode 100644 packages/connectivity-controller/CHANGELOG.md create mode 100644 packages/connectivity-controller/LICENSE create mode 100644 packages/connectivity-controller/README.md create mode 100644 packages/connectivity-controller/jest.config.js create mode 100644 packages/connectivity-controller/package.json create mode 100644 packages/connectivity-controller/src/ConnectivityController.test.ts create mode 100644 packages/connectivity-controller/src/ConnectivityController.ts create mode 100644 packages/connectivity-controller/src/index.ts create mode 100644 packages/connectivity-controller/tsconfig.build.json create mode 100644 packages/connectivity-controller/tsconfig.json create mode 100644 packages/connectivity-controller/typedoc.json diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index dd322799ccc..f97fef01a56 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -68,6 +68,7 @@ /packages/base-controller @MetaMask/core-platform /packages/build-utils @MetaMask/core-platform /packages/composable-controller @MetaMask/core-platform +/packages/connectivity-controller @MetaMask/core-platform /packages/controller-utils @MetaMask/core-platform /packages/error-reporting-service @MetaMask/core-platform /packages/eth-json-rpc-middleware @MetaMask/core-platform diff --git a/README.md b/README.md index 92d9c369396..48d06d72c30 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,7 @@ Each package in this repository has its own README where you can find installati - [`@metamask/chain-agnostic-permission`](packages/chain-agnostic-permission) - [`@metamask/claims-controller`](packages/claims-controller) - [`@metamask/composable-controller`](packages/composable-controller) +- [`@metamask/connectivity-controller`](packages/connectivity-controller) - [`@metamask/controller-utils`](packages/controller-utils) - [`@metamask/core-backend`](packages/core-backend) - [`@metamask/delegation-controller`](packages/delegation-controller) @@ -111,6 +112,7 @@ linkStyle default opacity:0.5 chain_agnostic_permission(["@metamask/chain-agnostic-permission"]); claims_controller(["@metamask/claims-controller"]); composable_controller(["@metamask/composable-controller"]); + connectivity_controller(["@metamask/connectivity-controller"]); controller_utils(["@metamask/controller-utils"]); core_backend(["@metamask/core-backend"]); delegation_controller(["@metamask/delegation-controller"]); @@ -231,6 +233,8 @@ linkStyle default opacity:0.5 composable_controller --> base_controller; composable_controller --> messenger; composable_controller --> json_rpc_engine; + connectivity_controller --> base_controller; + connectivity_controller --> messenger; core_backend --> accounts_controller; core_backend --> controller_utils; core_backend --> keyring_controller; diff --git a/packages/connectivity-controller/CHANGELOG.md b/packages/connectivity-controller/CHANGELOG.md new file mode 100644 index 00000000000..a7b62e188a8 --- /dev/null +++ b/packages/connectivity-controller/CHANGELOG.md @@ -0,0 +1,14 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +### Added + +- Initial release ([#7623](https://github.com/MetaMask/core/pull/7623)) + +[Unreleased]: https://github.com/MetaMask/core/ diff --git a/packages/connectivity-controller/LICENSE b/packages/connectivity-controller/LICENSE new file mode 100644 index 00000000000..c8a0ff6be3a --- /dev/null +++ b/packages/connectivity-controller/LICENSE @@ -0,0 +1,20 @@ +MIT License + +Copyright (c) 2026 MetaMask + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE diff --git a/packages/connectivity-controller/README.md b/packages/connectivity-controller/README.md new file mode 100644 index 00000000000..fb6eabf17b6 --- /dev/null +++ b/packages/connectivity-controller/README.md @@ -0,0 +1,15 @@ +# `@metamask/connectivity-controller` + +ConnectivityController stores the device's internet connectivity status. + +## Installation + +`yarn add @metamask/connectivity-controller` + +or + +`npm install @metamask/connectivity-controller` + +## Contributing + +This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/core#readme). diff --git a/packages/connectivity-controller/jest.config.js b/packages/connectivity-controller/jest.config.js new file mode 100644 index 00000000000..ca084133399 --- /dev/null +++ b/packages/connectivity-controller/jest.config.js @@ -0,0 +1,26 @@ +/* + * For a detailed explanation regarding each configuration property and type check, visit: + * https://jestjs.io/docs/configuration + */ + +const merge = require('deepmerge'); +const path = require('path'); + +const baseConfig = require('../../jest.config.packages'); + +const displayName = path.basename(__dirname); + +module.exports = merge(baseConfig, { + // The display name when running multiple projects + displayName, + + // An object that configures minimum threshold enforcement for coverage results + coverageThreshold: { + global: { + branches: 100, + functions: 100, + lines: 100, + statements: 100, + }, + }, +}); diff --git a/packages/connectivity-controller/package.json b/packages/connectivity-controller/package.json new file mode 100644 index 00000000000..404f78b55e8 --- /dev/null +++ b/packages/connectivity-controller/package.json @@ -0,0 +1,72 @@ +{ + "name": "@metamask/connectivity-controller", + "version": "0.0.0", + "description": "ConnectivityController stores the device's internet connectivity status", + "keywords": [ + "MetaMask", + "Ethereum" + ], + "homepage": "https://github.com/MetaMask/core/tree/main/packages/connectivity-controller#readme", + "bugs": { + "url": "https://github.com/MetaMask/core/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/MetaMask/core.git" + }, + "license": "MIT", + "sideEffects": false, + "exports": { + ".": { + "import": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "require": { + "types": "./dist/index.d.cts", + "default": "./dist/index.cjs" + } + }, + "./package.json": "./package.json" + }, + "main": "./dist/index.cjs", + "types": "./dist/index.d.cts", + "files": [ + "dist/" + ], + "scripts": { + "build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references", + "build:all": "ts-bridge --project tsconfig.build.json --verbose --clean", + "build:docs": "typedoc", + "changelog:update": "../../scripts/update-changelog.sh @metamask/connectivity-controller", + "changelog:validate": "../../scripts/validate-changelog.sh @metamask/connectivity-controller", + "publish:preview": "yarn npm publish --tag preview", + "since-latest-release": "../../scripts/since-latest-release.sh", + "test": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter", + "test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache", + "test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose", + "test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch" + }, + "dependencies": { + "@metamask/base-controller": "^9.0.0", + "@metamask/messenger": "^0.3.0" + }, + "devDependencies": { + "@metamask/auto-changelog": "^3.4.4", + "@ts-bridge/cli": "^0.6.4", + "@types/jest": "^27.4.1", + "deepmerge": "^4.2.2", + "jest": "^27.5.1", + "ts-jest": "^27.1.4", + "typedoc": "^0.24.8", + "typedoc-plugin-missing-exports": "^2.0.0", + "typescript": "~5.3.3" + }, + "engines": { + "node": "^18.18 || >=20" + }, + "publishConfig": { + "access": "public", + "registry": "https://registry.npmjs.org/" + } +} diff --git a/packages/connectivity-controller/src/ConnectivityController.test.ts b/packages/connectivity-controller/src/ConnectivityController.test.ts new file mode 100644 index 00000000000..f8d3a896276 --- /dev/null +++ b/packages/connectivity-controller/src/ConnectivityController.test.ts @@ -0,0 +1,160 @@ +import { deriveStateFromMetadata } from '@metamask/base-controller'; +import { Messenger, MOCK_ANY_NAMESPACE } from '@metamask/messenger'; +import type { + MockAnyNamespace, + MessengerActions, + MessengerEvents, +} from '@metamask/messenger'; + +import type { ConnectivityControllerMessenger } from './ConnectivityController'; +import { ConnectivityController } from './ConnectivityController'; + +describe('ConnectivityController', () => { + describe('constructor', () => { + it('accepts initial state', async () => { + const givenState = {}; + + await withController( + { options: { state: givenState } }, + ({ controller }) => { + expect(controller.state).toStrictEqual(givenState); + }, + ); + }); + + it('fills in missing initial state with defaults', async () => { + await withController(({ controller }) => { + expect(controller.state).toMatchInlineSnapshot(`Object {}`); + }); + }); + }); + + describe('metadata', () => { + it('includes expected state in debug snapshots', async () => { + await withController(({ controller }) => { + expect( + deriveStateFromMetadata( + controller.state, + controller.metadata, + 'includeInDebugSnapshot', + ), + ).toMatchInlineSnapshot(`Object {}`); + }); + }); + + it('includes expected state in state logs', async () => { + await withController(({ controller }) => { + expect( + deriveStateFromMetadata( + controller.state, + controller.metadata, + 'includeInStateLogs', + ), + ).toMatchInlineSnapshot(`Object {}`); + }); + }); + + it('persists expected state', async () => { + await withController(({ controller }) => { + expect( + deriveStateFromMetadata( + controller.state, + controller.metadata, + 'persist', + ), + ).toMatchInlineSnapshot(`Object {}`); + }); + }); + + it('exposes expected state to UI', async () => { + await withController(({ controller }) => { + expect( + deriveStateFromMetadata( + controller.state, + controller.metadata, + 'usedInUi', + ), + ).toMatchInlineSnapshot(`Object {}`); + }); + }); + }); +}); + +/** + * The type of the messenger populated with all external actions and events + * required by the controller under test. + */ +type RootMessenger = Messenger< + MockAnyNamespace, + MessengerActions, + MessengerEvents +>; + +/** + * The callback that `withController` calls. + */ +type WithControllerCallback = (payload: { + controller: ConnectivityController; + rootMessenger: RootMessenger; + controllerMessenger: ConnectivityControllerMessenger; +}) => Promise | ReturnValue; + +/** + * The options that `withController` takes. + */ +type WithControllerOptions = { + options: Partial[0]>; +}; + +/** + * Constructs the messenger populated with all external actions and events + * required by the controller under test. + * + * @returns The root messenger. + */ +function getRootMessenger(): RootMessenger { + return new Messenger({ namespace: MOCK_ANY_NAMESPACE }); +} + +/** + * Constructs the messenger for the controller under test. + * + * @param rootMessenger - The root messenger, with all external actions and + * events required by the controller's messenger. + * @returns The controller-specific messenger. + */ +function getMessenger( + rootMessenger: RootMessenger, +): ConnectivityControllerMessenger { + return new Messenger({ + namespace: 'ConnectivityController', + parent: rootMessenger, + }); +} + +/** + * Wrap tests for the controller under test by ensuring that the controller is + * created ahead of time and then safely destroyed afterward as needed. + * + * @param args - Either a function, or an options bag + a function. The options + * bag contains arguments for the controller constructor. All constructor + * arguments are optional and will be filled in with defaults in as needed + * (including `messenger`). The function is called with the instantiated + * controller, root messenger, and controller messenger. + * @returns The same return value as the given function. + */ +async function withController( + ...args: + | [WithControllerCallback] + | [WithControllerOptions, WithControllerCallback] +): Promise { + const [{ options = {} }, testFunction] = + args.length === 2 ? args : [{}, args[0]]; + const rootMessenger = getRootMessenger(); + const controllerMessenger = getMessenger(rootMessenger); + const controller = new ConnectivityController({ + messenger: controllerMessenger, + ...options, + }); + return await testFunction({ controller, rootMessenger, controllerMessenger }); +} diff --git a/packages/connectivity-controller/src/ConnectivityController.ts b/packages/connectivity-controller/src/ConnectivityController.ts new file mode 100644 index 00000000000..76ba2bc4a7d --- /dev/null +++ b/packages/connectivity-controller/src/ConnectivityController.ts @@ -0,0 +1,158 @@ +import type { + ControllerGetStateAction, + ControllerStateChangeEvent, + StateMetadata, +} from '@metamask/base-controller'; +import { BaseController } from '@metamask/base-controller'; +import type { Messenger } from '@metamask/messenger'; + +/** + * The name of the {@link ConnectivityController}, used to namespace the + * controller's actions and events and to namespace the controller's state data + * when composed with other controllers. + */ +export const controllerName = 'ConnectivityController'; + +/** + * Describes the shape of the state object for {@link ConnectivityController}. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type +export type ConnectivityControllerState = { + // Empty state - to be implemented +}; + +/** + * The metadata for each property in {@link ConnectivityControllerState}. + */ +const connectivityControllerMetadata = + {} satisfies StateMetadata; + +/** + * Constructs the default {@link ConnectivityController} state. This allows + * consumers to provide a partial state object when initializing the controller + * and also helps in constructing complete state objects for this controller in + * tests. + * + * @returns The default {@link ConnectivityController} state. + */ +export function getDefaultConnectivityControllerState(): ConnectivityControllerState { + return {}; +} + +/** + * Retrieves the state of the {@link ConnectivityController}. + */ +export type ConnectivityControllerGetStateAction = ControllerGetStateAction< + typeof controllerName, + ConnectivityControllerState +>; + +/** + * Actions that {@link ConnectivityControllerMessenger} exposes to other consumers. + */ +export type ConnectivityControllerActions = + ConnectivityControllerGetStateAction; + +/** + * Actions from other messengers that {@link ConnectivityControllerMessenger} calls. + */ +type AllowedActions = never; + +/** + * Published when the state of {@link ConnectivityController} changes. + */ +export type ConnectivityControllerStateChangeEvent = ControllerStateChangeEvent< + typeof controllerName, + ConnectivityControllerState +>; + +/** + * Events that {@link ConnectivityControllerMessenger} exposes to other consumers. + */ +export type ConnectivityControllerEvents = + ConnectivityControllerStateChangeEvent; + +/** + * Events from other messengers that {@link ConnectivityControllerMessenger} subscribes + * to. + */ +type AllowedEvents = never; + +/** + * The messenger restricted to actions and events accessed by + * {@link ConnectivityController}. + */ +export type ConnectivityControllerMessenger = Messenger< + typeof controllerName, + ConnectivityControllerActions | AllowedActions, + ConnectivityControllerEvents | AllowedEvents +>; + +/** + * `ConnectivityController` manages connectivity for the application. + * + * @example + * + * ``` ts + * import { Messenger } from '@metamask/messenger'; + * import type { + * ConnectivityControllerActions, + * ConnectivityControllerEvents, + * } from '@metamask/connectivity-controller'; + * import { ConnectivityController } from '@metamask/connectivity-controller'; + * + * const rootMessenger = new Messenger< + * 'Root', + * ConnectivityControllerActions, + * ConnectivityControllerEvents + * >({ namespace: 'Root' }); + * const connectivityControllerMessenger = new Messenger< + * 'ConnectivityController', + * ConnectivityControllerActions, + * ConnectivityControllerEvents, + * typeof rootMessenger, + * >({ + * namespace: 'ConnectivityController', + * parent: rootMessenger, + * }); + * // Instantiate the controller to register its actions on the messenger + * new ConnectivityController({ + * messenger: connectivityControllerMessenger, + * }); + * + * const connectivityControllerState = await rootMessenger.call( + * 'ConnectivityController:getState', + * ); + * ``` + */ +export class ConnectivityController extends BaseController< + typeof controllerName, + ConnectivityControllerState, + ConnectivityControllerMessenger +> { + /** + * Constructs a new {@link ConnectivityController}. + * + * @param args - The arguments to this controller. + * @param args.messenger - The messenger suited for this controller. + * @param args.state - The desired state with which to initialize this + * controller. Missing properties will be filled in with defaults. + */ + constructor({ + messenger, + state, + }: { + messenger: ConnectivityControllerMessenger; + state?: Partial; + }) { + super({ + messenger, + metadata: connectivityControllerMetadata, + name: controllerName, + state: { + ...getDefaultConnectivityControllerState(), + ...state, + }, + }); + } +} diff --git a/packages/connectivity-controller/src/index.ts b/packages/connectivity-controller/src/index.ts new file mode 100644 index 00000000000..8f04773025d --- /dev/null +++ b/packages/connectivity-controller/src/index.ts @@ -0,0 +1,12 @@ +export type { + ConnectivityControllerState, + ConnectivityControllerGetStateAction, + ConnectivityControllerActions, + ConnectivityControllerStateChangeEvent, + ConnectivityControllerEvents, + ConnectivityControllerMessenger, +} from './ConnectivityController'; +export { + ConnectivityController, + getDefaultConnectivityControllerState, +} from './ConnectivityController'; diff --git a/packages/connectivity-controller/tsconfig.build.json b/packages/connectivity-controller/tsconfig.build.json new file mode 100644 index 00000000000..931c4d6594b --- /dev/null +++ b/packages/connectivity-controller/tsconfig.build.json @@ -0,0 +1,13 @@ +{ + "extends": "../../tsconfig.packages.build.json", + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist", + "rootDir": "./src" + }, + "references": [ + { "path": "../base-controller/tsconfig.build.json" }, + { "path": "../messenger/tsconfig.build.json" } + ], + "include": ["../../types", "./src"] +} diff --git a/packages/connectivity-controller/tsconfig.json b/packages/connectivity-controller/tsconfig.json new file mode 100644 index 00000000000..68c3ddfc2cd --- /dev/null +++ b/packages/connectivity-controller/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.packages.json", + "compilerOptions": { + "baseUrl": "./" + }, + "references": [{ "path": "../base-controller" }, { "path": "../messenger" }], + "include": ["../../types", "./src"] +} diff --git a/packages/connectivity-controller/typedoc.json b/packages/connectivity-controller/typedoc.json new file mode 100644 index 00000000000..c9da015dbf8 --- /dev/null +++ b/packages/connectivity-controller/typedoc.json @@ -0,0 +1,7 @@ +{ + "entryPoints": ["./src/index.ts"], + "excludePrivate": true, + "hideGenerator": true, + "out": "docs", + "tsconfig": "./tsconfig.build.json" +} diff --git a/teams.json b/teams.json index 0d749eecf5d..dc7dc9d2f93 100644 --- a/teams.json +++ b/teams.json @@ -37,6 +37,7 @@ "metamask/base-controller": "team-core-platform", "metamask/build-utils": "team-core-platform", "metamask/composable-controller": "team-core-platform", + "metamask/connectivity-controller": "team-core-platform", "metamask/controller-utils": "team-core-platform", "metamask/error-reporting-service": "team-core-platform", "metamask/messenger": "team-core-platform", diff --git a/tsconfig.build.json b/tsconfig.build.json index a76d9f8d06b..5231360a42a 100644 --- a/tsconfig.build.json +++ b/tsconfig.build.json @@ -21,6 +21,7 @@ { "path": "./packages/bridge-controller/tsconfig.build.json" }, { "path": "./packages/bridge-status-controller/tsconfig.build.json" }, { "path": "./packages/build-utils/tsconfig.build.json" }, + { "path": "./packages/connectivity-controller/tsconfig.build.json" }, { "path": "./packages/chain-agnostic-permission/tsconfig.build.json" }, { "path": "./packages/claims-controller/tsconfig.build.json" }, { "path": "./packages/composable-controller/tsconfig.build.json" }, diff --git a/tsconfig.json b/tsconfig.json index abe30f5662f..c818b2a0693 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,6 +21,7 @@ { "path": "./packages/bridge-controller" }, { "path": "./packages/bridge-status-controller" }, { "path": "./packages/build-utils" }, + { "path": "./packages/connectivity-controller" }, { "path": "./packages/chain-agnostic-permission" }, { "path": "./packages/claims-controller" }, { "path": "./packages/composable-controller" }, diff --git a/yarn.lock b/yarn.lock index 5da153fd94f..82462656171 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2964,6 +2964,24 @@ __metadata: languageName: unknown linkType: soft +"@metamask/connectivity-controller@workspace:packages/connectivity-controller": + version: 0.0.0-use.local + resolution: "@metamask/connectivity-controller@workspace:packages/connectivity-controller" + dependencies: + "@metamask/auto-changelog": "npm:^3.4.4" + "@metamask/base-controller": "npm:^9.0.0" + "@metamask/messenger": "npm:^0.3.0" + "@ts-bridge/cli": "npm:^0.6.4" + "@types/jest": "npm:^27.4.1" + deepmerge: "npm:^4.2.2" + jest: "npm:^27.5.1" + ts-jest: "npm:^27.1.4" + typedoc: "npm:^0.24.8" + typedoc-plugin-missing-exports: "npm:^2.0.0" + typescript: "npm:~5.3.3" + languageName: unknown + linkType: soft + "@metamask/contract-metadata@npm:^2.4.0": version: 2.5.0 resolution: "@metamask/contract-metadata@npm:2.5.0" From 9e00b40b5353f90ce196b8c944c1a412997d1caf Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Wed, 14 Jan 2026 14:44:53 +0100 Subject: [PATCH 2/6] feat: add initial controller implementation --- .../src/ConnectivityController.test.ts | 281 +++++++++++++++++- .../src/ConnectivityController.ts | 117 +++++--- packages/connectivity-controller/src/index.ts | 2 + packages/connectivity-controller/src/types.ts | 43 +++ 4 files changed, 384 insertions(+), 59 deletions(-) create mode 100644 packages/connectivity-controller/src/types.ts diff --git a/packages/connectivity-controller/src/ConnectivityController.test.ts b/packages/connectivity-controller/src/ConnectivityController.test.ts index f8d3a896276..99d7ca36d2b 100644 --- a/packages/connectivity-controller/src/ConnectivityController.test.ts +++ b/packages/connectivity-controller/src/ConnectivityController.test.ts @@ -7,25 +7,111 @@ import type { } from '@metamask/messenger'; import type { ConnectivityControllerMessenger } from './ConnectivityController'; -import { ConnectivityController } from './ConnectivityController'; +import { + ConnectivityController, + controllerName, +} from './ConnectivityController'; +import { ConnectivityStatus } from './types'; +import type { ConnectivityService } from './types'; + +/** + * A test implementation of ConnectivityService. + * Allows manual control of connectivity status via setStatus. + */ +class TestConnectivityService implements ConnectivityService { + #status: ConnectivityStatus; + + #onConnectivityChangeCallbacks: ((status: ConnectivityStatus) => void)[] = []; + + constructor(initialStatus: ConnectivityStatus = ConnectivityStatus.Online) { + this.#status = initialStatus; + } + + getStatus(): ConnectivityStatus { + return this.#status; + } + + onConnectivityChange(callback: (status: ConnectivityStatus) => void): void { + this.#onConnectivityChangeCallbacks.push(callback); + } + + setStatus(status: ConnectivityStatus): void { + this.#status = status; + this.#onConnectivityChangeCallbacks.forEach((callback) => callback(status)); + } + + destroy(): void { + this.#onConnectivityChangeCallbacks = []; + } +} describe('ConnectivityController', () => { describe('constructor', () => { - it('accepts initial state', async () => { - const givenState = {}; + it('uses service initial state when online', async () => { + const mockService: ConnectivityService = { + getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + onConnectivityChange: jest.fn(), + destroy: jest.fn(), + }; await withController( - { options: { state: givenState } }, + { options: { connectivityService: mockService } }, ({ controller }) => { - expect(controller.state).toStrictEqual(givenState); + expect(controller.state.connectivityStatus).toBe( + ConnectivityStatus.Online, + ); + expect(mockService.getStatus).toHaveBeenCalled(); }, ); }); - it('fills in missing initial state with defaults', async () => { - await withController(({ controller }) => { - expect(controller.state).toMatchInlineSnapshot(`Object {}`); - }); + it('uses service initial state when offline', async () => { + const mockService: ConnectivityService = { + getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Offline), + onConnectivityChange: jest.fn(), + destroy: jest.fn(), + }; + + await withController( + { options: { connectivityService: mockService } }, + ({ controller }) => { + expect(controller.state.connectivityStatus).toBe( + ConnectivityStatus.Offline, + ); + }, + ); + }); + + it('subscribes to service connectivity changes', async () => { + const mockService: ConnectivityService = { + getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + onConnectivityChange: jest.fn(), + destroy: jest.fn(), + }; + + await withController( + { options: { connectivityService: mockService } }, + () => { + expect(mockService.onConnectivityChange).toHaveBeenCalledWith( + expect.any(Function), + ); + }, + ); + }); + + it('has correct name property', async () => { + const mockService: ConnectivityService = { + getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + onConnectivityChange: jest.fn(), + destroy: jest.fn(), + }; + + await withController( + { options: { connectivityService: mockService } }, + ({ controller }) => { + expect(controller.name).toBe(controllerName); + }, + ); }); }); @@ -38,7 +124,11 @@ describe('ConnectivityController', () => { controller.metadata, 'includeInDebugSnapshot', ), - ).toMatchInlineSnapshot(`Object {}`); + ).toMatchInlineSnapshot(` + Object { + "connectivityStatus": "online", + } + `); }); }); @@ -50,7 +140,11 @@ describe('ConnectivityController', () => { controller.metadata, 'includeInStateLogs', ), - ).toMatchInlineSnapshot(`Object {}`); + ).toMatchInlineSnapshot(` + Object { + "connectivityStatus": "online", + } + `); }); }); @@ -74,10 +168,167 @@ describe('ConnectivityController', () => { controller.metadata, 'usedInUi', ), - ).toMatchInlineSnapshot(`Object {}`); + ).toMatchInlineSnapshot(` + Object { + "connectivityStatus": "online", + } + `); }); }); }); + + describe('service callbacks', () => { + it('updates state when service reports offline', async () => { + const mockOnConnectivityChange = jest.fn(); + const mockService: ConnectivityService = { + getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + onConnectivityChange: mockOnConnectivityChange, + destroy: jest.fn(), + }; + + await withController( + { options: { connectivityService: mockService } }, + ({ controller }) => { + expect(controller.state.connectivityStatus).toBe( + ConnectivityStatus.Online, + ); + + // Get the callback that was passed to onConnectivityChange + const capturedCallback = mockOnConnectivityChange.mock + .calls[0]?.[0] as + | ((status: ConnectivityStatus) => void) + | undefined; + expect(capturedCallback).toBeDefined(); + + // Simulate service reporting offline + capturedCallback?.(ConnectivityStatus.Offline); + + expect(controller.state.connectivityStatus).toBe( + ConnectivityStatus.Offline, + ); + }, + ); + }); + + it('updates state when service reports online', async () => { + const mockOnConnectivityChange = jest.fn(); + const mockService: ConnectivityService = { + getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Offline), + onConnectivityChange: mockOnConnectivityChange, + destroy: jest.fn(), + }; + + await withController( + { options: { connectivityService: mockService } }, + ({ controller }) => { + expect(controller.state.connectivityStatus).toBe( + ConnectivityStatus.Offline, + ); + + // Get the callback that was passed to onConnectivityChange + const capturedCallback = mockOnConnectivityChange.mock + .calls[0]?.[0] as + | ((status: ConnectivityStatus) => void) + | undefined; + expect(capturedCallback).toBeDefined(); + + // Simulate service reporting online + capturedCallback?.(ConnectivityStatus.Online); + + expect(controller.state.connectivityStatus).toBe( + ConnectivityStatus.Online, + ); + }, + ); + }); + + it('emits stateChange event when status changes', async () => { + const mockOnConnectivityChange = jest.fn(); + const mockService: ConnectivityService = { + getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + onConnectivityChange: mockOnConnectivityChange, + destroy: jest.fn(), + }; + + await withController( + { options: { connectivityService: mockService } }, + ({ controllerMessenger }) => { + const eventHandler = jest.fn(); + controllerMessenger.subscribe( + `${controllerName}:stateChange`, + eventHandler, + ); + + // Get the callback that was passed to onConnectivityChange + const capturedCallback = mockOnConnectivityChange.mock + .calls[0]?.[0] as + | ((status: ConnectivityStatus) => void) + | undefined; + expect(capturedCallback).toBeDefined(); + + capturedCallback?.(ConnectivityStatus.Offline); + + expect(eventHandler).toHaveBeenCalledWith( + { connectivityStatus: ConnectivityStatus.Offline }, + expect.any(Array), + ); + }, + ); + }); + + it('does not emit event when status does not change', async () => { + const mockOnConnectivityChange = jest.fn(); + const mockService: ConnectivityService = { + getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + onConnectivityChange: mockOnConnectivityChange, + destroy: jest.fn(), + }; + + await withController( + { options: { connectivityService: mockService } }, + ({ controllerMessenger }) => { + const eventHandler = jest.fn(); + controllerMessenger.subscribe( + `${controllerName}:stateChange`, + eventHandler, + ); + + // Get the callback that was passed to onConnectivityChange + const capturedCallback = mockOnConnectivityChange.mock + .calls[0]?.[0] as + | ((status: ConnectivityStatus) => void) + | undefined; + expect(capturedCallback).toBeDefined(); + + // Report online when already online + capturedCallback?.(ConnectivityStatus.Online); + + expect(eventHandler).not.toHaveBeenCalled(); + }, + ); + }); + }); + + describe('with TestConnectivityService', () => { + it('updates state when service.setStatus is called', async () => { + const service = new TestConnectivityService(); + + await withController( + { options: { connectivityService: service } }, + ({ controller }) => { + expect(controller.state.connectivityStatus).toBe( + ConnectivityStatus.Online, + ); + + service.setStatus(ConnectivityStatus.Offline); + + expect(controller.state.connectivityStatus).toBe( + ConnectivityStatus.Offline, + ); + }, + ); + }); + }); }); /** @@ -139,8 +390,8 @@ function getMessenger( * @param args - Either a function, or an options bag + a function. The options * bag contains arguments for the controller constructor. All constructor * arguments are optional and will be filled in with defaults in as needed - * (including `messenger`). The function is called with the instantiated - * controller, root messenger, and controller messenger. + * (including `messenger` and `connectivityService`). The function is called + * with the instantiated controller, root messenger, and controller messenger. * @returns The same return value as the given function. */ async function withController( @@ -152,8 +403,10 @@ async function withController( args.length === 2 ? args : [{}, args[0]]; const rootMessenger = getRootMessenger(); const controllerMessenger = getMessenger(rootMessenger); + const defaultService = new TestConnectivityService(); const controller = new ConnectivityController({ messenger: controllerMessenger, + connectivityService: defaultService, ...options, }); return await testFunction({ controller, rootMessenger, controllerMessenger }); diff --git a/packages/connectivity-controller/src/ConnectivityController.ts b/packages/connectivity-controller/src/ConnectivityController.ts index 76ba2bc4a7d..1fd9be1fcca 100644 --- a/packages/connectivity-controller/src/ConnectivityController.ts +++ b/packages/connectivity-controller/src/ConnectivityController.ts @@ -6,6 +6,9 @@ import type { import { BaseController } from '@metamask/base-controller'; import type { Messenger } from '@metamask/messenger'; +import { ConnectivityStatus } from './types'; +import type { ConnectivityService } from './types'; + /** * The name of the {@link ConnectivityController}, used to namespace the * controller's actions and events and to namespace the controller's state data @@ -14,18 +17,27 @@ import type { Messenger } from '@metamask/messenger'; export const controllerName = 'ConnectivityController'; /** - * Describes the shape of the state object for {@link ConnectivityController}. + * State for the {@link ConnectivityController}. */ -// eslint-disable-next-line @typescript-eslint/no-empty-object-type export type ConnectivityControllerState = { - // Empty state - to be implemented + /** + * The current device connectivity status. + * Named with 'connectivity' prefix to avoid conflicts when state is flattened in Redux. + */ + connectivityStatus: ConnectivityStatus; }; /** * The metadata for each property in {@link ConnectivityControllerState}. */ -const connectivityControllerMetadata = - {} satisfies StateMetadata; +const connectivityControllerMetadata = { + connectivityStatus: { + persist: false, + includeInDebugSnapshot: true, + includeInStateLogs: true, + usedInUi: true, + }, +} satisfies StateMetadata; /** * Constructs the default {@link ConnectivityController} state. This allows @@ -36,7 +48,9 @@ const connectivityControllerMetadata = * @returns The default {@link ConnectivityController} state. */ export function getDefaultConnectivityControllerState(): ConnectivityControllerState { - return {}; + return { + connectivityStatus: ConnectivityStatus.Online, + }; } /** @@ -89,41 +103,50 @@ export type ConnectivityControllerMessenger = Messenger< >; /** - * `ConnectivityController` manages connectivity for the application. + * Options for constructing the {@link ConnectivityController}. + */ +export type ConnectivityControllerOptions = { + /** + * The messenger for inter-controller communication. + */ + messenger: ConnectivityControllerMessenger; + + /** + * Connectivity service for platform-specific detection. + * + * The controller subscribes to the service's `onConnectivityChange` + * callback to receive connectivity updates. + * + * Platform implementations: + * - Mobile: Use `NetInfoConnectivityService` with `@react-native-community/netinfo` + * - Extension (same context): Use `BrowserConnectivityService` + * - Extension (cross-context): Use `PassiveConnectivityService` and call + * `setStatus()` from the UI context + */ + connectivityService: ConnectivityService; +}; + +/** + * ConnectivityController stores the device's internet connectivity status. * - * @example + * This controller is platform-agnostic and designed to be used across different + * MetaMask clients (extension, mobile). It requires a `ConnectivityService` to + * be injected, which provides platform-specific connectivity detection. * - * ``` ts - * import { Messenger } from '@metamask/messenger'; - * import type { - * ConnectivityControllerActions, - * ConnectivityControllerEvents, - * } from '@metamask/connectivity-controller'; - * import { ConnectivityController } from '@metamask/connectivity-controller'; + * The controller subscribes to the service's `onConnectivityChange` callback + * and updates its state accordingly. All connectivity updates flow through + * the service, ensuring a single source of truth. * - * const rootMessenger = new Messenger< - * 'Root', - * ConnectivityControllerActions, - * ConnectivityControllerEvents - * >({ namespace: 'Root' }); - * const connectivityControllerMessenger = new Messenger< - * 'ConnectivityController', - * ConnectivityControllerActions, - * ConnectivityControllerEvents, - * typeof rootMessenger, - * >({ - * namespace: 'ConnectivityController', - * parent: rootMessenger, - * }); - * // Instantiate the controller to register its actions on the messenger - * new ConnectivityController({ - * messenger: connectivityControllerMessenger, - * }); + * **Platform implementations:** * - * const connectivityControllerState = await rootMessenger.call( - * 'ConnectivityController:getState', - * ); - * ``` + * - **Mobile:** Inject `NetInfoConnectivityService` using `@react-native-community/netinfo` + * - **Extension:** Inject `PassiveConnectivityService` in the background. + * Status is updated via the `setDeviceConnectivityStatus` API, which is called from: + * - MV3: Offscreen document (where browser events work reliably) + * - MV2: Background page (where browser events work directly) + * + * This controller provides a centralized state for connectivity status, + * enabling the UI and other controllers to adapt when the user goes offline. */ export class ConnectivityController extends BaseController< typeof controllerName, @@ -135,24 +158,28 @@ export class ConnectivityController extends BaseController< * * @param args - The arguments to this controller. * @param args.messenger - The messenger suited for this controller. - * @param args.state - The desired state with which to initialize this - * controller. Missing properties will be filled in with defaults. + * @param args.connectivityService - The connectivity service to use. */ constructor({ messenger, - state, - }: { - messenger: ConnectivityControllerMessenger; - state?: Partial; - }) { + connectivityService, + }: ConnectivityControllerOptions) { + const initialStatus = connectivityService.getStatus(); + super({ messenger, metadata: connectivityControllerMetadata, name: controllerName, state: { ...getDefaultConnectivityControllerState(), - ...state, + connectivityStatus: initialStatus, }, }); + + connectivityService.onConnectivityChange((status) => { + this.update((draftState) => { + draftState.connectivityStatus = status; + }); + }); } } diff --git a/packages/connectivity-controller/src/index.ts b/packages/connectivity-controller/src/index.ts index 8f04773025d..fee79e50fd9 100644 --- a/packages/connectivity-controller/src/index.ts +++ b/packages/connectivity-controller/src/index.ts @@ -6,6 +6,8 @@ export type { ConnectivityControllerEvents, ConnectivityControllerMessenger, } from './ConnectivityController'; +export type { ConnectivityService } from './types'; +export { ConnectivityStatus } from './types'; export { ConnectivityController, getDefaultConnectivityControllerState, diff --git a/packages/connectivity-controller/src/types.ts b/packages/connectivity-controller/src/types.ts new file mode 100644 index 00000000000..48f0771a32e --- /dev/null +++ b/packages/connectivity-controller/src/types.ts @@ -0,0 +1,43 @@ +/** + * Connectivity status constants. + * Used to represent whether the device has internet connectivity. + */ +export const ConnectivityStatus = { + Online: 'online', + Offline: 'offline', +} as const; + +export type ConnectivityStatus = + (typeof ConnectivityStatus)[keyof typeof ConnectivityStatus]; + +/** + * Service interface for platform-specific connectivity detection. + * + * Each platform (extension, mobile) implements this interface using + * platform-specific APIs: + * - Extension: `navigator.onLine` and `online`/`offline` events + * - Mobile: `@react-native-community/netinfo` + * + * The service is injected into the ConnectivityController, which + * subscribes to connectivity changes and updates its state accordingly. + */ +export type ConnectivityService = { + /** + * Returns the current connectivity status. + * + * @returns 'online' if the device is online, 'offline' otherwise. + */ + getStatus(): ConnectivityStatus; + + /** + * Registers a callback to be called when connectivity status changes. + * + * @param callback - Function called with 'online' when online, 'offline' when offline. + */ + onConnectivityChange(callback: (status: ConnectivityStatus) => void): void; + + /** + * Cleans up any resources (event listeners, subscriptions). + */ + destroy(): void; +}; From 9d171f5a60034c219129f29fcbf0b5f928b81efa Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Wed, 14 Jan 2026 22:14:30 +0100 Subject: [PATCH 3/6] refactor(connectivity-controller): rename ConnectivityStatus to CONNECTIVITY_STATUSES - Rename ConnectivityStatus constant to CONNECTIVITY_STATUSES - Export ConnectivityStatus as a type instead of enum - Update all references to use CONNECTIVITY_STATUSES - Export CONNECTIVITY_STATUSES from index --- .../src/ConnectivityController.test.ts | 52 ++++++++++--------- .../src/ConnectivityController.ts | 6 +-- packages/connectivity-controller/src/index.ts | 4 +- packages/connectivity-controller/src/types.ts | 4 +- 4 files changed, 34 insertions(+), 32 deletions(-) diff --git a/packages/connectivity-controller/src/ConnectivityController.test.ts b/packages/connectivity-controller/src/ConnectivityController.test.ts index 99d7ca36d2b..cab93b3c321 100644 --- a/packages/connectivity-controller/src/ConnectivityController.test.ts +++ b/packages/connectivity-controller/src/ConnectivityController.test.ts @@ -11,8 +11,8 @@ import { ConnectivityController, controllerName, } from './ConnectivityController'; -import { ConnectivityStatus } from './types'; -import type { ConnectivityService } from './types'; +import { CONNECTIVITY_STATUSES } from './types'; +import type { ConnectivityService, ConnectivityStatus } from './types'; /** * A test implementation of ConnectivityService. @@ -23,7 +23,9 @@ class TestConnectivityService implements ConnectivityService { #onConnectivityChangeCallbacks: ((status: ConnectivityStatus) => void)[] = []; - constructor(initialStatus: ConnectivityStatus = ConnectivityStatus.Online) { + constructor( + initialStatus: ConnectivityStatus = CONNECTIVITY_STATUSES.Online, + ) { this.#status = initialStatus; } @@ -49,7 +51,7 @@ describe('ConnectivityController', () => { describe('constructor', () => { it('uses service initial state when online', async () => { const mockService: ConnectivityService = { - getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: jest.fn(), destroy: jest.fn(), }; @@ -58,7 +60,7 @@ describe('ConnectivityController', () => { { options: { connectivityService: mockService } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( - ConnectivityStatus.Online, + CONNECTIVITY_STATUSES.Online, ); expect(mockService.getStatus).toHaveBeenCalled(); }, @@ -67,7 +69,7 @@ describe('ConnectivityController', () => { it('uses service initial state when offline', async () => { const mockService: ConnectivityService = { - getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Offline), + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Offline), onConnectivityChange: jest.fn(), destroy: jest.fn(), }; @@ -76,7 +78,7 @@ describe('ConnectivityController', () => { { options: { connectivityService: mockService } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( - ConnectivityStatus.Offline, + CONNECTIVITY_STATUSES.Offline, ); }, ); @@ -84,7 +86,7 @@ describe('ConnectivityController', () => { it('subscribes to service connectivity changes', async () => { const mockService: ConnectivityService = { - getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: jest.fn(), destroy: jest.fn(), }; @@ -101,7 +103,7 @@ describe('ConnectivityController', () => { it('has correct name property', async () => { const mockService: ConnectivityService = { - getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: jest.fn(), destroy: jest.fn(), }; @@ -181,7 +183,7 @@ describe('ConnectivityController', () => { it('updates state when service reports offline', async () => { const mockOnConnectivityChange = jest.fn(); const mockService: ConnectivityService = { - getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: mockOnConnectivityChange, destroy: jest.fn(), }; @@ -190,7 +192,7 @@ describe('ConnectivityController', () => { { options: { connectivityService: mockService } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( - ConnectivityStatus.Online, + CONNECTIVITY_STATUSES.Online, ); // Get the callback that was passed to onConnectivityChange @@ -201,10 +203,10 @@ describe('ConnectivityController', () => { expect(capturedCallback).toBeDefined(); // Simulate service reporting offline - capturedCallback?.(ConnectivityStatus.Offline); + capturedCallback?.(CONNECTIVITY_STATUSES.Offline); expect(controller.state.connectivityStatus).toBe( - ConnectivityStatus.Offline, + CONNECTIVITY_STATUSES.Offline, ); }, ); @@ -213,7 +215,7 @@ describe('ConnectivityController', () => { it('updates state when service reports online', async () => { const mockOnConnectivityChange = jest.fn(); const mockService: ConnectivityService = { - getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Offline), + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Offline), onConnectivityChange: mockOnConnectivityChange, destroy: jest.fn(), }; @@ -222,7 +224,7 @@ describe('ConnectivityController', () => { { options: { connectivityService: mockService } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( - ConnectivityStatus.Offline, + CONNECTIVITY_STATUSES.Offline, ); // Get the callback that was passed to onConnectivityChange @@ -233,10 +235,10 @@ describe('ConnectivityController', () => { expect(capturedCallback).toBeDefined(); // Simulate service reporting online - capturedCallback?.(ConnectivityStatus.Online); + capturedCallback?.(CONNECTIVITY_STATUSES.Online); expect(controller.state.connectivityStatus).toBe( - ConnectivityStatus.Online, + CONNECTIVITY_STATUSES.Online, ); }, ); @@ -245,7 +247,7 @@ describe('ConnectivityController', () => { it('emits stateChange event when status changes', async () => { const mockOnConnectivityChange = jest.fn(); const mockService: ConnectivityService = { - getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: mockOnConnectivityChange, destroy: jest.fn(), }; @@ -266,10 +268,10 @@ describe('ConnectivityController', () => { | undefined; expect(capturedCallback).toBeDefined(); - capturedCallback?.(ConnectivityStatus.Offline); + capturedCallback?.(CONNECTIVITY_STATUSES.Offline); expect(eventHandler).toHaveBeenCalledWith( - { connectivityStatus: ConnectivityStatus.Offline }, + { connectivityStatus: CONNECTIVITY_STATUSES.Offline }, expect.any(Array), ); }, @@ -279,7 +281,7 @@ describe('ConnectivityController', () => { it('does not emit event when status does not change', async () => { const mockOnConnectivityChange = jest.fn(); const mockService: ConnectivityService = { - getStatus: jest.fn().mockReturnValue(ConnectivityStatus.Online), + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: mockOnConnectivityChange, destroy: jest.fn(), }; @@ -301,7 +303,7 @@ describe('ConnectivityController', () => { expect(capturedCallback).toBeDefined(); // Report online when already online - capturedCallback?.(ConnectivityStatus.Online); + capturedCallback?.(CONNECTIVITY_STATUSES.Online); expect(eventHandler).not.toHaveBeenCalled(); }, @@ -317,13 +319,13 @@ describe('ConnectivityController', () => { { options: { connectivityService: service } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( - ConnectivityStatus.Online, + CONNECTIVITY_STATUSES.Online, ); - service.setStatus(ConnectivityStatus.Offline); + service.setStatus(CONNECTIVITY_STATUSES.Offline); expect(controller.state.connectivityStatus).toBe( - ConnectivityStatus.Offline, + CONNECTIVITY_STATUSES.Offline, ); }, ); diff --git a/packages/connectivity-controller/src/ConnectivityController.ts b/packages/connectivity-controller/src/ConnectivityController.ts index 1fd9be1fcca..8928f31ccf1 100644 --- a/packages/connectivity-controller/src/ConnectivityController.ts +++ b/packages/connectivity-controller/src/ConnectivityController.ts @@ -6,8 +6,8 @@ import type { import { BaseController } from '@metamask/base-controller'; import type { Messenger } from '@metamask/messenger'; -import { ConnectivityStatus } from './types'; -import type { ConnectivityService } from './types'; +import { CONNECTIVITY_STATUSES } from './types'; +import type { ConnectivityService, ConnectivityStatus } from './types'; /** * The name of the {@link ConnectivityController}, used to namespace the @@ -49,7 +49,7 @@ const connectivityControllerMetadata = { */ export function getDefaultConnectivityControllerState(): ConnectivityControllerState { return { - connectivityStatus: ConnectivityStatus.Online, + connectivityStatus: CONNECTIVITY_STATUSES.Online, }; } diff --git a/packages/connectivity-controller/src/index.ts b/packages/connectivity-controller/src/index.ts index fee79e50fd9..d171cb0bf1b 100644 --- a/packages/connectivity-controller/src/index.ts +++ b/packages/connectivity-controller/src/index.ts @@ -6,8 +6,8 @@ export type { ConnectivityControllerEvents, ConnectivityControllerMessenger, } from './ConnectivityController'; -export type { ConnectivityService } from './types'; -export { ConnectivityStatus } from './types'; +export type { ConnectivityService, ConnectivityStatus } from './types'; +export { CONNECTIVITY_STATUSES } from './types'; export { ConnectivityController, getDefaultConnectivityControllerState, diff --git a/packages/connectivity-controller/src/types.ts b/packages/connectivity-controller/src/types.ts index 48f0771a32e..c64d94b3024 100644 --- a/packages/connectivity-controller/src/types.ts +++ b/packages/connectivity-controller/src/types.ts @@ -2,13 +2,13 @@ * Connectivity status constants. * Used to represent whether the device has internet connectivity. */ -export const ConnectivityStatus = { +export const CONNECTIVITY_STATUSES = { Online: 'online', Offline: 'offline', } as const; export type ConnectivityStatus = - (typeof ConnectivityStatus)[keyof typeof ConnectivityStatus]; + (typeof CONNECTIVITY_STATUSES)[keyof typeof CONNECTIVITY_STATUSES]; /** * Service interface for platform-specific connectivity detection. From eda16e41722eec8742eb145f6139160134dd0b96 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Wed, 14 Jan 2026 22:20:10 +0100 Subject: [PATCH 4/6] refactor(connectivity-controller): twik jsdoc --- .../src/ConnectivityController.ts | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/packages/connectivity-controller/src/ConnectivityController.ts b/packages/connectivity-controller/src/ConnectivityController.ts index 8928f31ccf1..eeb63d71675 100644 --- a/packages/connectivity-controller/src/ConnectivityController.ts +++ b/packages/connectivity-controller/src/ConnectivityController.ts @@ -113,15 +113,6 @@ export type ConnectivityControllerOptions = { /** * Connectivity service for platform-specific detection. - * - * The controller subscribes to the service's `onConnectivityChange` - * callback to receive connectivity updates. - * - * Platform implementations: - * - Mobile: Use `NetInfoConnectivityService` with `@react-native-community/netinfo` - * - Extension (same context): Use `BrowserConnectivityService` - * - Extension (cross-context): Use `PassiveConnectivityService` and call - * `setStatus()` from the UI context */ connectivityService: ConnectivityService; }; @@ -137,14 +128,6 @@ export type ConnectivityControllerOptions = { * and updates its state accordingly. All connectivity updates flow through * the service, ensuring a single source of truth. * - * **Platform implementations:** - * - * - **Mobile:** Inject `NetInfoConnectivityService` using `@react-native-community/netinfo` - * - **Extension:** Inject `PassiveConnectivityService` in the background. - * Status is updated via the `setDeviceConnectivityStatus` API, which is called from: - * - MV3: Offscreen document (where browser events work reliably) - * - MV2: Background page (where browser events work directly) - * * This controller provides a centralized state for connectivity status, * enabling the UI and other controllers to adapt when the user goes offline. */ From 85ecacbae6d8790d7be4727fee5923f74b5e4d99 Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Wed, 14 Jan 2026 22:49:52 +0100 Subject: [PATCH 5/6] refactor(connectivity-controller): rename ConnectivityService to ConnectivityAdapter --- .../src/ConnectivityController.test.ts | 58 +++++++++---------- .../src/ConnectivityController.ts | 20 +++---- packages/connectivity-controller/src/index.ts | 2 +- packages/connectivity-controller/src/types.ts | 12 +--- 4 files changed, 43 insertions(+), 49 deletions(-) diff --git a/packages/connectivity-controller/src/ConnectivityController.test.ts b/packages/connectivity-controller/src/ConnectivityController.test.ts index cab93b3c321..caeb87f728f 100644 --- a/packages/connectivity-controller/src/ConnectivityController.test.ts +++ b/packages/connectivity-controller/src/ConnectivityController.test.ts @@ -12,13 +12,13 @@ import { controllerName, } from './ConnectivityController'; import { CONNECTIVITY_STATUSES } from './types'; -import type { ConnectivityService, ConnectivityStatus } from './types'; +import type { ConnectivityAdapter, ConnectivityStatus } from './types'; /** - * A test implementation of ConnectivityService. + * A test implementation of ConnectivityAdapter. * Allows manual control of connectivity status via setStatus. */ -class TestConnectivityService implements ConnectivityService { +class TestConnectivityAdapter implements ConnectivityAdapter { #status: ConnectivityStatus; #onConnectivityChangeCallbacks: ((status: ConnectivityStatus) => void)[] = []; @@ -50,32 +50,32 @@ class TestConnectivityService implements ConnectivityService { describe('ConnectivityController', () => { describe('constructor', () => { it('uses service initial state when online', async () => { - const mockService: ConnectivityService = { + const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: jest.fn(), destroy: jest.fn(), }; await withController( - { options: { connectivityService: mockService } }, + { options: { connectivityAdapter: mockAdapter } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Online, ); - expect(mockService.getStatus).toHaveBeenCalled(); + expect(mockAdapter.getStatus).toHaveBeenCalled(); }, ); }); it('uses service initial state when offline', async () => { - const mockService: ConnectivityService = { + const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Offline), onConnectivityChange: jest.fn(), destroy: jest.fn(), }; await withController( - { options: { connectivityService: mockService } }, + { options: { connectivityAdapter: mockAdapter } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Offline, @@ -85,16 +85,16 @@ describe('ConnectivityController', () => { }); it('subscribes to service connectivity changes', async () => { - const mockService: ConnectivityService = { + const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: jest.fn(), destroy: jest.fn(), }; await withController( - { options: { connectivityService: mockService } }, + { options: { connectivityAdapter: mockAdapter } }, () => { - expect(mockService.onConnectivityChange).toHaveBeenCalledWith( + expect(mockAdapter.onConnectivityChange).toHaveBeenCalledWith( expect.any(Function), ); }, @@ -102,14 +102,14 @@ describe('ConnectivityController', () => { }); it('has correct name property', async () => { - const mockService: ConnectivityService = { + const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: jest.fn(), destroy: jest.fn(), }; await withController( - { options: { connectivityService: mockService } }, + { options: { connectivityAdapter: mockAdapter } }, ({ controller }) => { expect(controller.name).toBe(controllerName); }, @@ -182,14 +182,14 @@ describe('ConnectivityController', () => { describe('service callbacks', () => { it('updates state when service reports offline', async () => { const mockOnConnectivityChange = jest.fn(); - const mockService: ConnectivityService = { + const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: mockOnConnectivityChange, destroy: jest.fn(), }; await withController( - { options: { connectivityService: mockService } }, + { options: { connectivityAdapter: mockAdapter } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Online, @@ -214,14 +214,14 @@ describe('ConnectivityController', () => { it('updates state when service reports online', async () => { const mockOnConnectivityChange = jest.fn(); - const mockService: ConnectivityService = { + const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Offline), onConnectivityChange: mockOnConnectivityChange, destroy: jest.fn(), }; await withController( - { options: { connectivityService: mockService } }, + { options: { connectivityAdapter: mockAdapter } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Offline, @@ -246,14 +246,14 @@ describe('ConnectivityController', () => { it('emits stateChange event when status changes', async () => { const mockOnConnectivityChange = jest.fn(); - const mockService: ConnectivityService = { + const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: mockOnConnectivityChange, destroy: jest.fn(), }; await withController( - { options: { connectivityService: mockService } }, + { options: { connectivityAdapter: mockAdapter } }, ({ controllerMessenger }) => { const eventHandler = jest.fn(); controllerMessenger.subscribe( @@ -280,14 +280,14 @@ describe('ConnectivityController', () => { it('does not emit event when status does not change', async () => { const mockOnConnectivityChange = jest.fn(); - const mockService: ConnectivityService = { + const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), onConnectivityChange: mockOnConnectivityChange, destroy: jest.fn(), }; await withController( - { options: { connectivityService: mockService } }, + { options: { connectivityAdapter: mockAdapter } }, ({ controllerMessenger }) => { const eventHandler = jest.fn(); controllerMessenger.subscribe( @@ -311,18 +311,18 @@ describe('ConnectivityController', () => { }); }); - describe('with TestConnectivityService', () => { - it('updates state when service.setStatus is called', async () => { - const service = new TestConnectivityService(); + describe('with TestConnectivityAdapter', () => { + it('updates state when adapter.setStatus is called', async () => { + const adapter = new TestConnectivityAdapter(); await withController( - { options: { connectivityService: service } }, + { options: { connectivityAdapter: adapter } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Online, ); - service.setStatus(CONNECTIVITY_STATUSES.Offline); + adapter.setStatus(CONNECTIVITY_STATUSES.Offline); expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Offline, @@ -392,7 +392,7 @@ function getMessenger( * @param args - Either a function, or an options bag + a function. The options * bag contains arguments for the controller constructor. All constructor * arguments are optional and will be filled in with defaults in as needed - * (including `messenger` and `connectivityService`). The function is called + * (including `messenger` and `connectivityAdapter`). The function is called * with the instantiated controller, root messenger, and controller messenger. * @returns The same return value as the given function. */ @@ -405,10 +405,10 @@ async function withController( args.length === 2 ? args : [{}, args[0]]; const rootMessenger = getRootMessenger(); const controllerMessenger = getMessenger(rootMessenger); - const defaultService = new TestConnectivityService(); + const defaultAdapter = new TestConnectivityAdapter(); const controller = new ConnectivityController({ messenger: controllerMessenger, - connectivityService: defaultService, + connectivityAdapter: defaultAdapter, ...options, }); return await testFunction({ controller, rootMessenger, controllerMessenger }); diff --git a/packages/connectivity-controller/src/ConnectivityController.ts b/packages/connectivity-controller/src/ConnectivityController.ts index eeb63d71675..63bd8e304aa 100644 --- a/packages/connectivity-controller/src/ConnectivityController.ts +++ b/packages/connectivity-controller/src/ConnectivityController.ts @@ -7,7 +7,7 @@ import { BaseController } from '@metamask/base-controller'; import type { Messenger } from '@metamask/messenger'; import { CONNECTIVITY_STATUSES } from './types'; -import type { ConnectivityService, ConnectivityStatus } from './types'; +import type { ConnectivityAdapter, ConnectivityStatus } from './types'; /** * The name of the {@link ConnectivityController}, used to namespace the @@ -112,21 +112,21 @@ export type ConnectivityControllerOptions = { messenger: ConnectivityControllerMessenger; /** - * Connectivity service for platform-specific detection. + * Connectivity adapter for platform-specific detection. */ - connectivityService: ConnectivityService; + connectivityAdapter: ConnectivityAdapter; }; /** * ConnectivityController stores the device's internet connectivity status. * * This controller is platform-agnostic and designed to be used across different - * MetaMask clients (extension, mobile). It requires a `ConnectivityService` to + * MetaMask clients (extension, mobile). It requires a `ConnectivityAdapter` to * be injected, which provides platform-specific connectivity detection. * - * The controller subscribes to the service's `onConnectivityChange` callback + * The controller subscribes to the adapter's `onConnectivityChange` callback * and updates its state accordingly. All connectivity updates flow through - * the service, ensuring a single source of truth. + * the adapter, ensuring a single source of truth. * * This controller provides a centralized state for connectivity status, * enabling the UI and other controllers to adapt when the user goes offline. @@ -141,13 +141,13 @@ export class ConnectivityController extends BaseController< * * @param args - The arguments to this controller. * @param args.messenger - The messenger suited for this controller. - * @param args.connectivityService - The connectivity service to use. + * @param args.connectivityAdapter - The connectivity adapter to use. */ constructor({ messenger, - connectivityService, + connectivityAdapter, }: ConnectivityControllerOptions) { - const initialStatus = connectivityService.getStatus(); + const initialStatus = connectivityAdapter.getStatus(); super({ messenger, @@ -159,7 +159,7 @@ export class ConnectivityController extends BaseController< }, }); - connectivityService.onConnectivityChange((status) => { + connectivityAdapter.onConnectivityChange((status) => { this.update((draftState) => { draftState.connectivityStatus = status; }); diff --git a/packages/connectivity-controller/src/index.ts b/packages/connectivity-controller/src/index.ts index d171cb0bf1b..d3306e84e19 100644 --- a/packages/connectivity-controller/src/index.ts +++ b/packages/connectivity-controller/src/index.ts @@ -6,7 +6,7 @@ export type { ConnectivityControllerEvents, ConnectivityControllerMessenger, } from './ConnectivityController'; -export type { ConnectivityService, ConnectivityStatus } from './types'; +export type { ConnectivityAdapter, ConnectivityStatus } from './types'; export { CONNECTIVITY_STATUSES } from './types'; export { ConnectivityController, diff --git a/packages/connectivity-controller/src/types.ts b/packages/connectivity-controller/src/types.ts index c64d94b3024..13b336064fd 100644 --- a/packages/connectivity-controller/src/types.ts +++ b/packages/connectivity-controller/src/types.ts @@ -11,17 +11,11 @@ export type ConnectivityStatus = (typeof CONNECTIVITY_STATUSES)[keyof typeof CONNECTIVITY_STATUSES]; /** - * Service interface for platform-specific connectivity detection. - * + * Adapter interface for platform-specific connectivity detection. * Each platform (extension, mobile) implements this interface using - * platform-specific APIs: - * - Extension: `navigator.onLine` and `online`/`offline` events - * - Mobile: `@react-native-community/netinfo` - * - * The service is injected into the ConnectivityController, which - * subscribes to connectivity changes and updates its state accordingly. + * platform-specific APIs to detect internet connectivity. */ -export type ConnectivityService = { +export type ConnectivityAdapter = { /** * Returns the current connectivity status. * From 16c51b55a5cc3e4435f70715cbecedfe7e04fdde Mon Sep 17 00:00:00 2001 From: Salah-Eddine Saakoun Date: Thu, 15 Jan 2026 00:13:24 +0100 Subject: [PATCH 6/6] refactor: simplify and remove useless tests --- .../src/ConnectivityController.test.ts | 209 +++--------------- 1 file changed, 25 insertions(+), 184 deletions(-) diff --git a/packages/connectivity-controller/src/ConnectivityController.test.ts b/packages/connectivity-controller/src/ConnectivityController.test.ts index caeb87f728f..c7826c5118a 100644 --- a/packages/connectivity-controller/src/ConnectivityController.test.ts +++ b/packages/connectivity-controller/src/ConnectivityController.test.ts @@ -7,46 +7,10 @@ import type { } from '@metamask/messenger'; import type { ConnectivityControllerMessenger } from './ConnectivityController'; -import { - ConnectivityController, - controllerName, -} from './ConnectivityController'; +import { ConnectivityController } from './ConnectivityController'; import { CONNECTIVITY_STATUSES } from './types'; import type { ConnectivityAdapter, ConnectivityStatus } from './types'; -/** - * A test implementation of ConnectivityAdapter. - * Allows manual control of connectivity status via setStatus. - */ -class TestConnectivityAdapter implements ConnectivityAdapter { - #status: ConnectivityStatus; - - #onConnectivityChangeCallbacks: ((status: ConnectivityStatus) => void)[] = []; - - constructor( - initialStatus: ConnectivityStatus = CONNECTIVITY_STATUSES.Online, - ) { - this.#status = initialStatus; - } - - getStatus(): ConnectivityStatus { - return this.#status; - } - - onConnectivityChange(callback: (status: ConnectivityStatus) => void): void { - this.#onConnectivityChangeCallbacks.push(callback); - } - - setStatus(status: ConnectivityStatus): void { - this.#status = status; - this.#onConnectivityChangeCallbacks.forEach((callback) => callback(status)); - } - - destroy(): void { - this.#onConnectivityChangeCallbacks = []; - } -} - describe('ConnectivityController', () => { describe('constructor', () => { it('uses service initial state when online', async () => { @@ -83,38 +47,6 @@ describe('ConnectivityController', () => { }, ); }); - - it('subscribes to service connectivity changes', async () => { - const mockAdapter: ConnectivityAdapter = { - getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), - onConnectivityChange: jest.fn(), - destroy: jest.fn(), - }; - - await withController( - { options: { connectivityAdapter: mockAdapter } }, - () => { - expect(mockAdapter.onConnectivityChange).toHaveBeenCalledWith( - expect.any(Function), - ); - }, - ); - }); - - it('has correct name property', async () => { - const mockAdapter: ConnectivityAdapter = { - getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), - onConnectivityChange: jest.fn(), - destroy: jest.fn(), - }; - - await withController( - { options: { connectivityAdapter: mockAdapter } }, - ({ controller }) => { - expect(controller.name).toBe(controllerName); - }, - ); - }); }); describe('metadata', () => { @@ -179,32 +111,28 @@ describe('ConnectivityController', () => { }); }); - describe('service callbacks', () => { + describe('when connectivity changes via the adapter', () => { it('updates state when service reports offline', async () => { - const mockOnConnectivityChange = jest.fn(); + let onConnectivityChangeCallback: ( + connectivityStatus: ConnectivityStatus, + ) => void; const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), - onConnectivityChange: mockOnConnectivityChange, + onConnectivityChange( + callback: (connectivityStatus: ConnectivityStatus) => void, + ) { + onConnectivityChangeCallback = callback; + }, destroy: jest.fn(), }; - await withController( { options: { connectivityAdapter: mockAdapter } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Online, ); - - // Get the callback that was passed to onConnectivityChange - const capturedCallback = mockOnConnectivityChange.mock - .calls[0]?.[0] as - | ((status: ConnectivityStatus) => void) - | undefined; - expect(capturedCallback).toBeDefined(); - // Simulate service reporting offline - capturedCallback?.(CONNECTIVITY_STATUSES.Offline); - + onConnectivityChangeCallback(CONNECTIVITY_STATUSES.Offline); expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Offline, ); @@ -213,123 +141,32 @@ describe('ConnectivityController', () => { }); it('updates state when service reports online', async () => { - const mockOnConnectivityChange = jest.fn(); + let onConnectivityChangeCallback: ( + connectivityStatus: ConnectivityStatus, + ) => void; const mockAdapter: ConnectivityAdapter = { getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Offline), - onConnectivityChange: mockOnConnectivityChange, + onConnectivityChange( + callback: (connectivityStatus: ConnectivityStatus) => void, + ) { + onConnectivityChangeCallback = callback; + }, destroy: jest.fn(), }; - await withController( { options: { connectivityAdapter: mockAdapter } }, ({ controller }) => { expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Offline, ); - - // Get the callback that was passed to onConnectivityChange - const capturedCallback = mockOnConnectivityChange.mock - .calls[0]?.[0] as - | ((status: ConnectivityStatus) => void) - | undefined; - expect(capturedCallback).toBeDefined(); - // Simulate service reporting online - capturedCallback?.(CONNECTIVITY_STATUSES.Online); - + onConnectivityChangeCallback(CONNECTIVITY_STATUSES.Online); expect(controller.state.connectivityStatus).toBe( CONNECTIVITY_STATUSES.Online, ); }, ); }); - - it('emits stateChange event when status changes', async () => { - const mockOnConnectivityChange = jest.fn(); - const mockAdapter: ConnectivityAdapter = { - getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), - onConnectivityChange: mockOnConnectivityChange, - destroy: jest.fn(), - }; - - await withController( - { options: { connectivityAdapter: mockAdapter } }, - ({ controllerMessenger }) => { - const eventHandler = jest.fn(); - controllerMessenger.subscribe( - `${controllerName}:stateChange`, - eventHandler, - ); - - // Get the callback that was passed to onConnectivityChange - const capturedCallback = mockOnConnectivityChange.mock - .calls[0]?.[0] as - | ((status: ConnectivityStatus) => void) - | undefined; - expect(capturedCallback).toBeDefined(); - - capturedCallback?.(CONNECTIVITY_STATUSES.Offline); - - expect(eventHandler).toHaveBeenCalledWith( - { connectivityStatus: CONNECTIVITY_STATUSES.Offline }, - expect.any(Array), - ); - }, - ); - }); - - it('does not emit event when status does not change', async () => { - const mockOnConnectivityChange = jest.fn(); - const mockAdapter: ConnectivityAdapter = { - getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), - onConnectivityChange: mockOnConnectivityChange, - destroy: jest.fn(), - }; - - await withController( - { options: { connectivityAdapter: mockAdapter } }, - ({ controllerMessenger }) => { - const eventHandler = jest.fn(); - controllerMessenger.subscribe( - `${controllerName}:stateChange`, - eventHandler, - ); - - // Get the callback that was passed to onConnectivityChange - const capturedCallback = mockOnConnectivityChange.mock - .calls[0]?.[0] as - | ((status: ConnectivityStatus) => void) - | undefined; - expect(capturedCallback).toBeDefined(); - - // Report online when already online - capturedCallback?.(CONNECTIVITY_STATUSES.Online); - - expect(eventHandler).not.toHaveBeenCalled(); - }, - ); - }); - }); - - describe('with TestConnectivityAdapter', () => { - it('updates state when adapter.setStatus is called', async () => { - const adapter = new TestConnectivityAdapter(); - - await withController( - { options: { connectivityAdapter: adapter } }, - ({ controller }) => { - expect(controller.state.connectivityStatus).toBe( - CONNECTIVITY_STATUSES.Online, - ); - - adapter.setStatus(CONNECTIVITY_STATUSES.Offline); - - expect(controller.state.connectivityStatus).toBe( - CONNECTIVITY_STATUSES.Offline, - ); - }, - ); - }); }); }); @@ -405,7 +242,11 @@ async function withController( args.length === 2 ? args : [{}, args[0]]; const rootMessenger = getRootMessenger(); const controllerMessenger = getMessenger(rootMessenger); - const defaultAdapter = new TestConnectivityAdapter(); + const defaultAdapter: ConnectivityAdapter = { + getStatus: jest.fn().mockReturnValue(CONNECTIVITY_STATUSES.Online), + onConnectivityChange: jest.fn(), + destroy: jest.fn(), + }; const controller = new ConnectivityController({ messenger: controllerMessenger, connectivityAdapter: defaultAdapter,