@jsb188/app 1.1.9 → 1.1.11

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 (63) hide show
  1. package/package.json +54 -45
  2. package/src/constants/agent.ts +58 -25
  3. package/src/constants/app.ts +18 -14
  4. package/src/constants/billing.ts +92 -92
  5. package/src/constants/emoji.ts +9144 -8936
  6. package/src/constants/other.ts +1 -5
  7. package/src/constants/user.ts +16 -25
  8. package/src/constants/wsActions.ts +35 -0
  9. package/src/i18n/account.ts +129 -107
  10. package/src/i18n/agent.ts +63 -43
  11. package/src/i18n/agentDoc.ts +110 -0
  12. package/src/i18n/app.ts +101 -91
  13. package/src/i18n/auth.ts +119 -102
  14. package/src/i18n/billing.ts +73 -78
  15. package/src/i18n/campaign.ts +217 -0
  16. package/src/i18n/country.ts +248 -248
  17. package/src/i18n/datetime.ts +26 -26
  18. package/src/i18n/error.ts +428 -182
  19. package/src/i18n/field_docs.ts +28 -0
  20. package/src/i18n/form.ts +464 -344
  21. package/src/i18n/index.ts +25 -18
  22. package/src/i18n/log.ts +53 -213
  23. package/src/i18n/memory.ts +39 -0
  24. package/src/i18n/message.ts +3 -4
  25. package/src/i18n/note.ts +17 -0
  26. package/src/i18n/org.ts +115 -109
  27. package/src/i18n/sheet.ts +376 -4
  28. package/src/i18n/workflow.ts +70 -23
  29. package/src/main.ts +66 -62
  30. package/src/platform.ts +25 -24
  31. package/src/types/ai.d.ts +33 -23
  32. package/src/types/app.d.ts +95 -37
  33. package/src/types/auth.d.ts +66 -40
  34. package/src/types/console.d.ts +3 -0
  35. package/src/types/form.d.ts +65 -61
  36. package/src/types/other.d.ts +6 -6
  37. package/src/types.d.ts +12 -14
  38. package/src/utils/account.ts +64 -58
  39. package/src/utils/api.ts +280 -77
  40. package/src/utils/authSession.ts +24 -0
  41. package/src/utils/billing.ts +110 -103
  42. package/src/utils/color.ts +202 -0
  43. package/src/utils/cron.ts +49 -18
  44. package/src/utils/datetime.ts +255 -103
  45. package/src/utils/emoji.ts +107 -84
  46. package/src/utils/expression.ts +867 -0
  47. package/src/utils/interval.ts +80 -0
  48. package/src/utils/logic.ts +209 -36
  49. package/src/utils/managedSession.ts +34 -0
  50. package/src/utils/managedSessionBff.test.ts +60 -0
  51. package/src/utils/managedSessionBff.ts +117 -0
  52. package/src/utils/number.ts +60 -32
  53. package/src/utils/object.ts +198 -30
  54. package/src/utils/promise.ts +27 -0
  55. package/src/utils/queryReset.ts +179 -0
  56. package/src/utils/recurringTask.ts +60 -0
  57. package/src/utils/schema.ts +293 -0
  58. package/src/utils/string.test.ts +220 -208
  59. package/src/utils/string.ts +471 -438
  60. package/src/utils/timeZone.ts +309 -851
  61. package/src/utils/url_client.ts +73 -69
  62. package/tsconfig.json +10 -10
  63. package/src/i18n/product.ts +0 -76
@@ -1,25 +1,24 @@
1
-
2
1
  /**
3
2
  * Convert string value to BigInt safely
4
3
  */
5
4
 
6
5
  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
- }
6
+ try {
7
+ if (typeof value === 'bigint') {
8
+ return value;
9
+ } else if (typeof value === 'number') {
10
+ return BigInt(value);
11
+ } else if (typeof value === 'string') {
12
+ const trimmed = value.trim();
13
+ if (trimmed === '') {
14
+ return null;
15
+ }
16
+ return BigInt(trimmed);
17
+ }
18
+ return null;
19
+ } catch {
20
+ return null;
21
+ }
23
22
  }
24
23
 
25
24
  /**
@@ -142,7 +141,10 @@ export function secondsToTime(secs: number) {
142
141
  * Get percentage between 2 values
143
142
  */
