stream-chat 10.0.0-rc.21 → 10.0.0-rc.22

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 (33) hide show
  1. package/dist/cjs/index.browser.js +308 -216
  2. package/dist/cjs/index.browser.js.map +3 -3
  3. package/dist/cjs/index.node.js +308 -216
  4. package/dist/cjs/index.node.js.map +3 -3
  5. package/dist/esm/index.mjs +311 -219
  6. package/dist/esm/index.mjs.map +4 -4
  7. package/dist/types/client.d.ts +22 -21
  8. package/dist/types/configuration/types.d.ts +31 -0
  9. package/dist/types/messageComposer/linkPreviewsManager.d.ts +2 -2
  10. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +14 -0
  11. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -4
  12. package/dist/types/pagination/paginators/BasePaginator.d.ts +5 -1
  13. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +2 -0
  14. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +5 -3
  15. package/dist/types/pagination/paginators/MessagePaginator.d.ts +5 -1
  16. package/dist/types/types.d.ts +1 -39
  17. package/package.json +7 -2
  18. package/src/ChannelManager.ts +7 -0
  19. package/src/EventHandlerPipeline.ts +2 -1
  20. package/src/api-client.ts +14 -8
  21. package/src/channel.ts +10 -0
  22. package/src/client.ts +44 -43
  23. package/src/configuration/keys.ts +5 -0
  24. package/src/configuration/shape.ts +36 -0
  25. package/src/configuration/types.ts +31 -0
  26. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +30 -0
  27. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +12 -60
  28. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  29. package/src/pagination/paginators/BasePaginator.ts +43 -18
  30. package/src/pagination/paginators/ChannelPaginator.ts +39 -14
  31. package/src/pagination/paginators/MessageIntervalPaginator.ts +17 -11
  32. package/src/pagination/paginators/MessagePaginator.ts +51 -5
  33. package/src/types.ts +1 -40
package/src/client.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /* eslint no-unused-vars: "off" */
2
2
  /* global process */
3
3
 
4
- import type { AxiosInstance } from 'axios';
4
+ import type { AxiosInstance, AxiosRequestConfig } from 'axios';
5
5
  import axios from 'axios';
6
6
 
7
7
  import type { Channel } from './channel';
