1 import crypto from
'node:crypto';
2 import util from
'node:util';
4 import clone from
'just-clone';
6 // import { Constants } from './internal';
7 import { Constants
} from
'./Constants';
8 import { WebSocketCloseEventStatusString
} from
'../types';
11 private constructor() {
12 // This is intentional
15 public static logPrefix
= (prefixString
= ''): string => {
16 return `${new Date().toLocaleString()}${prefixString}`;
19 public static generateUUID(): string {
20 return crypto
.randomUUID();
23 public static validateUUID(uuid
: string): boolean {
24 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(
29 public static async sleep(milliSeconds
: number): Promise
<NodeJS
.Timeout
> {
30 return new Promise((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
33 public static formatDurationMilliSeconds(duration
: number): string {
34 duration
= Utils
.convertToInt(duration
);
35 const hours
= Math.floor(duration
/ (3600 * 1000));
36 const minutes
= Math.floor((duration
/ 1000 - hours
* 3600) / 60);
37 const seconds
= duration
/ 1000 - hours
* 3600 - minutes
* 60;
38 let hoursStr
= hours
.toString();
39 let minutesStr
= minutes
.toString();
40 let secondsStr
= seconds
.toString();
43 hoursStr
= `0${hours.toString()}`;
46 minutesStr
= `0${minutes.toString()}`;
49 secondsStr
= `0${seconds.toString()}`;
51 return `${hoursStr}:${minutesStr}:${secondsStr.substring(0, 6)}`;
54 public static formatDurationSeconds(duration
: number): string {
55 return Utils
.formatDurationMilliSeconds(duration
* 1000);
58 public static convertToDate(
59 value
: Date | string | number | null | undefined
60 ): Date | null | undefined {
61 if (Utils
.isNullOrUndefined(value
)) {
62 return value
as null | undefined;
64 if (value
instanceof Date) {
67 if (Utils
.isString(value
) || typeof value
=== 'number') {
68 return new Date(value
);
73 public static convertToInt(value
: unknown
): number {
77 let changedValue
: number = value
as number;
78 if (Number.isSafeInteger(value
)) {
79 return value
as number;
81 if (typeof value
=== 'number') {
82 return Math.trunc(value
);
84 if (Utils
.isString(value
)) {
85 changedValue
= parseInt(value
as string);
87 if (isNaN(changedValue
)) {
88 throw new Error(`Cannot convert to integer: ${value.toString()}`);
93 public static convertToFloat(value
: unknown
): number {
97 let changedValue
: number = value
as number;
98 if (Utils
.isString(value
)) {
99 changedValue
= parseFloat(value
as string);
101 if (isNaN(changedValue
)) {
102 throw new Error(`Cannot convert to float: ${value.toString()}`);
107 public static convertToBoolean(value
: unknown
): boolean {
111 if (typeof value
=== 'boolean') {
114 Utils
.isString(value
) &&
115 ((value
as string).toLowerCase() === 'true' || value
=== '1')
118 } else if (typeof value
=== 'number' && value
=== 1) {
125 public static getRandomFloat(max
= Number.MAX_VALUE
, min
= 0): number {
127 throw new RangeError('Invalid interval');
129 if (max
- min
=== Infinity) {
130 throw new RangeError('Invalid interval');
132 return (crypto
.randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
;
135 public static getRandomInteger(max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number {
136 max
= Math.floor(max
);
137 if (!Utils
.isNullOrUndefined(min
) && min
!== 0) {
138 min
= Math.ceil(min
);
139 return Math.floor(crypto
.randomInt(min
, max
+ 1));
141 return Math.floor(crypto
.randomInt(max
+ 1));
144 public static roundTo(numberValue
: number, scale
: number): number {
145 const roundPower
= Math.pow(10, scale
);
146 return Math.round(numberValue
* roundPower
) / roundPower
;
149 public static truncTo(numberValue
: number, scale
: number): number {
150 const truncPower
= Math.pow(10, scale
);
151 return Math.trunc(numberValue
* truncPower
) / truncPower
;
154 public static getRandomFloatRounded(max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number {
156 return Utils
.roundTo(Utils
.getRandomFloat(max
, min
), scale
);
158 return Utils
.roundTo(Utils
.getRandomFloat(max
), scale
);
161 public static getRandomFloatFluctuatedRounded(
163 fluctuationPercent
: number,
166 if (fluctuationPercent
=== 0) {
167 return Utils
.roundTo(staticValue
, scale
);
169 const fluctuationRatio
= fluctuationPercent
/ 100;
170 return Utils
.getRandomFloatRounded(
171 staticValue
* (1 + fluctuationRatio
),
172 staticValue
* (1 - fluctuationRatio
),
177 public static isObject(item
: unknown
): boolean {
179 Utils
.isNullOrUndefined(item
) === false &&
180 typeof item
=== 'object' &&
181 Array.isArray(item
) === false
185 public static cloneObject
<T
extends object
>(object
: T
): T
{
186 return clone
<T
>(object
);
189 public static hasOwnProp(object
: unknown
, property
: PropertyKey
): boolean {
190 return Utils
.isObject(object
) && Object.hasOwn(object
as object
, property
);
193 public static isCFEnvironment(): boolean {
194 return process
.env
.VCAP_APPLICATION
!== undefined;
197 public static isIterable
<T
>(obj
: T
): boolean {
198 return !Utils
.isNullOrUndefined(obj
) ? typeof obj
[Symbol
.iterator
] === 'function' : false;
201 public static isString(value
: unknown
): boolean {
202 return typeof value
=== 'string';
205 public static isEmptyString(value
: unknown
): boolean {
207 Utils
.isNullOrUndefined(value
) ||
208 (Utils
.isString(value
) && (value
as string).trim().length
=== 0)
212 public static isNotEmptyString(value
: unknown
): boolean {
213 return Utils
.isString(value
) && (value
as string).trim().length
> 0;
216 public static isUndefined(value
: unknown
): boolean {
217 return value
=== undefined;
220 public static isNullOrUndefined(value
: unknown
): boolean {
221 // eslint-disable-next-line eqeqeq, no-eq-null
222 return value
== null;
225 public static isEmptyArray(object
: unknown
| unknown
[]): boolean {
226 return Array.isArray(object
) && object
.length
=== 0;
229 public static isNotEmptyArray(object
: unknown
| unknown
[]): boolean {
230 return Array.isArray(object
) && object
.length
> 0;
233 public static isEmptyObject(obj
: object
): boolean {
234 if (obj
?.constructor
!== Object) {
237 // Iterates over the keys of an object, if
238 // any exist, return false.
239 for (const _
in obj
) {
245 public static insertAt
= (str
: string, subStr
: string, pos
: number): string =>
246 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
249 * @param retryNumber - the number of retries that have already been attempted
250 * @returns delay in milliseconds
252 public static exponentialDelay(retryNumber
= 0): number {
253 const delay
= Math.pow(2, retryNumber
) * 100;
254 const randomSum
= delay
* 0.2 * Utils
.secureRandom(); // 0-20% of the delay
255 return delay
+ randomSum
;
258 public static isPromisePending(promise
: Promise
<unknown
>): boolean {
259 return util
.inspect(promise
).includes('pending');
262 public static async promiseWithTimeout
<T
>(
266 timeoutCallback
: () => void = () => {
267 /* This is intentional */
270 // Create a timeout promise that rejects in timeout milliseconds
271 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
273 if (Utils
.isPromisePending(promise
)) {
275 // FIXME: The original promise shall be canceled
277 reject(timeoutError
);
281 // Returns a race between timeout promise and the passed promise
282 return Promise
.race
<T
>([promise
, timeoutPromise
]);
286 * Generate a cryptographically secure random number in the [0,1[ range
290 public static secureRandom(): number {
291 return crypto
.randomBytes(4).readUInt32LE() / 0x100000000;
294 public static JSONStringifyWithMapSupport(
295 obj
: Record
<string, unknown
> | Record
<string, unknown
>[] | Map
<unknown
, unknown
>,
298 return JSON
.stringify(
300 (key
, value
: Record
<string, unknown
>) => {
301 if (value
instanceof Map
) {
314 * Convert websocket error code to human readable string message
316 * @param code - websocket error code
317 * @returns human readable string message
319 public static getWebSocketCloseEventStatusString(code
: number): string {
320 if (code
>= 0 && code
<= 999) {
322 } else if (code
>= 1016) {
324 return '(For WebSocket standard)';
325 } else if (code
<= 2999) {
326 return '(For WebSocket extensions)';
327 } else if (code
<= 3999) {
328 return '(For libraries and frameworks)';
329 } else if (code
<= 4999) {
330 return '(For applications)';
333 if (!Utils
.isUndefined(WebSocketCloseEventStatusString
[code
])) {
334 return WebSocketCloseEventStatusString
[code
] as string;