/** * Chrome Runtime 消息通信封装 * 基于 TypeScript 的类型安全消息系统(Builder 模式) * * @packageDocumentation */ /** * 运行时配置选项 */ export interface RuntimeConfig { /** 是否启用调试日志,默认 true */ debug?: boolean; /** 日志前缀,默认 "[MessageBus]" */ logPrefix?: string; } /** * 消息定义结构 */ export interface MessageDefinition { payload: unknown; response: unknown; } /** * 消息协议表类型 */ export type MessageProtocol = Record; /** * sendToTab 的目标。 * * 裸 tabId 发给该 tab 的所有 frame(由先响应的那个决定结果); * 需要限定 frame 时传描述符,字段与 chrome.tabs.sendMessage 的 options 一致。 * 放在第一个参数而不是尾部,是因为 payload 是变长的, * 尾部 options 会迫使 void payload 的调用写成 `sendToTab(id, type, undefined, opts)`。 */ export type TabTarget = number | { tabId: number; frameId?: number; documentId?: string; }; /** * 可选 payload 参数类型 * 当 payload 为 void 或 undefined 时,无需传参 */ export type OptionalPayload

= P extends void | undefined ? [] : [P]; /** * 错误响应结构 */ export interface ErrorResponse { __error: true; message: string; } /** * 类型守卫:检查响应是否为错误响应 */ export declare function isErrorResponse(response: unknown): response is ErrorResponse; /** * 消息处理器类型 */ export type MessageHandler = (payload: P, sender: chrome.runtime.MessageSender) => R | Promise; /** * 消息总线接口 */ export interface MessageBus { /** * 发送消息到 background */ send(type: K, ...payload: OptionalPayload): Promise; /** * 发送消息到指定 Tab * * @param target - 裸 tabId,或 `{ tabId, frameId?, documentId? }` 限定到某个 frame * * @example * ```ts * bus.sendToTab(tabId, "tab/highlight", { selector: ".card" }); * bus.sendToTab({ tabId, frameId: 0 }, "system/ping"); // 只问顶层 frame * ``` */ sendToTab(target: TabTarget, type: K, ...payload: OptionalPayload): Promise; /** * 监听消息 */ on(type: K, handler: MessageHandler): () => void; /** * 批量注册监听器 */ onMany(handlers: Partial<{ [P in K]: MessageHandler; }>): () => void; /** * 检查是否已注册处理器 */ hasHandler(type: keyof T): boolean; /** * 获取已注册的消息类型 */ getRegisteredTypes(): (keyof T)[]; /** * 清除所有处理器 */ clearAllHandlers(): void; } /** * 创建类型安全的消息总线 * * @param config - 可选配置 * @returns 类型化的消息总线实例 * * @example * ```ts * // 1. 定义消息类型 * type MyMessages = { * "user/login": { * payload: { username: string; password: string }; * response: { token: string }; * }; * "user/logout": { * payload: void; * response: void; * }; * }; * * // 2. 创建消息总线 * const bus = createMessageBus(); * * // 3. 发送消息(content script) * const result = await bus.send("user/login", { * username: "admin", * password: "123456" * }); * console.log(result.token); // 类型安全! * * // 4. 监听消息(background) * bus.on("user/login", async ({ username, password }) => { * const user = await authenticate(username, password); * return { token: user.token }; * }); * ``` */ export declare function createMessageBus(config?: RuntimeConfig): MessageBus;