144
143
 
145
- export function calculateDiscount(normalPrice: number, discountedPrice: number) {
144
+ export function calculateDiscount(
145
+ normalPrice: number,
146
+ discountedPrice: number,
147
+ ) {
146
148
  return Math.round(((normalPrice - discountedPrice) / normalPrice) * 100);
147
149
  }
148
150
 
@@ -186,10 +188,9 @@ export function getQuantityText(
186
188
  unit?: string,
187
189
  ): string {
188
190
  const value = formatDecimal(quantity, true, true);
189
- return [
190
- value + (value && unit && /^[0-9]/.test(unit) ? ', ' : ''),
191
- unit,
192
- ].filter(Boolean).join(' ');
191
+ return [value + (value && unit && /^[0-9]/.test(unit) ? ', ' : ''), unit]
192
+ .filter(Boolean)
193
+ .join(' ');
193
194
  }
194
195
 
195
196
  /**
@@ -238,10 +239,13 @@ export function formatCurrency(
238
239
  const hasDecimals = num % 1 !== 0;
239
240
  const symbol = getCurrencySymbol(locale, currency);
240
241
 
241
- return symbol + num.toLocaleString(locale, {
242
- minimumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
243
- maximumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
244
- });
242
+ return (
243
+ symbol +
244
+ num.toLocaleString(locale, {
245
+ minimumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
246
+ maximumFractionDigits: hasDecimals || trailZeros ? 2 : 0,
247
+ })
248
+ );
245
249
  }
246
250
 
247
251
  /**
@@ -267,7 +271,9 @@ export function kFormat(
267
271
  * Convert number based time to military time format (e.g., 1300 to 13:00)
268
272
  */
269
273
 
270
- export function convertToMilitaryTime(time?: number | string | null): string | null {
274
+ export function convertToMilitaryTime(
275
+ time?: number | string | null,
276
+ ): string | null {
271
277
  if (time) {
272
278
  const timeString = String(time).padStart(4, '0');
273
279
  return `${timeString.slice(0, 2)}:${timeString.slice(2)}`;
@@ -275,6 +281,32 @@ export function convertToMilitaryTime(time?: number | string | null): string | n
275
281
  return null;
276
282
  }
277
283
 
284
+ /**
285
+ * Return the stored total amount from a label/value line item
286
+ */
287
+
288
+ export function getLabelAndValueTotalAmount(
289
+ item?: { value?: string | number | null } | null,
290
+ ): number {
291
+ const val = parseFloat(String(item?.value ?? ''));
292
+ return isNaN(val) ? 0 : val;
293
+ }
294
+
295
+ /**
296
+ * Return the unit amount from a label/value line item whose value stores the line total
297
+ */
298
+
299
+ export function getLabelAndValueUnitAmount(
300
+ item?: {
301
+ value?: string | number | null;
302
+ quantity?: string | number | null;
303
+ } | null,
304
+ ): number {
305
+ const totalAmount = getLabelAndValueTotalAmount(item);
306
+ const quantity = Number(item?.quantity || 1);
307
+ return !quantity || isNaN(quantity) ? totalAmount : totalAmount / quantity;
308
+ }
309
+
278
310
  /**
279
311
  * Calculate totals from LabelAndValueObj[]
280
312
  */
@@ -282,10 +314,6 @@ export function convertToMilitaryTime(time?: number | string | null): string | n
282
314
  export function calculateTotalAmount(values: any[], tax: number = 0): number {
283
315
  return (values || []).reduce((acc, obj) => {
284
316
  // 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;
317
+ return acc + getLabelAndValueTotalAmount(obj);
290
318
  }, tax || 0);
291
319
  }
@@ -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,109 @@ 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.
85
91
  */
86
92
 
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);
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;
90
133
  }
91
134
 
92
- return JSON.stringify(obj, (_key, value) => typeof value === 'bigint' ? value.toString() : value);
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
+ );
93
193
  }
94
194
 
