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'
19 type ProtocolResponse
,
21 WebSocketCloseEventStatusString
22 } from
'../types/index.js'
24 export const logPrefix
= (prefixString
= ''): string => {
25 return `${new Date().toLocaleString()}${prefixString}`
28 export const generateUUID
= (): string => {
32 export const validateUUID
= (uuid
: string): boolean => {
33 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
)
36 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
37 return await new Promise
<NodeJS
.Timeout
>(resolve
=>
38 setTimeout(resolve
as () => void, milliSeconds
)
42 export const formatDurationMilliSeconds
= (duration
: number): string => {
43 duration
= convertToInt(duration
)
45 throw new RangeError('Duration cannot be negative')
47 const days
= Math.floor(duration
/ (24 * 3600 * 1000))
48 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24)
49 const minutes
= Math.floor(
50 millisecondsToMinutes(duration
) - days
* 24 * 60 - hoursToMinutes(hours
)
52 const seconds
= Math.floor(
53 millisecondsToSeconds(duration
) -
55 hoursToSeconds(hours
) -
56 minutesToSeconds(minutes
)
58 if (days
=== 0 && hours
=== 0 && minutes
=== 0 && seconds
=== 0) {
59 return formatDuration({ seconds
}, { zero
: true })
61 return formatDuration({
69 export const formatDurationSeconds
= (duration
: number): string => {
70 return formatDurationMilliSeconds(secondsToMilliseconds(duration
))
73 // More efficient time validation function than the one provided by date-fns
74 export const isValidDate
= (date
: Date | number | undefined): date
is Date | number => {
75 if (typeof date
=== 'number') {
77 } else if (isDate(date
)) {
78 return !isNaN(date
.getTime())
83 export const convertToDate
= (
84 value
: Date | string | number | undefined | null
85 ): Date | undefined => {
92 if (isString(value
) || typeof value
=== 'number') {
93 const valueToDate
= new Date(value
)
94 if (isNaN(valueToDate
.getTime())) {
95 throw new Error(`Cannot convert to date: '${value}'`)
101 export const convertToInt
= (value
: unknown
): number => {
105 let changedValue
: number = value
as number
106 if (Number.isSafeInteger(value
)) {
107 return value
as number
109 if (typeof value
=== 'number') {
110 return Math.trunc(value
)
112 if (isString(value
)) {
113 changedValue
= parseInt(value
)
115 if (isNaN(changedValue
)) {
116 throw new Error(`Cannot convert to integer: '${String(value)}'`)
121 export const convertToFloat
= (value
: unknown
): number => {
125 let changedValue
: number = value
as number
126 if (isString(value
)) {
127 changedValue
= parseFloat(value
)
129 if (isNaN(changedValue
)) {
130 throw new Error(`Cannot convert to float: '${String(value)}'`)
135 export const convertToBoolean
= (value
: unknown
): boolean => {
139 if (typeof value
=== 'boolean') {
141 } else if (isString(value
) && (value
.toLowerCase() === 'true' || value
=== '1')) {
143 } else if (typeof value
=== 'number' && value
=== 1) {
150 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
152 throw new RangeError('Invalid interval')
154 if (max
- min
=== Infinity) {
155 throw new RangeError('Invalid interval')
157 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
160 export const getRandomInteger
= (max
= Constants
.MAX_RANDOM_INTEGER
, min
= 0): number => {
161 max
= Math.floor(max
)
164 return Math.floor(randomInt(min
, max
+ 1))
166 return Math.floor(randomInt(max
+ 1))
170 * Rounds the given number to the given scale.
171 * The rounding is done using the "round half away from zero" method.
173 * @param numberValue - The number to round.
174 * @param scale - The scale to round to.
175 * @returns The rounded number.
177 export const roundTo
= (numberValue
: number, scale
: number): number => {
178 const roundPower
= Math.pow(10, scale
)
179 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
182 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
184 return roundTo(getRandomFloat(max
, min
), scale
)
186 return roundTo(getRandomFloat(max
), scale
)
189 export const getRandomFloatFluctuatedRounded
= (
191 fluctuationPercent
: number,
194 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
195 throw new RangeError(
196 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
199 if (fluctuationPercent
=== 0) {
200 return roundTo(staticValue
, scale
)
202 const fluctuationRatio
= fluctuationPercent
/ 100
203 return getRandomFloatRounded(
204 staticValue
* (1 + fluctuationRatio
),
205 staticValue
* (1 - fluctuationRatio
),
210 export const extractTimeSeriesValues
= (timeSeries
: TimestampedData
[]): number[] => {
211 return timeSeries
.map(timeSeriesItem
=> timeSeriesItem
.value
)
222 | { [key
: string]: CloneableData
}
224 type FormatKey
= (key
: string) => string
226 const deepClone
= <I
extends CloneableData
, O
extends CloneableData
= I
>(
228 formatKey
?: FormatKey
,
229 refs
: Map
<I
, O
> = new Map
<I
, O
>()
231 const ref
= refs
.get(value
)
232 if (ref
!== undefined) {
235 if (Array.isArray(value
)) {
236 const clone
: CloneableData
[] = []
237 refs
.set(value
, clone
as O
)
238 for (let i
= 0; i
< value
.length
; i
++) {
239 clone
[i
] = deepClone(value
[i
], formatKey
, refs
)
243 if (value
instanceof Date) {
244 return new Date(value
.getTime()) as O
246 if (typeof value
!== 'object' || value
=== null) {
247 return value
as unknown
as O
249 const clone
: Record
<string, CloneableData
> = {}
250 refs
.set(value
, clone
as O
)
251 for (const key
of Object.keys(value
)) {
252 clone
[typeof formatKey
=== 'function' ? formatKey(key
) : key
] = deepClone(
261 export const clone
= <T
>(object
: T
): T
=> {
262 return deepClone(object
as CloneableData
) as T
266 * Detects whether the given value is an asynchronous function or not.
268 * @param fn - Unknown value.
269 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
272 export const isAsyncFunction
= (fn
: unknown
): fn
is (...args
: unknown
[]) => Promise
<unknown
> => {
273 return typeof fn
=== 'function' && fn
.constructor
.name
=== 'AsyncFunction'
276 export const isObject
= (value
: unknown
): value
is object
=> {
277 return value
!= null && typeof value
=== 'object' && !Array.isArray(value
)
280 export const isEmptyObject
= (object
: object
): object
is EmptyObject
=> {
281 if (object
.constructor
!== Object) {
284 // Iterates over the keys of an object, if
285 // any exist, return false.
286 // eslint-disable-next-line no-unreachable-loop
287 for (const _
in object
) {
293 export const hasOwnProp
= (value
: unknown
, property
: PropertyKey
): boolean => {
294 return isObject(value
) && Object.hasOwn(value
, property
)
297 export const isCFEnvironment
= (): boolean => {
298 return env
.VCAP_APPLICATION
!= null
301 const isString
= (value
: unknown
): value
is string => {
302 return typeof value
=== 'string'
305 export const isEmptyString
= (value
: unknown
): value
is '' | undefined | null => {
306 return value
== null || (isString(value
) && value
.trim().length
=== 0)
309 export const isNotEmptyString
= (value
: unknown
): value
is string => {
310 return isString(value
) && value
.trim().length
> 0
313 export const isEmptyArray
= (value
: unknown
): value
is never[] => {
314 return Array.isArray(value
) && value
.length
=== 0
317 export const isNotEmptyArray
= (value
: unknown
): value
is unknown
[] => {
318 return Array.isArray(value
) && value
.length
> 0
321 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
322 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
325 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
327 * @param retryNumber - the number of retries that have already been attempted
328 * @param delayFactor - the base delay factor in milliseconds
329 * @returns delay in milliseconds
331 export const exponentialDelay
= (retryNumber
= 0, delayFactor
= 100): number => {
332 const delay
= Math.pow(2, retryNumber
) * delayFactor
333 const randomSum
= delay
* 0.2 * secureRandom() // 0-20% of the delay
334 return delay
+ randomSum
338 * Generates a cryptographically secure random number in the [0,1[ range
340 * @returns A number in the [0,1[ range
342 export const secureRandom
= (): number => {
343 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
346 export const JSONStringifyWithMapSupport
= (
348 | Record
<string, unknown
>
349 | Array<Record
<string, unknown
>>
350 | Map
<unknown
, unknown
>
352 space
?: string | number
354 return JSON
.stringify(
356 (_
, value
: Record
<string, unknown
>) => {
357 if (value
instanceof Map
) {
370 * Converts websocket error code to human readable string message
372 * @param code - websocket error code
373 * @returns human readable string message
375 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
376 if (code
>= 0 && code
<= 999) {
378 } else if (code
>= 1016) {
380 return '(For WebSocket standard)'
381 } else if (code
<= 2999) {
382 return '(For WebSocket extensions)'
383 } else if (code
<= 3999) {
384 return '(For libraries and frameworks)'
385 } else if (code
<= 4999) {
386 return '(For applications)'
390 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
391 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
] != null
393 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
]
398 export const isArraySorted
= <T
>(array
: T
[], compareFn
: (a
: T
, b
: T
) => number): boolean => {
399 for (let index
= 0; index
< array
.length
- 1; ++index
) {
400 if (compareFn(array
[index
], array
[index
+ 1]) > 0) {
407 // eslint-disable-next-line @typescript-eslint/no-explicit-any
408 export const once
= <T
, A
extends any[], R
>(
409 fn
: (...args
: A
) => R
,
411 ): ((...args
: A
) => R
) => {
413 return (...args
: A
) => {
414 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
416 result
= fn
.apply
<T
, A
, R
>(context
, args
)
417 ;(fn
as unknown
as undefined) = (context
as unknown
as undefined) = undefined
423 export const min
= (...args
: number[]): number =>
424 args
.reduce((minimum
, num
) => (minimum
< num
? minimum
: num
), Infinity)
426 export const max
= (...args
: number[]): number =>
427 args
.reduce((maximum
, num
) => (maximum
> num
? maximum
: num
), -Infinity)
429 export const throwErrorInNextTick
= (error
: Error): void => {