@metamask/auth-network-utils
Advanced tools
+9
-1
@@ -10,2 +10,9 @@ # Changelog | ||
| ## [0.3.0] | ||
| ### Fixed | ||
| - Added two new utils, `add0x` and `remove0x` to add/remove `0x` prefix to/from the hexadecimal string. ([#112](https://github.com/MetaMask/toprf-secure-backup/pull/112)) | ||
| - Added `cancellation` logic to the `timeoutPromise` after the `Promise.race` in `Some` function. ([#110](https://github.com/MetaMask/toprf-secure-backup/pull/110)) | ||
| ## [0.2.0] | ||
@@ -34,4 +41,5 @@ | ||
| [Unreleased]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/auth-network-utils@0.2.0...HEAD | ||
| [Unreleased]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/auth-network-utils@0.3.0...HEAD | ||
| [0.3.0]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/auth-network-utils@0.2.0...@metamask/auth-network-utils@0.3.0 | ||
| [0.2.0]: https://github.com/MetaMask/toprf-secure-backup/compare/@metamask/auth-network-utils@0.1.0...@metamask/auth-network-utils@0.2.0 | ||
| [0.1.0]: https://github.com/MetaMask/toprf-secure-backup/releases/tag/@metamask/auth-network-utils@0.1.0 |
+35
-2
@@ -6,3 +6,3 @@ "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.toSnakeCaseKeys = exports.toCamelCaseKeys = exports.convertKeys = exports.toSnake = exports.toCamel = exports.isJSONRPCError = exports.filterErrorResponses = exports.filterCompletedRequests = exports.Some = exports.getProxyCoordinatorNodeIndex = exports.kCombinations = exports.thresholdSame = exports.safeStringify = exports.keccak256AndHexify = void 0; | ||
| exports.toSnakeCaseKeys = exports.toCamelCaseKeys = exports.convertKeys = exports.toSnake = exports.toCamel = exports.isJSONRPCError = exports.filterErrorResponses = exports.filterCompletedRequests = exports.Some = exports.getProxyCoordinatorNodeIndex = exports.kCombinations = exports.thresholdSame = exports.safeStringify = exports.add0x = exports.remove0x = exports.keccak256AndHexify = void 0; | ||
| const sha3_1 = require("@noble/hashes/sha3"); | ||
@@ -24,2 +24,28 @@ const bn_js_1 = __importDefault(require("bn.js")); | ||
| /** | ||
| * Removes the `0x` prefix from a hex string | ||
| * | ||
| * @param hexString - The hex string to remove the `0x` prefix from | ||
| * @returns The hex string without the `0x` prefix | ||
| */ | ||
| function remove0x(hexString) { | ||
| if (hexString.startsWith('0x')) { | ||
| return hexString.slice(2); | ||
| } | ||
| return hexString; | ||
| } | ||
| exports.remove0x = remove0x; | ||
| /** | ||
| * Adds the `0x` prefix to a hex string if it is not already present | ||
| * | ||
| * @param hexString - The hex string to add the `0x` prefix to | ||
| * @returns The hex string with the `0x` prefix | ||
| */ | ||
| function add0x(hexString) { | ||
| if (hexString.startsWith('0x')) { | ||
| return hexString; | ||
| } | ||
| return `0x${hexString}`; | ||
| } | ||
| exports.add0x = add0x; | ||
| /** | ||
| * Stringifies a JSON object and persists the key orders of the object | ||
@@ -165,6 +191,7 @@ * | ||
| for (const [i, promise] of promises.entries()) { | ||
| let timeoutId; | ||
| try { | ||
| // Race the promise against a timeout | ||
| const timeoutPromise = new Promise((_resolve, reject) => { | ||
| setTimeout(() => reject(new Error('Promise timed out')), 10000); | ||
| timeoutId = setTimeout(() => reject(new Error('Promise timed out')), 10000); | ||
| }); | ||
@@ -176,2 +203,8 @@ resultArr[i] = await Promise.race([promise, timeoutPromise]); | ||
| } | ||
| finally { | ||
| // Clear the timeout if it exists and still hasn't been cleared after the Promise.race is settled. | ||
| if (timeoutId) { | ||
| clearTimeout(timeoutId); | ||
| } | ||
| } | ||
| try { | ||
@@ -178,0 +211,0 @@ const allSettled = resultArr.every((result) => result !== undefined); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"common.cjs","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":";;;;;;AAAA,6CAA6D;AAC7D,kDAAuB;AACvB,kFAAkD;AAElD,yCAAqC;AAGrC;;;;;GAKG;AACH,SAAgB,kBAAkB,CAAC,MAAkB;IACnD,MAAM,IAAI,GAAG,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AE,CAC3D,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AADf,QAAA,eAAe,mBACA","sourcesContent":["import { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport BN from 'bn.js';\nimport JsonStringify from 'json-stable-stringify';\n\nimport { SomeError } from './errors';\nimport type { JSONRPCError } from './interfaces';\n\n/**\n * Hashes a buffer using the keccak256 algorithm and hexify the result\n *\n * @param buffer - The uint8array to hash\n * @returns The hash of the buffer as a hex string\n */\nexport function keccak256AndHexify(buffer: Uint8Array): `0x${string}` {\n const hash = Buffer.from(keccak256(buffer)).toString('hex');\n return `0x${hash}`;\n}\n\n/**\n * Stringifies a JSON object and persists the key orders of the object\n *\n * @param json - The JSON object to stringify\n * @param options - The options to pass to the stringify function\n * @returns The stringified JSON object\n */\nexport function safeStringify(\n json: unknown,\n options?: Parameters<typeof JsonStringify>[1],\n): string {\n const stringified = JsonStringify(json, options);\n if (!stringified) {\n throw new Error('Failed to stringify');\n }\n return stringified;\n}\n\n/**\n * Finds the first element that appears t times in the array\n *\n * @param arr - The array to search\n * @param threshold - The number of times the element should appear\n * @returns The first element that appears t times in the array\n */\nexport function thresholdSame<Type>(\n arr: Type[],\n threshold: number,\n): Type | undefined {\n const hashMap: Record<string, number> = {};\n for (const item of arr) {\n const str = JsonStringify(item);\n if (!str) {\n continue;\n }\n hashMap[str] = hashMap[str] ? hashMap[str] + 1 : 1;\n if (hashMap[str] === threshold) {\n return item;\n }\n }\n return undefined;\n}\n\n/**\n * Generates all possible combinations of k elements from a set.\n *\n * @param inputSet - The set to generate combinations from\n * @param k - The number of elements in each combination\n * @yields All possible combinations of k elements from the set s\n */\nexport function* kCombinations(\n inputSet: number | number[],\n k: number,\n): Generator<number[]> {\n let set = inputSet;\n if (typeof set === 'number') {\n set = Array.from({ length: set }, (_, i) => i);\n }\n if (k > set.length || k <= 0) {\n return;\n }\n\n if (k === set.length) {\n yield set;\n return;\n }\n\n if (k === 1) {\n for (const item of set) {\n yield [item];\n }\n return;\n }\n\n const indices = Array.from({ length: set.length - k + 2 }, (_, i) => i);\n for (const i of indices) {\n for (const j of kCombinations(set.slice(i + 1), k - 1)) {\n yield [set[i], ...j];\n }\n }\n}\n\n/**\n * Calculates the index of the proxy coordinator endpoint based on auth connection id details\n *\n * @param indexes - The indexes to choose from.\n * @param authConnectionId - The auth connection id to use to generate the index\n * @param userId - The user id to use to generate the index\n * @returns The node index of the proxy coordinator endpoint.\n */\nexport const getProxyCoordinatorNodeIndex = (\n indexes: number[],\n authConnectionId: string,\n userId: string,\n): number => {\n const authConnectionIdStr = `${authConnectionId}${userId}`;\n const hashedAuthConnectionId = keccak256AndHexify(\n Buffer.from(authConnectionIdStr, 'utf8'),\n ).slice(2);\n const proxyEndpointNum = new BN(hashedAuthConnectionId, 'hex')\n .mod(new BN(indexes.length))\n .toNumber();\n return indexes[proxyEndpointNum];\n};\n\n/**\n * This function handles when `Some` function cannot determine the outcome of the operation\\\n * even after all promises are settled\n *\n * @param errorArr - array of errors\n * @param resultArr - array of resolved results\n * @param predicateError - error thrown by the callbackFn\n */\nfunction handleSomeCallBackFnError<Type>(\n errorArr: Error[],\n resultArr: Type[],\n predicateError?: Error,\n): never {\n // check if there's any rejected promises\n let hasError = errorArr.some((error) => error !== undefined);\n if (hasError) {\n throw new SomeError({\n errors: errorArr,\n responses: resultArr,\n predicate: predicateError,\n });\n }\n\n type ResultWithError = { error?: { data?: string } };\n\n // check if there're any error inside resolved result array\n const resultArrWithError = resultArr as ResultWithError[];\n hasError = resultArrWithError.some((result) => Boolean(result?.error));\n if (hasError) {\n const errors = resultArr.map((result) => {\n const { error } = result as ResultWithError;\n if (error?.data && error.data.length > 0) {\n return new Error(error.data);\n }\n return undefined;\n });\n throw new SomeError({\n errors,\n responses: resultArr,\n predicate: predicateError,\n });\n }\n\n // no error was thrown and callback never returned a value\n throw new SomeError({\n errors: errorArr,\n responses: resultArr,\n predicate: predicateError,\n });\n}\n\n/**\n * This function executes an array of promises and returns a result of the operation based on the callbackFn return value\n *\n * @param promises - array of promises to execute\n * @param callbackFn - function to execute resolved promises and determine the outcome of the operation conditionally\n * @returns - result of the operation\n */\nexport async function Some<Input, Output>(\n promises: Promise<Input>[],\n callbackFn: (\n resultArr: Input[],\n params: { allSettled: boolean },\n ) => Promise<Output | undefined>,\n): Promise<Output> {\n let predicateError: Error | undefined; // to keep track of the latest error thrown by the callbackFn\n const resultArr: Input[] = new Array(promises.length).fill(undefined);\n const errorArr: Error[] = new Array(promises.length).fill(undefined);\n\n for (const [i, promise] of promises.entries()) {\n try {\n // Race the promise against a timeout\n const timeoutPromise = new Promise<Input>((_resolve, reject) => {\n setTimeout(() => reject(new Error('Promise timed out')), 10_000);\n });\n resultArr[i] = await Promise.race([promise, timeoutPromise]);\n } catch (error: unknown) {\n errorArr[i] = error as Error;\n }\n\n try {\n const allSettled = resultArr.every((result) => result !== undefined);\n const result = await callbackFn(resultArr, { allSettled });\n if (result) {\n return result;\n }\n } catch (error: unknown) {\n predicateError = error as Error;\n }\n }\n\n // If we still don't have a result, handle the error\n handleSomeCallBackFnError(errorArr, resultArr, predicateError);\n}\n\n/**\n * Filters out invalid responses.\n *\n * @param resultArr - The result array to filter.\n * @returns The filtered result array.\n */\nexport function filterCompletedRequests<Type>(resultArr: Type[]): Type[] {\n return resultArr.filter((res) => {\n const isValidObject = res && typeof res === 'object';\n\n const maybeRes = res as { error?: unknown; result?: unknown };\n const hasNoError = !maybeRes?.error;\n const hasResult = Boolean(maybeRes?.result);\n\n return isValidObject && hasNoError && hasResult;\n });\n}\n\n/**\n * Extracts error responses from a result array.\n *\n * @param resultArr - Array of responses to check for errors\n * @returns Array of error responses extracted from the input array\n */\nexport function filterErrorResponses<Type>(\n resultArr: Type[],\n): (Type & { error: unknown })[] {\n return resultArr.filter((res): res is Type & { error: unknown } => {\n const isValidObject = res && typeof res === 'object';\n\n const maybeRes = res as { error?: unknown };\n const hasError = Boolean(maybeRes?.error);\n\n return isValidObject && hasError;\n });\n}\n\n/**\n * Checks if an unknown value is a properly structured JSON-RPC error object\n *\n * @param error - The value to check\n * @returns True if the value is a JSON-RPC error object with the required properties\n */\nexport function isJSONRPCError(error: unknown): error is JSONRPCError {\n const isValidObject = Boolean(error && typeof error === 'object');\n\n const maybeError = error as Partial<JSONRPCError>;\n const hasCode = typeof maybeError?.code === 'number';\n const hasMessage = typeof maybeError?.message === 'string';\n\n return isValidObject && hasCode && hasMessage;\n}\n\nexport type Primitive = string | number | boolean | null;\nexport type JSONObject = { [key: string]: JSONValue };\nexport type JSONArray = JSONValue[];\nexport type JSONValue = Primitive | JSONObject | JSONArray;\n\n// Convert snake_case to camelCase\n/**\n *\n * @param str - The string to convert to camelCase.\n * @returns The camelCase string.\n */\nexport function toCamel(str: string): string {\n return str.replace(/_([a-z])/gu, (_, letter) => letter.toUpperCase());\n}\n\n// Convert camelCase to snake_case\n/**\n *\n * @param str - The string to convert to snake_case.\n * @returns The snake_case string.\n */\nexport function toSnake(str: string): string {\n return str.replace(/([A-Z])/gu, '_$1').toLowerCase();\n}\n\n// Recursive key converter\n/**\n *\n * @param obj - The object to convert the keys of.\n * @param convertFunc - The function to convert the keys of the object.\n * @returns The object with the converted keys.\n */\nexport function convertKeys(\n obj: JSONValue,\n convertFunc: (key: string) => string,\n): JSONValue {\n if (Array.isArray(obj)) {\n return obj.map((item) => convertKeys(item, convertFunc));\n } else if (obj !== null && typeof obj === 'object') {\n const newObj: JSONObject = {};\n for (const [key, value] of Object.entries(obj)) {\n newObj[convertFunc(key)] = convertKeys(value, convertFunc);\n }\n return newObj;\n }\n return obj;\n}\n\n/**\n * Converts the keys of an object from snake_case to camelCase.\n *\n * @param obj - The object to convert the keys of.\n * @returns The object with the converted keys.\n */\nexport const toCamelCaseKeys = (obj: JSONValue): JSONValue =>\n convertKeys(obj, toCamel);\n\n/**\n * Converts the keys of an object from camelCase to snake_case.\n *\n * @param obj - The object to convert the keys of.\n * @returns The object with the converted keys.\n */\nexport const toSnakeCaseKeys = (obj: JSONValue): JSONValue =>\n convertKeys(obj, toSnake);\n"]} | ||
| {"version":3,"file":"common.cjs","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":";;;;;;AAAA,6CAA6D;AAC7D,kDAAuB;AACvB,kFAAkD;AAElD,yCAAqC;AAGrC;;;;;GAKG;AACH,SAAgB,kBAAkB,CAAC,MAAkB;IACnD,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAA,iBAAS,EAAC,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC5D,OAAO,KAAK,IAAI,EAAE,CAAC;AACrB,CAAC;AAHD,gDAGC;AAED;;;;;GAKG;AACH,SAAgB,QAAQ,CAAC,SAAwB;IAC/C,IAAI,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAC9B,OAAO,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;KAC3B;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AALD,4BAKC;AAED;;;;;GAKG;AACH,SAAgB,KAAK,CAAC,SAAiB;IACrC,IAAI,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;QAC9B,OAAO,SAA0B,CAAC;KACnC;IACD,OAAO,KAAK,SAAS,EAAE,CAAC;AAC1B,CAAC;AALD,sBAKC;AAED;;;;;;GAMG;AACH,SAAgB,aAAa,CAC3B,IAAa,EACb,OAA6C;IAE7C,MAAM,WAAW,GAAG,IAAA,+BAAa,EAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACjD,IAAI,CAAC,WAAW,EAAE;QAChB,MAAM,IAAI,KAAK,CAAC,qBAAqB,CAAC,CAAC;KACxC;IACD,OAAO,WAAW,CAAC;AACrB,CAAC;AATD,sCASC;AAED;;;;;;GAMG;AACH,SAAgB,aAAa,CAC3B,GAAW,EACX,SAAiB;IAEjB,MAAM,OAAO,GAA2B,EAAE,CAAC;IAC3C,KAAK,MAAM,IAAI,IAAI,GAAG,EAAE;QACtB,MAAM,G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CACzB,GAAc,EACd,WAAoC;IAEpC,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;QACtB,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC;KAC1D;SAAM,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAClD,MAAM,MAAM,GAAe,EAAE,CAAC;QAC9B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YAC9C,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;SAC5D;QACD,OAAO,MAAM,CAAC;KACf;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAdD,kCAcC;AAED;;;;;GAKG;AACI,MAAM,eAAe,GAAG,CAAC,GAAc,EAAa,EAAE,CAC3D,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AADf,QAAA,eAAe,mBACA;AAE5B;;;;;GAKG;AACI,MAAM,eAAe,GAAG,CAAC,GAAc,EAAa,EAAE,CAC3D,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AADf,QAAA,eAAe,mBACA","sourcesContent":["import { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport BN from 'bn.js';\nimport JsonStringify from 'json-stable-stringify';\n\nimport { SomeError } from './errors';\nimport type { JSONRPCError } from './interfaces';\n\n/**\n * Hashes a buffer using the keccak256 algorithm and hexify the result\n *\n * @param buffer - The uint8array to hash\n * @returns The hash of the buffer as a hex string\n */\nexport function keccak256AndHexify(buffer: Uint8Array): `0x${string}` {\n const hash = Buffer.from(keccak256(buffer)).toString('hex');\n return `0x${hash}`;\n}\n\n/**\n * Removes the `0x` prefix from a hex string\n *\n * @param hexString - The hex string to remove the `0x` prefix from\n * @returns The hex string without the `0x` prefix\n */\nexport function remove0x(hexString: `0x${string}`): string {\n if (hexString.startsWith('0x')) {\n return hexString.slice(2);\n }\n return hexString;\n}\n\n/**\n * Adds the `0x` prefix to a hex string if it is not already present\n *\n * @param hexString - The hex string to add the `0x` prefix to\n * @returns The hex string with the `0x` prefix\n */\nexport function add0x(hexString: string): `0x${string}` {\n if (hexString.startsWith('0x')) {\n return hexString as `0x${string}`;\n }\n return `0x${hexString}`;\n}\n\n/**\n * Stringifies a JSON object and persists the key orders of the object\n *\n * @param json - The JSON object to stringify\n * @param options - The options to pass to the stringify function\n * @returns The stringified JSON object\n */\nexport function safeStringify(\n json: unknown,\n options?: Parameters<typeof JsonStringify>[1],\n): string {\n const stringified = JsonStringify(json, options);\n if (!stringified) {\n throw new Error('Failed to stringify');\n }\n return stringified;\n}\n\n/**\n * Finds the first element that appears t times in the array\n *\n * @param arr - The array to search\n * @param threshold - The number of times the element should appear\n * @returns The first element that appears t times in the array\n */\nexport function thresholdSame<Type>(\n arr: Type[],\n threshold: number,\n): Type | undefined {\n const hashMap: Record<string, number> = {};\n for (const item of arr) {\n const str = JsonStringify(item);\n if (!str) {\n continue;\n }\n hashMap[str] = hashMap[str] ? hashMap[str] + 1 : 1;\n if (hashMap[str] === threshold) {\n return item;\n }\n }\n return undefined;\n}\n\n/**\n * Generates all possible combinations of k elements from a set.\n *\n * @param inputSet - The set to generate combinations from\n * @param k - The number of elements in each combination\n * @yields All possible combinations of k elements from the set s\n */\nexport function* kCombinations(\n inputSet: number | number[],\n k: number,\n): Generator<number[]> {\n let set = inputSet;\n if (typeof set === 'number') {\n set = Array.from({ length: set }, (_, i) => i);\n }\n if (k > set.length || k <= 0) {\n return;\n }\n\n if (k === set.length) {\n yield set;\n return;\n }\n\n if (k === 1) {\n for (const item of set) {\n yield [item];\n }\n return;\n }\n\n const indices = Array.from({ length: set.length - k + 2 }, (_, i) => i);\n for (const i of indices) {\n for (const j of kCombinations(set.slice(i + 1), k - 1)) {\n yield [set[i], ...j];\n }\n }\n}\n\n/**\n * Calculates the index of the proxy coordinator endpoint based on auth connection id details\n *\n * @param indexes - The indexes to choose from.\n * @param authConnectionId - The auth connection id to use to generate the index\n * @param userId - The user id to use to generate the index\n * @returns The node index of the proxy coordinator endpoint.\n */\nexport const getProxyCoordinatorNodeIndex = (\n indexes: number[],\n authConnectionId: string,\n userId: string,\n): number => {\n const authConnectionIdStr = `${authConnectionId}${userId}`;\n const hashedAuthConnectionId = keccak256AndHexify(\n Buffer.from(authConnectionIdStr, 'utf8'),\n ).slice(2);\n const proxyEndpointNum = new BN(hashedAuthConnectionId, 'hex')\n .mod(new BN(indexes.length))\n .toNumber();\n return indexes[proxyEndpointNum];\n};\n\n/**\n * This function handles when `Some` function cannot determine the outcome of the operation\\\n * even after all promises are settled\n *\n * @param errorArr - array of errors\n * @param resultArr - array of resolved results\n * @param predicateError - error thrown by the callbackFn\n */\nfunction handleSomeCallBackFnError<Type>(\n errorArr: Error[],\n resultArr: Type[],\n predicateError?: Error,\n): never {\n // check if there's any rejected promises\n let hasError = errorArr.some((error) => error !== undefined);\n if (hasError) {\n throw new SomeError({\n errors: errorArr,\n responses: resultArr,\n predicate: predicateError,\n });\n }\n\n type ResultWithError = { error?: { data?: string } };\n\n // check if there're any error inside resolved result array\n const resultArrWithError = resultArr as ResultWithError[];\n hasError = resultArrWithError.some((result) => Boolean(result?.error));\n if (hasError) {\n const errors = resultArr.map((result) => {\n const { error } = result as ResultWithError;\n if (error?.data && error.data.length > 0) {\n return new Error(error.data);\n }\n return undefined;\n });\n throw new SomeError({\n errors,\n responses: resultArr,\n predicate: predicateError,\n });\n }\n\n // no error was thrown and callback never returned a value\n throw new SomeError({\n errors: errorArr,\n responses: resultArr,\n predicate: predicateError,\n });\n}\n\n/**\n * This function executes an array of promises and returns a result of the operation based on the callbackFn return value\n *\n * @param promises - array of promises to execute\n * @param callbackFn - function to execute resolved promises and determine the outcome of the operation conditionally\n * @returns - result of the operation\n */\nexport async function Some<Input, Output>(\n promises: Promise<Input>[],\n callbackFn: (\n resultArr: Input[],\n params: { allSettled: boolean },\n ) => Promise<Output | undefined>,\n): Promise<Output> {\n let predicateError: Error | undefined; // to keep track of the latest error thrown by the callbackFn\n const resultArr: Input[] = new Array(promises.length).fill(undefined);\n const errorArr: Error[] = new Array(promises.length).fill(undefined);\n\n for (const [i, promise] of promises.entries()) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n // Race the promise against a timeout\n const timeoutPromise = new Promise<Input>((_resolve, reject) => {\n timeoutId = setTimeout(\n () => reject(new Error('Promise timed out')),\n 10_000,\n );\n });\n resultArr[i] = await Promise.race([promise, timeoutPromise]);\n } catch (error: unknown) {\n errorArr[i] = error as Error;\n } finally {\n // Clear the timeout if it exists and still hasn't been cleared after the Promise.race is settled.\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n\n try {\n const allSettled = resultArr.every((result) => result !== undefined);\n const result = await callbackFn(resultArr, { allSettled });\n if (result) {\n return result;\n }\n } catch (error: unknown) {\n predicateError = error as Error;\n }\n }\n\n // If we still don't have a result, handle the error\n handleSomeCallBackFnError(errorArr, resultArr, predicateError);\n}\n\n/**\n * Filters out invalid responses.\n *\n * @param resultArr - The result array to filter.\n * @returns The filtered result array.\n */\nexport function filterCompletedRequests<Type>(resultArr: Type[]): Type[] {\n return resultArr.filter((res) => {\n const isValidObject = res && typeof res === 'object';\n\n const maybeRes = res as { error?: unknown; result?: unknown };\n const hasNoError = !maybeRes?.error;\n const hasResult = Boolean(maybeRes?.result);\n\n return isValidObject && hasNoError && hasResult;\n });\n}\n\n/**\n * Extracts error responses from a result array.\n *\n * @param resultArr - Array of responses to check for errors\n * @returns Array of error responses extracted from the input array\n */\nexport function filterErrorResponses<Type>(\n resultArr: Type[],\n): (Type & { error: unknown })[] {\n return resultArr.filter((res): res is Type & { error: unknown } => {\n const isValidObject = res && typeof res === 'object';\n\n const maybeRes = res as { error?: unknown };\n const hasError = Boolean(maybeRes?.error);\n\n return isValidObject && hasError;\n });\n}\n\n/**\n * Checks if an unknown value is a properly structured JSON-RPC error object\n *\n * @param error - The value to check\n * @returns True if the value is a JSON-RPC error object with the required properties\n */\nexport function isJSONRPCError(error: unknown): error is JSONRPCError {\n const isValidObject = Boolean(error && typeof error === 'object');\n\n const maybeError = error as Partial<JSONRPCError>;\n const hasCode = typeof maybeError?.code === 'number';\n const hasMessage = typeof maybeError?.message === 'string';\n\n return isValidObject && hasCode && hasMessage;\n}\n\nexport type Primitive = string | number | boolean | null;\nexport type JSONObject = { [key: string]: JSONValue };\nexport type JSONArray = JSONValue[];\nexport type JSONValue = Primitive | JSONObject | JSONArray;\n\n// Convert snake_case to camelCase\n/**\n *\n * @param str - The string to convert to camelCase.\n * @returns The camelCase string.\n */\nexport function toCamel(str: string): string {\n return str.replace(/_([a-z])/gu, (_, letter) => letter.toUpperCase());\n}\n\n// Convert camelCase to snake_case\n/**\n *\n * @param str - The string to convert to snake_case.\n * @returns The snake_case string.\n */\nexport function toSnake(str: string): string {\n return str.replace(/([A-Z])/gu, '_$1').toLowerCase();\n}\n\n// Recursive key converter\n/**\n *\n * @param obj - The object to convert the keys of.\n * @param convertFunc - The function to convert the keys of the object.\n * @returns The object with the converted keys.\n */\nexport function convertKeys(\n obj: JSONValue,\n convertFunc: (key: string) => string,\n): JSONValue {\n if (Array.isArray(obj)) {\n return obj.map((item) => convertKeys(item, convertFunc));\n } else if (obj !== null && typeof obj === 'object') {\n const newObj: JSONObject = {};\n for (const [key, value] of Object.entries(obj)) {\n newObj[convertFunc(key)] = convertKeys(value, convertFunc);\n }\n return newObj;\n }\n return obj;\n}\n\n/**\n * Converts the keys of an object from snake_case to camelCase.\n *\n * @param obj - The object to convert the keys of.\n * @returns The object with the converted keys.\n */\nexport const toCamelCaseKeys = (obj: JSONValue): JSONValue =>\n convertKeys(obj, toCamel);\n\n/**\n * Converts the keys of an object from camelCase to snake_case.\n *\n * @param obj - The object to convert the keys of.\n * @returns The object with the converted keys.\n */\nexport const toSnakeCaseKeys = (obj: JSONValue): JSONValue =>\n convertKeys(obj, toSnake);\n"]} |
+14
-0
@@ -11,2 +11,16 @@ import JsonStringify from "json-stable-stringify"; | ||
| /** | ||
| * Removes the `0x` prefix from a hex string | ||
| * | ||
| * @param hexString - The hex string to remove the `0x` prefix from | ||
| * @returns The hex string without the `0x` prefix | ||
| */ | ||
| export declare function remove0x(hexString: `0x${string}`): string; | ||
| /** | ||
| * Adds the `0x` prefix to a hex string if it is not already present | ||
| * | ||
| * @param hexString - The hex string to add the `0x` prefix to | ||
| * @returns The hex string with the `0x` prefix | ||
| */ | ||
| export declare function add0x(hexString: string): `0x${string}`; | ||
| /** | ||
| * Stringifies a JSON object and persists the key orders of the object | ||
@@ -13,0 +27,0 @@ * |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"common.d.cts","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":"AAEA,OAAO,aAAa,8BAA8B;AAGlD,OAAO,KAAK,EAAE,YAAY,EAAE,yBAAqB;AAEjD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,UAAU,GAAG,KAAK,MAAM,EAAE,CAGpE;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,OAAO,EACb,OAAO,CAAC,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,GAC5C,MAAM,CAMR;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAChC,GAAG,EAAE,IAAI,EAAE,EACX,SAAS,EAAE,MAAM,GAChB,IAAI,GAAG,SAAS,CAalB;AAED;;;;;;GAMG;AACH,wBAAiB,aAAa,CAC5B,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,EAC3B,CAAC,EAAE,MAAM,GACR,SAAS,CAAC,MAAM,EAAE,CAAC,CA2BrB;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,4BAA4B,YAC9B,MAAM,EAAE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AAG,SACtB,CAAC"} |
+14
-0
@@ -11,2 +11,16 @@ import JsonStringify from "json-stable-stringify"; | ||
| /** | ||
| * Removes the `0x` prefix from a hex string | ||
| * | ||
| * @param hexString - The hex string to remove the `0x` prefix from | ||
| * @returns The hex string without the `0x` prefix | ||
| */ | ||
| export declare function remove0x(hexString: `0x${string}`): string; | ||
| /** | ||
| * Adds the `0x` prefix to a hex string if it is not already present | ||
| * | ||
| * @param hexString - The hex string to add the `0x` prefix to | ||
| * @returns The hex string with the `0x` prefix | ||
| */ | ||
| export declare function add0x(hexString: string): `0x${string}`; | ||
| /** | ||
| * Stringifies a JSON object and persists the key orders of the object | ||
@@ -13,0 +27,0 @@ * |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"common.d.mts","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":"AAEA,OAAO,aAAa,8BAA8B;AAGlD,OAAO,KAAK,EAAE,YAAY,EAAE,yBAAqB;AAEjD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,UAAU,GAAG,KAAK,MAAM,EAAE,CAGpE;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,OAAO,EACb,OAAO,CAAC,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC,CAAC,CAAC,GAC5C,MAAM,CAMR;AAED;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAChC,GAAG,EAAE,IAAI,EAAE,EACX,SAAS,EAAE,MAAM,GAChB,IAAI,GAAG,SAAS,CAalB;AAED;;;;;;GAMG;AACH,wBAAiB,aAAa,CAC5B,QAAQ,EAAE,MAAM,GAAG,MAAM,EAAE,EAC3B,CAAC,EAAE,MAAM,GACR,SAAS,CAAC,MAAM,EAAE,CAAC,CA2BrB;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,4BAA4B,YAC9B,MAAM,EAAE,oBACC,MAAM,UAChB,MAAM,KACb,MASF,CAAC;AAqDF;;;;;;G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module) { | ||
| /** | ||
| * Removes the `0x` prefix from a hex string | ||
| * | ||
| * @param hexString - The hex string to remove the `0x` prefix from | ||
| * @returns The hex string without the `0x` prefix | ||
| */ | ||
| export function remove0x(hexString) { | ||
| if (hexString.startsWith('0x')) { | ||
| return hexString.slice(2); | ||
| } | ||
| return hexString; | ||
| } | ||
| /** | ||
| * Adds the `0x` prefix to a hex string if it is not already present | ||
| * | ||
| * @param hexString - The hex string to add the `0x` prefix to | ||
| * @returns The hex string with the `0x` prefix | ||
| */ | ||
| export function add0x(hexString) { | ||
| if (hexString.startsWith('0x')) { | ||
| return hexString; | ||
| } | ||
| return `0x${hexString}`; | ||
| } | ||
| /** | ||
| * Stringifies a JSON object and persists the key orders of the object | ||
@@ -161,6 +185,7 @@ * | ||
| for (const [i, promise] of promises.entries()) { | ||
| let timeoutId; | ||
| try { | ||
| // Race the promise against a timeout | ||
| const timeoutPromise = new Promise((_resolve, reject) => { | ||
| setTimeout(() => reject(new Error('Promise timed out')), 10000); | ||
| timeoutId = setTimeout(() => reject(new Error('Promise timed out')), 10000); | ||
| }); | ||
@@ -172,2 +197,8 @@ resultArr[i] = await Promise.race([promise, timeoutPromise]); | ||
| } | ||
| finally { | ||
| // Clear the timeout if it exists and still hasn't been cleared after the Promise.race is settled. | ||
| if (timeoutId) { | ||
| clearTimeout(timeoutId); | ||
| } | ||
| } | ||
| try { | ||
@@ -174,0 +205,0 @@ const allSettled = resultArr.every((result) => result !== undefined); |
@@ -1,1 +0,1 @@ | ||
| {"version":3,"file":"common.mjs","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,UAAU,IAAI,SAAS,EAAE,2BAA2B;AAC7D,OAAO,GAAE,cAAc;;AACvB,OAAO,cAAa,8BAA8B;;AAElD,OAAO,EAAE,SAAS,EAAE,qBAAiB;AAGrC;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,MAAkB;IACnD,MAAM,IAAI,GAAG,MAAM,CAA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O,CAAC,YAAY,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;AACxE,CAAC;AAED,kCAAkC;AAClC;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,GAAW;IACjC,OAAO,GAAG,CAAC,OAAO,CAAC,WAAW,EAAE,KAAK,CAAC,CAAC,WAAW,EAAE,CAAC;AACvD,CAAC;AAED,0BAA0B;AAC1B;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CACzB,GAAc,EACd,WAAoC;IAEpC,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;QACtB,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC,CAAC;KAC1D;SAAM,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAClD,MAAM,MAAM,GAAe,EAAE,CAAC;QAC9B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YAC9C,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;SAC5D;QACD,OAAO,MAAM,CAAC;KACf;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAc,EAAa,EAAE,CAC3D,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AAE5B;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAc,EAAa,EAAE,CAC3D,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC","sourcesContent":["import { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport BN from 'bn.js';\nimport JsonStringify from 'json-stable-stringify';\n\nimport { SomeError } from './errors';\nimport type { JSONRPCError } from './interfaces';\n\n/**\n * Hashes a buffer using the keccak256 algorithm and hexify the result\n *\n * @param buffer - The uint8array to hash\n * @returns The hash of the buffer as a hex string\n */\nexport function keccak256AndHexify(buffer: Uint8Array): `0x${string}` {\n const hash = Buffer.from(keccak256(buffer)).toString('hex');\n return `0x${hash}`;\n}\n\n/**\n * Stringifies a JSON object and persists the key orders of the object\n *\n * @param json - The JSON object to stringify\n * @param options - The options to pass to the stringify function\n * @returns The stringified JSON object\n */\nexport function safeStringify(\n json: unknown,\n options?: Parameters<typeof JsonStringify>[1],\n): string {\n const stringified = JsonStringify(json, options);\n if (!stringified) {\n throw new Error('Failed to stringify');\n }\n return stringified;\n}\n\n/**\n * Finds the first element that appears t times in the array\n *\n * @param arr - The array to search\n * @param threshold - The number of times the element should appear\n * @returns The first element that appears t times in the array\n */\nexport function thresholdSame<Type>(\n arr: Type[],\n threshold: number,\n): Type | undefined {\n const hashMap: Record<string, number> = {};\n for (const item of arr) {\n const str = JsonStringify(item);\n if (!str) {\n continue;\n }\n hashMap[str] = hashMap[str] ? hashMap[str] + 1 : 1;\n if (hashMap[str] === threshold) {\n return item;\n }\n }\n return undefined;\n}\n\n/**\n * Generates all possible combinations of k elements from a set.\n *\n * @param inputSet - The set to generate combinations from\n * @param k - The number of elements in each combination\n * @yields All possible combinations of k elements from the set s\n */\nexport function* kCombinations(\n inputSet: number | number[],\n k: number,\n): Generator<number[]> {\n let set = inputSet;\n if (typeof set === 'number') {\n set = Array.from({ length: set }, (_, i) => i);\n }\n if (k > set.length || k <= 0) {\n return;\n }\n\n if (k === set.length) {\n yield set;\n return;\n }\n\n if (k === 1) {\n for (const item of set) {\n yield [item];\n }\n return;\n }\n\n const indices = Array.from({ length: set.length - k + 2 }, (_, i) => i);\n for (const i of indices) {\n for (const j of kCombinations(set.slice(i + 1), k - 1)) {\n yield [set[i], ...j];\n }\n }\n}\n\n/**\n * Calculates the index of the proxy coordinator endpoint based on auth connection id details\n *\n * @param indexes - The indexes to choose from.\n * @param authConnectionId - The auth connection id to use to generate the index\n * @param userId - The user id to use to generate the index\n * @returns The node index of the proxy coordinator endpoint.\n */\nexport const getProxyCoordinatorNodeIndex = (\n indexes: number[],\n authConnectionId: string,\n userId: string,\n): number => {\n const authConnectionIdStr = `${authConnectionId}${userId}`;\n const hashedAuthConnectionId = keccak256AndHexify(\n Buffer.from(authConnectionIdStr, 'utf8'),\n ).slice(2);\n const proxyEndpointNum = new BN(hashedAuthConnectionId, 'hex')\n .mod(new BN(indexes.length))\n .toNumber();\n return indexes[proxyEndpointNum];\n};\n\n/**\n * This function handles when `Some` function cannot determine the outcome of the operation\\\n * even after all promises are settled\n *\n * @param errorArr - array of errors\n * @param resultArr - array of resolved results\n * @param predicateError - error thrown by the callbackFn\n */\nfunction handleSomeCallBackFnError<Type>(\n errorArr: Error[],\n resultArr: Type[],\n predicateError?: Error,\n): never {\n // check if there's any rejected promises\n let hasError = errorArr.some((error) => error !== undefined);\n if (hasError) {\n throw new SomeError({\n errors: errorArr,\n responses: resultArr,\n predicate: predicateError,\n });\n }\n\n type ResultWithError = { error?: { data?: string } };\n\n // check if there're any error inside resolved result array\n const resultArrWithError = resultArr as ResultWithError[];\n hasError = resultArrWithError.some((result) => Boolean(result?.error));\n if (hasError) {\n const errors = resultArr.map((result) => {\n const { error } = result as ResultWithError;\n if (error?.data && error.data.length > 0) {\n return new Error(error.data);\n }\n return undefined;\n });\n throw new SomeError({\n errors,\n responses: resultArr,\n predicate: predicateError,\n });\n }\n\n // no error was thrown and callback never returned a value\n throw new SomeError({\n errors: errorArr,\n responses: resultArr,\n predicate: predicateError,\n });\n}\n\n/**\n * This function executes an array of promises and returns a result of the operation based on the callbackFn return value\n *\n * @param promises - array of promises to execute\n * @param callbackFn - function to execute resolved promises and determine the outcome of the operation conditionally\n * @returns - result of the operation\n */\nexport async function Some<Input, Output>(\n promises: Promise<Input>[],\n callbackFn: (\n resultArr: Input[],\n params: { allSettled: boolean },\n ) => Promise<Output | undefined>,\n): Promise<Output> {\n let predicateError: Error | undefined; // to keep track of the latest error thrown by the callbackFn\n const resultArr: Input[] = new Array(promises.length).fill(undefined);\n const errorArr: Error[] = new Array(promises.length).fill(undefined);\n\n for (const [i, promise] of promises.entries()) {\n try {\n // Race the promise against a timeout\n const timeoutPromise = new Promise<Input>((_resolve, reject) => {\n setTimeout(() => reject(new Error('Promise timed out')), 10_000);\n });\n resultArr[i] = await Promise.race([promise, timeoutPromise]);\n } catch (error: unknown) {\n errorArr[i] = error as Error;\n }\n\n try {\n const allSettled = resultArr.every((result) => result !== undefined);\n const result = await callbackFn(resultArr, { allSettled });\n if (result) {\n return result;\n }\n } catch (error: unknown) {\n predicateError = error as Error;\n }\n }\n\n // If we still don't have a result, handle the error\n handleSomeCallBackFnError(errorArr, resultArr, predicateError);\n}\n\n/**\n * Filters out invalid responses.\n *\n * @param resultArr - The result array to filter.\n * @returns The filtered result array.\n */\nexport function filterCompletedRequests<Type>(resultArr: Type[]): Type[] {\n return resultArr.filter((res) => {\n const isValidObject = res && typeof res === 'object';\n\n const maybeRes = res as { error?: unknown; result?: unknown };\n const hasNoError = !maybeRes?.error;\n const hasResult = Boolean(maybeRes?.result);\n\n return isValidObject && hasNoError && hasResult;\n });\n}\n\n/**\n * Extracts error responses from a result array.\n *\n * @param resultArr - Array of responses to check for errors\n * @returns Array of error responses extracted from the input array\n */\nexport function filterErrorResponses<Type>(\n resultArr: Type[],\n): (Type & { error: unknown })[] {\n return resultArr.filter((res): res is Type & { error: unknown } => {\n const isValidObject = res && typeof res === 'object';\n\n const maybeRes = res as { error?: unknown };\n const hasError = Boolean(maybeRes?.error);\n\n return isValidObject && hasError;\n });\n}\n\n/**\n * Checks if an unknown value is a properly structured JSON-RPC error object\n *\n * @param error - The value to check\n * @returns True if the value is a JSON-RPC error object with the required properties\n */\nexport function isJSONRPCError(error: unknown): error is JSONRPCError {\n const isValidObject = Boolean(error && typeof error === 'object');\n\n const maybeError = error as Partial<JSONRPCError>;\n const hasCode = typeof maybeError?.code === 'number';\n const hasMessage = typeof maybeError?.message === 'string';\n\n return isValidObject && hasCode && hasMessage;\n}\n\nexport type Primitive = string | number | boolean | null;\nexport type JSONObject = { [key: string]: JSONValue };\nexport type JSONArray = JSONValue[];\nexport type JSONValue = Primitive | JSONObject | JSONArray;\n\n// Convert snake_case to camelCase\n/**\n *\n * @param str - The string to convert to camelCase.\n * @returns The camelCase string.\n */\nexport function toCamel(str: string): string {\n return str.replace(/_([a-z])/gu, (_, letter) => letter.toUpperCase());\n}\n\n// Convert camelCase to snake_case\n/**\n *\n * @param str - The string to convert to snake_case.\n * @returns The snake_case string.\n */\nexport function toSnake(str: string): string {\n return str.replace(/([A-Z])/gu, '_$1').toLowerCase();\n}\n\n// Recursive key converter\n/**\n *\n * @param obj - The object to convert the keys of.\n * @param convertFunc - The function to convert the keys of the object.\n * @returns The object with the converted keys.\n */\nexport function convertKeys(\n obj: JSONValue,\n convertFunc: (key: string) => string,\n): JSONValue {\n if (Array.isArray(obj)) {\n return obj.map((item) => convertKeys(item, convertFunc));\n } else if (obj !== null && typeof obj === 'object') {\n const newObj: JSONObject = {};\n for (const [key, value] of Object.entries(obj)) {\n newObj[convertFunc(key)] = convertKeys(value, convertFunc);\n }\n return newObj;\n }\n return obj;\n}\n\n/**\n * Converts the keys of an object from snake_case to camelCase.\n *\n * @param obj - The object to convert the keys of.\n * @returns The object with the converted keys.\n */\nexport const toCamelCaseKeys = (obj: JSONValue): JSONValue =>\n convertKeys(obj, toCamel);\n\n/**\n * Converts the keys of an object from camelCase to snake_case.\n *\n * @param obj - The object to convert the keys of.\n * @returns The object with the converted keys.\n */\nexport const toSnakeCaseKeys = (obj: JSONValue): JSONValue =>\n convertKeys(obj, toSnake);\n"]} | ||
| {"version":3,"file":"common.mjs","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,UAAU,IAAI,SAAS,EAAE,2BAA2B;AAC7D,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I,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAClD,MAAM,MAAM,GAAe,EAAE,CAAC;QAC9B,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;YAC9C,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,GAAG,WAAW,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;SAC5D;QACD,OAAO,MAAM,CAAC;KACf;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAc,EAAa,EAAE,CAC3D,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;AAE5B;;;;;GAKG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,CAAC,GAAc,EAAa,EAAE,CAC3D,WAAW,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC","sourcesContent":["import { keccak_256 as keccak256 } from '@noble/hashes/sha3';\nimport BN from 'bn.js';\nimport JsonStringify from 'json-stable-stringify';\n\nimport { SomeError } from './errors';\nimport type { JSONRPCError } from './interfaces';\n\n/**\n * Hashes a buffer using the keccak256 algorithm and hexify the result\n *\n * @param buffer - The uint8array to hash\n * @returns The hash of the buffer as a hex string\n */\nexport function keccak256AndHexify(buffer: Uint8Array): `0x${string}` {\n const hash = Buffer.from(keccak256(buffer)).toString('hex');\n return `0x${hash}`;\n}\n\n/**\n * Removes the `0x` prefix from a hex string\n *\n * @param hexString - The hex string to remove the `0x` prefix from\n * @returns The hex string without the `0x` prefix\n */\nexport function remove0x(hexString: `0x${string}`): string {\n if (hexString.startsWith('0x')) {\n return hexString.slice(2);\n }\n return hexString;\n}\n\n/**\n * Adds the `0x` prefix to a hex string if it is not already present\n *\n * @param hexString - The hex string to add the `0x` prefix to\n * @returns The hex string with the `0x` prefix\n */\nexport function add0x(hexString: string): `0x${string}` {\n if (hexString.startsWith('0x')) {\n return hexString as `0x${string}`;\n }\n return `0x${hexString}`;\n}\n\n/**\n * Stringifies a JSON object and persists the key orders of the object\n *\n * @param json - The JSON object to stringify\n * @param options - The options to pass to the stringify function\n * @returns The stringified JSON object\n */\nexport function safeStringify(\n json: unknown,\n options?: Parameters<typeof JsonStringify>[1],\n): string {\n const stringified = JsonStringify(json, options);\n if (!stringified) {\n throw new Error('Failed to stringify');\n }\n return stringified;\n}\n\n/**\n * Finds the first element that appears t times in the array\n *\n * @param arr - The array to search\n * @param threshold - The number of times the element should appear\n * @returns The first element that appears t times in the array\n */\nexport function thresholdSame<Type>(\n arr: Type[],\n threshold: number,\n): Type | undefined {\n const hashMap: Record<string, number> = {};\n for (const item of arr) {\n const str = JsonStringify(item);\n if (!str) {\n continue;\n }\n hashMap[str] = hashMap[str] ? hashMap[str] + 1 : 1;\n if (hashMap[str] === threshold) {\n return item;\n }\n }\n return undefined;\n}\n\n/**\n * Generates all possible combinations of k elements from a set.\n *\n * @param inputSet - The set to generate combinations from\n * @param k - The number of elements in each combination\n * @yields All possible combinations of k elements from the set s\n */\nexport function* kCombinations(\n inputSet: number | number[],\n k: number,\n): Generator<number[]> {\n let set = inputSet;\n if (typeof set === 'number') {\n set = Array.from({ length: set }, (_, i) => i);\n }\n if (k > set.length || k <= 0) {\n return;\n }\n\n if (k === set.length) {\n yield set;\n return;\n }\n\n if (k === 1) {\n for (const item of set) {\n yield [item];\n }\n return;\n }\n\n const indices = Array.from({ length: set.length - k + 2 }, (_, i) => i);\n for (const i of indices) {\n for (const j of kCombinations(set.slice(i + 1), k - 1)) {\n yield [set[i], ...j];\n }\n }\n}\n\n/**\n * Calculates the index of the proxy coordinator endpoint based on auth connection id details\n *\n * @param indexes - The indexes to choose from.\n * @param authConnectionId - The auth connection id to use to generate the index\n * @param userId - The user id to use to generate the index\n * @returns The node index of the proxy coordinator endpoint.\n */\nexport const getProxyCoordinatorNodeIndex = (\n indexes: number[],\n authConnectionId: string,\n userId: string,\n): number => {\n const authConnectionIdStr = `${authConnectionId}${userId}`;\n const hashedAuthConnectionId = keccak256AndHexify(\n Buffer.from(authConnectionIdStr, 'utf8'),\n ).slice(2);\n const proxyEndpointNum = new BN(hashedAuthConnectionId, 'hex')\n .mod(new BN(indexes.length))\n .toNumber();\n return indexes[proxyEndpointNum];\n};\n\n/**\n * This function handles when `Some` function cannot determine the outcome of the operation\\\n * even after all promises are settled\n *\n * @param errorArr - array of errors\n * @param resultArr - array of resolved results\n * @param predicateError - error thrown by the callbackFn\n */\nfunction handleSomeCallBackFnError<Type>(\n errorArr: Error[],\n resultArr: Type[],\n predicateError?: Error,\n): never {\n // check if there's any rejected promises\n let hasError = errorArr.some((error) => error !== undefined);\n if (hasError) {\n throw new SomeError({\n errors: errorArr,\n responses: resultArr,\n predicate: predicateError,\n });\n }\n\n type ResultWithError = { error?: { data?: string } };\n\n // check if there're any error inside resolved result array\n const resultArrWithError = resultArr as ResultWithError[];\n hasError = resultArrWithError.some((result) => Boolean(result?.error));\n if (hasError) {\n const errors = resultArr.map((result) => {\n const { error } = result as ResultWithError;\n if (error?.data && error.data.length > 0) {\n return new Error(error.data);\n }\n return undefined;\n });\n throw new SomeError({\n errors,\n responses: resultArr,\n predicate: predicateError,\n });\n }\n\n // no error was thrown and callback never returned a value\n throw new SomeError({\n errors: errorArr,\n responses: resultArr,\n predicate: predicateError,\n });\n}\n\n/**\n * This function executes an array of promises and returns a result of the operation based on the callbackFn return value\n *\n * @param promises - array of promises to execute\n * @param callbackFn - function to execute resolved promises and determine the outcome of the operation conditionally\n * @returns - result of the operation\n */\nexport async function Some<Input, Output>(\n promises: Promise<Input>[],\n callbackFn: (\n resultArr: Input[],\n params: { allSettled: boolean },\n ) => Promise<Output | undefined>,\n): Promise<Output> {\n let predicateError: Error | undefined; // to keep track of the latest error thrown by the callbackFn\n const resultArr: Input[] = new Array(promises.length).fill(undefined);\n const errorArr: Error[] = new Array(promises.length).fill(undefined);\n\n for (const [i, promise] of promises.entries()) {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n try {\n // Race the promise against a timeout\n const timeoutPromise = new Promise<Input>((_resolve, reject) => {\n timeoutId = setTimeout(\n () => reject(new Error('Promise timed out')),\n 10_000,\n );\n });\n resultArr[i] = await Promise.race([promise, timeoutPromise]);\n } catch (error: unknown) {\n errorArr[i] = error as Error;\n } finally {\n // Clear the timeout if it exists and still hasn't been cleared after the Promise.race is settled.\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n\n try {\n const allSettled = resultArr.every((result) => result !== undefined);\n const result = await callbackFn(resultArr, { allSettled });\n if (result) {\n return result;\n }\n } catch (error: unknown) {\n predicateError = error as Error;\n }\n }\n\n // If we still don't have a result, handle the error\n handleSomeCallBackFnError(errorArr, resultArr, predicateError);\n}\n\n/**\n * Filters out invalid responses.\n *\n * @param resultArr - The result array to filter.\n * @returns The filtered result array.\n */\nexport function filterCompletedRequests<Type>(resultArr: Type[]): Type[] {\n return resultArr.filter((res) => {\n const isValidObject = res && typeof res === 'object';\n\n const maybeRes = res as { error?: unknown; result?: unknown };\n const hasNoError = !maybeRes?.error;\n const hasResult = Boolean(maybeRes?.result);\n\n return isValidObject && hasNoError && hasResult;\n });\n}\n\n/**\n * Extracts error responses from a result array.\n *\n * @param resultArr - Array of responses to check for errors\n * @returns Array of error responses extracted from the input array\n */\nexport function filterErrorResponses<Type>(\n resultArr: Type[],\n): (Type & { error: unknown })[] {\n return resultArr.filter((res): res is Type & { error: unknown } => {\n const isValidObject = res && typeof res === 'object';\n\n const maybeRes = res as { error?: unknown };\n const hasError = Boolean(maybeRes?.error);\n\n return isValidObject && hasError;\n });\n}\n\n/**\n * Checks if an unknown value is a properly structured JSON-RPC error object\n *\n * @param error - The value to check\n * @returns True if the value is a JSON-RPC error object with the required properties\n */\nexport function isJSONRPCError(error: unknown): error is JSONRPCError {\n const isValidObject = Boolean(error && typeof error === 'object');\n\n const maybeError = error as Partial<JSONRPCError>;\n const hasCode = typeof maybeError?.code === 'number';\n const hasMessage = typeof maybeError?.message === 'string';\n\n return isValidObject && hasCode && hasMessage;\n}\n\nexport type Primitive = string | number | boolean | null;\nexport type JSONObject = { [key: string]: JSONValue };\nexport type JSONArray = JSONValue[];\nexport type JSONValue = Primitive | JSONObject | JSONArray;\n\n// Convert snake_case to camelCase\n/**\n *\n * @param str - The string to convert to camelCase.\n * @returns The camelCase string.\n */\nexport function toCamel(str: string): string {\n return str.replace(/_([a-z])/gu, (_, letter) => letter.toUpperCase());\n}\n\n// Convert camelCase to snake_case\n/**\n *\n * @param str - The string to convert to snake_case.\n * @returns The snake_case string.\n */\nexport function toSnake(str: string): string {\n return str.replace(/([A-Z])/gu, '_$1').toLowerCase();\n}\n\n// Recursive key converter\n/**\n *\n * @param obj - The object to convert the keys of.\n * @param convertFunc - The function to convert the keys of the object.\n * @returns The object with the converted keys.\n */\nexport function convertKeys(\n obj: JSONValue,\n convertFunc: (key: string) => string,\n): JSONValue {\n if (Array.isArray(obj)) {\n return obj.map((item) => convertKeys(item, convertFunc));\n } else if (obj !== null && typeof obj === 'object') {\n const newObj: JSONObject = {};\n for (const [key, value] of Object.entries(obj)) {\n newObj[convertFunc(key)] = convertKeys(value, convertFunc);\n }\n return newObj;\n }\n return obj;\n}\n\n/**\n * Converts the keys of an object from snake_case to camelCase.\n *\n * @param obj - The object to convert the keys of.\n * @returns The object with the converted keys.\n */\nexport const toCamelCaseKeys = (obj: JSONValue): JSONValue =>\n convertKeys(obj, toCamel);\n\n/**\n * Converts the keys of an object from camelCase to snake_case.\n *\n * @param obj - The object to convert the keys of.\n * @returns The object with the converted keys.\n */\nexport const toSnakeCaseKeys = (obj: JSONValue): JSONValue =>\n convertKeys(obj, toSnake);\n"]} |
+1
-1
| { | ||
| "name": "@metamask/auth-network-utils", | ||
| "version": "0.2.0", | ||
| "version": "0.3.0", | ||
| "description": "common utilities to access and format responses from auth network", | ||
@@ -5,0 +5,0 @@ "keywords": [ |
258632
2.62%2106
3.13%