95
195
  /**
@@ -127,7 +227,11 @@ export function areObjectsEqual(
127
227
  if (isNested) {
128
228
  return JSON.stringify(obj1) === JSON.stringify(obj2);
129
229
  } else if (obj1 && obj2) {
130
- return Object.keys(obj1).every((key: string) => Object.prototype.hasOwnProperty.call(obj2, key) && obj1[key] === obj2[key]);
230
+ return Object.keys(obj1).every(
231
+ (key: string) =>
232
+ Object.prototype.hasOwnProperty.call(obj2, key) &&
233
+ obj1[key] === obj2[key],
234
+ );
131
235
  }
132
236
  return obj1 === obj2;
133
237
  }
@@ -186,10 +290,12 @@ export function uniqBy(arr: any[], keys: ((obj: any) => any) | string) {
186
290
 
187
291
  return arr.filter((obj, index, self) => {
188
292
  const key = keyGetter(obj);
189
- return self.findIndex((obj2) => {
190
- const key2 = keyGetter(obj2);
191
- return key2 === key;
192
- }) === index;
293
+ return (
294
+ self.findIndex((obj2) => {
295
+ const key2 = keyGetter(obj2);
296
+ return key2 === key;
297
+ }) === index
298
+ );
193
299
  });
194
300
  }
195
301
 
@@ -205,7 +311,11 @@ export function randomItem(arr: Array<any>) {
205
311
  * Rearrange an array left or right
206
312
  */
207
313
 
