@dittolive/ditto 1.0.18 → 1.1.1

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.
package/types/ditto.d.ts CHANGED
@@ -5,6 +5,25 @@ declare type SortDirection = 'ascending' | 'descending';
5
5
  /**
6
6
  * Defines the various strategies available when inserting a document into a
7
7
  * collection.
8
+ *
9
+ * - `merge`: the existing document will be merged with the document being
10
+ * inserted, if there is a pre-existing document.
11
+ *
12
+ * - `overwrite`: an existing document will be overwritten. This can be thought
13
+ * of as first removing the existing document completely and then inserting
14
+ * the new document in its place, if there is a pre-existing document.
15
+ *
16
+ * - `insertIfAbsent`: insert the document only if there is not already a
17
+ * document with the same ID in the store. If there is already a document in
18
+ * the store with the same ID then this will be a no-op.
19
+ *
20
+ * - `insertDefaultIfAbsent`: insert the document, with its contents treated as
21
+ * default data, only if there is not already a document with the same ID in
22
+ * the store. If there is already a document in the store with the same ID
23
+ * then this will be a no-op. Use this strategy if you want to insert default
24
+ * data for a given document ID, which you want to treat as common initial
25
+ * data amongst all peers and that you expect to be mutated or overwritten in
26
+ * due course.
8
27
  */
9
28
  declare type WriteStrategy = 'merge' | 'overwrite' | 'insertIfAbsent' | 'insertDefaultIfAbsent';
10
29
  /**
@@ -49,95 +68,173 @@ declare type InitOptions = {
49
68
  */
50
69
  declare function init(options?: InitOptions): Promise<void>;
51
70
 
71
+ /** @internal */
72
+ declare class KeepAlive {
73
+ /** @internal */
74
+ get isActive(): boolean;
75
+ /** @internal */
76
+ constructor();
77
+ /** @internal */
78
+ retain(id: string): void;
79
+ /** @internal */
80
+ release(id: string): void;
81
+ /** @internal */
82
+ currentIDs(): string[];
83
+ /** @internal */
84
+ countForID(id: string): number | null;
85
+ private static finalizationRegistry;
86
+ private intervalID;
87
+ private countsByID;
88
+ }
89
+
52
90
  /**
53
- * Provides feedback to the developer about Ditto authentication status.
91
+ * Part of {@link TransportConfig} type, configuration for listening for TCP
92
+ * connections.
54
93
  */
