Skip to content

[DRAFT][EDU-1899] Chat JS API references #2681

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 18 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion gatsby-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export const plugins = [
className: `gatsby-copyable-header`,
removeAccents: true,
isIconAfterHeader: true,
elements: [`h2`, `h3`],
elements: [`h2`, `h3`, `h4`],
},
},
{
Expand Down
61 changes: 61 additions & 0 deletions src/data/nav/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,67 @@ export default {
link: '/docs/api/chat-rest',
name: 'REST API',
},
{
name: 'JavaScript SDK',
pages: [
{
name: 'ChatClient',
link: '/docs/chat/api/javascript/chat-client',
},
{
name: 'Authentication',
link: '/docs/chat/api/javascript/auth',
},
{
name: 'Connection',
link: '/docs/chat/api/javascript/connection',
},
{
name: 'Rooms',
link: '/docs/chat/api/javascript/rooms',
},
{
name: 'Room',
link: '/docs/chat/api/javascript/room',
},
{
name: 'Room reactions',
link: '/docs/chat/api/javascript/room-reactions',
},
{
name: 'Message',
link: '/docs/chat/api/javascript/message',
},
{
name: 'Messages',
link: '/docs/chat/api/javascript/messages',
},
{
name: 'Message reactions',
link: '/docs/chat/api/javascript/messages-reactions',
},
{
name: 'Presence',
link: '/docs/chat/api/javascript/presence',
},
{
name: 'Occupancy',
link: '/docs/chat/api/javascript/occupancy',
},
{
name: 'Typing',
link: '/docs/chat/api/javascript/typing',
},
{
name: 'Subscriptions',
link: '/docs/chat/api/javascript/subscriptions',
},
{
name: 'ErrorInfo',
link: '/docs/chat/api/javascript/error-info',
},
],
},
],
},
],
Expand Down
193 changes: 193 additions & 0 deletions src/pages/docs/chat/api/javascript/auth.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
---
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we call out the JWT format here?

title: Authentication
meta_description: "Ably Chat JavaScript API references for authentication."
---

The [ChatClient](/docs/chat/api/javascript/chat-client) requires a realtime client generated by the core [Pub/Sub SDK](/docs/basics) to establish a connection with Ably. This realtime client is used to handle authentication with Ably.

There are broadly three mechanisms of authentication with Ably:

* JSON Web Tokens (JWT): a standard JWT constructed to be compatible with Ably.
* Ably Tokens: a token generated by the Ably service for authentication. Your server can create a tokenRequest for clients to authenticate with Ably, or it can request an Ably Token directly from Ably and pass that to clients.
* Basic authentication: a method of authenticating using only your API key. This should only be used during development or server-side where it cannot be exposed.

JWTs are recommended for authenticating in a production environment. Use Ably Tokens if your JWT is too large, such as when you are requesting a large set of capabilities, or have very long clientIds. This is because there is a limit on URL length in browsers when using JWTs as an accessToken query param. The other use-case for Ably Tokens is because claims are publicly visible in JWTs. Ably Tokens are encrypted so clientIds and capabilities cannot be inspected.

---

## Pub/Sub constructor

The Pub/Sub constructor instantiates a realtime client that can be passed to the [`ChatClient`](/docs/chat/api/javascript/chat-client).

`new Ably.Realtime(ClientOptions clientOptions)`

### Parameters

Use the following parameters:

