@questwork/q-utilities 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3628 +0,0 @@
1
- (function webpackUniversalModuleDefinition(root, factory) {
2
- if(typeof exports === 'object' && typeof module === 'object')
3
- module.exports = factory();
4
- else if(typeof define === 'function' && define.amd)
5
- define([], factory);
6
- else if(typeof exports === 'object')
7
- exports["@questwork/q-utilities"] = factory();
8
- else
9
- root["@questwork/q-utilities"] = factory();
10
- })(this, () => {
11
- return /******/ (() => { // webpackBootstrap
12
- /******/ // The require scope
13
- /******/ var __webpack_require__ = {};
14
- /******/
15
- /************************************************************************/
16
- /******/ /* webpack/runtime/define property getters */
17
- /******/ (() => {
18
- /******/ // define getter functions for harmony exports
19
- /******/ __webpack_require__.d = (exports, definition) => {
20
- /******/ for(var key in definition) {
21
- /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
22
- /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
23
- /******/ }
24
- /******/ }
25
- /******/ };
26
- /******/ })();
27
- /******/
28
- /******/ /* webpack/runtime/hasOwnProperty shorthand */
29
- /******/ (() => {
30
- /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
31
- /******/ })();
32
- /******/
33
- /******/ /* webpack/runtime/make namespace object */
34
- /******/ (() => {
35
- /******/ // define __esModule on exports
36
- /******/ __webpack_require__.r = (exports) => {
37
- /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
38
- /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
39
- /******/ }
40
- /******/ Object.defineProperty(exports, '__esModule', { value: true });
41
- /******/ };
42
- /******/ })();
43
- /******/
44
- /************************************************************************/
45
- var __webpack_exports__ = {};
46
- // ESM COMPAT FLAG
47
- __webpack_require__.r(__webpack_exports__);
48
-
49
- // EXPORTS
50
- __webpack_require__.d(__webpack_exports__, {
51
- ApiResponse: () => (/* reexport */ ApiResponse),
52
- AwsStsS3Client: () => (/* reexport */ AwsStsS3Client),
53
- KeyValueObject: () => (/* reexport */ KeyValueObject),
54
- Metadata: () => (/* reexport */ Metadata),
55
- QMeta: () => (/* reexport */ QMeta),
56
- Repo: () => (/* reexport */ Repo),
57
- Service: () => (/* reexport */ Service),
58
- TemplateCompiler: () => (/* reexport */ TemplateCompiler),
59
- TenantAwareEntity: () => (/* reexport */ TenantAwareEntity),
60
- TrackedEntity: () => (/* reexport */ TrackedEntity),
61
- UniqueKeyGenerator: () => (/* reexport */ UniqueKeyGenerator),
62
- authorize: () => (/* reexport */ authorize),
63
- changeCreatorOwner: () => (/* reexport */ changeCreatorOwner),
64
- concatStringByArray: () => (/* reexport */ concatStringByArray),
65
- convertString: () => (/* reexport */ convertString),
66
- escapeRegex: () => (/* reexport */ escapeRegex),
67
- expressHelper: () => (/* reexport */ expressHelper),
68
- extractEmails: () => (/* reexport */ extractEmails),
69
- formatDate: () => (/* reexport */ formatDate),
70
- generalPost: () => (/* reexport */ generalPost),
71
- getValidation: () => (/* reexport */ getValidation),
72
- getValueByKeys: () => (/* reexport */ getValueByKeys_getValueByKeys),
73
- init: () => (/* reexport */ init),
74
- initFromArray: () => (/* reexport */ initFromArray),
75
- initOnlyValidFromArray: () => (/* reexport */ initOnlyValidFromArray),
76
- makeApiResponse: () => (/* reexport */ makeApiResponse),
77
- makeService: () => (/* reexport */ makeService),
78
- mergeArraysByKey: () => (/* reexport */ mergeArraysByKey),
79
- objectHelper: () => (/* reexport */ objectHelper),
80
- pReduce: () => (/* reexport */ pReduce),
81
- padZeros: () => (/* reexport */ padZeros),
82
- replacePlaceholders: () => (/* reexport */ replacePlaceholders),
83
- sanitizeText: () => (/* reexport */ sanitizeText),
84
- stringFormatter: () => (/* reexport */ stringFormatter),
85
- stringHelper: () => (/* reexport */ stringHelper),
86
- tenantPlugin: () => (/* reexport */ tenantPlugin),
87
- trackingPlugin: () => (/* reexport */ trackingPlugin)
88
- });
89
-
90
- ;// ./lib/helpers/authorize/authorize.js
91
- function authorize({ allowCoordinator, allowOwner, query = {}, required, user }) {
92
- if (!user) {
93
- throw new Error('Require login.')
94
- }
95
- if (!user.permission) {
96
- // throw new Error('You do not have any permission.')
97
- }
98
- const scopes = user.permission.getScopes(required || {}) || []
99
- if (!scopes || scopes.length === 0) {
100
- // throw new Error('You are not allowed in this scope.')
101
- }
102
- if (!scopes.includes('*')) {
103
- query.tenantCode = user.tenantCode
104
- }
105
- if (!scopes.includes('TENANT')) {
106
- query.eventShortCode = user.eventShortCode
107
- }
108
- // if (!scopes.includes('EVENT')) {
109
- // query.eventRegistrationCode = user.eventRegistrationCode
110
- // }
111
- if (allowCoordinator) {
112
- if (query.registrationGroupCode && user.myManagedRegistrationGroupCodes.includes(query.registrationGroupCode)) {
113
- query.__ALLOW_COORDINATOR = true
114
- } else {
115
- if (!scopes.includes('EVENT')) {
116
- query.eventRegistrationCode = user.eventRegistrationCode
117
- }
118
- }
119
- } else {
120
- if (!scopes.includes('EVENT')) {
121
- query.eventRegistrationCode = user.eventRegistrationCode
122
- }
123
- }
124
- if (allowOwner) {
125
- query.__ALLOW_OWNER = true
126
- }
127
- // not good, just use it as example
128
- if (user.hasExcludedFields) {
129
- query.__EXCLUDED_FIELDS = user.getExcludedFields(required)
130
- }
131
- query.__LOGIN_SUBJECT_CODE = user.loginSubjectCode
132
- return query
133
- }
134
-
135
- ;// ./lib/helpers/authorize/index.js
136
-
137
-
138
- ;// ./lib/helpers/changeCreatorOwner/changeCreatorOwner.js
139
- function changeCreatorOwner(that, { source, target }) {
140
- if (that.meta) {
141
- if (!that.meta.creator || that.meta.creator === source.getId()) {
142
- that.meta.creator = target.getId()
143
- }
144
- if (!that.meta.owner || that.meta.owner === source.getId()) {
145
- that.meta.owner = target.getId()
146
- }
147
- } else {
148
- if (!that.creator || that.creator === source.getId()) {
149
- that.creator = target.getId()
150
- }
151
- if (!that.owner || that.owner === source.getId()) {
152
- that.owner = target.getId()
153
- }
154
- }
155
- return that
156
- }
157
-
158
- ;// ./lib/helpers/changeCreatorOwner/index.js
159
-
160
-
161
- ;// ./lib/helpers/getValidation/getValidation.js
162
- function getValidation(rule, data, getDataByKey, KeyValueObject) {
163
- if (!rule) {
164
- return true
165
- }
166
- if (typeof getDataByKey !== 'function' || (KeyValueObject && typeof KeyValueObject !== 'function')) {
167
- return false
168
- }
169
- const { key = '', value, placeholder, keyValuePath = '' } = rule
170
- const [valueAttribute] = Object.keys(value)
171
-
172
- if (!key && typeof placeholder === 'undefined') {
173
- switch (valueAttribute) {
174
- case '$and': {
175
- return value['$and'].reduce((acc, item) => (acc && getValidation(item, data, getDataByKey, KeyValueObject)), true)
176
- }
177
- case '$or': {
178
- return value['$or'].reduce((acc, item) => (acc || getValidation(item, data, getDataByKey, KeyValueObject)), false)
179
- }
180
- default:
181
- return false
182
- }
183
- }
184
- let rowValue = typeof placeholder === 'undefined' ? getDataByKey(key, data) : placeholder
185
-
186
- // if KeyValue object
187
- if (keyValuePath) {
188
- const rowValueData = KeyValueObject.toObject(rowValue)
189
- rowValue = getDataByKey(keyValuePath, rowValueData)
190
- }
191
-
192
- switch (valueAttribute) {
193
- case '$empty': {
194
- const isEmpty = rowValue === null || rowValue === undefined
195
- return isEmpty === value['$empty']
196
- }
197
- case '$eq': {
198
- return rowValue === value['$eq']
199
- }
200
- case '$gt': {
201
- return rowValue > value['$gt']
202
- }
203
- case '$gte': {
204
- return rowValue >= value['$gte']
205
- }
206
- case '$hasOverlap': {
207
- return _hasOverlap(rowValue, value['$hasOverlap'])
208
- }
209
- case '$lt': {
210
- return rowValue < value['$lt']
211
- }
212
- case '$lte': {
213
- return rowValue <= value['$lte']
214
- }
215
- case '$in': {
216
- if (Array.isArray(rowValue)) {
217
- return !!rowValue.find((e) => (value['$in'].includes(e)))
218
- }
219
- if (typeof rowValue !== 'object') {
220
- return !!value['$in'].includes(rowValue)
221
- }
222
- return false
223
- }
224
- case '$inValue': {
225
- const result = getDataByKey(value['$inValue'], data)
226
- const _value = Array.isArray(result) ? result : []
227
- if (Array.isArray(rowValue)) {
228
- return !!rowValue.find((e) => (_value.includes(e)))
229
- }
230
- if (typeof rowValue === 'string') {
231
- return !!_value.includes(rowValue)
232
- }
233
- return false
234
- }
235
- case '$ne': {
236
- return rowValue !== value['$ne']
237
- }
238
- case '$notIn': {
239
- if (Array.isArray(rowValue)) {
240
- return !rowValue.find((e) => (value['$notIn'].includes(e)))
241
- }
242
- if (typeof rowValue !== 'object') {
243
- return !value['$notIn'].includes(rowValue)
244
- }
245
- return false
246
- }
247
- case '$intervalTimeGt': {
248
- const now = new Date().getTime()
249
- const timestamp = new Date(rowValue).getTime()
250
- return (now - timestamp) > value['$intervalTimeGt']
251
- }
252
- case '$intervalTimeLt': {
253
- const now = new Date().getTime()
254
- const timestamp = new Date(rowValue).getTime()
255
- return (now - timestamp) < value['$intervalTimeLt']
256
- }
257
- case '$isToday': {
258
- const currentDate = new Date()
259
- const start = currentDate.setHours(0,0,0,0)
260
- const end = currentDate.setHours(23,59,59,59)
261
- const dateValue = new Date(rowValue).getTime()
262
- return (start <= dateValue && end >= dateValue) === value['$isToday']
263
- }
264
- case '$notInValue': {
265
- const result = getDataByKey(value['$notInValue'], data)
266
- const _value = Array.isArray(result) ? result : []
267
- if (Array.isArray(rowValue)) {
268
- return !rowValue.find((e) => (_value.includes(e)))
269
- }
270
- if (typeof rowValue !== 'object') {
271
- return !_value.includes(rowValue)
272
- }
273
- return false
274
- }
275
- case '$range': {
276
- const [min, max] = value['$range']
277
- if (typeof min === 'number' && typeof max === 'number' && rowValue >= min && rowValue <= max) {
278
- return true
279
- }
280
- return false
281
- }
282
- default:
283
- return false
284
- }
285
-
286
- }
287
-
288
- function _hasOverlap(item1, item2) {
289
- let arr1 = item1
290
- let arr2 = item2
291
- if (typeof arr1 === 'string') {
292
- arr1 = arr1.split(',')
293
- }
294
- if (typeof arr2 === 'string') {
295
- arr2 = arr2.split(',')
296
- }
297
- const set1 = new Set(arr1)
298
- return arr2.find((i) => (set1.has(i)))
299
- }
300
-
301
- /* harmony default export */ const getValidation_getValidation = ({
302
- getValidation
303
- });
304
-
305
-
306
- ;// ./lib/helpers/getValidation/index.js
307
-
308
-
309
- ;// ./lib/helpers/formatDate/formatDate.js
310
-
311
- function formatDate(date, format) {
312
- const _date = date && date instanceof Date ? date : new Date(date)
313
- const dayMapChi = ['日','一','二','三','四','五','六']
314
- const dayMapEng = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
315
- const dayMapEngShort = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']
316
- const _format = format || 'YYYY/MM/DD hh:mm'
317
- const e = _date.getDay()
318
- const ee = dayMapEngShort[e]
319
- const eee = dayMapChi[e]
320
- const eeee = dayMapEng[e]
321
- const y = _date.getFullYear()
322
- const m = _date.getMonth() + 1
323
- const d = _date.getDate()
324
- const h = _date.getHours()
325
- const mm = _date.getMinutes()
326
- const s = _date.getSeconds()
327
-
328
- return _format.replace('YYYY', y)
329
- .replace('MM', padding(m))
330
- .replace('MM', padding(m))
331
- .replace('DD', padding(d))
332
- .replace('hh', padding(h))
333
- .replace('mm', padding(mm))
334
- .replace('ss', padding(s))
335
- .replace('M', m)
336
- .replace('D', d)
337
- .replace('h', h)
338
- .replace('m', mm)
339
- .replace('s', s)
340
- .replace('EEEE', padding(eeee))
341
- .replace('EEE', padding(eee))
342
- .replace('EE', padding(ee))
343
- .replace('E', padding(e))
344
- }
345
-
346
- function padding(m) {
347
- return m < 10 ? `0${m}` : m
348
- }
349
-
350
-
351
- /* harmony default export */ const formatDate_formatDate = ({
352
- formatDate
353
- });
354
-
355
-
356
-
357
- ;// ./lib/helpers/formatDate/index.js
358
-
359
-
360
- ;// ./lib/helpers/getValueByKeys/getValueByKeys.js
361
- // keys can be array or object or string
362
- function getValueByKeys_getValueByKeys(keys, data) {
363
- let _keys = keys
364
- let _data = data
365
- if (typeof keys === 'string') {
366
- _keys = _keys.split('.')
367
- }
368
- if (!Array.isArray(keys) && typeof keys === 'object') {
369
- const { keys: keyArr, obj } = keys
370
- _keys = keyArr
371
- _data = obj
372
- }
373
- if (_keys.length === 0) {
374
- return _data
375
- }
376
- const firstKey = _keys.shift()
377
- if (_data && Object.prototype.hasOwnProperty.call(_data, firstKey)) {
378
- return getValueByKeys_getValueByKeys(_keys, _data[firstKey])
379
- }
380
- if (_data && firstKey) {
381
- if (_keys.length > 0) {
382
- return getValueByKeys_getValueByKeys(_keys, _data[firstKey])
383
- }
384
- return _data[firstKey]
385
- }
386
- return _data
387
-
388
- }
389
- /* harmony default export */ const getValueByKeys = ({
390
- getValueByKeys: getValueByKeys_getValueByKeys
391
- });
392
-
393
-
394
- ;// ./lib/helpers/getValueByKeys/index.js
395
-
396
-
397
- ;// ./lib/models/templateCompiler/templateCompilerException.js
398
- const TEMPLATE_COMPILER_EXCEPTION_TYPE = {
399
- argumentEmptyException: 'Argument is empty',
400
- argumentFormatException: 'Incorrect number or format of argument',
401
- invalidFuntionException: 'Function Name is invalid',
402
- invalidRegExpException: 'Invalid regular expression',
403
- isNotAFunctionException: 'Is not a function',
404
- notExistException: 'Key does not exist',
405
- resultEmptyException: 'Result is empty',
406
- resultMoreThanOneException: 'More than one result'
407
- }
408
-
409
- class TemplateCompilerException extends Error {
410
- constructor(message) {
411
- super(message)
412
- this.message = message
413
- }
414
- }
415
-
416
-
417
-
418
- ;// ./lib/models/templateCompiler/constants.js
419
- const _EMPTY = '_EMPTY'
420
- const _FN_NAMES = [
421
- 'concatIf',
422
- 'divide',
423
- 'eq',
424
- 'exec',
425
- 'filterAll',
426
- 'filterOne',
427
- 'formatDate',
428
- 'get',
429
- 'gt',
430
- 'gte',
431
- 'isEmpty',
432
- 'isNotEmpty',
433
- 'join',
434
- 'lt',
435
- 'lte',
436
- 'map',
437
- 'neq',
438
- 'removeHtml',
439
- 'toLowerCase',
440
- 'toUpperCase',
441
- ]
442
- const _HIDE = '_HIDE'
443
- const _NOT_EMPTY = '_NOT_EMPTY'
444
- const _SELF = '_SELF'
445
- const TAGS_EJS = ['<%=', '%>']
446
- const TAGS_HANDLEBAR = ['{{', '}}']
447
-
448
-
449
-
450
- ;// ./lib/models/templateCompiler/helpers/_concatIf.js
451
-
452
-
453
-
454
-
455
- function _concatIf(data, args) {
456
- if (typeof data !== 'string') {
457
- throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string :${data.join(', ')}`)
458
- }
459
- if (args.length !== 3) {
460
- throw new TemplateCompilerException(`_concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
461
- }
462
- if (data === null || (typeof data === 'undefined')) {
463
- return null
464
- }
465
- const [condition, success, failover] = args
466
- const validConditions = [_EMPTY, _NOT_EMPTY]
467
- if (validConditions.includes(condition) || success.length !== 2) {
468
- throw new TemplateCompilerException(`concatIf: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException}: ${condition}, ${success}`)
469
- }
470
- if (data === '' && failover.includes(_HIDE)) {
471
- return ''
472
- }
473
- if (data !== '' && (data !== null || data !== undefined) && failover.includes(_HIDE)) {
474
- return `${success[0]}${data}${success[success.length - 1]}`
475
- }
476
- return failover
477
- }
478
-
479
-
480
-
481
- ;// ./lib/models/templateCompiler/helpers/_divide.js
482
- function _divide(value, divisor) {
483
- try {
484
- if (Number.isNaN(value)) {
485
- return value
486
- }
487
- return (value / divisor)
488
- } catch (e) {
489
- throw e
490
- }
491
- }
492
-
493
-
494
-
495
- ;// ./lib/models/templateCompiler/helpers/_eq.js
496
-
497
-
498
-
499
-
500
- function _eq(data, args) {
501
- if (args.length !== 3) {
502
- throw new TemplateCompilerException(`eq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
503
- }
504
- if (data === null || (typeof data === 'undefined')) {
505
- return null
506
- }
507
- if (args.includes(_SELF)) {
508
- args = args.map((arg) => {
509
- return (arg === _SELF) ? data : arg
510
- })
511
- }
512
- const expected = args[0]
513
- return data === expected ? args[1] : args[2]
514
- }
515
-
516
-
517
-
518
- ;// ./lib/models/templateCompiler/helpers/_exec.js
519
- function _exec(data, args) {
520
- try {
521
- const [methodName, ..._args] = args
522
- return data[methodName](..._args)
523
- } catch (e) {
524
- throw e
525
- }
526
- }
527
-
528
-
529
-
530
- ;// ./lib/models/templateCompiler/helpers/_filterAll.js
531
-
532
-
533
-
534
- // const DELIMITER = '~~~'
535
-
536
- function _filterAll(data, args) {
537
- try {
538
- if (!Array.isArray(args) || args.length === 0) {
539
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
540
- }
541
- if (!Array.isArray(data) || data.length === 0) {
542
- return []
543
- }
544
- if (typeof data[0] === 'object') {
545
- return _existObject(data, args)
546
- }
547
- if (typeof data[0] === 'string' || typeof data[0] === 'number') {
548
- return _exist(data, args)
549
- }
550
- return []
551
- } catch (e) {
552
- throw e
553
- }
554
- }
555
-
556
- function _exist(data, args) {
557
- const _args = args.flat()
558
- return data.filter((e) => _args.some((arg) => _performOperation(arg, e)))
559
- }
560
-
561
- function _existObject(data, args) {
562
- if (args.length === 1) {
563
- const arg = args[0]
564
- return data.filter((e) => {
565
- if (arg.includes('.')) {
566
- return getValueByKeys_getValueByKeys(arg.split('.'), e)
567
- }
568
- return Object.prototype.hasOwnProperty.call(e, arg)
569
- })
570
- }
571
-
572
- if (args.length > 2) {
573
- let res = data
574
- for (let i = 0; i < args.length; i += 2) {
575
- const group = [args[i], args[i + 1]]
576
- res = _existObject(res, group)
577
- }
578
- return res
579
- }
580
-
581
- const [key, ..._argsArr] = args
582
- const _args = _argsArr.flat()
583
- return data.filter((e) => {
584
- const value = key.includes('.') ? getValueByKeys_getValueByKeys(key.split('.'), e) : e[key]
585
- return _args.some((arg) => _performOperation(arg, value))
586
- })
587
- }
588
-
589
- function _performOperation(arg, value) {
590
- // the arg is undefined
591
- if (arg === undefined && value === undefined) return true
592
-
593
- // the arg is null
594
- if (arg === null && value === null) return true
595
-
596
- // the arg is boolean
597
- if (typeof arg === 'boolean') {
598
- return arg === value
599
- }
600
-
601
- // the arg is blank or *: Blank => Empty, * => Not Empty
602
- if (arg === '' || arg === '*') {
603
- // null and undefined are not included in either case
604
- if (value === null || value === undefined) {
605
- return false
606
- }
607
- if (typeof value === 'string') {
608
- return arg === '' ? value === '' : value !== ''
609
- }
610
- if (Array.isArray(value)) {
611
- return arg === '' ? value.length === 0 : value.length !== 0
612
- }
613
- return arg !== ''
614
- }
615
-
616
- // the arg is alphabetic or number
617
- if (_isPureStringOrNumber(arg)) {
618
- return arg === value
619
- }
620
-
621
- // the arg is array of [] or [*]: [] => Empty, [*] => Not Empty
622
- if (arg.startsWith('[') && arg.endsWith(']')) {
623
- if (arg === '[]') {
624
- return Array.isArray(value) && value.length === 0
625
- }
626
- if (arg === '[*]') {
627
- return Array.isArray(value) && value.length !== 0
628
- }
629
- return false
630
- }
631
-
632
- // the arg is 'operator + string | number'
633
- const { operator, value: argValue } = _splitOperator(arg)
634
- if (!operator || (argValue !== 0 && !argValue)) {
635
- return false
636
- }
637
- switch (operator) {
638
- case '>':
639
- return value > argValue
640
- case '<':
641
- return value < argValue
642
- case '!=':
643
- return value !== argValue
644
- case '>=':
645
- return value >= argValue
646
- case '<=':
647
- return value <= argValue
648
- default:
649
- return false
650
- }
651
- }
652
-
653
- function _isPureStringOrNumber(input) {
654
- if (typeof input === 'string') {
655
- if (input.startsWith('[') && input.endsWith(']')) {
656
- return false
657
- }
658
- if (/!=|>=|<=|>|</.test(input)) {
659
- return false
660
- }
661
- return true
662
- }
663
- return !Number.isNaN(input)
664
- }
665
-
666
- function _splitOperator(str) {
667
- const operators = ['!=', '>=', '<=', '>', '<']
668
-
669
- const matchedOp = operators.find((op) => str.startsWith(op))
670
- if (!matchedOp) return { operator: null, value: null }
671
-
672
- const remaining = str.slice(matchedOp.length)
673
-
674
- // '>Primary' or '<Primary' is invalid
675
- if (/^[a-zA-Z]*$/.test(remaining) && matchedOp !== '!=') {
676
- return { operator: null, value: null }
677
- }
678
-
679
- // if it is a number it is converted to a number
680
- const value = (!Number.isNaN(parseFloat(remaining)) && !Number.isNaN(remaining)) ? Number(remaining) : remaining
681
-
682
- return {
683
- operator: matchedOp,
684
- value
685
- }
686
- }
687
-
688
-
689
-
690
- ;// ./lib/models/templateCompiler/helpers/_filterOne.js
691
-
692
-
693
-
694
- function _filterOne(data, args) {
695
- try {
696
- const list = _filterAll(data, args)
697
- if (list.length === 1) {
698
- return list[0]
699
- }
700
- if (list.length === 0) {
701
- return null
702
- }
703
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.resultMoreThanOneException)
704
- } catch (e) {
705
- throw e
706
- }
707
- }
708
-
709
-
710
-
711
- ;// ./lib/models/templateCompiler/helpers/_formatDate.js
712
-
713
-
714
- function _formatDate(timestamp, format) {
715
- if (format.length === 0) {
716
- throw new TemplateCompilerException(`_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: format parts must be not empty array`)
717
- }
718
-
719
- if (timestamp === null || timestamp === undefined) {
720
- return null
721
- }
722
-
723
- const date = new Date(timestamp)
724
-
725
- const partsMap = {
726
- yyyy: String(date.getFullYear()),
727
- mm: String(date.getMonth() + 1).padStart(2, '0'),
728
- dd: String(date.getDate()).padStart(2, '0')
729
- }
730
-
731
- // Check for invalid format tokens
732
- const validTokens = ['yyyy', 'mm', 'dd']
733
- const invalidTokens = format.filter((part) => part.length > 1 && !validTokens.includes(part))
734
-
735
- if (invalidTokens.length > 0) {
736
- throw new TemplateCompilerException(
737
- `_formateDate: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the format type is not valid: ${format.join(', ')}`
738
- )
739
- }
740
-
741
- // Build the formatted string using reduce
742
- return format.reduce((result, part) => result + (partsMap[part] || part), '')
743
- }
744
-
745
-
746
-
747
- ;// ./lib/models/templateCompiler/helpers/_get.js
748
-
749
-
750
- function _get(data, key, failover = null) {
751
- try {
752
- if (key === null || (typeof key === 'undefined') || key === '') {
753
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
754
- }
755
- if (data === null) {
756
- return null
757
- }
758
- if (key.includes('.')) {
759
- const parts = key.split('.')
760
- if (parts.length > 1) {
761
- const first = parts.shift()
762
- const remainingKey = parts.join('.')
763
- if (typeof data[first] !== 'undefined') {
764
- return _get(data[first], remainingKey, failover)
765
- }
766
- return _handleFailover(key, failover)
767
- }
768
- }
769
- if (typeof data[key] !== 'undefined') {
770
- return data[key]
771
- }
772
- return _handleFailover(key, failover)
773
- } catch (e) {
774
- throw e
775
- }
776
- }
777
-
778
- function _handleFailover(key, failover) {
779
- if (failover !== null) {
780
- return failover
781
- }
782
- return null
783
- // throw new TemplateCompilerException(`Key "${key}" does not exist and no failover`)
784
- }
785
-
786
-
787
-
788
- ;// ./lib/models/templateCompiler/helpers/_gt.js
789
-
790
-
791
-
792
-
793
- function _gt(data, args) {
794
- if (args.length !== 3) {
795
- throw new TemplateCompilerException(`_gt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
796
- }
797
- if (data === null || (typeof data === 'undefined')) {
798
- return null
799
- }
800
- if (args.includes(_SELF)) {
801
- args = args.map((arg) => {
802
- return (arg === _SELF) ? data : arg
803
- })
804
- }
805
- const expected = args[0]
806
- return data > expected ? args[1] : args[2]
807
- }
808
-
809
-
810
-
811
- ;// ./lib/models/templateCompiler/helpers/_gte.js
812
-
813
-
814
-
815
-
816
- function _gte(data, args) {
817
- if (args.length !== 3) {
818
- throw new TemplateCompilerException(`_gte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
819
- }
820
- if (data === null || (typeof data === 'undefined')) {
821
- return null
822
- }
823
- if (args.includes(_SELF)) {
824
- args = args.map((arg) => {
825
- return (arg === _SELF) ? data : arg
826
- })
827
- }
828
- const expected = args[0]
829
- return data >= expected ? args[1] : args[2]
830
- }
831
-
832
-
833
-
834
- ;// ./lib/models/templateCompiler/helpers/_isEmpty.js
835
-
836
-
837
-
838
-
839
- function _isEmpty(data, args) {
840
- if (args.length !== 2) {
841
- throw new TemplateCompilerException(`_isEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
842
- }
843
- // if (data === null || (typeof data === 'undefined')) {
844
- // return null
845
- // }
846
- if (args.includes(_SELF)) {
847
- args = args.map((arg) => {
848
- return (arg === _SELF) ? data : arg
849
- })
850
- }
851
- if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
852
- return args[0]
853
- }
854
- return (data === '' || data === null || data === undefined || data.length === 0) ? args[0] : args[1]
855
- }
856
-
857
-
858
-
859
- ;// ./lib/models/templateCompiler/helpers/_isNotEmpty.js
860
-
861
-
862
-
863
-
864
- function _isNotEmpty(data, args) {
865
- if (args.length !== 2) {
866
- throw new TemplateCompilerException(`_isNotEmpty: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
867
- }
868
- // if (data === null || (typeof data === 'undefined')) {
869
- // return null
870
- // }
871
- if (args.includes(_SELF)) {
872
- args = args.map((arg) => {
873
- return (arg === _SELF) ? data : arg
874
- })
875
- }
876
- if (data !== null && typeof data === 'object' && Object.keys(data).length === 0) {
877
- return args[1]
878
- }
879
- if (Array.isArray(data) && data.length === 0) {
880
- return args[1]
881
- }
882
- if (typeof data === 'string' && data === '') {
883
- return args[1]
884
- }
885
- if (data === null || data === undefined) {
886
- return args[1]
887
- }
888
- return args[0]
889
- }
890
-
891
-
892
- ;// ./lib/models/templateCompiler/helpers/_join.js
893
- function _join(data, delimiter) {
894
- try {
895
- if (data.length === 0) return ''
896
- if (data.length === 1) return _stringifyObject(data[0])
897
- return data.map((item) => _stringifyObject(item)).join(delimiter)
898
- } catch (e) {
899
- throw e
900
- }
901
- }
902
-
903
- function _stringifyObject(obj) {
904
- return JSON.stringify(obj).replace(/"([^"]+)":/g, '$1: ').replace(/"([^"]+)"/g, '$1').replace(/,/g, ', ')
905
- }
906
-
907
-
908
-
909
- ;// ./lib/models/templateCompiler/helpers/_lt.js
910
-
911
-
912
-
913
-
914
- function _lt(data, args) {
915
- if (args.length !== 3) {
916
- throw new TemplateCompilerException(`_lt: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
917
- }
918
- if (data === null || (typeof data === 'undefined')) {
919
- return null
920
- }
921
- if (args.includes(_SELF)) {
922
- args = args.map((arg) => {
923
- return (arg === _SELF) ? data : arg
924
- })
925
- }
926
- const expected = args[0]
927
- return data < expected ? args[1] : args[2]
928
- }
929
-
930
-
931
-
932
- ;// ./lib/models/templateCompiler/helpers/_lte.js
933
-
934
-
935
-
936
-
937
- function _lte(data, args) {
938
- if (args.length !== 3) {
939
- throw new TemplateCompilerException(`_lte: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
940
- }
941
- if (data === null || (typeof data === 'undefined')) {
942
- return null
943
- }
944
- if (args.includes(_SELF)) {
945
- args = args.map((arg) => {
946
- return (arg === _SELF) ? data : arg
947
- })
948
- }
949
- const expected = args[0]
950
- return data <= expected ? args[1] : args[2]
951
- }
952
-
953
-
954
-
955
- ;// ./lib/models/templateCompiler/helpers/_map.js
956
-
957
-
958
-
959
- function _map(data, args) {
960
- try {
961
- if (args.length === 0) {
962
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentEmptyException)
963
- }
964
- if (data === null || (typeof data === 'undefined')) {
965
- return null
966
- }
967
-
968
- const result = data.reduce((acc, item) => {
969
- if (args.length === 1 && Array.isArray(args[0])) {
970
- args = args[0]
971
- acc.hasFormat = true
972
- }
973
- const list = args.map((key) => {
974
- if (key.includes('.')) {
975
- const parts = key.split('.')
976
- const first = parts[0]
977
- parts.shift()
978
- const remainingKey = parts.join('.')
979
- return _get(item[first], remainingKey)
980
- }
981
- if (typeof item[key] !== 'undefined') {
982
- return item[key]
983
- }
984
- return null
985
- })
986
- if (acc.hasFormat) {
987
- acc.content.push(list)
988
- } else {
989
- acc.content = acc.content.concat(list)
990
- }
991
- return acc
992
- }, {
993
- content: [],
994
- hasFormat: false
995
- })
996
- return result.content
997
- } catch (e) {
998
- throw e
999
- }
1000
- }
1001
-
1002
-
1003
-
1004
- ;// ./lib/models/templateCompiler/helpers/_neq.js
1005
-
1006
-
1007
-
1008
-
1009
- function _neq(data, args) {
1010
- if (args.length !== 3) {
1011
- throw new TemplateCompilerException(`_neq: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1012
- }
1013
- if (data === null || (typeof data === 'undefined')) {
1014
- return null
1015
- }
1016
- if (args.includes(_SELF)) {
1017
- args = args.map((arg) => {
1018
- return (arg === _SELF) ? data : arg
1019
- })
1020
- }
1021
- const expected = args[0]
1022
- return data !== expected ? args[1] : args[2]
1023
- }
1024
-
1025
-
1026
-
1027
- ;// ./lib/models/templateCompiler/helpers/_removeHtml.js
1028
-
1029
-
1030
- function _removeHtml(html, args) {
1031
- if (html === null || html === undefined) {
1032
- return null
1033
- }
1034
- if (!Array.isArray(args)) {
1035
- throw new TemplateCompilerException(`_removeHtml: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: args parts must be array`)
1036
- }
1037
-
1038
- return _htmlToPlainText(html, args[0])
1039
- }
1040
-
1041
- function _htmlToPlainText(html, delimiter = '\n') {
1042
- if (typeof delimiter !== 'string') {
1043
- delimiter = '\n'; // Fallback to default if not a string
1044
- }
1045
-
1046
- // First decode HTML entities and normalize whitespace
1047
- const decodedHtml = html
1048
- .replace(/&nbsp;/g, ' ')
1049
- .replace(/\s+/g, ' '); // Collapse all whitespace to single spaces
1050
-
1051
- // Process HTML tags
1052
- let text = decodedHtml
1053
- // Replace block tags with temporary marker (~~~)
1054
- .replace(/<\/?(p|div|h[1-6]|ul|ol|li|pre|section|article|table|tr|td|th)(\s[^>]*)?>/gi, '~~~')
1055
- // Replace <br> tags with temporary marker (~~~)
1056
- .replace(/<br\s*\/?>/gi, '~~~')
1057
- // Remove all other tags
1058
- .replace(/<[^>]+>/g, '')
1059
- // Convert markers to specified delimiter
1060
- .replace(/~~~+/g, delimiter)
1061
- // Trim and clean whitespace
1062
- .trim();
1063
-
1064
- // Special handling for empty delimiter
1065
- if (delimiter === '') {
1066
- // Collapse all whitespace to single space
1067
- text = text.replace(/\s+/g, ' ');
1068
- } else {
1069
-
1070
-
1071
- // Collapse multiple delimiters to single
1072
- text = text.replace(new RegExp(`${escapeRegExp(delimiter)}+`, 'g'), delimiter);
1073
- // Remove leading/trailing delimiters
1074
- text = text.replace(new RegExp(`^${escapeRegExp(delimiter)}|${escapeRegExp(delimiter)}$`, 'g'), '');
1075
- }
1076
-
1077
- return text;
1078
- }
1079
-
1080
-
1081
- function escapeRegExp(string) {
1082
- return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1083
- }
1084
-
1085
-
1086
-
1087
- ;// ./lib/models/templateCompiler/helpers/_toLowerCase.js
1088
-
1089
-
1090
- function _toLowerCase(data, args) {
1091
- if (args !== undefined) {
1092
- throw new TemplateCompilerException(`_toLowerCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: ${args.join(', ')}`)
1093
- }
1094
- if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
1095
- return null
1096
- }
1097
- return String(data).toLowerCase()
1098
- }
1099
-
1100
-
1101
-
1102
- ;// ./lib/models/templateCompiler/helpers/_toUpperCase.js
1103
-
1104
-
1105
- function _toUpperCase(data, args) {
1106
- if (typeof data !== 'string') {
1107
- throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the data must be string: ${data}`)
1108
- }
1109
- if (args !== undefined) {
1110
- throw new TemplateCompilerException(`_toUpperCase: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException}: the argument must be empty: ${args.join(', ')}`)
1111
- }
1112
- if (data === null || (typeof data === 'undefined') || typeof data !== 'string') {
1113
- return null
1114
- }
1115
- return String(data).toUpperCase()
1116
- }
1117
-
1118
-
1119
-
1120
- ;// ./lib/models/templateCompiler/helpers/index.js
1121
-
1122
-
1123
-
1124
-
1125
-
1126
-
1127
-
1128
-
1129
-
1130
-
1131
-
1132
-
1133
-
1134
-
1135
-
1136
-
1137
-
1138
-
1139
-
1140
-
1141
-
1142
-
1143
-
1144
- ;// ./lib/models/templateCompiler/templateCompiler.js
1145
-
1146
-
1147
-
1148
-
1149
- class TemplateCompiler {
1150
- constructor(data) {
1151
- this.data = data
1152
- }
1153
- static init(options) {
1154
- return new this(options)
1155
- }
1156
- static initFromArray(arr = []) {
1157
- if (Array.isArray(arr)) {
1158
- return arr.map((a) => this.init(a))
1159
- }
1160
- return []
1161
- }
1162
- static initOnlyValidFromArray(arr = []) {
1163
- return this.initFromArray(arr).filter((i) => i)
1164
- }
1165
- static concatIf(data, args) {
1166
- return _concatIf(data, args)
1167
- }
1168
- static divide(data, args) {
1169
- return _divide(data, args)
1170
- }
1171
- static eq(data, args) {
1172
- return _eq(data, args)
1173
- }
1174
-
1175
- static filterAll(data, args) {
1176
- return _filterAll(data, args)
1177
- }
1178
-
1179
- static formatDate(data, args) {
1180
- return _formatDate(data, args)
1181
- }
1182
- static get(data, key, failover = null) {
1183
- return _get(data, key, failover)
1184
- }
1185
- static gt(data, args) {
1186
- return _gt(data, args)
1187
- }
1188
- static gte(data, args) {
1189
- return _gte(data, args)
1190
- }
1191
- static isEmpty(data, args) {
1192
- return _isEmpty(data, args)
1193
- }
1194
- static isNotEmpty(data, args) {
1195
- return _isNotEmpty(data, args)
1196
- }
1197
- static join(data, separator = '') {
1198
- return _join(data, separator)
1199
- }
1200
- static lt(data, args) {
1201
- return _lt(data, args)
1202
- }
1203
- static lte(data, args) {
1204
- return _lte(data, args)
1205
- }
1206
- static map(data, args = []) {
1207
- return _map(data, args)
1208
- }
1209
- static neq(data, args) {
1210
- return _neq(data, args)
1211
- }
1212
- static removeHtml(data, args) {
1213
- return _removeHtml(data, args)
1214
- }
1215
- static toLowerCase(data, args) {
1216
- return _toLowerCase(data, args)
1217
- }
1218
- static toUpperCase(data, args) {
1219
- return _toUpperCase(data, args)
1220
- }
1221
- static parseFunction(expression) {
1222
- return _parseFunction(expression, _FN_NAMES)
1223
- }
1224
- static parseParams(parameters) {
1225
- return _parseParams(parameters)
1226
- }
1227
-
1228
- pipe(expression = '') {
1229
- this.delimiters = expression.substring(0, 2) === '{{' ? TAGS_HANDLEBAR : TAGS_EJS
1230
- const regex = new RegExp(`${this.delimiters[0]}\\s(.*?)\\s${this.delimiters[1]}`)
1231
- const match = expression.match(regex)
1232
- if (match !== null) {
1233
- try {
1234
- const functionList = _parseFunction(match[1], _FN_NAMES)
1235
- return functionList.reduce((acc, fn) => {
1236
- return _callFunction(acc, fn.name, fn.args)
1237
- }, this.data)
1238
- } catch (e) {
1239
- throw new TemplateCompilerException(`TemplateCompiler engine error: ${e.message}`)
1240
- }
1241
- }
1242
- throw new TemplateCompilerException(`TemplateCompiler engine error: ${TEMPLATE_COMPILER_EXCEPTION_TYPE.invalidRegExpException}`)
1243
- }
1244
- }
1245
-
1246
- function _parseFunction(expression, existFunctionNames) {
1247
- const regExp = new RegExp(/(\w+)\(([^)]*)\)/)
1248
- let parts
1249
- if (expression.includes('|')) {
1250
- parts = expression.split('|')
1251
- } else {
1252
- parts = [expression]
1253
- }
1254
- return parts.reduce((acc, part) => {
1255
- const match = part.match(regExp)
1256
- if (match !== null) {
1257
- const functionName = match[1]
1258
- const parameters = match[2]
1259
- const paramList = _parseParams(parameters)
1260
- if (existFunctionNames.includes(functionName)) {
1261
- acc.push({
1262
- name: functionName,
1263
- args: paramList
1264
- })
1265
- } else {
1266
- throw new TemplateCompilerException(`${functionName} is not a valid function`)
1267
- }
1268
- }
1269
- return acc
1270
- }, [])
1271
- }
1272
-
1273
- function _parseParams(parameters) {
1274
- const _parameters = parameters.trim()
1275
- const regExp = new RegExp(/^[^\w\d\s]+$/)
1276
- const match = _parameters.match(regExp)
1277
- if (match !== null) {
1278
- return [_parameters.substring(1, _parameters.length - 1)]
1279
- }
1280
- if (_parameters.includes(',')) {
1281
- // 用正则表达式匹配逗号,但忽略方括号中的逗号
1282
- const parts = _splitIgnoringBrackets(_parameters)
1283
- return parts.map((part) => _parseSinglePart(part))
1284
- }
1285
- return [_parseSinglePart(_parameters)]
1286
- }
1287
-
1288
- function _splitIgnoringBrackets(input) {
1289
- const regExp2 = new RegExp(/^\d+(\.\d+)?$/)
1290
- const regExp = new RegExp(/(?![^\[]*\])\s*,\s*/)
1291
- const parts = input.split(regExp)
1292
- return parts.map((part) => {
1293
- const _part = part.trim()
1294
- if (_part !== '' && !!_part.match(regExp2)) {
1295
- // 如果是数字,转换为 num 类型
1296
- return Number.isNaN(_part) ? _part : parseInt(_part, 10)
1297
- }
1298
- // 否则当作字符串处理
1299
- return _part
1300
- })
1301
- }
1302
-
1303
- function _parseSinglePart(input) {
1304
- if (typeof input === 'string') {
1305
- if (input.startsWith('"') && input.endsWith('"')) {
1306
- // 去掉双引号,返回
1307
- return input.substring(1, input.length - 1)
1308
- }
1309
- if (input.startsWith("'") && input.endsWith("'")) {
1310
- // 去掉双引号,返回
1311
- return input.substring(1, input.length - 1)
1312
- }
1313
-
1314
- const _input = _toBasicType(input)
1315
-
1316
- if (typeof _input !== 'string') {
1317
- return _input
1318
- }
1319
-
1320
- // 如果是一个列表形式(例如 ["p", "d"] 或 [p, d])
1321
- if (_input.startsWith('[') && _input.endsWith(']')) {
1322
- const listContent = _input.substring(1, _input.length - 1).trim()
1323
- if (listContent !== '') {
1324
- return listContent.split(',').map((item) => {
1325
- return _toBasicType(item.trim())
1326
- })
1327
- }
1328
- return []
1329
- }
1330
- return input
1331
- }
1332
- return input
1333
- }
1334
-
1335
- function _toBasicType(input) {
1336
- if (input.startsWith('"') && input.endsWith('"')) {
1337
- // 去掉双引号,返回
1338
- return input.substring(1, input.length - 1)
1339
- }
1340
- if (input.startsWith("'") && input.endsWith("'")) {
1341
- // 去掉双引号,返回
1342
- return input.substring(1, input.length - 1)
1343
- }
1344
- if (input === 'true') {
1345
- return true
1346
- }
1347
- if (input === 'false') {
1348
- return false
1349
- }
1350
- if (input === 'undefined') {
1351
- return undefined
1352
- }
1353
- if (input === 'null') {
1354
- return null
1355
- }
1356
- if (!Number.isNaN(input) && !Number.isNaN(Number.parseFloat(input))) {
1357
- return Number(input)
1358
- }
1359
- return input
1360
- }
1361
-
1362
- function _callFunction(data, functionName, parameters) {
1363
- try {
1364
- let failover
1365
- switch (functionName) {
1366
- case 'concatIf':
1367
- return _concatIf(data, parameters)
1368
- case 'divide':
1369
- return _divide(data, parameters)
1370
- case 'eq':
1371
- return _eq(data, parameters)
1372
- case 'exec':
1373
- return _exec(data, parameters)
1374
- case 'filterAll':
1375
- return _filterAll(data, parameters)
1376
- case 'filterOne':
1377
- return _filterOne(data, parameters)
1378
- case 'formatDate':
1379
- return _formatDate(data, parameters)
1380
- case 'get':
1381
- if (parameters.length > 2) {
1382
- throw new TemplateCompilerException(TEMPLATE_COMPILER_EXCEPTION_TYPE.argumentFormatException)
1383
- }
1384
- if (parameters.length === 2) {
1385
- failover = parameters[parameters.length - 1]
1386
- }
1387
- return _get(data, parameters[0], failover)
1388
- case 'gt':
1389
- return _gt(data, parameters)
1390
- case 'gte':
1391
- return _gte(data, parameters)
1392
- case 'isEmpty':
1393
- return _isEmpty(data, parameters)
1394
- case 'isNotEmpty':
1395
- return _isNotEmpty(data, parameters)
1396
- case 'join':
1397
- return _join(data, parameters[0])
1398
- case 'lt':
1399
- return _lt(data, parameters)
1400
- case 'lte':
1401
- return _lte(data, parameters)
1402
- case 'map':
1403
- return _map(data, parameters)
1404
- case 'neq':
1405
- return _neq(data, parameters)
1406
- case 'removeHtml':
1407
- return _removeHtml(data, parameters)
1408
- case 'toLowerCase':
1409
- return _toLowerCase(data)
1410
- case 'toUpperCase':
1411
- return _toUpperCase(data)
1412
- default:
1413
- throw new Error(`${functionName} is not a valid function`)
1414
- }
1415
- } catch (e) {
1416
- throw e
1417
- }
1418
- }
1419
-
1420
-
1421
-
1422
- ;// ./lib/models/templateCompiler/index.js
1423
-
1424
-
1425
-
1426
-
1427
- ;// ./lib/helpers/concatStringByArray/concatStringByArray.js
1428
-
1429
-
1430
-
1431
-
1432
-
1433
- function concatStringByArray(arrTemplate, data) {
1434
- return arrTemplate.reduce((acc, item) => {
1435
- const { type, value = '', restriction, template, format, showMinutes } = item
1436
- switch (type) {
1437
- case('array'): {
1438
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1439
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || []
1440
- acc += _value.reduce((_acc, item) => {
1441
- return _acc += concatStringByArray(template, item)
1442
- }, '')
1443
- }
1444
- break
1445
- }
1446
- case ('date'): {
1447
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1448
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1449
- acc += (formatDate(_value, format).toString())
1450
- }
1451
- break
1452
- }
1453
- case('ellipsis'): {
1454
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1455
- const { maxLength } = item
1456
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1457
- if (_value.length <= maxLength) {
1458
- acc += (_value.toString())
1459
- } else {
1460
- acc += `${_value.substr(0, maxLength)}...`
1461
- }
1462
- }
1463
- break
1464
- }
1465
- case('group'): {
1466
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1467
- return concatStringByArray(value, data)
1468
- }
1469
- break
1470
- }
1471
- case('label'): {
1472
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1473
- acc += (value.toString())
1474
- }
1475
- break
1476
- }
1477
- case ('templateCompiler'): {
1478
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1479
- const templateCompiler = new TemplateCompiler({ data })
1480
- acc += templateCompiler.pipe(value)
1481
- }
1482
- break
1483
- }
1484
- case('value'): {
1485
- if (getValidation(restriction, data, getValueByKeys_getValueByKeys)) {
1486
- const _value = getValueByKeys_getValueByKeys(value.split('.'), data) || ''
1487
- acc += (_value.toString())
1488
- }
1489
- break
1490
- }
1491
- }
1492
- return acc
1493
- }, '')
1494
- }
1495
- /* harmony default export */ const concatStringByArray_concatStringByArray = ({
1496
- concatStringByArray
1497
- });
1498
-
1499
-
1500
-
1501
- ;// ./lib/helpers/concatStringByArray/index.js
1502
-
1503
-
1504
- ;// ./lib/helpers/convertString/convertString.js
1505
-
1506
-
1507
- function convertString(string, patternMatch = /\$\{(.+?)\}/g, value, getValueByKeys) {
1508
- if (!string) {
1509
- return ''
1510
- }
1511
- let _getValueByKeys = typeof getValueByKeys === 'function' ? getValueByKeys : getValueByKeys_getValueByKeys
1512
- const reg = new RegExp(patternMatch, 'g')
1513
- return string.replace(reg, (match, key) => {
1514
- const result = _getValueByKeys({ keys: key.split('.'), obj: value })
1515
- if (result === null || result === undefined) {
1516
- return ''
1517
- }
1518
- return typeof result === 'object' ? JSON.stringify(result) : result
1519
- })
1520
- }
1521
-
1522
- /* harmony default export */ const convertString_convertString = ({
1523
- convertString
1524
- });
1525
-
1526
-
1527
- ;// ./lib/helpers/convertString/index.js
1528
-
1529
-
1530
- ;// ./lib/helpers/escapeRegex/escapeRegex.js
1531
- function escapeRegex(string) {
1532
- return String(string).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
1533
- }
1534
-
1535
- ;// ./lib/helpers/escapeRegex/index.js
1536
-
1537
-
1538
- ;// ./lib/helpers/expressHelper/customHandler.js
1539
- function customHandler({ responseHelper, handler, ignoreError = false }) {
1540
- return async (req, res, next) => {
1541
- try {
1542
- await handler({ req, res })
1543
- await next()
1544
- } catch (err) {
1545
- if (ignoreError) {
1546
- await next()
1547
- } else {
1548
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1549
- }
1550
- }
1551
- }
1552
- }
1553
-
1554
- ;// ./lib/helpers/expressHelper/findAllResult.js
1555
- function findAllResult({ responseHelper, service }) {
1556
- return async (req, res, next) => {
1557
- try {
1558
- const { query } = req
1559
- const result = await service.findAll({ query })
1560
- res.locals.findAllResult = result
1561
- await next()
1562
- } catch (err) {
1563
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1564
- }
1565
- }
1566
- }
1567
-
1568
- ;// ./lib/helpers/expressHelper/findOneResult.js
1569
- function findOneResult({ responseHelper, service }) {
1570
- return async (req, res, next) => {
1571
- try {
1572
- const { params, query } = req
1573
- const { id } = params
1574
- const result = await service.findOne({
1575
- query: {
1576
- ...query,
1577
- id
1578
- }
1579
- })
1580
- res.locals.findOneResult = result
1581
- await next()
1582
- } catch (err) {
1583
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1584
- }
1585
- }
1586
- }
1587
-
1588
- ;// ./lib/helpers/expressHelper/postResult.js
1589
- function postResult({ responseHelper, service }) {
1590
- return async (req, res, next) => {
1591
- try {
1592
- const { body } = req
1593
- let result
1594
- if (Array.isArray(body)) {
1595
- result = await service.saveAll({ docs: body })
1596
- } else {
1597
- result = await service.saveOne({ doc: body })
1598
- }
1599
- res.locals.postResult = result
1600
- await next()
1601
- } catch (err) {
1602
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1603
- }
1604
- }
1605
- }
1606
-
1607
- ;// ./lib/helpers/expressHelper/updateOneResult.js
1608
- function updateOneResult({ responseHelper, service }) {
1609
- return async (req, res, next) => {
1610
- try {
1611
- const { body, params } = req
1612
- const { id } = params
1613
- if (id !== body.id) {
1614
- throw new Error('id in params and body must be same')
1615
- }
1616
- const { data } = await service.findOne({ query: { id } })
1617
- const doc = data[0]
1618
- doc.update(body)
1619
- const result = await service.saveOne({ doc })
1620
- res.locals.updateOneResult = result
1621
- await next()
1622
- } catch (err) {
1623
- res.status(400).json(responseHelper.standardizeResponse({ err, message: err.message || err }))
1624
- }
1625
- }
1626
- }
1627
-
1628
- ;// ./lib/helpers/expressHelper/index.js
1629
-
1630
-
1631
-
1632
-
1633
-
1634
-
1635
-
1636
- const expressHelper = {
1637
- customHandler: customHandler,
1638
- findAllResult: findAllResult,
1639
- findOneResult: findOneResult,
1640
- postResult: postResult,
1641
- updateOneResult: updateOneResult,
1642
- }
1643
-
1644
- ;// ./lib/helpers/extractEmails/extractEmails.js
1645
- /**
1646
- * Extracts and normalizes unique email addresses from an array containing messy entries
1647
- * @param {Array} dirtyArray - Array that may contain emails in various formats (may include null/empty entries)
1648
- * @returns {Array} Sorted array of unique, lowercase email addresses
1649
- */
1650
- function extractEmails(dirtyArray) {
1651
- const emailRegex = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g
1652
- const emails = new Set()
1653
-
1654
- // Handle null/undefined input array
1655
- if (!dirtyArray) return []
1656
-
1657
- dirtyArray.forEach(entry => {
1658
- // Skip null, undefined, empty, or whitespace-only entries
1659
- if (!entry || typeof entry !== 'string' || !entry.trim()) return
1660
-
1661
- try {
1662
- const cleanEntry = entry
1663
- .replace(/[\u200B-\u200D\uFEFF\u202A-\u202E]/g, '') // Remove hidden chars
1664
- .replace(/[<>]/g, ' ') // Convert email delimiters to spaces
1665
- .replace(/\s+/g, ' ') // Collapse multiple whitespace
1666
- .trim()
1667
-
1668
- // Extract all email matches
1669
- const matches = cleanEntry.match(emailRegex)
1670
- if (matches) {
1671
- matches.forEach(email => emails.add(email.toLowerCase())) // Normalize to lowercase
1672
- }
1673
- } catch (e) {
1674
- console.warn('Failed to process entry:', entry, e)
1675
- }
1676
- })
1677
-
1678
- // Convert Set to array and sort alphabetically
1679
- return Array.from(emails).sort((a, b) => a.localeCompare(b))
1680
- }
1681
-
1682
- ;// ./lib/helpers/extractEmails/index.js
1683
-
1684
-
1685
- ;// ./lib/helpers/objectHelper/objectHelper.js
1686
- const objectHelper = {
1687
- get(obj, path) {
1688
- const parts = path.split('.')
1689
- return parts.reduce((acc, part) => {
1690
- if (part.endsWith('[]')) {
1691
- // 处理数组遍历
1692
- const key = part.slice(0, -2) // 去掉 '[]' 得到属性名
1693
- if (Array.isArray(acc[key])) {
1694
- return acc[key] // 返回整个数组
1695
- }
1696
- return [] // 如果不是数组,返回空数组
1697
- }
1698
- if (part.includes('[') && part.includes(']')) {
1699
- // 处理数组索引
1700
- const arrayMatch = part.match(/(\w+)\[(\d+)\]/)
1701
- if (arrayMatch) {
1702
- const key = arrayMatch[1]
1703
- const index = arrayMatch[2]
1704
- return acc && acc[key] && acc[key][index]
1705
- }
1706
- } else if (acc && Array.isArray(acc)) {
1707
- // 如果当前值是数组,提取每个对象的指定属性
1708
- return acc.map((item) => item[part])
1709
- } else {
1710
- // 处理普通属性
1711
- return acc && acc[part]
1712
- }
1713
- }, obj)
1714
- },
1715
- merge,
1716
- set(obj, path, value) {
1717
- const parts = path.split('.');
1718
- let current = obj;
1719
-
1720
- // 处理所有中间部分
1721
- for (let i = 0; i < parts.length - 1; i++) {
1722
- const part = parts[i];
1723
- let key, index;
1724
-
1725
- // 检查是否是数组索引格式,如key[0]
1726
- const arrayMatch = part.match(/^(\w+)\[(\d+)\]$/);
1727
- if (arrayMatch) {
1728
- key = arrayMatch[1];
1729
- index = parseInt(arrayMatch[2], 10);
1730
- // 确保当前层级的数组存在
1731
- if (!current[key] || !Array.isArray(current[key])) {
1732
- current[key] = [];
1733
- }
1734
- // 扩展数组到足够大
1735
- while (current[key].length <= index) {
1736
- current[key].push(undefined);
1737
- }
1738
- // 如果当前位置未定义或为null,初始化为对象
1739
- if (current[key][index] == null) {
1740
- current[key][index] = {};
1741
- }
1742
- current = current[key][index];
1743
- } else {
1744
- // 处理普通属性
1745
- if (!current[part]) {
1746
- current[part] = {};
1747
- }
1748
- current = current[part];
1749
- }
1750
- }
1751
-
1752
- // 处理最后一部分
1753
- const lastPart = parts[parts.length - 1];
1754
- const arrayMatch = lastPart.match(/^(\w+)\[(\d+)\]$/);
1755
- if (arrayMatch) {
1756
- const key = arrayMatch[1];
1757
- const index = parseInt(arrayMatch[2], 10);
1758
- // 确保数组存在
1759
- if (!current[key] || !Array.isArray(current[key])) {
1760
- current[key] = [];
1761
- }
1762
- // 扩展数组到所需索引
1763
- while (current[key].length <= index) {
1764
- current[key].push(undefined);
1765
- }
1766
- current[key][index] = value;
1767
- } else {
1768
- current[lastPart] = value;
1769
- }
1770
- }
1771
- }
1772
-
1773
- function merge(target, ...sources) {
1774
- if (!sources.length) return target
1775
-
1776
- const source = sources.shift() // 取出第一个源对象
1777
-
1778
- if (_isObject(target) && _isObject(source)) {
1779
- for (const key in source) {
1780
- if (_isObject(source[key])) {
1781
- if (!target[key]) {
1782
- // 如果目标对象没有该属性,创建一个空对象
1783
- target[key] = {}
1784
- }
1785
- // 递归合并
1786
- merge(target[key], source[key])
1787
- } else {
1788
- // 直接覆盖
1789
- target[key] = source[key]
1790
- }
1791
- }
1792
- }
1793
-
1794
- // 继续合并剩余的源对象
1795
- return merge(target, ...sources)
1796
- }
1797
-
1798
- function _isObject(obj) {
1799
- return obj && typeof obj === 'object' && !Array.isArray(obj)
1800
- }
1801
-
1802
-
1803
-
1804
- ;// ./lib/helpers/objectHelper/index.js
1805
-
1806
-
1807
-
1808
-
1809
- ;// ./lib/helpers/pReduce/pReduce.js
1810
- async function pReduce(iterable, reducer, initialValue) {
1811
- return new Promise((resolve, reject) => {
1812
- const iterator = iterable[Symbol.iterator]()
1813
- let index = 0
1814
-
1815
- const next = async total => {
1816
- const element = iterator.next()
1817
-
1818
- if (element.done) {
1819
- resolve(total)
1820
- return
1821
- }
1822
-
1823
- try {
1824
- const [resolvedTotal, resolvedValue] = await Promise.all([total, element.value])
1825
- next(reducer(resolvedTotal, resolvedValue, index++))
1826
- } catch (error) {
1827
- reject(error)
1828
- }
1829
- }
1830
-
1831
- next(initialValue)
1832
- })
1833
- }
1834
-
1835
-
1836
-
1837
- ;// ./lib/models/repo/repo.js
1838
-
1839
-
1840
- class Repo {
1841
- constructor(options) {
1842
- options = options || {}
1843
- this.model = options.model
1844
- this._sharedOptions = options._sharedOptions // { session: this.dbTransaction }
1845
- this._queryOptions = options._queryOptions
1846
- this._saveOptions = options._saveOptions
1847
- this._Class = options._constructor && options._constructor._Class
1848
- ? options._constructor._Class
1849
- : null
1850
- }
1851
- static init(options = {}) {
1852
- return init(this, options)
1853
- }
1854
- static get _classname() {
1855
- return 'Repo'
1856
- }
1857
- static get _superclass() {
1858
- return 'Repo'
1859
- }
1860
-
1861
- get _classname() {
1862
- return 'Repo'
1863
- }
1864
-
1865
- get _superclass() {
1866
- return 'Repo'
1867
- }
1868
-
1869
- get isValid() {
1870
- return this.model
1871
- && (typeof this.model.deleteOne === 'function')
1872
- && (typeof this.model.findAll === 'function')
1873
- && (typeof this.model.saveOne === 'function')
1874
- }
1875
-
1876
- get queryOptions() {
1877
- return {
1878
- ...this._sharedOptions,
1879
- ...this._queryOptions,
1880
- }
1881
- }
1882
-
1883
- get saveOptions() {
1884
- return {
1885
- ...this._sharedOptions,
1886
- ...this._saveOptions,
1887
- }
1888
- }
1889
-
1890
- init(options) {
1891
- if (this._Class && typeof this._Class.init === 'function') {
1892
- return this._Class.init(options)
1893
- }
1894
- return options
1895
- }
1896
-
1897
- async deleteOne({ id }) {
1898
- try {
1899
- const result = await this.model.deleteOne({ _id: id })
1900
- return {
1901
- ...result, // { message: 'ok', total }
1902
- isNew: false,
1903
- data: []
1904
- }
1905
- } catch (err) {
1906
- throw err
1907
- }
1908
- }
1909
-
1910
- // systemLog is optional
1911
- findAll({ query, systemLog }) {
1912
- const log = _makeLog({
1913
- systemLog,
1914
- label: 'REPO_READ',
1915
- message: `fn ${this._classname}.prototype.findAll`,
1916
- input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1917
- })
1918
- return new Promise((resolve, reject) => {
1919
- this.model.findAll(query, this.queryOptions, (err, data, total) => {
1920
- if (err) {
1921
- log({ level: 'warn', output: err.toString() })
1922
- reject(err)
1923
- } else {
1924
- const result = {
1925
- isNew: false,
1926
- data,
1927
- total: total || data.length
1928
- }
1929
- log({ level: 'info', output: { ...result } })
1930
- resolve(result)
1931
- }
1932
- })
1933
- })
1934
- }
1935
-
1936
- findOne({ query, systemLog }) {
1937
- const log = _makeLog({
1938
- systemLog,
1939
- label: 'REPO_READ',
1940
- message: `fn ${this._classname}.prototype.findOne`,
1941
- input: [{ query: { ...query }, systemLog: { ...systemLog } }]
1942
- })
1943
- return new Promise((resolve, reject) => {
1944
- this.model.findAll(query, this.queryOptions, (err, data) => {
1945
- if (err) {
1946
- reject(err)
1947
- } else if (data.length === 1) {
1948
- const result = {
1949
- isNew: false,
1950
- data,
1951
- total: 1
1952
- }
1953
- log({ level: 'info', output: { ...result } })
1954
- resolve(result)
1955
- } else if (data.length === 0) {
1956
- reject(new Error('record not found'))
1957
- } else {
1958
- reject(new Error('more than one is found'))
1959
- }
1960
- })
1961
- })
1962
- .catch((err) => {
1963
- log({ level: 'warn', output: err.toString() })
1964
- throw err
1965
- })
1966
- }
1967
-
1968
- saveAll({ config = {}, docs, systemLog }) {
1969
- let isNew
1970
- const log = _makeLog({
1971
- systemLog,
1972
- label: 'REPO_WRITE',
1973
- message: `fn ${this._classname}.prototype.saveAll`,
1974
- input: [{ config, docs: [...docs], systemLog: { ...systemLog } }]
1975
- })
1976
- const promise = typeof this.model.saveAll === 'function'
1977
- ? this.model.saveAll({ config, docs })
1978
- : Promise.all(docs.map(async (doc) => {
1979
- if (doc) {
1980
- const result = await this.saveOne({ config, doc })
1981
- isNew = result.isNew
1982
- const _data = result._data || result.data
1983
- return _data[0]
1984
- }
1985
- return null
1986
- }))
1987
- return promise.then((savedData) => {
1988
- if (savedData.length !== 1) isNew = null
1989
- const result = {
1990
- data: savedData,
1991
- isNew,
1992
- total: savedData.length
1993
- }
1994
- log({ level: 'info', output: { ...result } })
1995
- return result
1996
- }).catch((err) => {
1997
- log({ level: 'warn', output: err.toString() })
1998
- throw err
1999
- })
2000
- }
2001
-
2002
- saveOne({ config = {}, doc, systemLog }) {
2003
- const log = _makeLog({
2004
- systemLog,
2005
- label: 'REPO_WRITE',
2006
- message: `fn ${this._classname}.prototype.saveOne`,
2007
- input: [{ config, doc: { ...doc }, systemLog: { ...systemLog } }]
2008
- })
2009
- const saveOptions = {
2010
- ...this.saveOptions,
2011
- ...config,
2012
- }
2013
- return new Promise((resolve, reject) => {
2014
- this.model.saveOne(doc, saveOptions, (err, result) => {
2015
- if (err) {
2016
- log({ level: 'warn', output: err.toString() })
2017
- reject(err)
2018
- } else {
2019
- log({ level: 'info', output: { ...result } })
2020
- resolve(result)
2021
- }
2022
- })
2023
- })
2024
- }
2025
- }
2026
-
2027
- function _makeLog({ systemLog, label, message: message1, input } = {}) {
2028
- return ({ level, messgae: massage2, output } = {}) => {
2029
- if (systemLog && systemLog.systemLogHelper) {
2030
- systemLog.systemLogHelper.log({
2031
- batchId: systemLog.batchId,
2032
- label,
2033
- level,
2034
- message: massage2 || message1,
2035
- data: {
2036
- payload: {
2037
- input,
2038
- output
2039
- }
2040
- }
2041
- })
2042
- }
2043
- }
2044
- }
2045
-
2046
-
2047
-
2048
- ;// ./lib/models/repo/index.js
2049
-
2050
-
2051
-
2052
-
2053
- ;// ./lib/models/apiResponse/apiResponse.js
2054
- class ApiResponse {
2055
- constructor(options = {}) {
2056
- options = options || {}
2057
- this._data = options.data || options._data || []
2058
- this.err = options.err
2059
- this.isNew = options.isNew || false
2060
- this.message = options.message
2061
- this.total = options.total || 0
2062
- this._instanceBuilder = options._instanceBuilder
2063
- }
2064
-
2065
- static init(options = {}) {
2066
- if (options instanceof this) {
2067
- return options
2068
- }
2069
- const instance = new this(options)
2070
- return instance
2071
- }
2072
- static get _classname() {
2073
- return 'ApiResponse'
2074
- }
2075
- static get _superclass() {
2076
- return 'ApiResponse'
2077
- }
2078
-
2079
- // getters
2080
- get data() {
2081
- if (this._instanceBuilder && (typeof this._instanceBuilder === 'function')) {
2082
- return this._data.map(this._instanceBuilder)
2083
- }
2084
- return this._data
2085
- }
2086
- }
2087
-
2088
-
2089
-
2090
- ;// ./lib/models/apiResponse/makeApiResponse.js
2091
-
2092
-
2093
- function makeApiResponse({ repo, result }) {
2094
- return ApiResponse.init({
2095
- ...result,
2096
- _instanceBuilder: (i) => {
2097
- return repo.init(i)
2098
- }
2099
- })
2100
- }
2101
-
2102
-
2103
-
2104
- ;// ./lib/models/service/service.js
2105
-
2106
-
2107
-
2108
- class Service {
2109
- constructor({ repo }) {
2110
- this.repo = repo
2111
- }
2112
-
2113
- static get _classname() {
2114
- return 'Service'
2115
- }
2116
- static get _superclass() {
2117
- return 'Service'
2118
- }
2119
-
2120
- deleteOne({ id }) {
2121
- return this.repo.deleteOne({ id })
2122
- .catch(() => {
2123
- throw new Error(`Not found for query: ${id}`)
2124
- })
2125
- }
2126
-
2127
- async findAll({ query = {}, systemLog } = {}) {
2128
- const result = await this.repo.findAll({ query, systemLog })
2129
- return makeApiResponse({
2130
- repo: this.repo,
2131
- result
2132
- })
2133
- }
2134
-
2135
- async findOne({ query = {}, systemLog } = {}) {
2136
- const result = await this.repo.findOne({ query, systemLog })
2137
- return makeApiResponse({
2138
- repo: this.repo,
2139
- result
2140
- })
2141
- }
2142
-
2143
- init(options) {
2144
- return this.repo.init(options)
2145
- }
2146
- initFromArray(arr = []) {
2147
- if (Array.isArray(arr)) {
2148
- return arr.map((a) => this.init(a))
2149
- }
2150
- return []
2151
- }
2152
- initOnlyValidFromArray(arr = []) {
2153
- return this.initFromArray(arr).filter((i) => i)
2154
- }
2155
-
2156
- async saveAll({ config = {}, docs = [], systemLog } = {}) {
2157
- const copies = docs.map((doc) => {
2158
- return config.skipInit ? doc : this.init(doc)
2159
- })
2160
- const result = await this.repo.saveAll({ config, docs: copies, systemLog })
2161
- return makeApiResponse({
2162
- repo: this.repo,
2163
- result
2164
- })
2165
- }
2166
-
2167
- // set skipInit to true if we want to use POST for query
2168
- async saveOne({ config = {}, doc = {}, systemLog } = {}) {
2169
- const copy = config.skipInit ? doc : this.init(doc)
2170
- if (copy) {
2171
- const result = await this.repo.saveOne({ config, doc: copy, systemLog })
2172
- return makeApiResponse({
2173
- repo: this.repo,
2174
- result
2175
- })
2176
- }
2177
- return {
2178
- isNew: null,
2179
- data: [],
2180
- err: new Error('doc is not a valid instance')
2181
- }
2182
- }
2183
- }
2184
-
2185
- function makeService({ repo }) {
2186
- if (repo === undefined) {
2187
- throw new Error('repo is required.')
2188
- }
2189
- if (repo._superclass !== Repo._superclass) {
2190
- throw new Error('repo is not an instance of Repo.')
2191
- }
2192
- return new Service({ repo })
2193
- }
2194
-
2195
-
2196
-
2197
- ;// ./lib/models/service/index.js
2198
-
2199
-
2200
-
2201
-
2202
- ;// ./lib/helpers/generalPost/generalPost.js
2203
-
2204
-
2205
-
2206
-
2207
-
2208
- async function generalPost({ body = {}, GeneralModel, UniqueKeyGenerator, resourceInfo }) {
2209
- const { resources, data, globalShared = {}, shared = {}, relationship = {} } = body
2210
- const _resourceInfo = resourceInfo || body.resourceInfo
2211
- _attachShared(data, globalShared, shared)
2212
- const obj = await pReduce(resources, async (acc, resource) => {
2213
- const service = _makeService(resource, _resourceInfo, UniqueKeyGenerator, GeneralModel)
2214
- _createRelationship(data, relationship[resource], acc)
2215
- const _data = data[resource]
2216
- const result = await service.saveAll({ docs: [].concat(_data) })
2217
- acc[resource] = Array.isArray(_data) ? result._data : result._data[0]
2218
- return acc
2219
- }, {})
2220
- return obj
2221
- }
2222
-
2223
- function _attachShared(data, globalShared = {}, shared = {}) {
2224
- Object.keys(shared).forEach((key) => {
2225
- const _data = data[key]
2226
- if (Array.isArray(_data)) {
2227
- data[key] = _data.map((_dataItem) => {
2228
- return objectHelper.merge({}, _dataItem, globalShared, shared[key] || {})
2229
- })
2230
- } else {
2231
- data[key] = objectHelper.merge({}, _data, globalShared, shared[key] || {})
2232
- }
2233
- })
2234
- }
2235
-
2236
- function _createRelationship(data, relationship = {}, object) {
2237
- Object.keys(relationship).forEach((key) => {
2238
- const path = relationship[key]
2239
- const val = objectHelper.get(object, path)
2240
- objectHelper.set(data, key, val)
2241
- })
2242
- }
2243
-
2244
- function _makeService(resource, resourceInfo, UniqueKeyGenerator, GeneralModel) {
2245
- const { collectionName, fields } = resourceInfo[resource]
2246
- const uniqueKeyGenerator = UniqueKeyGenerator.makeGenerator(fields)
2247
- const model = new GeneralModel({ collectionName, uniqueKeyGenerator })
2248
- return makeService({
2249
- repo: new Repo({ model })
2250
- })
2251
- }
2252
-
2253
-
2254
-
2255
- ;// ./lib/helpers/generalPost/index.js
2256
-
2257
-
2258
-
2259
-
2260
- ;// ./lib/helpers/init/init.js
2261
- function init(_class, options) {
2262
- if (options instanceof _class) {
2263
- return options
2264
- }
2265
- try {
2266
- const instance = new _class(options)
2267
- return instance.isValid !== false ? instance : null
2268
- } catch (e) {
2269
- console.log(`init failed for class: ${_class._classname || 'no _classname'}`, e)
2270
- return null
2271
- }
2272
- }
2273
-
2274
- ;// ./lib/helpers/init/index.js
2275
-
2276
-
2277
- ;// ./lib/helpers/initFromArray/initFromArray.js
2278
-
2279
-
2280
- function initFromArray(_class, arr) {
2281
- if (Array.isArray(arr)) {
2282
- return arr.map((a) => init(_class, a))
2283
- }
2284
- return []
2285
- }
2286
-
2287
- ;// ./lib/helpers/initFromArray/index.js
2288
-
2289
-
2290
- ;// ./lib/helpers/initOnlyValidFromArray/initOnlyValidFromArray.js
2291
-
2292
-
2293
- function initOnlyValidFromArray(_class, arr) {
2294
- return initFromArray(_class, arr).filter((i) => i)
2295
- }
2296
-
2297
- ;// ./lib/helpers/initOnlyValidFromArray/index.js
2298
-
2299
-
2300
- ;// ./lib/helpers/mergeArraysByKey/mergeArraysByKey.js
2301
- function mergeArraysByKey(arr1, arr2) {
2302
- // Handle undefined/null inputs by defaulting to empty arrays
2303
- const safeArr1 = Array.isArray(arr1) ? arr1 : []
2304
- const safeArr2 = Array.isArray(arr2) ? arr2 : []
2305
-
2306
- const mergedMap = new Map()
2307
-
2308
- // Helper function to merge values based on their type
2309
- const mergeValues = (existingValue, newValue) => {
2310
- if (existingValue === undefined) return newValue
2311
-
2312
- // Handle arrays by concatenating
2313
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
2314
- return [...new Set([...existingValue, ...newValue])]
2315
- }
2316
-
2317
- // Handle objects by merging
2318
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
2319
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
2320
- return { ...existingValue, ...newValue }
2321
- }
2322
-
2323
- // // Handle numbers by adding
2324
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
2325
- // return existingValue
2326
- // }
2327
-
2328
- // // Handle strings by concatenating
2329
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
2330
- // return existingValue
2331
- // }
2332
-
2333
- // Default: use the new value
2334
- return newValue
2335
- }
2336
-
2337
- // Process first array
2338
- safeArr1.forEach(item => {
2339
- mergedMap.set(item.key, item.value)
2340
- })
2341
-
2342
- // Process second array and merge values
2343
- safeArr2.forEach(item => {
2344
- const existingValue = mergedMap.get(item.key)
2345
- mergedMap.set(item.key, mergeValues(existingValue, item.value))
2346
- })
2347
-
2348
- // Convert back to array format
2349
- return Array.from(mergedMap.entries()).map(([key, value]) => ({
2350
- key,
2351
- value
2352
- }))
2353
- }
2354
-
2355
- ;// ./lib/helpers/mergeArraysByKey/index.js
2356
-
2357
-
2358
- ;// ./lib/helpers/padZeros/padZeros.js
2359
- function padZeros(num, minLength = 6) {
2360
- num = num.toString()
2361
- if (num.length < minLength) {
2362
- return padZeros('0' + num, minLength)
2363
- }
2364
- return num
2365
- }
2366
-
2367
-
2368
-
2369
- ;// ./lib/helpers/padZeros/index.js
2370
-
2371
-
2372
-
2373
-
2374
- ;// ./lib/helpers/pReduce/index.js
2375
-
2376
-
2377
-
2378
-
2379
- ;// ./lib/helpers/replacePlaceholders/replacePlaceholders.js
2380
- function replacePlaceholders({ content, mapping }) {
2381
- let isObjectMode = false
2382
-
2383
- if (typeof content === 'object' && content !== null) {
2384
- content = JSON.stringify(content)
2385
- isObjectMode = true
2386
- }
2387
-
2388
- // [[ eventRegistration.eventRegistrationCode | 0 ]]
2389
- const regex = /(\[*)\[\[\s*([\w.\-_]+)(?:\s*\|\s*([^:\]\s]+))?(?:\s*:\s*([^\]\s]+))?\s*\]\](\]*)/g;
2390
-
2391
- const result = content.replace(regex, (match, leadingBrackets, path, defaultValue, type, trailingBrackets) => {
2392
-
2393
- // Split the path into parts
2394
- const keys = path.trim().split('.')
2395
-
2396
- // Traverse the nested object structure
2397
- let value = mapping
2398
- for (const key of keys) {
2399
- // Handle empty keys (in case of double dots or leading/trailing dots)
2400
- if (!key) continue
2401
-
2402
- value = value?.[key]
2403
- if (value === undefined) {
2404
- break
2405
- }
2406
- }
2407
-
2408
- // Apply default if missing
2409
- if (value === undefined) value = defaultValue?.trim();
2410
- if (value === undefined) return isObjectMode ? undefined : match;
2411
-
2412
- value = value !== undefined
2413
- ? leadingBrackets + value + trailingBrackets
2414
- : match
2415
-
2416
- // Return replacement or original if not found
2417
- return value
2418
- })
2419
-
2420
- if (isObjectMode) {
2421
- return JSON.parse(result)
2422
- }
2423
- return result
2424
- }
2425
-
2426
- ;// ./lib/helpers/replacePlaceholders/index.js
2427
-
2428
-
2429
- ;// ./lib/helpers/sanitizeText/sanitizeText.js
2430
- /**
2431
- * Sanitizes input by removing hidden/control characters with customizable whitespace handling.
2432
- * @param {string} input - The string to sanitize.
2433
- * @param {Object} [options] - Configuration options.
2434
- * @param {boolean} [options.normalizeWhitespace=true] - Collapse multiple spaces/tabs into one space.
2435
- * @param {boolean} [options.removeNewlines=false] - If true, replaces newlines with spaces.
2436
- * @param {boolean} [options.trim=true] - If true, trims leading/trailing whitespace.
2437
- * @returns {string} The sanitized string.
2438
- */
2439
- function sanitizeText(input, options = {}) {
2440
- const {
2441
- normalizeWhitespace = true,
2442
- removeNewlines = false,
2443
- trim = true,
2444
- preserveBasicWhitespace = true, // new option to keep tabs, newlines if removeNewlines=false
2445
- } = options
2446
-
2447
- if (typeof input !== 'string') {
2448
- return input
2449
- }
2450
-
2451
- let result = input
2452
-
2453
- // Phase 1: Remove all control characters except basic whitespace if requested
2454
- if (preserveBasicWhitespace && !removeNewlines) {
2455
- // Keep tab (\t), newline (\n), carriage return (\r)
2456
- result = result.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g, '')
2457
- } else {
2458
- // Remove all control characters including basic whitespace
2459
- result = result.replace(/[\x00-\x1F\x7F-\x9F\u200B-\u200D\uFEFF\u202A-\u202E]/g, '')
2460
- }
2461
-
2462
- // Phase 2: Handle whitespace transformations
2463
- if (removeNewlines) {
2464
- result = result.replace(/[\r\n]+/g, ' ') // Convert newlines to spaces
2465
- }
2466
-
2467
- if (normalizeWhitespace) {
2468
- result = result.replace(/[ \t]+/g, ' ') // Collapse spaces/tabs to single space
2469
- }
2470
-
2471
- // Phase 3: Final trimming
2472
- if (trim) {
2473
- result = result.trim()
2474
- }
2475
-
2476
- return result
2477
- }
2478
-
2479
- ;// ./lib/helpers/sanitizeText/index.js
2480
-
2481
-
2482
- ;// ./lib/helpers/stringFormatter/stringFormatter.js
2483
- function stringFormatter(str, delimiter = '_') {
2484
- if (str === null || typeof str === 'undefined' || typeof str.toString === 'undefined') {
2485
- return null
2486
- }
2487
- return str.toString()
2488
- .trim()
2489
- .toUpperCase()
2490
- .replace('-', delimiter)
2491
- .replace(' ', delimiter)
2492
- }
2493
-
2494
-
2495
-
2496
- ;// ./lib/helpers/stringFormatter/index.js
2497
-
2498
-
2499
-
2500
-
2501
- ;// ./lib/helpers/stringHelper/stringHelper.js
2502
- function baseXEncode(num, base = 34) {
2503
- const charset = getBaseCharset(base)
2504
- return encode(num, charset)
2505
- }
2506
-
2507
- function encode(int, charset) {
2508
- const { byCode } = charset
2509
- if (int === 0) {
2510
- return byCode[0]
2511
- }
2512
-
2513
- let res = ''
2514
- const max = charset.length
2515
- while (int > 0) {
2516
- res = byCode[int % max] + res
2517
- int = Math.floor(int / max)
2518
- }
2519
- return res
2520
- }
2521
-
2522
- function getBaseCharset(base) {
2523
- let charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZ'
2524
- if (base === 58) {
2525
- charset = '9876543210ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz'
2526
- }
2527
- return indexCharset(charset)
2528
- }
2529
-
2530
- function indexCharset(str) {
2531
- const byCode = {}
2532
- const byChar = {}
2533
- const { length } = str
2534
- let char
2535
- for (let i = 0; i < length; i++) {
2536
- char = str[i]
2537
- byCode[i] = char
2538
- byChar[char] = i;
2539
- }
2540
- return { byCode, byChar, length }
2541
- }
2542
-
2543
- function isSame(str1, str2) {
2544
- if (typeof str1 !== 'string' || typeof str2 !== 'string') {
2545
- return false
2546
- }
2547
- return str1.trim().toUpperCase() === str2.trim().toUpperCase()
2548
- }
2549
-
2550
- function randomString({ len = 16, pattern = 'a1' } = {}) {
2551
- const A = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
2552
- const a = 'abcdefghijklmnopqrstuvwxyz'
2553
- const num = '1234567890'
2554
- const mark = '~!@#$%^&*_+-='
2555
- let str = ''
2556
- if (pattern.includes('A')) {
2557
- str += A
2558
- }
2559
- if (pattern.includes('a')) {
2560
- str += a
2561
- }
2562
- if (pattern.includes('1')) {
2563
- str += num
2564
- }
2565
- if (pattern.includes('#')) {
2566
- str += mark
2567
- }
2568
- const chars = [...str]
2569
- return [...Array(len)].map(i => {
2570
- return chars[(Math.random() * chars.length) | 0]
2571
- }).join``
2572
- }
2573
-
2574
- function reverse(str) {
2575
- const _str = (typeof str !== 'string') ? str.toString() : str
2576
- const splitString = _str.split('')
2577
- const reverseArray = splitString.reverse()
2578
- return reverseArray.join('')
2579
- }
2580
-
2581
- function setCode(base = 34) {
2582
- const now = (new Date()).valueOf()
2583
- const random = randomString({
2584
- len: 8,
2585
- pattern: '1'
2586
- })
2587
- const str = reverse(`${now}${random}`)
2588
- // const str = `${now}${random}`
2589
- return baseXEncode(str, base)
2590
- }
2591
-
2592
- function toCamelCase(str) {
2593
- if (!str) return ''
2594
- return str
2595
- .trim()
2596
- .split(/\s+/)
2597
- .map((word, index) => {
2598
- if (!word) return ''
2599
- if (index === 0) {
2600
- return word.toLowerCase()
2601
- }
2602
- return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
2603
- })
2604
- .join('')
2605
- }
2606
-
2607
- function toLowerCase(str) {
2608
- if (!str) return ''
2609
- return str
2610
- .trim()
2611
- .toLowerCase()
2612
- }
2613
-
2614
- const stringHelper = {
2615
- isSame,
2616
- setCode,
2617
- toCamelCase,
2618
- toLowerCase,
2619
- }
2620
-
2621
-
2622
-
2623
- ;// ./lib/helpers/stringHelper/index.js
2624
-
2625
-
2626
-
2627
-
2628
- ;// ./lib/helpers/trackingPlugin/trackingPlugin.js
2629
- function trackingPlugin(schema, options) {
2630
- // Add meta fields
2631
- schema.add({
2632
- meta: {
2633
- active: { type: Boolean, default: true },
2634
- created: { type: Number },
2635
- creator: { type: String },
2636
- deleted: { type: Boolean, default: false },
2637
- modified: { type: Number },
2638
- owner: { type: String },
2639
- }
2640
- })
2641
-
2642
- // Auto-update hook
2643
- schema.pre('save', function(next) {
2644
- this.meta.modified = Date.now()
2645
- next()
2646
- })
2647
-
2648
- // Add core indexes
2649
- schema.index({
2650
- 'meta.active': 1,
2651
- 'meta.deleted': 1
2652
- }, {
2653
- name: 'tracking_status_index',
2654
- background: true,
2655
- partialFilterExpression: {
2656
- 'meta.active': true,
2657
- 'meta.deleted': false
2658
- }
2659
- })
2660
-
2661
- // Optional: Add helper methods
2662
- // schema.methods.touch = function(userId) {
2663
- // this.meta.updatedAt = new Date()
2664
- // this.meta.updatedBy = userId
2665
- // }
2666
- }
2667
-
2668
- ;// ./lib/helpers/tenantPlugin/tenantPlugin.js
2669
-
2670
-
2671
- function tenantPlugin(schema, options) {
2672
- // Apply tracking plugin first if not already present
2673
- if (!schema.path('meta')) {
2674
- trackingPlugin(schema, options)
2675
- }
2676
-
2677
- // Add tenant-specific fields
2678
- schema.add({
2679
- metadata: [{ type: Object }], // Instead of Schema.Types.Mixed
2680
- remarks: [{ type: Object }],
2681
- tenantCode: { type: String, required: true }
2682
- })
2683
-
2684
- // Add core indexes
2685
- schema.index({
2686
- 'tenantCode': 1
2687
- }, {
2688
- name: 'tenant_core_index',
2689
- background: true
2690
- })
2691
-
2692
- // 1. ENHANCE EXISTING TRACKING INDEXES
2693
- const existingIndexes = schema.indexes()
2694
-
2695
- // Check if tracking_status_index exists
2696
- const hasTenantStatusIndex = existingIndexes.some(idx =>
2697
- idx.name === 'tenant_status_index' // Check by name for reliability
2698
- )
2699
-
2700
- if (!hasTenantStatusIndex) {
2701
- schema.index({
2702
- 'tenantCode': 1, // Unique field first
2703
- _type: 1, // Low-cardinality field last
2704
- }, {
2705
- name: 'tenant_status_index',
2706
- background: true,
2707
- partialFilterExpression: {
2708
- '_type': 'Tenant',
2709
- 'meta.active': true,
2710
- 'meta.deleted': false
2711
- }
2712
- })
2713
- }
2714
- }
2715
-
2716
- ;// ./lib/helpers/tenantPlugin/index.js
2717
-
2718
-
2719
- ;// ./lib/helpers/trackingPlugin/index.js
2720
-
2721
-
2722
- ;// ./lib/helpers/index.js
2723
-
2724
-
2725
-
2726
-
2727
-
2728
-
2729
-
2730
-
2731
-
2732
-
2733
-
2734
-
2735
-
2736
-
2737
-
2738
-
2739
-
2740
-
2741
-
2742
-
2743
-
2744
-
2745
-
2746
-
2747
-
2748
- ;// ./lib/models/apiResponse/index.js
2749
-
2750
-
2751
-
2752
-
2753
-
2754
- ;// ./lib/models/awsStsS3Client/awsStsS3Client.js
2755
- class AwsStsS3Client {
2756
- constructor(options) {
2757
- options = options || {}
2758
-
2759
- this.expiration = options.expiration || null
2760
- this.s3Client = options.s3Client || null
2761
- this.getIdToken = options.getIdToken
2762
- this.region = options.region || 'ap-east-1'
2763
- this.roleArn = options.roleArn
2764
- this.roleSessionName = options.roleSessionName || 'web-identity-session'
2765
- this.durationSession = options.durationSession || 3600
2766
- this.awsClientSts = options.awsClientSts
2767
- this.awsClientS3 = options.awsClientS3
2768
- }
2769
-
2770
- static dummyData() {
2771
- return {
2772
- getIdToken: () => 'mock-web-identity-token',
2773
- roleArn: 'arn:aws:iam::846252828949:role/oidcS3Jccpa',
2774
- awsClientSts: {
2775
- STSClient: class {},
2776
- AssumeRoleWithWebIdentityCommand: class {}
2777
- },
2778
- awsClientS3: {
2779
- S3Client: class {},
2780
- PutObjectCommand: class {},
2781
- GetObjectCommand: class {},
2782
- DeleteObjectCommand: class {}
2783
- }
2784
- }
2785
- }
2786
-
2787
- static init(options = {}) {
2788
- if (options instanceof this) {
2789
- return options
2790
- }
2791
- try {
2792
- const instance = new this(options)
2793
- if (!instance.isValid) {
2794
- return null
2795
- }
2796
- return instance
2797
- } catch (error) {
2798
- return null
2799
- }
2800
- }
2801
-
2802
- get isExpired() {
2803
- if (!this.expiration) return true;
2804
- const now = new Date();
2805
- const bufferMs = 1 * 60 * 1000; // 一分钟缓冲
2806
- return now >= new Date(this.expiration.getTime() - bufferMs);
2807
- }
2808
-
2809
- get isValid() {
2810
- if (!this.getIdToken) {
2811
- throw new Error('Missing required configuration: getIdToken function')
2812
- }
2813
- if (!this.roleArn) {
2814
- throw new Error('Missing required configuration: roleArn')
2815
- }
2816
- if (!this.awsClientSts) {
2817
- throw new Error('Missing required AWS awsClientSts client configuration')
2818
- }
2819
- if (!this.awsClientSts.STSClient) {
2820
- throw new Error('Missing STSClient in AWS awsClientSts client configuration')
2821
- }
2822
- if (!this.awsClientSts.AssumeRoleWithWebIdentityCommand) {
2823
- throw new Error('Missing AssumeRoleWithWebIdentityCommand in AWS awsClientSts client configuration')
2824
- }
2825
- if (!this.awsClientS3) {
2826
- throw new Error('Missing required AWS awsClientS3 client configuration')
2827
- }
2828
-
2829
- const requiredS3Components = [
2830
- 'S3Client',
2831
- 'PutObjectCommand',
2832
- 'GetObjectCommand',
2833
- 'DeleteObjectCommand'
2834
- ]
2835
-
2836
- for (const component of requiredS3Components) {
2837
- if (!this.awsClientS3[component]) {
2838
- throw new Error(`Missing ${component} in AWS awsClientS3 client configuration`)
2839
- }
2840
- }
2841
-
2842
- return true
2843
- }
2844
-
2845
- async refreshCredentials() {
2846
- try {
2847
- const webIdentityToken = await this.getIdToken()
2848
- if (!webIdentityToken) {
2849
- throw new Error('getIdToken function returned empty or invalid token')
2850
- }
2851
-
2852
- const stsClient = new this.awsClientSts.STSClient({ region: this.region })
2853
-
2854
- const stsResponse = await stsClient.send(
2855
- new this.awsClientSts.AssumeRoleWithWebIdentityCommand({
2856
- RoleArn: this.roleArn,
2857
- RoleSessionName: this.roleSessionName,
2858
- WebIdentityToken: await this.getIdToken(),
2859
- DurationSeconds: this.durationSession,
2860
- })
2861
- )
2862
-
2863
- const credentials = stsResponse.Credentials
2864
- if (!credentials) {
2865
- throw new Error('No credentials returned from awsClientSts')
2866
- }
2867
-
2868
- this.expiration = credentials.Expiration
2869
-
2870
- this.s3Client = new this.awsClientS3.S3Client({
2871
- region: this.region,
2872
- credentials: {
2873
- accessKeyId: credentials.AccessKeyId,
2874
- secretAccessKey: credentials.SecretAccessKey,
2875
- sessionToken: credentials.SessionToken,
2876
- }
2877
- })
2878
-
2879
- return this
2880
- } catch (error) {
2881
- throw new Error(`Failed to refresh credentials: ${error.message}`)
2882
- }
2883
- }
2884
-
2885
- async getS3Client() {
2886
- if (this.isExpired || !this.s3Client) {
2887
- await this.refreshCredentials()
2888
- }
2889
- return this.s3Client
2890
- }
2891
-
2892
- async putObject(params) {
2893
- try {
2894
- const client = await this.getS3Client()
2895
- const command = new this.awsClientS3.PutObjectCommand(params)
2896
- await client.send(command)
2897
- const fileArr = params.Key.split('/')
2898
- return {
2899
- url: `https://s3.${this.region}.amazonaws.com/${params.Bucket}/${params.Key}`,
2900
- filename: fileArr.pop(),
2901
- folder: params.Bucket,
2902
- subFolders: fileArr
2903
- }
2904
- } catch (error) {
2905
- throw new Error(`Failed to put object: ${error.message}`)
2906
- }
2907
- }
2908
-
2909
- async getObject(params) {
2910
- try {
2911
- const client = await this.getS3Client()
2912
- const command = new this.awsClientS3.GetObjectCommand(params)
2913
- const response = await client.send(command)
2914
- return {
2915
- body: response.Body,
2916
- contentType: response.ContentType,
2917
- lastModified: response.LastModified,
2918
- contentLength: response.ContentLength,
2919
- }
2920
- } catch (error) {
2921
- throw new Error(`Failed to get object: ${error.message}`)
2922
- }
2923
- }
2924
-
2925
- async deleteObject(params) {
2926
- try {
2927
- const client = await this.getS3Client()
2928
- const command = new this.awsClientS3.DeleteObjectCommand(params)
2929
- await client.send(command)
2930
- return true
2931
- } catch (error) {
2932
- throw new Error(`Failed to delete object: ${error.message}`)
2933
- }
2934
- }
2935
- }
2936
-
2937
-
2938
-
2939
- ;// ./lib/models/awsStsS3Client/index.js
2940
-
2941
-
2942
-
2943
-
2944
- ;// ./lib/models/keyValueObject/keyValueObject.js
2945
- class KeyValueObject {
2946
- constructor(options = {}) {
2947
- options = options || {}
2948
- this.key = options.key || null
2949
- this.value = (typeof options.value !== 'undefined') ? options.value : ''
2950
- }
2951
-
2952
- // Class methods
2953
- static init(options = {}) {
2954
- if (options instanceof this) {
2955
- return options
2956
- }
2957
- const instance = new this(options)
2958
- return instance.isValid ? instance : null
2959
- }
2960
- static initFromArray(arr = []) {
2961
- if (Array.isArray(arr)) {
2962
- return arr.map((a) => this.init(a))
2963
- }
2964
- return []
2965
- }
2966
- static initOnlyValidFromArray(arr = []) {
2967
- return this.initFromArray(arr).filter((i) => i)
2968
- }
2969
- static get _classname() {
2970
- return 'KeyValueObject'
2971
- }
2972
- static get _superclass() {
2973
- return 'KeyValueObject'
2974
- }
2975
-
2976
- static addItem(arr, key, value) {
2977
- arr.push(this.init({ key, value }))
2978
- }
2979
- static addRecord(arr = [], key, value) {
2980
- if (!this.hasKeyValue(arr, key, value)) {
2981
- arr.push(this.init({ key, value }))
2982
- }
2983
- return arr
2984
- }
2985
- static appendRecord(arr = [], key, value) {
2986
- return arr.map((item) => {
2987
- if (this.sameKey(item, key)) {
2988
- item.value = [...item.value, ...value]
2989
- }
2990
- return item
2991
- })
2992
- }
2993
- static appendValueArray(arr = [], key, value) {
2994
- return arr.map((item) => {
2995
- if (this.sameKey(item, key)) {
2996
- item.value = [...item.value, ...value]
2997
- }
2998
- return item
2999
- })
3000
- }
3001
- static foundByKey(arr = [], key) {
3002
- const found = arr.find((m) => {
3003
- return this.sameKey(m, key)
3004
- })
3005
- return found || null
3006
- }
3007
- static foundValueByKey(arr = [], key) {
3008
- const found = this.foundByKey(arr, key)
3009
- return found ? found.value : null
3010
- }
3011
- static fromObject(options = {}) {
3012
- return Object.keys(options).reduce((acc, key) => {
3013
- acc.push(this.init({ key, value: options[key] }))
3014
- return acc
3015
- }, [])
3016
- }
3017
- static getValueByKey(arr = [], key) {
3018
- return this.foundValueByKey(arr, key)
3019
- }
3020
- static getValueByKeyFromArray(arr = [], key) {
3021
- if (arr.length === 0) {
3022
- return null
3023
- }
3024
- const firstArr = arr.shift()
3025
- const found = firstArr.find((i) => {
3026
- return this.sameKey(i, key)
3027
- })
3028
- if (found && found.value) {
3029
- return found.value
3030
- }
3031
- return this.getValueByKeyFromArray(arr, key)
3032
- }
3033
- static getValuesByKey(arr = [], key) {
3034
- return arr.reduce((acc, item) => {
3035
- if (this.sameKey(item, key)) {
3036
- acc.push(item.value)
3037
- }
3038
- return acc
3039
- }, [])
3040
- }
3041
- static hasKeyValue(arr = [], key, value) {
3042
- if (typeof value === 'undefined') {
3043
- return arr.filter((item) => this.sameKey(item, key)).length > 0
3044
- }
3045
- return arr.filter((item) => (this.sameKey(item, key) && _isSame(item.value, value))).length > 0
3046
- }
3047
- static insertOrUpdateRecord(arr = [], key, value) {
3048
- let copy = [...arr]
3049
- if (!this.hasKeyValue(arr, key)) {
3050
- copy.push(this.init({ key, value }))
3051
- } else {
3052
- copy = this.updateRecord(arr, key, value)
3053
- }
3054
- return copy
3055
- }
3056
- static keys(arr = []) {
3057
- if (Array.isArray(arr)) {
3058
- return arr.reduce((acc, item) => {
3059
- acc.push(item.key)
3060
- return acc
3061
- }, [])
3062
- }
3063
- return []
3064
- }
3065
- static merge(toArr, fromArr) {
3066
- (fromArr || []).map((from) => {
3067
- const found = toArr.find((to) => {
3068
- return to.key === from.key
3069
- })
3070
- if (found) {
3071
- found.value = _mergeValues(from.value, found.value)
3072
- } else {
3073
- toArr.push(from)
3074
- }
3075
- })
3076
- return toArr
3077
- }
3078
- static removeByKey(arr, key) {
3079
- return arr.reduce((acc, item) => {
3080
- if (!this.sameKey(item, key)) {
3081
- acc.push(item)
3082
- }
3083
- return acc
3084
- }, [])
3085
- }
3086
- static sameKey(item, key) {
3087
- if (item) {
3088
- return _isSame(item.key, key)
3089
- }
3090
- return false
3091
- }
3092
- static toObject(arr = []) {
3093
- if (Array.isArray(arr)) {
3094
- return arr.reduce((acc, item) => {
3095
- acc[item.key] = item.value
3096
- return acc
3097
- }, {})
3098
- }
3099
- return {}
3100
- }
3101
- static toString(arr = [], delimiter = '; ') {
3102
- if (Array.isArray(arr)) {
3103
- return arr.reduce((acc, item) => {
3104
- acc.push(`${item.key}: ${item.value}`)
3105
- return acc
3106
- }, []).join(delimiter)
3107
- }
3108
- return ''
3109
- }
3110
- static updateRecord(arr = [], key, value) {
3111
- return arr.map((item) => {
3112
- if (this.sameKey(item, key)) {
3113
- return {
3114
- ...item,
3115
- value
3116
- }
3117
- }
3118
- return item
3119
- })
3120
- }
3121
- static updateOrInsertRecord(arr = [], key, value) {
3122
- return this.insertOrUpdateRecord(arr, key, value)
3123
- }
3124
- static updateRecordsFromArray(arr = [], updateArr = []) {
3125
- if (Array.isArray(arr) && Array.isArray(updateArr)) {
3126
- const obj1 = this.toObject(arr)
3127
- const obj2 = this.toObject(updateArr)
3128
- return this.fromObject({
3129
- ...obj1,
3130
- ...obj2
3131
- })
3132
- }
3133
- return []
3134
- }
3135
- static values(arr = []) {
3136
- if (Array.isArray(arr)) {
3137
- return arr.reduce((acc, item) => {
3138
- acc.push(item.value)
3139
- return acc
3140
- }, [])
3141
- }
3142
- return []
3143
- }
3144
-
3145
- // getters
3146
- get isValid() {
3147
- return !!this.key
3148
- }
3149
-
3150
- get toObject() {
3151
- const obj = {}
3152
- if (this.isValid) {
3153
- obj[this.key] = this.value
3154
- }
3155
- return obj
3156
- }
3157
- }
3158
-
3159
- function _mergeValues(existingValue, newValue) {
3160
- if (existingValue === undefined) return newValue
3161
-
3162
- // Handle arrays by concatenating
3163
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
3164
- return [...new Set([...existingValue, ...newValue])]
3165
- }
3166
-
3167
- // Handle objects by merging
3168
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
3169
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
3170
- return { ...existingValue, ...newValue }
3171
- }
3172
-
3173
- // // Handle numbers by adding
3174
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
3175
- // return existingValue
3176
- // }
3177
-
3178
- // // Handle strings by concatenating
3179
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
3180
- // return existingValue
3181
- // }
3182
-
3183
- // Default: use the new value
3184
- return newValue
3185
- }
3186
-
3187
- function _isSame(key1, key2) {
3188
- return key1 === key2
3189
- }
3190
-
3191
-
3192
-
3193
- ;// ./lib/models/keyValueObject/index.js
3194
-
3195
-
3196
-
3197
-
3198
- ;// ./lib/models/metadata/metadata.js
3199
-
3200
-
3201
-
3202
- const DELIMITER = '_'
3203
-
3204
- class Metadata extends KeyValueObject {
3205
- static init(options = {}) {
3206
- if (options instanceof this) {
3207
- return options
3208
- }
3209
- const instance = new this({
3210
- ...options,
3211
- key: stringFormatter(options.key, DELIMITER),
3212
- })
3213
- return instance.isValid ? instance : null
3214
- }
3215
- static get _classname() {
3216
- return 'Metadata'
3217
- }
3218
-
3219
- static merge(toArr, fromArr) {
3220
- (fromArr || []).map((from) => {
3221
- const found = toArr.find((to) => {
3222
- return metadata_isSame(to.key, from.key)
3223
- })
3224
- if (found) {
3225
- found.value = metadata_mergeValues(from.value, found.value)
3226
- } else {
3227
- toArr.push(from)
3228
- }
3229
- })
3230
- return toArr
3231
- }
3232
- static sameKey(item, key) {
3233
- return metadata_isSame(item.key, key)
3234
- }
3235
- }
3236
-
3237
- function metadata_isSame(key1, key2) {
3238
- return stringFormatter(key1, DELIMITER) === stringFormatter(key2, DELIMITER)
3239
- }
3240
-
3241
- function metadata_mergeValues(existingValue, newValue) {
3242
- if (existingValue === undefined) return newValue
3243
-
3244
- // Handle arrays by concatenating
3245
- if (Array.isArray(existingValue) && Array.isArray(newValue)) {
3246
- return [...new Set([...existingValue, ...newValue])]
3247
- }
3248
-
3249
- // Handle objects by merging
3250
- if (typeof existingValue === 'object' && typeof newValue === 'object' &&
3251
- !Array.isArray(existingValue) && !Array.isArray(newValue)) {
3252
- return { ...existingValue, ...newValue }
3253
- }
3254
-
3255
- // // Handle numbers by adding
3256
- // if (typeof existingValue === 'number' && typeof newValue === 'number') {
3257
- // return existingValue
3258
- // }
3259
-
3260
- // // Handle strings by concatenating
3261
- // if (typeof existingValue === 'string' && typeof newValue === 'string') {
3262
- // return existingValue
3263
- // }
3264
-
3265
- // Default: use the new value
3266
- return newValue
3267
- }
3268
-
3269
-
3270
-
3271
- ;// ./lib/models/metadata/index.js
3272
-
3273
-
3274
-
3275
-
3276
- ;// ./lib/models/qMeta/qMeta.js
3277
-
3278
-
3279
- const updateAllowedProps = [
3280
- 'attributes',
3281
- 'ref'
3282
- ]
3283
-
3284
- class QMeta {
3285
- constructor(options = {}) {
3286
- options = options || {}
3287
- this.attributes = KeyValueObject.initOnlyValidFromArray(options.attributes)
3288
- this.ref = options.ref || {}
3289
- }
3290
-
3291
- static get _classname() {
3292
- return 'QMeta'
3293
- }
3294
- static get _superclass() {
3295
- return 'QMeta'
3296
- }
3297
-
3298
- // Class methods
3299
- static init(options = {}) {
3300
- if (options instanceof QMeta) {
3301
- return options
3302
- }
3303
- return new QMeta(options)
3304
- }
3305
-
3306
- // instance methods
3307
- addAttribute(obj) {
3308
- const kvObject = KeyValueObject.init(obj)
3309
- if (!kvObject) {
3310
- throw new Error('invalid meta attribute')
3311
- }
3312
- this.attributes.push(kvObject)
3313
- return this
3314
- }
3315
-
3316
- update(obj) {
3317
- Object.keys(obj).forEach((key) => {
3318
- if (updateAllowedProps.includes(key)) {
3319
- if (key === 'attributes') {
3320
- this[key] = KeyValueObject.initOnlyValidFromArray(obj[key])
3321
- } else {
3322
- this[key] = obj[key]
3323
- }
3324
- }
3325
- })
3326
- return this
3327
- }
3328
- }
3329
-
3330
-
3331
-
3332
- ;// ./lib/models/qMeta/index.js
3333
-
3334
-
3335
-
3336
-
3337
- ;// ./lib/models/trackedEntity/trackedEntity.js
3338
-
3339
-
3340
- class TrackedEntity {
3341
- constructor(options = {}) {
3342
- options = options || {}
3343
- const timestamp = Date.now()
3344
- this.meta = {
3345
- active: options.meta?.active ?? options.active ?? true,
3346
- created: options.meta?.created ?? (options.created
3347
- ? new Date(options.created).getTime()
3348
- : timestamp),
3349
- creator: options.meta?.creator ?? options.creator ?? '',
3350
- deleted: options.meta?.deleted ?? options.deleted ?? false,
3351
- modified: options.meta?.modified ?? (options.modified
3352
- ? new Date(options.modified).getTime()
3353
- : timestamp),
3354
- owner: options.meta?.owner ?? options.owner ?? '',
3355
- }
3356
-
3357
- // if (trackFlat) {
3358
- // Object.assign(this, _tracking)
3359
- // } else {
3360
- // this.meta = { ..._tracking, ...options.meta }
3361
- // }
3362
- }
3363
-
3364
- // Class methods
3365
- static get _classname() {
3366
- return 'TrackedEntity'
3367
- }
3368
- static get _superclass() {
3369
- return 'TrackedEntity'
3370
- }
3371
-
3372
- static init(options = {}) {
3373
- return init(this, options)
3374
- }
3375
- static initFromArray(arr = []) {
3376
- return initFromArray(this, arr)
3377
- }
3378
- static initOnlyValidFromArray(arr = []) {
3379
- return initOnlyValidFromArray(this, arr)
3380
- }
3381
- // static nest(entity) {
3382
- // const { active, created, creator, deleted, modified, owner, ...rest } = entity
3383
- // return { ...rest, meta: { active, created, creator, deleted, modified, owner } }
3384
- // }
3385
-
3386
- // getters
3387
- get isValid() {
3388
- return !!this
3389
- }
3390
- get active() {
3391
- return this.meta?.active ?? this.active
3392
- }
3393
- get created() {
3394
- return this.meta?.created ?? this.created
3395
- }
3396
- get creator() {
3397
- return this.meta?.creator ?? this.creator
3398
- }
3399
- get deleted() {
3400
- return this.meta?.deleted ?? this.deleted
3401
- }
3402
- get modified() {
3403
- return this.meta?.modified ?? this.modified
3404
- }
3405
- get owner() {
3406
- return this.meta?.owner ?? this.owner
3407
- }
3408
- changeCreatorOwner({ source, target }) {
3409
- return changeCreatorOwner(this, { source, target }).setModified()
3410
- }
3411
- delete() {
3412
- return this.setDeleted()
3413
- }
3414
- setActive() {
3415
- if (this.meta) {
3416
- this.meta.active = true
3417
- } else {
3418
- this.active = true
3419
- }
3420
- return this
3421
- }
3422
- setDeleted() {
3423
- if (this.meta) {
3424
- this.meta.deleted = true
3425
- } else {
3426
- this.deleted = true
3427
- }
3428
- return this
3429
- }
3430
- setModified() {
3431
- const timestamp = Date.now()
3432
- if (this.meta) {
3433
- this.meta.modified = timestamp
3434
- } else {
3435
- this.modified = timestamp
3436
- }
3437
- return this
3438
- }
3439
- setOwner(owner) {
3440
- if (!owner) {
3441
- return this
3442
- }
3443
- if (this.meta) {
3444
- this.meta.owner = owner
3445
- } else {
3446
- this.owner = owner
3447
- }
3448
- return this
3449
- }
3450
- unsetActive() {
3451
- if (this.meta) {
3452
- this.meta.active = false
3453
- } else {
3454
- this.active = false
3455
- }
3456
- return this
3457
- }
3458
- unsetDeleted() {
3459
- if (this.meta) {
3460
- this.meta.deleted = false
3461
- } else {
3462
- this.deleted = false
3463
- }
3464
- return this
3465
- }
3466
-
3467
- update(update) {
3468
- if (update.meta) {
3469
- this.meta = { ...this.meta, ...update.meta }
3470
- }
3471
- return this.setModified()
3472
- }
3473
- }
3474
-
3475
- ;// ./lib/models/trackedEntity/index.js
3476
-
3477
- // Explicit named export (optional)
3478
-
3479
- ;// ./lib/models/tenantAwareEntity/tenantAwareEntity.js
3480
-
3481
-
3482
-
3483
-
3484
- class TenantAwareEntity extends TrackedEntity {
3485
- constructor(options = {}) {
3486
- options = options || {}
3487
-
3488
- /**
3489
- * instead of throw error, we choose to implement the isValid checking
3490
- */
3491
- // if (!options.tenantCode) {
3492
- // throw new Error('tenantCode required')
3493
- // }
3494
-
3495
- super(options)
3496
-
3497
- this._tenant = options._tenant
3498
-
3499
- this.metadata = Metadata.initOnlyValidFromArray(options.metadata)
3500
- this.remarks = KeyValueObject.initOnlyValidFromArray(options.remarks)
3501
- this.tenantCode = options.tenantCode // Required for multi-tenancy
3502
- }
3503
-
3504
- // Class methods
3505
- static get _classname() {
3506
- return 'TenantAwareEntity'
3507
- }
3508
- static get _superclass() {
3509
- return 'TenantAwareEntity'
3510
- }
3511
-
3512
- // getters
3513
- get isValid() {
3514
- return super.isValid && !!this.tenantCode // Required for multi-tenancy
3515
- }
3516
-
3517
- // instance methods
3518
- getMetadata() {
3519
- return this.metadata
3520
- }
3521
- getMetadataByKey(key) {
3522
- return Metadata.foundByKey(this.metadata, key)
3523
- }
3524
- getMetadataValueByKey(key) {
3525
- const found = this.getMetadataByKey(key)
3526
- return found ? found.value : null
3527
- }
3528
- getRemarks() {
3529
- return this.remarks
3530
- }
3531
- getRemarkByKey(key) {
3532
- return KeyValueObject.foundByKey(this.remarks, key)
3533
- }
3534
- getRemarksValueByKey(key) {
3535
- const found = this.getRemarkByKey(key)
3536
- return found ? found.value : null
3537
- }
3538
- getTenantCode() {
3539
- return this.tenantCode
3540
- }
3541
-
3542
- update(update) {
3543
- if (update.metadata && Array.isArray(update.metadata)) {
3544
- this.metadata = Metadata.initOnlyValidFromArray(update.metadata)
3545
- }
3546
- if (update.remarks && Array.isArray(update.remarks)) {
3547
- this.remarks = KeyValueObject.initOnlyValidFromArray(update.remarks)
3548
- }
3549
- return super.update(update)
3550
- }
3551
- }
3552
-
3553
- ;// ./lib/models/tenantAwareEntity/index.js
3554
-
3555
-
3556
-
3557
- ;// ./lib/models/uniqueKeyGenerator/uniqueKeyGenerator.js
3558
-
3559
-
3560
- class UniqueKeyGenerator {
3561
- static get _classname() {
3562
- return 'UniqueKeyGenerator'
3563
- }
3564
- static get _superclass() {
3565
- return 'UniqueKeyGenerator'
3566
- }
3567
- static makeFormatter({ fieldName, format, options }) {
3568
- switch (format) {
3569
- case 'set_code':
3570
- return _makeSetCode(fieldName, options)
3571
- default:
3572
- return _makeSetCode(fieldName, options)
3573
- }
3574
- }
3575
- static makeGenerator(arr) {
3576
- const fns = arr.map((item) => this.makeFormatter(item))
3577
- return async (obj) => {
3578
- const output = await pReduce(fns, async (acc, fn) => {
3579
- const _obj = await fn(obj)
3580
- return Object.assign(acc, _obj)
3581
- }, obj)
3582
- return output
3583
- }
3584
- }
3585
- }
3586
-
3587
- function _makeSetCode(fieldName, options) {
3588
- return async (obj = {}) => {
3589
- if (obj[fieldName]) {
3590
- return {}
3591
- }
3592
- return {
3593
- [fieldName]: stringHelper.setCode()
3594
- }
3595
- }
3596
- }
3597
-
3598
-
3599
-
3600
- ;// ./lib/models/uniqueKeyGenerator/index.js
3601
-
3602
-
3603
-
3604
-
3605
- ;// ./lib/models/index.js
3606
-
3607
-
3608
-
3609
-
3610
-
3611
-
3612
-
3613
-
3614
-
3615
-
3616
-
3617
-
3618
- ;// ./lib/index.js
3619
-
3620
-
3621
-
3622
- ;// ./index.js
3623
-
3624
-
3625
- /******/ return __webpack_exports__;
3626
- /******/ })()
3627
- ;
3628
- });