-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathably.d.ts
2983 lines (2825 loc) · 140 KB
/
ably.d.ts
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
// Type definitions for Ably Realtime and Rest client library 1.2
// Project: https://www.ably.com/
// Definitions by: Ably <https://github.com/ably/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* You are currently viewing the default variant of the Ably JavaScript Client Library SDK. View the modular variant {@link modular | here}.
*
* To get started with the Ably JavaScript Client Library SDK, follow the [Quickstart Guide](https://ably.com/docs/quick-start-guide) or view the introductions to the [realtime](https://ably.com/docs/realtime/usage) and [REST](https://ably.com/docs/rest/usage) interfaces.
*
* @module
*/
/**
* The `ChannelStates` namespace describes the possible values of the {@link ChannelState} type.
*/
declare namespace ChannelStates {
/**
* The channel has been initialized but no attach has yet been attempted.
*/
type INITIALIZED = 'initialized';
/**
* An attach has been initiated by sending a request to Ably. This is a transient state, followed either by a transition to `ATTACHED`, `SUSPENDED`, or `FAILED`.
*/
type ATTACHING = 'attaching';
/**
* The attach has succeeded. In the `ATTACHED` state a client may publish and subscribe to messages, or be present on the channel.
*/
type ATTACHED = 'attached';
/**
* A detach has been initiated on an `ATTACHED` channel by sending a request to Ably. This is a transient state, followed either by a transition to `DETACHED` or `FAILED`.
*/
type DETACHING = 'detaching';
/**
* The channel, having previously been `ATTACHED`, has been detached by the user.
*/
type DETACHED = 'detached';
/**
* The channel, having previously been `ATTACHED`, has lost continuity, usually due to the client being disconnected from Ably for longer than two minutes. It will automatically attempt to reattach as soon as connectivity is restored.
*/
type SUSPENDED = 'suspended';
/**
* An indefinite failure condition. This state is entered if a channel error has been received from the Ably service, such as an attempt to attach without the necessary access rights.
*/
type FAILED = 'failed';
}
/**
* Describes the possible states of a {@link Channel} or {@link RealtimeChannel} object.
*/
export type ChannelState =
| ChannelStates.FAILED
| ChannelStates.INITIALIZED
| ChannelStates.SUSPENDED
| ChannelStates.ATTACHED
| ChannelStates.ATTACHING
| ChannelStates.DETACHED
| ChannelStates.DETACHING;
/**
* The `ChannelEvents` namespace describes the possible values of the {@link ChannelEvent} type.
*/
declare namespace ChannelEvents {
/**
* The channel has been initialized but no attach has yet been attempted.
*/
type INITIALIZED = 'initialized';
/**
* An attach has been initiated by sending a request to Ably. This is a transient state, followed either by a transition to `ATTACHED`, `SUSPENDED`, or `FAILED`.
*/
type ATTACHING = 'attaching';
/**
* The attach has succeeded. In the `ATTACHED` state a client may publish and subscribe to messages, or be present on the channel.
*/
type ATTACHED = 'attached';
/**
* A detach has been initiated on an `ATTACHED` channel by sending a request to Ably. This is a transient state, followed either by a transition to `DETACHED` or `FAILED`.
*/
type DETACHING = 'detaching';
/**
* The channel, having previously been `ATTACHED`, has been detached by the user.
*/
type DETACHED = 'detached';
/**
* The channel, having previously been `ATTACHED`, has lost continuity, usually due to the client being disconnected from Ably for longer than two minutes. It will automatically attempt to reattach as soon as connectivity is restored.
*/
type SUSPENDED = 'suspended';
/**
* An indefinite failure condition. This state is entered if a channel error has been received from the Ably service, such as an attempt to attach without the necessary access rights.
*/
type FAILED = 'failed';
/**
* An event for changes to channel conditions that do not result in a change in {@link ChannelState}.
*/
type UPDATE = 'update';
}
/**
* Describes the events emitted by a {@link Channel} or {@link RealtimeChannel} object. An event is either an `UPDATE` or a {@link ChannelState}.
*/
export type ChannelEvent =
| ChannelEvents.FAILED
| ChannelEvents.INITIALIZED
| ChannelEvents.SUSPENDED
| ChannelEvents.ATTACHED
| ChannelEvents.ATTACHING
| ChannelEvents.DETACHED
| ChannelEvents.DETACHING
| ChannelEvents.UPDATE;
/**
* The `ConnectionStates` namespace describes the possible values of the {@link ConnectionState} type.
*/
declare namespace ConnectionStates {
/**
* A connection with this state has been initialized but no connection has yet been attempted.
*/
type INITIALIZED = 'initialized';
/**
* A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
*/
type CONNECTING = 'connecting';
/**
* A connection exists and is active.
*/
type CONNECTED = 'connected';
/**
* A temporary failure condition. No current connection exists because there is no network connectivity or no host is available. The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible. In this state, developers can continue to publish messages as they are automatically placed in a local queue, to be sent as soon as a connection is reestablished. Messages published by other clients while this client is disconnected will be delivered to it upon reconnection, so long as the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible and the connection will move to the `SUSPENDED` state.
*/
type DISCONNECTED = 'disconnected';
/**
* A long term failure condition. No current connection exists because there is no network connectivity or no host is available. The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call to {@link Connection.connect | `connect()`}. Once the connection has been re-established, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the [History API](https://ably.com/docs/realtime/history).
*/
type SUSPENDED = 'suspended';
/**
* An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection is forcibly terminated and the connection state becomes `CLOSED`.
*/
type CLOSING = 'closing';
/**
* The connection has been explicitly closed by the client. In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call to {@link Connection.connect | `connect()`}, which results in a new connection.
*/
type CLOSED = 'closed';
/**
* This state is entered if the client library encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service, for example an attempt to connect with an incorrect API key, or a local terminal error, for example the token in use has expired and the library does not have any way to renew it. In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call to {@link Connection.connect | `connect()`}.
*/
type FAILED = 'failed';
}
/**
* Describes the realtime {@link Connection} object states.
*/
export type ConnectionState =
| ConnectionStates.INITIALIZED
| ConnectionStates.CONNECTED
| ConnectionStates.CONNECTING
| ConnectionStates.DISCONNECTED
| ConnectionStates.SUSPENDED
| ConnectionStates.CLOSED
| ConnectionStates.CLOSING
| ConnectionStates.FAILED;
/**
* The `ConnectionEvents` namespace describes the possible values of the {@link ConnectionEvent} type.
*/
declare namespace ConnectionEvents {
/**
* A connection with this state has been initialized but no connection has yet been attempted.
*/
type INITIALIZED = 'initialized';
/**
* A connection attempt has been initiated. The connecting state is entered as soon as the library has completed initialization, and is reentered each time connection is re-attempted following disconnection.
*/
type CONNECTING = 'connecting';
/**
* A connection exists and is active.
*/
type CONNECTED = 'connected';
/**
* A temporary failure condition. No current connection exists because there is no network connectivity or no host is available. The disconnected state is entered if an established connection is dropped, or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt to open a new connection (approximately every 15 seconds), anticipating that the connection will be re-established soon and thus connection and channel continuity will be possible. In this state, developers can continue to publish messages as they are automatically placed in a local queue, to be sent as soon as a connection is reestablished. Messages published by other clients while this client is disconnected will be delivered to it upon reconnection, so long as the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible and the connection will move to the `SUSPENDED` state.
*/
type DISCONNECTED = 'disconnected';
/**
* A long term failure condition. No current connection exists because there is no network connectivity or no host is available. The suspended state is entered after a failed connection attempt if there has then been no connection for a period of two minutes. In the suspended state, the library will periodically attempt to open a new connection every 30 seconds. Developers are unable to publish messages in this state. A new connection attempt can also be triggered by an explicit call to {@link Connection.connect | `connect()`}. Once the connection has been re-established, channels will be automatically re-attached. The client has been disconnected for too long for them to resume from where they left off, so if it wants to catch up on messages published by other clients while it was disconnected, it needs to use the [History API](https://ably.com/docs/realtime/history).
*/
type SUSPENDED = 'suspended';
/**
* An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection is forcibly terminated and the connection state becomes `CLOSED`.
*/
type CLOSING = 'closing';
/**
* The connection has been explicitly closed by the client. In the closed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. No connection state is preserved by the service or by the library. A new connection attempt can be triggered by an explicit call to {@link Connection.connect | `connect()`}, which results in a new connection.
*/
type CLOSED = 'closed';
/**
* This state is entered if the client library encounters a failure condition that it cannot recover from. This may be a fatal connection error received from the Ably service, for example an attempt to connect with an incorrect API key, or a local terminal error, for example the token in use has expired and the library does not have any way to renew it. In the failed state, no reconnection attempts are made automatically by the library, and clients may not publish messages. A new connection attempt can be triggered by an explicit call to {@link Connection.connect | `connect()`}.
*/
type FAILED = 'failed';
/**
* An event for changes to connection conditions for which the {@link ConnectionState} does not change.
*/
type UPDATE = 'update';
}
/**
* Describes the events emitted by a {@link Connection} object. An event is either an `UPDATE` or a {@link ConnectionState}.
*/
export type ConnectionEvent =
| ConnectionEvents.INITIALIZED
| ConnectionEvents.CONNECTED
| ConnectionEvents.CONNECTING
| ConnectionEvents.DISCONNECTED
| ConnectionEvents.SUSPENDED
| ConnectionEvents.CLOSED
| ConnectionEvents.CLOSING
| ConnectionEvents.FAILED
| ConnectionEvents.UPDATE;
/**
* The `PresenceActions` namespace describes the possible values of the {@link PresenceAction} type.
*/
declare namespace PresenceActions {
/**
* A member is not present in the channel.
*/
type ABSENT = 'absent';
/**
* When subscribing to presence events on a channel that already has members present, this event is emitted for every member already present on the channel before the subscribe listener was registered.
*/
type PRESENT = 'present';
/**
* A new member has entered the channel.
*/
type ENTER = 'enter';
/**
* A member who was present has now left the channel. This may be a result of an explicit request to leave or implicitly when detaching from the channel. Alternatively, if a member's connection is abruptly disconnected and they do not resume their connection within a minute, Ably treats this as a leave event as the client is no longer present.
*/
type LEAVE = 'leave';
/**
* An already present member has updated their member data. Being notified of member data updates can be very useful, for example, it can be used to update the status of a user when they are typing a message.
*/
type UPDATE = 'update';
}
/**
* Describes the possible actions members in the presence set can emit.
*/
export type PresenceAction =
| PresenceActions.ABSENT
| PresenceActions.PRESENT
| PresenceActions.ENTER
| PresenceActions.LEAVE
| PresenceActions.UPDATE;
/**
* The `StatsIntervalGranularities` namespace describes the possible values of the {@link StatsIntervalGranularity} type.
*/
declare namespace StatsIntervalGranularities {
/**
* Interval unit over which statistics are gathered as minutes.
*/
type MINUTE = 'minute';
/**
* Interval unit over which statistics are gathered as hours.
*/
type HOUR = 'hour';
/**
* Interval unit over which statistics are gathered as days.
*/
type DAY = 'day';
/**
* Interval unit over which statistics are gathered as months.
*/
type MONTH = 'month';
}
/**
* Describes the interval unit over which statistics are gathered.
*/
export type StatsIntervalGranularity =
| StatsIntervalGranularities.MINUTE
| StatsIntervalGranularities.HOUR
| StatsIntervalGranularities.DAY
| StatsIntervalGranularities.MONTH;
/**
* HTTP Methods, used internally.
*/
declare namespace HTTPMethods {
/**
* Represents a HTTP POST request.
*/
type POST = 'POST';
/**
* Represents a HTTP GET request.
*/
type GET = 'GET';
}
/**
* HTTP Methods, used internally.
*/
export type HTTPMethod = HTTPMethods.GET | HTTPMethods.POST;
/**
* A type which specifies the valid transport names. [See here](https://faqs.ably.com/which-transports-are-supported) for more information.
*/
export type Transport = 'web_socket' | 'xhr_polling' | 'comet';
/**
* Contains the details of a {@link Channel} or {@link RealtimeChannel} object such as its ID and {@link ChannelStatus}.
*/
export interface ChannelDetails {
/**
* The identifier of the channel.
*/
channelId: string;
/**
* A {@link ChannelStatus} object.
*/
status: ChannelStatus;
}
/**
* Contains the status of a {@link Channel} or {@link RealtimeChannel} object such as whether it is active and its {@link ChannelOccupancy}.
*/
export interface ChannelStatus {
/**
* If `true`, the channel is active, otherwise `false`.
*/
isActive: boolean;
/**
* A {@link ChannelOccupancy} object.
*/
occupancy: ChannelOccupancy;
}
/**
* Contains the metrics of a {@link Channel} or {@link RealtimeChannel} object.
*/
export interface ChannelOccupancy {
/**
* A {@link ChannelMetrics} object.
*/
metrics: ChannelMetrics;
}
/**
* Contains the metrics associated with a {@link Channel} or {@link RealtimeChannel}, such as the number of publishers, subscribers and connections it has.
*/
export interface ChannelMetrics {
/**
* The number of realtime connections attached to the channel.
*/
connections: number;
/**
* The number of realtime connections attached to the channel with permission to enter the presence set, regardless of whether or not they have entered it. This requires the `presence` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelModes.PRESENCE}.
*/
presenceConnections: number;
/**
* The number of members in the presence set of the channel.
*/
presenceMembers: number;
/**
* The number of realtime attachments receiving presence messages on the channel. This requires the `subscribe` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelModes.PRESENCE_SUBSCRIBE}.
*/
presenceSubscribers: number;
/**
* The number of realtime attachments permitted to publish messages to the channel. This requires the `publish` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelModes.PUBLISH}.
*/
publishers: number;
/**
* The number of realtime attachments receiving messages on the channel. This requires the `subscribe` capability and for a client to not have specified a {@link ChannelMode} flag that excludes {@link ChannelModes.SUBSCRIBE}.
*/
subscribers: number;
}
/**
* Passes additional client-specific properties to the REST constructor or the Realtime constructor.
*/
export interface ClientOptions<Plugins = CorePlugins> extends AuthOptions {
/**
* When `true`, the client connects to Ably as soon as it is instantiated. You can set this to `false` and explicitly connect to Ably using the {@link Connection.connect | `connect()`} method. The default is `true`.
*
* @defaultValue `true`
*/
autoConnect?: boolean;
/**
* When a {@link TokenParams} object is provided, it overrides the client library defaults when issuing new Ably Tokens or Ably {@link TokenRequest | `TokenRequest`s}.
*/
defaultTokenParams?: TokenParams;
/**
* If `false`, prevents messages originating from this connection being echoed back on the same connection. The default is `true`.
*
* @defaultValue `true`
*/
echoMessages?: boolean;
/**
* Enables a [custom environment](https://ably.com/docs/platform-customization) to be used with the Ably service.
*/
environment?: string;
/**
* Controls the verbosity of the logs output from the library. Valid values are: 0 (no logs), 1 (errors only), 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
*/
logLevel?: number;
/**
* Controls the log output of the library. This is a function to handle each line of log output. If you do not set this value, then `console.log` will be used.
*
* @param msg - The log message emitted by the library.
* @param level - The level of the log. Values are one of: 0 (no logs), 1 (errors only), 2 (errors plus connection and channel state changes), 3 (high-level debug output), and 4 (full debug output).
*/
logHandler?: (msg: string, level: number) => void;
/**
* Enables a non-default Ably port to be specified. For development environments only. The default value is 80.
*
* @defaultValue 80
*/
port?: number;
/**
* If `false`, this disables the default behavior whereby the library queues messages on a connection in the disconnected or connecting states. The default behavior enables applications to submit messages immediately upon instantiating the library without having to wait for the connection to be established. Applications may use this option to disable queueing if they wish to have application-level control over the queueing. The default is `true`.
*
* @defaultValue `true`
*/
queueMessages?: boolean;
/**
* Enables a non-default Ably host to be specified. For development environments only. The default value is `rest.ably.io`.
*
* @defaultValue `"rest.ably.io"`
*/
restHost?: string;
/**
* Enables a non-default Ably host to be specified for realtime connections. For development environments only. The default value is `realtime.ably.io`.
*
* @defaultValue `"realtime.ably.io"`
*/
realtimeHost?: string;
/**
* An array of fallback hosts to be used in the case of an error necessitating the use of an alternative host. If you have been provided a set of custom fallback hosts by Ably, please specify them here.
*
* @defaultValue `['a.ably-realtime.com', 'b.ably-realtime.com', 'c.ably-realtime.com', 'd.ably-realtime.com', 'e.ably-realtime.com']``
*/
fallbackHosts?: string[];
/**
* Set of configurable options to set on the HTTP(S) agent used for REST requests.
*
* See the [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions) for descriptions of these options.
*/
restAgentOptions?: {
/**
* See [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions)
*/
maxSockets?: number;
/**
* See [NodeJS docs](https://nodejs.org/api/http.html#new-agentoptions)
*/
keepAlive?: boolean;
};
/**
* Enables a connection to inherit the state of a previous connection that may have existed under a different instance of the Realtime library. This might typically be used by clients of the browser library to ensure connection state can be preserved when the user refreshes the page. A recovery key string can be explicitly provided, or alternatively if a callback function is provided, the client library will automatically persist the recovery key between page reloads and call the callback when the connection is recoverable. The callback is then responsible for confirming whether the connection should be recovered or not. See [connection state recovery](https://ably.com/docs/realtime/connection/#connection-state-recovery) for further information.
*/
recover?: string | recoverConnectionCallback;
/**
* If specified, the SDK's internal persistence mechanism for storing the recovery key
* over page loads (see the `recover` client option) will store the recovery key under
* this identifier (in sessionstorage), so only another library instance which specifies
* the same recoveryKeyStorageName will attempt to recover from it. This is useful if you have
* multiple ably-js instances sharing a given origin (the origin being the scope of
* sessionstorage), as otherwise the multiple instances will overwrite each other's
* recovery keys, and after a reload they will all try and recover the same connection,
* which is not permitted and will cause broken behaviour.
*/
recoveryKeyStorageName?: string;
/**
* When `false`, the client will use an insecure connection. The default is `true`, meaning a TLS connection will be used to connect to Ably.
*
* @defaultValue `true`
*/
tls?: boolean;
/**
* Enables a non-default Ably TLS port to be specified. For development environments only. The default value is 443.
*
* @defaultValue 443
*/
tlsPort?: number;
/**
* When `true`, the more efficient MsgPack binary encoding is used. When `false`, JSON text encoding is used. The default is `true` for Node.js, and `false` for all other platforms.
*
* @defaultValue `true` for Node.js, `false` for all other platforms
*/
useBinaryProtocol?: boolean;
/**
* Override the URL used by the realtime client to check if the internet is available.
*
* In the event of a failure to connect to the primary endpoint, the client will send a
* GET request to this URL to check if the internet is available. If this request returns
* a success response the client will attempt to connect to a fallback host.
*/
connectivityCheckUrl?: string;
/**
* Override the URL used by the realtime client to check if WebSocket connections are available.
*
* If the client suspects that WebSocket connections are unavailable on the current network,
* it will attempt to open a WebSocket connection to this URL to check WebSocket connectivity.
* If this fails, the client will attempt to connect to Ably systems using fallback transports, if available.
*/
wsConnectivityCheckUrl?: string;
/**
* Disable the check used by the realtime client to check if the internet
* is available before connecting to a fallback host.
*/
disableConnectivityCheck?: boolean;
/**
* If the connection is still in the {@link ConnectionStates.DISCONNECTED} state after this delay in milliseconds, the client library will attempt to reconnect automatically. The default is 15 seconds.
*
* @defaultValue 15s
*/
disconnectedRetryTimeout?: number;
/**
* When the connection enters the {@link ConnectionStates.SUSPENDED} state, after this delay in milliseconds, if the state is still {@link ConnectionStates.SUSPENDED | `SUSPENDED`}, the client library attempts to reconnect automatically. The default is 30 seconds.
*
* @defaultValue 30s
*/
suspendedRetryTimeout?: number;
/**
* When `true`, the client library will automatically send a close request to Ably whenever the `window` [`beforeunload` event](https://developer.mozilla.org/en-US/docs/Web/API/BeforeUnloadEvent) fires. By enabling this option, the close request sent to Ably ensures the connection state will not be retained and all channels associated with the channel will be detached. This is commonly used by developers who want presence leave events to fire immediately (that is, if a user navigates to another page or closes their browser, then enabling this option will result in the presence member leaving immediately). Without this option or an explicit call to the `close` method of the `Connection` object, Ably expects that the abruptly disconnected connection could later be recovered and therefore does not immediately remove the user from presence. Instead, to avoid “twitchy” presence behaviour an abruptly disconnected client is removed from channels in which they are present after 15 seconds, and the connection state is retained for two minutes. Defaults to `true`.
*/
closeOnUnload?: boolean;
/**
* When `true`, enables idempotent publishing by assigning a unique message ID client-side, allowing the Ably servers to discard automatic publish retries following a failure such as a network fault. The default is `true`.
*
* @defaultValue `true`
*/
idempotentRestPublishing?: boolean;
/**
* A set of key-value pairs that can be used to pass in arbitrary connection parameters, such as [`heartbeatInterval`](https://ably.com/docs/realtime/connection#heartbeats) or [`remainPresentFor`](https://ably.com/docs/realtime/presence#unstable-connections).
*/
transportParams?: { [k: string]: string | number };
/**
* An array of transports to use, in descending order of preference. In the browser environment the available transports are: `web_socket` and `xhr`.
*/
transports?: Transport[];
/**
* The maximum number of fallback hosts to use as a fallback when an HTTP request to the primary host is unreachable or indicates that it is unserviceable. The default value is 3.
*
* @defaultValue 3
*/
httpMaxRetryCount?: number;
/**
* The maximum elapsed time in milliseconds in which fallback host retries for HTTP requests will be attempted. The default is 15 seconds.
*
* @defaultValue 15s
*/
httpMaxRetryDuration?: number;
/**
* Timeout in milliseconds for opening a connection to Ably to initiate an HTTP request. The default is 4 seconds.
*
* @defaultValue 4s
*/
httpOpenTimeout?: number;
/**
* Timeout in milliseconds for a client performing a complete HTTP request to Ably, including the connection phase. The default is 10 seconds.
*
* @defaultValue 10s
*/
httpRequestTimeout?: number;
/**
* Timeout for the wait of acknowledgement for operations performed via a realtime connection, before the client library considers a request failed and triggers a failure condition. Operations include establishing a connection with Ably, or sending a `HEARTBEAT`, `CONNECT`, `ATTACH`, `DETACH` or `CLOSE` request. It is the equivalent of `httpRequestTimeout` but for realtime operations, rather than REST. The default is 10 seconds.
*
* @defaultValue 10s
*/
realtimeRequestTimeout?: number;
/**
* A map between a plugin type and a plugin object.
*/
plugins?: Plugins;
/**
* The maximum message size is an attribute of an Ably account which represents the largest permitted payload size of a single message or set of messages published in a single operation. Publish requests whose payload exceeds this limit are rejected by the server. `maxMessageSize` enables the client to enforce, or further restrict, the maximum size of a single message or set of messages published via REST. The default value is `65536` (64 KiB). In the case of a realtime connection, the server may indicate the associated maximum message size on connection establishment; this value takes precedence over the client's default `maxMessageSize`.
*
* @defaultValue 65536
*/
maxMessageSize?: number;
/**
* A URL pointing to a service worker script which is used as the target for web push notifications.
*/
pushServiceWorkerUrl?: string;
}
/**
* Describes the {@link ClientOptions.plugins | plugins} accepted by all variants of the SDK.
*/
export interface CorePlugins {
/**
* A plugin capable of decoding `vcdiff`-encoded messages. For more information on how to configure a channel to use delta encoding, see the [documentation for the `@ably-forks/vcdiff-decoder` package](https://github.com/ably-forks/vcdiff-decoder#usage).
*/
vcdiff?: any;
/**
* A plugin which allows the client to be the target of push notifications.
*/
Push?: unknown;
}
/**
* Passes authentication-specific properties in authentication requests to Ably. Properties set using `AuthOptions` are used instead of the default values set when the client library is instantiated, as opposed to being merged with them.
*/
export interface AuthOptions {
/**
* Called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed {@link TokenRequest}; a {@link TokenDetails} (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication.ably-jwt). See [the authentication documentation](https://ably.com/docs/realtime/authentication) for details of the Ably {@link TokenRequest} format and associated API calls.
*
* @param data - The parameters that should be used to generate the token.
* @param callback - A function which, upon success, the `authCallback` should call with one of: an Ably Token string (in plain text format); a signed `TokenRequest`; a `TokenDetails` (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication#ably-jwt). Upon failure, the `authCallback` should call this function with information about the error.
*/
authCallback?(
data: TokenParams,
/**
* A function which, upon success, the `authCallback` should call with one of: an Ably Token string (in plain text format); a signed `TokenRequest`; a `TokenDetails` (in JSON format); an [Ably JWT](https://ably.com/docs/core-features/authentication#ably-jwt). Upon failure, the `authCallback` should call this function with information about the error.
*
* @param error - Should be `null` if the auth request completed successfully, or containing details of the error if not.
* @param tokenRequestOrDetails - A valid `TokenRequest`, `TokenDetails` or Ably JWT to be used for authentication.
*/
callback: (
error: ErrorInfo | string | null,
tokenRequestOrDetails: TokenDetails | TokenRequest | string | null,
) => void,
): void;
/**
* A set of key-value pair headers to be added to any request made to the `authUrl`. Useful when an application requires these to be added to validate the request or implement the response. If the `authHeaders` object contains an `authorization` key, then `withCredentials` is set on the XHR request.
*/
authHeaders?: { [index: string]: string };
/**
* The HTTP verb to use for any request made to the `authUrl`, either `GET` or `POST`. The default value is `GET`.
*
* @defaultValue `HTTPMethod.GET`
*/
authMethod?: HTTPMethod;
/**
* A set of key-value pair params to be added to any request made to the `authUrl`. When the `authMethod` is `GET`, query params are added to the URL, whereas when `authMethod` is `POST`, the params are sent as URL encoded form data. Useful when an application requires these to be added to validate the request or implement the response.
*/
authParams?: { [index: string]: string };
/**
* A URL that the library may use to obtain a token string (in plain text format), or a signed {@link TokenRequest} or {@link TokenDetails} (in JSON format) from.
*/
authUrl?: string;
/**
* The full API key string, as obtained from the [Ably dashboard](https://ably.com/dashboard). Use this option if you wish to use Basic authentication, or wish to be able to issue Ably Tokens without needing to defer to a separate entity to sign Ably {@link TokenRequest | `TokenRequest`s}. Read more about [Basic authentication](https://ably.com/docs/core-features/authentication#basic-authentication).
*/
key?: string;
/**
* If `true`, the library queries the Ably servers for the current time when issuing {@link TokenRequest | `TokenRequest`s} instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably {@link TokenRequest | `TokenRequest`s}, so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an [NTP daemon](https://en.wikipedia.org/wiki/Ntpd). The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request. The default is `false`.
*
* @defaultValue `false`
*/
queryTime?: boolean;
/**
* An authenticated token. This can either be a {@link TokenDetails} object or token string (obtained from the `token` property of a {@link TokenDetails} component of an Ably {@link TokenRequest} response, or a JSON Web Token satisfying [the Ably requirements for JWTs](https://ably.com/docs/core-features/authentication#ably-jwt)). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that enables the client library to renew the token automatically when the previous one expires, such as `authUrl` or `authCallback`. Read more about [Token authentication](https://ably.com/docs/core-features/authentication#token-authentication).
*/
token?: TokenDetails | string;
/**
* An authenticated {@link TokenDetails} object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that enables the client library to renew the token automatically when the previous one expires, such as `authUrl` or `authCallback`. Use this option if you wish to use Token authentication. Read more about [Token authentication](https://ably.com/docs/core-features/authentication#token-authentication).
*/
tokenDetails?: TokenDetails;
/**
* When `true`, forces token authentication to be used by the library. If a `clientId` is not specified in the {@link ClientOptions} or {@link TokenParams}, then the Ably Token issued is [anonymous](https://ably.com/docs/core-features/authentication#identified-clients).
*/
useTokenAuth?: boolean;
/**
* A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a `clientId` may also be implicit in a token used to instantiate the library. An error will be raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [client identities](https://ably.com/documentation/how-ably-works#client-identity).
*/
clientId?: string;
}
/**
* Capabilities which are available for use within {@link TokenParams}.
*/
export type capabilityOp =
| 'publish'
| 'subscribe'
| 'presence'
| 'history'
| 'stats'
| 'channel-metadata'
| 'push-subscribe'
| 'push-admin'
| 'privileged-headers';
/**
* Capabilities which are available for use within {@link TokenParams}.
*/
export type CapabilityOp = capabilityOp;
/**
* Defines the properties of an Ably Token.
*/
export interface TokenParams {
/**
* The capabilities associated with this Ably Token. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/core-features/authentication/#capabilities-explained).
*
* @defaultValue `'{"*":["*"]}'`
*/
capability?: { [key: string]: capabilityOp[] | ['*'] } | string;
/**
* A client ID, used for identifying this client when publishing messages or for presence purposes. The `clientId` can be any non-empty string, except it cannot contain a `*`. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a `clientId` may also be implicit in a token used to instantiate the library. An error is raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [identified clients](https://ably.com/docs/core-features/authentication#identified-clients).
*/
clientId?: string;
/**
* A cryptographically secure random string of at least 16 characters, used to ensure the {@link TokenRequest} cannot be reused.
*/
nonce?: string;
/**
* The timestamp of this request as milliseconds since the Unix epoch. Timestamps, in conjunction with the `nonce`, are used to prevent requests from being replayed. `timestamp` is a "one-time" value, and is valid in a request, but is not validly a member of any default token params such as `ClientOptions.defaultTokenParams`.
*/
timestamp?: number;
/**
* Requested time to live for the token in milliseconds. The default is 60 minutes.
*
* @defaultValue 60min
*/
ttl?: number;
}
/**
* Sets the properties to configure encryption for a {@link Channel} or {@link RealtimeChannel} object.
*/
export interface CipherParams {
/**
* The algorithm to use for encryption. Only `AES` is supported and is the default value.
*
* @defaultValue `"AES"`
*/
algorithm: string;
/**
* The private key used to encrypt and decrypt payloads. You should not set this value directly; rather, you should pass a `key` of type {@link CipherKeyParam} to {@link Crypto.getDefaultParams}.
*/
key: unknown;
/**
* The length of the key in bits; either 128 or 256.
*/
keyLength: number;
/**
* The cipher mode. Only `CBC` is supported and is the default value.
*
* @defaultValue `"CBC"`
*/
mode: string;
}
/**
* Contains an Ably Token and its associated metadata.
*/
export interface TokenDetails {
/**
* The capabilities associated with this Ably Token. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/core-features/authentication/#capabilities-explained).
*/
capability: string;
/**
* The client ID, if any, bound to this Ably Token. If a client ID is included, then the Ably Token authenticates its bearer as that client ID, and the Ably Token may only be used to perform operations on behalf of that client ID. The client is then considered to be an [identified client](https://ably.com/docs/core-features/authentication#identified-clients).
*/
clientId?: string;
/**
* The timestamp at which this token expires as milliseconds since the Unix epoch.
*/
expires: number;
/**
* The timestamp at which this token was issued as milliseconds since the Unix epoch.
*/
issued: number;
/**
* The [Ably Token](https://ably.com/docs/core-features/authentication#ably-tokens) itself. A typical Ably Token string appears with the form `xVLyHw.A-pwh7wicf3afTfgiw4k2Ku33kcnSA7z6y8FjuYpe3QaNRTEo4`.
*/
token: string;
}
/**
* Contains the properties of a request for a token to Ably. Tokens are generated using {@link Auth.requestToken}.
*/
export interface TokenRequest {
/**
* Capability of the requested Ably Token. If the Ably `TokenRequest` is successful, the capability of the returned Ably Token will be the intersection of this capability with the capability of the issuing key. The capabilities value is a JSON-encoded representation of the resource paths and associated operations. Read more about capabilities in the [capabilities docs](https://ably.com/docs/realtime/authentication).
*/
capability: string;
/**
* The client ID to associate with the requested Ably Token. When provided, the Ably Token may only be used to perform operations on behalf of that client ID.
*/
clientId?: string;
/**
* The name of the key against which this request is made. The key name is public, whereas the key secret is private.
*/
keyName: string;
/**
* The Message Authentication Code for this request.
*/
mac: string;
/**
* A cryptographically secure random string of at least 16 characters, used to ensure the `TokenRequest` cannot be reused.
*/
nonce: string;
/**
* The timestamp of this request as milliseconds since the Unix epoch.
*/
timestamp: number;
/**
* Requested time to live for the Ably Token in milliseconds. If the Ably `TokenRequest` is successful, the TTL of the returned Ably Token is less than or equal to this value, depending on application settings and the attributes of the issuing key. The default is 60 minutes.
*
* @defaultValue 60min
*/
ttl?: number;
}
/**
* [Channel Parameters](https://ably.com/docs/realtime/channels/channel-parameters/overview) used within {@link ChannelOptions}.
*/
export type ChannelParams = { [key: string]: string };
/**
* The `ChannelModes` namespace describes the possible values of the {@link ChannelMode} type.
*/
declare namespace ChannelModes {
/**
* The client can publish messages.
*/
type PUBLISH = 'PUBLISH';
/**
* The client can subscribe to messages.
*/
type SUBSCRIBE = 'SUBSCRIBE';
/**
* The client can enter the presence set.
*/
type PRESENCE = 'PRESENCE';
/**
* The client can receive presence messages.
*/
type PRESENCE_SUBSCRIBE = 'PRESENCE_SUBSCRIBE';
}
/**
* Describes the possible flags used to configure client capabilities, using {@link ChannelOptions}.
*/
export type ChannelMode =
| ChannelModes.PUBLISH
| ChannelModes.SUBSCRIBE
| ChannelModes.PRESENCE
| ChannelModes.PRESENCE_SUBSCRIBE;
/**
* Passes additional properties to a {@link Channel} or {@link RealtimeChannel} object, such as encryption, {@link ChannelMode} and channel parameters.
*/
export interface ChannelOptions {
/**
* Requests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See [an example](https://ably.com/docs/realtime/encryption#getting-started). When running in a browser, encryption is only available when the current environment is a [secure context](https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).
*/
cipher?: CipherParamOptions | CipherParams;
/**
* [Channel Parameters](https://ably.com/docs/realtime/channels/channel-parameters/overview) that configure the behavior of the channel.
*/
params?: ChannelParams;
/**
* An array of {@link ChannelMode} objects.
*/
modes?: ChannelMode[];
}
/**
* Passes additional properties to a {@link RealtimeChannel} name to produce a new derived channel
*/
export interface DeriveOptions {
/**
* The JMESPath Query filter string to be used to derive new channel.
*/
filter?: string;
}
/**
* The `RestHistoryParams` interface describes the parameters accepted by the following methods:
*
* - {@link Presence.history}
* - {@link Channel.history}
*/
export interface RestHistoryParams {
/**
* The time from which messages are retrieved, specified as milliseconds since the Unix epoch.
*/
start?: number;
/**
* The time until messages are retrieved, specified as milliseconds since the Unix epoch.
*
* @defaultValue The current time.
*/
end?: number;
/**
* The order for which messages are returned in. Valid values are `'backwards'` which orders messages from most recent to oldest, or `'forwards'` which orders messages from oldest to most recent. The default is `'backwards'`.
*
* @defaultValue `'backwards'`
*/
direction?: 'forwards' | 'backwards';
/**
* An upper limit on the number of messages returned. The default is 100, and the maximum is 1000.
*
* @defaultValue 100
*/
limit?: number;
}
/**
* The `RestPresenceParams` interface describes the parameters accepted by {@link Presence.get}.
*/
export interface RestPresenceParams {
/**
* An upper limit on the number of messages returned. The default is 100, and the maximum is 1000.
*
* @defaultValue 100
*/
limit?: number;
/**
* Filters the list of returned presence members by a specific client using its ID.
*/
clientId?: string;
/**
* Filters the list of returned presence members by a specific connection using its ID.
*/
connectionId?: string;
}
/**
* The `RealtimePresenceParams` interface describes the parameters accepted by {@link RealtimePresence.get}.
*/
export interface RealtimePresenceParams {
/**
* Sets whether to wait for a full presence set synchronization between Ably and the clients on the channel to complete before returning the results. Synchronization begins as soon as the channel is {@link ChannelStates.ATTACHED}. When set to `true` the results will be returned as soon as the sync is complete. When set to `false` the current list of members will be returned without the sync completing. The default is `true`.
*
* @defaultValue `true`
*/
waitForSync?: boolean;
/**
* Filters the array of returned presence members by a specific client using its ID.
*/
clientId?: string;
/**
* Filters the array of returned presence members by a specific connection using its ID.
*/
connectionId?: string;
}
/**
* The `RealtimeHistoryParams` interface describes the parameters accepted by the following methods:
*
* - {@link RealtimePresence.history}
* - {@link RealtimeChannel.history}
*/
export interface RealtimeHistoryParams {
/**
* The time from which messages are retrieved, specified as milliseconds since the Unix epoch.
*/
start?: number;
/**
* The time until messages are retrieved, specified as milliseconds since the Unix epoch.
*
* @defaultValue The current time.
*/
end?: number;
/**
* The order for which messages are returned in. Valid values are `'backwards'` which orders messages from most recent to oldest, or `'forwards'` which orders messages from oldest to most recent. The default is `'backwards'`.
*
* @defaultValue `'backwards'`
*/