1 import crypto from
'crypto';
3 import clone from
'just-clone';
5 import { WebSocketCloseEventStatusString
} from
'../types/WebSocket';
7 export default class Utils
{
8 private constructor() {
12 public static logPrefix(prefixString
= ''): string {
13 return new Date().toLocaleString() + prefixString
;
16 public static generateUUID(): string {
17 return crypto
.randomUUID();
20 public static validateUUID(uuid
: string): boolean {
21 return /^[0-9a
-fA
-F
]{8}-[0-9a
-fA
-F
]{4}-4[0-9a
-fA
-F
]{3}-[0-9a
-fA
-F
]{4}-[0-9a
-fA
-F
]{12}$
/.test(
26 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
27 return new Promise((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
30 public static formatDurationMilliSeconds(duration
: number): string {
31 duration
= Utils
.convertToInt(duration
);
32 const hours
= Math.floor(duration
/ (3600 * 1000));
33 const minutes
= Math.floor((duration
/ 1000 - hours
* 3600) / 60);
34 const seconds
= duration
/ 1000 - hours
* 3600 - minutes
* 60;
35 let hoursStr
= hours
.toString();
36 let minutesStr
= minutes
.toString();
37 let secondsStr
= seconds
.toString();
40 hoursStr
= '0' + hours
.toString();
43 minutesStr
= '0' + minutes
.toString();
46 secondsStr
= '0' + seconds
.toString();
48 return hoursStr
+ ':' + minutesStr
+ ':' + secondsStr
.substring(0, 6);
51 public static formatDurationSeconds(duration
: number): string {
52 return Utils
.formatDurationMilliSeconds(duration
* 1000);
55 public static convertToDate(value
: unknown
): Date | null | undefined {
56 if (Utils
.isNullOrUndefined(value
)) {
57 return value
as null | undefined;
59 if (value
instanceof Date) {
62 if (Utils
.isString(value
) || typeof value
=== 'number') {
63 return new Date(value
as string | number);
68 public static convertToInt(value
: unknown
): number {
72 let changedValue
: number = value
as number;
73 if (Number.isSafeInteger(value
)) {
74 return value
as number;
76 if (typeof value
=== 'number') {
77 changedValue
= Math.trunc(value
);
79 if (Utils
.isString(value
)) {
80 changedValue
= parseInt(value
as string);
85 public static convertToFloat(value
: unknown
): number {
89 let changedValue
: number = value
as number;
90 if (Utils
.isString(value
)) {
91 changedValue
= parseFloat(value
as string);
96 public static convertToBoolean(value
: unknown
): boolean {
100 if (typeof value
=== 'boolean') {
103 Utils
.isString(value
) &&
104 ((value
as string).toLowerCase() === 'true' || value
=== '1')
107 } else if (typeof value
=== 'number' && value
=== 1) {
114 public static getRandomFloat(max
= Number.MAX_VALUE
, min
= 0, negative
= false): number {
115 if (max
< min
|| max
< 0 || min
< 0) {
116 throw new RangeError('Invalid interval');
118 const randomPositiveFloat
= crypto
.randomBytes(4).readUInt32LE() / 0xffffffff;
119 const sign
= negative
&& randomPositiveFloat
< 0.5 ? -1 : 1;
120 return sign
* (randomPositiveFloat
* (max
- min
) + min
);
123 public static getRandomInteger(max
= Number.MAX_SAFE_INTEGER
, min
= 0): number {
124 if (max
< min
|| max
< 0 || min
< 0) {
125 throw new RangeError('Invalid interval');
127 max
= Math.floor(max
);
128 if (!Utils
.isNullOrUndefined(min
) && min
!== 0) {
129 min
= Math.ceil(min
);
130 return Math.floor(Utils
.secureRandom() * (max
- min
+ 1)) + min
;
132 return Math.floor(Utils
.secureRandom() * (max
+ 1));
135 public static roundTo(numberValue
: number, scale
: number): number {
136 const roundPower
= Math.pow(10, scale
);
137 return Math.round(numberValue
* roundPower
) / roundPower
;
140 public static truncTo(numberValue
: number, scale
: number): number {
141 const truncPower
= Math.pow(10, scale
);
142 return Math.trunc(numberValue
* truncPower
) / truncPower
;
145 public static getRandomFloatRounded(max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number {
147 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
149 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
152 public static getRandomFloatFluctuatedRounded(
154 fluctuationPercent
: number,
157 if (fluctuationPercent
=== 0) {
158 return Utils
.roundTo(staticValue
, scale
);
160 const fluctuationRatio
= fluctuationPercent
/ 100;
161 return Utils
.getRandomFloatRounded(
162 staticValue
* (1 + fluctuationRatio
),
163 staticValue
* (1 - fluctuationRatio
),
168 public static isObject(item
: unknown
): boolean {
169 return item
&& typeof item
=== 'object' && Array.isArray(item
) === false;
172 public static cloneObject
<T
extends object
>(object
: T
): T
{
173 return clone
<T
>(object
);
176 public static isIterable
<T
>(obj
: T
): boolean {
177 return obj
? typeof obj
[Symbol
.iterator
] === 'function' : false;
180 public static isString(value
: unknown
): boolean {
181 return typeof value
=== 'string';
184 public static isEmptyString(value
: unknown
): boolean {
185 return Utils
.isString(value
) && (value
as string).trim().length
=== 0;
188 public static isUndefined(value
: unknown
): boolean {
189 return typeof value
=== 'undefined';
192 public static isNullOrUndefined(value
: unknown
): boolean {
193 // eslint-disable-next-line eqeqeq, no-eq-null
194 return value
== null ? true : false;
197 public static isEmptyArray(object
: unknown
| unknown
[]): boolean {
198 if (!Array.isArray(object
)) {
201 if (object
.length
> 0) {
207 public static isEmptyObject(obj
: object
): boolean {
208 if (obj
?.constructor
!== Object) {
211 // Iterates over the keys of an object, if
212 // any exist, return false.
213 for (const _
in obj
) {
219 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
220 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
223 * @param [retryNumber=0]
224 * @returns delay in milliseconds
226 public static exponentialDelay(retryNumber
= 0): number {
227 const delay
= Math.pow(2, retryNumber
) * 100;
228 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
229 return delay
+ randomSum
;
232 public static async promiseWithTimeout
<T
>(
236 timeoutCallback
: () => void = () => {
237 /* This is intentional */
240 // Create a timeout promise that rejects in timeout milliseconds
241 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
244 reject(timeoutError
);
248 // Returns a race between timeout promise and the passed promise
249 return Promise
.race
<T
>([promise
, timeoutPromise
]);
253 * Generate a cryptographically secure random number in the [0,1[ range
257 public static secureRandom(): number {
258 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;
261 public static JSONStringifyWithMapSupport(
262 obj
: Record
<string, unknown
> | Record
<string, unknown
>[] | Map
<string, unknown
>,
265 return JSON
.stringify(
267 (key
, value
: Record
<string, unknown
>) => {
268 if (value
instanceof Map
) {
281 * Convert websocket error code to human readable string message
283 * @param code websocket error code
284 * @returns human readable string message
286 public static getWebSocketCloseEventStatusString(code
: number): string {
287 if (code
>= 0 && code
<= 999) {
289 } else if (code
>= 1016) {
291 return '(For WebSocket standard)';
292 } else if (code
<= 2999) {
293 return '(For WebSocket extensions)';
294 } else if (code
<= 3999) {
295 return '(For libraries and frameworks)';
296 } else if (code
<= 4999) {
297 return '(For applications)';
300 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
301 return WebSocketCloseEventStatusString
[code
] as string;