### Install @adonisjs/transmit-client Source: https://context7.com/adonisjs/transmit-client/llms.txt Installs the @adonisjs/transmit-client package using npm. This is the first step to using the library in your project. ```bash npm i @adonisjs/transmit-client ``` -------------------------------- ### Complete Real-Time Chat Example with Transmit Client Source: https://context7.com/adonisjs/transmit-client/llms.txt Demonstrates a full integration pattern for a real-time chat application using the Transmit client. Includes managing multiple subscriptions, handling connection events, and proper cleanup. ```typescript import { Transmit } from '@adonisjs/transmit-client' interface ChatMessage { user: string text: string timestamp: number } interface NotificationPayload { type: 'mention' | 'dm' | 'system' message: string } // Initialize transmit client with full configuration const transmit = new Transmit({ baseUrl: 'http://localhost:3333', maxReconnectAttempts: 10, onReconnectAttempt: (attempt) => { console.log(`Reconnecting... attempt ${attempt}/10`) }, onReconnectFailed: () => { alert('Connection lost. Please refresh the page.') }, onSubscription: (channel) => { console.log(`Joined channel: ${channel}`) }, }) // Wait for connection before subscribing transmit.on('connected', async () => { // Subscribe to a chat room const roomSubscription = transmit.subscription('chat/room-general') await roomSubscription.create() roomSubscription.onMessage((message) => { console.log(`[${message.user}]: ${message.text}`) // Output: [Alice]: Hello everyone! }) // Subscribe to user-specific notifications const userId = 'user-123' const notificationSubscription = transmit.subscription(`notifications/${userId}`) await notificationSubscription.create() notificationSubscription.onMessage((notification) => { if (notification.type === 'mention') { console.log('You were mentioned:', notification.message) } }) // Subscribe to presence updates const presenceSubscription = transmit.subscription('presence/room-general') await presenceSubscription.create() presenceSubscription.onMessage((users: string[]) => { console.log('Online users:', users.join(', ')) // Output: Online users: Alice, Bob, Charlie }) }) // Handle disconnection transmit.on('disconnected', () => { console.log('Connection lost, waiting for reconnection...') }) // Cleanup on page unload window.addEventListener('beforeunload', () => { transmit.close() }) ``` -------------------------------- ### Custom EventSource Factory for Transmit Client Authentication Source: https://context7.com/adonisjs/transmit-client/llms.txt Enables header-based authentication for Server-Sent Events by providing a custom `eventSourceFactory`. This example uses `@microsoft/fetch-event-source` to include custom headers like Authorization. ```typescript import { Transmit } from '@adonisjs/transmit-client' import { fetchEventSource } from '@microsoft/fetch-event-source' function createFetchEventSource( url: string | URL, options: { withCredentials: boolean }, headers: Record ) { const controller = new AbortController() const listeners = new Map void>>() const dispatch = (type: string, data?: string) => { const event = new MessageEvent(type, { data }) listeners.get(type)?.forEach((listener) => listener(event)) } fetchEventSource(url.toString(), { headers, credentials: options.withCredentials ? 'include' : 'omit', signal: controller.signal, onopen: () => dispatch('open'), onmessage: (message) => dispatch(message.event ?? 'message', message.data), onerror: () => dispatch('error'), }) return { addEventListener(type: string, listener: (event: MessageEvent) => void) { if (!listeners.has(type)) listeners.set(type, new Set()) listeners.get(type)!.add(listener) }, removeEventListener(type: string, listener: (event: MessageEvent) => void) { listeners.get(type)?.delete(listener) }, close() { controller.abort() }, } as EventSource } const token = 'your-jwt-token' const transmit = new Transmit({ baseUrl: 'http://localhost:3333', eventSourceFactory: (url, options) => { return createFetchEventSource(url, options, { Authorization: `Bearer ${token}`, }) }, }) ``` -------------------------------- ### Initialize Transmit Client (TypeScript) Source: https://context7.com/adonisjs/transmit-client/llms.txt Demonstrates how to create an instance of the Transmit client. It shows basic initialization with a base URL and a more comprehensive configuration including reconnection attempts and various event hooks. ```typescript import { Transmit } from '@adonisjs/transmit-client' // Basic initialization const transmit = new Transmit({ baseUrl: 'http://localhost:3333', }) // Full configuration with all options const transmitFull = new Transmit({ baseUrl: 'http://localhost:3333', maxReconnectAttempts: 5, beforeSubscribe: (request: Request) => { console.log('Subscribing to channel...') }, beforeUnsubscribe: (request: Request) => { console.log('Unsubscribing from channel...') }, onReconnectAttempt: (attempt: number) => { console.log(`Reconnection attempt ${attempt}`) }, onReconnectFailed: () => { console.log('All reconnection attempts failed') }, onSubscribeFailed: (response: Response) => { console.error('Subscription failed:', response.status) }, onSubscription: (channel: string) => { console.log(`Successfully subscribed to ${channel}`) }, onUnsubscription: (channel: string) => { console.log(`Unsubscribed from ${channel}`) }, }) // Access the unique client identifier console.log('Client UID:', transmit.uid) ``` -------------------------------- ### Create and Manage Subscriptions Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Demonstrates how to create a subscription to a specific channel, register it with the server, and listen for incoming messages. It also covers unsubscribing from message handlers and the entire subscription. ```typescript const subscription = transmit.subscription('chat/1') await subscription.create() subscription.onMessage((message) => { console.log(message) }) const unsubscribe = subscription.onMessage(() => { console.log('message received!') }) // later unsubscribe() await subscription.delete() ``` -------------------------------- ### Initialize Transmit Client Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Initialize the Transmit client by creating a new instance of the Transmit class. Provide the base URL of the server to connect to. This sets up the connection to the SSE endpoint. ```typescript import { Transmit } from '@adonisjs/transmit-client' const transmit = new Transmit({ baseUrl: 'http://localhost:3333', }) ``` -------------------------------- ### Manage Transmit Subscriptions (TypeScript) Source: https://context7.com/adonisjs/transmit-client/llms.txt Shows how to create, manage, and delete subscriptions to specific channels using the Transmit client. It covers listening for messages, listening for a single message, and handling subscription lifecycle events. ```typescript import { Transmit } from '@adonisjs/transmit-client' const transmit = new Transmit({ baseUrl: 'http://localhost:3333', }) // Create a subscription to a channel const chatSubscription = transmit.subscription('chat/room-1') // Register the subscription on the server await chatSubscription.create() // Listen for messages on the channel const unsubscribe = chatSubscription.onMessage((message) => { console.log('Received message:', message) // Output: Received message: { user: 'John', text: 'Hello!' } }) // Listen for a single message only chatSubscription.onMessageOnce((message) => { console.log('First message received:', message) }) // Remove the message handler unsubscribe() // Delete the subscription from the server await chatSubscription.delete() // Check subscription status console.log('Is created:', chatSubscription.isCreated) // false after delete console.log('Is deleted:', chatSubscription.isDeleted) // true console.log('Handler count:', chatSubscription.handlerCount) // 0 ``` -------------------------------- ### Authenticated Event Stream Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Demonstrates how to establish an authenticated event stream using a custom `eventSourceFactory` to include authorization headers. ```APIDOC ## Authenticated Event Stream ### Description The `__transmit/events` stream can be secured by providing a custom `eventSourceFactory` that includes necessary authentication headers. This example uses `@microsoft/fetch-event-source` to create such a factory. ### Method POST (Implicitly via EventSource) ### Endpoint `/__transmit/events` (or similar, depending on server configuration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (Connection is established via EventSource) ### Request Example ```typescript import { fetchEventSource } from '@microsoft/fetch-event-source'; function createFetchEventSource( url: string | URL, options: { withCredentials: boolean }, headers: Record ) { const controller = new AbortController(); const listeners = new Map void>>(); const dispatch = (type: string, data?: string) => { const event = new MessageEvent(type, { data }); listeners.get(type)?.forEach((listener) => listener(event)); }; fetchEventSource(url.toString(), { headers, credentials: options.withCredentials ? 'include' : 'omit', signal: controller.signal, onopen: () => dispatch('open'), onmessage: (message) => dispatch(message.event ?? 'message', message.data), onerror: () => { dispatch('error'); }, }); return { addEventListener(type: string, listener: (event: MessageEvent) => void) { if (!listeners.has(type)) { listeners.set(type, new Set()); } listeners.get(type)!.add(listener); }, removeEventListener(type: string, listener: (event: MessageEvent) => void) { listeners.get(type)?.delete(listener); }, close() { controller.abort(); }, } as EventSource; } const token = 'YOUR_AUTH_TOKEN'; // Replace with your actual token const transmit = new Transmit({ baseUrl: 'http://localhost:3333', eventSourceFactory: (url, options) => { return createFetchEventSource(url, options, { Authorization: `Bearer ${token}`, }); }, }); ``` ### Response #### Success Response (200) An `EventSource` object is returned, which emits `open`, `message`, and `error` events. #### Response Example (EventSource stream events, not a direct JSON response) ``` -------------------------------- ### Customize Subscription Requests Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Illustrates how to intercept and modify subscription and unsubscription requests using the `beforeSubscribe` and `beforeUnsubscribe` options during Transmit client initialization. This allows for adding custom headers or logic before requests are sent. ```typescript const transmit = new Transmit({ baseUrl: 'http://localhost:3333', beforeSubscribe: (_request: Request) => { console.log('beforeSubscribe') }, beforeUnsubscribe: (_request: Request) => { console.log('beforeUnsubscribe') }, }) ``` -------------------------------- ### Reconnecting Configuration Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Details how to configure automatic reconnection attempts and hook into the reconnection lifecycle events. ```APIDOC ## Reconnecting Configuration ### Description Transmit client automatically attempts to reconnect when the connection is lost. This section explains how to customize the number of retries and handle reconnection events. ### Method N/A (Configuration option) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const transmit = new Transmit({ baseUrl: 'http://localhost:3333', maxReconnectionAttempts: 5, // Set the maximum number of reconnection attempts onReconnectAttempt: (attempt) => { // Callback for each reconnection attempt console.log('Reconnect attempt ' + attempt); }, onReconnectFailed: () => { // Callback when all reconnection attempts fail console.log('Reconnect failed'); }, }); ``` ### Response N/A (This is a client-side configuration) ``` -------------------------------- ### Listen for Message Once Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Shows how to use the `onMessageOnce` method to listen for a single message on a subscription. This listener will be automatically removed after the first message is received. ```typescript subscription.onMessageOnce((message) => { console.log('I will be called only once') }) ``` -------------------------------- ### Event Handling Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Explains how to subscribe to and unsubscribe from events emitted by the Transmit client, such as 'connected', 'disconnected', and 'reconnecting'. ```APIDOC ## Event Handling ### Description The `Transmit` class implements the `EventTarget` interface, allowing you to listen for various connection-related events. ### Method `on(eventName, listener)`: Registers an event listener. `off(eventName, listener)`: Removes an event listener. ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example **Registering listeners:** ```typescript transmit.on('connected', () => { console.log('connected'); }); transmit.on('disconnected', () => { console.log('disconnected'); }); transmit.on('reconnecting', () => { console.log('reconnecting'); }); ``` **Removing a listener:** ```typescript const onConnected = () => { console.log('connected'); }; transmit.on('connected', onConnected); transmit.off('connected', onConnected); // Removes the specific listener ``` ### Response N/A (Event listeners are callbacks) ``` -------------------------------- ### Event Handling with Transmit Client Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Illustrates how to use the `EventTarget` interface of the Transmit client to manage connection events. It shows how to register listeners for 'connected', 'disconnected', and 'reconnecting' events, and how to remove them using `off`. ```typescript transmit.on('connected', () => { console.log('connected') }) transmit.on('disconnected', () => { console.log('disconnected') }) transmit.on('reconnecting', () => { console.log('reconnecting') }) ``` ```typescript const onConnected = () => { console.log('connected') } transmit.on('connected', onConnected) transmit.off('connected', onConnected) ``` -------------------------------- ### Listen to Connection Events (TypeScript) Source: https://context7.com/adonisjs/transmit-client/llms.txt Explains how to listen for connection state changes emitted by the Transmit client using the EventTarget API. It covers listening for 'connected', 'disconnected', and 'reconnecting' events, as well as manually closing the connection. ```typescript import { Transmit } from '@adonisjs/transmit-client' const transmit = new Transmit({ baseUrl: 'http://localhost:3333', }) // Add event listeners for connection state changes transmit.on('connected', () => { console.log('Connected to SSE stream') // Safe to create subscriptions now }) transmit.on('disconnected', () => { console.log('Disconnected from SSE stream') // Connection lost, reconnection will be attempted }) transmit.on('reconnecting', () => { console.log('Attempting to reconnect...') }) // Remove an event listener const onConnected = () => { console.log('Custom connected handler') } transmit.on('connected', onConnected) transmit.off('connected', onConnected) // Close the connection manually transmit.close() ``` -------------------------------- ### Configuring Reconnection Logic in Transmit Client Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Details how to configure the automatic reconnection behavior of the Transmit client. It shows how to set the maximum number of reconnection attempts and how to hook into the reconnection lifecycle using `onReconnectAttempt` and `onReconnectFailed`. ```typescript const transmit = new Transmit({ baseUrl: 'http://localhost:3333', maxReconnectionAttempts: 5, onReconnectAttempt: (attempt) => { console.log('Reconnect attempt ' + attempt) }, onReconnectFailed: () => { console.log('Reconnect failed') }, }) ``` -------------------------------- ### Custom UID Generator for Transmit Client Source: https://context7.com/adonisjs/transmit-client/llms.txt Allows providing a custom UID generator for the Transmit client, essential for environments where crypto.randomUUID() is not available (e.g., HTTP). Supports both custom hex generators and libraries like 'uuid'. ```typescript import { Transmit } from '@adonisjs/transmit-client' import { v4 as uuid } from 'uuid' // Using a custom random hex generator const transmit = new Transmit({ baseUrl: 'http://localhost:3333', uidGenerator: () => { return Array.from({ length: 16 }, () => Math.floor(Math.random() * 256).toString(16).padStart(2, '0') ).join('') }, }) // Using the uuid library const transmitWithUuid = new Transmit({ baseUrl: 'http://localhost:3333', uidGenerator: () => uuid(), }) console.log('Generated UID:', transmit.uid) ``` -------------------------------- ### Custom UID Generator Source: https://github.com/adonisjs/transmit-client/blob/develop/README.md Configures a custom function to generate unique client identifiers, necessary when Transmit is used over HTTP. ```APIDOC ## Custom UID Generator ### Description By default, Transmit uses `crypto.randomUUID()` for client identifiers, which requires a secure context (HTTPS). This section shows how to provide a custom `uidGenerator` for use over HTTP. ### Method N/A (Configuration option) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example **Using `Math.random`:** ```typescript const transmit = new Transmit({ baseUrl: 'http://localhost:3333', uidGenerator: () => { return Array.from({ length: 16 }, () => Math.floor(Math.random() * 256).toString(16).padStart(2, '0') ).join(''); }, }); ``` **Using `uuid` library:** ```typescript import { v4 as uuid } from 'uuid'; const transmit = new Transmit({ baseUrl: 'http://localhost:3333', uidGenerator: () => uuid(), }); ``` ### Response N/A (This is a client-side configuration) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.