@umx-bot/plugin-testkit 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 qq-bot contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # @umx-bot/plugin-testkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ In-memory integration host for testing qq-bot plugins with their real command,
4
+ event, middleware, storage and lifecycle runtime.
5
+
6
+ ```ts
7
+ const host = createPluginTestHost();
8
+ await host.load(plugin, { config: { endpoint: "https://example.com" } });
9
+ await host.start();
10
+ const replies = await host.receive("/hello");
11
+ await host.emit("contact.added", {
12
+ platform: "test",
13
+ userId: "user-1",
14
+ timestamp: new Date()
15
+ });
16
+ await host.stop();
17
+ ```
18
+
19
+ `receive()` can inject attachments, mentions, bot mention state, timestamps and
20
+ raw platform data. `createPluginTestHost()` also accepts a custom `store` and
21
+ `logger` for persistence and diagnostics tests. Use `adapterCapabilities` to
22
+ stub recall, typing and streaming support.
@@ -0,0 +1,35 @@
1
+ import type { Awaitable, BotAdapter, ChatScope } from "@umx-bot/plugin-sdk";
2
+ export interface AdapterConformanceOptions {
3
+ /**
4
+ * Builds a fresh adapter. Called once per check, so a check can never be
5
+ * affected by state another check left behind.
6
+ */
7
+ createAdapter: () => Awaitable<BotAdapter>;
8
+ /**
9
+ * A conversation the adapter accepts. Defaults to a group conversation,
10
+ * which every adapter in this project supports.
11
+ */
12
+ conversation?: {
13
+ scope: ChatScope;
14
+ conversationId: string;
15
+ };
16
+ /** Skips the `send()` checks for an adapter that cannot send in tests. */
17
+ skipSend?: boolean;
18
+ }
19
+ export interface AdapterConformanceCheck {
20
+ name: string;
21
+ run: () => Promise<void>;
22
+ }
23
+ /**
24
+ * The `BotAdapter` contract, as executable checks.
25
+ *
26
+ * The framework claims to be platform-neutral, but that claim is only worth
27
+ * something if every adapter is held to the same behaviour. These checks cover
28
+ * the invariants the kernel and the application rely on, so a new adapter can
29
+ * be validated before it is wired into anything.
30
+ *
31
+ * Framework-agnostic on purpose: each check throws on failure, so it can be
32
+ * driven from `it()`, `test()` or a plain loop.
33
+ */
34
+ export declare function adapterConformanceChecks(options: AdapterConformanceOptions): AdapterConformanceCheck[];
35
+ //# sourceMappingURL=conformance.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conformance.d.ts","sourceRoot":"","sources":["../src/conformance.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,SAAS,EACT,UAAU,EAEV,SAAS,EAGV,MAAM,qBAAqB,CAAC;AAE7B,MAAM,WAAW,yBAAyB;IACxC;;;OAGG;IACH,aAAa,EAAE,MAAM,SAAS,CAAC,UAAU,CAAC,CAAC;IAC3C;;;OAGG;IACH,YAAY,CAAC,EAAE;QAAE,KAAK,EAAE,SAAS,CAAC;QAAC,cAAc,EAAE,MAAM,CAAA;KAAE,CAAC;IAC5D,0EAA0E;IAC1E,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB;AAED,MAAM,WAAW,uBAAuB;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC1B;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,yBAAyB,GACjC,uBAAuB,EAAE,CAkL3B"}
@@ -0,0 +1,178 @@
1
+ /**
2
+ * The `BotAdapter` contract, as executable checks.
3
+ *
4
+ * The framework claims to be platform-neutral, but that claim is only worth
5
+ * something if every adapter is held to the same behaviour. These checks cover
6
+ * the invariants the kernel and the application rely on, so a new adapter can
7
+ * be validated before it is wired into anything.
8
+ *
9
+ * Framework-agnostic on purpose: each check throws on failure, so it can be
10
+ * driven from `it()`, `test()` or a plain loop.
11
+ */
12
+ export function adapterConformanceChecks(options) {
13
+ const conversation = options.conversation ?? {
14
+ scope: "group",
15
+ conversationId: "conformance-conversation"
16
+ };
17
+ const create = async () => options.createAdapter();
18
+ const noopHandlers = () => [() => undefined, () => undefined];
19
+ const checks = [
20
+ {
21
+ name: "exposes a stable lowercase name",
22
+ run: async () => {
23
+ const adapter = await create();
24
+ assert(typeof adapter.name === "string" && adapter.name.length > 0, "adapter.name must be a non-empty string");
25
+ assert(adapter.name === adapter.name.toLowerCase(), `adapter.name must be lowercase, got "${adapter.name}"`);
26
+ assert(!/\s/u.test(adapter.name), `adapter.name must not contain whitespace, got "${adapter.name}"`);
27
+ // The kernel reads `name` on every message, so it must not change.
28
+ const first = adapter.name;
29
+ await adapter.stop();
30
+ assert(adapter.name === first, "adapter.name must not change over the lifecycle");
31
+ }
32
+ },
33
+ {
34
+ name: "tolerates stop() before start()",
35
+ run: async () => {
36
+ const adapter = await create();
37
+ // The kernel calls stop() during a failed startup rollback, possibly
38
+ // before the adapter ever started.
39
+ await adapter.stop();
40
+ }
41
+ },
42
+ {
43
+ name: "tolerates a repeated stop()",
44
+ run: async () => {
45
+ const adapter = await create();
46
+ const [onMessage, onEvent] = noopHandlers();
47
+ await adapter.start(onMessage, onEvent);
48
+ await adapter.stop();
49
+ await adapter.stop();
50
+ }
51
+ },
52
+ {
53
+ name: "treats a repeated start() as idempotent",
54
+ run: async () => {
55
+ const adapter = await create();
56
+ const [onMessage, onEvent] = noopHandlers();
57
+ await adapter.start(onMessage, onEvent);
58
+ await adapter.start(onMessage, onEvent);
59
+ await adapter.stop();
60
+ }
61
+ },
62
+ {
63
+ name: "can be restarted after a stop()",
64
+ run: async () => {
65
+ const adapter = await create();
66
+ const [onMessage, onEvent] = noopHandlers();
67
+ await adapter.start(onMessage, onEvent);
68
+ await adapter.stop();
69
+ await adapter.start(onMessage, onEvent);
70
+ await adapter.stop();
71
+ }
72
+ },
73
+ {
74
+ name: "starts without an event handler",
75
+ run: async () => {
76
+ const adapter = await create();
77
+ // `onEvent` is optional in the contract; an adapter must not assume it.
78
+ await adapter.start(() => undefined);
79
+ await adapter.stop();
80
+ }
81
+ },
82
+ {
83
+ name: "reports JSON-serializable diagnostics",
84
+ run: async () => {
85
+ const adapter = await create();
86
+ if (!adapter.getDiagnostics) {
87
+ return;
88
+ }
89
+ const [onMessage, onEvent] = noopHandlers();
90
+ await adapter.start(onMessage, onEvent);
91
+ try {
92
+ const diagnostics = adapter.getDiagnostics();
93
+ assert(diagnostics !== null && typeof diagnostics === "object", "getDiagnostics() must return an object");
94
+ // The application writes diagnostics into its health snapshot, so a
95
+ // value that cannot be serialized breaks health checks in production.
96
+ const serialized = JSON.stringify(diagnostics);
97
+ assert(typeof serialized === "string", "getDiagnostics() must be JSON-serializable");
98
+ JSON.parse(serialized);
99
+ }
100
+ finally {
101
+ await adapter.stop();
102
+ }
103
+ }
104
+ },
105
+ {
106
+ name: "keeps diagnostics callable before start()",
107
+ run: async () => {
108
+ const adapter = await create();
109
+ if (!adapter.getDiagnostics) {
110
+ return;
111
+ }
112
+ // The health snapshot is written before the kernel starts.
113
+ JSON.stringify(adapter.getDiagnostics());
114
+ await adapter.stop();
115
+ }
116
+ }
117
+ ];
118
+ if (!options.skipSend) {
119
+ checks.push({
120
+ name: "returns a usable receipt from send()",
121
+ run: async () => {
122
+ const adapter = await create();
123
+ const [onMessage, onEvent] = noopHandlers();
124
+ await adapter.start(onMessage, onEvent);
125
+ try {
126
+ const receipt = await adapter.send({
127
+ scope: conversation.scope,
128
+ conversationId: conversation.conversationId,
129
+ content: "conformance",
130
+ delivery: { type: "active", idempotencyKey: "conformance-1" }
131
+ });
132
+ assertReceipt(receipt, adapter.name, conversation);
133
+ }
134
+ finally {
135
+ await adapter.stop();
136
+ }
137
+ }
138
+ }, {
139
+ name: "echoes the conversation of a passive reply",
140
+ run: async () => {
141
+ const adapter = await create();
142
+ const [onMessage, onEvent] = noopHandlers();
143
+ await adapter.start(onMessage, onEvent);
144
+ try {
145
+ const receipt = await adapter.send({
146
+ scope: conversation.scope,
147
+ conversationId: conversation.conversationId,
148
+ content: "conformance",
149
+ delivery: {
150
+ type: "passive",
151
+ target: { type: "message", messageId: "incoming-1" }
152
+ }
153
+ });
154
+ assertReceipt(receipt, adapter.name, conversation);
155
+ }
156
+ finally {
157
+ await adapter.stop();
158
+ }
159
+ }
160
+ });
161
+ }
162
+ return checks;
163
+ }
164
+ function assertReceipt(receipt, platform, conversation) {
165
+ assert(receipt !== null && typeof receipt === "object", "send() must resolve with a SentMessage");
166
+ assert(receipt.platform === platform, `receipt.platform must be "${platform}", got "${receipt.platform}"`);
167
+ assert(receipt.scope === conversation.scope, `receipt.scope must echo the request, got "${receipt.scope}"`);
168
+ assert(receipt.conversationId === conversation.conversationId, "receipt.conversationId must echo the request");
169
+ assert(typeof receipt.id === "string" && receipt.id.length > 0, "receipt.id must be a non-empty string so the message can be recalled");
170
+ assert(receipt.timestamp instanceof Date &&
171
+ Number.isFinite(receipt.timestamp.getTime()), "receipt.timestamp must be a valid Date");
172
+ }
173
+ function assert(condition, message) {
174
+ if (!condition) {
175
+ throw new Error(`adapter conformance: ${message}`);
176
+ }
177
+ }
178
+ //# sourceMappingURL=conformance.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conformance.js","sourceRoot":"","sources":["../src/conformance.ts"],"names":[],"mappings":"AA6BA;;;;;;;;;;GAUG;AACH,MAAM,UAAU,wBAAwB,CACtC,OAAkC;IAElC,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI;QAC3C,KAAK,EAAE,OAAoB;QAC3B,cAAc,EAAE,0BAA0B;KAC3C,CAAC;IACF,MAAM,MAAM,GAAG,KAAK,IAAyB,EAAE,CAAC,OAAO,CAAC,aAAa,EAAE,CAAC;IACxE,MAAM,YAAY,GAAG,GAMnB,EAAE,CAAC,CAAC,GAAG,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAExC,MAAM,MAAM,GAA8B;QACxC;YACE,IAAI,EAAE,iCAAiC;YACvC,GAAG,EAAE,KAAK,IAAI,EAAE;gBACd,MAAM,OAAO,GAAG,MAAM,MAAM,EAAE,CAAC;gBAC/B,MAAM,CACJ,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,EAC3D,yCAAyC,CAC1C,CAAC;gBACF,MAAM,CACJ,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,EAC3C,wCAAwC,OAAO,CAAC,IAAI,GAAG,CACxD,CAAC;gBACF,MAAM,CACJ,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EACzB,kDAAkD,OAAO,CAAC,IAAI,GAAG,CAClE,CAAC;gBACF,mEAAmE;gBACnE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;gBAC3B,MAAM,OAA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,CAAC;IACF,MAAM,CACJ,OAAO,OAAO,CAAC,EAAE,KAAK,QAAQ,IAAI,OAAO,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,EACvD,sEAAsE,CACvE,CAAC;IACF,MAAM,CACJ,OAAO,CAAC,SAAS,YAAY,IAAI;QAC/B,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC,OAAO,EAAE,CAAC,EAC9C,wCAAwC,CACzC,CAAC;AACJ,CAAC;AAED,SAAS,MAAM,CAAC,SAAkB,EAAE,OAAe;IACjD,IAAI,CAAC,SAAS,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,wBAAwB,OAAO,EAAE,CAAC,CAAC;IACrD,CAAC;AACH,CAAC"}
@@ -0,0 +1,58 @@
1
+ export { type AdapterConformanceCheck, type AdapterConformanceOptions, adapterConformanceChecks } from "./conformance.js";
2
+ import type { BotKernelOptions, PluginLoadOptions } from "@umx-bot/core";
3
+ import { BotKernel } from "@umx-bot/core";
4
+ import type { BotEvents, BotPlugin, ChatScope, ConversationRef, IncomingMessage, KeyValueStore, Logger, MemberRole, MessageStream, MessageStreamOptions, NavigationPageSummary, OutgoingMessage, ReplyTarget, SentMessage } from "@umx-bot/plugin-sdk";
5
+ export interface TestMessageOptions {
6
+ id?: string;
7
+ authorId?: string;
8
+ authorName?: string;
9
+ role?: MemberRole;
10
+ platform?: string;
11
+ scope?: ChatScope;
12
+ conversationId?: string;
13
+ attachments?: IncomingMessage["attachments"];
14
+ mentions?: IncomingMessage["mentions"];
15
+ quote?: IncomingMessage["quote"];
16
+ botMentioned?: boolean;
17
+ timestamp?: Date;
18
+ raw?: unknown;
19
+ }
20
+ export interface PluginTestHostOptions {
21
+ commandPrefix?: string;
22
+ ownerIds?: BotKernelOptions["ownerIds"];
23
+ accessPolicy?: BotKernelOptions["accessPolicy"];
24
+ contextExtensions?: BotKernelOptions["contextExtensions"];
25
+ logger?: Logger;
26
+ store?: KeyValueStore;
27
+ adapterCapabilities?: {
28
+ recall?: (message: SentMessage) => Promise<void>;
29
+ setTyping?: (conversation: ConversationRef, seconds: number, target: ReplyTarget) => Promise<void>;
30
+ openMessageStream?: (options: MessageStreamOptions) => Promise<MessageStream>;
31
+ };
32
+ }
33
+ export declare class PluginTestHost {
34
+ private readonly adapter;
35
+ private readonly kernel;
36
+ private sentCursor;
37
+ constructor(options?: PluginTestHostOptions);
38
+ load(plugin: BotPlugin, options?: PluginLoadOptions): Promise<void>;
39
+ unload(name: string): Promise<boolean>;
40
+ start(): Promise<void>;
41
+ stop(): Promise<void>;
42
+ receive(content: string, options?: TestMessageOptions): Promise<OutgoingMessage[]>;
43
+ emit<K extends Exclude<keyof BotEvents, "message.created">>(event: K, payload: BotEvents[K]): Promise<void>;
44
+ /**
45
+ * Messages sent since the last `receive` or `flush`. Use it after `emit`,
46
+ * which has no return value, to see what an event handler or a callback
47
+ * button handler sent.
48
+ */
49
+ flush(): OutgoingMessage[];
50
+ /** Prometheus text for kernel and plugin metrics. */
51
+ getMetricsText(): string;
52
+ /** Settings defined by loaded plugins. */
53
+ get settings(): BotKernel["settings"];
54
+ getHealth(): import("@umx-bot/core").BotKernelHealth;
55
+ getNavigation(): NavigationPageSummary[];
56
+ }
57
+ export declare function createPluginTestHost(options?: PluginTestHostOptions): PluginTestHost;
58
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,uBAAuB,EAC5B,KAAK,yBAAyB,EAC9B,wBAAwB,EACzB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACzE,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,KAAK,EAGV,SAAS,EACT,SAAS,EACT,SAAS,EACT,eAAe,EACf,eAAe,EACf,aAAa,EACb,MAAM,E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iB,CAAC,EAAE,CAClB,OAAO,EAAE,oBAAoB,KAC1B,OAAO,CAAC,aAAa,CAAC,CAAC;KAC7B,CAAC;CACH;AAuHD,qBAAa,cAAc;IACzB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAc;IACtC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,UAAU,CAAK;gBAEJ,OAAO,GAAE,qBAA0B;IAiB/C,IAAI,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAInE,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAItC,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAItB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAIf,OAAO,CAClB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE,kBAAkB,GAC3B,OAAO,CAAC,eAAe,EAAE,CAAC;IAStB,IAAI,CAAC,CAAC,SAAS,OAAO,CAAC,MAAM,SAAS,EAAE,iBAAiB,CAAC,EAC/D,KAAK,EAAE,CAAC,EACR,OAAO,EAAE,SAAS,CAAC,CAAC,CAAC,GACpB,OAAO,CAAC,IAAI,CAAC;IAIhB;;;;OAIG;IACI,KAAK,IAAI,eAAe,EAAE;IAQjC,qDAAqD;IAC9C,cAAc,IAAI,MAAM;IAI/B,0CAA0C;IAC1C,IAAW,QAAQ,IAAI,SAAS,CAAC,UAAU,CAAC,CAE3C;IAEM,SAAS;IAIT,aAAa,IAAI,qBAAqB,EAAE;CAGhD;AAED,wBAAgB,oBAAoB,CAClC,OAAO,GAAE,qBAA0B,GAClC,cAAc,CAEhB"}
package/dist/index.js ADDED
@@ -0,0 +1,158 @@
1
+ export { adapterConformanceChecks } from "./conformance.js";
2
+ import { BotKernel } from "@umx-bot/core";
3
+ class SilentLogger {
4
+ debug() { }
5
+ info() { }
6
+ warn() { }
7
+ error() { }
8
+ child() {
9
+ return this;
10
+ }
11
+ }
12
+ class TestAdapter {
13
+ name = "test";
14
+ sent = [];
15
+ recall;
16
+ setTyping;
17
+ openMessageStream;
18
+ onMessage;
19
+ onEvent;
20
+ nextMessageId = 1;
21
+ constructor(capabilities = {}) {
22
+ if (capabilities.recall) {
23
+ this.recall = capabilities.recall;
24
+ }
25
+ if (capabilities.setTyping) {
26
+ this.setTyping = capabilities.setTyping;
27
+ }
28
+ if (capabilities.openMessageStream) {
29
+ this.openMessageStream = capabilities.openMessageStream;
30
+ }
31
+ }
32
+ async start(onMessage, onEvent) {
33
+ this.onMessage = onMessage;
34
+ this.onEvent = onEvent;
35
+ }
36
+ async stop() {
37
+ this.onMessage = undefined;
38
+ this.onEvent = undefined;
39
+ }
40
+ async send(message) {
41
+ this.sent.push(message);
42
+ return {
43
+ platform: this.name,
44
+ scope: message.scope,
45
+ conversationId: message.conversationId,
46
+ id: `sent-${this.sent.length}`,
47
+ timestamp: new Date()
48
+ };
49
+ }
50
+ async receive(content, options = {}) {
51
+ if (!this.onMessage) {
52
+ throw new Error("plugin test host is not started");
53
+ }
54
+ const author = {
55
+ id: options.authorId ?? "user-1",
56
+ role: options.role ?? "member",
57
+ ...(options.authorName ? { name: options.authorName } : {})
58
+ };
59
+ await this.onMessage({
60
+ id: options.id ?? `message-${this.nextMessageId++}`,
61
+ platform: options.platform ?? this.name,
62
+ scope: options.scope ?? "group",
63
+ conversationId: options.conversationId ?? "conversation-1",
64
+ author,
65
+ content,
66
+ attachments: structuredClone(options.attachments ?? []),
67
+ mentions: structuredClone(options.mentions ?? []),
68
+ ...(options.quote !== undefined
69
+ ? { quote: structuredClone(options.quote) }
70
+ : {}),
71
+ ...(options.botMentioned !== undefined
72
+ ? { botMentioned: options.botMentioned }
73
+ : {}),
74
+ timestamp: options.timestamp ? new Date(options.timestamp) : new Date(),
75
+ ...(options.raw !== undefined ? { raw: options.raw } : {})
76
+ });
77
+ }
78
+ async emit(event, payload) {
79
+ if (!this.onEvent) {
80
+ throw new Error("plugin test host is not started");
81
+ }
82
+ await this.onEvent(event, payload);
83
+ }
84
+ }
85
+ export class PluginTestHost {
86
+ adapter;
87
+ kernel;
88
+ sentCursor = 0;
89
+ constructor(options = {}) {
90
+ this.adapter = new TestAdapter(options.adapterCapabilities);
91
+ this.kernel = new BotKernel({
92
+ adapter: this.adapter,
93
+ logger: options.logger ?? new SilentLogger(),
94
+ ...(options.store ? { store: options.store } : {}),
95
+ ...(options.commandPrefix
96
+ ? { commandPrefix: options.commandPrefix }
97
+ : {}),
98
+ ...(options.ownerIds ? { ownerIds: options.ownerIds } : {}),
99
+ ...(options.accessPolicy ? { accessPolicy: options.accessPolicy } : {}),
100
+ ...(options.contextExtensions
101
+ ? { contextExtensions: options.contextExtensions }
102
+ : {})
103
+ });
104
+ }
105
+ load(plugin, options) {
106
+ return this.kernel.load(plugin, options);
107
+ }
108
+ unload(name) {
109
+ return this.kernel.unload(name);
110
+ }
111
+ start() {
112
+ return this.kernel.start();
113
+ }
114
+ stop() {
115
+ return this.kernel.stop();
116
+ }
117
+ async receive(content, options) {
118
+ await this.adapter.receive(content, options);
119
+ const messages = this.adapter.sent
120
+ .slice(this.sentCursor)
121
+ .map((message) => ({ ...message }));
122
+ this.sentCursor = this.adapter.sent.length;
123
+ return messages;
124
+ }
125
+ emit(event, payload) {
126
+ return this.adapter.emit(event, payload);
127
+ }
128
+ /**
129
+ * Messages sent since the last `receive` or `flush`. Use it after `emit`,
130
+ * which has no return value, to see what an event handler or a callback
131
+ * button handler sent.
132
+ */
133
+ flush() {
134
+ const messages = this.adapter.sent
135
+ .slice(this.sentCursor)
136
+ .map((message) => ({ ...message }));
137
+ this.sentCursor = this.adapter.sent.length;
138
+ return messages;
139
+ }
140
+ /** Prometheus text for kernel and plugin metrics. */
141
+ getMetricsText() {
142
+ return this.kernel.getMetricsText();
143
+ }
144
+ /** Settings defined by loaded plugins. */
145
+ get settings() {
146
+ return this.kernel.settings;
147
+ }
148
+ getHealth() {
149
+ return this.kernel.getHealth();
150
+ }
151
+ getNavigation() {
152
+ return this.kernel.getNavigation();
153
+ }
154
+ }
155
+ export function createPluginTestHost(options = {}) {
156
+ return new PluginTestHost(options);
157
+ }
158
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,wBAAwB,EACzB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAwD1C,MAAM,YAAY;IACT,KAAK,KAAU,CAAC;IAChB,IAAI,KAAU,CAAC;IACf,IAAI,KAAU,CAAC;IACf,KAAK,KAAU,CAAC;IAChB,KAAK;QACV,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAED,MAAM,WAAW;IACC,IAAI,GAAG,MAAM,CAAC;IACd,IAAI,GAAsB,EAAE,CAAC;IAC7B,MAAM,CAA2C;IACjD,SAAS,CAIN;IACH,iBAAiB,CAEL;IACpB,SAAS,CAEH;IACN,OAAO,CAKD;IACN,aAAa,GAAG,CAAC,CAAC;IAE1B,YACE,eAA6D,EAAE;QAE/D,IAAI,YAAY,CAAC,MAAM,EAAE,CAAC;YACxB,IAAI,CAAC,MAAM,GAAG,YAAY,CAAC,MAAM,CAAC;QACpC,CAAC;QACD,IAAI,YAAY,CAAC,SAAS,EAAE,CAAC;YAC3B,IAAI,CAAC,SAAS,GAAG,YAAY,CAAC,SAAS,CAAC;QAC1C,CAAC;QACD,IAAI,YAAY,CAAC,iBAAiB,EAAE,CAAC;YACnC,IAAI,CAAC,iBAAiB,GAAG,YAAY,CAAC,iBAAiB,CAAC;QAC1D,CAAC;IACH,CAAC;IAEM,KAAK,CAAC,KAAK,CAChB,SAAwD,EACxD,OAGoB;QAEpB,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAEM,KAAK,C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package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@umx-bot/plugin-testkit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.7.0",
4
+ "description": "In-memory integration test host for qq-bot plugins",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "files": [
9
+ "dist/**/*.js",
10
+ "dist/**/*.js.map",
11
+ "dist/**/*.d.ts",
12
+ "dist/**/*.d.ts.map",
13
+ "!dist/**/*.test.*",
14
+ "src/**/*.ts",
15
+ "!src/**/*.test.ts",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "engines": {
20
+ "node": ">=22"
21
+ },
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "peerDependencies": {
29
+ "@umx-bot/plugin-sdk": "^0.7.0"
30
+ },
31
+ "dependencies": {
32
+ "@umx-bot/core": "0.7.0"
33
+ },
34
+ "devDependencies": {
35
+ "@umx-bot/plugin-sdk": "0.7.0"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/Kningc/UMX-Bot.git",
40
+ "directory": "packages/plugin-testkit"
41
+ },
42
+ "homepage": "https://github.com/Kningc/UMX-Bot#readme",
43
+ "bugs": {
44
+ "url": "https://github.com/Kningc/UMX-Bot/issues"
45
+ },
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "scripts": {
50
+ "build": "tsc -p tsconfig.build.json",
51
+ "typecheck": "tsc -p tsconfig.json --noEmit"
52
+ }
6
53
  }
