1 import { randomBytes
, randomInt
, randomUUID
} from
'node:crypto';
2 import { inspect
} from
'node:util';
11 import clone from
'just-clone';
13 import { Constants
} from
'./Constants';
14 import { type TimestampedData
, WebSocketCloseEventStatusString
} from
'../types';
16 export const logPrefix
= (prefixString
= ''): string => {
17 return `${new Date().toLocaleString()}${prefixString}`;
20 export const generateUUID
= (): string => {
24 export const validateUUID
= (uuid
: string): boolean => {
25 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(
30 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
31 return new Promise
<NodeJS
.Timeout
>((resolve
) => setTimeout(resolve
as () => void, milliSeconds
));
34 export const formatDurationMilliSeconds
= (duration
: number): string => {
35 duration
= convertToInt(duration
);
36 const days
= Math.floor(duration
/ (24 * 3600 * 1000));
37 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24);
38 const minutes
= Math.floor(millisecondsToMinutes(duration
) - days
* 24 * 60 - hours
* 60);
39 const seconds
= Math.floor(
40 millisecondsToSeconds(duration
) - days
* 24 * 3600 - hours
* 3600 - minutes
* 60,
42 return formatDuration({
50 export const formatDurationSeconds
= (duration
: number): string => {
51 return formatDurationMilliSeconds(secondsToMilliseconds(duration
));
54 export const convertToDate
= (
55 value
: Date | string | number | null | undefined,
56 ): Date | null | undefined => {
57 if (isNullOrUndefined(value
)) {
58 return value
as null | undefined;
60 if (value
instanceof Date) {
63 if (isString(value
) || typeof value
=== 'number') {
64 return new Date(value
!);
69 export const convertToInt
= (value
: unknown
): number => {
73 let changedValue
: number = value
as number;
74 if (Number.isSafeInteger(value
)) {
75 return value
as number;
77 if (typeof value
=== 'number') {
78 return Math.trunc(value
);
80 if (isString(value
)) {
81 changedValue
= parseInt(value
as string);
83 if (isNaN(changedValue
)) {
84 // eslint-disable-next-line @typescript-eslint/no-base-to-string
85 throw new Error(`Cannot convert to integer: ${value.toString()}`);
90 export const convertToFloat
= (value
: unknown
): number => {
94 let changedValue
: number = value
as number;
95 if (isString(value
)) {
96 changedValue
= parseFloat(value
as string);
98 if (isNaN(changedValue
)) {
99 // eslint-disable-next-line @typescript-eslint/no-base-to-string
100 throw new Error(`Cannot convert to float: ${value.toString()}`);
105 export const convertToBoolean
= (value
: unknown
): boolean => {
109 if (typeof value
=== 'boolean') {
111 } else if (isString(value
) && ((value
as string).toLowerCase() === 'true' || value
=== '1')) {
113 } else if (typeof value
=== 'number' && value
=== 1) {
120 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
122 throw new RangeError('Invalid interval');
124 if (max
- min
=== Infinity) {
125 throw new RangeError('Invalid interval');
127 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
;
130 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
131 max
= Math.floor(max
);
132 if (!isNullOrUndefined(min
) && min
!== 0) {
133 min
= Math.ceil(min
);
134 return Math.floor(randomInt(min
, max
+ 1));
136 return Math.floor(randomInt(max
+ 1));
140 * Rounds the given number to the given scale.
141 * The rounding is done using the "round half away from zero" method.
143 * @param numberValue - The number to round.
144 * @param scale - The scale to round to.
145 * @returns The rounded number.
147 export const roundTo
= (numberValue
: number, scale
: number): number => {
148 const roundPower
= Math.pow(10, scale
);
149 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
;
152 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
154 return roundTo(getRandomFloat(max
, min
), scale
);
156 return roundTo(getRandomFloat(max
), scale
);
159 export const getRandomFloatFluctuatedRounded
= (
161 fluctuationPercent
: number,
164 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
165 throw new RangeError(
166 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`,
169 if (fluctuationPercent
=== 0) {
170 return roundTo(staticValue
, scale
);
172 const fluctuationRatio
= fluctuationPercent
/ 100;
173 return getRandomFloatRounded(
174 staticValue
* (1 + fluctuationRatio
),
175 staticValue
* (1 - fluctuationRatio
),
180 export const extractTimeSeriesValues
= (timeSeries
: Array<TimestampedData
>): number[] => {
181 return timeSeries
.map((timeSeriesItem
) => timeSeriesItem
.value
);
184 export const isObject
= (item
: unknown
): boolean => {
186 isNullOrUndefined(item
) === false && typeof item
=== 'object' && Array.isArray(item
) === false
190 export const cloneObject
= <T
extends object
>(object
: T
): T
=> {
191 return clone
<T
>(object
);
194 export const hasOwnProp
= (object
: unknown
, property
: PropertyKey
): boolean => {
195 return isObject(object
) && Object.hasOwn(object
as object
, property
);
198 export const isCFEnvironment
= (): boolean => {
199 return !isNullOrUndefined(process
.env
.VCAP_APPLICATION
);
202 export const isIterable
= <T
>(obj
: T
): boolean => {
203 return !isNullOrUndefined(obj
) ? typeof obj
[Symbol
.iterator
as keyof T
] === 'function' : false;
206 const isString
= (value
: unknown
): boolean => {
207 return typeof value
=== 'string';
210 export const isEmptyString
= (value
: unknown
): boolean => {
211 return isNullOrUndefined(value
) || (isString(value
) && (value
as string).trim().length
=== 0);
214 export const isNotEmptyString
= (value
: unknown
): boolean => {
215 return isString(value
) && (value
as string).trim().length
> 0;
218 export const isUndefined
= (value
: unknown
): boolean => {
219 return value
=== undefined;
222 export const isNullOrUndefined
= (value
: unknown
): boolean => {
223 // eslint-disable-next-line eqeqeq, no-eq-null
224 return value
== null;
227 export const isEmptyArray
= (object
: unknown
): boolean => {
228 return Array.isArray(object
) && object
.length
=== 0;
231 export const isNotEmptyArray
= (object
: unknown
): boolean => {
232 return Array.isArray(object
) && object
.length
> 0;
235 export const isEmptyObject
= (obj
: object
): boolean => {
236 if (obj
?.constructor
!== Object) {
239 // Iterates over the keys of an object, if
240 // any exist, return false.
241 for (const _
in obj
) {
247 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
248 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`;
251 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
253 * @param retryNumber - the number of retries that have already been attempted
254 * @returns delay in milliseconds
256 export const exponentialDelay
= (retryNumber
= 0, maxDelayRatio
= 0.2): number => {
257 const delay
= Math.pow(2, retryNumber
) * 100;
258 const randomSum
= delay
* maxDelayRatio
* secureRandom(); // 0-20% of the delay
259 return delay
+ randomSum
;
262 const isPromisePending
= (promise
: Promise
<unknown
>): boolean => {
263 return inspect(promise
).includes('pending');
266 export const promiseWithTimeout
= async <T
>(
270 timeoutCallback
: () => void = () => {
271 /* This is intentional */
274 // Create a timeout promise that rejects in timeout milliseconds
275 const timeoutPromise
= new Promise
<never>((_
, reject
) => {
277 if (isPromisePending(promise
)) {
279 // FIXME: The original promise shall be canceled
281 reject(timeoutError
);
285 // Returns a race between timeout promise and the passed promise
286 return Promise
.race
<T
>([promise
, timeoutPromise
]);
290 * Generates a cryptographically secure random number in the [0,1[ range
294 export const secureRandom
= (): number => {
295 return randomBytes(4).readUInt32LE() / 0x100000000;
298 export const JSONStringifyWithMapSupport
= (
299 obj
: Record
<string, unknown
> | Record
<string, unknown
>[] | Map
<unknown
, unknown
>,
302 return JSON
.stringify(
304 (_
, value
: Record
<string, unknown
>) => {
305 if (value
instanceof Map
) {
318 * Converts websocket error code to human readable string message
320 * @param code - websocket error code
321 * @returns human readable string message
323 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
324 if (code
>= 0 && code
<= 999) {
326 } else if (code
>= 1016) {
328 return '(For WebSocket standard)';
329 } else if (code
<= 2999) {
330 return '(For WebSocket extensions)';
331 } else if (code
<= 3999) {
332 return '(For libraries and frameworks)';
333 } else if (code
<= 4999) {
334 return '(For applications)';
339 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
],
342 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
];