UNPKG

@metamask/snaps-rpc-methods

Version:
90 lines 3.27 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.trackEventHandler = void 0; const rpc_errors_1 = require("@metamask/rpc-errors"); const superstruct_1 = require("@metamask/superstruct"); const utils_1 = require("@metamask/utils"); const PropertiesStruct = (0, superstruct_1.optional)((0, superstruct_1.record)((0, superstruct_1.string)(), utils_1.JsonStruct)); const snakeCaseRegex = /^[a-z][a-z0-9]*(?:_[a-z0-9]+)*$/u; const SnakeCasePropertiesStruct = (0, superstruct_1.refine)(PropertiesStruct, 'snake_case_keys', (value) => { if (!value) { return true; } return Object.keys(value).every((key) => snakeCaseRegex.test(key)); }); const hookNames = { trackEvent: true, }; const TrackEventParametersStruct = (0, superstruct_1.object)({ event: (0, superstruct_1.object)({ event: (0, superstruct_1.string)(), properties: SnakeCasePropertiesStruct, sensitiveProperties: SnakeCasePropertiesStruct, }), }); /** * Handler for the `snap_trackEvent` method. * * @internal */ exports.trackEventHandler = { implementation: getTrackEventImplementation, hookNames, actionNames: ['SnapController:getSnap'], }; /** * The `snap_trackEvent` method implementation. * This method allows pre-installed Snaps to submit tracking events to the client. * * @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. * @param hooks.trackEvent - The function to track the event. * @param messenger - The messenger used to call controller actions. * @returns Nothing. */ function getTrackEventImplementation(req, res, _next, end, { trackEvent }, messenger) { const snap = messenger.call('SnapController:getSnap', req.origin); if (!snap?.preinstalled) { return end(rpc_errors_1.rpcErrors.methodNotFound()); } const { params } = req; try { const validatedParams = getValidatedParams(params); trackEvent(validatedParams.event); res.result = null; } catch (error) { return end(error); } return end(); } /** * Validates the parameters for the snap_trackEvent 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, TrackEventParametersStruct); } catch (error) { if (error instanceof superstruct_1.StructError) { if (error.refinement === 'snake_case_keys') { throw rpc_errors_1.rpcErrors.invalidParams({ message: `Invalid params: All property keys must be in snake_case format. The following key contains invalid properties: "${error.key}".`, }); } throw rpc_errors_1.rpcErrors.invalidParams({ message: `Invalid params: ${error.message}.`, }); } /* istanbul ignore next */ throw rpc_errors_1.rpcErrors.internal(); } } //# sourceMappingURL=trackEvent.cjs.map