Commit | Line | Data |
---|---|---|
fcda9151 | 1 | import { getRandomValues, randomBytes, randomUUID } from 'node:crypto' |
66a7748d | 2 | import { env, nextTick } from 'node:process' |
8114d10e | 3 | |
f0c6601c JB |
4 | import { |
5 | formatDuration, | |
be4c6702 JB |
6 | hoursToMinutes, |
7 | hoursToSeconds, | |
b5c19509 | 8 | isDate, |
f0c6601c JB |
9 | millisecondsToHours, |
10 | millisecondsToMinutes, | |
11 | millisecondsToSeconds, | |
be4c6702 | 12 | minutesToSeconds, |
66a7748d JB |
13 | secondsToMilliseconds |
14 | } from 'date-fns' | |
088ee3c1 | 15 | |
4ccf551d | 16 | import { |
276e05ae JB |
17 | type JsonType, |
18 | MapStringifyFormat, | |
4ccf551d JB |
19 | type TimestampedData, |
20 | WebSocketCloseEventStatusString | |
21 | } from '../types/index.js' | |
5e3cb728 | 22 | |
9bf0ef23 | 23 | export const logPrefix = (prefixString = ''): string => { |
66a7748d JB |
24 | return `${new Date().toLocaleString()}${prefixString}` |
25 | } | |
d5bd1c00 | 26 | |
2c5c7443 | 27 | export const generateUUID = (): `${string}-${string}-${string}-${string}-${string}` => { |
66a7748d JB |
28 | return randomUUID() |
29 | } | |
147d0e0f | 30 | |
2c5c7443 JB |
31 | export const validateUUID = ( |
32 | uuid: `${string}-${string}-${string}-${string}-${string}` | |
33 | ): uuid is `${string}-${string}-${string}-${string}-${string}` => { | |
66a7748d JB |
34 | 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 | } | |
03eacbe5 | 36 | |
9bf0ef23 | 37 | export const sleep = async (milliSeconds: number): Promise<NodeJS.Timeout> => { |
a974c8e4 | 38 | return await new Promise<NodeJS.Timeout>(resolve => |
66a7748d JB |
39 | setTimeout(resolve as () => void, milliSeconds) |
40 | ) | |
41 | } | |
7dde0b73 | 42 | |
9bf0ef23 | 43 | export const formatDurationMilliSeconds = (duration: number): string => { |
66a7748d | 44 | duration = convertToInt(duration) |
17b07e47 | 45 | if (duration < 0) { |
66a7748d | 46 | throw new RangeError('Duration cannot be negative') |
17b07e47 | 47 | } |
66a7748d JB |
48 | const days = Math.floor(duration / (24 * 3600 * 1000)) |
49 | const hours = Math.floor(millisecondsToHours(duration) - days * 24) | |
be4c6702 | 50 | const minutes = Math.floor( |
66a7748d JB |
51 | millisecondsToMinutes(duration) - days * 24 * 60 - hoursToMinutes(hours) |
52 | ) | |
f0c6601c | 53 | const seconds = Math.floor( |
be4c6702 JB |
54 | millisecondsToSeconds(duration) - |
55 | days * 24 * 3600 - | |
56 | hoursToSeconds(hours) - | |
66a7748d JB |
57 | minutesToSeconds(minutes) |
58 | ) | |
d7ceb0f0 | 59 | if (days === 0 && hours === 0 && minutes === 0 && seconds === 0) { |
66a7748d | 60 | return formatDuration({ seconds }, { zero: true }) |
d7ceb0f0 JB |
61 | } |
62 | return formatDuration({ | |
63 | days, | |
64 | hours, | |
65 | minutes, | |
66a7748d JB |
66 | seconds |
67 | }) | |
68 | } | |
7dde0b73 | 69 | |
9bf0ef23 | 70 | export const formatDurationSeconds = (duration: number): string => { |
66a7748d JB |
71 | return formatDurationMilliSeconds(secondsToMilliseconds(duration)) |
72 | } | |
7dde0b73 | 73 | |
0bd926c1 | 74 | // More efficient time validation function than the one provided by date-fns |
5dc7c990 | 75 | export const isValidDate = (date: Date | number | undefined): date is Date | number => { |
b5c19509 | 76 | if (typeof date === 'number') { |
66a7748d | 77 | return !isNaN(date) |
b5c19509 | 78 | } else if (isDate(date)) { |
66a7748d | 79 | return !isNaN(date.getTime()) |
b5c19509 | 80 | } |
66a7748d JB |
81 | return false |
82 | } | |
b5c19509 | 83 | |
a78c196b | 84 | export const convertToDate = ( |
5dc7c990 | 85 | value: Date | string | number | undefined | null |
79fd697f | 86 | ): Date | undefined => { |
66a7748d | 87 | if (value == null) { |
79fd697f | 88 | return undefined |
7dde0b73 | 89 | } |
0bd926c1 | 90 | if (isDate(value)) { |
66a7748d | 91 | return value |
a6e68f34 | 92 | } |
87bcd3b4 | 93 | if (typeof value === 'string' || typeof value === 'number') { |
66a7748d | 94 | const valueToDate = new Date(value) |
85cce27f | 95 | if (isNaN(valueToDate.getTime())) { |
66a7748d | 96 | throw new Error(`Cannot convert to date: '${value}'`) |
43ff25b8 | 97 | } |
66a7748d | 98 | return valueToDate |
560bcf5b | 99 | } |
66a7748d | 100 | } |
560bcf5b | 101 | |
9bf0ef23 | 102 | export const convertToInt = (value: unknown): number => { |
66a7748d JB |
103 | if (value == null) { |
104 | return 0 | |
560bcf5b | 105 | } |
9bf0ef23 | 106 | if (Number.isSafeInteger(value)) { |
66a7748d | 107 | return value as number |
6d3a11a0 | 108 | } |
9bf0ef23 | 109 | if (typeof value === 'number') { |
66a7748d | 110 | return Math.trunc(value) |
7dde0b73 | 111 | } |
f5ee1403 | 112 | let changedValue: number = value as number |
87bcd3b4 | 113 | if (typeof value === 'string') { |
5dc7c990 | 114 | changedValue = parseInt(value) |
9ccca265 | 115 | } |
9bf0ef23 | 116 | if (isNaN(changedValue)) { |
66a7748d | 117 | throw new Error(`Cannot convert to integer: '${String(value)}'`) |
dada83ec | 118 | } |
66a7748d JB |
119 | return changedValue |
120 | } | |
dada83ec | 121 | |
9bf0ef23 | 122 | export const convertToFloat = (value: unknown): number => { |
66a7748d JB |
123 | if (value == null) { |
124 | return 0 | |
dada83ec | 125 | } |
66a7748d | 126 | let changedValue: number = value as number |
87bcd3b4 | 127 | if (typeof value === 'string') { |
5dc7c990 | 128 | changedValue = parseFloat(value) |
560bcf5b | 129 | } |
9bf0ef23 | 130 | if (isNaN(changedValue)) { |
66a7748d | 131 | throw new Error(`Cannot convert to float: '${String(value)}'`) |
5a2a53cf | 132 | } |
66a7748d JB |
133 | return changedValue |
134 | } | |
5a2a53cf | 135 | |
9bf0ef23 | 136 | export const convertToBoolean = (value: unknown): boolean => { |
66a7748d | 137 | let result = false |
a78c196b | 138 | if (value != null) { |
9bf0ef23 JB |
139 | // Check the type |
140 | if (typeof value === 'boolean') { | |
66a7748d | 141 | return value |
87bcd3b4 | 142 | } else if (typeof value === 'string' && (value.toLowerCase() === 'true' || value === '1')) { |
66a7748d | 143 | result = true |
9bf0ef23 | 144 | } else if (typeof value === 'number' && value === 1) { |
66a7748d | 145 | result = true |
e7aeea18 | 146 | } |
c37528f1 | 147 | } |
66a7748d JB |
148 | return result |
149 | } | |
9bf0ef23 JB |
150 | |
151 | export const getRandomFloat = (max = Number.MAX_VALUE, min = 0): number => { | |
152 | if (max < min) { | |
66a7748d | 153 | throw new RangeError('Invalid interval') |
9bf0ef23 JB |
154 | } |
155 | if (max - min === Infinity) { | |
66a7748d | 156 | throw new RangeError('Invalid interval') |
9bf0ef23 | 157 | } |
66a7748d JB |
158 | return (randomBytes(4).readUInt32LE() / 0xffffffff) * (max - min) + min |
159 | } | |
9bf0ef23 | 160 | |
9bf0ef23 JB |
161 | /** |
162 | * Rounds the given number to the given scale. | |
163 | * The rounding is done using the "round half away from zero" method. | |
164 | * | |
165 | * @param numberValue - The number to round. | |
166 | * @param scale - The scale to round to. | |
167 | * @returns The rounded number. | |
168 | */ | |
169 | export const roundTo = (numberValue: number, scale: number): number => { | |
66a7748d JB |
170 | const roundPower = Math.pow(10, scale) |
171 | return Math.round(numberValue * roundPower * (1 + Number.EPSILON)) / roundPower | |
172 | } | |
9bf0ef23 JB |
173 | |
174 | export const getRandomFloatRounded = (max = Number.MAX_VALUE, min = 0, scale = 2): number => { | |
5199f9fd | 175 | if (min !== 0) { |
66a7748d | 176 | return roundTo(getRandomFloat(max, min), scale) |
9bf0ef23 | 177 | } |
66a7748d JB |
178 | return roundTo(getRandomFloat(max), scale) |
179 | } | |
9bf0ef23 JB |
180 | |
181 | export const getRandomFloatFluctuatedRounded = ( | |
182 | staticValue: number, | |
183 | fluctuationPercent: number, | |
66a7748d | 184 | scale = 2 |
9bf0ef23 JB |
185 | ): number => { |
186 | if (fluctuationPercent < 0 || fluctuationPercent > 100) { | |
187 | throw new RangeError( | |
66a7748d JB |
188 | `Fluctuation percent must be between 0 and 100. Actual value: ${fluctuationPercent}` |
189 | ) | |
fe791818 | 190 | } |
9bf0ef23 | 191 | if (fluctuationPercent === 0) { |
66a7748d | 192 | return roundTo(staticValue, scale) |
9bf0ef23 | 193 | } |
66a7748d | 194 | const fluctuationRatio = fluctuationPercent / 100 |
9bf0ef23 JB |
195 | return getRandomFloatRounded( |
196 | staticValue * (1 + fluctuationRatio), | |
197 | staticValue * (1 - fluctuationRatio), | |
66a7748d JB |
198 | scale |
199 | ) | |
200 | } | |
9bf0ef23 | 201 | |
66a7748d | 202 | export const extractTimeSeriesValues = (timeSeries: TimestampedData[]): number[] => { |
a974c8e4 | 203 | return timeSeries.map(timeSeriesItem => timeSeriesItem.value) |
66a7748d | 204 | } |
da55bd34 | 205 | |
40615072 | 206 | export const clone = <T>(object: T): T => { |
3fad0dec | 207 | return structuredClone<T>(object) |
66a7748d | 208 | } |
9bf0ef23 | 209 | |
be0a4d4d JB |
210 | /** |
211 | * Detects whether the given value is an asynchronous function or not. | |
212 | * | |
213 | * @param fn - Unknown value. | |
214 | * @returns `true` if `fn` was an asynchronous function, otherwise `false`. | |
215 | * @internal | |
216 | */ | |
217 | export const isAsyncFunction = (fn: unknown): fn is (...args: unknown[]) => Promise<unknown> => { | |
218 | return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction' | |
219 | } | |
220 | ||
bfcd3a87 JB |
221 | export const isObject = (value: unknown): value is object => { |
222 | return value != null && typeof value === 'object' && !Array.isArray(value) | |
223 | } | |
224 | ||
bfcd3a87 JB |
225 | export const hasOwnProp = (value: unknown, property: PropertyKey): boolean => { |
226 | return isObject(value) && Object.hasOwn(value, property) | |
66a7748d | 227 | } |
9bf0ef23 JB |
228 | |
229 | export const isCFEnvironment = (): boolean => { | |
aa63c9b7 | 230 | return env.VCAP_APPLICATION != null |
66a7748d | 231 | } |
9bf0ef23 | 232 | |
5dc7c990 | 233 | export const isNotEmptyString = (value: unknown): value is string => { |
87bcd3b4 | 234 | return typeof value === 'string' && value.trim().length > 0 |
66a7748d | 235 | } |
9bf0ef23 | 236 | |
bfcd3a87 JB |
237 | export const isNotEmptyArray = (value: unknown): value is unknown[] => { |
238 | return Array.isArray(value) && value.length > 0 | |
66a7748d | 239 | } |
9bf0ef23 JB |
240 | |
241 | export const insertAt = (str: string, subStr: string, pos: number): string => | |
66a7748d | 242 | `${str.slice(0, pos)}${subStr}${str.slice(pos)}` |
9bf0ef23 JB |
243 | |
244 | /** | |
245 | * Computes the retry delay in milliseconds using an exponential backoff algorithm. | |
246 | * | |
247 | * @param retryNumber - the number of retries that have already been attempted | |
45abd3c6 | 248 | * @param delayFactor - the base delay factor in milliseconds |
9bf0ef23 JB |
249 | * @returns delay in milliseconds |
250 | */ | |
45abd3c6 | 251 | export const exponentialDelay = (retryNumber = 0, delayFactor = 100): number => { |
66a7748d JB |
252 | const delay = Math.pow(2, retryNumber) * delayFactor |
253 | const randomSum = delay * 0.2 * secureRandom() // 0-20% of the delay | |
254 | return delay + randomSum | |
255 | } | |
9bf0ef23 | 256 | |
9bf0ef23 JB |
257 | /** |
258 | * Generates a cryptographically secure random number in the [0,1[ range | |
259 | * | |
ab93b184 | 260 | * @returns A number in the [0,1[ range |
9bf0ef23 JB |
261 | */ |
262 | export const secureRandom = (): number => { | |
66a7748d JB |
263 | return getRandomValues(new Uint32Array(1))[0] / 0x100000000 |
264 | } | |
9bf0ef23 | 265 | |
276e05ae | 266 | export const JSONStringify = < |
28f384aa JB |
267 | T extends |
268 | | JsonType | |
269 | | Array<Record<string, unknown>> | |
270 | | Set<Record<string, unknown>> | |
271 | | Map<string, Record<string, unknown>> | |
276e05ae JB |
272 | >( |
273 | object: T, | |
274 | space?: string | number, | |
275 | mapFormat?: MapStringifyFormat | |
276 | ): string => { | |
9bf0ef23 | 277 | return JSON.stringify( |
bfcd3a87 | 278 | object, |
58ddf341 | 279 | (_, value: Record<string, unknown>) => { |
9bf0ef23 | 280 | if (value instanceof Map) { |
276e05ae JB |
281 | switch (mapFormat) { |
282 | case MapStringifyFormat.object: | |
61877a2e | 283 | return { ...Object.fromEntries<Map<string, Record<string, unknown>>>(value.entries()) } |
276e05ae JB |
284 | case MapStringifyFormat.array: |
285 | default: | |
286 | return [...value] | |
66a7748d | 287 | } |
276e05ae | 288 | } else if (value instanceof Set) { |
61877a2e | 289 | return [...value] as JsonType[] |
9bf0ef23 | 290 | } |
66a7748d | 291 | return value |
9bf0ef23 | 292 | }, |
66a7748d JB |
293 | space |
294 | ) | |
295 | } | |
9bf0ef23 JB |
296 | |
297 | /** | |
298 | * Converts websocket error code to human readable string message | |
299 | * | |
300 | * @param code - websocket error code | |
301 | * @returns human readable string message | |
302 | */ | |
303 | export const getWebSocketCloseEventStatusString = (code: number): string => { | |
304 | if (code >= 0 && code <= 999) { | |
66a7748d | 305 | return '(Unused)' |
9bf0ef23 JB |
306 | } else if (code >= 1016) { |
307 | if (code <= 1999) { | |
66a7748d | 308 | return '(For WebSocket standard)' |
9bf0ef23 | 309 | } else if (code <= 2999) { |
66a7748d | 310 | return '(For WebSocket extensions)' |
9bf0ef23 | 311 | } else if (code <= 3999) { |
66a7748d | 312 | return '(For libraries and frameworks)' |
9bf0ef23 | 313 | } else if (code <= 4999) { |
66a7748d | 314 | return '(For applications)' |
5e3cb728 | 315 | } |
5e3cb728 | 316 | } |
a37fc6dc | 317 | if ( |
5199f9fd JB |
318 | // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition |
319 | WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] != null | |
a37fc6dc | 320 | ) { |
66a7748d | 321 | return WebSocketCloseEventStatusString[code as keyof typeof WebSocketCloseEventStatusString] |
9bf0ef23 | 322 | } |
66a7748d JB |
323 | return '(Unknown)' |
324 | } | |
80c58041 | 325 | |
991fb26b JB |
326 | export const isArraySorted = <T>(array: T[], compareFn: (a: T, b: T) => number): boolean => { |
327 | for (let index = 0; index < array.length - 1; ++index) { | |
328 | if (compareFn(array[index], array[index + 1]) > 0) { | |
66a7748d | 329 | return false |
80c58041 JB |
330 | } |
331 | } | |
66a7748d JB |
332 | return true |
333 | } | |
5f742aac | 334 | |
29dff95e JB |
335 | export const throwErrorInNextTick = (error: Error): void => { |
336 | nextTick(() => { | |
66a7748d JB |
337 | throw error |
338 | }) | |
339 | } |