208
- export function rearrangeArray(arr: Array<any>, loop: number = 1, shiftRight?: boolean) {
314
+ export function rearrangeArray(
315
+ arr: Array<any>,
316
+ loop: number = 1,
317
+ shiftRight?: boolean,
318
+ ) {
209
319
  if (shiftRight) {
210
320
  for (let i = 0; i < loop; i++) {
211
321
  arr.unshift(arr.pop());
@@ -230,7 +340,10 @@ export function get(object: any, path: string) {
230
340
  * NOTE: Use this after Redis.hgetall()
231
341
  */
232
342
 
233
- export function hgetZipObject(arr: Array<string>, mapperFn?: (value: string, index: number) => any) {
343
+ export function hgetZipObject(
344
+ arr: Array<string>,
345
+ mapperFn?: (value: string, index: number) => any,
346
+ ) {
234
347
  const obj: Record<string, any> = {};
235
348
  for (let i = 0; i < arr.length; i += 2) {
236
349
  if (mapperFn) {
@@ -259,7 +372,10 @@ export function zipObject(keys: Array<string>, values: Array<any>) {
259
372
  * NOTE: Use this for best NodeJS and browser compatibility
260
373
  */
261
374
 
262
- export function findLastIndex(arr: Array<any>, fn: (value: any, index: number, array: any[]) => boolean) {
375
+ export function findLastIndex(
376
+ arr: Array<any>,
377
+ fn: (value: any, index: number, array: any[]) => boolean,
378
+ ) {
263
379
  if (typeof arr.findLastIndex === 'function') {
264
380
  return arr.findLastIndex(fn);
265
381
  }
@@ -276,8 +392,21 @@ export function findLastIndex(arr: Array<any>, fn: (value: any, index: number, a
276
392
  * Array intersection
277
393
  */
278
394
 
279
- export function intersection(arr1: Array<any>, arr2: Array<any>) {
280
- return arr1.filter((value) => arr2.includes(value));
395
+ export function intersection(arr1: unknown, arr2: unknown) {
396
+ const normalizedArr1 = normalizeArrayLikeValue(arr1) || [];
397
+ const normalizedArr2 = normalizeArrayLikeValue(arr2) || [];
398
+
399
+ return normalizedArr1.filter((value) => normalizedArr2.includes(value));
400
+ }
401
+
402
+ /**
403
+ * Toggle one value in an array; removes the value when present, appends it otherwise
404
+ */
405
+
406
+ export function toggleArrayValue<T>(arr: Array<T>, value: T): Array<T> {
407
+ return arr.includes(value)
408
+ ? arr.filter((currentValue) => currentValue !== value)
409
+ : [...arr, value];
281
410
  }
282
411
 
283
412
  /**
@@ -322,7 +451,10 @@ export function groupCollections(
322
451
  }
323
452
 
324
453
  for (const key in obj) {
325
- if (!Object.prototype.hasOwnProperty.call(obj, key) || key.startsWith('__')) {
454
+ if (
455
+ !Object.prototype.hasOwnProperty.call(obj, key) ||
456
+ key.startsWith('__')
457
+ ) {
326
458
  continue;
327
459
  }
328
460
 
@@ -452,11 +584,19 @@ export function groupCollections(
452
584
  if (innerPKFn) {
453
585
  return innerPKFn(o) === innerPKFn(innerObj);
454
586
  }
455
- return (o.id && o.id === innerObj.id) ||
456
- (!o.id && Object.entries(o).flat().join('|') === Object.entries(innerObj).flat().join('|'));
587
+ return (
588
+ (o.id && o.id === innerObj.id) ||
589
+ (!o.id &&
590
+ Object.entries(o).flat().join('|') ===
591
+ Object.entries(innerObj).flat().join('|'))
592
+ );
457
593
  })
458
594
  ) {
459
- setObject(acc[i], name, Array.isArray(ref) ? ref.concat(innerObj) : innerObj);
595
+ setObject(
596
+ acc[i],
597
+ name,
598
+ Array.isArray(ref) ? ref.concat(innerObj) : innerObj,
599
+ );
460
600
  }
461
601
 
462
602
  // Old version, but this doesn't support merged array collections
@@ -489,9 +629,15 @@ export function groupCollections(
489
629
  collections.forEach((obj) => {
490
630
  const innerObj = getObject(obj, flatName);
491
631
  const primaryKey = obj[primaryKeyName];
492
- const i = groupedCollections.findIndex((o: any) => o[primaryKeyName] === primaryKey);
632
+ const i = groupedCollections.findIndex(
633
+ (o: any) => o[primaryKeyName] === primaryKey,
634
+ );
493
635
  const innerParent = getObject(obj, beforeHash);
494
- const innerParentId = makeMergeKey(innerParent, parentPKFn, primaryKeyName);
636
+ const innerParentId = makeMergeKey(
637
+ innerParent,
638
+ parentPKFn,
639
+ primaryKeyName,
640
+ );
495
641
 
496
642
  if (!innerObj || !hasMeaningfulValue(innerObj)) {
497
643
  return;
@@ -499,7 +645,10 @@ export function groupCollections(
499
645
 
500
646
  if (innerParentId && i >= 0) {
501
647
  const innerArr = getObject(groupedCollections[i], beforeHash) || [];
502
- const j = innerArr.findIndex((o: any) => makeMergeKey(o, parentPKFn, primaryKeyName) === innerParentId);
648
+ const j = innerArr.findIndex(
649
+ (o: any) =>
650
+ makeMergeKey(o, parentPKFn, primaryKeyName) === innerParentId,
651
+ );
503
652
 
504
653
  if (j >= 0) {
505
654
  const currentValue = innerArr[j][afterHash];
@@ -509,7 +658,11 @@ export function groupCollections(
509
658
 
510
659
  let newValue;
511
660
  if (currentValueIsArray) {
512
- if (!currentValue.find((o) => makeMergeKey(o, childPKFn) === nextInnerObjKey)) {
661
+ if (
662
+ !currentValue.find(
663
+ (o) => makeMergeKey(o, childPKFn) === nextInnerObjKey,
664
+ )
665
+ ) {
513
666
  newValue = currentValue.concat(innerObj);
514
667
  }
515
668
  } else if (
@@ -541,7 +694,11 @@ export function groupCollections(
541
694
  if (childPKFn) {
542
695
  setObject(obj, afterHash, uniqBy(innerParentObj, childPKFn));
543
696
  } else {
544
- setObject(obj, afterHash, uniqBy(innerParentObj, (iObj: any) => makeMergeKey(iObj)));
697
+ setObject(
698
+ obj,
699
+ afterHash,
700
+ uniqBy(innerParentObj, (iObj: any) => makeMergeKey(iObj)),
701
+ );
545
702
  }
546
703
  } else {
547
704
  setObject(obj, afterHash, [innerParentObj]);
@@ -584,7 +741,9 @@ export function cloneArrayLike(obj: any) {
584
741
 
585
742
  export function mapArrayLikeObjects(obj: any) {
586
743
  if (
587
- !Array.isArray(obj) && obj !== null && typeof obj === 'object' &&
744
+ !Array.isArray(obj) &&
745
+ obj !== null &&
746
+ typeof obj === 'object' &&
588
747
  Object.keys(obj).every((key, i) => key === i.toString())
589
748
  ) {
590
749
  return Object.values(obj);
@@ -660,6 +819,11 @@ export function setObject(obj: any, path: string, value: any): any {
660
819
  return obj;
661
820
  }
662
821
  const keys = path.split('.');
822
+ if (
823
+ keys.some((key) => ['__proto__', 'constructor', 'prototype'].includes(key))
824
+ ) {
825
+ return obj;
826
+ }
663
827
  const lastKey = keys.pop();
664
828
  const nestedObj = keys.reduce((o, key) => {
665
829
  if (!o[key]) {
@@ -672,7 +836,9 @@ export function setObject(obj: any, path: string, value: any): any {
672
836
  if (typeof nestedObj === 'object' && nestedObj !== null) {
673
837
  nestedObj[lastKey] = value;
674
838
  } else {
675
- console.warn(`(!1) Cannot assign value to ${lastKey} because its reference is not an object.`);
839
+ console.warn(
840
+ `(!1) Cannot assign value to ${lastKey} because its reference is not an object.`,
841
+ );
676
842
  }
677
843
  }
678
844
 
@@ -705,7 +871,9 @@ export function hasObject(obj: any, namespace: string): boolean {
705
871
  * @returns - Returns a new object with keys sorted alphabetically
706
872
  */
707
873
 
708
- export function sortObjectByKeys(obj: Record<string, any>): Record<string, any> {
874
+ export function sortObjectByKeys(
875
+ obj: Record<string, any>,
876
+ ): Record<string, any> {
709
877
  if (!obj || typeof obj !== 'object') {
710
878
  return obj;
711
879
  }
@@ -0,0 +1,27 @@
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 &&
13
+ (typeof value === 'object' || typeof value === 'function') &&
14
+ typeof (value as Promise<T>).then === 'function',
15
+ );
16
+ }
17
+
18
+ /*
19
+ * Chain one continuation onto a maybe-promise without forcing async:
20
+ * plain values invoke the continuation synchronously.
21
+ */
22
+ export function chainMaybePromise<T, R>(
23
+ value: MaybePromise<T>,
24
+ onValue: (value: T) => MaybePromise<R>,
25
+ ): MaybePromise<R> {
26
+ return isPromiseLike(value) ? value.then(onValue) : onValue(value);
27
+ }
@@ -0,0 +1,179 @@
1
+ /*
2
+ * Structured query-reset targets. A target names one GraphQL query and,
3
+ * optionally, the serialized variable values a cached page must carry to be
4
+ * reset by it without building or evaluating a regex.
5
+ *
6
+ * Cache keys are '#queryName:' + makeVariablesKey(variables). The query name
7
+ * keeps its GraphQL casing; only the variables segment is lowercased, so the
8
+ * name is compared case-sensitively here and variables are compared lowercased.
9
+ */
10
+
11
+ export interface QueryResetTarget {
12
+ name: string;
13
+ match?: Record<string, string>;
14
+ }
15
+
16
+ /*
17
+ * Build one structured query-reset target. Variable names and values are
18
+ * lowercased to line up with makeVariablesKey().
19
+ *
20
+ * Callers decide which constraints apply: omit a key to widen the target (no
21
+ * constraint on that variable), and pass an empty value only if the intent is
22
+ * a target that matches nothing, since makeVariablesKey() drops empty values
23
+ * from cache keys entirely.
24
+ */
25
+
26
+ export function makeQueryResetTarget(
27
+ name: string,
28
+ match?: Record<string, string | number | bigint | undefined>,
29
+ ): QueryResetTarget {
30
+ const normalizedMatch: Record<string, string> = {};
31
+
32
+ for (const [variableName, value] of Object.entries(match || {})) {
33
+ // An explicitly undefined value is an absent constraint, which is how
34
+ // callers widen a target; an empty string is a real constraint that
35
+ // matches nothing, since makeVariablesKey() drops empty values
36
+ if (value === undefined) {
37
+ continue;
38
+ }
39
+
40
+ normalizedMatch[variableName.toLowerCase()] = String(value).toLowerCase();
41
+ }
42
+
43
+ return Object.keys(normalizedMatch).length
44
+ ? { name, match: normalizedMatch }
45
+ : { name };
46
+ }
47
+
48
+ /*
49
+ * Build unconstrained structured reset targets for a list of GraphQL queries.
50
+ */
51
+
52
+ export function makeQueryResetTargets(...names: string[]) {
53
+ return names.map((name) => makeQueryResetTarget(name));
54
+ }
55
+
56
+ /*
57
+ * Parse one serialized variables key ('$a:1$b:2') into its variable/value
58
+ * pairs. Values are collected per name because a serialized JSON variable can
59
+ * itself contain '$' and split into extra segments; keeping every candidate
60
+ * prevents a structured target from missing a matching serialized variable.
61
+ */
62
+
63
+ function parseVariablesKeySegments(variablesKey: string) {
64
+ const pairs: Record<string, string[]> = {};
65
+
66
+ for (const segment of variablesKey.split('$')) {
67
+ const separatorIndex = segment.indexOf(':');
68
+ if (separatorIndex < 1) {
69
+ continue;
70
+ }
71
+
72
+ const variableName = segment.slice(0, separatorIndex);
73
+ const value = segment.slice(separatorIndex + 1);
74
+ if (pairs[variableName]) {
75
+ pairs[variableName].push(value);
76
+ } else {
77
+ pairs[variableName] = [value];
78
+ }
79
+ }
80
+
81
+ return pairs;
82
+ }
83
+
84
+ /*
85
+ * Return whether one cached query key is covered by a structured reset target.
86
+ * A target with no match constraints covers every page of that query, which is
87
+ * what the plain '#queryName:' prefix keys have always done.
88
+ */
89
+
90
+ export function queryCacheKeyMatchesResetTarget(
91
+ queryCacheKey: string,
92
+ target: QueryResetTarget,
93
+ ) {
94
+ const queryPrefix = `#${target.name}:`;
95
+ if (!queryCacheKey.startsWith(queryPrefix)) {
96
+ return false;
97
+ }
98
+
99
+ const matchEntries = Object.entries(target.match || {});
100
+ if (!matchEntries.length) {
101
+ return true;
102
+ }
103
+
104
+ const pairs = parseVariablesKeySegments(
105
+ queryCacheKey.slice(queryPrefix.length),
106
+ );
107
+ return matchEntries.every(([variableName, value]) =>
108
+ Boolean(pairs[variableName]?.includes(value)),
109
+ );
110
+ }
111
+
112
+ /*
113
+ * Return whether any target in a list covers one cached query key.
114
+ */
115
+
116
+ export function queryCacheKeyMatchesAnyResetTarget(
117
+ queryCacheKey: string,
118
+ targets: QueryResetTarget[],
119
+ ) {
120
+ return targets.some((target) =>
121
+ queryCacheKeyMatchesResetTarget(queryCacheKey, target),
122
+ );
123
+ }
124
+
125
+ /*
126
+ * Remove targets that duplicate an earlier one by value. Structured targets are
127
+ * plain objects, so they need stable value identities for deduplication.
128
+ */
129
+
130
+ export function dedupeQueryResetTargets(targets: QueryResetTarget[]) {
131
+ const seenIds = new Set<string>();
132
+
133
+ return targets.filter((target) => {
134
+ const targetId = getQueryResetTargetId(target);
135
+ if (seenIds.has(targetId)) {
136
+ return false;
137
+ }
138
+
139
+ seenIds.add(targetId);
140
+ return true;
141
+ });
142
+ }
143
+
144
+ /*
145
+ * Build the structured reset field for websocket payload builders that measure
146
+ * their complete packet before publishing.
147
+ */
148
+
149
+ export function buildResetQueryPayloadFields(
150
+ targets?: QueryResetTarget[] | null,
151
+ ) {
152
+ if (!targets?.length) {
153
+ return { resetQueries: undefined };
154
+ }
155
+
156
+ return {
157
+ resetQueries: targets,
158
+ };
159
+ }
160
+
161
+ /*
162
+ * Return a stable identity string for one target. Used as the query observer
163
+ * event name where a single string is required; the '~' prefix keeps it from
164
+ * colliding with a real cache key.
165
+ */
166
+
167
+ export function getQueryResetTargetId(target: QueryResetTarget) {
168
+ const matchEntries = Object.entries(target.match || {});
169
+
170
+ if (!matchEntries.length) {
171
+ return `~#${target.name}:`;
172
+ }
173
+
174
+ const matchers = matchEntries
175
+ .map(([variableName, value]) => `$${variableName}:${value}`)
176
+ .join('');
177
+
178
+ return `~#${target.name}:${matchers}`;
179
+ }