@@ -48,7 +48,6 @@ import type {
48
48
  QueryThreadsRequest,
49
49
  ReactionResponse,
50
50
  SdkIdentifier,
51
- StreamChatOptions,
52
51
  StreamRequestOptions,
53
52
  TimestampNS,
54
53
  TokenOrProvider,
@@ -80,7 +79,8 @@ import type { AbstractOfflineDB } from './offline-support';
80
79
  import { FixedSizeQueueCache } from './utils/FixedSizeQueueCache';
81
80
  import { isEqual } from './utils/mergeWith/mergeWithCore';
82
81
  import type { MessageComposer } from './messageComposer';
83
- import type { InstanceSetupState } from './configuration';
82
+ import type { InstanceConfigTree, InstanceSetupState } from './configuration';
83
+ import type { DeepPartial } from './types.utility';
84
84
  import { InstanceConfigurationRegistry } from './configuration/InstanceConfigurationRegistry';
85
85
  import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
86
86
  import { StateStore } from '@stream-io/state-store';
@@ -203,10 +203,8 @@ export class StreamChat extends ChatApi {
203
203
  offlineDb?: AbstractOfflineDB;
204
204
  notifications: NotificationManager;
205
205
  reminders: ReminderManager;
206
- persistUserOnConnectionFailure?: boolean;
207
206
  axiosInstance: AxiosInstance;
208
207
  baseURL?: string;
209
- browser: boolean;
210
208
  cleaningIntervalRef?: ReturnType<typeof setTimeout>;
211
209
  clientId?: string;
212
210
  key: string;
@@ -231,8 +229,6 @@ export class StreamChat extends ChatApi {
231
229
  */
232
230
  readonly channelServerConfigsStore: StateStore<ChannelConfigsState>;
233
231
  blockedUsers: StateStore<BlockedUsersState>;
234
- node: boolean;
235
- options: StreamChatOptions;
236
232
  setUserPromise: ConnectAPIResponse | null;
237
233
  state: ClientState;
238
234
  tokenManager: TokenManager;
@@ -246,6 +242,16 @@ export class StreamChat extends ChatApi {
246
242
  private _resolveWsPromise?: (value: Awaited<ConnectAPIResponse>) => void;
247
243
  private _rejectWsPromise?: (reason?: unknown) => void;
248
244
 
245
+ /**
246
+ * Whether the client runs in a browser. `client.browser` in the configuration when set, otherwise
247
+ * whether a global `window` exists.
248
+ */
249
+ get browser(): boolean {
250
+ return this.config.getConfig('client')?.browser ?? typeof window !== 'undefined';
251
+ }
252
+ get node(): boolean {
253
+ return !this.browser;
254
+ }
249
255
  get anonymous(): boolean {
250
256
  return this.tokenManager.isAnonymous;
251
257
  }
@@ -293,16 +299,16 @@ export class StreamChat extends ChatApi {
293
299
  *
294
300
  * @example <caption>initialize the client in user mode</caption>
295
301
  * new StreamChat('api_key')
296
- * @example <caption>initialize the client with options</caption>
297
- * new StreamChat('api_key', { axiosRequestConfig: { timeout: 5000 } })
302
+ * @example <caption>initialize the client with configuration</caption>
303
+ * new StreamChat('api_key', { client: { axiosRequestConfig: { timeout: 5000 } } })
298
304
  *
299
305
  * @param key - The API key.
300
- * @param options - Additional options (optional).
301
- * @param options.browser - Enforce the client to be in browser mode (optional).
302
- * @param options.axiosRequestConfig - Axios-level request configuration such as `timeout`,
303
- * `headers` or `httpsAgent`, spread into the client's axios instance (optional).
306
+ * @param config - Declarative configuration, the same tree `client.config.set()` takes (optional).
307
+ * Seeded before anything is built, so it reaches the client's own managers and the fields that are
308
+ * read once during construction — `client.baseURL`, `client.axiosRequestConfig` and
309
+ * `client.notificationManager`.
304
310
  */
305
- constructor(key: string, options: StreamChatOptions = {}) {
311
+ constructor(key: string, config?: DeepPartial<InstanceConfigTree>) {
306
312
  // generated client requires ApiClient right away
307
313
  super(new ApiClient());
308
314
  // but ApiClient relies on properties defined here so we set it after (can't pass `this` in super call)
@@ -310,6 +316,12 @@ export class StreamChat extends ChatApi {
310
316
 
311
317
  // set the key
312
318
  this.key = key;
319
+
320
+ // Seeded before anything is built: the fields read once below come from the `client` slice, and the
321
+ // registry is a field initializer, so it exists from here on. Wiring the managers to it stays the last
322
+ // statement of the constructor.
323
+ if (config) this.config.set(config);
324
+ const clientConfig = this.config.getConfig('client');
313
325
  this.listeners = new Map();
314
326
  this.state = new ClientState({ client: this });
315
327
  // a list of channels to hide ws events from
@@ -324,22 +336,17 @@ export class StreamChat extends ChatApi {
324
336
 
325
337
  this.moderation = new Moderation(this);
326
338
 
327
- this.notifications = options?.notifications ?? new NotificationManager();
339
+ this.notifications = clientConfig?.notificationManager ?? new NotificationManager();
328
340
  this.uploadManager = new UploadManager(this);
329
341
 
330
- this.browser = options.browser ?? typeof window !== 'undefined';
331
- this.node = !this.browser;
332
-
333
- this.options = { ...options };
334
-
335
342
  this.axiosInstance = axios.create({
336
343
  timeout: 3000,
337
344
  withCredentials: false,
338
- ...this.options.axiosRequestConfig,
345
+ ...(clientConfig?.axiosRequestConfig as AxiosRequestConfig | undefined),
339
346
  paramsSerializer: axiosParamsSerializer,
340
347
  });
341
348
 
342
- this.setBaseURL(this.options.baseURL || 'https://chat.stream-io-api.com');
349
+ this.setBaseURL(clientConfig?.baseURL || 'https://chat.stream-io-api.com');
343
350
 
344
351
  const streamLocalTestRun = getEnv('STREAM_LOCAL_TEST_RUN');
345
352
  const streamLocalTestHost = getEnv('STREAM_LOCAL_TEST_HOST');
@@ -362,8 +369,6 @@ export class StreamChat extends ChatApi {
362
369
  this.setUserPromise = null;
363
370
  // keeps a reference to all the channels that are in use
364
371
 
365
- this.persistUserOnConnectionFailure = this.options?.persistUserOnConnectionFailure;
366
-
367
372
  this.tokenManager = new TokenManager();
368
373
 
369
374
  this.messageStore = new EntityStore<LocalMessage>({
@@ -385,11 +390,6 @@ export class StreamChat extends ChatApi {
385
390
  name: 'message-composer-cache',
386
391
  });
387
392
 
388
- // Seed the declarative configuration before wiring, so a tree passed via `options.config` reaches
389
- // the managers above. `'client'` is the one key that cannot be configured after construction —
390
- // this registry is born here, so there is no earlier moment for a caller to register anything.
391
- if (this.options.config) this.config.set(this.options.config);
392
-
393
393
  // Last statement: everything a setup function might reach now exists. Subscribing applies the
394
394
  // current configuration on the spot, which is the managers' one derivation — deriving here as
395
395
  // well would run every `initializeConfig` twice per construction. `StateStore.subscribe` fires
@@ -485,23 +485,24 @@ export class StreamChat extends ChatApi {
485
485
  *
486
486
  * This function always returns the same client instance to avoid issues raised by multiple client and WS connections.
487
487
  *
488
- * **After the first call, the client configuration will not change if the key or options parameters change.**
488
+ * **After the first call, the client configuration will not change if the key or config parameters change.**
489
489
  *
490
490
  * @example <caption>initialize the client in user mode</caption>
491
491
  * StreamChat.getInstance('api_key')
492
- * @example <caption>initialize the client with options</caption>
493
- * StreamChat.getInstance('api_key', { axiosRequestConfig: { timeout: 5000 } })
492
+ * @example <caption>initialize the client with configuration</caption>
493
+ * StreamChat.getInstance('api_key', { client: { axiosRequestConfig: { timeout: 5000 } } })
494
494
  *
495
495
  * @param key - The API key.
496
- * @param options - Additional options (optional).
497
- * @param options.browser - Enforce the client to be in browser mode (optional).
498
- * @param options.axiosRequestConfig - Axios-level request configuration such as `timeout`,
499
- * `headers` or `httpsAgent`, spread into the client's axios instance (optional).
496
+ * @param config - Declarative configuration, as for the constructor (optional). Ignored once the
497
+ * instance exists.
500
498
  * @returns The shared client instance.
501
499
  */
502
- public static getInstance(key: string, options?: StreamChatOptions): StreamChat {
500
+ public static getInstance(
501
+ key: string,
502
+ config?: DeepPartial<InstanceConfigTree>,
503
+ ): StreamChat {
503
504
  if (!StreamChat._instance) {
504
- StreamChat._instance = new StreamChat(key, options);
505
+ StreamChat._instance = new StreamChat(key, config);
505
506
  }
506
507
 
507
508
  return StreamChat._instance as StreamChat;
@@ -568,11 +569,11 @@ export class StreamChat extends ChatApi {
568
569
  );
569
570
  }
570
571
 
571
- if (this.node && !this.options.allowServerSideConnect) {
572
+ if (this.node && !this.config.getConfig('client')?.allowServerSideConnect) {
572
573
  logger
573
574
  .withExtraTags('connectUser')
574
575
  .warn(
575
- 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set "allowServerSideConnect: true" in the client options to disable this warning.',
576
+ 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set `client.allowServerSideConnect: true` in the client configuration to disable this warning.',
576
577
  );
577
578
  }
578
579
 
@@ -595,7 +596,7 @@ export class StreamChat extends ChatApi {
595
596
  // connectAnonymousUser(), which never sets setUserPromise, and a bare disconnectUser()
596
597
  // that already cleaned up.
597
598
  if (this.setUserPromise === setUserPromise && this.userId === user.id) {
598
- if (!this.persistUserOnConnectionFailure) {
599
+ if (!this.config.getConfig('client')?.persistUserOnConnectionFailure) {
599
600
  // No user is kept, so there is nothing left to reconnect as. Tearing the socket down with
600
601
  // it is the point: the application is expected to call `connectUser` again.
601
602
  this.disconnectUser();
@@ -888,11 +889,11 @@ export class StreamChat extends ChatApi {
888
889
  * @returns A promise that resolves when the connection is set up.
889
890
  */
890
891
  connectAnonymousUser = () => {
891
- if (this.node && !this.options.allowServerSideConnect) {
892
+ if (this.node && !this.config.getConfig('client')?.allowServerSideConnect) {
892
893
  logger
893
894
  .withExtraTags('connectAnonymousUser')
894
895
  .warn(
895
- 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set "allowServerSideConnect: true" in the client options to disable this warning.',
896
+ 'Do not use connectUser server-side. connectUser impacts MAU and concurrent connection usage, and therefore your bill. If you have a valid use case, set `client.allowServerSideConnect: true` in the client configuration to disable this warning.',
896
897
  );
897
898
  }
898
899
 
@@ -71,6 +71,11 @@ export const CONSTRUCTION_ONLY_CONFIG_PATHS: Readonly<Record<string, readonly st
71
71
  // `messagePaginator` was silent while the identical field under `channel`/`thread` warned — the same
72
72
  // read-once field, warned through one route and not the other.
73
73
  messagePaginator: ['initialCursor', 'initialOffset', 'unreadReferencePolicy'],
74
+ // Each is consumed while the client is being constructed — the axios instance, the base URL and the
75
+ // notification manager are built from it — so a value registered once the client exists never
76
+ // reaches them. `browser` and `persistUserOnConnectionFailure` are read when needed, so they are not
77
+ // listed.
78
+ client: ['axiosRequestConfig', 'baseURL', 'notificationManager'],
74
79
  channel: [
75
80
  'messagePaginator.initialCursor',
76
81
  'messagePaginator.initialOffset',
@@ -546,6 +546,30 @@ const WS_CONNECTION_FIELDS: Record<keyof WSConnectionConfig, ConfigNode> = {
546
546
  };
547
547
 
548
548
  const CLIENT_FIELDS: Record<keyof ClientDeclarativeConfig, ConfigNode> = {
549
+ allowServerSideConnect: {
550
+ description:
551
+ 'Silences the warning logged when `connectUser` is called server-side, where a connection counts towards MAU and concurrent-connection billing. Was `StreamChatOptions.allowServerSideConnect`.',
552
+ kind: 'value',
553
+ type: 'boolean',
554
+ },
555
+ axiosRequestConfig: {
556
+ description:
557
+ "Axios-level request configuration — `timeout`, `headers`, `httpsAgent` and so on. Built into the client's axios instance at construction; `headers` and `params` are also read on every request. Was `StreamChatOptions.axiosRequestConfig`.",
558
+ kind: 'value',
559
+ type: 'object',
560
+ },
561
+ baseURL: {
562
+ description:
563
+ 'Base URL of the API, such as `https://chat-proxy-dublin.stream-io-api.com`. Read at construction. Was `StreamChatOptions.baseURL`.',
564
+ kind: 'value',
565
+ type: 'string',
566
+ },
567
+ browser: {
568
+ description:
569
+ 'Enforces browser (`true`) or Node (`false`) mode; detected from the global `window` when absent. Read live, through `client.browser` and `client.node`. Was `StreamChatOptions.browser`.',
570
+ kind: 'value',
571
+ type: 'boolean',
572
+ },
549
573
  connectionRecovery: {
550
574
  description:
551
575
  'Bringing the channels, lists and threads you are reading back in line after a reconnect.',
@@ -563,11 +587,23 @@ const CLIENT_FIELDS: Record<keyof ClientDeclarativeConfig, ConfigNode> = {
563
587
  fields: NETWORK_CONNECTION_FIELDS,
564
588
  kind: 'group',
565
589
  },
590
+ notificationManager: {
591
+ description:
592
+ 'A pre-built `NotificationManager` to use instead of the client constructing its own, to share one between clients or hand over one that already holds notifications. Read at construction. Was `StreamChatOptions.notifications`.',
593
+ kind: 'value',
594
+ type: 'object',
595
+ },
566
596
  notifications: {
567
597
  description: 'The client-wide notification (toast) manager.',
568
598
  fields: NOTIFICATION_FIELDS,
569
599
  kind: 'group',
570
600
  },
601
+ persistUserOnConnectionFailure: {
602
+ description:
603
+ 'Keeps the user on the client when `connectUser` fails, so an application working offline keeps `client.user` and need not call `connectUser` again to retry. Read when a connect fails. Was `StreamChatOptions.persistUserOnConnectionFailure`.',
604
+ kind: 'value',
605
+ type: 'boolean',
606
+ },
571
607
  reminders: {
572
608
  description: 'Message reminders and their scheduling offsets.',
573
609
  fields: REMINDER_FIELDS,
@@ -1,3 +1,4 @@
1
+ import type { AxiosRequestConfig } from 'axios';
1
2
  import type { StreamChat } from '../client';
2
3
  import type {
3
4
  LiveLocationManager,
@@ -12,6 +13,7 @@ import type { MessageComposerConfig } from '../messageComposer/configuration/typ
12
13
  import type { Channel, ChannelConfig } from '../channel';
13
14
  import type { Thread, ThreadConfig } from '../thread';
14
15
  import type { ReminderManagerConfig } from '../reminders/ReminderManager';
16
+ import type { NotificationManager } from '../notifications/NotificationManager';
15
17
  import type { NotificationManagerConfig } from '../notifications/types';
16
18
  import type { MessageDeliveryReporterConfig } from '../messageDelivery/MessageDeliveryReporter';
17
19
  import type { ThreadManagerConfig } from '../thread_manager';
@@ -137,6 +139,35 @@ export type ThreadDeclarativeConfig = {
137
139
  };
138
140
 
139
141
  export type ClientDeclarativeConfig = {
142
+ /**
143
+ * Silences the warning `connectUser` / `connectAnonymousUser` log when called server-side, where a
144
+ * connection counts towards MAU and concurrent-connection billing. Read on every connect.
145
+ */
146
+ allowServerSideConnect?: boolean;
147
+ /**
148
+ * Axios-level request configuration — `timeout`, `headers`, `httpsAgent` and so on. Built into the
149
+ * client's axios instance once, at construction; `headers` and `params` are additionally read on every
150
+ * request. Copied when registered, so changing the object you passed afterwards has no effect — register
151
+ * a new value instead.
152
+ */
153
+ axiosRequestConfig?: AxiosRequestConfig;
154
+ /** Base URL of the API, such as `https://chat-proxy-dublin.stream-io-api.com`. Read once, at construction. */
155
+ baseURL?: string;
156
+ /** Enforces browser (`true`) or Node (`false`) mode; detected from the global `window` when absent. Read live, through `client.browser` and `client.node`. */
157
+ browser?: boolean;
158
+ /**
159
+ * A pre-built {@link NotificationManager} for the client to use instead of constructing its own — to
160
+ * share one between clients, or to hand over one that already holds notifications. Read once, at
161
+ * construction. The client still applies the `notifications` slice below to it, on top of any
162
+ * configuration the manager was constructed with.
163
+ */
164
+ notificationManager?: NotificationManager;
165
+ /**
166
+ * When true, the user stays on the client if `connectUser` fails, so a chat application working offline
167
+ * keeps `client.user` and does not have to call `connectUser` again to retry. Read when a connect fails,
168
+ * so it can be changed at any time.
169
+ */
170
+ persistUserOnConnectionFailure?: boolean;
140
171
  /**
141
172
  * Nested rather than top-level keys: each of these managers has exactly one parent — the client — so
142
173
  * there is nothing to say once and reuse, which is what a top-level key buys (**DEC-25**).
@@ -0,0 +1,30 @@
1
+ import type { Interval, PaginationFlags } from '../paginators';
2
+
3
+ /**
4
+ * Flags for a page centred on a point (`id_around` / `created_at_around`). The server splits the
5
+ * items around the point evenly and, when one side runs out, fills the rest from the other side. So
6
+ * on a full page a side that got less than the smaller half ran out. A page shorter than the limit
7
+ * holds everything on both sides.
8
+ */
9
+ export const deriveAroundPaginationFlags = ({
10
+ interval,
11
+ newerCount,
12
+ olderCount,
13
+ pageLength,
14
+ requestedPageSize,
15
+ }: {
16
+ interval: Interval;
17
+ newerCount: number;
18
+ olderCount: number;
19
+ pageLength: number;
20
+ requestedPageSize: number;
21
+ }): PaginationFlags => {
22
+ const isPageFull = pageLength >= requestedPageSize;
23
+ // the smaller half, so an odd slot the server gives either side does not matter
24
+ const minShare = Math.floor((olderCount + newerCount) / 2);
25
+ // an interval already known to reach the dataset head or tail stays there
26
+ return {
27
+ hasMoreHead: !interval.isHead && isPageFull && newerCount >= minShare,
28
+ hasMoreTail: !interval.isTail && isPageFull && olderCount >= minShare,
29
+ };
30
+ };
@@ -1,77 +1,29 @@
1
- import { binarySearch } from '../sortCompiler';
1
+ import { deriveAroundPaginationFlags } from './aroundPaginationFlags';
2
2
  import { dateToNs } from '../../utils/time';
3
3
  import type { TimestampNS } from '../../types';
4
- import type { BasePaginator, CursorDeriveContext, PaginationFlags } from '../paginators';
5
- import { ComparisonResult } from '../types.normalization';
4
+ import type { CursorDeriveContext, PaginationFlags } from '../paginators';
6
5
 
7
6
  export const deriveCreatedAtAroundPaginationFlags = <
8
7
  T extends { id: string; created_at: TimestampNS },
9
8
  Q extends { created_at_around?: Date | string },
10
- P extends BasePaginator<T, Q>,
11
9
  >({
12
10
  hasMoreHead,
13
11
  hasMoreTail,
14
12
  interval,
15
13
  page,
16
- paginator,
17
14
  queryShape,
18
15
  requestedPageSize,
19
- }: CursorDeriveContext<T, Q> & { paginator: P }): PaginationFlags => {
20
- let flags: PaginationFlags = { hasMoreHead, hasMoreTail };
21
- if (!queryShape?.created_at_around) return flags;
16
+ }: CursorDeriveContext<T, Q>): PaginationFlags => {
17
+ if (!queryShape?.created_at_around) return { hasMoreHead, hasMoreTail };
22
18
  // `created_at_around` is a REQUEST field, so it is still a `Date` (or an ISO string). Items carry
23
19
  // the wire unit, so bring the bound into that unit before comparing the two.
24
20
  const createdAtAround = dateToNs(new Date(queryShape.created_at_around));
25
- const [firstPageItem, lastPageItem] = [page[0], page.slice(-1)[0]];
26
-
27
- // expect ASC order (from oldest to newest)
28
- const isAboveHeadBound =
29
- paginator.sortComparator({ created_at: createdAtAround } as T, lastPageItem) ===
30
- ComparisonResult.A_PRECEDES_B;
31
- const isBelowTailBound =
32
- paginator.sortComparator(firstPageItem, { created_at: createdAtAround } as T) ===
33
- ComparisonResult.A_PRECEDES_B;
34
-
35
- const requestedPageSizeNotMet =
36
- requestedPageSize > interval.itemIds.length && requestedPageSize > page.length;
37
- const noMoreMessages =
38
- (requestedPageSize > interval.itemIds.length ||
39
- interval.itemIds.length >= page.length) &&
40
- requestedPageSize > page.length;
41
-
42
- if (isAboveHeadBound) {
43
- flags.hasMoreHead = false;
44
- if (requestedPageSizeNotMet) {
45
- flags.hasMoreTail = false;
46
- }
47
- } else if (isBelowTailBound) {
48
- flags.hasMoreTail = false;
49
- if (requestedPageSizeNotMet) {
50
- flags.hasMoreHead = false;
51
- }
52
- } else if (noMoreMessages) {
53
- flags = { hasMoreHead: false, hasMoreTail: false };
54
- } else {
55
- const [firstPageMsgIsFirstInSet, lastPageMsgIsLastInSet] = [
56
- firstPageItem?.id && firstPageItem.id === interval.itemIds[0],
57
- lastPageItem?.id && lastPageItem.id === interval.itemIds.slice(-1)[0],
58
- ];
59
-
60
- const midPointByCount = Math.floor(page.length / 2);
61
- const { insertionIndex } = binarySearch({
62
- needle: { created_at: createdAtAround } as T,
63
- length: page.length,
64
- getItemAt: (index) => page[index],
65
- compare: (a, b) => a.created_at - b.created_at,
66
- itemIdentityEquals: (a, b) => a.created_at === b.created_at,
67
- plateauScan: false,
68
- });
69
-
70
- if (insertionIndex !== -1) {
71
- if (firstPageMsgIsFirstInSet) flags.hasMoreTail = midPointByCount <= insertionIndex;
72
- if (lastPageMsgIsLastInSet) flags.hasMoreHead = midPointByCount >= insertionIndex;
73
- }
74
- }
75
-
76
- return flags;
21
+ const olderCount = page.filter((item) => item.created_at < createdAtAround).length;
22
+ return deriveAroundPaginationFlags({
23
+ interval,
24
+ newerCount: page.length - olderCount,
25
+ olderCount,
26
+ pageLength: page.length,
27
+ requestedPageSize,
28
+ });
77
29
  };
@@ -1,3 +1,4 @@
1
+ import { deriveAroundPaginationFlags } from './aroundPaginationFlags';
1
2
  import type { CursorDeriveContext, PaginationFlags } from '../paginators';
2
3
 
3
4
  export const deriveIdAroundPaginationFlags = <
@@ -11,43 +12,14 @@ export const deriveIdAroundPaginationFlags = <
11
12
  queryShape,
12
13
  requestedPageSize,
13
14
  }: CursorDeriveContext<T, Q>): PaginationFlags => {
14
- let flags: PaginationFlags = { hasMoreHead, hasMoreTail };
15
- if (!queryShape?.id_around) return flags;
16
- const { id_around } = queryShape;
17
-
18
- const [firstPageMsg, lastPageMsg] = [page[0], page.slice(-1)[0]];
19
- const [firstPageMsgIsFirstInSet, lastPageMsgIsLastInSet] = [
20
- firstPageMsg?.id === interval.itemIds[0],
21
- lastPageMsg?.id === interval.itemIds.slice(-1)[0],
22
- ];
23
-
24
- const midPoint = Math.floor(page.length / 2);
25
- const noMoreMessages =
26
- (requestedPageSize > interval.itemIds.length ||
27
- interval.itemIds.length >= page.length) &&
28
- requestedPageSize > page.length;
29
-
30
- if (noMoreMessages) {
31
- flags = { hasMoreHead: false, hasMoreTail: false };
32
- } else if (!page[midPoint]) {
33
- return flags;
34
- } else if (page[midPoint].id === id_around) {
35
- flags = { hasMoreHead: true, hasMoreTail: true };
36
- } else {
37
- const halves = [page.slice(0, midPoint), page.slice(midPoint)];
38
- if (firstPageMsgIsFirstInSet) {
39
- const targetMsg = halves[0].find((message) => message.id === id_around);
40
- if (targetMsg) {
41
- flags.hasMoreTail = false;
42
- }
43
- }
44
- if (lastPageMsgIsLastInSet) {
45
- const targetMsg = halves[1].find((message) => message.id === id_around);
46
- if (targetMsg) {
47
- flags.hasMoreHead = false;
48
- }
49
- }
50
- }
51
-
52
- return flags;
15
+ const targetIndex = page.findIndex((item) => item.id === queryShape?.id_around);
16
+ // Without the target in the page, the page says nothing about where it sits.
17
+ if (!queryShape?.id_around || targetIndex === -1) return { hasMoreHead, hasMoreTail };
18
+ return deriveAroundPaginationFlags({
19
+ interval,
20
+ newerCount: page.length - 1 - targetIndex,
21
+ olderCount: targetIndex,
22
+ pageLength: page.length,
23
+ requestedPageSize,
24
+ });
53
25
  };
@@ -1968,9 +1968,12 @@ export abstract class BasePaginator<T, Q> {
1968
1968
  protected locateByItemInInterval({
1969
1969
  item,
1970
1970
  interval,
1971
+ plateauScan = true,
1971
1972
  }: {
1972
1973
  item: T;
1973
1974
  interval: Interval | LogicalInterval;
1975
+ /** Walk the interval for an item the binary search missed. Off when it cannot be there. */
1976
+ plateauScan?: boolean;
1974
1977
  }): ItemLocation | null {
1975
1978
  const ids = interval.itemIds;
1976
1979
 
@@ -1982,7 +1985,7 @@ export abstract class BasePaginator<T, Q> {
1982
1985
  this.getItemId(item1) === this.getItemId(item2),
1983
1986
  // items in intervals are not sorted by effectiveComparator
1984
1987
  compare: this.itemOrderComparator.bind(this),
1985
- plateauScan: true,
1988
+ plateauScan,
1986
1989
  });
1987
1990
  }
1988
1991
 
@@ -2008,22 +2011,21 @@ export abstract class BasePaginator<T, Q> {
2008
2011
  }
2009
2012
 
2010
2013
  protected locateByItemInIntervals(item: T): ItemCoordinates['interval'] | undefined {
2011
- // Two different questions, asked in this order:
2012
- // 1. which interval's sort bounds does this item fall into (`locateIntervalForItem`)? The only
2013
- // one that can answer for an item this paginator has never stored.
2014
- // 2. which interval actually lists this id (`findIntervalHoldingItem`)?
2015
- //
2016
- // They disagree when an item is updated in place: the interval holds the very object being
2017
- // ingested, so it already carries the item's NEW sort value, and an item that moved outside its
2018
- // own window's bounds is no longer found by (1) — even though (2) still lists it. The fallback
2019
- // is what lets `ingestItem` take the old entry out before re-inserting; without it the id stays
2020
- // behind in that interval and ends up stored in two places at once.
2021
- const interval =
2022
- this.locateIntervalForItem(item) ?? this.findIntervalHoldingItem(item);
2023
- if (!interval) return undefined;
2024
- const itemLocation = this.locateByItemInInterval({ item, interval });
2025
- if (!itemLocation) return undefined;
2026
- return { interval, ...itemLocation };
2014
+ const locateIn = (interval: AnyInterval | undefined, plateauScan?: boolean) => {
2015
+ const location =
2016
+ interval && this.locateByItemInInterval({ item, interval, plateauScan });
2017
+ return interval && location ? { interval, ...location } : undefined;
2018
+ };
2019
+ const boundsInterval = this.locateIntervalForItem(item);
2020
+ // Not held by this list, so it is in no interval. It goes where it should be located.
2021
+ if (!this._itemIndex.has(this.getItemId(item)))
2022
+ return locateIn(boundsInterval, false);
2023
+ // Item held by some interval and has not moved. It goes where its sort value puts it, found without a scan.
2024
+ const inBounds = locateIn(boundsInterval);
2025
+ if (inBounds && inBounds.currentIndex > -1) return inBounds;
2026
+ // The item is held by some interval but has moved. We have to scan all intervals to find it.
2027
+ const holdingInterval = this.findIntervalHoldingItem(item);
2028
+ return holdingInterval ? locateIn(holdingInterval) : inBounds;
2027
2029
  }
2028
2030
 
2029
2031
  /**
@@ -3064,6 +3066,11 @@ export abstract class BasePaginator<T, Q> {
3064
3066
  return false;
3065
3067
  }
3066
3068
 
3069
+ /** The page size a query's results are measured against when deriving the head/tail flags. */
3070
+ protected getRequestedPageSize(_queryShape: Q | undefined): number {
3071
+ return this.pageSize;
3072
+ }
3073
+
3067
3074
  protected getStateAfterQuery(
3068
3075
  stateUpdate: Partial<PaginatorState<T>>,
3069
3076
 
@@ -3223,7 +3230,7 @@ export abstract class BasePaginator<T, Q> {
3223
3230
  isFirstPage,
3224
3231
  keepPreviousItems,
3225
3232
  queryShape,
3226
- requestedPageSize: this.pageSize,
3233
+ requestedPageSize: this.getRequestedPageSize(queryShape),
3227
3234
  results,
3228
3235
  updateState,
3229
3236
  });
@@ -3332,6 +3339,21 @@ export abstract class BasePaginator<T, Q> {
3332
3339
  stateUpdate.cursor = cursor;
3333
3340
  stateUpdate.hasMoreTail = hasMoreTail;
3334
3341
  stateUpdate.hasMoreHead = hasMoreHead;
3342
+ } else if (this.config.deriveCursor && direction && !isFirstPage) {
3343
+ // Nothing was ingested, so there is no interval to derive from and the query only resolved
3344
+ // the direction it paginated in. The other side keeps its cursor.
3345
+ stateUpdate.cursor =
3346
+ direction === 'headward'
3347
+ ? {
3348
+ headward: resolvedHeadward || null,
3349
+ tailward: this.cursor?.tailward ?? null,
3350
+ }
3351
+ : {
3352
+ headward: this.cursor?.headward ?? null,
3353
+ tailward: resolvedTailward || null,
3354
+ };
3355
+ if (direction === 'headward') stateUpdate.hasMoreHead = !!resolvedHeadward;
3356
+ else stateUpdate.hasMoreTail = !!resolvedTailward;
3335
3357
  } else {
3336
3358
  stateUpdate.cursor = {
3337
3359
  tailward: resolvedTailward || null,
@@ -3408,7 +3430,10 @@ export abstract class BasePaginator<T, Q> {
3408
3430
  }
3409
3431
 
3410
3432
  const state = this.getStateAfterQuery(stateUpdate, isFirstPage);
3433
+ // `updateState` decides whether the results are committed, not whether the query is over: a
3434
+ // caller that commits its own state must not be left with the `isLoading` executeQuery published.
3411
3435
  if (updateState) this.state.next(state);
3436
+ else if (this.isLoading) this.state.partialNext({ isLoading: false });
3412
3437
  // Only the first page is cached and a later page cannot change it.
3413
3438
  if (isFirstPage) this.populateOfflineDbAfterQuery({ items: state.items, queryShape });
3414
3439