@axiom-lattice/client-sdk 8.0.0 → 8.0.2

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.
@@ -0,0 +1,785 @@
1
+ import { WeChatClient } from "../wechat-client";
2
+ import { ApiError, AuthenticationError, NetworkError } from "../types";
3
+ let requests;
4
+ let chunkHandlers;
5
+ let tasks;
6
+ function installWx() {
7
+ global.wx = {
8
+ request: (options) => {
9
+ requests.push(options);
10
+ const task = {
11
+ onChunkReceived: jest.fn((handler) => {
12
+ chunkHandlers.push(handler);
13
+ }),
14
+ abort: jest.fn(),
15
+ };
16
+ tasks.push(task);
17
+ return task;
18
+ },
19
+ };
20
+ }
21
+ function chunk(text) {
22
+ const bytes = new TextEncoder().encode(text);
23
+ return {
24
+ data: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
25
+ };
26
+ }
27
+ function chunkAt(text, index) {
28
+ const bytes = new TextEncoder().encode(text);
29
+ return [chunkBytes(bytes.slice(0, index)), chunkBytes(bytes.slice(index))];
30
+ }
31
+ function chunkBytes(bytes) {
32
+ return {
33
+ data: bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
34
+ };
35
+ }
36
+ function flush() {
37
+ return new Promise((resolve) => setTimeout(resolve, 0));
38
+ }
39
+ const baseConfig = {
40
+ baseURL: "https://api.test",
41
+ apiKey: "key-1",
42
+ assistantId: "asst-1",
43
+ transport: "sse",
44
+ };
45
+ function makeClient(overrides = {}) {
46
+ return new WeChatClient({ ...baseConfig, ...overrides });
47
+ }
48
+ beforeEach(() => {
49
+ requests = [];
50
+ chunkHandlers = [];
51
+ tasks = [];
52
+ installWx();
53
+ });
54
+ afterEach(() => {
55
+ global.wx = undefined;
56
+ });
57
+ describe("WeChatClient constructor", () => {
58
+ it("defaults timeout to 300000", async () => {
59
+ const client = makeClient();
60
+ const pending = client.request("/api/thing");
61
+ requests[0].success({ statusCode: 200, data: { ok: true } });
62
+ await expect(pending).resolves.toEqual({ ok: true });
63
+ expect(requests[0].timeout).toBe(300000);
64
+ });
65
+ it("keeps a custom timeout", async () => {
66
+ const client = makeClient({ timeout: 4321 });
67
+ const pending = client.request("/api/thing");
68
+ requests[0].success({ statusCode: 200, data: null });
69
+ await pending;
70
+ expect(requests[0].timeout).toBe(4321);
71
+ });
72
+ });
73
+ describe("WeChatClient tenant and workspace context", () => {
74
+ it("setTenantId adds x-tenant-id to requests", async () => {
75
+ const client = makeClient();
76
+ client.setTenantId("tenant-1");
77
+ const pending = client.request("/api/thing");
78
+ requests[0].success({ statusCode: 200, data: {} });
79
+ await pending;
80
+ expect(requests[0].header["x-tenant-id"]).toBe("tenant-1");
81
+ });
82
+ it("sets, leaves unchanged, and clears workspace/project headers", () => {
83
+ const client = makeClient();
84
+ client.setWorkspaceContext("ws-1", "pj-1");
85
+ expect(client.getWorkspaceHeaders()).toEqual({
86
+ "x-workspace-id": "ws-1",
87
+ "x-project-id": "pj-1",
88
+ });
89
+ client.setWorkspaceContext(undefined, "pj-2");
90
+ expect(client.getWorkspaceHeaders()).toEqual({
91
+ "x-workspace-id": "ws-1",
92
+ "x-project-id": "pj-2",
93
+ });
94
+ client.setWorkspaceContext("ws-2");
95
+ expect(client.getWorkspaceHeaders()).toEqual({
96
+ "x-workspace-id": "ws-2",
97
+ "x-project-id": "pj-2",
98
+ });
99
+ client.setWorkspaceContext("", "");
100
+ expect(client.getWorkspaceHeaders()).toEqual({});
101
+ });
102
+ it("returns a copy from getWorkspaceHeaders", () => {
103
+ const client = makeClient();
104
+ client.setWorkspaceContext("ws-1", "pj-1");
105
+ const headers = client.getWorkspaceHeaders();
106
+ headers["x-workspace-id"] = "tampered";
107
+ headers["x-extra"] = "nope";
108
+ expect(client.getWorkspaceHeaders()).toEqual({
109
+ "x-workspace-id": "ws-1",
110
+ "x-project-id": "pj-1",
111
+ });
112
+ });
113
+ });
114
+ describe("WeChatClient makeRequest", () => {
115
+ it("joins baseURL + path, defaults to GET, and forwards body", async () => {
116
+ const client = makeClient();
117
+ const pending = client.request("/api/things", {
118
+ body: { name: "thing" },
119
+ });
120
+ requests[0].success({ statusCode: 200, data: { id: "t-1" } });
121
+ await expect(pending).resolves.toEqual({ id: "t-1" });
122
+ expect(requests[0].url).toBe("https://api.test/api/things");
123
+ expect(requests[0].method).toBe("GET");
124
+ expect(requests[0].data).toEqual({ name: "thing" });
125
+ });
126
+ it("forwards an explicit method and the standard headers", async () => {
127
+ const client = makeClient({ headers: { "x-config": "cfg" } });
128
+ client.setTenantId("tenant-1");
129
+ client.setWorkspaceContext("ws-1", "pj-1");
130
+ const pending = client.request("/api/things", { method: "POST" });
131
+ requests[0].success({ statusCode: 200, data: {} });
132
+ await pending;
133
+ expect(requests[0].method).toBe("POST");
134
+ expect(requests[0].header).toMatchObject({
135
+ "Content-Type": "application/json",
136
+ Authorization: "Bearer key-1",
137
+ "x-config": "cfg",
138
+ "x-tenant-id": "tenant-1",
139
+ "x-workspace-id": "ws-1",
140
+ "x-project-id": "pj-1",
141
+ });
142
+ });
143
+ it("forwards per-request headers", async () => {
144
+ const client = makeClient();
145
+ const pending = client.request("/api/things", {
146
+ headers: { "x-axiom-affinity": "thread-1" },
147
+ });
148
+ requests[0].success({ statusCode: 200, data: {} });
149
+ await pending;
150
+ expect(requests[0].header["x-axiom-affinity"]).toBe("thread-1");
151
+ });
152
+ it("lets workspace context override config headers", async () => {
153
+ const client = makeClient({
154
+ headers: { "x-workspace-id": "config-ws", "x-project-id": "config-pj" },
155
+ });
156
+ client.setWorkspaceContext("instance-ws", "instance-pj");
157
+ const pending = client.request("/api/things");
158
+ requests[0].success({ statusCode: 200, data: {} });
159
+ await pending;
160
+ expect(requests[0].header["x-workspace-id"]).toBe("instance-ws");
161
+ expect(requests[0].header["x-project-id"]).toBe("instance-pj");
162
+ });
163
+ it("lets per-request headers win over config and workspace headers", async () => {
164
+ const client = makeClient({ headers: { "x-shared": "config", "x-keep": "config" } });
165
+ client.setWorkspaceContext("instance-ws", "instance-pj");
166
+ const pending = client.request("/api/things", {
167
+ headers: { "x-shared": "request", "x-workspace-id": "request-ws" },
168
+ });
169
+ requests[0].success({ statusCode: 200, data: {} });
170
+ await pending;
171
+ expect(requests[0].header["x-shared"]).toBe("request");
172
+ expect(requests[0].header["x-workspace-id"]).toBe("request-ws");
173
+ expect(requests[0].header["x-project-id"]).toBe("instance-pj");
174
+ expect(requests[0].header["x-keep"]).toBe("config");
175
+ });
176
+ it("omits Content-Type on a bodyless DELETE", async () => {
177
+ const client = makeClient({ headers: { "Content-Type": "application/json" } });
178
+ const pending = client.request("/api/things/1", { method: "DELETE" });
179
+ requests[0].success({ statusCode: 204, data: undefined });
180
+ await pending;
181
+ expect(requests[0].header["Content-Type"]).toBeUndefined();
182
+ });
183
+ it("keeps Content-Type on a DELETE with a body", async () => {
184
+ const client = makeClient();
185
+ const pending = client.request("/api/things/1", {
186
+ method: "DELETE",
187
+ body: { reason: "cleanup" },
188
+ });
189
+ requests[0].success({ statusCode: 204, data: undefined });
190
+ await pending;
191
+ expect(requests[0].header["Content-Type"]).toBe("application/json");
192
+ });
193
+ it("delegates through the public request<T> method", async () => {
194
+ const client = makeClient();
195
+ const pending = client.request("/api/value");
196
+ requests[0].success({ statusCode: 200, data: 42 });
197
+ await expect(pending).resolves.toBe(42);
198
+ });
199
+ });
200
+ describe("WeChatClient wechatRequest status handling", () => {
201
+ it("resolves 2xx responses", async () => {
202
+ const client = makeClient();
203
+ const pending = client.request("/api/ok");
204
+ requests[0].success({ statusCode: 204, data: undefined });
205
+ await expect(pending).resolves.toBeUndefined();
206
+ });
207
+ it("rejects 401 with AuthenticationError and the server message", async () => {
208
+ const client = makeClient();
209
+ const pending = client.request("/api/secure");
210
+ requests[0].success({ statusCode: 401, data: { message: "bad token" } });
211
+ await expect(pending).rejects.toMatchObject({
212
+ name: "AuthenticationError",
213
+ message: "bad token",
214
+ });
215
+ await expect(pending).rejects.toBeInstanceOf(AuthenticationError);
216
+ });
217
+ it("falls back to a default 401 message", async () => {
218
+ const client = makeClient();
219
+ const pending = client.request("/api/secure");
220
+ requests[0].success({ statusCode: 401, data: {} });
221
+ await expect(pending).rejects.toThrow("Authentication failed");
222
+ });
223
+ it("rejects other non-2xx responses with ApiError message/status/body", async () => {
224
+ const client = makeClient();
225
+ const pending = client.request("/api/broken");
226
+ const body = { message: "server exploded", code: "BOOM" };
227
+ requests[0].success({ statusCode: 500, data: body });
228
+ const error = await pending.catch((err) => err);
229
+ expect(error).toBeInstanceOf(ApiError);
230
+ expect(error).toMatchObject({
231
+ name: "ApiError",
232
+ message: "server exploded",
233
+ statusCode: 500,
234
+ responseBody: body,
235
+ });
236
+ });
237
+ it("falls back to a default non-401 API error message", async () => {
238
+ const client = makeClient();
239
+ const pending = client.request("/api/broken");
240
+ requests[0].success({ statusCode: 500, data: null });
241
+ await expect(pending).rejects.toThrow("API Error");
242
+ });
243
+ it("rejects transport failures with NetworkError", async () => {
244
+ const client = makeClient();
245
+ const pending = client.request("/api/offline");
246
+ requests[0].fail({ errMsg: "request:fail timeout" });
247
+ await expect(pending).rejects.toMatchObject({
248
+ name: "NetworkError",
249
+ message: "Request failed: request:fail timeout",
250
+ });
251
+ await expect(pending).rejects.toBeInstanceOf(NetworkError);
252
+ });
253
+ it.each([
254
+ ["error field", { success: false, error: "boom error" }, "boom error"],
255
+ ["message field", { message: "boom message" }, "boom message"],
256
+ ["json string", JSON.stringify({ error: "json error" }), "json error"],
257
+ ["plain text", " plain failure ", "plain failure"],
258
+ ])("extracts %s from a non-2xx response body", async (_label, data, message) => {
259
+ const client = makeClient();
260
+ const pending = client.request("/api/broken");
261
+ requests[0].success({ statusCode: 400, data });
262
+ const error = await pending.catch((err) => err);
263
+ expect(error).toBeInstanceOf(ApiError);
264
+ expect(error).toMatchObject({ message, statusCode: 400 });
265
+ });
266
+ it("uses the error field for 401 responses", async () => {
267
+ const client = makeClient();
268
+ const pending = client.request("/api/secure");
269
+ requests[0].success({ statusCode: 401, data: { error: "token expired" } });
270
+ await expect(pending).rejects.toMatchObject({
271
+ name: "AuthenticationError",
272
+ message: "token expired",
273
+ });
274
+ });
275
+ it("rejects with a descriptive error when the global wx object is missing", async () => {
276
+ const client = makeClient();
277
+ global.wx = undefined;
278
+ await expect(client.request("/api/thing")).rejects.toThrow(/wx\.request.*is not available/);
279
+ });
280
+ it("rejects with a descriptive error when wx.request is missing", async () => {
281
+ const client = makeClient();
282
+ global.wx = {};
283
+ await expect(client.request("/api/thing")).rejects.toThrow(/wx\.request.*is not available/);
284
+ });
285
+ });
286
+ describe("WeChatClient clone", () => {
287
+ it("creates a new WeChatClient with overrides", () => {
288
+ const client = makeClient();
289
+ const cloned = client.clone({ assistantId: "asst-2" });
290
+ expect(cloned).toBeInstanceOf(WeChatClient);
291
+ expect(cloned).not.toBe(client);
292
+ expect(cloned.assistantId).toBe("asst-2");
293
+ });
294
+ it("copies the tenant id", () => {
295
+ const client = makeClient();
296
+ client.setTenantId("tenant-1");
297
+ expect(client.clone().tenantId).toBe("tenant-1");
298
+ });
299
+ it("shares workspace headers with the parent in both directions", () => {
300
+ const client = makeClient();
301
+ client.setWorkspaceContext("ws-1", "pj-1");
302
+ const cloned = client.clone();
303
+ expect(cloned.getWorkspaceHeaders()).toEqual({
304
+ "x-workspace-id": "ws-1",
305
+ "x-project-id": "pj-1",
306
+ });
307
+ cloned.setWorkspaceContext("ws-2");
308
+ expect(client.getWorkspaceHeaders()["x-workspace-id"]).toBe("ws-2");
309
+ client.setWorkspaceContext(undefined, "pj-3");
310
+ expect(cloned.getWorkspaceHeaders()["x-project-id"]).toBe("pj-3");
311
+ });
312
+ });
313
+ describe("WeChatClient resumeStream", () => {
314
+ const resumeOptions = {
315
+ assistantId: "asst-1",
316
+ threadId: "thread-1",
317
+ messageId: "msg-1",
318
+ knownContent: "hello",
319
+ };
320
+ it("posts to /api/resume_stream with headers, body, and affinity", () => {
321
+ const client = makeClient({ headers: { "x-config": "cfg" } });
322
+ client.setTenantId("tenant-1");
323
+ client.setWorkspaceContext("ws-1", "pj-1");
324
+ client.resumeStream(resumeOptions, jest.fn());
325
+ const request = requests[0];
326
+ expect(request.url).toBe("https://api.test/api/resume_stream");
327
+ expect(request.method).toBe("POST");
328
+ expect(request.data).toEqual({
329
+ assistant_id: "asst-1",
330
+ thread_id: "thread-1",
331
+ message_id: "msg-1",
332
+ known_content: "hello",
333
+ poll_interval: 100,
334
+ });
335
+ expect(request.responseType).toBe("text");
336
+ expect(request.enableChunked).toBe(true);
337
+ expect(request.header).toMatchObject({
338
+ "Content-Type": "application/json",
339
+ Authorization: "Bearer key-1",
340
+ Accept: "text/event-stream",
341
+ "x-config": "cfg",
342
+ "x-tenant-id": "tenant-1",
343
+ "x-workspace-id": "ws-1",
344
+ "x-project-id": "pj-1",
345
+ "x-axiom-affinity": "thread-1",
346
+ });
347
+ expect(request.header["Last-Event-ID"]).toBeUndefined();
348
+ });
349
+ it("honors a custom poll interval", () => {
350
+ const client = makeClient();
351
+ client.resumeStream({ ...resumeOptions, pollInterval: 250 }, jest.fn());
352
+ expect(requests[0].data.poll_interval).toBe(250);
353
+ });
354
+ it("sends a trimmed Last-Event-ID when provided", () => {
355
+ const client = makeClient();
356
+ client.resumeStream({ ...resumeOptions, lastEventId: " event-42 " }, jest.fn());
357
+ expect(requests[0].header["Last-Event-ID"]).toBe("event-42");
358
+ });
359
+ it("omits Last-Event-ID when it is absent or whitespace only", () => {
360
+ const client = makeClient();
361
+ client.resumeStream({ ...resumeOptions, lastEventId: " " }, jest.fn());
362
+ expect(requests[0].header["Last-Event-ID"]).toBeUndefined();
363
+ });
364
+ it("parses every data: line across multiple SSE lines", () => {
365
+ const client = makeClient();
366
+ const onEvent = jest.fn();
367
+ const onError = jest.fn();
368
+ client.resumeStream(resumeOptions, onEvent, undefined, onError);
369
+ chunkHandlers[0](chunk('event: ping\ndata: {"type":"ai","n":1}\n data: {"type":"ai","n":2}\n'));
370
+ expect(onEvent).toHaveBeenNthCalledWith(1, { type: "ai", n: 1 });
371
+ expect(onEvent).toHaveBeenNthCalledWith(2, { type: "ai", n: 2 });
372
+ expect(onError).not.toHaveBeenCalled();
373
+ });
374
+ it("ignores lines that are not data: frames and empty chunks", () => {
375
+ const client = makeClient();
376
+ const onEvent = jest.fn();
377
+ client.resumeStream(resumeOptions, onEvent);
378
+ chunkHandlers[0]({ data: new ArrayBuffer(0) });
379
+ chunkHandlers[0]({ data: undefined });
380
+ chunkHandlers[0](chunk('event: ping\nid: 1\n: comment\ndata : nope\n'));
381
+ expect(onEvent).not.toHaveBeenCalled();
382
+ });
383
+ it("accepts data: frames without a space", () => {
384
+ const client = makeClient();
385
+ const onEvent = jest.fn();
386
+ client.resumeStream(resumeOptions, onEvent);
387
+ chunkHandlers[0](chunk('data:{"type":"ai","n":1}\n'));
388
+ expect(onEvent).toHaveBeenCalledWith({ type: "ai", n: 1 });
389
+ });
390
+ it("buffers a JSON frame split mid-string across chunks", () => {
391
+ const client = makeClient();
392
+ const onEvent = jest.fn();
393
+ const onError = jest.fn();
394
+ client.resumeStream(resumeOptions, onEvent, undefined, onError);
395
+ const frame = 'data: {"type":"ai","data":{"content":"hello world"}}\n';
396
+ const [first, second] = chunkAt(frame, frame.indexOf("hello") + 3);
397
+ chunkHandlers[0](first);
398
+ expect(onEvent).not.toHaveBeenCalled();
399
+ chunkHandlers[0](second);
400
+ expect(onEvent).toHaveBeenCalledWith({
401
+ type: "ai",
402
+ data: { content: "hello world" },
403
+ });
404
+ expect(onError).not.toHaveBeenCalled();
405
+ });
406
+ it("keeps a trailing partial line until the next chunk completes it", () => {
407
+ const client = makeClient();
408
+ const onEvent = jest.fn();
409
+ client.resumeStream(resumeOptions, onEvent);
410
+ chunkHandlers[0](chunk('data: {"n":1}\ndata: {"n":'));
411
+ expect(onEvent).toHaveBeenCalledTimes(1);
412
+ expect(onEvent).toHaveBeenCalledWith({ n: 1 });
413
+ chunkHandlers[0](chunk('2}\n'));
414
+ expect(onEvent).toHaveBeenNthCalledWith(2, { n: 2 });
415
+ });
416
+ it("decodes a multibyte character split across chunks", () => {
417
+ const client = makeClient();
418
+ const onEvent = jest.fn();
419
+ client.resumeStream(resumeOptions, onEvent);
420
+ const frame = 'data: {"type":"ai","data":{"content":"你好"}}\n';
421
+ const [first, second] = chunkAt(frame, frame.indexOf("你") + 1);
422
+ chunkHandlers[0](first);
423
+ expect(onEvent).not.toHaveBeenCalled();
424
+ chunkHandlers[0](second);
425
+ expect(onEvent).toHaveBeenCalledWith({
426
+ type: "ai",
427
+ data: { content: "你好" },
428
+ });
429
+ });
430
+ it.each([
431
+ { status: 400, name: "ApiError", message: "bad request" },
432
+ { status: 401, name: "AuthenticationError", message: "expired" },
433
+ { status: 500, name: "ApiError", message: "boom" },
434
+ ])("reports stream status $status without chunks or completion", ({ status, name, message }) => {
435
+ const client = makeClient();
436
+ const onEvent = jest.fn();
437
+ const onComplete = jest.fn();
438
+ const onError = jest.fn();
439
+ client.resumeStream(resumeOptions, onEvent, onComplete, onError);
440
+ requests[0].success({ statusCode: status, data: { message } });
441
+ chunkHandlers[0](chunk('data: {"type":"ai"}\n'));
442
+ requests[0].complete?.();
443
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ name, message }));
444
+ expect(onEvent).not.toHaveBeenCalled();
445
+ expect(onComplete).not.toHaveBeenCalled();
446
+ });
447
+ it.each([
448
+ ["object message", { message: "object message" }],
449
+ ["object error", { error: "object error" }],
450
+ ["json message", JSON.stringify({ message: "json message" })],
451
+ ["json error", JSON.stringify({ error: "json error" })],
452
+ ["bad gateway", " bad gateway "],
453
+ ])("extracts %s from a text error body", (expected, data) => {
454
+ const client = makeClient();
455
+ const onError = jest.fn();
456
+ client.resumeStream(resumeOptions, jest.fn(), jest.fn(), onError);
457
+ requests[0].success({ statusCode: 500, data });
458
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: expected }));
459
+ });
460
+ it("falls back to status text for empty error bodies", () => {
461
+ const unauthorized = makeClient();
462
+ const unauthorizedError = jest.fn();
463
+ unauthorized.resumeStream(resumeOptions, jest.fn(), jest.fn(), unauthorizedError);
464
+ requests[0].success({ statusCode: 401, data: undefined });
465
+ expect(unauthorizedError).toHaveBeenCalledWith(expect.objectContaining({ name: "AuthenticationError", message: "Authentication failed" }));
466
+ requests.length = 0;
467
+ const broken = makeClient();
468
+ const brokenError = jest.fn();
469
+ broken.resumeStream(resumeOptions, jest.fn(), jest.fn(), brokenError);
470
+ requests[0].success({ statusCode: 502, data: "" });
471
+ expect(brokenError).toHaveBeenCalledWith(expect.objectContaining({
472
+ name: "ApiError",
473
+ message: "HTTP error! Status: 502",
474
+ statusCode: 502,
475
+ }));
476
+ requests.length = 0;
477
+ const unmessaged = makeClient();
478
+ const unmessagedError = jest.fn();
479
+ unmessaged.resumeStream(resumeOptions, jest.fn(), jest.fn(), unmessagedError);
480
+ requests[0].success({ statusCode: 500, data: JSON.stringify({ code: "NOPE" }) });
481
+ expect(unmessagedError).toHaveBeenCalledWith(expect.objectContaining({
482
+ name: "ApiError",
483
+ message: "HTTP error! Status: 500",
484
+ statusCode: 500,
485
+ }));
486
+ });
487
+ it("reports invalid JSON through onError and continues", () => {
488
+ const client = makeClient();
489
+ const onEvent = jest.fn();
490
+ const onError = jest.fn();
491
+ client.resumeStream(resumeOptions, onEvent, undefined, onError);
492
+ chunkHandlers[0](chunk('data: {not json}\ndata: {"ok":true}\n'));
493
+ expect(onError).toHaveBeenCalledTimes(1);
494
+ expect(onError.mock.calls[0][0]).toBeInstanceOf(Error);
495
+ expect(onEvent).toHaveBeenCalledWith({ ok: true });
496
+ });
497
+ it("does not throw on invalid JSON when no onError is provided", () => {
498
+ const client = makeClient();
499
+ client.resumeStream(resumeOptions, jest.fn());
500
+ expect(() => chunkHandlers[0](chunk("data: {bad}\n"))).not.toThrow();
501
+ });
502
+ it("wraps non-Error parse failures in an Error", () => {
503
+ const client = makeClient();
504
+ const onError = jest.fn();
505
+ client.resumeStream(resumeOptions, jest.fn(), undefined, onError);
506
+ const parse = jest.spyOn(JSON, "parse").mockImplementationOnce(() => {
507
+ throw "raw failure";
508
+ });
509
+ try {
510
+ chunkHandlers[0](chunk("data: anything\n"));
511
+ }
512
+ finally {
513
+ parse.mockRestore();
514
+ }
515
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "raw failure" }));
516
+ });
517
+ it("reports transport failure through onError", () => {
518
+ const client = makeClient();
519
+ const onError = jest.fn();
520
+ client.resumeStream(resumeOptions, jest.fn(), undefined, onError);
521
+ requests[0].fail({ errMsg: "disconnected" });
522
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "Resume stream request failed: disconnected" }));
523
+ });
524
+ it("does not throw on transport failure when no onError is provided", () => {
525
+ const client = makeClient();
526
+ client.resumeStream(resumeOptions, jest.fn());
527
+ expect(() => requests[0].fail({ errMsg: "disconnected" })).not.toThrow();
528
+ });
529
+ it("calls onComplete when the request completes", () => {
530
+ const client = makeClient();
531
+ const onComplete = jest.fn();
532
+ client.resumeStream(resumeOptions, jest.fn(), onComplete);
533
+ requests[0].success({ statusCode: 200 });
534
+ requests[0].complete?.();
535
+ expect(onComplete).toHaveBeenCalledTimes(1);
536
+ });
537
+ it("flushes a final data: line without a trailing newline on complete", () => {
538
+ const client = makeClient();
539
+ const onEvent = jest.fn();
540
+ client.resumeStream(resumeOptions, onEvent);
541
+ chunkHandlers[0](chunk('data: {"type":"final"}'));
542
+ expect(onEvent).not.toHaveBeenCalled();
543
+ requests[0].complete?.();
544
+ expect(onEvent).toHaveBeenCalledWith({ type: "final" });
545
+ });
546
+ it("does not call onComplete after a transport failure", () => {
547
+ const client = makeClient();
548
+ const onComplete = jest.fn();
549
+ const onError = jest.fn();
550
+ client.resumeStream(resumeOptions, jest.fn(), onComplete, onError);
551
+ requests[0].fail({ errMsg: "disconnected" });
552
+ requests[0].complete?.();
553
+ expect(onError).toHaveBeenCalledTimes(1);
554
+ expect(onComplete).not.toHaveBeenCalled();
555
+ });
556
+ it("returns an abort function backed by RequestTask.abort", () => {
557
+ const client = makeClient();
558
+ const stop = client.resumeStream(resumeOptions, jest.fn());
559
+ stop();
560
+ expect(tasks[0].abort).toHaveBeenCalledTimes(1);
561
+ });
562
+ it("suppresses onError and onComplete after an abort", () => {
563
+ const client = makeClient();
564
+ const onComplete = jest.fn();
565
+ const onError = jest.fn();
566
+ const stop = client.resumeStream(resumeOptions, jest.fn(), onComplete, onError);
567
+ stop();
568
+ requests[0].fail({ errMsg: "request:fail abort" });
569
+ requests[0].complete?.();
570
+ expect(onError).not.toHaveBeenCalled();
571
+ expect(onComplete).not.toHaveBeenCalled();
572
+ });
573
+ it.each([400, 0])("ignores a late resume success status %s after an abort", (statusCode) => {
574
+ const client = makeClient();
575
+ const onError = jest.fn();
576
+ const onComplete = jest.fn();
577
+ const stop = client.resumeStream(resumeOptions, jest.fn(), onComplete, onError);
578
+ stop();
579
+ requests[0].success({ statusCode, data: { message: "aborted" } });
580
+ requests[0].complete?.();
581
+ expect(onError).not.toHaveBeenCalled();
582
+ expect(onComplete).not.toHaveBeenCalled();
583
+ });
584
+ it("throws synchronously with a descriptive error when wx is missing", () => {
585
+ const client = makeClient();
586
+ global.wx = undefined;
587
+ expect(() => client.resumeStream(resumeOptions, jest.fn())).toThrow(/wx\.request.*is not available/);
588
+ });
589
+ });
590
+ describe("WeChatClient chat.stream (streamRequest/streamRun)", () => {
591
+ const streamOptions = {
592
+ assistantId: "asst-1",
593
+ threadId: "thread-stream",
594
+ messages: [{ id: "msg-1", role: "user", content: "你好" }],
595
+ };
596
+ it("posts the built run body with headers and affinity", () => {
597
+ const client = makeClient({ headers: { "x-config": "cfg" } });
598
+ client.setTenantId("tenant-1");
599
+ client.setWorkspaceContext("ws-1", "pj-1");
600
+ client.chat.stream(streamOptions, jest.fn());
601
+ const request = requests[0];
602
+ expect(request.url).toBe("https://api.test/api/runs");
603
+ expect(request.method).toBe("POST");
604
+ expect(request.data).toMatchObject({
605
+ assistant_id: "asst-1",
606
+ thread_id: "thread-stream",
607
+ message: "你好",
608
+ message_id: "msg-1",
609
+ streaming: true,
610
+ background: false,
611
+ });
612
+ expect(request.responseType).toBe("text");
613
+ expect(request.enableChunked).toBe(true);
614
+ expect(request.header).toMatchObject({
615
+ "Content-Type": "application/json",
616
+ Authorization: "Bearer key-1",
617
+ Accept: "text/event-stream",
618
+ "x-config": "cfg",
619
+ "x-tenant-id": "tenant-1",
620
+ "x-workspace-id": "ws-1",
621
+ "x-project-id": "pj-1",
622
+ "x-axiom-affinity": "thread-stream",
623
+ });
624
+ });
625
+ it("parses data: frames and reports malformed JSON", () => {
626
+ const client = makeClient();
627
+ const onEvent = jest.fn();
628
+ const onError = jest.fn();
629
+ client.chat.stream(streamOptions, onEvent, undefined, onError);
630
+ chunkHandlers[0]({ data: undefined });
631
+ chunkHandlers[0](chunk('data: {"type":"ai"}\ndata: {oops}\ndata: {"type":"done"}\n'));
632
+ expect(onEvent).toHaveBeenNthCalledWith(1, { type: "ai" });
633
+ expect(onEvent).toHaveBeenNthCalledWith(2, { type: "done" });
634
+ expect(onError).toHaveBeenCalledTimes(1);
635
+ });
636
+ it("wraps non-Error stream parse failures in an Error", () => {
637
+ const client = makeClient();
638
+ const onError = jest.fn();
639
+ client.chat.stream(streamOptions, jest.fn(), undefined, onError);
640
+ const parse = jest.spyOn(JSON, "parse").mockImplementationOnce(() => {
641
+ throw "raw failure";
642
+ });
643
+ try {
644
+ chunkHandlers[0](chunk("data: anything\n"));
645
+ }
646
+ finally {
647
+ parse.mockRestore();
648
+ }
649
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "raw failure" }));
650
+ });
651
+ it("does not complete or fetch state after a transport failure", async () => {
652
+ const client = makeClient();
653
+ const onComplete = jest.fn();
654
+ const onError = jest.fn();
655
+ client.chat.stream({ ...streamOptions, enableReturnStateWhenSteamCompleted: true }, jest.fn(), onComplete, onError);
656
+ requests[0].fail({ errMsg: "lost" });
657
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: "Stream request failed: lost" }));
658
+ requests[0].complete?.();
659
+ await flush();
660
+ expect(requests).toHaveLength(1);
661
+ expect(onComplete).not.toHaveBeenCalled();
662
+ });
663
+ it("reports non-2xx stream status and does not complete or fetch state", async () => {
664
+ const client = makeClient();
665
+ const onEvent = jest.fn();
666
+ const onComplete = jest.fn();
667
+ const onError = jest.fn();
668
+ client.chat.stream({ ...streamOptions, enableReturnStateWhenSteamCompleted: true }, onEvent, onComplete, onError);
669
+ requests[0].success({ statusCode: 400, data: { message: "bad run" } });
670
+ chunkHandlers[0](chunk('data: {"type":"ai"}\n'));
671
+ requests[0].complete?.();
672
+ await flush();
673
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({
674
+ name: "ApiError",
675
+ message: "bad run",
676
+ statusCode: 400,
677
+ }));
678
+ expect(onEvent).not.toHaveBeenCalled();
679
+ expect(onComplete).not.toHaveBeenCalled();
680
+ expect(requests).toHaveLength(1);
681
+ });
682
+ it("calls onComplete without state on normal completion when state is not requested", async () => {
683
+ const client = makeClient();
684
+ const onComplete = jest.fn();
685
+ client.chat.stream(streamOptions, jest.fn(), onComplete);
686
+ requests[0].success({ statusCode: 200 });
687
+ requests[0].complete?.();
688
+ await flush();
689
+ expect(onComplete).toHaveBeenCalledWith();
690
+ expect(requests).toHaveLength(1);
691
+ });
692
+ it("flushes a final data: line without a trailing newline on complete", async () => {
693
+ const client = makeClient();
694
+ const onEvent = jest.fn();
695
+ client.chat.stream(streamOptions, onEvent);
696
+ chunkHandlers[0](chunk('data: {"type":"final"}'));
697
+ expect(onEvent).not.toHaveBeenCalled();
698
+ requests[0].success({ statusCode: 200 });
699
+ requests[0].complete?.();
700
+ await flush();
701
+ expect(onEvent).toHaveBeenCalledWith({ type: "final" });
702
+ });
703
+ it("fetches agent state before onComplete when enabled", async () => {
704
+ const client = makeClient();
705
+ const onComplete = jest.fn();
706
+ const state = { values: { messages: [] }, tasks: [] };
707
+ client.chat.stream({ ...streamOptions, enableReturnStateWhenSteamCompleted: true }, jest.fn(), onComplete);
708
+ requests[0].success({ statusCode: 200 });
709
+ requests[0].complete?.();
710
+ expect(requests[1].url).toBe("https://api.test/api/assistants/asst-1/thread-stream/state");
711
+ requests[1].success({ statusCode: 200, data: state });
712
+ await flush();
713
+ expect(onComplete).toHaveBeenCalledWith(state);
714
+ });
715
+ it("still completes without state when the state request fails", async () => {
716
+ const client = makeClient();
717
+ const onComplete = jest.fn();
718
+ client.chat.stream({ ...streamOptions, enableReturnStateWhenSteamCompleted: true }, jest.fn(), onComplete);
719
+ requests[0].success({ statusCode: 200 });
720
+ requests[0].complete?.();
721
+ requests[1].success({ statusCode: 500, data: { message: "nope" } });
722
+ await flush();
723
+ expect(onComplete).toHaveBeenCalledWith();
724
+ });
725
+ it("returns an abort function backed by RequestTask.abort", () => {
726
+ const client = makeClient();
727
+ const stop = client.chat.stream(streamOptions, jest.fn());
728
+ stop();
729
+ expect(tasks[0].abort).toHaveBeenCalledTimes(1);
730
+ });
731
+ it("suppresses onError, completion, and state fetch after an abort", async () => {
732
+ const client = makeClient();
733
+ const onComplete = jest.fn();
734
+ const onError = jest.fn();
735
+ const stop = client.chat.stream({ ...streamOptions, enableReturnStateWhenSteamCompleted: true }, jest.fn(), onComplete, onError);
736
+ stop();
737
+ requests[0].fail({ errMsg: "request:fail abort" });
738
+ requests[0].complete?.();
739
+ await flush();
740
+ expect(onError).not.toHaveBeenCalled();
741
+ expect(onComplete).not.toHaveBeenCalled();
742
+ expect(requests).toHaveLength(1);
743
+ });
744
+ it.each([400, 0])("ignores a late stream success status %s after an abort", async (statusCode) => {
745
+ const client = makeClient();
746
+ const onComplete = jest.fn();
747
+ const onError = jest.fn();
748
+ const stop = client.chat.stream({ ...streamOptions, enableReturnStateWhenSteamCompleted: true }, jest.fn(), onComplete, onError);
749
+ stop();
750
+ requests[0].success({ statusCode, data: { message: "aborted" } });
751
+ requests[0].complete?.();
752
+ await flush();
753
+ expect(onError).not.toHaveBeenCalled();
754
+ expect(onComplete).not.toHaveBeenCalled();
755
+ expect(requests).toHaveLength(1);
756
+ });
757
+ });
758
+ describe("WeChatClient byte helpers", () => {
759
+ it("decodes UTF-8 Chinese from an ArrayBuffer", () => {
760
+ const client = makeClient();
761
+ expect(client.decodeUint8Array(chunk("你好, world").data)).toBe("你好, world");
762
+ });
763
+ it("converts bytes to lowercase hex", () => {
764
+ const client = makeClient();
765
+ expect(client.buf2hex(chunk("A你").data)).toBe("41e4bda0");
766
+ expect(client.buf2hex(new ArrayBuffer(0))).toBe("");
767
+ });
768
+ it("decodes hex to text including Chinese", () => {
769
+ const client = makeClient();
770
+ expect(client.hexToStr("e4bda0e5a5bd")).toBe("你好");
771
+ expect(client.hexToStr("4142")).toBe("AB");
772
+ });
773
+ it("accepts a 0x prefix, mixed case, and surrounding whitespace", () => {
774
+ const client = makeClient();
775
+ expect(client.hexToStr("0xe4bda0")).toBe("你");
776
+ expect(client.hexToStr(" 0XE4BDA0 ")).toBe("你");
777
+ expect(client.hexToStr(" 4142 ")).toBe("AB");
778
+ });
779
+ it("returns an empty string for odd-length hex", () => {
780
+ const client = makeClient();
781
+ expect(client.hexToStr("abc")).toBe("");
782
+ expect(client.hexToStr("0xabc")).toBe("");
783
+ });
784
+ });
785
+ //# sourceMappingURL=wechat-client.test.js.map