-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathliveobjects.d.ts
More file actions
2368 lines (2183 loc) · 92.1 KB
/
liveobjects.d.ts
File metadata and controls
2368 lines (2183 loc) · 92.1 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
/**
* You are currently viewing the Ably LiveObjects plugin type definitions for the Ably JavaScript Client Library SDK.
*
* To get started with LiveObjects, follow the [Quickstart Guide](https://ably.com/docs/liveobjects/quickstart/javascript) or view the [Introduction to LiveObjects](https://ably.com/docs/liveobjects).
*
* @module
*/
/* eslint-disable no-unused-vars, @typescript-eslint/no-unused-vars */
import {
ErrorInfo,
EventCallback,
RealtimeChannel,
RealtimeClient,
RestClient,
StatusSubscription,
Subscription,
__livetype,
} from './ably';
import { BaseRealtime, BaseRest, Rest } from './modular';
/* eslint-enable no-unused-vars, @typescript-eslint/no-unused-vars */
/**
* Blocks inferences to the contained type.
* Polyfill for TypeScript's `NoInfer` utility type introduced in TypeScript 5.4.
*
* This works by leveraging deferred conditional types - the compiler can't
* evaluate the conditional until it knows what T is, which prevents TypeScript
* from digging into the type to find inference candidates.
*
* See:
* - https://stackoverflow.com/questions/56687668
* - https://www.typescriptlang.org/docs/handbook/utility-types.html#noinfertype
*/
type NoInfer<T> = [T][T extends any ? 0 : never];
/**
* The `ObjectsEvents` namespace describes the possible values of the {@link ObjectsEvent} type.
*/
declare namespace ObjectsEvents {
/**
* The local copy of Objects on a channel is currently being synchronized with the Ably service.
*/
type SYNCING = 'syncing';
/**
* The local copy of Objects on a channel has been synchronized with the Ably service.
*/
type SYNCED = 'synced';
}
/**
* Describes the events emitted by a {@link RealtimeObject} object.
*/
export type ObjectsEvent = ObjectsEvents.SYNCED | ObjectsEvents.SYNCING;
/**
* The callback used for the events emitted by {@link RealtimeObject}.
*/
export type ObjectsEventCallback = () => void;
/**
* A function passed to the {@link BatchOperations.batch | batch} method to group multiple Objects operations into a single channel message.
*
* The function must be synchronous.
*
* @param ctx - The {@link BatchContext} used to group operations together.
*/
export type BatchFunction<T extends LiveObject> = (ctx: BatchContext<T>) => void;
/**
* Enables REST-based operations on Objects on a channel.
*/
export declare interface RestObject {
/**
* Reads object data from the channel in compact object response format.
* If no `objectId` is provided then the entire channel object is returned.
*
* Returns a {@link RestObjectGetCompactResult} representing the logical structure of your data as a JSON-like value.
* {@link LiveMap} instances appear as JSON objects with their entries, and {@link LiveCounter} instances appear
* as numbers. Binary values appear as base64 strings (JSON protocol) or `Buffer`/`ArrayBuffer` (binary protocol).
* JSON-typed values remain as their JSON-encoded string representation.
*
* Cyclic references are included as `{ objectId: string }` rather than including the same object instance
* in the result more than once.
*
* @param params - Optional parameters to specify the object to fetch.
* @returns A promise which, upon success, will be fulfilled with the object data in compact format. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
get(params?: RestObjectGetCompactParams): Promise<RestObjectGetCompactResult>;
/**
* Reads object data from the channel in full object response format.
* If no `objectId` is provided then the entire channel object is returned.
*
* Returns a {@link RestObjectGetFullResult} with full object metadata and decoded object data values
* (`bytes` decoded to `Buffer`/`ArrayBuffer`, `json` decoded to native objects/arrays).
* If the path resolves to a leaf value in a map, returns the decoded {@link RestObjectData | ObjectData} directly.
*
* Cyclic references are included as `{ objectId: string }` rather than including the same object instance
* in the result more than once.
*
* @param params - Parameters specifying the object to fetch with `compact: false`.
* @returns A promise which, upon success, will be fulfilled with the object data in full format. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
get(params: RestObjectGetFullParams): Promise<RestObjectGetFullResult>;
/**
* Reads object data from the channel.
* If no `objectId` is provided then the entire channel object is returned.
*
* When `compact` is `true` (the default), returns a {@link RestObjectGetCompactResult} representing the logical
* structure of your data as a JSON-like value. {@link LiveMap} instances appear as JSON objects with their entries,
* and {@link LiveCounter} instances appear as numbers. Binary values appear as base64 strings (JSON protocol) or
* `Buffer`/`ArrayBuffer` (binary protocol). JSON-typed values remain as their JSON-encoded string representation.
*
* When `compact` is `false`, returns a {@link RestObjectGetFullResult} with full object metadata
* and decoded object data values (`bytes` decoded to `Buffer`/`ArrayBuffer`, `json` decoded to native objects/arrays).
* If the path resolves to a leaf value in a map, returns the decoded {@link RestObjectData | ObjectData} directly.
*
* For both formats, cyclic references in the channel object are included as `{ objectId: string }`
* rather than including the same object instance in the result more than once.
*
* @param params - Optional parameters to specify the object to fetch and the format of the returned data.
* @returns A promise which, upon success, will be fulfilled with the object data in the requested format. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
get(params?: RestObjectGetParams): Promise<RestObjectGetCompactResult | RestObjectGetFullResult>;
/**
* Publishes one or more operations to modify objects on the channel.
* When an array is provided, all operations are published as an atomic batch.
*
* Operations can target objects using `objectId`, `path`, or neither (for create operations that create standalone objects):
* - `objectId`: The unique identifier of the object instance to create or update.
* - `path`: The path to the object instance within the channel object.
*
* Use dot-separated notation for paths (for example `votes.up`), relative to the channel object.
* An empty path `""` refers to the channel object itself.
* Paths can contain wildcards (`*`) to target multiple objects at once. Wildcards match exactly one level
* in the channel object and can appear at the end or middle of paths (for example `votes.*` or `posts.*.votes.up`).
* If a key contains a dot, escape it with a backslash (for example `posts.post\\.123.votes.up`).
*
* When using path operations, the server resolves object IDs at the time it receives the request.
* If the object instances at the specified path change due to concurrent updates before the server processes
* the operation, the operation is not applied to the new object instances.
*
* @param op - A single operation or array of operations to publish.
* @returns A promise which, upon success, will be fulfilled with a {@link RestObjectPublishResult} containing information about the published operations. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
publish(op: RestObjectOperation | RestObjectOperation[]): Promise<RestObjectPublishResult>;
/**
* Generates an object ID for a create operation. The returned ID, nonce, and initial value
* can be used to construct a {@link RestObjectOperationMapCreateWithObjectId} or
* {@link RestObjectOperationCounterCreateWithObjectId} operation for use with {@link publish}.
*
* Client-generated object IDs enable atomic batch operations with cross-references between
* newly created objects. When publishing a batch of operations using {@link publish}, you
* can reference an object by its pre-computed ID in the same batch - for example, creating
* a map and assigning it to a key in another map in a single atomic publish call.
*
* @param createBody - The create operation body, either a {@link RestObjectOperationMapCreateBody} or {@link RestObjectOperationCounterCreateBody}.
* @returns A promise which, upon success, will be fulfilled with a {@link RestObjectGenerateIdResult}. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
generateObjectId(
createBody: RestObjectOperationMapCreateBody | RestObjectOperationCounterCreateBody,
): Promise<RestObjectGenerateIdResult>;
}
/**
* Base interface for all REST object operations. Contains common fields shared across all operation types.
*/
export interface RestObjectOperationBase {
/**
* An ID associated with the message. Clients may set this field explicitly when publishing an operation to enable
* idempotent publishing. If not set, this will be generated by the server.
*/
id?: string;
}
// Enforce exactly one target at compile time using a union of the types below.
/**
* Targets an object by its object ID.
*/
type TargetByObjectId = {
/** The unique identifier of the object instance to target. */
objectId: string;
/** Not applicable when targeting by object ID. */
path?: never;
};
/**
* Targets an object by its location using the path.
* Paths are expressed relative to the structure of the object as defined by the compact view of the channel object.
*/
type TargetByPath = {
/**
* Use dot-separated notation (for example `votes.up`), relative to the channel object.
* An empty path `""` refers to the channel object itself.
* Paths can contain wildcards (`*`) to target multiple objects at once. Wildcards match exactly one level
* in the channel object and can appear at the end or middle of paths (for example `votes.*` or `posts.*.votes.up`).
* If a key contains a dot, escape it with a backslash (for example `posts.post\\.123.votes.up`).
*/
path: string;
/** Not applicable when targeting by path. */
objectId?: never;
};
/**
* Base type for operations that can target objects either by object ID or by path.
* Ensures that exactly one targeting method is specified.
*/
export type AnyTargetRestObjectOperationBase = RestObjectOperationBase & (TargetByObjectId | TargetByPath);
/**
* Represents a leaf data value used when publishing operations via {@link RestObject.publish}.
* Either a primitive value or a reference to another object. Exactly one property must be set, indicating the type.
*/
export type PublishObjectData =
| {
/** A string value. */
string: string;
/** Not applicable. */ number?: never;
/** Not applicable. */ boolean?: never;
/** Not applicable. */ bytes?: never;
/** Not applicable. */ json?: never;
/** Not applicable. */ objectId?: never;
}
| {
/** A numeric value. */
number: number;
/** Not applicable. */ string?: never;
/** Not applicable. */ boolean?: never;
/** Not applicable. */ bytes?: never;
/** Not applicable. */ json?: never;
/** Not applicable. */ objectId?: never;
}
| {
/** A boolean value. */
boolean: boolean;
/** Not applicable. */ string?: never;
/** Not applicable. */ number?: never;
/** Not applicable. */ bytes?: never;
/** Not applicable. */ json?: never;
/** Not applicable. */ objectId?: never;
}
| {
/** A binary value. */
bytes: Buffer | ArrayBuffer;
/** Not applicable. */ string?: never;
/** Not applicable. */ number?: never;
/** Not applicable. */ boolean?: never;
/** Not applicable. */ json?: never;
/** Not applicable. */ objectId?: never;
}
| {
/** A JSON value (array or object). */
json: JsonArray | JsonObject;
/** Not applicable. */ string?: never;
/** Not applicable. */ number?: never;
/** Not applicable. */ boolean?: never;
/** Not applicable. */ bytes?: never;
/** Not applicable. */ objectId?: never;
}
| {
/** A reference to another object by its ID. */
objectId: string;
/** Not applicable. */ string?: never;
/** Not applicable. */ number?: never;
/** Not applicable. */ boolean?: never;
/** Not applicable. */ bytes?: never;
/** Not applicable. */ json?: never;
};
/**
* The map creation payload, specifying the semantics and initial entries for a new map object.
* Used as the body of {@link RestObjectOperationMapCreate} and as input to {@link RestObject.generateObjectId}.
*/
export interface RestObjectOperationMapCreateBody {
/** The map creation parameters. */
mapCreate: {
/** The conflict-resolution semantics for the map. */
semantics: Exclude<ObjectsMapSemantics, ObjectsMapSemanticsNamespace.UNKNOWN>;
/** Initial key-value pairs for the map. */
entries: Record<
string,
{
/**
* The initial value for this key, which is either a primitive value or the ID of another LiveObject.
*/
data: PublishObjectData;
}
>;
};
}
/**
* Operation to create a new map object at the specified path with initial entries.
*/
export type RestObjectOperationMapCreate = RestObjectOperationBase &
Partial<TargetByPath> &
RestObjectOperationMapCreateBody;
/**
* Operation to create a new map object with a client-generated object ID and initial entries.
* Use {@link RestObject.generateObjectId} to generate the object ID, nonce, and initial value
* needed for this operation.
*/
export type RestObjectOperationMapCreateWithObjectId = RestObjectOperationBase & {
/**
* The object ID for the new map object.
* Use {@link RestObject.generateObjectId} to generate this value along with the matching nonce and initial value.
*/
objectId: string;
/** The map creation parameters for a pre-computed object ID. */
mapCreateWithObjectId: {
/**
* JSON-encoded string representation of the {@link RestObjectOperationMapCreate.mapCreate} object.
* Binary values in entries must be Base64-encoded in this JSON string.
* For example: `'{"semantics":"lww","entries":{"name":{"data":{"string":"Alice"}}}}'`.
*/
initialValue: string;
/** Random string used to generate the object ID. */
nonce: string;
};
};
/**
* Operation to set a key to a specified value in an existing map object.
* Can target the map by either object ID or path.
*/
export type RestObjectOperationMapSet = AnyTargetRestObjectOperationBase & {
/** The map set parameters. */
mapSet: {
/** The key to set. */
key: string;
/** The value to assign to the key. */
value: PublishObjectData;
};
};
/**
* Operation to remove a key from an existing map object.
* Can target the map by either object ID or path.
*/
export type RestObjectOperationMapRemove = AnyTargetRestObjectOperationBase & {
/** The map remove parameters. */
mapRemove: {
/** The key to remove. */
key: string;
};
};
/**
* The counter creation payload, specifying the initial count for a new counter object.
* Used as the body of {@link RestObjectOperationCounterCreate} and as input to {@link RestObject.generateObjectId}.
*/
export interface RestObjectOperationCounterCreateBody {
/** The counter creation parameters. */
counterCreate: {
/** The initial value of the counter. */
count: number;
};
}
/**
* Operation to create a new counter object at the specified path with an initial count value.
*/
export type RestObjectOperationCounterCreate = RestObjectOperationBase &
Partial<TargetByPath> &
RestObjectOperationCounterCreateBody;
/**
* Operation to create a new counter object with a client-generated object ID and an initial count value.
* Use {@link RestObject.generateObjectId} to generate the object ID, nonce, and initial value
* needed for this operation.
*/
export type RestObjectOperationCounterCreateWithObjectId = RestObjectOperationBase & {
/**
* The object ID for the new counter object.
* Use {@link RestObject.generateObjectId} to generate this value along with the matching nonce and initial value.
*/
objectId: string;
/** The counter creation parameters for a pre-computed object ID. */
counterCreateWithObjectId: {
/**
* JSON-encoded string representation of the {@link RestObjectOperationCounterCreate.counterCreate} object.
* For example: `'{"count":0}'`.
*/
initialValue: string;
/** Random string used to generate the object ID. */
nonce: string;
};
};
/**
* Operation to increment (or decrement with negative values) an existing counter object.
* Can target the counter by either object ID or path.
*/
export type RestObjectOperationCounterInc = AnyTargetRestObjectOperationBase & {
/** The counter increment parameters. */
counterInc: {
/** The amount to increment by. Use a negative value to decrement. */
number: number;
};
};
/**
* Union type representing all possible REST object operations.
*/
export type RestObjectOperation =
| RestObjectOperationMapCreate
| RestObjectOperationMapCreateWithObjectId
| RestObjectOperationMapSet
| RestObjectOperationMapRemove
| RestObjectOperationCounterCreate
| RestObjectOperationCounterCreateWithObjectId
| RestObjectOperationCounterInc;
/**
* Result returned after successfully publishing object operations via REST.
* Contains information about the published message and affected object IDs.
*/
export interface RestObjectPublishResult {
/** The ID of the message containing the published operations. */
messageId: string;
/** The name of the channel the object message was published to. */
channel: string;
/**
* Array of object IDs that were affected by the operations.
* May include multiple IDs for wildcard paths and batch operations.
*/
objectIds: string[];
}
/**
* Result returned by {@link RestObject.generateObjectId}, containing the generated object ID
* and the values needed to construct a {@link RestObjectOperationMapCreateWithObjectId}
* or {@link RestObjectOperationCounterCreateWithObjectId} operation.
*/
export interface RestObjectGenerateIdResult {
/** The generated object ID. */
objectId: string;
/** The nonce used in ID generation. */
nonce: string;
/** The JSON-encoded initial value used in ID generation. */
initialValue: string;
}
/**
* Request parameters for {@link RestObject.get}.
*/
export interface RestObjectGetParams {
/** The unique identifier of the object instance to fetch. If omitted, fetches from the channel object. */
objectId?: string;
/** A dot-separated path to return a subset of the object. Evaluated relative to the channel object or the specified objectId. */
path?: string;
/** When true (default), returns a values-only representation. When false, includes object IDs and type metadata. */
compact?: boolean;
}
/**
* Parameters for {@link RestObject.get} when requesting compact format (default).
*/
export type RestObjectGetCompactParams = Omit<RestObjectGetParams, 'compact'> & {
/** Must be `true` or omitted for compact format. */
compact?: true;
};
/**
* Parameters for {@link RestObject.get} when requesting full object response format.
*/
export type RestObjectGetFullParams = Omit<RestObjectGetParams, 'compact'> & {
/** Must be `false` for full object response format. */
compact: false;
};
// Note: this type does not include arrays as no LiveObject type currently compacts
// into one, and json-typed values remain as JSON-encoded strings rather than being parsed.
/**
* Result of {@link RestObject.get} when `compact` is `true` (default).
* Represents a compacted view of the object on a channel or its leaf value.
*/
export type RestObjectGetCompactResult =
| JsonScalar
| Buffer
| ArrayBuffer
| { [key: string]: RestObjectGetCompactResult };
/**
* Result of {@link RestObject.get} when `compact` is `false`.
*
* One of:
* - A {@link RestLiveMap} or {@link RestLiveCounter} with full object metadata and decoded data values.
* - An {@link AnyRestLiveObject} for unrecognized object types.
* - A {@link RestObjectData | ObjectData} leaf value when the path resolves to a primitive entry in a map.
*
* In all cases, `bytes` values are decoded to `Buffer`/`ArrayBuffer` and `json` values are decoded
* to native objects/arrays.
*/
export type RestObjectGetFullResult = RestLiveObject | RestObjectData;
/**
* A full object structure including object IDs and type metadata, returned as part of {@link RestObjectGetFullResult}.
*/
export type RestLiveObject = RestLiveMap | RestLiveCounter | AnyRestLiveObject;
/**
* Full object structure of a map object with metadata.
*/
export interface RestLiveMap {
/** The ID of the map object. */
objectId: string;
/** Describes the value of a map object. */
map: {
/** The conflict-resolution semantics used by the map object, one of the {@link ObjectsMapSemantics} enum values. */
semantics: ObjectsMapSemantics;
/** The map entries, indexed by key. */
entries: Record<string, RestObjectDataMapEntry | RestLiveObjectMapEntry>;
};
}
/**
* A map entry containing a primitive leaf value.
*/
export interface RestObjectDataMapEntry {
/** The decoded object data for this entry. */
data: RestObjectData;
}
/**
* A map entry containing a nested LiveObject.
*/
export interface RestLiveObjectMapEntry {
/** The nested LiveObject at this entry. */
data: RestLiveObject;
}
/**
* Full object structure of a counter object with metadata.
*/
export interface RestLiveCounter {
/** The ID of the counter object. */
objectId: string;
/** Describes the value of a counter object. */
counter: {
/** Holds the value of the counter. */
data: {
/** The value of the counter. */
number: number;
};
};
}
/**
* Fallback type for compatibility with future object types.
*/
export type AnyRestLiveObject = {
/** The ID of the object, available for all object types. */
objectId: string;
};
/**
* A decoded leaf data value in the full {@link RestObject.get} responses.
*/
type RestObjectData = Omit<ObjectData, 'value'>;
/**
* Enables the Objects to be read, modified and subscribed to for a realtime channel.
*/
export declare interface RealtimeObject {
/**
* Retrieves a {@link PathObject} for the object on a channel.
* Implicitly {@link RealtimeChannel.attach | attaches to the channel} if not already attached.
*
* A type parameter can be provided to describe the structure of the Objects on the channel.
*
* Example:
*
* ```typescript
* import { LiveCounter } from 'ably/liveobjects';
*
* type MyObject = {
* myTypedCounter: LiveCounter;
* };
*
* const myTypedObject = await channel.object.get<MyObject>();
* ```
*
* @returns A promise which, upon success, will be fulfilled with a {@link PathObject}. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
get<T extends Record<string, Value>>(): Promise<PathObject<LiveMap<T>>>;
/**
* Registers the provided listener for the specified event. If `on()` is called more than once with the same listener and event, the listener is added multiple times to its listener registry. Therefore, as an example, assuming the same listener is registered twice using `on()`, and an event is emitted once, the listener would be invoked twice.
*
* @param event - The named event to listen for.
* @param callback - The event listener.
* @returns A {@link StatusSubscription} object that allows the provided listener to be deregistered from future updates.
*/
on(event: ObjectsEvent, callback: ObjectsEventCallback): StatusSubscription;
/**
* Removes all registrations that match both the specified listener and the specified event.
*
* @param event - The named event.
* @param callback - The event listener.
*/
off(event: ObjectsEvent, callback: ObjectsEventCallback): void;
}
/**
* Primitive types that can be stored in collection types.
* Includes JSON-serializable data so that maps and lists can hold plain JS values.
*/
export type Primitive =
| string
| number
| boolean
| Buffer
| ArrayBuffer
// JSON-serializable primitive values
| JsonArray
| JsonObject;
/**
* Represents a JSON-encodable value.
*/
export type Json = JsonScalar | JsonArray | JsonObject;
/**
* Represents a JSON-encodable scalar value.
*/
export type JsonScalar = null | boolean | number | string;
/**
* Represents a JSON-encodable array.
*/
export type JsonArray = Json[];
/**
* Represents a JSON-encodable object.
*/
export type JsonObject = { [prop: string]: Json | undefined };
// Branded interfaces that enables TypeScript to distinguish
// between LiveObject types even when they have identical structure (empty interfaces in this case).
// Enables PathObject<T> to dispatch to correct method sets via conditional types.
/**
* A {@link LiveMap} is a collection type that maps string keys to values, which can be either primitive values or other LiveObjects.
*/
export interface LiveMap<_T extends Record<string, Value> = Record<string, Value>> {
/** LiveMap type symbol */
[__livetype]: 'LiveMap';
}
/**
* A {@link LiveCounter} is a numeric type that supports atomic increment and decrement operations.
*/
export interface LiveCounter {
/** LiveCounter type symbol */
[__livetype]: 'LiveCounter';
}
/**
* Type union that matches any LiveObject type that can be mutated, subscribed to, etc.
*/
export type LiveObject = LiveMap | LiveCounter;
/**
* Type union that defines the base set of allowed types that can be stored in collection types.
* Describes the set of all possible values that can parameterize PathObject.
* This is the canonical union used when a narrower type cannot be inferred.
*/
export type Value = LiveObject | Primitive;
/**
* CompactedValue transforms LiveObject types into in-memory JavaScript equivalents.
* LiveMap becomes an object, LiveCounter becomes a number, primitive values remain unchanged.
*/
export type CompactedValue<T extends Value> =
// LiveMap types
[T] extends [LiveMap<infer U>]
? { [K in keyof U]: CompactedValue<U[K]> }
: [T] extends [LiveMap<infer U> | undefined]
? { [K in keyof U]: CompactedValue<U[K]> } | undefined
: // LiveCounter types
[T] extends [LiveCounter]
? number
: [T] extends [LiveCounter | undefined]
? number | undefined
: // Other primitive types
[T] extends [Primitive]
? T
: [T] extends [Primitive | undefined]
? T
: any;
/**
* Represents a cyclic object reference in a JSON-serializable format.
*/
export interface ObjectIdReference {
/** The referenced object Id. */
objectId: string;
}
/**
* CompactedJsonValue transforms LiveObject types into JSON-serializable equivalents.
* LiveMap becomes an object, LiveCounter becomes a number, binary values become base64-encoded strings,
* other primitives remain unchanged.
*
* Additionally, cyclic references are represented as `{ objectId: string }` instead of in-memory pointers to same objects.
*/
export type CompactedJsonValue<T extends Value> =
// LiveMap types - note: cyclic references become ObjectIdReference
[T] extends [LiveMap<infer U>]
? { [K in keyof U]: CompactedJsonValue<U[K]> } | ObjectIdReference
: [T] extends [LiveMap<infer U> | undefined]
? { [K in keyof U]: CompactedJsonValue<U[K]> } | ObjectIdReference | undefined
: // LiveCounter types
[T] extends [LiveCounter]
? number
: [T] extends [LiveCounter | undefined]
? number | undefined
: // Binary types (converted to base64 strings)
[T] extends [ArrayBuffer]
? string
: [T] extends [ArrayBuffer | undefined]
? string | undefined
: [T] extends [ArrayBufferView]
? string
: [T] extends [ArrayBufferView | undefined]
? string | undefined
: // Other primitive types
[T] extends [Primitive]
? T
: [T] extends [Primitive | undefined]
? T
: any;
/**
* PathObjectBase defines the set of common methods on a PathObject
* that are present regardless of the underlying type.
*/
interface PathObjectBase {
/**
* Get the fully-qualified path string for this PathObject.
*
* Path segments with dots in them are escaped with a backslash.
* For example, a path with segments `['a', 'b.c', 'd']` will be represented as `a.b\.c.d`.
*/
path(): string;
/**
* Registers a listener that is called each time the object or a primitive value at this path is updated.
*
* The provided listener receives a {@link PathObject} representing the path at which there was an object change,
* and, if applicable, an {@link ObjectMessage} that carried the operation that led to the change.
*
* By default, subscriptions observe nested changes, but you can configure the observation depth
* using the `options` parameter.
*
* A PathObject subscription observes whichever value currently exists at this path.
* The subscription remains active even if the path temporarily does not resolve to any value
* (for example, if an entry is removed from a map). If the object instance at this path changes,
* the subscription automatically switches to observe the new instance and stops observing the old one.
*
* @param listener - An event listener function.
* @param options - Optional subscription configuration.
* @returns A {@link Subscription} object that allows the provided listener to be deregistered from future updates.
*/
subscribe(
listener: EventCallback<PathObjectSubscriptionEvent>,
options?: PathObjectSubscriptionOptions,
): Subscription;
/**
* Registers a subscription listener and returns an async iterator that yields
* subscription events each time the object or a primitive value at this path is updated.
*
* This method functions in the same way as the regular {@link PathObjectBase.subscribe | PathObject.subscribe()} method,
* but instead returns an async iterator that can be used in a `for await...of` loop for convenience.
*
* @param options - Optional subscription configuration.
* @returns An async iterator that yields {@link PathObjectSubscriptionEvent} objects.
*/
subscribeIterator(options?: PathObjectSubscriptionOptions): AsyncIterableIterator<PathObjectSubscriptionEvent>;
}
/**
* PathObjectCollectionMethods defines the set of common methods on a PathObject
* that are present for any collection type, regardless of the specific underlying type.
*/
interface PathObjectCollectionMethods {
/**
* Collection types support obtaining a PathObject with a fully-qualified string path,
* which is evaluated from the current path.
* Using this method loses rich compile-time type information.
*
* @param path - A fully-qualified path string to navigate to, relative to the current path.
* @returns A {@link PathObject} for the specified path.
*/
at<T extends Value = Value>(path: string): PathObject<T>;
}
/**
* Defines collection methods available on a {@link LiveMapPathObject}.
*/
interface LiveMapPathObjectCollectionMethods<T extends Record<string, Value> = Record<string, Value>> {
/**
* Returns an iterable of key-value pairs for each entry in the map at this path.
* Each value is represented as a {@link PathObject} corresponding to its key.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
entries(): IterableIterator<[keyof T, PathObject<T[keyof T]>]>;
/**
* Returns an iterable of keys in the map at this path.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
keys(): IterableIterator<keyof T>;
/**
* Returns an iterable of values in the map at this path.
* Each value is represented as a {@link PathObject}.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
values(): IterableIterator<PathObject<T[keyof T]>>;
/**
* Returns the number of entries in the map at this path.
*
* If the path does not resolve to a map object, returns `undefined`.
*/
size(): number | undefined;
}
/**
* A PathObject representing a {@link LiveMap} instance at a specific path.
* The type parameter T describes the expected structure of the map's entries.
*/
export interface LiveMapPathObject<T extends Record<string, Value> = Record<string, Value>>
extends PathObjectBase,
PathObjectCollectionMethods,
LiveMapPathObjectCollectionMethods<T>,
LiveMapOperations<T> {
/**
* Navigate to a child path within the map by obtaining a PathObject for that path.
* The next path segment in a LiveMap is identified with a string key.
*
* @param key - A string key for the next path segment within the map.
* @returns A {@link PathObject} for the specified key.
*/
get<K extends keyof T & string>(key: K): PathObject<T[K]>;
/**
* Get the specific map instance currently at this path.
* If the path does not resolve to any specific instance, returns `undefined`.
*
* @returns The {@link LiveMapInstance} at this path, or `undefined` if none exists.
*/
instance(): LiveMapInstance<T> | undefined;
/**
* Get an in-memory JavaScript object representation of the map at this path.
* Cyclic references are handled through memoization, returning shared compacted
* object references for previously visited objects. This means the value returned
* from `compact()` cannot be directly JSON-stringified if the object may contain cycles.
*
* If the path does not resolve to any specific instance, returns `undefined`.
*
* Use {@link LiveMapPathObject.compactJson | compactJson()} for a JSON-serializable representation.
*/
compact(): CompactedValue<LiveMap<T>> | undefined;
/**
* Get a JSON-serializable representation of the map at this path.
* Binary values are converted to base64-encoded strings.
* Cyclic references are represented as `{ objectId: string }` instead of in-memory pointers,
* making the result safe to pass to `JSON.stringify()`.
*
* If the path does not resolve to any specific instance, returns `undefined`.
*
* Use {@link LiveMapPathObject.compact | compact()} for an in-memory representation.
*/
compactJson(): CompactedJsonValue<LiveMap<T>> | undefined;
}
/**
* A PathObject representing a {@link LiveCounter} instance at a specific path.
*/
export interface LiveCounterPathObject extends PathObjectBase, LiveCounterOperations {
/**
* Get the current value of the counter instance currently at this path.
* If the path does not resolve to any specific instance, returns `undefined`.
*/
value(): number | undefined;
/**
* Get the specific counter instance currently at this path.
* If the path does not resolve to any specific instance, returns `undefined`.
*
* @returns The {@link LiveCounterInstance} at this path, or `undefined` if none exists.
*/
instance(): LiveCounterInstance | undefined;
/**
* Get a number representation of the counter at this path.
* This is an alias for calling {@link LiveCounterPathObject.value | value()}.
*
* If the path does not resolve to any specific instance, returns `undefined`.
*/
compact(): CompactedValue<LiveCounter> | undefined;
/**
* Get a number representation of the counter at this path.
* This is an alias for calling {@link LiveCounterPathObject.value | value()}.
*
* If the path does not resolve to any specific instance, returns `undefined`.
*/
compactJson(): CompactedJsonValue<LiveCounter> | undefined;
}
/**
* A PathObject representing a primitive value at a specific path.
*/
export interface PrimitivePathObject<T extends Primitive = Primitive> extends PathObjectBase {
/**
* Get the current value of the primitive currently at this path.
* If the path does not resolve to any specific entry, returns `undefined`.
*/
value(): T | undefined;
/**
* Get a JavaScript object representation of the primitive value at this path.
* This is an alias for calling {@link PrimitivePathObject.value | value()}.
*
* If the path does not resolve to any specific entry, returns `undefined`.
*/
compact(): CompactedValue<T> | undefined;
/**
* Get a JSON-serializable representation of the primitive value at this path.
* Binary values are converted to base64-encoded strings.
*
* If the path does not resolve to any specific entry, returns `undefined`.
*/
compactJson(): CompactedJsonValue<T> | undefined;
}
/**
* AnyPathObjectCollectionMethods defines all possible methods available on a PathObject
* for the underlying collection types.
*/
interface AnyPathObjectCollectionMethods {
// LiveMap collection methods
/**
* Returns an iterable of key-value pairs for each entry in the map, if the path resolves to a {@link LiveMap}.
* Each value is represented as a {@link PathObject} corresponding to its key.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
entries<T extends Record<string, Value>>(): IterableIterator<[keyof T, PathObject<T[keyof T]>]>;
/**
* Returns an iterable of keys in the map, if the path resolves to a {@link LiveMap}.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
keys<T extends Record<string, Value>>(): IterableIterator<keyof T>;
/**
* Returns an iterable of values in the map, if the path resolves to a {@link LiveMap}.
* Each value is represented as a {@link PathObject}.
*
* If the path does not resolve to a map object, returns an empty iterator.
*/
values<T extends Record<string, Value>>(): IterableIterator<PathObject<T[keyof T]>>;
/**
* Returns the number of entries in the map, if the path resolves to a {@link LiveMap}.
*
* If the path does not resolve to a map object, returns `undefined`.
*/
size(): number | undefined;
}
/**
* Represents a {@link PathObject} when its underlying type is not known.
* Provides a unified interface that includes all possible methods.
*
* Each method supports type parameters to specify the expected
* underlying type when needed.
*/
export interface AnyPathObject
extends PathObjectBase,
PathObjectCollectionMethods,
AnyPathObjectCollectionMethods,
AnyOperations {