feat(sdk): add media sends, quoted replies, and event waits
Add local media upload-and-send helpers with an optional Node file source and stage-aware errors. Add explicit quoted replies and cancellable event waits while preserving existing methods and handler contracts. Propagate group-file publication failures instead of reporting success. Cover cancellation, cleanup, signed message IDs, package exports, consumer types, and real HTTP/WebSocket upload-to-send integration. Validation: pnpm run ci (6231 tests passed, 9 skipped); SDK package contents verified with npm pack --dry-run --ignore-scripts.
This commit is contained in:
28 files changed
+1798
-37
No files matched your search
@@ -0,0 +1,387 @@
|
||||
import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest';
|
||||
import {
|
||||
SnowLumaAbortError,
|
||||
SnowLumaConnectionError,
|
||||
SnowLumaTimeoutError,
|
||||
SnowLumaWebSocketClient,
|
||||
isGroupMessageEvent,
|
||||
type OneBotGroupMessageEvent,
|
||||
type OneBotMessageEvent,
|
||||
type OneBotPrivateMessageEvent,
|
||||
type SnowLumaEvent,
|
||||
} from '../src';
|
||||
|
||||
class EventSocket {
|
||||
static instances: EventSocket[] = [];
|
||||
readyState = 0;
|
||||
readonly listeners = new Map<string, Set<(...args: unknown[]) => void>>();
|
||||
|
||||
constructor(readonly url: string) {
|
||||
EventSocket.instances.push(this);
|
||||
}
|
||||
|
||||
addEventListener(name: string, listener: (...args: unknown[]) => void): void {
|
||||
const listeners = this.listeners.get(name) ?? new Set();
|
||||
listeners.add(listener);
|
||||
this.listeners.set(name, listeners);
|
||||
}
|
||||
|
||||
removeEventListener(name: string, listener: (...args: unknown[]) => void): void {
|
||||
this.listeners.get(name)?.delete(listener);
|
||||
}
|
||||
|
||||
send(): void {}
|
||||
|
||||
close(): void {
|
||||
this.readyState = 3;
|
||||
this.emit('close', { code: 1000, reason: 'closed' });
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.readyState = 1;
|
||||
this.emit('open');
|
||||
}
|
||||
|
||||
message(event: SnowLumaEvent): void {
|
||||
this.emit('message', { data: JSON.stringify(event) });
|
||||
}
|
||||
|
||||
emit(name: string, ...args: unknown[]): void {
|
||||
for (const listener of [...(this.listeners.get(name) ?? [])]) {
|
||||
listener(...args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const privateEvent: OneBotPrivateMessageEvent = {
|
||||
time: 1,
|
||||
self_id: 10000,
|
||||
post_type: 'message',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: -7,
|
||||
user_id: 10001,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'hello',
|
||||
font: 0,
|
||||
sender: { user_id: 10001, nickname: 'tester' },
|
||||
};
|
||||
|
||||
const groupEvent: OneBotGroupMessageEvent = {
|
||||
...privateEvent,
|
||||
message_type: 'group',
|
||||
sub_type: 'normal',
|
||||
group_id: 20000,
|
||||
};
|
||||
|
||||
describe('WebSocket event waits', () => {
|
||||
const clients: SnowLumaWebSocketClient[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
EventSocket.instances = [];
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const client of clients.splice(0)) {
|
||||
client.close();
|
||||
}
|
||||
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
function createClient(reconnect = false): SnowLumaWebSocketClient {
|
||||
const client = new SnowLumaWebSocketClient({
|
||||
webSocket: EventSocket,
|
||||
requestTimeoutMs: 1000,
|
||||
reconnect: reconnect ? { minDelayMs: 10 } : false,
|
||||
});
|
||||
clients.push(client);
|
||||
return client;
|
||||
}
|
||||
|
||||
async function connect(client: SnowLumaWebSocketClient): Promise<EventSocket> {
|
||||
const opening = client.connect();
|
||||
const socket = EventSocket.instances.at(-1)!;
|
||||
socket.open();
|
||||
await opening;
|
||||
return socket;
|
||||
}
|
||||
|
||||
it('registers immediately before connect and observes the first matching event', async () => {
|
||||
const client = createClient();
|
||||
const predicate = vi.fn((event: SnowLumaEvent) => event.post_type === 'message');
|
||||
const waiting = client.waitForEvent(predicate);
|
||||
expect(EventSocket.instances).toHaveLength(0);
|
||||
const socket = await connect(client);
|
||||
socket.message(privateEvent);
|
||||
await expect(waiting).resolves.toEqual(privateEvent);
|
||||
socket.message(groupEvent);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(predicate).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('filters messages before invoking a predicate and accepts self-sent messages', async () => {
|
||||
const client = createClient();
|
||||
const socket = await connect(client);
|
||||
const predicate = vi.fn((event: OneBotMessageEvent) => event.message_type === 'group');
|
||||
const waiting = client.waitForMessage(predicate);
|
||||
socket.message({
|
||||
time: 1,
|
||||
self_id: 10000,
|
||||
post_type: 'notice',
|
||||
notice_type: 'group_upload',
|
||||
});
|
||||
socket.message(privateEvent);
|
||||
const sent: OneBotGroupMessageEvent = { ...groupEvent, post_type: 'message_sent' };
|
||||
socket.message(sent);
|
||||
await expect(waiting).resolves.toEqual(sent);
|
||||
expect(predicate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('supports type guards, boolean predicates, omitted predicates and options-only calls', async () => {
|
||||
const client = createClient();
|
||||
const socket = await connect(client);
|
||||
const narrowedEvent = client.waitForEvent(isGroupMessageEvent);
|
||||
const narrowedMessage = client.waitForMessage(isGroupMessageEvent);
|
||||
const booleanEvent = client.waitForEvent((event): boolean => event.post_type === 'message');
|
||||
const booleanMessage = client.waitForMessage((event): boolean => event.user_id === 10001);
|
||||
const anyEvent = client.waitForEvent({ timeoutMs: 100 });
|
||||
const anyMessage = client.waitForMessage({ timeoutMs: 100 });
|
||||
const defaultMessage = client.waitForMessage();
|
||||
const explicitUndefined = client.waitForEvent(undefined, { timeoutMs: 100 });
|
||||
expectTypeOf(narrowedEvent).toEqualTypeOf<Promise<OneBotGroupMessageEvent>>();
|
||||
expectTypeOf(narrowedMessage).toEqualTypeOf<Promise<OneBotGroupMessageEvent>>();
|
||||
expectTypeOf(booleanEvent).toEqualTypeOf<Promise<SnowLumaEvent>>();
|
||||
expectTypeOf(booleanMessage).toEqualTypeOf<Promise<OneBotMessageEvent>>();
|
||||
socket.message(groupEvent);
|
||||
|
||||
for (const wait of [
|
||||
narrowedEvent,
|
||||
narrowedMessage,
|
||||
booleanEvent,
|
||||
booleanMessage,
|
||||
anyEvent,
|
||||
anyMessage,
|
||||
defaultMessage,
|
||||
explicitUndefined,
|
||||
]) {
|
||||
await expect(wait).resolves.toEqual(groupEvent);
|
||||
}
|
||||
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'success',
|
||||
'timeout',
|
||||
'abort',
|
||||
'predicate error',
|
||||
'remote close',
|
||||
'client close',
|
||||
] as const)(
|
||||
'cleans event subscriptions, timers and abort listeners after %s',
|
||||
async (outcome) => {
|
||||
const client = createClient();
|
||||
const socket = await connect(client);
|
||||
const controller = new AbortController();
|
||||
const removeAbort = vi.spyOn(controller.signal, 'removeEventListener');
|
||||
const subscribe = client.onEvent.bind(client);
|
||||
const unsubscribe = vi.fn();
|
||||
vi.spyOn(client, 'onEvent').mockImplementation((listener) => {
|
||||
const off = subscribe(listener);
|
||||
|
||||
return () => {
|
||||
unsubscribe();
|
||||
off();
|
||||
};
|
||||
});
|
||||
const cause = new Error('predicate failed');
|
||||
const predicate = vi.fn(() => {
|
||||
if (outcome === 'predicate error') {
|
||||
throw cause;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
const waiting = client.waitForEvent(predicate, { signal: controller.signal });
|
||||
const settled = waiting.then(
|
||||
(event) => event,
|
||||
(error: unknown) => error,
|
||||
);
|
||||
|
||||
switch (outcome) {
|
||||
case 'success':
|
||||
case 'predicate error':
|
||||
socket.message(privateEvent);
|
||||
break;
|
||||
case 'timeout':
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
break;
|
||||
case 'abort':
|
||||
controller.abort(cause);
|
||||
break;
|
||||
case 'remote close':
|
||||
socket.close();
|
||||
break;
|
||||
case 'client close':
|
||||
client.close();
|
||||
break;
|
||||
}
|
||||
|
||||
const result = await settled;
|
||||
|
||||
if (outcome === 'success') {
|
||||
expect(result).toEqual(privateEvent);
|
||||
} else if (outcome === 'predicate error') {
|
||||
expect(result).toBe(cause);
|
||||
} else if (outcome === 'abort') {
|
||||
expect(result).toBeInstanceOf(SnowLumaAbortError);
|
||||
expect(result).toHaveProperty('cause', cause);
|
||||
} else if (outcome === 'timeout') {
|
||||
expect(result).toBeInstanceOf(SnowLumaTimeoutError);
|
||||
expect(result).toHaveProperty('timeoutMs', 1000);
|
||||
} else {
|
||||
expect(result).toBeInstanceOf(SnowLumaConnectionError);
|
||||
}
|
||||
|
||||
expect(unsubscribe).toHaveBeenCalledOnce();
|
||||
expect(removeAbort).toHaveBeenCalledWith('abort', expect.any(Function));
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
socket.message(groupEvent);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(predicate).toHaveBeenCalledTimes(
|
||||
['success', 'predicate error'].includes(outcome) ? 1 : 0,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('rejects all waits immediately when closed before any connection is created', async () => {
|
||||
const client = createClient();
|
||||
const first = expect(client.waitForEvent()).rejects.toBeInstanceOf(SnowLumaConnectionError);
|
||||
const second = expect(client.waitForMessage({ timeoutMs: 0 })).rejects.toBeInstanceOf(
|
||||
SnowLumaConnectionError,
|
||||
);
|
||||
client.close();
|
||||
await Promise.all([first, second]);
|
||||
expect(EventSocket.instances).toHaveLength(0);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('rejects on explicit close even if the socket never emits its close event', async () => {
|
||||
const client = createClient();
|
||||
const socket = await connect(client);
|
||||
vi.spyOn(socket, 'close').mockImplementation(() => {
|
||||
socket.readyState = 2;
|
||||
});
|
||||
const waiting = expect(client.waitForEvent()).rejects.toBeInstanceOf(
|
||||
SnowLumaConnectionError,
|
||||
);
|
||||
client.close();
|
||||
await waiting;
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('rejects a pre-aborted signal without adding event listeners or timers', async () => {
|
||||
const client = createClient();
|
||||
const controller = new AbortController();
|
||||
const cause = new Error('cancelled');
|
||||
controller.abort(cause);
|
||||
const subscribe = vi.spyOn(client, 'onEvent');
|
||||
await expect(client.waitForMessage({ signal: controller.signal })).rejects.toMatchObject({
|
||||
name: 'SnowLumaAbortError',
|
||||
cause,
|
||||
});
|
||||
expect(subscribe).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('does not carry a wait across an unexpected disconnect and automatic reconnect', async () => {
|
||||
const client = createClient(true);
|
||||
const socket = await connect(client);
|
||||
const predicate = vi.fn(() => true);
|
||||
const waiting = expect(client.waitForEvent(predicate)).rejects.toBeInstanceOf(
|
||||
SnowLumaConnectionError,
|
||||
);
|
||||
socket.close();
|
||||
await waiting;
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
const replacement = EventSocket.instances.at(-1)!;
|
||||
replacement.open();
|
||||
replacement.message(privateEvent);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(predicate).not.toHaveBeenCalled();
|
||||
const newWait = client.waitForMessage();
|
||||
replacement.message(groupEvent);
|
||||
await expect(newWait).resolves.toEqual(groupEvent);
|
||||
});
|
||||
|
||||
it('observes middleware ordering and ignores stopped events', async () => {
|
||||
const client = createClient();
|
||||
const socket = await connect(client);
|
||||
const predicate = vi.fn((event: SnowLumaEvent) => event.raw_message === 'processed');
|
||||
client.use(async (event, context, next) => {
|
||||
if (event.message_id === -7) {
|
||||
context.stopPropagation();
|
||||
return;
|
||||
}
|
||||
|
||||
event.raw_message = 'processed';
|
||||
await next();
|
||||
});
|
||||
const waiting = client.waitForEvent(predicate);
|
||||
socket.message(privateEvent);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(predicate).not.toHaveBeenCalled();
|
||||
socket.message({ ...groupEvent, message_id: -8 });
|
||||
await expect(waiting).resolves.toMatchObject({ message_id: -8, raw_message: 'processed' });
|
||||
expect(predicate).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('allows a zero timeout and still supports cancellation', async () => {
|
||||
const client = createClient();
|
||||
const controller = new AbortController();
|
||||
const waiting = expect(
|
||||
client.waitForEvent({ timeoutMs: 0, signal: controller.signal }),
|
||||
).rejects.toBeInstanceOf(SnowLumaAbortError);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(100_000);
|
||||
controller.abort();
|
||||
await waiting;
|
||||
});
|
||||
|
||||
it('keeps cancellation authoritative when a predicate cancels its own wait', async () => {
|
||||
const client = createClient();
|
||||
const socket = await connect(client);
|
||||
const controller = new AbortController();
|
||||
const removeAbort = vi.spyOn(controller.signal, 'removeEventListener');
|
||||
const waiting = expect(
|
||||
client.waitForMessage(
|
||||
() => {
|
||||
controller.abort('cancel while checking');
|
||||
return true;
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
name: 'SnowLumaAbortError',
|
||||
cause: 'cancel while checking',
|
||||
});
|
||||
socket.message(privateEvent);
|
||||
await waiting;
|
||||
expect(removeAbort).toHaveBeenCalledOnce();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it.each([-1, Number.NaN, Number.POSITIVE_INFINITY, 2_147_483_648])(
|
||||
'rejects invalid timeout %s before subscribing',
|
||||
async (timeoutMs) => {
|
||||
const client = createClient();
|
||||
const subscribe = vi.spyOn(client, 'onEvent');
|
||||
await expect(client.waitForEvent({ timeoutMs })).rejects.toBeInstanceOf(RangeError);
|
||||
expect(subscribe).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import {
|
||||
createEventContext,
|
||||
isGroupMessageEvent,
|
||||
quoteMessage,
|
||||
text,
|
||||
type EventHandler,
|
||||
type EventMiddleware,
|
||||
type EventWaitOptions,
|
||||
type MediaSource,
|
||||
type OneBotGroupMessageEvent,
|
||||
type OneBotMessageEvent,
|
||||
type SendMessageResult,
|
||||
type SnowLumaEvent,
|
||||
type SnowLumaEventContext,
|
||||
type SnowLumaEventContextWithQuote,
|
||||
type SnowLumaHttpClient,
|
||||
type SnowLumaWebSocketClient,
|
||||
} from '@snowluma/sdk';
|
||||
import { localFile } from '@snowluma/sdk/node';
|
||||
import type { EventWaitOptions as ClientWaitOptions } from '@snowluma/sdk/client';
|
||||
import type { SendImageOptions } from '@snowluma/sdk/types';
|
||||
import { quoteMessage as messageQuote } from '@snowluma/sdk/messages';
|
||||
|
||||
declare const http: SnowLumaHttpClient;
|
||||
declare const ws: SnowLumaWebSocketClient;
|
||||
declare const event: OneBotMessageEvent;
|
||||
const source: MediaSource = await localFile('./picture.png');
|
||||
const options: SendImageOptions = { image: { summary: 'picture' }, chunkSize: 16384 };
|
||||
const sent: Promise<SendMessageResult> = http.sendGroupImage(123, source, options);
|
||||
const sentPrivate: Promise<SendMessageResult> = ws.sendPrivateVideo(456, new Blob(['bytes']));
|
||||
const file: Promise<{ file_id: string | null }> = ws.sendPrivateFile(456, new Uint8Array([1]));
|
||||
ws.sendGroupFile(
|
||||
123,
|
||||
{ source: new Blob(['bytes']), filename: 'notes.txt' },
|
||||
{ folderId: '/docs' },
|
||||
);
|
||||
// @ts-expect-error Strings remain server paths; opening a local file must be explicit.
|
||||
http.sendPrivateImage(456, './picture.png');
|
||||
// @ts-expect-error Media attributes remain checked.
|
||||
http.sendGroupImage(123, source, { image: { subType: 'invalid' } });
|
||||
|
||||
const oldContext: SnowLumaEventContext<OneBotMessageEvent> = {
|
||||
event,
|
||||
client: http,
|
||||
stopped: false,
|
||||
stopPropagation() {},
|
||||
async reply() {},
|
||||
async approve() {},
|
||||
async reject() {},
|
||||
async quickOperation() {},
|
||||
};
|
||||
|
||||
const oldHandler: EventHandler<OneBotMessageEvent> = async (_event, context) => {
|
||||
await context.reply('unchanged');
|
||||
};
|
||||
|
||||
oldHandler(event, oldContext);
|
||||
ws.onMessage(oldHandler);
|
||||
|
||||
const oldMiddleware: EventMiddleware = async (_event, context, next) => {
|
||||
await context.reply('unchanged');
|
||||
await next();
|
||||
};
|
||||
|
||||
oldMiddleware(event, oldContext, async () => {});
|
||||
ws.use(oldMiddleware);
|
||||
|
||||
const context: SnowLumaEventContextWithQuote<OneBotMessageEvent> = createEventContext(event, http);
|
||||
const quoted: Promise<SendMessageResult> = context.quote(text('hello'));
|
||||
ws.onMessage(async (_event, ctx) => {
|
||||
await ctx.quote('hello');
|
||||
});
|
||||
ws.onGroupMessage(async (_event, ctx) => {
|
||||
await ctx.quote('hello');
|
||||
});
|
||||
ws.use(async (_event, ctx, next) => {
|
||||
await ctx.quote('hello');
|
||||
await next();
|
||||
});
|
||||
ws.command('ping', async (_event, ctx) => {
|
||||
await ctx.quote('pong');
|
||||
});
|
||||
http.sendGroupMessage(123, quoteMessage(-42, 'body'));
|
||||
http.sendPrivateMessage(456, messageQuote(-42, text('body')));
|
||||
|
||||
const waitOptions: EventWaitOptions & ClientWaitOptions = {
|
||||
timeoutMs: 100,
|
||||
signal: new AbortController().signal,
|
||||
};
|
||||
const group: Promise<OneBotGroupMessageEvent> = ws.waitForEvent(isGroupMessageEvent, waitOptions);
|
||||
const groupMessage: Promise<OneBotGroupMessageEvent> = ws.waitForMessage(isGroupMessageEvent);
|
||||
const message: Promise<OneBotMessageEvent> = ws.waitForMessage(
|
||||
(e) => e.user_id === 456,
|
||||
waitOptions,
|
||||
);
|
||||
const anyEvent: Promise<SnowLumaEvent> = ws.waitForEvent(waitOptions);
|
||||
ws.waitForEvent(undefined, waitOptions);
|
||||
ws.waitForMessage(waitOptions);
|
||||
// @ts-expect-error A filter without a type guard does not promise group fields.
|
||||
const wrong: Promise<OneBotGroupMessageEvent> = ws.waitForEvent(() => true);
|
||||
// @ts-expect-error Wait predicates are synchronous.
|
||||
ws.waitForMessage(async () => true);
|
||||
export { sent, sentPrivate, file, quoted, group, groupMessage, message, anyEvent, wrong };
|
||||
@@ -0,0 +1,382 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
SnowLumaAbortError,
|
||||
SnowLumaApiError,
|
||||
SnowLumaHttpClient,
|
||||
SnowLumaMediaSendError,
|
||||
SnowLumaTimeoutError,
|
||||
type JsonObject,
|
||||
} from '../src/index.js';
|
||||
import { localFile } from '../src/node/index.js';
|
||||
|
||||
function server(
|
||||
options: {
|
||||
failUpload?: boolean;
|
||||
failSend?: boolean;
|
||||
sendResponse?: (init?: RequestInit) => Promise<Response>;
|
||||
} = {},
|
||||
) {
|
||||
const calls: Array<{ action: string; params: JsonObject }> = [];
|
||||
let first: JsonObject;
|
||||
const fetch = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
|
||||
const { action, params } = JSON.parse(String(init?.body)) as {
|
||||
action: string;
|
||||
params: JsonObject;
|
||||
};
|
||||
calls.push({ action, params });
|
||||
|
||||
if (action !== 'upload_file_stream') {
|
||||
if (options.sendResponse) {
|
||||
return options.sendResponse(init);
|
||||
}
|
||||
|
||||
return Response.json(
|
||||
options.failSend
|
||||
? { status: 'failed', retcode: 123, data: null, wording: 'send rejected' }
|
||||
: {
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: action.startsWith('upload_')
|
||||
? { file_id: 'file-id' }
|
||||
: { message_id: -42 },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
if (params.chunk_index === 0) {
|
||||
first = params;
|
||||
}
|
||||
|
||||
if (options.failUpload) {
|
||||
return new Response(
|
||||
JSON.stringify({ status: 'failed', retcode: 321, data: null }) + '\r\n\r\n',
|
||||
);
|
||||
}
|
||||
|
||||
const data = params.is_complete
|
||||
? {
|
||||
type: 'response',
|
||||
status: 'file_complete',
|
||||
stream_id: first.stream_id,
|
||||
received_chunks: first.total_chunks,
|
||||
total_chunks: first.total_chunks,
|
||||
file_size: first.file_size,
|
||||
file_path: '/server/staged.bin',
|
||||
file_name: first.filename ?? 'generated.bin',
|
||||
sha256: 'a'.repeat(64),
|
||||
}
|
||||
: {
|
||||
type: 'stream',
|
||||
status: 'chunk_received',
|
||||
stream_id: params.stream_id,
|
||||
received_chunks: Number(params.chunk_index) + 1,
|
||||
total_chunks: params.total_chunks,
|
||||
};
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({ status: 'ok', retcode: 0, stream: 'stream-action', data }) +
|
||||
'\r\n\r\n',
|
||||
);
|
||||
});
|
||||
return { client: new SnowLumaHttpClient({ fetch }), calls, fetch };
|
||||
}
|
||||
|
||||
describe('one-step media sends', () => {
|
||||
it.each([
|
||||
['sendGroupImage', 'send_group_msg', 'group_id', 'image'],
|
||||
['sendPrivateImage', 'send_private_msg', 'user_id', 'image'],
|
||||
['sendGroupRecord', 'send_group_msg', 'group_id', 'record'],
|
||||
['sendPrivateRecord', 'send_private_msg', 'user_id', 'record'],
|
||||
['sendGroupVideo', 'send_group_msg', 'group_id', 'video'],
|
||||
['sendPrivateVideo', 'send_private_msg', 'user_id', 'video'],
|
||||
] as const)(
|
||||
'%s sends only after every chunk and final ACK',
|
||||
async (method, action, id, type) => {
|
||||
const { client, calls } = server();
|
||||
const progress = vi.fn();
|
||||
await expect(
|
||||
client[method](123, new Uint8Array([1, 2, 3]), {
|
||||
chunkSize: 2,
|
||||
onProgress: progress,
|
||||
}),
|
||||
).resolves.toEqual({ message_id: -42 });
|
||||
expect(calls.map((call) => call.action)).toEqual([
|
||||
'upload_file_stream',
|
||||
'upload_file_stream',
|
||||
'upload_file_stream',
|
||||
action,
|
||||
]);
|
||||
expect(calls.slice(0, 2).map((call) => call.params.chunk_data)).toEqual([
|
||||
'AQI=',
|
||||
'Aw==',
|
||||
]);
|
||||
expect(calls[2].params.is_complete).toBe(true);
|
||||
expect(calls[3].params).toEqual({
|
||||
[id]: 123,
|
||||
message: [{ type, data: { file: '/server/staged.bin' } }],
|
||||
});
|
||||
expect(progress).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ uploadedBytes: 3 }),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('preserves media attributes and does not mutate options', async () => {
|
||||
const { client, calls } = server();
|
||||
const image = Object.freeze({ subType: 1, summary: 'picture' });
|
||||
await client.sendGroupImage(123, new Blob(['bytes']), { image });
|
||||
expect(calls.at(-1)?.params.message).toEqual([
|
||||
{ type: 'image', data: { file: '/server/staged.bin', subType: 1, summary: 'picture' } },
|
||||
]);
|
||||
await client.sendPrivateVideo(456, new Uint8Array([1]), {
|
||||
video: { thumb: '/server/thumb' },
|
||||
});
|
||||
expect(calls.at(-1)?.params.message).toEqual([
|
||||
{ type: 'video', data: { file: '/server/staged.bin', thumb: '/server/thumb' } },
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps the uploaded file authoritative when callers pass wider attribute objects', async () => {
|
||||
const { client, calls } = server();
|
||||
// Structurally typed options may include extra fields from an existing segment.
|
||||
const image = { file: '/wrong/image', summary: 'picture' };
|
||||
const record = { file: '/wrong/record', url: 'https://example.test/voice' };
|
||||
const video = { file: '/wrong/video', thumb: '/server/thumb' };
|
||||
const source = new Uint8Array([1]);
|
||||
await client.sendGroupImage(123, source, { image });
|
||||
await client.sendPrivateImage(123, source, { image });
|
||||
await client.sendGroupRecord(123, source, { record });
|
||||
await client.sendPrivateRecord(123, source, { record });
|
||||
await client.sendGroupVideo(123, source, { video });
|
||||
await client.sendPrivateVideo(123, source, { video });
|
||||
const sends = calls.filter((call) => call.action.startsWith('send_'));
|
||||
expect(sends).toHaveLength(6);
|
||||
|
||||
for (const send of sends) {
|
||||
expect(send.params.message).toEqual([
|
||||
expect.objectContaining({
|
||||
data: expect.objectContaining({ file: '/server/staged.bin' }),
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
expect(image.file).toBe('/wrong/image');
|
||||
});
|
||||
|
||||
it('preserves File names and uses the existing file publishing actions exactly once', async () => {
|
||||
const { client, calls } = server();
|
||||
await expect(
|
||||
client.sendGroupFile(123, new File(['bytes'], '报告.txt'), {
|
||||
folderId: '/folder',
|
||||
}),
|
||||
).resolves.toEqual({ file_id: 'file-id' });
|
||||
expect(calls[0].params.filename).toBe('报告.txt');
|
||||
expect(calls.at(-1)).toEqual({
|
||||
action: 'upload_group_file',
|
||||
params: {
|
||||
group_id: 123,
|
||||
file: '/server/staged.bin',
|
||||
name: '报告.txt',
|
||||
folder_id: '/folder',
|
||||
upload_file: true,
|
||||
},
|
||||
});
|
||||
await client.sendPrivateFile(
|
||||
456,
|
||||
{ source: new Uint8Array([1]), filename: 'original.txt' },
|
||||
{
|
||||
filename: 'staged.txt',
|
||||
name: '发送.txt',
|
||||
},
|
||||
);
|
||||
expect(calls[3].params.filename).toBe('staged.txt');
|
||||
expect(calls.at(-1)).toEqual({
|
||||
action: 'upload_private_file',
|
||||
params: {
|
||||
user_id: 456,
|
||||
file: '/server/staged.bin',
|
||||
name: '发送.txt',
|
||||
upload_file: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps async sources incremental and accepts declared sizes', async () => {
|
||||
const { client, calls } = server();
|
||||
const source = (async function* () {
|
||||
yield new Uint8Array([1]);
|
||||
expect(calls).toHaveLength(1);
|
||||
yield new Uint8Array([2]);
|
||||
})();
|
||||
await client.sendGroupImage(123, source, { fileSize: 2, chunkSize: 1 });
|
||||
expect(calls).toHaveLength(4);
|
||||
});
|
||||
|
||||
it('reports upload failure with its cause and never dispatches the message', async () => {
|
||||
const { client, calls } = server({ failUpload: true });
|
||||
await expect(client.sendGroupImage(123, new Uint8Array([1]))).rejects.toMatchObject({
|
||||
name: 'SnowLumaMediaSendError',
|
||||
stage: 'upload',
|
||||
upload: undefined,
|
||||
cause: expect.any(SnowLumaApiError),
|
||||
});
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('retains the completed upload and original send error without retrying', async () => {
|
||||
const { client, calls } = server({ failSend: true });
|
||||
await expect(client.sendGroupImage(123, new Uint8Array([1]))).rejects.toMatchObject({
|
||||
stage: 'send',
|
||||
upload: { file_path: '/server/staged.bin' },
|
||||
cause: expect.objectContaining({ retcode: 123 }),
|
||||
});
|
||||
expect(calls).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('prevents dispatch when cancellation occurs between upload and send', async () => {
|
||||
const controller = new AbortController();
|
||||
const { client, calls } = server();
|
||||
const upload = client.uploadFileStream.bind(client);
|
||||
vi.spyOn(client, 'uploadFileStream').mockImplementation(async (...args) => {
|
||||
const result = await upload(...args);
|
||||
controller.abort('stop');
|
||||
return result;
|
||||
});
|
||||
await expect(
|
||||
client.sendGroupImage(123, new Uint8Array([1]), {
|
||||
signal: controller.signal,
|
||||
}),
|
||||
).rejects.toMatchObject({ stage: 'send', cause: expect.any(SnowLumaAbortError) });
|
||||
expect(calls.every((call) => call.action === 'upload_file_stream')).toBe(true);
|
||||
});
|
||||
|
||||
it('passes cancellation to the upload and stops before any later stage', async () => {
|
||||
const controller = new AbortController();
|
||||
const { client, calls } = server();
|
||||
await expect(
|
||||
client.sendPrivateFile(123, new Uint8Array([1, 2]), {
|
||||
chunkSize: 1,
|
||||
signal: controller.signal,
|
||||
onProgress: () => controller.abort(),
|
||||
}),
|
||||
).rejects.toMatchObject({ stage: 'upload', cause: expect.any(SnowLumaAbortError) });
|
||||
expect(calls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('passes request controls to both stages', async () => {
|
||||
const { client } = server();
|
||||
const upload = vi.spyOn(client, 'uploadFileStream');
|
||||
const send = vi.spyOn(client, 'sendGroupMessage');
|
||||
const controls = { signal: new AbortController().signal, timeoutMs: 1234, echo: 'media' };
|
||||
await client.sendGroupImage(123, new Uint8Array([1]), controls);
|
||||
expect(upload.mock.calls[0][1]).toMatchObject(controls);
|
||||
expect(send.mock.calls[0][2]).toEqual(controls);
|
||||
});
|
||||
|
||||
it.each(['abort', 'timeout'] as const)(
|
||||
'retains upload metadata when an in-flight send ends by %s',
|
||||
async (mode) => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
const controller = new AbortController();
|
||||
const { client, calls } = server({
|
||||
sendResponse: (init) =>
|
||||
new Promise((_resolve, reject) => {
|
||||
init?.signal?.addEventListener(
|
||||
'abort',
|
||||
() => reject(init.signal?.reason),
|
||||
{ once: true },
|
||||
);
|
||||
}),
|
||||
});
|
||||
const result = client.sendGroupImage(123, new Uint8Array([1]), {
|
||||
signal: controller.signal,
|
||||
timeoutMs: 1000,
|
||||
});
|
||||
const rejected = expect(result).rejects.toMatchObject({
|
||||
stage: 'send',
|
||||
upload: { file_path: '/server/staged.bin' },
|
||||
cause:
|
||||
mode === 'abort'
|
||||
? expect.any(SnowLumaAbortError)
|
||||
: expect.any(SnowLumaTimeoutError),
|
||||
});
|
||||
await vi.waitFor(() => expect(calls.at(-1)?.action).toBe('send_group_msg'));
|
||||
|
||||
if (mode === 'abort') {
|
||||
controller.abort();
|
||||
} else {
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
}
|
||||
|
||||
await rejected;
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('never treats a string as a local path', async () => {
|
||||
const { client, fetch } = server();
|
||||
// @ts-expect-error A local path must be explicitly opened with localFile().
|
||||
await expect(client.sendGroupImage(123, './local.png')).rejects.toBeInstanceOf(
|
||||
SnowLumaMediaSendError,
|
||||
);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Node localFile source', () => {
|
||||
let directory: string | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
if (directory) {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
async function fixture() {
|
||||
directory = await mkdtemp(join(tmpdir(), 'sdk-local-media-'));
|
||||
const path = join(directory, '图片.bin');
|
||||
await writeFile(path, new Uint8Array([7, 8, 9]));
|
||||
return path;
|
||||
}
|
||||
|
||||
it('sends file-backed bytes from paths and file URLs without leaking the local path', async () => {
|
||||
const path = await fixture();
|
||||
|
||||
for (const location of [path, pathToFileURL(path)]) {
|
||||
const source = await localFile(location);
|
||||
const { client, calls } = server();
|
||||
await client.sendPrivateImage(123, source);
|
||||
expect(calls[0].params).toMatchObject({
|
||||
filename: '图片.bin',
|
||||
file_size: 3,
|
||||
chunk_data: 'BwgJ',
|
||||
});
|
||||
expect(JSON.stringify(calls)).not.toContain(directory);
|
||||
}
|
||||
});
|
||||
|
||||
it('reports missing files and rejects directories before uploading', async () => {
|
||||
const path = await fixture();
|
||||
await expect(localFile(path + '.missing')).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
await expect(localFile(directory!)).rejects.toThrow('regular file');
|
||||
});
|
||||
|
||||
it('fails if the file changes after the source is created', async () => {
|
||||
const path = await fixture();
|
||||
const source = await localFile(path);
|
||||
await writeFile(path, 'modified file');
|
||||
const { client, fetch } = server();
|
||||
await expect(client.sendGroupFile(123, source)).rejects.toMatchObject({ stage: 'upload' });
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -49,6 +49,10 @@ beforeAll(() => {
|
||||
path.join(sdkRoot, 'tests', 'fixtures', 'action-contracts.ts'),
|
||||
path.join(consumerRoot, 'action-contracts.ts'),
|
||||
);
|
||||
copyFileSync(
|
||||
path.join(sdkRoot, 'tests', 'fixtures', 'messaging-types.mts'),
|
||||
path.join(consumerRoot, 'messaging-types.mts'),
|
||||
);
|
||||
|
||||
// Compile fresh output outside the workspace so neither stale dist files nor
|
||||
// Vitest's source resolver can hide a broken published entry point.
|
||||
@@ -117,8 +121,10 @@ import * as actions from '@snowluma/sdk/actions';
|
||||
assert.equal(sdk.SnowLumaHttpClient, client.SnowLumaHttpClient);
|
||||
assert.equal(sdk.SnowLumaWebSocketClient, client.SnowLumaWebSocketClient);
|
||||
assert.equal(sdk.MessageChain, messages.MessageChain);
|
||||
assert.equal(sdk.quoteMessage, messages.quoteMessage);
|
||||
assert.equal(sdk.isMessageEvent, events.isMessageEvent);
|
||||
assert.equal(sdk.SnowLumaApiError, errors.SnowLumaApiError);
|
||||
assert.equal(sdk.SnowLumaMediaSendError, errors.SnowLumaMediaSendError);
|
||||
assert.equal(sdk.SNOWLUMA_ACTIONS, actions.SNOWLUMA_ACTIONS);
|
||||
assert.equal(sdk.isSnowLumaAction, actions.isSnowLumaAction);
|
||||
assert.ok(sdk.text('hello') instanceof messages.MessageChain);
|
||||
@@ -148,6 +154,7 @@ assert.equal(actions.isSnowLumaAction('consumer_extension'), false);
|
||||
resolution,
|
||||
path.join(consumerRoot, 'consumer.mts'),
|
||||
path.join(consumerRoot, 'action-types.mts'),
|
||||
path.join(consumerRoot, 'messaging-types.mts'),
|
||||
]);
|
||||
},
|
||||
30_000,
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { SnowLumaApiClient } from '../src/client/api-client';
|
||||
import { SnowLumaApiError } from '../src/errors';
|
||||
import { createEventContext } from '../src/events/context';
|
||||
import { chain } from '../src/messages/chain';
|
||||
import { quoteMessage } from '../src/messages/quote';
|
||||
import { segments } from '../src/messages/segments';
|
||||
import type {
|
||||
ActionParams,
|
||||
ActionResult,
|
||||
ApiResponse,
|
||||
OneBotGroupMessageEvent,
|
||||
OneBotPrivateMessageEvent,
|
||||
OneBotRequestEvent,
|
||||
RequestOptions,
|
||||
SnowLumaAction,
|
||||
} from '../src/types';
|
||||
|
||||
class RecordingClient extends SnowLumaApiClient {
|
||||
readonly calls: Array<{
|
||||
action: string;
|
||||
params: unknown;
|
||||
options: RequestOptions | undefined;
|
||||
}> = [];
|
||||
|
||||
response: ApiResponse = { status: 'ok', retcode: 0, data: { message_id: -19 } };
|
||||
|
||||
async request<TAction extends SnowLumaAction>(
|
||||
action: TAction,
|
||||
params?: ActionParams<TAction>,
|
||||
options?: RequestOptions,
|
||||
): Promise<ApiResponse<ActionResult<TAction>>> {
|
||||
this.calls.push({ action, params, options });
|
||||
return this.response as ApiResponse<ActionResult<TAction>>;
|
||||
}
|
||||
}
|
||||
|
||||
const PRIVATE_EVENT: OneBotPrivateMessageEvent = {
|
||||
time: 1,
|
||||
self_id: 10000,
|
||||
post_type: 'message',
|
||||
message_type: 'private',
|
||||
sub_type: 'friend',
|
||||
message_id: -2147483648,
|
||||
user_id: 10001,
|
||||
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||
raw_message: 'hello',
|
||||
font: 0,
|
||||
sender: { user_id: 10001, nickname: 'tester' },
|
||||
};
|
||||
|
||||
const GROUP_EVENT: OneBotGroupMessageEvent = {
|
||||
...PRIVATE_EVENT,
|
||||
message_type: 'group',
|
||||
sub_type: 'normal',
|
||||
group_id: 20001,
|
||||
message_id: 2147483647,
|
||||
};
|
||||
|
||||
describe('quoteMessage', () => {
|
||||
it('preserves CQ strings, extension fields and escaping byte for byte', () => {
|
||||
const body = 'hi&[CQ:image,file=a,b,subType=7,extension=keep]';
|
||||
expect(quoteMessage(-123, body)).toBe(`[CQ:reply,id=-123]${body}`);
|
||||
});
|
||||
|
||||
it('treats the complete string as literal text when autoEscape is enabled', () => {
|
||||
const body = '[CQ:reply,id=7] [ &';
|
||||
expect(quoteMessage(-123, body, { autoEscape: true })).toEqual([
|
||||
segments.reply(-123),
|
||||
segments.text(body),
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not interpret escaped CQ-like text as an existing reply', () => {
|
||||
const body = '[CQ:reply,id=7]';
|
||||
expect(quoteMessage(-123, body)).toBe(`[CQ:reply,id=-123]${body}`);
|
||||
});
|
||||
|
||||
it('adds a quote to one segment, an array and a chain without mutating inputs', () => {
|
||||
const segment = Object.freeze({
|
||||
type: 'text' as const,
|
||||
data: Object.freeze({ text: 'hello' }),
|
||||
});
|
||||
const array = [segment];
|
||||
Object.freeze(array);
|
||||
const messageChain = chain().text('hello');
|
||||
const expected = [segments.reply(-123), segment];
|
||||
|
||||
expect(quoteMessage(-123, segment)).toEqual(expected);
|
||||
expect(quoteMessage(-123, array)).toEqual(expected);
|
||||
expect(quoteMessage(-123, messageChain)).toEqual(expected);
|
||||
expect(array).toEqual([segment]);
|
||||
expect(messageChain.toSegments()).toEqual([segment]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'[CQ:reply,id=-12]hello',
|
||||
segments.reply(-12),
|
||||
[segments.text('hello'), segments.reply(-12)],
|
||||
chain().text('hello').reply(-12),
|
||||
segments.customReply('quoted'),
|
||||
])('rejects a body that already contains a reply: %j', (body) => {
|
||||
expect(() => quoteMessage(-123, body)).toThrow(/containing a reply/);
|
||||
});
|
||||
|
||||
it('does not treat replies inside a forward node as an outer reply', () => {
|
||||
const node = segments.node(10001, 'tester', [segments.reply(-12), segments.text('body')]);
|
||||
expect(quoteMessage(-123, node)).toEqual([segments.reply(-123), node]);
|
||||
});
|
||||
|
||||
it.each([0, NaN, Infinity, -Infinity, 1.5, -2147483649, 2147483648])(
|
||||
'rejects invalid message ID %s',
|
||||
(messageId) => {
|
||||
expect(() => quoteMessage(messageId, 'hello')).toThrow(/signed 32-bit message ID/);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('event context quote', () => {
|
||||
it('quotes a private event with its signed ID and forwards request options', async () => {
|
||||
const client = new RecordingClient();
|
||||
const context = createEventContext(PRIVATE_EVENT, client);
|
||||
const options = { signal: new AbortController().signal, timeoutMs: 250, echo: 'quote' };
|
||||
|
||||
await expect(context.quote('reply body', options)).resolves.toEqual({ message_id: -19 });
|
||||
expect(client.calls).toEqual([
|
||||
{
|
||||
action: 'send_private_msg',
|
||||
params: {
|
||||
user_id: 10001,
|
||||
message: '[CQ:reply,id=-2147483648]reply body',
|
||||
auto_escape: undefined,
|
||||
},
|
||||
options,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('quotes a group event in its group rather than sending privately to its author', async () => {
|
||||
const client = new RecordingClient();
|
||||
const context = createEventContext(GROUP_EVENT, client);
|
||||
|
||||
await context.quote(chain().text('reply body'));
|
||||
expect(client.calls).toEqual([
|
||||
{
|
||||
action: 'send_group_msg',
|
||||
params: {
|
||||
group_id: 20001,
|
||||
message: [segments.reply(2147483647), segments.text('reply body')],
|
||||
auto_escape: undefined,
|
||||
},
|
||||
options: undefined,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('sends literal CQ text with autoEscape without escaping the added quote', async () => {
|
||||
const client = new RecordingClient();
|
||||
const context = createEventContext(PRIVATE_EVENT, client);
|
||||
|
||||
await context.quote('[CQ:reply,id=-99]hello', { autoEscape: true });
|
||||
expect(client.calls[0]?.params).toEqual({
|
||||
user_id: 10001,
|
||||
message: [segments.reply(-2147483648), segments.text('[CQ:reply,id=-99]hello')],
|
||||
auto_escape: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps reply() unquoted and preserves its existing CQ behavior', async () => {
|
||||
const client = new RecordingClient();
|
||||
const context = createEventContext(PRIVATE_EVENT, client);
|
||||
const body = '[CQ:reply,id=7]hello';
|
||||
|
||||
await context.reply(body);
|
||||
expect(client.calls[0]?.params).toEqual({
|
||||
user_id: 10001,
|
||||
message: body,
|
||||
auto_escape: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not perform a request when the event is not a message', async () => {
|
||||
const client = new RecordingClient();
|
||||
const event: OneBotRequestEvent = {
|
||||
time: 1,
|
||||
self_id: 10000,
|
||||
post_type: 'request',
|
||||
request_type: 'friend',
|
||||
user_id: 10001,
|
||||
flag: 'request-1',
|
||||
};
|
||||
|
||||
await expect(createEventContext(event, client).quote('hello')).rejects.toThrow(
|
||||
'quote() is only available for message events',
|
||||
);
|
||||
expect(client.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not send duplicate quotes or invalid event IDs', async () => {
|
||||
const client = new RecordingClient();
|
||||
|
||||
await expect(
|
||||
createEventContext(PRIVATE_EVENT, client).quote('[CQ:reply,id=7]'),
|
||||
).rejects.toThrow(/containing a reply/);
|
||||
await expect(
|
||||
createEventContext({ ...PRIVATE_EVENT, message_id: 0 }, client).quote('hello'),
|
||||
).rejects.toThrow(/signed 32-bit message ID/);
|
||||
expect(client.calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('preserves the original transport failure', async () => {
|
||||
const client = new RecordingClient();
|
||||
const failure = new Error('connection lost');
|
||||
|
||||
client.request = async () => {
|
||||
throw failure;
|
||||
};
|
||||
|
||||
await expect(createEventContext(PRIVATE_EVENT, client).quote('hello')).rejects.toBe(
|
||||
failure,
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves API failure details without retrying the send', async () => {
|
||||
const client = new RecordingClient();
|
||||
client.response = {
|
||||
status: 'failed',
|
||||
retcode: 1200,
|
||||
data: null,
|
||||
wording: 'quote unavailable',
|
||||
};
|
||||
|
||||
await expect(
|
||||
createEventContext(PRIVATE_EVENT, client).quote('hello'),
|
||||
).rejects.toMatchObject({
|
||||
constructor: SnowLumaApiError,
|
||||
retcode: 1200,
|
||||
wording: 'quote unavailable',
|
||||
});
|
||||
expect(client.calls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user