1 import { randomBytes
, randomInt
, randomUUID
, webcrypto
} from
'node:crypto';
2 import { env
} from
'node:process';
3 import { inspect
} from
'node:util';
11 millisecondsToMinutes
,
12 millisecondsToSeconds
,
14 secondsToMilliseconds
,
17 import { Constants
} from
'./Constants';
18 import { type TimestampedData
, WebSocketCloseEventStatusString
} from
'../types';
20 export const logPrefix
= (prefixString
= ''): string => {
21 return `${new Date().toLocaleString()}${prefixString}`;
24 export const generateUUID
= (): string => {
28 export const validateUUID
= (uuid
: string): boolean => {
29 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(
34 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
35 return new Promise
<NodeJS
.Timeout
>((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
38 export const formatDurationMilliSeconds
= (duration
: number): string => {
39 duration
= convertToInt(duration
);
40 const days
= Math.floor(duration
/ (24 * 3600 * 1000));
41 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24);
42 const minutes
= Math.floor(
43 millisecondsToMinutes(duration
) - days
* 24 * 60 - hoursToMinutes(hours
),
45 const seconds
= Math.floor(
46 millisecondsToSeconds(duration
) -
48 hoursToSeconds(hours
) -
49 minutesToSeconds(minutes
),
51 return formatDuration({
59 export const formatDurationSeconds
= (duration
: number): string => {
60 return formatDurationMilliSeconds(secondsToMilliseconds(duration
));
63 // More efficient time validation function than the one provided by date-fns
64 export const isValidTime
= (date
: unknown
): boolean => {
65 if (typeof date
=== 'number') {
67 } else if (isDate(date
)) {
68 return !isNaN((date
as Date).getTime());
73 export const convertToDate
= (value
: Date | string | number | undefined): Date | undefined => {
74 if (isNullOrUndefined(value
)) {
75 return value
as undefined;
80 if (isString(value
) || typeof value
=== 'number') {
81 const valueToDate
= new Date(value
as string | number);
82 if (isNaN(valueToDate
.getTime())) {
83 throw new Error(`Cannot convert to date: '${value as string | number}'`);
89 export const convertToInt
= (value
: unknown
): number => {
93 let changedValue
: number = value
as number;
94 if (Number.isSafeInteger(value
)) {
95 return value
as number;
97 if (typeof value
=== 'number') {
98 return Math.trunc(value
);
100 if (isString(value
)) {
101 changedValue
= parseInt(value
as string);
103 if (isNaN(changedValue
)) {
104 throw new Error(`Cannot convert to integer: '${String(value)}'`);
109 export const convertToFloat
= (value
: unknown
): number => {
113 let changedValue
: number = value
as number;
114 if (isString(value
)) {
115 changedValue
= parseFloat(value
as string);
117 if (isNaN(changedValue
)) {
118 throw new Error(`Cannot convert to float: '${String(value)}'`);
123 export const convertToBoolean
= (value
: unknown
): boolean => {
127 if (typeof value
=== 'boolean') {
129 } else if (isString(value
) && ((value
as string).toLowerCase() === 'true' || value
=== '1')) {
131 } else if (typeof value
=== 'number' && value
=== 1) {
138 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
140 throw new RangeError('Invalid interval');
142 if (max
- min
=== Infinity) {
143 throw new RangeError('Invalid interval');
145 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
;
148 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
149 max
= Math.floor(max
);
150 if (!isNullOrUndefined(min
) && min
!== 0) {
151 min
= Math.ceil(min
);
152 return Math.floor(randomInt(min
, max
+ 1));
154 return Math.floor(randomInt(max
+ 1));
158 * Rounds the given number to the given scale.
159 * The rounding is done using the "round half away from zero" method.
161 * @param numberValue - The number to round.
162 * @param scale - The scale to round to.
163 * @returns The rounded number.
165 export const roundTo
= (numberValue
: number, scale
: number): number => {
166 const roundPower
= Math.pow(10, scale
);
167 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
;
170 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
172 return roundTo(getRandomFloat(max
, min
), scale
);
174 return roundTo(getRandomFloat(max
), scale
);
177 export const getRandomFloatFluctuatedRounded
= (
179 fluctuationPercent
: number,
182 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
183 throw new RangeError(
184 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
187 if (fluctuationPercent
=== 0) {
188 return roundTo(staticValue
, scale
);
190 const fluctuationRatio
= fluctuationPercent
/ 100;
191 return getRandomFloatRounded(
192 staticValue
* (1 + fluctuationRatio
),
193 staticValue
* (1 - fluctuationRatio
),
198 export const extractTimeSeriesValues
= (timeSeries
: Array<TimestampedData
>): number[] => {
199 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
202 export const isObject
= (item
: unknown
): boolean => {
204 isNullOrUndefined(item
) === false && typeof item
=== 'object' && Array.isArray(item
) === false
216 | { [key
: string]: CloneableData
};
218 type FormatKey
= (key
: string) => string;
220 const deepClone
= <I
extends CloneableData
, O
extends CloneableData
= I
>(
222 formatKey
?: FormatKey
,
223 refs
: Map
<I
, O
> = new Map
<I
, O
>(),
225 const ref
= refs
.get(value
);
226 if (ref
!== undefined) {
229 if (Array.isArray(value
)) {
230 const clone
: CloneableData
[] = [];
231 refs
.set(value
, clone
as O
);
232 for (let i
= 0; i
< value
.length
; i
++) {
233 clone
[i
] = deepClone(value
[i
], formatKey
, refs
);
237 if (value
instanceof Date) {
238 return new Date(value
.valueOf()) as O
;
240 if (typeof value
!== 'object' || value
=== null) {
241 return value
as unknown
as O
;
243 const clone
: Record
<string, CloneableData
> = {};
244 refs
.set(value
, clone
as O
);
245 for (const key
of Object.keys(value
)) {
246 clone
[typeof formatKey
=== 'function' ? formatKey(key
) : key
] = deepClone(
255 export const cloneObject
= <T
>(object
: T
): T
=> {
256 return deepClone(object
as CloneableData
) as T
;
259 export const hasOwnProp
= (object
: unknown
, property
: PropertyKey
): boolean => {
260 return isObject(object
) && Object.hasOwn(object
as object
, property
);
263 export const isCFEnvironment
= (): boolean => {
264 return !isNullOrUndefined(env
.VCAP_APPLICATION
);
267 export const isIterable
= <T
>(obj
: T
): boolean => {
268 return !isNullOrUndefined(obj
) ? typeof obj
[Symbol
.iterator
as keyof T
] === 'function' : false;
271 const isString
= (value
: unknown
): boolean => {
272 return typeof value
=== 'string';
275 export const isEmptyString
= (value
: unknown
): boolean => {
276 return isNullOrUndefined(value
) || (isString(value
) && (value
as string).trim().length
=== 0);
279 export const isNotEmptyString
= (value
: unknown
): boolean => {
280 return isString(value
) && (value
as string).trim().length
> 0;
283 export const isUndefined
= (value
: unknown
): boolean => {
284 return value
=== undefined;
287 export const isNullOrUndefined
= (value
: unknown
): boolean => {
288 // eslint-disable-next-line eqeqeq, no-eq-null
289 return value
== null;
292 export const isEmptyArray
= (object
: unknown
): boolean => {
293 return Array.isArray(object
) && object
.length
=== 0;
296 export const isNotEmptyArray
= (object
: unknown
): boolean => {
297 return Array.isArray(object
) && object
.length
> 0;
300 export const isEmptyObject
= (obj
: object
): boolean => {
301 if (obj
?.constructor
!== Object) {
304 // Iterates over the keys of an object, if
305 // any exist, return false.
306 for (const _
in obj
) {
312 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
313 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
316 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
318 * @param retryNumber - the number of retries that have already been attempted
319 * @param delayFactor - the base delay factor in milliseconds
320 * @returns delay in milliseconds
322 export const exponentialDelay
= (retryNumber
= 0, delayFactor
= 100): number => {
323 const delay
= Math.pow(2, retryNumber
) * delayFactor
;
324 const randomSum
= delay
* 0.2 * secureRandom(); // 0-20% of the delay
325 return delay
+ randomSum
;
328 const isPromisePending
= (promise
: Promise
<unknown
>): boolean => {
329 return inspect(promise
).includes('pending');
332 export const promiseWithTimeout
= async <T
>(
336 timeoutCallback
: () => void = () => {
337 /* This is intentional */
340 // Creates a timeout promise that rejects in timeout milliseconds
341 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
343 if (isPromisePending(promise
)) {
345 // FIXME: The original promise shall be canceled
347 reject(timeoutError
);
351 // Returns a race between timeout promise and the passed promise
352 return Promise
.race
<T
>([promise
, timeoutPromise
]);
356 * Generates a cryptographically secure random number in the [0,1[ range
358 * @returns A number in the [0,1[ range
360 export const secureRandom
= (): number => {
361 return webcrypto
.getRandomValues(new Uint32Array(1))[0] / 0x100000000;
364 export const JSONStringifyWithMapSupport
= (
365 obj
: Record
<string, unknown
> | Record
<string, unknown
>[] | Map
<unknown
, unknown
>,
368 return JSON
.stringify(
370 (_
, value
: Record
<string, unknown
>) => {
371 if (value
instanceof Map
) {
384 * Converts websocket error code to human readable string message
386 * @param code - websocket error code
387 * @returns human readable string message
389 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
390 if (code
>= 0 && code
<= 999) {
392 } else if (code
>= 1016) {
394 return '(For WebSocket standard)';
395 } else if (code
<= 2999) {
396 return '(For WebSocket extensions)';
397 } else if (code
<= 3999) {
398 return '(For libraries and frameworks)';
399 } else if (code
<= 4999) {
400 return '(For applications)';
405 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
],
408 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
];
413 export const isArraySorted
= <T
>(array
: T
[], compareFn
: (a
: T
, b
: T
) => number): boolean => {
414 for (let index
= 0; index
< array
.length
- 1; ++index
) {
415 if (compareFn(array
[index
], array
[index
+ 1]) > 0) {
422 // eslint-disable-next-line @typescript-eslint/no-explicit-any
423 export const once
= <T
, A
extends any[], R
>(
424 fn
: (...args
: A
) => R
,
426 ): ((...args
: A
) => R
) => {
428 return (...args
: A
) => {
430 result
= fn
.apply
<T
, A
, R
>(context
, args
);
431 (fn
as unknown
as undefined) = (context
as unknown
as undefined) = undefined;
437 export const min
= (...args
: number[]): number =>
438 args
.reduce((minimum
, num
) => (minimum
< num
? minimum
: num
), Infinity);
440 export const max
= (...args
: number[]): number =>
441 args
.reduce((maximum
, num
) => (maximum
> num
? maximum
: num
), -Infinity);