-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathutils.ts
More file actions
1267 lines (1105 loc) · 37.3 KB
/
utils.ts
File metadata and controls
1267 lines (1105 loc) · 37.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import FormData from 'form-data';
import type {
AscDesc,
ChannelFilters,
ChannelQueryOptions,
ChannelSort,
ChannelSortBase,
LocalMessage,
LocalMessageBase,
Logger,
Message,
MessagePaginationOptions,
MessageResponse,
MessageResponseBase,
MessageSet,
OwnUserBase,
OwnUserResponse,
PromoteChannelParams,
QueryChannelAPIResponse,
ReactionGroupResponse,
UpdatedMessage,
UserResponse,
} from './types';
import type { StreamChat } from './client';
import type { Channel } from './channel';
import type { AxiosRequestConfig } from 'axios';
import { LOCAL_MESSAGE_FIELDS, RESERVED_UPDATED_MESSAGE_FIELDS } from './constants';
/**
* logChatPromiseExecution - utility function for logging the execution of a promise..
* use this when you want to run the promise and handle errors by logging a warning
*
* @param {Promise<T>} promise The promise you want to run and log
* @param {string} name A descriptive name of what the promise does for log output
*
*/
export function logChatPromiseExecution<T>(promise: Promise<T>, name: string) {
promise.then().catch((error) => {
console.warn(`failed to do ${name}, ran into error: `, error);
});
}
export const sleep = (m: number): Promise<void> => new Promise((r) => setTimeout(r, m));
export function isFunction(value: unknown): value is (...args: unknown[]) => unknown {
return (
typeof value === 'function' ||
value instanceof Function ||
Object.prototype.toString.call(value) === '[object Function]'
);
}
export const chatCodes = {
TOKEN_EXPIRED: 40,
WS_CLOSED_SUCCESS: 1000,
};
function isReadableStream(obj: unknown): obj is NodeJS.ReadStream {
return (
obj !== null &&
typeof obj === 'object' &&
((obj as NodeJS.ReadStream).readable ||
typeof (obj as NodeJS.ReadStream)._read === 'function')
);
}
function isBuffer(obj: unknown): obj is Buffer {
return (
obj != null &&
(obj as Buffer).constructor != null &&
// @ts-expect-error expected
typeof obj.constructor.isBuffer === 'function' &&
// @ts-expect-error expected
obj.constructor.isBuffer(obj)
);
}
function isFileWebAPI(uri: unknown): uri is File {
return typeof window !== 'undefined' && 'File' in window && uri instanceof File;
}
export function isOwnUser(
user?: OwnUserResponse | UserResponse,
): user is OwnUserResponse {
return (user as OwnUserResponse)?.total_unread_count !== undefined;
}
function isBlobWebAPI(uri: unknown): uri is Blob {
return typeof window !== 'undefined' && 'Blob' in window && uri instanceof Blob;
}
export function isOwnUserBaseProperty(property: string) {
const ownUserBaseProperties: {
[Property in keyof Required<OwnUserBase>]: boolean;
} = {
channel_mutes: true,
devices: true,
mutes: true,
total_unread_count: true,
unread_channels: true,
unread_count: true,
unread_threads: true,
invisible: true,
privacy_settings: true,
roles: true,
push_preferences: true,
};
return ownUserBaseProperties[property as keyof OwnUserBase];
}
export function addFileToFormData(
uri: string | NodeJS.ReadableStream | Buffer | File,
name?: string,
contentType?: string,
) {
const data = new FormData();
if (isReadableStream(uri) || isBuffer(uri) || isFileWebAPI(uri) || isBlobWebAPI(uri)) {
if (name) data.append('file', uri, name);
else data.append('file', uri);
} else {
data.append('file', {
uri,
name: name || (uri as string).split('/').reverse()[0],
contentType: contentType || undefined,
type: contentType || undefined,
});
}
return data;
}
export function normalizeQuerySort<T extends Record<string, AscDesc | undefined>>(
sort: T | T[],
) {
const sortFields: Array<{ direction: AscDesc; field: keyof T }> = [];
const sortArr = Array.isArray(sort) ? sort : [sort];
for (const item of sortArr) {
const entries = Object.entries(item) as [keyof T, AscDesc][];
if (entries.length > 1) {
console.warn(
"client._buildSort() - multiple fields in a single sort object detected. Object's field order is not guaranteed",
);
}
for (const [field, direction] of entries) {
sortFields.push({ field, direction });
}
}
return sortFields;
}
/**
* retryInterval - A retry interval which increases acc to number of failures
*
* @return {number} Duration to wait in milliseconds
*/
export function retryInterval(numberOfFailures: number) {
// try to reconnect in 0.25-25 seconds (random to spread out the load from failures)
const max = Math.min(500 + numberOfFailures * 2000, 25000);
const min = Math.min(Math.max(250, (numberOfFailures - 1) * 2000), 25000);
return Math.floor(Math.random() * (max - min) + min);
}
export function randomId() {
return generateUUIDv4();
}
function hex(bytes: Uint8Array): string {
let s = '';
for (let i = 0; i < bytes.length; i++) {
s += bytes[i].toString(16).padStart(2, '0');
}
return s;
}
// https://tools.ietf.org/html/rfc4122
export function generateUUIDv4() {
const bytes = getRandomBytes(16);
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version
bytes[8] = (bytes[8] & 0xbf) | 0x80; // variant
return (
hex(bytes.subarray(0, 4)) +
'-' +
hex(bytes.subarray(4, 6)) +
'-' +
hex(bytes.subarray(6, 8)) +
'-' +
hex(bytes.subarray(8, 10)) +
'-' +
hex(bytes.subarray(10, 16))
);
}
function getRandomValuesWithMathRandom(bytes: Uint8Array): void {
const max = Math.pow(2, (8 * bytes.byteLength) / bytes.length);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = Math.random() * max;
}
}
declare const msCrypto: Crypto;
const getRandomValues = (() => {
if (typeof crypto !== 'undefined' && typeof crypto?.getRandomValues !== 'undefined') {
return crypto.getRandomValues.bind(crypto);
} else if (typeof msCrypto !== 'undefined') {
return msCrypto.getRandomValues.bind(msCrypto);
} else {
return getRandomValuesWithMathRandom;
}
})();
function getRandomBytes(length: number): Uint8Array {
const bytes = new Uint8Array(length);
getRandomValues(bytes);
return bytes;
}
export function convertErrorToJson(err: Error) {
const jsonObj = {} as Record<string, unknown>;
if (!err) return jsonObj;
try {
Object.getOwnPropertyNames(err).forEach((key) => {
jsonObj[key] = Object.getOwnPropertyDescriptor(err, key);
});
} catch (_) {
return {
error: 'failed to serialize the error',
};
}
return jsonObj;
}
/**
* isOnline safely return the navigator.online value for browser env
* if navigator is not in global object, it always return true
*/
export function isOnline() {
const nav =
typeof navigator !== 'undefined'
? navigator
: typeof window !== 'undefined' && window.navigator
? window.navigator
: undefined;
if (!nav) {
console.warn(
'isOnline failed to access window.navigator and assume browser is online',
);
return true;
}
// RN navigator has undefined for onLine
if (typeof nav.onLine !== 'boolean') {
return true;
}
return nav.onLine;
}
/**
* listenForConnectionChanges - Adds an event listener fired on browser going online or offline
*/
export function addConnectionEventListeners(cb: (e: Event) => void) {
if (typeof window !== 'undefined' && window.addEventListener) {
window.addEventListener('offline', cb);
window.addEventListener('online', cb);
}
}
export function removeConnectionEventListeners(cb: (e: Event) => void) {
if (typeof window !== 'undefined' && window.removeEventListener) {
window.removeEventListener('offline', cb);
window.removeEventListener('online', cb);
}
}
export const axiosParamsSerializer: AxiosRequestConfig['paramsSerializer'] = (params) => {
const newParams = [];
for (const k in params) {
// Stream backend doesn't treat "undefined" value same as value not being present.
// So, we need to skip the undefined values.
if (params[k] === undefined) continue;
if (Array.isArray(params[k]) || typeof params[k] === 'object') {
newParams.push(`${k}=${encodeURIComponent(JSON.stringify(params[k]))}`);
} else {
newParams.push(`${k}=${encodeURIComponent(params[k])}`);
}
}
return newParams.join('&');
};
/**
* Takes the message object, parses the dates, sets `__html`
* and sets the status to `received` if missing; returns a new LocalMessage object.
*
* @param {LocalMessage} message `LocalMessage` object
*/
export function formatMessage(
message: MessageResponse | MessageResponseBase | LocalMessage,
): LocalMessage {
const toLocalMessageBase = (
msg: MessageResponse | MessageResponseBase | LocalMessage | null | undefined,
): LocalMessageBase | null => {
if (!msg) return null;
return {
...msg,
created_at: message.created_at ? new Date(message.created_at) : new Date(),
deleted_at: message.deleted_at ? new Date(message.deleted_at) : null,
pinned_at: message.pinned_at ? new Date(message.pinned_at) : null,
reaction_groups: maybeGetReactionGroupsFallback(
message.reaction_groups,
message.reaction_counts,
message.reaction_scores,
),
status: message.status || 'received',
updated_at: message.updated_at ? new Date(message.updated_at) : new Date(),
};
};
return {
...toLocalMessageBase(message),
error: (message as LocalMessage).error ?? null,
quoted_message: toLocalMessageBase((message as MessageResponse).quoted_message),
} as LocalMessage;
}
/**
* @private
*
* Takes a LocalMessage, parses the dates back to strings,
* and converts the message back to a MessageResponse.
*
* @param {MessageResponse} message `MessageResponse` object
*/
export function unformatMessage(message: LocalMessage): MessageResponse {
const toMessageResponseBase = (
msg: LocalMessage | null | undefined,
): MessageResponseBase | null => {
if (!msg) return null;
const newDateString = new Date().toISOString();
return {
...msg,
created_at: message.created_at ? message.created_at.toISOString() : newDateString,
deleted_at: message.deleted_at ? message.deleted_at.toISOString() : undefined,
pinned_at: message.pinned_at ? message.pinned_at.toISOString() : undefined,
updated_at: message.updated_at ? message.updated_at.toISOString() : newDateString,
};
};
return {
...toMessageResponseBase(message),
quoted_message: toMessageResponseBase((message as LocalMessage).quoted_message),
} as MessageResponse;
}
export const localMessageToNewMessagePayload = (localMessage: LocalMessage): Message => {
/* eslint-disable @typescript-eslint/no-unused-vars */
const {
// Remove all timestamp fields and client-specific fields.
// Field pinned_at can therefore be earlier than created_at as new message payload can hold it.
created_at,
updated_at,
deleted_at,
// Client-specific fields
error,
status,
// Reaction related fields
latest_reactions,
own_reactions,
reaction_counts,
reaction_scores,
reply_count,
// Message text related fields that shouldn't be in update
command,
html,
i18n,
quoted_message,
mentioned_users,
// Message content related fields
...messageFields
} = localMessage;
return {
...messageFields,
pinned_at: messageFields.pinned_at?.toISOString(),
mentioned_users: mentioned_users?.map((user) => user.id),
};
};
export const toUpdatedMessagePayload = (
message: LocalMessage | Partial<MessageResponse>,
): UpdatedMessage => {
const reservedKeys = {
...RESERVED_UPDATED_MESSAGE_FIELDS,
...LOCAL_MESSAGE_FIELDS,
} as const;
const messageFields = Object.fromEntries(
Object.entries(message).filter(
([key]) => !reservedKeys[key as keyof typeof reservedKeys],
),
) as UpdatedMessage;
return {
...messageFields,
pinned: !!message.pinned_at,
mentioned_users: message.mentioned_users?.map((user) =>
typeof user === 'string' ? user : user.id,
),
};
};
export const findIndexInSortedArray = <T, L>({
needle,
sortedArray,
selectKey,
selectValueToCompare = (e) => e,
sortDirection = 'ascending',
}: {
needle: T;
sortedArray: readonly T[];
/**
* In an array of objects (like messages), pick a unique property identifying
* an element. It will be used to find a direct match for the needle element
* in case compare values are not unique.
*
* @example
* ```ts
* selectKey: (message) => message.id
* ```
*/
selectKey?: (arrayElement: T) => string;
/**
* In an array of objects (like messages), pick a specific
* property to compare the needle value to.
*
* @example
* ```ts
* selectValueToCompare: (message) => message.created_at.getTime()
* ```
*/
selectValueToCompare?: (arrayElement: T) => L | T;
/**
* @default ascending
* @description
* ```md
* ascending - [1,2,3,4,5...]
* descending - [...5,4,3,2,1]
* ```
*/
sortDirection?: 'ascending' | 'descending';
}) => {
if (!sortedArray.length) return 0;
let left = 0;
let right = sortedArray.length - 1;
let middle = 0;
const recalculateMiddle = () => {
middle = Math.round((left + right) / 2);
};
const comparableNeedle = selectValueToCompare(needle);
while (left <= right) {
recalculateMiddle();
const comparableMiddle = selectValueToCompare(sortedArray[middle]);
if (
(sortDirection === 'ascending' && comparableNeedle < comparableMiddle) ||
(sortDirection === 'descending' && comparableNeedle >= comparableMiddle)
) {
right = middle - 1;
} else {
left = middle + 1;
}
}
// In case there are several array elements with the same comparable value, search around the insertion
// point to possibly find an element with the same key. If found, prefer it.
// This, for example, prevents duplication of messages with the same creation date.
if (selectKey) {
const needleKey = selectKey(needle);
const step = sortDirection === 'ascending' ? -1 : +1;
for (
let i = left + step;
0 <= i &&
i < sortedArray.length &&
selectValueToCompare(sortedArray[i]) === comparableNeedle;
i += step
) {
if (selectKey(sortedArray[i]) === needleKey) {
return i;
}
}
}
return left;
};
export function addToMessageList<T extends LocalMessage>(
messages: readonly T[],
newMessage: T,
timestampChanged = false,
sortBy: 'pinned_at' | 'created_at' = 'created_at',
addIfDoesNotExist = true,
) {
const addMessageToList = addIfDoesNotExist || timestampChanged;
let newMessages = [...messages];
// if created_at has changed, message should be filtered and re-inserted in correct order
// slow op but usually this only happens for a message inserted to state before actual response with correct timestamp
if (timestampChanged) {
newMessages = newMessages.filter(
(message) => !(message.id && newMessage.id === message.id),
);
}
// for empty list just concat and return unless it's an update or deletion
if (newMessages.length === 0 && addMessageToList) {
return newMessages.concat(newMessage);
} else if (newMessages.length === 0) {
return newMessages;
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const messageTime = newMessage[sortBy]!.getTime();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const messageIsNewest = newMessages.at(-1)![sortBy]!.getTime() < messageTime;
// if message is newer than last item in the list concat and return unless it's an update or deletion
if (messageIsNewest && addMessageToList) {
return newMessages.concat(newMessage);
} else if (messageIsNewest) {
return newMessages;
}
// find the closest index to push the new message
const insertionIndex = findIndexInSortedArray({
needle: newMessage,
sortedArray: newMessages,
sortDirection: 'ascending',
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
selectValueToCompare: (m) => m[sortBy]!.getTime(),
selectKey: (m) => m.id,
});
// message already exists and not filtered with timestampChanged, update and return
if (
!timestampChanged &&
newMessage.id &&
newMessages[insertionIndex] &&
newMessage.id === newMessages[insertionIndex].id
) {
newMessages[insertionIndex] = newMessage;
return newMessages;
}
// do not add updated or deleted messages to the list if they already exist or come with a timestamp change
if (addMessageToList) {
newMessages.splice(insertionIndex, 0, newMessage);
}
return newMessages;
}
function maybeGetReactionGroupsFallback(
groups: { [key: string]: ReactionGroupResponse } | null | undefined,
counts: { [key: string]: number } | null | undefined,
scores: { [key: string]: number } | null | undefined,
): { [key: string]: ReactionGroupResponse } | null {
if (groups) {
return groups;
}
if (counts && scores) {
const fallback: { [key: string]: ReactionGroupResponse } = {};
for (const type of Object.keys(counts)) {
fallback[type] = {
count: counts[type],
sum_scores: scores[type],
};
}
return fallback;
}
return null;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface DebouncedFunc<T extends (...args: any[]) => any> {
/**
* Call the original function, but applying the debounce rules.
*
* If the debounced function can be run immediately, this calls it and returns its return
* value.
*
* Otherwise, it returns the return value of the last invocation, or undefined if the debounced
* function was not invoked yet.
*/
(...args: Parameters<T>): ReturnType<T> | undefined;
/**
* Throw away any pending invocation of the debounced function.
*/
cancel(): void;
/**
* If there is a pending invocation of the debounced function, invoke it immediately and return
* its return value.
*
* Otherwise, return the value from the last invocation, or undefined if the debounced function
* was never invoked.
*/
flush(): ReturnType<T> | undefined;
}
// works exactly the same as lodash.debounce
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const debounce = <T extends (...args: any[]) => any>(
fn: T,
timeout = 0,
{ leading = false, trailing = true }: { leading?: boolean; trailing?: boolean } = {},
): DebouncedFunc<T> => {
let runningTimeout: null | NodeJS.Timeout = null;
let argsForTrailingExecution: Parameters<T> | null = null;
let lastResult: ReturnType<T> | undefined;
const debouncedFn = (...args: Parameters<T>) => {
if (runningTimeout) {
clearTimeout(runningTimeout);
} else if (leading) {
lastResult = fn(...args);
}
if (trailing) argsForTrailingExecution = args;
const timeoutHandler = () => {
if (argsForTrailingExecution) {
lastResult = fn(...argsForTrailingExecution);
argsForTrailingExecution = null;
}
runningTimeout = null;
};
runningTimeout = setTimeout(timeoutHandler, timeout);
return lastResult;
};
debouncedFn.cancel = () => {
if (runningTimeout) clearTimeout(runningTimeout);
};
debouncedFn.flush = () => {
if (runningTimeout) {
clearTimeout(runningTimeout);
runningTimeout = null;
if (argsForTrailingExecution) {
lastResult = fn(...argsForTrailingExecution);
}
}
return lastResult;
};
return debouncedFn;
};
// works exactly the same as lodash.throttle
export const throttle = <T extends (...args: unknown[]) => unknown>(
fn: T,
timeout = 200,
{ leading = true, trailing = false }: { leading?: boolean; trailing?: boolean } = {},
) => {
let runningTimeout: null | NodeJS.Timeout = null;
let storedArgs: Parameters<T> | null = null;
return (...args: Parameters<T>) => {
if (runningTimeout) {
if (trailing) storedArgs = args;
return;
}
if (leading) fn(...args);
const timeoutHandler = () => {
if (storedArgs) {
fn(...storedArgs);
storedArgs = null;
runningTimeout = setTimeout(timeoutHandler, timeout);
return;
}
runningTimeout = null;
};
runningTimeout = setTimeout(timeoutHandler, timeout);
};
};
const get = <T>(obj: T, path: string): unknown =>
path.split('.').reduce<unknown>((acc, key) => {
if (acc && typeof acc === 'object' && key in acc) {
return (acc as Record<string, unknown>)[key];
}
return undefined;
}, obj);
// works exactly the same as lodash.uniqBy
export const uniqBy = <T>(
array: T[] | unknown,
iteratee: ((item: T) => unknown) | keyof T,
): T[] => {
if (!Array.isArray(array)) return [];
const seen = new Set<unknown>();
return array.filter((item) => {
const key =
typeof iteratee === 'function' ? iteratee(item) : get(item, iteratee as string);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
};
type MessagePaginationUpdatedParams = {
parentSet: MessageSet;
requestedPageSize: number;
returnedPage: MessageResponse[];
logger?: Logger;
messagePaginationOptions?: MessagePaginationOptions;
};
export function binarySearchByDateEqualOrNearestGreater(
array: {
created_at?: string;
}[],
targetDate: Date,
): number {
let left = 0;
let right = array.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const midCreatedAt = array[mid].created_at;
if (!midCreatedAt) {
left += 1;
continue;
}
const midDate = new Date(midCreatedAt);
if (midDate.getTime() === targetDate.getTime()) {
return mid;
} else if (midDate.getTime() < targetDate.getTime()) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left;
}
const messagePaginationCreatedAtAround = ({
parentSet,
requestedPageSize,
returnedPage,
messagePaginationOptions,
}: MessagePaginationUpdatedParams) => {
const newPagination = { ...parentSet.pagination };
if (!messagePaginationOptions?.created_at_around) return newPagination;
let hasPrev;
let hasNext;
let updateHasPrev;
let updateHasNext;
const createdAtAroundDate = new Date(messagePaginationOptions.created_at_around);
const [firstPageMsg, lastPageMsg] = [returnedPage[0], returnedPage.slice(-1)[0]];
// expect ASC order (from oldest to newest)
const wholePageHasNewerMessages =
!!firstPageMsg?.created_at && new Date(firstPageMsg.created_at) > createdAtAroundDate;
const wholePageHasOlderMessages =
!!lastPageMsg?.created_at && new Date(lastPageMsg.created_at) < createdAtAroundDate;
const requestedPageSizeNotMet =
requestedPageSize > parentSet.messages.length &&
requestedPageSize > returnedPage.length;
const noMoreMessages =
(requestedPageSize > parentSet.messages.length ||
parentSet.messages.length >= returnedPage.length) &&
requestedPageSize > returnedPage.length;
if (wholePageHasNewerMessages) {
hasPrev = false;
updateHasPrev = true;
if (requestedPageSizeNotMet) {
hasNext = false;
updateHasNext = true;
}
} else if (wholePageHasOlderMessages) {
hasNext = false;
updateHasNext = true;
if (requestedPageSizeNotMet) {
hasPrev = false;
updateHasPrev = true;
}
} else if (noMoreMessages) {
hasNext = hasPrev = false;
updateHasPrev = updateHasNext = true;
} else {
const [firstPageMsgIsFirstInSet, lastPageMsgIsLastInSet] = [
firstPageMsg?.id && firstPageMsg.id === parentSet.messages[0]?.id,
lastPageMsg?.id && lastPageMsg.id === parentSet.messages.slice(-1)[0]?.id,
];
updateHasPrev = firstPageMsgIsFirstInSet;
updateHasNext = lastPageMsgIsLastInSet;
const midPointByCount = Math.floor(returnedPage.length / 2);
const midPointByCreationDate = binarySearchByDateEqualOrNearestGreater(
returnedPage,
createdAtAroundDate,
);
if (midPointByCreationDate !== -1) {
hasPrev = midPointByCount <= midPointByCreationDate;
hasNext = midPointByCount >= midPointByCreationDate;
}
}
if (updateHasPrev && typeof hasPrev !== 'undefined') newPagination.hasPrev = hasPrev;
if (updateHasNext && typeof hasNext !== 'undefined') newPagination.hasNext = hasNext;
return newPagination;
};
const messagePaginationIdAround = ({
parentSet,
requestedPageSize,
returnedPage,
messagePaginationOptions,
}: MessagePaginationUpdatedParams) => {
const newPagination = { ...parentSet.pagination };
const { id_around } = messagePaginationOptions || {};
if (!id_around) return newPagination;
let hasPrev;
let hasNext;
const [firstPageMsg, lastPageMsg] = [returnedPage[0], returnedPage.slice(-1)[0]];
const [firstPageMsgIsFirstInSet, lastPageMsgIsLastInSet] = [
firstPageMsg?.id === parentSet.messages[0]?.id,
lastPageMsg?.id === parentSet.messages.slice(-1)[0]?.id,
];
let updateHasPrev = firstPageMsgIsFirstInSet;
let updateHasNext = lastPageMsgIsLastInSet;
const midPoint = Math.floor(returnedPage.length / 2);
const noMoreMessages =
(requestedPageSize > parentSet.messages.length ||
parentSet.messages.length >= returnedPage.length) &&
requestedPageSize > returnedPage.length;
if (noMoreMessages) {
hasNext = hasPrev = false;
updateHasPrev = updateHasNext = true;
} else if (!returnedPage[midPoint]) {
return newPagination;
} else if (returnedPage[midPoint].id === id_around) {
hasPrev = hasNext = true;
} else {
let targetMsg;
const halves = [returnedPage.slice(0, midPoint), returnedPage.slice(midPoint)];
hasPrev = hasNext = true;
for (let i = 0; i < halves.length; i++) {
targetMsg = halves[i].find((message) => message.id === id_around);
if (targetMsg && i === 0) {
hasPrev = false;
}
if (targetMsg && i === 1) {
hasNext = false;
}
}
}
if (updateHasPrev && typeof hasPrev !== 'undefined') newPagination.hasPrev = hasPrev;
if (updateHasNext && typeof hasNext !== 'undefined') newPagination.hasNext = hasNext;
return newPagination;
};
const messagePaginationLinear = ({
parentSet,
requestedPageSize,
returnedPage,
messagePaginationOptions,
}: MessagePaginationUpdatedParams) => {
const newPagination = { ...parentSet.pagination };
let hasPrev;
let hasNext;
const [firstPageMsg, lastPageMsg] = [returnedPage[0], returnedPage.slice(-1)[0]];
const [firstPageMsgIsFirstInSet, lastPageMsgIsLastInSet] = [
firstPageMsg?.id && firstPageMsg.id === parentSet.messages[0]?.id,
lastPageMsg?.id && lastPageMsg.id === parentSet.messages.slice(-1)[0]?.id,
];
const queriedNextMessages =
messagePaginationOptions &&
(messagePaginationOptions.created_at_after_or_equal ||
messagePaginationOptions.created_at_after ||
messagePaginationOptions.id_gt ||
messagePaginationOptions.id_gte);
const queriedPrevMessages =
typeof messagePaginationOptions === 'undefined'
? true
: messagePaginationOptions.created_at_before_or_equal ||
messagePaginationOptions.created_at_before ||
messagePaginationOptions.id_lt ||
messagePaginationOptions.id_lte ||
messagePaginationOptions.offset;
const containsUnrecognizedOptionsOnly =
!queriedNextMessages &&
!queriedPrevMessages &&
!messagePaginationOptions?.id_around &&
!messagePaginationOptions?.created_at_around;
const hasMore = returnedPage.length >= requestedPageSize;
if (typeof queriedPrevMessages !== 'undefined' || containsUnrecognizedOptionsOnly) {
hasPrev = hasMore;
}
if (typeof queriedNextMessages !== 'undefined') {
hasNext = hasMore;
}
const returnedPageIsEmpty = returnedPage.length === 0;
if ((firstPageMsgIsFirstInSet || returnedPageIsEmpty) && typeof hasPrev !== 'undefined')
newPagination.hasPrev = hasPrev;
if ((lastPageMsgIsLastInSet || returnedPageIsEmpty) && typeof hasNext !== 'undefined')
newPagination.hasNext = hasNext;
return newPagination;
};
export const messageSetPagination = (params: MessagePaginationUpdatedParams) => {
const messagesFilteredLocally = params.returnedPage.filter(({ shadowed }) => shadowed);
if (
params.parentSet.messages.length + messagesFilteredLocally.length <
params.returnedPage.length
) {
params.logger?.(
'error',
'Corrupted message set state: parent set size < returned page size',
);
return params.parentSet.pagination;
}
if (params.messagePaginationOptions?.created_at_around) {
return messagePaginationCreatedAtAround(params);
} else if (params.messagePaginationOptions?.id_around) {
return messagePaginationIdAround(params);
} else {
return messagePaginationLinear(params);
}
};
/**
* A utility object used to prevent duplicate invocation of channel.watch() to be triggered when
* 'notification.message_new' and 'notification.added_to_channel' events arrive at the same time.
*/
const WATCH_QUERY_IN_PROGRESS_FOR_CHANNEL: Record<
string,
Promise<QueryChannelAPIResponse> | undefined
> = {};
type GetChannelParams = {
client: StreamChat;
channel?: Channel;
id?: string;
members?: string[];
options?: ChannelQueryOptions;
type?: string;
};
/**
* Calls channel.watch() if it was not already recently called. Waits for watch promise to resolve even if it was invoked previously.
* If the channel is not passed as a property, it will get it either by its channel.cid or by its members list and do the same.
* @param client
* @param members
* @param options
* @param type
* @param id
* @param channel