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
+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,
});
});
});