1 import { getRandomValues
, randomBytes
, randomUUID
} from
'node:crypto'
2 import { env
, nextTick
} from
'node:process'
10 millisecondsToMinutes
,
11 millisecondsToSeconds
,
15 import { is } from
'rambda'
21 WebSocketCloseEventStatusString
22 } from
'../types/index.js'
24 export const logPrefix
= (prefixString
= ''): string => {
25 return `${new Date().toLocaleString()}${prefixString}`
28 export const generateUUID
= (): `${string}-${string}-${string}-${string}-${string}` => {
32 export const validateUUID
= (
33 uuid
: `${string}-${string}-${string}-${string}-${string}`
34 ): uuid
is `${string}-${string}-${string}-${string}-${string}` => {
35 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
)
38 export const sleep
= async (milliSeconds
: number): Promise
<NodeJS
.Timeout
> => {
39 return await new Promise
<NodeJS
.Timeout
>(resolve
=>
40 setTimeout(resolve
as () => void, milliSeconds
)
44 export const formatDurationMilliSeconds
= (duration
: number): string => {
45 duration
= convertToInt(duration
)
47 throw new RangeError('Duration cannot be negative')
49 const days
= Math.floor(duration
/ (24 * 3600 * 1000))
50 const hours
= Math.floor(millisecondsToHours(duration
) - days
* 24)
51 const minutes
= Math.floor(
52 millisecondsToMinutes(duration
) - days
* 24 * 60 - hoursToMinutes(hours
)
54 const seconds
= Math.floor(
55 millisecondsToSeconds(duration
) -
57 hoursToSeconds(hours
) -
58 minutesToSeconds(minutes
)
60 if (days
=== 0 && hours
=== 0 && minutes
=== 0 && seconds
=== 0) {
61 return formatDuration({ seconds
}, { zero
: true })
63 return formatDuration({
71 export const formatDurationSeconds
= (duration
: number): string => {
72 return formatDurationMilliSeconds(secondsToMilliseconds(duration
))
75 // More efficient time validation function than the one provided by date-fns
76 export const isValidDate
= (date
: Date | number | undefined): date
is Date | number => {
77 if (typeof date
=== 'number') {
79 } else if (isDate(date
)) {
80 return !isNaN(date
.getTime())
85 export const convertToDate
= (
86 value
: Date | string | number | undefined | null
87 ): Date | undefined => {
94 if (typeof value
=== 'string' || typeof value
=== 'number') {
95 const valueToDate
= new Date(value
)
96 if (isNaN(valueToDate
.getTime())) {
97 throw new Error(`Cannot convert to date: '${value}'`)
103 export const convertToInt
= (value
: unknown
): number => {
107 if (Number.isSafeInteger(value
)) {
108 return value
as number
110 if (typeof value
=== 'number') {
111 return Math.trunc(value
)
113 let changedValue
: number = value
as number
114 if (typeof value
=== 'string') {
115 changedValue
= parseInt(value
)
117 if (isNaN(changedValue
)) {
118 throw new Error(`Cannot convert to integer: '${String(value)}'`)
123 export const convertToFloat
= (value
: unknown
): number => {
127 let changedValue
: number = value
as number
128 if (typeof value
=== 'string') {
129 changedValue
= parseFloat(value
)
131 if (isNaN(changedValue
)) {
132 throw new Error(`Cannot convert to float: '${String(value)}'`)
137 export const convertToBoolean
= (value
: unknown
): boolean => {
141 if (typeof value
=== 'boolean') {
143 } else if (typeof value
=== 'string' && (value
.toLowerCase() === 'true' || value
=== '1')) {
145 } else if (typeof value
=== 'number' && value
=== 1) {
152 export const getRandomFloat
= (max
= Number.MAX_VALUE
, min
= 0): number => {
154 throw new RangeError('Invalid interval')
156 if (max
- min
=== Infinity) {
157 throw new RangeError('Invalid interval')
159 return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max
- min
) + min
163 * Rounds the given number to the given scale.
164 * The rounding is done using the "round half away from zero" method.
166 * @param numberValue - The number to round.
167 * @param scale - The scale to round to.
168 * @returns The rounded number.
170 export const roundTo
= (numberValue
: number, scale
: number): number => {
171 const roundPower
= Math.pow(10, scale
)
172 return Math.round(numberValue
* roundPower
* (1 + Number.EPSILON
)) / roundPower
175 export const getRandomFloatRounded
= (max
= Number.MAX_VALUE
, min
= 0, scale
= 2): number => {
177 return roundTo(getRandomFloat(max
, min
), scale
)
179 return roundTo(getRandomFloat(max
), scale
)
182 export const getRandomFloatFluctuatedRounded
= (
184 fluctuationPercent
: number,
187 if (fluctuationPercent
< 0 || fluctuationPercent
> 100) {
188 throw new RangeError(
189 `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}`
192 if (fluctuationPercent
=== 0) {
193 return roundTo(staticValue
, scale
)
195 const fluctuationRatio
= fluctuationPercent
/ 100
196 return getRandomFloatRounded(
197 staticValue
* (1 + fluctuationRatio
),
198 staticValue
* (1 - fluctuationRatio
),
203 export const extractTimeSeriesValues
= (timeSeries
: TimestampedData
[]): number[] => {
204 return timeSeries
.map(timeSeriesItem
=> timeSeriesItem
.value
)
207 export const clone
= <T
>(object
: T
): T
=> {
208 return structuredClone
<T
>(object
)
212 * Detects whether the given value is an asynchronous function or not.
214 * @param fn - Unknown value.
215 * @returns `true` if `fn` was an asynchronous function, otherwise `false`.
218 export const isAsyncFunction
= (fn
: unknown
): fn
is (...args
: unknown
[]) => Promise
<unknown
> => {
219 return is(Function, fn
) && fn
.constructor
.name
=== 'AsyncFunction'
222 export const isObject
= (value
: unknown
): value
is object
=> {
223 return value
!= null && !Array.isArray(value
) && is(Object, value
)
226 export const hasOwnProp
= (value
: unknown
, property
: PropertyKey
): boolean => {
227 return isObject(value
) && Object.hasOwn(value
, property
)
230 export const isCFEnvironment
= (): boolean => {
231 return env
.VCAP_APPLICATION
!= null
234 export const isNotEmptyString
= (value
: unknown
): value
is string => {
235 return typeof value
=== 'string' && value
.trim().length
> 0
238 export const isNotEmptyArray
= (value
: unknown
): value
is unknown
[] => {
239 return Array.isArray(value
) && value
.length
> 0
242 export const insertAt
= (str
: string, subStr
: string, pos
: number): string =>
243 `${str.slice(0, pos)}${subStr}${str.slice(pos)}`
246 * Computes the retry delay in milliseconds using an exponential backoff algorithm.
248 * @param retryNumber - the number of retries that have already been attempted
249 * @param delayFactor - the base delay factor in milliseconds
250 * @returns delay in milliseconds
252 export const exponentialDelay
= (retryNumber
= 0, delayFactor
= 100): number => {
253 const delay
= Math.pow(2, retryNumber
) * delayFactor
254 const randomSum
= delay
* 0.2 * secureRandom() // 0-20% of the delay
255 return delay
+ randomSum
259 * Generates a cryptographically secure random number in the [0,1[ range
261 * @returns A number in the [0,1[ range
263 export const secureRandom
= (): number => {
264 return getRandomValues(new Uint32Array(1))[0] / 0x100000000
267 export const JSONStringify
= <
270 | Array<Record
<string, unknown
>>
271 | Set
<Record
<string, unknown
>>
272 | Map
<string, Record
<string, unknown
>>
275 space
?: string | number,
276 mapFormat
?: MapStringifyFormat
278 return JSON
.stringify(
280 (_
, value
: Record
<string, unknown
>) => {
281 if (is(Map
, value
)) {
283 case MapStringifyFormat
.object
:
284 return { ...Object.fromEntries
<Map
<string, Record
<string, unknown
>>>(value
.entries()) }
285 case MapStringifyFormat
.array
:
289 } else if (is(Set
, value
)) {
290 return [...value
] as JsonType
[]
299 * Converts websocket error code to human readable string message
301 * @param code - websocket error code
302 * @returns human readable string message
304 export const getWebSocketCloseEventStatusString
= (code
: number): string => {
305 if (code
>= 0 && code
<= 999) {
307 } else if (code
>= 1016) {
309 return '(For WebSocket standard)'
310 } else if (code
<= 2999) {
311 return '(For WebSocket extensions)'
312 } else if (code
<= 3999) {
313 return '(For libraries and frameworks)'
314 } else if (code
<= 4999) {
315 return '(For applications)'
319 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
320 WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
] != null
322 return WebSocketCloseEventStatusString
[code
as keyof
typeof WebSocketCloseEventStatusString
]
327 export const isArraySorted
= <T
>(array
: T
[], compareFn
: (a
: T
, b
: T
) => number): boolean => {
328 for (let index
= 0; index
< array
.length
- 1; ++index
) {
329 if (compareFn(array
[index
], array
[index
+ 1]) > 0) {
336 export const throwErrorInNextTick
= (error
: Error): void => {