-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathUtils.js
More file actions
581 lines (533 loc) · 17.1 KB
/
Utils.js
File metadata and controls
581 lines (533 loc) · 17.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
/**
* utils.js
* @file General purpose utilities
* @description General purpose utilities.
*/
const path = require('path');
const fs = require('fs').promises;
const { types } = require('util');
/**
* The general purpose utilities.
*/
class Utils {
/**
* @function getLocalizedPath
* @description Returns a localized file path accoring to the locale.
*
* Localized files are searched in subfolders of a given path, e.g.
*
* root/
* ├── base/ // base path to files
* │ ├── example.html // default file
* │ └── de/ // de language folder
* │ │ └── example.html // de localized file
* │ └── de-AT/ // de-AT locale folder
* │ │ └── example.html // de-AT localized file
*
* Files are matched with the locale in the following order:
* 1. Locale match, e.g. locale `de-AT` matches file in folder `de-AT`.
* 2. Language match, e.g. locale `de-AT` matches file in folder `de`.
* 3. Default; file in base folder is returned.
*
* @param {String} defaultPath The absolute file path, which is also
* the default path returned if localization is not available.
* @param {String} locale The locale.
* @returns {Promise<Object>} The object contains:
* - `path`: The path to the localized file, or the original path if
* localization is not available.
* - `subdir`: The subdirectory of the localized file, or undefined if
* there is no matching localized file.
*/
static async getLocalizedPath(defaultPath, locale) {
// Get file name and paths
const file = path.basename(defaultPath);
const basePath = path.dirname(defaultPath);
// If locale is not set return default file
if (!locale) {
return { path: defaultPath };
}
// Check file for locale exists
const localePath = path.join(basePath, locale, file);
const localeFileExists = await Utils.fileExists(localePath);
// If file for locale exists return file
if (localeFileExists) {
return { path: localePath, subdir: locale };
}
// Check file for language exists
const language = locale.split('-')[0];
const languagePath = path.join(basePath, language, file);
const languageFileExists = await Utils.fileExists(languagePath);
// If file for language exists return file
if (languageFileExists) {
return { path: languagePath, subdir: language };
}
// Return default file
return { path: defaultPath };
}
/**
* @function fileExists
* @description Checks whether a file exists.
* @param {String} path The file path.
* @returns {Promise<Boolean>} Is true if the file can be accessed, false otherwise.
*/
static async fileExists(path) {
try {
await fs.access(path);
return true;
} catch {
return false;
}
}
/**
* @function isPath
* @description Evaluates whether a string is a file path (as opposed to a URL for example).
* @param {String} s The string to evaluate.
* @returns {Boolean} Returns true if the evaluated string is a path.
*/
static isPath(s) {
return /(^\/)|(^\.\/)|(^\.\.\/)/.test(s);
}
/**
* Flattens an object and crates new keys with custom delimiters.
* @param {Object} obj The object to flatten.
* @param {String} [delimiter='.'] The delimiter of the newly generated keys.
* @param {Object} result
* @returns {Object} The flattened object.
**/
static flattenObject(obj, parentKey, delimiter = '.', result = {}) {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
const newKey = parentKey ? parentKey + delimiter + key : key;
if (typeof obj[key] === 'object' && obj[key] !== null) {
this.flattenObject(obj[key], newKey, delimiter, result);
} else {
result[newKey] = obj[key];
}
}
}
return result;
}
/**
* Realm-safe check for Date.
* @param {any} value The value to check.
* @returns {Boolean} Returns true if the value is a Date.
*/
static isDate(value) {
return types.isDate(value);
}
/**
* Realm-safe check for RegExp.
* @param {any} value The value to check.
* @returns {Boolean} Returns true if the value is a RegExp.
*/
static isRegExp(value) {
return types.isRegExp(value);
}
/**
* Realm-safe check for Map.
* @param {any} value The value to check.
* @returns {Boolean} Returns true if the value is a Map.
*/
static isMap(value) {
return types.isMap(value);
}
/**
* Realm-safe check for Set.
* @param {any} value The value to check.
* @returns {Boolean} Returns true if the value is a Set.
*/
static isSet(value) {
return types.isSet(value);
}
/**
* Realm-safe check for native Error.
* @param {any} value The value to check.
* @returns {Boolean} Returns true if the value is a native Error.
*/
static isNativeError(value) {
return types.isNativeError(value);
}
/**
* Realm-safe check for Promise (duck-typed as thenable).
* Guards against Object.prototype pollution by ensuring `then` is not
* inherited solely from Object.prototype.
* @param {any} value The value to check.
* @returns {Boolean} Returns true if the value is a Promise or thenable.
*/
static isPromise(value) {
if (value == null || typeof value.then !== 'function') {
return false;
}
return Object.getPrototypeOf(value) !== Object.prototype || Object.prototype.hasOwnProperty.call(value, 'then');
}
/**
* Realm-safe check for object type. Uses `typeof` instead of `instanceof Object`
* which fails across realms. Returns true for any non-null value where
* `typeof` is `'object'`, including plain objects, arrays, dates, maps, sets,
* regex, and boxed primitives (e.g. `new String()`). Returns false for `null`,
* `undefined`, unboxed primitives, and functions.
* @param {any} value The value to check.
* @returns {Boolean} Returns true if the value is a non-null object type.
*/
static isObject(value) {
return typeof value === 'object' && value !== null;
}
/**
* Creates an object with all permutations of the original keys.
* For example, this definition:
* ```
* {
* a: [true, false],
* b: [1, 2],
* c: ['x']
* }
* ```
* permutates to:
* ```
* [
* { a: true, b: 1, c: 'x' },
* { a: true, b: 2, c: 'x' },
* { a: false, b: 1, c: 'x' },
* { a: false, b: 2, c: 'x' }
* ]
* ```
* @param {Object} object The object to permutate.
* @param {Integer} [index=0] The current key index.
* @param {Object} [current={}] The current result entry being composed.
* @param {Array} [results=[]] The resulting array of permutations.
*/
static getObjectKeyPermutations(object, index = 0, current = {}, results = []) {
const keys = Object.keys(object);
const key = keys[index];
const values = object[key];
for (const value of values) {
current[key] = value;
const nextIndex = index + 1;
if (nextIndex < keys.length) {
Utils.getObjectKeyPermutations(object, nextIndex, current, results);
} else {
const result = Object.assign({}, current);
results.push(result);
}
}
return results;
}
/**
* Validates parameters and throws if a parameter is invalid.
* Example parameter types syntax:
* ```
* {
* parameterName: {
* t: 'boolean',
* v: isBoolean,
* o: true
* },
* ...
* }
* ```
* @param {Object} params The parameters to validate.
* @param {Array<Object>} types The parameter types used for validation.
* @param {Object} types.t The parameter type; used for error message, not for validation.
* @param {Object} types.v The function to validate the parameter value.
* @param {Boolean} [types.o=false] Is true if the parameter is optional.
*/
static validateParams(params, types) {
for (const key of Object.keys(params)) {
const type = types[key];
const isOptional = !!type.o;
const param = params[key];
if (!(isOptional && param == null) && !type.v(param)) {
throw `Invalid parameter ${key} must be of type ${type.t} but is ${typeof param}`;
}
}
}
/**
* Computes the relative date based on a string.
* @param {String} text The string to interpret the date from.
* @param {Date} now The date the string is comparing against.
* @returns {Object} The relative date object.
**/
static relativeTimeToDate(text, now = new Date()) {
text = text.toLowerCase();
let parts = text.split(' ');
// Filter out whitespace
parts = parts.filter(part => part !== '');
const future = parts[0] === 'in';
const past = parts[parts.length - 1] === 'ago';
if (!future && !past && text !== 'now') {
return {
status: 'error',
info: "Time should either start with 'in' or end with 'ago'",
};
}
if (future && past) {
return {
status: 'error',
info: "Time cannot have both 'in' and 'ago'",
};
}
// strip the 'ago' or 'in'
if (future) {
parts = parts.slice(1);
} else {
// past
parts = parts.slice(0, parts.length - 1);
}
if (parts.length % 2 !== 0 && text !== 'now') {
return {
status: 'error',
info: 'Invalid time string. Dangling unit or number.',
};
}
const pairs = [];
while (parts.length) {
pairs.push([parts.shift(), parts.shift()]);
}
let seconds = 0;
for (const [num, interval] of pairs) {
const val = Number(num);
if (!Number.isInteger(val)) {
return {
status: 'error',
info: `'${num}' is not an integer.`,
};
}
switch (interval) {
case 'yr':
case 'yrs':
case 'year':
case 'years':
seconds += val * 31536000; // 365 * 24 * 60 * 60
break;
case 'wk':
case 'wks':
case 'week':
case 'weeks':
seconds += val * 604800; // 7 * 24 * 60 * 60
break;
case 'd':
case 'day':
case 'days':
seconds += val * 86400; // 24 * 60 * 60
break;
case 'hr':
case 'hrs':
case 'hour':
case 'hours':
seconds += val * 3600; // 60 * 60
break;
case 'min':
case 'mins':
case 'minute':
case 'minutes':
seconds += val * 60;
break;
case 'sec':
case 'secs':
case 'second':
case 'seconds':
seconds += val;
break;
default:
return {
status: 'error',
info: `Invalid interval: '${interval}'`,
};
}
}
const milliseconds = seconds * 1000;
if (future) {
return {
status: 'success',
info: 'future',
result: new Date(now.valueOf() + milliseconds),
};
} else if (past) {
return {
status: 'success',
info: 'past',
result: new Date(now.valueOf() - milliseconds),
};
} else {
return {
status: 'success',
info: 'present',
result: new Date(now.valueOf()),
};
}
}
/**
* Deep-scans an object for a matching key/value definition.
* @param {Object} obj The object to scan.
* @param {String | undefined} key The key to match, or undefined if only the value should be matched.
* @param {any | undefined} value The value to match, or undefined if only the key should be matched.
* @returns {Boolean} True if a match was found, false otherwise.
*/
static objectContainsKeyValue(obj, key, value) {
const isMatch = (a, b) => (typeof a === 'string' && new RegExp(b).test(a)) || a === b;
const isKeyMatch = k => isMatch(k, key);
const isValueMatch = v => isMatch(v, value);
const stack = [obj];
const seen = new WeakSet();
while (stack.length > 0) {
const current = stack.pop();
if (seen.has(current)) {
continue;
}
seen.add(current);
for (const [k, v] of Object.entries(current)) {
if (key !== undefined && value === undefined && isKeyMatch(k)) {
return true;
} else if (key === undefined && value !== undefined && isValueMatch(v)) {
return true;
} else if (key !== undefined && value !== undefined && isKeyMatch(k) && isValueMatch(v)) {
return true;
}
if (['[object Object]', '[object Array]'].includes(Object.prototype.toString.call(v))) {
stack.push(v);
}
}
}
return false;
}
static checkProhibitedKeywords(config, data) {
if (config?.requestKeywordDenylist) {
// Scan request data for denied keywords
for (const keyword of config.requestKeywordDenylist) {
const match = Utils.objectContainsKeyValue(data, keyword.key, keyword.value);
if (match) {
throw `Prohibited keyword in request data: ${JSON.stringify(keyword)}.`;
}
}
}
}
/**
* Moves the nested keys of a specified key in an object to the root of the object.
*
* @param {Object} obj The object to modify.
* @param {String} key The key whose nested keys will be moved to root.
* @returns {Object} The modified object, or the original object if no modification happened.
* @example
* const obj = {
* a: 1,
* b: {
* c: 2,
* d: 3
* },
* e: 4
* };
* addNestedKeysToRoot(obj, 'b');
* console.log(obj);
* // Output: { a: 1, e: 4, c: 2, d: 3 }
*/
static addNestedKeysToRoot(obj, key) {
if (obj[key] && typeof obj[key] === 'object') {
// Add nested keys to root
Object.assign(obj, { ...obj[key] });
// Delete original nested key
delete obj[key];
}
return obj;
}
/**
* Encodes a string to be used in a URL.
* @param {String} input The string to encode.
* @returns {String} The encoded string.
*/
static encodeForUrl(input) {
return encodeURIComponent(input).replace(/[!'.()*]/g, char =>
'%' + char.charCodeAt(0).toString(16).toUpperCase()
);
}
/**
* Creates a JSON replacer function that handles Map, Set, and circular references.
* This replacer can be used with JSON.stringify to safely serialize complex objects.
*
* @returns {Function} A replacer function for JSON.stringify that:
* - Converts Map instances to plain objects
* - Converts Set instances to arrays
* - Replaces circular references with '[Circular]' marker
*
* @example
* const obj = { name: 'test', map: new Map([['key', 'value']]) };
* obj.self = obj; // circular reference
* JSON.stringify(obj, Utils.getCircularReplacer());
* // Output: {"name":"test","map":{"key":"value"},"self":"[Circular]"}
*/
static getCircularReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (Utils.isMap(value)) {
return Object.fromEntries(value);
}
if (Utils.isSet(value)) {
return Array.from(value);
}
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return '[Circular]';
}
seen.add(value);
}
return value;
};
}
/**
* Gets a nested property value from an object using dot notation.
* @param {Object} obj The object to get the property from.
* @param {String} path The property path in dot notation, e.g. 'databaseOptions.allowPublicExplain'.
* @returns {any} The property value or undefined if not found.
* @example
* const obj = { database: { options: { enabled: true } } };
* Utils.getNestedProperty(obj, 'database.options.enabled');
* // Output: true
*/
static getNestedProperty(obj, path) {
if (!obj || !path) {
return undefined;
}
const keys = path.split('.');
let current = obj;
for (const key of keys) {
if (current == null || typeof current !== 'object') {
return undefined;
}
current = current[key];
}
return current;
}
/**
* Parses a human-readable size string into a byte count.
* @param {number | string} size - A number (floored to an integer), a numeric string
* (treated as bytes), or a string with a unit suffix: `b`, `kb`, `mb`, `gb`
* (case-insensitive). Examples: `'20mb'`, `'512kb'`, `'1.5gb'`, `1048576`.
* @returns {number} The size in bytes, floored to the nearest integer.
* @throws {Error} If the string does not match the expected format.
*/
static parseSizeToBytes(size) {
if (typeof size === 'number') {
if (!Number.isFinite(size) || size < 0) {
throw new Error(`Invalid size value: ${size}`);
}
return Math.floor(size);
}
const str = String(size).trim().toLowerCase();
const match = str.match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/);
if (!match) {
throw new Error(`Invalid size value: ${size}`);
}
const num = parseFloat(match[1]);
const unit = match[2];
switch (unit) {
case 'kb':
return Math.floor(num * 1024);
case 'mb':
return Math.floor(num * 1024 * 1024);
case 'gb':
return Math.floor(num * 1024 * 1024 * 1024);
default:
return Math.floor(num);
}
}
}
module.exports = Utils;