From 3dddbda02d02b54e44716d99230efe8992d28e61 Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Thu, 22 Jun 2023 14:26:34 -0300
Subject: [PATCH 1/9] Remove Platform.Config.Promise
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
I’m not sure what purpose this was serving — Promise can just be
accessed as a global variable.
---
src/common/lib/util/defaults.ts | 2 +-
src/common/lib/util/eventemitter.ts | 8 ++++----
src/common/types/IPlatformConfig.d.ts | 1 -
src/platform/nativescript/config.js | 1 -
src/platform/nodejs/config.ts | 1 -
src/platform/react-native/config.ts | 1 -
src/platform/web/config.ts | 1 -
7 files changed, 5 insertions(+), 10 deletions(-)
diff --git a/src/common/lib/util/defaults.ts b/src/common/lib/util/defaults.ts
index 47803a22e0..57a764bf14 100644
--- a/src/common/lib/util/defaults.ts
+++ b/src/common/lib/util/defaults.ts
@@ -233,7 +233,7 @@ export function normaliseOptions(options: InternalClientOptions): NormalisedClie
options.idempotentRestPublishing = true;
}
- if (options.internal?.promises && !Platform.Config.Promise) {
+ if (options.internal?.promises && typeof Promise === 'undefined') {
Logger.logAction(
Logger.LOG_ERROR,
'Defaults.normaliseOptions',
diff --git a/src/common/lib/util/eventemitter.ts b/src/common/lib/util/eventemitter.ts
index d24e448e8b..25605e77c8 100644
--- a/src/common/lib/util/eventemitter.ts
+++ b/src/common/lib/util/eventemitter.ts
@@ -241,9 +241,9 @@ class EventEmitter {
once(...args: unknown[]): void | Promise {
const argCount = args.length;
- if ((argCount === 0 || (argCount === 1 && typeof args[0] !== 'function')) && Platform.Config.Promise) {
+ if ((argCount === 0 || (argCount === 1 && typeof args[0] !== 'function')) && typeof Promise !== 'undefined') {
const event = args[0];
- return new Platform.Config.Promise((resolve) => {
+ return new Promise((resolve) => {
this.once(event as string | string[] | null, resolve);
});
}
@@ -300,8 +300,8 @@ class EventEmitter {
if (typeof targetState !== 'string' || typeof currentState !== 'string') {
throw 'whenState requires a valid event String argument';
}
- if (typeof listener !== 'function' && Platform.Config.Promise) {
- return new Platform.Config.Promise((resolve) => {
+ if (typeof listener !== 'function' && typeof Promise !== 'undefined') {
+ return new Promise((resolve) => {
EventEmitter.prototype.whenState.apply(
this,
[targetState, currentState, resolve].concat(listenerArgs as any[]) as any
diff --git a/src/common/types/IPlatformConfig.d.ts b/src/common/types/IPlatformConfig.d.ts
index f4766ea2e5..ecb0e4868d 100644
--- a/src/common/types/IPlatformConfig.d.ts
+++ b/src/common/types/IPlatformConfig.d.ts
@@ -16,7 +16,6 @@ export interface IPlatformConfig {
inspect: (value: unknown) => string;
stringByteSize: Buffer.byteLength;
addEventListener?: typeof window.addEventListener | typeof global.addEventListener | null;
- Promise: typeof Promise;
getRandomValues?: (arr: ArrayBufferView, callback?: (error: Error | null) => void) => void;
userAgent?: string | null;
inherits?: typeof import('util').inherits;
diff --git a/src/platform/nativescript/config.js b/src/platform/nativescript/config.js
index a68d0e7468..31090e0240 100644
--- a/src/platform/nativescript/config.js
+++ b/src/platform/nativescript/config.js
@@ -47,7 +47,6 @@ var Config = {
},
TextEncoder: global.TextEncoder,
TextDecoder: global.TextDecoder,
- Promise: global.Promise,
getRandomValues: function (arr, callback) {
var bytes = randomBytes(arr.length);
for (var i = 0; i < arr.length; i++) {
diff --git a/src/platform/nodejs/config.ts b/src/platform/nodejs/config.ts
index 2a99da4ad7..716be3b12a 100644
--- a/src/platform/nodejs/config.ts
+++ b/src/platform/nodejs/config.ts
@@ -30,7 +30,6 @@ const Config: IPlatformConfig = {
callback(null);
}
},
- Promise: global && global.Promise,
};
export default Config;
diff --git a/src/platform/react-native/config.ts b/src/platform/react-native/config.ts
index 81c7cd362c..f6e6f29a2e 100644
--- a/src/platform/react-native/config.ts
+++ b/src/platform/react-native/config.ts
@@ -32,7 +32,6 @@ export default function (bufferUtils: typeof BufferUtils): IPlatformConfig {
},
TextEncoder: global.TextEncoder,
TextDecoder: global.TextDecoder,
- Promise: global.Promise,
getRandomArrayBuffer: (function (RNRandomBytes) {
return function (byteLength: number, callback: (err: Error | null, result: ArrayBuffer | null) => void) {
RNRandomBytes.randomBytes(byteLength, function (err: Error | null, base64String: string | null) {
diff --git a/src/platform/web/config.ts b/src/platform/web/config.ts
index 0877337f3e..87536361ad 100644
--- a/src/platform/web/config.ts
+++ b/src/platform/web/config.ts
@@ -59,7 +59,6 @@ const Config: IPlatformConfig = {
},
TextEncoder: globalObject.TextEncoder,
TextDecoder: globalObject.TextDecoder,
- Promise: globalObject.Promise,
getRandomValues: (function (crypto) {
if (crypto === undefined) {
return undefined;
From 9f1c38bbadfffa4b0918cbfb9ce0c933b4da3934 Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Thu, 22 Jun 2023 14:37:36 -0300
Subject: [PATCH 2/9] Remove all checks for Promise availability
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
In version 2.0 of the library we’re assuming Promise is always
available.
---
src/common/lib/util/defaults.ts | 9 ---
src/common/lib/util/eventemitter.ts | 4 +-
test/realtime/event_emitter.test.js | 92 ++++++++++++++---------------
test/realtime/init.test.js | 36 ++++++-----
4 files changed, 64 insertions(+), 77 deletions(-)
diff --git a/src/common/lib/util/defaults.ts b/src/common/lib/util/defaults.ts
index 57a764bf14..6f8f83123a 100644
--- a/src/common/lib/util/defaults.ts
+++ b/src/common/lib/util/defaults.ts
@@ -233,15 +233,6 @@ export function normaliseOptions(options: InternalClientOptions): NormalisedClie
options.idempotentRestPublishing = true;
}
- if (options.internal?.promises && typeof Promise === 'undefined') {
- Logger.logAction(
- Logger.LOG_ERROR,
- 'Defaults.normaliseOptions',
- '{promises: true} was specified, but no Promise constructor found; disabling promises'
- );
- options.internal.promises = false;
- }
-
let connectivityCheckParams = null;
let connectivityCheckUrl = options.connectivityCheckUrl;
if (options.connectivityCheckUrl) {
diff --git a/src/common/lib/util/eventemitter.ts b/src/common/lib/util/eventemitter.ts
index 25605e77c8..4044343b31 100644
--- a/src/common/lib/util/eventemitter.ts
+++ b/src/common/lib/util/eventemitter.ts
@@ -241,7 +241,7 @@ class EventEmitter {
once(...args: unknown[]): void | Promise {
const argCount = args.length;
- if ((argCount === 0 || (argCount === 1 && typeof args[0] !== 'function')) && typeof Promise !== 'undefined') {
+ if (argCount === 0 || (argCount === 1 && typeof args[0] !== 'function')) {
const event = args[0];
return new Promise((resolve) => {
this.once(event as string | string[] | null, resolve);
@@ -300,7 +300,7 @@ class EventEmitter {
if (typeof targetState !== 'string' || typeof currentState !== 'string') {
throw 'whenState requires a valid event String argument';
}
- if (typeof listener !== 'function' && typeof Promise !== 'undefined') {
+ if (typeof listener !== 'function') {
return new Promise((resolve) => {
EventEmitter.prototype.whenState.apply(
this,
diff --git a/test/realtime/event_emitter.test.js b/test/realtime/event_emitter.test.js
index 4575594f21..c20acbb885 100644
--- a/test/realtime/event_emitter.test.js
+++ b/test/realtime/event_emitter.test.js
@@ -439,62 +439,60 @@ define(['shared_helper', 'chai'], function (helper, chai) {
closeAndFinish(done, realtime);
});
- if (typeof Promise !== 'undefined') {
- describe('event_emitter_promise', function () {
- it('whenState', function (done) {
- var realtime = helper.AblyRealtime({ internal: { promises: true } });
- var eventEmitter = realtime.connection;
-
- eventEmitter
- .whenState('connected')
- .then(function () {
- closeAndFinish(done, realtime);
- })
- ['catch'](function (err) {
- closeAndFinish(done, realtime, err);
- });
- });
-
- it('once', function (done) {
- var realtime = helper.AblyRealtime({ internal: { promises: true } });
- var eventEmitter = realtime.connection;
-
- eventEmitter
- .once('connected')
- .then(function () {
- closeAndFinish(done, realtime);
- })
- ['catch'](function (err) {
- closeAndFinish(done, realtime, err);
- });
- });
-
- it('anyEventsWithOnce', function (done) {
- var realtime = helper.AblyRealtime({ autoConnect: false }),
- eventEmitter = realtime.connection;
-
- const p = eventEmitter.once();
- eventEmitter.emit('b');
- p.then(function () {
+ describe('event_emitter_promise', function () {
+ it('whenState', function (done) {
+ var realtime = helper.AblyRealtime({ internal: { promises: true } });
+ var eventEmitter = realtime.connection;
+
+ eventEmitter
+ .whenState('connected')
+ .then(function () {
closeAndFinish(done, realtime);
- }).catch(function (err) {
+ })
+ ['catch'](function (err) {
closeAndFinish(done, realtime, err);
});
- });
+ });
- it('arrayOfEventsWithOnce', function (done) {
- var realtime = helper.AblyRealtime({ autoConnect: false }),
- eventEmitter = realtime.connection;
+ it('once', function (done) {
+ var realtime = helper.AblyRealtime({ internal: { promises: true } });
+ var eventEmitter = realtime.connection;
- const p = eventEmitter.once(['a', 'b', 'c']);
- eventEmitter.emit('b');
- p.then(function () {
+ eventEmitter
+ .once('connected')
+ .then(function () {
closeAndFinish(done, realtime);
- }).catch(function (err) {
+ })
+ ['catch'](function (err) {
closeAndFinish(done, realtime, err);
});
+ });
+
+ it('anyEventsWithOnce', function (done) {
+ var realtime = helper.AblyRealtime({ autoConnect: false }),
+ eventEmitter = realtime.connection;
+
+ const p = eventEmitter.once();
+ eventEmitter.emit('b');
+ p.then(function () {
+ closeAndFinish(done, realtime);
+ }).catch(function (err) {
+ closeAndFinish(done, realtime, err);
+ });
+ });
+
+ it('arrayOfEventsWithOnce', function (done) {
+ var realtime = helper.AblyRealtime({ autoConnect: false }),
+ eventEmitter = realtime.connection;
+
+ const p = eventEmitter.once(['a', 'b', 'c']);
+ eventEmitter.emit('b');
+ p.then(function () {
+ closeAndFinish(done, realtime);
+ }).catch(function (err) {
+ closeAndFinish(done, realtime, err);
});
});
- }
+ });
});
});
diff --git a/test/realtime/init.test.js b/test/realtime/init.test.js
index 998a1c2623..4b85dd005f 100644
--- a/test/realtime/init.test.js
+++ b/test/realtime/init.test.js
@@ -410,27 +410,25 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
});
});
- if (typeof Promise === 'undefined') {
- it('init_callbacks_promises', function (done) {
- try {
- var realtime,
- keyStr = helper.getTestApp().keys[0].keyStr,
- getOptions = function () {
- return { key: keyStr, autoConnect: false };
- };
+ it('init_callbacks_promises', function (done) {
+ try {
+ var realtime,
+ keyStr = helper.getTestApp().keys[0].keyStr,
+ getOptions = function () {
+ return { key: keyStr, autoConnect: false };
+ };
- realtime = new Ably.Realtime.Promise(getOptions());
- expect(realtime.options.promises, 'Check promises default to true with promise constructor').to.be.ok;
+ realtime = new Ably.Realtime.Promise(getOptions());
+ expect(realtime.options.promises, 'Check promises default to true with promise constructor').to.be.ok;
- if (!isBrowser && typeof require == 'function') {
- realtime = new require('../../promises').Realtime(getOptions());
- expect(realtime.options.promises, 'Check promises default to true with promise require target').to.be.ok;
- }
- done();
- } catch (err) {
- done(err);
+ if (!isBrowser && typeof require == 'function') {
+ realtime = new require('../../promises').Realtime(getOptions());
+ expect(realtime.options.promises, 'Check promises default to true with promise require target').to.be.ok;
}
- });
- }
+ done();
+ } catch (err) {
+ done(err);
+ }
+ });
});
});
From 471f112f4bb5fb03815f45996e7c70fb16c6dfea Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Tue, 27 Jun 2023 11:58:11 -0300
Subject: [PATCH 3/9] Expand documentation for channelEventCallback and
connectionEventCallback
---
ably.d.ts | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/ably.d.ts b/ably.d.ts
index f3f4a028d7..9a7bddca9d 100644
--- a/ably.d.ts
+++ b/ably.d.ts
@@ -1440,13 +1440,13 @@ declare namespace Types {
*/
type errorCallback = (error?: ErrorInfo | null) => void;
/**
- * The callback used by {@link RealtimeChannelCallbacks.whenState}.
+ * The callback used by {@link RealtimeChannelCallbacks.whenState} and for the events emitted by {@link RealtimeChannelBase}.
*
* @param changeStateChange - The state change that occurred.
*/
type channelEventCallback = (changeStateChange: ChannelStateChange) => void;
/**
- * The callback used by {@link ConnectionCallbacks.whenState}.
+ * The callback used by {@link ConnectionCallbacks.whenState} and for the events emitted by {@link ConnectionBase}.
*
* @param connectionStateChange - The state change that occurred.
*/
From 2a2ed49e40e6ce9a8b1a119b66b2f3eeaf235054 Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Thu, 22 Jun 2023 14:56:55 -0300
Subject: [PATCH 4/9] Remove the callbacks public API
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
We’ve decided that in version 2 of the SDK, we’ll only offer a
promise-based API.
Note that this doesn’t change the use of callbacks internally in the
SDK; that’s a separate thing we might wish to do in the future.
Resolves #1199.
---
README.md | 320 +++------
ably.d.ts | 790 +--------------------
callbacks.d.ts | 2 -
callbacks.js | 6 -
docs/landing-page.md | 7 +
docs/landing-pages/choose-library.html | 31 -
docs/landing-pages/default.md | 7 -
docs/landing-pages/promises.md | 7 -
package.json | 4 +-
src/common/lib/client/auth.ts | 8 +-
src/common/lib/client/channel.ts | 12 +-
src/common/lib/client/connection.ts | 7 +-
src/common/lib/client/paginatedresource.ts | 6 +-
src/common/lib/client/presence.ts | 12 +-
src/common/lib/client/push.ts | 52 +-
src/common/lib/client/realtime.ts | 10 +-
src/common/lib/client/realtimechannel.ts | 31 +-
src/common/lib/client/realtimepresence.ts | 27 +-
src/common/lib/client/rest.ts | 27 +-
src/common/lib/util/defaults.ts | 1 -
src/common/types/ClientOptions.ts | 2 -
test/realtime/event_emitter.test.js | 4 +-
test/realtime/init.test.js | 21 -
test/rest/init.test.js | 14 -
24 files changed, 159 insertions(+), 1249 deletions(-)
delete mode 100644 callbacks.d.ts
delete mode 100644 callbacks.js
create mode 100644 docs/landing-page.md
delete mode 100644 docs/landing-pages/choose-library.html
delete mode 100644 docs/landing-pages/default.md
delete mode 100644 docs/landing-pages/promises.md
diff --git a/README.md b/README.md
index 03c9c1e3bc..a120817518 100644
--- a/README.md
+++ b/README.md
@@ -52,8 +52,6 @@ and require as:
var Ably = require('ably');
```
-For the version of the library where async methods return promises, use `var Ably = require('ably/promises');` instead. For the explicitly-callback-based variant use `require('ably/callbacks')`– see [Async API style](#async-api-style).
-
For usage, jump to [Using the Realtime API](#using-the-realtime-api) or [Using the REST API](#using-the-rest-api).
#### Serverside usage with webpack
@@ -92,21 +90,11 @@ let client = new Ably.Realtime(options); /* inferred type Ably.Realtime */
let channel = client.channels.get('feed'); /* inferred type Ably.Types.RealtimeChannel */
```
-For the version of the library where async methods return promises, use `import * as Ably from 'ably/promises';` instead. For the explicitly-callback-based variant use `import * as Ably from 'ably/callbacks'` – see [Async API style](#async-api-style).
-
Intellisense in IDEs with TypeScript support is supported:
![TypeScript suggestions](./resources/typescript-demo.gif)
-If you need to explicitly import the type definitions, see [ably.d.ts](./ably.d.ts) (or `promises.d.ts` if you're requiring the library as `ably/promises`).
-
-## Async API style
-
-This library exposes two API variants. Firstly, the original (and presently the default) callback-based API, which follows the usual Node.js error-first callback style. Second, a promises-based API. With the promises variant, you can still pass a callback to methods and the callback will work as expected, but if you do not pass a callback, the method will return a promise. The API in use can be selected explicitly by requiring that specific variant when requiring/importing the library (or in the case of the browser version, when instantiating it). The usage instructions below make reference to both variants.
-
-For this library version, and for all future 1.x versions, the callback-based API will be the default. This means that the promises-based variant will need to be explicitly selected, to avoid breaking backwards compatibility. A move to the promises-based variant as the default is likely at the next major release (i.e. 2.x onwards).
-
-For usage, jump to [Using the async API style](#using-the-async-api-style).
+If you need to explicitly import the type definitions, see [ably.d.ts](./ably.d.ts).
## NativeScript
@@ -128,13 +116,6 @@ var client = new Ably.Realtime(key: string);
// which must contain at least one auth option, i.e. at least
// one of: key, token, tokenDetails, authUrl, or authCallback
var client = new Ably.Realtime(options: ClientOptions);
-
-// For a version of the library where async methods return promises if
-// you don't pass a callback:
-var client = new Ably.Realtime.Promise(options: string | ClientOptions);
-
-// For the explicitly-callback-based variant (see 'Async API style' below):
-var client = new Ably.Rest.Callbacks(options: string | ClientOptions);
```
### Connection
@@ -195,36 +176,26 @@ If you would like to inspect the `Message` instances in order to identify whethe
```javascript
// Publish a single message with name and data
-channel.publish('greeting', 'Hello World!');
-
-// Optionally, you can use a callback to be notified of success or failure
-channel.publish('greeting', 'Hello World!', function(err) {
- if(err) {
- console.log('publish failed with error ' + err);
- } else {
- console.log('publish succeeded');
- }
-})
+await channel.publish('greeting', 'Hello World!');
// Publish several messages at once
-channel.publish([{name: 'greeting', data: 'Hello World!'}, ...], callback);
+await channel.publish([{name: 'greeting', data: 'Hello World!'}, ...]);
```
### Querying the History
```javascript
-channel.history(function(err, messagesPage) {
- messagesPage // PaginatedResult
- messagesPage.items // array of Message
- messagesPage.items[0].data // payload for first message
- messagesPage.items.length // number of messages in the current page of history
- messagesPage.hasNext() // true if there are further pages
- messagesPage.isLast() // true if this page is the last page
- messagesPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const messagesPage = channel.history()
+messagesPage // PaginatedResult
+messagesPage.items // array of Message
+messagesPage.items[0].data // payload for first message
+messagesPage.items.length // number of messages in the current page of history
+messagesPage.hasNext() // true if there are further pages
+messagesPage.isLast() // true if this page is the last page
+const nextPage = await messagesPage.next(); // retrieves the next page as PaginatedResult
// Can optionally take an options param, see https://www.ably.com/docs/rest-api/#message-history
-channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
+const messagesPage = await channel.history({start: ..., end: ..., limit: ..., direction: ...});
```
### Presence on a channel
@@ -232,9 +203,8 @@ channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err
Getting presence:
```javascript
-channel.presence.get(function (err, presenceSet) {
- presenceSet; // array of PresenceMessages
-});
+const presenceSet = channel.presence.get();
+presenceSet; // array of PresenceMessages
```
Note that presence#get on a realtime channel does not return a
@@ -243,17 +213,14 @@ PaginatedResult, as the library maintains a local copy of the presence set.
Entering (and leaving) the presence set:
```javascript
-channel.presence.enter('my status', function (err) {
- // now I am entered
-});
+await channel.presence.enter('my status');
+// now I am entered
-channel.presence.update('new status', function (err) {
- // my presence data is updated
-});
+await channel.presence.update('new status');
+// my presence data is updated
-channel.presence.leave(function (err) {
- // I've left the presence set
-});
+await channel.presence.leave()
+// I've left the presence set
```
If you are using a client which is allowed to use any clientId --
@@ -263,24 +230,23 @@ https://www.ably.com/docs/general/authentication for more information), you
can use
```javascript
-channel.presence.enterClient('myClientId', 'status', function(err) { ... });
+await channel.presence.enterClient('myClientId', 'status');
// and similiarly, updateClient and leaveClient
```
### Querying the Presence History
```javascript
-channel.presence.history(function(err, messagesPage) { // PaginatedResult
- messagesPage.items // array of PresenceMessage
- messagesPage.items[0].data // payload for first message
- messagesPage.items.length // number of messages in the current page of history
- messagesPage.hasNext() // true if there are further pages
- messagesPage.isLast() // true if this page is the last page
- messagesPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const messagesPage = channel.presence.history(); // PaginatedResult
+messagesPage.items // array of PresenceMessage
+messagesPage.items[0].data // payload for first message
+messagesPage.items.length // number of messages in the current page of history
+messagesPage.hasNext() // true if there are further pages
+messagesPage.isLast() // true if this page is the last page
+const nextPage = await messagesPage.next(); // retrieves the next page as PaginatedResult
// Can optionally take an options param, see https://www.ably.com/docs/rest-api/#message-history
-channel.presence.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
+const messagesPage = await channel.presence.history({start: ..., end: ..., limit: ..., direction: ...);
```
### Symmetrical end-to-end encrypted payloads on a channel
@@ -290,24 +256,22 @@ When a 128 bit or 256 bit key is provided to the library, the `data` attributes
```javascript
// Generate a random 256-bit key for demonstration purposes (in
// practice you need to create one and distribute it to clients yourselves)
-Ably.Realtime.Crypto.generateRandomKey(function (err, key) {
- var channel = client.channels.get('channelName', { cipher: { key: key } });
+const key = await Ably.Realtime.Crypto.generateRandomKey();
+var channel = client.channels.get('channelName', { cipher: { key: key } });
- channel.subscribe(function (message) {
- message.name; // 'name is not encrypted'
- message.data; // 'sensitive data is encrypted'
- });
-
- channel.publish('name is not encrypted', 'sensitive data is encrypted');
+channel.subscribe(function (message) {
+ message.name; // 'name is not encrypted'
+ message.data; // 'sensitive data is encrypted'
});
+
+channel.publish('name is not encrypted', 'sensitive data is encrypted');
```
-You can also change the key on an existing channel using setOptions (which takes a callback which is called after the new encryption settings have taken effect):
+You can also change the key on an existing channel using setOptions (which completes after the new encryption settings have taken effect):
```javascript
-channel.setOptions({cipher: {key: }}, function() {
- // New encryption settings are in effect
-})
+await channel.setOptions({cipher: {key: }});
+// New encryption settings are in effect
```
### Message interactions
@@ -340,13 +304,6 @@ var client = new Ably.Rest(key: string);
// which must contain at least one auth option, i.e. at least
// one of: key, token, tokenDetails, authUrl, or authCallback
var client = new Ably.Rest(options: ClientOptions);
-
-// For a version of the library where async methods return promises if
-// you don't pass a callback:
-var client = new Ably.Rest.Promise(options: string | ClientOptions);
-
-// For the explicitly-callback-based variant (see 'Async API style' above):
-var client = new Ably.Rest.Callbacks(options: string | ClientOptions);
```
Given:
@@ -359,75 +316,67 @@ var channel = client.channels.get('test');
```javascript
// Publish a single message with name and data
-channel.publish('greeting', 'Hello World!');
-
-// Optionally, you can use a callback to be notified of success or failure
-channel.publish('greeting', 'Hello World!', function(err) {
- if(err) {
- console.log('publish failed with error ' + err);
- } else {
- console.log('publish succeeded');
- }
-})
+try {
+ channel.publish('greeting', 'Hello World!');
+ console.log('publish succeeded');
+} catch (err) {
+ console.log('publish failed with error ' + err);
+}
// Publish several messages at once
-channel.publish([{name: 'greeting', data: 'Hello World!'}, ...], callback);
+await channel.publish([{name: 'greeting', data: 'Hello World!'}, ...]);
```
### Querying the History
```javascript
-channel.history(function(err, messagesPage) {
- messagesPage // PaginatedResult
- messagesPage.items // array of Message
- messagesPage.items[0].data // payload for first message
- messagesPage.items.length // number of messages in the current page of history
- messagesPage.hasNext() // true if there are further pages
- messagesPage.isLast() // true if this page is the last page
- messagesPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const messagesPage = await channel.history();
+messagesPage // PaginatedResult
+messagesPage.items // array of Message
+messagesPage.items[0].data // payload for first message
+messagesPage.items.length // number of messages in the current page of history
+messagesPage.hasNext() // true if there are further pages
+messagesPage.isLast() // true if this page is the last page
+const nextPage = await messagesPage.next(); // retrieves the next page as PaginatedResult
// Can optionally take an options param, see https://www.ably.com/docs/rest-api/#message-history
-channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
+await channel.history({start: ..., end: ..., limit: ..., direction: ...});
```
### Presence on a channel
```javascript
-channel.presence.get(function(err, presencePage) { // PaginatedResult
- presencePage.items // array of PresenceMessage
- presencePage.items[0].data // payload for first message
- presencePage.items.length // number of messages in the current page of members
- presencePage.hasNext() // true if there are further pages
- presencePage.isLast() // true if this page is the last page
- presencePage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const presencePage = await channel.presence.get() // PaginatedResult
+presencePage.items // array of PresenceMessage
+presencePage.items[0].data // payload for first message
+presencePage.items.length // number of messages in the current page of members
+presencePage.hasNext() // true if there are further pages
+presencePage.isLast() // true if this page is the last page
+const nextPage = await presencePage.next(); // retrieves the next page as PaginatedResult
```
### Querying the Presence History
```javascript
-channel.presence.history(function(err, messagesPage) { // PaginatedResult
- messagesPage.items // array of PresenceMessage
- messagesPage.items[0].data // payload for first message
- messagesPage.items.length // number of messages in the current page of history
- messagesPage.hasNext() // true if there are further pages
- messagesPage.isLast() // true if this page is the last page
- messagesPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const messagesPage = channel.presence.history(); // PaginatedResult
+messagesPage.items // array of PresenceMessage
+messagesPage.items[0].data // payload for first message
+messagesPage.items.length // number of messages in the current page of history
+messagesPage.hasNext() // true if there are further pages
+messagesPage.isLast() // true if this page is the last page
+const nextPage = await messagesPage.next(); // retrieves the next page as PaginatedResult
// Can optionally take an options param, see https://www.ably.com/docs/rest-api/#message-history
-channel.history({start: ..., end: ..., limit: ..., direction: ...}, function(err, messagesPage) { ...});
+const messagesPage = channel.history({start: ..., end: ..., limit: ..., direction: ...});
```
### Getting the status of a channel
```javascript
-channel.status(function(err, channelDetails) {
- channelDetails.channelId // The name of the channel
- channelDetails.status.isActive // A boolean indicating whether the channel is active
- channelDetails.status.occupancy // Contains metadata relating to the occupants of the channel
-});
+const channelDetails = await channel.status();
+channelDetails.channelId // The name of the channel
+channelDetails.status.isActive // A boolean indicating whether the channel is active
+channelDetails.status.occupancy // Contains metadata relating to the occupants of the channel
```
### Generate Token and Token Request
@@ -438,134 +387,49 @@ explanation of Ably's authentication mechanism.
Requesting a token:
```javascript
-client.auth.requestToken(function(err, tokenDetails) {
- // tokenDetails is instance of TokenDetails
- // see https://www.ably.com/docs/rest/authentication/#token-details for its properties
+const tokenDetails = await client.auth.requestToken();
+// tokenDetails is instance of TokenDetails
+// see https://www.ably.com/docs/rest/authentication/#token-details for its properties
- // Now we have the token, we can send it to someone who can instantiate a client with it:
- var clientUsingToken = new Ably.Realtime(tokenDetails.token);
-});
+// Now we have the token, we can send it to someone who can instantiate a client with it:
+var clientUsingToken = new Ably.Realtime(tokenDetails.token);
// requestToken can take two optional params
// tokenParams: https://www.ably.com/docs/rest/authentication/#token-params
// authOptions: https://www.ably.com/docs/rest/authentication/#auth-options
-client.auth.requestToken(tokenParams, authOptions, function(err, tokenDetails) { ... });
+const tokenDetails = await client.auth.requestToken(tokenParams, authOptions);
```
Creating a token request (for example, on a server in response to a
request by a client using the `authCallback` or `authUrl` mechanisms):
```javascript
-client.auth.createTokenRequest(function(err, tokenRequest) {
- // now send the tokenRequest back to the client, which will
- // use it to request a token and connect to Ably
-});
+const tokenRequest = await client.auth.createTokenRequest();
+// now send the tokenRequest back to the client, which will
+// use it to request a token and connect to Ably
// createTokenRequest can take two optional params
// tokenParams: https://www.ably.com/docs/rest/authentication/#token-params
// authOptions: https://www.ably.com/docs/rest/authentication/#auth-options
-client.auth.createTokenRequest(tokenParams, authOptions, function(err, tokenRequest) { ... });
+const tokenRequest = await client.auth.createTokenRequest(tokenParams, authOptions);
```
### Fetching your application's stats
```javascript
-client.stats(function(err, statsPage) { // statsPage as PaginatedResult
- statsPage.items // array of Stats
- statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
- statsPage.items.length; // number of stats in the current page of history
- statsPage.hasNext() // true if there are further pages
- statsPage.isLast() // true if this page is the last page
- statsPage.next(function(nextPage) { ... }); // retrieves the next page as PaginatedResult
-});
+const statsPage = await client.stats() // statsPage as PaginatedResult
+statsPage.items // array of Stats
+statsPage.items[0].inbound.rest.messages.count; // total messages published over REST
+statsPage.items.length; // number of stats in the current page of history
+statsPage.hasNext() // true if there are further pages
+statsPage.isLast() // true if this page is the last page
+const nextPage = await statsPage.next(); // retrieves the next page as PaginatedResult
```
### Fetching the Ably service time
```javascript
-client.time(function(err, time) { ... }); // time is in ms since epoch
-```
-
-## Using the async API style
-
-### Realtime Example
-
-```ts
-import * as Ably from 'ably/promises';
-
-const client = new Ably.Realtime.Promise(options);
-
-const ablyRealtimePromiseExample = async () => {
- const channel = client.channels.get('myChannel');
-
- // Attaching to a channel
- await channel.attach();
-
- // Getting presence on a channel
- const presenceMessage = await channel.presence.get();
- console.log(presenceMessage);
-
- // Updating presence on a client
- await channel.presence.enter();
- await channel.presence.update('new status');
- await channel.presence.leave();
-
- // Publishing a message
- await channel.publish('greeting', 'Hello, World!');
-
- // Querying history
- const history = await channel.history({ limit: 25 });
- console.log(history);
-
- client.close();
-};
-
-ablyRealtimePromiseExample();
-```
-
-### REST Example
-
-```ts
-import * as Ably from 'ably/promises';
-
-const client = new Ably.Rest.Promise(options);
-
-const ablyRestPromiseExample = async () => {
- const channel = client.channels.get('myChannel');
-
- // Publishing a message
- await channel.publish('greeting', 'Hello, World!');
-
- // Getting presence on a channel
- const presenceMessage = await channel.presence.get();
- console.log(presenceMessage);
-
- // Querying history
- const history = await channel.history({ limit: 25 });
- console.log(await history.current());
-
- // Getting the status of a channel
- const channelDetails = await channel.status();
- console.log(channelDetails);
-
- // Requesting a token
- const token = await client.auth.requestToken(tokenParams);
-
- // Creating a token request
- const tokenRequest = await client.auth.createTokenRequest();
-
- // Fetching your application's stats
- const stats = await client.stats();
- console.log(stats);
-
- // Fetching the Ably service time
- const time = await client.time();
- console.log(`Ably service time: ${time}`);
-
- client.close();
-};
-
-ablyRestPromiseExample();
+const time = await client.time(); // time is in ms since epoch
```
## Delta Plugin
diff --git a/ably.d.ts b/ably.d.ts
index 9a7bddca9d..852b7ad5ab 100644
--- a/ably.d.ts
+++ b/ably.d.ts
@@ -890,7 +890,7 @@ declare namespace Types {
}
/**
- * Contains the properties of a request for a token to Ably. Tokens are generated using {@link AuthCallbacks.requestToken} or {@link AuthPromise.requestToken}.
+ * Contains the properties of a request for a token to Ably. Tokens are generated using {@link AuthPromise.requestToken}.
*/
interface TokenRequest {
/**
@@ -1001,9 +1001,7 @@ declare namespace Types {
/**
* The `RestHistoryParams` interface describes the parameters accepted by the following methods:
*
- * - {@link PresenceCallbacks.history}
* - {@link PresencePromise.history}
- * - {@link ChannelCallbacks.history}
* - {@link ChannelPromise.history}
*/
interface RestHistoryParams {
@@ -1032,10 +1030,7 @@ declare namespace Types {
}
/**
- * The `RestPresenceParams` interface describes the parameters accepted by the following methods:
- *
- * - {@link PresenceCallbacks.get}
- * - {@link PresencePromise.get}
+ * The `RestPresenceParams` interface describes the parameters accepted by {@link PresencePromise.get}.
*/
interface RestPresenceParams {
/**
@@ -1055,10 +1050,7 @@ declare namespace Types {
}
/**
- * The `RealtimePresenceParams` interface describes the parameters accepted by the following methods:
- *
- * - {@link RealtimePresenceCallbacks.get}
- * - {@link RealtimePresencePromise.get}
+ * The `RealtimePresenceParams` interface describes the parameters accepted by {@link RealtimePresencePromise.get}.
*/
interface RealtimePresenceParams {
/**
@@ -1080,9 +1072,7 @@ declare namespace Types {
/**
* The `RealtimeHistoryParams` interface describes the parameters accepted by the following methods:
*
- * - {@link RealtimePresenceCallbacks.history}
* - {@link RealtimePresencePromise.history}
- * - {@link RealtimeChannelCallbacks.history}
* - {@link RealtimeChannelPromise.history}
*/
interface RealtimeHistoryParams {
@@ -1310,8 +1300,6 @@ declare namespace Types {
/**
* The `DeviceRegistrationParams` interface describes the parameters accepted by the following methods:
*
- * - {@link PushDeviceRegistrationsCallbacks.list}
- * - {@link PushDeviceRegistrationsCallbacks.removeWhere}
* - {@link PushDeviceRegistrationsPromise.list}
* - {@link PushDeviceRegistrationsPromise.removeWhere}
*/
@@ -1337,8 +1325,6 @@ declare namespace Types {
/**
* The `PushChannelSubscriptionParams` interface describes the parameters accepted by the following methods:
*
- * - {@link PushChannelSubscriptionsCallbacks.list}
- * - {@link PushChannelSubscriptionsCallbacks.removeWhere}
* - {@link PushChannelSubscriptionsPromise.list}
* - {@link PushChannelSubscriptionsPromise.removeWhere}
*/
@@ -1362,10 +1348,7 @@ declare namespace Types {
}
/**
- * The `PushChannelsParams` interface describes the parameters accepted by the following methods:
- *
- * - {@link PushChannelSubscriptionsCallbacks.listChannels}
- * - {@link PushChannelSubscriptionsPromise.listChannels}
+ * The `PushChannelsParams` interface describes the parameters accepted by {@link PushChannelSubscriptionsPromise.listChannels}.
*/
interface PushChannelsParams {
/**
@@ -1377,9 +1360,7 @@ declare namespace Types {
/**
* The `StatsParams` interface describes the parameters accepted by the following methods:
*
- * - {@link RestCallbacks.stats}
* - {@link RestPromise.stats}
- * - {@link RealtimeCallbacks.stats}
* - {@link RealtimePromise.stats}
*/
interface StatsParams {
@@ -1416,17 +1397,6 @@ declare namespace Types {
}
// Common Listeners
- /**
- * A standard callback format used in most areas of the callback API.
- *
- * @param err - An error object if the request failed.
- * @param result - The result of the request, if any.
- */
- type StandardCallback = (err: ErrorInfo | null, result?: T) => void;
- /**
- * A {@link StandardCallback} which returns a {@link PaginatedResult}.
- */
- type paginatedResultCallback = StandardCallback>;
/**
* A callback which returns only a single argument, used for {@link RealtimeChannelBase} subscriptions.
*
@@ -1434,47 +1404,17 @@ declare namespace Types {
*/
type messageCallback = (message: T) => void;
/**
- * A callback which returns only an error, or null, when complete.
- *
- * @param error - The error if the request failed, or null not.
- */
- type errorCallback = (error?: ErrorInfo | null) => void;
- /**
- * The callback used by {@link RealtimeChannelCallbacks.whenState} and for the events emitted by {@link RealtimeChannelBase}.
+ * The callback used for the events emitted by {@link RealtimeChannelBase}.
*
* @param changeStateChange - The state change that occurred.
*/
type channelEventCallback = (changeStateChange: ChannelStateChange) => void;
/**
- * The callback used by {@link ConnectionCallbacks.whenState} and for the events emitted by {@link ConnectionBase}.
+ * The callback used for the events emitted by {@link ConnectionBase}.
*
* @param connectionStateChange - The state change that occurred.
*/
type connectionEventCallback = (connectionStateChange: ConnectionStateChange) => void;
- /**
- * The callback used by {@link RestCallbacks.time} and {@link RealtimeCallbacks.time}.
- *
- * @param timeCallback - The time in milliseconds since the Unix epoch.
- */
- type timeCallback = StandardCallback;
- /**
- * The callback used by {@link RealtimePresenceCallbacks.get}.
- *
- * @param realtimePresenceGetCallback - An array of {@link PresenceMessage} objects.
- */
- type realtimePresenceGetCallback = StandardCallback;
- /**
- * The callback used by {@link AuthCallbacks.authorize}.
- *
- * @param tokenDetailsCallback - A {@link TokenDetails} object.
- */
- type tokenDetailsCallback = StandardCallback;
- /**
- * The callback used by {@link AuthCallbacks.createTokenRequest}.
- *
- * @param tokenRequestCallback - A {@link TokenRequest} object
- */
- type tokenRequestCallback = StandardCallback;
/**
* The callback used by {@link recoverConnectionCallback}.
*
@@ -1592,7 +1532,7 @@ declare namespace Types {
// Classes
/**
- * The `RestBase` class acts as a base class for the {@link RestCallbacks} and {@link RestPromise} classes.
+ * The `RestBase` class acts as a base class for the {@link RestPromise} class.
*/
class RestBase {
/**
@@ -1621,71 +1561,6 @@ declare namespace Types {
static PresenceMessage: Types.PresenceMessageStatic;
}
- /**
- * A client that offers a simple stateless API to interact directly with Ably's REST API.
- */
- class RestCallbacks extends RestBase {
- /**
- * A promisified version of the library (use this if you prefer to use Promises or async/await instead of callbacks)
- */
- static Promise: typeof Types.RestPromise;
- /**
- * A callback based version of the library
- */
- static Callbacks: typeof Types.RestCallbacks;
- /**
- * An {@link Types.AuthCallbacks} object.
- */
- auth: Types.AuthCallbacks;
- /**
- * A {@link Types.Channels} object.
- */
- channels: Types.Channels;
- /**
- * Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
- *
- * @param method - The request method to use, such as `GET`, `POST`.
- * @param path - The request path.
- * @param version - The major version of the Ably REST API to use. See the [REST API reference](https://ably.com/docs/api/rest-api#versioning) for information on versioning.
- * @param params - The parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the [REST API reference](https://ably.com/docs/api/rest-api) for the available parameters of each endpoint.
- * @param body - The JSON body of the request.
- * @param headers - Additional HTTP headers to include in the request.
- * @param callback - A function which, upon success, will be called with an {@link Types.HttpPaginatedResponse} response object returned by the HTTP request. This response object will contain an empty or JSON-encodable object. Upon failure, the function will be called with information about the error.
- */
- request(
- method: string,
- path: string,
- version: number,
- params?: any,
- body?: any[] | any,
- headers?: any,
- callback?: Types.StandardCallback>
- ): void;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param params - A set of parameters which are used to specify which statistics should be retrieved. This parameter should be a {@link Types.StatsParams} object. For reasons of backwards compatibility this parameter will also accept `any`; this ability will be removed in the next major release of this SDK. If you do not provide this argument, then this method will use the default parameters described in the {@link Types.StatsParams} interface.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the function will be called with information about the error.
- */
- stats(params?: StatsParams | any, callback?: Types.paginatedResultCallback): void;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics, using the default parameters described in the {@link Types.StatsParams} interface. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the function will be called with information about the error.
- */
- stats(callback?: Types.paginatedResultCallback): void;
- /**
- * Retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably {@link Types.TokenRequest | `TokenRequest`s} with a more accurate timestamp should use the {@link Types.ClientOptions.queryTime} property instead of this method.
- *
- * @param callback - A function which, upon success, will be called with the time as milliseconds since the Unix epoch. Upon failure, the function will be called with information about the error.
- */
- time(callback?: Types.timeCallback): void;
- /**
- * A {@link Types.PushCallbacks} object.
- */
- push: Types.PushCallbacks;
- }
-
/**
* A client that offers a simple stateless API to interact directly with Ably's REST API.
*/
@@ -1694,10 +1569,6 @@ declare namespace Types {
* A promisified version of the library (use this if you prefer to use Promises or async/await instead of callbacks)
*/
static Promise: typeof Types.RestPromise;
- /**
- * A callback based version of the library
- */
- static Callbacks: typeof Types.RestCallbacks;
/**
* An {@link Types.AuthPromise} object.
*/
@@ -1752,10 +1623,6 @@ declare namespace Types {
* A promisified version of the library (use this if you prefer to use Promises or async/await instead of callbacks)
*/
static Promise: typeof Types.RealtimePromise;
- /**
- * A callback based version of the library
- */
- static Callbacks: typeof Types.RealtimeCallbacks;
/**
* 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. 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.
*/
@@ -1770,67 +1637,6 @@ declare namespace Types {
connect(): void;
}
- /**
- * A client that extends the functionality of {@link RestCallbacks} and provides additional realtime-specific features.
- */
- class RealtimeCallbacks extends RealtimeBase {
- /**
- * An {@link Types.AuthCallbacks} object.
- */
- auth: Types.AuthCallbacks;
- /**
- * A {@link Types.Channels} object.
- */
- channels: Types.Channels;
- /**
- * A {@link Types.ConnectionCallbacks} object.
- */
- connection: Types.ConnectionCallbacks;
- /**
- * Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
- *
- * @param method - The request method to use, such as `GET`, `POST`.
- * @param path - The request path.
- * @param version - The major version of the Ably REST API to use. See the [REST API reference](https://ably.com/docs/api/rest-api#versioning) for information on versioning.
- * @param params - The parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the [REST API reference](https://ably.com/docs/api/rest-api) for the available parameters of each endpoint.
- * @param body - The JSON body of the request.
- * @param headers - Additional HTTP headers to include in the request.
- * @param callback - A function which, upon success, will be called with the {@link Types.HttpPaginatedResponse} response object returned by the HTTP request. This response object will contain an empty or JSON-encodable object. Upon failure, the function will be called with information about the error.
- */
- request(
- method: string,
- path: string,
- version: number,
- params?: any,
- body?: any[] | any,
- headers?: any,
- callback?: Types.StandardCallback>
- ): void;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param params - A set of parameters which are used to specify which statistics should be retrieved. This parameter should be a {@link Types.StatsParams} object. For reasons of backwards compatibility this parameter will also accept `any`; this ability will be removed in the next major release of this SDK.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the function will be called with information about the error.
- */
- stats(params: StatsParams | any, callback: Types.paginatedResultCallback): void;
- /**
- * Queries the REST `/stats` API and retrieves your application's usage statistics, using the default parameters described in the {@link Types.StatsParams} interface. Returns a {@link Types.PaginatedResult} object, containing an array of {@link Types.Stats} objects. See the [Stats docs](https://ably.com/docs/general/statistics).
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Types.Stats} objects. Upon failure, the function will be called with information about the error.
- */
- stats(callback: Types.paginatedResultCallback): void;
- /**
- * Retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably {@link Types.TokenRequest | `TokenRequest`s} with a more accurate timestamp should use the {@link Types.ClientOptions.queryTime} property instead of this method.
- *
- * @param callback - A function which, upon success, will be called with the time as milliseconds since the Unix epoch. Upon failure, the function will be called with information about the error.
- */
- time(callback?: Types.timeCallback): void;
- /**
- * A {@link Types.PushCallbacks} object.
- */
- push: Types.PushCallbacks;
- }
-
/**
* A client that extends the functionality of {@link RestPromise} and provides additional realtime-specific features.
*/
@@ -1886,7 +1692,7 @@ declare namespace Types {
}
/**
- * The `AuthBase` class acts as a base class for the {@link AuthCallbacks} and {@link AuthPromise} classes.
+ * The `AuthBase` class acts as a base class for the {@link AuthPromise} class.
*/
class AuthBase {
/**
@@ -1895,83 +1701,6 @@ declare namespace Types {
clientId: string;
}
- /**
- * Creates Ably {@link TokenRequest} objects and obtains Ably Tokens from Ably to subsequently issue to less trusted clients.
- */
- class AuthCallbacks extends AuthBase {
- /**
- * Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained. Also stores any {@link TokenParams} and {@link AuthOptions} passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. Any {@link TokenParams} and {@link AuthOptions} objects passed in entirely replace, as opposed to being merged with, the current client library saved values.
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- authorize(tokenParams?: TokenParams, authOptions?: AuthOptions, callback?: tokenDetailsCallback): void;
- /**
- * Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained. Also stores any {@link TokenParams} passed in as the new default, to be used for all subsequent implicit or explicit token requests. Any {@link TokenParams} object passed in entirely replaces, as opposed to being merged with, the current client library saved value.
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- authorize(tokenParams?: TokenParams, callback?: tokenDetailsCallback): void;
- /**
- * Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained.
- *
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- authorize(callback?: tokenDetailsCallback): void;
- /**
- * Creates and signs an Ably {@link TokenRequest} based on the specified (or if none specified, the client library stored) {@link TokenParams} and {@link AuthOptions}. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably {@link TokenRequest} must be obtained from the key owner. Use this to generate an Ably {@link TokenRequest} in order to implement an Ably Token request callback for use by other clients. Both {@link TokenParams} and {@link AuthOptions} are optional. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenRequest} object. Upon failure, the function will be called with information about the error.
- */
- createTokenRequest(
- tokenParams?: TokenParams | null,
- authOptions?: AuthOptions | null,
- callback?: tokenRequestCallback
- ): void;
- /**
- * Creates and signs an Ably {@link TokenRequest} based on the specified (or if none specified, the client library stored) {@link TokenParams}. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably {@link TokenParams} must be obtained from the key owner. Use this to generate an Ably {@link TokenRequest} in order to implement an Ably Token request callback for use by other clients. When the {@link TokenRequest} is omitted or `null`, the default token parameters for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param tokenParams - A {@link TokenParams} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenRequest} object. Upon failure, the function will be called with information about the error.
- */
- createTokenRequest(tokenParams?: TokenParams | null, callback?: tokenRequestCallback): void;
- /**
- * Creates and signs an Ably {@link TokenRequest} based on the the client library stored {@link TokenParams} and {@link AuthOptions}. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably {@link TokenRequest} must be obtained from the key owner. Use this to generate an Ably {@link TokenRequest} in order to implement an Ably Token request callback for use by other clients. The default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param callback - A function which, upon success, will be called with a {@link TokenRequest} object. Upon failure, the function will be called with information about the error.
- */
- createTokenRequest(callback?: tokenRequestCallback): void;
- /**
- * Calls the `requestToken` REST API endpoint to obtain an Ably Token according to the specified {@link TokenParams} and {@link AuthOptions}. Both {@link TokenParams} and {@link AuthOptions} are optional. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param TokenParams - A {@link TokenParams} object.
- * @param authOptions - An {@link AuthOptions} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- requestToken(
- TokenParams?: TokenParams | null,
- authOptions?: AuthOptions | null,
- callback?: tokenDetailsCallback
- ): void;
- /**
- * Calls the `requestToken` REST API endpoint to obtain an Ably Token according to the specified {@link TokenParams}. When omitted or `null`, the default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param TokenParams - A {@link TokenParams} object.
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- requestToken(TokenParams?: TokenParams | null, callback?: tokenDetailsCallback): void;
- /**
- * Calls the `requestToken` REST API endpoint to obtain an Ably Token. The default token parameters and authentication options for the client library are used, as specified in the {@link ClientOptions} when the client library was instantiated, or later updated with an explicit `authorize` request. To understand why an Ably {@link TokenRequest} may be issued to clients in favor of a token, see [Token Authentication explained](https://ably.com/docs/core-features/authentication/#token-authentication).
- *
- * @param callback - A function which, upon success, will be called with a {@link TokenDetails} object. Upon failure, the function will be called with information about the error.
- */
- requestToken(callback?: tokenDetailsCallback): void;
- }
-
/**
* Creates Ably {@link TokenRequest} objects and obtains Ably Tokens from Ably to subsequently issue to less trusted clients.
*/
@@ -2002,38 +1731,6 @@ declare namespace Types {
requestToken(TokenParams?: TokenParams, authOptions?: AuthOptions): Promise;
}
- /**
- * Enables the retrieval of the current and historic presence set for a channel.
- */
- class PresenceCallbacks {
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns a {@link Types.PaginatedResult} object, containing an array of {@link PresenceMessage} objects.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- get(params?: RestPresenceParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their [PresenceAction]{@link PresenceAction} and ID.
- *
- * @param callback - A function which, upon success, will be called with a [PaginatedResult]{@link PaginatedResult} object, containing an array of [PresenceMessage]{@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- get(callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which messages should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- history(params: RestHistoryParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- history(callback: paginatedResultCallback): void;
- }
-
/**
* Enables the retrieval of the current and historic presence set for a channel.
*/
@@ -2055,7 +1752,7 @@ declare namespace Types {
}
/**
- * The `RealtimePresenceBase` class acts as a base class for the {@link RealtimePresenceCallbacks} and {@link RealtimePresencePromise} classes.
+ * The `RealtimePresenceBase` class acts as a base class for the {@link RealtimePresencePromise} class.
*/
class RealtimePresenceBase {
/**
@@ -2100,128 +1797,6 @@ declare namespace Types {
unsubscribe(): void;
}
- /**
- * Enables the presence set to be entered and subscribed to, and the historic presence set to be retrieved for a channel.
- */
- class RealtimePresenceCallbacks extends RealtimePresenceBase {
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns an array of {@link PresenceMessage} objects.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @param callback - A function which, upon success, will be called with an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- get(params?: RealtimePresenceParams, callback?: realtimePresenceGetCallback): void;
- /**
- * Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns an array of {@link PresenceMessage} objects.
- *
- * @param callback - A function which, upon success, will be called with an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- get(callback?: realtimePresenceGetCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which presence messages should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- history(params?: RealtimeHistoryParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link PresenceMessage} objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PresenceMessage} objects. Upon failure, the function will be called with information about the error.
- */
- history(callback?: paginatedResultCallback): void;
- /**
- * Registers a listener that is called each time a {@link PresenceMessage} matching a given {@link PresenceAction}, or an action within an array of {@link PresenceAction | `PresenceAction`s}, is received on the channel, such as a new member entering the presence set.
- *
- * @param presence - A {@link PresenceAction} or an array of {@link PresenceAction | `PresenceAction`s} to register the listener for.
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(
- presence: PresenceAction | Array,
- listener?: messageCallback,
- callbackWhenAttached?: errorCallback
- ): void;
- /**
- * Registers a listener that is called each time a {@link PresenceMessage} is received on the channel, such as a new member entering the presence set.
- *
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(listener: messageCallback, callbackWhenAttached?: errorCallback): void;
- /**
- * Enters the presence set for the channel, passing a `data` payload. A `clientId` is required to be present on a channel.
- *
- * @param data - The payload associated with the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- enter(data?: any, callback?: errorCallback): void;
- /**
- * Enters the presence set for the channel. A `clientId` is required to be present on a channel.
- *
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- enter(callback?: errorCallback): void;
- /**
- * Updates the `data` payload for a presence member. If called before entering the presence set, this is treated as an {@link PresenceAction.ENTER} event.
- *
- * @param data - The payload to update for the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- update(data?: any, callback?: errorCallback): void;
- /**
- * Leaves the presence set for the channel. A client must have previously entered the presence set before they can leave it.
- *
- * @param data - The payload associated with the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- leave(data?: any, callback?: errorCallback): void;
- /**
- * Leaves the presence set for the channel. A client must have previously entered the presence set before they can leave it.
- *
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- leave(callback?: errorCallback): void;
- /**
- * Enters the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to enter into the presence set.
- * @param data - The payload associated with the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- enterClient(clientId: string, data?: any, callback?: errorCallback): void;
- /**
- * Enters the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to enter into the presence set.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- enterClient(clientId: string, callback?: errorCallback): void;
- /**
- * Updates the `data` payload for a presence member using a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to update in the presence set.
- * @param data - The payload to update for the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- updateClient(clientId: string, data?: any, callback?: errorCallback): void;
- /**
- * Leaves the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to leave the presence set for.
- * @param data - The payload associated with the presence member.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- leaveClient(clientId: string, data?: any, callback?: errorCallback): void;
- /**
- * Leaves the presence set of the channel for a given `clientId`. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard `clientId`.
- *
- * @param clientId - The ID of the client to leave the presence set for.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- leaveClient(clientId: string, callback?: errorCallback): void;
- }
-
/**
* Enables the presence set to be entered and subscribed to, and the historic presence set to be retrieved for a channel.
*/
@@ -2306,7 +1881,7 @@ declare namespace Types {
}
/**
- * The `ChannelBase` class acts as a base class for the {@link ChannelCallbacks} and {@link ChannelPromise} classes.
+ * The `ChannelBase` class acts as a base class for the {@link ChannelPromise} class.
*/
class ChannelBase {
/**
@@ -2315,66 +1890,6 @@ declare namespace Types {
name: string;
}
- /**
- * Enables messages to be published and historic messages to be retrieved for a channel.
- */
- class ChannelCallbacks extends ChannelBase {
- /**
- * A {@link PresenceCallbacks} object.
- */
- presence: PresenceCallbacks;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which messages should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the function will be called with information about the error.
- */
- history(params?: RestHistoryParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the function will be called with information about the error.
- */
- history(callback?: paginatedResultCallback): void;
- /**
- * Publishes a single message to the channel with the given event name and payload.
- *
- * @param name - The name of the message.
- * @param data - The payload of the message.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(name: string, data: any, callback?: errorCallback): void;
- /**
- * Publishes an array of messages to the channel.
- *
- * @param messages - An array of {@link Message} objects.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(messages: any[], callback?: errorCallback): void;
- /**
- * Publishes a message to the channel.
- *
- * @param message - A {@link Message} object.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(message: any, callback?: errorCallback): void;
- /**
- * Publishes a single message to the channel with the given event name and payload.
- *
- * @param name - The name of the message.
- * @param data - The payload of the message.
- * @param options - Optional parameters, such as [`quickAck`](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes) sent as part of the query string.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(name: string, data: any, options?: PublishOptions, callback?: errorCallback): void;
- /**
- * Retrieves a {@link ChannelDetails} object for the channel, which includes status and occupancy metrics.
- *
- * @param callback - A function which, upon success, will be called a {@link ChannelDetails} object. Upon failure, the function will be called with information about the error.
- */
- status(callback: StandardCallback): void;
- }
-
/**
* Enables messages to be published and historic messages to be retrieved for a channel.
*/
@@ -2424,7 +1939,7 @@ declare namespace Types {
}
/**
- * The `RealtimeChannelBase` class acts as a base class for the {@link RealtimeChannelCallbacks} and {@link RealtimeChannelPromise} classes.
+ * The `RealtimeChannelBase` class acts as a base class for the {@link RealtimeChannelPromise} class.
*/
class RealtimeChannelBase extends EventEmitter {
/**
@@ -2503,7 +2018,7 @@ declare namespace Types {
};
/**
- * Contains properties to filter messages with when calling {@link RealtimeChannelCallbacks.subscribe | `RealtimeChannelCallbacks.subscribe()`} or {@link RealtimeChannelPromise.subscribe | `RealtimeChannelPromise.subscribe()`}.
+ * Contains properties to filter messages with when calling {@link RealtimeChannelPromise.subscribe | `RealtimeChannelPromise.subscribe()`}.
*/
type MessageFilter = {
/**
@@ -2528,116 +2043,6 @@ declare namespace Types {
clientId: string;
};
- /**
- * Enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the {@link RealtimePresenceCallbacks} object of a channel.
- */
- class RealtimeChannelCallbacks extends RealtimeChannelBase {
- /**
- * A {@link RealtimePresenceCallbacks} object.
- */
- presence: RealtimePresenceCallbacks;
- /**
- * Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using {@link RealtimeChannelCallbacks.subscribe | `subscribe()`}. Any resulting channel state change will be emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. As a convenience, `attach()` is called implicitly if {@link RealtimeChannelCallbacks.subscribe | `subscribe()`} for the channel is called, or {@link RealtimePresenceCallbacks.enter | `enter()`} or {@link RealtimePresenceCallbacks.subscribe | `subscribe()`} are called on the {@link RealtimePresenceCallbacks} object for this channel.
- *
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- attach(callback?: errorCallback): void;
- /**
- * Detach from this channel. Any resulting channel state change is emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes.
- *
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- detach(callback?: errorCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param params - A set of parameters which are used to specify which presence members should be retrieved.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the function will be called with information about the error.
- */
- history(params?: RealtimeHistoryParams, callback?: paginatedResultCallback): void;
- /**
- * Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
- *
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link Message} objects. Upon failure, the function will be called with information about the error.
- */
- history(callback?: paginatedResultCallback): void;
- /**
- * Sets the {@link ChannelOptions} for the channel.
- *
- * @param options - A {@link ChannelOptions} object.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- setOptions(options: ChannelOptions, callback?: errorCallback): void;
- /**
- * Registers a listener for messages with a given event name on this channel. The caller supplies a listener function, which is called each time one or more matching messages arrives on the channel.
- *
- * @param event - The event name.
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(event: string, listener?: messageCallback, callbackWhenAttached?: errorCallback): void;
- /**
- * Registers a listener for messages on this channel for multiple event name values.
- *
- * @param events - An array of event names.
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(events: Array, listener?: messageCallback, callbackWhenAttached?: errorCallback): void;
- /**
- * Registers a listener for messages on this channel that match the supplied filter.
- *
- * @param filter - A {@link MessageFilter}.
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(filter: MessageFilter, listener?: messageCallback, callbackWhenAttached?: errorCallback): void;
- /**
- * Registers a listener for messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.
- *
- * @param listener - An event listener function.
- * @param callbackWhenAttached - A function which will be called upon completion of the channel {@link RealtimeChannelCallbacks.attach | `attach()`} operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- subscribe(listener: messageCallback, callbackWhenAttached?: errorCallback): void;
- /**
- * Publishes a single message to the channel with the given event name and payload. When publish is called with this client library, it won't attempt to implicitly attach to the channel, so long as [transient publishing](https://ably.com/docs/realtime/channels#transient-publish) is available in the library. Otherwise, the client will implicitly attach.
- *
- * @param name - The event name.
- * @param data - The message payload.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(name: string, data: any, callback?: errorCallback): void;
- /**
- * Publishes an array of messages to the channel. When publish is called with this client library, it won't attempt to implicitly attach to the channel.
- *
- * @param messages - An array of {@link Message} objects.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(messages: any[], callback?: errorCallback): void;
- /**
- * Publish a message to the channel. When publish is called with this client library, it won't attempt to implicitly attach to the channel.
- *
- * @param message - A {@link Message} object.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(message: any, callback?: errorCallback): void;
- /**
- * Publishes a single message to the channel with the given event name and payload. When publish is called with this client library, it won't attempt to implicitly attach to the channel, so long as [transient publishing](https://ably.com/docs/realtime/channels#transient-publish) is available in the library. Otherwise, the client will implicitly attach.
- *
- * @param name - The event name.
- * @param data - The message payload.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(name: string, data: any, callback?: errorCallback): void;
- /**
- * Calls the supplied function when the channel reaches the specified {@link ChannelState}. If the channel is already in the specified state, the callback is called immediately.
- *
- * @param targetState - The state which should be reached.
- * @param callback - A function which will be called when the channel has reached the specified {@link ChannelState} with a {@link ChannelStateChange} object as the first argument.
- */
- whenState(targetState: ChannelState, callback: channelEventCallback): void;
- }
-
/**
* Enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the {@link RealtimePresencePromise} object of a channel.
*/
@@ -2976,7 +2381,7 @@ declare namespace Types {
}
/**
- * The `ConnectionBase` class acts as a base class for the {@link ChannelCallbacks} and {@link ChannelPromise} classes.
+ * The `ConnectionBase` class acts as a base class for the {@link ChannelPromise} class.
*/
class ConnectionBase extends EventEmitter {
/**
@@ -3013,25 +2418,6 @@ declare namespace Types {
connect(): void;
}
- /**
- * Enables the management of a connection to Ably.
- */
- class ConnectionCallbacks extends ConnectionBase {
- /**
- * When connected, sends a heartbeat ping to the Ably server and executes the callback with any error and the response time in milliseconds when a heartbeat ping request is echoed from the server. This can be useful for measuring true round-trip latency to the connected Ably server.
- *
- * @param callback - A function which, upon success, will be called with the response time in milliseconds. Upon failure, the function will be called with information about the error.
- */
- ping(callback?: Types.StandardCallback): void;
- /**
- * Calls the supplied function when the connection reaches the specified {@link ConnectionState}. If the connection is already in the specified state, the callback is called immediately.
- *
- * @param targetState - The state which should be reached.
- * @param callback - A function which will be called when the connection has reached the specified {@link ConnectionState} with a {@link ConnectionStateChange} object as the first argument.
- */
- whenState(targetState: ConnectionState, callback: connectionEventCallback): void;
- }
-
/**
* Enables the management of a connection to Ably.
*/
@@ -3100,36 +2486,18 @@ declare namespace Types {
* Contains the current page of results; for example, an array of {@link Message} or {@link PresenceMessage} objects for a channel history request.
*/
items: T[];
- /**
- * Returns a new `PaginatedResult` for the first page of results.
- *
- * @param results - A function which, upon success, will be called with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the function will be called with information about the error.
- */
- first(results: paginatedResultCallback): void;
/**
* Returns a new `PaginatedResult` for the first page of results.
*
* @returns A promise which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
first(): Promise>;
- /**
- * Returns a new `PaginatedResult` loaded with the next page of results. If there are no further pages, then `null` is returned.
- *
- * @param results - A function which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the function will be called with information about the error.
- */
- next(results: paginatedResultCallback): void;
/**
* Returns a new `PaginatedResult` loaded with the next page of results. If there are no further pages, then `null` is returned.
*
* @returns A promise which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the promise will be rejected with an {@link ErrorInfo} object which explains the error.
*/
next(): Promise>;
- /**
- * Returns the `PaginatedResult` for the current page of results.
- *
- * @param results - A function which, upon success, will be fulfilled with a page of results for message and presence history, stats, and REST presence requests. Upon failure, the function will be called with information about the error.
- */
- current(results: paginatedResultCallback): void;
/**
* Returns the `PaginatedResult` for the current page of results.
*/
@@ -3174,16 +2542,6 @@ declare namespace Types {
headers: any;
}
- /**
- * Enables a device to be registered and deregistered from receiving push notifications.
- */
- class PushCallbacks {
- /**
- * A {@link PushAdminCallbacks} object.
- */
- admin: PushAdminCallbacks;
- }
-
/**
* Enables a device to be registered and deregistered from receiving push notifications.
*/
@@ -3194,28 +2552,6 @@ declare namespace Types {
admin: PushAdminPromise;
}
- /**
- * Enables the management of device registrations and push notification subscriptions. Also enables the publishing of push notifications to devices.
- */
- class PushAdminCallbacks {
- /**
- * A {@link PushDeviceRegistrationsCallbacks} object.
- */
- deviceRegistrations: PushDeviceRegistrationsCallbacks;
- /**
- * A {@link PushChannelSubscriptionsCallbacks} object.
- */
- channelSubscriptions: PushChannelSubscriptionsCallbacks;
- /**
- * Sends a push notification directly to a device, or a group of devices sharing the same `clientId`.
- *
- * @param recipient - A JSON object containing the recipient details using `clientId`, `deviceId` or the underlying notifications service.
- * @param payload - A JSON object containing the push notification payload.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- publish(recipient: any, payload: any, callback?: errorCallback): void;
- }
-
/**
* Enables the management of device registrations and push notification subscriptions. Also enables the publishing of push notifications to devices.
*/
@@ -3238,61 +2574,6 @@ declare namespace Types {
publish(recipient: any, payload: any): Promise;
}
- /**
- * Enables the management of push notification registrations with Ably.
- */
- class PushDeviceRegistrationsCallbacks {
- /**
- * Registers or updates a {@link DeviceDetails} object with Ably. Returns the new, or updated {@link DeviceDetails} object.
- *
- * @param deviceDetails - The {@link DeviceDetails} object to create or update.
- * @param callback - A function which, upon success, will be called with a {@link DeviceDetails} object. Upon failure, the function will be called with information about the error.
- */
- save(deviceDetails: DeviceDetails, callback?: Types.StandardCallback): void;
- /**
- * Retrieves the {@link DeviceDetails} of a device registered to receive push notifications using its `deviceId`.
- *
- * @param deviceId - The unique ID of the device.
- * @param callback - A function which, upon success, will be called with a {@link DeviceDetails} object. Upon failure, the function will be called with information about the error.
- */
- get(deviceId: string, callback: Types.StandardCallback): void;
- /**
- * Retrieves the {@link DeviceDetails} of a device registered to receive push notifications using the `id` property of a {@link DeviceDetails} object.
- *
- * @param deviceDetails - The {@link DeviceDetails} object containing the `id` property of the device.
- * @param callback - A function which, upon success, will be called with a {@link DeviceDetails} object. Upon failure, the function will be called with information about the error.
- */
- get(deviceDetails: DeviceDetails, callback: Types.StandardCallback): void;
- /**
- * Retrieves all devices matching the filter `params` provided. Returns a {@link Types.PaginatedResult} object, containing an array of {@link DeviceDetails} objects.
- *
- * @param params - An object containing key-value pairs to filter devices by.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link DeviceDetails} objects. Upon failure, the function will be called with information about the error.
- */
- list(params: DeviceRegistrationParams, callback: paginatedResultCallback): void;
- /**
- * Removes a device registered to receive push notifications from Ably using its `deviceId`.
- *
- * @param deviceId - The unique ID of the device.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- remove(deviceId: string, callback?: errorCallback): void;
- /**
- * Removes a device registered to receive push notifications from Ably using the `id` property of a {@link DeviceDetails} object.
- *
- * @param deviceDetails - The {@link DeviceDetails} object containing the `id` property of the device.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- remove(deviceDetails: DeviceDetails, callback?: errorCallback): void;
- /**
- * Removes all devices registered to receive push notifications from Ably matching the filter `params` provided.
- *
- * @param params - An object containing key-value pairs to filter devices by. This object’s {@link DeviceRegistrationParams.limit} property will be ignored.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- removeWhere(params: DeviceRegistrationParams, callback?: errorCallback): void;
- }
-
/**
* Enables the management of push notification registrations with Ably.
*/
@@ -3348,47 +2629,6 @@ declare namespace Types {
removeWhere(params: DeviceRegistrationParams): Promise;
}
- /**
- * Enables device push channel subscriptions.
- */
- class PushChannelSubscriptionsCallbacks {
- /**
- * Subscribes a device, or a group of devices sharing the same `clientId` to push notifications on a channel. Returns a {@link PushChannelSubscription} object.
- *
- * @param subscription - A {@link PushChannelSubscription} object.
- * @param callback - A function which, upon success, will be called with a {@link PushChannelSubscription} object describing the new or updated subscriptions. Upon failure, the function will be called with information about the error.
- */
- save(subscription: PushChannelSubscription, callback?: Types.StandardCallback): void;
- /**
- * Retrieves all push channel subscriptions matching the filter `params` provided. Returns a {@link Types.PaginatedResult} object, containing an array of {@link PushChannelSubscription} objects.
- *
- * @param params - An object containing key-value pairs to filter subscriptions by.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of {@link PushChannelSubscription} objects. Upon failure, the function will be called with information about the error.
- */
- list(params: PushChannelSubscriptionParams, callback: paginatedResultCallback): void;
- /**
- * Retrieves all channels with at least one device subscribed to push notifications. Returns a {@link Types.PaginatedResult} object, containing an array of channel names.
- *
- * @param params - An object containing key-value pairs to filter channels by.
- * @param callback - A function which, upon success, will be called with a {@link Types.PaginatedResult} object containing an array of channel names. Upon failure, the function will be called with information about the error.
- */
- listChannels(params: PushChannelsParams, callback: paginatedResultCallback): void;
- /**
- * Unsubscribes a device, or a group of devices sharing the same `clientId` from receiving push notifications on a channel.
- *
- * @param subscription - A {@link PushChannelSubscription} object.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- remove(subscription: PushChannelSubscription, callback?: errorCallback): void;
- /**
- * Unsubscribes all devices from receiving push notifications on a channel that match the filter `params` provided.
- *
- * @param params - An object containing key-value pairs to filter subscriptions by. Can contain `channel`, and optionally either `clientId` or `deviceId`.
- * @param callback - A function which will be called upon completion of the operation. If the operation succeeded, then the function will be called with `null`. If it failed, the function will be called with information about the error.
- */
- removeWhere(params: PushChannelSubscriptionParams, callback?: errorCallback): void;
- }
-
/**
* Enables device push channel subscriptions.
*/
@@ -3434,9 +2674,9 @@ declare namespace Types {
/**
* A client that offers a simple stateless API to interact directly with Ably's REST API.
*/
-export declare class Rest extends Types.RestCallbacks {}
+export declare class Rest extends Types.RestPromise {}
/**
* A client that extends the functionality of {@link Rest} and provides additional realtime-specific features.
*/
-export declare class Realtime extends Types.RealtimeCallbacks {}
+export declare class Realtime extends Types.RealtimePromise {}
diff --git a/callbacks.d.ts b/callbacks.d.ts
deleted file mode 100644
index e0a434a3dd..0000000000
--- a/callbacks.d.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-import Ably = require('./ably');
-export = Ably;
diff --git a/callbacks.js b/callbacks.js
deleted file mode 100644
index 8bfe2c458f..0000000000
--- a/callbacks.js
+++ /dev/null
@@ -1,6 +0,0 @@
-'use strict';
-/* When returning promises becomes the default in some future version, this
- * file will start modifying the exports as promises.js does today.
- * Please note that the file imported below is only generated after running
- * the build task. */
-module.exports = require('./build/ably-node');
diff --git a/docs/landing-page.md b/docs/landing-page.md
new file mode 100644
index 0000000000..f9a0bb6212
--- /dev/null
+++ b/docs/landing-page.md
@@ -0,0 +1,7 @@
+# Ably JavaScript Client Library SDK API Reference
+
+The JavaScript Client Library SDK supports a realtime and a REST interface. The JavaScript API references are generated from the [Ably JavaScript Client Library SDK source code](https://github.com/ably/ably-js/) using [TypeDoc](https://typedoc.org) and structured by classes.
+
+The realtime interface enables a client to maintain a persistent connection to Ably and publish, subscribe and be present on channels. The REST interface is stateless and typically implemented server-side. It is used to make requests such as retrieving statistics, token authentication and publishing to a channel.
+
+View the [Ably docs](https://ably.com/docs/) for conceptual information on using Ably, and for API references featuring all languages. The combined [API references](https://ably.com/docs/api/) are organized by features and split between the [realtime](https://ably.com/docs/api/realtime-sdk) and [REST](https://ably.com/docs/api/rest-sdk) interfaces.
diff --git a/docs/landing-pages/choose-library.html b/docs/landing-pages/choose-library.html
deleted file mode 100644
index c4243efaf1..0000000000
--- a/docs/landing-pages/choose-library.html
+++ /dev/null
@@ -1,31 +0,0 @@
-
-
-
-
- Ably JavaScript Client Library SDK API Reference
-
-
- Ably JavaScript Client Library SDK API Reference
-
-
- The JavaScript Client Library SDK supports a realtime and a REST interface. The JavaScript API references are generated from the Ably JavaScript Client Library SDK source code using TypeDoc and structured by classes.
-
-
-
- The realtime interface enables a client to maintain a persistent connection to Ably and publish, subscribe and be present on channels. The REST interface is stateless and typically implemented server-side. It is used to make requests such as retrieving statistics, token authentication and publishing to a channel.
-
-
-
- There are two API variants of the Ably JavaScript Client Library SDK:
-
-
-
-
-
- View the Ably docs for conceptual information on using Ably, and for API references featuring all languages. The combined API references are organized by features and split between the realtime and REST interfaces.
-
-
-
diff --git a/docs/landing-pages/default.md b/docs/landing-pages/default.md
deleted file mode 100644
index 994b06cd18..0000000000
--- a/docs/landing-pages/default.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# Ably JavaScript Client Library SDK API Reference for Callbacks
-
-You are currently viewing the callback-based variant of the Ably JavaScript Client Library SDK. View the promise-based variant [here](../promises/index.html).
-
-The callback-based variant of the API implements the common Node.js error-first callback style.
-
-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.
diff --git a/docs/landing-pages/promises.md b/docs/landing-pages/promises.md
deleted file mode 100644
index c312a44660..0000000000
--- a/docs/landing-pages/promises.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# Ably JavaScript Client Library SDK API Reference for Promises
-
-You are currently viewing the promise-based variant of the Ably JavaScript Client Library SDK. View the callback-based variant [here](../default/index.html).
-
-Passing callbacks to methods when using the promise-based variant of the API is still possible, however, if a method does not receive a callback then it will instead return a promise.
-
-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.
diff --git a/package.json b/package.json
index ce9639b23b..c0b79298eb 100644
--- a/package.json
+++ b/package.json
@@ -18,8 +18,6 @@
"files": [
"build/**",
"ably.d.ts",
- "callbacks.d.ts",
- "callbacks.js",
"promises.d.ts",
"promises.js",
"resources/**"
@@ -101,6 +99,6 @@
"format:check": "prettier --check --ignore-path .gitignore --ignore-path .prettierignore src test ably.d.ts webpack.config.js Gruntfile.js scripts/cdn_deploy.js",
"sourcemap": "source-map-explorer build/ably.min.js",
"sourcemap:noencryption": "source-map-explorer build/ably.noencryption.min.js",
- "docs": "typedoc --entryPoints ably.d.ts --out docs/generated/default --readme docs/landing-pages/default.md && typedoc --entryPoints promises.d.ts --out docs/generated/promises --name \"ably (Promise-based)\" --readme docs/landing-pages/promises.md && cp docs/landing-pages/choose-library.html docs/generated/index.html"
+ "docs": "typedoc --entryPoints ably.d.ts --out docs/generated --readme docs/landing-page.md"
}
}
diff --git a/src/common/lib/client/auth.ts b/src/common/lib/client/auth.ts
index bb4f636d1b..794ea837e1 100644
--- a/src/common/lib/client/auth.ts
+++ b/src/common/lib/client/auth.ts
@@ -259,9 +259,7 @@ class Auth {
_authOptions = authOptions as API.Types.AuthOptions;
}
if (!callback) {
- if (this.client.options.promises) {
- return Utils.promisify(this, 'authorize', arguments);
- }
+ return Utils.promisify(this, 'authorize', arguments);
}
/* RSA10a: authorize() call implies token auth. If a key is passed it, we
@@ -418,7 +416,7 @@ class Auth {
callback = authOptions;
authOptions = null;
}
- if (!callback && this.client.options.promises) {
+ if (!callback) {
return Utils.promisify(this, 'requestToken', arguments);
}
@@ -746,7 +744,7 @@ class Auth {
callback = authOptions;
authOptions = null;
}
- if (!callback && this.client.options.promises) {
+ if (!callback) {
return Utils.promisify(this, 'createTokenRequest', arguments);
}
diff --git a/src/common/lib/client/channel.ts b/src/common/lib/client/channel.ts
index 8937709d5e..efb273351e 100644
--- a/src/common/lib/client/channel.ts
+++ b/src/common/lib/client/channel.ts
@@ -78,10 +78,7 @@ class Channel extends EventEmitter {
callback = params;
params = null;
} else {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'history', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'history', arguments);
}
}
@@ -115,10 +112,7 @@ class Channel extends EventEmitter {
let params: any;
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'publish', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'publish', arguments);
}
if (typeof first === 'string' || first === null) {
@@ -192,7 +186,7 @@ class Channel extends EventEmitter {
}
status(callback?: StandardCallback): void | Promise {
- if (typeof callback !== 'function' && this.rest.options.promises) {
+ if (typeof callback !== 'function') {
return Utils.promisify(this, 'status', []);
}
diff --git a/src/common/lib/client/connection.ts b/src/common/lib/client/connection.ts
index a1f823710d..be5177ba48 100644
--- a/src/common/lib/client/connection.ts
+++ b/src/common/lib/client/connection.ts
@@ -8,8 +8,6 @@ import { NormalisedClientOptions } from '../../types/ClientOptions';
import Realtime from './realtime';
import Platform from 'common/platform';
-function noop() {}
-
class Connection extends EventEmitter {
ably: Realtime;
connectionManager: ConnectionManager;
@@ -58,10 +56,7 @@ class Connection extends EventEmitter {
ping(callback: Function): Promise | void {
Logger.logAction(Logger.LOG_MINOR, 'Connection.ping()', '');
if (!callback) {
- if (this.ably.options.promises) {
- return Utils.promisify(this, 'ping', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'ping', arguments);
}
this.connectionManager.ping(null, callback);
}
diff --git a/src/common/lib/client/paginatedresource.ts b/src/common/lib/client/paginatedresource.ts
index bf54698b23..416c59fae6 100644
--- a/src/common/lib/client/paginatedresource.ts
+++ b/src/common/lib/client/paginatedresource.ts
@@ -195,7 +195,7 @@ export class PaginatedResult {
if (relParams) {
if ('first' in relParams) {
this.first = function (callback: (result?: ErrorInfo | null) => void) {
- if (!callback && self.resource.rest.options.promises) {
+ if (!callback) {
return Utils.promisify(self, 'first', []);
}
self.get(relParams.first, callback);
@@ -203,14 +203,14 @@ export class PaginatedResult {
}
if ('current' in relParams) {
this.current = function (callback: (results?: ErrorInfo | null) => void) {
- if (!callback && self.resource.rest.options.promises) {
+ if (!callback) {
return Utils.promisify(self, 'current', []);
}
self.get(relParams.current, callback);
};
}
this.next = function (callback: (results?: ErrorInfo | null) => void) {
- if (!callback && self.resource.rest.options.promises) {
+ if (!callback) {
return Utils.promisify(self, 'next', []);
}
if ('next' in relParams) {
diff --git a/src/common/lib/client/presence.ts b/src/common/lib/client/presence.ts
index 77210ade55..8d521bdf4c 100644
--- a/src/common/lib/client/presence.ts
+++ b/src/common/lib/client/presence.ts
@@ -8,8 +8,6 @@ import { PaginatedResultCallback } from '../../types/utils';
import Channel from './channel';
import RealtimeChannel from './realtimechannel';
-function noop() {}
-
class Presence extends EventEmitter {
channel: RealtimeChannel | Channel;
basePath: string;
@@ -28,10 +26,7 @@ class Presence extends EventEmitter {
callback = params;
params = null;
} else {
- if (this.channel.rest.options.promises) {
- return Utils.promisify(this, 'get', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'get', arguments);
}
}
const rest = this.channel.rest,
@@ -69,10 +64,7 @@ class Presence extends EventEmitter {
callback = params;
params = null;
} else {
- if (this.channel.rest.options.promises) {
- return Utils.promisify(this, '_history', [params]);
- }
- callback = noop;
+ return Utils.promisify(this, '_history', [params]);
}
}
diff --git a/src/common/lib/client/push.ts b/src/common/lib/client/push.ts
index fb694eaded..b628457f50 100644
--- a/src/common/lib/client/push.ts
+++ b/src/common/lib/client/push.ts
@@ -7,8 +7,6 @@ import PushChannelSubscription from '../types/pushchannelsubscription';
import { ErrCallback, PaginatedResultCallback, StandardCallback } from '../../types/utils';
import Rest from './rest';
-const noop = function () {};
-
class Push {
rest: Rest;
admin: Admin;
@@ -38,10 +36,7 @@ class Admin {
const body = Utils.mixin({ recipient: recipient }, payload);
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'publish', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'publish', arguments);
}
Utils.mixin(headers, rest.options.headers);
@@ -68,10 +63,7 @@ class DeviceRegistrations {
params = {};
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'save', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'save', arguments);
}
Utils.mixin(headers, rest.options.headers);
@@ -107,10 +99,7 @@ class DeviceRegistrations {
deviceId = deviceIdOrDetails.id || deviceIdOrDetails;
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'get', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'get', arguments);
}
if (typeof deviceId !== 'string' || !deviceId.length) {
@@ -153,10 +142,7 @@ class DeviceRegistrations {
headers = Utils.defaultGetHeaders(rest.options, { format });
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'list', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'list', arguments);
}
Utils.mixin(headers, rest.options.headers);
@@ -178,10 +164,7 @@ class DeviceRegistrations {
deviceId = deviceIdOrDetails.id || deviceIdOrDetails;
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'remove', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'remove', arguments);
}
if (typeof deviceId !== 'string' || !deviceId.length) {
@@ -215,10 +198,7 @@ class DeviceRegistrations {
headers = Utils.defaultGetHeaders(rest.options, { format });
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'removeWhere', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'removeWhere', arguments);
}
Utils.mixin(headers, rest.options.headers);
@@ -244,10 +224,7 @@ class ChannelSubscriptions {
params = {};
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'save', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'save', arguments);
}
Utils.mixin(headers, rest.options.headers);
@@ -278,10 +255,7 @@ class ChannelSubscriptions {
headers = Utils.defaultGetHeaders(rest.options, { format });
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'list', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'list', arguments);
}
Utils.mixin(headers, rest.options.headers);
@@ -301,10 +275,7 @@ class ChannelSubscriptions {
headers = Utils.defaultGetHeaders(rest.options, { format });
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'removeWhere', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'removeWhere', arguments);
}
Utils.mixin(headers, rest.options.headers);
@@ -324,10 +295,7 @@ class ChannelSubscriptions {
headers = Utils.defaultGetHeaders(rest.options, { format });
if (typeof callback !== 'function') {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'listChannels', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'listChannels', arguments);
}
Utils.mixin(headers, rest.options.headers);
diff --git a/src/common/lib/client/realtime.ts b/src/common/lib/client/realtime.ts
index e3b39c7519..58c21a5fcd 100644
--- a/src/common/lib/client/realtime.ts
+++ b/src/common/lib/client/realtime.ts
@@ -4,11 +4,10 @@ import EventEmitter from '../util/eventemitter';
import Logger from '../util/logger';
import Connection from './connection';
import RealtimeChannel from './realtimechannel';
-import Defaults from '../util/defaults';
import ErrorInfo from '../types/errorinfo';
import ProtocolMessage from '../types/protocolmessage';
import { ChannelOptions } from '../../types/channel';
-import ClientOptions, { InternalClientOptions } from '../../types/ClientOptions';
+import ClientOptions from '../../types/ClientOptions';
import * as API from '../../../../ably';
import ConnectionManager from '../transport/connectionmanager';
import Platform from 'common/platform';
@@ -36,13 +35,8 @@ class Realtime extends Rest {
this.connection.close();
}
- static Promise = function (options: InternalClientOptions): Realtime {
- options = Defaults.objectifyOptions(options);
- options.internal = { ...options.internal, promises: true };
- return new Realtime(options);
- };
+ static Promise = Realtime;
- static Callbacks = Realtime;
static Utils = Utils;
static ConnectionManager = ConnectionManager;
static Platform = Platform;
diff --git a/src/common/lib/client/realtimechannel.ts b/src/common/lib/client/realtimechannel.ts
index 4a04ee5051..0c55e901da 100644
--- a/src/common/lib/client/realtimechannel.ts
+++ b/src/common/lib/client/realtimechannel.ts
@@ -136,9 +136,7 @@ class RealtimeChannel extends Channel {
setOptions(options?: API.Types.ChannelOptions, callback?: ErrCallback): void | Promise {
if (!callback) {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'setOptions', arguments);
- }
+ return Utils.promisify(this, 'setOptions', arguments);
}
const _callback =
callback ||
@@ -194,11 +192,7 @@ class RealtimeChannel extends Channel {
let callback = args[argCount - 1];
if (typeof callback !== 'function') {
- if (this.realtime.options.promises) {
- return Utils.promisify(this, 'publish', arguments);
- }
- callback = noop;
- ++argCount;
+ return Utils.promisify(this, 'publish', arguments);
}
if (!this.connectionManager.activeState()) {
callback(this.connectionManager.getError());
@@ -274,14 +268,7 @@ class RealtimeChannel extends Channel {
attach(callback?: ErrCallback): void | Promise {
if (!callback) {
- if (this.realtime.options.promises) {
- return Utils.promisify(this, 'attach', arguments);
- }
- callback = function (err?: ErrorInfo | null) {
- if (err) {
- Logger.logAction(Logger.LOG_MAJOR, 'RealtimeChannel.attach()', 'Channel attach failed: ' + err.toString());
- }
- };
+ return Utils.promisify(this, 'attach', arguments);
}
if (this.state === 'attached') {
callback();
@@ -357,10 +344,7 @@ class RealtimeChannel extends Channel {
detach(callback: ErrCallback): void | Promise {
if (!callback) {
- if (this.realtime.options.promises) {
- return Utils.promisify(this, 'detach', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'detach', arguments);
}
const connectionManager = this.connectionManager;
if (!connectionManager.activeState()) {
@@ -413,7 +397,7 @@ class RealtimeChannel extends Channel {
subscribe(...args: unknown[] /* [event], listener, [callback] */): void | Promise {
const [event, listener, callback] = RealtimeChannel.processListenerArgs(args);
- if (!callback && this.realtime.options.promises) {
+ if (!callback) {
return Utils.promisify(this, 'subscribe', [event, listener]);
}
@@ -957,10 +941,7 @@ class RealtimeChannel extends Channel {
callback = params;
params = null;
} else {
- if (this.rest.options.promises) {
- return Utils.promisify(this, 'history', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'history', arguments);
}
}
diff --git a/src/common/lib/client/realtimepresence.ts b/src/common/lib/client/realtimepresence.ts
index 39901b2a63..1d2f60be06 100644
--- a/src/common/lib/client/realtimepresence.ts
+++ b/src/common/lib/client/realtimepresence.ts
@@ -26,8 +26,6 @@ interface RealtimeHistoryParams {
from_serial?: string | null;
}
-const noop = function () {};
-
function getClientId(realtimePresence: RealtimePresence) {
return realtimePresence.channel.realtime.auth.clientId;
}
@@ -134,10 +132,7 @@ class RealtimePresence extends Presence {
callback = data as ErrCallback;
data = null;
} else {
- if (this.channel.realtime.options.promises) {
- return Utils.promisify(this, '_enterOrUpdateClient', [id, clientId, data, action]);
- }
- callback = noop;
+ return Utils.promisify(this, '_enterOrUpdateClient', [id, clientId, data, action]);
}
}
@@ -207,10 +202,7 @@ class RealtimePresence extends Presence {
callback = data as ErrCallback;
data = null;
} else {
- if (this.channel.realtime.options.promises) {
- return Utils.promisify(this, 'leaveClient', [clientId, data]);
- }
- callback = noop;
+ return Utils.promisify(this, 'leaveClient', [clientId, data]);
}
}
@@ -266,10 +258,7 @@ class RealtimePresence extends Presence {
const waitForSync = !params || ('waitForSync' in params ? params.waitForSync : true);
if (!callback) {
- if (this.channel.realtime.options.promises) {
- return Utils.promisify(this, 'get', args);
- }
- callback = noop;
+ return Utils.promisify(this, 'get', args);
}
function returnMembers(members: PresenceMap) {
@@ -315,10 +304,7 @@ class RealtimePresence extends Presence {
callback = params;
params = null;
} else {
- if (this.channel.realtime.options.promises) {
- return Utils.promisify(this, 'history', arguments);
- }
- callback = noop;
+ return Utils.promisify(this, 'history', arguments);
}
}
@@ -518,10 +504,7 @@ class RealtimePresence extends Presence {
const channel = this.channel;
if (!callback) {
- if (this.channel.realtime.options.promises) {
- return Utils.promisify(this, 'subscribe', [event, listener]);
- }
- callback = noop;
+ return Utils.promisify(this, 'subscribe', [event, listener]);
}
if (channel.state === 'failed') {
diff --git a/src/common/lib/client/rest.ts b/src/common/lib/client/rest.ts
index 5629f8f391..3c7776135b 100644
--- a/src/common/lib/client/rest.ts
+++ b/src/common/lib/client/rest.ts
@@ -11,7 +11,7 @@ import HttpMethods from '../../constants/HttpMethods';
import { ChannelOptions } from '../../types/channel';
import { PaginatedResultCallback, StandardCallback } from '../../types/utils';
import { ErrnoException, IHttp, RequestParams } from '../../types/http';
-import ClientOptions, { InternalClientOptions, NormalisedClientOptions } from '../../types/ClientOptions';
+import ClientOptions, { NormalisedClientOptions } from '../../types/ClientOptions';
import Platform from '../../platform';
import Message from '../types/message';
@@ -92,10 +92,7 @@ class Rest {
callback = params;
params = null;
} else {
- if (this.options.promises) {
- return Utils.promisify(this, 'stats', [params]) as Promise>;
- }
- callback = noop;
+ return Utils.promisify(this, 'stats', [params]) as Promise>;
}
}
const headers = Utils.defaultGetHeaders(this.options),
@@ -122,9 +119,7 @@ class Rest {
callback = params;
params = null;
} else {
- if (this.options.promises) {
- return Utils.promisify(this, 'time', [params]) as Promise;
- }
+ return Utils.promisify(this, 'time', [params]) as Promise;
}
}
@@ -187,12 +182,9 @@ class Rest {
: Utils.defaultPostHeaders(this.options, { format, protocolVersion: version });
if (callback === undefined) {
- if (this.options.promises) {
- return Utils.promisify(this, 'request', [method, path, version, params, body, customHeaders]) as Promise<
- HttpPaginatedResponse
- >;
- }
- callback = noop;
+ return Utils.promisify(this, 'request', [method, path, version, params, body, customHeaders]) as Promise<
+ HttpPaginatedResponse
+ >;
}
if (typeof body !== 'string') {
@@ -231,13 +223,8 @@ class Rest {
Logger.setLog(logOptions.level, logOptions.handler);
}
- static Promise = function (options: InternalClientOptions): Rest {
- options = Defaults.objectifyOptions(options);
- options.internal = { ...options.internal, promises: true };
- return new Rest(options);
- };
+ static Promise = Rest;
- static Callbacks = Rest;
static Platform = Platform;
static Crypto?: typeof Platform.Crypto;
static Message = Message;
diff --git a/src/common/lib/util/defaults.ts b/src/common/lib/util/defaults.ts
index 6f8f83123a..1b1fd275fe 100644
--- a/src/common/lib/util/defaults.ts
+++ b/src/common/lib/util/defaults.ts
@@ -257,7 +257,6 @@ export function normaliseOptions(options: InternalClientOptions): NormalisedClie
connectivityCheckParams,
connectivityCheckUrl,
headers,
- promises: options.internal?.promises ?? false,
};
}
diff --git a/src/common/types/ClientOptions.ts b/src/common/types/ClientOptions.ts
index ab279cfd65..1eeac34905 100644
--- a/src/common/types/ClientOptions.ts
+++ b/src/common/types/ClientOptions.ts
@@ -19,7 +19,6 @@ export type InternalClientOptions = Modify<
ClientOptions,
{
internal?: {
- promises?: boolean;
maxMessageSize?: number;
};
}
@@ -36,6 +35,5 @@ export type NormalisedClientOptions = Modify<
maxMessageSize: number;
connectivityCheckParams: Record | null;
headers: Record;
- promises: boolean;
}
>;
diff --git a/test/realtime/event_emitter.test.js b/test/realtime/event_emitter.test.js
index c20acbb885..1fac46d249 100644
--- a/test/realtime/event_emitter.test.js
+++ b/test/realtime/event_emitter.test.js
@@ -441,7 +441,7 @@ define(['shared_helper', 'chai'], function (helper, chai) {
describe('event_emitter_promise', function () {
it('whenState', function (done) {
- var realtime = helper.AblyRealtime({ internal: { promises: true } });
+ var realtime = helper.AblyRealtime();
var eventEmitter = realtime.connection;
eventEmitter
@@ -455,7 +455,7 @@ define(['shared_helper', 'chai'], function (helper, chai) {
});
it('once', function (done) {
- var realtime = helper.AblyRealtime({ internal: { promises: true } });
+ var realtime = helper.AblyRealtime();
var eventEmitter = realtime.connection;
eventEmitter
diff --git a/test/realtime/init.test.js b/test/realtime/init.test.js
index 4b85dd005f..f299dbefa2 100644
--- a/test/realtime/init.test.js
+++ b/test/realtime/init.test.js
@@ -409,26 +409,5 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
closeAndFinish(done, realtime);
});
});
-
- it('init_callbacks_promises', function (done) {
- try {
- var realtime,
- keyStr = helper.getTestApp().keys[0].keyStr,
- getOptions = function () {
- return { key: keyStr, autoConnect: false };
- };
-
- realtime = new Ably.Realtime.Promise(getOptions());
- expect(realtime.options.promises, 'Check promises default to true with promise constructor').to.be.ok;
-
- if (!isBrowser && typeof require == 'function') {
- realtime = new require('../../promises').Realtime(getOptions());
- expect(realtime.options.promises, 'Check promises default to true with promise require target').to.be.ok;
- }
- done();
- } catch (err) {
- done(err);
- }
- });
});
});
diff --git a/test/rest/init.test.js b/test/rest/init.test.js
index f4debf54f4..915a7a5a49 100644
--- a/test/rest/init.test.js
+++ b/test/rest/init.test.js
@@ -62,19 +62,5 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
var rest = helper.AblyRest({ clientId: false });
}, 'Check can’t init library with a boolean clientId').to.throw;
});
-
- it('Init promises', function () {
- var rest,
- keyStr = helper.getTestApp().keys[0].keyStr;
-
- rest = new Ably.Rest.Promise(keyStr);
- expect(rest.options.promises, 'Check promises default to true with promise constructor').to.be.ok;
-
- if (!isBrowser && typeof require == 'function') {
- var AblyPromises = require('../../promises');
- rest = new AblyPromises.Rest(keyStr);
- expect(rest.options.promises, 'Check promises default to true with promise require target').to.be.ok;
- }
- });
});
});
From 693804c5499691766de7b6580d39ffbe87887676 Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Tue, 27 Jun 2023 11:42:52 -0300
Subject: [PATCH 5/9] Remove the Promise static property
No longer needed now that, as of 2a2ed49, the promises API is the only
one we offer.
---
ably.d.ts | 8 --------
src/common/lib/client/realtime.ts | 2 --
src/common/lib/client/rest.ts | 2 --
test/common/modules/client_module.js | 4 ++--
test/realtime/api.test.js | 1 -
test/realtime/init.test.js | 8 ++++----
test/rest/api.test.js | 1 -
test/rest/init.test.js | 4 ++--
8 files changed, 8 insertions(+), 22 deletions(-)
diff --git a/ably.d.ts b/ably.d.ts
index 852b7ad5ab..c2c5843a14 100644
--- a/ably.d.ts
+++ b/ably.d.ts
@@ -1565,10 +1565,6 @@ declare namespace Types {
* A client that offers a simple stateless API to interact directly with Ably's REST API.
*/
class RestPromise extends RestBase {
- /**
- * A promisified version of the library (use this if you prefer to use Promises or async/await instead of callbacks)
- */
- static Promise: typeof Types.RestPromise;
/**
* An {@link Types.AuthPromise} object.
*/
@@ -1619,10 +1615,6 @@ declare namespace Types {
* A base class used internally for Realtime APIs.
*/
class RealtimeBase extends RestBase {
- /**
- * A promisified version of the library (use this if you prefer to use Promises or async/await instead of callbacks)
- */
- static Promise: typeof Types.RealtimePromise;
/**
* 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. 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.
*/
diff --git a/src/common/lib/client/realtime.ts b/src/common/lib/client/realtime.ts
index 58c21a5fcd..416f5748f6 100644
--- a/src/common/lib/client/realtime.ts
+++ b/src/common/lib/client/realtime.ts
@@ -35,8 +35,6 @@ class Realtime extends Rest {
this.connection.close();
}
- static Promise = Realtime;
-
static Utils = Utils;
static ConnectionManager = ConnectionManager;
static Platform = Platform;
diff --git a/src/common/lib/client/rest.ts b/src/common/lib/client/rest.ts
index 3c7776135b..d6e57416e2 100644
--- a/src/common/lib/client/rest.ts
+++ b/src/common/lib/client/rest.ts
@@ -223,8 +223,6 @@ class Rest {
Logger.setLog(logOptions.level, logOptions.handler);
}
- static Promise = Rest;
-
static Platform = Platform;
static Crypto?: typeof Platform.Crypto;
static Message = Message;
diff --git a/test/common/modules/client_module.js b/test/common/modules/client_module.js
index d0806d6d4b..7f2c990ea0 100644
--- a/test/common/modules/client_module.js
+++ b/test/common/modules/client_module.js
@@ -23,11 +23,11 @@ define(['ably', 'globals', 'test/common/modules/testapp_module'], function (Ably
}
function ablyRest(options) {
- return new Ably.Rest.Promise(ablyClientOptions(options));
+ return new Ably.Rest(ablyClientOptions(options));
}
function ablyRealtime(options) {
- return new Ably.Realtime.Promise(ablyClientOptions(options));
+ return new Ably.Realtime(ablyClientOptions(options));
}
return (module.exports = {
diff --git a/test/realtime/api.test.js b/test/realtime/api.test.js
index 36f3dd080b..951c0d0669 100644
--- a/test/realtime/api.test.js
+++ b/test/realtime/api.test.js
@@ -6,7 +6,6 @@ define(['ably', 'chai'], function (Ably, chai) {
describe('realtime/api', function () {
it('Client constructors', function () {
expect(typeof Ably.Realtime).to.equal('function');
- expect(typeof Ably.Realtime.Promise).to.equal('function');
});
it('Crypto', function () {
diff --git a/test/realtime/init.test.js b/test/realtime/init.test.js
index f299dbefa2..f617628641 100644
--- a/test/realtime/init.test.js
+++ b/test/realtime/init.test.js
@@ -54,7 +54,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
var realtime;
try {
var keyStr = helper.getTestApp().keys[0].keyStr;
- realtime = new helper.Ably.Realtime.Promise(keyStr);
+ realtime = new helper.Ably.Realtime(keyStr);
try {
expect(realtime.options.key).to.equal(keyStr);
@@ -83,7 +83,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
}
var tokenStr = tokenDetails.token,
- realtime = new helper.Ably.Realtime.Promise(tokenStr);
+ realtime = new helper.Ably.Realtime(tokenStr);
try {
expect(realtime.options.token).to.equal(tokenStr);
@@ -208,7 +208,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
try {
var keyStr = helper.getTestApp().keys[0].keyStr;
expect(function () {
- realtime = new helper.Ably.Realtime.Promise({ key: keyStr, useTokenAuth: false, clientId: 'foo' });
+ realtime = new helper.Ably.Realtime({ key: keyStr, useTokenAuth: false, clientId: 'foo' });
}).to.throw;
done();
} catch (err) {
@@ -222,7 +222,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
/* want to check the default host when no custom environment or custom
* host set, so not using helpers.realtime this time, which will use a
* test env */
- var realtime = new Ably.Realtime.Promise({ key: 'not_a.real:key', autoConnect: false });
+ var realtime = new Ably.Realtime({ key: 'not_a.real:key', autoConnect: false });
var defaultHost = realtime.connection.connectionManager.httpHosts[0];
expect(defaultHost).to.equal('rest.ably.io', 'Verify correct default rest host chosen');
realtime.close();
diff --git a/test/rest/api.test.js b/test/rest/api.test.js
index 02950ca883..fcc19aa3df 100644
--- a/test/rest/api.test.js
+++ b/test/rest/api.test.js
@@ -6,7 +6,6 @@ define(['ably', 'chai'], function (Ably, chai) {
describe('rest/api', function () {
it('Client constructors', function () {
expect(typeof Ably.Rest).to.equal('function');
- expect(typeof Ably.Rest.Promise).to.equal('function');
});
it('Crypto', function () {
diff --git a/test/rest/init.test.js b/test/rest/init.test.js
index 915a7a5a49..2d4b316dde 100644
--- a/test/rest/init.test.js
+++ b/test/rest/init.test.js
@@ -18,7 +18,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
it('Init with key string', function () {
var keyStr = helper.getTestApp().keys[0].keyStr;
- var rest = new helper.Ably.Rest.Promise(keyStr);
+ var rest = new helper.Ably.Rest(keyStr);
expect(rest.options.key).to.equal(keyStr);
});
@@ -30,7 +30,7 @@ define(['ably', 'shared_helper', 'chai'], function (Ably, helper, chai) {
var tokenDetails = await rest.auth.requestToken(null, testKeyOpts);
var tokenStr = tokenDetails.token,
- rest = new helper.Ably.Rest.Promise(tokenStr);
+ rest = new helper.Ably.Rest(tokenStr);
expect(rest.options.token).to.equal(tokenStr);
});
From 6cf248fbc18434629def4fa7a37b006a396afd76 Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Tue, 27 Jun 2023 09:11:02 -0300
Subject: [PATCH 6/9] Remove promises.js / .d.ts
Motivation as in 693804c.
---
package.json | 2 --
promises.d.ts | 14 --------------
promises.js | 32 --------------------------------
3 files changed, 48 deletions(-)
delete mode 100644 promises.d.ts
delete mode 100644 promises.js
diff --git a/package.json b/package.json
index c0b79298eb..1c0a2d9914 100644
--- a/package.json
+++ b/package.json
@@ -18,8 +18,6 @@
"files": [
"build/**",
"ably.d.ts",
- "promises.d.ts",
- "promises.js",
"resources/**"
],
"dependencies": {
diff --git a/promises.d.ts b/promises.d.ts
deleted file mode 100644
index 0c79c9e897..0000000000
--- a/promises.d.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import Ably = require('./ably');
-
-/**
- * The `Rest` object offers a simple stateless API to interact directly with Ably's REST API.
- */
-export declare class Rest extends Ably.Rest.Promise {}
-/**
- * A client that extends the functionality of {@link Rest} and provides additional realtime-specific features.
- */
-export declare class Realtime extends Ably.Realtime.Promise {}
-
-// Re-export the Types namespace.
-import Types = Ably.Types;
-export { Types };
diff --git a/promises.js b/promises.js
deleted file mode 100644
index c40986d4a4..0000000000
--- a/promises.js
+++ /dev/null
@@ -1,32 +0,0 @@
-'use strict';
-function promisifyOptions(options) {
- if (typeof options == 'string') {
- options = options.indexOf(':') == -1 ? { token: options } : { key: options };
- }
- if (options.internal === undefined) {
- options.internal = { promises: true }
- } else {
- options.internal.promises = true
- }
- return options;
-}
-
-/* Please note that the file imported below is only generated after running
- * the build task. */
-// eslint-disable-next-line @typescript-eslint/no-var-requires
-var Ably = require('./build/ably-node');
-
-var RestPromise = function (options) {
- return new Ably.Rest(promisifyOptions(options));
-};
-Object.assign(RestPromise, Ably.Rest);
-
-var RealtimePromise = function (options) {
- return new Ably.Realtime(promisifyOptions(options));
-};
-Object.assign(RealtimePromise, Ably.Realtime);
-
-module.exports = {
- Rest: RestPromise,
- Realtime: RealtimePromise,
-};
From 8c3afa4915513ffe125cba9e211201a1193b566f Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Mon, 26 Jun 2023 17:27:07 -0300
Subject: [PATCH 7/9] Move RealtimeChannelPromise declaration directly below
RealtimeChannelBase
Preparation for merging the *Base and *Promise classes.
---
ably.d.ts | 72 +++++++++++++++++++++++++++----------------------------
1 file changed, 36 insertions(+), 36 deletions(-)
diff --git a/ably.d.ts b/ably.d.ts
index c2c5843a14..be583fa897 100644
--- a/ably.d.ts
+++ b/ably.d.ts
@@ -1999,42 +1999,6 @@ declare namespace Types {
unsubscribe(): void;
}
- /**
- * Optional parameters for message publishing.
- */
- type PublishOptions = {
- /**
- * See [here](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes).
- */
- quickAck?: boolean;
- };
-
- /**
- * Contains properties to filter messages with when calling {@link RealtimeChannelPromise.subscribe | `RealtimeChannelPromise.subscribe()`}.
- */
- type MessageFilter = {
- /**
- * Filters messages by a specific message `name`.
- */
- name?: string;
- /**
- * Filters messages by a specific `extras.ref.timeserial` value.
- */
- refTimeserial?: string;
- /**
- * Filters messages by a specific `extras.ref.type` value.
- */
- refType?: string;
- /**
- * Filters messages based on whether they contain an `extras.ref`.
- */
- isRef?: boolean;
- /**
- * Filters messages by a specific message `clientId`.
- */
- clientId: string;
- };
-
/**
* Enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the {@link RealtimePresencePromise} object of a channel.
*/
@@ -2130,6 +2094,42 @@ declare namespace Types {
whenState(targetState: ChannelState): Promise;
}
+ /**
+ * Optional parameters for message publishing.
+ */
+ type PublishOptions = {
+ /**
+ * See [here](https://faqs.ably.com/why-are-some-rest-publishes-on-a-channel-slow-and-then-typically-faster-on-subsequent-publishes).
+ */
+ quickAck?: boolean;
+ };
+
+ /**
+ * Contains properties to filter messages with when calling {@link RealtimeChannelPromise.subscribe | `RealtimeChannelPromise.subscribe()`}.
+ */
+ type MessageFilter = {
+ /**
+ * Filters messages by a specific message `name`.
+ */
+ name?: string;
+ /**
+ * Filters messages by a specific `extras.ref.timeserial` value.
+ */
+ refTimeserial?: string;
+ /**
+ * Filters messages by a specific `extras.ref.type` value.
+ */
+ refType?: string;
+ /**
+ * Filters messages based on whether they contain an `extras.ref`.
+ */
+ isRef?: boolean;
+ /**
+ * Filters messages by a specific message `clientId`.
+ */
+ clientId: string;
+ };
+
/**
* Creates and destroys {@link ChannelBase} and {@link RealtimeChannelBase} objects.
*/
From 69c35f14fd82e8b33f9d88ad78180db3d3acc888 Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Tue, 27 Jun 2023 15:49:24 -0300
Subject: [PATCH 8/9] Remove Realtime < Rest inheritance in public API
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
I want to merge the following classes together:
- RestBase and RestPromise into a class named Rest
- RealtimeBase and RealtimePromise into a class named Realtime
However, I need to decide what to do about the inheritance of
RealtimeBase from RestBase. The obvious thing to do would be to make
Realtime inherit from Rest, but this won’t work because
RealtimeChannel’s type declaration does not include a `status()`
function and hence Realtime.channels cannot satisfy the type of
Rest.channels.
So, since the IDL does not mention any inheritance relation between the
REST and Realtime classes, I’m going to sever this connection in the
type declarations. (We can consider the fact that _internally_ there is
inheritance to be an implementation detail.)
---
ably.d.ts | 26 +++++++++++++++++++++++++-
1 file changed, 25 insertions(+), 1 deletion(-)
diff --git a/ably.d.ts b/ably.d.ts
index be583fa897..4567547545 100644
--- a/ably.d.ts
+++ b/ably.d.ts
@@ -1614,7 +1614,31 @@ declare namespace Types {
/**
* A base class used internally for Realtime APIs.
*/
- class RealtimeBase extends RestBase {
+ class RealtimeBase {
+ /**
+ * Construct a client object using an Ably {@link Types.ClientOptions} object.
+ *
+ * @param options - A {@link Types.ClientOptions} object to configure the client connection to Ably.
+ */
+ constructor(options: Types.ClientOptions);
+ /**
+ * Constructs a client object using an Ably API key or token string.
+ *
+ * @param keyOrToken - The Ably API key or token string used to validate the client.
+ */
+ constructor(keyOrToken: string);
+ /**
+ * The cryptographic functions available in the library.
+ */
+ static Crypto: Types.Crypto;
+ /**
+ * Static utilities related to messages.
+ */
+ static Message: Types.MessageStatic;
+ /**
+ * Static utilities related to presence messages.
+ */
+ static PresenceMessage: Types.PresenceMessageStatic;
/**
* 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. 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.
*/
From 6cb717990d5a993ebd6e0430b2b2629660c27cf8 Mon Sep 17 00:00:00 2001
From: Lawrence Forooghian
Date: Thu, 22 Jun 2023 16:59:45 -0300
Subject: [PATCH 9/9] Merge *Base and *Promise classes
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The *Base classes are no longer needed now that we’ve removed the
*Callbacks classes.
---
ably.d.ts | 233 +++++++++++++++++++++++-------------------------------
1 file changed, 99 insertions(+), 134 deletions(-)
diff --git a/ably.d.ts b/ably.d.ts
index 4567547545..a276fade46 100644
--- a/ably.d.ts
+++ b/ably.d.ts
@@ -41,7 +41,7 @@ declare namespace Types {
type FAILED = 'failed';
}
/**
- * Describes the possible states of a {@link ChannelBase} or {@link RealtimeChannelBase} object.
+ * Describes the possible states of a {@link Channel} or {@link RealtimeChannel} object.
*/
type ChannelState =
| ChannelState.FAILED
@@ -90,7 +90,7 @@ declare namespace Types {
type UPDATE = 'update';
}
/**
- * Describes the events emitted by a {@link ChannelBase} or {@link RealtimeChannelBase} object. An event is either an `UPDATE` or a {@link ChannelState}.
+ * Describes the events emitted by a {@link Channel} or {@link RealtimeChannel} object. An event is either an `UPDATE` or a {@link ChannelState}.
*/
type ChannelEvent =
| ChannelEvent.FAILED
@@ -123,7 +123,7 @@ declare namespace Types {
*/
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 ConnectionBase.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).
+ * 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';
/**
@@ -131,16 +131,16 @@ declare namespace Types {
*/
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 ConnectionBase.connect | `connect()`}, which results in a new connection.
+ * 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 ConnectionBase.connect | `connect()`}.
+ * 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 ConnectionBase} object states.
+ * Describes the realtime {@link Connection} object states.
*/
type ConnectionState =
| ConnectionState.INITIALIZED
@@ -173,7 +173,7 @@ declare namespace Types {
*/
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 ConnectionBase.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).
+ * 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';
/**
@@ -181,11 +181,11 @@ declare namespace Types {
*/
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 ConnectionBase.connect | `connect()`}, which results in a new connection.
+ * 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 ConnectionBase.connect | `connect()`}.
+ * 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';
/**
@@ -194,7 +194,7 @@ declare namespace Types {
type UPDATE = 'update';
}
/**
- * Describes the events emitted by a {@link ConnectionBase} object. An event is either an `UPDATE` or a {@link ConnectionState}.
+ * Describes the events emitted by a {@link Connection} object. An event is either an `UPDATE` or a {@link ConnectionState}.
*/
type ConnectionEvent =
| ConnectionEvent.INITIALIZED
@@ -296,7 +296,7 @@ declare namespace Types {
type Transport = 'web_socket' | 'xhr_streaming' | 'xhr_polling' | 'comet';
/**
- * Contains the details of a {@link ChannelBase} or {@link RealtimeChannelBase} object such as its ID and {@link ChannelStatus}.
+ * Contains the details of a {@link Channel} or {@link RealtimeChannel} object such as its ID and {@link ChannelStatus}.
*/
interface ChannelDetails {
/**
@@ -310,7 +310,7 @@ declare namespace Types {
}
/**
- * Contains the status of a {@link ChannelBase} or {@link RealtimeChannelBase} object such as whether it is active and its {@link ChannelOccupancy}.
+ * Contains the status of a {@link Channel} or {@link RealtimeChannel} object such as whether it is active and its {@link ChannelOccupancy}.
*/
interface ChannelStatus {
/**
@@ -324,7 +324,7 @@ declare namespace Types {
}
/**
- * Contains the metrics of a {@link ChannelBase} or {@link RealtimeChannelBase} object.
+ * Contains the metrics of a {@link Channel} or {@link RealtimeChannel} object.
*/
interface ChannelOccupancy {
/**
@@ -334,7 +334,7 @@ declare namespace Types {
}
/**
- * Contains the metrics associated with a {@link ChannelBase} or {@link RealtimeChannelBase}, such as the number of publishers, subscribers and connections it has.
+ * Contains the metrics associated with a {@link Channel} or {@link RealtimeChannel}, such as the number of publishers, subscribers and connections it has.
*/
interface ChannelMetrics {
/**
@@ -364,11 +364,11 @@ declare namespace Types {
}
/**
- * Passes additional client-specific properties to the REST {@link RestBase.constructor | `constructor()`} or the Realtime {@link RealtimeBase.constructor | `constructor()`}.
+ * Passes additional client-specific properties to the REST {@link Rest.constructor | `constructor()`} or the Realtime {@link Realtime.constructor | `constructor()`}.
*/
interface ClientOptions 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 ConnectionBase.connect | `connect()`} method. The default is `true`.
+ * 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`
*/
@@ -704,7 +704,7 @@ declare namespace Types {
}
/**
- * Sets the properties to configure encryption for a {@link ChannelBase} or {@link RealtimeChannelBase} object.
+ * Sets the properties to configure encryption for a {@link Channel} or {@link RealtimeChannel} object.
*/
interface CipherParams {
/**
@@ -890,7 +890,7 @@ declare namespace Types {
}
/**
- * Contains the properties of a request for a token to Ably. Tokens are generated using {@link AuthPromise.requestToken}.
+ * Contains the properties of a request for a token to Ably. Tokens are generated using {@link Auth.requestToken}.
*/
interface TokenRequest {
/**
@@ -971,7 +971,7 @@ declare namespace Types {
type ChannelModes = Array;
/**
- * Passes additional properties to a {@link ChannelBase} or {@link RealtimeChannelBase} object, such as encryption, {@link ChannelMode} and channel parameters.
+ * Passes additional properties to a {@link Channel} or {@link RealtimeChannel} object, such as encryption, {@link ChannelMode} and channel parameters.
*/
interface ChannelOptions {
/**
@@ -989,7 +989,7 @@ declare namespace Types {
}
/**
- * Passes additional properties to a {@link RealtimeChannelBase} name to produce a new derived channel
+ * Passes additional properties to a {@link RealtimeChannel} name to produce a new derived channel
*/
interface DeriveOptions {
/**
@@ -1001,8 +1001,8 @@ declare namespace Types {
/**
* The `RestHistoryParams` interface describes the parameters accepted by the following methods:
*
- * - {@link PresencePromise.history}
- * - {@link ChannelPromise.history}
+ * - {@link Presence.history}
+ * - {@link Channel.history}
*/
interface RestHistoryParams {
/**
@@ -1030,7 +1030,7 @@ declare namespace Types {
}
/**
- * The `RestPresenceParams` interface describes the parameters accepted by {@link PresencePromise.get}.
+ * The `RestPresenceParams` interface describes the parameters accepted by {@link Presence.get}.
*/
interface RestPresenceParams {
/**
@@ -1050,7 +1050,7 @@ declare namespace Types {
}
/**
- * The `RealtimePresenceParams` interface describes the parameters accepted by {@link RealtimePresencePromise.get}.
+ * The `RealtimePresenceParams` interface describes the parameters accepted by {@link RealtimePresence.get}.
*/
interface RealtimePresenceParams {
/**
@@ -1072,8 +1072,8 @@ declare namespace Types {
/**
* The `RealtimeHistoryParams` interface describes the parameters accepted by the following methods:
*
- * - {@link RealtimePresencePromise.history}
- * - {@link RealtimeChannelPromise.history}
+ * - {@link RealtimePresence.history}
+ * - {@link RealtimeChannel.history}
*/
interface RealtimeHistoryParams {
/**
@@ -1105,7 +1105,7 @@ declare namespace Types {
}
/**
- * Contains state change information emitted by {@link ChannelBase} and {@link RealtimeChannelBase} objects.
+ * Contains state change information emitted by {@link Channel} and {@link RealtimeChannel} objects.
*/
interface ChannelStateChange {
/**
@@ -1127,7 +1127,7 @@ declare namespace Types {
}
/**
- * Contains {@link ConnectionState} change information emitted by the {@link ConnectionBase} object.
+ * Contains {@link ConnectionState} change information emitted by the {@link Connection} object.
*/
interface ConnectionStateChange {
/**
@@ -1300,8 +1300,8 @@ declare namespace Types {
/**
* The `DeviceRegistrationParams` interface describes the parameters accepted by the following methods:
*
- * - {@link PushDeviceRegistrationsPromise.list}
- * - {@link PushDeviceRegistrationsPromise.removeWhere}
+ * - {@link PushDeviceRegistrations.list}
+ * - {@link PushDeviceRegistrations.removeWhere}
*/
interface DeviceRegistrationParams {
/**
@@ -1325,8 +1325,8 @@ declare namespace Types {
/**
* The `PushChannelSubscriptionParams` interface describes the parameters accepted by the following methods:
*
- * - {@link PushChannelSubscriptionsPromise.list}
- * - {@link PushChannelSubscriptionsPromise.removeWhere}
+ * - {@link PushChannelSubscriptions.list}
+ * - {@link PushChannelSubscriptions.removeWhere}
*/
interface PushChannelSubscriptionParams {
/**
@@ -1348,7 +1348,7 @@ declare namespace Types {
}
/**
- * The `PushChannelsParams` interface describes the parameters accepted by {@link PushChannelSubscriptionsPromise.listChannels}.
+ * The `PushChannelsParams` interface describes the parameters accepted by {@link PushChannelSubscriptions.listChannels}.
*/
interface PushChannelsParams {
/**
@@ -1360,8 +1360,8 @@ declare namespace Types {
/**
* The `StatsParams` interface describes the parameters accepted by the following methods:
*
- * - {@link RestPromise.stats}
- * - {@link RealtimePromise.stats}
+ * - {@link Rest.stats}
+ * - {@link Realtime.stats}
*/
interface StatsParams {
/**
@@ -1398,19 +1398,19 @@ declare namespace Types {
// Common Listeners
/**
- * A callback which returns only a single argument, used for {@link RealtimeChannelBase} subscriptions.
+ * A callback which returns only a single argument, used for {@link RealtimeChannel} subscriptions.
*
* @param message - The message which triggered the callback.
*/
type messageCallback = (message: T) => void;
/**
- * The callback used for the events emitted by {@link RealtimeChannelBase}.
+ * The callback used for the events emitted by {@link RealtimeChannel}.
*
* @param changeStateChange - The state change that occurred.
*/
type channelEventCallback = (changeStateChange: ChannelStateChange) => void;
/**
- * The callback used for the events emitted by {@link ConnectionBase}.
+ * The callback used for the events emitted by {@link Connection}.
*
* @param connectionStateChange - The state change that occurred.
*/
@@ -1456,7 +1456,7 @@ declare namespace Types {
// that returns a Promise if desired, EventEmitter uses method overloading to
// present both methods
/**
- * A generic interface for event registration and delivery used in a number of the types in the Realtime client library. For example, the {@link ConnectionBase} object emits events for connection state using the `EventEmitter` pattern.
+ * A generic interface for event registration and delivery used in a number of the types in the Realtime client library. For example, the {@link Connection} object emits events for connection state using the `EventEmitter` pattern.
*/
class EventEmitter {
/**
@@ -1532,9 +1532,9 @@ declare namespace Types {
// Classes
/**
- * The `RestBase` class acts as a base class for the {@link RestPromise} class.
+ * A client that offers a simple stateless API to interact directly with Ably's REST API.
*/
- class RestBase {
+ class Rest {
/**
* Construct a client object using an Ably {@link Types.ClientOptions} object.
*
@@ -1559,20 +1559,15 @@ declare namespace Types {
* Static utilities related to presence messages.
*/
static PresenceMessage: Types.PresenceMessageStatic;
- }
- /**
- * A client that offers a simple stateless API to interact directly with Ably's REST API.
- */
- class RestPromise extends RestBase {
/**
- * An {@link Types.AuthPromise} object.
+ * An {@link Types.Auth} object.
*/
- auth: Types.AuthPromise;
+ auth: Types.Auth;
/**
* A {@link Types.Channels} object.
*/
- channels: Types.Channels;
+ channels: Types.Channels;
/**
* Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
*
@@ -1606,15 +1601,15 @@ declare namespace Types {
*/
time(): Promise;
/**
- * A {@link Types.PushPromise} object.
+ * A {@link Types.Push} object.
*/
- push: Types.PushPromise;
+ push: Types.Push;
}
/**
- * A base class used internally for Realtime APIs.
+ * A client that extends the functionality of {@link Rest} and provides additional realtime-specific features.
*/
- class RealtimeBase {
+ class Realtime {
/**
* Construct a client object using an Ably {@link Types.ClientOptions} object.
*
@@ -1644,31 +1639,26 @@ declare namespace Types {
*/
clientId: string;
/**
- * Calls {@link Types.ConnectionBase.close | `connection.close()`} and causes the connection to close, entering the closing state. Once closed, the library will not attempt to re-establish the connection without an explicit call to {@link Types.ConnectionBase.connect | `connect()`}.
+ * Calls {@link Types.Connection.close | `connection.close()`} and causes the connection to close, entering the closing state. Once closed, the library will not attempt to re-establish the connection without an explicit call to {@link Types.Connection.connect | `connect()`}.
*/
close(): void;
/**
- * Calls {@link Types.ConnectionBase.connect | `connection.connect()`} and causes the connection to open, entering the connecting state. Explicitly calling `connect()` is unnecessary unless the {@link Types.ClientOptions.autoConnect} property is disabled.
+ * Calls {@link Types.Connection.connect | `connection.connect()`} and causes the connection to open, entering the connecting state. Explicitly calling `connect()` is unnecessary unless the {@link Types.ClientOptions.autoConnect} property is disabled.
*/
connect(): void;
- }
- /**
- * A client that extends the functionality of {@link RestPromise} and provides additional realtime-specific features.
- */
- class RealtimePromise extends RealtimeBase {
/**
- * An {@link Types.AuthPromise} object.
+ * An {@link Types.Auth} object.
*/
- auth: Types.AuthPromise;
+ auth: Types.Auth;
/**
* A {@link Types.Channels} object.
*/
- channels: Types.Channels;
+ channels: Types.Channels;
/**
- * A {@link Types.ConnectionPromise} object.
+ * A {@link Types.Connection} object.
*/
- connection: Types.ConnectionPromise;
+ connection: Types.Connection;
/**
* Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support.
*
@@ -1702,25 +1692,20 @@ declare namespace Types {
*/
time(): Promise;
/**
- * A {@link Types.PushPromise} object.
+ * A {@link Types.Push} object.
*/
- push: Types.PushPromise;
+ push: Types.Push;
}
/**
- * The `AuthBase` class acts as a base class for the {@link AuthPromise} class.
+ * Creates Ably {@link TokenRequest} objects and obtains Ably Tokens from Ably to subsequently issue to less trusted clients.
*/
- class AuthBase {
+ class Auth {
/**
* 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;
- }
- /**
- * Creates Ably {@link TokenRequest} objects and obtains Ably Tokens from Ably to subsequently issue to less trusted clients.
- */
- class AuthPromise extends AuthBase {
/**
* Instructs the library to get a new token immediately. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained. Also stores any {@link TokenParams} and {@link AuthOptions} passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. Any {@link TokenParams} and {@link AuthOptions} objects passed in entirely replace, as opposed to being merged with, the current client library saved values.
*
@@ -1750,7 +1735,7 @@ declare namespace Types {
/**
* Enables the retrieval of the current and historic presence set for a channel.
*/
- class PresencePromise {
+ class Presence {
/**
* Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns a {@link Types.PaginatedResult} object, containing an array of {@link PresenceMessage} objects.
*
@@ -1768,9 +1753,9 @@ declare namespace Types {
}
/**
- * The `RealtimePresenceBase` class acts as a base class for the {@link RealtimePresencePromise} class.
+ * Enables the presence set to be entered and subscribed to, and the historic presence set to be retrieved for a channel.
*/
- class RealtimePresenceBase {
+ class RealtimePresence {
/**
* Indicates whether the presence set synchronization between Ably and the clients on the channel has been completed. Set to `true` when the sync is complete.
*/
@@ -1811,12 +1796,7 @@ declare namespace Types {
* Deregisters all listeners currently receiving {@link PresenceMessage} for the channel.
*/
unsubscribe(): void;
- }
- /**
- * Enables the presence set to be entered and subscribed to, and the historic presence set to be retrieved for a channel.
- */
- class RealtimePresencePromise extends RealtimePresenceBase {
/**
* Retrieves the current members present on the channel and the metadata for each member, such as their {@link PresenceAction} and ID. Returns an array of {@link PresenceMessage} objects.
*
@@ -1836,7 +1816,7 @@ declare namespace Types {
*
* @param action - A {@link PresenceAction} or an array of {@link PresenceAction | `PresenceAction`s} to register the listener for.
* @param listener - An event listener function.
- * @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
+ * @returns A promise which resolves upon success of the channel {@link RealtimeChannel.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
subscribe(
action: PresenceAction | Array,
@@ -1846,7 +1826,7 @@ declare namespace Types {
* Registers a listener that is called each time a {@link PresenceMessage} is received on the channel, such as a new member entering the presence set.
*
* @param listener - An event listener function.
- * @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
+ * @returns A promise which resolves upon success of the channel {@link RealtimeChannel.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
subscribe(listener?: messageCallback): Promise;
/**
@@ -1897,23 +1877,18 @@ declare namespace Types {
}
/**
- * The `ChannelBase` class acts as a base class for the {@link ChannelPromise} class.
+ * Enables messages to be published and historic messages to be retrieved for a channel.
*/
- class ChannelBase {
+ class Channel {
/**
* The channel name.
*/
name: string;
- }
- /**
- * Enables messages to be published and historic messages to be retrieved for a channel.
- */
- class ChannelPromise extends ChannelBase {
/**
- * A {@link PresencePromise} object.
+ * A {@link Presence} object.
*/
- presence: PresencePromise;
+ presence: Presence;
/**
* Retrieves a {@link Types.PaginatedResult} object, containing an array of historical {@link Message} objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.
*
@@ -1955,9 +1930,9 @@ declare namespace Types {
}
/**
- * The `RealtimeChannelBase` class acts as a base class for the {@link RealtimeChannelPromise} class.
+ * Enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the {@link RealtimePresence} object of a channel.
*/
- class RealtimeChannelBase extends EventEmitter {
+ class RealtimeChannel extends EventEmitter {
/**
* The channel name.
*/
@@ -2021,18 +1996,13 @@ declare namespace Types {
* Deregisters all listeners to messages on this channel. This removes all earlier subscriptions.
*/
unsubscribe(): void;
- }
- /**
- * Enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the {@link RealtimePresencePromise} object of a channel.
- */
- class RealtimeChannelPromise extends RealtimeChannelBase {
/**
- * A {@link RealtimePresencePromise} object.
+ * A {@link RealtimePresence} object.
*/
- presence: RealtimePresencePromise;
+ presence: RealtimePresence;
/**
- * Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using {@link RealtimeChannelPromise.subscribe | `subscribe()`}. Any resulting channel state change will be emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. As a convenience, `attach()` is called implicitly if {@link RealtimeChannelPromise.subscribe | `subscribe()`} for the channel is called, or {@link RealtimePresencePromise.enter | `enter()`} or {@link RealtimePresencePromise.subscribe | `subscribe()`} are called on the {@link RealtimePresencePromise} object for this channel.
+ * Attach to this channel ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using {@link RealtimeChannel.subscribe | `subscribe()`}. Any resulting channel state change will be emitted to any listeners registered using the {@link EventEmitter.on | `on()`} or {@link EventEmitter.once | `once()`} methods. As a convenience, `attach()` is called implicitly if {@link RealtimeChannel.subscribe | `subscribe()`} for the channel is called, or {@link RealtimePresence.enter | `enter()`} or {@link RealtimePresence.subscribe | `subscribe()`} are called on the {@link RealtimePresence} object for this channel.
*
* @returns A promise which resolves upon success of the operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
@@ -2062,7 +2032,7 @@ declare namespace Types {
*
* @param event - The event name.
* @param listener - An event listener function.
- * @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
+ * @returns A promise which resolves upon success of the channel {@link RealtimeChannel.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
subscribe(event: string, listener?: messageCallback): Promise;
/**
@@ -2070,7 +2040,7 @@ declare namespace Types {
*
* @param events - An array of event names.
* @param listener - An event listener function.
- * @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
+ * @returns A promise which resolves upon success of the channel {@link RealtimeChannel.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
subscribe(events: Array, listener?: messageCallback): Promise;
/**
@@ -2078,14 +2048,14 @@ declare namespace Types {
*
* @param filter - A {@link MessageFilter}.
* @param listener - An event listener function.
- * @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
+ * @returns A promise which resolves upon success of the channel {@link RealtimeChannel.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
subscribe(filter: MessageFilter, listener?: messageCallback): Promise;
/**
* Registers a listener for messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel.
*
* @param callback - An event listener function.
- * @returns A promise which resolves upon success of the channel {@link RealtimeChannelPromise.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
+ * @returns A promise which resolves upon success of the channel {@link RealtimeChannel.attach | `attach()`} operation and rejects with an {@link ErrorInfo} object upon its failure.
*/
subscribe(callback: messageCallback): Promise;
/**
@@ -2129,7 +2099,7 @@ declare namespace Types {
};
/**
- * Contains properties to filter messages with when calling {@link RealtimeChannelPromise.subscribe | `RealtimeChannelPromise.subscribe()`}.
+ * Contains properties to filter messages with when calling {@link RealtimeChannel.subscribe | `RealtimeChannel.subscribe()`}.
*/
type MessageFilter = {
/**
@@ -2155,15 +2125,15 @@ declare namespace Types {
};
/**
- * Creates and destroys {@link ChannelBase} and {@link RealtimeChannelBase} objects.
+ * Creates and destroys {@link Channel} and {@link RealtimeChannel} objects.
*/
class Channels {
/**
- * Creates a new {@link ChannelBase} or {@link RealtimeChannelBase} object, with the specified {@link ChannelOptions}, or returns the existing channel object.
+ * Creates a new {@link Channel} or {@link RealtimeChannel} object, with the specified {@link ChannelOptions}, or returns the existing channel object.
*
* @param name - The channel name.
* @param channelOptions - A {@link ChannelOptions} object.
- * @returns A {@link ChannelBase} or {@link RealtimeChannelBase} object.
+ * @returns A {@link Channel} or {@link RealtimeChannel} object.
*/
get(name: string, channelOptions?: ChannelOptions): T;
/**
@@ -2172,17 +2142,17 @@ declare namespace Types {
* to receive only part of the data from the channel.
* See the [announcement post](https://pages.ably.com/subscription-filters-preview) for more information.
*
- * Creates a new {@link ChannelBase} or {@link RealtimeChannelBase} object, with the specified channel {@link DeriveOptions}
+ * Creates a new {@link Channel} or {@link RealtimeChannel} object, with the specified channel {@link DeriveOptions}
* and {@link ChannelOptions}, or returns the existing channel object.
*
* @param name - The channel name.
* @param deriveOptions - A {@link DeriveOptions} object.
* @param channelOptions - A {@link ChannelOptions} object.
- * @returns A {@link RealtimeChannelBase} object.
+ * @returns A {@link RealtimeChannel} object.
*/
getDerived(name: string, deriveOptions: DeriveOptions, channelOptions?: ChannelOptions): T;
/**
- * Releases a {@link ChannelBase} or {@link RealtimeChannelBase} object, deleting it, and enabling it to be garbage collected. It also removes any listeners associated with the channel. To release a channel, the {@link ChannelState} must be `INITIALIZED`, `DETACHED`, or `FAILED`.
+ * Releases a {@link Channel} or {@link RealtimeChannel} object, deleting it, and enabling it to be garbage collected. It also removes any listeners associated with the channel. To release a channel, the {@link ChannelState} must be `INITIALIZED`, `DETACHED`, or `FAILED`.
*
* @param name - The channel name.
*/
@@ -2397,9 +2367,9 @@ declare namespace Types {
}
/**
- * The `ConnectionBase` class acts as a base class for the {@link ChannelPromise} class.
+ * Enables the management of a connection to Ably.
*/
- class ConnectionBase extends EventEmitter {
+ class Connection extends EventEmitter {
/**
* An {@link ErrorInfo} object describing the last error received if a connection failure occurs.
*/
@@ -2425,19 +2395,14 @@ declare namespace Types {
*/
readonly state: ConnectionState;
/**
- * Causes the connection to close, entering the {@link ConnectionState.CLOSING} state. Once closed, the library does not attempt to re-establish the connection without an explicit call to {@link ConnectionBase.connect | `connect()`}.
+ * Causes the connection to close, entering the {@link ConnectionState.CLOSING} state. Once closed, the library does not attempt to re-establish the connection without an explicit call to {@link Connection.connect | `connect()`}.
*/
close(): void;
/**
* Explicitly calling `connect()` is unnecessary unless the `autoConnect` attribute of the {@link ClientOptions} object is `false`. Unless already connected or connecting, this method causes the connection to open, entering the {@link ConnectionState.CONNECTING} state.
*/
connect(): void;
- }
- /**
- * Enables the management of a connection to Ably.
- */
- class ConnectionPromise extends ConnectionBase {
/**
* When connected, sends a heartbeat ping to the Ably server and executes the callback with any error and the response time in milliseconds when a heartbeat ping request is echoed from the server. This can be useful for measuring true round-trip latency to the connected Ably server.
*
@@ -2561,25 +2526,25 @@ declare namespace Types {
/**
* Enables a device to be registered and deregistered from receiving push notifications.
*/
- class PushPromise {
+ class Push {
/**
- * A {@link PushAdminPromise | `PushAdmin`} object.
+ * A {@link PushAdmin} object.
*/
- admin: PushAdminPromise;
+ admin: PushAdmin;
}
/**
* Enables the management of device registrations and push notification subscriptions. Also enables the publishing of push notifications to devices.
*/
- class PushAdminPromise {
+ class PushAdmin {
/**
- * A {@link PushDeviceRegistrationsPromise} object.
+ * A {@link PushDeviceRegistrations} object.
*/
- deviceRegistrations: PushDeviceRegistrationsPromise;
+ deviceRegistrations: PushDeviceRegistrations;
/**
- * A {@link PushChannelSubscriptionsPromise} object.
+ * A {@link PushChannelSubscriptions} object.
*/
- channelSubscriptions: PushChannelSubscriptionsPromise;
+ channelSubscriptions: PushChannelSubscriptions;
/**
* Sends a push notification directly to a device, or a group of devices sharing the same `clientId`.
*
@@ -2593,7 +2558,7 @@ declare namespace Types {
/**
* Enables the management of push notification registrations with Ably.
*/
- class PushDeviceRegistrationsPromise {
+ class PushDeviceRegistrations {
/**
* Registers or updates a {@link DeviceDetails} object with Ably. Returns the new, or updated {@link DeviceDetails} object.
*
@@ -2648,7 +2613,7 @@ declare namespace Types {
/**
* Enables device push channel subscriptions.
*/
- class PushChannelSubscriptionsPromise {
+ class PushChannelSubscriptions {
/**
* Subscribes a device, or a group of devices sharing the same `clientId` to push notifications on a channel. Returns a {@link PushChannelSubscription} object.
*
@@ -2690,9 +2655,9 @@ declare namespace Types {
/**
* A client that offers a simple stateless API to interact directly with Ably's REST API.
*/
-export declare class Rest extends Types.RestPromise {}
+export declare class Rest extends Types.Rest {}
/**
* A client that extends the functionality of {@link Rest} and provides additional realtime-specific features.
*/
-export declare class Realtime extends Types.RealtimePromise {}
+export declare class Realtime extends Types.Realtime {}