/****************************************************************************** * Copyright 2022 TypeFox GmbH * This program and the accompanying materials are made available under the * terms of the MIT License, which is available in the project root. ******************************************************************************/ import type { CancellationToken, Disposable, Message, MessageParticipant, MessengerAPI, NotificationHandler, NotificationMessage, NotificationType, RequestHandler, RequestMessage, RequestType, ResponseError, ResponseMessage } from 'vscode-messenger-common'; import { CancellationTokenImpl, Deferred } from 'vscode-messenger-common'; import type { VsCodeApi } from './vscode-api'; export declare class Messenger implements MessengerAPI { protected readonly handlerRegistry: Map | NotificationHandler>; protected readonly requests: Map>; protected readonly pendingHandlers: Map; protected readonly vscode: VsCodeApi; protected readonly options: MessengerOptions; private started; constructor(vscode?: VsCodeApi, options?: MessengerOptions); /** * Register a request handler. * @param type The request type. * @param handler The request handler. * @returns A Disposable for automatic cleanup. * * @see {@link unregisterHandler} - Manual method to unregister handlers by method name * * @example * ```typescript * // Define message types * const myRequest: RequestType<{ userId: string }, { name: string }> = { method: 'getUser' }; * const myNotification: NotificationType = { method: 'statusUpdate' }; * * // Register handlers and get disposables for cleanup * const requestDisposable = messenger.onRequest(myRequest, handler); * const notificationDisposable = messenger.onNotification(myNotification, notifHandler); * * // Manual unregistration * messenger.unregisterHandler(myRequest.method); * * // Or use the disposable for automatic cleanup * requestDisposable.dispose(); // Clean up when done * ``` */ onRequest(type: RequestType, handler: RequestHandler): Disposable; /** * Register a notification handler. * @param type The notification type. * @param handler The notification handler. * @returns A Disposable for automatic cleanup. * * @see {@link unregisterHandler} - Manual method to unregister handlers by method name * * @example * ```typescript * // Define message types * const myNotification: NotificationType<{ status: string }> = { method: 'statusChanged' }; * const myRequest: RequestType = { method: 'getCount' }; * * // Register handlers and get disposables for cleanup * const notificationDisposable = messenger.onNotification(myNotification, handler); * const requestDisposable = messenger.onRequest(myRequest, reqHandler); * * // Manual unregistration * messenger.unregisterHandler(myNotification.method); * * // Or use the disposable for automatic cleanup * notificationDisposable.dispose(); // Clean up when done * ``` */ onNotification

(type: NotificationType

, handler: NotificationHandler

): Disposable; /** * Start the message processing. */ start(): void; /** * Unregisters a handler by its method name. * @param method The method name of the handler to unregister. Use `.method` for type safety. * @returns True if the handler was successfully unregistered, false otherwise. */ unregisterHandler(method: string): boolean; protected processMessage(msg: Message): Promise; protected processResponseMessage(msg: ResponseMessage): Promise; protected processNotificationMessage(msg: NotificationMessage): Promise; protected processRequestMessage(msg: RequestMessage): Promise; protected createResponseError(error: unknown): ResponseError; /** * Send a request message to another participant and wait for a response. * * @template P The type of the request parameters * @template R The type of the response data * @param type The request type definition containing the method name * @param receiver The target participant to send the request to (extension or specific webview) * @param params Optional parameters to send with the request * @param cancelable Optional cancellation token to cancel the request * @returns A Promise that resolves with the response data or rejects if the request fails * * @throws {Error} If the receiver is a broadcast participant (broadcasts are only allowed for notifications) * * @example * ```typescript * // Define a request type * const GetUserRequest: RequestType<{ userId: string }, { name: string, email: string }> = { * method: 'getUser' * }; * * // Send a request to the host extension * const user = await messenger.sendRequest( * GetUserRequest, * HOST_EXTENSION, * { userId: '123' } * ); * console.log(`User: ${user.name} (${user.email})`); * * // Send a request with cancellation support * const controller = new AbortController(); * const cancelToken = createCancellationToken(controller.signal); * * try { * const result = await messenger.sendRequest( * GetUserRequest, * HOST_EXTENSION, * { userId: '456' }, * cancelToken * ); * } catch (error) { * if (controller.signal.aborted) { * console.log('Request was cancelled'); * } else { * console.error('Request failed:', error); * } * } * * // Cancel the request after 5 seconds * setTimeout(() => controller.abort('Timeout'), 5000); * ``` */ sendRequest(type: RequestType, receiver: MessageParticipant, params?: P, cancelable?: CancellationToken): Promise; /** * Send a notification message to another participant without expecting a response. * * Notifications are fire-and-forget messages that don't require acknowledgment or return values. * Unlike requests, notifications can be sent to broadcast receivers to notify all registered handlers. * * @template P The type of the notification parameters * @param type The notification type definition containing the method name * @param receiver The target participant to send the notification to (extension, webview, or broadcast) * @param params Optional parameters to send with the notification * * @example * ```typescript * // Define a notification type * const UserLoggedInNotification: NotificationType<{ userId: string, timestamp: number }> = { * method: 'userLoggedIn' * }; * * // Send a notification to the host extension * messenger.sendNotification( * UserLoggedInNotification, * HOST_EXTENSION, * { userId: '123', timestamp: Date.now() } * ); * * // Send a notification to a specific webview * messenger.sendNotification( * UserLoggedInNotification, * { type: 'webview', webviewType: 'dashboard' }, * { userId: '123', timestamp: Date.now() } * ); * * // Broadcast a notification to all registered handlers * messenger.sendNotification( * UserLoggedInNotification, * BROADCAST, * { userId: '123', timestamp: Date.now() } * ); * * // Send a simple notification without parameters * const RefreshNotification: NotificationType = { method: 'refresh' }; * messenger.sendNotification(RefreshNotification, HOST_EXTENSION); * ``` */ sendNotification

(type: NotificationType

, receiver: MessageParticipant, params?: P): void; private nextMsgId; protected createMsgId(): string; /** * Log a message to the console. * @param text The message to log. * @param level The log level. Defaults to 'debug'. */ protected log(text: string, level?: 'debug' | 'warn' | 'error'): void; } export interface MessengerOptions { /** Whether to log any debug-level messages to the console. */ debugLog?: boolean; } /** * Create a CancellationToken that is linked to the given signal. * * @param signal An AbortSignal to create a CancellationToken for. * @returns A CancellationToken that is linked to the given signal. */ export declare function createCancellationToken(signal: AbortSignal): CancellationToken; //# sourceMappingURL=messenger.d.ts.map