diff --git a/src/data/nav/pubsub.ts b/src/data/nav/pubsub.ts index 7196e88661..398d02396d 100644 --- a/src/data/nav/pubsub.ts +++ b/src/data/nav/pubsub.ts @@ -626,13 +626,41 @@ export default { }, ], }, + { + name: 'REST interface', + pages: [ + { name: 'REST client', link: '/docs/pub-sub/api/javascript/rest/rest-client' }, + { name: 'Auth', link: '/docs/pub-sub/api/javascript/rest/auth' }, + { name: 'Crypto', link: '/docs/pub-sub/api/javascript/rest/crypto' }, + { + name: 'Channels and messages', + pages: [ + { name: 'Channels', link: '/docs/pub-sub/api/javascript/rest/channels' }, + { name: 'Channel', link: '/docs/pub-sub/api/javascript/rest/channel' }, + { name: 'ChannelDetails', link: '/docs/pub-sub/api/javascript/rest/channel-details' }, + { name: 'Message', link: '/docs/pub-sub/api/javascript/rest/message' }, + { name: 'RestAnnotations', link: '/docs/pub-sub/api/javascript/rest/rest-annotations' }, + ], + }, + { + name: 'Presence', + pages: [ + { name: 'Presence', link: '/docs/pub-sub/api/javascript/rest/presence' }, + { name: 'PresenceMessage', link: '/docs/pub-sub/api/javascript/rest/presence-message' }, + ], + }, + { + name: 'Push notifications', + pages: [ + { name: 'Push', link: '/docs/pub-sub/api/javascript/rest/push' }, + { name: 'PushChannel', link: '/docs/pub-sub/api/javascript/rest/push-channel' }, + { name: 'PushAdmin', link: '/docs/pub-sub/api/javascript/rest/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/rest/auth.mdx b/src/pages/docs/pub-sub/api/javascript/rest/auth.mdx new file mode 100644 index 0000000000..9910df6d1f --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/auth.mdx @@ -0,0 +1,276 @@ +--- +title: Auth +meta_description: "API reference for the Authentication (Auth) interface in the Ably Pub/Sub JavaScript REST SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Auth API, authorize, createTokenRequest, requestToken, revokeTokens, AuthOptions, TokenParams, TokenDetails, TokenRequest" +--- + +The `Auth` interface is used to issue short-lived credentials to less-trusted clients without sharing your private API key. The recommended approach for most applications is to use [Ably JWTs](/docs/auth/token/jwt), which enable your server to mint tokens using standard JWT libraries. + +Access it via the `auth` property of a [`Rest`](/docs/pub-sub/api/javascript/rest/rest-client) client instance. + +The `Auth` interface also supports the creation of Ably `TokenRequest` objects with `createTokenRequest()`, and the ability to obtain Ably Tokens from Ably with `requestToken()`. `TokenRequest` objects and Ably Tokens are only recommended over JWTs when your [capability](/docs/auth/capabilities) list is very large, or you need to keep your capabilities confidential. + + +```javascript +const auth = rest.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. | String | + +
+ +## Authorize the client + +{`auth.authorize(tokenParams?: TokenParams, authOptions?: AuthOptions): Promise`} + +Instructs the SDK to get a new token immediately. Once fetched, the token is used for all subsequent REST requests made by this client. 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 rest.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 | +| 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 `*`. 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 | +| 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, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object if a token could not be obtained. + +## 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 rest.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/rest/rest-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](/docs/api/rest-api#request-token) 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/rest/rest-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 rest.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/rest/rest-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 rest.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/rest/rest-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/rest/rest-client#errorinfo) object describing the reason token revocation failed for this target. | [ErrorInfo](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) | + + diff --git a/src/pages/docs/pub-sub/api/javascript/rest/channel-details.mdx b/src/pages/docs/pub-sub/api/javascript/rest/channel-details.mdx new file mode 100644 index 0000000000..2a2994234f --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/channel-details.mdx @@ -0,0 +1,83 @@ +--- +title: ChannelDetails +meta_description: "API reference for channel metadata (ChannelDetails) in the Ably Pub/Sub JavaScript REST SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, channel metadata, ChannelDetails, ChannelStatus, occupancy, metrics, status" +--- + +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, which a [`Channel`](/docs/pub-sub/api/javascript/rest/channel) returns from its [`status()`](/docs/pub-sub/api/javascript/rest/channel#status) method. + + +```javascript +const channel = rest.channels.get('{{RANDOM_CHANNEL_NAME}}'); +const details = await channel.status(); +console.log(details.channelId, details.status.occupancy.metrics.connections); +``` + + +## 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/rest/channel.mdx b/src/pages/docs/pub-sub/api/javascript/rest/channel.mdx new file mode 100644 index 0000000000..6adba981af --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/channel.mdx @@ -0,0 +1,312 @@ +--- +title: Channel +meta_description: "API reference for the Channel interface in the Ably Pub/Sub JavaScript REST SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Channel API, publish, history, status, getMessage, getMessageVersions, updateMessage, appendMessage, deleteMessage, presence, push, annotations" +--- + +A `Channel` represents a single channel, obtained via the [`channels.get()`](/docs/pub-sub/api/javascript/rest/channels#get) method. Use it to publish messages, retrieve message history, query the presence set, and access channel features such as push notifications and annotations. + +The REST channel is stateless: each operation is a single HTTP request to Ably. Attaching, subscribing, and managing channel state require the [realtime SDK's `RealtimeChannel`](/docs/pub-sub/api/javascript/realtime/realtime-channel) interface. + + +```javascript +const channel = rest.channels.get('{{RANDOM_CHANNEL_NAME}}'); +``` + + +## Properties + +The `Channel` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| name | The name of this channel. | String | +| presence | Access the [`Presence`](/docs/pub-sub/api/javascript/rest/presence) object for this channel, used to query the presence set and its history. | [Presence](/docs/pub-sub/api/javascript/rest/presence) | +| push | Access the [`PushChannel`](/docs/pub-sub/api/javascript/rest/push-channel) object for this channel, used to manage push notification subscriptions. | [PushChannel](/docs/pub-sub/api/javascript/rest/push-channel) | +| annotations | Access the [`RestAnnotations`](/docs/pub-sub/api/javascript/rest/rest-annotations) object for this channel, used to publish, delete, and retrieve [annotations](/docs/messages/annotations) on messages. | [RestAnnotations](/docs/pub-sub/api/javascript/rest/rest-annotations) | + +
+ +## 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. + +Each call results in a single REST request to Ably. It is also possible to publish to multiple channels at once using the [batch publish](/docs/messages/batch#batch-publish) feature. + + +```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/rest/message) object to publish. | [Message](/docs/pub-sub/api/javascript/rest/message) | +| messages | Required | An array of [`Message`](/docs/pub-sub/api/javascript/rest/message) objects to publish atomically. | [Message](/docs/pub-sub/api/javascript/rest/message)[] | +| options | Optional | An open map of server-defined publish options (string, number, or boolean values), such as `quickAck`. The SDK passes these through as publish parameters; the set of valid options is defined by the Ably service, not the SDK. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| quickAck | Optional | Reduces the latency of REST publishes, though provides a slightly lower quality of service. | 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/rest/rest-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 | + +
+ +## Get message history
+ +{`channel.history(params?: RestHistoryParams): Promise>`} + +Retrieve a [`PaginatedResult`](/docs/pub-sub/api/javascript/rest/rest-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 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, as specified in the [message history API documentation](/docs/storage-history/history#retrieve-channel). |
| + +
+ + + +| 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 | + + + +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/rest/rest-client#PaginatedResult) containing an array of received [`Message`](/docs/pub-sub/api/javascript/rest/message) objects (typed `InboundMessage`), or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object. + +## Get channel status + +{`channel.status(): Promise`} + +Retrieve the current status of the channel, including whether it is active and its [occupancy](/docs/presence-occupancy/occupancy) metrics, as a [`ChannelDetails`](/docs/pub-sub/api/javascript/rest/channel-details) object. This is the canonical, typed way to fetch a channel's current metadata on demand. + + +```javascript +const details = await channel.status(); +console.log(details.status.occupancy.metrics.connections); +``` + + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled with a [`ChannelDetails`](/docs/pub-sub/api/javascript/rest/channel-details#ChannelDetails) object describing the channel's current state, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-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/rest/message) object containing a populated `serial` field. | String or [Message](/docs/pub-sub/api/javascript/rest/message) | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with the [`Message`](/docs/pub-sub/api/javascript/rest/message), or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object. + +## Get all versions of a message + +{`channel.getMessageVersions(serialOrMessage: string | Message, params?: Record): 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/rest/message) object containing a populated `serial` field. | String or [Message](/docs/pub-sub/api/javascript/rest/message) | +| params | Optional | Query parameters sent as part of the request, such as `limit`. | Object | + +
+ +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/rest/rest-client#PaginatedResult) of message versions, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object. + +## 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/rest/message) | +| operation | Optional | Metadata about the update operation. |
| +| options | Optional | Server-defined 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/rest/rest-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. Requires the `message-update-own` or `message-update-any` [capability](/docs/auth/capabilities). + +For publishing a high rate of appends, you typically want to use a realtime client rather than a REST client, in order to preserve [append ordering](/docs/messages/updates-deletes#append-ordering). + +### 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/rest/message) | +| operation | Optional | Metadata about the append operation. |
| +| options | Optional | Server-defined 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/rest/rest-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. 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/rest/message) | +| operation | Optional | Metadata about the delete operation. |
| +| options | Optional | Server-defined 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/rest/rest-client#errorinfo) object. diff --git a/src/pages/docs/pub-sub/api/javascript/rest/channels.mdx b/src/pages/docs/pub-sub/api/javascript/rest/channels.mdx new file mode 100644 index 0000000000..0ec57da0e8 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/channels.mdx @@ -0,0 +1,138 @@ +--- +title: Channels +meta_description: "API reference for the Channels interface in the Ably Pub/Sub JavaScript REST SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Channels API, get, release, ChannelOptions" +--- + +The `Channels` interface is used to create and destroy [`Channel`](/docs/pub-sub/api/javascript/rest/channel) objects. Access it via the `channels` property of a [`Rest`](/docs/pub-sub/api/javascript/rest/rest-client) client instance. + + +```javascript +const channels = rest.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): Channel`} + +Creates a new [`Channel`](/docs/pub-sub/api/javascript/rest/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 = rest.channels.get('{{RANDOM_CHANNEL_NAME}}'); + +// With channel options +const encryptedChannel = rest.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. |
| + +
+ + + +| 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. Modes are applied when a realtime connection attaches to the channel; they have no effect on REST operations, which are governed by [capabilities](/docs/auth/capabilities). | Array of
| + +
+ + + +| Property | Description | Type | +| --- | --- | --- | +| key | The private key used for encryption and decryption. Do not set this value directly; pass a key to [`Crypto.getDefaultParams()`](/docs/pub-sub/api/javascript/rest/crypto#get-default-params) instead. | `unknown` | +| 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`, 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
+ +`Channel` + +Returns a [`Channel`](/docs/pub-sub/api/javascript/rest/channel) object for the given name. If a channel with that name already exists, the existing object is returned. + +## Release a channel + +{`channels.release(name: string): void`} + +Releases all SDK-held references to a [`Channel`](/docs/pub-sub/api/javascript/rest/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. After release, calling [`channels.get()`](#get) with the same name returns a fresh channel object. + + +```javascript +rest.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/rest/crypto.mdx b/src/pages/docs/pub-sub/api/javascript/rest/crypto.mdx new file mode 100644 index 0000000000..708e94e01e --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/crypto.mdx @@ -0,0 +1,106 @@ +--- +title: Crypto +meta_description: "API reference for the Encryption (Crypto) utility in the Ably Pub/Sub JavaScript REST 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 [`Rest`](/docs/pub-sub/api/javascript/rest/rest-client) client instance. + + + + +```javascript +const crypto = Ably.Rest.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 [obtaining a channel](/docs/pub-sub/api/javascript/rest/channels#get) (as in the [getting started example](/docs/channels/options/encryption)). + + +```javascript +const cipherParams = Ably.Rest.Crypto.getDefaultParams({ key: '' }); +const channelOpts = { cipher: cipherParams }; +const channel = rest.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 binary (`ArrayBuffer` or `Uint8Array`) or a base64-encoded `String`. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| key | Required | The private key used for encryption and decryption. Can be binary or base64-encoded. | `ArrayBuffer`, `Uint8Array`, 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 private key used for encryption and decryption. Do not set this value directly; pass a key to [`getDefaultParams()`](#get-default-params) instead. | `unknown` | +| 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.Rest.Crypto.generateRandomKey(256); +const channel = rest.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/rest/rest-client#errorinfo) object. diff --git a/src/pages/docs/pub-sub/api/javascript/rest/message.mdx b/src/pages/docs/pub-sub/api/javascript/rest/message.mdx new file mode 100644 index 0000000000..27b2a48bed --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/message.mdx @@ -0,0 +1,176 @@ +--- +title: Message +meta_description: "API reference for the Message interface in the Ably Pub/Sub JavaScript REST 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 published through a channel's [`publish()`](/docs/pub-sub/api/javascript/rest/channel#publish) method and retrieved via [`history()`](/docs/pub-sub/api/javascript/rest/channel#history). + + +```javascript +const result = await channel.history(); +const message = result.items[0]; +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 | The summary entry for `distinct.v1`, an object mapping each name to a `SummaryClientIdList` value. | `Record` | +| SummaryUniqueValues | The summary entry for `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 | Optional | 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 | Optional | 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(JsonObject: any, 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.Rest.Message.fromEncoded(encodedMsg); +``` + + +### Parameters + +The `Message.fromEncoded()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| JsonObject | Required | A `Message`-like deserialized object. | Any | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/rest/channels#get) | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with the decoded message, typed `InboundMessage`: a `Message` whose `id`, `timestamp`, `action`, `version`, and `annotations` fields are guaranteed to be present. The promise is rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object if the object cannot be decoded. + +## Create messages from an encoded array + +{`Message.fromEncodedArray(JsonArray: any[], 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.Rest.Message.fromEncodedArray(encodedMsgs); +``` + + +### Parameters + +The `Message.fromEncodedArray()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| JsonArray | Required | An array of `Message`-like deserialized objects. | `Any[]` | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/rest/channels#get) | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with an array of decoded messages, typed `InboundMessage` as for [`fromEncoded()`](#from-encoded-returns). The promise is rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object if the array cannot be decoded. diff --git a/src/pages/docs/pub-sub/api/javascript/rest/presence-message.mdx b/src/pages/docs/pub-sub/api/javascript/rest/presence-message.mdx new file mode 100644 index 0000000000..21ed20a7c1 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/presence-message.mdx @@ -0,0 +1,142 @@ +--- +title: PresenceMessage +meta_description: "API reference for the PresenceMessage type in the Ably Pub/Sub JavaScript REST 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 retrieved via [`presence.get()`](/docs/pub-sub/api/javascript/rest/presence#get) and [`presence.history()`](/docs/pub-sub/api/javascript/rest/presence#history). + + +```javascript +const members = await channel.presence.get(); +members.items.forEach((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) 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 that is present on the channel. This is the action for each member returned by `presence.get()`. | +| 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(JsonObject: any, 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.Rest.PresenceMessage.fromEncoded(encodedMsg); +``` + + +### Parameters + +The `PresenceMessage.fromEncoded()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| JsonObject | Required | A `PresenceMessage`-like deserialized object. | Any | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/rest/channels#get) | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with a `PresenceMessage` object decoded from the supplied object, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object if the object cannot be decoded. + +## Create an array of PresenceMessages from encoded objects + +{`PresenceMessage.fromEncodedArray(JsonArray: any[], 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.Rest.PresenceMessage.fromEncodedArray(encodedMsgs); +``` + + +### Parameters + +The `PresenceMessage.fromEncodedArray()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| JsonArray | Required | An array of `PresenceMessage`-like deserialized objects. | `Any[]` | +| channelOptions | Optional | If you have an encrypted channel, use this to allow the SDK to decrypt the data. | [ChannelOptions](/docs/pub-sub/api/javascript/rest/channels#get) | + +
+ +### Returns
+ +`Promise` + +Returns a promise. The promise is fulfilled with an array of `PresenceMessage` objects decoded from the supplied array, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object if the array cannot be decoded. + +## 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.Rest.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 the `clientId`, `data`, and `extras` fields are accepted. | Object | + +
+ +### Returns
+ +`PresenceMessage` + +Returns a `PresenceMessage` object initialised from the supplied values. diff --git a/src/pages/docs/pub-sub/api/javascript/rest/presence.mdx b/src/pages/docs/pub-sub/api/javascript/rest/presence.mdx new file mode 100644 index 0000000000..dd40ca2563 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/presence.mdx @@ -0,0 +1,103 @@ +--- +title: Presence +meta_description: "API reference for the Presence interface in the Ably Pub/Sub JavaScript REST SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Presence API, get, history, RestPresenceParams, RestHistoryParams, PresenceMessage" +--- + +A `Presence` object enables a client to query the presence set of a channel over REST. Access it via the `presence` property of a [`Channel`](/docs/pub-sub/api/javascript/rest/channel) instance. + +The REST presence interface is query-only: it retrieves the current members of the presence set and their history. Entering, updating, leaving, and subscribing to presence events require the [realtime SDK's `RealtimePresence`](/docs/pub-sub/api/javascript/realtime/realtime-presence) interface. + + +```javascript +const channel = rest.channels.get('{{RANDOM_CHANNEL_NAME}}'); +const members = await channel.presence.get(); +``` + + +## Get the presence set + +{`presence.get(params?: RestPresenceParams): Promise>`} + +Retrieve the current members of the presence set for the channel. This method directly queries [Ably's REST presence API](/docs/api/rest-api#presence) and returns a [paginated](/docs/pub-sub/api/javascript/rest/rest-client#PaginatedResult) set of [`PresenceMessage`](/docs/pub-sub/api/javascript/rest/presence-message) objects, one for each member, with metadata such as the member's `clientId`, `connectionId`, action, and any associated data. + + +```javascript +const members = await channel.presence.get({ limit: 100 }); +members.items.forEach((member) => { + console.log(member.clientId, member.data); +}); +``` + + +### Parameters + +The `get()` method takes the following parameters: + + + +| Parameter | Required | Description | Type | +| --- | --- | --- | --- | +| params | Optional | Filter options for the query. |
| + +
+ + + +| Property | Required | Description | Type | +| --- | --- | --- | --- | +| clientId | Optional | Filters the returned members by the [`clientId`](/docs/auth/identified-clients) they are identified as. | String | +| connectionId | Optional | Filters the returned members by the ID of the [realtime connection](/docs/pub-sub/api/javascript/realtime/connection) they entered on. | String | +| limit | Optional | An upper limit on the number of members returned. Default: 100. Maximum: 1000. | Number | + + + +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/rest/rest-client#PaginatedResult) containing an array of [`PresenceMessage`](/docs/pub-sub/api/javascript/rest/presence-message) objects representing the current members of the presence set, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object. + +## Get presence history + +{`presence.history(params?: RestHistoryParams): Promise>`} + +Get a [paginated](/docs/pub-sub/api/javascript/rest/rest-client#PaginatedResult) set of historical presence message events for the channel. If the channel is [configured to persist messages](/docs/storage-history/storage), presence message history is available for the duration configured for your account. Otherwise, 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 presence events are retrieved, as milliseconds since the Unix epoch. Default: the beginning of time. | Number | +| end | Optional | The time until which presence events are retrieved, as milliseconds since the Unix epoch. Default: current time. | Number | +| direction | Optional | The order of returned presence events. `'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 presence events returned. Default: 100. Maximum: 1000. | Number | + + + +### Returns
+ +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/rest/rest-client#PaginatedResult) containing an array of [`PresenceMessage`](/docs/pub-sub/api/javascript/rest/presence-message) objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object. diff --git a/src/pages/docs/pub-sub/api/javascript/rest/push-admin.mdx b/src/pages/docs/pub-sub/api/javascript/rest/push-admin.mdx new file mode 100644 index 0000000000..f9b520461a --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/push-admin.mdx @@ -0,0 +1,456 @@ +--- +title: PushAdmin +meta_description: "API reference for the Push admin (PushAdmin) interface in the Ably Pub/Sub JavaScript REST 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 [`rest.push.admin`](/docs/pub-sub/api/javascript/rest/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 = rest.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 rest.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/rest/rest-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 = rest.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 rest.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/rest/rest-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 rest.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/rest/rest-client#PaginatedResult) of [`DeviceDetails`](#DeviceDetails) objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-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 rest.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/rest/rest-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 rest.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/rest/rest-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 rest.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/rest/rest-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 = rest.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 rest.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/rest/rest-client#PaginatedResult) of `PushChannelSubscription` objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-client#errorinfo) object. + +### List channels with subscriptions + +{`channelSubscriptions.listChannels(params: PushChannelsParams): Promise>`} + +Retrieves all channels with at least one device [subscribed to push notifications](/docs/push/publish#sub-channels). Requires `push-admin` permission. + + +```javascript +const channels = await rest.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/rest/rest-client#PaginatedResult) of channel name strings, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-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 rest.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/rest/rest-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 rest.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/rest/rest-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 rest.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/rest/rest-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 or Undefined | +| deviceSecret | A unique device secret generated by the Ably SDK. | String or Undefined | +| 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 or Undefined | +| error | When `state` is `FAILING` or `FAILED`, this contains the reason for the most recent failure. | [ErrorInfo](/docs/pub-sub/api/javascript/rest/rest-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/rest/push-channel.mdx b/src/pages/docs/pub-sub/api/javascript/rest/push-channel.mdx new file mode 100644 index 0000000000..2a01503040 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/push-channel.mdx @@ -0,0 +1,125 @@ +--- +title: PushChannel +meta_description: "API reference for the PushChannel interface in the Ably Pub/Sub JavaScript REST 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/rest/rest-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/rest/rest-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/rest/rest-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/rest/rest-client#errorinfo) object. + +## List subscriptions on this channel + +{`pushChannel.listSubscriptions(params?: Record): Promise>`} + +Lists push subscriptions on the channel by querying the REST API's [list channel subscriptions endpoint](/docs/api/rest-api#list-channel-subscriptions). These subscriptions can be a list of client (`clientId`) subscriptions, device (`deviceId`) subscriptions, or a combination 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`, or a combination of both, 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/rest/rest-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/rest/rest-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 or Undefined | +| clientId | Devices with this [client identifier](/docs/auth/identified-clients) are included in this channel subscription. When present, `deviceId` is never present. | String or Undefined | + +
diff --git a/src/pages/docs/pub-sub/api/javascript/rest/push.mdx b/src/pages/docs/pub-sub/api/javascript/rest/push.mdx new file mode 100644 index 0000000000..a13e191057 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/push.mdx @@ -0,0 +1,133 @@ +--- +title: Push +meta_description: "API reference for the Push interface in the Ably Pub/Sub JavaScript REST 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 [`Rest`](/docs/pub-sub/api/javascript/rest/rest-client) client instance (`rest.push`). + +Device activation operates on the local device's push registration, so it is only meaningful in environments that have a push-capable device, such as a browser or a mobile app. For server-side push administration, use the [`PushAdmin`](/docs/pub-sub/api/javascript/rest/push-admin) object instead. + + +```javascript +const push = rest.push; +``` + + +## Properties + +The `Push` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| admin | A [`PushAdmin`](/docs/pub-sub/api/javascript/rest/push-admin) object for managing push notifications administratively (requires the `push-admin` capability). | [PushAdmin](/docs/pub-sub/api/javascript/rest/push-admin) | + +
+ +## Activate the device
+ +{`push.activate(registerCallback?: Function, updateFailedCallback?: Function): Promise`} + +[Activates the device](/docs/push/configure/web#browser) for push notifications. Subsequently registers the device with Ably and stores the `deviceIdentityToken` in local storage. + + +```javascript +await rest.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/rest/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/rest/rest-client#errorinfo) object. + +## Deactivate the device + +{`push.deactivate(deregisterCallback?: Function): Promise`} + +Deactivates the device from receiving push notifications. + + +```javascript +await rest.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/rest/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/rest/rest-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 `await rest.getDevice()`. + +### 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. Not present until device activation has completed. | String or Undefined | + +
+ +### List subscriptions for the local device
+ +{`localDevice.listSubscriptions(): Promise>`} + +Retrieves push subscriptions active for the local device. + + +```javascript +const device = await rest.getDevice(); +const subs = await device.listSubscriptions(); +``` + + +#### Returns + +`Promise>` + +Returns a promise. The promise is fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/rest/rest-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/rest/rest-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 or Undefined | +| clientId | Devices with this [client identifier](/docs/auth/identified-clients) are included in this channel subscription. When present, `deviceId` is never present. | String or Undefined | + +
diff --git a/src/pages/docs/pub-sub/api/javascript/rest/rest-annotations.mdx b/src/pages/docs/pub-sub/api/javascript/rest/rest-annotations.mdx new file mode 100644 index 0000000000..3159124625 --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/rest-annotations.mdx @@ -0,0 +1,216 @@ +--- +title: RestAnnotations +meta_description: "API reference for message annotations (the RestAnnotations interface) in the Ably Pub/Sub JavaScript REST SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, RestAnnotations, message annotations, publish, delete, get, Annotation, OutboundAnnotation, AnnotationAction, fromEncoded, fromEncodedArray" +--- + +The `RestAnnotations` object lets you publish, delete, and retrieve [annotations](/docs/messages/annotations) on messages. Access it via the `annotations` property of a [`Channel`](/docs/pub-sub/api/javascript/rest/channel). + +Subscribing to individual annotations in realtime requires the [realtime SDK's `RealtimeAnnotations`](/docs/pub-sub/api/javascript/realtime/realtime-annotations) interface. + + +```javascript +const annotations = channel.annotations; +``` + + +## 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](/docs/auth/identified-clients). + +### 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/rest/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/rest/rest-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](/docs/messages/annotations#delete). 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/rest/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/rest/rest-client#errorinfo) object. + +## Get annotations for a message + +{`annotations.get(message: Message, params: GetAnnotationsParams | null): Promise>`} + +Retrieve all annotations for a message identified by a `Message` object. + +{`annotations.get(messageSerial: string, params: GetAnnotationsParams | null): 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/rest/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/rest/message) | +| messageSerial | Required | The serial string of the message to get annotations for. Provide either `message` or `messageSerial`. | String | +| params | Required | Restrictions on which annotations to return, in particular a limit. Pass `null` to apply no restrictions; the argument cannot be omitted. |
or Null | + +
+ +### Returns
+ +`Promise>` + +Returns a promise, fulfilled with a [`PaginatedResult`](/docs/pub-sub/api/javascript/rest/rest-client#PaginatedResult) containing an array of `Annotation` objects, or rejected with an [`ErrorInfo`](/docs/pub-sub/api/javascript/rest/rest-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 the `multiple.v1` annotation type. | Number | +| data | An optional publisher-provided payload. Available on individual annotations but not aggregated or included in [annotation summaries](/docs/messages/annotations#annotation-summaries). | Any | +| encoding | The encoding of the payload; typically empty as annotations received from Ably are automatically decoded client-side using this value. However, if the annotation encoding cannot be processed, this attribute contains the remaining transformations not applied to the `data` payload. | 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 | Metadata and/or ancillary payloads, if provided. Valid payloads include [`push`](/docs/push/publish#payload), `headers` (a map of strings to strings for arbitrary customer-supplied metadata), [`ephemeral`](/docs/pub-sub/advanced#ephemeral), and [`privileged`](/docs/platform/integrations/skip-integrations) objects. | Any | + +
+ + + +| 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 the `multiple.v1` annotation type. | Number | +| data | Optional | An optional publisher-provided payload. Available on individual annotations but not aggregated or included in [annotation summaries](/docs/messages/annotations#annotation-summaries). | Any | +| encoding | Optional | The encoding of the payload. | String | +| extras | Optional | Metadata and/or ancillary payloads, if provided. Valid payloads include [`push`](/docs/push/publish#payload), `headers` (a map of strings to strings for arbitrary customer-supplied metadata), [`ephemeral`](/docs/pub-sub/advanced#ephemeral), and [`privileged`](/docs/platform/integrations/skip-integrations) objects. | 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.Rest.Annotation`. The returned promise resolves with the decoded annotation. + + +```javascript +const annotation = await Ably.Rest.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/rest/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.Rest.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/rest/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/rest/rest-client.mdx b/src/pages/docs/pub-sub/api/javascript/rest/rest-client.mdx new file mode 100644 index 0000000000..273da0652f --- /dev/null +++ b/src/pages/docs/pub-sub/api/javascript/rest/rest-client.mdx @@ -0,0 +1,510 @@ +--- +title: REST client +meta_description: "API reference for the Rest client class in the Ably Pub/Sub JavaScript REST SDK." +meta_keywords: "Ably Pub/Sub SDK, JavaScript, Rest, Rest client, constructor, ClientOptions, auth, channels, push, time, stats, request, batchPublish, batchPresence, getDevice, ErrorInfo" +--- + +The `Rest` class is the entry point for using the Ably Pub/Sub JavaScript SDK in REST mode. It is a stateless client that interacts with the Ably REST API over HTTP, without maintaining a persistent connection, and provides access to channels, presence, push notifications, and authentication. It is well suited to server-side environments and to publishing or querying from contexts that don't need realtime updates. + + +```javascript +const rest = new Ably.Rest({ key: '{{API_KEY}}' }); +``` + + +This example uses [basic authentication](/docs/auth/basic) with an API key, which is appropriate for trusted, server-side environments. For browsers and other untrusted clients, use [token authentication](/docs/auth/token) instead, by supplying an [`authCallback`](#constructor-params) or [`authUrl`](#constructor-params) that fetches tokens from your own server, keeping your API key off the client. + + + +## Properties + +The `Rest` interface has the following properties: + + + +| Property | Description | Type | +| --- | --- | --- | +| auth | The [`Auth`](/docs/pub-sub/api/javascript/rest/auth) object for this client. Manages tokens and authentication. | [Auth](/docs/pub-sub/api/javascript/rest/auth) | +| channels | The [`Channels`](/docs/pub-sub/api/javascript/rest/channels) collection for this client. Used to obtain `Channel` instances. | [Channels](/docs/pub-sub/api/javascript/rest/channels) | +| push | The [`Push`](/docs/pub-sub/api/javascript/rest/push) object for this client. Used for push notification device activation and admin operations. | [Push](/docs/pub-sub/api/javascript/rest/push) | +| Crypto | Static access to the [`Crypto`](/docs/pub-sub/api/javascript/rest/crypto) utility. Accessed on the class: `Ably.Rest.Crypto`. | [Crypto](/docs/pub-sub/api/javascript/rest/crypto) | +| Message | Static access to the [`Message`](/docs/pub-sub/api/javascript/rest/message) class for `fromEncoded()` factory methods. Accessed on the class: `Ably.Rest.Message`. | [Message](/docs/pub-sub/api/javascript/rest/message) | +| PresenceMessage | Static access to the [`PresenceMessage`](/docs/pub-sub/api/javascript/rest/presence-message) class for `fromEncoded()` factory methods. Accessed on the class: `Ably.Rest.PresenceMessage`. | [PresenceMessage](/docs/pub-sub/api/javascript/rest/presence-message) | +| Annotation | Static access to the [`Annotation`](/docs/pub-sub/api/javascript/rest/rest-annotations) type for `fromEncoded()` factory methods. Accessed on the class: `Ably.Rest.Annotation`. | [Annotation](/docs/pub-sub/api/javascript/rest/rest-annotations) | + +
+ +## Create a new Rest client
+ +{`new Ably.Rest(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.Rest(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 rest = new Ably.Rest({ + key: '{{API_KEY}}', + clientId: 'user-123', + logLevel: 3 +}); + +// Or with just a key string +const rest = new Ably.Rest('{{API_KEY}}'); +``` + + +### Parameters + +The `Rest()` 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 | A function 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`, a `TokenDetails` (in JSON format), or an [Ably JWT](/docs/auth/token/jwt), per the [`AuthOptions`](/docs/pub-sub/api/javascript/rest/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 | +| idempotentRestPublishing | Optional | Whether to enable client-side message ID assignment for idempotent REST publishing. Default: `true`. | Boolean | +| 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[]` | +| 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 | +| 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 | +| 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. | 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 | + + + +## Get server time
+ +{`rest.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 rest.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 + +{`rest.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 rest.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.rest.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
+ +{`rest.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 rest.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, if sent in the response. | Number | +| errorMessage | The error message, derived from the `X-Ably-Errormessage` HTTP header, if sent in the response. | String | +| 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 a [`PaginatedResult`](#PaginatedResult), 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 as a [`PaginatedResult`](#PaginatedResult), 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 as a [`PaginatedResult`](#PaginatedResult), or rejected with an [`ErrorInfo`](#errorinfo) object. + +## Batch publish to multiple channels + +{`rest.batchPublish(spec: BatchPublishSpec): Promise`} + +Publish using a single `BatchPublishSpec`, fulfilled with a single `BatchResult`. + +{`rest.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 rest.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/rest/message) objects. | [Message](/docs/pub-sub/api/javascript/rest/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
+ +{`rest.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 [presence action](/docs/presence-occupancy/presence#trigger-events). + +### 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/rest/presence-message) objects describing the members present on the channel. | [PresenceMessage](/docs/pub-sub/api/javascript/rest/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
+ +{`rest.getDevice(): Promise`} + +Retrieves a [`LocalDevice`](/docs/pub-sub/api/javascript/rest/push#LocalDevice) object representing the current device as a push notification target, loading its state from persistent storage if necessary. + +### Returns + +`Promise` + +Returns a promise. The promise is fulfilled with the [`LocalDevice`](/docs/pub-sub/api/javascript/rest/push#LocalDevice), or rejected with an [`ErrorInfo`](#errorinfo) object. + +## PaginatedResult + +A `PaginatedResult` represents a page of results from a paginated query such as [`stats()`](#stats), [`channel.history()`](/docs/pub-sub/api/javascript/rest/channel#history), [`presence.history()`](/docs/pub-sub/api/javascript/rest/presence#history), or [`channel.getMessageVersions()`](/docs/pub-sub/api/javascript/rest/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 | +| remediation | Actionable guidance describing how to fix the error, as distinct from `message`, which describes what went wrong. Present only on SDK-originating errors with meaningful remediation steps. | String or Undefined | + +