Socket
Socket
Sign inDemoInstall

@toruslabs/openlogin-jrpc

Package Overview
Dependencies
Maintainers
5
Versions
97
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@toruslabs/openlogin-jrpc - npm Package Compare versions

Comparing version 8.1.1 to 8.3.0

dist/types/errors/error-constants.d.ts

659

dist/openloginJrpc.esm.js
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import { Duplex } from 'readable-stream';
import safeStringify from 'fast-safe-stringify';
import _objectSpread from '@babel/runtime/helpers/objectSpread2';
import { EventEmitter } from 'events';
import stringify from 'fast-safe-stringify';
import _objectSpread from '@babel/runtime/helpers/objectSpread2';
import { serializeError, rpcErrors } from '@metamask/rpc-errors';
import eos from 'end-of-stream';

@@ -115,2 +114,652 @@ import once from 'once';

const errorCodes = {
rpc: {
invalidInput: -32000,
resourceNotFound: -32001,
resourceUnavailable: -32002,
transactionRejected: -32003,
methodNotSupported: -32004,
limitExceeded: -32005,
parse: -32700,
invalidRequest: -32600,
methodNotFound: -32601,
invalidParams: -32602,
internal: -32603
},
provider: {
userRejectedRequest: 4001,
unauthorized: 4100,
unsupportedMethod: 4200,
disconnected: 4900,
chainDisconnected: 4901
}
};
const errorValues = {
"-32700": {
standard: "JSON RPC 2.0",
message: "Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text."
},
"-32600": {
standard: "JSON RPC 2.0",
message: "The JSON sent is not a valid Request object."
},
"-32601": {
standard: "JSON RPC 2.0",
message: "The method does not exist / is not available."
},
"-32602": {
standard: "JSON RPC 2.0",
message: "Invalid method parameter(s)."
},
"-32603": {
standard: "JSON RPC 2.0",
message: "Internal JSON-RPC error."
},
"-32000": {
standard: "EIP-1474",
message: "Invalid input."
},
"-32001": {
standard: "EIP-1474",
message: "Resource not found."
},
"-32002": {
standard: "EIP-1474",
message: "Resource unavailable."
},
"-32003": {
standard: "EIP-1474",
message: "Transaction rejected."
},
"-32004": {
standard: "EIP-1474",
message: "Method not supported."
},
"-32005": {
standard: "EIP-1474",
message: "Request limit exceeded."
},
"4001": {
standard: "EIP-1193",
message: "User rejected the request."
},
"4100": {
standard: "EIP-1193",
message: "The requested account and/or method has not been authorized by the user."
},
"4200": {
standard: "EIP-1193",
message: "The requested method is not supported by this Ethereum provider."
},
"4900": {
standard: "EIP-1193",
message: "The provider is disconnected from all chains."
},
"4901": {
standard: "EIP-1193",
message: "The provider is disconnected from the specified chain."
}
};
const FALLBACK_ERROR_CODE = errorCodes.rpc.internal;
const FALLBACK_MESSAGE = "Unspecified error message. This is a bug, please report it.";
const JSON_RPC_SERVER_ERROR_MESSAGE = "Unspecified server error.";
/**
* Returns whether the given code is valid.
* A code is valid if it is an integer.
*
* @param code - The error code.
* @returns Whether the given code is valid.
*/
function isValidCode(code) {
return Number.isInteger(code);
}
function isValidString(value) {
return typeof value === "string" && value.length > 0;
}
/**
* A type guard for {@link RuntimeObject}.
*
* @param value - The value to check.
* @returns Whether the specified value has a runtime type of `object` and is
* neither `null` nor an `Array`.
*/
function isObject(value) {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
/**
* Check if the value is plain object.
*
* @param value - Value to be checked.
* @returns True if an object is the plain JavaScript object,
* false if the object is not plain (e.g. function).
*/
function isPlainObject(value) {
if (typeof value !== "object" || value === null) {
return false;
}
try {
let proto = value;
while (Object.getPrototypeOf(proto) !== null) {
proto = Object.getPrototypeOf(proto);
}
return Object.getPrototypeOf(value) === proto;
} catch (_) {
return false;
}
}
/**
* Check if the given code is a valid JSON-RPC server error code.
*
* @param code - The error code.
* @returns Whether the given code is a valid JSON-RPC server error code.
*/
function isJsonRpcServerError(code) {
return code >= -32099 && code <= -32000;
}
function isJsonRpcError(value) {
const castValue = value;
if (!castValue) return false;
if (!isValidCode(castValue.code) || !isValidString(castValue.message)) return false;
if (castValue.stack && !isValidString(castValue.stack)) return false;
return true;
}
/**
* Gets the message for a given code, or a fallback message if the code has
* no corresponding message.
*
* @param code - The error code.
* @param fallbackMessage - The fallback message to use if the code has no
* corresponding message.
* @returns The message for the given code, or the fallback message if the code
* has no corresponding message.
*/
function getMessageFromCode(code) {
let fallbackMessage = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : FALLBACK_MESSAGE;
if (isValidCode(code)) {
const codeString = code.toString();
if (Object.hasOwn(errorValues, codeString)) {
return errorValues[codeString].message;
}
if (isJsonRpcServerError(code)) {
return JSON_RPC_SERVER_ERROR_MESSAGE;
}
}
return fallbackMessage;
}
const FALLBACK_ERROR = {
code: FALLBACK_ERROR_CODE,
message: getMessageFromCode(FALLBACK_ERROR_CODE)
};
function isValidJson(str) {
try {
JSON.parse(JSON.stringify(str, (strKey, strVal) => {
if (strKey === "__proto__" || strKey === "constructor") {
throw new Error("Not valid json");
}
if (typeof strVal === "function" || typeof strVal === "symbol") {
throw new Error("Not valid json");
}
return strVal;
}), (propKey, propValue) => {
// Strip __proto__ and constructor properties to prevent prototype pollution.
if (propKey === "__proto__" || propKey === "constructor") {
return undefined;
}
return propValue;
});
// this means, it's a valid json so far
} catch (e) {
return false;
}
return true;
}
/**
* Extracts all JSON-serializable properties from an object.
*
* @param object - The object in question.
* @returns An object containing all the JSON-serializable properties.
*/
function serializeObject(object) {
return Object.getOwnPropertyNames(object).reduce((acc, key) => {
const value = object[key];
if (isValidJson(value)) {
acc[key] = value;
}
return acc;
}, {});
}
/**
* Serializes an unknown error to be used as the `cause` in a fallback error.
*
* @param error - The unknown error.
* @returns A JSON-serializable object containing as much information about the original error as possible.
*/
function serializeCause(error) {
if (Array.isArray(error)) {
return error.map(entry => {
if (isValidJson(entry)) {
return entry;
} else if (isObject(entry)) {
return serializeObject(entry);
}
return null;
});
} else if (isObject(error)) {
return serializeObject(error);
}
if (isValidJson(error)) {
return error;
}
return null;
}
/**
* Construct a JSON-serializable object given an error and a JSON serializable `fallbackError`
*
* @param error - The error in question.
* @param fallbackError - A JSON serializable fallback error.
* @returns A JSON serializable error object.
*/
function buildError(error, fallbackError) {
// If an error specifies a `serialize` function, we call it and return the result.
if (error && typeof error === "object" && "serialize" in error && typeof error.serialize === "function") {
return error.serialize();
}
if (isJsonRpcError(error)) {
return error;
}
// If the error does not match the JsonRpcError type, use the fallback error, but try to include the original error as `cause`.
const cause = serializeCause(error);
const fallbackWithCause = _objectSpread(_objectSpread({}, fallbackError), {}, {
data: {
cause
}
});
return fallbackWithCause;
}
/**
* Serializes the given error to an Ethereum JSON RPC-compatible error object.
* If the given error is not fully compatible, it will be preserved on the
* returned object's data.cause property.
*
* @param error - The error to serialize.
* @param options - Options bag.
* @param options.fallbackError - The error to return if the given error is
* not compatible. Should be a JSON serializable value.
* @param options.shouldIncludeStack - Whether to include the error's stack
* on the returned object.
* @returns The serialized error.
*/
function serializeError(error) {
let {
fallbackError = FALLBACK_ERROR,
shouldIncludeStack = true
} = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!isJsonRpcError(fallbackError)) {
throw new Error("Must provide fallback error with integer number code and string message.");
}
const serialized = buildError(error, fallbackError);
if (!shouldIncludeStack) {
delete serialized.stack;
}
return serialized;
}
/**
* Returns true if supplied error data has a usable `cause` property; false otherwise.
*
* @param data - Optional data to validate.
* @returns Whether cause property is present and an object.
*/
function dataHasCause(data) {
return isObject(data) && Object.hasOwn(data, "cause") && isObject(data.cause);
}
/**
* Check if the given code is a valid JSON-RPC error code.
*
* @param code - The code to check.
* @returns Whether the code is valid.
*/
function isValidEthProviderCode(code) {
return Number.isInteger(code) && code >= 1000 && code <= 4999;
}
/**
* A JSON replacer function that omits circular references.
*
* @param _ - The key being replaced.
* @param value - The value being replaced.
* @returns The value to use in place of the original value.
*/
function stringifyReplacer(_, value) {
if (value === "[Circular]") {
return undefined;
}
return value;
}
/**
* Error subclass implementing JSON RPC 2.0 errors and Ethereum RPC errors
* per EIP-1474.
*
* Permits any integer error code.
*/
class JsonRpcError extends Error {
constructor(code, message, data) {
if (!Number.isInteger(code)) {
throw new Error('"code" must be an integer.');
}
if (!message || typeof message !== "string") {
throw new Error('"message" must be a non-empty string.');
}
if (dataHasCause(data)) {
super(message, {
cause: data.cause
});
// Browser backwards-compatibility fallback
// The `cause` definition can be removed when tsconfig lib and/or target have changed to >=es2022
_defineProperty(this, "cause", void 0);
_defineProperty(this, "code", void 0);
_defineProperty(this, "data", void 0);
if (!Object.hasOwn(this, "cause")) {
Object.assign(this, {
cause: data.cause
});
}
} else {
super(message);
// The `cause` definition can be removed when tsconfig lib and/or target have changed to >=es2022
_defineProperty(this, "cause", void 0);
_defineProperty(this, "code", void 0);
_defineProperty(this, "data", void 0);
}
if (data !== undefined) {
this.data = data;
}
this.code = code;
this.cause = data === null || data === void 0 ? void 0 : data.cause;
}
/**
* Get the error as JSON-serializable object.
*
* @returns A plain object with all public class properties.
*/
serialize() {
const serialized = {
code: this.code,
message: this.message
};
if (this.data !== undefined) {
// `this.data` is not guaranteed to be a plain object, but this simplifies
// the type guard below. We can safely cast it because we know it's a
// JSON-serializable value.
serialized.data = this.data;
if (isPlainObject(this.data)) {
serialized.data.cause = serializeCause(this.data.cause);
}
}
if (this.stack) {
serialized.stack = this.stack;
}
return serialized;
}
/**
* Get a string representation of the serialized error, omitting any circular
* references.
*
* @returns A string representation of the serialized error.
*/
toString() {
return safeStringify(this.serialize(), stringifyReplacer, 2);
}
}
/**
* Error subclass implementing Ethereum Provider errors per EIP-1193.
* Permits integer error codes in the [ 1000 <= 4999 ] range.
*/
class EthereumProviderError extends JsonRpcError {
/**
* Create an Ethereum Provider JSON-RPC error.
*
* @param code - The JSON-RPC error code. Must be an integer in the
* `1000 <= n <= 4999` range.
* @param message - The JSON-RPC error message.
* @param data - Optional data to include in the error.
*/
constructor(code, message, data) {
if (!isValidEthProviderCode(code)) {
throw new Error('"code" must be an integer such that: 1000 <= code <= 4999');
}
super(code, message, data);
}
}
/**
* Get an error message and optional data from an options bag.
*
* @param arg - The error message or options bag.
* @returns A tuple containing the error message and optional data.
*/
function parseOpts(arg) {
if (arg) {
if (typeof arg === "string") {
return [arg];
} else if (typeof arg === "object" && !Array.isArray(arg)) {
const {
message,
data
} = arg;
if (message && typeof message !== "string") {
throw new Error("Must specify string message.");
}
return [message !== null && message !== void 0 ? message : undefined, data];
}
}
return [];
}
/**
* Get a generic JSON-RPC error class instance.
*
* @param code - The error code.
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
function getJsonRpcError(code, arg) {
const [message, data] = parseOpts(arg);
return new JsonRpcError(code, message !== null && message !== void 0 ? message : getMessageFromCode(code), data);
}
/**
* Get an Ethereum Provider error class instance.
*
* @param code - The error code.
* @param arg - The error message or options bag.
* @returns An instance of the {@link EthereumProviderError} class.
*/
function getEthProviderError(code, arg) {
const [message, data] = parseOpts(arg);
return new EthereumProviderError(code, message !== null && message !== void 0 ? message : getMessageFromCode(code), data);
}
const rpcErrors = {
/**
* Get a JSON RPC 2.0 Parse (-32700) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
parse: arg => getJsonRpcError(errorCodes.rpc.parse, arg),
/**
* Get a JSON RPC 2.0 Invalid Request (-32600) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
invalidRequest: arg => getJsonRpcError(errorCodes.rpc.invalidRequest, arg),
/**
* Get a JSON RPC 2.0 Invalid Params (-32602) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
invalidParams: arg => getJsonRpcError(errorCodes.rpc.invalidParams, arg),
/**
* Get a JSON RPC 2.0 Method Not Found (-32601) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
methodNotFound: arg => getJsonRpcError(errorCodes.rpc.methodNotFound, arg),
/**
* Get a JSON RPC 2.0 Internal (-32603) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
internal: arg => getJsonRpcError(errorCodes.rpc.internal, arg),
/**
* Get a JSON RPC 2.0 Server error.
* Permits integer error codes in the [ -32099 <= -32005 ] range.
* Codes -32000 through -32004 are reserved by EIP-1474.
*
* @param opts - The error options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
server: opts => {
if (!opts || typeof opts !== "object" || Array.isArray(opts)) {
throw new Error("Ethereum RPC Server errors must provide single object argument.");
}
const {
code
} = opts;
if (!Number.isInteger(code) || code > -32005 || code < -32099) {
throw new Error('"code" must be an integer such that: -32099 <= code <= -32005');
}
return getJsonRpcError(code, opts);
},
/**
* Get an Ethereum JSON RPC Invalid Input (-32000) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
invalidInput: arg => getJsonRpcError(errorCodes.rpc.invalidInput, arg),
/**
* Get an Ethereum JSON RPC Resource Not Found (-32001) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
resourceNotFound: arg => getJsonRpcError(errorCodes.rpc.resourceNotFound, arg),
/**
* Get an Ethereum JSON RPC Resource Unavailable (-32002) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
resourceUnavailable: arg => getJsonRpcError(errorCodes.rpc.resourceUnavailable, arg),
/**
* Get an Ethereum JSON RPC Transaction Rejected (-32003) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
transactionRejected: arg => getJsonRpcError(errorCodes.rpc.transactionRejected, arg),
/**
* Get an Ethereum JSON RPC Method Not Supported (-32004) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
methodNotSupported: arg => getJsonRpcError(errorCodes.rpc.methodNotSupported, arg),
/**
* Get an Ethereum JSON RPC Limit Exceeded (-32005) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link JsonRpcError} class.
*/
limitExceeded: arg => getJsonRpcError(errorCodes.rpc.limitExceeded, arg)
};
const providerErrors = {
/**
* Get an Ethereum Provider User Rejected Request (4001) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link EthereumProviderError} class.
*/
userRejectedRequest: arg => {
return getEthProviderError(errorCodes.provider.userRejectedRequest, arg);
},
/**
* Get an Ethereum Provider Unauthorized (4100) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link EthereumProviderError} class.
*/
unauthorized: arg => {
return getEthProviderError(errorCodes.provider.unauthorized, arg);
},
/**
* Get an Ethereum Provider Unsupported Method (4200) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link EthereumProviderError} class.
*/
unsupportedMethod: arg => {
return getEthProviderError(errorCodes.provider.unsupportedMethod, arg);
},
/**
* Get an Ethereum Provider Not Connected (4900) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link EthereumProviderError} class.
*/
disconnected: arg => {
return getEthProviderError(errorCodes.provider.disconnected, arg);
},
/**
* Get an Ethereum Provider Chain Not Connected (4901) error.
*
* @param arg - The error message or options bag.
* @returns An instance of the {@link EthereumProviderError} class.
*/
chainDisconnected: arg => {
return getEthProviderError(errorCodes.provider.chainDisconnected, arg);
},
/**
* Get a custom Ethereum Provider error.
*
* @param opts - The error options bag.
* @returns An instance of the {@link EthereumProviderError} class.
*/
custom: opts => {
if (!opts || typeof opts !== "object" || Array.isArray(opts)) {
throw new Error("Ethereum Provider custom errors must provide single object argument.");
}
const {
code,
message,
data
} = opts;
if (!message || typeof message !== "string") {
throw new Error('"message" must be a nonempty string');
}
return new EthereumProviderError(code, message, data);
}
};
/* eslint-disable @typescript-eslint/no-explicit-any */

