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