@web3auth/ws-embed
Version:
Embed script
71 lines (66 loc) • 2.38 kB
JavaScript
import _objectSpread from '@babel/runtime/helpers/objectSpread2';
import { DASHBOARD_PUBLIC_API_MAP } from '@toruslabs/constants';
import { get } from '@toruslabs/http-helpers';
import { rpcErrors, BUILD_ENV } from '@web3auth/auth';
import log from './loglevel.js';
// utility functions
/**
* json-rpc-engine middleware that logs RPC errors and and validates req.method.
*
* @param log - The logging API to use.
* @returns json-rpc-engine middleware function
*/
function createErrorMiddleware() {
return ({
request,
next
}) => {
if (typeof request.method !== "string" || !request.method) {
log.error(`The request 'method' must be a non-empty string.`, request);
throw rpcErrors.invalidRequest({
message: `The request 'method' must be a non-empty string.`,
data: _objectSpread(_objectSpread({}, request || {}), {}, {
cause: `The request 'method' must be a non-empty string.`
})
});
}
return next();
};
}
/**
* Logs a stream disconnection error. Emits an 'error' if given an
* EventEmitter that has listeners for the 'error' event.
*
* @param log - The logging API to use.
* @param remoteLabel - The label of the disconnected stream.
* @param error - The associated error to log.
* @param emitter - The logging API to use.
*/
function logStreamDisconnectWarning(remoteLabel, error, emitter) {
let warningMsg = `Web3Auth: Lost connection to "${remoteLabel}".`;
if (error !== null && error !== void 0 && error.stack) {
warningMsg += `\n${error.stack}`;
}
log.warn(warningMsg);
if (emitter && emitter.listenerCount("error") > 0) {
emitter.emit("error", warningMsg);
}
}
const EMITTED_NOTIFICATIONS = ["eth_subscription" // per eth-json-rpc-filters/subscriptionManager
];
const signerHost = (buildEnv = BUILD_ENV.PRODUCTION) => {
return DASHBOARD_PUBLIC_API_MAP[buildEnv];
};
const fetchProjectConfig = async ({
clientId,
web3AuthNetwork,
buildEnv
}) => {
const url = new URL(`${signerHost(buildEnv)}/api/v2/configuration`);
url.searchParams.append("project_id", clientId);
url.searchParams.append("network", web3AuthNetwork);
if (buildEnv) url.searchParams.append("build_env", buildEnv);
const res = await get(url.href);
return res;
};
export { EMITTED_NOTIFICATIONS, createErrorMiddleware, fetchProjectConfig, logStreamDisconnectWarning, signerHost };