55
- interface AuthenticationHandler {
56
- /**
57
- * There is no Ditto authentication token or it has expired. Sync will not
58
- * work until there is a successful login using one of the login methods on
59
- * {@link Authenticator}.
60
- */
61
- authenticationRequired(authenticator: Authenticator): any;
94
+ interface TransportConfigListenTCP {
95
+ isEnabled: boolean;
96
+ interfaceIP: string;
97
+ port: number;
98
+ }
99
+ /**
100
+ * Part of {@link TransportConfig} type, configuration for listening for HTTP,
101
+ * including Websocket, connections.
102
+ */
103
+ interface TransportConfigListenHTTP {
104
+ isEnabled: boolean;
105
+ interfaceIP: string;
106
+ port: number;
107
+ staticContentPath?: string;
108
+ websocketSync: boolean;
109
+ tlsKeyPath?: string;
110
+ tlsCertificatePath?: string;
111
+ }
112
+ /**
113
+ * Part of {@link TransportConfig} type, configuration for all P2P transports.
114
+ */
115
+ interface TransportConfigPeerToPeer {
116
+ bluetoothLE: {
117
+ isEnabled: boolean;
118
+ };
119
+ awdl: {
120
+ isEnabled: boolean;
121
+ };
122
+ lan: TransportConfigLan;
123
+ }
124
+ /**
125
+ * Part of {@link TransportConfig} type, configuration for discovering and syncing with peers on LAN.
126
+ */
127
+ interface TransportConfigLan {
128
+ isEnabled: boolean;
129
+ isMdnsEnabled: boolean;
130
+ isMulticastEnabled: boolean;
131
+ }
132
+ /**
133
+ * Part of {@link TransportConfig} type, configuration for connecting to TCP
134
+ * and Websocket servers.
135
+ */
136
+ interface TransportConfigConnect {
137
+ tcpServers: string[];
138
+ websocketURLs: string[];
139
+ }
140
+ /**
141
+ * Part of {@link TransportConfig} type, configuration for listening for
142
+ * incoming TCP and HTTP connections.
143
+ */
144
+ interface TransportConfigListen {
145
+ tcp: TransportConfigListenTCP;
146
+ http: TransportConfigListenHTTP;
147
+ }
148
+ /**
149
+ * Part of {@link TransportConfig} type, settings not associated with any specific type of transport.
150
+ */
151
+ interface TransportConfigGlobal {
62
152
  /**
63
- * Warns that the Ditto authentication token is getting old.
153
+ * The sync group for this device.
64
154
  *
65
- * Ditto will attempt to refresh tokens periodically, starting from halfway
66
- * through the token's validity period. This reduces the risk of
67
- * authentication expiring while the user is offline.
155
+ * When peer-to-peer transports are enabled, all devices with the same App ID will
156
+ * normally form an interconnected mesh network. In some situations it may be
157
+ * desirable to have distinct groups of devices within the same app, so that
158
+ * connections will only be formed within each group. The `syncGroup` parameter
159
+ * changes that group membership. A device can only ever be in one sync group, which
160
+ * by default is group 0. Up to 2^32 distinct group numbers can be used in an app.
68
161
  *
69
- * The refresh will happen automatically if Ditto has a suitable refresh
70
- * token. If new credentials are required, such as a third-party token or a
71
- * username/password, then Ditto does not cache that information and you must
72
- * submit it again using one of the `login` methods on {@link Authenticator}.
162
+ * This is an optimization, not a security control. If a connection is created
163
+ * manually, such as by specifying a `connect` transport, then devices from
164
+ * different sync groups will still sync as normal. If two groups of devices are
165
+ * intended to have access to different data sets, this must be enforced using
166
+ * Ditto's permissions system.
73
167
  */
74
- authenticationExpiringSoon(authenticator: Authenticator, secondsRemaining: number): any;
168
+ syncGroup: number;
75
169
  }
76
170
  /**
77
- * Log in to a remote authentication service, using an
78
- * `OnlineWithAuthentication` or an `Online` identity.
171
+ * A configuration object specifying which network transports Ditto should
172
+ * use to sync data.
173
+ *
174
+ * A Ditto object comes with a default transport configuration where all
175
+ * available peer-to-peer transports are enabled. You can customize this by
176
+ * copying that or initializing a new `TransportConfig`, adjusting its
177
+ * properties, and supplying it to `setTransportConfig()` on `Ditto`.
178
+ *
179
+ * When you initialize a new `TransportConfig` instance, all transports are
180
+ * disabled. You must enable each one explicitly.
181
+ *
182
+ * Peer-to-peer transports will automatically discover peers in the vicinity
183
+ * and create connections without any configuration. These are configured via
184
+ * the `peerToPeer` property. To turn each one on, set its `isEnabled` property
185
+ * to `true`.
186
+ *
187
+ * To connect to a peer at a known location, such as a Ditto Big Peer, add its
188
+ * address inside the connect configuration. These are either "host:port"
189
+ * strings for raw TCP sync, or a "wss://…" URL for websockets.
190
+ *
191
+ * The listen configurations are for specific less common data sync scenarios.
192
+ * Please read the documentation on the Ditto website for examples. Incorrect
193
+ * use of listen can result in insecure configurations.
194
+ *
195
+ * **IMPORTANT**: when running in the browser, only the `connect.websocketURLs`
196
+ * part is considered, the rest of the configuration is ignored.
79
197
  */
80
- interface Authenticator {
198
+ declare class TransportConfig {
199
+ /** Configuration for peer-to-peer connections. */
200
+ readonly peerToPeer: TransportConfigPeerToPeer;
201
+ /** Configuration for connecting to servers. */
202
+ readonly connect: TransportConfigConnect;
203
+ /** Configuration for listening for incomping connections. */
204
+ readonly listen: TransportConfigListen;
205
+ /** Settings not associated with any specific type of transport. */
206
+ readonly global: TransportConfigGlobal;
81
207
  /**
82
- * Returns `true` if authentication is avaiable and the login methods can be
83
- * used, otherwise returns `false`. Currently, authentication is only
84
- * available if Ditto was initialized with an identity of type
85
- * {@link IdentityOnlineWithAuthentication | 'onlineWithAuthentication'}.
208
+ * Create a new transport config initialized with the default settings.
86
209
  */
87
- readonly loginSupported: boolean;
210
+ constructor();
88
211
  /**
89
- * Log in to Ditto with a third-party token. Throws if authentication is not
90
- * available, which can be checked with {@link loginSupported}.
91
- *
92
- * @param token the authentication token required to log in.
93
- * @param options.provider the name of the authentication provider.
212
+ * Enables all peer-to-peer transports. Throws if receiver is frozen.
94
213
  */
95
- loginWithToken(token: string, options?: any): Promise<void>;
214
+ setAllPeerToPeerEnabled(enabled: boolean): void;
96
215
  /**
97
- * Log in to Ditto with a username and password. Throws if authentication is
98
- * not available, which can be checked with {@link loginSupported}.
99
- *
100
- * @param username the username component of the credentials used for log in.
101
- * @param password the password component of the credentials used for log in.
102
- * @param options.provider the name of the authentication provider.
216
+ * Returns `true` if the transport configuration is frozen, otherwise
217
+ * returns `false`.
103
218
  */
104
- loginWithUsernameAndPassword(username: string, password: string, options?: any): Promise<void>;
219
+ readonly isFrozen: boolean;
105
220
  /**
106
- * Query whether Ditto has a valid authentication token.
107
- *
108
- * This will only be `true` when using an `OnlineWithAuthentication` or an
109
- * `Online` identity, after a successful login. If the authentication token is
110
- * allowed to expire then it will return `false` instead.
221
+ * (Deep) freezes the receiver such that it can't be modified anymore.
111
222
  */
112
- isAuthenticated(): boolean;
223
+ freeze(): TransportConfig;
113
224
  /**
114
- * Return the currently logged-in user ID.
115
- *
116
- * This will be `null` if there is no valid authentication or
117
- * `OnlineWithAuthentication`/`Online` mode is not being used.
225
+ * Returns a (deep) copy of the receiver.
118
226
  */
119
- readonly userID: string | null;
120
- }
121
- /** @internal */
122
- declare class OnlineWithAuthenticationAuthenticator implements Authenticator {
123
- readonly loginSupported: boolean;
124
- loginWithToken(token: string, provider: string): Promise<void>;
125
- loginWithUsernameAndPassword(username: string, password: string, provider: string): Promise<void>;
126
- isAuthenticated(): boolean;
127
- readonly authClientPointer: Pointer<AuthClientType>;
128
- constructor(authClientPointer: Pointer<AuthClientType>);
129
- private static finalizationRegistry;
130
- private static finalize;
131
- get userID(): string | null;
132
- }
133
- /** @internal */
134
- declare class NotAvailableAuthenticator implements Authenticator {
135
- readonly loginSupported: boolean;
136
- loginWithToken(token: string, options?: any): Promise<void>;
137
- loginWithUsernameAndPassword(username: string, password: string, options?: any): Promise<void>;
138
- isAuthenticated(): boolean;
139
- get userID(): string | null;
140
- constructor();
227
+ copy(): TransportConfig;
228
+ /**
229
+ * Returns `true` if passed in TCP configurations are equal, otherwise
230
+ * returns `false`.
231
+ */
232
+ static areListenTCPsEqual(left: TransportConfigListenTCP, right: TransportConfigListenTCP): boolean;
233
+ /**
234
+ * Returns `true` if passed in HTTP configurations are equal, otherwise
235
+ * returns `false`.
236
+ */
237
+ static areListenHTTPsEqual(left: TransportConfigListenHTTP, right: TransportConfigListenHTTP): boolean;
141
238
  }
142
239
 
143
240
  /**
@@ -341,156 +438,6 @@ interface IdentityOnlineWithAuthentication {
341
438
  */
342
439
  declare type Identity = IdentityDevelopment | IdentityOfflinePlayground | IdentitySharedKey | IdentityProduction | IdentityManual | IdentityOnlinePlayground | IdentityOnline | IdentityOnlineWithAuthentication;
343
440
 
344
- /**
345
- * Part of {@link TransportConfig} type, configuration for listening for TCP
346
- * connections.
347
- */
348
- interface TransportConfigListenTCP {
349
- isEnabled: boolean;
350
- interfaceIP: string;
351
- port: number;
352
- }
353
- /**
354
- * Part of {@link TransportConfig} type, configuration for listening for HTTP,
355
- * including Websocket, connections.
356
- */
357
- interface TransportConfigListenHTTP {
358
- isEnabled: boolean;
359
- interfaceIP: string;
360
- port: number;
361
- staticContentPath?: string;
362
- websocketSync: boolean;
363
- tlsKeyPath?: string;
364
- tlsCertificatePath?: string;
365
- }
366
- /**
367
- * Part of {@link TransportConfig} type, configuration for all P2P transports.
368
- */
369
- interface TransportConfigPeerToPeer {
370
- bluetoothLE: {
371
- isEnabled: boolean;
372
- };
373
- awdl: {
374
- isEnabled: boolean;
375
- };
376
- lan: TransportConfigLan;
377
- }
378
- /**
379
- * Part of {@link TransportConfig} type, configuration for discovering and syncing with peers on LAN.
380
- */
381
- interface TransportConfigLan {
382
- isEnabled: boolean;
383
- isMdnsEnabled: boolean;
384
- isMulticastEnabled: boolean;
385
- }
386
- /**
387
- * Part of {@link TransportConfig} type, configuration for connecting to TCP
388
- * and Websocket servers.
389
- */
390
- interface TransportConfigConnect {
391
- tcpServers: string[];
392
- websocketURLs: string[];
393
- }
394
- /**
395
- * Part of {@link TransportConfig} type, configuration for listening for
396
- * incoming TCP and HTTP connections.
397
- */
398
- interface TransportConfigListen {
399
- tcp: TransportConfigListenTCP;
400
- http: TransportConfigListenHTTP;
401
- }
402
- /**
403
- * Part of {@link TransportConfig} type, settings not associated with any specific type of transport.
404
- */
405
- interface TransportConfigGlobal {
406
- /**
407
- * The sync group for this device.
408
- *
409
- * When peer-to-peer transports are enabled, all devices with the same App ID will
410
- * normally form an interconnected mesh network. In some situations it may be
411
- * desirable to have distinct groups of devices within the same app, so that
412
- * connections will only be formed within each group. The `syncGroup` parameter
413
- * changes that group membership. A device can only ever be in one sync group, which
414
- * by default is group 0. Up to 2^32 distinct group numbers can be used in an app.
415
- *
416
- * This is an optimization, not a security control. If a connection is created
417
- * manually, such as by specifying a `connect` transport, then devices from
418
- * different sync groups will still sync as normal. If two groups of devices are
419
- * intended to have access to different data sets, this must be enforced using
420
- * Ditto's permissions system.
421
- */
422
- syncGroup: number;
423
- }
424
- /**
425
- * A configuration object specifying which network transports Ditto should
426
- * use to sync data.
427
- *
428
- * A Ditto object comes with a default transport configuration where all
429
- * available peer-to-peer transports are enabled. You can customize this by
430
- * copying that or initializing a new `TransportConfig`, adjusting its
431
- * properties, and supplying it to `setTransportConfig()` on `Ditto`.
432
- *
433
- * When you initialize a new `TransportConfig` instance, all transports are
434
- * disabled. You must enable each one explicitly.
435
- *
436
- * Peer-to-peer transports will automatically discover peers in the vicinity
437
- * and create connections without any configuration. These are configured via
438
- * the `peerToPeer` property. To turn each one on, set its `isEnabled` property
439
- * to `true`.
440
- *
441
- * To connect to a peer at a known location, such as a Ditto Big Peer, add its
442
- * address inside the connect configuration. These are either "host:port"
443
- * strings for raw TCP sync, or a "wss://…" URL for websockets.
444
- *
445
- * The listen configurations are for specific less common data sync scenarios.
446
- * Please read the documentation on the Ditto website for examples. Incorrect
447
- * use of listen can result in insecure configurations.
448
- *
449
- * **IMPORTANT**: when running in the browser, only the `connect.websocketURLs`
450
- * part is considered, the rest of the configuration is ignored.
451
- */
452
- declare class TransportConfig {
453
- /** Configuration for peer-to-peer connections. */
454
- readonly peerToPeer: TransportConfigPeerToPeer;
455
- /** Configuration for connecting to servers. */
456
- readonly connect: TransportConfigConnect;
457
- /** Configuration for listening for incomping connections. */
458
- readonly listen: TransportConfigListen;
459
- /** Settings not associated with any specific type of transport. */
460
- readonly global: TransportConfigGlobal;
461
- /**
462
- * Create a new transport config initialized with the default settings.
463
- */
464
- constructor();
465
- /**
466
- * Enables all peer-to-peer transports. Throws if receiver is frozen.
467
- */
468
- setAllPeerToPeerEnabled(enabled: boolean): void;
469
- /**
470
- * Returns `true` if the transport configuration is frozen, otherwise
471
- * returns `false`.
472
- */
473
- readonly isFrozen: boolean;
474
- /**
475
- * (Deep) freezes the receiver such that it can't be modified anymore.
476
- */
477
- freeze(): TransportConfig;
478
- /**
479
- * Returns a (deep) copy of the receiver.
480
- */
481
- copy(): TransportConfig;
482
- /**
483
- * Returns `true` if passed in TCP configurations are equal, otherwise
484
- * returns `false`.
485
- */
486
- static areListenTCPsEqual(left: TransportConfigListenTCP, right: TransportConfigListenTCP): boolean;
487
- /**
488
- * Returns `true` if passed in HTTP configurations are equal, otherwise
489
- * returns `false`.
490
- */
491
- static areListenHTTPsEqual(left: TransportConfigListenHTTP, right: TransportConfigListenHTTP): boolean;
492
- }
493
-
494
441
  /**
495
442
  * TODO: document.
496
443
  * @internal
@@ -787,8 +734,18 @@ declare class Document {
787
734
  * represents the passed in document(s).
788
735
  */
789
736
  static hashMnemonic(documentOrMany: DocumentLike | DocumentLike[]): string;
737
+ /**
738
+ * Support for JSON-stringifying a document directly.
739
+ */
740
+ toJSON(): DocumentValue;
790
741
  /** @internal */
791
742
  constructor();
743
+ /** @internal */
744
+ static idCBOR(document: DocumentLike): Uint8Array;
745
+ /** @internal */
746
+ static canonicalizedIDCBOR(idCBOR: Uint8Array): Uint8Array;
747
+ /** @internal */
748
+ static isIDCBORCanonical(idCBOR: Uint8Array): boolean;
792
749
  }
793
750
  /**
794
751
  * A representation of a {@link Document} that can be mutated via
@@ -855,12 +812,26 @@ declare class MutableDocument {
855
812
  * Increments the counter of `mutableDocument` at the given `keyPath`.
856
813
  */
857
814
  static incrementCounterAt(mutableDocument: MutableDocumentLike, keyPath: string, amount: number, skipValidation?: boolean): void;
815
+ /**
816
+ * Support for JSON-stringifying a mutable document directly.
817
+ */
818
+ toJSON(): DocumentValue;
858
819
  /** @internal */
859
820
  constructor();
860
821
  /** @internal */
861
822
  readonly '@ditto.updateResults': UpdateResult[];
823
+ /** @internal */
824
+ static idCBOR(mutableDocument: MutableDocumentLike): Uint8Array;
825
+ /** @internal */
826
+ static canonicalizedIDCBOR: typeof Document.canonicalizedIDCBOR;
827
+ /** @internal */
828
+ static isIDCBORCanonical: typeof Document.isIDCBORCanonical;
862
829
  }
