### Install Dependencies Source: https://github.com/getstream/stream-node/blob/main/CONTRIBUTING.md Run this command to install project dependencies using Yarn. ```shell yarn install ``` -------------------------------- ### StreamClient Initialization Example Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Example of how to instantiate StreamClient with custom timeout and base path options. ```typescript const client = new StreamClient(apiKey, secret, { timeout: 5000, basePath: 'https://custom.stream-io-api.com', }); ``` -------------------------------- ### Create User Token Payload Example Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Example of creating a UserTokenPayload object with required fields and custom claims. Includes standard iat and exp timestamps. ```typescript const payload: UserTokenPayload = { user_id: 'user123', iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 3600, custom_claim: 'value', }; ``` -------------------------------- ### CallTokenPayload Example Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Demonstrates how to construct a CallTokenPayload object for generating call-specific authentication tokens. ```typescript const payload: CallTokenPayload = { user_id: 'user123', call_cids: ['default:call-001', 'default:call-002'], role: 'admin', iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 3600, }; ``` -------------------------------- ### StreamFeed Example Usage Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeed.md Demonstrates common operations on a StreamFeed, including adding, retrieving, reacting to, and deleting activities. Ensure the StreamFeedsClient is initialized before use. ```typescript const userFeed = client.feeds.feed('user', 'user123'); // Add an activity const activity = await userFeed.addActivity({ actor: 'user:user123', verb: 'post', object: 'article:123', text: 'User posted an article', }); // Retrieve activities const result = await userFeed.get({ pagination: { limit: 20, offset: 0 }, }); result.results.forEach(activity => { console.log(activity.text); }); // React to an activity await userFeed.addActivityReaction({ activity_id: activity.id, kind: 'like', user_id: 'user123', }); // Delete an activity await userFeed.deleteActivity(activity.id); ``` -------------------------------- ### Create and Get Video Call Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Initiate or retrieve a video call, generating a call token for the specified user. This is useful for starting real-time meetings. ```typescript async function startCall(userId, callType, callId) { const call = client.video.call(callType, callId); const response = await call.getOrCreate({ data: { title: 'Meeting' } }); const token = client.generateCallToken({ user_id: userId, call_cids: [call.cid], validity_in_seconds: 3600, }); return { call: response.call, token }; } ``` -------------------------------- ### Pagination with Limit and Offset Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Specify the number of results to return (limit) and the starting point (offset) for pagination. ```typescript { limit: 20, offset: 0, } ``` -------------------------------- ### Generating User and Call Tokens Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Provides examples for generating server-side authentication tokens for users and specific calls using the StreamClient. ```typescript const client = new StreamClient(apiKey, secret); // User auth token const userToken = client.generateUserToken({ user_id: 'user-id', validity_in_seconds: 3600, }); // Call-specific token const callToken = client.generateCallToken({ user_id: 'user-id', call_cids: ['default:call-001'], validity_in_seconds: 3600, }); ``` -------------------------------- ### Add Stream Node.js SDK Dependency Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md To validate as a package consumer, add the SDK to your project's package.json and install. ```json { "dependencies": { "@stream-io/node-sdk": ">=0.6.5" } } ``` -------------------------------- ### Sorting Example Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Define sorting criteria for query results using a sort array with field and direction. ```typescript { sort: [ { field: 'created_at', direction: 'desc' } ] } ``` -------------------------------- ### Checking Rate Limits with StreamError Source: https://github.com/getstream/stream-node/blob/main/_autodocs/errors.md This example shows how to check for rate limit errors. It specifically looks for a rate limit remaining of 0 and logs the time when the rate limit will reset. ```typescript try { await client.video.queryCallMembers(request); } catch (error) { if (error instanceof StreamError) { const remaining = error.metadata.rateLimit?.rateLimitRemaining; if (remaining === 0) { console.error('Rate limit exceeded'); const reset = error.metadata.rateLimit?.rateLimitReset; console.log('Resets at:', reset); } } } ``` -------------------------------- ### get() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Retrieves current call data without creating. Populates the internal `data` property. Throws an error if the call does not exist. ```APIDOC ## get() Retrieve current call data without creating. ```typescript get(): Promise ``` **Returns:** Promise resolving to GetCallResponse **Side Effect:** Populates the internal `data` property with call information **Throws:** Error if call does not exist **Example:** ```typescript const response = await callClient.get(); console.log(response.call.created_at); ``` ``` -------------------------------- ### Filter Conditions Example Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Use filter_conditions to specify criteria for querying data. This example filters by role and status. ```typescript { filter_conditions: { role: 'admin', status: 'active', } } ``` -------------------------------- ### Create a StreamFeed Instance Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeedsClient.md Use the `feed()` method to get a StreamFeed instance for a specific feed group and ID. This instance can then be used to retrieve activities. ```typescript const userFeed = client.feeds.feed('user', 'user123'); const activities = await userFeed.get(); ``` -------------------------------- ### Fully-Qualified Resource IDs Source: https://github.com/getstream/stream-node/blob/main/_autodocs/README.md Resources use composite IDs combining type and identifier. Examples include call CIDs, channel CIDs, and feed IDs. ```typescript call.cid // "type:id" format, e.g., "default:call-001" channel.cid // "type:id" format, e.g., "messaging:general" feed.feed // "group:id" format, e.g., "user:user-123" ``` -------------------------------- ### Connect OpenAI Realtime API Agent to a Call Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamVideoClient.md This method creates and connects an OpenAI Realtime API agent to a specified call. Ensure that the '@stream-io/openai-realtime-api' package is installed and provide a valid OpenAI API key. The agentUserId is required for the agent participant. ```typescript const realtimeClient = await client.video.connectOpenAi({ call: callClient, agentUserId: 'ai-agent-001', openAiApiKey: process.env.OPENAI_API_KEY, model: 'gpt-4-realtime-preview', }); await realtimeClient.connect(); ``` -------------------------------- ### Access Response Data and Metadata Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Example of how to access both the specific response data (e.g., `response.call`) and the associated metadata (e.g., `response.metadata.responseCode`) from a Stream API call. ```typescript const response = await client.video.getOrCreateCall(request); // response.call contains the call data // response.metadata contains request/response info console.log(response.metadata.responseCode); console.log(response.metadata.rateLimit.rateLimitRemaining); ``` -------------------------------- ### Create SRT Credentials Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Generate SRT streaming credentials for a user after ensuring call data is initialized by calling get() or getOrCreate(). The returned address includes embedded authentication. ```typescript const call = await callClient.getOrCreate(); const srtCreds = callClient.createSRTCredentials('user123'); console.log(srtCreds.address); // Output: srt://stream.example.com:5000?passphrase=...&token=... ``` -------------------------------- ### Initialize Stream Client and Use SDK Features Source: https://github.com/getstream/stream-node/blob/main/_autodocs/README.md Demonstrates how to initialize the StreamClient, generate user tokens, and interact with video call and chat functionalities. Also shows how to verify and parse incoming webhooks. ```typescript import { StreamClient } from '@stream-io/node-sdk'; const client = new StreamClient(apiKey, apiSecret); // Token generation const userToken = client.generateUserToken({ user_id: 'user-123' }); // Video calls const call = client.video.call('default', 'call-001'); await call.getOrCreate(); // Chat const channel = client.chat.channel('messaging', 'general'); await channel.getOrCreate({ name: 'General' }); // Webhook handling const event = client.verifyAndParseWebhook(rawBody, signature); ``` -------------------------------- ### Initialize Stream Client and Use Core Features Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Demonstrates initializing the StreamClient and performing basic operations for Video, Chat, Feeds, and Token Generation. Ensure you have your API key and secret. ```typescript import { StreamClient } from '@stream-io/node-sdk'; // Initialize client const client = new StreamClient(apiKey, apiSecret); // Video const call = client.video.call('default', 'call-id'); await call.getOrCreate(); // Chat const channel = client.chat.channel('messaging', 'general'); await channel.getOrCreate({ name: 'General' }); // Feeds const feed = client.feeds.feed('user', 'user-id'); // Token generation const token = client.generateUserToken({ user_id: 'user-id', validity_in_seconds: 3600, }); // Webhook verification const event = client.verifyAndParseWebhook(rawBody, signature); ``` -------------------------------- ### Get Fully-Qualified Feed ID Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeed.md Access the 'feed' property to get the computed feed ID in the format '{group}:{id}'. ```typescript const userFeed = client.feeds.feed('user', 'user123'); console.log(userFeed.feed); // 'user:user123' ``` -------------------------------- ### Initialize StreamClient with Custom Configuration Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Demonstrates how to initialize the StreamClient with custom options such as request timeout, a custom API base path, and a custom HTTP agent. ```typescript const client = new StreamClient(apiKey, secret, { timeout: 5000, // Request timeout in ms basePath: 'https://api.custom.io', // Custom API URL agent: customHttpAgent, // Custom HTTP agent }); ``` -------------------------------- ### Get Call Data Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Retrieve current call data using the get method without creating a new call. This populates the internal `data` property but will throw an error if the call does not exist. ```typescript const response = await callClient.get(); console.log(response.call.created_at); ``` -------------------------------- ### Initialize Stream Client (With Options) Source: https://github.com/getstream/stream-node/blob/main/_autodocs/README.md Configure timeout, custom API base path, or a custom HTTP agent for advanced use cases. ```typescript const client = new StreamClient(apiKey, secret, { timeout: 5000, // Request timeout basePath: 'https://custom.stream-api.com', // Custom API URL agent: customHttpAgent, // Custom HTTP agent }); ``` -------------------------------- ### Create or Retrieve a StreamCall Instance Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamVideoClient.md Use this method to get a StreamCall instance for a specific call type and ID. You can then use the instance to perform call-related operations like getting or creating the call. ```typescript const callClient = client.video.call('default', 'call-001'); const call = await callClient.getOrCreate(); ``` -------------------------------- ### Run Tests with Bun Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md Execute project tests specifically using the Bun runtime. ```bash yarn test:bun ``` -------------------------------- ### Initialize Stream Client (Basic) Source: https://github.com/getstream/stream-node/blob/main/_autodocs/README.md Use this for basic initialization with only API key and secret. ```typescript const client = new StreamClient(apiKey, secret); ``` -------------------------------- ### Get Call CID Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Access the computed call ID in the format {type}:{id} from a StreamCall instance. ```typescript const callClient = client.video.call('default', 'call-001'); console.log(callClient.cid); // 'default:call-001' ``` -------------------------------- ### Pre-commit Hooks: Lint and Format Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md Commands to run before committing code, ensuring code quality and consistency. ```bash yarn lint yarn prettier:fix ``` -------------------------------- ### StreamVideoClient Constructor Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamVideoClient.md Initializes a new StreamVideoClient instance. It requires a parent StreamClient for token generation and an ApiClient for making HTTP requests. ```APIDOC ## Constructor StreamVideoClient ### Description Initializes a new StreamVideoClient instance. It requires a parent StreamClient for token generation and an ApiClient for making HTTP requests. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options.streamClient** (StreamClient) - Required - Parent StreamClient instance for token generation - **options.apiClient** (ApiClient) - Required - HTTP API client for making requests ``` -------------------------------- ### StreamClient Methods Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Primary entry point for the Stream Node SDK. Initialize once at application startup to access various services like Video, Chat, Feeds, Moderation, and token generation. ```APIDOC ## StreamClient Methods ### Description Primary entry point for the Stream Node SDK. Initialize once at application startup to access various services like Video, Chat, Feeds, Moderation, and token generation. ### Methods - `generateUserToken(options)`: Create user authentication tokens. - `generateCallToken(options)`: Create call-specific tokens. - `verifyAndParseWebhook(rawBody, signature)`: Verify and parse incoming webhook events. - `parseSqs(message)`: Parse SQS firehose messages. - `parseSns(notification)`: Parse SNS notifications. ### Properties - `video: StreamVideoClient`: Provides access to Video API operations. - `chat: StreamChatClient`: Provides access to Chat API operations. - `feeds: StreamFeedsClient`: Provides access to Feeds API operations. - `moderation: StreamModerationClient`: Provides access to Moderation tools. ``` -------------------------------- ### connectOpenAi() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamVideoClient.md Creates and connects an OpenAI Realtime API agent to a specified call. This method facilitates integrating AI capabilities into video calls. ```APIDOC ## connectOpenAi(options: { call: StreamCall; agentUserId: string; openAiApiKey: string; model?: RealtimeAPIModel; validityInSeconds?: number; }) ### Description Create and connect an OpenAI Realtime API agent to a call. ### Method None (SDK method) ### Endpoint None (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options.call** (StreamCall) - Required - The call to connect the agent to - **options.agentUserId** (string) - Required - User ID for the agent participant - **options.openAiApiKey** (string) - Required - OpenAI API key - **options.model** (RealtimeAPIModel) - Optional - OpenAI Realtime API model to use - **options.validityInSeconds** (number) - Optional - Token validity duration in seconds ### Returns Promise resolving to RealtimeClient instance ### Throws - Error when @stream-io/openai-realtime-api is not installed - Error when agentUserId is not provided ### Example ```typescript const realtimeClient = await client.video.connectOpenAi({ call: callClient, agentUserId: 'ai-agent-001', openAiApiKey: process.env.OPENAI_API_KEY, model: 'gpt-4-realtime-preview', }); await realtimeClient.connect(); ``` ``` -------------------------------- ### OmitTypeId Usage Example Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Illustrates using OmitTypeId to create request payloads by excluding automatically set fields like 'type' and 'id'. ```typescript // Omit type and id from a request const request: OmitTypeId = { filter_conditions: { role: 'user' }, }; ``` -------------------------------- ### Optional Environment Variables Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Configure optional settings like custom API URL, request timeout, or HTTP proxy using environment variables. ```bash STREAM_API_URL=https://api.custom.io # Custom API URL STREAM_TIMEOUT=5000 # Request timeout in ms HTTPS_PROXY=http://proxy:3128 # HTTP proxy ``` -------------------------------- ### Handle Stream API Errors Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Example of catching and inspecting a StreamError in a try-catch block. Checks for the error type and logs relevant details. ```typescript try { await client.chat.getOrCreateChannel(request); } catch (error) { if (error instanceof StreamError) { console.error('API error:', error.code, error.message); console.log('Response code:', error.metadata.responseCode); } } ``` -------------------------------- ### Agent Checklist for Commits Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md A quick checklist for AI agents to perform before each commit to ensure code quality and project standards. ```bash yarn build yarn test yarn lint yarn prettier:fix Add/adjust tests No new warnings or linting errors ``` -------------------------------- ### Stream Node.js Client Hierarchy Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Illustrates the main entry point and the hierarchical structure for accessing different Stream services like Video, Chat, and Feeds. ```text StreamClient (main entry point) ├── StreamVideoClient (extends VideoApi) │ └── call() → StreamCall (extends CallApi) ├── StreamChatClient (extends ChatApi) │ └── channel() → StreamChannel (extends ChannelApi) ├── StreamFeedsClient (extends FeedsApi) │ └── feed() → StreamFeed (extends FeedApi) ├── StreamModerationClient (extends ModerationApi) └── CommonApi (for user management) ``` -------------------------------- ### Build Project with Yarn Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md Use this command to build the TypeScript project into the dist/ directory. ```bash yarn build ``` -------------------------------- ### Run ESLint for Linting Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md Execute ESLint to check code for potential errors and style issues. ```bash yarn lint ``` -------------------------------- ### Configure HTTP Agent with Proxy Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Set up a proxy agent for requests using Undici. Ensure the proxy URL is correctly formatted. ```typescript import { Agent, ProxyAgent } from 'undici'; const proxyAgent = new ProxyAgent('http://proxy.example.com:3128'); const client = new StreamClient(apiKey, secret, { agent: proxyAgent, }); ``` -------------------------------- ### Run All Tests with Vitest Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md Execute all project tests using the Vitest test runner. ```bash yarn test ``` -------------------------------- ### StreamClient Constructor Parameters Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Initialize the StreamClient with your API key, secret, and optional configuration. ```typescript const client = new StreamClient( apiKey: string, secret: string, config?: StreamClientOptions ); ``` -------------------------------- ### Create or Get Call Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Use getOrCreate to create a new call if it doesn't exist or retrieve existing call data. This method populates the internal `data` property with call information. ```typescript const response = await callClient.getOrCreate({ data: { title: 'Team Meeting', description: 'Weekly sync', settings_override: { audio: true, video: true }, }, }); console.log(response.call.id); ``` -------------------------------- ### Get or Create Channel Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamChannel.md Creates a channel if it doesn't exist or retrieves existing channel data. Use for both named and distinct channels. For distinct channels, the internal ID is populated upon creation. ```typescript getOrCreate(request?: ChannelGetOrCreateRequest): Promise ``` ```typescript // Named channel const response = await channel.getOrCreate({ name: 'General', data: { color: 'blue' }, members: [{ id: 'user1' }, { id: 'user2' }], }); console.log(response.channel.name); // Distinct channel (1-on-1) const distinctChannel = client.chat.channel('messaging'); const response = await distinctChannel.getOrCreate({ members: [{ id: 'user1' }, { id: 'user2' }], }); console.log(distinctChannel.id); // Now populated with generated ID ``` -------------------------------- ### Module Exports Source: https://github.com/getstream/stream-node/blob/main/_autodocs/README.md Imports available classes and types from the main SDK entry point. ```typescript export * from './src/StreamClient'; export * from './src/StreamCall'; export * from './src/StreamChatClient'; export * from './src/StreamChannel'; export * from './src/StreamVideoClient'; export * from './src/gen/models'; // All model types export * from './src/StreamFeedsClient'; export * from './src/StreamFeed'; export { InvalidWebhookError, InvalidWebhookErrorMessages, } from './src/utils/webhook'; ``` -------------------------------- ### StreamClient Constructor Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamClient.md Initializes a new StreamClient instance with your API key and secret. Optionally, you can provide configuration options for timeouts, base paths, and HTTP agents. ```APIDOC ## StreamClient Constructor ### Description Initializes a new StreamClient instance with your API key and secret. Optionally, you can provide configuration options for timeouts, base paths, and HTTP agents. ### Parameters #### Path Parameters - **apiKey** (string) - Required - Stream API key for authentication - **secret** (string) - Required - Stream API secret for token generation and webhook verification - **config** (StreamClientOptions) - Optional - Configuration options ### StreamClientOptions #### Properties - **timeout** (number) - Optional - Request timeout in milliseconds (Default: 3000) - **basePath** (string) - Optional - Base URL for API requests (Default: Uses default Stream endpoints) - **agent** (unknown) - Optional - HTTP Agent for request handling ``` -------------------------------- ### Handle Request Timeout Errors Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Catch and identify Stream API request timeouts. This example demonstrates how to check for timeout-related error messages and log a user-friendly warning, suggesting an increase in the client's timeout configuration. ```typescript try { await client.video.getOrCreateCall(request); } catch (error) { if (error instanceof StreamError) { if (error.message.includes('timeout')) { console.error('Request timed out. Try increasing timeout in config.'); } } } ``` -------------------------------- ### StreamClient Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Main entry point for interacting with Stream services, including token generation and webhook handling. ```APIDOC ## StreamClient ### Description Main entry point for interacting with Stream services, including token generation and webhook handling. ### Usage ```javascript import StreamClient from '@stream-io/node-sdk'; const client = new StreamClient('YOUR_API_KEY', 'YOUR_API_SECRET'); ``` ``` -------------------------------- ### Verifying and Parsing Webhooks Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Demonstrates how to securely verify webhook signatures and parse incoming event data using the StreamClient. ```typescript const event = client.verifyAndParseWebhook( req.rawBody, req.headers['x-signature'] ); // event is guaranteed valid ``` -------------------------------- ### Development Configuration Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Basic client configuration for development environments. Ensure API keys and secrets are set as environment variables. ```typescript const client = new StreamClient( process.env.STREAM_API_KEY, process.env.STREAM_API_SECRET, { timeout: 10000, basePath: process.env.STREAM_API_URL || 'https://video.stream-io-api.com', } ); ``` -------------------------------- ### Production Configuration with Connection Pooling Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Configure the client for production with connection pooling using undici. This optimizes performance by managing a pool of persistent connections. ```typescript import { Agent } from 'undici'; const agent = new Agent({ connections: 100, pipelining: 10, keepAliveTimeout: 60000, }); const client = new StreamClient( process.env.STREAM_API_KEY, process.env.STREAM_API_SECRET, { timeout: 5000, agent, } ); ``` -------------------------------- ### StreamCall Constructor Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Initializes a new StreamCall instance. ```APIDOC ## Constructor ```typescript constructor( videoApi: VideoApi, type: string, id: string, streamClient: StreamClient ) ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | videoApi | VideoApi | ✓ | Parent VideoApi instance | | type | string | ✓ | Call type (e.g., 'default', 'livestream') | | id | string | ✓ | Unique call identifier | | streamClient | StreamClient | ✓ | StreamClient instance for token generation | ``` -------------------------------- ### Format Code with Prettier Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md Use Prettier to automatically format code according to project standards. ```bash yarn prettier:fix ``` -------------------------------- ### create() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Alias for getOrCreate(). Creates a call if it doesn't exist. ```APIDOC ## create() Alias for getOrCreate(). Creates a call if it doesn't exist. ```typescript create(request?: GetOrCreateCallRequest): Promise ``` **Example:** ```typescript const response = await callClient.create(); ``` ``` -------------------------------- ### WebhookHelpers Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Functions for parsing and verifying webhooks. ```APIDOC ## WebhookHelpers ### Description Functions for parsing and verifying webhooks. ### Usage ```javascript import { verifyWebhook } from '@stream-io/node-sdk'; const isValid = verifyWebhook(req.headers, req.body, 'YOUR_API_SECRET'); ``` ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Configure the client using environment variables for API key, secret, base path, and timeout. Ensure these variables are set in your deployment environment. ```typescript const client = new StreamClient( process.env.STREAM_API_KEY, // API key from env process.env.STREAM_API_SECRET, // API secret from env { timeout: parseInt(process.env.STREAM_TIMEOUT || '3000'), basePath: process.env.STREAM_API_URL, } ); ``` -------------------------------- ### decodeSqsPayload() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/WebhookHelpers.md Reverses the SQS firehose envelope by first base64-decoding the input string and then decompressing it if it appears to be gzipped. This is useful for processing messages received from AWS SQS. ```APIDOC ## decodeSqsPayload() ### Description Reverse SQS firehose envelope (base64-decode then gzip-if-magic). Performs strict base64 validation (no permissive decoding) to avoid silently corrupting payload. ### Method N/A (Function Signature) ### Function Signature ```typescript export function decodeSqsPayload(body: string): Buffer ``` ### Parameters #### Arguments - **body** (string) - Required - Base64-encoded SQS message Body ### Returns Buffer with decoded and optionally decompressed content ### Throws `InvalidWebhookError` when base64/gzip envelope is malformed ``` -------------------------------- ### Stream Node.js SDK File Structure Source: https://github.com/getstream/stream-node/blob/main/_autodocs/README.md Overview of the directory structure for the Stream Node.js SDK, indicating the location of various documentation files and API references. ```text output/ ├── INDEX.md ← Navigation index ├── REFERENCE.md ← Complete reference ├── Configuration.md ← Config options ├── Types.md ← Type definitions ├── Errors.md ← Error reference ├── README.md ← This file └── api-reference/ ├── StreamClient.md ← Main client ├── StreamVideoClient.md ← Video API ├── StreamChatClient.md ← Chat API ├── StreamFeedsClient.md ← Feeds API ├── StreamModerationClient.md ← Moderation API ├── StreamCall.md ← Call resource ├── StreamChannel.md ← Channel resource ├── StreamFeed.md ← Feed resource ├── TokenGeneration.md ← Token functions └── WebhookHelpers.md ← Webhook functions ``` -------------------------------- ### Accessing Fully-Qualified IDs (CIDs) Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Demonstrates how to access the fully-qualified ID (CID) for calls, channels, and feeds using the .cid or .feed property. ```typescript const call = client.video.call('default', 'call-001'); console.log(call.cid); // "default:call-001" const channel = client.chat.channel('messaging', 'general'); console.log(channel.cid); // "messaging:general" const feed = client.feeds.feed('user', 'user-123'); console.log(feed.feed); // "user:user-123" ``` -------------------------------- ### StreamChannel Constructor Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamChannel.md Initializes a new StreamChannel instance. Requires a ChatApi instance, channel type, and optionally a channel ID for named channels. ```typescript constructor( chatApi: ChatApi, type: string, id?: string ) ``` -------------------------------- ### Required Environment Variables Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Set the STREAM_API_KEY and STREAM_API_SECRET environment variables to authenticate with the Stream API. ```bash STREAM_API_KEY=key_xxx STREAM_API_SECRET=secret_xxx ``` -------------------------------- ### createSRTCredentials() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Generates SRT (Secure Reliable Transport) streaming credentials for a user. Requires call data to be initialized first. ```APIDOC ## createSRTCredentials() Generate SRT (Secure Reliable Transport) streaming credentials for a user. ```typescript createSRTCredentials(userID: string): { address: string } ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | userID | string | ✓ | ID of the user streaming | **Returns:** Object with SRT address containing embedded authentication **Throws:** Error if call data is not initialized (must call get() or getOrCreate() first) **Example:** ```typescript const call = await callClient.getOrCreate(); const srtCreds = callClient.createSRTCredentials('user123'); console.log(srtCreds.address); // Output: srt://stream.example.com:5000?passphrase=...&token=... ``` ``` -------------------------------- ### StreamChatClient Constructor Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamChatClient.md Initializes a new instance of the StreamChatClient. It requires an ApiClient for making HTTP requests. ```APIDOC ## Constructor StreamChatClient ### Description Initializes a new instance of the StreamChatClient. It requires an ApiClient for making HTTP requests. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **apiClient** (ApiClient) - Required - HTTP API client for making requests ``` -------------------------------- ### StreamFeedsClient Methods Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Manage activity feeds, including creating, querying, and reacting to activities. ```APIDOC ## StreamFeedsClient Methods ### Description Manage activity feeds, including creating, querying, and reacting to activities. ### Methods - `feed(group, id)`: Access a specific feed by its group and ID. - `queryFeeds(options)`: Query multiple feeds based on specified criteria. - `addActivityReaction(activityId, reactionType, options)`: React to a specific activity. - `getOrCreateFollows(userId, targetFeeds, options)`: Create follows for a user to specified feeds. - `getOrCreateUnfollows(userId, targetFeeds, options)`: Remove follows for a user from specified feeds. ``` -------------------------------- ### feed() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeedsClient.md Create or retrieve a StreamFeed instance for a specific activity feed. ```APIDOC ## feed() ### Description Create or retrieve a StreamFeed instance for a specific activity feed. ### Method Signature ```typescript feed(group: string, id: string): StreamFeed ``` ### Parameters #### Path Parameters - **group** (string) - Required - Feed group/type (e.g., 'user', 'timeline') - **id** (string) - Required - Feed identifier ### Returns StreamFeed instance ### Example ```typescript const userFeed = client.feeds.feed('user', 'user123'); const activities = await userFeed.get(); ``` ``` -------------------------------- ### Create Chat Channel Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Create a new chat channel with a specified type and members. The channel can be named and configured with initial members. ```typescript async function createChannel(channelType, members) { const channel = client.chat.channel(channelType); const response = await channel.getOrCreate({ name: 'New Channel', members: members.map(id => ({ id })), }); return response.channel; } ``` -------------------------------- ### Regenerate API Clients Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md Command to regenerate API clients based on OpenAPI specifications. ```bash yarn generate:open-api ``` -------------------------------- ### queryFeeds() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeedsClient.md Query activity feeds with filtering and pagination. ```APIDOC ## queryFeeds() ### Description Query activity feeds with filtering and pagination. ### Method Signature ```typescript queryFeeds(request: QueryFeedsRequest): Promise ``` ### Parameters #### Request Body - **request.filter** (Record) - Optional - Filter conditions - **request.pagination** ({ limit?: number; offset?: number }) - Optional - Pagination settings ### Returns Promise resolving to QueryFeedsResponse ### Example ```typescript const result = await client.feeds.queryFeeds({ filter: { group: 'user' }, pagination: { limit: 10 }, }); result.results.forEach(feed => { console.log(feed.id); }); ``` ``` -------------------------------- ### StreamFeed Constructor Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeed.md Initializes a new StreamFeed instance. It requires a FeedsApi instance, a feed group, and a feed identifier. ```APIDOC ## StreamFeed Constructor ### Description Initializes a new StreamFeed instance. It requires a FeedsApi instance, a feed group, and a feed identifier. ### Parameters #### Path Parameters - **feedsApi** (FeedsApi) - Required - Parent FeedsApi instance - **group** (string) - Required - Feed group/type (e.g., 'user', 'timeline') - **id** (string) - Required - Feed identifier ``` -------------------------------- ### Configure HTTP Agent with Custom TLS Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Use a custom TLS configuration for the HTTP agent, providing certificates and keys for secure connections. ```typescript import { Agent } from 'undici'; import https from 'https'; const tlsAgent = new https.Agent({ ca: fs.readFileSync('./ca.pem'), cert: fs.readFileSync('./cert.pem'), key: fs.readFileSync('./key.pem'), }); const client = new StreamClient(apiKey, secret, { agent: tlsAgent, }); ``` -------------------------------- ### Generate User and Call Tokens Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/TokenGeneration.md This snippet demonstrates how to generate both user tokens and call tokens using the StreamClient. Ensure you have your API key and secret configured as environment variables. User tokens are for general chat functionality, while call tokens are specifically for video calls. ```typescript import { StreamClient } from '@stream-io/node-sdk'; const client = new StreamClient( process.env.STREAM_API_KEY, process.env.STREAM_API_SECRET ); // Server endpoint to issue tokens app.post('/auth/stream-token', (req, res) => { const { userId } = req.body; // Validate user is authenticated if (!userId) { return res.status(401).json({ error: 'Unauthorized' }); } // Generate token valid for 1 hour const token = client.generateUserToken({ user_id: userId, validity_in_seconds: 3600, }); res.json({ token }); }); // For video calls app.post('/auth/stream-call-token', (req, res) => { const { userId, callId } = req.body; if (!userId || !callId) { return res.status(400).json({ error: 'Missing parameters' }); } const token = client.generateCallToken({ user_id: userId, call_cids: [`default:${callId}`], validity_in_seconds: 3600, }); res.json({ token }); }); ``` -------------------------------- ### StreamChannel Methods Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Methods for interacting with chat channel instances, including creation, retrieval, and member querying. ```APIDOC ## StreamChannel Represents a chat channel instance. ### Methods - `getOrCreate()` - Create or retrieve channel - `queryMembers()` - Get channel members ### Properties - `cid` (string) - Fully-qualified channel ID (type:id) ``` -------------------------------- ### Verify and Parse Incoming Webhooks Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Handle incoming webhooks by verifying the signature and parsing the event data. This ensures the integrity of the data received from Stream. ```typescript app.post('/webhooks/stream', (req, res) => { try { const event = client.verifyAndParseWebhook( req.body, req.headers['x-signature'] ); console.log('Event:', event.type); res.status(200).json({ ok: true }); } catch (error) { console.error('Invalid webhook:', error.message); res.status(400).json({ error: 'Invalid' }); } }); ``` -------------------------------- ### WebhookHelpers Functions Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Functions for parsing and verifying webhook data, including signature verification and event parsing from various sources like SQS and SNS. ```APIDOC ## WebhookHelpers Webhook parsing and verification. ### Functions - `verifyAndParseWebhook()` - Verify signature and parse HTTP webhook - `parseSqs()` - Parse SQS message - `parseSns()` - Parse SNS message - `verifySignature()` - Verify signature only - `gunzipPayload()` - Decompress gzipped payload - `parseEvent()` - Parse JSON event ``` -------------------------------- ### StreamFeedsClient Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Client for managing activity feeds and reactions. ```APIDOC ## StreamFeedsClient ### Description Client for managing activity feeds and reactions. ### Usage ```javascript import { StreamFeedsClient } from '@stream-io/node-sdk'; const feedsClient = new StreamFeedsClient('YOUR_API_KEY', 'YOUR_API_SECRET'); ``` ``` -------------------------------- ### Configure HTTP Agent with Undici Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Provide a custom HTTP agent for request handling, such as for connection pooling or custom TLS configuration. ```typescript import { Agent } from 'undici'; const agent = new Agent({ connections: 100, pipelining: 10, }); const client = new StreamClient(apiKey, secret, { agent, }); ``` -------------------------------- ### StreamCall Methods Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Methods for interacting with video call instances, including creation, retrieval, member querying, and SRT credential generation. ```APIDOC ## StreamCall Represents a video call instance. ### Methods - `getOrCreate()` - Create or retrieve call - `get()` - Retrieve call data - `queryMembers()` - Get call members - `createSRTCredentials()` - Generate SRT streaming credentials ### Properties - `cid` (string) - Fully-qualified call ID (type:id) ``` -------------------------------- ### getOrCreateFollows() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeedsClient.md Create or retrieve follow relationships in batch. ```APIDOC ## getOrCreateFollows() ### Description Create or retrieve follow relationships in batch. ### Method Signature ```typescript getOrCreateFollows(request: FollowBatchRequest): Promise ``` ### Parameters #### Request Body - **request.follows** (Array<{ source: string; target: string; follower_role?: string }>) - Required - Array of follow relationships to create ### Returns Promise resolving to FollowBatchResponse ### Example ```typescript const result = await client.feeds.getOrCreateFollows({ follows: [ { source: 'user:user1', target: 'user:user2' }, { source: 'user:user1', target: 'user:user3' }, ], }); ``` ``` -------------------------------- ### Connection Pooling with Undici Agent Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Utilize Undici Agent for connection reuse to improve performance. Configure the number of connections and pipelining. ```typescript import { Agent } from 'undici'; const agent = new Agent({ connections: 100, pipelining: 10, }); const client = new StreamClient(apiKey, secret, { agent }); ``` -------------------------------- ### queryMembers() Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md Queries call members with optional filtering and pagination. ```APIDOC ## queryMembers() Query call members with optional filtering and pagination. ```typescript queryMembers(request?: OmitTypeId): Promise ``` | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | request.filter_conditions | Record | — | Filter members by conditions | | request.sort | SortParamRequest[] | — | Sort results | | request.limit | number | — | Maximum number of results | | request.offset | number | — | Pagination offset | **Returns:** Promise resolving to QueryCallMembersResponse **Example:** ```typescript const members = await callClient.queryMembers({ filter_conditions: { role: 'user' }, limit: 10, offset: 0, }); members.members.forEach(member => { console.log(member.user.name); }); ``` ``` -------------------------------- ### StreamClientOptions Interface Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Defines the structure for optional StreamClient configuration settings. ```typescript interface StreamClientOptions { timeout?: number; basePath?: string; agent?: unknown; } ``` -------------------------------- ### Check Rate Limits Before Blocking Source: https://github.com/getstream/stream-node/blob/main/_autodocs/errors.md Proactively check rate limit remaining counts in the response metadata and implement backoff strategies when limits are approaching to avoid request blocking. ```typescript if (response.metadata.rateLimit.rateLimitRemaining < 10) { // Implement backoff } ``` -------------------------------- ### ApiConfig Interface Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Defines the configuration structure for the HTTP API client, including API key, token, and base URL. ```typescript interface ApiConfig { apiKey: string; token: string; baseUrl: string; timeout: number; agent?: RequestInit['dispatcher']; secret?: string; } ``` -------------------------------- ### Production with Corporate Proxy Source: https://github.com/getstream/stream-node/blob/main/_autodocs/configuration.md Configure the client to use a corporate proxy for production environments. This is necessary when network policies require traffic to be routed through a proxy. ```typescript import { ProxyAgent } from 'undici'; const proxyAgent = new ProxyAgent( process.env.HTTPS_PROXY || 'http://proxy.corporate.com:3128' ); const client = new StreamClient( process.env.STREAM_API_KEY, process.env.STREAM_API_SECRET, { timeout: 5000, agent: proxyAgent, } ); ``` -------------------------------- ### StreamVideoClient Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Client for managing video calls and integrating with OpenAI. ```APIDOC ## StreamVideoClient ### Description Client for managing video calls and integrating with OpenAI. ### Usage ```javascript import { StreamVideoClient } from '@stream-io/node-sdk'; const videoClient = new StreamVideoClient('YOUR_API_KEY', 'YOUR_API_SECRET'); ``` ``` -------------------------------- ### upsertUsers Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamClient.md Creates or updates multiple user profiles in the Stream system. This is an efficient way to manage user data in bulk. ```APIDOC ## upsertUsers() ### Description Create or update multiple users. ### Method N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### SDK Parameters - **users** (UserRequest[]) - Required - Array of user objects to create or update ### Returns Promise resolving to user response with metadata (StreamResponse) ### Example ```typescript const response = await client.upsertUsers([ { id: 'user1', name: 'Alice' }, { id: 'user2', name: 'Bob' }, ]); ``` ``` -------------------------------- ### Pagination with Pagination Object Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Alternatively, use a pagination object to encapsulate limit and offset for query methods. ```typescript { pagination: { limit: 20, offset: 0, } } ``` -------------------------------- ### Create Follow Relationships in Batch Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeedsClient.md Use `getOrCreateFollows()` to create multiple follow relationships in a single request. Specify an array of follow objects, each with a source and target feed identifier. ```typescript const result = await client.feeds.getOrCreateFollows({ follows: [ { source: 'user:user1', target: 'user:user2' }, { source: 'user:user1', target: 'user:user3' }, ], }); ``` -------------------------------- ### Check Rate Limit Status Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Demonstrates how to check the `rateLimitRemaining` property within the `metadata.rateLimit` object to warn users when they are approaching API rate limits. ```typescript const response = await client.chat.queryChannels(request); if (response.metadata.rateLimit.rateLimitRemaining < 10) { console.warn('Approaching rate limit'); } ``` -------------------------------- ### Fix Linting Errors with ESLint Source: https://github.com/getstream/stream-node/blob/main/AGENTS.md Run ESLint with the auto-fix option to automatically resolve linting issues. ```bash yarn lint:fix ``` -------------------------------- ### RateLimit Source: https://github.com/getstream/stream-node/blob/main/_autodocs/types.md Contains information about the API rate limits, including the total allowed requests, remaining requests in the current window, and the time when the window resets. ```APIDOC ## RateLimit ### Description Provides details about the API rate limiting status, including the total number of requests allowed within a specific time window, the number of requests remaining in the current window, and the timestamp when the rate limit window will reset. ### Properties - **rateLimit** (number) - Optional. The total number of requests allowed per time window. - **rateLimitRemaining** (number) - Optional. The number of requests remaining in the current rate limit window. - **rateLimitReset** (Date) - Optional. The date and time when the current rate limit window resets. ``` -------------------------------- ### Post Activity to Feed Source: https://github.com/getstream/stream-node/blob/main/_autodocs/REFERENCE.md Add a new activity to a user's feed, such as posting an article. This pattern is fundamental for building activity streams. ```typescript async function postActivity(userId, activity) { const feed = client.feeds.feed('timeline', userId); const response = await feed.addActivity({ actor: `user:${userId}`, verb: 'post', object: 'article:123', text: 'User posted an article', ...activity, }); return response.activity; } ``` -------------------------------- ### Monitor Rate Limits Source: https://github.com/getstream/stream-node/blob/main/_autodocs/INDEX.md Check the rateLimitRemaining from response metadata to monitor API rate limits. Implement backoff strategies when limits are low. ```typescript const response = await client.chat.queryChannels(request); const remaining = response.metadata.rateLimit.rateLimitRemaining; if (remaining < 10) { // Implement backoff } ``` -------------------------------- ### Generate User Token Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamClient.md Create a JWT token for user authentication. Specify the user ID and optionally the token's validity period in seconds. ```typescript const token = client.generateUserToken({ user_id: 'user123', validity_in_seconds: 3600, }); ``` -------------------------------- ### StreamModerationClient Constructor Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamModerationClient.md Initializes the StreamModerationClient with an ApiClient instance. ```typescript constructor(apiClient: ApiClient) ``` -------------------------------- ### Create Call (Alias) Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamCall.md The create method is an alias for getOrCreate, providing a shorthand for creating a call if it does not already exist. ```typescript const response = await callClient.create(); ``` -------------------------------- ### Query Activity Feeds Source: https://github.com/getstream/stream-node/blob/main/_autodocs/api-reference/StreamFeedsClient.md Query activity feeds using `queryFeeds()`, allowing filtering by feed group and pagination. The results contain a list of feeds matching the criteria. ```typescript const result = await client.feeds.queryFeeds({ filter: { group: 'user' }, pagination: { limit: 10 }, }); result.results.forEach(feed => { console.log(feed.id); }); ```