@apifuse/provider-sdk 2.2.0-beta.12 → 2.2.0-beta.13
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/AUTHORING.md +201 -0
- package/CHANGELOG.md +10 -0
- package/README.md +26 -2
- package/bin/apifuse-pack-types.ts +30 -1
- package/bin/apifuse-record.ts +622 -57
- package/bin/apifuse-submit-check.ts +43 -10
- package/dist/define.d.ts +2 -1
- package/dist/define.js +61 -3
- package/dist/fixture-sanitization.d.ts +26 -0
- package/dist/fixture-sanitization.js +216 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -0
- package/dist/provider.d.ts +2 -1
- package/dist/provider.js +1 -0
- package/dist/runtime/http.js +86 -32
- package/dist/runtime/instrumentation.js +295 -9
- package/dist/runtime/native-network.d.ts +53 -0
- package/dist/runtime/native-network.js +477 -0
- package/dist/runtime/proxy-nodemaven.d.ts +14 -0
- package/dist/runtime/proxy-nodemaven.js +20 -2
- package/dist/runtime/request-options.d.ts +68 -1
- package/dist/runtime/request-options.js +548 -0
- package/dist/runtime/stealth.d.ts +3 -1
- package/dist/runtime/stealth.js +239 -39
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/self-test-input-tokens.d.ts +2 -1
- package/dist/server/self-test-input-tokens.js +18 -14
- package/dist/stream-evidence.d.ts +74 -0
- package/dist/stream-evidence.js +785 -0
- package/dist/testing/index.d.ts +1 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/run.d.ts +32 -2
- package/dist/testing/run.js +451 -19
- package/dist/types.d.ts +162 -0
- package/package.json +2 -1
- package/src/define.ts +81 -3
- package/src/fixture-sanitization.ts +247 -0
- package/src/index.ts +37 -0
- package/src/provider.ts +37 -0
- package/src/runtime/http.ts +144 -38
- package/src/runtime/instrumentation.ts +424 -8
- package/src/runtime/native-network.ts +600 -0
- package/src/runtime/proxy-nodemaven.ts +37 -2
- package/src/runtime/request-options.ts +680 -1
- package/src/runtime/stealth.ts +293 -40
- package/src/server/index.ts +4 -1
- package/src/server/self-test-input-tokens.ts +29 -14
- package/src/stream-evidence.ts +988 -0
- package/src/testing/index.ts +9 -1
- package/src/testing/run.ts +608 -12
- package/src/types.ts +194 -0
package/src/testing/run.ts
CHANGED
|
@@ -5,12 +5,18 @@ import { createTestProviderChoiceContext } from "../runtime/choice.js";
|
|
|
5
5
|
import { createMemoryProviderRuntimeState } from "../runtime/state.js";
|
|
6
6
|
import { createUnsupportedSttClient } from "../runtime/stt.js";
|
|
7
7
|
import { safeParseSchemaSync } from "../schema.js";
|
|
8
|
+
import { requestPathForFixture } from "../fixture-sanitization.js";
|
|
9
|
+
import { findStreamCaptureGroup, replayStreamEvidence } from "../stream-evidence.js";
|
|
8
10
|
import type {
|
|
9
11
|
AuthMode,
|
|
12
|
+
BrowserPage,
|
|
10
13
|
CredentialContext,
|
|
11
14
|
HttpResponse,
|
|
15
|
+
NativeNetworkConnection,
|
|
12
16
|
ProviderContext,
|
|
13
17
|
ProviderDefinition,
|
|
18
|
+
StealthCookieStoreV1,
|
|
19
|
+
StealthResponse,
|
|
14
20
|
} from "../types.js";
|
|
15
21
|
|
|
16
22
|
// Mirrors CONNECTOR_ID_REGEX in ../define.ts, which defineProvider() enforces.
|
|
@@ -19,6 +25,10 @@ import type {
|
|
|
19
25
|
const CONNECTOR_ID_REGEX = /^[a-z][a-z0-9]*(-[a-z][a-z0-9]*)*$/;
|
|
20
26
|
const VALID_AUTH_MODES = ["none", "platform-managed", "credentials", "oauth2"] as const;
|
|
21
27
|
const UPDATE_SNAPSHOT_ARGS = new Set(["-u", "--update-snapshots"]);
|
|
28
|
+
const snapshotCaptureStates = new WeakMap<
|
|
29
|
+
ProviderContext,
|
|
30
|
+
{ assertConsumed(): void; consumed(): number }
|
|
31
|
+
>();
|
|
22
32
|
|
|
23
33
|
export interface StandardTestsManifest {
|
|
24
34
|
id?: string;
|
|
@@ -44,6 +54,40 @@ export interface StandardTestsOptions {
|
|
|
44
54
|
validateAuthMode?: boolean;
|
|
45
55
|
/** Override inferred __fixtures__ directory for tests generated outside providers/<id>. */
|
|
46
56
|
fixtureDir?: string;
|
|
57
|
+
/** Opt in to real-handler E2E with strict, offline canned upstream responses. */
|
|
58
|
+
upstreamStub?: StandardTestsUpstreamStub;
|
|
59
|
+
/** Require a committed snapshot; missing files fail unless --update-snapshots is passed. */
|
|
60
|
+
requireSnapshot?: boolean;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface StandardTestsUpstreamCall {
|
|
64
|
+
/** Operation whose real handler initiated the call. */
|
|
65
|
+
operationName: string;
|
|
66
|
+
/** ProviderContext transport surface used by the handler. */
|
|
67
|
+
transport: "http" | "stealth" | "browser" | "native";
|
|
68
|
+
method: string;
|
|
69
|
+
url?: string;
|
|
70
|
+
body?: unknown;
|
|
71
|
+
options?: unknown;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface StandardTestsUpstreamResponse {
|
|
75
|
+
status?: number;
|
|
76
|
+
headers?: Readonly<Record<string, string>>;
|
|
77
|
+
/** JSON-compatible values are encoded as JSON; strings and bytes are preserved. */
|
|
78
|
+
body?: unknown;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export type StandardTestsUpstreamStub = (
|
|
82
|
+
call: StandardTestsUpstreamCall,
|
|
83
|
+
) =>
|
|
84
|
+
| Response
|
|
85
|
+
| StandardTestsUpstreamResponse
|
|
86
|
+
| undefined
|
|
87
|
+
| Promise<Response | StandardTestsUpstreamResponse | undefined>;
|
|
88
|
+
|
|
89
|
+
export interface StandardTestsResult {
|
|
90
|
+
warnings: readonly string[];
|
|
47
91
|
}
|
|
48
92
|
|
|
49
93
|
interface FixtureEnvelope {
|
|
@@ -136,11 +180,394 @@ function jsonResponse(data: unknown): HttpResponse {
|
|
|
136
180
|
};
|
|
137
181
|
}
|
|
138
182
|
|
|
183
|
+
interface NormalizedUpstreamResponse {
|
|
184
|
+
status: number;
|
|
185
|
+
headers: Record<string, string>;
|
|
186
|
+
data: unknown;
|
|
187
|
+
text: string;
|
|
188
|
+
bytes: Uint8Array;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function headersToRecord(headers: Headers): Record<string, string> {
|
|
192
|
+
return Object.fromEntries(headers.entries());
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
async function normalizeUpstreamResponse(
|
|
196
|
+
response: Response | StandardTestsUpstreamResponse,
|
|
197
|
+
): Promise<NormalizedUpstreamResponse> {
|
|
198
|
+
if (response instanceof Response) {
|
|
199
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
200
|
+
const text = new TextDecoder().decode(bytes);
|
|
201
|
+
const headers = headersToRecord(response.headers);
|
|
202
|
+
let data: unknown = text;
|
|
203
|
+
if (response.headers.get("content-type")?.includes("application/json")) {
|
|
204
|
+
data = text.length > 0 ? JSON.parse(text) : null;
|
|
205
|
+
}
|
|
206
|
+
return { status: response.status, headers, data, text, bytes };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
const headers = { ...(response.headers ?? {}) };
|
|
210
|
+
const body = response.body ?? null;
|
|
211
|
+
let bytes: Uint8Array;
|
|
212
|
+
let text: string;
|
|
213
|
+
let data: unknown;
|
|
214
|
+
if (body instanceof Uint8Array) {
|
|
215
|
+
bytes = body.slice(0);
|
|
216
|
+
text = new TextDecoder().decode(bytes);
|
|
217
|
+
data = text;
|
|
218
|
+
} else if (body instanceof ArrayBuffer) {
|
|
219
|
+
bytes = new Uint8Array(body.slice(0));
|
|
220
|
+
text = new TextDecoder().decode(bytes);
|
|
221
|
+
data = text;
|
|
222
|
+
} else if (typeof body === "string") {
|
|
223
|
+
text = body;
|
|
224
|
+
bytes = new TextEncoder().encode(text);
|
|
225
|
+
data = body;
|
|
226
|
+
} else {
|
|
227
|
+
text = JSON.stringify(body);
|
|
228
|
+
bytes = new TextEncoder().encode(text);
|
|
229
|
+
data = body;
|
|
230
|
+
if (!Object.keys(headers).some((name) => name.toLowerCase() === "content-type")) {
|
|
231
|
+
headers["content-type"] = "application/json";
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return { status: response.status ?? 200, headers, data, text, bytes };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
function toHttpResponse(response: NormalizedUpstreamResponse): HttpResponse {
|
|
238
|
+
return {
|
|
239
|
+
status: response.status,
|
|
240
|
+
ok: response.status >= 200 && response.status < 300,
|
|
241
|
+
headers: response.headers,
|
|
242
|
+
data: response.data,
|
|
243
|
+
json: async <T = unknown>() => JSON.parse(response.text) as T,
|
|
244
|
+
text: async () => response.text,
|
|
245
|
+
arrayBuffer: async () => response.bytes.slice(0).buffer,
|
|
246
|
+
bytes: async () => response.bytes.slice(0),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
const emptyCookieJar = {
|
|
251
|
+
get: () => undefined,
|
|
252
|
+
getAll: () => ({}),
|
|
253
|
+
toString: () => "",
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
function emptyCookieStore(): StealthCookieStoreV1 {
|
|
257
|
+
return {
|
|
258
|
+
version: 1,
|
|
259
|
+
jar: { cookies: [] } as unknown as StealthCookieStoreV1["jar"],
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function toStealthResponse(response: NormalizedUpstreamResponse, url?: string): StealthResponse {
|
|
264
|
+
return {
|
|
265
|
+
status: response.status,
|
|
266
|
+
ok: response.status >= 200 && response.status < 300,
|
|
267
|
+
url,
|
|
268
|
+
redirected: false,
|
|
269
|
+
headers: response.headers,
|
|
270
|
+
rawHeaders: Object.entries(response.headers),
|
|
271
|
+
body: response.text,
|
|
272
|
+
cookies: emptyCookieJar,
|
|
273
|
+
json: async <T>() => JSON.parse(response.text) as T,
|
|
274
|
+
arrayBuffer: async () => response.bytes.slice(0).buffer,
|
|
275
|
+
bytes: async () => response.bytes.slice(0),
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
function streamFromBytes(bytes: Uint8Array): ReadableStream<Uint8Array> {
|
|
280
|
+
return new ReadableStream({
|
|
281
|
+
start(controller) {
|
|
282
|
+
controller.enqueue(bytes.slice(0));
|
|
283
|
+
controller.close();
|
|
284
|
+
},
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function* singleBytes(bytes: Uint8Array): AsyncIterable<Uint8Array> {
|
|
289
|
+
yield bytes.slice(0);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
async function* singleText(textValue: string): AsyncIterable<string> {
|
|
293
|
+
yield textValue;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function createUpstreamContext(
|
|
297
|
+
provider: ProviderDefinition,
|
|
298
|
+
operationName: string,
|
|
299
|
+
upstreamStub: StandardTestsUpstreamStub,
|
|
300
|
+
): ProviderContext {
|
|
301
|
+
const credential: CredentialContext = {
|
|
302
|
+
mode: "none",
|
|
303
|
+
get: () => undefined,
|
|
304
|
+
getAll: () => ({}),
|
|
305
|
+
getAccessToken: () => undefined,
|
|
306
|
+
getScopes: () => [],
|
|
307
|
+
};
|
|
308
|
+
const request = { headers: {} };
|
|
309
|
+
const state = createMemoryProviderRuntimeState();
|
|
310
|
+
const dispatch = async (
|
|
311
|
+
call: Omit<StandardTestsUpstreamCall, "operationName">,
|
|
312
|
+
): Promise<NormalizedUpstreamResponse> => {
|
|
313
|
+
const canned = await upstreamStub({ operationName, ...call });
|
|
314
|
+
if (canned === undefined) {
|
|
315
|
+
throw new Error(
|
|
316
|
+
`Unmatched upstream call for operation "${operationName}": ${call.transport}.${call.method}${call.url ? ` ${call.url}` : ""}. Add a canned response to upstreamStub; live network passthrough is disabled.`,
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
return normalizeUpstreamResponse(canned);
|
|
320
|
+
};
|
|
321
|
+
const httpCall = async (
|
|
322
|
+
method: string,
|
|
323
|
+
url: string,
|
|
324
|
+
body?: unknown,
|
|
325
|
+
options?: unknown,
|
|
326
|
+
): Promise<HttpResponse> =>
|
|
327
|
+
toHttpResponse(await dispatch({ transport: "http", method, url, body, options }));
|
|
328
|
+
const stealthCall = async (url: string, options?: { method?: string; body?: unknown }) =>
|
|
329
|
+
toStealthResponse(
|
|
330
|
+
await dispatch({
|
|
331
|
+
transport: "stealth",
|
|
332
|
+
method: options?.method?.toUpperCase() ?? "GET",
|
|
333
|
+
url,
|
|
334
|
+
body: options?.body,
|
|
335
|
+
options,
|
|
336
|
+
}),
|
|
337
|
+
url,
|
|
338
|
+
);
|
|
339
|
+
|
|
340
|
+
const createBrowserPage = (): BrowserPage => {
|
|
341
|
+
let currentUrl = "about:blank";
|
|
342
|
+
let currentResponse: NormalizedUpstreamResponse | undefined;
|
|
343
|
+
const browserAction = async (method: string, body?: unknown) => {
|
|
344
|
+
currentResponse = await dispatch({
|
|
345
|
+
transport: "browser",
|
|
346
|
+
method,
|
|
347
|
+
url: currentUrl,
|
|
348
|
+
body,
|
|
349
|
+
});
|
|
350
|
+
return currentResponse;
|
|
351
|
+
};
|
|
352
|
+
const page: BrowserPage = {
|
|
353
|
+
id: `standard-test-${operationName}`,
|
|
354
|
+
url: async () => currentUrl,
|
|
355
|
+
title: async () => currentResponse?.text.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1] ?? "",
|
|
356
|
+
content: async () => currentResponse?.text ?? "",
|
|
357
|
+
evaluate: async <T>(fn: string | (() => T)) =>
|
|
358
|
+
(await browserAction("evaluate", typeof fn === "string" ? fn : String(fn))).data as T,
|
|
359
|
+
locator: (selector) => ({
|
|
360
|
+
click: async () => {
|
|
361
|
+
await browserAction("locator.click", { selector });
|
|
362
|
+
},
|
|
363
|
+
fill: async (textValue) => {
|
|
364
|
+
await browserAction("locator.fill", { selector, text: textValue });
|
|
365
|
+
},
|
|
366
|
+
textContent: async () => {
|
|
367
|
+
const value = (await browserAction("locator.textContent", { selector })).data;
|
|
368
|
+
return value === null || value === undefined ? null : String(value);
|
|
369
|
+
},
|
|
370
|
+
waitFor: async (options) => {
|
|
371
|
+
await browserAction("locator.waitFor", { selector, options });
|
|
372
|
+
},
|
|
373
|
+
}),
|
|
374
|
+
close: async () => {},
|
|
375
|
+
fill: async (selector, textValue) => {
|
|
376
|
+
await browserAction("fill", { selector, text: textValue });
|
|
377
|
+
},
|
|
378
|
+
goto: async (url) => {
|
|
379
|
+
currentUrl = url;
|
|
380
|
+
await browserAction("goto");
|
|
381
|
+
},
|
|
382
|
+
screenshot: async (options) =>
|
|
383
|
+
Buffer.from((await browserAction("screenshot", options)).bytes),
|
|
384
|
+
click: async (selector) => {
|
|
385
|
+
await browserAction("click", { selector });
|
|
386
|
+
},
|
|
387
|
+
type: async (selector, textValue) => {
|
|
388
|
+
await browserAction("type", { selector, text: textValue });
|
|
389
|
+
},
|
|
390
|
+
waitForSelector: async (selector, options) => {
|
|
391
|
+
await browserAction("waitForSelector", { selector, options });
|
|
392
|
+
},
|
|
393
|
+
frames: async () => [page],
|
|
394
|
+
withResourcePolicy: async (_policy, run) => run(),
|
|
395
|
+
};
|
|
396
|
+
return page;
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
const createStealthSession = (): ReturnType<ProviderContext["stealth"]["createSession"]> => ({
|
|
400
|
+
fetch: stealthCall,
|
|
401
|
+
cookies: {
|
|
402
|
+
...emptyCookieJar,
|
|
403
|
+
has: () => false,
|
|
404
|
+
setFromCookieStrings: () => {},
|
|
405
|
+
toHeader: () => "",
|
|
406
|
+
snapshot: () => ({}),
|
|
407
|
+
restore: () => {},
|
|
408
|
+
serialize: emptyCookieStore,
|
|
409
|
+
deserialize: () => {},
|
|
410
|
+
clear: () => {},
|
|
411
|
+
},
|
|
412
|
+
redirects: {
|
|
413
|
+
run: async (options) => {
|
|
414
|
+
const final = await stealthCall(options.url, options);
|
|
415
|
+
return {
|
|
416
|
+
final,
|
|
417
|
+
hops: [],
|
|
418
|
+
reason: "completed",
|
|
419
|
+
cookies: {},
|
|
420
|
+
cookieStore: emptyCookieStore(),
|
|
421
|
+
};
|
|
422
|
+
},
|
|
423
|
+
},
|
|
424
|
+
close: () => {},
|
|
425
|
+
});
|
|
426
|
+
|
|
427
|
+
return {
|
|
428
|
+
env: { get: () => undefined },
|
|
429
|
+
credential,
|
|
430
|
+
request,
|
|
431
|
+
http: {
|
|
432
|
+
request: (url, options) =>
|
|
433
|
+
httpCall(options?.method?.toUpperCase() ?? "GET", url, options?.body, options),
|
|
434
|
+
get: (url, options) => httpCall("GET", url, undefined, options),
|
|
435
|
+
post: (url, body, options) => httpCall("POST", url, body, options),
|
|
436
|
+
put: (url, body, options) => httpCall("PUT", url, body, options),
|
|
437
|
+
delete: (url, options) => httpCall("DELETE", url, undefined, options),
|
|
438
|
+
stream: async (url, options) => {
|
|
439
|
+
const response = await dispatch({
|
|
440
|
+
transport: "http",
|
|
441
|
+
method: options?.method?.toUpperCase() ?? "GET",
|
|
442
|
+
url,
|
|
443
|
+
body: options?.body,
|
|
444
|
+
options,
|
|
445
|
+
});
|
|
446
|
+
return {
|
|
447
|
+
status: response.status,
|
|
448
|
+
ok: response.status >= 200 && response.status < 300,
|
|
449
|
+
headers: response.headers,
|
|
450
|
+
body: streamFromBytes(response.bytes),
|
|
451
|
+
bytes: () => singleBytes(response.bytes),
|
|
452
|
+
textChunks: () => singleText(response.text),
|
|
453
|
+
lines: () => singleText(response.text),
|
|
454
|
+
};
|
|
455
|
+
},
|
|
456
|
+
sse: async (url, options) => {
|
|
457
|
+
const response = await dispatch({
|
|
458
|
+
transport: "http",
|
|
459
|
+
method: options?.method?.toUpperCase() ?? "GET",
|
|
460
|
+
url,
|
|
461
|
+
body: options?.body,
|
|
462
|
+
options,
|
|
463
|
+
});
|
|
464
|
+
async function* messages() {
|
|
465
|
+
for (const block of response.text.split(/\r?\n\r?\n/)) {
|
|
466
|
+
const data = block
|
|
467
|
+
.split(/\r?\n/)
|
|
468
|
+
.filter((line) => line.startsWith("data:"))
|
|
469
|
+
.map((line) => line.slice(5).trimStart())
|
|
470
|
+
.join("\n");
|
|
471
|
+
if (!data) continue;
|
|
472
|
+
yield { event: "message", data, json: <T>() => JSON.parse(data) as T };
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return messages();
|
|
476
|
+
},
|
|
477
|
+
},
|
|
478
|
+
cache: createProviderCache({ providerId: `standard-test-${operationName}` }),
|
|
479
|
+
state,
|
|
480
|
+
stealth: {
|
|
481
|
+
fetch: stealthCall,
|
|
482
|
+
createSession: createStealthSession,
|
|
483
|
+
},
|
|
484
|
+
browser: {
|
|
485
|
+
engine: "playwright-stealth",
|
|
486
|
+
newPage: async () => createBrowserPage(),
|
|
487
|
+
rawPage: async () => createBrowserPage(),
|
|
488
|
+
withIsolatedContext: async (handler) => handler(createBrowserPage()),
|
|
489
|
+
solveChallenge: async (challenge) =>
|
|
490
|
+
(
|
|
491
|
+
await dispatch({
|
|
492
|
+
transport: "browser",
|
|
493
|
+
method: "solveChallenge",
|
|
494
|
+
body: challenge,
|
|
495
|
+
})
|
|
496
|
+
).data as Awaited<ReturnType<ProviderContext["browser"]["solveChallenge"]>>,
|
|
497
|
+
},
|
|
498
|
+
...(provider.native
|
|
499
|
+
? {
|
|
500
|
+
native: {
|
|
501
|
+
network: {
|
|
502
|
+
connectTcp: async (options) =>
|
|
503
|
+
createNativeConnection(
|
|
504
|
+
await dispatch({
|
|
505
|
+
transport: "native",
|
|
506
|
+
method: "connectTcp",
|
|
507
|
+
url: `tcp://${options.host}:${options.port}`,
|
|
508
|
+
options,
|
|
509
|
+
}),
|
|
510
|
+
dispatch,
|
|
511
|
+
`tcp://${options.host}:${options.port}`,
|
|
512
|
+
),
|
|
513
|
+
connectTls: async (options) =>
|
|
514
|
+
createNativeConnection(
|
|
515
|
+
await dispatch({
|
|
516
|
+
transport: "native",
|
|
517
|
+
method: "connectTls",
|
|
518
|
+
url: `tls://${options.host}:${options.port}`,
|
|
519
|
+
options,
|
|
520
|
+
}),
|
|
521
|
+
dispatch,
|
|
522
|
+
`tls://${options.host}:${options.port}`,
|
|
523
|
+
),
|
|
524
|
+
grantTcpEgress: () => ({ revoke: () => {} }),
|
|
525
|
+
},
|
|
526
|
+
},
|
|
527
|
+
}
|
|
528
|
+
: {}),
|
|
529
|
+
trace: { span: async (_name, fn) => fn() },
|
|
530
|
+
auth: { requestField: async (name) => unsupported(`ctx.auth.requestField(${name})`) },
|
|
531
|
+
stt: createUnsupportedSttClient(
|
|
532
|
+
"Standard test upstream context does not support ctx.stt.transcribe",
|
|
533
|
+
),
|
|
534
|
+
choice: createTestProviderChoiceContext({
|
|
535
|
+
providerId: `standard-test-${operationName}`,
|
|
536
|
+
request,
|
|
537
|
+
credential,
|
|
538
|
+
state,
|
|
539
|
+
}),
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function createNativeConnection(
|
|
544
|
+
initialResponse: NormalizedUpstreamResponse,
|
|
545
|
+
dispatch: (
|
|
546
|
+
call: Omit<StandardTestsUpstreamCall, "operationName">,
|
|
547
|
+
) => Promise<NormalizedUpstreamResponse>,
|
|
548
|
+
url: string,
|
|
549
|
+
): NativeNetworkConnection {
|
|
550
|
+
let unread = initialResponse.bytes.slice(0);
|
|
551
|
+
return {
|
|
552
|
+
read: async () => {
|
|
553
|
+
if (unread.byteLength === 0) return null;
|
|
554
|
+
const bytes = unread;
|
|
555
|
+
unread = new Uint8Array();
|
|
556
|
+
return bytes;
|
|
557
|
+
},
|
|
558
|
+
write: async (body) => {
|
|
559
|
+
const response = await dispatch({ transport: "native", method: "write", url, body });
|
|
560
|
+
unread = response.bytes.slice(0);
|
|
561
|
+
},
|
|
562
|
+
close: async () => {},
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
139
566
|
function unsupported(name: string): never {
|
|
140
567
|
throw new Error(`Standard test snapshot context does not support ${name}`);
|
|
141
568
|
}
|
|
142
569
|
|
|
143
|
-
function createSnapshotContext(rawFixture: unknown): ProviderContext {
|
|
570
|
+
export function createSnapshotContext(rawFixture: unknown): ProviderContext {
|
|
144
571
|
const credential: CredentialContext = {
|
|
145
572
|
mode: "none",
|
|
146
573
|
get: () => undefined,
|
|
@@ -150,18 +577,61 @@ function createSnapshotContext(rawFixture: unknown): ProviderContext {
|
|
|
150
577
|
};
|
|
151
578
|
const request = { headers: {} };
|
|
152
579
|
const state = createMemoryProviderRuntimeState();
|
|
580
|
+
const streamCaptureGroup = findStreamCaptureGroup(rawFixture);
|
|
581
|
+
let nextCaptureItem = 0;
|
|
582
|
+
const replayJsonResponse = () => {
|
|
583
|
+
if (!streamCaptureGroup) return jsonResponse(rawFixture);
|
|
584
|
+
const item = streamCaptureGroup.items[nextCaptureItem];
|
|
585
|
+
if (!item) {
|
|
586
|
+
throw new Error(
|
|
587
|
+
`Stream fixture exhausted: no recorded response exists for ordinary HTTP call ${nextCaptureItem + 1}.`,
|
|
588
|
+
);
|
|
589
|
+
}
|
|
590
|
+
if (item.kind !== "response") {
|
|
591
|
+
throw new Error(
|
|
592
|
+
`Stream fixture call-order mismatch: expected a stream call at position ${nextCaptureItem + 1}, received an ordinary HTTP call.`,
|
|
593
|
+
);
|
|
594
|
+
}
|
|
595
|
+
nextCaptureItem += 1;
|
|
596
|
+
return jsonResponse(item.value);
|
|
597
|
+
};
|
|
153
598
|
|
|
154
|
-
|
|
599
|
+
const context: ProviderContext = {
|
|
155
600
|
env: { get: () => undefined },
|
|
156
601
|
credential,
|
|
157
602
|
request,
|
|
158
603
|
http: {
|
|
159
|
-
request: async () =>
|
|
160
|
-
get: async () =>
|
|
161
|
-
post: async () =>
|
|
162
|
-
put: async () =>
|
|
163
|
-
delete: async () =>
|
|
164
|
-
stream: async () =>
|
|
604
|
+
request: async () => replayJsonResponse(),
|
|
605
|
+
get: async () => replayJsonResponse(),
|
|
606
|
+
post: async () => replayJsonResponse(),
|
|
607
|
+
put: async () => replayJsonResponse(),
|
|
608
|
+
delete: async () => replayJsonResponse(),
|
|
609
|
+
stream: async (...args) => {
|
|
610
|
+
if (!streamCaptureGroup) return unsupported("ctx.http.stream");
|
|
611
|
+
const item = streamCaptureGroup.items[nextCaptureItem];
|
|
612
|
+
if (!item) {
|
|
613
|
+
throw new Error(
|
|
614
|
+
`Stream fixture exhausted: no recorded evidence exists for stream call ${nextCaptureItem + 1}.`,
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
if (item.kind !== "stream") {
|
|
618
|
+
throw new Error(
|
|
619
|
+
`Stream fixture call-order mismatch: expected an ordinary HTTP call at position ${nextCaptureItem + 1}, received a stream call.`,
|
|
620
|
+
);
|
|
621
|
+
}
|
|
622
|
+
if (item.evidence.request) {
|
|
623
|
+
const expected = item.evidence.request;
|
|
624
|
+
const actualMethod = (args[1]?.method ?? "GET").toUpperCase();
|
|
625
|
+
const actualPath = replayRequestPath(args[0], expected.path);
|
|
626
|
+
if (actualMethod !== expected.method || actualPath !== expected.path) {
|
|
627
|
+
throw new Error(
|
|
628
|
+
`Stream fixture request mismatch: expected ${expected.method} ${expected.path}, received ${actualMethod} ${actualPath}.`,
|
|
629
|
+
);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
nextCaptureItem += 1;
|
|
633
|
+
return replayStreamEvidence(item.evidence);
|
|
634
|
+
},
|
|
165
635
|
sse: async () => unsupported("ctx.http.sse"),
|
|
166
636
|
},
|
|
167
637
|
cache: createProviderCache({ providerId: "standard-test" }),
|
|
@@ -193,6 +663,26 @@ function createSnapshotContext(rawFixture: unknown): ProviderContext {
|
|
|
193
663
|
state,
|
|
194
664
|
}),
|
|
195
665
|
};
|
|
666
|
+
snapshotCaptureStates.set(context, {
|
|
667
|
+
assertConsumed() {
|
|
668
|
+
if (streamCaptureGroup && nextCaptureItem !== streamCaptureGroup.items.length) {
|
|
669
|
+
throw new Error(
|
|
670
|
+
`Stream fixture has ${streamCaptureGroup.items.length - nextCaptureItem} unconsumed capture item${streamCaptureGroup.items.length - nextCaptureItem === 1 ? "" : "s"} after handler completion.`,
|
|
671
|
+
);
|
|
672
|
+
}
|
|
673
|
+
},
|
|
674
|
+
consumed: () => nextCaptureItem,
|
|
675
|
+
});
|
|
676
|
+
return context;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function replayRequestPath(requestUrl: string, expectedPath: string): string {
|
|
680
|
+
if (/^[a-z][a-z\d+.-]*:\/\//i.test(requestUrl) || requestUrl.startsWith("/")) {
|
|
681
|
+
return requestPathForFixture(requestUrl);
|
|
682
|
+
}
|
|
683
|
+
return requestPathForFixture(
|
|
684
|
+
new URL(requestUrl, `https://fixture.invalid${expectedPath}`).toString(),
|
|
685
|
+
);
|
|
196
686
|
}
|
|
197
687
|
|
|
198
688
|
async function transformSnapshotOutput(
|
|
@@ -200,14 +690,21 @@ async function transformSnapshotOutput(
|
|
|
200
690
|
rawFixture: unknown,
|
|
201
691
|
): Promise<unknown> {
|
|
202
692
|
const entries = Object.entries(provider.operations);
|
|
203
|
-
const
|
|
693
|
+
const captureStates: Array<{ assertConsumed(): void; consumed(): number }> = [];
|
|
204
694
|
const outputs = await Promise.all(
|
|
205
695
|
entries.map(async ([operationName, operation]) => {
|
|
696
|
+
const context = createSnapshotContext(rawFixture);
|
|
206
697
|
const request = operation.fixtures?.request ?? {};
|
|
207
698
|
const output = await operation.handler(context, request);
|
|
699
|
+
const captureState = snapshotCaptureStates.get(context);
|
|
700
|
+
if (captureState) captureStates.push(captureState);
|
|
701
|
+
if (captureState?.consumed()) captureState.assertConsumed();
|
|
208
702
|
return [operationName, output] as const;
|
|
209
703
|
}),
|
|
210
704
|
);
|
|
705
|
+
if (findStreamCaptureGroup(rawFixture) && !captureStates.some((state) => state.consumed() > 0)) {
|
|
706
|
+
captureStates[0]?.assertConsumed();
|
|
707
|
+
}
|
|
211
708
|
|
|
212
709
|
if (outputs.length === 1) {
|
|
213
710
|
return outputs[0]?.[1];
|
|
@@ -284,6 +781,58 @@ function parseSchemaFixture(
|
|
|
284
781
|
);
|
|
285
782
|
}
|
|
286
783
|
|
|
784
|
+
async function materializeHandlerOutput(output: unknown): Promise<unknown> {
|
|
785
|
+
if (!(output instanceof Response)) return output;
|
|
786
|
+
const contentType = output.headers.get("content-type") ?? "";
|
|
787
|
+
if (contentType.includes("application/json")) return output.json();
|
|
788
|
+
return output.text();
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/** Internal execution seam exported for focused SDK tests; use runStandardTests as public API. */
|
|
792
|
+
export async function executeStandardTestHandler(
|
|
793
|
+
provider: ProviderDefinition,
|
|
794
|
+
operationName: string,
|
|
795
|
+
upstreamStub: StandardTestsUpstreamStub,
|
|
796
|
+
): Promise<unknown> {
|
|
797
|
+
const operation = provider.operations[operationName];
|
|
798
|
+
if (!operation) throw new Error(`Unknown operation "${operationName}".`);
|
|
799
|
+
if (operation.fixtures?.request === undefined) {
|
|
800
|
+
throw new Error(
|
|
801
|
+
`Operation "${operationName}" has no fixtures.request for handler E2E execution.`,
|
|
802
|
+
);
|
|
803
|
+
}
|
|
804
|
+
const context = createUpstreamContext(provider, operationName, upstreamStub);
|
|
805
|
+
const output = await materializeHandlerOutput(
|
|
806
|
+
await operation.handler(context, operation.fixtures.request),
|
|
807
|
+
);
|
|
808
|
+
const result = safeParseSchemaSync(
|
|
809
|
+
operation.output,
|
|
810
|
+
output,
|
|
811
|
+
`operations.${operationName}.handler.output`,
|
|
812
|
+
);
|
|
813
|
+
if (!result.success) {
|
|
814
|
+
throw new Error(
|
|
815
|
+
[
|
|
816
|
+
`Handler output for operation "${operationName}" failed schema validation.`,
|
|
817
|
+
formatJsonDiff(
|
|
818
|
+
{ valid: false, value: output, error: result.error },
|
|
819
|
+
{ valid: true, value: output },
|
|
820
|
+
),
|
|
821
|
+
].join("\n"),
|
|
822
|
+
);
|
|
823
|
+
}
|
|
824
|
+
return output;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
function isOptionsShortcut(value: unknown): value is StandardTestsOptions {
|
|
828
|
+
return (
|
|
829
|
+
value !== null &&
|
|
830
|
+
typeof value === "object" &&
|
|
831
|
+
!Array.isArray(value) &&
|
|
832
|
+
Object.hasOwn(value, "upstreamStub")
|
|
833
|
+
);
|
|
834
|
+
}
|
|
835
|
+
|
|
287
836
|
/**
|
|
288
837
|
* Run standard SDK tests for a provider in one line.
|
|
289
838
|
*
|
|
@@ -292,13 +841,39 @@ function parseSchemaFixture(
|
|
|
292
841
|
* import { runStandardTests } from "@apifuse/provider-sdk/testing";
|
|
293
842
|
* runStandardTests(myProvider, rawFixture, manifest, { snapshot: true });
|
|
294
843
|
*/
|
|
844
|
+
export function runStandardTests(
|
|
845
|
+
provider: ProviderDefinition,
|
|
846
|
+
options: StandardTestsOptions & { upstreamStub: StandardTestsUpstreamStub },
|
|
847
|
+
): StandardTestsResult;
|
|
295
848
|
export function runStandardTests(
|
|
296
849
|
provider: ProviderDefinition,
|
|
297
850
|
rawFixture?: unknown,
|
|
298
851
|
manifest?: StandardTestsManifest,
|
|
299
|
-
options
|
|
300
|
-
):
|
|
852
|
+
options?: StandardTestsOptions,
|
|
853
|
+
): StandardTestsResult;
|
|
854
|
+
export function runStandardTests(
|
|
855
|
+
provider: ProviderDefinition,
|
|
856
|
+
rawFixtureOrOptions?: unknown,
|
|
857
|
+
manifest?: StandardTestsManifest,
|
|
858
|
+
legacyOptions?: StandardTestsOptions,
|
|
859
|
+
): StandardTestsResult {
|
|
860
|
+
const shortcut =
|
|
861
|
+
manifest === undefined && legacyOptions === undefined && isOptionsShortcut(rawFixtureOrOptions);
|
|
862
|
+
const rawFixture = shortcut ? undefined : rawFixtureOrOptions;
|
|
863
|
+
const options = shortcut ? rawFixtureOrOptions : (legacyOptions ?? {});
|
|
301
864
|
const operations = Object.entries(provider.operations);
|
|
865
|
+
const warnings = options.upstreamStub
|
|
866
|
+
? operations
|
|
867
|
+
.filter(([, operation]) => operation.fixtures?.request === undefined)
|
|
868
|
+
.map(
|
|
869
|
+
([operationName]) =>
|
|
870
|
+
`[provider-sdk] Operation "${provider.id}.${operationName}" has no fixtures.request, so runStandardTests cannot invoke its handler E2E.`,
|
|
871
|
+
)
|
|
872
|
+
: operations.map(
|
|
873
|
+
([operationName]) =>
|
|
874
|
+
`[provider-sdk] Operation "${provider.id}.${operationName}" has no handler E2E coverage in runStandardTests; configure upstreamStub to invoke the real handler.`,
|
|
875
|
+
);
|
|
876
|
+
for (const warning of warnings) console.warn(warning);
|
|
302
877
|
|
|
303
878
|
const assertFixtureValidation = (): void => {
|
|
304
879
|
expect(rawFixture).toBeDefined();
|
|
@@ -421,7 +996,13 @@ export function runStandardTests(
|
|
|
421
996
|
const serialized = stableStringify(actual);
|
|
422
997
|
const snapshotFile = Bun.file(snapshotPath);
|
|
423
998
|
|
|
424
|
-
|
|
999
|
+
const snapshotExists = await snapshotFile.exists();
|
|
1000
|
+
if (!snapshotExists && options.requireSnapshot && !shouldUpdateSnapshots()) {
|
|
1001
|
+
throw new Error(
|
|
1002
|
+
`Required golden snapshot is missing: ${snapshotPath}. Regenerate it with bun test --update-snapshots.`,
|
|
1003
|
+
);
|
|
1004
|
+
}
|
|
1005
|
+
if (shouldUpdateSnapshots() || !snapshotExists) {
|
|
425
1006
|
await Bun.write(snapshotPath, serialized);
|
|
426
1007
|
}
|
|
427
1008
|
|
|
@@ -429,5 +1010,20 @@ export function runStandardTests(
|
|
|
429
1010
|
expect(actual).toEqual(expected);
|
|
430
1011
|
});
|
|
431
1012
|
}
|
|
1013
|
+
|
|
1014
|
+
if (options.upstreamStub) {
|
|
1015
|
+
for (const [operationName, operation] of operations) {
|
|
1016
|
+
if (operation.fixtures?.request === undefined) continue;
|
|
1017
|
+
it(`invokes the real ${operationName} handler with canned upstream responses`, async () => {
|
|
1018
|
+
await executeStandardTestHandler(
|
|
1019
|
+
provider,
|
|
1020
|
+
operationName,
|
|
1021
|
+
options.upstreamStub as StandardTestsUpstreamStub,
|
|
1022
|
+
);
|
|
1023
|
+
});
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
432
1026
|
});
|
|
1027
|
+
|
|
1028
|
+
return { warnings };
|
|
433
1029
|
}
|