@escapeaihq/client-core 0.5.0 → 0.6.1

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,261 @@
1
+ /**
2
+ * Tests for ApiClient.getChatWsToken + listVoices — the two 0.6.0
3
+ * REST additions. Both go through chatRequest → makeRequest → fetch,
4
+ * so the global fetch-mock pattern from extractImage/regenerateImage
5
+ * tests in api-pollers.test.ts is the right fit.
6
+ *
7
+ * Listed gaps from the spec doc (§1, §4) require:
8
+ * - getChatWsToken POSTs to `${chatBaseUrl}/api/v1/chat/ws-token`
9
+ * and surfaces the WebSocketTokenResponse shape (wsToken,
10
+ * expiresAt, expiresIn).
11
+ * - listVoices GETs `${chatBaseUrl}/api/voices`, building the query
12
+ * string from optional language + refresh params (no `?` when
13
+ * both absent — protects against `/api/voices?` which some servers
14
+ * treat as bad input).
15
+ * - Auth header is included when a sessionToken is set on the client.
16
+ * - Non-2xx responses surface as Errors so callers can `try/catch`.
17
+ */
18
+
19
+ import { ApiClient } from '../api';
20
+
21
+ const TEST_BASE_URL = 'http://test.local';
22
+ const TEST_CHAT_BASE_URL = 'http://test.local/chat';
23
+
24
+ // Two helpers instead of one with a default arg: JS triggers default
25
+ // parameters on `undefined` as well as on "missing arg," so a single
26
+ // `makeAuthedClient(sessionToken = 'test-token')` cannot express the
27
+ // "explicitly no token" case that the unauthed test needs.
28
+ const makeAuthedClient = (sessionToken: string = 'test-token') =>
29
+ new ApiClient(TEST_BASE_URL, sessionToken, TEST_CHAT_BASE_URL);
30
+
31
+ const makeUnauthedClient = () =>
32
+ new ApiClient(TEST_BASE_URL, undefined, TEST_CHAT_BASE_URL);
33
+
34
+ // Mirror the originalFetch save/restore pattern from
35
+ // api-pollers.test.ts so a misbehaving test doesn't leak the mock
36
+ // into the rest of the suite. `jest.restoreAllMocks` only unwinds
37
+ // `jest.spyOn` calls, not direct property assignment to globalThis.
38
+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;
39
+
40
+ afterEach(() => {
41
+ if (originalFetch === undefined) {
42
+ delete (globalThis as { fetch?: typeof fetch }).fetch;
43
+ } else {
44
+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;
45
+ }
46
+ jest.restoreAllMocks();
47
+ });
48
+
49
+ describe('getChatWsToken', () => {
50
+ const buildTokenResponse = () => ({
51
+ wsToken: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.ephemeral',
52
+ expiresAt: 1699999999.5,
53
+ expiresIn: 600,
54
+ });
55
+
56
+ it('POSTs to /api/v1/chat/ws-token on the chat base URL', async () => {
57
+ const fetchMock = jest.fn().mockResolvedValue({
58
+ ok: true,
59
+ status: 201,
60
+ json: async () => buildTokenResponse(),
61
+ });
62
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
63
+
64
+ const result = await makeAuthedClient().getChatWsToken();
65
+
66
+ expect(fetchMock).toHaveBeenCalledTimes(1);
67
+ const [url, init] = fetchMock.mock.calls[0];
68
+ // Crucially: chatBaseUrl, not baseURL — the token endpoint lives
69
+ // on the chat service.
70
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/v1/chat/ws-token`);
71
+ expect(init.method).toBe('POST');
72
+ expect(result).toEqual(buildTokenResponse());
73
+ });
74
+
75
+ it('includes Authorization header when a sessionToken is set', async () => {
76
+ const fetchMock = jest.fn().mockResolvedValue({
77
+ ok: true,
78
+ status: 201,
79
+ json: async () => buildTokenResponse(),
80
+ });
81
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
82
+
83
+ await makeAuthedClient('user-jwt-abc').getChatWsToken();
84
+
85
+ const [, init] = fetchMock.mock.calls[0];
86
+ expect(init.headers).toMatchObject({
87
+ Authorization: 'Bearer user-jwt-abc',
88
+ });
89
+ });
90
+
91
+ it('omits Authorization header when sessionToken is undefined', async () => {
92
+ const fetchMock = jest.fn().mockResolvedValue({
93
+ ok: true,
94
+ status: 201,
95
+ json: async () => buildTokenResponse(),
96
+ });
97
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
98
+
99
+ await makeUnauthedClient().getChatWsToken();
100
+
101
+ const [, init] = fetchMock.mock.calls[0];
102
+ expect(init.headers).not.toHaveProperty('Authorization');
103
+ });
104
+
105
+ it('propagates non-2xx responses as Errors with the backend detail', async () => {
106
+ const fetchMock = jest.fn().mockResolvedValue({
107
+ ok: false,
108
+ status: 401,
109
+ statusText: 'Unauthorized',
110
+ json: async () => ({ detail: 'Authentication required' }),
111
+ });
112
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
113
+
114
+ await expect(makeAuthedClient().getChatWsToken()).rejects.toThrow(
115
+ 'Authentication required',
116
+ );
117
+ });
118
+
119
+ it('preserves fractional seconds on expiresAt (Python float on the wire)', async () => {
120
+ // Backend declares expiresAt: float — `.5` suffix verifies we
121
+ // don't accidentally coerce to integer at any layer.
122
+ const fetchMock = jest.fn().mockResolvedValue({
123
+ ok: true,
124
+ status: 201,
125
+ json: async () => buildTokenResponse(),
126
+ });
127
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
128
+
129
+ const result = await makeAuthedClient().getChatWsToken();
130
+ expect(result.expiresAt).toBe(1699999999.5);
131
+ });
132
+ });
133
+
134
+ describe('listVoices', () => {
135
+ const buildVoicesResponse = () => ({
136
+ voices: [
137
+ {
138
+ voiceId: 'Ashley',
139
+ displayName: 'Ashley',
140
+ description: 'A warm, natural female voice',
141
+ langCode: 'EN_US',
142
+ languages: ['EN_US'],
143
+ tags: ['warm', 'female'],
144
+ source: 'SYSTEM',
145
+ isCustom: false,
146
+ },
147
+ ],
148
+ cached: true,
149
+ });
150
+
151
+ it('GETs /api/voices with no query string when no params provided', async () => {
152
+ const fetchMock = jest.fn().mockResolvedValue({
153
+ ok: true,
154
+ status: 200,
155
+ json: async () => buildVoicesResponse(),
156
+ });
157
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
158
+
159
+ const result = await makeAuthedClient().listVoices();
160
+
161
+ expect(fetchMock).toHaveBeenCalledTimes(1);
162
+ const [url, init] = fetchMock.mock.calls[0];
163
+ // Plain `/api/voices` — no trailing `?` (some servers reject the
164
+ // empty query string as a malformed URL).
165
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/voices`);
166
+ expect(init.method).toBeUndefined();
167
+ expect(result.voices).toHaveLength(1);
168
+ expect(result.cached).toBe(true);
169
+ });
170
+
171
+ it('appends ?language= when language is set', async () => {
172
+ const fetchMock = jest.fn().mockResolvedValue({
173
+ ok: true,
174
+ status: 200,
175
+ json: async () => buildVoicesResponse(),
176
+ });
177
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
178
+
179
+ await makeAuthedClient().listVoices({ language: 'en' });
180
+
181
+ const [url] = fetchMock.mock.calls[0];
182
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/voices?language=en`);
183
+ });
184
+
185
+ it('appends ?refresh=true when refresh is set', async () => {
186
+ const fetchMock = jest.fn().mockResolvedValue({
187
+ ok: true,
188
+ status: 200,
189
+ json: async () => buildVoicesResponse(),
190
+ });
191
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
192
+
193
+ await makeAuthedClient().listVoices({ refresh: true });
194
+
195
+ const [url] = fetchMock.mock.calls[0];
196
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/voices?refresh=true`);
197
+ });
198
+
199
+ it('combines language + refresh in a single query string', async () => {
200
+ const fetchMock = jest.fn().mockResolvedValue({
201
+ ok: true,
202
+ status: 200,
203
+ json: async () => buildVoicesResponse(),
204
+ });
205
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
206
+
207
+ await makeAuthedClient().listVoices({ language: 'en', refresh: true });
208
+
209
+ const [url] = fetchMock.mock.calls[0];
210
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/voices?language=en&refresh=true`);
211
+ });
212
+
213
+ it('omits refresh from the query when explicitly false', async () => {
214
+ // `refresh: false` is the default behavior — emitting `?refresh=false`
215
+ // would surprise a server that uses truthy-presence semantics
216
+ // (`refresh in query` rather than `query.get('refresh') === 'true'`).
217
+ const fetchMock = jest.fn().mockResolvedValue({
218
+ ok: true,
219
+ status: 200,
220
+ json: async () => buildVoicesResponse(),
221
+ });
222
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
223
+
224
+ await makeAuthedClient().listVoices({ refresh: false });
225
+
226
+ const [url] = fetchMock.mock.calls[0];
227
+ expect(url).toBe(`${TEST_CHAT_BASE_URL}/api/voices`);
228
+ });
229
+
230
+ it('propagates non-2xx responses as Errors with the backend detail', async () => {
231
+ const fetchMock = jest.fn().mockResolvedValue({
232
+ ok: false,
233
+ status: 503,
234
+ statusText: 'Service Unavailable',
235
+ json: async () => ({ detail: 'Voice listing service unavailable' }),
236
+ });
237
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
238
+
239
+ await expect(makeAuthedClient().listVoices()).rejects.toThrow(
240
+ 'Voice listing service unavailable',
241
+ );
242
+ });
243
+
244
+ it('exposes the new langCode and source fields on returned voices', async () => {
245
+ // Regression guard for the 0.6.0 VoiceInfo additions — if a
246
+ // future refactor strips these off the response type, this test
247
+ // breaks instead of silently coercing them away.
248
+ const fetchMock = jest.fn().mockResolvedValue({
249
+ ok: true,
250
+ status: 200,
251
+ json: async () => buildVoicesResponse(),
252
+ });
253
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
254
+
255
+ const result = await makeAuthedClient().listVoices();
256
+ expect(result.voices[0]).toMatchObject({
257
+ langCode: 'EN_US',
258
+ source: 'SYSTEM',
259
+ });
260
+ });
261
+ });
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Tests for the §6 additions — `getEntityTimeline` and
3
+ * `createPersonaCharacter`. Both go through `request` → `makeRequest`
4
+ * → fetch (NOT chatRequest — entity-timeline + persona-character live
5
+ * on the tools API, not the chat API). Same global-fetch-mock pattern
6
+ * as `chat-auth.test.ts`.
7
+ */
8
+
9
+ import { ApiClient } from '../api';
10
+
11
+ const TEST_BASE_URL = 'http://test.local';
12
+ const TEST_CHAT_BASE_URL = 'http://test.local/chat';
13
+
14
+ const makeClient = (sessionToken: string = 'test-token') =>
15
+ new ApiClient(TEST_BASE_URL, sessionToken, TEST_CHAT_BASE_URL);
16
+
17
+ const originalFetch = (globalThis as { fetch?: typeof fetch }).fetch;
18
+
19
+ afterEach(() => {
20
+ if (originalFetch === undefined) {
21
+ delete (globalThis as { fetch?: typeof fetch }).fetch;
22
+ } else {
23
+ (globalThis as { fetch?: typeof fetch }).fetch = originalFetch;
24
+ }
25
+ jest.restoreAllMocks();
26
+ });
27
+
28
+ describe('getEntityTimeline', () => {
29
+ const buildResponse = () => ({
30
+ traceId: 'trace-abc',
31
+ results: [
32
+ {
33
+ shotId: 'shot-1',
34
+ videoId: 'video-1',
35
+ t0: 0.0,
36
+ t1: 4.2,
37
+ entityStart: 0.5,
38
+ entityEnd: 3.8,
39
+ caption: 'A wide shot of the protagonist',
40
+ dialog: [{ speaker: 'narrator', text: 'In a galaxy far, far away...' }],
41
+ citation: { videoId: 'video-1', t0: 0.0, t1: 4.2, shotId: 'shot-1' },
42
+ source: { system: 'neo4j', details: { node_id: 'n-1' } },
43
+ },
44
+ ],
45
+ });
46
+
47
+ it('POSTs to /api/v1/tools/entity-timeline on the tools base URL', async () => {
48
+ const fetchMock = jest.fn().mockResolvedValue({
49
+ ok: true,
50
+ status: 200,
51
+ json: async () => buildResponse(),
52
+ });
53
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
54
+
55
+ const result = await makeClient().getEntityTimeline('video-1', 'protagonist');
56
+
57
+ expect(fetchMock).toHaveBeenCalledTimes(1);
58
+ const [url, init] = fetchMock.mock.calls[0];
59
+ // Important: baseURL, NOT chatBaseUrl — entity-timeline lives on
60
+ // the tools API, not the chat API.
61
+ expect(url).toBe(`${TEST_BASE_URL}/api/v1/tools/entity-timeline`);
62
+ expect(init.method).toBe('POST');
63
+ expect(JSON.parse(init.body)).toEqual({
64
+ videoId: 'video-1',
65
+ entity: 'protagonist',
66
+ t0: undefined,
67
+ t1: undefined,
68
+ });
69
+ expect(result.results).toHaveLength(1);
70
+ expect(result.traceId).toBe('trace-abc');
71
+ });
72
+
73
+ it('passes optional t0/t1 bounds through to the request body', async () => {
74
+ const fetchMock = jest.fn().mockResolvedValue({
75
+ ok: true,
76
+ status: 200,
77
+ json: async () => ({ traceId: 't', results: [] }),
78
+ });
79
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
80
+
81
+ await makeClient().getEntityTimeline('video-1', 'protagonist', {
82
+ t0: 10,
83
+ t1: 30,
84
+ });
85
+
86
+ const [, init] = fetchMock.mock.calls[0];
87
+ expect(JSON.parse(init.body)).toEqual({
88
+ videoId: 'video-1',
89
+ entity: 'protagonist',
90
+ t0: 10,
91
+ t1: 30,
92
+ });
93
+ });
94
+
95
+ it('surfaces empty results as a normal response (server returns 200 with []) ', async () => {
96
+ // Server-side, an entity that resolves to "not found" returns 200
97
+ // with `results: []` rather than 404. Verify the client surfaces
98
+ // that to the caller faithfully — important because callers can
99
+ // then render an empty-state without try/catch.
100
+ const fetchMock = jest.fn().mockResolvedValue({
101
+ ok: true,
102
+ status: 200,
103
+ json: async () => ({ traceId: 't', results: [] }),
104
+ });
105
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
106
+
107
+ const result = await makeClient().getEntityTimeline('video-1', 'no-such-entity');
108
+ expect(result.results).toEqual([]);
109
+ });
110
+
111
+ it('propagates non-2xx responses as Errors with the backend detail', async () => {
112
+ const fetchMock = jest.fn().mockResolvedValue({
113
+ ok: false,
114
+ status: 422,
115
+ statusText: 'Unprocessable Entity',
116
+ json: async () => ({ detail: "Parameter 't1' must exceed 't0'" }),
117
+ });
118
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
119
+
120
+ await expect(
121
+ makeClient().getEntityTimeline('video-1', 'x', { t0: 30, t1: 10 }),
122
+ ).rejects.toThrow("Parameter 't1' must exceed 't0'");
123
+ });
124
+ });
125
+
126
+ describe('createPersonaCharacter', () => {
127
+ const buildResponse = () => ({
128
+ character_image_id: 'img-7',
129
+ status: 'pending' as const,
130
+ status_url: '/api/v1/images/img-7',
131
+ traceId: 'trace-xyz',
132
+ });
133
+
134
+ it('POSTs to /api/v1/personas/{id}/character with the body verbatim', async () => {
135
+ const fetchMock = jest.fn().mockResolvedValue({
136
+ ok: true,
137
+ status: 202,
138
+ json: async () => buildResponse(),
139
+ });
140
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
141
+
142
+ const result = await makeClient().createPersonaCharacter('persona-1', {
143
+ source_image_id: 'src-img-3',
144
+ style: 'noir, high contrast',
145
+ });
146
+
147
+ expect(fetchMock).toHaveBeenCalledTimes(1);
148
+ const [url, init] = fetchMock.mock.calls[0];
149
+ expect(url).toBe(`${TEST_BASE_URL}/api/v1/personas/persona-1/character`);
150
+ expect(init.method).toBe('POST');
151
+ expect(JSON.parse(init.body)).toEqual({
152
+ source_image_id: 'src-img-3',
153
+ style: 'noir, high contrast',
154
+ });
155
+ // 202 envelope passes through; the snake_case shape is intentional
156
+ // (mirrors the server) and downstream pollers key off
157
+ // `character_image_id`.
158
+ expect(result.character_image_id).toBe('img-7');
159
+ expect(result.status_url).toBe('/api/v1/images/img-7');
160
+ expect(result.status).toBe('pending');
161
+ });
162
+
163
+ it('URL-encodes the persona ID', async () => {
164
+ // Persona IDs are caller-controlled in some flows (e.g. synthesized
165
+ // personas). Guard against an unencoded slash splitting the path.
166
+ const fetchMock = jest.fn().mockResolvedValue({
167
+ ok: true,
168
+ status: 202,
169
+ json: async () => buildResponse(),
170
+ });
171
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
172
+
173
+ await makeClient().createPersonaCharacter('user/123', {
174
+ video_id: 'v-1',
175
+ entity: 'protagonist',
176
+ });
177
+
178
+ const [url] = fetchMock.mock.calls[0];
179
+ expect(url).toBe(`${TEST_BASE_URL}/api/v1/personas/user%2F123/character`);
180
+ });
181
+
182
+ it('passes the video-source path (entity + timestamp) through', async () => {
183
+ const fetchMock = jest.fn().mockResolvedValue({
184
+ ok: true,
185
+ status: 202,
186
+ json: async () => buildResponse(),
187
+ });
188
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
189
+
190
+ await makeClient().createPersonaCharacter('p-1', {
191
+ video_id: 'v-1',
192
+ entity: 'wizard',
193
+ timestamp: 42.5,
194
+ style: 'cel-shaded',
195
+ });
196
+
197
+ const [, init] = fetchMock.mock.calls[0];
198
+ expect(JSON.parse(init.body)).toEqual({
199
+ video_id: 'v-1',
200
+ entity: 'wizard',
201
+ timestamp: 42.5,
202
+ style: 'cel-shaded',
203
+ });
204
+ });
205
+
206
+ it('propagates non-2xx responses as Errors with the backend detail', async () => {
207
+ const fetchMock = jest.fn().mockResolvedValue({
208
+ ok: false,
209
+ status: 404,
210
+ statusText: 'Not Found',
211
+ json: async () => ({ detail: 'Persona not found: p-1' }),
212
+ });
213
+ (globalThis as { fetch?: typeof fetch }).fetch = fetchMock as unknown as typeof fetch;
214
+
215
+ await expect(
216
+ makeClient().createPersonaCharacter('p-1', { source_image_id: 'i-1' }),
217
+ ).rejects.toThrow('Persona not found: p-1');
218
+ });
219
+ });