@@ -0,0 +1,259 @@
1
+ import type {
2
+ Awaitable,
3
+ BotAdapter,
4
+ BotEvents,
5
+ ChatScope,
6
+ IncomingMessage,
7
+ SentMessage
8
+ } from "@umx-bot/plugin-sdk";
9
+
10
+ export interface AdapterConformanceOptions {
11
+ /**
12
+ * Builds a fresh adapter. Called once per check, so a check can never be
13
+ * affected by state another check left behind.
14
+ */
15
+ createAdapter: () => Awaitable<BotAdapter>;
16
+ /**
17
+ * A conversation the adapter accepts. Defaults to a group conversation,
18
+ * which every adapter in this project supports.
19
+ */
20
+ conversation?: { scope: ChatScope; conversationId: string };
21
+ /** Skips the `send()` checks for an adapter that cannot send in tests. */
22
+ skipSend?: boolean;
23
+ }
24
+
25
+ export interface AdapterConformanceCheck {
26
+ name: string;
27
+ run: () => Promise<void>;
28
+ }
29
+
30
+ /**
31
+ * The `BotAdapter` contract, as executable checks.
32
+ *
33
+ * The framework claims to be platform-neutral, but that claim is only worth
34
+ * something if every adapter is held to the same behaviour. These checks cover
35
+ * the invariants the kernel and the application rely on, so a new adapter can
36
+ * be validated before it is wired into anything.
37
+ *
38
+ * Framework-agnostic on purpose: each check throws on failure, so it can be
39
+ * driven from `it()`, `test()` or a plain loop.
40
+ */
41
+ export function adapterConformanceChecks(
42
+ options: AdapterConformanceOptions
43
+ ): AdapterConformanceCheck[] {
44
+ const conversation = options.conversation ?? {
45
+ scope: "group" as ChatScope,
46
+ conversationId: "conformance-conversation"
47
+ };
48
+ const create = async (): Promise<BotAdapter> => options.createAdapter();
49
+ const noopHandlers = (): [
50
+ (message: IncomingMessage) => Awaitable<void>,
51
+ <K extends Exclude<keyof BotEvents, "message.created">>(
52
+ event: K,
53
+ payload: BotEvents[K]
54
+ ) => Awaitable<void>
55
+ ] => [() => undefined, () => undefined];
56
+
57
+ const checks: AdapterConformanceCheck[] = [
58
+ {
59
+ name: "exposes a stable lowercase name",
60
+ run: async () => {
61
+ const adapter = await create();
62
+ assert(
63
+ typeof adapter.name === "string" && adapter.name.length > 0,
64
+ "adapter.name must be a non-empty string"
65
+ );
66
+ assert(
67
+ adapter.name === adapter.name.toLowerCase(),
68
+ `adapter.name must be lowercase, got "${adapter.name}"`
69
+ );
70
+ assert(
71
+ !/\s/u.test(adapter.name),
72
+ `adapter.name must not contain whitespace, got "${adapter.name}"`
73
+ );
74
+ // The kernel reads `name` on every message, so it must not change.
75
+ const first = adapter.name;
76
+ await adapter.stop();
77
+ assert(
78
+ adapter.name === first,
79
+ "adapter.name must not change over the lifecycle"
80
+ );
81
+ }
82
+ },
83
+ {
84
+ name: "tolerates stop() before start()",
85
+ run: async () => {
86
+ const adapter = await create();
87
+ // The kernel calls stop() during a failed startup rollback, possibly
88
+ // before the adapter ever started.
89
+ await adapter.stop();
90
+ }
91
+ },
92
+ {
93
+ name: "tolerates a repeated stop()",
94
+ run: async () => {
95
+ const adapter = await create();
96
+ const [onMessage, onEvent] = noopHandlers();
97
+ await adapter.start(onMessage, onEvent);
98
+ await adapter.stop();
99
+ await adapter.stop();
100
+ }
101
+ },
102
+ {
103
+ name: "treats a repeated start() as idempotent",
104
+ run: async () => {
105
+ const adapter = await create();
106
+ const [onMessage, onEvent] = noopHandlers();
107
+ await adapter.start(onMessage, onEvent);
108
+ await adapter.start(onMessage, onEvent);
109
+ await adapter.stop();
110
+ }
111
+ },
112
+ {
113
+ name: "can be restarted after a stop()",
114
+ run: async () => {
115
+ const adapter = await create();
116
+ const [onMessage, onEvent] = noopHandlers();
117
+ await adapter.start(onMessage, onEvent);
118
+ await adapter.stop();
119
+ await adapter.start(onMessage, onEvent);
120
+ await adapter.stop();
121
+ }
122
+ },
123
+ {
124
+ name: "starts without an event handler",
125
+ run: async () => {
126
+ const adapter = await create();
127
+ // `onEvent` is optional in the contract; an adapter must not assume it.
128
+ await adapter.start(() => undefined);
129
+ await adapter.stop();
130
+ }
131
+ },
132
+ {
133
+ name: "reports JSON-serializable diagnostics",
134
+ run: async () => {
135
+ const adapter = await create();
136
+ if (!adapter.getDiagnostics) {
137
+ return;
138
+ }
139
+ const [onMessage, onEvent] = noopHandlers();
140
+ await adapter.start(onMessage, onEvent);
141
+ try {
142
+ const diagnostics = adapter.getDiagnostics();
143
+ assert(
144
+ diagnostics !== null && typeof diagnostics === "object",
145
+ "getDiagnostics() must return an object"
146
+ );
147
+ // The application writes diagnostics into its health snapshot, so a
148
+ // value that cannot be serialized breaks health checks in production.
149
+ const serialized = JSON.stringify(diagnostics);
150
+ assert(
151
+ typeof serialized === "string",
152
+ "getDiagnostics() must be JSON-serializable"
153
+ );
154
+ JSON.parse(serialized);
155
+ } finally {
156
+ await adapter.stop();
157
+ }
158
+ }
159
+ },
160
+ {
161
+ name: "keeps diagnostics callable before start()",
162
+ run: async () => {
163
+ const adapter = await create();
164
+ if (!adapter.getDiagnostics) {
165
+ return;
166
+ }
167
+ // The health snapshot is written before the kernel starts.
168
+ JSON.stringify(adapter.getDiagnostics());
169
+ await adapter.stop();
170
+ }
171
+ }
172
+ ];
173
+
174
+ if (!options.skipSend) {
175
+ checks.push(
176
+ {
177
+ name: "returns a usable receipt from send()",
178
+ run: async () => {
179
+ const adapter = await create();
180
+ const [onMessage, onEvent] = noopHandlers();
181
+ await adapter.start(onMessage, onEvent);
182
+ try {
183
+ const receipt = await adapter.send({
184
+ scope: conversation.scope,
185
+ conversationId: conversation.conversationId,
186
+ content: "conformance",
187
+ delivery: { type: "active", idempotencyKey: "conformance-1" }
188
+ });
189
+ assertReceipt(receipt, adapter.name, conversation);
190
+ } finally {
191
+ await adapter.stop();
192
+ }
193
+ }
194
+ },
195
+ {
196
+ name: "echoes the conversation of a passive reply",
197
+ run: async () => {
198
+ const adapter = await create();
199
+ const [onMessage, onEvent] = noopHandlers();
200
+ await adapter.start(onMessage, onEvent);
201
+ try {
202
+ const receipt = await adapter.send({
203
+ scope: conversation.scope,
204
+ conversationId: conversation.conversationId,
205
+ content: "conformance",
206
+ delivery: {
207
+ type: "passive",
208
+ target: { type: "message", messageId: "incoming-1" }
209
+ }
210
+ });
211
+ assertReceipt(receipt, adapter.name, conversation);
212
+ } finally {
213
+ await adapter.stop();
214
+ }
215
+ }
216
+ }
217
+ );
218
+ }
219
+
220
+ return checks;
221
+ }
222
+
223
+ function assertReceipt(
224
+ receipt: SentMessage,
225
+ platform: string,
226
+ conversation: { scope: ChatScope; conversationId: string }
227
+ ): void {
228
+ assert(
229
+ receipt !== null && typeof receipt === "object",
230
+ "send() must resolve with a SentMessage"
231
+ );
232
+ assert(
233
+ receipt.platform === platform,
234
+ `receipt.platform must be "${platform}", got "${receipt.platform}"`
235
+ );
236
+ assert(
237
+ receipt.scope === conversation.scope,
238
+ `receipt.scope must echo the request, got "${receipt.scope}"`
239
+ );
240
+ assert(
241
+ receipt.conversationId === conversation.conversationId,
242
+ "receipt.conversationId must echo the request"
243
+ );
244
+ assert(
245
+ typeof receipt.id === "string" && receipt.id.length > 0,
246
+ "receipt.id must be a non-empty string so the message can be recalled"
247
+ );
248
+ assert(
249
+ receipt.timestamp instanceof Date &&
250
+ Number.isFinite(receipt.timestamp.getTime()),
251
+ "receipt.timestamp must be a valid Date"
252
+ );
253
+ }
254
+
255
+ function assert(condition: boolean, message: string): void {
256
+ if (!condition) {
257
+ throw new Error(`adapter conformance: ${message}`);
258
+ }
259
+ }
package/src/index.ts ADDED
@@ -0,0 +1,274 @@
1
+ export {
2
+ type AdapterConformanceCheck,
3
+ type AdapterConformanceOptions,
4
+ adapterConformanceChecks
5
+ } from "./conformance.js";
6
+
7
+ import type { BotKernelOptions, PluginLoadOptions } from "@umx-bot/core";
8
+ import { BotKernel } from "@umx-bot/core";
9
+ import type {
10
+ Awaitable,
11
+ BotAdapter,
12
+ BotEvents,
13
+ BotPlugin,
14
+ ChatScope,
15
+ ConversationRef,
16
+ IncomingMessage,
17
+ KeyValueStore,
18
+ Logger,
19
+ MemberRole,
20
+ MessageStream,
21
+ MessageStreamOptions,
22
+ NavigationPageSummary,
23
+ OutgoingMessage,
24
+ ReplyTarget,
25
+ SentMessage
26
+ } from "@umx-bot/plugin-sdk";
27
+
28
+ export interface TestMessageOptions {
29
+ id?: string;
30
+ authorId?: string;
31
+ authorName?: string;
32
+ role?: MemberRole;
33
+ platform?: string;
34
+ scope?: ChatScope;
35
+ conversationId?: string;
36
+ attachments?: IncomingMessage["attachments"];
37
+ mentions?: IncomingMessage["mentions"];
38
+ quote?: IncomingMessage["quote"];
39
+ botMentioned?: boolean;
40
+ timestamp?: Date;
41
+ raw?: unknown;
42
+ }
43
+
44
+ export interface PluginTestHostOptions {
45
+ commandPrefix?: string;
46
+ ownerIds?: BotKernelOptions["ownerIds"];
47
+ accessPolicy?: BotKernelOptions["accessPolicy"];
48
+ contextExtensions?: BotKernelOptions["contextExtensions"];
49
+ logger?: Logger;
50
+ store?: KeyValueStore;
51
+ adapterCapabilities?: {
52
+ recall?: (message: SentMessage) => Promise<void>;
53
+ setTyping?: (
54
+ conversation: ConversationRef,
55
+ seconds: number,
56
+ target: ReplyTarget
57
+ ) => Promise<void>;
58
+ openMessageStream?: (
59
+ options: MessageStreamOptions
60
+ ) => Promise<MessageStream>;
61
+ };
62
+ }
63
+
64
+ class SilentLogger implements Logger {
65
+ public debug(): void {}
66
+ public info(): void {}
67
+ public warn(): void {}
68
+ public error(): void {}
69
+ public child(): Logger {
70
+ return this;
71
+ }
72
+ }
73
+
74
+ class TestAdapter implements BotAdapter {
75
+ public readonly name = "test";
76
+ public readonly sent: OutgoingMessage[] = [];
77
+ public readonly recall?: (message: SentMessage) => Promise<void>;
78
+ public readonly setTyping?: (
79
+ conversation: ConversationRef,
80
+ seconds: number,
81
+ target: ReplyTarget
82
+ ) => Promise<void>;
83
+ public readonly openMessageStream?: (
84
+ options: MessageStreamOptions
85
+ ) => Promise<MessageStream>;
86
+ private onMessage:
87
+ | ((message: IncomingMessage) => Awaitable<void>)
88
+ | undefined;
89
+ private onEvent:
90
+ | (<K extends Exclude<keyof BotEvents, "message.created">>(
91
+ event: K,
92
+ payload: BotEvents[K]
93
+ ) => Awaitable<void>)
94
+ | undefined;
95
+ private nextMessageId = 1;
96
+
97
+ public constructor(
98
+ capabilities: PluginTestHostOptions["adapterCapabilities"] = {}
99
+ ) {
100
+ if (capabilities.recall) {
101
+ this.recall = capabilities.recall;
102
+ }
103
+ if (capabilities.setTyping) {
104
+ this.setTyping = capabilities.setTyping;
105
+ }
106
+ if (capabilities.openMessageStream) {
107
+ this.openMessageStream = capabilities.openMessageStream;
108
+ }
109
+ }
110
+
111
+ public async start(
112
+ onMessage: (message: IncomingMessage) => Awaitable<void>,
113
+ onEvent?: <K extends Exclude<keyof BotEvents, "message.created">>(
114
+ event: K,
115
+ payload: BotEvents[K]
116
+ ) => Awaitable<void>
117
+ ): Promise<void> {
118
+ this.onMessage = onMessage;
119
+ this.onEvent = onEvent;
120
+ }
121
+
122
+ public async stop(): Promise<void> {
123
+ this.onMessage = undefined;
124
+ this.onEvent = undefined;
125
+ }
126
+
127
+ public async send(message: OutgoingMessage): Promise<SentMessage> {
128
+ this.sent.push(message);
129
+ return {
130
+ platform: this.name,
131
+ scope: message.scope,
132
+ conversationId: message.conversationId,
133
+ id: `sent-${this.sent.length}`,
134
+ timestamp: new Date()
135
+ };
136
+ }
137
+
138
+ public async receive(
139
+ content: string,
140
+ options: TestMessageOptions = {}
141
+ ): Promise<void> {
142
+ if (!this.onMessage) {
143
+ throw new Error("plugin test host is not started");
144
+ }
145
+ const author: IncomingMessage["author"] = {
146
+ id: options.authorId ?? "user-1",
147
+ role: options.role ?? "member",
148
+ ...(options.authorName ? { name: options.authorName } : {})
149
+ };
150
+ await this.onMessage({
151
+ id: options.id ?? `message-${this.nextMessageId++}`,
152
+ platform: options.platform ?? this.name,
153
+ scope: options.scope ?? "group",
154
+ conversationId: options.conversationId ?? "conversation-1",
155
+ author,
156
+ content,
157
+ attachments: structuredClone(options.attachments ?? []),
158
+ mentions: structuredClone(options.mentions ?? []),
159
+ ...(options.quote !== undefined
160
+ ? { quote: structuredClone(options.quote) }
161
+ : {}),
162
+ ...(options.botMentioned !== undefined
163
+ ? { botMentioned: options.botMentioned }
164
+ : {}),
165
+ timestamp: options.timestamp ? new Date(options.timestamp) : new Date(),
166
+ ...(options.raw !== undefined ? { raw: options.raw } : {})
167
+ });
168
+ }
169
+
170
+ public async emit<K extends Exclude<keyof BotEvents, "message.created">>(
171
+ event: K,
172
+ payload: BotEvents[K]
173
+ ): Promise<void> {
174
+ if (!this.onEvent) {
175
+ throw new Error("plugin test host is not started");
176
+ }
177
+ await this.onEvent(event, payload);
178
+ }
179
+ }
180
+
181
+ export class PluginTestHost {
182
+ private readonly adapter: TestAdapter;
183
+ private readonly kernel: BotKernel;
184
+ private sentCursor = 0;
185
+
186
+ public constructor(options: PluginTestHostOptions = {}) {
187
+ this.adapter = new TestAdapter(options.adapterCapabilities);
188
+ this.kernel = new BotKernel({
189
+ adapter: this.adapter,
190
+ logger: options.logger ?? new SilentLogger(),
191
+ ...(options.store ? { store: options.store } : {}),
192
+ ...(options.commandPrefix
193
+ ? { commandPrefix: options.commandPrefix }
194
+ : {}),
195
+ ...(options.ownerIds ? { ownerIds: options.ownerIds } : {}),
196
+ ...(options.accessPolicy ? { accessPolicy: options.accessPolicy } : {}),
197
+ ...(options.contextExtensions
198
+ ? { contextExtensions: options.contextExtensions }
199
+ : {})
200
+ });
201
+ }
202
+
203
+ public load(plugin: BotPlugin, options?: PluginLoadOptions): Promise<void> {
204
+ return this.kernel.load(plugin, options);
205
+ }
206
+
207
+ public unload(name: string): Promise<boolean> {
208
+ return this.kernel.unload(name);
209
+ }
210
+
211
+ public start(): Promise<void> {
212
+ return this.kernel.start();
213
+ }
214
+
215
+ public stop(): Promise<void> {
216
+ return this.kernel.stop();
217
+ }
218
+
219
+ public async receive(
220
+ content: string,
221
+ options?: TestMessageOptions
222
+ ): Promise<OutgoingMessage[]> {
223
+ await this.adapter.receive(content, options);
224
+ const messages = this.adapter.sent
225
+ .slice(this.sentCursor)
226
+ .map((message) => ({ ...message }));
227
+ this.sentCursor = this.adapter.sent.length;
228
+ return messages;
229
+ }
230
+
231
+ public emit<K extends Exclude<keyof BotEvents, "message.created">>(
232
+ event: K,
233
+ payload: BotEvents[K]
234
+ ): Promise<void> {
235
+ return this.adapter.emit(event, payload);
236
+ }
237
+
238
+ /**
239
+ * Messages sent since the last `receive` or `flush`. Use it after `emit`,
240
+ * which has no return value, to see what an event handler or a callback
241
+ * button handler sent.
242
+ */
243
+ public flush(): OutgoingMessage[] {
244
+ const messages = this.adapter.sent
245
+ .slice(this.sentCursor)
246
+ .map((message) => ({ ...message }));
247
+ this.sentCursor = this.adapter.sent.length;
248
+ return messages;
249
+ }
250
+
251
+ /** Prometheus text for kernel and plugin metrics. */
252
+ public getMetricsText(): string {
253
+ return this.kernel.getMetricsText();
254
+ }
255
+
256
+ /** Settings defined by loaded plugins. */
257
+ public get settings(): BotKernel["settings"] {
258
+ return this.kernel.settings;
259
+ }
260
+
261
+ public getHealth() {
262
+ return this.kernel.getHealth();
263
+ }
264
+
265
+ public getNavigation(): NavigationPageSummary[] {
266
+ return this.kernel.getNavigation();
267
+ }
268
+ }
269
+
270
+ export function createPluginTestHost(
271
+ options: PluginTestHostOptions = {}
272
+ ): PluginTestHost {
273
+ return new PluginTestHost(options);
274
+ }