1 import { getRandomValues
, randomBytes
, randomInt
, randomUUID
} from
'node:crypto'
2 import { env
, nextTick
} from
'node:process'
10 millisecondsToMinutes
,
11 millisecondsToSeconds
,
16 import { Constants
} from
'./Constants.js'
20 WebSocketCloseEventStatusString
21 } from
'../types/index.js'
23 export const logPrefix
= (prefixString
= ''): string => {
24 return `${new Date().toLocaleString()}${prefixString}`
27 export const generateUUID
= (): string => {
31 export const validateUUID
= (uuid
: string): boolean => {
32 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(uuid
)
35 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
36 return await new Promise
<NodeJS
.Timeout
>(resolve
=>
37 setTimeout(resolve
as () => void, milliSeconds
)
41 export const formatDurationMilliSeconds
= (duration
: number): string => {
42 duration
= convertToInt(duration
)
44 throw new RangeError('Duration cannot be negative')
46 const days
= Math.floor(duration
/ (24 * 3600 * 1000))
47 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24)
48 const minutes
= Math.floor(
49 millisecondsToMinutes(duration
) - days
* 24 * 60 - hoursToMinutes(hours
)
51 const seconds
= Math.floor(
52 millisecondsToSeconds(duration
) -
54 hoursToSeconds(hours
) -
55 minutesToSeconds(minutes
)
57 if (days
=== 0 && hours
=== 0 && minutes
=== 0 && seconds
=== 0) {
58 return formatDuration({ seconds
}, { zero
: true })
60 return formatDuration({
68 export const formatDurationSeconds
= (duration
: number): string => {
69 return formatDurationMilliSeconds(secondsToMilliseconds(duration
))
72 // More efficient time validation function than the one provided by date-fns
73 export const isValidDate
= (date
: Date | number | undefined): date
is Date | number => {
74 if (typeof date
=== 'number') {
76 } else if (isDate(date
)) {
77 return !isNaN(date
.getTime())
82 export const convertToDate
= (
83 value
: Date | string | number | undefined | null
84 ): Date | undefined => {
91 if (isString(value
) || typeof value
=== 'number') {
92 const valueToDate
= new Date(value
)
93 if (isNaN(valueToDate
.getTime())) {
94 throw new Error(`Cannot convert to date: '${value}'`)
100 export const convertToInt
= (value
: unknown
): number => {
104 let changedValue
: number = value
as number
105 if (Number.isSafeInteger(value
)) {
106 return value
as number
108 if (typeof value
=== 'number') {
109 return Math.trunc(value
)
111 if (isString(value
)) {
112 changedValue
= parseInt(value
)
114 if (isNaN(changedValue
)) {
115 throw new Error(`Cannot convert to integer: '${String(value)}'`)
120 export const convertToFloat
= (value
: unknown
): number => {
124 let changedValue
: number = value
as number
125 if (isString(value
)) {
126 changedValue
= parseFloat(value
)
128 if (isNaN(changedValue
)) {
129 throw new Error(`Cannot convert to float: '${String(value)}'`)
134 export const convertToBoolean
= (value
: unknown
): boolean => {
138 if (typeof value
=== 'boolean') {
140 } else if (isString(value
) && (value
.toLowerCase() === 'true' || value
=== '1')) {
142 } else if (typeof value
=== 'number' && value
=== 1) {
149 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
151 throw new RangeError('Invalid interval')
153 if (max
- min
=== Infinity) {
154 throw new RangeError('Invalid interval')
156 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
159 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
160 max
= Math.floor(max
)
163 return Math.floor(randomInt(min
, max
+ 1))
165 return Math.floor(randomInt(max
+ 1))
169 * Rounds the given number to the given scale.
170 * The rounding is done using the "round half away from zero" method.
172 * @param numberValue - The number to round.
173 * @param scale - The scale to round to.
174 * @returns The rounded number.
176 export const roundTo
= (numberValue
: number, scale
: number): number => {
177 const roundPower
= Math.pow(10, scale
)
178 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
181 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
183 return roundTo(getRandomFloat(max
, min
), scale
)
185 return roundTo(getRandomFloat(max
), scale
)
188 export const getRandomFloatFluctuatedRounded
= (
190 fluctuationPercent
: number,
193 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
194 throw new RangeError(
195 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
198 if (fluctuationPercent
=== 0) {
199 return roundTo(staticValue
, scale
)
201 const fluctuationRatio
= fluctuationPercent
/ 100
202 return getRandomFloatRounded(
203 staticValue
* (1 + fluctuationRatio
),
204 staticValue
* (1 - fluctuationRatio
),
209 export const extractTimeSeriesValues
= (timeSeries
: TimestampedData
[]): number[] => {
210 return timeSeries
.map(timeSeriesItem
=> timeSeriesItem
.value
)
221 | { [key
: string]: CloneableData
}
223 type FormatKey
= (key
: string) => string
225 const deepClone
= <I
extends CloneableData
, O
extends CloneableData
= I
>(
227 formatKey
?: FormatKey
,
228 refs
: Map
<I
, O
> = new Map
<I
, O
>()
230 const ref
= refs
.get(value
)
231 if (ref
!== undefined) {
234 if (Array.isArray(value
)) {
235 const clone
: CloneableData
[] = []
236 refs
.set(value
, clone
as O
)
237 for (let i
= 0; i
< value
.length
; i
++) {
238 clone
[i
] = deepClone(value
[i
], formatKey
, refs
)
242 if (value
instanceof Date) {
243 return new Date(value
.getTime()) as O
245 if (typeof value
!== 'object' || value
=== null) {
246 return value
as unknown
as O
248 const clone
: Record
<string, CloneableData
> = {}
249 refs
.set(value
, clone
as O
)
250 for (const key
of Object.keys(value
)) {
251 clone
[typeof formatKey
=== 'function' ? formatKey(key
) : key
] = deepClone(
260 export const clone
= <T
>(object
: T
): T
=> {
261 return deepClone(object
as CloneableData
) as T
265 * Detects whether the given value is an asynchronous function or not.
267 * @param fn - Unknown value.
268 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
271 export const isAsyncFunction
= (fn
: unknown
): fn
is (...args
: unknown
[]) => Promise
<unknown
> => {
272 return typeof fn
=== 'function' && fn
.constructor
.name
=== 'AsyncFunction'
275 export const isObject
= (value
: unknown
): value
is object
=> {
276 return value
!= null && typeof value
=== 'object' && !Array.isArray(value
)
279 export const isEmptyObject
= (object
: object
): object
is EmptyObject
=> {
280 if (object
.constructor
!== Object) {
283 // Iterates over the keys of an object, if
284 // any exist, return false.
285 // eslint-disable-next-line no-unreachable-loop
286 for (const _
in object
) {
292 export const hasOwnProp
= (value
: unknown
, property
: PropertyKey
): boolean => {
293 return isObject(value
) && Object.hasOwn(value
, property
)
296 export const isCFEnvironment
= (): boolean => {
297 return env
.VCAP_APPLICATION
!= null
300 const isString
= (value
: unknown
): value
is string => {
301 return typeof value
=== 'string'
304 export const isEmptyString
= (value
: unknown
): value
is '' | undefined | null => {
305 return value
== null || (isString(value
) && value
.trim().length
=== 0)
308 export const isNotEmptyString
= (value
: unknown
): value
is string => {
309 return isString(value
) && value
.trim().length
> 0
312 export const isEmptyArray
= (value
: unknown
): value
is never[] => {
313 return Array.isArray(value
) && value
.length
=== 0
316 export const isNotEmptyArray
= (value
: unknown
): value
is unknown
[] => {
317 return Array.isArray(value
) && value
.length
> 0
320 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
321 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
324 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
326 * @param retryNumber - the number of retries that have already been attempted
327 * @param delayFactor - the base delay factor in milliseconds
328 * @returns delay in milliseconds
330 export const exponentialDelay
= (retryNumber
= 0, delayFactor
= 100): number => {
331 const delay
= Math.pow(2, retryNumber
) * delayFactor
332 const randomSum
= delay
* 0.2 * secureRandom() // 0-20% of the delay
333 return delay
+ randomSum
337 * Generates a cryptographically secure random number in the [0,1[ range
339 * @returns A number in the [0,1[ range
341 export const secureRandom
= (): number => {
342 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
345 export const JSONStringifyWithMapSupport
= (
346 object
: Record
<string, unknown
> | Array<Record
<string, unknown
>> | Map
<unknown
, unknown
>,
349 return JSON
.stringify(
351 (_
, value
: Record
<string, unknown
>) => {
352 if (value
instanceof Map
) {
365 * Converts websocket error code to human readable string message
367 * @param code - websocket error code
368 * @returns human readable string message
370 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
371 if (code
>= 0 && code
<= 999) {
373 } else if (code
>= 1016) {
375 return '(For WebSocket standard)'
376 } else if (code
<= 2999) {
377 return '(For WebSocket extensions)'
378 } else if (code
<= 3999) {
379 return '(For libraries and frameworks)'
380 } else if (code
<= 4999) {
381 return '(For applications)'
385 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
386 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
] != null
388 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
]
393 export const isArraySorted
= <T
>(array
: T
[], compareFn
: (a
: T
, b
: T
) => number): boolean => {
394 for (let index
= 0; index
< array
.length
- 1; ++index
) {
395 if (compareFn(array
[index
], array
[index
+ 1]) > 0) {
402 // eslint-disable-next-line @typescript-eslint/no-explicit-any
403 export const once
= <T
, A
extends any[], R
>(
404 fn
: (...args
: A
) => R
,
406 ): ((...args
: A
) => R
) => {
408 return (...args
: A
) => {
409 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
411 result
= fn
.apply
<T
, A
, R
>(context
, args
)
412 ;(fn
as unknown
as undefined) = (context
as unknown
as undefined) = undefined
418 export const min
= (...args
: number[]): number =>
419 args
.reduce((minimum
, num
) => (minimum
< num
? minimum
: num
), Infinity)
421 export const max
= (...args
: number[]): number =>
422 args
.reduce((maximum
, num
) => (maximum
> num
? maximum
: num
), -Infinity)
424 export const throwErrorInNextTick
= (error
: Error): void => {