UNPKG

@metamask/snaps-rpc-methods

Version:
109 lines 3.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.openWebSocketHandler = void 0; const rpc_errors_1 = require("@metamask/rpc-errors"); const snaps_sdk_1 = require("@metamask/snaps-sdk"); const snaps_utils_1 = require("@metamask/snaps-utils"); const superstruct_1 = require("@metamask/superstruct"); const endowments_1 = require("../endowments/index.cjs"); const OpenWebSocketParametersStruct = (0, superstruct_1.object)({ url: (0, snaps_utils_1.uri)({ protocol: (0, snaps_sdk_1.union)([(0, snaps_sdk_1.literal)('wss:'), (0, snaps_sdk_1.literal)('ws:')]) }), protocols: (0, superstruct_1.optional)((0, superstruct_1.array)((0, superstruct_1.string)())), }); /** * Open a WebSocket connection to the specified URL with optional protocols. * * Note: This method is only available to snaps that have the * [`endowment:network-access`](https://docs.metamask.io/snaps/features/network-access/) * permission. * * @example * ```json name="Manifest" * { * "initialPermissions": { * "endowment:network-access": {} * } * } * ``` * ```ts name="Usage" * // Open a connection to a WebSocket server, e.g., in the JSON-RPC handler of * // the Snap: * snap.request({ * method: 'snap_openWebSocket', * params: { * url: 'wss://example.com/socket', * protocols: ['protocol1', 'protocol2'], // Optional * }, * }); * * // Listen for events from the WebSocket connection in the `onWebSocketEvent` * // handler of the Snap: * export const onWebSocketEvent: OnWebSocketEventHandler = async ({ event }) => { * switch (event.type) { * case 'open': * console.log(`WebSocket connection opened with origin ${event.origin}`); * break; * case 'message': * console.log(`WebSocket message received from origin ${event.origin}:`, event.data); * break; * case 'close': * console.log(`WebSocket connection closed with origin ${event.origin}`); * break; * case 'error': * console.error(`WebSocket error from origin ${event.origin}:`, event.error); * break; * } * }; * ``` */ exports.openWebSocketHandler = { implementation: openWebSocketImplementation, actionNames: ['PermissionController:hasPermission', 'WebSocketService:open'], }; /** * The `snap_openWebSocket` method implementation. * * @param req - The JSON-RPC request object. * @param res - The JSON-RPC response object. * @param _next - The `json-rpc-engine` "next" callback. Not used by this function. * @param end - The `json-rpc-engine` "end" callback. * @param _hooks - The RPC method hooks. Not used by this function. * @param messenger - The messenger used to call controller actions. * @returns Nothing. */ async function openWebSocketImplementation(req, res, _next, end, _hooks, messenger) { const { params, origin } = req; if (!messenger.call('PermissionController:hasPermission', origin, endowments_1.SnapEndowments.NetworkAccess)) { return end(rpc_errors_1.providerErrors.unauthorized()); } try { const { url, protocols } = getValidatedParams(params); res.result = await messenger.call('WebSocketService:open', origin, url, protocols); } catch (error) { return end(error); } return end(); } /** * Validates the parameters for the snap_openWebSocket method. * * @param params - Parameters to validate. * @returns Validated parameters. * @throws Throws RPC error if validation fails. */ function getValidatedParams(params) { try { return (0, superstruct_1.create)(params, OpenWebSocketParametersStruct); } catch (error) { if (error instanceof superstruct_1.StructError) { throw rpc_errors_1.rpcErrors.invalidParams({ message: `Invalid params: ${error.message}.`, }); } /* istanbul ignore next */ throw rpc_errors_1.rpcErrors.internal(); } } //# sourceMappingURL=openWebSocket.cjs.map