-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathhelpers.js
568 lines (506 loc) · 14 KB
/
helpers.js
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
import numbro from 'numbro';
import _cloneDeep from 'lodash/cloneDeep';
import _isPlainObject from 'lodash/isPlainObject';
/**
* @memberof Helpers
* @module General
*/
/**
* Fill for AggregatedError
*
* @param {Array|*} errors An array of errors
* @param {string|*} message
* @param {object} options
* @param {string} options.name
* @returns {Error|window.AggregateError<Error>}
*/
const aggregatedError = (errors, message, { name = 'AggregateError' } = {}) => {
const { AggregateError, Error } = window;
let err;
if (AggregateError) {
err = new AggregateError(errors, message);
} else {
err = new Error(message);
err.name = name;
err.errors = (Array.isArray(errors) && errors) || [errors];
err.isEmulated = true;
}
return err;
};
/**
* Generate a random'ish ID.
*
* @param {string} prefix
* @returns {string}
*/
const generateId = prefix =>
`${prefix || 'generatedid'}-${(process.env.REACT_APP_ENV !== 'test' && Math.ceil(1e5 * Math.random())) || ''}`;
/**
* Check if "is a Date"
*
* @param {Date|*} date
* @returns {boolean}
*/
const isDate = date => Object.prototype.toString.call(date) === '[object Date]';
/**
* Check if "is a Promise", "Promise like".
*
* @param {Promise|*} obj
* @returns {boolean}
*/
const isPromise = obj => /^\[object (Promise|Async|AsyncFunction)]/.test(Object.prototype.toString.call(obj));
/**
* Generate a consistent hash
* String hash generator based from, https://gist.github.com/jlevy/c246006675becc446360a798e2b2d781
*
* @param {*|object} anyValue
* @returns {string}
*/
const generateHash = anyValue => {
const hashCode = str =>
`c${Array.from(new Uint8Array(new TextEncoder().encode(str))).reduce((hash, encodedValue) => {
// eslint-disable-next-line no-bitwise
let updatedHash = (hash << 5) - hash + encodedValue;
// eslint-disable-next-line no-bitwise
updatedHash |= 0;
return updatedHash;
}, 0)}`;
return hashCode(
JSON.stringify({
value:
(_isPlainObject(anyValue) &&
JSON.stringify(
Object.entries(anyValue).sort(([a], [b]) => a.localeCompare(b)),
(key, value) => {
if (value !== anyValue && _isPlainObject(value)) {
return JSON.stringify(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)) || []);
}
if (typeof value === 'function') {
return value.toString();
}
return value;
}
)) ||
`${typeof anyValue}${anyValue?.toString() || anyValue}`
})
);
};
/**
* Simple memoize, cache based arguments with adjustable limit.
*
* @param {Function} func
* @param {object} options
* @param {number} options.cacheLimit
* @returns {Function}
*/
const memo = (func, { cacheLimit = 1 } = {}) => {
// eslint-disable-next-line func-names
const ized = function () {
const cache = [];
return (...args) => {
const key = JSON.stringify({ value: [...args].map(arg => (typeof arg === 'function' && arg.toString()) || arg) });
const keyIndex = cache.indexOf(key);
if (keyIndex < 0) {
const result = func.call(null, ...args);
cache.unshift(key, result);
cache.length = cacheLimit * 2;
return cache[1];
}
return cache[keyIndex + 1];
};
};
return ized();
};
/**
* Used for the numerous configuration callbacks that drive the UI. Often the same data
* is passed repeatedly. Avoid "accidental" mutation.
*
* @param {any} value
* @returns {any}
*/
const memoClone = memo(value => _cloneDeep(value), { cacheLimit: 25 });
/**
* An empty function.
* Typically used as a default prop.
*/
const noop = Function.prototype;
/**
* An empty promise.
* Typically used as a default prop, or during testing.
*
* @type {Promise<{}>}
*/
const noopPromise = Promise.resolve({});
/**
* ToDo: review adding "locale" for numbro
*/
/**
* Convenience wrapper for numbro. Numbro assumes all values passed to it conform as "number".
* This allows us to optional chain the function results.
*
* @param {*} value
* @returns {numbro.Numbro|*}
*/
const numberDisplay = value => {
if (typeof value !== 'number' || Number.isNaN(value)) {
return value;
}
return numbro(value);
};
/**
* Recursive object and props freeze/immutable.
* Used from deep-freeze-strict, an older npm package, license - public domain
* https://bit.ly/3HR4XWP and https://bit.ly/3Ye4S6B
*
* @param {object} obj
* @returns {*}
*/
const objFreeze = obj => {
Object.freeze(obj);
const oIsFunction = typeof obj === 'function';
const hasOwnProp = Object.prototype.hasOwnProperty;
Object.getOwnPropertyNames(obj).forEach(prop => {
if (
hasOwnProp.call(obj, prop) &&
(oIsFunction ? prop !== 'caller' && prop !== 'callee' && prop !== 'arguments' : true) &&
obj[prop] !== null &&
(typeof obj[prop] === 'object' || typeof obj[prop] === 'function') &&
!Object.isFrozen(obj[prop])
) {
objFreeze(obj[prop]);
}
});
return obj;
};
/**
* Quick set data as "immutable-like". Typically used to pass object and array data through configuration callbacks.
*
* @param {*} data
* @param {object} options
* @param {boolean} options.isClone Clone your data before mutating it.
* @returns {*}
*/
const setImmutableData = memo(
(data, { isClone = false } = {}) => (isClone && objFreeze(_cloneDeep(data))) || objFreeze(data)
);
/**
* Is dev mode active.
* Associated with using the NPM script "start". See dotenv config files for activation.
*
* @type {boolean}
*/
const DEV_MODE = process.env.REACT_APP_ENV === 'development';
/**
* Is prod mode active.
* Associated with production builds. See dotenv config files for activation.
*
* @type {boolean}
*/
const PROD_MODE = process.env.REACT_APP_ENV === 'production';
/**
* Is review/proxy mode active.
* Associated with using the NPM script "start:proxy". See dotenv config files for activation.
*
* @type {boolean}
*/
const REVIEW_MODE = process.env.REACT_APP_ENV === 'review';
/**
* Is test mode active.
* Associated with running unit tests. See dotenv config files for activation.
*
* @type {boolean}
*/
const TEST_MODE = process.env.REACT_APP_ENV === 'test';
/**
* CONFIG export download file expiration.
*
* @type {string}
*/
const CONFIG_EXPORT_EXPIRE = process.env.REACT_APP_CONFIG_EXPORT_EXPIRE;
/**
* CONFIG export download file extension.
*
* @type {string}
*/
const CONFIG_EXPORT_FILE_EXT = process.env.REACT_APP_CONFIG_EXPORT_FILE_EXT;
/**
* CONFIG export download file mime type.
*
* @type {string}
*/
const CONFIG_EXPORT_FILE_TYPE = process.env.REACT_APP_CONFIG_EXPORT_FILE_TYPE;
/**
* CONFIG export download file name.
*
* @type {string}
*/
const CONFIG_EXPORT_FILENAME = process.env.REACT_APP_CONFIG_EXPORT_FILENAME;
/**
* CONFIG export "post" download name prefix, for consistency.
*
* @type {string}
*/
const CONFIG_EXPORT_SERVICE_NAME_PREFIX = process.env.REACT_APP_CONFIG_EXPORT_SERVICE_NAME_PREFIX;
/**
* Apply a path prefix for routing.
* Typically associated with applying a "beta" path prefix. See dotenv config files for updating.
* See build scripts for generated prefix.
*
* @deprecated
* @type {string}
*/
const UI_DEPLOY_PATH_PREFIX = process.env.REACT_APP_UI_DEPLOY_PATH_PREFIX;
/**
* Patch for compensating for platform updates where a mismatch between "beta" and "preview" for redirects means
* that the same prefix can no longer be used for both additional remote resources and links.
* See build scripts for generated prefix.
*
* @deprecated
* @type {string}
*/
const UI_DEPLOY_PATH_LINK_PREFIX = process.env.REACT_APP_UI_DEPLOY_PATH_LINK_PREFIX;
/**
* Disable an aspect of the UI.
* Typically associated with disabling views through route settings. See dotenv config files for activation.
*
* @type {boolean}
*/
const UI_DISABLED = process.env.REACT_APP_UI_DISABLED === 'true';
/**
* Disable the graph card aspect of the UI.
* See dotenv config files for activation.
*
* @type {boolean}
*/
const UI_DISABLED_GRAPH = process.env.REACT_APP_UI_DISABLED_GRAPH === 'true';
/**
* Disable platform notifications.
* See dotenv config files for activation.
*
* @type {boolean}
*/
const UI_DISABLED_NOTIFICATIONS = process.env.REACT_APP_UI_DISABLED_NOTIFICATIONS === 'true';
/**
* Disable the inventory/table aspect of the UI.
* See dotenv config files for activation.
*
* @type {boolean}
*/
const UI_DISABLED_TABLE = process.env.REACT_APP_UI_DISABLED_TABLE === 'true';
/**
* Disable the current instances inventory/table aspect of the UI.
* See dotenv config files for activation.
*
* @type {boolean}
*/
const UI_DISABLED_TABLE_INSTANCES = process.env.REACT_APP_UI_DISABLED_TABLE_INSTANCES === 'true';
/**
* Disable the current subscriptions inventory/table aspect of the UI.
* See dotenv config files for activation.
*
* @type {boolean}
*/
const UI_DISABLED_TABLE_SUBSCRIPTIONS = process.env.REACT_APP_UI_DISABLED_TABLE_SUBSCRIPTIONS === 'true';
/**
* Disable the filter toolbar aspect of the UI.
* See dotenv config files for activation.
*
* @type {boolean}
*/
const UI_DISABLED_TOOLBAR = process.env.REACT_APP_UI_DISABLED_TOOLBAR === 'true';
/**
* Disable the group variant filter aspect of the toolbar.
* See dotenv config files for activation.
*
* @type {boolean}
*/
const UI_DISABLED_TOOLBAR_GROUP_VARIANT = process.env.REACT_APP_UI_DISABLED_TOOLBAR_GROUP_VARIANT === 'true';
/**
* UI application name.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_DISPLAY_NAME = process.env.REACT_APP_UI_DISPLAY_NAME;
/**
* UI application configuration name.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_DISPLAY_CONFIG_NAME = process.env.REACT_APP_UI_DISPLAY_CONFIG_NAME;
/**
* UI application sentence start name.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_DISPLAY_START_NAME = process.env.REACT_APP_UI_DISPLAY_START_NAME;
/**
* Url, or uri, for the UI changelog.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LINK_CHANGELOG = process.env.REACT_APP_UI_LINK_CHANGELOG;
/**
* Url, or uri, for "contact us".
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LINK_CONTACT_US = process.env.REACT_APP_UI_LINK_CONTACT_US;
/**
* Url, or uri, for "learn more".
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LINK_LEARN_MORE = process.env.REACT_APP_UI_LINK_LEARN_MORE;
/**
* Url, or uri, for platform level status
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LINK_PLATFORM_STATUS = process.env.REACT_APP_UI_LINK_PLATFORM_STATUS;
/**
* Url, or uri, for "recommend actions"
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LINK_REPORT_ACCURACY_RECOMMENDATIONS = process.env.REACT_APP_UI_LINK_REPORT_ACCURACY_RECOMMENDATIONS;
/**
* UI locale default.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LOCALE_DEFAULT = process.env.REACT_APP_CONFIG_SERVICE_LOCALES_DEFAULT_LNG;
/**
* UI locale default description.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LOCALE_DEFAULT_DESC = process.env.REACT_APP_CONFIG_SERVICE_LOCALES_DEFAULT_LNG_DESC;
/**
* UI state logging name/id.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LOGGER_ID = process.env.REACT_APP_UI_LOGGER_ID || 'GUI';
/**
* UI state logging file name.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_LOGGER_FILE = process.env.REACT_APP_UI_LOGGER_FILE || 'debug_log_{0}.json';
/**
* UI packaged application name.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_NAME = process.env.REACT_APP_UI_NAME;
/**
* UI internal application name.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_INTERNAL_NAME = process.env.REACT_APP_UI_INTERNAL_NAME;
/**
* UI packaged application path, with generated prefix.
* See dotenv config files for updating. See build scripts for generated prefix.
*
* @type {string}
*/
const UI_PATH = process.env.PUBLIC_URL || '/';
/**
* UI packaged application version, with generated hash.
* See dotenv config files for updating. See build scripts for generated hash.
*
* @type {string}
*/
const UI_VERSION = process.env.REACT_APP_UI_VERSION;
/**
* UI exposed window name/id.
* See dotenv config files for updating.
*
* @type {string}
*/
const UI_WINDOW_ID = process.env.REACT_APP_UI_WINDOW_ID || 'GUI';
/**
* Expose an application specific object.
* Associated with access on a browser's developer console. Limits exposed additions to
* test and non-production environments only. Exposes helpers across all environments.
*
* @param {object} obj
* @param {object} options
* @param {boolean} options.limit
* @param {string} options.id
*/
const browserExpose = (obj = {}, options) => {
const { limit = PROD_MODE, id = UI_WINDOW_ID } = options || {};
window[id] = (limit && { ...window[id] }) || { ...window[id], ...obj };
};
const helpers = {
aggregatedError,
browserExpose,
generateHash,
generateId,
isDate,
isPromise,
memo,
memoClone,
noop,
noopPromise,
numberDisplay,
objFreeze,
setImmutableData,
DEV_MODE,
PROD_MODE,
REVIEW_MODE,
TEST_MODE,
CONFIG_EXPORT_EXPIRE,
CONFIG_EXPORT_FILE_EXT,
CONFIG_EXPORT_FILE_TYPE,
CONFIG_EXPORT_FILENAME,
CONFIG_EXPORT_SERVICE_NAME_PREFIX,
UI_DEPLOY_PATH_PREFIX,
UI_DEPLOY_PATH_LINK_PREFIX,
UI_DISABLED,
UI_DISABLED_GRAPH,
UI_DISABLED_NOTIFICATIONS,
UI_DISABLED_TABLE,
UI_DISABLED_TABLE_INSTANCES,
UI_DISABLED_TABLE_SUBSCRIPTIONS,
UI_DISABLED_TOOLBAR,
UI_DISABLED_TOOLBAR_GROUP_VARIANT,
UI_DISPLAY_NAME,
UI_DISPLAY_CONFIG_NAME,
UI_DISPLAY_START_NAME,
UI_INTERNAL_NAME,
UI_LINK_CHANGELOG,
UI_LINK_CONTACT_US,
UI_LINK_LEARN_MORE,
UI_LINK_PLATFORM_STATUS,
UI_LINK_REPORT_ACCURACY_RECOMMENDATIONS,
UI_LOCALE_DEFAULT,
UI_LOCALE_DEFAULT_DESC,
UI_LOGGER_ID,
UI_LOGGER_FILE,
UI_NAME,
UI_PATH,
UI_VERSION,
UI_WINDOW_ID
};
/**
* Expose helpers to the browser's developer console.
*/
helpers.browserExpose({ ...helpers }, { limit: false });
export { helpers as default, helpers };