feat: add SnowLuma TypeScript SDK

This commit is contained in:
DrSmoothl committed 2026-05-10 01:26:35 +08:00
1 parent 9ab4128799
commit c343021318
43 files changed
+4157 -2

No files matched your search

+470
View File
@@ -0,0 +1,470 @@
import { createSnowLumaApiError } from '../errors';
import { normalizeMessage } from '../messages/index';
import type {
ActionParams,
ActionResult,
ApiResponse,
DomainParams,
DownloadFileParams,
ForwardMessageParams,
GetForwardMsgParams,
GetFriendMessageHistoryParams,
GetGroupHonorInfoParams,
GetGroupMessageHistoryParams,
GetMediaParams,
JsonObject,
JsonValue,
OutgoingMessage,
PrivateForwardMessageParams,
RequestOptions,
SendMsgParams,
SetGroupReactionParams,
SnowLumaAction,
} from '../types/index';
/**
* Base class for SnowLuma API clients.
*
* Concrete transports implement request(); this facade adds typed OneBot actions,
* message normalization, and failed-response error handling.
*/
export abstract class SnowLumaApiClient {
/** Sends a raw OneBot action and returns the complete API response. */
abstract request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>>;
/** Sends a OneBot action and returns data, throwing SnowLumaApiError on failed responses. */
async call<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ActionResult<TAction>> {
const response = await this.request(action, params, options);
if (response.status !== 'ok' || response.retcode !== 0) {
throw createSnowLumaApiError(response);
}
return response.data;
}
getLoginInfo(options?: RequestOptions) {
return this.call('get_login_info', {}, options);
}
getStatus(options?: RequestOptions) {
return this.call('get_status', {}, options);
}
getVersionInfo(options?: RequestOptions) {
return this.call('get_version_info', {}, options);
}
canSendImage(options?: RequestOptions) {
return this.call('can_send_image', {}, options);
}
canSendRecord(options?: RequestOptions) {
return this.call('can_send_record', {}, options);
}
sendMsg(params: Omit<SendMsgParams, 'message'> & { message: OutgoingMessage }, options?: RequestOptions) {
return this.call('send_msg', { ...params, message: normalizeMessage(params.message) as JsonValue }, options);
}
sendPrivateMessage(userId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }) {
return this.call('send_private_msg', {
user_id: userId,
message: normalizeMessage(message) as JsonValue,
auto_escape: options?.autoEscape,
}, options);
}
sendGroupMessage(groupId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }) {
return this.call('send_group_msg', {
group_id: groupId,
message: normalizeMessage(message) as JsonValue,
auto_escape: options?.autoEscape,
}, options);
}
getMessage(messageId: number, options?: RequestOptions) {
return this.call('get_msg', { message_id: messageId }, options);
}
deleteMessage(messageId: number, options?: RequestOptions) {
return this.call('delete_msg', { message_id: messageId }, options);
}
getFriendList(options?: RequestOptions) {
return this.call('get_friend_list', {}, options);
}
getStrangerInfo(userId: number, options?: RequestOptions) {
return this.call('get_stranger_info', { user_id: userId }, options);
}
deleteFriend(userId: number, options?: RequestOptions & { block?: boolean }) {
return this.call('delete_friend', { user_id: userId, block: options?.block }, options);
}
getGroupList(options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_list', { no_cache: options?.noCache }, options);
}
getGroupInfo(groupId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_info', { group_id: groupId, no_cache: options?.noCache }, options);
}
getGroupMemberList(groupId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_member_list', { group_id: groupId, no_cache: options?.noCache }, options);
}
getGroupMemberInfo(groupId: number, userId: number, options?: RequestOptions & { noCache?: boolean }) {
return this.call('get_group_member_info', {
group_id: groupId,
user_id: userId,
no_cache: options?.noCache,
}, options);
}
getGroupHonorInfo(params: GetGroupHonorInfoParams, options?: RequestOptions) {
return this.call('get_group_honor_info', params, options);
}
getGroupSystemMessages(options?: RequestOptions) {
return this.call('get_group_system_msg', {}, options);
}
setGroupKick(groupId: number, userId: number, options?: RequestOptions & { rejectAddRequest?: boolean }) {
return this.call('set_group_kick', {
group_id: groupId,
user_id: userId,
reject_add_request: options?.rejectAddRequest,
}, options);
}
setGroupBan(groupId: number, userId: number, duration?: number, options?: RequestOptions) {
return this.call('set_group_ban', { group_id: groupId, user_id: userId, duration }, options);
}
setGroupWholeBan(groupId: number, enable = true, options?: RequestOptions) {
return this.call('set_group_whole_ban', { group_id: groupId, enable }, options);
}
setGroupAdmin(groupId: number, userId: number, enable = true, options?: RequestOptions) {
return this.call('set_group_admin', { group_id: groupId, user_id: userId, enable }, options);
}
setGroupCard(groupId: number, userId: number, card = '', options?: RequestOptions) {
return this.call('set_group_card', { group_id: groupId, user_id: userId, card }, options);
}
setGroupName(groupId: number, name: string, options?: RequestOptions) {
return this.call('set_group_name', { group_id: groupId, group_name: name }, options);
}
setGroupLeave(groupId: number, options?: RequestOptions) {
return this.call('set_group_leave', { group_id: groupId }, options);
}
setGroupSpecialTitle(groupId: number, userId: number, title = '', options?: RequestOptions) {
return this.call('set_group_special_title', {
group_id: groupId,
user_id: userId,
special_title: title,
}, options);
}
uploadGroupFile(groupId: number, file: string, options: RequestOptions & {
name?: string;
folder?: string;
folderId?: string;
uploadFile?: boolean;
} = {}) {
return this.call('upload_group_file', {
group_id: groupId,
file,
name: options.name,
folder: options.folder,
folder_id: options.folderId,
upload_file: options.uploadFile,
}, options);
}
uploadPrivateFile(userId: number, file: string, options: RequestOptions & {
name?: string;
uploadFile?: boolean;
} = {}) {
return this.call('upload_private_file', {
user_id: userId,
file,
name: options.name,
upload_file: options.uploadFile,
}, options);
}
getGroupFileUrl(groupId: number, fileId: string, options?: RequestOptions & { busid?: number }) {
return this.call('get_group_file_url', { group_id: groupId, file_id: fileId, busid: options?.busid }, options);
}
getGroupRootFiles(groupId: number, options?: RequestOptions) {
return this.call('get_group_root_files', { group_id: groupId }, options);
}
getGroupFilesByFolder(groupId: number, folderId = '/', options?: RequestOptions) {
return this.call('get_group_files_by_folder', { group_id: groupId, folder_id: folderId }, options);
}
deleteGroupFile(groupId: number, fileId: string, options?: RequestOptions) {
return this.call('delete_group_file', { group_id: groupId, file_id: fileId }, options);
}
moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string, options?: RequestOptions) {
return this.call('move_group_file', {
group_id: groupId,
file_id: fileId,
parent_directory: parentDirectory,
target_directory: targetDirectory,
}, options);
}
createGroupFileFolder(groupId: number, name: string, parentId = '/', options?: RequestOptions) {
return this.call('create_group_file_folder', { group_id: groupId, name, parent_id: parentId }, options);
}
deleteGroupFileFolder(groupId: number, folderId: string, options?: RequestOptions) {
return this.call('delete_group_file_folder', { group_id: groupId, folder_id: folderId }, options);
}
renameGroupFileFolder(groupId: number, folderId: string, newName: string, options?: RequestOptions) {
return this.call('rename_group_file_folder', {
group_id: groupId,
folder_id: folderId,
new_folder_name: newName,
}, options);
}
getPrivateFileUrl(userId: number, fileId: string, fileHash: string, options?: RequestOptions) {
return this.call('get_private_file_url', { user_id: userId, file_id: fileId, file_hash: fileHash }, options);
}
setFriendAddRequest(flag: string, approve = true, options?: RequestOptions) {
return this.call('set_friend_add_request', { flag, approve }, options);
}
setGroupAddRequest(flag: string, params: RequestOptions & {
subType?: string;
type?: string;
approve?: boolean;
reason?: string;
} = {}) {
return this.call('set_group_add_request', {
flag,
sub_type: params.subType,
type: params.type,
approve: params.approve,
reason: params.reason,
}, params);
}
sendLike(userId: number, times = 1, options?: RequestOptions) {
return this.call('send_like', { user_id: userId, times }, options);
}
friendPoke(userId: number, options?: RequestOptions & { targetId?: number }) {
return this.call('friend_poke', { user_id: userId, target_id: options?.targetId }, options);
}
groupPoke(groupId: number, userId: number, options?: RequestOptions) {
return this.call('group_poke', { group_id: groupId, user_id: userId }, options);
}
sendPoke(userId: number, options?: RequestOptions & { groupId?: number }) {
return this.call('send_poke', { user_id: userId, group_id: options?.groupId }, options);
}
setEssenceMessage(messageId: number, options?: RequestOptions) {
return this.call('set_essence_msg', { message_id: messageId }, options);
}
deleteEssenceMessage(messageId: number, options?: RequestOptions) {
return this.call('delete_essence_msg', { message_id: messageId }, options);
}
getEssenceMessageList(groupId: number, options?: RequestOptions) {
return this.call('get_essence_msg_list', { group_id: groupId }, options);
}
setGroupReaction(params: SetGroupReactionParams, options?: RequestOptions) {
return this.call('set_group_reaction', params, options);
}
getGroupMessageHistory(params: GetGroupMessageHistoryParams, options?: RequestOptions) {
return this.call('get_group_msg_history', params, options);
}
getFriendMessageHistory(params: GetFriendMessageHistoryParams, options?: RequestOptions) {
return this.call('get_friend_msg_history', params, options);
}
markGroupMessageAsRead(messageId: number, groupId?: number, options?: RequestOptions) {
return this.call('mark_group_msg_as_read', { message_id: messageId, group_id: groupId }, options);
}
markPrivateMessageAsRead(messageId: number, userId?: number, options?: RequestOptions) {
return this.call('mark_private_msg_as_read', { message_id: messageId, user_id: userId }, options);
}
markMessageAsRead(messageId: number, targetId?: number, options?: RequestOptions) {
return this.call('mark_msg_as_read', { message_id: messageId, target_id: targetId }, options);
}
getRKey(options?: RequestOptions) {
return this.call('get_rkey', {}, options);
}
sendGroupNotice(groupId: number, content: string, options: RequestOptions & {
image?: string;
pinned?: number;
type?: number;
confirmRequired?: number;
} = {}) {
return this.call('_send_group_notice', {
group_id: groupId,
content,
image: options.image,
pinned: options.pinned,
type: options.type,
confirm_required: options.confirmRequired,
}, options);
}
getGroupNotice(groupId: number, options?: RequestOptions) {
return this.call('_get_group_notice', { group_id: groupId }, options);
}
uploadForwardMessage(params: ForwardMessageParams, options?: RequestOptions) {
return this.call('upload_forward_msg', params, options);
}
sendForwardMessage(params: ForwardMessageParams, options?: RequestOptions) {
return this.call('send_forward_msg', params, options);
}
sendGroupForwardMessage(groupId: number, messages: OutgoingMessage, options?: RequestOptions) {
return this.call('send_group_forward_msg', {
group_id: groupId,
messages: normalizeMessage(messages) as JsonValue,
}, options);
}
sendPrivateForwardMessage(userId: number, messages: OutgoingMessage, options?: RequestOptions) {
return this.call('send_private_forward_msg', {
user_id: userId,
messages: normalizeMessage(messages) as JsonValue,
}, options);
}
getForwardMessage(params: GetForwardMsgParams, options?: RequestOptions) {
return this.call('get_forward_msg', params, options);
}
getImage(params: GetMediaParams, options?: RequestOptions) {
return this.call('get_image', params, options);
}
getRecord(params: GetMediaParams, options?: RequestOptions) {
return this.call('get_record', params, options);
}
getCookies(params: DomainParams = {}, options?: RequestOptions) {
return this.call('get_cookies', params, options);
}
getCsrfToken(options?: RequestOptions) {
return this.call('get_csrf_token', {}, options);
}
getCredentials(params: DomainParams = {}, options?: RequestOptions) {
return this.call('get_credentials', params, options);
}
cleanCache(options?: RequestOptions) {
return this.call('clean_cache', {}, options);
}
setFriendRemark(userId: number, remark: string, options?: RequestOptions) {
return this.call('set_friend_remark', { user_id: userId, remark }, options);
}
setMsgEmojiLike(messageId: number, emojiId: string, set = true, options?: RequestOptions) {
return this.call('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId, set }, options);
}
markAllAsRead(options?: RequestOptions) {
return this.call('_mark_all_as_read', {}, options);
}
getGroupFileSystemInfo(groupId: number, options?: RequestOptions) {
return this.call('get_group_file_system_info', { group_id: groupId }, options);
}
checkUrlSafely(options?: RequestOptions) {
return this.call('check_url_safely', {}, options);
}
downloadFile(params: DownloadFileParams, options?: RequestOptions) {
return this.call('download_file', params, options);
}
setQqProfile(params: { nickname?: string; personalNote?: string }, options?: RequestOptions) {
return this.call('set_qq_profile', {
nickname: params.nickname,
personal_note: params.personalNote,
}, options);
}
setOnlineStatus(status: number, params: RequestOptions & { extStatus?: number; batteryStatus?: number } = {}) {
return this.call('set_online_status', {
status,
ext_status: params.extStatus,
battery_status: params.batteryStatus,
}, params);
}
getClientKey(options?: RequestOptions) {
return this.call('get_clientkey', {}, options);
}
getGroupInfoEx(groupId: number, options?: RequestOptions) {
return this.call('get_group_info_ex', { group_id: groupId }, options);
}
getGroupDetailInfo(groupId: number, options?: RequestOptions) {
return this.call('get_group_detail_info', { group_id: groupId }, options);
}
/** Calls any registered SnowLuma action and returns the response data. */
raw<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
) {
return this.call(action, params, options);
}
/** Calls any registered SnowLuma action and preserves the full OneBot response envelope. */
rawResponse<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
) {
return this.request(action, params, options);
}
}
export function toJsonObject(value: JsonObject | undefined): JsonObject {
return value ?? {};
}
+115
View File
@@ -0,0 +1,115 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
} from '../errors';
import { SnowLumaApiClient, toJsonObject } from './api-client';
import { createRequestAbortState, isAbortError } from '../internal/abort';
import { assertApiResponse } from '../internal/json';
import type {
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
RequestOptions,
SnowLumaAction,
SnowLumaClientOptions,
} from '../types/index';
/** Options for the HTTP transport client. */
export interface SnowLumaHttpClientOptions extends SnowLumaClientOptions {
/** OneBot HTTP endpoint. Defaults to http://127.0.0.1:3000/. */
baseUrl?: string;
/** Custom fetch implementation for tests or non-standard runtimes. */
fetch?: typeof fetch;
/** Extra headers sent with every request. Authorization is managed by accessToken. */
headers?: Record<string, string>;
}
/** OneBot HTTP client for SnowLuma. */
export class SnowLumaHttpClient extends SnowLumaApiClient {
readonly baseUrl: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
private readonly fetchImpl: typeof fetch;
private readonly headers: Record<string, string>;
constructor(options: SnowLumaHttpClientOptions = {}) {
super();
this.baseUrl = options.baseUrl ?? 'http://127.0.0.1:3000/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.fetchImpl = options.fetch ?? globalThis.fetch;
this.headers = options.headers ?? {};
if (!this.fetchImpl) {
throw new SnowLumaConnectionError('No fetch implementation is available');
}
}
/** Sends one OneBot action over HTTP and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const abort = createRequestAbortState(timeoutMs, options?.signal);
try {
const response = await this.fetchImpl(this.baseUrl, {
method: 'POST',
headers: this.createHeaders(),
body: JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo: options?.echo,
}),
signal: abort.signal,
});
const text = await response.text();
let parsed: unknown;
try {
parsed = text ? JSON.parse(text) : null;
} catch (error) {
throw new SnowLumaParseError(`SnowLuma returned non-JSON HTTP ${response.status}`, { cause: error });
}
const apiResponse = assertApiResponse(parsed) as ApiResponse<ActionResult<TAction>>;
return apiResponse;
} catch (error) {
if (error instanceof SnowLumaTransportError) throw error;
if (isAbortError(error) || abort.signal.aborted) {
if (abort.isTimedOut()) {
throw new SnowLumaTimeoutError(`SnowLuma request timed out after ${timeoutMs}ms`, timeoutMs, { cause: error });
}
if (abort.isExternallyAborted()) {
throw new SnowLumaAbortError('SnowLuma request aborted', { cause: error });
}
}
throw new SnowLumaConnectionError('SnowLuma HTTP request failed', { cause: error });
} finally {
abort.cleanup();
}
}
private createHeaders(): Record<string, string> {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
Accept: 'application/json',
...this.headers,
};
if (this.accessToken) {
headers.Authorization = `Bearer ${this.accessToken}`;
}
return headers;
}
}
export function createHttpClient(options?: SnowLumaHttpClientOptions): SnowLumaHttpClient {
return new SnowLumaHttpClient(options);
}
+12
View File
@@ -0,0 +1,12 @@
export { SnowLumaApiClient } from './api-client';
export { SnowLumaHttpClient, createHttpClient } from './http-client';
export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-client';
export type { SnowLumaHttpClientOptions } from './http-client';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-client';
+421
View File
@@ -0,0 +1,421 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
} from '../errors';
import { Emitter } from '../emitter';
import {
createEventContext,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType,
type CommandHandler,
type CommandOptions,
type EventHandler,
type EventMiddleware,
type EventPredicate,
} from '../events/index';
import { SnowLumaApiClient, toJsonObject } from './api-client';
import { raceWithAbort, throwIfAborted } from '../internal/abort';
import { appendAccessToken, assertApiResponse, createEcho, echoKey, isJsonObject } from '../internal/json';
import {
addSocketListener,
closeInfo,
normalizeReconnect,
rawToString,
unwrapEventPayload,
unwrapMessagePayload,
WEBSOCKET_CLOSED,
WEBSOCKET_OPEN,
} from './websocket-utils';
import type {
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
JsonValue,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotRequestEvent,
RequestOptions,
SnowLumaAction,
SnowLumaEvent,
WsRole,
} from '../types/index';
import type {
PendingRequest,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketConstructor,
WebSocketLike,
} from './websocket-types';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-types';
/** OneBot WebSocket client for SnowLuma APIs and realtime events. */
export class SnowLumaWebSocketClient extends SnowLumaApiClient {
readonly url: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
readonly role: WsRole;
private readonly protocols?: string | string[];
private readonly WebSocketCtor: WebSocketConstructor;
private readonly reconnect: ReconnectOptions | null;
private readonly emitter = new Emitter<SnowLumaWebSocketEvents>();
private readonly pending = new Map<string, PendingRequest>();
private readonly middlewares: EventMiddleware[] = [];
private socket: WebSocketLike | null = null;
private connectPromise: Promise<void> | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectAttempts = 0;
private closedByUser = false;
constructor(options: SnowLumaWebSocketClientOptions = {}) {
super();
this.url = options.url ?? 'ws://127.0.0.1:3001/';
this.accessToken = options.accessToken;
this.requestTimeoutMs = options.requestTimeoutMs ?? 30_000;
this.role = options.role ?? 'Universal';
this.protocols = options.protocols;
this.WebSocketCtor = options.webSocket ?? globalThis.WebSocket as unknown as WebSocketConstructor;
this.reconnect = normalizeReconnect(options.reconnect);
if (!this.WebSocketCtor) {
throw new SnowLumaConnectionError('No WebSocket implementation is available');
}
}
/** True when the underlying WebSocket is currently open. */
get isConnected(): boolean {
return this.socket?.readyState === WEBSOCKET_OPEN;
}
/** Subscribes to low-level client events. Returns an unsubscribe function. */
on<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.on(event, listener);
}
/** Subscribes to one low-level client event, then automatically unsubscribes. */
once<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): () => void {
return this.emitter.once(event, listener);
}
/** Removes a previously registered low-level client event listener. */
off<TKey extends keyof SnowLumaWebSocketEvents>(
event: TKey,
listener: (payload: SnowLumaWebSocketEvents[TKey]) => void,
): void {
this.emitter.off(event, listener);
}
/** Subscribes to every SnowLuma event packet. */
onEvent(listener: (event: SnowLumaEvent) => void): () => void {
return this.on('event', listener);
}
/** Adds event middleware to the dispatch pipeline. */
use(middleware: EventMiddleware): () => void {
this.middlewares.push(middleware);
return () => {
const index = this.middlewares.indexOf(middleware);
if (index >= 0) this.middlewares.splice(index, 1);
};
}
/** Runs a handler when a type guard or predicate matches an event. */
when<TEvent extends SnowLumaEvent>(
predicate: EventPredicate<TEvent>,
handler: EventHandler<TEvent>,
): () => void {
return this.use(async (event, context, next) => {
if (predicate(event)) {
await handler(event, context as never);
}
if (!context.stopped) await next();
});
}
onMessage(handler: EventHandler<OneBotMessageEvent>): () => void {
return this.when(isMessageEvent, handler);
}
onPrivateMessage(handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'private' }>>): () => void {
return this.when(isPrivateMessageEvent, handler);
}
onGroupMessage(handler: EventHandler<Extract<OneBotMessageEvent, { message_type: 'group' }>>): () => void {
return this.when(isGroupMessageEvent, handler);
}
onNotice(handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(type: string, handler: EventHandler<OneBotNoticeEvent>): () => void;
onNotice(typeOrHandler: string | EventHandler<OneBotNoticeEvent>, handler?: EventHandler<OneBotNoticeEvent>): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) throw new TypeError('onNotice(type, handler) requires a handler');
return this.when(noticeType(typeOrHandler), handler);
}
return this.when(isNoticeEvent, typeOrHandler);
}
onRequest(handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(type: string, handler: EventHandler<OneBotRequestEvent>): () => void;
onRequest(typeOrHandler: string | EventHandler<OneBotRequestEvent>, handler?: EventHandler<OneBotRequestEvent>): () => void {
if (typeof typeOrHandler === 'string') {
if (!handler) throw new TypeError('onRequest(type, handler) requires a handler');
return this.when(requestType(typeOrHandler), handler);
}
return this.when(isRequestEvent, typeOrHandler);
}
onMetaEvent(handler: EventHandler<OneBotMetaEvent>): () => void {
return this.when(isMetaEvent, handler);
}
command(
command: string | RegExp,
handler: CommandHandler,
options?: CommandOptions,
): () => void {
return this.onMessage(async (event, context) => {
const matched = matchCommand(event, command, options);
if (!matched) return;
await handler(event, Object.assign(context, { command: matched }), matched);
});
}
/** Connects to SnowLuma's OneBot WebSocket endpoint. */
async connect(): Promise<void> {
if (this.isConnected) return;
if (this.connectPromise) return this.connectPromise;
this.closedByUser = false;
this.connectPromise = new Promise((resolve, reject) => {
const url = appendAccessToken(this.url, this.accessToken);
const socket = new this.WebSocketCtor(url, this.protocols);
this.socket = socket;
const cleanup = [
addSocketListener(socket, 'open', () => {
cleanup.forEach((off) => off());
this.bindSocket(socket);
this.reconnectAttempts = 0;
this.connectPromise = null;
this.emitter.emit('open', undefined);
resolve();
}),
addSocketListener(socket, 'error', (error) => {
this.emitter.emit('error', unwrapEventPayload(error));
}),
addSocketListener(socket, 'close', (...args) => {
cleanup.forEach((off) => off());
this.connectPromise = null;
this.socket = null;
reject(new SnowLumaConnectionError('SnowLuma WebSocket closed before opening'));
this.handleClose(args);
}),
];
});
return this.connectPromise;
}
/** Closes the socket and rejects all pending API requests. */
close(code = 1000, reason = 'normal'): void {
this.closedByUser = true;
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket client closed'));
if (this.socket && this.socket.readyState !== WEBSOCKET_CLOSED) {
this.socket.close(code, reason);
}
this.socket = null;
this.connectPromise = null;
}
/** Sends one OneBot action over WebSocket and returns the raw response envelope. */
override async request<TAction extends SnowLumaAction>(
action: TAction,
params?: ActionParams<TAction>,
options?: RequestOptions,
): Promise<ApiResponse<ActionResult<TAction>>> {
throwIfAborted(options?.signal);
await raceWithAbort(this.connect(), options?.signal, 'SnowLuma WebSocket request aborted before connection opened');
throwIfAborted(options?.signal);
const socket = this.socket;
if (!socket || socket.readyState !== WEBSOCKET_OPEN) {
throw new SnowLumaConnectionError('SnowLuma WebSocket is not open');
}
const echo = options?.echo ?? createEcho();
const key = echoKey(echo);
const timeoutMs = options?.timeoutMs ?? this.requestTimeoutMs;
const promise = new Promise<ApiResponse>((resolve, reject) => {
let timer: ReturnType<typeof setTimeout> | null = null;
let abortListener: (() => void) | undefined;
const cleanup = (): void => {
if (timer) clearTimeout(timer);
if (abortListener) options?.signal?.removeEventListener('abort', abortListener);
};
timer = timeoutMs > 0
? setTimeout(() => {
this.pending.delete(key);
cleanup();
reject(new SnowLumaTimeoutError(`SnowLuma WebSocket request timed out after ${timeoutMs}ms`, timeoutMs));
}, timeoutMs)
: null;
abortListener = () => {
this.pending.delete(key);
cleanup();
reject(new SnowLumaAbortError('SnowLuma WebSocket request aborted', { cause: options?.signal?.reason }));
};
options?.signal?.addEventListener('abort', abortListener, { once: true });
this.pending.set(key, { resolve, reject, timer, cleanup });
});
try {
socket.send(JSON.stringify({
action,
params: toJsonObject(params as JsonObject | undefined),
echo,
}));
} catch (error) {
const pending = this.pending.get(key);
pending?.cleanup?.();
this.pending.delete(key);
throw new SnowLumaConnectionError('Failed to send SnowLuma WebSocket request', { cause: error });
}
return promise as Promise<ApiResponse<ActionResult<TAction>>>;
}
private bindSocket(socket: WebSocketLike): void {
addSocketListener(socket, 'message', (...args) => this.handleMessage(args));
addSocketListener(socket, 'error', (error) => this.emitter.emit('error', unwrapEventPayload(error)));
addSocketListener(socket, 'close', (...args) => this.handleClose(args));
}
private handleMessage(args: unknown[]): void {
const raw = unwrapMessagePayload(args[0]);
this.emitter.emit('raw', raw);
let parsed: unknown;
try {
parsed = JSON.parse(rawToString(raw));
} catch (error) {
this.emitter.emit('error', new SnowLumaParseError('SnowLuma WebSocket returned non-JSON message', { cause: error }));
return;
}
if (isJsonObject(parsed) && parsed.echo !== undefined) {
const key = echoKey(parsed.echo as JsonValue);
const pending = this.pending.get(key);
if (pending) {
this.pending.delete(key);
pending.cleanup?.();
try {
const response = assertApiResponse(parsed);
pending.resolve(response);
this.emitter.emit('response', response);
} catch (error) {
pending.reject(new SnowLumaParseError('SnowLuma WebSocket response is invalid', { cause: error }));
}
return;
}
}
if (isJsonObject(parsed) && typeof parsed.post_type === 'string') {
void this.dispatchEvent(parsed as SnowLumaEvent).catch((error) => {
this.emitter.emit('error', error);
});
}
}
private async dispatchEvent(event: SnowLumaEvent): Promise<void> {
const context = createEventContext(event, this);
let index = -1;
const next = async (): Promise<void> => {
index += 1;
const middleware = this.middlewares[index];
if (!middleware || context.stopped) return;
await middleware(event, context, next);
};
await next();
if (!context.stopped && index >= this.middlewares.length - 1) {
this.emitter.emit('event', event);
}
}
private handleClose(args: unknown[]): void {
const info = closeInfo(args);
this.socket = null;
this.connectPromise = null;
this.rejectPending(new SnowLumaConnectionError('SnowLuma WebSocket closed'));
this.emitter.emit('close', info);
if (!this.closedByUser && this.reconnect) {
this.scheduleReconnect();
}
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
const reconnect = this.reconnect;
if (!reconnect) return;
const retries = reconnect.retries ?? Number.POSITIVE_INFINITY;
if (this.reconnectAttempts >= retries) return;
const minDelay = reconnect.minDelayMs ?? 1000;
const maxDelay = reconnect.maxDelayMs ?? 30_000;
const delay = Math.min(maxDelay, minDelay * 2 ** this.reconnectAttempts);
this.reconnectAttempts += 1;
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.connect().catch((error) => {
this.emitter.emit('error', error);
if (!this.closedByUser) this.scheduleReconnect();
});
}, delay);
}
private rejectPending(error: Error): void {
for (const pending of this.pending.values()) {
pending.cleanup?.();
pending.reject(error);
}
this.pending.clear();
}
}
export function createWebSocketClient(options?: SnowLumaWebSocketClientOptions): SnowLumaWebSocketClient {
return new SnowLumaWebSocketClient(options);
}
@@ -0,0 +1,64 @@
import type {
ApiResponse,
SnowLumaClientOptions,
SnowLumaEvent,
WsRole,
} from '../types/index';
export interface WebSocketLike {
readyState: number;
send(data: string): void;
close(code?: number, reason?: string): void;
addEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
removeEventListener?: (event: string, listener: (...args: unknown[]) => void) => void;
on?: (event: string, listener: (...args: unknown[]) => void) => void;
off?: (event: string, listener: (...args: unknown[]) => void) => void;
removeListener?: (event: string, listener: (...args: unknown[]) => void) => void;
}
export type WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocketLike;
/** Reconnect policy for the WebSocket client. */
export interface ReconnectOptions {
/** Maximum reconnect attempts. Omit for unlimited retries. */
retries?: number;
/** Initial reconnect delay in milliseconds. Defaults to 1000. */
minDelayMs?: number;
/** Maximum reconnect delay in milliseconds. Defaults to 30000. */
maxDelayMs?: number;
}
/** Options for the WebSocket transport client. */
export interface SnowLumaWebSocketClientOptions extends SnowLumaClientOptions {
/** OneBot WebSocket endpoint. Defaults to ws://127.0.0.1:3001/. */
url?: string;
/** OneBot WebSocket role advertised by the client. */
role?: WsRole;
/** Optional WebSocket protocols argument. */
protocols?: string | string[];
/** Custom WebSocket constructor for Node runtimes or tests. */
webSocket?: WebSocketConstructor;
/** Enables or configures automatic reconnect after unexpected close. */
reconnect?: boolean | ReconnectOptions;
}
export interface WebSocketCloseInfo {
code?: number;
reason?: string;
}
export interface SnowLumaWebSocketEvents {
open: undefined;
close: WebSocketCloseInfo;
error: unknown;
event: SnowLumaEvent;
response: ApiResponse;
raw: unknown;
}
export interface PendingRequest {
resolve: (response: ApiResponse) => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout> | null;
cleanup?: () => void;
}
@@ -0,0 +1,77 @@
import { isJsonObject } from '../internal/json';
import type {
ReconnectOptions,
WebSocketCloseInfo,
WebSocketLike,
} from './websocket-types';
export const WEBSOCKET_OPEN = 1;
export const WEBSOCKET_CLOSED = 3;
export function normalizeReconnect(value: boolean | ReconnectOptions | undefined): ReconnectOptions | null {
if (!value) return null;
if (value === true) return {};
return value;
}
export function addSocketListener(
socket: WebSocketLike,
event: string,
listener: (...args: unknown[]) => void,
): () => void {
if (socket.addEventListener) {
socket.addEventListener(event, listener);
return () => socket.removeEventListener?.(event, listener);
}
if (socket.on) {
socket.on(event, listener);
return () => {
if (socket.off) socket.off(event, listener);
else socket.removeListener?.(event, listener);
};
}
return () => undefined;
}
export function unwrapMessagePayload(value: unknown): unknown {
if (isJsonObject(value) && 'data' in value) {
return value.data;
}
return value;
}
export function unwrapEventPayload(value: unknown): unknown {
if (isJsonObject(value) && 'error' in value) {
return value.error;
}
return value;
}
export function rawToString(value: unknown): string {
if (typeof value === 'string') return value;
if (value instanceof ArrayBuffer) return new TextDecoder().decode(value);
if (ArrayBuffer.isView(value)) {
return new TextDecoder().decode(value);
}
if (value instanceof Blob) {
throw new Error('Blob WebSocket messages are not supported synchronously');
}
if (value && typeof value === 'object' && 'toString' in value && typeof value.toString === 'function') {
return value.toString();
}
return String(value);
}
export function closeInfo(args: unknown[]): WebSocketCloseInfo {
const first = args[0];
if (isJsonObject(first)) {
return {
code: typeof first.code === 'number' ? first.code : undefined,
reason: typeof first.reason === 'string' ? first.reason : undefined,
};
}
return {
code: typeof args[0] === 'number' ? args[0] : undefined,
reason: typeof args[1] === 'string' ? args[1] : undefined,
};
}