This commit is contained in:
DrSmoothl committed 2026-10-12 15:43:34 +08:00
1 parent effeb66554
commit 7c0519f75f
977 files changed
+198426 -158324

No files matched your search

File diff suppressed because it is too large. Load diff
+104 -90
View File
@@ -1,115 +1,129 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
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,
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 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;
readonly baseUrl: string;
readonly accessToken?: string;
readonly requestTimeoutMs: number;
private readonly fetchImpl: typeof fetch;
private readonly headers: Record<string, string>;
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 ?? {};
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 (!this.fetchImpl) {
throw new SnowLumaConnectionError('No fetch implementation is available');
}
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}`;
/** 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;
}
return headers;
}
}
export function createHttpClient(options?: SnowLumaHttpClientOptions): SnowLumaHttpClient {
return new SnowLumaHttpClient(options);
return new SnowLumaHttpClient(options);
}
+5 -5
View File
@@ -4,9 +4,9 @@ export { SnowLumaWebSocketClient, createWebSocketClient } from './websocket-clie
export type { SnowLumaHttpClientOptions } from './http-client';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './websocket-client';
+500 -392
View File
@@ -1,427 +1,535 @@
import {
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaAbortError,
SnowLumaConnectionError,
SnowLumaParseError,
SnowLumaTimeoutError,
} from '../errors';
import { Emitter } from '../emitter';
import {
createEventContext,
isBotStatusEvent,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType,
type CommandHandler,
type CommandOptions,
type EventHandler,
type EventMiddleware,
type EventPredicate,
createEventContext,
isBotStatusEvent,
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,
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,
OneBotBotStatusEvent,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotRequestEvent,
RequestOptions,
SnowLumaAction,
SnowLumaEvent,
WsRole,
ActionParams,
ActionResult,
ApiResponse,
JsonObject,
JsonValue,
OneBotBotStatusEvent,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotRequestEvent,
RequestOptions,
SnowLumaAction,
SnowLumaEvent,
WsRole,
} from '../types/index';
import type {
PendingRequest,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketConstructor,
WebSocketLike,
PendingRequest,
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketConstructor,
WebSocketLike,
} from './websocket-types';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
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;
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;
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);
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);
}
onBotStatus(handler: EventHandler<OneBotBotStatusEvent>): () => void {
return this.when(isBotStatusEvent, handler);
}
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 }));
if (!this.WebSocketCtor) {
throw new SnowLumaConnectionError('No WebSocket implementation is available');
}
return;
}
}
if (isJsonObject(parsed) && typeof parsed.post_type === 'string') {
void this.dispatchEvent(parsed as SnowLumaEvent).catch((error) => {
this.emitter.emit('error', error);
});
/** True when the underlying WebSocket is currently open. */
get isConnected(): boolean {
return this.socket?.readyState === WEBSOCKET_OPEN;
}
}
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);
/** 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);
}
}
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();
/** 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);
}
}
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);
/** 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);
}
onBotStatus(handler: EventHandler<OneBotBotStatusEvent>): () => void {
return this.when(isBotStatusEvent, handler);
}
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();
}
this.pending.clear();
}
}
export function createWebSocketClient(options?: SnowLumaWebSocketClientOptions): SnowLumaWebSocketClient {
return new SnowLumaWebSocketClient(options);
export function createWebSocketClient(
options?: SnowLumaWebSocketClientOptions,
): SnowLumaWebSocketClient {
return new SnowLumaWebSocketClient(options);
}
+41 -43
View File
@@ -1,64 +1,62 @@
import type {
ApiResponse,
SnowLumaClientOptions,
SnowLumaEvent,
WsRole,
} from '../types/index';
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;
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;
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;
/** 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;
/** 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;
code?: number;
reason?: string;
}
export interface SnowLumaWebSocketEvents {
open: undefined;
close: WebSocketCloseInfo;
error: unknown;
event: SnowLumaEvent;
response: ApiResponse;
raw: unknown;
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;
resolve: (response: ApiResponse) => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout> | null;
cleanup?: () => void;
}
+81 -53
View File
@@ -1,77 +1,105 @@
import { isJsonObject } from '../internal/json';
import type {
ReconnectOptions,
WebSocketCloseInfo,
WebSocketLike,
} from './websocket-types';
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 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,
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;
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;
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;
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);
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)) {
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 first.code === 'number' ? first.code : undefined,
reason: typeof first.reason === 'string' ? first.reason : undefined,
code: typeof args[0] === 'number' ? args[0] : undefined,
reason: typeof args[1] === 'string' ? args[1] : undefined,
};
}
return {
code: typeof args[0] === 'number' ? args[0] : undefined,
reason: typeof args[1] === 'string' ? args[1] : undefined,
};
}
+36 -30
View File
@@ -1,39 +1,45 @@
type Listener<TPayload> = (payload: TPayload) => void;
export class Emitter<TEvents extends object> {
private readonly listeners = new Map<keyof TEvents, Set<Listener<never>>>();
private readonly listeners = new Map<keyof TEvents, Set<Listener<never>>>();
on<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): () => void {
let set = this.listeners.get(event);
if (!set) {
set = new Set();
this.listeners.set(event, set);
on<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): () => void {
let set = this.listeners.get(event);
if (!set) {
set = new Set();
this.listeners.set(event, set);
}
set.add(listener as Listener<never>);
return () => this.off(event, listener);
}
set.add(listener as Listener<never>);
return () => this.off(event, listener);
}
once<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): () => void {
const off = this.on(event, (payload) => {
off();
listener(payload);
});
return off;
}
off<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): void {
this.listeners.get(event)?.delete(listener as Listener<never>);
}
emit<TKey extends keyof TEvents>(event: TKey, payload: TEvents[TKey]): void {
const set = this.listeners.get(event);
if (!set) return;
for (const listener of [...set]) {
listener(payload as never);
once<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): () => void {
const off = this.on(event, (payload) => {
off();
listener(payload);
});
return off;
}
}
clear(): void {
this.listeners.clear();
}
off<TKey extends keyof TEvents>(event: TKey, listener: Listener<TEvents[TKey]>): void {
this.listeners.get(event)?.delete(listener as Listener<never>);
}
emit<TKey extends keyof TEvents>(event: TKey, payload: TEvents[TKey]): void {
const set = this.listeners.get(event);
if (!set) {
return;
}
for (const listener of [...set]) {
listener(payload as never);
}
}
clear(): void {
this.listeners.clear();
}
}
+47 -43
View File
@@ -2,82 +2,86 @@ import type { ApiResponse } from './types/index';
/** Base error for every exception intentionally thrown by the SnowLuma SDK. */
export class SnowLumaError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaError';
}
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaError';
}
}
/** Transport-layer failures before a valid OneBot API response is available. */
export class SnowLumaTransportError extends SnowLumaError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaTransportError';
}
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaTransportError';
}
}
/** The request was cancelled by the caller's AbortSignal. */
export class SnowLumaAbortError extends SnowLumaTransportError {
constructor(message = 'SnowLuma request aborted', options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaAbortError';
}
constructor(message = 'SnowLuma request aborted', options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaAbortError';
}
}
/** The request exceeded the configured timeout. */
export class SnowLumaTimeoutError extends SnowLumaTransportError {
readonly timeoutMs: number;
readonly timeoutMs: number;
constructor(message: string, timeoutMs: number, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaTimeoutError';
this.timeoutMs = timeoutMs;
}
constructor(message: string, timeoutMs: number, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaTimeoutError';
this.timeoutMs = timeoutMs;
}
}
/** The SDK could not establish or keep a connection to SnowLuma. */
export class SnowLumaConnectionError extends SnowLumaTransportError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaConnectionError';
}
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaConnectionError';
}
}
/** SnowLuma returned a payload that could not be parsed as the expected protocol shape. */
export class SnowLumaParseError extends SnowLumaTransportError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaParseError';
}
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'SnowLumaParseError';
}
}
/** A OneBot API response with status failed or a non-zero retcode. */
export class SnowLumaApiError<TData = unknown> extends SnowLumaError {
readonly response: ApiResponse<TData>;
readonly retcode: number;
readonly wording?: string;
readonly response: ApiResponse<TData>;
readonly retcode: number;
readonly wording?: string;
constructor(response: ApiResponse<TData>) {
super(response.wording || `SnowLuma API failed with retcode ${response.retcode}`);
this.name = 'SnowLumaApiError';
this.response = response;
this.retcode = response.retcode;
this.wording = response.wording;
}
constructor(response: ApiResponse<TData>) {
super(response.wording || `SnowLuma API failed with retcode ${response.retcode}`);
this.name = 'SnowLumaApiError';
this.response = response;
this.retcode = response.retcode;
this.wording = response.wording;
}
}
/** Authentication or authorization failure returned by SnowLuma. */
export class SnowLumaAuthError<TData = unknown> extends SnowLumaApiError<TData> {
constructor(response: ApiResponse<TData>) {
super(response);
this.name = 'SnowLumaAuthError';
}
constructor(response: ApiResponse<TData>) {
super(response);
this.name = 'SnowLumaAuthError';
}
}
export function createSnowLumaApiError<TData>(response: ApiResponse<TData>): SnowLumaApiError<TData> {
return isAuthFailure(response) ? new SnowLumaAuthError(response) : new SnowLumaApiError(response);
export function createSnowLumaApiError<TData>(
response: ApiResponse<TData>,
): SnowLumaApiError<TData> {
return isAuthFailure(response)
? new SnowLumaAuthError(response)
: new SnowLumaApiError(response);
}
function isAuthFailure(response: ApiResponse<unknown>): boolean {
return response.retcode === 1401 || response.retcode === 401 || response.retcode === 403;
return response.retcode === 1401 || response.retcode === 401 || response.retcode === 403;
}
+53 -41
View File
@@ -2,54 +2,66 @@ import type { OneBotMessageEvent } from '../types/index';
import type { CommandMatch, CommandOptions } from './types';
export function matchCommand(
event: OneBotMessageEvent,
command: string | RegExp,
options: CommandOptions = {},
event: OneBotMessageEvent,
command: string | RegExp,
options: CommandOptions = {},
): CommandMatch | null {
const trim = options.trim ?? true;
const raw = trim ? event.raw_message.trim() : event.raw_message;
const prefixes = normalizePrefixes(options.prefixes ?? '/');
const trim = options.trim ?? true;
const raw = trim ? event.raw_message.trim() : event.raw_message;
const prefixes = normalizePrefixes(options.prefixes ?? '/');
for (const prefix of prefixes) {
if (prefix && !raw.startsWith(prefix)) continue;
for (const prefix of prefixes) {
if (prefix && !raw.startsWith(prefix)) {
continue;
}
const text = prefix ? raw.slice(prefix.length).trimStart() : raw;
if (!text) continue;
const text = prefix ? raw.slice(prefix.length).trimStart() : raw;
if (command instanceof RegExp) {
const match = text.match(command);
if (!match || match.index !== 0) continue;
const matchedText = match[0] ?? '';
const rest = text.slice(matchedText.length).trim();
return {
command: matchedText,
text,
args: rest ? rest.split(/\s+/) : [],
rest,
prefix,
match,
};
if (!text) {
continue;
}
if (command instanceof RegExp) {
const match = text.match(command);
if (!match || match.index !== 0) {
continue;
}
const matchedText = match[0] ?? '';
const rest = text.slice(matchedText.length).trim();
return {
command: matchedText,
text,
args: rest ? rest.split(/\s+/) : [],
rest,
prefix,
match,
};
}
const [head = '', ...args] = text.split(/\s+/);
const matches = options.caseSensitive
? head === command
: head.toLowerCase() === command.toLowerCase();
if (!matches) {
continue;
}
return {
command: head,
text,
args,
rest: text.slice(head.length).trim(),
prefix,
match: null,
};
}
const [head = '', ...args] = text.split(/\s+/);
const matches = options.caseSensitive
? head === command
: head.toLowerCase() === command.toLowerCase();
if (!matches) continue;
return {
command: head,
text,
args,
rest: text.slice(head.length).trim(),
prefix,
match: null,
};
}
return null;
return null;
}
function normalizePrefixes(prefixes: string | string[]): string[] {
return Array.isArray(prefixes) ? prefixes : [prefixes];
return Array.isArray(prefixes) ? prefixes : [prefixes];
}
+74 -63
View File
@@ -3,71 +3,82 @@ import type { SnowLumaEvent } from '../types/index';
import { isGroupMessageEvent, isPrivateMessageEvent, isRequestEvent } from './guards';
import type { SnowLumaEventContext } from './types';
export function createEventContext<TEvent extends SnowLumaEvent>(
event: TEvent,
client: SnowLumaApiClient,
event: TEvent,
client: SnowLumaApiClient,
): SnowLumaEventContext<TEvent> {
let stopped = false;
let stopped = false;
const context: SnowLumaEventContext<TEvent> = {
event,
client,
get stopped() {
return stopped;
},
stopPropagation() {
stopped = true;
},
async reply(message, options) {
if (isGroupMessageEvent(event)) {
return client.sendGroupMessage(event.group_id, message, options);
}
if (isPrivateMessageEvent(event)) {
return client.sendPrivateMessage(event.user_id, message, options);
}
throw new Error('reply() is only available for message events');
},
async approve(options) {
if (!isRequestEvent(event)) {
throw new Error('approve() is only available for request events');
}
if (event.request_type === 'friend') {
return client.setFriendAddRequest(event.flag, true, options);
}
if (event.request_type === 'group') {
return client.setGroupAddRequest(event.flag, {
...options,
subType: options?.subType ?? event.sub_type,
approve: true,
});
}
throw new Error(`approve() does not support request_type=${event.request_type}`);
},
async reject(reason, options) {
if (!isRequestEvent(event)) {
throw new Error('reject() is only available for request events');
}
if (event.request_type === 'friend') {
return client.setFriendAddRequest(event.flag, false, options);
}
if (event.request_type === 'group') {
return client.setGroupAddRequest(event.flag, {
...options,
subType: options?.subType ?? event.sub_type,
approve: false,
reason: reason ?? options?.reason,
});
}
throw new Error(`reject() does not support request_type=${event.request_type}`);
},
async quickOperation(operation, options) {
return client.raw('.handle_quick_operation', {
context: event,
operation,
}, options);
},
};
const context: SnowLumaEventContext<TEvent> = {
event,
client,
get stopped() {
return stopped;
},
stopPropagation() {
stopped = true;
},
async reply(message, options) {
if (isGroupMessageEvent(event)) {
return client.sendGroupMessage(event.group_id, message, options);
}
return context;
if (isPrivateMessageEvent(event)) {
return client.sendPrivateMessage(event.user_id, message, options);
}
throw new Error('reply() is only available for message events');
},
async approve(options) {
if (!isRequestEvent(event)) {
throw new Error('approve() is only available for request events');
}
if (event.request_type === 'friend') {
return client.setFriendAddRequest(event.flag, true, options);
}
if (event.request_type === 'group') {
return client.setGroupAddRequest(event.flag, {
...options,
subType: options?.subType ?? event.sub_type,
approve: true,
});
}
throw new Error(`approve() does not support request_type=${event.request_type}`);
},
async reject(reason, options) {
if (!isRequestEvent(event)) {
throw new Error('reject() is only available for request events');
}
if (event.request_type === 'friend') {
return client.setFriendAddRequest(event.flag, false, options);
}
if (event.request_type === 'group') {
return client.setGroupAddRequest(event.flag, {
...options,
subType: options?.subType ?? event.sub_type,
approve: false,
reason: reason ?? options?.reason,
});
}
throw new Error(`reject() does not support request_type=${event.request_type}`);
},
async quickOperation(operation, options) {
return client.raw(
'.handle_quick_operation',
{
context: event,
operation,
},
options,
);
},
};
return context;
}
+31 -21
View File
@@ -1,51 +1,61 @@
import type {
OneBotBotStatusEvent,
OneBotGroupMessageEvent,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotPrivateMessageEvent,
OneBotRequestEvent,
SnowLumaEvent,
OneBotBotStatusEvent,
OneBotGroupMessageEvent,
OneBotMessageEvent,
OneBotMetaEvent,
OneBotNoticeEvent,
OneBotPrivateMessageEvent,
OneBotRequestEvent,
SnowLumaEvent,
} from '../types/index';
import type { EventPredicate } from './types';
export function isMessageEvent(event: SnowLumaEvent): event is OneBotMessageEvent {
return (event.post_type === 'message' || event.post_type === 'message_sent')
&& (event.message_type === 'private' || event.message_type === 'group');
return (
(event.post_type === 'message' || event.post_type === 'message_sent') &&
(event.message_type === 'private' || event.message_type === 'group')
);
}
export function isPrivateMessageEvent(event: SnowLumaEvent): event is OneBotPrivateMessageEvent {
return isMessageEvent(event) && event.message_type === 'private';
return isMessageEvent(event) && event.message_type === 'private';
}
export function isGroupMessageEvent(event: SnowLumaEvent): event is OneBotGroupMessageEvent {
return isMessageEvent(event) && event.message_type === 'group';
return isMessageEvent(event) && event.message_type === 'group';
}
export function isNoticeEvent(event: SnowLumaEvent): event is OneBotNoticeEvent {
return event.post_type === 'notice' && typeof event.notice_type === 'string';
return event.post_type === 'notice' && typeof event.notice_type === 'string';
}
export function isBotStatusEvent(event: SnowLumaEvent): event is OneBotBotStatusEvent {
return isNoticeEvent(event)
&& event.notice_type === 'bot_status'
&& (event.sub_type === 'online' || event.sub_type === 'offline')
&& typeof event.user_id === 'number';
return (
isNoticeEvent(event) &&
event.notice_type === 'bot_status' &&
(event.sub_type === 'online' || event.sub_type === 'offline') &&
typeof event.user_id === 'number'
);
}
export function isRequestEvent(event: SnowLumaEvent): event is OneBotRequestEvent {
return event.post_type === 'request' && typeof event.request_type === 'string' && typeof event.flag === 'string';
return (
event.post_type === 'request' &&
typeof event.request_type === 'string' &&
typeof event.flag === 'string'
);
}
export function isMetaEvent(event: SnowLumaEvent): event is OneBotMetaEvent {
return event.post_type === 'meta_event' && typeof event.meta_event_type === 'string';
return event.post_type === 'meta_event' && typeof event.meta_event_type === 'string';
}
export function noticeType(type: string): EventPredicate<OneBotNoticeEvent> {
return (event): event is OneBotNoticeEvent => isNoticeEvent(event) && event.notice_type === type;
return (event): event is OneBotNoticeEvent =>
isNoticeEvent(event) && event.notice_type === type;
}
export function requestType(type: string): EventPredicate<OneBotRequestEvent> {
return (event): event is OneBotRequestEvent => isRequestEvent(event) && event.request_type === type;
return (event): event is OneBotRequestEvent =>
isRequestEvent(event) && event.request_type === type;
}
+38 -38
View File
@@ -1,66 +1,66 @@
import type { SnowLumaApiClient } from '../client/api-client';
import type {
JsonObject,
OneBotMessageEvent,
OutgoingMessage,
RequestOptions,
SnowLumaEvent,
JsonObject,
OneBotMessageEvent,
OutgoingMessage,
RequestOptions,
SnowLumaEvent,
} from '../types/index';
export type MaybePromise<T = void> = T | Promise<T>;
export type EventNext = () => Promise<void>;
export type EventPredicate<TEvent extends SnowLumaEvent = SnowLumaEvent> = (event: SnowLumaEvent) => event is TEvent;
export type EventPredicate<TEvent extends SnowLumaEvent = SnowLumaEvent> = (
event: SnowLumaEvent,
) => event is TEvent;
export type EventHandler<TEvent extends SnowLumaEvent = SnowLumaEvent> = (
event: TEvent,
context: SnowLumaEventContext<TEvent>,
event: TEvent,
context: SnowLumaEventContext<TEvent>,
) => MaybePromise;
export type EventMiddleware = (
event: SnowLumaEvent,
context: SnowLumaEventContext,
next: EventNext,
event: SnowLumaEvent,
context: SnowLumaEventContext,
next: EventNext,
) => MaybePromise;
export interface RequestDecisionOptions extends RequestOptions {
reason?: string;
subType?: string;
reason?: string;
subType?: string;
}
export interface SnowLumaEventContext<TEvent extends SnowLumaEvent = SnowLumaEvent> {
readonly event: TEvent;
readonly client: SnowLumaApiClient;
readonly stopped: boolean;
stopPropagation(): void;
reply(message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
approve(options?: RequestDecisionOptions): Promise<unknown>;
reject(reason?: string, options?: RequestDecisionOptions): Promise<unknown>;
quickOperation(operation: JsonObject, options?: RequestOptions): Promise<unknown>;
readonly event: TEvent;
readonly client: SnowLumaApiClient;
readonly stopped: boolean;
stopPropagation(): void;
reply(
message: OutgoingMessage,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown>;
approve(options?: RequestDecisionOptions): Promise<unknown>;
reject(reason?: string, options?: RequestDecisionOptions): Promise<unknown>;
quickOperation(operation: JsonObject, options?: RequestOptions): Promise<unknown>;
}
export interface CommandOptions {
prefixes?: string | string[];
trim?: boolean;
caseSensitive?: boolean;
prefixes?: string | string[];
trim?: boolean;
caseSensitive?: boolean;
}
export interface CommandMatch {
command: string;
text: string;
args: string[];
rest: string;
prefix: string;
match: RegExpMatchArray | null;
command: string;
text: string;
args: string[];
rest: string;
prefix: string;
match: RegExpMatchArray | null;
}
export type CommandHandler<TEvent extends OneBotMessageEvent = OneBotMessageEvent> = (
event: TEvent,
context: SnowLumaEventContext<TEvent> & { command: CommandMatch },
match: CommandMatch,
event: TEvent,
context: SnowLumaEventContext<TEvent> & { command: CommandMatch },
match: CommandMatch,
) => MaybePromise;
+64 -62
View File
@@ -1,79 +1,81 @@
export { SnowLumaApiClient } from './client/api-client';
export { createHttpClient, SnowLumaHttpClient } from './client/http-client';
export type {
SnowLumaHttpClientOptions
} from './client/http-client';
export type { SnowLumaHttpClientOptions } from './client/http-client';
export { createWebSocketClient, SnowLumaWebSocketClient } from './client/websocket-client';
export {
createSnowLumaApiError, SnowLumaAbortError,
SnowLumaApiError,
SnowLumaAuthError,
SnowLumaConnectionError,
SnowLumaError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError
createSnowLumaApiError,
SnowLumaAbortError,
SnowLumaApiError,
SnowLumaAuthError,
SnowLumaConnectionError,
SnowLumaError,
SnowLumaParseError,
SnowLumaTimeoutError,
SnowLumaTransportError,
} from './errors';
export {
createEventContext,
isBotStatusEvent,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType
createEventContext,
isBotStatusEvent,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
matchCommand,
noticeType,
requestType,
} from './events/index';
export {
at,
atAll,
br,
chain,
contact,
escapeCqParam,
escapeCqText,
face,
forward, fromCQString, image,
json,
location,
message, MessageChain, music,
node,
normalizeMessage,
parseSegments,
poke,
raw,
record,
reply,
share,
text,
toCQString,
video,
xml
at,
atAll,
br,
chain,
contact,
escapeCqParam,
escapeCqText,
face,
forward,
fromCQString,
image,
json,
location,
message,
MessageChain,
music,
node,
normalizeMessage,
parseSegments,
poke,
raw,
record,
reply,
share,
text,
toCQString,
video,
xml,
} from './messages/index';
export type {
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor
ReconnectOptions,
SnowLumaWebSocketClientOptions,
SnowLumaWebSocketEvents,
WebSocketCloseInfo,
WebSocketConstructor,
} from './client/websocket-client';
export type {
CommandHandler,
CommandMatch,
CommandOptions,
EventHandler,
EventMiddleware,
EventNext,
EventPredicate,
MaybePromise,
RequestDecisionOptions,
SnowLumaEventContext
CommandHandler,
CommandMatch,
CommandOptions,
EventHandler,
EventMiddleware,
EventNext,
EventPredicate,
MaybePromise,
RequestDecisionOptions,
SnowLumaEventContext,
} from './events/index';
export type * from './types/index';
+66 -57
View File
@@ -1,82 +1,91 @@
import { SnowLumaAbortError } from '../errors';
export interface RequestAbortState {
signal: AbortSignal;
cleanup(): void;
isTimedOut(): boolean;
isExternallyAborted(): boolean;
signal: AbortSignal;
cleanup(): void;
isTimedOut(): boolean;
isExternallyAborted(): boolean;
}
export function createRequestAbortState(
timeoutMs: number,
externalSignal?: AbortSignal,
timeoutMs: number,
externalSignal?: AbortSignal,
): RequestAbortState {
const controller = new AbortController();
let timedOut = false;
let externallyAborted = false;
const controller = new AbortController();
let timedOut = false;
let externallyAborted = false;
const onExternalAbort = (): void => {
externallyAborted = true;
controller.abort(externalSignal?.reason);
};
const onExternalAbort = (): void => {
externallyAborted = true;
controller.abort(externalSignal?.reason);
};
if (externalSignal?.aborted) {
onExternalAbort();
} else {
externalSignal?.addEventListener('abort', onExternalAbort, { once: true });
}
if (externalSignal?.aborted) {
onExternalAbort();
} else {
externalSignal?.addEventListener('abort', onExternalAbort, { once: true });
}
const timer = timeoutMs > 0
? setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs)
: null;
const timer =
timeoutMs > 0
? setTimeout(() => {
timedOut = true;
controller.abort();
}, timeoutMs)
: null;
return {
signal: controller.signal,
cleanup() {
if (timer) clearTimeout(timer);
externalSignal?.removeEventListener('abort', onExternalAbort);
},
isTimedOut() {
return timedOut;
},
isExternallyAborted() {
return externallyAborted || externalSignal?.aborted === true;
},
};
return {
signal: controller.signal,
cleanup() {
if (timer) {
clearTimeout(timer);
}
externalSignal?.removeEventListener('abort', onExternalAbort);
},
isTimedOut() {
return timedOut;
},
isExternallyAborted() {
return externallyAborted || externalSignal?.aborted === true;
},
};
}
export function throwIfAborted(signal?: AbortSignal, message = 'SnowLuma request aborted'): void {
if (signal?.aborted) {
throw new SnowLumaAbortError(message, { cause: signal.reason });
}
if (signal?.aborted) {
throw new SnowLumaAbortError(message, { cause: signal.reason });
}
}
export function isAbortError(error: unknown): boolean {
return typeof error === 'object'
&& error !== null
&& 'name' in error
&& (error as { name?: unknown }).name === 'AbortError';
return (
typeof error === 'object' &&
error !== null &&
'name' in error &&
(error as { name?: unknown }).name === 'AbortError'
);
}
export function raceWithAbort<T>(
promise: Promise<T>,
signal?: AbortSignal,
message = 'SnowLuma request aborted',
promise: Promise<T>,
signal?: AbortSignal,
message = 'SnowLuma request aborted',
): Promise<T> {
if (!signal) return promise;
throwIfAborted(signal, message);
if (!signal) {
return promise;
}
return new Promise<T>((resolve, reject) => {
const onAbort = (): void => {
reject(new SnowLumaAbortError(message, { cause: signal.reason }));
};
throwIfAborted(signal, message);
signal.addEventListener('abort', onAbort, { once: true });
promise.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
return new Promise<T>((resolve, reject) => {
const onAbort = (): void => {
reject(new SnowLumaAbortError(message, { cause: signal.reason }));
};
signal.addEventListener('abort', onAbort, { once: true });
promise.then(resolve, reject).finally(() => {
signal.removeEventListener('abort', onAbort);
});
});
});
}
+66 -41
View File
@@ -1,64 +1,89 @@
import type { ApiResponse, JsonObject, JsonValue } from '../types/index';
export function isJsonObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function asJsonValue(value: unknown): JsonValue {
if (value === null) return null;
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return value;
}
if (Array.isArray(value)) return value.map(asJsonValue);
if (isJsonObject(value)) {
const out: JsonObject = {};
for (const [key, item] of Object.entries(value)) {
if (item === undefined) continue;
out[key] = asJsonValue(item);
if (value === null) {
return null;
}
return out;
}
return String(value);
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return value;
}
if (Array.isArray(value)) {
return value.map(asJsonValue);
}
if (isJsonObject(value)) {
const out: JsonObject = {};
for (const [key, item] of Object.entries(value)) {
if (item === undefined) {
continue;
}
out[key] = asJsonValue(item);
}
return out;
}
return String(value);
}
export function assertApiResponse(value: unknown): ApiResponse {
if (!isJsonObject(value)) {
throw new Error('response is not a JSON object');
}
if (!isJsonObject(value)) {
throw new Error('response is not a JSON object');
}
const status = value.status === 'ok' ? 'ok' : value.status === 'failed' ? 'failed' : null;
if (!status) {
throw new Error('response status is missing or invalid');
}
const status = value.status === 'ok' ? 'ok' : value.status === 'failed' ? 'failed' : null;
const retcode = typeof value.retcode === 'number' && Number.isFinite(value.retcode)
? value.retcode
: status === 'ok' ? 0 : -1;
if (!status) {
throw new Error('response status is missing or invalid');
}
return {
status,
retcode,
data: asJsonValue(value.data ?? null),
echo: value.echo === undefined ? undefined : asJsonValue(value.echo),
wording: typeof value.wording === 'string' ? value.wording : undefined,
};
const retcode =
typeof value.retcode === 'number' && Number.isFinite(value.retcode)
? value.retcode
: status === 'ok'
? 0
: -1;
return {
status,
retcode,
data: asJsonValue(value.data ?? null),
echo: value.echo === undefined ? undefined : asJsonValue(value.echo),
wording: typeof value.wording === 'string' ? value.wording : undefined,
};
}
export function createEcho(): string {
const random = Math.random().toString(36).slice(2);
return `snowluma-sdk:${Date.now().toString(36)}:${random}`;
const random = Math.random().toString(36).slice(2);
return `snowluma-sdk:${Date.now().toString(36)}:${random}`;
}
export function echoKey(value: JsonValue | undefined): string {
if (value === undefined) return '';
return JSON.stringify(value);
if (value === undefined) {
return '';
}
return JSON.stringify(value);
}
export function appendAccessToken(urlValue: string, accessToken?: string): string {
if (!accessToken) return urlValue;
const url = new URL(urlValue);
if (!url.searchParams.has('access_token')) {
url.searchParams.set('access_token', accessToken);
}
return url.toString();
if (!accessToken) {
return urlValue;
}
const url = new URL(urlValue);
if (!url.searchParams.has('access_token')) {
url.searchParams.set('access_token', accessToken);
}
return url.toString();
}
+270 -212
View File
@@ -1,286 +1,344 @@
import type {
AnyMessageSegment,
ContactSegment,
FaceSegment,
ImageSegment,
JsonObject,
LocationSegment,
MessageChainLike,
MusicSegment,
OutgoingMessage,
RecordSegment,
RequestOptions,
ShareSegment,
VideoSegment,
XmlSegment,
AnyMessageSegment,
ContactSegment,
FaceSegment,
ImageSegment,
JsonObject,
LocationSegment,
MessageChainLike,
MusicSegment,
OutgoingMessage,
RecordSegment,
RequestOptions,
ShareSegment,
VideoSegment,
XmlSegment,
} from '../types/index';
import { segmentsToCQString } from './cq-format';
import { segments } from './segments';
export interface MessageChainSender {
sendGroupMessage(groupId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
sendPrivateMessage(userId: number, message: OutgoingMessage, options?: RequestOptions & { autoEscape?: boolean }): Promise<unknown>;
sendGroupMessage(
groupId: number,
message: OutgoingMessage,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown>;
sendPrivateMessage(
userId: number,
message: OutgoingMessage,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown>;
}
const SINGLE_USE_TYPES = new Set(['reply']);
export class MessageChain<THasReply extends boolean = false> implements MessageChainLike {
declare private readonly replyStateBrand?: THasReply;
declare private readonly replyStateBrand?: THasReply;
private constructor(
private readonly items: AnyMessageSegment[] = [],
private readonly used: ReadonlySet<string> = new Set(),
) { }
private constructor(
private readonly items: AnyMessageSegment[] = [],
private readonly used: ReadonlySet<string> = new Set(),
) {}
static empty(): MessageChain<false> {
return new MessageChain<false>();
}
get length(): number {
return this.items.length;
}
get isEmpty(): boolean {
return this.items.length === 0;
}
text(text = ''): MessageChain<THasReply> {
return this.addSegment(segments.text(text));
}
br(): MessageChain<THasReply> {
return this.text('\n');
}
face(id: number | string, options: Omit<FaceSegment['data'], 'id'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.face(id, options));
}
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain<THasReply> {
return this.addSegment(segments.at(qq, options));
}
atAll(): MessageChain<THasReply> {
return this.at('all');
}
reply(this: MessageChain<false>, id: number | string): MessageChain<true> {
return this.addSegment(segments.reply(id), 'reply') as MessageChain<true>;
}
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.image(file, options));
}
record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.record(file, options));
}
video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.video(file, options));
}
json(data: string | JsonObject): MessageChain<THasReply> {
return this.addSegment(segments.json(data));
}
xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.xml(data, options));
}
poke(type: number | string, id?: number | string): MessageChain<THasReply> {
return this.addSegment(segments.poke(type, id));
}
forward(id: string): MessageChain<THasReply> {
return this.addSegment(segments.forward(id));
}
node(userId: number, nickname: string, content: OutgoingMessage): MessageChain<THasReply> {
return this.addSegment(segments.node(userId, nickname, content));
}
share(options: ShareSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.share(options));
}
music(options: MusicSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.music(options));
}
location(options: LocationSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.location(options));
}
contact(type: ContactSegment['data']['type'], id: number | string): MessageChain<THasReply> {
return this.addSegment(segments.contact(type, id));
}
raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageChain<THasReply> {
return this.addSegment(segments.raw(type, data), type);
}
append(messageInput: OutgoingMessage): MessageChain<THasReply> {
let next: MessageChain<THasReply> = this;
const normalized = normalizeMessage(messageInput);
if (typeof normalized === 'string') {
return next.text(normalized);
}
for (const segment of normalized) {
next = next.addFromSegment(segment);
}
return next;
}
build(): AnyMessageSegment[] {
return this.toSegments();
}
toArray(): AnyMessageSegment[] {
return this.toSegments();
}
toSegments(): AnyMessageSegment[] {
return [...this.items];
}
toJSON(): AnyMessageSegment[] {
return this.toSegments();
}
toString(): string {
return segmentsToCQString(this.items);
}
sendToGroup(
client: MessageChainSender,
groupId: number,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown> {
return client.sendGroupMessage(groupId, this, options);
}
sendToPrivate(
client: MessageChainSender,
userId: number,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown> {
return client.sendPrivateMessage(userId, this, options);
}
[Symbol.iterator](): IterableIterator<AnyMessageSegment> {
return this.items[Symbol.iterator]();
}
private addFromSegment(segment: AnyMessageSegment): MessageChain<THasReply> {
return this.addSegment(segment, segment.type);
}
private addSegment<TNextReply extends boolean = THasReply>(
segment: AnyMessageSegment,
singleUseType?: string,
): MessageChain<TNextReply> {
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType) && this.used.has(singleUseType)) {
throw new Error(`Message segment "${singleUseType}" can only appear once in a chain`);
static empty(): MessageChain<false> {
return new MessageChain<false>();
}
const nextUsed = new Set(this.used);
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType)) {
nextUsed.add(singleUseType);
get length(): number {
return this.items.length;
}
get isEmpty(): boolean {
return this.items.length === 0;
}
text(text = ''): MessageChain<THasReply> {
return this.addSegment(segments.text(text));
}
br(): MessageChain<THasReply> {
return this.text('\n');
}
face(
id: number | string,
options: Omit<FaceSegment['data'], 'id'> = {},
): MessageChain<THasReply> {
return this.addSegment(segments.face(id, options));
}
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain<THasReply> {
return this.addSegment(segments.at(qq, options));
}
atAll(): MessageChain<THasReply> {
return this.at('all');
}
reply(this: MessageChain<false>, id: number | string): MessageChain<true> {
return this.addSegment(segments.reply(id), 'reply') as MessageChain<true>;
}
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.image(file, options));
}
record(
file: string,
options: Omit<RecordSegment['data'], 'file'> = {},
): MessageChain<THasReply> {
return this.addSegment(segments.record(file, options));
}
video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.video(file, options));
}
json(data: string | JsonObject): MessageChain<THasReply> {
return this.addSegment(segments.json(data));
}
xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): MessageChain<THasReply> {
return this.addSegment(segments.xml(data, options));
}
poke(type: number | string, id?: number | string): MessageChain<THasReply> {
return this.addSegment(segments.poke(type, id));
}
forward(id: string): MessageChain<THasReply> {
return this.addSegment(segments.forward(id));
}
node(userId: number, nickname: string, content: OutgoingMessage): MessageChain<THasReply> {
return this.addSegment(segments.node(userId, nickname, content));
}
share(options: ShareSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.share(options));
}
music(options: MusicSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.music(options));
}
location(options: LocationSegment['data']): MessageChain<THasReply> {
return this.addSegment(segments.location(options));
}
contact(type: ContactSegment['data']['type'], id: number | string): MessageChain<THasReply> {
return this.addSegment(segments.contact(type, id));
}
raw<TType extends string, TData extends JsonObject>(
type: TType,
data: TData,
): MessageChain<THasReply> {
return this.addSegment(segments.raw(type, data), type);
}
append(messageInput: OutgoingMessage): MessageChain<THasReply> {
let next: MessageChain<THasReply> = this;
const normalized = normalizeMessage(messageInput);
if (typeof normalized === 'string') {
return next.text(normalized);
}
for (const segment of normalized) {
next = next.addFromSegment(segment);
}
return next;
}
build(): AnyMessageSegment[] {
return this.toSegments();
}
toArray(): AnyMessageSegment[] {
return this.toSegments();
}
toSegments(): AnyMessageSegment[] {
return [...this.items];
}
toJSON(): AnyMessageSegment[] {
return this.toSegments();
}
toString(): string {
return segmentsToCQString(this.items);
}
sendToGroup(
client: MessageChainSender,
groupId: number,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown> {
return client.sendGroupMessage(groupId, this, options);
}
sendToPrivate(
client: MessageChainSender,
userId: number,
options?: RequestOptions & { autoEscape?: boolean },
): Promise<unknown> {
return client.sendPrivateMessage(userId, this, options);
}
[Symbol.iterator](): IterableIterator<AnyMessageSegment> {
return this.items[Symbol.iterator]();
}
private addFromSegment(segment: AnyMessageSegment): MessageChain<THasReply> {
return this.addSegment(segment, segment.type);
}
private addSegment<TNextReply extends boolean = THasReply>(
segment: AnyMessageSegment,
singleUseType?: string,
): MessageChain<TNextReply> {
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType) && this.used.has(singleUseType)) {
throw new Error(`Message segment "${singleUseType}" can only appear once in a chain`);
}
const nextUsed = new Set(this.used);
if (singleUseType && SINGLE_USE_TYPES.has(singleUseType)) {
nextUsed.add(singleUseType);
}
return new MessageChain<TNextReply>([...this.items, segment], nextUsed);
}
return new MessageChain<TNextReply>([...this.items, segment], nextUsed);
}
}
export function chain(): MessageChain<false> {
return MessageChain.empty();
return MessageChain.empty();
}
export function text(value = ''): MessageChain<false> {
return chain().text(value);
return chain().text(value);
}
export function br(): MessageChain<false> {
return chain().br();
return chain().br();
}
export function face(id: number | string, options: Omit<FaceSegment['data'], 'id'> = {}): MessageChain<false> {
return chain().face(id, options);
export function face(
id: number | string,
options: Omit<FaceSegment['data'], 'id'> = {},
): MessageChain<false> {
return chain().face(id, options);
}
export function at(qq: number | 'all', options: { name?: string; uid?: string } = {}): MessageChain<false> {
return chain().at(qq, options);
export function at(
qq: number | 'all',
options: { name?: string; uid?: string } = {},
): MessageChain<false> {
return chain().at(qq, options);
}
export function atAll(): MessageChain<false> {
return chain().atAll();
return chain().atAll();
}
export function reply(id: number | string): MessageChain<true> {
return chain().reply(id);
return chain().reply(id);
}
export function image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().image(file, options);
export function image(
file: string,
options: Omit<ImageSegment['data'], 'file'> = {},
): MessageChain<false> {
return chain().image(file, options);
}
export function record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().record(file, options);
export function record(
file: string,
options: Omit<RecordSegment['data'], 'file'> = {},
): MessageChain<false> {
return chain().record(file, options);
}
export function video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): MessageChain<false> {
return chain().video(file, options);
export function video(
file: string,
options: Omit<VideoSegment['data'], 'file'> = {},
): MessageChain<false> {
return chain().video(file, options);
}
export function json(data: string | JsonObject): MessageChain<false> {
return chain().json(data);
return chain().json(data);
}
export function xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): MessageChain<false> {
return chain().xml(data, options);
export function xml(
data: string,
options: Omit<XmlSegment['data'], 'data'> = {},
): MessageChain<false> {
return chain().xml(data, options);
}
export function poke(type: number | string, id?: number | string): MessageChain<false> {
return chain().poke(type, id);
return chain().poke(type, id);
}
export function forward(id: string): MessageChain<false> {
return chain().forward(id);
return chain().forward(id);
}
export function node(userId: number, nickname: string, content: OutgoingMessage): MessageChain<false> {
return chain().node(userId, nickname, content);
export function node(
userId: number,
nickname: string,
content: OutgoingMessage,
): MessageChain<false> {
return chain().node(userId, nickname, content);
}
export function share(options: ShareSegment['data']): MessageChain<false> {
return chain().share(options);
return chain().share(options);
}
export function music(options: MusicSegment['data']): MessageChain<false> {
return chain().music(options);
return chain().music(options);
}
export function location(options: LocationSegment['data']): MessageChain<false> {
return chain().location(options);
return chain().location(options);
}
export function contact(type: ContactSegment['data']['type'], id: number | string): MessageChain<false> {
return chain().contact(type, id);
export function contact(
type: ContactSegment['data']['type'],
id: number | string,
): MessageChain<false> {
return chain().contact(type, id);
}
export function raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageChain<false> {
return chain().raw(type, data);
export function raw<TType extends string, TData extends JsonObject>(
type: TType,
data: TData,
): MessageChain<false> {
return chain().raw(type, data);
}
export function normalizeMessage(input: OutgoingMessage): string | AnyMessageSegment[] {
if (typeof input === 'string') return input;
if (isMessageChainLike(input)) return input.toSegments();
return Array.isArray(input) ? input : [input];
if (typeof input === 'string') {
return input;
}
if (isMessageChainLike(input)) {
return input.toSegments();
}
return Array.isArray(input) ? input : [input];
}
function isMessageChainLike(value: unknown): value is MessageChainLike {
return typeof value === 'object'
&& value !== null
&& 'toSegments' in value
&& typeof value.toSegments === 'function';
return (
typeof value === 'object' &&
value !== null &&
'toSegments' in value &&
typeof value.toSegments === 'function'
);
}
+11 -14
View File
@@ -1,29 +1,26 @@
import type { KnownMessageSegment, MessageSegment } from '../types/index';
export function escapeCqText(text: string): string {
return text
.replace(/&/g, '&amp;')
.replace(/\[/g, '&#91;')
.replace(/\]/g, '&#93;');
return text.replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;');
}
export function escapeCqParam(text: string): string {
return escapeCqText(text).replace(/,/g, '&#44;');
return escapeCqText(text).replace(/,/g, '&#44;');
}
export function segmentsToCQString(segments: Array<KnownMessageSegment | MessageSegment>): string {
return segments.map(segmentToCq).join('');
return segments.map(segmentToCq).join('');
}
function segmentToCq(segment: KnownMessageSegment | MessageSegment): string {
if (segment.type === 'text') {
return escapeCqText(String(segment.data.text ?? ''));
}
if (segment.type === 'text') {
return escapeCqText(String(segment.data.text ?? ''));
}
const params = Object.entries(segment.data)
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${key}=${escapeCqParam(String(value))}`)
.join(',');
const params = Object.entries(segment.data)
.filter(([, value]) => value !== undefined && value !== null)
.map(([key, value]) => `${key}=${escapeCqParam(String(value))}`)
.join(',');
return params ? `[CQ:${segment.type},${params}]` : `[CQ:${segment.type}]`;
return params ? `[CQ:${segment.type},${params}]` : `[CQ:${segment.type}]`;
}
+114 -78
View File
@@ -6,108 +6,144 @@ import type { AnyMessageSegment, FaceSegment, OutgoingMessage } from '../types/i
const CQ_REGEX = /\[CQ:([a-zA-Z0-9_.-]+)(?:,([^\]]*))?\]/g;
export function toCQString(input: OutgoingMessage): string {
if (typeof input === 'string') return escapeCqText(input);
const normalized = normalizeMessage(input);
return typeof normalized === 'string'
? escapeCqText(normalized)
: segmentsToCQString(normalized);
if (typeof input === 'string') {
return escapeCqText(input);
}
const normalized = normalizeMessage(input);
return typeof normalized === 'string'
? escapeCqText(normalized)
: segmentsToCQString(normalized);
}
export function fromCQString(input: string) {
let current = chain();
let lastIndex = 0;
let current = chain();
let lastIndex = 0;
for (const match of input.matchAll(CQ_REGEX)) {
const index = match.index ?? 0;
if (index > lastIndex) {
const textValue = cqUnescape(input.slice(lastIndex, index));
if (textValue) current = current.text(textValue);
for (const match of input.matchAll(CQ_REGEX)) {
const index = match.index ?? 0;
if (index > lastIndex) {
const textValue = cqUnescape(input.slice(lastIndex, index));
if (textValue) {
current = current.text(textValue);
}
}
const segment = segmentFromCq(match[1] ?? '', parseCQParams(match[2] ?? ''));
if (segment) {
current = current.append(segment);
}
lastIndex = index + match[0].length;
}
const segment = segmentFromCq(match[1] ?? '', parseCQParams(match[2] ?? ''));
if (segment) current = current.append(segment);
lastIndex = index + match[0].length;
}
if (lastIndex < input.length) {
const textValue = cqUnescape(input.slice(lastIndex));
if (lastIndex < input.length) {
const textValue = cqUnescape(input.slice(lastIndex));
if (textValue) current = current.text(textValue);
}
if (textValue) {
current = current.text(textValue);
}
}
return current;
return current;
}
export function parseSegments(input: string): AnyMessageSegment[] {
return fromCQString(input).toSegments();
return fromCQString(input).toSegments();
}
function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
const params: Record<string, string> = {};
for (const pair of raw.split(',')) {
const eq = pair.indexOf('=');
if (eq <= 0) continue;
params[pair.slice(0, eq)] = cqUnescapeParam(pair.slice(eq + 1));
}
if (!raw) {
return params;
}
return params;
for (const pair of raw.split(',')) {
const eq = pair.indexOf('=');
if (eq <= 0) {
continue;
}
params[pair.slice(0, eq)] = cqUnescapeParam(pair.slice(eq + 1));
}
return params;
}
function cqUnescape(text: string): string {
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&amp;/g, '&');
return text.replace(/&#91;/g, '[').replace(/&#93;/g, ']').replace(/&amp;/g, '&');
}
function cqUnescapeParam(text: string): string {
return cqUnescape(text).replace(/&#44;/g, ',');
return cqUnescape(text).replace(/&#44;/g, ',');
}
function segmentFromCq(type: string, data: Record<string, string>): AnyMessageSegment | null {
switch (type) {
case 'text':
return segments.text(data.text ?? '');
case 'face': {
const options: Omit<FaceSegment['data'], 'id'> = {};
if (data.resultId !== undefined) options.resultId = data.resultId;
if (data.large !== undefined) {
if (data.large === 'true' || data.large === '1') options.large = true;
else if (data.large === 'false' || data.large === '0') options.large = false;
else throw new Error('face.large must be true, false, 1, or 0');
}
return segments.face(data.id ?? '0', options);
switch (type) {
case 'text':
return segments.text(data.text ?? '');
case 'face': {
const options: Omit<FaceSegment['data'], 'id'> = {};
if (data.resultId !== undefined) {
options.resultId = data.resultId;
}
if (data.large !== undefined) {
if (data.large === 'true' || data.large === '1') {
options.large = true;
} else if (data.large === 'false' || data.large === '0') {
options.large = false;
} else {
throw new Error('face.large must be true, false, 1, or 0');
}
}
return segments.face(data.id ?? '0', options);
}
case 'at':
if (data.qq === 'all') {
return segments.at('all');
}
{
const qq = Number(data.qq);
return Number.isFinite(qq) && qq > 0
? segments.at(qq, { name: data.name, uid: data.uid })
: segments.raw(type, data);
}
case 'reply':
return segments.reply(data.id ?? '0');
case 'image':
return segments.image(data.file ?? data.url ?? '', {
url: data.url,
type: data.type === 'flash' ? 'flash' : undefined,
summary: data.summary,
});
case 'record':
return segments.record(data.file ?? data.url ?? '', { url: data.url });
case 'video':
return segments.video(data.file ?? data.url ?? '', {
url: data.url,
thumb: data.thumb,
});
case 'json':
return segments.json(data.data ?? '');
case 'xml':
return segments.xml(data.data ?? '', { id: data.id });
case 'poke':
return segments.poke(data.type ?? data.id ?? '0', data.id);
case 'forward':
return segments.forward(data.id ?? data.res_id ?? data.forward_id ?? '');
default:
return segments.raw(type, data);
}
case 'at':
if (data.qq === 'all') return segments.at('all');
{
const qq = Number(data.qq);
return Number.isFinite(qq) && qq > 0
? segments.at(qq, { name: data.name, uid: data.uid })
: segments.raw(type, data);
}
case 'reply':
return segments.reply(data.id ?? '0');
case 'image':
return segments.image(data.file ?? data.url ?? '', {
url: data.url,
type: data.type === 'flash' ? 'flash' : undefined,
summary: data.summary,
});
case 'record':
return segments.record(data.file ?? data.url ?? '', { url: data.url });
case 'video':
return segments.video(data.file ?? data.url ?? '', { url: data.url, thumb: data.thumb });
case 'json':
return segments.json(data.data ?? '');
case 'xml':
return segments.xml(data.data ?? '', { id: data.id });
case 'poke':
return segments.poke(data.type ?? data.id ?? '0', data.id);
case 'forward':
return segments.forward(data.id ?? data.res_id ?? data.forward_id ?? '');
default:
return segments.raw(type, data);
}
}
+22 -22
View File
@@ -2,32 +2,32 @@ import { segments } from './segments';
export { MessageChain } from './chain';
export {
at,
atAll,
br,
chain,
contact,
face,
forward,
image,
json,
location,
music,
node,
normalizeMessage,
poke,
raw,
record,
reply,
share,
text,
video,
xml,
at,
atAll,
br,
chain,
contact,
face,
forward,
image,
json,
location,
music,
node,
normalizeMessage,
poke,
raw,
record,
reply,
share,
text,
video,
xml,
} from './chain';
export { escapeCqParam, escapeCqText } from './cq-format';
export { fromCQString, parseSegments, toCQString } from './cq';
export { segments };
export const message = {
...segments,
...segments,
};
+94 -77
View File
@@ -1,100 +1,117 @@
import type {
AtSegment,
ContactSegment,
FaceSegment,
ForwardSegment,
ImageSegment,
JsonObject,
JsonSegment,
LocationSegment,
MessageSegment,
MusicSegment,
NodeSegment,
OutgoingMessage,
PokeSegment,
RecordSegment,
ReplySegment,
ShareSegment,
TextSegment,
VideoSegment,
XmlSegment,
AtSegment,
ContactSegment,
FaceSegment,
ForwardSegment,
ImageSegment,
JsonObject,
JsonSegment,
LocationSegment,
MessageSegment,
MusicSegment,
NodeSegment,
OutgoingMessage,
PokeSegment,
RecordSegment,
ReplySegment,
ShareSegment,
TextSegment,
VideoSegment,
XmlSegment,
} from '../types/index';
function seg<TType extends string, TData extends Record<string, unknown>>(type: TType, data: TData): MessageSegment<TType, TData> {
return { type, data };
function seg<TType extends string, TData extends Record<string, unknown>>(
type: TType,
data: TData,
): MessageSegment<TType, TData> {
return { type, data };
}
export const segments = {
text(text: string): TextSegment {
return seg('text', { text });
},
text(text: string): TextSegment {
return seg('text', { text });
},
face(id: number | string, options: Omit<FaceSegment['data'], 'id'> = {}): FaceSegment {
return seg('face', { id: String(id), ...options });
},
face(id: number | string, options: Omit<FaceSegment['data'], 'id'> = {}): FaceSegment {
return seg('face', { id: String(id), ...options });
},
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): AtSegment {
const data: AtSegment['data'] = { qq: String(qq) };
if (options.name) data.name = options.name;
if (options.uid) data.uid = options.uid;
return seg('at', data);
},
at(qq: number | 'all', options: { name?: string; uid?: string } = {}): AtSegment {
const data: AtSegment['data'] = { qq: String(qq) };
reply(id: number | string): ReplySegment {
return seg('reply', { id: String(id) });
},
if (options.name) {
data.name = options.name;
}
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): ImageSegment {
return seg('image', { file, ...options });
},
if (options.uid) {
data.uid = options.uid;
}
record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): RecordSegment {
return seg('record', { file, ...options });
},
return seg('at', data);
},
video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): VideoSegment {
return seg('video', { file, ...options });
},
reply(id: number | string): ReplySegment {
return seg('reply', { id: String(id) });
},
json(data: string | JsonObject): JsonSegment {
return seg('json', { data: typeof data === 'string' ? data : JSON.stringify(data) });
},
image(file: string, options: Omit<ImageSegment['data'], 'file'> = {}): ImageSegment {
return seg('image', { file, ...options });
},
xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): XmlSegment {
return seg('xml', { data, ...options });
},
record(file: string, options: Omit<RecordSegment['data'], 'file'> = {}): RecordSegment {
return seg('record', { file, ...options });
},
poke(type: number | string, id?: number | string): PokeSegment {
const data: PokeSegment['data'] = { type };
if (id !== undefined) data.id = id;
return seg('poke', data);
},
video(file: string, options: Omit<VideoSegment['data'], 'file'> = {}): VideoSegment {
return seg('video', { file, ...options });
},
forward(id: string): ForwardSegment {
return seg('forward', { id, res_id: id, forward_id: id });
},
json(data: string | JsonObject): JsonSegment {
return seg('json', { data: typeof data === 'string' ? data : JSON.stringify(data) });
},
node(userId: number, nickname: string, content: OutgoingMessage): NodeSegment {
return seg('node', { user_id: userId, nickname, content });
},
xml(data: string, options: Omit<XmlSegment['data'], 'data'> = {}): XmlSegment {
return seg('xml', { data, ...options });
},
share(options: ShareSegment['data']): ShareSegment {
return seg('share', options);
},
poke(type: number | string, id?: number | string): PokeSegment {
const data: PokeSegment['data'] = { type };
music(options: MusicSegment['data']): MusicSegment {
return seg('music', options);
},
if (id !== undefined) {
data.id = id;
}
location(options: LocationSegment['data']): LocationSegment {
return seg('location', options);
},
return seg('poke', data);
},
contact(type: ContactSegment['data']['type'], id: number | string): ContactSegment {
return seg('contact', { type, id });
},
forward(id: string): ForwardSegment {
return seg('forward', { id, res_id: id, forward_id: id });
},
raw<TType extends string, TData extends JsonObject>(type: TType, data: TData): MessageSegment<TType, TData> {
return seg(type, data);
},
node(userId: number, nickname: string, content: OutgoingMessage): NodeSegment {
return seg('node', { user_id: userId, nickname, content });
},
share(options: ShareSegment['data']): ShareSegment {
return seg('share', options);
},
music(options: MusicSegment['data']): MusicSegment {
return seg('music', options);
},
location(options: LocationSegment['data']): LocationSegment {
return seg('location', options);
},
contact(type: ContactSegment['data']['type'], id: number | string): ContactSegment {
return seg('contact', { type, id });
},
raw<TType extends string, TData extends JsonObject>(
type: TType,
data: TData,
): MessageSegment<TType, TData> {
return seg(type, data);
},
};
+267 -265
View File
@@ -1,282 +1,284 @@
import type { JsonArray, JsonObject, JsonValue } from './json';
import type {
CreateGroupFileFolderParams,
DeleteFriendParams,
DeleteGroupFileFolderParams,
DeleteGroupFileParams,
DomainParams,
DownloadFileParams,
FetchCustomFaceParams,
SendCustomFaceParams,
FetchFaceEntityParams,
FetchSysFacesParams,
FetchEmojiLikeParams,
ForwardMessageParams,
FriendPokeParams,
GetEmojiLikesParams,
GetForwardMsgParams,
GetFriendMessageHistoryParams,
GetGroupFilesParams,
GetGroupFileUrlParams,
GetGroupHonorInfoParams,
GetGroupSystemMsgParams,
GetGroupInfoParams,
GetGroupListParams,
GetGroupMemberInfoParams,
GetGroupMemberListParams,
GetGroupMessageHistoryParams,
GetMediaParams,
GetOnlineClientsParams,
GetPrivateFileUrlParams,
GroupForwardMessageParams,
GroupIdParams,
GroupClassParams,
GroupCategoryTagNameParams,
GroupNoticeParams,
GroupPokeParams,
MarkGroupMsgAsReadParams,
MarkMsgAsReadParams,
MarkPrivateMsgAsReadParams,
MessageIdParams,
MoveGroupFileParams,
PrivateForwardMessageParams,
RenameGroupFileFolderParams,
SendGroupMsgParams,
SendLikeParams,
SendMsgParams,
SendPokeParams,
SendPrivateMsgParams,
SetFriendAddRequestParams,
SetFriendRemarkParams,
SetFriendsCategoryParams,
SetGroupAddRequestParams,
SetGroupAddOptionParams,
SetGroupAdminParams,
SetGroupBanParams,
SetGroupCardParams,
SetGroupKickParams,
SetGroupKickMembersParams,
SetGroupNameParams,
SetGroupRemarkParams,
SetGroupReactionParams,
SetGroupSpecialTitleParams,
SetGroupWholeBanParams,
SetMsgEmojiLikeParams,
SetOnlineStatusParams,
SetQqProfileParams,
UploadGroupFileParams,
UploadPrivateFileParams,
UserIdParams,
QuickOperationParams,
SetDiyOnlineStatusParams,
NcGetUserStatusParams,
GroupTodoParams,
GetAiCharactersParams,
GetCollectionListParams,
AiVoiceParams,
DeleteGroupFolderParams,
SendPacketParams,
SearchSysFacesParams,
CreateGroupFileFolderParams,
DeleteFriendParams,
DeleteGroupFileFolderParams,
DeleteGroupFileParams,
DomainParams,
DownloadFileParams,
FetchCustomFaceParams,
SendCustomFaceParams,
FetchFaceEntityParams,
FetchSysFacesParams,
FetchEmojiLikeParams,
ForwardMessageParams,
FriendPokeParams,
GetEmojiLikesParams,
GetForwardMsgParams,
GetFriendMessageHistoryParams,
GetGroupFilesParams,
GetGroupFileUrlParams,
GetGroupHonorInfoParams,
GetGroupSystemMsgParams,
GetGroupInfoParams,
GetGroupListParams,
GetGroupMemberInfoParams,
GetGroupMemberListParams,
GetGroupMessageHistoryParams,
GetMediaParams,
GetOnlineClientsParams,
GetPrivateFileUrlParams,
GroupForwardMessageParams,
GroupIdParams,
GroupClassParams,
GroupCategoryTagNameParams,
GroupNoticeParams,
GroupPokeParams,
MarkGroupMsgAsReadParams,
MarkMsgAsReadParams,
MarkPrivateMsgAsReadParams,
MessageIdParams,
MoveGroupFileParams,
PrivateForwardMessageParams,
RenameGroupFileFolderParams,
SendGroupMsgParams,
SendLikeParams,
SendMsgParams,
SendPokeParams,
SendPrivateMsgParams,
SetFriendAddRequestParams,
SetFriendRemarkParams,
SetFriendsCategoryParams,
SetGroupAddRequestParams,
SetGroupAddOptionParams,
SetGroupAdminParams,
SetGroupBanParams,
SetGroupCardParams,
SetGroupKickParams,
SetGroupKickMembersParams,
SetGroupNameParams,
SetGroupRemarkParams,
SetGroupReactionParams,
SetGroupSpecialTitleParams,
SetGroupWholeBanParams,
SetMsgEmojiLikeParams,
SetOnlineStatusParams,
SetQqProfileParams,
UploadGroupFileParams,
UploadPrivateFileParams,
UserIdParams,
QuickOperationParams,
SetDiyOnlineStatusParams,
NcGetUserStatusParams,
GroupTodoParams,
GetAiCharactersParams,
GetCollectionListParams,
AiVoiceParams,
DeleteGroupFolderParams,
SendPacketParams,
SearchSysFacesParams,
} from './params';
import type {
CapabilityInfo,
ClientKeyInfo,
CookieInfo,
CredentialsInfo,
CsrfInfo,
DownloadFileResult,
EmptyData,
ForwardMessageResult,
FriendCategoryResult,
FriendMessageHistory,
GroupAdminSettings,
GroupCategoryTagList,
GroupAtAllRemainInfo,
GroupFileSystemInfo,
GroupFileUrl,
GroupMessageHistory,
GroupNoticeInfo,
GroupTodoListItem,
LoginInfo,
MediaInfo,
OnlineClientsInfo,
PrivateFileUrl,
SendMessageResult,
StatusInfo,
UploadForwardResult,
UrlSafetyInfo,
VersionInfo,
AiCharacterCategory,
UserOnlineStatus,
SendGroupAiRecordResult,
CollectionListInfo,
SuperFaceInfo,
SystemFaceCatalogInfo,
SystemFaceInfo,
SystemFaceSearchInfo,
CapabilityInfo,
ClientKeyInfo,
CookieInfo,
CredentialsInfo,
CsrfInfo,
DownloadFileResult,
EmptyData,
ForwardMessageResult,
FriendCategoryResult,
FriendMessageHistory,
GroupAdminSettings,
GroupCategoryTagList,
GroupAtAllRemainInfo,
GroupFileSystemInfo,
GroupFileUrl,
GroupMessageHistory,
GroupNoticeInfo,
GroupTodoListItem,
LoginInfo,
MediaInfo,
OnlineClientsInfo,
PrivateFileUrl,
SendMessageResult,
StatusInfo,
UploadForwardResult,
UrlSafetyInfo,
VersionInfo,
AiCharacterCategory,
UserOnlineStatus,
SendGroupAiRecordResult,
CollectionListInfo,
SuperFaceInfo,
SystemFaceCatalogInfo,
SystemFaceInfo,
SystemFaceSearchInfo,
} from './results';
export type ActionData = JsonValue;
export interface SnowLumaActionMap {
get_login_info: { params: JsonObject; data: LoginInfo };
get_status: { params: JsonObject; data: StatusInfo };
get_version_info: { params: JsonObject; data: VersionInfo };
can_send_image: { params: JsonObject; data: CapabilityInfo };
can_send_record: { params: JsonObject; data: CapabilityInfo };
send_msg: { params: SendMsgParams; data: SendMessageResult };
send_private_msg: { params: SendPrivateMsgParams; data: SendMessageResult };
send_group_msg: { params: SendGroupMsgParams; data: SendMessageResult };
get_msg: { params: MessageIdParams; data: JsonObject };
delete_msg: { params: MessageIdParams; data: EmptyData };
get_friend_list: { params: JsonObject; data: JsonObject[] };
get_stranger_info: { params: UserIdParams; data: JsonObject };
delete_friend: { params: DeleteFriendParams; data: EmptyData };
get_group_list: { params: GetGroupListParams; data: JsonObject[] };
get_group_info: { params: GetGroupInfoParams; data: JsonObject };
get_group_member_list: { params: GetGroupMemberListParams; data: JsonObject[] };
get_group_member_info: { params: GetGroupMemberInfoParams; data: JsonObject };
get_group_honor_info: { params: GetGroupHonorInfoParams; data: JsonValue };
get_group_system_msg: { params: GetGroupSystemMsgParams; data: JsonObject[] };
set_group_kick: { params: SetGroupKickParams; data: EmptyData };
set_group_kick_members: { params: SetGroupKickMembersParams; data: EmptyData };
set_group_ban: { params: SetGroupBanParams; data: EmptyData };
set_group_whole_ban: { params: SetGroupWholeBanParams; data: EmptyData };
set_group_add_option: { params: SetGroupAddOptionParams; data: EmptyData };
set_group_search: { params: GroupIdParams; data: EmptyData };
get_group_admin_settings: { params: GroupIdParams; data: GroupAdminSettings };
get_group_tags: { params: GroupClassParams; data: GroupCategoryTagList };
add_group_tag: { params: GroupCategoryTagNameParams; data: EmptyData };
delete_group_tag: { params: GroupCategoryTagNameParams; data: EmptyData };
set_group_admin: { params: SetGroupAdminParams; data: EmptyData };
set_group_card: { params: SetGroupCardParams; data: EmptyData };
set_group_name: { params: SetGroupNameParams; data: EmptyData };
set_group_leave: { params: GroupIdParams; data: EmptyData };
set_group_special_title: { params: SetGroupSpecialTitleParams; data: EmptyData };
set_group_anonymous: { params: JsonObject; data: EmptyData };
set_group_anonymous_ban: { params: JsonObject; data: EmptyData };
set_group_portrait: { params: JsonObject; data: EmptyData };
upload_group_file: { params: UploadGroupFileParams; data: { file_id: string | null } };
upload_private_file: { params: UploadPrivateFileParams; data: { file_id: string | null } };
get_group_file_url: { params: GetGroupFileUrlParams; data: GroupFileUrl };
get_group_root_files: { params: GroupIdParams; data: JsonObject };
get_group_files_by_folder: { params: GetGroupFilesParams; data: JsonObject };
delete_group_file: { params: DeleteGroupFileParams; data: EmptyData };
move_group_file: { params: MoveGroupFileParams; data: EmptyData };
create_group_file_folder: { params: CreateGroupFileFolderParams; data: EmptyData };
delete_group_file_folder: { params: DeleteGroupFileFolderParams; data: EmptyData };
rename_group_file_folder: { params: RenameGroupFileFolderParams; data: EmptyData };
get_private_file_url: { params: GetPrivateFileUrlParams; data: PrivateFileUrl };
set_friend_add_request: { params: SetFriendAddRequestParams; data: EmptyData };
set_group_add_request: { params: SetGroupAddRequestParams; data: EmptyData };
send_like: { params: SendLikeParams; data: EmptyData };
friend_poke: { params: FriendPokeParams; data: EmptyData };
group_poke: { params: GroupPokeParams; data: EmptyData };
send_poke: { params: SendPokeParams; data: EmptyData };
set_essence_msg: { params: MessageIdParams; data: EmptyData };
delete_essence_msg: { params: MessageIdParams; data: EmptyData };
get_essence_msg_list: { params: GroupIdParams; data: JsonArray };
set_group_reaction: { params: SetGroupReactionParams; data: EmptyData };
get_group_msg_history: { params: GetGroupMessageHistoryParams; data: GroupMessageHistory };
get_friend_msg_history: { params: GetFriendMessageHistoryParams; data: FriendMessageHistory };
mark_group_msg_as_read: { params: MarkGroupMsgAsReadParams; data: EmptyData };
mark_private_msg_as_read: { params: MarkPrivateMsgAsReadParams; data: EmptyData };
mark_msg_as_read: { params: MarkMsgAsReadParams; data: EmptyData };
get_rkey: { params: JsonObject; data: JsonObject[] };
ocr_image: { params: JsonObject; data: JsonValue };
'.ocr_image': { params: JsonObject; data: JsonValue };
_send_group_notice: { params: GroupNoticeParams; data: EmptyData };
_get_group_notice: { params: GroupIdParams; data: GroupNoticeInfo[] };
_del_group_notice: { params: JsonObject; data: EmptyData };
upload_forward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
upload_foward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
send_forward_msg: { params: ForwardMessageParams; data: ForwardMessageResult };
send_group_forward_msg: { params: GroupForwardMessageParams; data: ForwardMessageResult };
send_private_forward_msg: { params: PrivateForwardMessageParams; data: ForwardMessageResult };
get_forward_msg: { params: GetForwardMsgParams; data: { messages: JsonObject[] } };
get_image: { params: GetMediaParams; data: MediaInfo };
get_record: { params: GetMediaParams; data: MediaInfo };
get_cookies: { params: DomainParams; data: CookieInfo };
get_csrf_token: { params: JsonObject; data: CsrfInfo };
get_credentials: { params: DomainParams; data: CredentialsInfo };
set_restart: { params: JsonObject; data: EmptyData };
clean_cache: { params: JsonObject; data: EmptyData };
'.handle_quick_operation': { params: QuickOperationParams; data: EmptyData };
set_friend_remark: { params: SetFriendRemarkParams; data: EmptyData };
set_group_remark: { params: SetGroupRemarkParams; data: EmptyData };
set_msg_emoji_like: { params: SetMsgEmojiLikeParams; data: EmptyData };
_mark_all_as_read: { params: JsonObject; data: EmptyData };
get_group_file_system_info: { params: GroupIdParams; data: GroupFileSystemInfo };
check_url_safely: { params: JsonObject; data: UrlSafetyInfo };
download_file: { params: DownloadFileParams; data: DownloadFileResult };
set_qq_profile: { params: SetQqProfileParams; data: EmptyData };
set_online_status: { params: SetOnlineStatusParams; data: EmptyData };
get_group_ignored_notifies: { params: JsonObject; data: JsonArray };
get_group_shut_list: { params: JsonObject; data: JsonArray };
forward_friend_single_msg: { params: JsonObject; data: JsonValue };
forward_group_single_msg: { params: JsonObject; data: JsonValue };
get_recent_contact: { params: JsonObject; data: JsonArray };
get_profile_like: { params: JsonObject; data: JsonObject };
fetch_custom_face: { params: FetchCustomFaceParams; data: string[] };
send_custom_face: { params: SendCustomFaceParams; data: SendMessageResult };
fetch_sys_faces: { params: FetchSysFacesParams; data: SystemFaceCatalogInfo };
fetch_face_entity: { params: FetchFaceEntityParams; data: SystemFaceInfo | null };
search_sys_faces: { params: SearchSysFacesParams; data: SystemFaceSearchInfo };
fetch_super_face_id: { params: FetchFaceEntityParams; data: SuperFaceInfo };
get_emoji_likes: { params: GetEmojiLikesParams; data: JsonObject };
fetch_emoji_like: { params: FetchEmojiLikeParams; data: JsonObject };
get_friends_with_category: { params: JsonObject; data: FriendCategoryResult[] };
set_friends_category: { params: SetFriendsCategoryParams; data: EmptyData };
get_online_clients: { params: GetOnlineClientsParams; data: OnlineClientsInfo };
_get_model_show: { params: JsonObject; data: { variants: JsonArray } };
_set_model_show: { params: JsonObject; data: EmptyData };
'.get_word_slices': { params: JsonObject; data: JsonValue };
get_group_at_all_remain: { params: JsonObject; data: GroupAtAllRemainInfo };
get_unidirectional_friend_list: { params: JsonObject; data: JsonArray };
set_self_longnick: { params: JsonObject; data: EmptyData };
get_collection_list: { params: GetCollectionListParams; data: CollectionListInfo };
create_collection: { params: JsonObject; data: JsonValue };
set_qq_avatar: { params: JsonObject; data: EmptyData };
set_input_status: { params: JsonObject; data: EmptyData };
translate_en2zh: { params: JsonObject; data: JsonValue };
get_clientkey: { params: JsonObject; data: ClientKeyInfo };
get_mini_app_ark: { params: JsonObject; data: JsonValue };
click_inline_keyboard_button: { params: JsonObject; data: JsonValue };
set_group_sign: { params: JsonObject; data: EmptyData };
send_group_sign: { params: JsonObject; data: EmptyData };
get_group_info_ex: { params: GetGroupInfoParams; data: JsonObject };
get_group_detail_info: { params: GetGroupInfoParams; data: JsonObject };
trans_group_file: { params: JsonObject; data: JsonValue };
rename_group_file: { params: JsonObject; data: JsonValue };
get_file: { params: GetMediaParams; data: JsonValue };
'.send_packet': { params: SendPacketParams; data: string };
get_login_info: { params: JsonObject; data: LoginInfo };
get_status: { params: JsonObject; data: StatusInfo };
get_version_info: { params: JsonObject; data: VersionInfo };
can_send_image: { params: JsonObject; data: CapabilityInfo };
can_send_record: { params: JsonObject; data: CapabilityInfo };
send_msg: { params: SendMsgParams; data: SendMessageResult };
send_private_msg: { params: SendPrivateMsgParams; data: SendMessageResult };
send_group_msg: { params: SendGroupMsgParams; data: SendMessageResult };
get_msg: { params: MessageIdParams; data: JsonObject };
delete_msg: { params: MessageIdParams; data: EmptyData };
get_friend_list: { params: JsonObject; data: JsonObject[] };
get_stranger_info: { params: UserIdParams; data: JsonObject };
delete_friend: { params: DeleteFriendParams; data: EmptyData };
get_group_list: { params: GetGroupListParams; data: JsonObject[] };
get_group_info: { params: GetGroupInfoParams; data: JsonObject };
get_group_member_list: { params: GetGroupMemberListParams; data: JsonObject[] };
get_group_member_info: { params: GetGroupMemberInfoParams; data: JsonObject };
get_group_honor_info: { params: GetGroupHonorInfoParams; data: JsonValue };
get_group_system_msg: { params: GetGroupSystemMsgParams; data: JsonObject[] };
set_group_kick: { params: SetGroupKickParams; data: EmptyData };
set_group_kick_members: { params: SetGroupKickMembersParams; data: EmptyData };
set_group_ban: { params: SetGroupBanParams; data: EmptyData };
set_group_whole_ban: { params: SetGroupWholeBanParams; data: EmptyData };
set_group_add_option: { params: SetGroupAddOptionParams; data: EmptyData };
set_group_search: { params: GroupIdParams; data: EmptyData };
get_group_admin_settings: { params: GroupIdParams; data: GroupAdminSettings };
get_group_tags: { params: GroupClassParams; data: GroupCategoryTagList };
add_group_tag: { params: GroupCategoryTagNameParams; data: EmptyData };
delete_group_tag: { params: GroupCategoryTagNameParams; data: EmptyData };
set_group_admin: { params: SetGroupAdminParams; data: EmptyData };
set_group_card: { params: SetGroupCardParams; data: EmptyData };
set_group_name: { params: SetGroupNameParams; data: EmptyData };
set_group_leave: { params: GroupIdParams; data: EmptyData };
set_group_special_title: { params: SetGroupSpecialTitleParams; data: EmptyData };
set_group_anonymous: { params: JsonObject; data: EmptyData };
set_group_anonymous_ban: { params: JsonObject; data: EmptyData };
set_group_portrait: { params: JsonObject; data: EmptyData };
upload_group_file: { params: UploadGroupFileParams; data: { file_id: string | null } };
upload_private_file: { params: UploadPrivateFileParams; data: { file_id: string | null } };
get_group_file_url: { params: GetGroupFileUrlParams; data: GroupFileUrl };
get_group_root_files: { params: GroupIdParams; data: JsonObject };
get_group_files_by_folder: { params: GetGroupFilesParams; data: JsonObject };
delete_group_file: { params: DeleteGroupFileParams; data: EmptyData };
move_group_file: { params: MoveGroupFileParams; data: EmptyData };
create_group_file_folder: { params: CreateGroupFileFolderParams; data: EmptyData };
delete_group_file_folder: { params: DeleteGroupFileFolderParams; data: EmptyData };
rename_group_file_folder: { params: RenameGroupFileFolderParams; data: EmptyData };
get_private_file_url: { params: GetPrivateFileUrlParams; data: PrivateFileUrl };
set_friend_add_request: { params: SetFriendAddRequestParams; data: EmptyData };
set_group_add_request: { params: SetGroupAddRequestParams; data: EmptyData };
send_like: { params: SendLikeParams; data: EmptyData };
friend_poke: { params: FriendPokeParams; data: EmptyData };
group_poke: { params: GroupPokeParams; data: EmptyData };
send_poke: { params: SendPokeParams; data: EmptyData };
set_essence_msg: { params: MessageIdParams; data: EmptyData };
delete_essence_msg: { params: MessageIdParams; data: EmptyData };
get_essence_msg_list: { params: GroupIdParams; data: JsonArray };
set_group_reaction: { params: SetGroupReactionParams; data: EmptyData };
get_group_msg_history: { params: GetGroupMessageHistoryParams; data: GroupMessageHistory };
get_friend_msg_history: { params: GetFriendMessageHistoryParams; data: FriendMessageHistory };
mark_group_msg_as_read: { params: MarkGroupMsgAsReadParams; data: EmptyData };
mark_private_msg_as_read: { params: MarkPrivateMsgAsReadParams; data: EmptyData };
mark_msg_as_read: { params: MarkMsgAsReadParams; data: EmptyData };
get_rkey: { params: JsonObject; data: JsonObject[] };
ocr_image: { params: JsonObject; data: JsonValue };
'.ocr_image': { params: JsonObject; data: JsonValue };
_send_group_notice: { params: GroupNoticeParams; data: EmptyData };
_get_group_notice: { params: GroupIdParams; data: GroupNoticeInfo[] };
_del_group_notice: { params: JsonObject; data: EmptyData };
upload_forward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
upload_foward_msg: { params: ForwardMessageParams; data: UploadForwardResult };
send_forward_msg: { params: ForwardMessageParams; data: ForwardMessageResult };
send_group_forward_msg: { params: GroupForwardMessageParams; data: ForwardMessageResult };
send_private_forward_msg: { params: PrivateForwardMessageParams; data: ForwardMessageResult };
get_forward_msg: { params: GetForwardMsgParams; data: { messages: JsonObject[] } };
get_image: { params: GetMediaParams; data: MediaInfo };
get_record: { params: GetMediaParams; data: MediaInfo };
get_cookies: { params: DomainParams; data: CookieInfo };
get_csrf_token: { params: JsonObject; data: CsrfInfo };
get_credentials: { params: DomainParams; data: CredentialsInfo };
set_restart: { params: JsonObject; data: EmptyData };
clean_cache: { params: JsonObject; data: EmptyData };
'.handle_quick_operation': { params: QuickOperationParams; data: EmptyData };
set_friend_remark: { params: SetFriendRemarkParams; data: EmptyData };
set_group_remark: { params: SetGroupRemarkParams; data: EmptyData };
set_msg_emoji_like: { params: SetMsgEmojiLikeParams; data: EmptyData };
_mark_all_as_read: { params: JsonObject; data: EmptyData };
get_group_file_system_info: { params: GroupIdParams; data: GroupFileSystemInfo };
check_url_safely: { params: JsonObject; data: UrlSafetyInfo };
download_file: { params: DownloadFileParams; data: DownloadFileResult };
set_qq_profile: { params: SetQqProfileParams; data: EmptyData };
set_online_status: { params: SetOnlineStatusParams; data: EmptyData };
get_group_ignored_notifies: { params: JsonObject; data: JsonArray };
get_group_shut_list: { params: JsonObject; data: JsonArray };
forward_friend_single_msg: { params: JsonObject; data: JsonValue };
forward_group_single_msg: { params: JsonObject; data: JsonValue };
get_recent_contact: { params: JsonObject; data: JsonArray };
get_profile_like: { params: JsonObject; data: JsonObject };
fetch_custom_face: { params: FetchCustomFaceParams; data: string[] };
send_custom_face: { params: SendCustomFaceParams; data: SendMessageResult };
fetch_sys_faces: { params: FetchSysFacesParams; data: SystemFaceCatalogInfo };
fetch_face_entity: { params: FetchFaceEntityParams; data: SystemFaceInfo | null };
search_sys_faces: { params: SearchSysFacesParams; data: SystemFaceSearchInfo };
fetch_super_face_id: { params: FetchFaceEntityParams; data: SuperFaceInfo };
get_emoji_likes: { params: GetEmojiLikesParams; data: JsonObject };
fetch_emoji_like: { params: FetchEmojiLikeParams; data: JsonObject };
get_friends_with_category: { params: JsonObject; data: FriendCategoryResult[] };
set_friends_category: { params: SetFriendsCategoryParams; data: EmptyData };
get_online_clients: { params: GetOnlineClientsParams; data: OnlineClientsInfo };
_get_model_show: { params: JsonObject; data: { variants: JsonArray } };
_set_model_show: { params: JsonObject; data: EmptyData };
'.get_word_slices': { params: JsonObject; data: JsonValue };
get_group_at_all_remain: { params: JsonObject; data: GroupAtAllRemainInfo };
get_unidirectional_friend_list: { params: JsonObject; data: JsonArray };
set_self_longnick: { params: JsonObject; data: EmptyData };
get_collection_list: { params: GetCollectionListParams; data: CollectionListInfo };
create_collection: { params: JsonObject; data: JsonValue };
set_qq_avatar: { params: JsonObject; data: EmptyData };
set_input_status: { params: JsonObject; data: EmptyData };
translate_en2zh: { params: JsonObject; data: JsonValue };
get_clientkey: { params: JsonObject; data: ClientKeyInfo };
get_mini_app_ark: { params: JsonObject; data: JsonValue };
click_inline_keyboard_button: { params: JsonObject; data: JsonValue };
set_group_sign: { params: JsonObject; data: EmptyData };
send_group_sign: { params: JsonObject; data: EmptyData };
get_group_info_ex: { params: GetGroupInfoParams; data: JsonObject };
get_group_detail_info: { params: GetGroupInfoParams; data: JsonObject };
trans_group_file: { params: JsonObject; data: JsonValue };
rename_group_file: { params: JsonObject; data: JsonValue };
get_file: { params: GetMediaParams; data: JsonValue };
'.send_packet': { params: SendPacketParams; data: string };
// — napcat-parity extensions (Tier 1 + Tier 2) —
send_packet: { params: SendPacketParams; data: string };
bot_exit: { params: JsonObject; data: EmptyData };
nc_get_packet_status: { params: JsonObject; data: JsonValue };
nc_get_rkey: { params: JsonObject; data: JsonObject[] };
nc_get_user_status: { params: NcGetUserStatusParams; data: UserOnlineStatus };
get_group_ignore_add_request: { params: JsonObject; data: JsonArray };
delete_group_folder: { params: DeleteGroupFolderParams; data: EmptyData };
get_group_todo_list: { params: GroupIdParams; data: GroupTodoListItem[] };
set_group_todo: { params: GroupTodoParams; data: EmptyData };
complete_group_todo: { params: GroupTodoParams; data: EmptyData };
cancel_group_todo: { params: GroupTodoParams; data: EmptyData };
// — napcat-parity extensions (Tier 1 + Tier 2) —
send_packet: { params: SendPacketParams; data: string };
bot_exit: { params: JsonObject; data: EmptyData };
nc_get_packet_status: { params: JsonObject; data: JsonValue };
nc_get_rkey: { params: JsonObject; data: JsonObject[] };
nc_get_user_status: { params: NcGetUserStatusParams; data: UserOnlineStatus };
get_group_ignore_add_request: { params: JsonObject; data: JsonArray };
delete_group_folder: { params: DeleteGroupFolderParams; data: EmptyData };
get_group_todo_list: { params: GroupIdParams; data: GroupTodoListItem[] };
set_group_todo: { params: GroupTodoParams; data: EmptyData };
complete_group_todo: { params: GroupTodoParams; data: EmptyData };
cancel_group_todo: { params: GroupTodoParams; data: EmptyData };
// — Tier 3: DIY status —
set_diy_online_status: { params: SetDiyOnlineStatusParams; data: EmptyData };
// — Tier 3: DIY status —
set_diy_online_status: { params: SetDiyOnlineStatusParams; data: EmptyData };
// — AI voice trio —
get_ai_characters: { params: GetAiCharactersParams; data: AiCharacterCategory[] };
get_ai_record: { params: AiVoiceParams; data: string };
send_group_ai_record: { params: AiVoiceParams; data: SendGroupAiRecordResult };
// — AI voice trio —
get_ai_characters: { params: GetAiCharactersParams; data: AiCharacterCategory[] };
get_ai_record: { params: AiVoiceParams; data: string };
send_group_ai_record: { params: AiVoiceParams; data: SendGroupAiRecordResult };
}
export type SnowLumaAction = keyof SnowLumaActionMap | (string & {});
export type ActionParams<TAction extends string> =
TAction extends keyof SnowLumaActionMap ? SnowLumaActionMap[TAction]['params'] : JsonObject;
export type ActionParams<TAction extends string> = TAction extends keyof SnowLumaActionMap
? SnowLumaActionMap[TAction]['params']
: JsonObject;
export type ActionResult<TAction extends string> =
TAction extends keyof SnowLumaActionMap ? SnowLumaActionMap[TAction]['data'] : ActionData;
export type ActionResult<TAction extends string> = TAction extends keyof SnowLumaActionMap
? SnowLumaActionMap[TAction]['data']
: ActionData;
+48 -52
View File
@@ -1,84 +1,80 @@
import type { JsonObject, JsonValue } from './json';
export interface OneBotBaseEvent extends JsonObject {
time: number;
self_id: number;
post_type: string;
time: number;
self_id: number;
post_type: string;
}
export interface OneBotSender extends JsonObject {
user_id: number;
nickname: string;
sex?: string;
age?: number;
card?: string;
role?: string;
user_id: number;
nickname: string;
sex?: string;
age?: number;
card?: string;
role?: string;
}
export interface OneBotPrivateMessageEvent extends OneBotBaseEvent {
post_type: 'message' | 'message_sent';
message_type: 'private';
sub_type: string;
message_id: number;
message_seq?: number;
user_id: number;
message: JsonValue;
raw_message: string;
font: number;
sender: OneBotSender;
post_type: 'message' | 'message_sent';
message_type: 'private';
sub_type: string;
message_id: number;
message_seq?: number;
user_id: number;
message: JsonValue;
raw_message: string;
font: number;
sender: OneBotSender;
}
export interface OneBotGroupMessageEvent extends OneBotBaseEvent {
post_type: 'message' | 'message_sent';
message_type: 'group';
sub_type: string;
message_id: number;
message_seq?: number;
group_id: number;
user_id: number;
message: JsonValue;
raw_message: string;
font: number;
sender: OneBotSender;
anonymous?: JsonValue;
post_type: 'message' | 'message_sent';
message_type: 'group';
sub_type: string;
message_id: number;
message_seq?: number;
group_id: number;
user_id: number;
message: JsonValue;
raw_message: string;
font: number;
sender: OneBotSender;
anonymous?: JsonValue;
}
export type OneBotMessageEvent = OneBotPrivateMessageEvent | OneBotGroupMessageEvent;
export interface OneBotNoticeEvent extends OneBotBaseEvent {
post_type: 'notice';
notice_type: string;
post_type: 'notice';
notice_type: string;
}
export type BotStatusSubType = 'online' | 'offline';
/** Bridge session edge. Not KickNT `bot_offline`. */
export interface OneBotBotStatusEvent extends OneBotNoticeEvent {
notice_type: 'bot_status';
sub_type: BotStatusSubType;
user_id: number;
notice_type: 'bot_status';
sub_type: BotStatusSubType;
user_id: number;
}
export interface OneBotRequestEvent extends OneBotBaseEvent {
post_type: 'request';
request_type: string;
flag: string;
sub_type?: string;
group_id?: number;
user_id?: number;
/** Invitee QQ number on `request.group` / `invite`. */
invited_id?: number;
comment?: string;
post_type: 'request';
request_type: string;
flag: string;
sub_type?: string;
group_id?: number;
user_id?: number;
/** Invitee QQ number on `request.group` / `invite`. */
invited_id?: number;
comment?: string;
}
export interface OneBotMetaEvent extends OneBotBaseEvent {
post_type: 'meta_event';
meta_event_type: string;
post_type: 'meta_event';
meta_event_type: string;
}
export type SnowLumaEvent =
| OneBotMessageEvent
| OneBotNoticeEvent
| OneBotRequestEvent
| OneBotMetaEvent
| OneBotBaseEvent;
OneBotMessageEvent | OneBotNoticeEvent | OneBotRequestEvent | OneBotMetaEvent | OneBotBaseEvent;
+19 -19
View File
@@ -2,23 +2,23 @@ export type JsonPrimitive = string | number | boolean | null;
export type JsonValue = JsonPrimitive | JsonObject | JsonArray;
export interface JsonObject {
[key: string]: JsonValue | undefined;
[key: string]: JsonValue | undefined;
}
export type JsonArray = JsonValue[];
export interface ApiResponse<TData = JsonValue> {
status: 'ok' | 'failed';
retcode: number;
data: TData;
echo?: JsonValue;
wording?: string;
status: 'ok' | 'failed';
retcode: number;
data: TData;
echo?: JsonValue;
wording?: string;
}
export interface OneBotRequest<TParams extends JsonObject = JsonObject> {
action: string;
params?: TParams;
echo?: JsonValue;
action: string;
params?: TParams;
echo?: JsonValue;
}
export type WsRole = 'Api' | 'Event' | 'Universal';
@@ -26,18 +26,18 @@ export type MessageFormat = 'array' | 'string';
/** Per-request controls shared by HTTP and WebSocket clients. */
export interface RequestOptions {
/** Echo value used to correlate OneBot request and response packets. */
echo?: JsonValue;
/** Override the client's default timeout for this request. Set to 0 to disable timeout. */
timeoutMs?: number;
/** Cancels the request before a SnowLuma response arrives. */
signal?: AbortSignal;
/** Echo value used to correlate OneBot request and response packets. */
echo?: JsonValue;
/** Override the client's default timeout for this request. Set to 0 to disable timeout. */
timeoutMs?: number;
/** Cancels the request before a SnowLuma response arrives. */
signal?: AbortSignal;
}
/** Shared options accepted by concrete SnowLuma clients. */
export interface SnowLumaClientOptions {
/** Access token configured in SnowLuma's OneBot settings. */
accessToken?: string;
/** Default timeout for API calls in milliseconds. Defaults to 30000. */
requestTimeoutMs?: number;
/** Access token configured in SnowLuma's OneBot settings. */
accessToken?: string;
/** Default timeout for API calls in milliseconds. Defaults to 30000. */
requestTimeoutMs?: number;
}
+86 -62
View File
@@ -1,85 +1,109 @@
import type { JsonObject } from './json';
export interface MessageSegment<
TType extends string = string,
TData extends Record<string, unknown> = JsonObject,
TType extends string = string,
TData extends Record<string, unknown> = JsonObject,
> {
type: TType;
data: TData;
type: TType;
data: TData;
}
export type TextSegment = MessageSegment<'text', { text: string }>;
export type FaceSegment = MessageSegment<'face', { id: string; large?: boolean; resultId?: string }>;
export type FaceSegment = MessageSegment<
'face',
{ id: string; large?: boolean; resultId?: string }
>;
export type AtSegment = MessageSegment<'at', { qq: string; name?: string; uid?: string }>;
export type ReplySegment = MessageSegment<'reply', { id: string }>;
export type ImageSegment = MessageSegment<'image', {
file: string;
type?: 'flash';
subType?: number;
summary?: string;
url?: string;
}>;
export type ImageSegment = MessageSegment<
'image',
{
file: string;
type?: 'flash';
subType?: number;
summary?: string;
url?: string;
}
>;
export type RecordSegment = MessageSegment<'record', { file: string; url?: string }>;
export type VideoSegment = MessageSegment<'video', { file: string; url?: string; thumb?: string }>;
export type JsonSegment = MessageSegment<'json', { data: string }>;
export type XmlSegment = MessageSegment<'xml', { data: string; id?: string }>;
export type PokeSegment = MessageSegment<'poke', { type: string | number; id?: string | number }>;
export type ForwardSegment = MessageSegment<'forward', { id: string; res_id?: string; forward_id?: string }>;
export type NodeSegment = MessageSegment<'node', {
user_id: number;
nickname: string;
content: OutgoingMessage;
}>;
export type ShareSegment = MessageSegment<'share', {
url: string;
title: string;
content?: string;
image?: string;
}>;
export type MusicSegment = MessageSegment<'music', {
type: string;
id?: string;
url?: string;
audio?: string;
title?: string;
image?: string;
content?: string;
}>;
export type LocationSegment = MessageSegment<'location', {
lat: string | number;
lon: string | number;
title?: string;
content?: string;
}>;
export type ContactSegment = MessageSegment<'contact', {
type: 'qq' | 'group' | string;
id: string | number;
}>;
export type ForwardSegment = MessageSegment<
'forward',
{ id: string; res_id?: string; forward_id?: string }
>;
export type NodeSegment = MessageSegment<
'node',
{
user_id: number;
nickname: string;
content: OutgoingMessage;
}
>;
export type ShareSegment = MessageSegment<
'share',
{
url: string;
title: string;
content?: string;
image?: string;
}
>;
export type MusicSegment = MessageSegment<
'music',
{
type: string;
id?: string;
url?: string;
audio?: string;
title?: string;
image?: string;
content?: string;
}
>;
export type LocationSegment = MessageSegment<
'location',
{
lat: string | number;
lon: string | number;
title?: string;
content?: string;
}
>;
export type ContactSegment = MessageSegment<
'contact',
{
type: 'qq' | 'group' | string;
id: string | number;
}
>;
export type KnownMessageSegment =
| TextSegment
| FaceSegment
| AtSegment
| ReplySegment
| ImageSegment
| RecordSegment
| VideoSegment
| JsonSegment
| XmlSegment
| PokeSegment
| ForwardSegment
| NodeSegment
| ShareSegment
| MusicSegment
| LocationSegment
| ContactSegment;
| TextSegment
| FaceSegment
| AtSegment
| ReplySegment
| ImageSegment
| RecordSegment
| VideoSegment
| JsonSegment
| XmlSegment
| PokeSegment
| ForwardSegment
| NodeSegment
| ShareSegment
| MusicSegment
| LocationSegment
| ContactSegment;
export type AnyMessageSegment = KnownMessageSegment | MessageSegment;
export interface MessageChainLike {
readonly length: number;
toSegments(): AnyMessageSegment[];
toJSON(): AnyMessageSegment[];
readonly length: number;
toSegments(): AnyMessageSegment[];
toJSON(): AnyMessageSegment[];
}
export type OutgoingMessage = string | MessageChainLike | AnyMessageSegment | AnyMessageSegment[];
+174 -173
View File
@@ -1,47 +1,47 @@
import type { JsonObject, JsonValue } from './json';
export interface SendMsgParams extends JsonObject {
message_type?: 'private' | 'group' | string;
user_id?: number;
group_id?: number;
message: JsonValue;
auto_escape?: boolean;
message_type?: 'private' | 'group' | string;
user_id?: number;
group_id?: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface SendPrivateMsgParams extends JsonObject {
user_id: number;
message: JsonValue;
auto_escape?: boolean;
user_id: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface SendGroupMsgParams extends JsonObject {
group_id: number;
message: JsonValue;
auto_escape?: boolean;
group_id: number;
message: JsonValue;
auto_escape?: boolean;
}
export interface MessageIdParams extends JsonObject {
message_id: number;
message_id: number;
}
export interface GroupIdParams extends JsonObject {
group_id: number;
group_id: number;
}
export interface GroupClassParams extends JsonObject {
group_class: number;
group_class: number;
}
export interface GroupCategoryTagNameParams extends GroupClassParams {
name: string;
name: string;
}
export interface UserIdParams extends JsonObject {
user_id: number;
user_id: number;
}
export interface NoCacheParams extends JsonObject {
no_cache?: boolean;
no_cache?: boolean;
}
export interface GetOnlineClientsParams extends NoCacheParams {}
@@ -49,336 +49,337 @@ export interface GetOnlineClientsParams extends NoCacheParams {}
export interface GetGroupListParams extends NoCacheParams {}
export interface GetGroupInfoParams extends GroupIdParams {
no_cache?: boolean;
no_cache?: boolean;
}
export interface GetGroupMemberListParams extends GroupIdParams {
no_cache?: boolean;
no_cache?: boolean;
}
export interface GetGroupMemberInfoParams extends GroupIdParams {
user_id: number;
no_cache?: boolean;
user_id: number;
no_cache?: boolean;
}
export interface GetGroupHonorInfoParams extends GroupIdParams {
type?: 'talkative' | 'performer' | 'legend' | 'strong_newbie' | 'emotion' | 'all' | string;
type?: 'talkative' | 'performer' | 'legend' | 'strong_newbie' | 'emotion' | 'all' | string;
}
export interface GetGroupSystemMsgParams extends JsonObject {
group_id?: number;
only_pending?: boolean;
count?: number;
group_id?: number;
only_pending?: boolean;
count?: number;
}
export interface DeleteFriendParams extends UserIdParams {
block?: boolean;
block?: boolean;
}
export interface SetGroupKickParams extends GroupIdParams {
user_id: number;
reject_add_request?: boolean;
user_id: number;
reject_add_request?: boolean;
}
export interface SetGroupKickMembersParams extends GroupIdParams {
user_id: number[];
reject_add_request?: boolean;
user_id: number[];
reject_add_request?: boolean;
}
export interface SetGroupBanParams extends GroupIdParams {
user_id: number;
duration?: number;
user_id: number;
duration?: number;
}
export interface SetGroupWholeBanParams extends GroupIdParams {
enable?: boolean;
enable?: boolean;
}
export interface SetGroupAddOptionParams extends GroupIdParams {
add_type: number;
group_question?: string;
group_answer?: string;
add_type: number;
group_question?: string;
group_answer?: string;
}
export interface SetGroupAdminParams extends GroupIdParams {
user_id: number;
enable?: boolean;
user_id: number;
enable?: boolean;
}
export interface SetGroupCardParams extends GroupIdParams {
user_id: number;
card?: string;
user_id: number;
card?: string;
}
export interface SetGroupNameParams extends GroupIdParams {
group_name: string;
group_name: string;
}
export interface SetGroupSpecialTitleParams extends GroupIdParams {
user_id: number;
special_title?: string;
user_id: number;
special_title?: string;
}
export type SetFriendsCategoryParams = JsonObject & (
| { uin: number; categoryId: number; categoryName?: never }
| { uin: number; categoryId?: never; categoryName: string }
);
export type SetFriendsCategoryParams = JsonObject &
(
| { uin: number; categoryId: number; categoryName?: never }
| { uin: number; categoryId?: never; categoryName: string }
);
export interface UploadGroupFileParams extends GroupIdParams {
file: string;
name?: string;
folder?: string;
folder_id?: string;
upload_file?: boolean;
file: string;
name?: string;
folder?: string;
folder_id?: string;
upload_file?: boolean;
}
export interface UploadPrivateFileParams extends UserIdParams {
file: string;
name?: string;
upload_file?: boolean;
file: string;
name?: string;
upload_file?: boolean;
}
export interface GetGroupFileUrlParams extends GroupIdParams {
file_id: string;
busid?: number;
file_id: string;
busid?: number;
}
export interface GetGroupFilesParams extends GroupIdParams {
folder_id?: string;
folder?: string;
folder_id?: string;
folder?: string;
}
export interface DeleteGroupFileParams extends GroupIdParams {
file_id: string;
file_id: string;
}
export interface MoveGroupFileParams extends GroupIdParams {
file_id: string;
parent_directory: string;
target_directory: string;
file_id: string;
parent_directory: string;
target_directory: string;
}
export interface CreateGroupFileFolderParams extends GroupIdParams {
name: string;
parent_id?: string;
name: string;
parent_id?: string;
}
export interface DeleteGroupFileFolderParams extends GroupIdParams {
folder_id: string;
folder_id: string;
}
export interface RenameGroupFileFolderParams extends GroupIdParams {
folder_id: string;
new_folder_name?: string;
name?: string;
folder_id: string;
new_folder_name?: string;
name?: string;
}
export interface GetPrivateFileUrlParams extends UserIdParams {
file_id: string;
file_hash: string;
file_id: string;
file_hash: string;
}
export interface SetFriendAddRequestParams extends JsonObject {
flag: string;
approve?: boolean;
flag: string;
approve?: boolean;
}
export interface SetGroupAddRequestParams extends JsonObject {
flag: string;
sub_type?: string;
type?: string;
approve?: boolean;
reason?: string;
flag: string;
sub_type?: string;
type?: string;
approve?: boolean;
reason?: string;
}
export interface SendLikeParams extends UserIdParams {
times?: number;
times?: number;
}
export interface FriendPokeParams extends UserIdParams {
target_id?: number;
target_id?: number;
}
export interface GroupPokeParams extends GroupIdParams {
user_id: number;
user_id: number;
}
export interface SendPokeParams extends UserIdParams {
group_id?: number;
group_id?: number;
}
export interface SetGroupReactionParams extends JsonObject {
message_id: number;
code: string;
group_id?: number;
is_set?: boolean;
message_id: number;
code: string;
group_id?: number;
is_set?: boolean;
}
export interface GetMessageHistoryParams extends JsonObject {
message_id?: number;
count?: number;
/** With a non-zero message_id, include the anchor and query older (`true`) or newer (`false`) messages. Defaults to `true`. */
reverse_order?: boolean;
message_id?: number;
count?: number;
/** With a non-zero message_id, include the anchor and query older (`true`) or newer (`false`) messages. Defaults to `true`. */
reverse_order?: boolean;
}
export interface GetGroupMessageHistoryParams extends GroupIdParams, GetMessageHistoryParams {}
export interface GetFriendMessageHistoryParams extends UserIdParams, GetMessageHistoryParams {}
export interface MarkGroupMsgAsReadParams extends JsonObject {
message_id: number;
group_id?: number;
message_id: number;
group_id?: number;
}
export interface MarkPrivateMsgAsReadParams extends JsonObject {
message_id: number;
user_id?: number;
message_id: number;
user_id?: number;
}
export interface MarkMsgAsReadParams extends JsonObject {
message_id: number;
target_id?: number;
message_id: number;
target_id?: number;
}
export interface GroupNoticeParams extends GroupIdParams {
content: string;
image?: string;
pinned?: 0 | 1;
/** Compatibility field: 1=regular announcement, 20=new-member announcement. */
type?: 1 | 20;
send_to_new_members?: boolean;
is_show_edit_card?: 0 | 1;
/** QQ's raw inverted field: 0=show popup, 1=do not show popup. */
tip_window_type?: 0 | 1;
confirm_required?: 0 | 1;
content: string;
image?: string;
pinned?: 0 | 1;
/** Compatibility field: 1=regular announcement, 20=new-member announcement. */
type?: 1 | 20;
send_to_new_members?: boolean;
is_show_edit_card?: 0 | 1;
/** QQ's raw inverted field: 0=show popup, 1=do not show popup. */
tip_window_type?: 0 | 1;
confirm_required?: 0 | 1;
}
export interface ForwardPreviewParams {
// Header above the preview ("群聊的聊天记录"). Default: "聊天记录" / nicks.
source?: string;
// Per-line preview entries ("nick: text"). Default: derived from nodes.
news?: Array<{ text: string }>;
// Grey footer ("查看 N 条转发消息"). Default: "查看 N 条转发消息".
summary?: string;
// Chat-list brief ("[聊天记录]"). Default: "[聊天记录]".
prompt?: string;
// Header above the preview ("群聊的聊天记录"). Default: "聊天记录" / nicks.
source?: string;
// Per-line preview entries ("nick: text"). Default: derived from nodes.
news?: Array<{ text: string }>;
// Grey footer ("查看 N 条转发消息"). Default: "查看 N 条转发消息".
summary?: string;
// Chat-list brief ("[聊天记录]"). Default: "[聊天记录]".
prompt?: string;
}
export interface ForwardMessageParams extends JsonObject, ForwardPreviewParams {
message_type?: 'private' | 'group' | string;
user_id?: number;
group_id?: number;
message?: JsonValue;
messages?: JsonValue;
message_type?: 'private' | 'group' | string;
user_id?: number;
group_id?: number;
message?: JsonValue;
messages?: JsonValue;
}
export interface GroupForwardMessageParams extends GroupIdParams, ForwardPreviewParams {
message?: JsonValue;
messages?: JsonValue;
message?: JsonValue;
messages?: JsonValue;
}
export interface PrivateForwardMessageParams extends UserIdParams, ForwardPreviewParams {
message?: JsonValue;
messages?: JsonValue;
message?: JsonValue;
messages?: JsonValue;
}
export interface GetForwardMsgParams extends JsonObject {
id?: string;
message_id?: number | string;
id?: string;
message_id?: number | string;
}
export interface GetMediaParams extends JsonObject {
file?: string;
file_id?: string;
file?: string;
file_id?: string;
}
export interface DomainParams extends JsonObject {
domain?: string;
domain?: string;
}
export interface QuickOperationParams extends JsonObject {
context: JsonObject;
operation: JsonObject;
context: JsonObject;
operation: JsonObject;
}
export interface SetFriendRemarkParams extends UserIdParams {
remark: string;
remark: string;
}
export interface SetGroupRemarkParams extends GroupIdParams {
remark: string;
remark: string;
}
export interface SetMsgEmojiLikeParams extends JsonObject {
message_id: number;
emoji_id: string;
set?: boolean;
message_id: number;
emoji_id: string;
set?: boolean;
}
export interface FetchCustomFaceParams extends JsonObject {
count?: number;
count?: number;
}
export type SendCustomFaceParams = JsonObject & {
/** Saved sticker resource ID or its 32-character content MD5. */
emoji_id: string;
reply_to?: number;
/** Saved sticker resource ID or its 32-character content MD5. */
emoji_id: string;
reply_to?: number;
} & ({ group_id: number; user_id?: never } | { user_id: number; group_id?: never });
export interface FetchSysFacesParams extends JsonObject {
refresh?: boolean;
refresh?: boolean;
}
export interface FetchFaceEntityParams extends FetchSysFacesParams {
face_id: number;
face_id: number;
}
export interface SearchSysFacesParams extends JsonObject {
query: string;
query: string;
}
export interface GetCollectionListParams extends JsonObject {
/** Collection category ID; 0 returns every category. */
category?: number;
/** Maximum number of collection items to return (1-500). */
count?: number;
/** Collection category ID; 0 returns every category. */
category?: number;
/** Maximum number of collection items to return (1-500). */
count?: number;
}
export interface GetEmojiLikesParams extends MessageIdParams {
emoji_id: string;
emoji_id: string;
}
export interface FetchEmojiLikeParams extends MessageIdParams {
emojiId: string;
emojiType?: number;
count?: number;
cookie?: string;
emojiId: string;
emojiType?: number;
count?: number;
cookie?: string;
}
export interface DownloadFileParams extends JsonObject {
url?: string;
base64?: string;
name?: string;
headers?: string | string[];
url?: string;
base64?: string;
name?: string;
headers?: string | string[];
}
export interface SetQqProfileParams extends JsonObject {
nickname?: string;
personal_note?: string;
sex?: number;
nickname?: string;
personal_note?: string;
sex?: number;
}
export interface SetOnlineStatusParams extends JsonObject {
status: number;
ext_status?: number;
battery_status?: number;
status: number;
ext_status?: number;
battery_status?: number;
}
// DIY online status — status/extStatus are forced to 10/2000 server-side,
// and these three fields land in the customExt sub-message.
export interface SetDiyOnlineStatusParams extends JsonObject {
face_id: number | string;
wording?: string;
face_type?: number | string;
face_id: number | string;
wording?: string;
face_type?: number | string;
}
// nc_get_user_status — read the QQ-side online/ext-status word for a uin.
@@ -387,32 +388,32 @@ export interface NcGetUserStatusParams extends UserIdParams {}
// set_/complete_/cancel_group_todo all share this shape; the action verb
// lives in the route, not the body.
export interface GroupTodoParams extends GroupIdParams {
message_id: number | string;
message_id: number | string;
}
// AI voice — fetch the in-group AI character list.
export interface GetAiCharactersParams extends GroupIdParams {
chat_type?: number | string;
chat_type?: number | string;
}
// AI voice — `get_ai_record` and `send_group_ai_record` share params.
// The action's verb (read vs send) is the route, not the body.
export interface AiVoiceParams extends GroupIdParams {
character: string;
text: string;
chat_type?: number | string;
character: string;
text: string;
chat_type?: number | string;
}
// delete_group_folder — napcat's alias for delete_group_file_folder.
// Same body, different action name.
export interface DeleteGroupFolderParams extends GroupIdParams {
folder_id: string;
folder_id: string;
}
// send_packet — debug endpoint, sends a hex-encoded raw packet.
// `rsp=false` skips waiting for a response.
export interface SendPacketParams extends JsonObject {
cmd: string;
data?: string;
rsp?: boolean;
cmd: string;
data?: string;
rsp?: boolean;
}
+146 -146
View File
@@ -1,280 +1,280 @@
import type { JsonArray, JsonObject, JsonValue } from './json';
export interface SendMessageResult {
message_id: number;
message_id: number;
}
export interface ForwardMessageResult {
message_id: number;
res_id: string;
forward_id: string;
message_id: number;
res_id: string;
forward_id: string;
}
export interface UploadForwardResult {
message_id: number;
res_id: string;
forward_id: string;
group_id?: number;
message_id: number;
res_id: string;
forward_id: string;
group_id?: number;
}
export interface LoginInfo {
user_id: number;
nickname: string;
user_id: number;
nickname: string;
}
export interface StatusInfo {
online: boolean;
good: boolean;
/** Current account-session uptime in seconds, matching #sl. */
time: number;
online: boolean;
good: boolean;
/** Current account-session uptime in seconds, matching #sl. */
time: number;
}
export interface VersionInfo {
app_name: string;
app_version: string;
protocol_version: string;
app_name: string;
app_version: string;
protocol_version: string;
}
export interface CapabilityInfo {
yes: boolean;
yes: boolean;
}
export interface GroupFileUrl {
url: string;
url: string;
}
export interface PrivateFileUrl {
url: string;
url: string;
}
export interface GroupFileSystemInfo {
file_count: number;
limit_count: number;
used_space: number;
total_space: number;
file_count: number;
limit_count: number;
used_space: number;
total_space: number;
}
export interface GroupMessageHistory {
messages: JsonObject[];
messages: JsonObject[];
}
export interface FriendMessageHistory {
messages: JsonObject[];
messages: JsonObject[];
}
export interface GroupNoticeInfo {
notice_id: string;
sender_id: number;
publish_time: number;
message: {
text: string;
image: Array<{ id: string; url: string; height: number; width: number }>;
images: Array<{ id: string; url: string; height: number; width: number }>;
};
settings: JsonValue;
read_num: number;
/** Server response type; regular announcements are commonly returned as 6. */
type: number;
pinned: number;
send_to_new_members: boolean;
notice_id: string;
sender_id: number;
publish_time: number;
message: {
text: string;
image: Array<{ id: string; url: string; height: number; width: number }>;
images: Array<{ id: string; url: string; height: number; width: number }>;
};
settings: JsonValue;
read_num: number;
/** Server response type; regular announcements are commonly returned as 6. */
type: number;
pinned: number;
send_to_new_members: boolean;
}
export interface CategorizedFriend {
user_id: number;
nickname: string;
remark: string;
user_id: number;
nickname: string;
remark: string;
}
export interface FriendCategoryResult {
categoryId: number;
categoryName: string;
categoryMbCount: number;
buddyList: CategorizedFriend[];
categoryId: number;
categoryName: string;
categoryMbCount: number;
buddyList: CategorizedFriend[];
}
export interface MediaInfo extends JsonObject {}
export interface CookieInfo {
cookies: string;
cookies: string;
}
export interface CsrfInfo {
token: number;
token: number;
}
export interface CredentialsInfo {
cookies: string;
token: number;
csrf_token: number;
cookies: string;
token: number;
csrf_token: number;
}
export interface DownloadFileResult {
file: string;
file: string;
}
export interface ClientKeyInfo {
clientKey: string;
keyIndex: string;
expireTime: string;
clientKey: string;
keyIndex: string;
expireTime: string;
}
export interface OnlineClientInfo {
app_id: number;
device_name: string;
device_kind: '电脑' | 'Pad' | '手机' | '未知设备';
app_id: number;
device_name: string;
device_kind: '电脑' | 'Pad' | '手机' | '未知设备';
}
export interface OnlineClientsInfo {
clients: OnlineClientInfo[];
clients: OnlineClientInfo[];
}
export interface CollectionAuthorInfo extends JsonObject {
type: number;
numId: string;
strId: string;
groupId: string;
groupName: string;
uid: string;
type: number;
numId: string;
strId: string;
groupId: string;
groupName: string;
uid: string;
}
export interface CollectionSummaryInfo extends JsonObject {
textSummary: JsonValue;
linkSummary: JsonValue;
gallerySummary: JsonValue;
audioSummary: JsonValue;
videoSummary: JsonValue;
fileSummary: JsonValue;
locationSummary: JsonValue;
richMediaSummary: JsonValue;
textSummary: JsonValue;
linkSummary: JsonValue;
gallerySummary: JsonValue;
audioSummary: JsonValue;
videoSummary: JsonValue;
fileSummary: JsonValue;
locationSummary: JsonValue;
richMediaSummary: JsonValue;
}
export interface CollectionItemInfo extends JsonObject {
cid: string;
type: number;
status: number;
author: CollectionAuthorInfo;
bid: number;
category: number;
createTime: string;
collectTime: string;
modifyTime: string;
sequence: string;
shareUrl: string;
customGroupId: number;
securityBeat: boolean;
summary: CollectionSummaryInfo;
cid: string;
type: number;
status: number;
author: CollectionAuthorInfo;
bid: number;
category: number;
createTime: string;
collectTime: string;
modifyTime: string;
sequence: string;
shareUrl: string;
customGroupId: number;
securityBeat: boolean;
summary: CollectionSummaryInfo;
}
export interface CollectionSearchListInfo extends JsonObject {
collectionItemList: CollectionItemInfo[];
hasMore: boolean;
bottomTimeStamp: string;
collectionItemList: CollectionItemInfo[];
hasMore: boolean;
bottomTimeStamp: string;
}
export interface CollectionListInfo extends JsonObject {
errCode: number;
errMsg: string;
collectionSearchList: CollectionSearchListInfo;
errCode: number;
errMsg: string;
collectionSearchList: CollectionSearchListInfo;
}
export interface SystemFaceInfo extends JsonObject {
q_sid: string;
q_des: string;
em_code: string;
q_cid: number | null;
ani_sticker_type: number | null;
ani_sticker_pack_id: number | null;
ani_sticker_id: number | null;
url: string | null;
emoji_name_alias: string[];
ani_sticker_width: number | null;
ani_sticker_height: number | null;
is_super: boolean;
q_sid: string;
q_des: string;
em_code: string;
q_cid: number | null;
ani_sticker_type: number | null;
ani_sticker_pack_id: number | null;
ani_sticker_id: number | null;
url: string | null;
emoji_name_alias: string[];
ani_sticker_width: number | null;
ani_sticker_height: number | null;
is_super: boolean;
}
export interface SystemFacePackInfo extends JsonObject {
pack_name: string;
emojis: SystemFaceInfo[];
pack_name: string;
emojis: SystemFaceInfo[];
}
export interface SystemFaceCatalogInfo extends JsonObject {
packs: SystemFacePackInfo[];
packs: SystemFacePackInfo[];
}
export interface SystemFaceSearchInfo extends JsonObject {
faces: SystemFaceInfo[];
faces: SystemFaceInfo[];
}
export interface SuperFaceInfo extends JsonObject {
is_super: boolean;
is_super: boolean;
}
export interface UrlSafetyInfo {
level: number;
level: number;
}
export interface GroupAtAllRemainInfo {
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
can_at_all: boolean;
remain_at_all_count_for_group: number;
remain_at_all_count_for_uin: number;
}
export interface GroupCategoryTag {
id: number;
name: string;
type: number;
id: number;
name: string;
type: number;
}
export interface GroupCategoryTagList {
tags: GroupCategoryTag[];
tags: GroupCategoryTag[];
}
export type GroupAdminSettings = {
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: 'disabled' | 'require_approval' | 'no_approval' | 'no_approval_under_100';
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: 'disabled' | 'require_approval' | 'no_approval' | 'no_approval_under_100';
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
};
export interface GroupTodoListItem {
message_id: number;
message_seq: number;
message_random: number;
message: JsonArray | null;
text: string;
create_time: number;
update_time: number;
message_id: number;
message_seq: number;
message_random: number;
message: JsonArray | null;
text: string;
create_time: number;
update_time: number;
}
export type EmptyData = null;
// — AI 语音角色:get_ai_characters 返回的分类数组 —
export interface AiCharacter {
character_id: string;
character_name: string;
preview_url: string;
character_id: string;
character_name: string;
preview_url: string;
}
export interface AiCharacterCategory {
type: string;
characters: AiCharacter[];
type: string;
characters: AiCharacter[];
}
// — nc_get_user_status 返回的状态字 —
export interface UserOnlineStatus {
status: number;
ext_status: number;
status: number;
ext_status: number;
}
// — send_group_ai_record 返回 —
export interface SendGroupAiRecordResult {
message_id: number;
message_id: number;
}
File diff suppressed because it is too large. Load diff
+458 -432
View File
@@ -1,506 +1,532 @@
import { describe, expect, it, vi } from 'vitest';
import {
at,
atAll,
br,
chain,
contact,
face,
forward,
image,
json,
location,
MessageChain,
music,
node,
normalizeMessage,
poke,
raw,
record,
reply,
share,
text,
video,
xml,
at,
atAll,
br,
chain,
contact,
face,
forward,
image,
json,
location,
MessageChain,
music,
node,
normalizeMessage,
poke,
raw,
record,
reply,
share,
text,
video,
xml,
} from '../src';
function sender() {
return {
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 61001 }),
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 61002 }),
};
return {
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 61001 }),
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 61002 }),
};
}
describe('MessageChain.empty and chain()', () => {
it('starts empty', () => {
const empty = MessageChain.empty();
it('starts empty', () => {
const empty = MessageChain.empty();
expect(empty).toBeInstanceOf(MessageChain);
expect(empty.length).toBe(0);
expect(empty.isEmpty).toBe(true);
expect(empty.toSegments()).toEqual([]);
expect(chain().toSegments()).toEqual([]);
});
expect(empty).toBeInstanceOf(MessageChain);
expect(empty.length).toBe(0);
expect(empty.isEmpty).toBe(true);
expect(empty.toSegments()).toEqual([]);
expect(chain().toSegments()).toEqual([]);
});
it('updates length and isEmpty after a segment is added', () => {
const next = chain().text('wave');
it('updates length and isEmpty after a segment is added', () => {
const next = chain().text('wave');
expect(next.length).toBe(1);
expect(next.isEmpty).toBe(false);
expect(chain().isEmpty).toBe(true);
});
expect(next.length).toBe(1);
expect(next.isEmpty).toBe(false);
expect(chain().isEmpty).toBe(true);
});
it('does not mutate the previous chain when a segment is added', () => {
const base = text('keep');
const next = base.face(39);
it('does not mutate the previous chain when a segment is added', () => {
const base = text('keep');
const next = base.face(39);
expect(base.toSegments()).toEqual([{ type: 'text', data: { text: 'keep' } }]);
expect(next.toSegments()).toEqual([
{ type: 'text', data: { text: 'keep' } },
{ type: 'face', data: { id: '39' } },
]);
});
expect(base.toSegments()).toEqual([{ type: 'text', data: { text: 'keep' } }]);
expect(next.toSegments()).toEqual([
{ type: 'text', data: { text: 'keep' } },
{ type: 'face', data: { id: '39' } },
]);
});
});
describe('segment builders', () => {
it('builds a text segment and defaults to an empty string', () => {
expect(text().toSegments()).toEqual([{ type: 'text', data: { text: '' } }]);
expect(text('wave').toSegments()).toEqual([{ type: 'text', data: { text: 'wave' } }]);
expect(chain().text().toSegments()).toEqual([{ type: 'text', data: { text: '' } }]);
});
it('builds a text segment and defaults to an empty string', () => {
expect(text().toSegments()).toEqual([{ type: 'text', data: { text: '' } }]);
expect(text('wave').toSegments()).toEqual([{ type: 'text', data: { text: 'wave' } }]);
expect(chain().text().toSegments()).toEqual([{ type: 'text', data: { text: '' } }]);
});
it('treats br as a newline text segment', () => {
expect(br().toSegments()).toEqual([{ type: 'text', data: { text: '\n' } }]);
});
it('treats br as a newline text segment', () => {
expect(br().toSegments()).toEqual([{ type: 'text', data: { text: '\n' } }]);
});
it('stringifies face ids', () => {
expect(face(39).toSegments()).toEqual([{ type: 'face', data: { id: '39' } }]);
expect(face('178').toSegments()).toEqual([{ type: 'face', data: { id: '178' } }]);
});
it('stringifies face ids', () => {
expect(face(39).toSegments()).toEqual([{ type: 'face', data: { id: '39' } }]);
expect(face('178').toSegments()).toEqual([{ type: 'face', data: { id: '178' } }]);
});
it('stringifies at targets and only copies truthy name/uid', () => {
expect(at(31415).toSegments()).toEqual([{ type: 'at', data: { qq: '31415' } }]);
expect(at('all').toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
expect(atAll().toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
expect(at(31415, { name: 'Ada', uid: 'uid-ada' }).toSegments()).toEqual([
{ type: 'at', data: { qq: '31415', name: 'Ada', uid: 'uid-ada' } },
]);
expect(at(31415, { name: '', uid: '' }).toSegments()).toEqual([
{ type: 'at', data: { qq: '31415' } },
]);
});
it('stringifies at targets and only copies truthy name/uid', () => {
expect(at(31415).toSegments()).toEqual([{ type: 'at', data: { qq: '31415' } }]);
expect(at('all').toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
expect(atAll().toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
expect(at(31415, { name: 'Ada', uid: 'uid-ada' }).toSegments()).toEqual([
{ type: 'at', data: { qq: '31415', name: 'Ada', uid: 'uid-ada' } },
]);
expect(at(31415, { name: '', uid: '' }).toSegments()).toEqual([
{ type: 'at', data: { qq: '31415' } },
]);
});
it('stringifies reply ids', () => {
expect(reply(88).toSegments()).toEqual([{ type: 'reply', data: { id: '88' } }]);
expect(reply('mid-88').toSegments()).toEqual([{ type: 'reply', data: { id: 'mid-88' } }]);
});
it('stringifies reply ids', () => {
expect(reply(88).toSegments()).toEqual([{ type: 'reply', data: { id: '88' } }]);
expect(reply('mid-88').toSegments()).toEqual([{ type: 'reply', data: { id: 'mid-88' } }]);
});
it('spreads image, record, and video options after file', () => {
expect(image('file://pic.webp').toSegments()).toEqual([
{ type: 'image', data: { file: 'file://pic.webp' } },
]);
expect(
image('file://pic.webp', {
type: 'flash',
subType: 4,
summary: 'cover',
url: 'https://cdn.example/pic.webp',
}).toSegments(),
).toEqual([
{
type: 'image',
data: {
file: 'file://pic.webp',
type: 'flash',
subType: 4,
summary: 'cover',
url: 'https://cdn.example/pic.webp',
},
},
]);
expect(record('file://voice.amr').toSegments()).toEqual([
{ type: 'record', data: { file: 'file://voice.amr' } },
]);
expect(record('file://voice.amr', { url: 'https://cdn.example/voice.amr' }).toSegments()).toEqual([
{ type: 'record', data: { file: 'file://voice.amr', url: 'https://cdn.example/voice.amr' } },
]);
expect(video('file://clip.mp4').toSegments()).toEqual([
{ type: 'video', data: { file: 'file://clip.mp4' } },
]);
expect(
video('file://clip.mp4', {
url: 'https://cdn.example/clip.mp4',
thumb: 'file://thumb.jpg',
}).toSegments(),
).toEqual([
{
type: 'video',
data: {
file: 'file://clip.mp4',
url: 'https://cdn.example/clip.mp4',
thumb: 'file://thumb.jpg',
},
},
]);
});
it('spreads image, record, and video options after file', () => {
expect(image('file://pic.webp').toSegments()).toEqual([
{ type: 'image', data: { file: 'file://pic.webp' } },
]);
expect(
image('file://pic.webp', {
type: 'flash',
subType: 4,
summary: 'cover',
url: 'https://cdn.example/pic.webp',
}).toSegments(),
).toEqual([
{
type: 'image',
data: {
file: 'file://pic.webp',
type: 'flash',
subType: 4,
summary: 'cover',
url: 'https://cdn.example/pic.webp',
},
},
]);
expect(record('file://voice.amr').toSegments()).toEqual([
{ type: 'record', data: { file: 'file://voice.amr' } },
]);
expect(
record('file://voice.amr', { url: 'https://cdn.example/voice.amr' }).toSegments(),
).toEqual([
{
type: 'record',
data: { file: 'file://voice.amr', url: 'https://cdn.example/voice.amr' },
},
]);
expect(video('file://clip.mp4').toSegments()).toEqual([
{ type: 'video', data: { file: 'file://clip.mp4' } },
]);
expect(
video('file://clip.mp4', {
url: 'https://cdn.example/clip.mp4',
thumb: 'file://thumb.jpg',
}).toSegments(),
).toEqual([
{
type: 'video',
data: {
file: 'file://clip.mp4',
url: 'https://cdn.example/clip.mp4',
thumb: 'file://thumb.jpg',
},
},
]);
});
it('keeps a json string and stringifies a json object', () => {
expect(json('{"prompt":"card"}').toSegments()).toEqual([
{ type: 'json', data: { data: '{"prompt":"card"}' } },
]);
expect(json({ prompt: 'card', n: 2 }).toSegments()).toEqual([
{ type: 'json', data: { data: '{"prompt":"card","n":2}' } },
]);
});
it('keeps a json string and stringifies a json object', () => {
expect(json('{"prompt":"card"}').toSegments()).toEqual([
{ type: 'json', data: { data: '{"prompt":"card"}' } },
]);
expect(json({ prompt: 'card', n: 2 }).toSegments()).toEqual([
{ type: 'json', data: { data: '{"prompt":"card","n":2}' } },
]);
});
it('spreads xml options after the payload', () => {
expect(xml('<item />').toSegments()).toEqual([{ type: 'xml', data: { data: '<item />' } }]);
expect(xml('<item />', { id: 'resid-3' }).toSegments()).toEqual([
{ type: 'xml', data: { data: '<item />', id: 'resid-3' } },
]);
});
it('spreads xml options after the payload', () => {
expect(xml('<item />').toSegments()).toEqual([{ type: 'xml', data: { data: '<item />' } }]);
expect(xml('<item />', { id: 'resid-3' }).toSegments()).toEqual([
{ type: 'xml', data: { data: '<item />', id: 'resid-3' } },
]);
});
it('omits poke id only when it is undefined', () => {
expect(poke(6).toSegments()).toEqual([{ type: 'poke', data: { type: 6 } }]);
expect(poke(6, 0).toSegments()).toEqual([{ type: 'poke', data: { type: 6, id: 0 } }]);
expect(poke('6', '-1').toSegments()).toEqual([{ type: 'poke', data: { type: '6', id: '-1' } }]);
});
it('omits poke id only when it is undefined', () => {
expect(poke(6).toSegments()).toEqual([{ type: 'poke', data: { type: 6 } }]);
expect(poke(6, 0).toSegments()).toEqual([{ type: 'poke', data: { type: 6, id: 0 } }]);
expect(poke('6', '-1').toSegments()).toEqual([
{ type: 'poke', data: { type: '6', id: '-1' } },
]);
});
it('mirrors a forward id onto res_id and forward_id', () => {
expect(forward('fwd-22').toSegments()).toEqual([
{ type: 'forward', data: { id: 'fwd-22', res_id: 'fwd-22', forward_id: 'fwd-22' } },
]);
});
it('mirrors a forward id onto res_id and forward_id', () => {
expect(forward('fwd-22').toSegments()).toEqual([
{ type: 'forward', data: { id: 'fwd-22', res_id: 'fwd-22', forward_id: 'fwd-22' } },
]);
});
it('stores node content as given', () => {
const inner = text('nested');
it('stores node content as given', () => {
const inner = text('nested');
expect(node(20002, 'bot', 'plain').toSegments()).toEqual([
{ type: 'node', data: { user_id: 20002, nickname: 'bot', content: 'plain' } },
]);
expect(node(20002, 'bot', { type: 'text', data: { text: 'seg' } }).toSegments()).toEqual([
{
type: 'node',
data: { user_id: 20002, nickname: 'bot', content: { type: 'text', data: { text: 'seg' } } },
},
]);
expect(node(20002, 'bot', inner).toSegments()).toEqual([
{ type: 'node', data: { user_id: 20002, nickname: 'bot', content: inner } },
]);
});
expect(node(20002, 'bot', 'plain').toSegments()).toEqual([
{ type: 'node', data: { user_id: 20002, nickname: 'bot', content: 'plain' } },
]);
expect(node(20002, 'bot', { type: 'text', data: { text: 'seg' } }).toSegments()).toEqual([
{
type: 'node',
data: {
user_id: 20002,
nickname: 'bot',
content: { type: 'text', data: { text: 'seg' } },
},
},
]);
expect(node(20002, 'bot', inner).toSegments()).toEqual([
{ type: 'node', data: { user_id: 20002, nickname: 'bot', content: inner } },
]);
});
it('passes share, music, location, and contact data through', () => {
expect(share({ url: 'https://ex.test/page', title: 'Page' }).toSegments()).toEqual([
{ type: 'share', data: { url: 'https://ex.test/page', title: 'Page' } },
]);
expect(
share({
url: 'https://ex.test/page',
title: 'Page',
content: 'blurb',
image: 'https://ex.test/cover.png',
}).toSegments(),
).toEqual([
{
type: 'share',
data: {
url: 'https://ex.test/page',
title: 'Page',
content: 'blurb',
image: 'https://ex.test/cover.png',
},
},
]);
expect(music({ type: 'qq', id: '991' }).toSegments()).toEqual([
{ type: 'music', data: { type: 'qq', id: '991' } },
]);
expect(
location({ lat: 30.1, lon: 120.2, title: 'Hangzhou', content: 'West Lake' }).toSegments(),
).toEqual([
{
type: 'location',
data: { lat: 30.1, lon: 120.2, title: 'Hangzhou', content: 'West Lake' },
},
]);
expect(contact('qq', 20002).toSegments()).toEqual([
{ type: 'contact', data: { type: 'qq', id: 20002 } },
]);
expect(contact('group', '987654').toSegments()).toEqual([
{ type: 'contact', data: { type: 'group', id: '987654' } },
]);
});
it('passes share, music, location, and contact data through', () => {
expect(share({ url: 'https://ex.test/page', title: 'Page' }).toSegments()).toEqual([
{ type: 'share', data: { url: 'https://ex.test/page', title: 'Page' } },
]);
expect(
share({
url: 'https://ex.test/page',
title: 'Page',
content: 'blurb',
image: 'https://ex.test/cover.png',
}).toSegments(),
).toEqual([
{
type: 'share',
data: {
url: 'https://ex.test/page',
title: 'Page',
content: 'blurb',
image: 'https://ex.test/cover.png',
},
},
]);
expect(music({ type: 'qq', id: '991' }).toSegments()).toEqual([
{ type: 'music', data: { type: 'qq', id: '991' } },
]);
expect(
location({
lat: 30.1,
lon: 120.2,
title: 'Hangzhou',
content: 'West Lake',
}).toSegments(),
).toEqual([
{
type: 'location',
data: { lat: 30.1, lon: 120.2, title: 'Hangzhou', content: 'West Lake' },
},
]);
expect(contact('qq', 20002).toSegments()).toEqual([
{ type: 'contact', data: { type: 'qq', id: 20002 } },
]);
expect(contact('group', '987654').toSegments()).toEqual([
{ type: 'contact', data: { type: 'group', id: '987654' } },
]);
});
it('builds an arbitrary raw segment', () => {
expect(raw('dice', { result: 3 }).toSegments()).toEqual([
{ type: 'dice', data: { result: 3 } },
]);
});
it('builds an arbitrary raw segment', () => {
expect(raw('dice', { result: 3 }).toSegments()).toEqual([
{ type: 'dice', data: { result: 3 } },
]);
});
it('chains fluent builders in order', () => {
const built = chain().text('ping').at(20002).br().image('file://b.jpg').face(39);
it('chains fluent builders in order', () => {
const built = chain().text('ping').at(20002).br().image('file://b.jpg').face(39);
expect(built.length).toBe(5);
expect(built.toSegments()).toEqual([
{ type: 'text', data: { text: 'ping' } },
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '\n' } },
{ type: 'image', data: { file: 'file://b.jpg' } },
{ type: 'face', data: { id: '39' } },
]);
});
expect(built.length).toBe(5);
expect(built.toSegments()).toEqual([
{ type: 'text', data: { text: 'ping' } },
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '\n' } },
{ type: 'image', data: { file: 'file://b.jpg' } },
{ type: 'face', data: { id: '39' } },
]);
});
});
describe('append', () => {
it('appends a string as a text segment', () => {
expect(text('pre').append('post').toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'text', data: { text: 'post' } },
]);
expect(text('pre').append('').toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'text', data: { text: '' } },
]);
});
it('appends a string as a text segment', () => {
expect(text('pre').append('post').toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'text', data: { text: 'post' } },
]);
expect(text('pre').append('').toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'text', data: { text: '' } },
]);
});
it('returns the same instance when appending an empty array', () => {
const base = text('keep');
expect(base.append([])).toBe(base);
});
it('returns the same instance when appending an empty array', () => {
const base = text('keep');
expect(base.append([])).toBe(base);
});
it('appends a single segment', () => {
expect(text('pre').append({ type: 'face', data: { id: '39' } }).toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'face', data: { id: '39' } },
]);
});
it('appends a single segment', () => {
expect(
text('pre')
.append({ type: 'face', data: { id: '39' } })
.toSegments(),
).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'face', data: { id: '39' } },
]);
});
it('appends a segment array', () => {
expect(
text('pre')
.append([
{ type: 'at', data: { qq: 'all' } },
{ type: 'face', data: { id: '39' } },
])
.toSegments(),
).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'at', data: { qq: 'all' } },
{ type: 'face', data: { id: '39' } },
]);
});
it('appends a segment array', () => {
expect(
text('pre')
.append([
{ type: 'at', data: { qq: 'all' } },
{ type: 'face', data: { id: '39' } },
])
.toSegments(),
).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'at', data: { qq: 'all' } },
{ type: 'face', data: { id: '39' } },
]);
});
it('appends another chain by copying its segments', () => {
const extra = at(20002).text('!');
expect(text('pre').append(extra).toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '!' } },
]);
expect(extra.toSegments()).toEqual([
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '!' } },
]);
});
it('appends another chain by copying its segments', () => {
const extra = at(20002).text('!');
expect(text('pre').append(extra).toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '!' } },
]);
expect(extra.toSegments()).toEqual([
{ type: 'at', data: { qq: '20002' } },
{ type: 'text', data: { text: '!' } },
]);
});
it('appends a duck-typed chain-like value via toSegments', () => {
const duck = {
length: 1,
toSegments() {
return [{ type: 'poke', data: { type: 6 } }];
},
toJSON() {
return this.toSegments();
},
};
it('appends a duck-typed chain-like value via toSegments', () => {
const duck = {
length: 1,
toSegments() {
return [{ type: 'poke', data: { type: 6 } }];
},
toJSON() {
return this.toSegments();
},
};
expect(text('pre').append(duck).toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'poke', data: { type: 6 } },
]);
});
expect(text('pre').append(duck).toSegments()).toEqual([
{ type: 'text', data: { text: 'pre' } },
{ type: 'poke', data: { type: 6 } },
]);
});
});
describe('single-use reply', () => {
it('throws when reply is added twice through reply()', () => {
const once = reply(88);
expect(() => (once as unknown as { reply(id: number): unknown }).reply(89)).toThrow(
'Message segment "reply" can only appear once in a chain',
);
});
it('throws when reply is added twice through reply()', () => {
const once = reply(88);
expect(() => (once as unknown as { reply(id: number): unknown }).reply(89)).toThrow(
'Message segment "reply" can only appear once in a chain',
);
});
it('throws when a second reply is appended', () => {
expect(() => reply(88).append({ type: 'reply', data: { id: '89' } })).toThrow(
'Message segment "reply" can only appear once in a chain',
);
expect(() =>
chain().append([
{ type: 'reply', data: { id: '88' } },
{ type: 'text', data: { text: 'x' } },
{ type: 'reply', data: { id: '89' } },
]),
).toThrow('Message segment "reply" can only appear once in a chain');
});
it('throws when a second reply is appended', () => {
expect(() => reply(88).append({ type: 'reply', data: { id: '89' } })).toThrow(
'Message segment "reply" can only appear once in a chain',
);
expect(() =>
chain().append([
{ type: 'reply', data: { id: '88' } },
{ type: 'text', data: { text: 'x' } },
{ type: 'reply', data: { id: '89' } },
]),
).toThrow('Message segment "reply" can only appear once in a chain');
});
it('throws when raw reply is added twice', () => {
expect(() => raw('reply', { id: '88' }).raw('reply', { id: '89' })).toThrow(
'Message segment "reply" can only appear once in a chain',
);
});
it('throws when raw reply is added twice', () => {
expect(() => raw('reply', { id: '88' }).raw('reply', { id: '89' })).toThrow(
'Message segment "reply" can only appear once in a chain',
);
});
it('allows two independent chains to each have their own reply', () => {
const base = text('fork');
expect(base.reply(88).toSegments()).toEqual([
{ type: 'text', data: { text: 'fork' } },
{ type: 'reply', data: { id: '88' } },
]);
expect(base.reply(89).toSegments()).toEqual([
{ type: 'text', data: { text: 'fork' } },
{ type: 'reply', data: { id: '89' } },
]);
});
it('allows two independent chains to each have their own reply', () => {
const base = text('fork');
expect(base.reply(88).toSegments()).toEqual([
{ type: 'text', data: { text: 'fork' } },
{ type: 'reply', data: { id: '88' } },
]);
expect(base.reply(89).toSegments()).toEqual([
{ type: 'text', data: { text: 'fork' } },
{ type: 'reply', data: { id: '89' } },
]);
});
it('allows non-reply types, including raw, to appear more than once', () => {
expect(image('a.webp').image('b.webp').toSegments()).toEqual([
{ type: 'image', data: { file: 'a.webp' } },
{ type: 'image', data: { file: 'b.webp' } },
]);
expect(raw('dice', { result: 1 }).raw('dice', { result: 2 }).toSegments()).toEqual([
{ type: 'dice', data: { result: 1 } },
{ type: 'dice', data: { result: 2 } },
]);
});
it('allows non-reply types, including raw, to appear more than once', () => {
expect(image('a.webp').image('b.webp').toSegments()).toEqual([
{ type: 'image', data: { file: 'a.webp' } },
{ type: 'image', data: { file: 'b.webp' } },
]);
expect(raw('dice', { result: 1 }).raw('dice', { result: 2 }).toSegments()).toEqual([
{ type: 'dice', data: { result: 1 } },
{ type: 'dice', data: { result: 2 } },
]);
});
it('still allows other segments after a reply', () => {
expect(reply(88).text('after').toSegments()).toEqual([
{ type: 'reply', data: { id: '88' } },
{ type: 'text', data: { text: 'after' } },
]);
});
it('still allows other segments after a reply', () => {
expect(reply(88).text('after').toSegments()).toEqual([
{ type: 'reply', data: { id: '88' } },
{ type: 'text', data: { text: 'after' } },
]);
});
});
describe('serialization and iteration', () => {
it('returns a shallow copy from build, toArray, toSegments, and toJSON', () => {
const built = text('copy').at(20002);
const viaBuild = built.build();
const viaArray = built.toArray();
const viaSegments = built.toSegments();
const viaJson = built.toJSON();
const expected = [
{ type: 'text', data: { text: 'copy' } },
{ type: 'at', data: { qq: '20002' } },
];
it('returns a shallow copy from build, toArray, toSegments, and toJSON', () => {
const built = text('copy').at(20002);
const viaBuild = built.build();
const viaArray = built.toArray();
const viaSegments = built.toSegments();
const viaJson = built.toJSON();
const expected = [
{ type: 'text', data: { text: 'copy' } },
{ type: 'at', data: { qq: '20002' } },
];
expect(viaBuild).toEqual(expected);
expect(viaArray).toEqual(expected);
expect(viaSegments).toEqual(expected);
expect(viaJson).toEqual(expected);
expect(viaBuild).not.toBe(viaArray);
expect(viaArray).not.toBe(viaSegments);
expect(viaSegments).not.toBe(viaJson);
expect(viaBuild).toEqual(expected);
expect(viaArray).toEqual(expected);
expect(viaSegments).toEqual(expected);
expect(viaJson).toEqual(expected);
expect(viaBuild).not.toBe(viaArray);
expect(viaArray).not.toBe(viaSegments);
expect(viaSegments).not.toBe(viaJson);
viaBuild.push({ type: 'face', data: { id: '1' } });
expect(built.toSegments()).toEqual(expected);
expect(built.length).toBe(2);
});
viaBuild.push({ type: 'face', data: { id: '1' } });
expect(built.toSegments()).toEqual(expected);
expect(built.length).toBe(2);
});
it('uses toJSON when stringified', () => {
expect(JSON.parse(JSON.stringify(text('copy').at(20002)))).toEqual([
{ type: 'text', data: { text: 'copy' } },
{ type: 'at', data: { qq: '20002' } },
]);
});
it('uses toJSON when stringified', () => {
expect(JSON.parse(JSON.stringify(text('copy').at(20002)))).toEqual([
{ type: 'text', data: { text: 'copy' } },
{ type: 'at', data: { qq: '20002' } },
]);
});
it('renders CQ text through toString', () => {
expect(chain().toString()).toBe('');
expect(text('A&B[C]').toString()).toBe('A&amp;B&#91;C&#93;');
expect(text('wave').at(20002).face(39).toString()).toBe('wave[CQ:at,qq=20002][CQ:face,id=39]');
expect(image('a,b').toString()).toBe('[CQ:image,file=a&#44;b]');
expect(raw('dice', {}).toString()).toBe('[CQ:dice]');
expect(chain().append({ type: 'image', data: { file: 'z.webp', url: undefined } }).toString()).toBe(
'[CQ:image,file=z.webp]',
);
});
it('renders CQ text through toString', () => {
expect(chain().toString()).toBe('');
expect(text('A&B[C]').toString()).toBe('A&amp;B&#91;C&#93;');
expect(text('wave').at(20002).face(39).toString()).toBe(
'wave[CQ:at,qq=20002][CQ:face,id=39]',
);
expect(image('a,b').toString()).toBe('[CQ:image,file=a&#44;b]');
expect(raw('dice', {}).toString()).toBe('[CQ:dice]');
expect(
chain()
.append({ type: 'image', data: { file: 'z.webp', url: undefined } })
.toString(),
).toBe('[CQ:image,file=z.webp]');
});
it('iterates stored segments', () => {
const built = text('wave').face(39);
expect([...built]).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'face', data: { id: '39' } },
]);
it('iterates stored segments', () => {
const built = text('wave').face(39);
expect([...built]).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'face', data: { id: '39' } },
]);
const walked: unknown[] = [];
for (const segment of built) {
walked.push(segment);
}
expect(walked).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'face', data: { id: '39' } },
]);
});
const walked: unknown[] = [];
for (const segment of built) {
walked.push(segment);
}
expect(walked).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'face', data: { id: '39' } },
]);
});
});
describe('sendToGroup and sendToPrivate', () => {
it('forwards the chain instance and options to the client', async () => {
const client = sender();
const groupPayload = text('group-hi');
const privatePayload = text('priv-hi');
const options = { autoEscape: true, timeoutMs: 2500, echo: 'echo-chain' };
it('forwards the chain instance and options to the client', async () => {
const client = sender();
const groupPayload = text('group-hi');
const privatePayload = text('priv-hi');
const options = { autoEscape: true, timeoutMs: 2500, echo: 'echo-chain' };
await expect(groupPayload.sendToGroup(client, 70001, options)).resolves.toEqual({
message_id: 61001,
});
await expect(privatePayload.sendToPrivate(client, 80001, options)).resolves.toEqual({
message_id: 61002,
await expect(groupPayload.sendToGroup(client, 70001, options)).resolves.toEqual({
message_id: 61001,
});
await expect(privatePayload.sendToPrivate(client, 80001, options)).resolves.toEqual({
message_id: 61002,
});
expect(client.sendGroupMessage).toHaveBeenCalledTimes(1);
expect(client.sendGroupMessage).toHaveBeenCalledWith(70001, groupPayload, options);
expect(client.sendPrivateMessage).toHaveBeenCalledTimes(1);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(80001, privatePayload, options);
});
expect(client.sendGroupMessage).toHaveBeenCalledTimes(1);
expect(client.sendGroupMessage).toHaveBeenCalledWith(70001, groupPayload, options);
expect(client.sendPrivateMessage).toHaveBeenCalledTimes(1);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(80001, privatePayload, options);
});
it('passes undefined options when none are given', async () => {
const client = sender();
const payload = text('plain');
it('passes undefined options when none are given', async () => {
const client = sender();
const payload = text('plain');
await payload.sendToGroup(client, 70002);
await payload.sendToPrivate(client, 80002);
await payload.sendToGroup(client, 70002);
await payload.sendToPrivate(client, 80002);
expect(client.sendGroupMessage).toHaveBeenCalledWith(70002, payload, undefined);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(80002, payload, undefined);
});
expect(client.sendGroupMessage).toHaveBeenCalledWith(70002, payload, undefined);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(80002, payload, undefined);
});
});
describe('normalizeMessage', () => {
it('returns a string unchanged', () => {
expect(normalizeMessage('plain-text')).toBe('plain-text');
expect(normalizeMessage('')).toBe('');
});
it('returns a string unchanged', () => {
expect(normalizeMessage('plain-text')).toBe('plain-text');
expect(normalizeMessage('')).toBe('');
});
it('returns toSegments() for a chain and for duck-typed chain-like values', () => {
expect(normalizeMessage(text('wave').at(20002))).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'at', data: { qq: '20002' } },
]);
it('returns toSegments() for a chain and for duck-typed chain-like values', () => {
expect(normalizeMessage(text('wave').at(20002))).toEqual([
{ type: 'text', data: { text: 'wave' } },
{ type: 'at', data: { qq: '20002' } },
]);
const segs = [{ type: 'face', data: { id: '39' } }];
const duck = { toSegments: () => segs };
expect(normalizeMessage(duck)).toBe(segs);
});
const segs = [{ type: 'face', data: { id: '39' } }];
const duck = { toSegments: () => segs };
expect(normalizeMessage(duck)).toBe(segs);
});
it('returns an array input by reference', () => {
const segs = [{ type: 'text', data: { text: 'arr' } }];
expect(normalizeMessage(segs)).toBe(segs);
});
it('returns an array input by reference', () => {
const segs = [{ type: 'text', data: { text: 'arr' } }];
expect(normalizeMessage(segs)).toBe(segs);
});
it('wraps a single segment in a new array', () => {
const segment = { type: 'text', data: { text: 'solo' } };
expect(normalizeMessage(segment)).toEqual([segment]);
expect(normalizeMessage(segment)).not.toBe(segment);
});
it('wraps a single segment in a new array', () => {
const segment = { type: 'text', data: { text: 'solo' } };
expect(normalizeMessage(segment)).toEqual([segment]);
expect(normalizeMessage(segment)).not.toBe(segment);
});
it('does not treat an object with a non-function toSegments as a chain', () => {
const value = { type: 'text', data: { text: 'solo' }, toSegments: 0 };
expect(normalizeMessage(value as never)).toEqual([value]);
});
it('does not treat an object with a non-function toSegments as a chain', () => {
const value = { type: 'text', data: { text: 'solo' }, toSegments: 0 };
expect(normalizeMessage(value as never)).toEqual([value]);
});
});
+305 -298
View File
@@ -2,330 +2,337 @@ import { describe, expect, it } from 'vitest';
import { Emitter } from '../src/emitter';
type TestEvents = {
open: undefined;
data: string;
count: number;
close: { code: number; reason: string };
open: undefined;
data: string;
count: number;
close: { code: number; reason: string };
};
describe('Emitter', () => {
it('delivers a payload to a listener registered with on', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
it('delivers a payload to a listener registered with on', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'hello');
emitter.on('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'hello');
expect(seen).toEqual(['hello']);
});
it('invokes every listener for the same event in registration order', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(`first:${payload}`);
});
emitter.on('data', (payload) => {
seen.push(`second:${payload}`);
});
emitter.emit('data', 'alpha');
expect(seen).toEqual(['first:alpha', 'second:alpha']);
});
it('keeps listeners for different events isolated', () => {
const emitter = new Emitter<TestEvents>();
const data: string[] = [];
const counts: number[] = [];
emitter.on('data', (payload) => {
data.push(payload);
});
emitter.on('count', (payload) => {
counts.push(payload);
});
emitter.emit('data', 'alpha');
emitter.emit('count', 7);
emitter.emit('data', 'beta');
expect(data).toEqual(['alpha', 'beta']);
expect(counts).toEqual([7]);
});
it('passes the payload object through by reference', () => {
const emitter = new Emitter<TestEvents>();
const payload = { code: 1000, reason: 'done' };
const seen: Array<{ code: number; reason: string }> = [];
emitter.on('close', (value) => {
seen.push(value);
});
emitter.emit('close', payload);
expect(seen).toEqual([{ code: 1000, reason: 'done' }]);
expect(seen[0]).toBe(payload);
});
it('forwards an undefined payload for events typed as undefined', () => {
const emitter = new Emitter<TestEvents>();
const seen: Array<undefined> = [];
emitter.on('open', (payload) => {
seen.push(payload);
});
emitter.emit('open', undefined);
expect(seen).toEqual([undefined]);
});
it('stores a listener only once when the same function is registered twice', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const listener = (payload: string) => {
seen.push(payload);
};
emitter.on('data', listener);
emitter.on('data', listener);
emitter.emit('data', 'once-only');
expect(seen).toEqual(['once-only']);
});
it('returns an unsubscribe function from on that stops later delivery', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.on('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'nope');
expect(seen).toEqual([]);
});
it('does not throw when emit is called with no listeners for that event', () => {
const emitter = new Emitter<TestEvents>();
expect(() => emitter.emit('data', 'orphan')).not.toThrow();
});
it('does not deliver after every listener has been unsubscribed, even if the event key remains', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.on('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'ghost');
expect(seen).toEqual([]);
});
it('fires a once listener exactly once', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.once('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'first');
emitter.emit('data', 'second');
expect(seen).toEqual(['first']);
});
it('lets once and on listeners share an event without once firing again', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(`on:${payload}`);
});
emitter.once('data', (payload) => {
seen.push(`once:${payload}`);
});
emitter.emit('data', 'a');
emitter.emit('data', 'b');
expect(seen).toEqual(['on:a', 'once:a', 'on:b']);
});
it('does not call a once listener that was unsubscribed before emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.once('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'nope');
expect(seen).toEqual([]);
});
it('allows calling the once unsubscribe after it has already fired', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.once('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'first');
off();
emitter.emit('data', 'second');
expect(seen).toEqual(['first']);
});
it('does not re-enter a once listener that emits the same event again', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.once('data', (payload) => {
seen.push(payload);
emitter.emit('data', 'again');
});
emitter.emit('data', 'first');
expect(seen).toEqual(['first']);
});
it('does not cancel a once subscription when off is given the original listener', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const listener = (payload: string) => {
seen.push(payload);
};
emitter.once('data', listener);
emitter.off('data', listener);
emitter.emit('data', 'still');
expect(seen).toEqual(['still']);
});
it('removes only the given listener when off is called', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const keep = (payload: string) => {
seen.push(`keep:${payload}`);
};
const drop = (payload: string) => {
seen.push(`drop:${payload}`);
};
emitter.on('data', keep);
emitter.on('data', drop);
emitter.off('data', drop);
emitter.emit('data', 'x');
expect(seen).toEqual(['keep:x']);
});
it('does not throw when off is called for an event that was never registered', () => {
const emitter = new Emitter<TestEvents>();
expect(() => {
emitter.off('data', () => {});
}).not.toThrow();
});
it('does not throw when off is called with a listener that was never added', () => {
const emitter = new Emitter<TestEvents>();
emitter.on('data', (payload) => {
void payload;
expect(seen).toEqual(['hello']);
});
expect(() => {
emitter.off('data', () => {});
}).not.toThrow();
});
it('invokes every listener for the same event in registration order', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
it('still delivers to a listener removed by an earlier listener during the same emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const second = (payload: string) => {
seen.push(`second:${payload}`);
};
emitter.on('data', (payload) => {
seen.push(`first:${payload}`);
});
emitter.on('data', (payload) => {
seen.push(`second:${payload}`);
});
emitter.emit('data', 'alpha');
emitter.on('data', (payload) => {
seen.push(`first:${payload}`);
emitter.off('data', second);
expect(seen).toEqual(['first:alpha', 'second:alpha']);
});
emitter.on('data', second);
emitter.emit('data', 'keep');
expect(seen).toEqual(['first:keep', 'second:keep']);
});
it('keeps listeners for different events isolated', () => {
const emitter = new Emitter<TestEvents>();
const data: string[] = [];
const counts: number[] = [];
it('does not deliver to a listener added during the same emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const late = (payload: string) => {
seen.push(`late:${payload}`);
};
emitter.on('data', (payload) => {
data.push(payload);
});
emitter.on('count', (payload) => {
counts.push(payload);
});
emitter.emit('data', 'alpha');
emitter.emit('count', 7);
emitter.emit('data', 'beta');
emitter.on('data', (payload) => {
seen.push(`early:${payload}`);
emitter.on('data', late);
expect(data).toEqual(['alpha', 'beta']);
expect(counts).toEqual([7]);
});
emitter.emit('data', 'now');
emitter.emit('data', 'next');
expect(seen).toEqual(['early:now', 'early:next', 'late:next']);
});
it('passes the payload object through by reference', () => {
const emitter = new Emitter<TestEvents>();
const payload = { code: 1000, reason: 'done' };
const seen: Array<{ code: number; reason: string }> = [];
it('stops all listeners after clear', () => {
const emitter = new Emitter<TestEvents>();
const seen: Array<string | number> = [];
emitter.on('close', (value) => {
seen.push(value);
});
emitter.emit('close', payload);
emitter.on('data', (payload) => {
seen.push(payload);
expect(seen).toEqual([{ code: 1000, reason: 'done' }]);
expect(seen[0]).toBe(payload);
});
emitter.on('count', (payload) => {
seen.push(payload);
it('forwards an undefined payload for events typed as undefined', () => {
const emitter = new Emitter<TestEvents>();
const seen: Array<undefined> = [];
emitter.on('open', (payload) => {
seen.push(payload);
});
emitter.emit('open', undefined);
expect(seen).toEqual([undefined]);
});
emitter.clear();
emitter.emit('data', 'x');
emitter.emit('count', 1);
expect(seen).toEqual([]);
});
it('stores a listener only once when the same function is registered twice', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
it('accepts new listeners after clear', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const listener = (payload: string) => {
seen.push(payload);
};
emitter.on('data', (payload) => {
seen.push(`old:${payload}`);
emitter.on('data', listener);
emitter.on('data', listener);
emitter.emit('data', 'once-only');
expect(seen).toEqual(['once-only']);
});
emitter.clear();
emitter.on('data', (payload) => {
seen.push(`new:${payload}`);
it('returns an unsubscribe function from on that stops later delivery', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.on('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'nope');
expect(seen).toEqual([]);
});
emitter.emit('data', 'after');
expect(seen).toEqual(['new:after']);
});
it('does not throw when emit is called with no listeners for that event', () => {
const emitter = new Emitter<TestEvents>();
it('does not throw when off is called after clear', () => {
const emitter = new Emitter<TestEvents>();
const listener = (payload: string) => {
void payload;
};
expect(() => emitter.emit('data', 'orphan')).not.toThrow();
});
emitter.on('data', listener);
emitter.clear();
it('does not deliver after every listener has been unsubscribed, even if the event key remains', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
expect(() => {
emitter.off('data', listener);
}).not.toThrow();
});
const off = emitter.on('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'ghost');
expect(seen).toEqual([]);
});
it('fires a once listener exactly once', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.once('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'first');
emitter.emit('data', 'second');
expect(seen).toEqual(['first']);
});
it('lets once and on listeners share an event without once firing again', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(`on:${payload}`);
});
emitter.once('data', (payload) => {
seen.push(`once:${payload}`);
});
emitter.emit('data', 'a');
emitter.emit('data', 'b');
expect(seen).toEqual(['on:a', 'once:a', 'on:b']);
});
it('does not call a once listener that was unsubscribed before emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.once('data', (payload) => {
seen.push(payload);
});
off();
emitter.emit('data', 'nope');
expect(seen).toEqual([]);
});
it('allows calling the once unsubscribe after it has already fired', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const off = emitter.once('data', (payload) => {
seen.push(payload);
});
emitter.emit('data', 'first');
off();
emitter.emit('data', 'second');
expect(seen).toEqual(['first']);
});
it('does not re-enter a once listener that emits the same event again', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.once('data', (payload) => {
seen.push(payload);
emitter.emit('data', 'again');
});
emitter.emit('data', 'first');
expect(seen).toEqual(['first']);
});
it('does not cancel a once subscription when off is given the original listener', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const listener = (payload: string) => {
seen.push(payload);
};
emitter.once('data', listener);
emitter.off('data', listener);
emitter.emit('data', 'still');
expect(seen).toEqual(['still']);
});
it('removes only the given listener when off is called', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const keep = (payload: string) => {
seen.push(`keep:${payload}`);
};
const drop = (payload: string) => {
seen.push(`drop:${payload}`);
};
emitter.on('data', keep);
emitter.on('data', drop);
emitter.off('data', drop);
emitter.emit('data', 'x');
expect(seen).toEqual(['keep:x']);
});
it('does not throw when off is called for an event that was never registered', () => {
const emitter = new Emitter<TestEvents>();
expect(() => {
emitter.off('data', () => {});
}).not.toThrow();
});
it('does not throw when off is called with a listener that was never added', () => {
const emitter = new Emitter<TestEvents>();
emitter.on('data', (payload) => {
void payload;
});
expect(() => {
emitter.off('data', () => {});
}).not.toThrow();
});
it('still delivers to a listener removed by an earlier listener during the same emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const second = (payload: string) => {
seen.push(`second:${payload}`);
};
emitter.on('data', (payload) => {
seen.push(`first:${payload}`);
emitter.off('data', second);
});
emitter.on('data', second);
emitter.emit('data', 'keep');
expect(seen).toEqual(['first:keep', 'second:keep']);
});
it('does not deliver to a listener added during the same emit', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
const late = (payload: string) => {
seen.push(`late:${payload}`);
};
emitter.on('data', (payload) => {
seen.push(`early:${payload}`);
emitter.on('data', late);
});
emitter.emit('data', 'now');
emitter.emit('data', 'next');
expect(seen).toEqual(['early:now', 'early:next', 'late:next']);
});
it('stops all listeners after clear', () => {
const emitter = new Emitter<TestEvents>();
const seen: Array<string | number> = [];
emitter.on('data', (payload) => {
seen.push(payload);
});
emitter.on('count', (payload) => {
seen.push(payload);
});
emitter.clear();
emitter.emit('data', 'x');
emitter.emit('count', 1);
expect(seen).toEqual([]);
});
it('accepts new listeners after clear', () => {
const emitter = new Emitter<TestEvents>();
const seen: string[] = [];
emitter.on('data', (payload) => {
seen.push(`old:${payload}`);
});
emitter.clear();
emitter.on('data', (payload) => {
seen.push(`new:${payload}`);
});
emitter.emit('data', 'after');
expect(seen).toEqual(['new:after']);
});
it('does not throw when off is called after clear', () => {
const emitter = new Emitter<TestEvents>();
const listener = (payload: string) => {
void payload;
};
emitter.on('data', listener);
emitter.clear();
expect(() => {
emitter.off('data', listener);
}).not.toThrow();
});
});
+73 -73
View File
@@ -1,88 +1,88 @@
import { describe, expect, it, vi } from 'vitest';
import {
createEventContext,
isGroupMessageEvent,
isPrivateMessageEvent,
matchCommand,
text,
type OneBotPrivateMessageEvent,
type OneBotRequestEvent,
type SnowLumaApiClient,
createEventContext,
isGroupMessageEvent,
isPrivateMessageEvent,
matchCommand,
text,
type OneBotPrivateMessageEvent,
type OneBotRequestEvent,
type SnowLumaApiClient,
} from '../src';
const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
time: 1,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 8,
user_id: 10001,
message: [{ type: 'text', data: { text: '/ping a b' } }],
raw_message: '/ping a b',
font: 0,
sender: { user_id: 10001, nickname: 'tester' },
time: 1,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 8,
user_id: 10001,
message: [{ type: 'text', data: { text: '/ping a b' } }],
raw_message: '/ping a b',
font: 0,
sender: { user_id: 10001, nickname: 'tester' },
};
function fakeClient(): SnowLumaApiClient {
return {
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 2 }),
setFriendAddRequest: vi.fn().mockResolvedValue(null),
setGroupAddRequest: vi.fn().mockResolvedValue(null),
raw: vi.fn().mockResolvedValue(null),
} as unknown as SnowLumaApiClient;
return {
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 2 }),
setFriendAddRequest: vi.fn().mockResolvedValue(null),
setGroupAddRequest: vi.fn().mockResolvedValue(null),
raw: vi.fn().mockResolvedValue(null),
} as unknown as SnowLumaApiClient;
}
describe('event helpers', () => {
it('narrows message event types', () => {
expect(isPrivateMessageEvent(PRIVATE_EVENT)).toBe(true);
expect(isGroupMessageEvent(PRIVATE_EVENT)).toBe(false);
});
it('replies to private messages through context', async () => {
const client = fakeClient();
const context = createEventContext(PRIVATE_EVENT, client);
await context.reply(text('pong'));
expect(client.sendPrivateMessage).toHaveBeenCalledWith(10001, text('pong'), undefined);
});
it('approves and rejects request events', async () => {
const client = fakeClient();
const request: OneBotRequestEvent = {
time: 1,
self_id: 10000,
post_type: 'request',
request_type: 'group',
sub_type: 'invite',
flag: 'flag-1',
};
const context = createEventContext(request, client);
await context.approve();
await context.reject('nope');
expect(client.setGroupAddRequest).toHaveBeenNthCalledWith(1, 'flag-1', {
subType: 'invite',
approve: true,
it('narrows message event types', () => {
expect(isPrivateMessageEvent(PRIVATE_EVENT)).toBe(true);
expect(isGroupMessageEvent(PRIVATE_EVENT)).toBe(false);
});
expect(client.setGroupAddRequest).toHaveBeenNthCalledWith(2, 'flag-1', {
subType: 'invite',
approve: false,
reason: 'nope',
});
});
it('matches commands with prefixes', () => {
expect(matchCommand(PRIVATE_EVENT, 'ping')).toMatchObject({
command: 'ping',
args: ['a', 'b'],
rest: 'a b',
prefix: '/',
it('replies to private messages through context', async () => {
const client = fakeClient();
const context = createEventContext(PRIVATE_EVENT, client);
await context.reply(text('pong'));
expect(client.sendPrivateMessage).toHaveBeenCalledWith(10001, text('pong'), undefined);
});
it('approves and rejects request events', async () => {
const client = fakeClient();
const request: OneBotRequestEvent = {
time: 1,
self_id: 10000,
post_type: 'request',
request_type: 'group',
sub_type: 'invite',
flag: 'flag-1',
};
const context = createEventContext(request, client);
await context.approve();
await context.reject('nope');
expect(client.setGroupAddRequest).toHaveBeenNthCalledWith(1, 'flag-1', {
subType: 'invite',
approve: true,
});
expect(client.setGroupAddRequest).toHaveBeenNthCalledWith(2, 'flag-1', {
subType: 'invite',
approve: false,
reason: 'nope',
});
});
it('matches commands with prefixes', () => {
expect(matchCommand(PRIVATE_EVENT, 'ping')).toMatchObject({
command: 'ping',
args: ['a', 'b'],
rest: 'a b',
prefix: '/',
});
expect(matchCommand(PRIVATE_EVENT, 'pong')).toBeNull();
});
expect(matchCommand(PRIVATE_EVENT, 'pong')).toBeNull();
});
});
+416 -400
View File
@@ -1,479 +1,495 @@
import { describe, expect, it } from 'vitest';
import {
isBotStatusEvent,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
noticeType,
requestType,
type OneBotGroupMessageEvent,
type OneBotMetaEvent,
type OneBotNoticeEvent,
type OneBotPrivateMessageEvent,
type OneBotRequestEvent,
type SnowLumaEvent,
isBotStatusEvent,
isGroupMessageEvent,
isMessageEvent,
isMetaEvent,
isNoticeEvent,
isPrivateMessageEvent,
isRequestEvent,
noticeType,
requestType,
type OneBotGroupMessageEvent,
type OneBotMetaEvent,
type OneBotNoticeEvent,
type OneBotPrivateMessageEvent,
type OneBotRequestEvent,
type SnowLumaEvent,
} from '../src';
const PRIVATE_MESSAGE: OneBotPrivateMessageEvent = {
time: 1_700_000_001,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 11,
message_seq: 12,
user_id: 20001,
message: [{ type: 'text', data: { text: 'hi' } }],
raw_message: 'hi',
font: 0,
sender: { user_id: 20001, nickname: 'alice' },
time: 1_700_000_001,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 11,
message_seq: 12,
user_id: 20001,
message: [{ type: 'text', data: { text: 'hi' } }],
raw_message: 'hi',
font: 0,
sender: { user_id: 20001, nickname: 'alice' },
};
const PRIVATE_SENT: OneBotPrivateMessageEvent = {
time: 1_700_000_002,
self_id: 10000,
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
message_id: 13,
user_id: 20002,
message: 'echo',
raw_message: 'echo',
font: 0,
sender: { user_id: 10000, nickname: 'bot' },
time: 1_700_000_002,
self_id: 10000,
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
message_id: 13,
user_id: 20002,
message: 'echo',
raw_message: 'echo',
font: 0,
sender: { user_id: 10000, nickname: 'bot' },
};
const GROUP_MESSAGE: OneBotGroupMessageEvent = {
time: 1_700_000_003,
self_id: 10000,
post_type: 'message',
message_type: 'group',
sub_type: 'normal',
message_id: 21,
message_seq: 22,
group_id: 30001,
user_id: 20003,
message: [{ type: 'text', data: { text: 'hey' } }],
raw_message: 'hey',
font: 0,
sender: { user_id: 20003, nickname: 'bob', card: 'Bobby', role: 'member' },
time: 1_700_000_003,
self_id: 10000,
post_type: 'message',
message_type: 'group',
sub_type: 'normal',
message_id: 21,
message_seq: 22,
group_id: 30001,
user_id: 20003,
message: [{ type: 'text', data: { text: 'hey' } }],
raw_message: 'hey',
font: 0,
sender: { user_id: 20003, nickname: 'bob', card: 'Bobby', role: 'member' },
};
const GROUP_SENT: OneBotGroupMessageEvent = {
time: 1_700_000_004,
self_id: 10000,
post_type: 'message_sent',
message_type: 'group',
sub_type: 'normal',
message_id: 23,
group_id: 30002,
user_id: 10000,
message: 'sent',
raw_message: 'sent',
font: 0,
sender: { user_id: 10000, nickname: 'bot' },
time: 1_700_000_004,
self_id: 10000,
post_type: 'message_sent',
message_type: 'group',
sub_type: 'normal',
message_id: 23,
group_id: 30002,
user_id: 10000,
message: 'sent',
raw_message: 'sent',
font: 0,
sender: { user_id: 10000, nickname: 'bot' },
};
const NOTICE: OneBotNoticeEvent = {
time: 1_700_000_005,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_increase',
time: 1_700_000_005,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_increase',
};
const REQUEST: OneBotRequestEvent = {
time: 1_700_000_006,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: 'flag-friend-1',
user_id: 20004,
comment: 'please',
time: 1_700_000_006,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: 'flag-friend-1',
user_id: 20004,
comment: 'please',
};
const META: OneBotMetaEvent = {
time: 1_700_000_007,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 'heartbeat',
time: 1_700_000_007,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 'heartbeat',
};
const UNKNOWN: SnowLumaEvent = {
time: 1_700_000_008,
self_id: 10000,
post_type: 'unknown',
time: 1_700_000_008,
self_id: 10000,
post_type: 'unknown',
};
describe('isMessageEvent', () => {
it('accepts inbound private and group messages', () => {
expect(isMessageEvent(PRIVATE_MESSAGE)).toBe(true);
expect(isMessageEvent(GROUP_MESSAGE)).toBe(true);
});
it('accepts inbound private and group messages', () => {
expect(isMessageEvent(PRIVATE_MESSAGE)).toBe(true);
expect(isMessageEvent(GROUP_MESSAGE)).toBe(true);
});
it('accepts message_sent private and group events', () => {
expect(isMessageEvent(PRIVATE_SENT)).toBe(true);
expect(isMessageEvent(GROUP_SENT)).toBe(true);
});
it('accepts message_sent private and group events', () => {
expect(isMessageEvent(PRIVATE_SENT)).toBe(true);
expect(isMessageEvent(GROUP_SENT)).toBe(true);
});
it('rejects message post types whose message_type is not private or group', () => {
const guild: SnowLumaEvent = {
time: 9,
self_id: 10000,
post_type: 'message',
message_type: 'guild',
};
const sentChannel: SnowLumaEvent = {
time: 10,
self_id: 10000,
post_type: 'message_sent',
message_type: 'channel',
};
const missingType: SnowLumaEvent = {
time: 11,
self_id: 10000,
post_type: 'message',
};
it('rejects message post types whose message_type is not private or group', () => {
const guild: SnowLumaEvent = {
time: 9,
self_id: 10000,
post_type: 'message',
message_type: 'guild',
};
const sentChannel: SnowLumaEvent = {
time: 10,
self_id: 10000,
post_type: 'message_sent',
message_type: 'channel',
};
const missingType: SnowLumaEvent = {
time: 11,
self_id: 10000,
post_type: 'message',
};
expect(isMessageEvent(guild)).toBe(false);
expect(isMessageEvent(sentChannel)).toBe(false);
expect(isMessageEvent(missingType)).toBe(false);
});
expect(isMessageEvent(guild)).toBe(false);
expect(isMessageEvent(sentChannel)).toBe(false);
expect(isMessageEvent(missingType)).toBe(false);
});
it('rejects non-message events even when message_type is present', () => {
const noticeShaped: SnowLumaEvent = {
time: 12,
self_id: 10000,
post_type: 'notice',
notice_type: 'notify',
message_type: 'private',
};
it('rejects non-message events even when message_type is present', () => {
const noticeShaped: SnowLumaEvent = {
time: 12,
self_id: 10000,
post_type: 'notice',
notice_type: 'notify',
message_type: 'private',
};
expect(isMessageEvent(NOTICE)).toBe(false);
expect(isMessageEvent(REQUEST)).toBe(false);
expect(isMessageEvent(META)).toBe(false);
expect(isMessageEvent(UNKNOWN)).toBe(false);
expect(isMessageEvent(noticeShaped)).toBe(false);
});
expect(isMessageEvent(NOTICE)).toBe(false);
expect(isMessageEvent(REQUEST)).toBe(false);
expect(isMessageEvent(META)).toBe(false);
expect(isMessageEvent(UNKNOWN)).toBe(false);
expect(isMessageEvent(noticeShaped)).toBe(false);
});
});
describe('isPrivateMessageEvent', () => {
it('accepts private inbound and sent messages', () => {
expect(isPrivateMessageEvent(PRIVATE_MESSAGE)).toBe(true);
expect(isPrivateMessageEvent(PRIVATE_SENT)).toBe(true);
});
it('accepts private inbound and sent messages', () => {
expect(isPrivateMessageEvent(PRIVATE_MESSAGE)).toBe(true);
expect(isPrivateMessageEvent(PRIVATE_SENT)).toBe(true);
});
it('rejects group messages and non-message events', () => {
expect(isPrivateMessageEvent(GROUP_MESSAGE)).toBe(false);
expect(isPrivateMessageEvent(GROUP_SENT)).toBe(false);
expect(isPrivateMessageEvent(NOTICE)).toBe(false);
expect(isPrivateMessageEvent(REQUEST)).toBe(false);
expect(isPrivateMessageEvent(META)).toBe(false);
});
it('rejects group messages and non-message events', () => {
expect(isPrivateMessageEvent(GROUP_MESSAGE)).toBe(false);
expect(isPrivateMessageEvent(GROUP_SENT)).toBe(false);
expect(isPrivateMessageEvent(NOTICE)).toBe(false);
expect(isPrivateMessageEvent(REQUEST)).toBe(false);
expect(isPrivateMessageEvent(META)).toBe(false);
});
it('rejects private message_type when post_type is not a message kind', () => {
const leftover: SnowLumaEvent = {
time: 13,
self_id: 10000,
post_type: 'notice',
notice_type: 'friend_add',
message_type: 'private',
};
it('rejects private message_type when post_type is not a message kind', () => {
const leftover: SnowLumaEvent = {
time: 13,
self_id: 10000,
post_type: 'notice',
notice_type: 'friend_add',
message_type: 'private',
};
expect(isPrivateMessageEvent(leftover)).toBe(false);
});
expect(isPrivateMessageEvent(leftover)).toBe(false);
});
});
describe('isGroupMessageEvent', () => {
it('accepts group inbound and sent messages', () => {
expect(isGroupMessageEvent(GROUP_MESSAGE)).toBe(true);
expect(isGroupMessageEvent(GROUP_SENT)).toBe(true);
});
it('accepts group inbound and sent messages', () => {
expect(isGroupMessageEvent(GROUP_MESSAGE)).toBe(true);
expect(isGroupMessageEvent(GROUP_SENT)).toBe(true);
});
it('rejects private messages and non-message events', () => {
expect(isGroupMessageEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isGroupMessageEvent(PRIVATE_SENT)).toBe(false);
expect(isGroupMessageEvent(NOTICE)).toBe(false);
expect(isGroupMessageEvent(REQUEST)).toBe(false);
expect(isGroupMessageEvent(META)).toBe(false);
});
it('rejects private messages and non-message events', () => {
expect(isGroupMessageEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isGroupMessageEvent(PRIVATE_SENT)).toBe(false);
expect(isGroupMessageEvent(NOTICE)).toBe(false);
expect(isGroupMessageEvent(REQUEST)).toBe(false);
expect(isGroupMessageEvent(META)).toBe(false);
});
it('rejects group message_type when post_type is not a message kind', () => {
const leftover: SnowLumaEvent = {
time: 14,
self_id: 10000,
post_type: 'request',
request_type: 'group',
flag: 'flag-x',
message_type: 'group',
};
it('rejects group message_type when post_type is not a message kind', () => {
const leftover: SnowLumaEvent = {
time: 14,
self_id: 10000,
post_type: 'request',
request_type: 'group',
flag: 'flag-x',
message_type: 'group',
};
expect(isGroupMessageEvent(leftover)).toBe(false);
});
expect(isGroupMessageEvent(leftover)).toBe(false);
});
});
describe('isNoticeEvent', () => {
it('accepts notice events with a string notice_type', () => {
expect(isNoticeEvent(NOTICE)).toBe(true);
expect(isNoticeEvent({
time: 15,
self_id: 10000,
post_type: 'notice',
notice_type: '',
})).toBe(true);
});
it('accepts notice events with a string notice_type', () => {
expect(isNoticeEvent(NOTICE)).toBe(true);
expect(
isNoticeEvent({
time: 15,
self_id: 10000,
post_type: 'notice',
notice_type: '',
}),
).toBe(true);
});
it('rejects notice post_type when notice_type is not a string', () => {
const missing: SnowLumaEvent = {
time: 16,
self_id: 10000,
post_type: 'notice',
};
const numeric: SnowLumaEvent = {
time: 17,
self_id: 10000,
post_type: 'notice',
notice_type: 7,
};
const nulled: SnowLumaEvent = {
time: 18,
self_id: 10000,
post_type: 'notice',
notice_type: null,
};
it('rejects notice post_type when notice_type is not a string', () => {
const missing: SnowLumaEvent = {
time: 16,
self_id: 10000,
post_type: 'notice',
};
const numeric: SnowLumaEvent = {
time: 17,
self_id: 10000,
post_type: 'notice',
notice_type: 7,
};
const nulled: SnowLumaEvent = {
time: 18,
self_id: 10000,
post_type: 'notice',
notice_type: null,
};
expect(isNoticeEvent(missing)).toBe(false);
expect(isNoticeEvent(numeric)).toBe(false);
expect(isNoticeEvent(nulled)).toBe(false);
});
expect(isNoticeEvent(missing)).toBe(false);
expect(isNoticeEvent(numeric)).toBe(false);
expect(isNoticeEvent(nulled)).toBe(false);
});
it('accepts bot_status notices and rejects incomplete ones', () => {
expect(isBotStatusEvent({
time: 19,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'online',
user_id: 10000,
})).toBe(true);
expect(isBotStatusEvent({
time: 20,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'offline',
user_id: 10000,
})).toBe(true);
expect(isBotStatusEvent(NOTICE)).toBe(false);
expect(isBotStatusEvent({
time: 21,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'flap',
user_id: 10000,
})).toBe(false);
});
it('accepts bot_status notices and rejects incomplete ones', () => {
expect(
isBotStatusEvent({
time: 19,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'online',
user_id: 10000,
}),
).toBe(true);
expect(
isBotStatusEvent({
time: 20,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'offline',
user_id: 10000,
}),
).toBe(true);
expect(isBotStatusEvent(NOTICE)).toBe(false);
expect(
isBotStatusEvent({
time: 21,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'flap',
user_id: 10000,
}),
).toBe(false);
});
it('rejects other post types', () => {
expect(isNoticeEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isNoticeEvent(REQUEST)).toBe(false);
expect(isNoticeEvent(META)).toBe(false);
expect(isNoticeEvent(UNKNOWN)).toBe(false);
});
it('rejects other post types', () => {
expect(isNoticeEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isNoticeEvent(REQUEST)).toBe(false);
expect(isNoticeEvent(META)).toBe(false);
expect(isNoticeEvent(UNKNOWN)).toBe(false);
});
});
describe('isRequestEvent', () => {
it('accepts request events with string request_type and flag', () => {
expect(isRequestEvent(REQUEST)).toBe(true);
expect(isRequestEvent({
time: 19,
self_id: 10000,
post_type: 'request',
request_type: 'group',
sub_type: 'add',
flag: '',
group_id: 30003,
})).toBe(true);
});
it('accepts request events with string request_type and flag', () => {
expect(isRequestEvent(REQUEST)).toBe(true);
expect(
isRequestEvent({
time: 19,
self_id: 10000,
post_type: 'request',
request_type: 'group',
sub_type: 'add',
flag: '',
group_id: 30003,
}),
).toBe(true);
});
it('rejects request post_type when request_type or flag is not a string', () => {
const missingFlag: SnowLumaEvent = {
time: 20,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
};
const numericFlag: SnowLumaEvent = {
time: 21,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: 99,
};
const missingType: SnowLumaEvent = {
time: 22,
self_id: 10000,
post_type: 'request',
flag: 'flag-2',
};
const numericType: SnowLumaEvent = {
time: 23,
self_id: 10000,
post_type: 'request',
request_type: 1,
flag: 'flag-3',
};
const nullFlag: SnowLumaEvent = {
time: 24,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: null,
};
it('rejects request post_type when request_type or flag is not a string', () => {
const missingFlag: SnowLumaEvent = {
time: 20,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
};
const numericFlag: SnowLumaEvent = {
time: 21,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: 99,
};
const missingType: SnowLumaEvent = {
time: 22,
self_id: 10000,
post_type: 'request',
flag: 'flag-2',
};
const numericType: SnowLumaEvent = {
time: 23,
self_id: 10000,
post_type: 'request',
request_type: 1,
flag: 'flag-3',
};
const nullFlag: SnowLumaEvent = {
time: 24,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
flag: null,
};
expect(isRequestEvent(missingFlag)).toBe(false);
expect(isRequestEvent(numericFlag)).toBe(false);
expect(isRequestEvent(missingType)).toBe(false);
expect(isRequestEvent(numericType)).toBe(false);
expect(isRequestEvent(nullFlag)).toBe(false);
});
expect(isRequestEvent(missingFlag)).toBe(false);
expect(isRequestEvent(numericFlag)).toBe(false);
expect(isRequestEvent(missingType)).toBe(false);
expect(isRequestEvent(numericType)).toBe(false);
expect(isRequestEvent(nullFlag)).toBe(false);
});
it('rejects other post types even when request fields are present', () => {
const leftover: SnowLumaEvent = {
time: 25,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_ban',
request_type: 'group',
flag: 'flag-4',
};
it('rejects other post types even when request fields are present', () => {
const leftover: SnowLumaEvent = {
time: 25,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_ban',
request_type: 'group',
flag: 'flag-4',
};
expect(isRequestEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isRequestEvent(NOTICE)).toBe(false);
expect(isRequestEvent(META)).toBe(false);
expect(isRequestEvent(leftover)).toBe(false);
});
expect(isRequestEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isRequestEvent(NOTICE)).toBe(false);
expect(isRequestEvent(META)).toBe(false);
expect(isRequestEvent(leftover)).toBe(false);
});
});
describe('isMetaEvent', () => {
it('accepts meta_event events with a string meta_event_type', () => {
expect(isMetaEvent(META)).toBe(true);
expect(isMetaEvent({
time: 26,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 'lifecycle',
})).toBe(true);
});
it('accepts meta_event events with a string meta_event_type', () => {
expect(isMetaEvent(META)).toBe(true);
expect(
isMetaEvent({
time: 26,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 'lifecycle',
}),
).toBe(true);
});
it('rejects meta_event post_type when meta_event_type is not a string', () => {
const missing: SnowLumaEvent = {
time: 27,
self_id: 10000,
post_type: 'meta_event',
};
const numeric: SnowLumaEvent = {
time: 28,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 0,
};
const nulled: SnowLumaEvent = {
time: 29,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: null,
};
it('rejects meta_event post_type when meta_event_type is not a string', () => {
const missing: SnowLumaEvent = {
time: 27,
self_id: 10000,
post_type: 'meta_event',
};
const numeric: SnowLumaEvent = {
time: 28,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: 0,
};
const nulled: SnowLumaEvent = {
time: 29,
self_id: 10000,
post_type: 'meta_event',
meta_event_type: null,
};
expect(isMetaEvent(missing)).toBe(false);
expect(isMetaEvent(numeric)).toBe(false);
expect(isMetaEvent(nulled)).toBe(false);
});
expect(isMetaEvent(missing)).toBe(false);
expect(isMetaEvent(numeric)).toBe(false);
expect(isMetaEvent(nulled)).toBe(false);
});
it('rejects other post types', () => {
expect(isMetaEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isMetaEvent(NOTICE)).toBe(false);
expect(isMetaEvent(REQUEST)).toBe(false);
expect(isMetaEvent(UNKNOWN)).toBe(false);
});
it('rejects other post types', () => {
expect(isMetaEvent(PRIVATE_MESSAGE)).toBe(false);
expect(isMetaEvent(NOTICE)).toBe(false);
expect(isMetaEvent(REQUEST)).toBe(false);
expect(isMetaEvent(UNKNOWN)).toBe(false);
});
});
describe('noticeType', () => {
it('matches notice events by notice_type', () => {
const isIncrease = noticeType('group_increase');
const isDecrease = noticeType('group_decrease');
it('matches notice events by notice_type', () => {
const isIncrease = noticeType('group_increase');
const isDecrease = noticeType('group_decrease');
expect(isIncrease(NOTICE)).toBe(true);
expect(isDecrease(NOTICE)).toBe(false);
expect(isIncrease({
time: 30,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_decrease',
})).toBe(false);
});
expect(isIncrease(NOTICE)).toBe(true);
expect(isDecrease(NOTICE)).toBe(false);
expect(
isIncrease({
time: 30,
self_id: 10000,
post_type: 'notice',
notice_type: 'group_decrease',
}),
).toBe(false);
});
it('rejects events that fail isNoticeEvent', () => {
const isIncrease = noticeType('group_increase');
const missingType: SnowLumaEvent = {
time: 31,
self_id: 10000,
post_type: 'notice',
};
const leftover: SnowLumaEvent = {
time: 32,
self_id: 10000,
post_type: 'message',
message_type: 'private',
notice_type: 'group_increase',
};
it('rejects events that fail isNoticeEvent', () => {
const isIncrease = noticeType('group_increase');
const missingType: SnowLumaEvent = {
time: 31,
self_id: 10000,
post_type: 'notice',
};
const leftover: SnowLumaEvent = {
time: 32,
self_id: 10000,
post_type: 'message',
message_type: 'private',
notice_type: 'group_increase',
};
expect(isIncrease(missingType)).toBe(false);
expect(isIncrease(leftover)).toBe(false);
expect(isIncrease(REQUEST)).toBe(false);
expect(isIncrease(PRIVATE_MESSAGE)).toBe(false);
});
expect(isIncrease(missingType)).toBe(false);
expect(isIncrease(leftover)).toBe(false);
expect(isIncrease(REQUEST)).toBe(false);
expect(isIncrease(PRIVATE_MESSAGE)).toBe(false);
});
});
describe('requestType', () => {
it('matches request events by request_type', () => {
const isFriend = requestType('friend');
const isGroup = requestType('group');
it('matches request events by request_type', () => {
const isFriend = requestType('friend');
const isGroup = requestType('group');
expect(isFriend(REQUEST)).toBe(true);
expect(isGroup(REQUEST)).toBe(false);
expect(isFriend({
time: 33,
self_id: 10000,
post_type: 'request',
request_type: 'group',
flag: 'flag-group-1',
})).toBe(false);
});
expect(isFriend(REQUEST)).toBe(true);
expect(isGroup(REQUEST)).toBe(false);
expect(
isFriend({
time: 33,
self_id: 10000,
post_type: 'request',
request_type: 'group',
flag: 'flag-group-1',
}),
).toBe(false);
});
it('rejects events that fail isRequestEvent', () => {
const isFriend = requestType('friend');
const missingFlag: SnowLumaEvent = {
time: 34,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
};
const leftover: SnowLumaEvent = {
time: 35,
self_id: 10000,
post_type: 'notice',
notice_type: 'friend_add',
request_type: 'friend',
flag: 'flag-5',
};
it('rejects events that fail isRequestEvent', () => {
const isFriend = requestType('friend');
const missingFlag: SnowLumaEvent = {
time: 34,
self_id: 10000,
post_type: 'request',
request_type: 'friend',
};
const leftover: SnowLumaEvent = {
time: 35,
self_id: 10000,
post_type: 'notice',
notice_type: 'friend_add',
request_type: 'friend',
flag: 'flag-5',
};
expect(isFriend(missingFlag)).toBe(false);
expect(isFriend(leftover)).toBe(false);
expect(isFriend(NOTICE)).toBe(false);
expect(isFriend(META)).toBe(false);
});
expect(isFriend(missingFlag)).toBe(false);
expect(isFriend(leftover)).toBe(false);
expect(isFriend(NOTICE)).toBe(false);
expect(isFriend(META)).toBe(false);
});
});
+126 -97
View File
@@ -1,115 +1,144 @@
import { describe, expect, it, vi } from 'vitest';
import {
SnowLumaAbortError,
SnowLumaAuthError,
SnowLumaHttpClient,
SnowLumaParseError,
SnowLumaAbortError,
SnowLumaAuthError,
SnowLumaHttpClient,
SnowLumaParseError,
} from '../src';
describe('SnowLumaHttpClient', () => {
it('maps extended group-info refresh options to OneBot field names', async () => {
const fetchImpl = vi.fn().mockImplementation(async () => new Response(JSON.stringify({
status: 'ok',
retcode: 0,
data: null,
})));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
it('maps extended group-info refresh options to OneBot field names', async () => {
const fetchImpl = vi.fn().mockImplementation(
async () =>
new Response(
JSON.stringify({
status: 'ok',
retcode: 0,
data: null,
}),
),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await client.getGroupInfoEx(123456, { noCache: true });
await client.getGroupDetailInfo(123456, { noCache: true });
await client.getGroupInfoEx(123456, { noCache: true });
await client.getGroupDetailInfo(123456, { noCache: true });
expect(fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string))).toEqual([
{ action: 'get_group_info_ex', params: { group_id: 123456, no_cache: true } },
{ action: 'get_group_detail_info', params: { group_id: 123456, no_cache: true } },
]);
});
it('maps system-face catalog helpers to their OneBot actions', async () => {
const fetchImpl = vi.fn().mockImplementation(async () => new Response(JSON.stringify({
status: 'ok',
retcode: 0,
data: null,
})));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await client.fetchSysFaces(true);
await client.fetchFaceEntity(392, { refresh: true });
await client.searchSysFaces('dragon');
await client.fetchSuperFaceId(392);
expect(fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string))).toEqual([
{ action: 'fetch_sys_faces', params: { refresh: true } },
{ action: 'fetch_face_entity', params: { face_id: 392, refresh: true } },
{ action: 'search_sys_faces', params: { query: 'dragon' } },
{ action: 'fetch_super_face_id', params: { face_id: 392, refresh: false } },
]);
});
it('maps group-announcement options to their OneBot field names', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response(JSON.stringify({
status: 'ok',
retcode: 0,
data: null,
})));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await client.sendGroupNotice(941657197, 'welcome', {
pinned: 1,
type: 20,
sendToNewMembers: true,
isShowEditCard: 0,
tipWindowType: 0,
confirmRequired: 0,
expect(
fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string)),
).toEqual([
{ action: 'get_group_info_ex', params: { group_id: 123456, no_cache: true } },
{ action: 'get_group_detail_info', params: { group_id: 123456, no_cache: true } },
]);
});
const init = fetchImpl.mock.calls[0]![1] as RequestInit;
expect(JSON.parse(init.body as string)).toEqual({
action: '_send_group_notice',
params: {
group_id: 941657197,
content: 'welcome',
pinned: 1,
type: 20,
send_to_new_members: true,
is_show_edit_card: 0,
tip_window_type: 0,
confirm_required: 0,
},
it('maps system-face catalog helpers to their OneBot actions', async () => {
const fetchImpl = vi.fn().mockImplementation(
async () =>
new Response(
JSON.stringify({
status: 'ok',
retcode: 0,
data: null,
}),
),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await client.fetchSysFaces(true);
await client.fetchFaceEntity(392, { refresh: true });
await client.searchSysFaces('dragon');
await client.fetchSuperFaceId(392);
expect(
fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string)),
).toEqual([
{ action: 'fetch_sys_faces', params: { refresh: true } },
{ action: 'fetch_face_entity', params: { face_id: 392, refresh: true } },
{ action: 'search_sys_faces', params: { query: 'dragon' } },
{ action: 'fetch_super_face_id', params: { face_id: 392, refresh: false } },
]);
});
});
it('throws SnowLumaAuthError for auth retcodes', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response(JSON.stringify({
status: 'failed',
retcode: 1401,
data: null,
wording: 'unauthorized',
})));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
it('maps group-announcement options to their OneBot field names', async () => {
const fetchImpl = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
status: 'ok',
retcode: 0,
data: null,
}),
),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaAuthError);
});
await client.sendGroupNotice(941657197, 'welcome', {
pinned: 1,
type: 20,
sendToNewMembers: true,
isShowEditCard: 0,
tipWindowType: 0,
confirmRequired: 0,
});
it('throws SnowLumaParseError for non-JSON responses', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response('not json', { status: 200 }));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const init = fetchImpl.mock.calls[0]![1] as RequestInit;
expect(JSON.parse(init.body as string)).toEqual({
action: '_send_group_notice',
params: {
group_id: 941657197,
content: 'welcome',
pinned: 1,
type: 20,
send_to_new_members: true,
is_show_edit_card: 0,
tip_window_type: 0,
confirm_required: 0,
},
});
});
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaParseError);
});
it('throws SnowLumaAuthError for auth retcodes', async () => {
const fetchImpl = vi.fn().mockResolvedValue(
new Response(
JSON.stringify({
status: 'failed',
retcode: 1401,
data: null,
wording: 'unauthorized',
}),
),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
it('supports caller AbortSignal cancellation', async () => {
const fetchImpl = vi.fn((_url: string | URL | Request, init?: RequestInit) => new Promise<Response>((_resolve, reject) => {
const signal = init?.signal;
const abort = () => reject(new DOMException('aborted', 'AbortError'));
if (signal?.aborted) abort();
signal?.addEventListener('abort', abort, { once: true });
}));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const controller = new AbortController();
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaAuthError);
});
const request = client.getStatus({ signal: controller.signal });
controller.abort();
it('throws SnowLumaParseError for non-JSON responses', async () => {
const fetchImpl = vi.fn().mockResolvedValue(new Response('not json', { status: 200 }));
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
await expect(request).rejects.toBeInstanceOf(SnowLumaAbortError);
});
await expect(client.getStatus()).rejects.toBeInstanceOf(SnowLumaParseError);
});
it('supports caller AbortSignal cancellation', async () => {
const fetchImpl = vi.fn(
(_url: string | URL | Request, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
const signal = init?.signal;
const abort = () => reject(new DOMException('aborted', 'AbortError'));
if (signal?.aborted) {
abort();
}
signal?.addEventListener('abort', abort, { once: true });
}),
);
const client = new SnowLumaHttpClient({ fetch: fetchImpl });
const controller = new AbortController();
const request = client.getStatus({ signal: controller.signal });
controller.abort();
await expect(request).rejects.toBeInstanceOf(SnowLumaAbortError);
});
});
+72 -72
View File
@@ -1,87 +1,87 @@
import { describe, expect, it, vi } from 'vitest';
import {
atAll,
chain,
face,
fromCQString,
message,
parseSegments,
text,
toCQString,
} from '../src';
import { atAll, chain, face, fromCQString, message, parseSegments, text, toCQString } from '../src';
describe('MessageChain', () => {
it.each([undefined, true])('preserves animation results through builders and CQ with large=%s', (large) => {
const options = { resultId: '0', ...(large !== undefined ? { large } : {}) };
const expected = [{ type: 'face', data: { id: '114', ...options } }];
expect(face(114, options).toSegments()).toEqual(expected);
expect(chain().face(114, options).toSegments()).toEqual(expected);
expect(message.face(114, options)).toEqual(expected[0]);
expect(parseSegments(toCQString(face(114, options)))).toEqual(expected);
});
it.each([undefined, true])(
'preserves animation results through builders and CQ with large=%s',
(large) => {
const options = { resultId: '0', ...(large !== undefined ? { large } : {}) };
const expected = [{ type: 'face', data: { id: '114', ...options } }];
expect(face(114, options).toSegments()).toEqual(expected);
expect(chain().face(114, options).toSegments()).toEqual(expected);
expect(message.face(114, options)).toEqual(expected[0]);
expect(parseSegments(toCQString(face(114, options)))).toEqual(expected);
},
);
it.each([false, true])('preserves face animation selection through builders and CQ, large=%s', (large) => {
const expected = [{ type: 'face', data: { id: '451', large } }];
const built = face(451, { large });
expect(built.toSegments()).toEqual(expected);
expect(chain().face(451, { large }).toSegments()).toEqual(expected);
expect(message.face(451, { large })).toEqual(expected[0]);
expect(parseSegments(toCQString(built))).toEqual(expected);
expect(parseSegments(`[CQ:face,id=451,large=${large ? 1 : 0}]`)).toEqual(expected);
});
it.each([false, true])(
'preserves face animation selection through builders and CQ, large=%s',
(large) => {
const expected = [{ type: 'face', data: { id: '451', large } }];
const built = face(451, { large });
expect(built.toSegments()).toEqual(expected);
expect(chain().face(451, { large }).toSegments()).toEqual(expected);
expect(message.face(451, { large })).toEqual(expected[0]);
expect(parseSegments(toCQString(built))).toEqual(expected);
expect(parseSegments(`[CQ:face,id=451,large=${large ? 1 : 0}]`)).toEqual(expected);
},
);
it('rejects an invalid face animation choice instead of discarding it', () => {
expect(() => parseSegments('[CQ:face,id=451,large=invalid]')).toThrow('face.large');
});
it('rejects an invalid face animation choice instead of discarding it', () => {
expect(() => parseSegments('[CQ:face,id=451,large=invalid]')).toThrow('face.large');
});
it('builds fluent segment chains', () => {
const chain = text('hello').at(10001).br().image('/tmp/a.png');
it('builds fluent segment chains', () => {
const chain = text('hello').at(10001).br().image('/tmp/a.png');
expect(chain.length).toBe(4);
expect(chain.toSegments()).toEqual([
{ type: 'text', data: { text: 'hello' } },
{ type: 'at', data: { qq: '10001' } },
{ type: 'text', data: { text: '\n' } },
{ type: 'image', data: { file: '/tmp/a.png' } },
]);
});
expect(chain.length).toBe(4);
expect(chain.toSegments()).toEqual([
{ type: 'text', data: { text: 'hello' } },
{ type: 'at', data: { qq: '10001' } },
{ type: 'text', data: { text: '\n' } },
{ type: 'image', data: { file: '/tmp/a.png' } },
]);
});
it('keeps the old segment builder API available', () => {
expect(message.text('hello')).toEqual({ type: 'text', data: { text: 'hello' } });
expect(atAll().toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
});
it('keeps the old segment builder API available', () => {
expect(message.text('hello')).toEqual({ type: 'text', data: { text: 'hello' } });
expect(atAll().toSegments()).toEqual([{ type: 'at', data: { qq: 'all' } }]);
});
it('allows reply only once in a chain at runtime', () => {
const chain = text('hello').reply(1);
expect(() => (chain as any).reply(2)).toThrow(/reply/);
expect(() => chain.append(message.reply(2))).toThrow(/reply/);
});
it('allows reply only once in a chain at runtime', () => {
const chain = text('hello').reply(1);
expect(() => (chain as any).reply(2)).toThrow(/reply/);
expect(() => chain.append(message.reply(2))).toThrow(/reply/);
});
it('appends other messages and converts to CQ string', () => {
const chain = text('hello').append([message.at('all'), message.face(14)]);
expect(toCQString(chain)).toBe('hello[CQ:at,qq=all][CQ:face,id=14]');
});
it('appends other messages and converts to CQ string', () => {
const chain = text('hello').append([message.at('all'), message.face(14)]);
expect(toCQString(chain)).toBe('hello[CQ:at,qq=all][CQ:face,id=14]');
});
it('parses CQ strings into chains', () => {
const chain = fromCQString('hi[CQ:at,qq=all][CQ:image,file=a&#44;b]');
expect(chain.toSegments()).toEqual([
{ type: 'text', data: { text: 'hi' } },
{ type: 'at', data: { qq: 'all' } },
{ type: 'image', data: { file: 'a,b', url: undefined, type: undefined, summary: undefined } },
]);
expect(parseSegments('[CQ:reply,id=7]')).toEqual([{ type: 'reply', data: { id: '7' } }]);
});
it('parses CQ strings into chains', () => {
const chain = fromCQString('hi[CQ:at,qq=all][CQ:image,file=a&#44;b]');
expect(chain.toSegments()).toEqual([
{ type: 'text', data: { text: 'hi' } },
{ type: 'at', data: { qq: 'all' } },
{
type: 'image',
data: { file: 'a,b', url: undefined, type: undefined, summary: undefined },
},
]);
expect(parseSegments('[CQ:reply,id=7]')).toEqual([{ type: 'reply', data: { id: '7' } }]);
});
it('can send itself through a compatible client', async () => {
const client = {
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 2 }),
};
it('can send itself through a compatible client', async () => {
const client = {
sendGroupMessage: vi.fn().mockResolvedValue({ message_id: 1 }),
sendPrivateMessage: vi.fn().mockResolvedValue({ message_id: 2 }),
};
await text('hi').sendToGroup(client, 123);
await text('yo').sendToPrivate(client, 456);
await text('hi').sendToGroup(client, 123);
await text('yo').sendToPrivate(client, 456);
expect(client.sendGroupMessage).toHaveBeenCalledWith(123, text('hi'), undefined);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(456, text('yo'), undefined);
});
expect(client.sendGroupMessage).toHaveBeenCalledWith(123, text('hi'), undefined);
expect(client.sendPrivateMessage).toHaveBeenCalledWith(456, text('yo'), undefined);
});
});
+246 -246
View File
@@ -2,346 +2,346 @@ import { describe, expect, it } from 'vitest';
import { segments } from '../src/messages/segments';
describe('segments.text', () => {
it('wraps a string as a text segment', () => {
expect(segments.text('hello')).toEqual({ type: 'text', data: { text: 'hello' } });
});
it('wraps a string as a text segment', () => {
expect(segments.text('hello')).toEqual({ type: 'text', data: { text: 'hello' } });
});
it('keeps empty text', () => {
expect(segments.text('')).toEqual({ type: 'text', data: { text: '' } });
});
it('keeps empty text', () => {
expect(segments.text('')).toEqual({ type: 'text', data: { text: '' } });
});
});
describe('segments.face', () => {
it('stringifies a numeric face id', () => {
expect(segments.face(14)).toEqual({ type: 'face', data: { id: '14' } });
});
it('stringifies a numeric face id', () => {
expect(segments.face(14)).toEqual({ type: 'face', data: { id: '14' } });
});
it('keeps a string face id', () => {
expect(segments.face('178')).toEqual({ type: 'face', data: { id: '178' } });
});
it('keeps a string face id', () => {
expect(segments.face('178')).toEqual({ type: 'face', data: { id: '178' } });
});
it('stringifies zero', () => {
expect(segments.face(0)).toEqual({ type: 'face', data: { id: '0' } });
});
it('stringifies zero', () => {
expect(segments.face(0)).toEqual({ type: 'face', data: { id: '0' } });
});
});
describe('segments.at', () => {
it('stringifies a numeric qq and omits empty options', () => {
expect(segments.at(10001)).toEqual({ type: 'at', data: { qq: '10001' } });
});
it('supports at-all', () => {
expect(segments.at('all')).toEqual({ type: 'at', data: { qq: 'all' } });
});
it('includes name when provided', () => {
expect(segments.at(10001, { name: 'luma' })).toEqual({
type: 'at',
data: { qq: '10001', name: 'luma' },
it('stringifies a numeric qq and omits empty options', () => {
expect(segments.at(10001)).toEqual({ type: 'at', data: { qq: '10001' } });
});
});
it('includes uid when provided', () => {
expect(segments.at(10001, { uid: 'u_abc' })).toEqual({
type: 'at',
data: { qq: '10001', uid: 'u_abc' },
it('supports at-all', () => {
expect(segments.at('all')).toEqual({ type: 'at', data: { qq: 'all' } });
});
});
it('includes both name and uid', () => {
expect(segments.at(10001, { name: 'luma', uid: 'u_abc' })).toEqual({
type: 'at',
data: { qq: '10001', name: 'luma', uid: 'u_abc' },
it('includes name when provided', () => {
expect(segments.at(10001, { name: 'luma' })).toEqual({
type: 'at',
data: { qq: '10001', name: 'luma' },
});
});
});
it('omits empty name and uid', () => {
expect(segments.at(10001, { name: '', uid: '' })).toEqual({
type: 'at',
data: { qq: '10001' },
it('includes uid when provided', () => {
expect(segments.at(10001, { uid: 'u_abc' })).toEqual({
type: 'at',
data: { qq: '10001', uid: 'u_abc' },
});
});
it('includes both name and uid', () => {
expect(segments.at(10001, { name: 'luma', uid: 'u_abc' })).toEqual({
type: 'at',
data: { qq: '10001', name: 'luma', uid: 'u_abc' },
});
});
it('omits empty name and uid', () => {
expect(segments.at(10001, { name: '', uid: '' })).toEqual({
type: 'at',
data: { qq: '10001' },
});
});
});
});
describe('segments.reply', () => {
it('stringifies a numeric message id', () => {
expect(segments.reply(7)).toEqual({ type: 'reply', data: { id: '7' } });
});
it('stringifies a numeric message id', () => {
expect(segments.reply(7)).toEqual({ type: 'reply', data: { id: '7' } });
});
it('keeps a string message id', () => {
expect(segments.reply('abc')).toEqual({ type: 'reply', data: { id: 'abc' } });
});
it('keeps a string message id', () => {
expect(segments.reply('abc')).toEqual({ type: 'reply', data: { id: 'abc' } });
});
});
describe('segments.image', () => {
it('uses only the file when no options are given', () => {
expect(segments.image('/tmp/a.png')).toEqual({
type: 'image',
data: { file: '/tmp/a.png' },
it('uses only the file when no options are given', () => {
expect(segments.image('/tmp/a.png')).toEqual({
type: 'image',
data: { file: '/tmp/a.png' },
});
});
});
it('spreads image options after file', () => {
expect(
segments.image('base64://abc', {
type: 'flash',
subType: 1,
summary: 'pic',
url: 'https://example.com/a.png',
}),
).toEqual({
type: 'image',
data: {
file: 'base64://abc',
type: 'flash',
subType: 1,
summary: 'pic',
url: 'https://example.com/a.png',
},
it('spreads image options after file', () => {
expect(
segments.image('base64://abc', {
type: 'flash',
subType: 1,
summary: 'pic',
url: 'https://example.com/a.png',
}),
).toEqual({
type: 'image',
data: {
file: 'base64://abc',
type: 'flash',
subType: 1,
summary: 'pic',
url: 'https://example.com/a.png',
},
});
});
});
});
describe('segments.record', () => {
it('uses only the file when no options are given', () => {
expect(segments.record('/tmp/a.amr')).toEqual({
type: 'record',
data: { file: '/tmp/a.amr' },
it('uses only the file when no options are given', () => {
expect(segments.record('/tmp/a.amr')).toEqual({
type: 'record',
data: { file: '/tmp/a.amr' },
});
});
});
it('spreads record options after file', () => {
expect(segments.record('/tmp/a.amr', { url: 'https://example.com/a.amr' })).toEqual({
type: 'record',
data: { file: '/tmp/a.amr', url: 'https://example.com/a.amr' },
it('spreads record options after file', () => {
expect(segments.record('/tmp/a.amr', { url: 'https://example.com/a.amr' })).toEqual({
type: 'record',
data: { file: '/tmp/a.amr', url: 'https://example.com/a.amr' },
});
});
});
});
describe('segments.video', () => {
it('uses only the file when no options are given', () => {
expect(segments.video('/tmp/a.mp4')).toEqual({
type: 'video',
data: { file: '/tmp/a.mp4' },
it('uses only the file when no options are given', () => {
expect(segments.video('/tmp/a.mp4')).toEqual({
type: 'video',
data: { file: '/tmp/a.mp4' },
});
});
});
it('spreads video options after file', () => {
expect(
segments.video('/tmp/a.mp4', {
url: 'https://example.com/a.mp4',
thumb: '/tmp/thumb.jpg',
}),
).toEqual({
type: 'video',
data: {
file: '/tmp/a.mp4',
url: 'https://example.com/a.mp4',
thumb: '/tmp/thumb.jpg',
},
it('spreads video options after file', () => {
expect(
segments.video('/tmp/a.mp4', {
url: 'https://example.com/a.mp4',
thumb: '/tmp/thumb.jpg',
}),
).toEqual({
type: 'video',
data: {
file: '/tmp/a.mp4',
url: 'https://example.com/a.mp4',
thumb: '/tmp/thumb.jpg',
},
});
});
});
});
describe('segments.json', () => {
it('keeps a JSON string as-is', () => {
expect(segments.json('{"app":"com.tencent.miniapp"}')).toEqual({
type: 'json',
data: { data: '{"app":"com.tencent.miniapp"}' },
it('keeps a JSON string as-is', () => {
expect(segments.json('{"app":"com.tencent.miniapp"}')).toEqual({
type: 'json',
data: { data: '{"app":"com.tencent.miniapp"}' },
});
});
});
it('stringifies a JSON object', () => {
expect(segments.json({ app: 'com.tencent.miniapp', desc: 'hi' })).toEqual({
type: 'json',
data: { data: '{"app":"com.tencent.miniapp","desc":"hi"}' },
it('stringifies a JSON object', () => {
expect(segments.json({ app: 'com.tencent.miniapp', desc: 'hi' })).toEqual({
type: 'json',
data: { data: '{"app":"com.tencent.miniapp","desc":"hi"}' },
});
});
});
});
describe('segments.xml', () => {
it('uses only the xml payload when no options are given', () => {
expect(segments.xml('<msg />')).toEqual({
type: 'xml',
data: { data: '<msg />' },
it('uses only the xml payload when no options are given', () => {
expect(segments.xml('<msg />')).toEqual({
type: 'xml',
data: { data: '<msg />' },
});
});
});
it('spreads xml options after data', () => {
expect(segments.xml('<msg />', { id: '12345' })).toEqual({
type: 'xml',
data: { data: '<msg />', id: '12345' },
it('spreads xml options after data', () => {
expect(segments.xml('<msg />', { id: '12345' })).toEqual({
type: 'xml',
data: { data: '<msg />', id: '12345' },
});
});
});
});
describe('segments.poke', () => {
it('omits id when it is not provided', () => {
expect(segments.poke(1)).toEqual({ type: 'poke', data: { type: 1 } });
});
it('omits id when it is not provided', () => {
expect(segments.poke(1)).toEqual({ type: 'poke', data: { type: 1 } });
});
it('includes a numeric id', () => {
expect(segments.poke(1, -1)).toEqual({ type: 'poke', data: { type: 1, id: -1 } });
});
it('includes a numeric id', () => {
expect(segments.poke(1, -1)).toEqual({ type: 'poke', data: { type: 1, id: -1 } });
});
it('keeps string type and id', () => {
expect(segments.poke('1', '0')).toEqual({ type: 'poke', data: { type: '1', id: '0' } });
});
it('keeps string type and id', () => {
expect(segments.poke('1', '0')).toEqual({ type: 'poke', data: { type: '1', id: '0' } });
});
it('includes an id of 0', () => {
expect(segments.poke(1, 0)).toEqual({ type: 'poke', data: { type: 1, id: 0 } });
});
it('includes an id of 0', () => {
expect(segments.poke(1, 0)).toEqual({ type: 'poke', data: { type: 1, id: 0 } });
});
});
describe('segments.forward', () => {
it('mirrors the id onto res_id and forward_id', () => {
expect(segments.forward('res-9')).toEqual({
type: 'forward',
data: { id: 'res-9', res_id: 'res-9', forward_id: 'res-9' },
it('mirrors the id onto res_id and forward_id', () => {
expect(segments.forward('res-9')).toEqual({
type: 'forward',
data: { id: 'res-9', res_id: 'res-9', forward_id: 'res-9' },
});
});
});
});
describe('segments.node', () => {
it('stores user_id, nickname, and string content', () => {
expect(segments.node(10001, 'luma', 'hello')).toEqual({
type: 'node',
data: { user_id: 10001, nickname: 'luma', content: 'hello' },
it('stores user_id, nickname, and string content', () => {
expect(segments.node(10001, 'luma', 'hello')).toEqual({
type: 'node',
data: { user_id: 10001, nickname: 'luma', content: 'hello' },
});
});
});
it('stores a single segment as content', () => {
expect(segments.node(10001, 'luma', { type: 'text', data: { text: 'hi' } })).toEqual({
type: 'node',
data: {
user_id: 10001,
nickname: 'luma',
content: { type: 'text', data: { text: 'hi' } },
},
it('stores a single segment as content', () => {
expect(segments.node(10001, 'luma', { type: 'text', data: { text: 'hi' } })).toEqual({
type: 'node',
data: {
user_id: 10001,
nickname: 'luma',
content: { type: 'text', data: { text: 'hi' } },
},
});
});
});
it('stores a segment array as content', () => {
expect(segments.node(10001, 'luma', [{ type: 'text', data: { text: 'hi' } }])).toEqual({
type: 'node',
data: {
user_id: 10001,
nickname: 'luma',
content: [{ type: 'text', data: { text: 'hi' } }],
},
it('stores a segment array as content', () => {
expect(segments.node(10001, 'luma', [{ type: 'text', data: { text: 'hi' } }])).toEqual({
type: 'node',
data: {
user_id: 10001,
nickname: 'luma',
content: [{ type: 'text', data: { text: 'hi' } }],
},
});
});
});
});
describe('segments.share', () => {
it('passes required share fields through', () => {
expect(segments.share({ url: 'https://example.com', title: 'Example' })).toEqual({
type: 'share',
data: { url: 'https://example.com', title: 'Example' },
it('passes required share fields through', () => {
expect(segments.share({ url: 'https://example.com', title: 'Example' })).toEqual({
type: 'share',
data: { url: 'https://example.com', title: 'Example' },
});
});
});
it('passes optional share fields through', () => {
expect(
segments.share({
url: 'https://example.com',
title: 'Example',
content: 'desc',
image: 'https://example.com/a.png',
}),
).toEqual({
type: 'share',
data: {
url: 'https://example.com',
title: 'Example',
content: 'desc',
image: 'https://example.com/a.png',
},
it('passes optional share fields through', () => {
expect(
segments.share({
url: 'https://example.com',
title: 'Example',
content: 'desc',
image: 'https://example.com/a.png',
}),
).toEqual({
type: 'share',
data: {
url: 'https://example.com',
title: 'Example',
content: 'desc',
image: 'https://example.com/a.png',
},
});
});
});
});
describe('segments.music', () => {
it('passes platform music id data through', () => {
expect(segments.music({ type: '163', id: '12345' })).toEqual({
type: 'music',
data: { type: '163', id: '12345' },
it('passes platform music id data through', () => {
expect(segments.music({ type: '163', id: '12345' })).toEqual({
type: 'music',
data: { type: '163', id: '12345' },
});
});
});
it('passes custom music data through', () => {
expect(
segments.music({
type: 'custom',
url: 'https://example.com/song',
audio: 'https://example.com/song.mp3',
title: 'Song',
image: 'https://example.com/cover.jpg',
content: 'Artist',
}),
).toEqual({
type: 'music',
data: {
type: 'custom',
url: 'https://example.com/song',
audio: 'https://example.com/song.mp3',
title: 'Song',
image: 'https://example.com/cover.jpg',
content: 'Artist',
},
it('passes custom music data through', () => {
expect(
segments.music({
type: 'custom',
url: 'https://example.com/song',
audio: 'https://example.com/song.mp3',
title: 'Song',
image: 'https://example.com/cover.jpg',
content: 'Artist',
}),
).toEqual({
type: 'music',
data: {
type: 'custom',
url: 'https://example.com/song',
audio: 'https://example.com/song.mp3',
title: 'Song',
image: 'https://example.com/cover.jpg',
content: 'Artist',
},
});
});
});
});
describe('segments.location', () => {
it('passes numeric coordinates and labels through', () => {
expect(
segments.location({
lat: 39.9,
lon: 116.4,
title: 'Beijing',
content: 'Tiananmen',
}),
).toEqual({
type: 'location',
data: {
lat: 39.9,
lon: 116.4,
title: 'Beijing',
content: 'Tiananmen',
},
it('passes numeric coordinates and labels through', () => {
expect(
segments.location({
lat: 39.9,
lon: 116.4,
title: 'Beijing',
content: 'Tiananmen',
}),
).toEqual({
type: 'location',
data: {
lat: 39.9,
lon: 116.4,
title: 'Beijing',
content: 'Tiananmen',
},
});
});
});
it('passes string coordinates through', () => {
expect(segments.location({ lat: '31.2', lon: '121.5' })).toEqual({
type: 'location',
data: { lat: '31.2', lon: '121.5' },
it('passes string coordinates through', () => {
expect(segments.location({ lat: '31.2', lon: '121.5' })).toEqual({
type: 'location',
data: { lat: '31.2', lon: '121.5' },
});
});
});
});
describe('segments.contact', () => {
it('builds a qq contact with a numeric id', () => {
expect(segments.contact('qq', 10001)).toEqual({
type: 'contact',
data: { type: 'qq', id: 10001 },
it('builds a qq contact with a numeric id', () => {
expect(segments.contact('qq', 10001)).toEqual({
type: 'contact',
data: { type: 'qq', id: 10001 },
});
});
});
it('builds a group contact with a string id', () => {
expect(segments.contact('group', '123456')).toEqual({
type: 'contact',
data: { type: 'group', id: '123456' },
it('builds a group contact with a string id', () => {
expect(segments.contact('group', '123456')).toEqual({
type: 'contact',
data: { type: 'group', id: '123456' },
});
});
});
});
describe('segments.raw', () => {
it('builds an arbitrary typed segment', () => {
expect(segments.raw('dice', { result: 6 })).toEqual({
type: 'dice',
data: { result: 6 },
it('builds an arbitrary typed segment', () => {
expect(segments.raw('dice', { result: 6 })).toEqual({
type: 'dice',
data: { result: 6 },
});
});
});
});
+152 -146
View File
@@ -1,175 +1,181 @@
import { describe, expect, it, vi } from 'vitest';
import {
SnowLumaAbortError,
SnowLumaWebSocketClient,
type OneBotPrivateMessageEvent,
SnowLumaAbortError,
SnowLumaWebSocketClient,
type OneBotPrivateMessageEvent,
} from '../src';
class MockWebSocket {
static instances: MockWebSocket[] = [];
static instances: MockWebSocket[] = [];
readyState = 0;
sent: string[] = [];
readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>();
readyState = 0;
sent: string[] = [];
readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>();
constructor(
readonly url: string,
readonly protocols?: string | string[],
) {
MockWebSocket.instances.push(this);
}
addEventListener(event: string, listener: (...args: unknown[]) => void): void {
let listeners = this.listeners.get(event);
if (!listeners) {
listeners = new Set();
this.listeners.set(event, listeners);
constructor(
readonly url: string,
readonly protocols?: string | string[],
) {
MockWebSocket.instances.push(this);
}
listeners.add(listener);
}
removeEventListener(event: string, listener: (...args: unknown[]) => void): void {
this.listeners.get(event)?.delete(listener);
}
addEventListener(event: string, listener: (...args: unknown[]) => void): void {
let listeners = this.listeners.get(event);
send(data: string): void {
this.sent.push(data);
}
if (!listeners) {
listeners = new Set();
this.listeners.set(event, listeners);
}
close(code?: number, reason?: string): void {
this.readyState = 3;
this.emit('close', { code, reason });
}
open(): void {
this.readyState = 1;
this.emit('open');
}
message(data: unknown): void {
this.emit('message', { data });
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) {
listener(...args);
listeners.add(listener);
}
removeEventListener(event: string, listener: (...args: unknown[]) => void): void {
this.listeners.get(event)?.delete(listener);
}
send(data: string): void {
this.sent.push(data);
}
close(code?: number, reason?: string): void {
this.readyState = 3;
this.emit('close', { code, reason });
}
open(): void {
this.readyState = 1;
this.emit('open');
}
message(data: unknown): void {
this.emit('message', { data });
}
emit(event: string, ...args: unknown[]): void {
for (const listener of this.listeners.get(event) ?? []) {
listener(...args);
}
}
}
}
const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
time: 1,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 8,
user_id: 10001,
message: [{ type: 'text', data: { text: '/ping a b' } }],
raw_message: '/ping a b',
font: 0,
sender: { user_id: 10001, nickname: 'tester' },
time: 1,
self_id: 10000,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 8,
user_id: 10001,
message: [{ type: 'text', data: { text: '/ping a b' } }],
raw_message: '/ping a b',
font: 0,
sender: { user_id: 10001, nickname: 'tester' },
};
describe('SnowLumaWebSocketClient', () => {
it('matches API responses by echo', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
accessToken: 'token',
webSocket: MockWebSocket,
it('matches API responses by echo', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
accessToken: 'token',
webSocket: MockWebSocket,
});
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
expect(socket.url).toContain('access_token=token');
socket.open();
await connecting;
const status = client.getStatus();
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
const request = JSON.parse(socket.sent[0]!) as { echo: string };
socket.message(
JSON.stringify({
status: 'ok',
retcode: 0,
data: { online: true, good: true },
echo: request.echo,
}),
);
await expect(status).resolves.toEqual({ online: true, good: true });
});
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
expect(socket.url).toContain('access_token=token');
socket.open();
await connecting;
it('runs command handlers for matching message events', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
});
const handler = vi.fn();
client.command('ping', handler);
const status = client.getStatus();
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
const request = JSON.parse(socket.sent[0]!) as { echo: string };
socket.message(JSON.stringify({
status: 'ok',
retcode: 0,
data: { online: true, good: true },
echo: request.echo,
}));
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
socket.message(JSON.stringify(PRIVATE_EVENT));
await expect(status).resolves.toEqual({ online: true, good: true });
});
it('runs command handlers for matching message events', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
await vi.waitFor(() => {
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0]![2]).toMatchObject({ args: ['a', 'b'] });
});
});
const handler = vi.fn();
client.command('ping', handler);
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
socket.message(JSON.stringify(PRIVATE_EVENT));
it('supports caller AbortSignal cancellation for pending requests', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
});
const controller = new AbortController();
await vi.waitFor(() => {
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0]![2]).toMatchObject({ args: ['a', 'b'] });
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
const request = client.getStatus({ signal: controller.signal });
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
controller.abort();
await expect(request).rejects.toBeInstanceOf(SnowLumaAbortError);
});
});
it('supports caller AbortSignal cancellation for pending requests', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
it('dispatches bot_status notices to onBotStatus', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
});
const handler = vi.fn();
client.onBotStatus(handler);
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
socket.message(
JSON.stringify({
time: 1_710_000_000,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'offline',
user_id: 10000,
}),
);
await vi.waitFor(() => {
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0]![0]).toMatchObject({
notice_type: 'bot_status',
sub_type: 'offline',
user_id: 10000,
});
});
});
const controller = new AbortController();
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
const request = client.getStatus({ signal: controller.signal });
await vi.waitFor(() => expect(socket.sent).toHaveLength(1));
controller.abort();
await expect(request).rejects.toBeInstanceOf(SnowLumaAbortError);
});
it('dispatches bot_status notices to onBotStatus', async () => {
MockWebSocket.instances = [];
const client = new SnowLumaWebSocketClient({
url: 'ws://127.0.0.1:3001/',
webSocket: MockWebSocket,
});
const handler = vi.fn();
client.onBotStatus(handler);
const connecting = client.connect();
const socket = MockWebSocket.instances[0]!;
socket.open();
await connecting;
socket.message(JSON.stringify({
time: 1_710_000_000,
self_id: 10000,
post_type: 'notice',
notice_type: 'bot_status',
sub_type: 'offline',
user_id: 10000,
}));
await vi.waitFor(() => {
expect(handler).toHaveBeenCalledTimes(1);
expect(handler.mock.calls[0]![0]).toMatchObject({
notice_type: 'bot_status',
sub_type: 'offline',
user_id: 10000,
});
});
});
});
+175 -175
View File
@@ -1,225 +1,225 @@
import { describe, expect, it, vi } from 'vitest';
import {
addSocketListener,
closeInfo,
normalizeReconnect,
rawToString,
unwrapEventPayload,
unwrapMessagePayload,
WEBSOCKET_CLOSED,
WEBSOCKET_OPEN,
addSocketListener,
closeInfo,
normalizeReconnect,
rawToString,
unwrapEventPayload,
unwrapMessagePayload,
WEBSOCKET_CLOSED,
WEBSOCKET_OPEN,
} from '../src/client/websocket-utils';
import type { WebSocketLike } from '../src/client/websocket-types';
function stubSocket(extra: Partial<WebSocketLike> = {}): WebSocketLike {
return {
readyState: 0,
send() {},
close() {},
...extra,
};
return {
readyState: 0,
send() {},
close() {},
...extra,
};
}
describe('websocket readyState constants', () => {
it('matches the standard WebSocket readyState values', () => {
expect(WEBSOCKET_OPEN).toBe(1);
expect(WEBSOCKET_CLOSED).toBe(3);
});
it('matches the standard WebSocket readyState values', () => {
expect(WEBSOCKET_OPEN).toBe(1);
expect(WEBSOCKET_CLOSED).toBe(3);
});
});
describe('normalizeReconnect', () => {
it('treats a disabled or omitted value as no reconnect policy', () => {
expect(normalizeReconnect(false)).toBeNull();
expect(normalizeReconnect(undefined)).toBeNull();
});
it('treats a disabled or omitted value as no reconnect policy', () => {
expect(normalizeReconnect(false)).toBeNull();
expect(normalizeReconnect(undefined)).toBeNull();
});
it('turns a boolean enable flag into an empty options object', () => {
expect(normalizeReconnect(true)).toEqual({});
});
it('turns a boolean enable flag into an empty options object', () => {
expect(normalizeReconnect(true)).toEqual({});
});
it('returns the given reconnect options object unchanged', () => {
const options = { retries: 4, minDelayMs: 250, maxDelayMs: 8_000 };
expect(normalizeReconnect(options)).toBe(options);
expect(normalizeReconnect({ retries: 0 })).toEqual({ retries: 0 });
expect(normalizeReconnect({})).toEqual({});
});
it('returns the given reconnect options object unchanged', () => {
const options = { retries: 4, minDelayMs: 250, maxDelayMs: 8_000 };
expect(normalizeReconnect(options)).toBe(options);
expect(normalizeReconnect({ retries: 0 })).toEqual({ retries: 0 });
expect(normalizeReconnect({})).toEqual({});
});
});
describe('addSocketListener', () => {
it('binds and unbinds through addEventListener when present', () => {
const listener = vi.fn();
const socket = stubSocket({
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
on: vi.fn(),
it('binds and unbinds through addEventListener when present', () => {
const listener = vi.fn();
const socket = stubSocket({
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
on: vi.fn(),
});
const off = addSocketListener(socket, 'message', listener);
expect(socket.addEventListener).toHaveBeenCalledTimes(1);
expect(socket.addEventListener).toHaveBeenCalledWith('message', listener);
expect(socket.on).not.toHaveBeenCalled();
off();
expect(socket.removeEventListener).toHaveBeenCalledTimes(1);
expect(socket.removeEventListener).toHaveBeenCalledWith('message', listener);
});
const off = addSocketListener(socket, 'message', listener);
expect(socket.addEventListener).toHaveBeenCalledTimes(1);
expect(socket.addEventListener).toHaveBeenCalledWith('message', listener);
expect(socket.on).not.toHaveBeenCalled();
off();
expect(socket.removeEventListener).toHaveBeenCalledTimes(1);
expect(socket.removeEventListener).toHaveBeenCalledWith('message', listener);
});
it('does not throw on cleanup when removeEventListener is absent', () => {
const socket = stubSocket({ addEventListener: vi.fn() });
const off = addSocketListener(socket, 'open', vi.fn());
expect(off).not.toThrow();
});
it('binds through on() and unbinds through off() when addEventListener is missing', () => {
const listener = vi.fn();
const socket = stubSocket({
on: vi.fn(),
off: vi.fn(),
removeListener: vi.fn(),
it('does not throw on cleanup when removeEventListener is absent', () => {
const socket = stubSocket({ addEventListener: vi.fn() });
const off = addSocketListener(socket, 'open', vi.fn());
expect(off).not.toThrow();
});
const off = addSocketListener(socket, 'close', listener);
it('binds through on() and unbinds through off() when addEventListener is missing', () => {
const listener = vi.fn();
const socket = stubSocket({
on: vi.fn(),
off: vi.fn(),
removeListener: vi.fn(),
});
expect(socket.on).toHaveBeenCalledTimes(1);
expect(socket.on).toHaveBeenCalledWith('close', listener);
const off = addSocketListener(socket, 'close', listener);
off();
expect(socket.off).toHaveBeenCalledTimes(1);
expect(socket.off).toHaveBeenCalledWith('close', listener);
expect(socket.removeListener).not.toHaveBeenCalled();
});
expect(socket.on).toHaveBeenCalledTimes(1);
expect(socket.on).toHaveBeenCalledWith('close', listener);
it('falls back to removeListener when off() is absent', () => {
const listener = vi.fn();
const socket = stubSocket({
on: vi.fn(),
removeListener: vi.fn(),
off();
expect(socket.off).toHaveBeenCalledTimes(1);
expect(socket.off).toHaveBeenCalledWith('close', listener);
expect(socket.removeListener).not.toHaveBeenCalled();
});
const off = addSocketListener(socket, 'error', listener);
off();
it('falls back to removeListener when off() is absent', () => {
const listener = vi.fn();
const socket = stubSocket({
on: vi.fn(),
removeListener: vi.fn(),
});
expect(socket.removeListener).toHaveBeenCalledTimes(1);
expect(socket.removeListener).toHaveBeenCalledWith('error', listener);
});
const off = addSocketListener(socket, 'error', listener);
off();
it('cleanup is a no-op when on() has neither off nor removeListener', () => {
const socket = stubSocket({ on: vi.fn() });
const off = addSocketListener(socket, 'message', vi.fn());
expect(off).not.toThrow();
});
expect(socket.removeListener).toHaveBeenCalledTimes(1);
expect(socket.removeListener).toHaveBeenCalledWith('error', listener);
});
it('returns a no-op cleanup when the socket has no listener APIs', () => {
const off = addSocketListener(stubSocket(), 'open', vi.fn());
expect(off).not.toThrow();
});
it('cleanup is a no-op when on() has neither off nor removeListener', () => {
const socket = stubSocket({ on: vi.fn() });
const off = addSocketListener(socket, 'message', vi.fn());
expect(off).not.toThrow();
});
it('returns a no-op cleanup when the socket has no listener APIs', () => {
const off = addSocketListener(stubSocket(), 'open', vi.fn());
expect(off).not.toThrow();
});
});
describe('unwrapMessagePayload', () => {
it('returns the data field from a JSON object envelope', () => {
expect(unwrapMessagePayload({ data: '{"ok":true}' })).toBe('{"ok":true}');
expect(unwrapMessagePayload({ data: { text: 'hi' } })).toEqual({ text: 'hi' });
expect(unwrapMessagePayload({ data: 0 })).toBe(0);
expect(unwrapMessagePayload({ data: undefined })).toBeUndefined();
});
it('returns the data field from a JSON object envelope', () => {
expect(unwrapMessagePayload({ data: '{"ok":true}' })).toBe('{"ok":true}');
expect(unwrapMessagePayload({ data: { text: 'hi' } })).toEqual({ text: 'hi' });
expect(unwrapMessagePayload({ data: 0 })).toBe(0);
expect(unwrapMessagePayload({ data: undefined })).toBeUndefined();
});
it('returns the original value when it is not a data envelope', () => {
expect(unwrapMessagePayload('raw-text')).toBe('raw-text');
expect(unwrapMessagePayload(null)).toBeNull();
expect(unwrapMessagePayload([{ data: 1 }])).toEqual([{ data: 1 }]);
expect(unwrapMessagePayload({ type: 'message' })).toEqual({ type: 'message' });
});
it('returns the original value when it is not a data envelope', () => {
expect(unwrapMessagePayload('raw-text')).toBe('raw-text');
expect(unwrapMessagePayload(null)).toBeNull();
expect(unwrapMessagePayload([{ data: 1 }])).toEqual([{ data: 1 }]);
expect(unwrapMessagePayload({ type: 'message' })).toEqual({ type: 'message' });
});
});
describe('unwrapEventPayload', () => {
it('returns the error field from a JSON object envelope', () => {
expect(unwrapEventPayload({ error: 'socket failed' })).toBe('socket failed');
expect(unwrapEventPayload({ error: { message: 'boom' } })).toEqual({ message: 'boom' });
expect(unwrapEventPayload({ error: undefined })).toBeUndefined();
});
it('returns the error field from a JSON object envelope', () => {
expect(unwrapEventPayload({ error: 'socket failed' })).toBe('socket failed');
expect(unwrapEventPayload({ error: { message: 'boom' } })).toEqual({ message: 'boom' });
expect(unwrapEventPayload({ error: undefined })).toBeUndefined();
});
it('returns the original value when it is not an error envelope', () => {
expect(unwrapEventPayload('plain-error')).toBe('plain-error');
expect(unwrapEventPayload(null)).toBeNull();
expect(unwrapEventPayload([{ error: 1 }])).toEqual([{ error: 1 }]);
expect(unwrapEventPayload({ type: 'error' })).toEqual({ type: 'error' });
});
it('returns the original value when it is not an error envelope', () => {
expect(unwrapEventPayload('plain-error')).toBe('plain-error');
expect(unwrapEventPayload(null)).toBeNull();
expect(unwrapEventPayload([{ error: 1 }])).toEqual([{ error: 1 }]);
expect(unwrapEventPayload({ type: 'error' })).toEqual({ type: 'error' });
});
});
describe('rawToString', () => {
it('returns strings unchanged', () => {
expect(rawToString('{"echo":1}')).toBe('{"echo":1}');
expect(rawToString('')).toBe('');
});
it('returns strings unchanged', () => {
expect(rawToString('{"echo":1}')).toBe('{"echo":1}');
expect(rawToString('')).toBe('');
});
it('decodes ArrayBuffer and ArrayBufferView payloads as UTF-8', () => {
const bytes = Uint8Array.from([0x68, 0x69]);
expect(rawToString(bytes.buffer)).toBe('hi');
expect(rawToString(bytes)).toBe('hi');
expect(rawToString(Buffer.from([0x68, 0x69]))).toBe('hi');
expect(rawToString(new DataView(bytes.buffer))).toBe('hi');
expect(rawToString(Uint8Array.from([0x21, 0x68, 0x69, 0x21]).subarray(1, 3))).toBe('hi');
expect(rawToString(new ArrayBuffer(0))).toBe('');
});
it('decodes ArrayBuffer and ArrayBufferView payloads as UTF-8', () => {
const bytes = Uint8Array.from([0x68, 0x69]);
expect(rawToString(bytes.buffer)).toBe('hi');
expect(rawToString(bytes)).toBe('hi');
expect(rawToString(Buffer.from([0x68, 0x69]))).toBe('hi');
expect(rawToString(new DataView(bytes.buffer))).toBe('hi');
expect(rawToString(Uint8Array.from([0x21, 0x68, 0x69, 0x21]).subarray(1, 3))).toBe('hi');
expect(rawToString(new ArrayBuffer(0))).toBe('');
});
it('rejects Blob payloads that cannot be read synchronously', () => {
expect(() => rawToString(new Blob(['hi']))).toThrow(
'Blob WebSocket messages are not supported synchronously',
);
});
it('rejects Blob payloads that cannot be read synchronously', () => {
expect(() => rawToString(new Blob(['hi']))).toThrow(
'Blob WebSocket messages are not supported synchronously',
);
});
it('uses toString() on objects and String() on primitives', () => {
expect(rawToString({ toString: () => 'from-toString' })).toBe('from-toString');
expect(rawToString([1, 2])).toBe('1,2');
expect(rawToString({ a: 1 })).toBe('[object Object]');
expect(rawToString(42)).toBe('42');
expect(rawToString(false)).toBe('false');
expect(rawToString(null)).toBe('null');
expect(rawToString(undefined)).toBe('undefined');
});
it('uses toString() on objects and String() on primitives', () => {
expect(rawToString({ toString: () => 'from-toString' })).toBe('from-toString');
expect(rawToString([1, 2])).toBe('1,2');
expect(rawToString({ a: 1 })).toBe('[object Object]');
expect(rawToString(42)).toBe('42');
expect(rawToString(false)).toBe('false');
expect(rawToString(null)).toBe('null');
expect(rawToString(undefined)).toBe('undefined');
});
});
describe('closeInfo', () => {
it('reads code and reason from a CloseEvent-like object', () => {
expect(closeInfo([{ code: 1000, reason: 'normal', wasClean: true }])).toEqual({
code: 1000,
reason: 'normal',
it('reads code and reason from a CloseEvent-like object', () => {
expect(closeInfo([{ code: 1000, reason: 'normal', wasClean: true }])).toEqual({
code: 1000,
reason: 'normal',
});
expect(closeInfo([{ code: 1001 }])).toEqual({
code: 1001,
reason: undefined,
});
expect(closeInfo([{ reason: 'going away' }])).toEqual({
code: undefined,
reason: 'going away',
});
expect(closeInfo([{ code: '1000', reason: 1 }])).toEqual({
code: undefined,
reason: undefined,
});
});
expect(closeInfo([{ code: 1001 }])).toEqual({
code: 1001,
reason: undefined,
});
expect(closeInfo([{ reason: 'going away' }])).toEqual({
code: undefined,
reason: 'going away',
});
expect(closeInfo([{ code: '1000', reason: 1 }])).toEqual({
code: undefined,
reason: undefined,
});
});
it('reads positional Node-style close arguments', () => {
expect(closeInfo([1006, 'abnormal'])).toEqual({
code: 1006,
reason: 'abnormal',
it('reads positional Node-style close arguments', () => {
expect(closeInfo([1006, 'abnormal'])).toEqual({
code: 1006,
reason: 'abnormal',
});
expect(closeInfo([1000])).toEqual({
code: 1000,
reason: undefined,
});
expect(closeInfo(['1000', 1])).toEqual({
code: undefined,
reason: undefined,
});
expect(closeInfo([])).toEqual({
code: undefined,
reason: undefined,
});
expect(closeInfo([[1000, 'nested']])).toEqual({
code: undefined,
reason: undefined,
});
});
expect(closeInfo([1000])).toEqual({
code: 1000,
reason: undefined,
});
expect(closeInfo(['1000', 1])).toEqual({
code: undefined,
reason: undefined,
});
expect(closeInfo([])).toEqual({
code: undefined,
reason: undefined,
});
expect(closeInfo([[1000, 'nested']])).toEqual({
code: undefined,
reason: undefined,
});
});
});