@@ -203,3 +852,3 @@ function safeApply(handler, context, args) {

toString() {
return stringify({
return safeStringify({
code: this.code,

@@ -984,2 +1633,2 @@ message: this.message,

export { BasePostMessageStream, IGNORE_SUBSTREAM, JRPCEngine, ObjectMultiplex, PostMessageStream, SafeEventEmitter, SerializableError, Substream, createAsyncMiddleware, createEngineStream, createErrorMiddleware, createIdRemapMiddleware, createLoggerMiddleware, createScaffoldMiddleware, createStreamMiddleware, getRpcPromiseCallback, mergeMiddleware, providerAsMiddleware, providerFromEngine, providerFromMiddleware, setupMultiplex };
export { BasePostMessageStream, EthereumProviderError, IGNORE_SUBSTREAM, JRPCEngine, JSON_RPC_SERVER_ERROR_MESSAGE, JsonRpcError, ObjectMultiplex, PostMessageStream, SafeEventEmitter, SerializableError, Substream, createAsyncMiddleware, createEngineStream, createErrorMiddleware, createIdRemapMiddleware, createLoggerMiddleware, createScaffoldMiddleware, createStreamMiddleware, dataHasCause, errorCodes, errorValues, getMessageFromCode, getRpcPromiseCallback, isObject, isPlainObject, isValidCode, isValidString, mergeMiddleware, providerAsMiddleware, providerErrors, providerFromEngine, providerFromMiddleware, rpcErrors, serializeCause, serializeError, setupMultiplex };
export { default as BasePostMessageStream } from "./basePostMessageStream";
export * from "./errors";
export * from "./interfaces";

@@ -3,0 +4,0 @@ export * from "./jrpc";

@@ -37,6 +37,24 @@ export type Json = boolean | number | string | null | {

}
/**
* A data object, that must be either:
*
* - A JSON-serializable object.
* - An object with a `cause` property that is an error-like value, and any
* other properties that are JSON-serializable.
*/
export type DataWithOptionalCause = Json | {
[key: string]: Json | unknown;
cause?: unknown;
};
/**
* A data object, that must be either:
*
* - A valid DataWithOptionalCause value.
* - undefined.
*/
export type OptionalDataWithOptionalCause = undefined | DataWithOptionalCause;
export interface JRPCError {
code: number;
message: string;
data?: unknown;
data?: DataWithOptionalCause;
stack?: string;

@@ -43,0 +61,0 @@ }

5

package.json
{
"name": "@toruslabs/openlogin-jrpc",
"version": "8.1.1",
"version": "8.3.0",
"homepage": "https://github.com/torusresearch/OpenLoginSdk#readme",

@@ -23,3 +23,2 @@ "license": "ISC",

"dependencies": {
"@metamask/rpc-errors": "^6.2.1",
"end-of-stream": "^1.4.4",

@@ -65,3 +64,3 @@ "events": "^3.3.0",

},
"gitHead": "de7d0db23e57ce7f32a6b25b7f11ccf9ebc33c78"
"gitHead": "63468c0ec59767fdde8b7caa8de9f7b95c6ab550"
}

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc