@jsb188/app 1.1.10 → 1.1.12

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.
Files changed (79) hide show
  1. package/package.json +57 -45
  2. package/src/constants/agent.ts +51 -41
  3. package/src/constants/app.ts +34 -13
  4. package/src/constants/emoji.ts +9144 -8936
  5. package/src/constants/other.ts +1 -5
  6. package/src/constants/user.ts +16 -25
  7. package/src/constants/wsActions.ts +27 -0
  8. package/src/i18n/account.ts +129 -107
  9. package/src/i18n/agent.ts +331 -73
  10. package/src/i18n/agentToolBusiness.ts +196 -0
  11. package/src/i18n/agentToolGrid.ts +137 -0
  12. package/src/i18n/agentToolWorkflow.ts +101 -0
  13. package/src/i18n/agent_note.ts +109 -0
  14. package/src/i18n/app.ts +107 -91
  15. package/src/i18n/auth.ts +117 -102
  16. package/src/i18n/billing.ts +5 -92
  17. package/src/i18n/c.ts +907 -0
  18. package/src/i18n/campaign.ts +919 -0
  19. package/src/i18n/country.ts +248 -248
  20. package/src/i18n/datetime.ts +32 -26
  21. package/src/i18n/editor.ts +58 -0
  22. package/src/i18n/error.ts +577 -192
  23. package/src/i18n/field_doc_editor.ts +21 -0
  24. package/src/i18n/field_doc_programs.ts +52 -0
  25. package/src/i18n/field_docs.ts +190 -0
  26. package/src/i18n/index.ts +42 -19
  27. package/src/i18n/log.ts +272 -238
  28. package/src/i18n/memory.ts +53 -0
  29. package/src/i18n/message.ts +3 -4
  30. package/src/i18n/note.ts +19 -0
  31. package/src/i18n/org.ts +164 -109
  32. package/src/i18n/schedule.ts +209 -0
  33. package/src/i18n/sheet.ts +333 -4
  34. package/src/i18n/sheet_formula.ts +165 -0
  35. package/src/i18n/workflow.ts +109 -23
  36. package/src/main.ts +68 -64
  37. package/src/platform.ts +90 -49
  38. package/src/types/ai.d.ts +52 -23
  39. package/src/types/app.d.ts +95 -44
  40. package/src/types/auth.d.ts +66 -40
  41. package/src/types/console.d.ts +3 -0
  42. package/src/types/other.d.ts +13 -6
  43. package/src/types.d.ts +12 -14
  44. package/src/utils/account.ts +64 -58
  45. package/src/utils/api.ts +326 -77
  46. package/src/utils/authSession.ts +24 -0
  47. package/src/utils/clientIP.ts +213 -0
  48. package/src/utils/color.ts +279 -0
  49. package/src/utils/cron.ts +49 -18
  50. package/src/utils/csv.ts +19 -0
  51. package/src/utils/datetime.ts +445 -117
  52. package/src/utils/deferredSave.ts +89 -0
  53. package/src/utils/email.ts +50 -0
  54. package/src/utils/emoji.ts +107 -84
  55. package/src/utils/expression.helpers.ts +470 -0
  56. package/src/utils/expression.test.ts +793 -0
  57. package/src/utils/expression.ts +2261 -0
  58. package/src/utils/interval.ts +80 -0
  59. package/src/utils/language.ts +9 -0
  60. package/src/utils/logic.ts +141 -121
  61. package/src/utils/managedSession.ts +34 -0
  62. package/src/utils/managedSessionBff.test.ts +60 -0
  63. package/src/utils/managedSessionBff.ts +117 -0
  64. package/src/utils/number.ts +85 -38
  65. package/src/utils/object.ts +227 -30
  66. package/src/utils/promise.ts +98 -0
  67. package/src/utils/queryReset.ts +266 -0
  68. package/src/utils/recurringTask.ts +60 -0
  69. package/src/utils/schema.ts +293 -0
  70. package/src/utils/string.test.ts +205 -208
  71. package/src/utils/string.ts +426 -463
  72. package/src/utils/timeZone.ts +309 -851
  73. package/src/utils/url_client.ts +145 -72
  74. package/tsconfig.json +10 -10
  75. package/src/constants/billing.ts +0 -146
  76. package/src/i18n/form.ts +0 -376
  77. package/src/i18n/product.ts +0 -76
  78. package/src/types/form.d.ts +0 -97
  79. package/src/utils/billing.ts +0 -134
@@ -1,25 +1,54 @@
1
+ /**
2
+ * Scale dimensions proportionally to fit inside the provided bounds.
3
+ */
4
+ export function getContainedDimensions(
5
+ width: number,
6
+ height: number,
7
+ maxWidth: number,
8
+ maxHeight: number,
9
+ ) {
10
+ if (
11
+ !Number.isFinite(width) ||
12
+ !Number.isFinite(height) ||
13
+ !Number.isFinite(maxWidth) ||
14
+ !Number.isFinite(maxHeight) ||
15
+ width <= 0 ||
16
+ height <= 0 ||
17
+ maxWidth <= 0 ||
18
+ maxHeight <= 0
19
+ ) {
20
+ return null;
21
+ }
22
+
23
+ const scale = Math.min(maxWidth / width, maxHeight / height);
24
+
25
+ return {
26
+ width: Math.round(width * scale),
27
+ height: Math.round(height * scale),
28
+ };
29
+ }
1
30
 
2
31
  /**
3
32
  * Convert string value to BigInt safely
4
33
  */
5
34
 
6
35
  export function toBigInt(value: string | number | bigint): bigint | null {
7
- try {
8
- if (typeof value === 'bigint') {
9
- return value;
10
- } else if (typeof value === 'number') {
11
- return BigInt(value);
12
- } else if (typeof value === 'string') {
13
- const trimmed = value.trim();
14
- if (trimmed === '') {
15
- return null;
16
- }
17
- return BigInt(trimmed);
18
- }
19
- return null;
20
- } catch {
21
- return null;
22
- }
36
+ try {
37
+ if (typeof value === 'bigint') {
38
+ return value;
39
+ } else if (typeof value === 'number') {
40
+ return BigInt(value);
41
+ } else if (typeof value === 'string') {
42
+ const trimmed = value.trim();
43
+ if (trimmed === '') {
44
+ return null;
45
+ }
46
+ return BigInt(trimmed);
47
+ }
48
+ return null;
49
+ } catch {
50
+ return null;
51
+ }
23
52
  }
24
53
 
25
54
  /**
@@ -138,14 +167,6 @@ export function secondsToTime(secs: number) {
138
167
  };
139
168
  }
140
169
 
141
- /**
142
- * Get percentage between 2 values
143
- */
144
-
145
- export function calculateDiscount(normalPrice: number, discountedPrice: number) {
146
- return Math.round(((normalPrice - discountedPrice) / normalPrice) * 100);
147
- }
148
-
149
170
  /**
150
171
  * Format decimal number to a string without decimal places or the first non-zero digit
151
172
  *
@@ -186,10 +207,9 @@ export function getQuantityText(
186
207
  unit?: string,
187
208
  ): string {
188
209
  const value = formatDecimal(quantity, true, true);
189
- return [
190
- value + (value && unit && /^[0-9]/.test(unit) ? ', ' : ''),
191
- unit,
192
- ].filter(Boolean).join(' ');
210
+ return [value + (value && unit && /^[0-9]/.test(unit) ? ', ' : ''), unit]
211
+ .filter(Boolean)
212
+ .join(' ');
193
213
  }
194
214
 
195
215
  /**
@@ -238,10 +258,13 @@ export function formatCurrency(
238
258
  const hasDecimals = num % 1 !== 0;
239
259
  const symbol = getCurrencySymbol(locale, currency);
240
260
 
241
- return symbol + num.toLocaleString(locale, {
242
- minimumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
243
- maximumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
244
- });
261
+ return (
262
+ symbol +
263
+ num.toLocaleString(locale, {
264
+ minimumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
265
+ maximumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
266
+ })
267
+ );
245
268
  }
246
269
 
247
270
  /**
@@ -267,7 +290,9 @@ export function kFormat(
267
290
  * Convert number based time to military time format (e.g., 1300 to 13:00)
268
291
  */
