@questwork/q-utilities 0.1.18 → 0.1.19

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