@hyperlane-xyz/utils
Version:
General utilities and types for the Hyperlane network
49 lines • 1.79 kB
JavaScript
import { ensure0x, strip0x } from './addresses.js';
export function toTitleCase(str) {
return str.replace(/\w\S*/g, (txt) => {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
export function toUpperCamelCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Only allows letters and numbers
const alphanumericRgex = /[^a-zA-Z0-9]/gi;
export function sanitizeString(str) {
if (!str || typeof str !== 'string')
return '';
return str.replaceAll(alphanumericRgex, '').toLowerCase();
}
export function trimToLength(value, maxLength) {
if (!value)
return '';
const trimmed = value.trim();
return trimmed.length > maxLength
? trimmed.substring(0, maxLength) + '...'
: trimmed;
}
export function streamToString(stream) {
return new Promise((resolve, reject) => {
const chunks = [];
stream
.setEncoding('utf8')
.on('data', (chunk) => chunks.push(chunk))
.on('error', (err) => reject(err))
.on('end', () => resolve(String.prototype.concat(...chunks)));
});
}
export function errorToString(error, maxLength = 300) {
if (!error)
return 'Unknown Error';
if (typeof error === 'string')
return trimToLength(error, maxLength);
if (typeof error === 'number')
return `Error code: ${error}`;
const details = error.message || error.reason || error;
if (typeof details === 'string')
return trimToLength(details, maxLength);
return trimToLength(JSON.stringify(details), maxLength);
}
export const fromHexString = (hexstr) => Buffer.from(strip0x(hexstr), 'hex');
export const toHexString = (buf) => ensure0x(buf.toString('hex'));
//# sourceMappingURL=strings.js.map