269
292
 
270
- export function convertToMilitaryTime(time?: number | string | null): string | null {
293
+ export function convertToMilitaryTime(
294
+ time?: number | string | null,
295
+ ): string | null {
271
296
  if (time) {
272
297
  const timeString = String(time).padStart(4, '0');
273
298
  return `${timeString.slice(0, 2)}:${timeString.slice(2)}`;
@@ -275,6 +300,32 @@ export function convertToMilitaryTime(time?: number | string | null): string | n
275
300
  return null;
276
301
  }
277
302
 
303
+ /**
304
+ * Return the stored total amount from a label/value line item
305
+ */
306
+
307
+ export function getLabelAndValueTotalAmount(
308
+ item?: { value?: string | number | null } | null,
309
+ ): number {
310
+ const val = parseFloat(String(item?.value ?? ''));
311
+ return isNaN(val) ? 0 : val;
312
+ }
313
+
314
+ /**
315
+ * Return the unit amount from a label/value line item whose value stores the line total
316
+ */
317
+
318
+ export function getLabelAndValueUnitAmount(
319
+ item?: {
320
+ value?: string | number | null;
321
+ quantity?: string | number | null;
322
+ } | null,
323
+ ): number {
324
+ const totalAmount = getLabelAndValueTotalAmount(item);
325
+ const quantity = Number(item?.quantity || 1);
326
+ return !quantity || isNaN(quantity) ? totalAmount : totalAmount / quantity;
327
+ }
328
+
278
329
  /**
279
330
  * Calculate totals from LabelAndValueObj[]
280
331
  */
@@ -282,10 +333,6 @@ export function convertToMilitaryTime(time?: number | string | null): string | n
282
333
  export function calculateTotalAmount(values: any[], tax: number = 0): number {
283
334
  return (values || []).reduce((acc, obj) => {
284
335
  // NOTE: obj.value is the total, so obj.quantity can be ignored
285
- const val = parseFloat(obj?.value) * (obj?.quantity || 1);
286
- if (!isNaN(val)) {
287
- return acc + val;
288
- }
289
- return acc;
336
+ return acc + getLabelAndValueTotalAmount(obj);
290
337
  }, tax || 0);
291
338
  }
@@ -2,7 +2,10 @@
2
2
  * Filter array and return only unique values
3
3
  */
4
4
 
5
- export function uniq(arr: Array<any>, fn?: (value: any, index: number, self: Array<any>) => boolean) {
5
+ export function uniq(
6
+ arr: Array<any>,
7
+ fn?: (value: any, index: number, self: Array<any>) => boolean,
8
+ ) {
6
9
  return arr.filter((value, index, self) => {
7
10
  return self.indexOf(value) === index && (!fn || fn(value, index, self));
8
11
  });
@@ -29,7 +32,11 @@ export function uniq(arr: Array<any>, fn?: (value: any, index: number, self: Arr
29
32
  * Remove undefined (and/or null) values from an object
30
33
  */
31
34
 
32
- export function removeUndefined<T>(obj: T, removeNull?: boolean, removeFalsy?: boolean): T {
35
+ export function removeUndefined<T>(
36
+ obj: T,
37
+ removeNull?: boolean,
38
+ removeFalsy?: boolean,
39
+ ): T {
33
40
  for (const key in obj) {
34
41
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
35
42
  if (
@@ -80,16 +87,138 @@ export function parseJSON(jsonStr?: string) {
80
87
  }
81
88
 
82
89
  /**
83
- * Stringify JSON objects with BigInt support
84
- * NOTE: This will work recursively for nested objects as well.
90
+ * Parse a Postgres string-array literal into plain string values.
91
+ */
92
+
93
+ export function parsePostgresStringArray(value: string) {
94
+ const trimmedValue = value.trim();
95
+ if (!trimmedValue.startsWith('{') || !trimmedValue.endsWith('}')) {
96
+ return null;
97
+ }
98
+
99
+ const body = trimmedValue.slice(1, -1);
100
+ if (!body) {
101
+ return [];
102
+ }
103
+
104
+ const values: string[] = [];
105
+ let currentValue = '';
106
+ let isInQuotes = false;
107
+ let isEscaped = false;
108
+
109
+ for (const character of body) {
110
+ if (isEscaped) {
111
+ currentValue += character;
112
+ isEscaped = false;
113
+ continue;
114
+ }
115
+
116
+ if (character === '\\' && isInQuotes) {
117
+ isEscaped = true;
118
+ continue;
119
+ }
120
+
121
+ if (character === '"') {
122
+ isInQuotes = !isInQuotes;
123
+ continue;
124
+ }
125
+
126
+ if (character === ',' && !isInQuotes) {
127
+ values.push(currentValue);
128
+ currentValue = '';
129
+ continue;
130
+ }
131
+
132
+ currentValue += character;
133
+ }
134
+
135
+ values.push(currentValue);
136
+ return values;
137
+ }
138
+
139
+ /**
140
+ * Normalize arrays, array-like objects, JSON arrays, and Postgres array strings.
141
+ */
142
+
143
+ export function normalizeArrayLikeValue<T = any>(value: unknown): T[] | null {
144
+ let arrayValue = value;
145
+
146
+ if (!arrayValue) {
147
+ return null;
148
+ }
149
+
150
+ if (typeof arrayValue === 'string') {
151
+ const trimmedValue = arrayValue.trim();
152
+
153
+ if (!trimmedValue || trimmedValue.toUpperCase() === 'NULL') {
154
+ return null;
155
+ }
156
+
157
+ if (trimmedValue.startsWith('[')) {
158
+ arrayValue = parseJSON(trimmedValue);
159
+ } else if (trimmedValue.startsWith('{')) {
160
+ arrayValue = parsePostgresStringArray(trimmedValue);
161
+ } else {
162
+ arrayValue = [trimmedValue];
163
+ }
164
+ }
165
+
166
+ if (
167
+ arrayValue &&
168
+ typeof arrayValue === 'object' &&
169
+ !Array.isArray(arrayValue)
170
+ ) {
171
+ arrayValue = mapArrayLikeObjects(arrayValue);
172
+ }
173
+
174
+ return Array.isArray(arrayValue) ? (arrayValue as T[]) : null;
175
+ }
176
+
177
+ /**
178
+ * Stringify JSON objects with recursive BigInt support. Precision-safe string
179
+ * conversion is the default; callers must opt into lossy number conversion.
180
+ */
181
+
182
+ export function stringifyJSON(
183
+ obj: any,
184
+ preserveBigIntPrecision: boolean = true,
185
+ ): string {
186
+ return JSON.stringify(obj, (_key, value) =>
187
+ typeof value === 'bigint'
188
+ ? preserveBigIntPrecision
189
+ ? value.toString()
190
+ : Number(value)
191
+ : value,
192
+ );
193
+ }
194
+
195
+ /**
196
+ * Normalize a JSON-like value for order-insensitive serialization: object keys
197
+ * sorted by UTF-16 code unit (never by locale), array order kept, and BigInt
198
+ * and Date values converted to their JSON text forms.
85
199
  */
86
200
 
87
- export function stringifyJSON(obj: any, convertBigIntToNumber: boolean = false): string {
88
- if (!convertBigIntToNumber) {
89
- return JSON.stringify(obj, (_key, value) => typeof value === 'bigint' ? Number(value) : value);
201
+ export function canonicalJSONValue(value: unknown): unknown {
202
+ if (typeof value === 'bigint') return String(value);
203
+ if (value instanceof Date) return value.toISOString();
204
+ if (Array.isArray(value)) return value.map(canonicalJSONValue);
205
+ if (value && typeof value === 'object') {
206
+ return Object.fromEntries(
207
+ Object.entries(value)
208
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
209
+ .map(([key, item]) => [key, canonicalJSONValue(item)]),
210
+ );
90
211
  }
212
+ return value;
213
+ }
91
214
 
92
- return JSON.stringify(obj, (_key, value) => typeof value === 'bigint' ? value.toString() : value);
215
+ /**
216
+ * Serialize JSON with sorted object keys (see canonicalJSONValue), so equal
217
+ * content always produces the same text regardless of property order.
218
+ */
219
+
220
+ export function stableJSONText(value: unknown): string {
221
+ return JSON.stringify(canonicalJSONValue(value));
93
222
  }
94
223
 
95
224
  /**
@@ -127,7 +256,11 @@ export function areObjectsEqual(
127
256
  if (isNested) {
128
257
  return JSON.stringify(obj1) === JSON.stringify(obj2);
129
258
  } else if (obj1 && obj2) {
130
- return Object.keys(obj1).every((key: string) => Object.prototype.hasOwnProperty.call(obj2, key) && obj1[key] === obj2[key]);
259
+ return Object.keys(obj1).every(
260
+ (key: string) =>
261
+ Object.prototype.hasOwnProperty.call(obj2, key) &&
262
+ obj1[key] === obj2[key],
263
+ );
131
264
  }
132
265
  return obj1 === obj2;
133
266
  }
@@ -186,10 +319,12 @@ export function uniqBy(arr: any[], keys: ((obj: any) => any) | string) {
186
319
 
187
320
  return arr.filter((obj, index, self) => {
188
321
  const key = keyGetter(obj);
189
- return self.findIndex((obj2) => {
190
- const key2 = keyGetter(obj2);
191
- return key2 === key;
192
- }) === index;
322
+ return (
323
+ self.findIndex((obj2) => {
324
+ const key2 = keyGetter(obj2);
325
+ return key2 === key;
326
+ }) === index
327
+ );
193
328
  });
194
329
  }
195
330
 
@@ -205,7 +340,11 @@ export function randomItem(arr: Array<any>) {
205
340
  * Rearrange an array left or right
206
341
  */
207
342
 
208
- export function rearrangeArray(arr: Array<any>, loop: number = 1, shiftRight?: boolean) {
343
+ export function rearrangeArray(
344
+ arr: Array<any>,
345
+ loop: number = 1,
346
+ shiftRight?: boolean,
347
+ ) {
209
348
  if (shiftRight) {
210
349
  for (let i = 0; i < loop; i++) {
211
350
  arr.unshift(arr.pop());
@@ -230,7 +369,10 @@ export function get(object: any, path: string) {
230
369
  * NOTE: Use this after Redis.hgetall()
231
370
  */
232
371
 
233
- export function hgetZipObject(arr: Array<string>, mapperFn?: (value: string, index: number) => any) {
372
+ export function hgetZipObject(
373
+ arr: Array<string>,
374
+ mapperFn?: (value: string, index: number) => any,
375
+ ) {
234
376
  const obj: Record<string, any> = {};
235
377
  for (let i = 0; i < arr.length; i += 2) {
236
378
  if (mapperFn) {
@@ -259,7 +401,10 @@ export function zipObject(keys: Array<string>, values: Array<any>) {
259
401
  * NOTE: Use this for best NodeJS and browser compatibility
260
402
  */
261
403
 
262
- export function findLastIndex(arr: Array<any>, fn: (value: any, index: number, array: any[]) => boolean) {
404
+ export function findLastIndex(
405
+ arr: Array<any>,
406
+ fn: (value: any, index: number, array: any[]) => boolean,
407
+ ) {
263
408
  if (typeof arr.findLastIndex === 'function') {
264
409
  return arr.findLastIndex(fn);
265
410
  }
@@ -276,8 +421,21 @@ export function findLastIndex(arr: Array<any>, fn: (value: any, index: number, a
276
421
  * Array intersection
277
422
  */
278
423
 
279
- export function intersection(arr1: Array<any>, arr2: Array<any>) {
280
- return arr1.filter((value) => arr2.includes(value));
424
+ export function intersection(arr1: unknown, arr2: unknown) {
425
+ const normalizedArr1 = normalizeArrayLikeValue(arr1) || [];
426
+ const normalizedArr2 = normalizeArrayLikeValue(arr2) || [];
427
+
428
+ return normalizedArr1.filter((value) => normalizedArr2.includes(value));
429
+ }
430
+
431
+ /**
432
+ * Toggle one value in an array; removes the value when present, appends it otherwise
433
+ */
434
+
435
+ export function toggleArrayValue<T>(arr: Array<T>, value: T): Array<T> {
436
+ return arr.includes(value)
437
+ ? arr.filter((currentValue) => currentValue !== value)
438
+ : [...arr, value];
281
439
  }
282
440
 
283
441
  /**
@@ -322,7 +480,10 @@ export function groupCollections(
322
480
  }
323
481
 
324
482
  for (const key in obj) {
325
- if (!Object.prototype.hasOwnProperty.call(obj, key) || key.startsWith('__')) {
483
+ if (
484
+ !Object.prototype.hasOwnProperty.call(obj, key) ||
485
+ key.startsWith('__')
486
+ ) {
326
487
  continue;
327
488
  }
328
489
 
@@ -452,11 +613,19 @@ export function groupCollections(
452
613
  if (innerPKFn) {
453
614
  return innerPKFn(o) === innerPKFn(innerObj);
454
615
  }
455
- return (o.id && o.id === innerObj.id) ||
456
- (!o.id && Object.entries(o).flat().join('|') === Object.entries(innerObj).flat().join('|'));
616
+ return (
617
+ (o.id && o.id === innerObj.id) ||
618
+ (!o.id &&
619
+ Object.entries(o).flat().join('|') ===
620
+ Object.entries(innerObj).flat().join('|'))
621
+ );
457
622
  })
458
623
  ) {
459
- setObject(acc[i], name, Array.isArray(ref) ? ref.concat(innerObj) : innerObj);
624
+ setObject(
625
+ acc[i],
626
+ name,
627
+ Array.isArray(ref) ? ref.concat(innerObj) : innerObj,
628
+ );
460
629
  }
461
630
 
462
631
  // Old version, but this doesn't support merged array collections
@@ -489,9 +658,15 @@ export function groupCollections(
489
658
  collections.forEach((obj) => {
490
659
  const innerObj = getObject(obj, flatName);
491
660
  const primaryKey = obj[primaryKeyName];
492
- const i = groupedCollections.findIndex((o: any) => o[primaryKeyName] === primaryKey);
661
+ const i = groupedCollections.findIndex(
662
+ (o: any) => o[primaryKeyName] === primaryKey,
663
+ );
493
664
  const innerParent = getObject(obj, beforeHash);
494
- const innerParentId = makeMergeKey(innerParent, parentPKFn, primaryKeyName);
665
+ const innerParentId = makeMergeKey(
666
+ innerParent,
667
+ parentPKFn,
668
+ primaryKeyName,
669
+ );
495
670
 
496
671
  if (!innerObj || !hasMeaningfulValue(innerObj)) {
497
672
  return;
@@ -499,7 +674,10 @@ export function groupCollections(
499
674
 
500
675
  if (innerParentId && i >= 0) {
501
676
  const innerArr = getObject(groupedCollections[i], beforeHash) || [];
502
- const j = innerArr.findIndex((o: any) => makeMergeKey(o, parentPKFn, primaryKeyName) === innerParentId);
677
+ const j = innerArr.findIndex(
678
+ (o: any) =>
679
+ makeMergeKey(o, parentPKFn, primaryKeyName) === innerParentId,
680
+ );
503
681
 
504
682
  if (j >= 0) {
505
683
  const currentValue = innerArr[j][afterHash];
@@ -509,7 +687,11 @@ export function groupCollections(
509
687
 
510
688
  let newValue;
511
689
  if (currentValueIsArray) {
512
- if (!currentValue.find((o) => makeMergeKey(o, childPKFn) === nextInnerObjKey)) {
690
+ if (
691
+ !currentValue.find(
692
+ (o) => makeMergeKey(o, childPKFn) === nextInnerObjKey,
693
+ )
694
+ ) {
513
695
  newValue = currentValue.concat(innerObj);
514
696
  }
515
697
  } else if (
@@ -541,7 +723,11 @@ export function groupCollections(
541
723
  if (childPKFn) {
542
724
  setObject(obj, afterHash, uniqBy(innerParentObj, childPKFn));
543
725
  } else {
544
- setObject(obj, afterHash, uniqBy(innerParentObj, (iObj: any) => makeMergeKey(iObj)));
726
+ setObject(
727
+ obj,
728
+ afterHash,
729
+ uniqBy(innerParentObj, (iObj: any) => makeMergeKey(iObj)),
730
+ );
545
731
  }
546
732
  } else {
547
733
  setObject(obj, afterHash, [innerParentObj]);
@@ -584,7 +770,9 @@ export function cloneArrayLike(obj: any) {
584
770
 
585
771
  export function mapArrayLikeObjects(obj: any) {
586
772
  if (
587
- !Array.isArray(obj) && obj !== null && typeof obj === 'object' &&
773
+ !Array.isArray(obj) &&
774
+ obj !== null &&
775
+ typeof obj === 'object' &&
588
776
  Object.keys(obj).every((key, i) => key === i.toString())
589
777
  ) {
590
778
  return Object.values(obj);
@@ -660,6 +848,11 @@ export function setObject(obj: any, path: string, value: any): any {
660
848
  return obj;
661
849
  }
662
850
  const keys = path.split('.');
851
+ if (
852
+ keys.some((key) => ['__proto__', 'constructor', 'prototype'].includes(key))
853
+ ) {
854
+ return obj;
855
+ }
663
856
  const lastKey = keys.pop();
664
857
  const nestedObj = keys.reduce((o, key) => {
665
858
  if (!o[key]) {
@@ -672,7 +865,9 @@ export function setObject(obj: any, path: string, value: any): any {
672
865
  if (typeof nestedObj === 'object' && nestedObj !== null) {
673
866
  nestedObj[lastKey] = value;
674
867
  } else {
675
- console.warn(`(!1) Cannot assign value to ${lastKey} because its reference is not an object.`);
868
+ console.warn(
869
+ `(!1) Cannot assign value to ${lastKey} because its reference is not an object.`,
870
+ );
676
871
  }
677
872
  }
678
873
 
@@ -705,7 +900,9 @@ export function hasObject(obj: any, namespace: string): boolean {
705
900
  * @returns - Returns a new object with keys sorted alphabetically
706
901
  */
707
902
 
708
- export function sortObjectByKeys(obj: Record<string, any>): Record<string, any> {
903
+ export function sortObjectByKeys(
904
+ obj: Record<string, any>,
905
+ ): Record<string, any> {
709
906
  if (!obj || typeof obj !== 'object') {
710
907
  return obj;
711
908
  }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Types
3
+ */
4
+
5
+ export type MaybePromise<T> = T | Promise<T>;
6
+
7
+ /*
8
+ * Return whether one value is thenable.
9
+ */
10
+ export function isPromiseLike<T>(value: MaybePromise<T>): value is Promise<T> {
11
+ return Boolean(
12
+ value && (typeof value === 'object' || typeof value === 'function') && typeof (value as Promise<T>).then === 'function',
13
+ );
14
+ }
15
+
16
+ /*
17
+ * Chain one continuation onto a maybe-promise without forcing async:
18
+ * plain values invoke the continuation synchronously.
19
+ */
20
+ export function chainMaybePromise<T, R>(value: MaybePromise<T>, onValue: (value: T) => MaybePromise<R>): MaybePromise<R> {
21
+ return isPromiseLike(value) ? value.then(onValue) : onValue(value);
22
+ }
23
+
24
+ /*
25
+ * Run one async task per item with at most `limit` in flight, starting the next
26
+ * item as soon as any task finishes. Every item runs even when some fail; the
27
+ * first failure is rethrown once all tasks have settled.
28
+ */
29
+ export async function runWithConcurrencyLimit<T>(items: readonly T[], limit: number, task: (item: T, index: number) => Promise<void>) {
30
+ let nextIndex = 0;
31
+ let failure: { error: unknown } | null = null;
32
+ const runWorker = async () => {
33
+ while (nextIndex < items.length) {
34
+ const index = nextIndex++;
35
+ try {
36
+ await task(items[index], index);
37
+ } catch (error) {
38
+ failure = failure || { error };
39
+ }
40
+ }
41
+ };
42
+
43
+ const workerLimit = Number.isFinite(limit) ? Math.floor(limit) : 1;
44
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(workerLimit, items.length)) }, runWorker));
45
+ if (failure) {
46
+ throw (failure as { error: unknown }).error;
47
+ }
48
+ }
49
+
50
+ export type ConcurrencyGate = {
51
+ run: <T>(task: () => Promise<T>) => Promise<T>;
52
+ tryRun: <T>(task: () => Promise<T>) => Promise<{ ran: true; value: T } | { ran: false }>;
53
+ };
54
+
55
+ /*
56
+ * Create a gate that lets at most `getLimit()` tasks run at once across every
57
+ * caller that shares it. `run` waits for a slot in arrival order; `tryRun` runs
58
+ * only when a slot is free now and nobody is waiting, and otherwise returns
59
+ * ran=false at once. The limit is read at each admission, so it may come from
60
+ * configuration loaded after the gate was created.
61
+ */
62
+ export function createConcurrencyGate(getLimit: () => number): ConcurrencyGate {
63
+ let active = 0;
64
+ const waiters: Array<() => void> = [];
65
+ const hasSlot = () => active < Math.max(1, Math.floor(getLimit()));
66
+ const release = () => {
67
+ active -= 1;
68
+ while (waiters.length && hasSlot()) {
69
+ active += 1;
70
+ waiters.shift()?.();
71
+ }
72
+ };
73
+ const runAdmitted = async <T>(task: () => Promise<T>) => {
74
+ try {
75
+ return await task();
76
+ } finally {
77
+ release();
78
+ }
79
+ };
80
+
81
+ return {
82
+ run: async (task) => {
83
+ if (hasSlot() && !waiters.length) {
84
+ active += 1;
85
+ } else {
86
+ await new Promise<void>((resolve) => waiters.push(resolve));
87
+ }
88
+ return await runAdmitted(task);
89
+ },
90
+ tryRun: async (task) => {
91
+ if (!hasSlot() || waiters.length) {
92
+ return { ran: false };
93
+ }
94
+ active += 1;
95
+ return { ran: true, value: await runAdmitted(task) };
96
+ },
97
+ };
98
+ }