| Parameter | Description | Type |
| --------- | ----------- | ---- |
| `clientOptions` | The options to pass to customize the client connection. | [`ClientOptions`](#clientoptions) |

### ClientOptions

The following `ClientOptions` can be set:

| Property | Description | Type |
| -------- | ----------- | ---- |
| `clientId` | *Optional* The identity of the client. It may also be implicit within an Ably Token or JWT. This is required to use the Chat SDK. | String |
| `authUrl` | *Optional* A URL that the SDK uses to obtain a fresh Ably Token or JWT. | String |
| `authCallback` | *Optional* A function in the form `function(tokenParams, callback(err, tokenOrTokenRequest))` which is called when a fresh Ably Token or JWT is required. | Callable |
| `key` | *Optional* A full API key obtained from your Ably dashboard. This should only used with basic authentication for your authentication server or for clients in development environments. | String |

---

## Auth

The `Auth` interface creates TokenRequest objects and obtains Ably Tokens from Ably to issue to less-trusted clients.

Access it via `RealtimeClient.Auth`.

### Properties

It has the following properties:

| Property | Description | Type |
| -------- | ----------- | ---- |
| `clientId` | The identity of the client. It may also be implicit within an Ably Token or JWT. This is required to use the Chat SDK. | String |

---

## Fetch a new token <a id="authorize"/>

`auth.authorize()`

Instructs the SDK to fetch a new Ably Token or JWT.

It upgrades the current realtime connection to use the new token if the client is already connected. If they haven't yet connected then it initiates a connection to Ably.

Any [`TokenParams`](#tokenparams) and [`AuthOptions`](#authoptions) will be used as the new defaults for subsequent implicit and explicit token requests. They also entirely replace, as opposed to merging with, the current stored values.

`authorize(TokenParams tokenParams?, AuthOptions authOptions?): Promise<TokenDetails>`

### Parameters

Use the following parameters:

| Parameter | Description | Type |
| --------- | ----------- | ---- |
| `tokenParams` | *Optional* The parameters of the token for the request. | [`TokenParams`](#tokenparams) |
| `authOptions` | *Optional* The authentication options for the request. | [`AuthOptions`](#authoptions) |

#### TokenParams

An object used in the parameters of token authentication requests for defining the required attributes of a token.

It has the following properties:

| Property | Description | Type |
| -------- | ----------- | ---- |
| `capability` | *Optional* The JSON stringified [capabilities](/docs/auth/capabilities) for the token. If the request is successful, this will be an intersection of these capabilities and the issuing API key. | String |
| `clientId` | *Optional* The identity of the client. This is required to use the Chat SDK. | String |
| `nonce` | *Optional* An opaque string of at least 16 characters to ensure uniqueness of the request. | String |
| `timestamp` | *Optional* The timestamp of the request in milliseconds since the Unix epoch. Used with the `nonce` to ensure uniqueness of the request. | Integer |
| `ttl` | *Optional* The time to live for the token in milliseconds. The default is 60 minutes. | Integer |

#### AuthOptions

An object used when making authentication requests. If supplied it will replace the default values provided when the connection was established rather than merging with them.

It has the following properties:

| Property | Description | Type |
| -------- | ----------- | ---- |
| `authCallback` | *Optional* A function in the form `function(tokenParams, callback(err, tokenOrTokenRequest))` which is called when a fresh Ably Token or JWT is required. | Callable |
| `authUrl` | *Optional* A URL that the SDK uses to obtain a fresh Ably Token or JWT. | String |
| `authMethod` | *Optional* The HTTP method to use for `authUrl` requests. Either `GET` or `POST`. The default is `GET`. | String |
| `authHeaders` | *Optional* A set of key-value pair headers to add to `authUrl` requests. | Object |
| `authParams` | *Optional* A set of key-value pairs to add to `authUrl` requests. When the `authMethod` is `GET` params are added to the URL. When the `authMethod` is `POST` they are sent as URL-encoded form data. | Object |
| `tokenDetails` | *Optional* An authenticated `TokenDetails` object. This is commonly used in testing. In production it is preferable to use a method that renews the token automatically since they are short-lived. | [`TokenDetails`](#tokendetails) |
| `key` | *Optional* A full API key string. Used for basic authentication requests. | String |
| `token` | *Optional* An authenticated token. Either a `TokenDetails` object, a token string from the `token` property of a `TokenDetails` component of a `TokenRequest` response, or a JWT. This is commonly used in testing. In production it is preferable to use a method that renews the token automatically since they are short-lived. | String \| Object |
| `queryTime` | *Optional* If `true`, queries Ably for the current time when issuing `TokenRequests`. The default is `false`. | Boolean |
| `useTokenAuth` | *Optional* If `true`, forces the SDK to use token authentication. | Boolean |

#### TokenDetails

Contains an Ably Token and its associated metadata.

It has the following properties:

| Property | Description | Type |
| -------- | ----------- | ---- |
| `token` | The Ably Token itself. | String |
| `expires` | The timestamp of when the token expires in milliseconds since the Unix epoch. | Integer |
| `issued` | The timestamp of when the token was issued in milliseconds since the Unix epoch. | Integer |
| `capability` | *Optional* The [capabilities](/docs/auth/capabilities) associated with the token. | String |
| `clientId` | *Optional* The identity of the client. This is required to use the Chat SDK. | String |

#### TokenRequest

Contains the properties of a request for a token to Ably. Tokens are generated using [`requestToken()`](#requesttoken).

It has the following properties:

| Property | Description | Type |
| -------- | ----------- | ---- |
| `keyName` | The name of the API key against which the request was is made. Note that the name is public, whereas the secret is private. | String |
| `timestamp` | The timestamp of when the request was made in milliseconds since the Unix epoch. | Integer |
| `capability` | The [capabilities](/docs/auth/capabilities) for the token. If the request is successful, this will be an intersection of these capabilities and the issuing API key. | String |
| `nonce` | An opaque string of at least 16 characters to ensure uniqueness of the request. | String |
| `mac` | The Message Authentication Code (MAC) for the request. | String |
| `ttl` | *Optional* The time to live for the token in milliseconds. | Integer |
| `clientId` | *Optional* The identity of the client. This is required to use the Chat SDK. | String |

### Returns

Returns a promise. On success, the promise is fulfilled with the new [`TokenDetails`](#tokendetails) once the connection has been upgraded or initiated. On failure, the connection will move to the `SUSPENDED` or `FAILED` state, and the promise will be rejected with an [`ErrorInfo`](/docs/chat/api/javascript/error-info) object which explains the error.

---

## Create a tokenRequest <a id="createTokenRequest"/>

`auth.createTokenRequest()`

Creates and signs an Ably [`TokenRequest`](#tokenrequest) based on the specified [`TokenParams`](#tokenparams) and [`AuthOptions`](#authoptions). If no `TokenParams` or `AuthOptions` are specified it will use those already stored by the SDK, set in the [`ClientOptions`](#clientoptions) when the SDK was instantiated or updated via an [`authorize()`](#authorize) request. New values replace the existing ones rather than merging with them.

`createTokenRequest(TokenParams tokenParams?, AuthOptions authOptions?): Promise<TokenRequest>`

### Parameters

Use the following parameters:

| Parameter | Description | Type |
| --------- | ----------- | ---- |
| `tokenParams` | *Optional* The parameters of the token for the request. | [`TokenParams`](#tokenparams) |
| `authOptions` | *Optional* The authentication options for the request. | [`AuthOptions`](#authoptions) |

### Returns

Returns a promise. On success it will be fulfilled with a [`TokenRequest`](#tokenrequest) object. Upon failure, the promise will be rejected with an [`ErrorInfo`](/docs/chat/api/javascript/error-info) object which explains the error.

---

## Request a token <a id="requesttoken"/>

`auth.requestToken()`

Calls the `requestToken` endpoint to obtain an Ably Token according to the specified [`TokenParams`](#tokenparams) and [`AuthOptions`](#authoptions). If no `TokenParams` or `AuthOptions` are specified it will use those already stored by the SDK, set in the [`ClientOptions`](#clientoptions) when the SDK was instantiated or updated via an [`authorize()`](#authorize) request. New values replace the existing ones rather than merging with them.

`requestToken(TokenParams tokenParams?, AuthOptions authOptions?): Promise<TokenDetails>`

### Parameters

Use the following parameters:

| Parameter | Description | Type |
| --------- | ----------- | ---- |
| `tokenParams` | *Optional* The parameters of the token for the request. | [`TokenParams`](#tokenparams) |
| `authOptions` | *Optional* The authentication options for the request. | [`AuthOptions`](#authoptions) |

### Returns

Returns a promise. On success it will be fulfilled with a [`TokenDetails`](#tokendetails) object. Upon failure, the promise will be rejected with an [`ErrorInfo`](/docs/chat/api/javascript/error-info) object which explains the error.
126 changes: 126 additions & 0 deletions src/pages/docs/chat/api/javascript/chat-client.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
---
title: ChatClient
meta_description: "Ably Chat JavaScript API references for the ChatClient constructor."
---

The `ChatClient` class is the core client for Ably Chat.

---

## Accessors

| Property | Description | Type |
| -------- | ----------- | ---- |
| `clientId` | The clientId of the current client. | String |
| `clientOptions` | The resolved client options for the client, including any defaults that have been set. | [`ChatClientOptions`](#chatclientoptions) |
| `connection` | The underlying connection to Ably, which can be used to monitor the client's connection to Ably servers. | [`Connection`](/docs/chat/api/javascript/connection) |
| `realtime` | The underlying Ably Realtime client. | [`Realtime`](#realtime) |
| `rooms` | The rooms object, which provides access to chat rooms. | [`Rooms`](/docs/chat/api/javascript/rooms) |

---

## Constructor

`new ChatClient()`

Creates a new ChatClient instance.

`new ChatClient(realtime: Realtime, clientOptions?: ChatClientOptions): ChatClient`

### Parameters

Use the following parameters:

| Parameter | Description | Type |
| --------- | ----------- | ---- |
| `realtime` | The Ably Realtime client. | [`Realtime`](#realtime) |
| `clientOptions` | *Optional* The client options. | [`ChatClientOptions`](#chatclientoptions) |

#### ChatClientOptions

The following `ChatClientOptions` can be set:

| Properties | Description | Type |
| ---------- | ----------- | ---- |
| `logLevel` | *Optional* The logging level to use. The default is `LogLevel.Error`. | [`LogLevel`](#loglevel) |
| `logHandler` | *Optional* A custom log handler. The default behavior will log messages to the console. | [`LogHandler`](#loghandler) |

#### LogLevel

An enum representing the different log levels.

Logs of higher severity than the specified `LogLevel` are automatically logged.

It has the following members:

| Member | Description |
| ------ | ----------- |
| `Silent` | No logging will be performed. |
| `Trace` | Something routine and expected has occurred. This level will provide logs for the vast majority of operations and function calls. |
| `Debug` | Development information, messages that are useful when trying to debug library behavior, but superfluous to normal operation. |
| `Info` | Informational messages. Operationally significant to the library but not out of the ordinary. |
| `Warn` | Anything that is not immediately an error, but could cause unexpected behavior in the future. For example, passing an invalid value to an option. Indicates that some action should be taken to prevent future errors. |
| `Error` | A given operation has failed and cannot be automatically recovered. The error may threaten the continuity of operation. |

#### LogHandler

A function that handles log messages.

`LogHandler: (message: string, level: LogLevel, context?: LogContext) => void`

Use the following parameters:

| Parameter | Description | Type |
| --------- | ----------- | ---- |
| `message` | The message being logged. | String |
| `logLevel` | The log level of the message. | [`LogLevel`](#loglevel) |
| `context` | *Optional* The context of the log message as key-value pairs. | [`LogContext`](#logcontext) |

#### LogContext

Represents the context of a log message. It is an object of key-value pairs that can be used to provide additional context to a log message.

`LogContext: Record<string, any>`

### Returns

Returns a new `ChatClient` instance.

<Code>
```javascript
import * as Ably from 'ably';
import { ChatClient, LogLevel } from '@ably/chat';

const realtimeClient = new Ably.Realtime({ key: 'your-api-key' });
const chatClient = new ChatClient(realtimeClient, {
logLevel: 'LogLevel.Debug'
});
```
</Code>

---

## Realtime

The Chat constructor requires a realtime client generated using the core [Pub/Sub SDK](/docs/basics) to establish a connection with Ably. The realtime client handles [authentication](/docs/chat/api/javascript/auth) with Ably.

`new Ably.Realtime(ClientOptions clientOptions)`

### Parameters

Use the following parameters:

| Parameter | Description | Type |
| --------- | ----------- | ---- |
| `clientOptions` | The options to pass to customize the client connection. | [`ClientOptions`](#clientoptions) |

### ClientOptions

The following `ClientOptions` can be set:

| Property | Description | Type |
| -------- | ----------- | ---- |
| `clientId` | *Optional* The identity of the client. It may also be implicit within an Ably Token or JWT. This is required to use the Chat SDK. | String |
| `authUrl` | *Optional* A URL that the SDK uses to obtain a fresh Ably Token or JWT. | String |
| `authCallback` | *Optional* A function in the form `function(tokenParams, callback(err, tokenOrTokenRequest))` which is called when a fresh Ably Token or JWT is required. | Callable |
| `key` | *Optional* A full API key obtained from your Ably dashboard. This should only used with basic authentication for your authentication server or for clients in development environments. | String |
Loading