863
830
  /** @internal */
831
+ declare function validateDocumentIDValue(id: DocumentIDValue): DocumentIDValue;
832
+ /** @internal */
833
+ declare function validateDocumentIDCBOR(idCBOR: Uint8Array): Uint8Array;
834
+ /** @internal */
864
835
  declare const documentBridge: Bridge<Document, "CDocument_t">;
865
836
  /** @internal */
866
837
  declare const mutableDocumentBridge: Bridge<MutableDocument, "CDocument_t">;
@@ -1073,6 +1044,9 @@ declare class UpdateResultsMap {
1073
1044
  * {@link PendingCursorOperation} object. It handles the logic for calling the
1074
1045
  * event handler that is provided to `observe` calls.
1075
1046
  *
1047
+ * Ditto will prevent the process from exiting as long as there are
1048
+ * active live queries (not relevant when running in the browser).
1049
+ *
1076
1050
  * `LiveQuery` objects must be kept in scope for as long as you wish to have
1077
1051
  * your event handler be called when there is an update to a document matching
1078
1052
  * the query you provide. When you no longer want to receive updates about
@@ -1085,6 +1059,8 @@ declare class LiveQuery {
1085
1059
  readonly queryArgs: QueryArguments | null;
1086
1060
  /** The name of the collection that the live query is based on. */
1087
1061
  get collectionName(): string;
1062
+ /** Returns true if the receiver has been stopped. */
1063
+ get isStopped(): boolean;
1088
1064
  /**
1089
1065
  * Stop the live query from delivering updates.
1090
1066
  */
@@ -1627,7 +1603,7 @@ declare class PendingIDSpecificOperation implements PromiseLike<DocumentLike | u
1627
1603
  */
1628
1604
  update(closure: (document: MutableDocumentLike) => void): Promise<UpdateResult[]>;
1629
1605
  /** @internal */
1630
- constructor(documentID: DocumentIDValue, collection: Collection);
1606
+ constructor(documentID: DocumentIDValue, collection: Collection, skipIDEncodingAndValidation?: boolean);
1631
1607
  /** @internal */
1632
1608
  then<TResult1 = any, TResult2 = never>(onfulfilled?: ((value: any) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | null | undefined): PromiseLike<TResult1 | TResult2>;
1633
1609
  private documentIDCBOR;
@@ -1640,6 +1616,9 @@ declare type InsertOptions = {
1640
1616
  isDefault?: boolean;
1641
1617
  writeStrategy?: WriteStrategy;
1642
1618
  };
1619
+ declare type UpsertOptions = {
1620
+ writeStrategy?: WriteStrategy;
1621
+ };
1643
1622
  /**
1644
1623
  * Represents a collection of a Ditto store.
1645
1624
  *
@@ -1690,6 +1669,17 @@ declare class Collection {
1690
1669
  * @param id The ID of the document to find.
1691
1670
  */
1692
1671
  findByID(id: DocumentIDValue): PendingIDSpecificOperation;
1672
+ /**
1673
+ * Inserts a new document into the collection and returns its ID. If the
1674
+ * document already exists, the contents of both are merged by default. You
1675
+ * can change this by providing a different `writeStrategy` via `options`.
1676
+ *
1677
+ * @param value The content for the new document to insert or update.
1678
+ *
1679
+ * @param options.writeStrategy Specifies the desired strategy for inserting a
1680
+ * document, defaults to `'merge'`.
1681
+ */
1682
+ upsert(value: DocumentValue, options?: UpsertOptions): Promise<DocumentIDValue>;
1693
1683
  /**
1694
1684
  * Inserts a new document into the collection and returns its ID.
1695
1685
  *
@@ -1708,6 +1698,8 @@ declare class Collection {
1708
1698
  *
1709
1699
  * @param options.writeStrategy Specifies the desired strategy for inserting a
1710
1700
  * document. The default value is `'overwrite'`.
1701
+ *
1702
+ * @deprecated: use `upsert()` instead.
1711
1703
  */
1712
1704
  insert(value: DocumentValue, options?: InsertOptions): Promise<DocumentIDValue>;
1713
1705
  /**
@@ -1762,6 +1754,10 @@ declare class Collection {
1762
1754
  fetchAttachment(token: AttachmentToken, eventHandler?: (AttachmentFetchEvent: any) => void): AttachmentFetcher;
1763
1755
  /** @internal */
1764
1756
  constructor(name: string, store: Store);
1757
+ /** @internal */
1758
+ findByIDCBOR(idCBOR: Uint8Array): PendingIDSpecificOperation;
1759
+ /** @private */
1760
+ private _insert;
1765
1761
  }
1766
1762
 
1767
1763
  /** @internal */
@@ -1980,10 +1976,14 @@ declare class Store {
1980
1976
  interface ObserverRemoving {
1981
1977
  removeObserver(token: any): any;
1982
1978
  }
1979
+ /** @internal */
1980
+ declare type ObserverOptions = {
1981
+ stopsWhenFinalized?: boolean;
1982
+ };
1983
1983
  /**
1984
1984
  * Generic observer handle returned by various observation APIs. The observation
1985
- * remains active until the {@link stop | stop()} method is called explicitly or the
1986
- * observer instance is garbage collected. Therefore, to keep the observation
1985
+ * remains active until the {@link stop | stop()} method is called explicitly or
1986
+ * the observer instance is garbage collected. Therefore, to keep the observation
1987
1987
  * alive, you have to keep a reference to the corresponding observer.
1988
1988
  */
1989
1989
  declare class Observer {
@@ -1992,7 +1992,9 @@ declare class Observer {
1992
1992
  /** @internal */
1993
1993
  readonly token?: any;
1994
1994
  /** @internal */
1995
- constructor(observerManager: ObserverRemoving, token: any);
1995
+ readonly options?: ObserverOptions;
1996
+ /** @internal */
1997
+ constructor(observerManager: ObserverRemoving, token: any, options?: ObserverOptions);
1996
1998
  /**
1997
1999
  * Returns `true` if the observer has been explicitly stopped via the `stop()`
1998
2000
  * method. Otherwise returns `false`.
@@ -2068,12 +2070,18 @@ declare class Ditto {
2068
2070
  * @see {@link setLicenseToken | setLicenseToken()}
2069
2071
  */
2070
2072
  readonly isActivated: boolean;
2073
+ /**
2074
+ * Returns `true` if sync active, otherwise returns `false`. Use
2075
+ * tryStartSync() to active and `stopSync()` to deactivate sync.
2076
+ */
2077
+ readonly isSyncActive: boolean;
2071
2078
  /**
2072
2079
  * Returns `true` if sync has been started, returns `false` if it has
2073
2080
  * been stopped. Returns `false` if sync has never been started for this
2074
2081
  * instance.
2082
+ * @deprecated: use isSyncActive instead.
2075
2083
  */
2076
- readonly isSyncEnabled: boolean;
2084
+ get isSyncEnabled(): boolean;
2077
2085
  /**
2078
2086
  * Initializes a new `Ditto` instance.
2079
2087
  *
@@ -2081,7 +2089,9 @@ declare class Ditto {
2081
2089
  * using this to create a Ditto instance in the web browser will throw an
2082
2090
  * exception.
2083
2091
  *
2084
- * @param identity - Identity for the new Ditto instance.
2092
+ * @param identity - Identity for the new Ditto instance, defaults to
2093
+ * `offlinePlayground` with `appID` being the empty string `''`.
2094
+ *
2085
2095
  * @param path - On Node, `path` corresponds to a real directory
2086
2096
  * on the file system (intermediate directories are created if needed). In the
2087
2097
  * browser, `path` is used as an internal namespace into the backing storage
@@ -2091,7 +2101,7 @@ declare class Ditto {
2091
2101
  * @see {@link identity}
2092
2102
  * @see {@link path}
2093
2103
  */
2094
- constructor(identity: Identity, path?: string);
2104
+ constructor(identity?: Identity, path?: string);
2095
2105
  /**
2096
2106
  * Activate a `Ditto` instance by setting a license token. You cannot sync
2097
2107
  * with `Ditto` before you have activated it.
@@ -2146,7 +2156,10 @@ declare class Ditto {
2146
2156
  * customized with `setTransportConfig()`. On the **Web**, only connecting via
2147
2157
  * Websockets is supported.
2148
2158
  *
2149
- * @see {@link isSyncEnabled}
2159
+ * Ditto will prevent the process from exiting until sync is stopped (not
2160
+ * relevant when running in the browser).
2161
+ *
2162
+ * @see {@link isSyncActive}
2150
2163
  * @see {@link stopSync | stopSync()}
2151
2164
  */
2152
2165
  startSync(): void;
@@ -2156,13 +2169,16 @@ declare class Ditto {
2156
2169
  * You may continue to use the database locally but no data will sync to or
2157
2170
  * from other devices.
2158
2171
  *
2159
- * @see {@link isSyncEnabled}
2172
+ * @see {@link isSyncActive}
2160
2173
  * @see {@link startSync | startSync()}
2161
2174
  */
2162
2175
  stopSync(): void;
2163
2176
  /**
2164
2177
  * Registers an observer for info about Ditto peers in range of this device.
2165
2178
  *
2179
+ * Ditto will prevent the process from exiting as long as there are active
2180
+ * peers observers (not relevant when running in the browser).
2181
+ *
2166
2182
  * @param callback called immediately with the current state of peers
2167
2183
  * in range and whenever that state changes. Then it will be invoked
2168
2184
  * repeatedly when Ditto devices come and go, or the active connections to
@@ -2172,6 +2188,9 @@ declare class Ditto {
2172
2188
  /**
2173
2189
  * Register observer for changes of underlying transport conditions.
2174
2190
  *
2191
+ * Ditto will prevent the process from exiting as long as there are active
2192
+ * transport conditions observers (not relevant when running in the browser).
2193
+ *
2175
2194
  * @param callback called when underlying transport conditions change with
2176
2195
  * the changed `condition` and it's `source`.
2177
2196
  */
@@ -2192,12 +2211,13 @@ declare class Ditto {
2192
2211
  * Only available in Node environments at the moment, no-op in the browser.
2193
2212
  */
2194
2213
  runGarbageCollection(): void;
2214
+ /** @internal */
2215
+ keepAlive: KeepAlive;
2195
2216
  private sync;
2196
2217
  private isWebValid;
2197
2218
  private isX509Valid;
2198
2219
  private presenceManager;
2199
2220
  private transportConditionsManager;
2200
- private authenticationExpiring;
2201
2221
  private authClientValidityChanged;
2202
2222
  private validateIdentity;
2203
2223
  private setSyncEnabled;
@@ -2207,6 +2227,185 @@ declare class Ditto {
2207
2227
  */
2208
2228
  declare const dittoBridge: Bridge<Ditto, "CDitto_t">;
2209
2229
 
2230
+ /** @internal */
2231
+ declare type ObserverToken = string;
2232
+ /** @internal */
2233
+ declare class ObserverManager {
2234
+ /** @internal */
2235
+ readonly id: string;
2236
+ /** @internal */
2237
+ readonly keepAlive: KeepAlive | null;
2238
+ /** @internal */
2239
+ constructor(id: string, keepAlive?: KeepAlive | null);
2240
+ /** @internal */
2241
+ addObserver(callback: any): ObserverToken;
2242
+ /** @internal */
2243
+ removeObserver(token: ObserverToken): void;
2244
+ /** @internal */
2245
+ notify(...args: any[]): void;
2246
+ /** @abstract */
2247
+ protected register(callback: (...args: any[]) => void): void;
2248
+ /** @abstract */
2249
+ protected unregister(): void;
2250
+ /** @abstract */
2251
+ protected processCallback(...args: any[]): any[];
2252
+ private isRegistered;
2253
+ private callbacksByToken;
2254
+ private hasObservers;
2255
+ private registerIfNeeded;
2256
+ private unregisterIfNeeded;
2257
+ private generateToken;
2258
+ private finalize;
2259
+ }
2260
+
2261
+ /**
2262
+ * Provides info about the authentication status.
2263
+ */
2264
+ declare type AuthenticationStatus = {
2265
+ /**
2266
+ * Returns `true` if authenticated, otherwise returns `false`.
2267
+ */
2268
+ isAuthenticated: boolean;
2269
+ /**
2270
+ * If authenticated, returns the `userID` if one was provided by the
2271
+ * authentication service. Otherwise returns `null`.
2272
+ */
2273
+ userID: string | null;
2274
+ };
2275
+ /**
2276
+ * Provides feedback to the developer about Ditto authentication status.
2277
+ */
2278
+ interface AuthenticationHandler {
2279
+ /**
2280
+ * There is no Ditto authentication token or it has expired. Sync will not
2281
+ * work until there is a successful login using one of the login methods on
2282
+ * {@link Authenticator}.
2283
+ */
2284
+ authenticationRequired: (authenticator: Authenticator) => void;
2285
+ /**
2286
+ * Warns that the Ditto authentication token is getting old.
2287
+ *
2288
+ * Ditto will attempt to refresh tokens periodically, starting from halfway
2289
+ * through the token's validity period. This reduces the risk of
2290
+ * authentication expiring while the user is offline.
2291
+ *
2292
+ * The refresh will happen automatically if Ditto has a suitable refresh
2293
+ * token. If new credentials are required, such as a third-party token or a
2294
+ * username/password, then Ditto does not cache that information and you must
2295
+ * submit it again using one of the `login` methods on {@link Authenticator}.
2296
+ */
2297
+ authenticationExpiringSoon: (authenticator: Authenticator, secondsRemaining: number) => void;
2298
+ /**
2299
+ * Notifies the authentication handler that the authentication status did
2300
+ * change. Use the `authenticator`s property `status` to query for the current
2301
+ * authentication status.
2302
+ *
2303
+ * This method is **optional**.
2304
+ */
2305
+ authenticationStatusDidChange?: (authenticator: Authenticator) => void;
2306
+ }
2307
+ /**
2308
+ * Log in to a remote authentication service, using an
2309
+ * `OnlineWithAuthentication` or an `Online` identity.
2310
+ */
2311
+ declare class Authenticator {
2312
+ /**
2313
+ * Returns `true` if authentication is avaiable and the login methods can be
2314
+ * used, otherwise returns `false`. Currently, authentication is only
2315
+ * available if Ditto was initialized with an identity of type
2316
+ * {@link IdentityOnlineWithAuthentication | 'onlineWithAuthentication'}.
2317
+ */
2318
+ readonly loginSupported: boolean;
2319
+ /**
2320
+ Returns the current authentication status.
2321
+ */
2322
+ readonly status: AuthenticationStatus;
2323
+ /**
2324
+ * Query whether Ditto has a valid authentication token.
2325
+ *
2326
+ * This will only be `true` when using an `OnlineWithAuthentication` or an
2327
+ * `Online` identity, after a successful login. If the authentication token is
2328
+ * allowed to expire then it will return `false` instead.
2329
+ *
2330
+ * @deprecated: use `status.isAuthenticated` property instead.
2331
+ */
2332
+ get isAuthenticated(): boolean;
2333
+ /**
2334
+ * Return the currently logged-in user ID.
2335
+ *
2336
+ * This will be `null` if there is no valid authentication or
2337
+ * `OnlineWithAuthentication`/`Online` mode is not being used.
2338
+ *
2339
+ * @deprecated: use `status.userID` property instead.
2340
+ */
2341
+ get userID(): string | null;
2342
+ /**
2343
+ * Log in to Ditto with a third-party token. Throws if authentication is not
2344
+ * available, which can be checked with {@link loginSupported}.
2345
+ *
2346
+ * @param token the authentication token required to log in.
2347
+ * @param provider the name of the authentication provider.
2348
+ */
2349
+ loginWithToken(token: string, provider: string): Promise<void>;
2350
+ /**
2351
+ * Log in to Ditto with a username and password. Throws if authentication is
2352
+ * not available, which can be checked with {@link loginSupported}.
2353
+ *
2354
+ * @param username the username component of the credentials used for log in.
2355
+ * @param password the password component of the credentials used for log in.
2356
+ * @param provider the name of the authentication provider.
2357
+ */
2358
+ loginWithUsernameAndPassword(username: string, password: string, provider: string): Promise<void>;
2359
+ /**
2360
+ * Log out of Ditto.
2361
+ *
2362
+ * This will stop sync, shut down all replication sessions, and remove any
2363
+ * cached authentication credentials. Note that this does not remove any data
2364
+ * from the store. If you wish to delete data from the store then use the
2365
+ * optional `cleanupFn` parameter to perform any required cleanup.
2366
+ *
2367
+ * @param cleanupFn An optional function that will be called with the relevant
2368
+ * [Ditto] instance as the sole argument that allows you to perform any
2369
+ * required cleanup of the store as part of the logout process.
2370
+ */
2371
+ logout(cleanupFn?: (Ditto: any) => void): Promise<void>;
2372
+ observeStatus(callback: (authenticationStatus: AuthenticationStatus) => void): Observer;
2373
+ /** @internal */
2374
+ constructor(keepAlive: KeepAlive);
2375
+ /** @internal */
2376
+ '@ditto.authenticationExpiring': (number: any) => void;
2377
+ /** @internal */
2378
+ '@ditto.authClientValidityChanged': (isWebValid: boolean, isX509Valid: boolean) => void;
2379
+ /** @internal */
2380
+ protected keepAlive: KeepAlive;
2381
+ /** @internal */
2382
+ protected observerManager: ObserverManager;
2383
+ }
2384
+ /** @internal */
2385
+ declare class OnlineAuthenticator extends Authenticator {
2386
+ loginWithToken(token: string, provider: string): Promise<void>;
2387
+ loginWithUsernameAndPassword(username: string, password: string, provider: string): Promise<void>;
2388
+ logout(cleanupFn?: (Ditto: any) => void): Promise<void>;
2389
+ readonly authClientPointer: Pointer<AuthClientType>;
2390
+ readonly authenticationHandler: AuthenticationHandler;
2391
+ private ditto;
2392
+ constructor(keepAlive: KeepAlive, authClientPointer: Pointer<AuthClientType>, ditto: Ditto, authenticationHandler: AuthenticationHandler);
2393
+ '@ditto.authenticationExpiring': (secondsRemaining: number) => void;
2394
+ '@ditto.authClientValidityChanged': (isWebValid: boolean, isX509Valid: boolean) => void;
2395
+ private updateAndNotify;
2396
+ private static finalizationRegistry;
2397
+ private static finalize;
2398
+ }
2399
+ /** @internal */
2400
+ declare class NotAvailableAuthenticator extends Authenticator {
2401
+ loginWithToken(token: string, provider: string): Promise<void>;
2402
+ loginWithUsernameAndPassword(username: string, password: string, provider: string): Promise<void>;
2403
+ logout(cleanupFn?: (Ditto: any) => void): Promise<void>;
2404
+ '@ditto.authenticationExpiring': (secondsRemaining: any) => never;
2405
+ /** @internal */
2406
+ '@ditto.authClientValidityChanged': (isWebValid: boolean, isX509Valid: boolean) => void;
2407
+ }
2408
+
2210
2409
  /** @internal */
2211
2410
  declare class Value {
2212
2411
  readonly value: unknown;
@@ -2407,5 +2606,13 @@ declare class Logger {
2407
2606
  private constructor();
2408
2607
  }
2409
2608
 
2410
- export { Attachment, AttachmentFetchEvent, AttachmentFetchEventCompleted, AttachmentFetchEventDeleted, AttachmentFetchEventProgress, AttachmentFetchEventType, AttachmentFetcher, AttachmentToken, AuthenticationHandler, Authenticator, Collection, CollectionsEvent, CollectionsEventParams, ConditionSource, Counter, CustomLogCallback, Ditto, Document, DocumentIDValue, DocumentLike, DocumentPath, DocumentValue, Identity, IdentityDevelopment, IdentityManual, IdentityOfflinePlayground, IdentityOnline, IdentityOnlinePlayground, IdentityOnlineWithAuthentication, IdentityProduction, IdentitySharedKey, InitOptions, InsertOptions, LiveQuery, LiveQueryEvent, LiveQueryEventInitial, LiveQueryEventUpdate, LiveQueryEventUpdateParams, LiveQueryMove, LogLevel, Logger, MutableDocument, MutableDocumentLike, MutableDocumentPath, NotAvailableAuthenticator, Observer, OnlineWithAuthenticationAuthenticator, PendingCursorOperation, PendingIDSpecificOperation, PresenceConnectionType, QueryArguments, QueryObservationHandler, RemotePeer, SingleDocumentLiveQueryEvent, SingleObservationHandler, SortDirection, Store, Subscription, SubscriptionContextInfo, TransportCondition, TransportConfig, TransportConfigConnect, TransportConfigGlobal, TransportConfigLan, TransportConfigListen, TransportConfigListenHTTP, TransportConfigListenTCP, TransportConfigPeerToPeer, UpdateResult, UpdateResultType, UpdateResultsMap, Value, WebAssemblyModule, WriteStrategy, __log, attachmentBridge, dittoBridge, documentBridge, init, mutableDocumentBridge };
2609
+ /** @internal */
2610
+ declare class CBOR {
2611
+ /** @internal */
2612
+ static encode(data: any): Uint8Array;
2613
+ /** @internal */
2614
+ static decode(data: Uint8Array): any;
2615
+ }
2616
+
2617
+ export { Attachment, AttachmentFetchEvent, AttachmentFetchEventCompleted, AttachmentFetchEventDeleted, AttachmentFetchEventProgress, AttachmentFetchEventType, AttachmentFetcher, AttachmentToken, AuthenticationHandler, AuthenticationStatus, Authenticator, CBOR, Collection, CollectionsEvent, CollectionsEventParams, ConditionSource, Counter, CustomLogCallback, Ditto, Document, DocumentIDValue, DocumentLike, DocumentPath, DocumentValue, Identity, IdentityDevelopment, IdentityManual, IdentityOfflinePlayground, IdentityOnline, IdentityOnlinePlayground, IdentityOnlineWithAuthentication, IdentityProduction, IdentitySharedKey, InitOptions, InsertOptions, KeepAlive, LiveQuery, LiveQueryEvent, LiveQueryEventInitial, LiveQueryEventUpdate, LiveQueryEventUpdateParams, LiveQueryMove, LogLevel, Logger, MutableDocument, MutableDocumentLike, MutableDocumentPath, NotAvailableAuthenticator, Observer, ObserverOptions, OnlineAuthenticator, PendingCursorOperation, PendingIDSpecificOperation, PresenceConnectionType, QueryArguments, QueryObservationHandler, RemotePeer, SingleDocumentLiveQueryEvent, SingleObservationHandler, SortDirection, Store, Subscription, SubscriptionContextInfo, TransportCondition, TransportConfig, TransportConfigConnect, TransportConfigGlobal, TransportConfigLan, TransportConfigListen, TransportConfigListenHTTP, TransportConfigListenTCP, TransportConfigPeerToPeer, UpdateResult, UpdateResultType, UpdateResultsMap, UpsertOptions, Value, WebAssemblyModule, WriteStrategy, __log, attachmentBridge, dittoBridge, documentBridge, init, mutableDocumentBridge, validateDocumentIDCBOR, validateDocumentIDValue };
2411
2618
  //# sourceMappingURL=ditto.d.ts.map