diff --git a/src/data/nav/pubsub.ts b/src/data/nav/pubsub.ts index f8671eee1c..df3bb22100 100644 --- a/src/data/nav/pubsub.ts +++ b/src/data/nav/pubsub.ts @@ -576,6 +576,50 @@ export default { name: 'SSE API', link: '/docs/api/sse', }, + { + name: 'JavaScript SDK', + pages: [ + { + name: 'Realtime interface', + pages: [ + { name: 'Realtime', link: '/docs/pub-sub/api/javascript/realtime/realtime-client' }, + { name: 'Auth', link: '/docs/pub-sub/api/javascript/realtime/auth' }, + { name: 'Connection', link: '/docs/pub-sub/api/javascript/realtime/connection' }, + { name: 'Crypto', link: '/docs/pub-sub/api/javascript/realtime/crypto' }, + { + name: 'Channels and messages', + pages: [ + { name: 'Channels', link: '/docs/pub-sub/api/javascript/realtime/channels' }, + { name: 'RealtimeChannel', link: '/docs/pub-sub/api/javascript/realtime/realtime-channel' }, + { name: 'ChannelDetails', link: '/docs/pub-sub/api/javascript/realtime/channel-details' }, + { name: 'Message', link: '/docs/pub-sub/api/javascript/realtime/message' }, + { name: 'RealtimeAnnotations', link: '/docs/pub-sub/api/javascript/realtime/realtime-annotations' }, + ], + }, + { + name: 'Presence', + pages: [ + { name: 'RealtimePresence', link: '/docs/pub-sub/api/javascript/realtime/realtime-presence' }, + { name: 'PresenceMessage', link: '/docs/pub-sub/api/javascript/realtime/presence-message' }, + ], + }, + { + name: 'Push notifications', + pages: [ + { name: 'Push', link: '/docs/pub-sub/api/javascript/realtime/push' }, + { name: 'PushChannel', link: '/docs/pub-sub/api/javascript/realtime/push-channel' }, + { name: 'PushAdmin', link: '/docs/pub-sub/api/javascript/realtime/push-admin' }, + ], + }, + ], + }, + ], + }, + { + link: 'https://ably.com/docs/sdk/js/v2.0/', + name: 'JavaScript SDK (TypeDoc)', + external: true, + }, ], }, ], diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/auth.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/auth.mdx new file mode 100644 index 0000000000..b451e2722f --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/auth.mdx @@ -0,0 +1,278 @@ +--- +title: Auth +meta_description: "API reference for the Authentication (Auth) interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Auth API, authorize, createTokenRequest, requestToken, revokeTokens, AuthOptions, TokenParams, TokenDetails, TokenRequest" +--- + +The `Auth` interface is responsible for managing tokens and [authentication](/docs/auth) for an Ably client. Access it via the `auth` property of a [`Realtime`](/docs/pub-sub/api/javascript/realtime/realtime-client) client instance. + +The principal use of `Auth` is to create Ably `TokenRequest`s with `createTokenRequest()`, or to obtain Ably Tokens from Ably with `requestToken()`, and then issue these short-lived tokens to less-trusted clients. Typically, your servers should be the only devices to hold the [private API key](/docs/auth#api-keys), which is used to sign Ably `TokenRequest`s or request Ably Tokens. If you adopt this model, your private API key is never shared with clients directly. + + +```javascript +const auth = realtime.auth; +``` + + + + +## Properties + +The `Auth` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| clientId | The client ID this client is identified as. Trusted [client identifiers](/docs/auth/identified-clients) allow a client to be identified to other clients. May be `null` if the client was instantiated without a `clientId` (anonymous client). | String or Null | + +
+ +## Authorize the client + +{`auth.authorize(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise`} + +Instructs the SDK to get a new token immediately. Once fetched, it will upgrade the current realtime connection to use the new token, or, if not connected, initiate a connection to Ably once the new token has been obtained. Also stores any `tokenParams` and `authOptions` passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. + +Any `tokenParams` and `authOptions` objects passed in will entirely replace (as opposed to being merged with) the current `client.auth` `tokenParams` and `authOptions`. + +A subsidiary use case for `authorize()` is to preemptively trigger renewal of a token or to acquire a new token with a revised set of capabilities. + + +```javascript +const tokenDetails = await realtime.auth.authorize({ clientId: 'user-123' }); +console.log(tokenDetails.token); +``` + + +### Parameters + +The `authorize()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| tokenParams | Optional | Parameters used when generating the requested token. When omitted, the default token parameters configured on the client are used. |
| +| authOptions | Optional | Authentication options. When omitted, the default authentication options configured on the client are used. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| ttl | Optional | Requested time to live for the token in milliseconds. When omitted, the Ably REST API default of 60 minutes is applied. Default: 1 hour. | Number | +| capability | Optional | The capabilities associated with this token. A JSON-encoded canonicalized representation of the [resource paths and associated operations](/docs/auth/capabilities). Default: `{"*":["*"]}`. | String or Object | +| clientId | Optional | A client ID, used for identifying this client as an [identified client](/docs/auth/identified-clients) 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 for use when the SDK is instantiated with a key. A `clientId` may also be implicit in a token used to instantiate the SDK, and an error is raised if a `clientId` specified here conflicts with the one implicit in the token. | String | +| timestamp | Optional | The timestamp of this request as milliseconds since the Unix epoch. Used together with `nonce` to prevent token requests being replayed. Not valid as a default token parameter. | Number | +| nonce | Optional | A cryptographically secure random string of at least 16 characters, used to ensure the `TokenRequest` cannot be reused. | String | + + + + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| authCallback | Optional | A function with the form `authCallback(tokenParams, callback(error, tokenOrTokenRequest))` that is called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed [`TokenRequest`](/docs/auth/token); a `TokenDetails` (in JSON format); an [Ably JWT](/docs/auth/token#jwt). The `callback` is invoked with the obtained token string, `TokenDetails`, `TokenRequest`, or Ably JWT on success, or with an error on failure. | Function | +| authUrl | Optional | A URL that the SDK may use to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed `TokenRequest` (in JSON format); a `TokenDetails` (in JSON format); an [Ably JWT](/docs/auth/token/jwt). For example, this can be used by a client to obtain signed Ably `TokenRequest`s from an application server. | String | +| authMethod | Optional | The HTTP verb to use for the request, either `GET` or `POST`. Default: `GET`. | String | +| authHeaders | Optional | A set of key-value pair headers to be added to any request made to the `authUrl`. Useful when an `authorization` header is required to authenticate a client to the `authUrl`. If the `authHeaders` object contains an `authorization` key, then `withCredentials` is set on the XHR request. | Object | +| authParams | Optional | A set of key-value pair params to be added to any request made to the `authUrl`. When the `authMethod` is `GET`, query params are sent. When it is `POST`, form encoded params are sent. | Object | +| key | Optional | The full API key string used in plain text. When defined, the client will use Basic authentication, or the SDK can use this key to create signed `TokenRequest`s. | String | +| token | Optional | An authenticated token. This can either be a token string or a `TokenDetails` object. The token string may be obtained from the `token` property of a `TokenDetails` component of an Ably `TokenRequest` response, or it may be a JSON Web Token satisfying [the Ably requirements for JWTs](/docs/auth/token#jwt). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the SDK to renew the token automatically when the previous one expires or is revoked. | String or | +| tokenDetails | Optional | A `TokenDetails` object. This option is mostly useful for testing. |
| +| useTokenAuth | Optional | When set to `true`, forces token authentication to be used. If a `clientId` has not been specified, the Ably Token issued is anonymous. | Boolean | +| queryTime | Optional | When `true`, the SDK will query the Ably servers for the current time when issuing `TokenRequest`s, instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably `TokenRequest`s, so this option is useful for SDK instances on auth servers whose clock cannot be kept synchronized through normal means, such as an NTP daemon. The server is queried for the current time once per SDK instance, which stores the offset from the local clock, so if using this option you should avoid instancing a new SDK instance per request. Default: `false`. | Boolean | + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| token | The Ably Token itself. A typical Ably Token string appears with the form `xVLyHw.A-pwh7wicf3afTfgiw4k2Ku33kcnSA7z6y8FjuYpe3QaNRTEo4`. | String | +| issued | The timestamp at which this token was issued as milliseconds since the Unix epoch. | Number | +| expires | The timestamp at which this token expires as milliseconds since the Unix epoch. | Number | +| capability | The capabilities associated with this token. A JSON-encoded canonicalized representation of the [resource paths and associated operations](/docs/auth/capabilities). | String | +| clientId | The client ID, if any, bound to this token. If a client ID is included, the token authenticates its bearer as that client ID, and the token may only be used to perform operations on behalf of that client ID. The client is then considered to be an [identified client](/docs/auth/identified-clients). | String | + + + +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with a `TokenDetails` object containing the new token once the realtime connection has been successfully upgraded to use it. On failure to obtain a token or upgrade the token, the connection moves to the `SUSPENDED` or `FAILED` state and the promise is rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Create a TokenRequest + +{`auth.createTokenRequest(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise`} + +Creates and signs an Ably `TokenRequest` based on the specified (or, if none specified, the SDK's stored) `tokenParams` and `authOptions`. Note this can only be used when the API `key` value is available locally. Otherwise, the Ably `TokenRequest` must be obtained from the key owner. Use this to generate an Ably `TokenRequest` in order to implement an Ably Token request callback for use by other clients. + +Both `authOptions` and `tokenParams` are optional. When omitted or `null`, the defaults specified in the `ClientOptions` when the SDK was instantiated, or set later via [`authorize()`](#authorize), are used. Values passed in are used instead of (rather than being merged with) the default values. + +Issuing an Ably `TokenRequest` to clients in favor of a token avoids sharing your private API key, as explained in [token authentication](/docs/auth/token). + + +```javascript +const tokenRequest = await realtime.auth.createTokenRequest({ clientId: 'user-123' }); +// Send tokenRequest JSON to the requesting client +``` + + +### Parameters + +The `createTokenRequest()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| tokenParams | Optional | Parameters used when generating the `TokenRequest`. |
| +| authOptions | Optional | Authentication options. |
| + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with a `TokenRequest` object, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + + + +| Property | Description | Type | +| --- | --- | --- | +| keyName | The name of the key against which this request is made. The key name is public, whereas the key secret is private. | String | +| ttl | Requested time to live for the token in milliseconds. When omitted, the default of 60 minutes is used. If the request is successful, the TTL of the returned token is less than or equal to this value, depending on application settings and the attributes of the issuing key. | Number | +| timestamp | The timestamp of this request as milliseconds since the Unix epoch. | Number | +| capability | Capability of the requested token. If the request is successful, the capability of the returned token will be the intersection of this capability with the capability of the issuing key. The capability is a JSON-encoded canonicalized representation of the [resource paths and associated operations](/docs/auth/capabilities). | String | +| clientId | The client ID to associate with the requested token. When provided, the token may only be used to perform operations on behalf of that client ID. | String | +| nonce | A cryptographically secure random string of at least 16 characters, used to ensure the `TokenRequest` cannot be reused. | String | +| mac | The Message Authentication Code for this request. | String | + +
+ +## Request an Ably Token
+ +{`auth.requestToken(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise`} + +Calls the `requestToken` REST API endpoint to obtain an Ably Token according to the specified `tokenParams` and `authOptions`. + +Both `authOptions` and `tokenParams` are optional. When omitted or `null`, the defaults specified in the `ClientOptions` when the SDK was instantiated, or set later via [`authorize()`](#authorize), are used. Values passed in are used instead of (rather than being merged with) the default values. + +Issuing an Ably `TokenRequest` to clients in favor of a token avoids sharing your private API key, as explained in [token authentication](/docs/auth/token). + +Note that since you normally use the [`ClientOptions`](/docs/pub-sub/api/javascript/realtime/realtime-client#constructor-params) callbacks to authenticate dynamically, you'll rarely need to call `requestToken()` explicitly, but it's available when you need finer control. + + +```javascript +const tokenDetails = await realtime.auth.requestToken(); +``` + + +### Parameters + +The `requestToken()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| tokenParams | Optional | Parameters for the requested token. |
| +| authOptions | Optional | Authentication options. |
| + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with a `TokenDetails` object, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Revoke tokens + +{`auth.revokeTokens(specifiers: TokenRevocationTargetSpecifier[], options?: TokenRevocationOptions): Promise`} + +Revokes the tokens specified by the provided array of `TokenRevocationTargetSpecifier`s. Only tokens issued by an API key that had [token revocation](/docs/auth/revocation) enabled before the token was issued can be revoked. + + +```javascript +const result = await realtime.auth.revokeTokens( + [{ type: 'clientId', value: 'user-123' }], + { allowReauthMargin: true } +); +console.log(`${result.successCount} succeeded, ${result.failureCount} failed`); +``` + + +### Parameters + +The `revokeTokens()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| specifiers | Required | An array of objects describing which tokens should be revoked. | Array of
| +| options | Optional | Options for the revoke request. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| type | Required | The type of token revocation target specifier. Valid values are `clientId`, `revocationKey`, or `channel`. | String | +| value | Required | The value of the token revocation target specifier. | String | + + + + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| issuedBefore | Optional | A Unix timestamp in milliseconds. Only tokens issued before this time are revoked. Default: the current time. Requests with an `issuedBefore` in the future, or more than an hour in the past, will be rejected. | Number | +| allowReauthMargin | Optional | If `true`, permits a token renewal cycle to take place without needing established connections to be dropped, by postponing enforcement to 30 seconds in the future and sending existing connections a hint to obtain (and upgrade the connection to use) a new token. Default: `false` (effect is near-immediate). | Boolean | + + + +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with a `BatchResult` whose `results` array contains a success or failure entry for each specifier. The promise is rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object if the request itself fails. + + + +| Property | Description | Type | +| --- | --- | --- | +| successCount | The number of successful operations in the request. | Number | +| failureCount | The number of unsuccessful operations in the request. | Number | +| results | The per-specifier results, one entry per specifier. | Array of
or
| + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| target | The target specifier. | String | +| appliesAt | The time at which the token revocation will take effect, as a Unix timestamp in milliseconds. | Number | +| issuedBefore | A Unix timestamp in milliseconds. Only tokens issued earlier than this time will be revoked. | Number | + + + + + +| Property | Description | Type | +| --- | --- | --- | +| target | The target specifier. | String | +| error | An [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object describing the reason token revocation failed for this target. | [ErrorInfo](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) | + + + diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/channel-details.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/channel-details.mdx new file mode 100644 index 0000000000..e13ea192b1 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/channel-details.mdx @@ -0,0 +1,101 @@ +--- +title: ChannelDetails +meta_description: "API reference for channel metadata (ChannelDetails) in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, channel metadata, ChannelDetails, ChannelStatus, occupancy, metrics, metachannel" +--- + +Channel metadata describes the current state of a channel, including whether it is active and its [occupancy](/docs/presence-occupancy/occupancy) metrics. It is represented by the `ChannelDetails` type. + +A realtime client receives `ChannelDetails` payloads in two ways: + +- By subscribing to a [metachannel](/docs/metadata-stats/metadata) such as `[meta]channel.lifecycle`, where each message's `data` is a `ChannelDetails` object describing a channel lifecycle event. +- By subscribing to a channel with the [`occupancy` channel option](/docs/channels/options#occupancy) enabled, which delivers `[meta]occupancy` events whose `data` contains the channel's occupancy metrics. + +The canonical, typed way to fetch a channel's current `ChannelDetails` on demand is the REST SDK's `channel.status()` method; over a realtime connection the same information arrives asynchronously as the events described above. + + +```javascript +// Receive channel lifecycle events, each carrying a ChannelDetails payload +const metaChannel = realtime.channels.get('[meta]channel.lifecycle'); +await metaChannel.subscribe((message) => { + const details = message.data; + console.log(details.channelId, details.status.occupancy.metrics.connections); +}); + +// Receive occupancy events by enabling the occupancy channel option +const channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}', { + params: { occupancy: 'metrics' }, +}); +await channel.subscribe('[meta]occupancy', (message) => { + console.log(message.data.metrics); +}); +``` + + +## ChannelDetails
+ +A `ChannelDetails` object contains information about a channel, along with its current state in a `ChannelStatus` object. + + + +| Property | Description | Type | +| --- | --- | --- | +| channelId | The name of the channel, including any qualifier. | String | +| status | The current state of the channel. |
| + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| isActive | Whether the channel is active. For events indicating regional activity, this reflects activity in that region rather than global activity. | Boolean | +| occupancy | The occupancy of the channel. For events indicating regional activity, this reflects activity in that region rather than global activity. | | + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| metrics | The occupancy metrics for the channel. | | + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| connections | The number of connections attached to the channel. | Number | +| publishers | The number of connections attached to the channel that are authorized to publish. | Number | +| subscribers | The number of connections attached that are authorized to subscribe to messages. | Number | +| presenceConnections | The number of connections that are authorized to enter members into the presence set. | Number | +| presenceMembers | The number of members currently entered into the presence set. | Number | +| presenceSubscribers | The number of connections that are authorized to subscribe to presence messages. | Number | + + + +## Example + +The following is an example of a `ChannelDetails` payload: + + +```json +{ + "channelId": "foo", + "status": { + "isActive": true, + "occupancy": { + "metrics": { + "connections": 1, + "publishers": 1, + "subscribers": 1, + "presenceConnections": 1, + "presenceMembers": 0, + "presenceSubscribers": 1 + } + } + } +} +``` + diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/channels.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/channels.mdx new file mode 100644 index 0000000000..98d4247131 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/channels.mdx @@ -0,0 +1,189 @@ +--- +title: Channels +meta_description: "API reference for the Channels interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Channels API, get, getDerived, release, ChannelOptions, DeriveOptions" +--- + +The `Channels` interface is used to create and destroy [`RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel) objects. Access it via the `channels` property of a [`Realtime`](/docs/pub-sub/api/javascript/realtime/realtime-client) client instance. + + +```javascript +const channels = realtime.channels; +``` + + +## Properties + +The `Channels` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| all | A map of all the channels that have been instantiated via [`get()`](#get) and have not yet been released via [`release()`](#release). | `Record` | + +
+ +## Get a channel
+ +{`channels.get(name: string, channelOptions?: ChannelOptions): RealtimeChannel`} + +Creates a new [`RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel) object if none for the given name exists, or returns the existing channel object. The channel is created or returned with the supplied `ChannelOptions`. + + +```javascript +const channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}'); + +// With channel options +const encryptedChannel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}', { + cipher: { key: '' } +}); +``` + + +### Parameters + +The `get()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| name | Required | The name of the channel. | String | +| channelOptions | Optional | Options for the channel, such as encryption or channel parameters. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| cipher | Optional | Requests [encryption](/docs/channels/options/encryption) for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length, and key). | or
| +| params | Optional | [Channel parameters](/docs/channels/options) that configure the behavior of the channel. Supported params include [`rewind`](/docs/channels/options/rewind), [`delta`](/docs/channels/options/deltas), [`occupancy`](/docs/presence-occupancy/occupancy), and [`echo`](/docs/channels/options/echo). | `Record` | +| modes | Optional | An array of channel mode values that restrict the operations a client can perform on a channel. | Array of
| +| attachOnSubscribe | Optional | Whether calling [`subscribe()`](/docs/pub-sub/api/javascript/realtime/realtime-channel#subscribe) on a channel or presence object should trigger an implicit attach. Default: `true`. | Boolean | + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| key | The private key used for encryption and decryption. Can be binary or base64-encoded. | `ArrayBuffer`, `Uint8Array`, `Buffer`, or String | +| algorithm | The name of the algorithm. Default: `AES`. | String | +| keyLength | The key length in bits of the cipher. Either 128 or 256. Default: 256. | Number | +| mode | The cipher mode. Default: `CBC`. | String | + + + + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| key | Required | The private key used for encryption and decryption. Can be binary or base64-encoded. | `ArrayBuffer`, `Uint8Array`, `Buffer`, or String | +| algorithm | Optional | The name of the algorithm. Default: `AES`. | String | +| keyLength | Optional | The key length in bits. Either 128 or 256. Default: 256. | Number | +| mode | Optional | The cipher mode. Default: `CBC`. | String | + + + + + +| Value | Description | +| --- | --- | +| PUBLISH | The client can publish messages to the channel. | +| SUBSCRIBE | The client can subscribe to messages on the channel. | +| PRESENCE | The client can enter the presence set on the channel. | +| PRESENCE_SUBSCRIBE | The client can subscribe to presence events on the channel. | +| OBJECT_PUBLISH | The client can publish LiveObjects messages on the channel. | +| OBJECT_SUBSCRIBE | The client can subscribe to LiveObjects messages on the channel. | +| ANNOTATION_PUBLISH | The client can publish annotations on the channel. | +| ANNOTATION_SUBSCRIBE | The client can subscribe to annotations on the channel. | + + + +### Returns
+ +`RealtimeChannel` + +Returns a [`RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel) object for the given name. If a channel with that name already exists, the existing object is returned. + +## Get a derived channel + +{`channels.getDerived(name: string, deriveOptions: DeriveOptions, channelOptions?: ChannelOptions): RealtimeChannel`} + +Creates a new [`RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel) object if none for the given name exists, or returns the existing channel object. The channel is created or returned with the specified `DeriveOptions` and optional `ChannelOptions`. + +Derived channels enable you to subscribe to a filtered subset of messages on a channel using [subscription filters](/docs/channels#subscription-filters). + + + + +```javascript +const derived = realtime.channels.getDerived('{{RANDOM_CHANNEL_NAME}}', { + filter: "name == 'important'" +}); +``` + + +### Parameters + +The `getDerived()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| name | Required | The name of the channel. | String | +| deriveOptions | Required | The derive options used to filter the channel. |
| +| channelOptions | Optional | Options for the channel. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| filter | Optional | The [JMESPath](https://jmespath.org/) query filter string used to derive the new channel. | String | + + + +### Returns
+ +`RealtimeChannel` + +Returns a derived [`RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel) object configured with the supplied filter. + +## Release a channel + +{`channels.release(name: string): void`} + +Releases all SDK-held references to a [`RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel) object, enabling it to be garbage collected. Useful for applications that work with a continually changing set of channels on a single client and need to avoid unbounded memory growth; if this does not describe your application, don't call it. + + + +This method only affects the local client-side representation of the channel. The channel itself on the Ably platform is not deleted or changed, and other client instances (in the same or different processes) are unaffected. + +Channels not already in the `initialized`, `detached`, or `failed` [state](/docs/channels/states) are detached before release. After release, calling [`channels.get()`](#get) with the same name returns a fresh channel object in the `initialized` state. + + +```javascript +realtime.channels.release('{{RANDOM_CHANNEL_NAME}}'); +``` + + +### Parameters + +The `release()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| name | Required | The name of the channel to release. | String | + +
diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/connection.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/connection.mdx new file mode 100644 index 0000000000..5cc0914c4c --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/connection.mdx @@ -0,0 +1,321 @@ +--- +title: Connection +meta_description: "API reference for the Connection interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Connection API, connect, close, on, once, off, ping, ConnectionState, ConnectionEvent, ConnectionStateChange" +--- + +The `Connection` interface represents the connection to Ably and provides methods to inspect the connection state, listen for state changes, and explicitly open or close the connection. Access it via the `connection` property of a [`Realtime`](/docs/pub-sub/api/javascript/realtime/realtime-client) client instance. + + +```javascript +const connection = realtime.connection; +``` + + +## Properties + +The `Connection` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| id | A unique public identifier for this connection, used to identify this member in presence events and messages. | String | +| state | The current [connection state](/docs/connect/states#connection-states) of this connection. |
| +| errorReason | When a connection failure occurs this property contains the error reason. | [ErrorInfo](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) or Undefined | +| key | A unique private connection key used to recover or resume a connection, assigned by Ably. When recovering a connection explicitly, the `recoveryKey` is used in the [`clientOptions.recover`](/docs/pub-sub/api/javascript/realtime/realtime-client#constructor-params) option as it contains both the `key` and the last message serial. This private connection key can also be used by other REST clients to [publish on behalf of this realtime client](/docs/pub-sub/advanced#publish-on-behalf). | String | + +
+ + + +| Value | Description | +| --- | --- | +| initialized | A connection object has been initialized but no connection has yet been attempted. | +| connecting | A connection attempt has been initiated. The `connecting` state is entered as soon as the SDK has completed initialization, and is reentered each time connection is re-attempted following disconnection. | +| connected | A connection exists and is active. | +| disconnected | A temporary failure condition. No current connection exists because there is no network connectivity or no host is available. The disconnected state is entered if an established connection is dropped, or if a connection attempt is unsuccessful. In the disconnected state the SDK will periodically attempt to open a new connection. | +| suspended | 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 has been made and a more or less immediate reconnection attempt has failed. In the suspended state, the SDK will periodically attempt to open a new connection every 30 seconds. Once reconnected, 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](/docs/storage-history/history). | +| closing | An explicit request by the developer to close the connection has been sent to the Ably service. If a reply is not received from Ably within a short period of time, the connection will be forcibly terminated and the connection state will become `closed`. | +| closed | The connection has been explicitly closed by the client. In the closed state, no reconnection attempts are made automatically by the SDK, and clients may not publish messages, subscribe to channels, or be present in any channels. Any channel objects that existed before the connection was closed are released. | +| failed | This state is entered if the SDK 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 invalid credentials), or a local terminal error (for example the token in use has expired and the SDK does not have any way to renew it). In the failed state, no reconnection attempts are made automatically by the SDK, and clients may not publish messages, subscribe to channels, or be present in any channels. | + + + +## Connect to Ably
+ +{`connection.connect(): void`} + +Explicitly calling `connect()` is unnecessary unless [`clientOptions.autoConnect`](/docs/pub-sub/api/javascript/realtime/realtime-client#constructor-params) is `false`. Unless already `connected` or `connecting`, this method causes the connection to open, entering the `connecting` state. + + +```javascript +realtime.connection.connect(); +await realtime.connection.once('connected'); +``` + + +## Close the connection + +{`connection.close(): void`} + +Causes the connection to close, entering the `closing` state. Once `closed`, the SDK will not attempt to re-establish the connection without an explicit call to [`connect()`](#connect). + + +```javascript +realtime.connection.close(); +``` + + +## Register a state change listener + +{`connection.on(event: ConnectionEvent, listener: connectionEventCallback): void`} + +Register the given listener for the specified `ConnectionEvent` on the `Connection`. The listener is passed a `ConnectionStateChange` object that contains the current state, previous state, the event, and an optional reason for the event or state change. + +{`connection.on(events: ConnectionEvent[], listener: connectionEventCallback): void`} + +Registers the listener for each event in the array. + +{`connection.on(listener: connectionEventCallback): void`} + +Register the given listener for all `ConnectionEvent`s on the `Connection`. The listener is passed a `ConnectionStateChange` object that contains the current state, previous state, the event, and an optional reason for the event or state change. For the `update` event, the current and previous states will be the same. + +If an exception is thrown in the listener and bubbles up to the event emitter, it will be caught and logged at `error` level, so as not to affect other listeners for the same event. + + +```javascript +realtime.connection.on('connected', (stateChange) => { + console.log('Connected to Ably'); +}); + +realtime.connection.on(['disconnected', 'suspended'], (stateChange) => { + console.log('Connection lost:', stateChange.reason); +}); +``` + + +### Parameters + +The `on()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| event | Optional | A single connection event to listen for. |
| +| events | Optional | An array of connection events to listen for. |
[] | +| listener | Required | A function notified for each matching event. If neither `event` nor `events` is supplied, it fires for every event. |
| + +
+ + + +| Value | Description | +| --- | --- | +| initialized | The connection object has been initialized but no connection has yet been attempted. | +| connecting | A connection attempt has been initiated. | +| connected | A connection has been established. | +| disconnected | The connection has been temporarily lost. | +| suspended | The connection has been lost for an extended period. | +| closing | An explicit close request has been sent. | +| closed | The connection has been explicitly closed. | +| failed | The connection failed and will not be reattempted. | +| update | An update to the connection has occurred (typically a re-auth or capability update) while the connection state remains `connected`. | + + + + + +| Parameter | Description | Type | +| --- | --- | --- | +| stateChange | The connection state change that occurred. | | + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| current | The new state. | | +| previous | The previous state. For the `update` event, this will be equal to the `current` state. |
| +| event | The event that triggered this state change. |
| +| reason | An `ErrorInfo` containing any information relating to the transition. | [ErrorInfo](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) or Undefined | +| retryIn | Duration in milliseconds upon which the SDK will retry a connection, where applicable. | Number or Undefined | + +
+ +## Register a one-time state change listener
+ +{`connection.once(event: ConnectionEvent, listener: connectionEventCallback): void`} + +Register the given listener for a single occurrence of the specified `ConnectionEvent` on the `Connection`. Once the listener has been called, it is removed as a registered listener and will not be called again. + +{`connection.once(listener: connectionEventCallback): void`} + +Register the given listener for a single occurrence of any `ConnectionEvent` on the `Connection`. + +{`connection.once(event: ConnectionEvent): Promise`} + +Returns a promise that is fulfilled with the next `ConnectionStateChange` for the specified event. This is the preferred way to await a specific connection state from async code. + +{`connection.once(): Promise`} + +Returns a promise that is fulfilled with the next `ConnectionStateChange`, regardless of the event type. + + +```javascript +await realtime.connection.once('connected'); +console.log('Connected'); +``` + + +### Parameters + +The `once()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| event | Optional | The connection event to listen for. If omitted, the listener fires for any event. |
| +| listener | Optional | A function notified for the next occurrence of the matching event. Omit to return a promise instead. |
| + +
+ +### Returns
+ +The callback-based overloads return `void`. + +The promise-based overloads return `Promise`. The promise is fulfilled with a `ConnectionStateChange` object the next time a matching event occurs, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object if the connection enters a state from which the event cannot occur. + +## Remove a state change listener + +{`connection.off(event: ConnectionEvent, listener: connectionEventCallback): void`} + +Remove the given listener for the specified `ConnectionEvent`. + +{`connection.off(listener: connectionEventCallback): void`} + +Remove the given listener for all `ConnectionEvent`s. + +{`connection.off(): void`} + +Removes all listeners, including those registered with and without specific events. + + +```javascript +const listener = (stateChange) => console.log(stateChange.current); +realtime.connection.on('connected', listener); + +// Remove the specific listener for 'connected' +realtime.connection.off('connected', listener); + +// Remove all listeners +realtime.connection.off(); +``` + + +### Parameters + +The `off()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| event | Optional | The connection event to unsubscribe from. If omitted, the listener is removed from all events. |
| +| listener | Optional | The listener function to remove. If omitted, all listeners are removed. |
| + +
+ +## Ping the Ably service
+ +{`connection.ping(): Promise`} + +When connected, sends a heartbeat ping to the Ably server and returns the round-trip time in milliseconds when a heartbeat ping response is received from the server. Useful for measuring the true round-trip latency to the connected Ably server. + + +```javascript +const latency = await realtime.connection.ping(); +console.log(`Latency: ${latency}ms`); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled with a number representing the time in milliseconds for the heartbeat ping request to be echoed, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object that details the reason why it was rejected. + +## Get registered listeners + +{`connection.listeners(eventName?: ConnectionEvent): null | connectionEventCallback[]`} + +Returns the listeners registered for the specified `ConnectionEvent`. If `eventName` is omitted, returns all registered listeners. + +### Parameters + +The `listeners()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| eventName | Optional | The connection event to filter listeners by. |
| + +
+ +### Returns
+ +`null | connectionEventCallback[]` + +Returns an array of registered listener functions, or `null` if no listeners are registered for the specified event. + +## Wait for a connection state + +{`connection.whenState(targetState: ConnectionState): Promise`} + +If the connection is already in the given state, returns a promise which immediately resolves to `null`. Otherwise calls [`once()`](#once) to return a promise which resolves the next time the connection transitions to the given state. + + +```javascript +await realtime.connection.whenState('connected'); +``` + + +### Parameters + +The `whenState()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| targetState | Required | The connection state to wait for. |
| + +
+ +### Returns
+ +`Promise` + +Returns a promise. If the connection is already in the given state, the promise immediately resolves to `null`. Otherwise it resolves with a `ConnectionStateChange` the next time the connection transitions to that state. + +## Create a connection recovery key + +{`connection.createRecoveryKey(): null | string`} + +Generates a string that can be used by another client to recover the current connection's state using [`clientOptions.recover`](/docs/pub-sub/api/javascript/realtime/realtime-client#constructor-params), as described in the [connection state recovery options](/docs/connect/states#connection-state-recover-options). + + +```javascript +const recoveryKey = realtime.connection.createRecoveryKey(); +``` + + +### Returns + +`null | string` + +Returns a recovery key string, or `null` if a recovery key cannot be generated (for example, if the connection has never been connected). diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/crypto.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/crypto.mdx new file mode 100644 index 0000000000..b21c38ff1e --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/crypto.mdx @@ -0,0 +1,107 @@ +--- +title: Crypto +meta_description: "API reference for the Encryption (Crypto) utility in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Crypto API, encryption, getDefaultParams, generateRandomKey, CipherParams" +--- + +The `Crypto` object provides utility methods for generating encryption keys and constructing `CipherParams` for use with [encrypted channels](/docs/channels/options/encryption). Access it via the `Crypto` property of a [`Realtime`](/docs/pub-sub/api/javascript/realtime/realtime-client) client instance. + + + + +```javascript +const crypto = Ably.Realtime.Crypto; +``` + + +## Get default cipher params + +{`Crypto.getDefaultParams(params: CipherParamOptions): CipherParams`} + +Obtains a `CipherParams` object using the values passed in (which must be a subset of `CipherParams` fields that at a minimum includes a `key`), filling in any unspecified fields with default values, and checks that the result is valid and self-consistent. + +You will rarely need to call this yourself, since the SDK will handle it for you if you specify `cipher` params when initializing a channel (as in the [getting started example](/docs/channels/options/encryption)) or when setting channel options with [`channel.setOptions()`](/docs/pub-sub/api/javascript/realtime/realtime-channel#set-options). + + +```javascript +const cipherParams = Ably.Realtime.Crypto.getDefaultParams({ key: '' }); +const channelOpts = { cipher: cipherParams }; +const channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}', channelOpts); +``` + + +### Parameters + +The `Crypto.getDefaultParams()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Required | The cipher params that you want to specify. It must at a minimum include a `key`, which should be either a binary (`ArrayBuffer`, `Uint8Array`, or Node.js `Buffer`) or a base64-encoded `String`. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| key | Required | The secret key used for encryption and decryption. Can be binary or base64-encoded. | `ArrayBuffer`, `Uint8Array`, `Buffer`, or String | +| algorithm | Optional | The name of the algorithm in the default system provider, or the lower-cased version of it; for example `aes` or `AES`. Default: `AES`. | String | +| keyLength | Optional | The key length in bits. Either 128 or 256. Default: 256. | Number | +| mode | Optional | The cipher mode. Default: `CBC`. | String | + + + +### Returns
+ +`CipherParams` + +Returns a complete `CipherParams` object. Throws an exception if the params are invalid or inconsistent. + + + +| Property | Description | Type | +| --- | --- | --- | +| key | The secret key used for encryption and decryption. Can be binary or base64-encoded. | `ArrayBuffer`, `Uint8Array`, `Buffer`, or String | +| algorithm | The name of the algorithm in the default system provider, or the lower-cased version of it; for example `aes` or `AES`. Default: `AES`. | String | +| keyLength | The key length in bits of the cipher. Either 128 or 256. Default: 256. | Number | +| mode | The cipher mode. Default: `CBC`. | String | + +
+ +## Generate a random key
+ +{`Crypto.generateRandomKey(keyLength?: number): Promise`} + +Generates a randomly-generated binary key of the specified key length. The returned key can be used directly as the `key` field of a `CipherParams` object or in a channel's `cipher` options. + +You will rarely need to call this yourself, since the SDK will handle key generation for you when [encryption is configured on a channel](/docs/channels/options/encryption). + + +```javascript +const key = await Ably.Realtime.Crypto.generateRandomKey(256); +const channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}', { cipher: { key } }); +``` + + +### Parameters + +The `Crypto.generateRandomKey()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| keyLength | Optional | The length of key to generate, in bits. For AES this should be either 128 or 256. Default: 256. | Number | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with the generated binary key (an `ArrayBuffer` in the browser, a `Buffer` in Node.js), or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/message.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/message.mdx new file mode 100644 index 0000000000..0e0be01c55 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/message.mdx @@ -0,0 +1,175 @@ +--- +title: Message +meta_description: "API reference for the Message interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Message API, name, data, extras, id, clientId, connectionId, timestamp, encoding, action, serial, annotations, version, summary, SummaryEntry, fromEncoded, fromEncodedArray" +--- + +A `Message` represents an individual message that is sent to or received from Ably. Messages are delivered through a channel's [`subscribe()`](/docs/pub-sub/api/javascript/realtime/realtime-channel#subscribe) method or retrieved via [`history()`](/docs/pub-sub/api/javascript/realtime/realtime-channel#history). + + +```javascript +channel.subscribe((message) => { + console.log(message.name, message.data); +}); +``` + + +## Properties + +The `Message` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| name | The event name, if provided. | String | +| data | The message payload, if provided. | String, JSON Object, or Buffer | +| extras | Metadata and/or ancillary payloads, if provided. Valid payloads include [`push`](/docs/push/publish#payload), [`headers`](/docs/channels#metadata) (a map of strings to strings for arbitrary customer-supplied metadata), [`ephemeral`](/docs/pub-sub/advanced#ephemeral), and [`privileged`](/docs/platform/integrations/skip-integrations). | JSON Object | +| id | A Unique ID assigned by Ably to this message. | String | +| clientId | The client ID of the publisher of this message. | String | +| connectionId | The connection ID of the publisher of this message. | String | +| connectionKey | A connection key, which can optionally be included for a REST publish as part of the [publishing on behalf of a realtime client functionality](/docs/pub-sub/advanced#publish-on-behalf). | String | +| timestamp | Timestamp when the message was first received by the Ably, as milliseconds since the epoch. | Integer | +| encoding | This will typically be empty as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the `data` payload. | String | +| action | The action type of the message. |
| +| serial | A server-assigned identifier that will be the same in all future updates of this message. It can be used to add [annotations](/docs/messages/annotations) to a message or to [update or delete](/docs/messages/updates-deletes) it. Serial will only be set if you enable annotations, updates, deletes, and appends in [rules](/docs/channels#rules). | String | +| annotations | An object containing information about annotations that have been made to the object. |
| +| version | An object containing version metadata for messages that have been [updated or deleted](/docs/messages/updates-deletes). |
| + +
+ + + +| Value | Description | +| --- | --- | +| MESSAGE_CREATE | A new message was created. The value is `message.create`. | +| MESSAGE_UPDATE | A message was updated. The value is `message.update`. | +| MESSAGE_DELETE | A message was deleted. The value is `message.delete`. | +| META | A meta-message from the Ably system. The value is `meta`. | +| MESSAGE_SUMMARY | A summary of annotations for a message. The value is `message.summary`. | +| MESSAGE_APPEND | A message was appended to an existing message. The value is `message.append`. | + + + + + +| Property | Description | Type | +| --- | --- | --- | +| summary | An object whose keys are [annotation types](/docs/messages/annotations#annotation-types) and whose values are aggregated [annotation summaries](/docs/messages/annotations#annotation-summaries) for that annotation type. The structure of each value depends on the summarization method, for example a `total.v1` entry has a `total` field, while a `flag.v1` entry has `total` and `clientIds` fields. Always populated for a `message.summary` action and may be populated for any other action (in particular, a message retrieved from history will have its latest summary included). | `Record`>` | + + + + + +| Shape | Description | Type | +| --- | --- | --- | +| SummaryClientIdList | The summary entry for `flag.v1`, and the per-name value for `distinct.v1` and `unique.v1`. | | +| SummaryDistinctValues / SummaryUniqueValues | The summary entry for `distinct.v1` and `unique.v1`, an object mapping each name to a `SummaryClientIdList` value. | `Record` | +| SummaryMultipleValues | The summary entry for `multiple.v1`, an object mapping each name to a summary client ID counts value. | `Record`>` | +| SummaryTotal | The summary entry for `total.v1`. |
| + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| total | The total number of clients who have published an annotation with this name (or type, depending on context). | Number | +| clientIds | A list of the clientIds of all clients who have published an annotation with this name (or type, depending on context). | `String[]` | +| clipped | Whether the list of clientIds has been clipped due to exceeding the maximum number of clients. | Boolean | + + + + + +| Property | Description | Type | +| --- | --- | --- | +| total | The sum of the counts from all clients who have published an annotation with this name. | Number | +| clientIds | A map from clientIds to the count each of those clients has contributed. | `Record` | +| totalUnidentified | The sum of the counts from all unidentified clients who have published an annotation with this name, and so who are not included in the `clientIds` map. | Number | +| clipped | Whether the `clientIds` map has been clipped due to exceeding the maximum number of clients. | Boolean | +| totalClientIds | The total number of distinct identified clients (equal to the size of `clientIds` if `clipped` is false). | Number | + + + + + +| Property | Description | Type | +| --- | --- | --- | +| total | The total number of annotations of this type that have been published for the message. | Number | + + + + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| serial | Required | An Ably-generated ID that uniquely identifies this version of the message. Can be compared lexicographically to determine version ordering. For an original message with an action of `message.create`, this will be equal to the top-level `serial`. | String | +| timestamp | Required | The time this version was created (when the update or delete operation was performed). For an original message, this will be equal to the top-level `timestamp`. | Integer | +| clientId | Optional | The client identifier of the user who performed the update or delete operation. Only present for `message.update` and `message.delete` actions. | String | +| description | Optional | Optional description provided when the update or delete was performed. Only present for `message.update` and `message.delete` actions. | String | +| metadata | Optional | Optional metadata provided when the update or delete was performed. Only present for `message.update` and `message.delete` actions. | `Record` | + + + +## Create a message from an encoded object
+ +{`Message.fromEncoded(encodedMsg: Object, channelOptions?: ChannelOptions): Promise`} + +A static factory method to create a `Message` from a deserialized `Message`-like object encoded using Ably's wire protocol. The returned promise resolves with the decoded message. + + +```javascript +const message = await Ably.Realtime.Message.fromEncoded(encodedMsg); +``` + + +### Parameters + +The `Message.fromEncoded()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| encodedMsg | Required | A `Message`-like deserialized object. | Object | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/realtime/channels#get) | + +
+ +### Returns
+ +`Promise` + +Returns a promise that resolves with a `Message` object decoded from the supplied object. + +## Create messages from an encoded array + +{`Message.fromEncodedArray(encodedMsgs: Object[], channelOptions?: ChannelOptions): Promise`} + +A static factory method to create an array of `Message` objects from an array of deserialized `Message`-like objects encoded using Ably's wire protocol. The returned promise resolves with the decoded messages. + + +```javascript +const messages = await Ably.Realtime.Message.fromEncodedArray(encodedMsgs); +``` + + +### Parameters + +The `Message.fromEncodedArray()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| encodedMsgs | Required | An array of `Message`-like deserialized objects. | `Array` | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/realtime/channels#get) | + +
+ +### Returns + +`Promise` + +Returns a promise that resolves with an array of `Message` objects decoded from the supplied array. diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/presence-message.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/presence-message.mdx new file mode 100644 index 0000000000..8efc45e48a --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/presence-message.mdx @@ -0,0 +1,141 @@ +--- +title: PresenceMessage +meta_description: "API reference for the PresenceMessage type in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, PresenceMessage, action, clientId, connectionId, data, encoding, extras, id, timestamp, PresenceAction, fromEncoded, fromEncodedArray, fromValues" +--- + +A `PresenceMessage` represents an individual presence event sent to or received from Ably. Presence messages are delivered through a channel's [`presence.subscribe()`](/docs/pub-sub/api/javascript/realtime/realtime-presence#subscribe) method, or retrieved via [`presence.get()`](/docs/pub-sub/api/javascript/realtime/realtime-presence#get) and [`presence.history()`](/docs/pub-sub/api/javascript/realtime/realtime-presence#history). + + +```javascript +await channel.presence.subscribe((presenceMessage) => { + console.log(presenceMessage.action, presenceMessage.clientId); +}); +``` + + +## Properties + +The `PresenceMessage` type has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| action | The type of [presence action](/docs/presence-occupancy/presence#trigger-events) this message represents. |
| +| clientId | The client ID of the publisher of this presence message. | String | +| connectionId | The connection ID of the publisher of this presence message. | String | +| data | The presence data payload, if provided. | String, JSON Object, or Buffer | +| encoding | This will typically be empty as all presence messages received from Ably are automatically decoded client-side using this value. However, if the encoding cannot be processed, this attribute will contain the remaining transformations not applied to the `data` payload. | String | +| extras | Metadata and/or ancillary payloads, if provided. The only currently valid payloads for `extras` are the [`push`](/docs/push/publish#sub-channels), [`ref`](/docs/messages#interactions) and [`privileged`](/docs/platform/integrations/skip-integrations) objects. | JSON Object | +| id | A unique ID assigned to each `PresenceMessage` by Ably. | String | +| timestamp | Timestamp when the presence message was first received by Ably, as milliseconds since the epoch. | Integer | + +
+ + + +| Value | Description | +| --- | --- | +| absent | Reserved for internal use. This is an internal enum value and is not delivered to subscribers as a presence event. | +| present | A member is present at the time of channel attach. Synthesized for each existing member when a client first subscribes. | +| enter | A new member entered the presence set. | +| leave | A member left the presence set, either explicitly or implicitly (e.g. due to disconnection). | +| update | A present member updated their data. | + + + +## Create a PresenceMessage from an encoded object
+ +{`PresenceMessage.fromEncoded(encodedMsg: Object, channelOptions?: ChannelOptions): Promise`} + +A static factory method to create a `PresenceMessage` from a deserialized `PresenceMessage`-like object encoded using Ably's wire protocol. The returned promise resolves with the decoded presence message. + + +```javascript +const presenceMessage = await Ably.Realtime.PresenceMessage.fromEncoded(encodedMsg); +``` + + +### Parameters + +The `PresenceMessage.fromEncoded()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| encodedMsg | Required | A `PresenceMessage`-like deserialized object. | Object | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/realtime/channels#get) | + +
+ +### Returns
+ +`Promise` + +Returns a promise that resolves with a `PresenceMessage` object decoded from the supplied object. + +## Create an array of PresenceMessages from encoded objects + +{`PresenceMessage.fromEncodedArray(encodedMsgs: Object[], channelOptions?: ChannelOptions): Promise`} + +A static factory method to create an array of `PresenceMessage` objects from an array of deserialized `PresenceMessage`-like objects encoded using Ably's wire protocol. The returned promise resolves with the decoded presence messages. + + +```javascript +const presenceMessages = await Ably.Realtime.PresenceMessage.fromEncodedArray(encodedMsgs); +``` + + +### Parameters + +The `PresenceMessage.fromEncodedArray()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| encodedMsgs | Required | An array of `PresenceMessage`-like deserialized objects. | `Array` | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/realtime/channels#get) | + +
+ +### Returns + +`Promise` + +Returns a promise that resolves with an array of `PresenceMessage` objects decoded from the supplied array. + +## Create a PresenceMessage from values + +{`PresenceMessage.fromValues(values: Partial): PresenceMessage`} + +A static factory method that initialises a `PresenceMessage` from a `PresenceMessage`-like object. Only the `clientId`, `data`, and `extras` fields are used. + + +```javascript +const presenceMessage = Ably.Realtime.PresenceMessage.fromValues({ + clientId: 'user-123', + data: { status: 'available' } +}); +``` + + +### Parameters + +The `PresenceMessage.fromValues()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| values | Required | A `PresenceMessage`-like object to initialise from. Only `clientId`, `data`, and `extras` are used. | Object | + +
+ +### Returns
+ +`PresenceMessage` + +Returns a `PresenceMessage` object initialised from the supplied values. diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/push-admin.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/push-admin.mdx new file mode 100644 index 0000000000..746d725d4c --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/push-admin.mdx @@ -0,0 +1,457 @@ +--- +title: PushAdmin +meta_description: "API reference for the Push admin (PushAdmin) interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, PushAdmin API, push notifications admin, publish, deviceRegistrations, channelSubscriptions, DeviceDetails" +--- + +The `PushAdmin` interface provides server-side and admin-level operations for managing push notifications across devices and channels. Access it via [`realtime.push.admin`](/docs/pub-sub/api/javascript/realtime/push). Most `PushAdmin` operations require the `push-admin` capability. The per-device operations `get`, `save`, and `remove` can alternatively be performed with the `push-subscribe` capability together with device authentication matching the requested `deviceId`. Required capabilities are noted on each method below. + + +```javascript +const admin = realtime.push.admin; +``` + + +## Properties + +The `PushAdmin` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| deviceRegistrations | A [`PushDeviceRegistrations`](#device-registrations) object for registering new devices, updating existing devices, deregistering devices, and retrieving or listing devices registered to an app. | [PushDeviceRegistrations](#device-registrations) | +| channelSubscriptions | A [`PushChannelSubscriptions`](#channel-subscriptions) object for subscribing, listing, and unsubscribing individual devices or groups of [identified devices](/docs/auth/identified-clients) to push notifications published on channels. | [PushChannelSubscriptions](#channel-subscriptions) | + +
+ +## Publish a push notification
+ +{`admin.publish(recipient: any, payload: any): Promise`} + +Sends a push notification using [direct publishing](/docs/push/publish#direct-publishing) to individual devices or to groups of devices sharing the same `clientId`, bypassing the realtime channel subscription model. + + +```javascript +await realtime.push.admin.publish( + { deviceId: '' }, + { + notification: { + title: 'Hello', + body: 'A push notification from Ably' + } + } +); +``` + + +### Parameters + +The `publish()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| recipient | Required | A JSON object identifying the recipient. Specify either `clientId`, `deviceId`, or the underlying notifications service identifiers (such as `fcmToken`, `apnsDeviceToken`). The [push publish REST API](/docs/api/rest-api#push-publish) documents the supported recipient fields. | Object | +| payload | Required | A JSON object containing the push notification payload. See the [push notification payload reference](/docs/push/publish#payload). | Object | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the notification has been accepted by Ably, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## PushDeviceRegistrations + +Registers new devices, updates existing devices, deregisters devices, and retrieves or lists devices registered to an app. Access it via `admin.deviceRegistrations`. + + +```javascript +const registrations = realtime.push.admin.deviceRegistrations; +``` + + +### Get a device registration + +{`deviceRegistrations.get(deviceId: string): Promise`} + +Retrieves the [`DeviceDetails`](#DeviceDetails) of a device registered to receive push notifications using its `deviceId`. + +{`deviceRegistrations.get(deviceDetails: DeviceDetails): Promise`} + +Retrieves the [`DeviceDetails`](#DeviceDetails) of a device registered to receive push notifications using the `id` property of an existing `DeviceDetails` object. + +Requires `push-admin` permission, or `push-subscribe` permission together with device authentication matching the requested `deviceId`. + + +```javascript +const device = await realtime.push.admin.deviceRegistrations.get(''); +``` + + +#### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| deviceId | required | The unique ID of the device to retrieve. Provide either `deviceId` or `deviceDetails`. | String | +| deviceDetails | required | A `DeviceDetails` object containing the `id` property of the device to retrieve. Provide either `deviceId` or `deviceDetails`. |
| + +
+ +#### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with a [`DeviceDetails`](#DeviceDetails) object, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +### List device registrations + +{`deviceRegistrations.list(params: DeviceRegistrationParams): Promise>`} + +Retrieves all devices matching the filter `params` provided. Requires `push-admin` permission. + + +```javascript +const devices = await realtime.push.admin.deviceRegistrations.list({ clientId: 'user-123' }); +``` + + +#### Parameters + +The `list()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Required | Filter parameters for the query. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| clientId | Optional | A `clientId` to filter by. Cannot be used with a `deviceId` param. | String | +| deviceId | Optional | A `deviceId` to filter by. Cannot be used with a `clientId` param. | String | +| limit | Optional | An upper limit on the number of devices returned. Default: 100. Maximum: 1000. | Number | +| state | Optional | Filter by the state of the device. Must be one of `ACTIVE`, `FAILING`, or `FAILED`. Applies to `list()` only; `removeWhere()` ignores this param. | String | + + + +#### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) of [`DeviceDetails`](#DeviceDetails) objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +### Save a device registration + +{`deviceRegistrations.save(deviceDetails: DeviceDetails): Promise`} + +Registers or updates a device with Ably for push notifications. Stores or updates the [`DeviceDetails`](#DeviceDetails) for the device. Requires `push-admin` permission, or `push-subscribe` permission together with device authentication matching the requested `deviceId`. + + +```javascript +const saved = await realtime.push.admin.deviceRegistrations.save(deviceDetails); +``` + + +#### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| deviceDetails | required | The `DeviceDetails` object to create or update. |
| + +
+ +#### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with the saved [`DeviceDetails`](#DeviceDetails) object, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +### Remove a device registration + +{`deviceRegistrations.remove(deviceId: string): Promise`} + +Removes a device registered to receive push notifications from Ably using its `deviceId`. + +{`deviceRegistrations.remove(deviceDetails: DeviceDetails): Promise`} + +Removes a device registered to receive push notifications from Ably using the `id` property of a `DeviceDetails` object. + +Requires `push-admin` permission, or `push-subscribe` permission together with device authentication matching the requested `deviceId`. + + +```javascript +await realtime.push.admin.deviceRegistrations.remove(''); +``` + + +#### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| deviceId | required | The unique ID of the device to remove. Provide either `deviceId` or `deviceDetails`. | String | +| deviceDetails | required | A `DeviceDetails` object containing the `id` property of the device to remove. Provide either `deviceId` or `deviceDetails`. |
| + +
+ +#### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the registration has been removed, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. A request to delete a device that does not exist results in a successful operation. + +### Remove device registrations matching params + +{`deviceRegistrations.removeWhere(params: DeviceRegistrationParams): Promise`} + +Removes all devices matching the filter `params` provided. The `limit` property is ignored. Requires `push-admin` permission. + + +```javascript +await realtime.push.admin.deviceRegistrations.removeWhere({ clientId: 'user-123' }); +``` + + +#### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | required | Filter parameters identifying the devices to remove. The `limit` property is ignored. |
| + +
+ +#### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the matching registrations have been removed, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. A request that does not match any existing devices still results in a successful operation. + +## PushChannelSubscriptions + +Subscribes a push notification device to a channel, ensuring the device receives any push notifications published in the future on that channel. It also allows these subscriptions to be retrieved, listed, updated, or removed for individual devices or groups of [identified devices](/docs/auth/identified-clients). Access it via `admin.channelSubscriptions`. + + +```javascript +const subscriptions = realtime.push.admin.channelSubscriptions; +``` + + +### List channel subscriptions + +{`channelSubscriptions.list(params: PushChannelSubscriptionParams): Promise>`} + +Retrieves all push channel subscriptions matching the filter `params` provided. + + +```javascript +const subs = await realtime.push.admin.channelSubscriptions.list({ channel: 'news' }); +``` + + +#### Parameters + +The `list()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Required | Filter parameters for the query. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| channel | Optional | The channel name to filter subscriptions by. | String | +| clientId | Optional | A `clientId` to filter subscriptions by. Cannot be used with a `deviceId` param. | String | +| deviceId | Optional | A `deviceId` to filter subscriptions by. Cannot be used with a `clientId` param. | String | +| limit | Optional | An upper limit on the number of subscriptions returned. Default: 100. Maximum: 1000. | Number | + + + +#### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) of `PushChannelSubscription` objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +### List channels with subscriptions + +{`channelSubscriptions.listChannels(params: PushChannelsParams): Promise>`} + +Retrieves all channels with at least one device subscribed to push notifications. Requires `push-admin` permission. + + +```javascript +const channels = await realtime.push.admin.channelSubscriptions.listChannels({}); +``` + + +#### Parameters + +The `listChannels()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Required | Pagination options. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| limit | Optional | An upper limit on the number of channels returned. Default: 100. Maximum: 1000. | Number | + + + +#### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) of channel name strings, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +### Save a channel subscription + +{`channelSubscriptions.save(subscription: PushChannelSubscription): Promise`} + +Subscribes a device, or group of devices sharing a [client identifier](/docs/auth/identified-clients), to push notifications on a channel. + + +```javascript +const saved = await realtime.push.admin.channelSubscriptions.save({ + channel: 'news', + clientId: 'user-123' +}); +``` + + +#### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| subscription | required | The push channel subscription to create or update. |
| + +
+ +#### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with the newly subscribed or updated `PushChannelSubscription` object, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +### Remove a channel subscription + +{`channelSubscriptions.remove(subscription: PushChannelSubscription): Promise`} + +Unsubscribes a device, or group of devices sharing a [client identifier](/docs/auth/identified-clients), from receiving push notifications on a channel. Requires `push-admin` permission, or, for a subscription associated with a given `deviceId`, `push-subscribe` permission together with device authentication matching that `deviceId`. + + +```javascript +await realtime.push.admin.channelSubscriptions.remove({ channel: 'news', clientId: 'user-123' }); +``` + + +#### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| subscription | required | The push channel subscription to remove. |
| + +
+ +#### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the subscription has been removed, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +### Remove channel subscriptions matching params + +{`channelSubscriptions.removeWhere(params: PushChannelSubscriptionParams): Promise`} + +Unsubscribes all devices matching the filter `params` provided from push notifications on a channel. Requires `push-admin` permission. + + +```javascript +await realtime.push.admin.channelSubscriptions.removeWhere({ channel: 'news' }); +``` + + +#### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | required | Filter parameters identifying the subscriptions to remove. Can contain `channel`, and optionally either `clientId` or `deviceId`. |
| + +
+ +#### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the matching subscriptions have been removed, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## DeviceDetails + +A `DeviceDetails` represents a device registered for push notifications. + + + +| Property | Description | Type | +| --- | --- | --- | +| id | A unique ID generated by the device. | String | +| clientId | Optional trusted [client identifier](/docs/auth/identified-clients) for the device. | String or Undefined | +| platform | The platform of the push device. One of `android`, `ios`, or `browser`. | String | +| formFactor | Form factor of the push device. One of `phone`, `tablet`, `desktop`, `tv`, `watch`, `car`, `embedded`, or `other`. | String | +| metadata | A JSON object of key-value pairs that contains metadata for the device. The metadata for a device may only be set by clients with `push-admin` privileges. | Object | +| deviceSecret | A unique device secret generated by the Ably SDK. | String | +| push | Contains details about the device's push notification registration. |
| + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| recipient | A JSON object containing the push transport and address (for example, an FCM registration token or APNs device token), as documented in the [push publish reference](/docs/api/rest-api#message-extras-push). | Object | +| state | The current state of the push device. One of `ACTIVE`, `FAILING`, or `FAILED`. | String | +| error | When `state` is `FAILING` or `FAILED`, this contains the reason for the most recent failure. | [ErrorInfo](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) or Undefined | + + + + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| channel | Required | The channel the push notification subscription is for. | String | +| deviceId | Optional | The unique ID of the device. Provide either `deviceId` or `clientId`. | String | +| clientId | Optional | The ID of the client the device, or devices, are associated with. Provide either `clientId` or `deviceId`. | String | + + + diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/push-channel.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/push-channel.mdx new file mode 100644 index 0000000000..ccca24c8da --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/push-channel.mdx @@ -0,0 +1,125 @@ +--- +title: PushChannel +meta_description: "API reference for the PushChannel interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, PushChannel, push notifications, subscribe, unsubscribe, PushChannelSubscription" +--- + +The `PushChannel` object lets a device subscribe to and unsubscribe from push notifications published on a channel, and list the push subscriptions on that channel. Access it via `channel.push`. + + +```javascript +const pushChannel = channel.push; +``` + + +## Subscribe this device
+ +{`pushChannel.subscribeDevice(): Promise`} + +Subscribe the local device to the channel's push notifications. + + +```javascript +await channel.push.subscribeDevice(); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled when the subscription has been created, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Subscribe all devices with this clientId + +{`pushChannel.subscribeClient(): Promise`} + +[Subscribe all devices associated with this client's `clientId`](/docs/push/publish#sub-channels) to the channel's push notifications. + + +```javascript +await channel.push.subscribeClient(); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled when the subscription has been created, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Unsubscribe this device + +{`pushChannel.unsubscribeDevice(): Promise`} + +Unsubscribe the local device from the channel's push notifications. + + +```javascript +await channel.push.unsubscribeDevice(); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled when the subscription has been removed, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Unsubscribe all devices with this clientId + +{`pushChannel.unsubscribeClient(): Promise`} + +[Unsubscribe all devices associated with this client's `clientId`](/docs/push/publish#sub-channels) from the channel's push notifications. + + +```javascript +await channel.push.unsubscribeClient(); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled when the subscriptions have been removed, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## List subscriptions on this channel + +{`pushChannel.listSubscriptions(params?: Record): Promise>`} + +Lists push subscriptions on the channel. These subscriptions can either be a list of client (`clientId`) subscriptions, device (`deviceId`) subscriptions, or, if `concatFilters` is set to `true`, a list of both. This method requires clients to have the [Push Admin capability](/docs/push#push-admin). + + +```javascript +const subscriptions = await channel.push.listSubscriptions({ deviceId: '' }); +``` + + +### Parameters + +The `listSubscriptions()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Optional | An object containing key-value pairs to filter subscriptions by. Can contain `clientId`, `deviceId`, `deviceClientId`, `concatFilters`, and a `limit` on the number of subscriptions returned (up to 1,000). | `Record` | + +
+ +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) containing an array of `PushChannelSubscription` objects, which supports pagination using its `next` and `first` methods, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + + + +| Property | Description | Type | +| --- | --- | --- | +| channel | The channel that this push notification subscription is associated with. | String | +| deviceId | The device with this identifier is linked to this channel subscription. When present, `clientId` is never present. | String | +| clientId | Devices with this [client identifier](/docs/auth/identified-clients) are included in this channel subscription. When present, `deviceId` is never present. | String | + +
diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/push.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/push.mdx new file mode 100644 index 0000000000..a92763439c --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/push.mdx @@ -0,0 +1,130 @@ +--- +title: Push +meta_description: "API reference for the Push interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Push API, activate, deactivate, push notifications, LocalDevice, DeviceDetails" +--- + +The `Push` object provides device-level [push notification](/docs/push) management, such as activating and deactivating the local device. Access it via the `push` property of a [`Realtime`](/docs/pub-sub/api/javascript/realtime/realtime-client) client instance (`realtime.push`). + + +```javascript +const push = realtime.push; +``` + + +## Properties + +The `Push` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| admin | A [`PushAdmin`](/docs/pub-sub/api/javascript/realtime/push-admin) object for managing push notifications administratively (requires the `push-admin` capability). | [PushAdmin](/docs/pub-sub/api/javascript/realtime/push-admin) | + +
+ +## Activate the device
+ +{`push.activate(registerCallback?: Function, updateFailedCallback?: Function): Promise`} + +[Activates the device](/docs/push/configure/web#activate-browsers) for push notifications. Subsequently registers the device with Ably and stores the `deviceIdentityToken` in local storage. + + +```javascript +await realtime.push.activate(); +``` + + +### Parameters + +The `activate()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| registerCallback | Optional | A function passed to override the default implementation to register the local device for push activation. Called with the local device's [`DeviceDetails`](/docs/pub-sub/api/javascript/realtime/push-admin#DeviceDetails) and a callback of the form `callback(err, deviceDetails)`, where `err` is an `ErrorInfo` or `null` and `deviceDetails` is the registered `DeviceDetails`. | Function | +| updateFailedCallback | Optional | A callback to be invoked when the device registration fails to update. Called with an `ErrorInfo` or `null` as `updateFailedCallback(err)`. | Function | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the device has been activated, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Deactivate the device + +{`push.deactivate(deregisterCallback?: Function): Promise`} + +Deactivates the device from receiving push notifications. + + +```javascript +await realtime.push.deactivate(); +``` + + +### Parameters + +The `deactivate()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| deregisterCallback | Optional | A function passed to override the default implementation to deregister the local device for push activation. Called with the local device's [`DeviceDetails`](/docs/pub-sub/api/javascript/realtime/push-admin#DeviceDetails) and a callback of the form `callback(err, deviceId)`, where `err` is an `ErrorInfo` or `null` and `deviceId` is the deregistered device's ID string. | Function | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the device has been deactivated, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## LocalDevice + +A `LocalDevice` represents the current device as registered for push notifications, exposing the identity token and secret it uses to authenticate itself with Ably. Access it by calling `realtime.device()`. + +### Properties + + + +| Property | Description | Type | +| --- | --- | --- | +| id | A unique ID generated by the device. | String | +| deviceSecret | A unique device secret generated by the Ably SDK. | String | +| deviceIdentityToken | A unique identity token the device uses to authenticate itself with Ably. | String | + +
+ +### List subscriptions for the local device
+ +{`localDevice.listSubscriptions(): Promise>`} + +Retrieves push subscriptions active for the local device. + + +```javascript +const subs = await realtime.device().listSubscriptions(); +``` + + +#### Returns + +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) containing an array of `PushChannelSubscription` objects for each push channel subscription active for the local device, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + + + +| Property | Description | Type | +| --- | --- | --- | +| channel | The channel that this push notification subscription is associated with. | String | +| deviceId | The device with this identifier is linked to this channel subscription. When present, `clientId` is never present. | String | +| clientId | Devices with this [client identifier](/docs/auth/identified-clients) are included in this channel subscription. When present, `deviceId` is never present. | String | + +
diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/realtime-annotations.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/realtime-annotations.mdx new file mode 100644 index 0000000000..b03f59bca1 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/realtime-annotations.mdx @@ -0,0 +1,272 @@ +--- +title: RealtimeAnnotations +meta_description: "API reference for message annotations (the RealtimeAnnotations interface) in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, RealtimeAnnotations, message annotations, publish, delete, get, subscribe, unsubscribe, Annotation, OutboundAnnotation, AnnotationAction, fromEncoded, fromEncodedArray" +--- + +The `RealtimeAnnotations` object lets you publish, delete, retrieve, and subscribe to [annotations](/docs/messages/annotations) on messages. Access it via the `annotations` property of a [`RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel). + + +```javascript +const annotations = channel.annotations; +``` + + +## Subscribe to annotations
+ +{`annotations.subscribe(type: string | string[], listener?: messageCallback): Promise`} + +Register a listener that is called each time an `Annotation` matching one of the given types is received on the channel. + +{`annotations.subscribe(listener?: messageCallback): Promise`} + +Register a listener that is called each time any `Annotation` is received on the channel, regardless of type. + +To receive individual realtime annotations (instead of just the rolled-up summaries), the `annotation_subscribe` [channel mode](/docs/channels/options#modes) must be requested, since annotations are not delivered by default. Most clients will not need this and can rely on the summary updates instead. + +### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| type | Optional | A specific annotation type, or an array of types, to register the listener for. | String or `String[]` | +| listener | Optional | A function called with each matching `Annotation`. | `messageCallback` | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled once the listener has been registered, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Publish an annotation + +{`annotations.publish(message: Message, annotation: OutboundAnnotation): Promise`} + +Publish an annotation to a message identified by a `Message` object. + +{`annotations.publish(messageSerial: string, annotation: OutboundAnnotation): Promise`} + +Publish an annotation to a message identified by its serial string. + +The `action` is set automatically to `annotation.create`. If a `clientId` is set on the client, it is associated with the annotation; some annotation summarization methods require an identified client. + +### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| message | Required | A `Message` object identifying the message to annotate. Provide either `message` or `messageSerial`. | [Message](/docs/pub-sub/api/javascript/realtime/message) | +| messageSerial | Required | The serial string of the message to annotate. Provide either `message` or `messageSerial`. | String | +| annotation | Required | The annotation to publish. Must include at least a `type`; other required fields depend on the annotation type. |
| + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the annotation has been published to Ably, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Delete an annotation + +{`annotations.delete(message: Message, annotation: OutboundAnnotation): Promise`} + +Remove an annotation contribution from a message identified by a `Message` object. + +{`annotations.delete(messageSerial: string, annotation: OutboundAnnotation): Promise`} + +Remove an annotation contribution from a message identified by its serial string. + +This removes the contribution this `clientId` previously made to the annotation summary for the message. The exact behaviour depends on the annotation type. The `action` is set automatically to `annotation.delete`. The annotation must include a `type` and may include a `name`. + +### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| message | Required | A `Message` object identifying the message whose annotation you want to delete. Provide either `message` or `messageSerial`. | [Message](/docs/pub-sub/api/javascript/realtime/message) | +| messageSerial | Required | The serial string of the message whose annotation you want to delete. Provide either `message` or `messageSerial`. | String | +| annotation | Required | The annotation deletion request. Must include at least a `type`; other required fields depend on the annotation type. |
| + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the deletion request has been published to Ably, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Get annotations for a message + +{`annotations.get(message: Message, params?: GetAnnotationsParams): Promise>`} + +Retrieve all annotations for a message identified by a `Message` object. + +{`annotations.get(messageSerial: string, params?: GetAnnotationsParams): Promise>`} + +Retrieve all annotations for a message identified by its serial string. + +Annotations are returned ordered from earliest to most recent. If you only need the latest summary, prefer [`channel.getMessage()`](/docs/pub-sub/api/javascript/realtime/realtime-channel#get-message); use `annotations.get()` only when you need the full list of raw annotations. + +### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| message | Required | A `Message` object identifying the message to get annotations for. Provide either `message` or `messageSerial`. | [Message](/docs/pub-sub/api/javascript/realtime/message) | +| messageSerial | Required | The serial string of the message to get annotations for. Provide either `message` or `messageSerial`. | String | +| params | Optional | Restrictions on which annotations to return, in particular a limit. |
| + +
+ +### Returns
+ +`Promise>` + +Returns a promise, fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) containing an array of `Annotation` objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + + + +| Property | Description | Type | +| --- | --- | --- | +| id | Unique ID assigned by Ably to this annotation. | String | +| clientId | The client ID of the publisher of this annotation, if any. | String | +| name | The name of the annotation. This is the field that most annotation aggregations operate on. | String | +| count | An optional count, only relevant to certain aggregation types. | Number | +| data | An arbitrary publisher-provided payload, if provided. Not aggregated. | Any | +| encoding | The encoding of the payload; typically empty as the data is decoded client-side back into the original data type. | String | +| timestamp | Timestamp of when the annotation was received by Ably, as milliseconds since the Unix epoch. | Number | +| action | The action, whether this is an annotation being added or removed. |
| +| serial | This annotation's unique serial, lexicographically totally ordered. | String | +| messageSerial | The serial of the message that this annotation is annotating. | String | +| type | The annotation type, typically a name together with an aggregation method, for example `emoji:distinct.v1`. | String | +| extras | A JSON object for metadata and ancillary payloads. | Any | + +
+ +## Unsubscribe from annotations
+ +{`annotations.unsubscribe(type: string | string[], listener: messageCallback): void`} + +Remove the given listener for the specified annotation type or types. + +{`annotations.unsubscribe(type: string | string[]): void`} + +Remove all listeners registered for the specified annotation type or types. + +{`annotations.unsubscribe(listener: messageCallback): void`} + +Remove the given listener from all annotation types. + +{`annotations.unsubscribe(): void`} + +Remove all annotation listeners on the channel. + +### Parameters + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| type | Optional | A specific annotation type, or an array of types, to deregister listeners for. | String or `String[]` | +| listener | Optional | The specific listener function to deregister. | `messageCallback` | + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| type | Required | The annotation type, typically a name together with an aggregation method, for example `emoji:distinct.v1`. Handled opaquely by the SDK and validated server-side. | String | +| name | Optional | The name of the annotation. This is the field that most annotation aggregations operate on. | String | +| count | Optional | An optional count, only relevant to certain aggregation types. | Number | +| data | Optional | An arbitrary publisher-provided payload. Not aggregated. | Any | +| encoding | Optional | The encoding of the payload. | String | +| extras | Optional | A JSON object for metadata and ancillary payloads. | Any | + + + + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| limit | Optional | An upper limit on the number of annotations returned. The default is 100, and the maximum is 1000. | Number | + + + + + +| Value | Description | +| --- | --- | +| annotation.create | The annotation is being added. | +| annotation.delete | The annotation is being removed. | + + + +## Create an annotation from an encoded object
+ +{`Annotation.fromEncoded(encodedAnnotation: Object, channelOptions?: ChannelOptions): Promise`} + +A static factory method to create an `Annotation` from a deserialized `Annotation`-like object encoded using Ably's wire protocol. Accessed on the class as `Ably.Realtime.Annotation`. The returned promise resolves with the decoded annotation. + + +```javascript +const annotation = await Ably.Realtime.Annotation.fromEncoded(encodedAnnotation); +``` + + +### Parameters + +The `Annotation.fromEncoded()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| encodedAnnotation | Required | An `Annotation`-like deserialized object. | Object | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/realtime/channels#get) | + +
+ +### Returns
+ +`Promise` + +Returns a promise that resolves with an `Annotation` object decoded from the supplied object. + +## Create annotations from an encoded array + +{`Annotation.fromEncodedArray(encodedAnnotations: Object[], channelOptions?: ChannelOptions): Promise`} + +A static factory method to create an array of `Annotation` objects from an array of deserialized `Annotation`-like objects encoded using Ably's wire protocol. The returned promise resolves with the decoded annotations. + + +```javascript +const annotations = await Ably.Realtime.Annotation.fromEncodedArray(encodedAnnotations); +``` + + +### Parameters + +The `Annotation.fromEncodedArray()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| encodedAnnotations | Required | An array of `Annotation`-like deserialized objects. | `Array` | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/realtime/channels#get) | + +
+ +### Returns + +`Promise` + +Returns a promise that resolves with an array of `Annotation` objects decoded from the supplied array. diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/realtime-channel.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/realtime-channel.mdx new file mode 100644 index 0000000000..07dd25de67 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/realtime-channel.mdx @@ -0,0 +1,760 @@ +--- +title: RealtimeChannel +meta_description: "API reference for the Channel (RealtimeChannel) interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, RealtimeChannel API, attach, detach, publish, subscribe, history, on, once, off, setOptions, ChannelState, ChannelEvent, PaginatedResult" +--- + +A `RealtimeChannel` represents a single channel, obtained via the [`channels.get()`](/docs/pub-sub/api/javascript/realtime/channels#get) method. Use it to publish and subscribe to messages, manage channel state, and access channel features such as presence, push notifications, and annotations. + + +```javascript +const channel = realtime.channels.get('{{RANDOM_CHANNEL_NAME}}'); +``` + + +## Properties + +The `RealtimeChannel` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| name | The name of this channel. | String | +| state | The current [channel state](/docs/channels/states). |
| +| errorReason | When a channel failure occurs, this property contains the error. | [ErrorInfo](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) or Undefined | +| presence | Access the [`RealtimePresence`](/docs/pub-sub/api/javascript/realtime/realtime-presence) object for this channel. | [RealtimePresence](/docs/pub-sub/api/javascript/realtime/realtime-presence) | +| push | Access the [`PushChannel`](/docs/pub-sub/api/javascript/realtime/push) object for this channel. | [PushChannel](/docs/pub-sub/api/javascript/realtime/push) | +| annotations | Access the `RealtimeAnnotations` object for this channel, used to publish, delete, retrieve, and subscribe to [annotations](/docs/messages/annotations) on messages. | [RealtimeAnnotations](/docs/pub-sub/api/javascript/realtime/realtime-annotations) | +| params | The current [channel parameters](/docs/channels/options#params) in effect for this channel. | `Record` | +| modes | The current [channel modes](/docs/channels/options#modes) in effect for this channel. | `ResolvedChannelMode[]` | + +
+ + + +| Value | Description | +| --- | --- | +| initialized | The channel has been initialized but no attach has yet been attempted. | +| attaching | An attach has been initiated by sending a request to Ably. This is a transient state and will be followed by `attached` or `failed`. | +| attached | The attach has succeeded. In the `attached` state, a client may publish, subscribe to, and be present in the channel. | +| detaching | A detach has been initiated on an `attached` channel by sending a request to Ably. | +| detached | The channel has been detached or the channel has not been attached. | +| suspended | The channel was previously attached, but the client is now disconnected and the SDK is unable to communicate with the Ably service. Any messages published while in this state are buffered for delivery once the channel becomes attached again. | +| failed | An indefinite failure condition. This state is entered if a channel error has been received from the Ably service, such as an attempt to attach without the necessary access rights. | + + + +## Subscribe to messages
+ +{`channel.subscribe(listener: messageCallback): Promise`} + +Subscribe to all messages on this channel. The listener is called for every message received. + +{`channel.subscribe(event: string, listener?: messageCallback): Promise`} + +Subscribe only to messages with a specific event name (client-side filter). + +{`channel.subscribe(events: string[], listener?: messageCallback): Promise`} + +Subscribe to messages matching any event name in the array (client-side filter). + +{`channel.subscribe(filter: MessageFilter, listener?: messageCallback): Promise`} + +Register a listener for messages on this channel that match the supplied filter. Filtering happens server-side as part of [filtered subscriptions](/docs/pub-sub/advanced#subscription-filters). + + +```javascript +// All messages +await channel.subscribe((message) => { + console.log(message.name, message.data); +}); + +// Specific event +await channel.subscribe('greeting', (message) => { + console.log('Hi:', message.data); +}); + +// Server-side filter (filtered subscription) +await channel.subscribe({ name: 'click', clientId: 'user-123' }, (message) => { + console.log('Filtered:', message.data); +}); +``` + + +If the channel is `initialized`, calling `subscribe()` implicitly attaches the channel. + +Calling `subscribe()` with an event name is a client-side filter. All messages are still sent over the wire, regardless of name. To filter messages server-side, use [filtered subscriptions](/docs/pub-sub/advanced#subscription-filters) with a `filter` argument. + +When subscribing, keep the following behaviours in mind: + +* If `subscribe()` is called more than once with the same listener, duplicates are registered. If you subscribe twice with the same listener and a message is later received, that listener is invoked twice. +* A registered listener remains active on the channel regardless of the current channel state. If you subscribe when a channel is `attached` and it later becomes `detached` or `failed`, the listener is still invoked when the channel reattaches and a message is received. Listeners are only removed by calling [`unsubscribe()`](#unsubscribe) or when the channel is released using [`channels.release()`](/docs/pub-sub/api/javascript/realtime/channels#release). +* If an exception is thrown in a listener and bubbles up to the event emitter, it is caught and logged at `error` level, so as not to affect other listeners for the same event. + +### Parameters + +The `subscribe()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| event | Optional | The event name to subscribe to. | String | +| events | Optional | An array of event names to subscribe to. | `String[]` | +| filter | Optional | A filter object used to filter messages server-side. |
| +| listener | Optional | A function called with each matching [`Message`](/docs/pub-sub/api/javascript/realtime/message). Required when subscribing to all messages; with an `event`, `events`, or `filter` argument it may be omitted to attach the channel without registering a listener. | Function | + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| name | Optional | A regular expression to match against the message name. | String | +| refTimeserial | Optional | A reference timeserial to match against. Useful for filtering message updates or annotations against the original message. | String | +| refType | Optional | A reference type to match against (for example `com.ably.reaction` for reactions). | String | +| isRef | Optional | Whether to match only messages that have a ref (`true`), only those that don't (`false`), or both (omitted). | Boolean | +| clientId | Optional | A `clientId` to match against. | String | + + + +### Returns
+ +`Promise` + +Returns a promise. On successful channel attachment, the promise is fulfilled with a `ChannelStateChange`. If the channel was already attached, the promise resolves with `null`. On failure, the promise is rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Publish a message + +{`channel.publish(name: string, data: any, options?: PublishOptions): Promise`} + +Publish a single message on the channel based on a given event name and payload. + +{`channel.publish(message: Message, options?: PublishOptions): Promise`} + +Publish a single message object on the channel. + +{`channel.publish(messages: Message[], options?: PublishOptions): Promise`} + +Publish multiple messages atomically on the channel. This means that: + +* Either all messages will be successfully published or none of them will. +* The [max message size](/docs/platform/pricing/limits#message) limit applies to the total size of all messages in the array. +* The publish counts as a single message for the purpose of [per-channel rate limit](/docs/platform/pricing/limits#message). +* If you are using client-specified message IDs, they must conform to certain restrictions. + +When `publish()` is called, the SDK will not implicitly attach to the channel so long as [transient publishing](/docs/pub-sub/advanced#transient-publish) is available. Otherwise, it will implicitly attach. + + +```javascript +await channel.publish('greeting', 'Hello, World!'); + +// Or with a Message object +await channel.publish({ name: 'greeting', data: 'Hello' }); + +// Or atomic batch +await channel.publish([ + { name: 'event1', data: 'one' }, + { name: 'event2', data: 'two' } +]); +``` + + +### Parameters + +The `publish()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| name | Required | The event name. | String | +| data | Required | The data payload for the message. Supported payload types are strings, JSON-serializable objects and arrays, buffers containing arbitrary binary data, and `null`. If sending binary data, that binary should be the entire payload; an object with a binary field within it may not be correctly encoded. | Any | +| message | Required | A single [`Message`](/docs/pub-sub/api/javascript/realtime/message) object to publish. | [Message](/docs/pub-sub/api/javascript/realtime/message) | +| messages | Required | An array of [`Message`](/docs/pub-sub/api/javascript/realtime/message) objects to publish atomically. | [Message](/docs/pub-sub/api/javascript/realtime/message)[] | +| options | Optional | Options affecting the publish, such as `quickAck`. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| quickAck | Optional | Whether to wait for an early acknowledgement of the publish, rather than the standard acknowledgement that the message has been processed and persisted. Default: `false`. | Boolean | + + + +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with a `PublishResult` when the message(s) have been delivered to Ably, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + + + +| Property | Description | Type | +| --- | --- | --- | +| serials | An array of message serials corresponding 1:1 to the messages that were published. A serial may be `null` if the message was discarded due to a [message conflation](/docs/messages#conflation). | Array of String or Null | + +
+ +## Update a message
+ +{`channel.updateMessage(message: Message, operation?: MessageOperation, options?: PublishOptions): Promise`} + +Publish an [update](/docs/messages/updates-deletes#update) to an existing message using shallow mixin semantics. Non-null `name`, `data`, and `extras` fields in the provided message replace the corresponding fields in the existing message; null fields are left unchanged. Requires the `message-update-own` or `message-update-any` [capability](/docs/auth/capabilities). + +### Parameters + +The `updateMessage()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| message | Required | The message to update. Must include the `serial` of the message being updated. | [Message](/docs/pub-sub/api/javascript/realtime/message) | +| operation | Optional | Metadata about the update operation. |
| +| options | Optional | Options affecting the publish of the update. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| clientId | Optional | The client ID performing the operation. | String | +| description | Optional | A human-readable description of why the operation was performed. | String | +| metadata | Optional | Additional metadata associated with the operation. | `Record` | + + + +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with an `UpdateDeleteResult` containing the updated version metadata, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + + + +| Property | Description | Type | +| --- | --- | --- | +| versionSerial | The serial of the new version of the message produced by the update, delete, or append operation. `null` if the message was superseded by a subsequent update before it could be published. | String or Null | + +
+ +## Append to a message
+ +{`channel.appendMessage(message: Message, operation?: MessageOperation, options?: PublishOptions): Promise`} + +[Append](/docs/messages/updates-deletes#append) data to an existing message on the channel. The supplied `data` is appended to the previous message's data, while `name` and `extras` replace the previous values if provided. Subscribers receive a `message.append` action. Requires the `message-update-own` or `message-update-any` [capability](/docs/auth/capabilities). + +### Parameters + +The `appendMessage()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| message | Required | The message to append data to. Must include the `serial` of the target message. | [Message](/docs/pub-sub/api/javascript/realtime/message) | +| operation | Optional | Metadata about the append operation. |
| +| options | Optional | Options affecting the publish of the append. |
| + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with an `UpdateDeleteResult`, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Delete a message + +{`channel.deleteMessage(message: Message, operation?: MessageOperation, options?: PublishOptions): Promise`} + +Mark a message as [deleted](/docs/messages/updates-deletes#delete) by publishing an update with an action of `MESSAGE_DELETE`. This does not remove the message from the server, and the full message history remains accessible. Uses shallow mixin semantics: non-null `name`, `data`, and `extras` fields in the provided message replace the corresponding fields in the existing message; null fields are left unchanged. Subscribers receive a `message.delete` action. Requires the `message-delete-own` or `message-delete-any` [capability](/docs/auth/capabilities). + +### Parameters + +The `deleteMessage()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| message | Required | The message to delete. Must include the `serial` of the message being deleted. | [Message](/docs/pub-sub/api/javascript/realtime/message) | +| operation | Optional | Metadata about the delete operation. |
| +| options | Optional | Options affecting the publish of the delete. |
| + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with an `UpdateDeleteResult`, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Get a single message by serial + +{`channel.getMessage(serialOrMessage: string | Message): Promise`} + +Retrieve the [latest version](/docs/messages/updates-deletes#get) of a message by its serial. Requires the `history` [capability](/docs/auth/capabilities). + +### Parameters + +The `getMessage()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| serialOrMessage | Required | Either the serial identifier string of the message to retrieve, or a [`Message`](/docs/pub-sub/api/javascript/realtime/message) object containing a populated `serial` field. | String or [Message](/docs/pub-sub/api/javascript/realtime/message) | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with the [`Message`](/docs/pub-sub/api/javascript/realtime/message), or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Unsubscribe from messages + +{`channel.unsubscribe(event: string, listener: messageCallback): void`} + +Remove the given listener for the specified event. + +{`channel.unsubscribe(events: string[], listener: messageCallback): void`} + +Remove the given listener from all events in the array. + +{`channel.unsubscribe(event: string): void`} + +Remove all listeners registered for the specified event. + +{`channel.unsubscribe(events: string[]): void`} + +Remove all listeners registered for any event in the array. + +{`channel.unsubscribe(filter: MessageFilter, listener?: messageCallback): void`} + +Remove the listener registered for the specified filter, or all listeners for the filter if `listener` is omitted. + +{`channel.unsubscribe(listener: messageCallback): void`} + +Remove the given listener from all events. + +{`channel.unsubscribe(): void`} + +Remove all message listeners on this channel. + + +```javascript +channel.unsubscribe(); +``` + + +### Parameters + +The `unsubscribe()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| event | Optional | A single event name to stop listening to. | String | +| events | Optional | An array of event names to stop listening to. | `String[]` | +| filter | Optional | The message filter whose listener should be removed. |
| +| listener | Optional | The listener to remove. If omitted, all listeners matching the supplied event(s) or filter are removed; if no arguments are given, all message listeners on the channel are removed. | Function | + +
+ +## Attach to the channel
+ +{`channel.attach(): Promise`} + +Attach to the channel. This first attempts to connect to Ably if not already connected, then sends an attach message for this channel. If the channel is already attached, this is a no-op and the promise resolves with `null`. + +As a convenience, `attach()` is called implicitly if [`subscribe()`](#subscribe) is called on the channel, or if [`presence.enter()`](/docs/pub-sub/api/javascript/realtime/realtime-presence#enter) or [`presence.subscribe()`](/docs/pub-sub/api/javascript/realtime/realtime-presence#subscribe) is called on the channel's presence. + + +```javascript +await channel.attach(); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled with a `ChannelStateChange` describing the transition to `attached`, or `null` if the channel was already attached. Rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object if the attach fails. + +## Detach from the channel + +{`channel.detach(): Promise`} + +Detach from the channel. Any resulting channel state change is emitted to listeners registered using [`on()`](#on) or [`once()`](#once). Once all clients globally have detached from the channel, the channel is released in the Ably service within two minutes. + + +```javascript +await channel.detach(); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled when the channel has been detached, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Set channel options + +{`channel.setOptions(options: ChannelOptions): Promise`} + +Configure the channel with new `ChannelOptions`. If the channel is already attached and the new options require a re-attach (for example, new channel modes or new params), the channel will be re-attached with the new options. + + +```javascript +await channel.setOptions({ cipher: { key } }); +``` + + +### Parameters + +The `setOptions()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| options | Required | The new channel options. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| cipher | Optional | Requests [encryption](/docs/channels/options/encryption) for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length, and key). | or
| +| params | Optional | [Channel parameters](/docs/channels/options) that configure the behavior of the channel. | `Record` | +| modes | Optional | An array of channel mode values that restrict the operations a client can perform on a channel. | Array of
| +| attachOnSubscribe | Optional | Whether calling [`subscribe()`](#subscribe) on a channel or presence object should trigger an implicit attach. Default: `true`. | Boolean | + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| key | The private key used for encryption and decryption. Can be binary or base64-encoded. | `ArrayBuffer`, `Uint8Array`, `Buffer`, or String | +| algorithm | The name of the algorithm. Default: `AES`. | String | +| keyLength | The key length in bits of the cipher. Either 128 or 256. Default: 256. | Number | +| mode | The cipher mode. Default: `CBC`. | String | + + + + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| key | Required | The private key used for encryption and decryption. Can be binary or base64-encoded. | `ArrayBuffer`, `Uint8Array`, `Buffer`, or String | +| algorithm | Optional | The name of the algorithm. Default: `AES`. | String | +| keyLength | Optional | The key length in bits. Either 128 or 256. Default: 256. | Number | +| mode | Optional | The cipher mode. Default: `CBC`. | String | + + + + + +| Value | Description | +| --- | --- | +| PUBLISH | The client can publish messages to the channel. | +| SUBSCRIBE | The client can subscribe to messages on the channel. | +| PRESENCE | The client can enter the presence set on the channel. | +| PRESENCE_SUBSCRIBE | The client can subscribe to presence events on the channel. | +| OBJECT_PUBLISH | The client can publish LiveObjects messages on the channel. | +| OBJECT_SUBSCRIBE | The client can subscribe to LiveObjects messages on the channel. | +| ANNOTATION_PUBLISH | The client can publish annotations on the channel. | +| ANNOTATION_SUBSCRIBE | The client can subscribe to annotations on the channel. | + + + +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled once the options have been applied (and the channel re-attached if required), or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Register a channel state listener + +{`channel.on(event: ChannelEvent, listener: channelEventCallback): void`} + +Register a listener for a single channel event. + +{`channel.on(events: ChannelEvent[], listener: channelEventCallback): void`} + +Register a listener for any of an array of channel events. + +{`channel.on(listener: channelEventCallback): void`} + +Register a listener for all channel events. + +In every form the listener receives a `ChannelStateChange` object describing the transition. + +If an exception is thrown in the listener and bubbles up to the event emitter, it is caught and logged at `error` level, so as not to affect other listeners. + + +```javascript +channel.on('attached', (stateChange) => { + console.log('Now attached'); +}); +``` + + +### Parameters + +The `on()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| event | Optional | A single channel event to listen for. |
| +| events | Optional | An array of channel events to listen for. |
[] | +| listener | Required | A function invoked for each matching event. If neither `event` nor `events` is supplied, it fires for every event. |
| + +
+ + + +| Value | Description | +| --- | --- | +| initialized | The channel has been initialized but no attach has yet been attempted. | +| attaching | An attach has been initiated by sending a request to Ably. | +| attached | The attach has succeeded. | +| detaching | A detach has been initiated. | +| detached | The channel has been detached. | +| suspended | The channel has been suspended. | +| failed | The channel has entered a failed state. | +| update | An update to the channel has occurred (typically a re-attach with updated capability or channel options) while the channel state remains `attached`. | + + + + + +| Parameter | Description | Type | +| --- | --- | --- | +| stateChange | The channel state change that occurred. | | + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| current | The new channel state. | | +| previous | The previous channel state. For the `update` event, this will be equal to the `current` state. |
| +| event | The event that triggered this state change. |
| +| reason | An `ErrorInfo` containing any information relating to the transition. | [ErrorInfo](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) or Undefined | +| resumed | When the channel has reattached after a loss of connection, `resumed` is `true` if message continuity is preserved (no missed messages), or `false` if it was not. | Boolean | +| hasBacklog | Indicates whether the client can expect a backlog of messages from a [rewind](/docs/channels/options/rewind) or resume. | Boolean or Undefined | + +
+ +## Register a one-time channel state listener
+ +{`channel.once(event: ChannelEvent, listener: channelEventCallback): void`} + +Register a one-time listener for a single channel event. It is invoked the next time that event occurs, then removed. + +{`channel.once(listener: channelEventCallback): void`} + +Register a one-time listener for the next channel event of any type. + +{`channel.once(event: ChannelEvent): Promise`} + +Return a promise that resolves the next time the specified event occurs. + +{`channel.once(): Promise`} + +Return a promise that resolves the next time any event occurs. + +The callback-based forms return `void`; the promise-based forms return a promise that resolves with the next matching `ChannelStateChange`. + +If an exception is thrown in the listener and bubbles up to the event emitter, it is caught and logged at `error` level, so as not to affect other listeners. + + +```javascript +await channel.once('attached'); +``` + + +### Parameters + +The `once()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| event | Optional | The channel event to listen for. If omitted, the listener fires for any event. |
| +| listener | Optional | A function invoked once with the next matching event. Omit to return a promise instead. |
| + +
+ +### Returns
+ +The callback-based overloads return `void`. + +The promise-based overloads return `Promise`, fulfilled with a `ChannelStateChange` the next time a matching event occurs. + +## Remove a channel state listener + +{`channel.off(event: ChannelEvent, listener: channelEventCallback): void`} + +Remove the given listener for a specific channel event. + +{`channel.off(listener: channelEventCallback): void`} + +Remove the given listener from all channel events. + +{`channel.off(): void`} + +Remove all channel state listeners. + + +```javascript +channel.off(); +``` + + +### Parameters + +The `off()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| event | Optional | The channel event to stop listening to. If omitted, the listener is removed from all events. |
| +| listener | Optional | The listener to remove. If omitted, all listeners (for the given event, or for the whole channel) are removed. |
| + +
+ +## Get registered listeners
+ +{`channel.listeners(eventName?: ChannelEvent): null | channelEventCallback[]`} + +Returns the channel state listeners registered for the specified `ChannelEvent`. If `eventName` is omitted, returns all registered listeners. Returns `null` if there are no matching listeners. + +### Parameters + +The `listeners()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| eventName | Optional | The channel event to filter listeners by. |
| + +
+ +### Returns
+ +`null | channelEventCallback[]` + +Returns an array of the registered listener functions, or `null` if there are none. + +## Wait for a channel state + +{`channel.whenState(targetState: ChannelState): Promise`} + +If the channel is already in the given state, returns a promise which immediately resolves to `null`. Otherwise calls [`once()`](#once) to return a promise which resolves the next time the channel transitions to the given state. + +### Parameters + +The `whenState()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| targetState | Required | The channel state to wait for. |
| + +
+ +### Returns
+ +`Promise` + +Returns a promise. If the channel is already in the given state, resolves to `null`. Otherwise resolves with the `ChannelStateChange` when the channel next transitions to that state. + +## Get message history + +{`channel.history(params?: RealtimeHistoryParams): Promise>`} + +Retrieve a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) of historical messages for this channel. If the channel is [configured to persist messages](/docs/storage-history/storage), message history is available for the persistence duration configured for your account. If not, messages are only retained in memory by the Ably service for two minutes. + + +```javascript +const page = await channel.history({ limit: 50, direction: 'backwards' }); +page.items.forEach((message) => console.log(message.data)); +``` + + +### Parameters + +The `history()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Optional | Query parameters to filter and control retrieval. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| start | Optional | The time from which messages are retrieved, as milliseconds since the Unix epoch. Default: the beginning of time. | Number | +| end | Optional | The time until which messages are retrieved, as milliseconds since the Unix epoch. Default: current time. | Number | +| direction | Optional | The order of returned messages. `'backwards'` orders from most recent to oldest; `'forwards'` orders from oldest to most recent. Default: `'backwards'`. | String | +| limit | Optional | An upper limit on the number of messages returned. Default: 100. Maximum: 1000. | Number | +| untilAttach | Optional | When `true`, retrieves [continuous history](/docs/storage-history/history#continuous-history) up until the point of the channel being attached. Requires `direction` to be `'backwards'` (the default). If the channel is not attached, or if `direction` is set to `'forwards'`, this option results in an error. Default: `false`. | Boolean | + + + +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) containing an array of [`Message`](/docs/pub-sub/api/javascript/realtime/message) objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Get all versions of a message + +{`channel.getMessageVersions(serialOrMessage: string | Message, params?: RealtimeHistoryParams): Promise>`} + +Retrieve all historical [versions](/docs/messages/updates-deletes#versions) of a message identified by its serial, ordered by version. This includes the original message and all subsequent updates and delete operations. Requires the `history` [capability](/docs/auth/capabilities). + +### Parameters + +The `getMessageVersions()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| serialOrMessage | Required | Either the serial identifier string of the message whose versions are to be retrieved, or a [`Message`](/docs/pub-sub/api/javascript/realtime/message) object containing a populated `serial` field. | String or [Message](/docs/pub-sub/api/javascript/realtime/message) | +| params | Optional | Query parameters to filter and control retrieval. |
| + +
+ +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) of message versions, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/realtime-client.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/realtime-client.mdx new file mode 100644 index 0000000000..f14ed17dd5 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/realtime-client.mdx @@ -0,0 +1,580 @@ +--- +title: Realtime +meta_description: "API reference for the Realtime client class in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Realtime, Realtime client, constructor, ClientOptions, auth, channels, connection, push, close, connect, time, stats, request, batchPublish, batchPresence, device, ErrorInfo" +--- + +The `Realtime` class is the main entry point for using the Ably Pub/Sub JavaScript SDK in realtime mode. It maintains a persistent connection to Ably and provides access to channels, presence, push notifications, and authentication. + + +```javascript +const realtime = new Ably.Realtime({ + authCallback: async (tokenParams, callback) => { + try { + // Request an Ably-compatible JWT from your own server + const response = await fetch('https://your-server.example.com/ably-jwt'); + const jwt = await response.text(); + callback(null, jwt); + } catch (error) { + callback(error, null); + } + }, +}); +``` + + +This example uses [token authentication](/docs/auth/token): the [`authCallback`](#constructor) requests an [Ably-compatible JWT](/docs/auth/token/jwt) from your server whenever a token is needed, which keeps your API key off the client. This is the recommended approach for browsers and other untrusted clients. For trusted, server-side environments you can instead pass a `key` directly to use [basic authentication](/docs/auth/basic). + + + +## Properties + +The `Realtime` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| auth | The [`Auth`](/docs/pub-sub/api/javascript/realtime/auth) object for this client. Manages tokens and authentication. | [Auth](/docs/pub-sub/api/javascript/realtime/auth) | +| channels | The [`Channels`](/docs/pub-sub/api/javascript/realtime/channels) collection for this client. Used to obtain `RealtimeChannel` instances. | [Channels](/docs/pub-sub/api/javascript/realtime/channels) | +| connection | The [`Connection`](/docs/pub-sub/api/javascript/realtime/connection) object for this client. Use this to inspect or subscribe to the connection state. | [Connection](/docs/pub-sub/api/javascript/realtime/connection) | +| push | The [`Push`](/docs/pub-sub/api/javascript/realtime/push) object for this client. Used for push notification device activation and admin operations. | [Push](/docs/pub-sub/api/javascript/realtime/push) | +| clientId | The client ID this client is identified as. `null` if anonymous. | String or Null | +| Crypto | Static access to the [`Crypto`](/docs/pub-sub/api/javascript/realtime/crypto) utility. Accessed on the class: `Ably.Realtime.Crypto`. | [Crypto](/docs/pub-sub/api/javascript/realtime/crypto) | +| Message | Static access to the [`Message`](/docs/pub-sub/api/javascript/realtime/message) class for `fromEncoded()` factory methods. Accessed on the class: `Ably.Realtime.Message`. | [Message](/docs/pub-sub/api/javascript/realtime/message) | +| PresenceMessage | Static access to the [`PresenceMessage`](/docs/pub-sub/api/javascript/realtime/presence-message) class for `fromEncoded()` factory methods. Accessed on the class: `Ably.Realtime.PresenceMessage`. | [PresenceMessage](/docs/pub-sub/api/javascript/realtime/presence-message) | +| Annotation | Static access to the [`Annotation`](/docs/pub-sub/api/javascript/realtime/realtime-annotations) type for `fromEncoded()` factory methods. Accessed on the class: `Ably.Realtime.Annotation`. | [Annotation](/docs/pub-sub/api/javascript/realtime/realtime-annotations) | + +
+ +## Create a new Realtime client
+ +{`new Ably.Realtime(options: ClientOptions)`} + +Construct a client with a `ClientOptions` object. This is the most common form, allowing all available client options to be configured. + +{`new Ably.Realtime(keyOrToken: string)`} + +A convenience constructor that takes a single API key or token string. Equivalent to passing `{ key: '' }` or `{ token: '' }` as `ClientOptions`. Useful for simple basic-authenticated or test setups. + + +```javascript +// With ClientOptions +const realtime = new Ably.Realtime({ + key: '{{API_KEY}}', + clientId: 'user-123', + logLevel: 3 +}); + +// Or with just a key string +const realtime = new Ably.Realtime('{{API_KEY}}'); +``` + + +### Parameters + +The `Realtime()` constructor takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| options | Required | Configuration options for the client. All properties are optional unless noted. |
| +| keyOrToken | Required | A full API key string for basic authentication, or a token string. | String | + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| key | Optional | The full API key string, as obtained from the [Ably dashboard](https://ably.com/dashboard). Use this option to use [basic authentication](/docs/auth/basic), or to issue Ably Tokens without deferring to a separate entity to sign Ably `TokenRequest`s. Initializing with a `key` does not necessarily mean the client uses basic auth: it can also create and sign Ably `TokenRequest`s, and can use token authentication itself if it needs to or if `useTokenAuth` is enabled. | String | +| token | Optional | An authenticated token (string) or `TokenDetails` for Token authentication. This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that lets the SDK renew the token automatically when the previous one expires, such as `authUrl` or `authCallback`. | String or | +| tokenDetails | Optional | A `TokenDetails` object. Used primarily for testing. |
| +| authCallback | Optional | Function called when a new token is required, following the [`AuthOptions`](/docs/pub-sub/api/javascript/realtime/auth#authorize) contract. | Function | +| authUrl | Optional | URL the SDK may call to obtain a token string, `TokenRequest`, or `TokenDetails`. | String | +| authMethod | Optional | HTTP verb (`GET` or `POST`) for `authUrl` requests. Default: `GET`. | String | +| authHeaders | Optional | Key-value headers added to `authUrl` requests. If the `authHeaders` object contains an `authorization` key, then `withCredentials` is set on the XHR request. | Object | +| authParams | Optional | Key-value parameters added to `authUrl` requests as query string (GET) or form data (POST). | Object | +| useTokenAuth | Optional | When `true`, forces token authentication. If no `clientId` is specified, the issued token is anonymous. | Boolean | +| queryTime | Optional | When `true`, queries Ably for the current time when issuing `TokenRequest`s rather than using the local clock. Knowing the time accurately is needed to create valid signed Ably `TokenRequest`s, so this option is useful for SDK instances on auth servers whose clock cannot be kept synchronized through normal means, such as an NTP daemon. The server is queried once per client instance, which stores the offset from the local clock, so you should avoid instancing a new SDK instance per request. Default: `false`. | Boolean | +| defaultTokenParams | Optional | The default `TokenParams` used when issuing tokens. |
| +| clientId | Optional | A non-empty client ID for this client. Cannot contain `*`. Used for publishing and presence. A `clientId` may also be implicit in a token used to instantiate the SDK; an error is raised if a `clientId` specified here conflicts with the `clientId` implicit in the token. Find out more about [identified clients](/docs/auth/identified-clients). | String | +| autoConnect | Optional | Whether to connect to Ably as soon as the client is instantiated. Default: `true`. | Boolean | +| closeOnUnload | Optional | Whether to send a close request on the browser `unload` event. Enabling this causes presence leave events to fire immediately when a user navigates away or closes the browser. Without it, an abruptly disconnected client is removed from presence after around 15 seconds and the connection state is retained for around two minutes. Default: `true`. | Boolean | +| echoMessages | Optional | Whether messages published from this connection are also received back. Default: `true`. | Boolean | +| queueMessages | Optional | Whether messages published while in the disconnected or connecting states are queued for delivery once reconnected. The default behaviour lets applications publish immediately on instancing the SDK without waiting for the connection to be established. Disable this option to take application-level control over queueing. Default: `true`. | Boolean | +| recover | Optional | A recovery key string, or a callback that enables [connection state recovery](/docs/connect/states#connection-state-recover-options). When a callback is provided, the SDK persists the recovery key between page reloads and calls the callback so it can decide whether to recover the connection. | String or
| +| recoveryKeyStorageName | Optional | The storage key used for persisting the recovery key. | String | +| endpoint | Optional | A custom routing policy or fully-qualified host name for the Ably service. Enables [enterprise customers](/docs/platform/account/enterprise-customization) to use their own custom endpoints, which support dedicated, isolated clusters and regional message routing and storage constraints. | String | +| environment | Optional | Deprecated, use `endpoint` instead. Enables [enterprise customers](/docs/platform/account/enterprise-customization) to use their own custom environments, which support dedicated, isolated clusters and regional message routing and storage constraints. | String | +| port | Optional | A non-default port for non-TLS connections. Default: `80`. | Number | +| tls | Optional | Whether to use a secure TLS connection. An insecure connection cannot be used with basic authentication, as it could compromise the private API key in transit. Default: `true`. | Boolean | +| tlsPort | Optional | A non-default port for TLS connections. Default: `443`. | Number | +| fallbackHosts | Optional | An array of alternative hosts used for failover. When a custom environment or endpoint is specified, fallback host functionality is disabled; in that case, use any custom fallback hosts provided by your customer success manager. Default: the five `a`–`e` `.ably-realtime.com` hosts. | `String[]` | +| transports | Optional | Preferred transports for the realtime connection, in descending order of preference. In the browser the available transports are `web_socket` and `xhr_polling`. In Node.js they are `web_socket`, `xhr_polling`, and `comet`. | `String[]` | +| transportParams | Optional | Arbitrary parameters appended to the connection URL, such as `heartbeatInterval` and `remainPresentFor`. | Object | +| logLevel | Optional | Logging verbosity: `0` (no logs), `1` (errors only), `2` (errors plus connection and channel state changes), `3` (high-level debug output), and `4` (full debug output). | Number | +| logHandler | Optional | A custom log handler function. Default: `console.log`. | Function | +| disconnectedRetryTimeout | Optional | The delay before retrying a disconnected connection, in milliseconds. Default: 15000. | Number | +| suspendedRetryTimeout | Optional | The delay between reconnection attempts when in the `suspended` state, in milliseconds. Default: 30000. | Number | +| realtimeRequestTimeout | Optional | The acknowledgement timeout for realtime operations, in milliseconds. Default: 10000. | Number | +| httpOpenTimeout | Optional | Timeout for opening an HTTP connection, in milliseconds. Default: 4000. | Number | +| httpRequestTimeout | Optional | Timeout for an entire HTTP request, in milliseconds. Default: 10000. | Number | +| httpMaxRetryCount | Optional | Maximum number of fallback host attempts for HTTP requests. Default: 3. | Number | +| httpMaxRetryDuration | Optional | Maximum elapsed time for HTTP retries, in milliseconds. Default: 15000. | Number | +| connectivityCheckUrl | Optional | A custom URL used to check internet availability. | String | +| disableConnectivityCheck | Optional | When `true`, disables the internet connectivity check. Default: `false`. | Boolean | +| wsConnectivityCheckUrl | Optional | A custom URL used for WebSocket connectivity checking. | String | +| idempotentRestPublishing | Optional | Whether to enable client-side message ID assignment for idempotent REST publishing. Default: `true`. | Boolean | +| useBinaryProtocol | Optional | Whether to use the binary MsgPack protocol. Disabled by default in browsers because browsers are optimized for decoding JSON. Default: `true` in Node.js, `false` elsewhere. | Boolean | +| maxMessageSize | Optional | Maximum payload size in bytes. Default: 65536. | Number | +| pushServiceWorkerUrl | Optional | The service worker URL used for push notifications. | String | +| plugins | Optional | A map of plugin types to plugin instances. Used to load optional modular features like LiveObjects. | Object | +| restAgentOptions | Optional | Node.js HTTP/HTTPS agent configuration. | Object | + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| ttl | Optional | Requested time to live for the token in milliseconds. When omitted, the Ably REST API default of 60 minutes is applied. Default: 1 hour. | Number | +| capability | Optional | The capabilities associated with this token. A JSON-encoded representation of the resource paths and associated operations. If the `TokenRequest` is successful, the capability of the returned token is the intersection of this capability with the capability of the issuing key. [Read more about capabilities](/docs/auth/capabilities). Default: `{"*":["*"]}`. | String or Object | +| clientId | Optional | 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 `*`. | String | +| timestamp | Optional | The timestamp of this request as milliseconds since the Unix epoch. `timestamp`, in conjunction with the `nonce`, is used to prevent token requests being replayed. It is a one-time value and is not valid as a member of any default token params, such as `defaultTokenParams`. | Number | +| nonce | Optional | A cryptographically secure random string of at least 16 characters, used to ensure the `TokenRequest` cannot be reused. | String | + + + + + +| Property | Description | Type | +| --- | --- | --- | +| token | The Ably Token itself. A typical Ably Token string appears with the form `xVLyHw.A-pwh7wicf3afTfgiw4k2Ku33kcnSA7z6y8FjuYpe3QaNRTEo4`. | String | +| issued | The timestamp at which this token was issued as milliseconds since the Unix epoch. | Number | +| expires | The timestamp at which this token expires as milliseconds since the Unix epoch. | Number | +| capability | The capabilities associated with this token. A JSON-encoded representation of the resource paths and associated operations. | String | +| clientId | The client ID, if any, bound to this token. If a client ID is included, the token may only be used to perform operations on behalf of that client ID. | String | + + + + + +| Parameter | Description | Type | +| --- | --- | --- | +| lastConnectionDetails | Details of the previous connection, used to decide whether to recover it. | | +| callback | Call with `true` to recover the connection, or `false` to establish a fresh connection. | `recoverConnectionCompletionCallback` | + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| recoveryKey | An opaque string obtained from the [`recoveryKey`](/docs/pub-sub/api/javascript/realtime/connection) of the connection before the page was unloaded, used to recover the connection. | String | +| disconnectedAt | The time at which the previous client was abruptly disconnected before the page was unloaded, as milliseconds since the Unix epoch. | Number | +| location | A clone of the `location` object of the previous page's `document` object before the page was unloaded. A common use is to confirm the previous page URL matches the current URL before allowing recovery. | String | +| clientId | The `clientId` of the client's `Auth` object before the page was unloaded. A common use is to confirm the current user's `clientId` matches the previous connection's `clientId` before allowing recovery. | String or Null | + + + +## Open the connection
+ +{`realtime.connect(): void`} + +Calls [`connection.connect()`](/docs/pub-sub/api/javascript/realtime/connection#connect), explicitly initiating the connection if [`clientOptions.autoConnect`](#constructor-params) was set to `false`. + + +```javascript +realtime.connect(); +``` + + +## Close the connection + +{`realtime.close(): void`} + +Calls [`connection.close()`](/docs/pub-sub/api/javascript/realtime/connection#close), causing the connection to close and entering the `closing` state. Once `closed`, the SDK will not attempt to reconnect. + + +```javascript +realtime.close(); +``` + + +## Get server time + +{`realtime.time(): Promise`} + +Returns 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 `TokenRequest`s with a more accurate timestamp should use the [`clientOptions.queryTime`](#constructor-params) client option instead of this method. + + +```javascript +const now = await realtime.time(); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled with the server time as milliseconds since the Unix epoch, or rejected with an [`ErrorInfo`](#errorinfo) object. + +## Get account stats + +{`realtime.stats(params?: StatsParams): Promise>`} + +Retrieves usage statistics for the account, filtered by the supplied query parameters. Returns a paginated set of `Stats` objects, each containing usage [metrics](/docs/metadata-stats/stats#metrics). + + +```javascript +const page = await realtime.stats({ unit: 'hour', limit: 24 }); +``` + + +### Parameters + +The `stats()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Optional | Query parameters for the stats request. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| start | Optional | The start time for the query, in milliseconds since the Unix epoch. Default: the beginning of time. | Number | +| end | Optional | The end time for the query, in milliseconds since the Unix epoch. Default: current time. | Number | +| direction | Optional | The order of returned stats. `'backwards'` or `'forwards'`. Default: `'backwards'`. | String | +| limit | Optional | An upper limit on the number of stats records returned. Default: 100. Maximum: 1000. | Number | +| unit | Optional | The granularity of the returned stats: `'minute'`, `'hour'`, `'day'`, or `'month'`. Based on the unit selected, the given start or end times are rounded down to the start of the relevant interval. Default: `'minute'`. | String | + + + +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](#PaginatedResult) of `Stats` objects, or rejected with an [`ErrorInfo`](#errorinfo) object. + +#### Stats + +Each `Stats` entry contains the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| appId | The Ably application ID. | String | +| intervalId | The UTC time period that this stats entry refers to. If `unit` was requested as `minute` this is in the format `YYYY-mm-dd:HH:MM`, if `hour` it is `YYYY-mm-dd:HH`, if `day` it is `YYYY-mm-dd:00`, and if `month` it is `YYYY-mm-01:00`. | String | +| inProgress | For entries that are still in progress, such as the current month, the last sub-interval included in this stats entry, in the format `yyyy-mm-dd:hh:mm:ss`. | String | +| entries | A map of statistics entries (for example `messages.all.count`, `messages.inbound.realtime.count`) to their values. The `schema` property provides further information. | `Record` | +| schema | A URL to the JSON Schema describing the structure of this object. | String | + +
+ +## Make a REST request
+ +{`realtime.request(method: string, path: string, version: number, params?: any, body?: any, headers?: any): Promise`} + +Makes a REST request to a provided path. Useful for accessing Ably APIs that do not have a dedicated method in the SDK, without having to handle authentication, paging, fallback hosts, and MsgPack or JSON support yourself. + + +```javascript +const response = await realtime.request( + 'GET', + '/channels/{{RANDOM_CHANNEL_NAME}}/messages', + 3, + { limit: 10 } +); +``` + + +### Parameters + +The `request()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| method | Required | The HTTP method (`GET`, `POST`, `PUT`, `PATCH`, `DELETE`). | String | +| path | Required | The path of the API endpoint to call. | String | +| version | Required | The API version (e.g. `3`). | Number | +| params | Optional | Query parameters. | Object | +| body | Optional | The request body, for `POST`, `PUT`, and `PATCH` methods only. Must be anything that can be serialized into JSON, such as an object or array. | Any | +| headers | Optional | Custom HTTP headers. | Object | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with an `HttpPaginatedResponse`, or rejected with an [`ErrorInfo`](#errorinfo) object. Note that if a response is obtained, any response, even one with a non-2xx status code, resolves as an `HttpPaginatedResponse` rather than rejecting. + +#### HttpPaginatedResponse + +`HttpPaginatedResponse` contains the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| statusCode | The HTTP status code of the response. | Number | +| success | `true` if the status code is in the 200-299 range. | Boolean | +| errorCode | The error code, derived from the `X-Ably-Errorcode` HTTP header. | Number or Undefined | +| errorMessage | The error message, derived from the `X-Ably-Errormessage` HTTP header. | String or Undefined | +| errorDetail | A map of structured error metadata. | Object or Undefined | +| headers | The response headers. | Object | +| items | The current page of results. | `Array` | + +
+ +`HttpPaginatedResponse` also contains the following methods to handle pagination: + +##### Check for more pages
+ +hasNext(): boolean + +Returns `true` if there are more pages available by calling `next()`. + +##### Check if last page + +isLast(): boolean + +Returns `true` if this is the last page of results. + +##### Get next page + +{`next(): Promise`} + +Returns a promise. The promise is fulfilled with the next page of results as an `HttpPaginatedResponse`, or `null` if there are no more pages. Rejected with an [`ErrorInfo`](#errorinfo) object on failure. + +##### Get first page + +{`first(): Promise`} + +Returns a promise. The promise is fulfilled with the first page of results, or rejected with an [`ErrorInfo`](#errorinfo) object. + +##### Get current page + +{`current(): Promise`} + +Returns a promise. The promise is fulfilled with the current page of results, or rejected with an [`ErrorInfo`](#errorinfo) object. + +## Batch publish to multiple channels + +{`realtime.batchPublish(spec: BatchPublishSpec): Promise`} + +Publish using a single `BatchPublishSpec`, fulfilled with a single `BatchResult`. + +{`realtime.batchPublish(specs: BatchPublishSpec[]): Promise`} + +Publish using an array of `BatchPublishSpec` objects, fulfilled with one `BatchResult` per spec. + +Each spec publishes one or more messages to up to 100 channels in a single [batch publish](/docs/messages/batch) request. + + +```javascript +const result = await realtime.batchPublish({ + channels: ['channel1', 'channel2'], + messages: [{ name: 'event', data: 'hello' }] +}); +``` + + +### Parameters + +The `batchPublish()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| spec | Required | A single batch publish spec. |
| +| specs | Required | An array of batch publish specs. |
[] | + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| channels | Required | The names of the channels to publish the messages to. | `String[]` | +| messages | Required | An array of [`Message`](/docs/pub-sub/api/javascript/realtime/message) objects. | [Message](/docs/pub-sub/api/javascript/realtime/message)[] | + + + +### Returns
+ +`Promise` + +Returns a promise. For a single spec, the promise is fulfilled with a `BatchResult`. For an array of specs, the promise is fulfilled with an array of `BatchResult`s. Rejected with an [`ErrorInfo`](#errorinfo) object on failure. + + + +| Property | Description | Type | +| --- | --- | --- | +| successCount | The number of successful operations in the request. | Number | +| failureCount | The number of unsuccessful operations in the request. | Number | +| results | The per-channel results, one entry per channel. | Array of
or
| + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| channel | The channel name. | String | +| messageId | A unique ID prefixed to the `Message.id` of each published message. | String | +| serials | An array of message serials corresponding 1:1 to the messages that were published. A serial may be `null` if the message was discarded due to [message conflation](/docs/messages#conflation). | Array of String or Null | + + + + + +| Property | Description | Type | +| --- | --- | --- | +| channel | The channel name. | String | +| error | The error describing why the publish to this channel failed. | [ErrorInfo](#errorinfo) | + + + +## Batch presence query
+ +{`realtime.batchPresence(channels: string[]): Promise`} + +Retrieves the presence set for up to 100 channels in a single REST request. The presence state includes the `clientId` of members and their current [`PresenceAction`](/docs/pub-sub/api/javascript/realtime/realtime-presence). + +### Parameters + +The `batchPresence()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| channels | Required | The names of the channels to query. | `String[]` | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with an array of `BatchResult` objects, one per channel, where each `results` entry is a `BatchPresenceSuccessResult` or a `BatchPresenceFailureResult`. Rejected with an [`ErrorInfo`](#errorinfo) object on failure. + + + +| Property | Description | Type | +| --- | --- | --- | +| successCount | The number of successful operations in the request. | Number | +| failureCount | The number of unsuccessful operations in the request. | Number | +| results | The per-channel results, one entry per channel. | Array of
or
| + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| channel | The channel name the presence state was retrieved for. | String | +| presence | An array of [`PresenceMessage`](/docs/pub-sub/api/javascript/realtime/presence-message) objects describing the members present on the channel. | [PresenceMessage](/docs/pub-sub/api/javascript/realtime/presence-message)[] | + + + + + +| Property | Description | Type | +| --- | --- | --- | +| channel | The channel name the presence state failed to be retrieved for. | String | +| error | The error describing why the presence query for this channel failed. | [ErrorInfo](#errorinfo) | + + + +## Get the local device
+ +{`realtime.device(): LocalDevice`} + +Returns a [`LocalDevice`](/docs/pub-sub/api/javascript/realtime/push#LocalDevice) object representing the current device used for push notifications. + +### Returns + +`LocalDevice` + +Returns the [`LocalDevice`](/docs/pub-sub/api/javascript/realtime/push#LocalDevice), or `null` if push notifications are not supported in the current environment. + +## PaginatedResult + +A `PaginatedResult` represents a page of results from a paginated query such as [`stats()`](#stats), [`channel.history()`](/docs/pub-sub/api/javascript/realtime/realtime-channel#history), [`presence.history()`](/docs/pub-sub/api/javascript/realtime/realtime-presence#history), or [`channel.getMessageVersions()`](/docs/pub-sub/api/javascript/realtime/realtime-channel#get-message-versions). + +### Properties + +`PaginatedResult` contains the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| items | The current page of results. | `Array` | + +
+ +`PaginatedResult` also contains the following methods to handle pagination: + +### Check for more pages
+ +hasNext(): boolean + +Returns `true` if there are more pages available. + +### Check if last page + +isLast(): boolean + +Returns `true` if this is the last page of results. + +### Get next page + +{`next(): Promise`} + +Returns a promise fulfilled with the next page of results, or `null` if there are no more pages. Rejected with an [`ErrorInfo`](#errorinfo) object on failure. + +### Get first page + +{`first(): Promise`} + +Returns a promise fulfilled with the first page of results, or rejected with an [`ErrorInfo`](#errorinfo) object. + +### Get current page + +{`current(): Promise`} + +Returns a promise fulfilled with the current page of results, or rejected with an [`ErrorInfo`](#errorinfo) object. + +## ErrorInfo + +A standardized, generic Ably error object that contains an Ably-specific error code, a generic HTTP status code, and a human-readable message. All errors emitted by Ably are `ErrorInfo` instances. + + + +| Property | Description | Type | +| --- | --- | --- | +| code | The Ably-specific error code. | Number | +| statusCode | The HTTP status code corresponding to this error, where applicable. | Number | +| message | A human-readable description of what went wrong. | String | +| cause | The underlying error that caused this error, where applicable. | ErrorInfo or Undefined | +| detail | An optional map of string key-value pairs containing structured metadata associated with the error. | Object or Undefined | +| hint | Actionable remediation guidance describing how to fix the error, as distinct from `message`, which describes what went wrong. | String or Undefined | + +
+ diff --git a/src/pages/docs/pub-sub/api/javascript/realtime/realtime-presence.mdx b/src/pages/docs/pub-sub/api/javascript/realtime/realtime-presence.mdx new file mode 100644 index 0000000000..8063e93af2 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/realtime/realtime-presence.mdx @@ -0,0 +1,400 @@ +--- +title: RealtimePresence +meta_description: "API reference for the Presence (RealtimePresence) interface in the Ably Pub/Sub JavaScript Realtime SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, RealtimePresence API, enter, leave, update, get, subscribe, unsubscribe, history, enterClient, leaveClient, updateClient, PresenceAction" +--- + +A `RealtimePresence` object enables a client to be present on a channel and to query and subscribe to the presence set; access it via the [`presence`](/docs/pub-sub/api/javascript/realtime/realtime-channel) property of a [`RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel) instance. + + +```javascript +const presence = channel.presence; +``` + + +## Properties + +The `RealtimePresence` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| syncComplete | Indicates whether the presence member set is synchronized with the server after a channel attach. When a channel is attached, the Ably service immediately synchronizes the presence member set with the client. Typically this completes in milliseconds, however when the presence member set is very large, bandwidth constraints may slow this synchronization down. | Boolean | + +
+ +## Subscribe to presence events
+ +{`presence.subscribe(listener: presenceMessageCallback): Promise`} + +Subscribe to presence events on the channel. The listener is invoked for every presence message received. + +{`presence.subscribe(action: PresenceAction | PresenceAction[], listener?: presenceMessageCallback): Promise`} + +Subscribe to presence events for a specific action (or array of actions). The listener is invoked only for matching events. + + +```javascript +await channel.presence.subscribe((presenceMessage) => { + console.log(`${presenceMessage.action} from ${presenceMessage.clientId}`); +}); + +await channel.presence.subscribe('enter', (presenceMessage) => { + console.log(`${presenceMessage.clientId} entered`); +}); +``` + + +### Parameters + +The `subscribe()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| action | Optional | The presence action(s) to subscribe to. If omitted, the listener fires for every presence event. |
or `PresenceAction[]` | +| listener | Optional | A function invoked with a [`PresenceMessage`](/docs/pub-sub/api/javascript/realtime/presence-message) for each matching event. Required when subscribing to all events; with an `action` argument it may be omitted to attach the channel without registering a listener. | Function | + +
+ + + +| Value | Description | +| --- | --- | +| absent | Reserved for internal use. This is an internal enum value and is not delivered to subscribers as a presence event. | +| present | A member is present at the time of channel attach. Synthesized for each existing member when a client first subscribes. | +| enter | A new member entered the presence set. | +| leave | A member left the presence set, either explicitly or implicitly (e.g. due to disconnection). | +| update | A present member updated their data. | + + + +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the channel has been attached and the subscription is active, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +### Considerations + +Note the following behaviours when subscribing to presence events: + +* If the channel is `initialized` (no attempt to attach has yet been made), calling `subscribe()` implicitly attaches the channel. The listener is still registered regardless of the outcome of the implicit attach. +* If `subscribe()` is called more than once with the same listener, the listener is registered each time. For example, if you subscribe twice with the same listener and a presence message is later received, that listener is invoked twice. +* The registered listener remains active regardless of the underlying channel state. For example, if the channel later becomes `detached` or `failed` and is then reattached, listeners originally registered are still invoked when a presence message is received. Listeners are only removed by calling [`unsubscribe()`](#unsubscribe) or by releasing the underlying channel with `realtime.channels.release(name)`. +* If an exception is thrown in a listener and bubbles up to the event emitter, it is caught and logged at `error` level so that it does not affect other listeners for the same event. + +## Enter the presence set + +{`presence.enter(data?: any): Promise`} + +Enter the presence set for the channel, optionally with data that is associated with the present member. In order to enter the presence set the client must be [identified by having a client ID](/docs/auth/identified-clients), [have permission to be present](/docs/auth/capabilities), and be attached to the channel. The SDK will implicitly attach to the channel when entering. Entering when already entered is treated as an [`update()`](#update). + + +```javascript +await channel.presence.enter('status string'); +``` + + +### Parameters + +The `enter()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| data | Optional | The data payload for the present member. Supported payload types are strings, JSON objects and arrays, buffers containing arbitrary binary data, and `null`. | Any | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the client has entered the presence set, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Update the present member + +{`presence.update(data?: any): Promise`} + +Update the current member's data on the channel. This broadcasts an `update` event to all presence subscribers. The pre-requisites for `update()` are the same as for [`enter()`](#enter). If an attempt to `update()` is made before the client has entered the channel, the update is treated as an `enter`. + + +```javascript +await channel.presence.update('new status'); +``` + + +### Parameters + +The `update()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| data | Optional | The new data payload for the present member. May be `null`. | Any | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the update has been delivered, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Leave the presence set + +{`presence.leave(data?: any): Promise`} + +Leave the presence set for the channel. Optionally provide data to broadcast with the leave event. The client must already have [entered the presence set](#enter). + + +```javascript +await channel.presence.leave(); +``` + + +### Parameters + +The `leave()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| data | Optional | The data payload to broadcast with the leave event. | Any | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the client has left the presence set, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Get the presence set + +{`presence.get(params?: RealtimePresenceParams): Promise`} + +Retrieve the current members of the presence set for the channel. The returned array contains a [`PresenceMessage`](/docs/pub-sub/api/javascript/realtime/presence-message) object for each member, with metadata such as the member's `clientId`, `connectionId`, action, and any associated data. + +The member set is retained in memory by the client, so this method typically returns immediately. However, by default it waits until the presence member set is synchronized, so if synchronization is not yet complete after the channel attaches, it waits until synchronization is complete. + +When a channel is attached, the Ably service synchronizes the presence member set with the client. This typically completes in milliseconds, however a very large member set may take longer. + +When a channel is `initialized` (i.e. no attempt to attach has yet been made), calling `get()` will implicitly attach the channel. + + +```javascript +const members = await channel.presence.get(); +console.log(`${members.length} members present`); +``` + + +### Parameters + +The `get()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Optional | Filter and synchronization options for the query. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| waitForSync | Optional | When `true`, `get()` returns the members once the presence set has been fully synchronized with the server. When `false`, the current presence set members are returned without waiting. Default: `true`. | Boolean | +| clientId | Optional | Filters the returned members by `clientId`. | String | +| connectionId | Optional | Filters the returned members by `connectionId`. | String | + + + +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with an array of [`PresenceMessage`](/docs/pub-sub/api/javascript/realtime/presence-message) objects representing the current members of the presence set, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Unsubscribe from presence events + +{`presence.unsubscribe(action: PresenceAction | PresenceAction[], listener: presenceMessageCallback): void`} + +Remove the listener for the specified `PresenceAction`. + +{`presence.unsubscribe(action: PresenceAction | PresenceAction[]): void`} + +Remove all listeners registered against the specified action(s). + +{`presence.unsubscribe(listener: presenceMessageCallback): void`} + +Remove the specified listener from all presence actions. + +{`presence.unsubscribe(): void`} + +Remove all listeners. + + +```javascript +channel.presence.unsubscribe(); +``` + + +### Parameters + +The `unsubscribe()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| action | Optional | The action(s) to unsubscribe from. |
or `PresenceAction[]` | +| listener | Optional | The specific listener to remove. If omitted, all matching listeners are removed. | Function | + +
+ +## Get presence history
+ +{`presence.history(params?: RealtimeHistoryParams): Promise>`} + +Get a [paginated](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) set of historical presence message events for the channel. If the [channel is configured to persist messages](/docs/storage-history/storage), the presence message history will typically be available for 24 - 72 hours. If not, presence message events are only retained in memory by the Ably service for two minutes. + + +```javascript +const history = await channel.presence.history({ limit: 50 }); +history.items.forEach((member) => { + console.log(member.action, member.clientId); +}); +``` + + +### Parameters + +The `history()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Optional | Query parameters as specified in the [presence history API documentation](/docs/storage-history/history#presence-history). |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| start | Optional | The time from which messages are retrieved, as milliseconds since the Unix epoch. | Number | +| end | Optional | The time until which messages are retrieved, as milliseconds since the Unix epoch. Default: current time. | Number | +| direction | Optional | The order of returned messages. `'backwards'` orders from most recent to oldest; `'forwards'` orders from oldest to most recent. Default: `'backwards'`. | String | +| limit | Optional | An upper limit on the number of messages returned. Default: 100. Maximum: 1000. | Number | +| untilAttach | Optional | When `true`, retrieves [continuous history](/docs/storage-history/history#continuous-history) up until the channel attachment point. Requires the channel to be attached and `direction` to be `'backwards'`. If the channel is not attached, or `direction` is `forwards`, this option results in an error. | Boolean | + + + +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/realtime/realtime-client#PaginatedResult) containing an array of [`PresenceMessage`](/docs/pub-sub/api/javascript/realtime/presence-message) objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Enter the presence set on behalf of a client + +{`presence.enterClient(clientId: string, data?: any): Promise`} + +Enter the presence set on behalf of the given client ID. This is useful when a single client is acting on behalf of multiple clients, for example a server-side process managing presence for [multiple client IDs](/docs/presence-occupancy/presence#multiple-client-ids). Requires the client to be authenticated with a `clientId` matching the supplied value, or with a wildcard `clientId`. The wildcard requirement can be satisfied with an API key, or a token bound to a wildcard client ID. + + +```javascript +await channel.presence.enterClient('user-123', 'status'); +``` + + +### Parameters + +The `enterClient()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| clientId | Required | The client ID to enter the presence set on behalf of. | String | +| data | Optional | The data payload for the present member. | Any | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the client has been entered into the presence set, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Update a client's presence data + +{`presence.updateClient(clientId: string, data?: any): Promise`} + +Update the data for an existing present member on behalf of the given client ID. If the client is not already in the presence set, this is treated as an [`enterClient()`](#enter-client). + + +```javascript +await channel.presence.updateClient('user-123', 'new status'); +``` + + +### Parameters + +The `updateClient()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| clientId | Required | The client ID whose data is to be updated. | String | +| data | Optional | The new data payload. | Any | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the update has been delivered, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. + +## Leave the presence set on behalf of a client + +{`presence.leaveClient(clientId: string, data?: any): Promise`} + +Leave the presence set on behalf of the given client ID. Requires the same authentication conditions as [`enterClient()`](#enter-client). + + +```javascript +await channel.presence.leaveClient('user-123'); +``` + + +### Parameters + +The `leaveClient()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| clientId | Required | The client ID to remove from the presence set. | String | +| data | Optional | The data payload to broadcast with the leave event. | Any | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled when the client has left the presence set, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/realtime/realtime-client#errorinfo) object. +