@nikhil-qeas/api-core 0.6.0 → 0.8.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/CHANGELOG.md +67 -0
- package/README.md +216 -5
- package/bin/qe-api.js +3 -0
- package/dist/contracts/assertions.d.ts +11 -0
- package/dist/contracts/assertions.js +31 -0
- package/dist/contracts/openapi.d.ts +28 -1
- package/dist/contracts/openapi.js +113 -0
- package/dist/graphql/graphql.d.ts +86 -0
- package/dist/graphql/graphql.js +312 -0
- package/dist/http/api-client.d.ts +20 -0
- package/dist/http/api-client.js +70 -9
- package/dist/http/cookies.d.ts +32 -0
- package/dist/http/cookies.js +116 -0
- package/dist/http/multipart.d.ts +20 -0
- package/dist/http/multipart.js +48 -0
- package/dist/http/trace.d.ts +26 -0
- package/dist/http/trace.js +43 -0
- package/dist/http/types.d.ts +22 -0
- package/dist/index.d.ts +31 -5
- package/dist/index.js +16 -3
- package/dist/integrations/mocha.d.ts +32 -0
- package/dist/integrations/mocha.js +81 -0
- package/dist/reporting/html-report.d.ts +23 -0
- package/dist/reporting/html-report.js +118 -0
- package/dist/reporting/junit.d.ts +11 -2
- package/dist/reporting/junit.js +9 -3
- package/dist/reporting/redaction.d.ts +10 -0
- package/dist/reporting/redaction.js +36 -2
- package/dist/security/authorization-matrix.d.ts +55 -0
- package/dist/security/authorization-matrix.js +102 -0
- package/dist/security/headers.d.ts +21 -0
- package/dist/security/headers.js +45 -0
- package/dist/security/policy.js +3 -2
- package/dist/security/sensitive-data.d.ts +22 -0
- package/dist/security/sensitive-data.js +76 -0
- package/dist/testing/json-path.d.ts +6 -0
- package/dist/testing/json-path.js +97 -0
- package/dist/testing/load.d.ts +85 -0
- package/dist/testing/load.js +134 -0
- package/dist/testing/matchers.d.ts +63 -0
- package/dist/testing/matchers.js +164 -0
- package/dist/testing/spec-cases.d.ts +136 -0
- package/dist/testing/spec-cases.js +1065 -0
- package/dist/testing/wait-for.d.ts +40 -0
- package/dist/testing/wait-for.js +82 -0
- package/package.json +1 -1
- package/templates/project/README.md +80 -5
- package/templates/project/__dot__env.example +4 -0
- package/templates/project/__dot__gitlab-ci.yml +1 -0
- package/templates/project/openapi/openapi.json +476 -19
- package/templates/project/src/clients/api.ts +4 -2
- package/templates/project/src/environment.ts +8 -0
- package/templates/project/src/observability.ts +15 -1
- package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
- package/templates/project/tests/performance/health.spec.ts +22 -0
- package/templates/project/tests/security/authentication.spec.ts +3 -1
- package/templates/project/tests/security/authorization.spec.ts +29 -0
- package/templates/project/tests/security/hygiene.spec.ts +37 -0
- package/templates/project/tests/security/spec-cases.spec.ts +61 -0
- package/templates/project/tests/security/write-protection.spec.ts +2 -2
- package/templates/project/tests/setup/hooks.ts +32 -5
- package/templates/project/tests/smoke/health.spec.ts +3 -3
- package/templates/project/tests/smoke/tracing.spec.ts +48 -0
- package/templates/project/tests/support/approved-writes.ts +27 -0
- package/templates/project/tests/support/identities.ts +24 -0
- package/templates/project/tests/support/mock-api.ts +166 -3
package/dist/http/api-client.js
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { CookieJar } from './cookies.js';
|
|
3
|
+
import { encodeMultipart } from './multipart.js';
|
|
2
4
|
import { backoffDelay, resolveRetryPolicy, retryDelay } from './retry.js';
|
|
5
|
+
import { formatTraceparent, isTraceId, newSpanId, newTraceId, parseTraceparent } from './trace.js';
|
|
3
6
|
export class ApiTransportError extends Error {
|
|
4
7
|
kind;
|
|
5
8
|
constructor(message, kind, options) {
|
|
@@ -55,16 +58,27 @@ function retryAllowed(method, idempotent) {
|
|
|
55
58
|
return ['GET', 'HEAD', 'OPTIONS'].includes(method) || idempotent;
|
|
56
59
|
}
|
|
57
60
|
function shouldRetryStatus(status) { return [408, 429, 502, 503, 504].includes(status); }
|
|
61
|
+
const textEncoder = new TextEncoder();
|
|
62
|
+
const textDecoder = new TextDecoder();
|
|
58
63
|
function hasHeader(headers, name) {
|
|
59
64
|
const wanted = name.toLowerCase();
|
|
60
65
|
return Object.keys(headers).some(key => key.toLowerCase() === wanted);
|
|
61
66
|
}
|
|
67
|
+
function headerValue(headers, name) {
|
|
68
|
+
const wanted = name.toLowerCase();
|
|
69
|
+
const key = Object.keys(headers).find(candidate => candidate.toLowerCase() === wanted);
|
|
70
|
+
return key === undefined ? undefined : headers[key];
|
|
71
|
+
}
|
|
72
|
+
const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
|
|
73
|
+
const BAD_TRACE_ID = 'A trace id is 32 lowercase hex digits and not all zeros';
|
|
62
74
|
/** Browserless, dependency-light HTTP engine. Keeps signed request bytes identical to transmitted bytes. */
|
|
63
75
|
export class ApiClient {
|
|
64
76
|
cfg;
|
|
65
77
|
url;
|
|
66
78
|
fetcher;
|
|
67
79
|
retryPolicy;
|
|
80
|
+
/** The cookie jar, when `cookies` is enabled. */
|
|
81
|
+
cookies;
|
|
68
82
|
constructor(cfg) {
|
|
69
83
|
this.cfg = cfg;
|
|
70
84
|
this.url = new URL(cfg.baseUrl.endsWith('/') ? cfg.baseUrl : `${cfg.baseUrl}/`);
|
|
@@ -72,13 +86,41 @@ export class ApiClient {
|
|
|
72
86
|
throw new Error('Clean HTTP(S) baseUrl required');
|
|
73
87
|
this.fetcher = cfg.fetchImpl ?? fetch;
|
|
74
88
|
this.retryPolicy = resolveRetryPolicy(cfg);
|
|
89
|
+
this.cookies = cfg.cookies === true ? new CookieJar() : cfg.cookies === false ? undefined : cfg.cookies;
|
|
90
|
+
if (cfg.requestIdHeader !== undefined && !HEADER_NAME.test(cfg.requestIdHeader))
|
|
91
|
+
throw new Error('requestIdHeader is not a valid header name');
|
|
92
|
+
if (typeof cfg.trace === 'object' && typeof cfg.trace.traceId === 'string' && !isTraceId(cfg.trace.traceId))
|
|
93
|
+
throw new Error(BAD_TRACE_ID);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* The trace a request joins, and how each attempt announces it. A `traceparent` header the caller set always wins (it is sent as
|
|
97
|
+
* it is, so a deliberately malformed one works for negative tests) and only supplies the trace id reported back.
|
|
98
|
+
*/
|
|
99
|
+
traceFor(req, callerTraceparent) {
|
|
100
|
+
if (callerTraceparent !== undefined)
|
|
101
|
+
return { traceId: parseTraceparent(callerTraceparent)?.traceId, traceparent: undefined };
|
|
102
|
+
if (req.traceId === undefined && !this.cfg.trace)
|
|
103
|
+
return { traceId: undefined, traceparent: undefined };
|
|
104
|
+
const config = typeof this.cfg.trace === 'object' ? this.cfg.trace : undefined;
|
|
105
|
+
const configured = typeof config?.traceId === 'function' ? config.traceId() : config?.traceId;
|
|
106
|
+
const chosen = req.traceId ?? configured;
|
|
107
|
+
if (chosen !== undefined && !isTraceId(chosen))
|
|
108
|
+
throw new Error(BAD_TRACE_ID);
|
|
109
|
+
const traceId = chosen ?? newTraceId();
|
|
110
|
+
const sampled = config?.sampled !== false;
|
|
111
|
+
return { traceId, traceparent: () => formatTraceparent(traceId, newSpanId(), sampled) };
|
|
75
112
|
}
|
|
76
113
|
async request(req) {
|
|
77
114
|
assertPath(req.path);
|
|
78
|
-
const bodyKinds = [req.json !== undefined, req.form !== undefined, req.rawBody !== undefined].filter(Boolean).length;
|
|
115
|
+
const bodyKinds = [req.json !== undefined, req.form !== undefined, req.rawBody !== undefined, req.multipart !== undefined].filter(Boolean).length;
|
|
79
116
|
if (bodyKinds > 1)
|
|
80
117
|
throw new Error('Supply only one body representation');
|
|
118
|
+
const multipart = req.multipart === undefined ? undefined : encodeMultipart(req.multipart);
|
|
119
|
+
if (multipart && hasHeader({ ...this.cfg.defaultHeaders, ...req.headers }, 'content-type'))
|
|
120
|
+
throw new Error('A multipart body sets its own Content-Type, boundary included: do not supply one');
|
|
81
121
|
const raw = req.rawBody ?? (req.form ? encodeForm(req.form) : (req.json === undefined ? '' : JSON.stringify(req.json)));
|
|
122
|
+
const payload = multipart?.body ?? raw;
|
|
123
|
+
const payloadBytes = typeof payload === 'string' ? textEncoder.encode(payload) : payload;
|
|
82
124
|
const url = new URL(this.url.href);
|
|
83
125
|
url.pathname = `${this.url.pathname.replace(/\/$/, '')}${req.path}`;
|
|
84
126
|
for (const [key, value] of Object.entries(req.query ?? {})) {
|
|
@@ -90,6 +132,8 @@ export class ApiClient {
|
|
|
90
132
|
const canRetry = retryAllowed(req.method, req.idempotent === true);
|
|
91
133
|
const retryCount = canRetry ? Math.min(Math.max(0, req.retry ?? this.cfg.maxSafeRetries ?? 1), 5) : 0;
|
|
92
134
|
const requestId = randomUUID();
|
|
135
|
+
const trace = this.traceFor(req, headerValue({ ...this.cfg.defaultHeaders, ...req.headers }, 'traceparent')); // before anything is sent: a bad trace id fails the request
|
|
136
|
+
const traceMarker = trace.traceId === undefined ? {} : { traceId: trace.traceId };
|
|
93
137
|
const started = performance.now();
|
|
94
138
|
const auth = this.cfg.auth;
|
|
95
139
|
const authHeader = auth?.header ?? 'Authorization';
|
|
@@ -98,7 +142,7 @@ export class ApiClient {
|
|
|
98
142
|
const policy = this.retryPolicy;
|
|
99
143
|
// Reports an attempt that is followed by another one, so retries are visible instead of hidden inside `attempts`.
|
|
100
144
|
const emitRetry = (attempt, attemptStarted, reason, retryInMs, extra) => {
|
|
101
|
-
this.cfg.onEvent?.({ kind: 'retry', method: req.method, path: req.path, durationMs: Math.round(performance.now() - attemptStarted), attempts: attempt, requestId, reason, retryInMs, ...extra });
|
|
145
|
+
this.cfg.onEvent?.({ kind: 'retry', method: req.method, path: req.path, durationMs: Math.round(performance.now() - attemptStarted), attempts: attempt, requestId, reason, retryInMs, ...traceMarker, ...extra });
|
|
102
146
|
};
|
|
103
147
|
for (let attempt = 1;; attempt++) {
|
|
104
148
|
const attemptStarted = performance.now();
|
|
@@ -108,19 +152,30 @@ export class ApiClient {
|
|
|
108
152
|
headers['Content-Type'] = 'application/json';
|
|
109
153
|
else if (!hasContentType && req.form !== undefined)
|
|
110
154
|
headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
155
|
+
if (multipart)
|
|
156
|
+
headers['Content-Type'] = multipart.contentType;
|
|
157
|
+
// Cookies the server set earlier go back with this request, unless the caller chose its own Cookie header or opted out.
|
|
158
|
+
const cookie = this.cookies !== undefined && req.skipCookies !== true && !hasHeader(headers, 'cookie') ? this.cookies.header(url) : undefined;
|
|
159
|
+
if (cookie !== undefined)
|
|
160
|
+
headers.Cookie = cookie;
|
|
111
161
|
// A header the caller set explicitly (e.g. a deliberately bad token) is never replaced or renewed.
|
|
112
162
|
let usedToken;
|
|
113
163
|
if (auth && req.skipAuth !== true && !hasHeader(headers, authHeader)) {
|
|
114
164
|
usedToken = (await auth.tokens.tokens()).accessToken;
|
|
115
165
|
headers[authHeader] = auth.scheme === '' ? usedToken : `${auth.scheme ?? 'Bearer'} ${usedToken}`;
|
|
116
166
|
}
|
|
167
|
+
// Each attempt is its own span of the same trace; the request id stays the same across attempts.
|
|
168
|
+
if (trace.traceparent !== undefined)
|
|
169
|
+
headers.traceparent = trace.traceparent();
|
|
170
|
+
if (this.cfg.requestIdHeader !== undefined && !hasHeader(headers, this.cfg.requestIdHeader))
|
|
171
|
+
headers[this.cfg.requestIdHeader] = requestId;
|
|
117
172
|
// Signature is regenerated each attempt; pass the exact body bytes, never a reserialized object.
|
|
118
|
-
Object.assign(headers, await this.cfg.signer?.({ method: req.method, path: req.path, exactBody:
|
|
173
|
+
Object.assign(headers, await this.cfg.signer?.({ method: req.method, path: req.path, exactBody: typeof payload === 'string' ? payload : textDecoder.decode(payload), exactBodyBytes: payloadBytes, requestId, attempt }));
|
|
119
174
|
const timeoutMs = req.timeoutMs ?? this.cfg.timeoutMs ?? 15_000;
|
|
120
175
|
let response;
|
|
121
176
|
try {
|
|
122
177
|
response = await this.fetcher(url, {
|
|
123
|
-
method: req.method, headers, ...(
|
|
178
|
+
method: req.method, headers, ...(payloadBytes.length ? { body: payload } : {}),
|
|
124
179
|
redirect: req.followRedirects ? 'follow' : 'manual', signal: AbortSignal.timeout(timeoutMs),
|
|
125
180
|
});
|
|
126
181
|
}
|
|
@@ -133,17 +188,23 @@ export class ApiClient {
|
|
|
133
188
|
await policy.clock.sleep(wait);
|
|
134
189
|
continue;
|
|
135
190
|
}
|
|
136
|
-
this.cfg.onEvent?.({ kind: 'network-error', method: req.method, path: req.path, error: isTimeout ? 'timeout' : 'network', durationMs: Math.round(performance.now() - started), attempts: attempt, requestId });
|
|
191
|
+
this.cfg.onEvent?.({ kind: 'network-error', method: req.method, path: req.path, error: isTimeout ? 'timeout' : 'network', durationMs: Math.round(performance.now() - started), attempts: attempt, requestId, ...traceMarker });
|
|
137
192
|
throw new ApiTransportError(`${req.method} ${req.path} ${isTimeout ? 'timed out' : 'failed to connect'}`, isTimeout ? 'timeout' : 'network');
|
|
138
193
|
}
|
|
139
194
|
{
|
|
140
|
-
let text;
|
|
195
|
+
let text = '';
|
|
196
|
+
let bytes;
|
|
141
197
|
try {
|
|
142
|
-
|
|
198
|
+
if (req.responseType === 'binary')
|
|
199
|
+
bytes = new Uint8Array(await response.arrayBuffer());
|
|
200
|
+
else
|
|
201
|
+
text = await response.text();
|
|
143
202
|
}
|
|
144
203
|
catch {
|
|
145
204
|
throw new ApiTransportError(`${req.method} ${req.path} response read failed`, 'network');
|
|
146
205
|
}
|
|
206
|
+
if (this.cookies !== undefined && req.skipCookies !== true)
|
|
207
|
+
this.cookies.store(response.headers.getSetCookie(), url);
|
|
147
208
|
if (response.status === 401 && auth && usedToken !== undefined && !reauthenticated && auth.refreshOnUnauthorized !== false) {
|
|
148
209
|
// The server rejected the token we sent. Tell the cache which one, so a burst of 401s renews once.
|
|
149
210
|
auth.tokens.invalidate(usedToken);
|
|
@@ -163,8 +224,8 @@ export class ApiClient {
|
|
|
163
224
|
}
|
|
164
225
|
const elapsed = Math.round(performance.now() - started);
|
|
165
226
|
const marker = reauthenticated ? { reauthenticated: true } : {};
|
|
166
|
-
this.cfg.onEvent?.({ kind: 'success', method: req.method, path: req.path, status: response.status, durationMs: elapsed, attempts: attempt, requestId, ...marker });
|
|
167
|
-
return { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers), body: parse(text, response.headers.get('content-type')), text, durationMs: elapsed, attempts: attempt, requestId, ...marker };
|
|
227
|
+
this.cfg.onEvent?.({ kind: 'success', method: req.method, path: req.path, status: response.status, durationMs: elapsed, attempts: attempt, requestId, ...traceMarker, ...marker });
|
|
228
|
+
return { status: response.status, statusText: response.statusText, headers: Object.fromEntries(response.headers), body: (bytes ?? parse(text, response.headers.get('content-type'))), text, durationMs: elapsed, attempts: attempt, requestId, ...traceMarker, ...marker };
|
|
168
229
|
}
|
|
169
230
|
}
|
|
170
231
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface CookieSetOptions {
|
|
2
|
+
/** Default '/'. */
|
|
3
|
+
path?: string | undefined;
|
|
4
|
+
/** Only sent over https. Default false. */
|
|
5
|
+
secure?: boolean | undefined;
|
|
6
|
+
/** Epoch milliseconds after which the cookie is no longer sent. Default: never. */
|
|
7
|
+
expiresAt?: number | undefined;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* A minimal cookie jar for a client that talks to one origin: it keeps the cookies the server sets and sends them back on matching
|
|
11
|
+
* requests. Path, Secure, Max-Age/Expires and Domain-must-match are honored; SameSite and HttpOnly are browser concerns and are ignored.
|
|
12
|
+
* Cookie values are credentials: the client never puts them in events or error messages.
|
|
13
|
+
*/
|
|
14
|
+
export declare class CookieJar {
|
|
15
|
+
private readonly now;
|
|
16
|
+
private readonly cookies;
|
|
17
|
+
private counter;
|
|
18
|
+
constructor(now?: () => number);
|
|
19
|
+
/** Records the Set-Cookie headers of a response to `url`. An expired or zero Max-Age cookie deletes the one it names. */
|
|
20
|
+
store(setCookie: readonly string[], url: URL): void;
|
|
21
|
+
/** The Cookie header for a request to `url`, or undefined when no cookie applies. Longer paths come first. */
|
|
22
|
+
header(url: URL): string | undefined;
|
|
23
|
+
/** The value of the first unexpired cookie with this name. */
|
|
24
|
+
get(name: string): string | undefined;
|
|
25
|
+
/** Sets a cookie directly, for tests that start from a known session (or a tampered one). */
|
|
26
|
+
set(name: string, value: string, options?: CookieSetOptions): void;
|
|
27
|
+
delete(name: string): void;
|
|
28
|
+
clear(): void;
|
|
29
|
+
/** Names only: values are credentials, so they are never listed. */
|
|
30
|
+
names(): string[];
|
|
31
|
+
get size(): number;
|
|
32
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
const MAX_COOKIES = 100;
|
|
2
|
+
const MAX_VALUE_LENGTH = 4096;
|
|
3
|
+
const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
4
|
+
/** True for ASCII control characters (and DEL), which a cookie value must not contain. */
|
|
5
|
+
function hasControlCharacter(value) {
|
|
6
|
+
for (let index = 0; index < value.length; index++) {
|
|
7
|
+
const code = value.charCodeAt(index);
|
|
8
|
+
if (code < 0x20 || code === 0x7f)
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
function defaultPath(url) {
|
|
14
|
+
const path = url.pathname;
|
|
15
|
+
const last = path.lastIndexOf('/');
|
|
16
|
+
return path.startsWith('/') && last > 0 ? path.slice(0, last) : '/';
|
|
17
|
+
}
|
|
18
|
+
function pathMatches(requestPath, cookiePath) {
|
|
19
|
+
if (requestPath === cookiePath)
|
|
20
|
+
return true;
|
|
21
|
+
return requestPath.startsWith(cookiePath) && (cookiePath.endsWith('/') || requestPath[cookiePath.length] === '/');
|
|
22
|
+
}
|
|
23
|
+
/** Parses one Set-Cookie header. Undefined for a cookie that must be ignored (malformed, or meant for another host). */
|
|
24
|
+
function parseSetCookie(header, url, now) {
|
|
25
|
+
const [pair = '', ...attributes] = header.split(';');
|
|
26
|
+
const equals = pair.indexOf('=');
|
|
27
|
+
if (equals <= 0)
|
|
28
|
+
return undefined;
|
|
29
|
+
const name = pair.slice(0, equals).trim();
|
|
30
|
+
const value = pair.slice(equals + 1).trim();
|
|
31
|
+
if (!COOKIE_NAME.test(name) || hasControlCharacter(value) || value.length > MAX_VALUE_LENGTH)
|
|
32
|
+
return undefined;
|
|
33
|
+
let path;
|
|
34
|
+
let secure = false;
|
|
35
|
+
let maxAge;
|
|
36
|
+
let expires;
|
|
37
|
+
let domain;
|
|
38
|
+
for (const attribute of attributes) {
|
|
39
|
+
const separator = attribute.indexOf('=');
|
|
40
|
+
const key = (separator < 0 ? attribute : attribute.slice(0, separator)).trim().toLowerCase();
|
|
41
|
+
const raw = separator < 0 ? '' : attribute.slice(separator + 1).trim();
|
|
42
|
+
if (key === 'path' && raw.startsWith('/'))
|
|
43
|
+
path = raw;
|
|
44
|
+
else if (key === 'secure')
|
|
45
|
+
secure = true;
|
|
46
|
+
else if (key === 'max-age' && /^-?\d+$/.test(raw))
|
|
47
|
+
maxAge = Number(raw);
|
|
48
|
+
else if (key === 'expires' && !Number.isNaN(Date.parse(raw)))
|
|
49
|
+
expires = Date.parse(raw);
|
|
50
|
+
else if (key === 'domain')
|
|
51
|
+
domain = raw.replace(/^\./, '').toLowerCase();
|
|
52
|
+
}
|
|
53
|
+
if (domain !== undefined) {
|
|
54
|
+
const host = url.hostname.toLowerCase();
|
|
55
|
+
if (host !== domain && !host.endsWith(`.${domain}`))
|
|
56
|
+
return undefined; // a cookie for another site is not ours to keep
|
|
57
|
+
}
|
|
58
|
+
return { name, value, path: path ?? defaultPath(url), secure, expiresAt: maxAge !== undefined ? now + maxAge * 1000 : expires };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* A minimal cookie jar for a client that talks to one origin: it keeps the cookies the server sets and sends them back on matching
|
|
62
|
+
* requests. Path, Secure, Max-Age/Expires and Domain-must-match are honored; SameSite and HttpOnly are browser concerns and are ignored.
|
|
63
|
+
* Cookie values are credentials: the client never puts them in events or error messages.
|
|
64
|
+
*/
|
|
65
|
+
export class CookieJar {
|
|
66
|
+
now;
|
|
67
|
+
cookies = new Map();
|
|
68
|
+
counter = 0;
|
|
69
|
+
constructor(now = Date.now) {
|
|
70
|
+
this.now = now;
|
|
71
|
+
}
|
|
72
|
+
/** Records the Set-Cookie headers of a response to `url`. An expired or zero Max-Age cookie deletes the one it names. */
|
|
73
|
+
store(setCookie, url) {
|
|
74
|
+
for (const header of setCookie) {
|
|
75
|
+
const cookie = parseSetCookie(header, url, this.now());
|
|
76
|
+
if (!cookie)
|
|
77
|
+
continue;
|
|
78
|
+
const key = `${cookie.name}|${cookie.path}`;
|
|
79
|
+
if (cookie.expiresAt !== undefined && cookie.expiresAt <= this.now()) {
|
|
80
|
+
this.cookies.delete(key);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!this.cookies.has(key) && this.cookies.size >= MAX_COOKIES)
|
|
84
|
+
continue;
|
|
85
|
+
this.cookies.set(key, { ...cookie, order: this.cookies.get(key)?.order ?? this.counter++ });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
/** The Cookie header for a request to `url`, or undefined when no cookie applies. Longer paths come first. */
|
|
89
|
+
header(url) {
|
|
90
|
+
const now = this.now();
|
|
91
|
+
const eligible = [...this.cookies.values()].filter(cookie => (cookie.expiresAt === undefined || cookie.expiresAt > now) && (!cookie.secure || url.protocol === 'https:') && pathMatches(url.pathname, cookie.path));
|
|
92
|
+
eligible.sort((a, b) => b.path.length - a.path.length || a.order - b.order);
|
|
93
|
+
return eligible.length ? eligible.map(cookie => `${cookie.name}=${cookie.value}`).join('; ') : undefined;
|
|
94
|
+
}
|
|
95
|
+
/** The value of the first unexpired cookie with this name. */
|
|
96
|
+
get(name) {
|
|
97
|
+
const now = this.now();
|
|
98
|
+
return [...this.cookies.values()].find(cookie => cookie.name === name && (cookie.expiresAt === undefined || cookie.expiresAt > now))?.value;
|
|
99
|
+
}
|
|
100
|
+
/** Sets a cookie directly, for tests that start from a known session (or a tampered one). */
|
|
101
|
+
set(name, value, options = {}) {
|
|
102
|
+
if (!COOKIE_NAME.test(name) || hasControlCharacter(value) || value.includes(';'))
|
|
103
|
+
throw new Error('Invalid cookie name or value');
|
|
104
|
+
const path = options.path ?? '/';
|
|
105
|
+
this.cookies.set(`${name}|${path}`, { name, value, path, secure: options.secure === true, expiresAt: options.expiresAt, order: this.counter++ });
|
|
106
|
+
}
|
|
107
|
+
delete(name) {
|
|
108
|
+
for (const [key, cookie] of this.cookies)
|
|
109
|
+
if (cookie.name === name)
|
|
110
|
+
this.cookies.delete(key);
|
|
111
|
+
}
|
|
112
|
+
clear() { this.cookies.clear(); }
|
|
113
|
+
/** Names only: values are credentials, so they are never listed. */
|
|
114
|
+
names() { return [...new Set([...this.cookies.values()].map(cookie => cookie.name))]; }
|
|
115
|
+
get size() { return this.cookies.size; }
|
|
116
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** A text field, or a file with its bytes (a string is sent as UTF-8). */
|
|
2
|
+
export type MultipartPart = {
|
|
3
|
+
name: string;
|
|
4
|
+
value: string;
|
|
5
|
+
} | {
|
|
6
|
+
name: string;
|
|
7
|
+
filename: string;
|
|
8
|
+
data: string | Uint8Array;
|
|
9
|
+
contentType?: string;
|
|
10
|
+
};
|
|
11
|
+
export interface EncodedMultipart {
|
|
12
|
+
body: Uint8Array<ArrayBuffer>;
|
|
13
|
+
/** `multipart/form-data; boundary=...`, the Content-Type the request must carry. */
|
|
14
|
+
contentType: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Encodes a multipart/form-data body. The boundary is random and chosen so that it appears nowhere in the data. The result is
|
|
18
|
+
* one fixed byte sequence: a retry or a signature sees exactly the bytes that are sent.
|
|
19
|
+
*/
|
|
20
|
+
export declare function encodeMultipart(parts: ReadonlyArray<MultipartPart>): EncodedMultipart;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
/** Escapes a name or filename for a Content-Disposition parameter the way browsers do: quotes and line breaks become %22, %0D, %0A. */
|
|
4
|
+
function quoted(value, what) {
|
|
5
|
+
if (value.length === 0)
|
|
6
|
+
throw new Error(`Multipart ${what} must not be empty`);
|
|
7
|
+
if (value.includes('\u0000'))
|
|
8
|
+
throw new Error(`Multipart ${what} must not contain a null character`);
|
|
9
|
+
return value.replace(/\r/g, '%0D').replace(/\n/g, '%0A').replace(/"/g, '%22');
|
|
10
|
+
}
|
|
11
|
+
function bytesOf(data) { return typeof data === 'string' ? encoder.encode(data) : data; }
|
|
12
|
+
function contains(haystack, needle) {
|
|
13
|
+
return Buffer.from(haystack.buffer, haystack.byteOffset, haystack.byteLength).includes(needle);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Encodes a multipart/form-data body. The boundary is random and chosen so that it appears nowhere in the data. The result is
|
|
17
|
+
* one fixed byte sequence: a retry or a signature sees exactly the bytes that are sent.
|
|
18
|
+
*/
|
|
19
|
+
export function encodeMultipart(parts) {
|
|
20
|
+
const contents = parts.map(part => ('value' in part ? encoder.encode(part.value) : bytesOf(part.data)));
|
|
21
|
+
let boundary = '';
|
|
22
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
23
|
+
boundary = `qe-${randomUUID().replace(/-/g, '')}`;
|
|
24
|
+
if (!contents.some(content => contains(content, boundary)))
|
|
25
|
+
break;
|
|
26
|
+
if (attempt === 4)
|
|
27
|
+
throw new Error('Could not find a multipart boundary that is absent from the data');
|
|
28
|
+
}
|
|
29
|
+
const chunks = [];
|
|
30
|
+
parts.forEach((part, index) => {
|
|
31
|
+
let header = `--${boundary}\r\nContent-Disposition: form-data; name="${quoted(part.name, 'field name')}"`;
|
|
32
|
+
if ('filename' in part) {
|
|
33
|
+
const contentType = part.contentType ?? 'application/octet-stream';
|
|
34
|
+
if (/[\r\n]/.test(contentType) || contentType.includes('\u0000'))
|
|
35
|
+
throw new Error('Multipart contentType must not contain line breaks');
|
|
36
|
+
header += `; filename="${quoted(part.filename, 'filename')}"\r\nContent-Type: ${contentType}`;
|
|
37
|
+
}
|
|
38
|
+
chunks.push(encoder.encode(`${header}\r\n\r\n`), contents[index] ?? new Uint8Array(0), encoder.encode('\r\n'));
|
|
39
|
+
});
|
|
40
|
+
chunks.push(encoder.encode(`--${boundary}--\r\n`));
|
|
41
|
+
const body = new Uint8Array(chunks.reduce((total, chunk) => total + chunk.byteLength, 0));
|
|
42
|
+
let offset = 0;
|
|
43
|
+
for (const chunk of chunks) {
|
|
44
|
+
body.set(chunk, offset);
|
|
45
|
+
offset += chunk.byteLength;
|
|
46
|
+
}
|
|
47
|
+
return { body, contentType: `multipart/form-data; boundary=${boundary}` };
|
|
48
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Join requests to a trace the server side can show (W3C Trace Context). */
|
|
2
|
+
export interface TraceConfig {
|
|
3
|
+
/**
|
|
4
|
+
* The trace every request joins: 32 lowercase hex digits, not all zeros. A function is called for each request, for example to
|
|
5
|
+
* return the id of the running test so that all its requests land in one trace; when it returns undefined the request gets a new
|
|
6
|
+
* trace. Default: a new trace for every request.
|
|
7
|
+
*/
|
|
8
|
+
traceId?: string | (() => string | undefined) | undefined;
|
|
9
|
+
/** Ask the server side to record the trace (the `sampled` flag). Default true: test traffic is worth keeping. */
|
|
10
|
+
sampled?: boolean | undefined;
|
|
11
|
+
}
|
|
12
|
+
export interface ParsedTraceparent {
|
|
13
|
+
traceId: string;
|
|
14
|
+
spanId: string;
|
|
15
|
+
sampled: boolean;
|
|
16
|
+
}
|
|
17
|
+
/** True for a trace id the W3C format allows: 32 lowercase hex digits that are not all zeros. */
|
|
18
|
+
export declare function isTraceId(value: unknown): value is string;
|
|
19
|
+
/** A new random trace id. */
|
|
20
|
+
export declare function newTraceId(): string;
|
|
21
|
+
/** A new random span id: one per attempt, so a retried request shows as separate spans of one trace. */
|
|
22
|
+
export declare function newSpanId(): string;
|
|
23
|
+
/** The `traceparent` header value. Throws for an id the format does not allow, because a server would silently ignore it. */
|
|
24
|
+
export declare function formatTraceparent(traceId: string, spanId: string, sampled?: boolean): string;
|
|
25
|
+
/** Reads a `traceparent` header value (version 00). Undefined for anything that is not exactly that format. */
|
|
26
|
+
export declare function parseTraceparent(header: string): ParsedTraceparent | undefined;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
const TRACE_ID = /^[0-9a-f]{32}$/;
|
|
3
|
+
const SPAN_ID = /^[0-9a-f]{16}$/;
|
|
4
|
+
const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
|
|
5
|
+
const NO_TRACE = '0'.repeat(32);
|
|
6
|
+
const NO_SPAN = '0'.repeat(16);
|
|
7
|
+
/** True for a trace id the W3C format allows: 32 lowercase hex digits that are not all zeros. */
|
|
8
|
+
export function isTraceId(value) { return typeof value === 'string' && TRACE_ID.test(value) && value !== NO_TRACE; }
|
|
9
|
+
function isSpanId(value) { return typeof value === 'string' && SPAN_ID.test(value) && value !== NO_SPAN; }
|
|
10
|
+
/** A new random trace id. */
|
|
11
|
+
export function newTraceId() {
|
|
12
|
+
let id;
|
|
13
|
+
do {
|
|
14
|
+
id = randomBytes(16).toString('hex');
|
|
15
|
+
} while (id === NO_TRACE);
|
|
16
|
+
return id;
|
|
17
|
+
}
|
|
18
|
+
/** A new random span id: one per attempt, so a retried request shows as separate spans of one trace. */
|
|
19
|
+
export function newSpanId() {
|
|
20
|
+
let id;
|
|
21
|
+
do {
|
|
22
|
+
id = randomBytes(8).toString('hex');
|
|
23
|
+
} while (id === NO_SPAN);
|
|
24
|
+
return id;
|
|
25
|
+
}
|
|
26
|
+
/** The `traceparent` header value. Throws for an id the format does not allow, because a server would silently ignore it. */
|
|
27
|
+
export function formatTraceparent(traceId, spanId, sampled = true) {
|
|
28
|
+
if (!isTraceId(traceId))
|
|
29
|
+
throw new Error('A trace id is 32 lowercase hex digits and not all zeros');
|
|
30
|
+
if (!isSpanId(spanId))
|
|
31
|
+
throw new Error('A span id is 16 lowercase hex digits and not all zeros');
|
|
32
|
+
return `00-${traceId}-${spanId}-${sampled ? '01' : '00'}`;
|
|
33
|
+
}
|
|
34
|
+
/** Reads a `traceparent` header value (version 00). Undefined for anything that is not exactly that format. */
|
|
35
|
+
export function parseTraceparent(header) {
|
|
36
|
+
const match = TRACEPARENT.exec(header);
|
|
37
|
+
if (!match)
|
|
38
|
+
return undefined;
|
|
39
|
+
const [, traceId, spanId, flags] = match;
|
|
40
|
+
if (!isTraceId(traceId) || !isSpanId(spanId) || flags === undefined)
|
|
41
|
+
return undefined;
|
|
42
|
+
return { traceId, spanId, sampled: (Number.parseInt(flags, 16) & 1) === 1 };
|
|
43
|
+
}
|
package/dist/http/types.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { MultipartPart } from './multipart.js';
|
|
1
2
|
export type Method = 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
2
3
|
export type Query = Record<string, string | number | boolean | readonly (string | number | boolean)[] | undefined>;
|
|
3
4
|
export interface ApiRequest {
|
|
@@ -8,13 +9,27 @@ export interface ApiRequest {
|
|
|
8
9
|
json?: unknown;
|
|
9
10
|
form?: ReadonlyArray<readonly [string, string]>;
|
|
10
11
|
rawBody?: string;
|
|
12
|
+
/** A multipart/form-data body: text fields and files. The client sets the Content-Type, boundary included. */
|
|
13
|
+
multipart?: ReadonlyArray<MultipartPart>;
|
|
11
14
|
timeoutMs?: number;
|
|
12
15
|
/** Explicitly mark mutation safe to repeat; obtain server-side idempotency support first. */
|
|
13
16
|
idempotent?: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Declares that this POST changes nothing on the server (a GraphQL query, a search endpoint that takes a body), so a read-only
|
|
19
|
+
* execution policy lets it through. A claim, not a check: set it only when you are sure. Ignored for every method except POST,
|
|
20
|
+
* because PUT, PATCH and DELETE are writes by definition. `GraphQLClient` sets it for you, and only for documents it can prove are queries.
|
|
21
|
+
*/
|
|
22
|
+
readOnly?: boolean;
|
|
14
23
|
retry?: number;
|
|
15
24
|
followRedirects?: boolean;
|
|
16
25
|
/** Send this request without the client's configured `auth` (login, public endpoints, negative authentication tests). */
|
|
17
26
|
skipAuth?: boolean;
|
|
27
|
+
/** Send this request without the client's cookies, and do not keep the cookies it sets (negative session tests). */
|
|
28
|
+
skipCookies?: boolean;
|
|
29
|
+
/** Put this request in this trace (32 lowercase hex digits), overriding the client's `trace` setting, and send a `traceparent` header even when the client does not trace. A `traceparent` header you set yourself always wins. */
|
|
30
|
+
traceId?: string;
|
|
31
|
+
/** 'binary' returns the response body as a Uint8Array in `body` (downloads), with an empty `text`. Default: text, parsed as JSON when the content type says so. */
|
|
32
|
+
responseType?: 'auto' | 'binary';
|
|
18
33
|
}
|
|
19
34
|
export interface ApiResult<T = unknown> {
|
|
20
35
|
status: number;
|
|
@@ -27,11 +42,16 @@ export interface ApiResult<T = unknown> {
|
|
|
27
42
|
requestId: string;
|
|
28
43
|
/** Present and true when a 401 made the client renew its token and resend the request once. */
|
|
29
44
|
reauthenticated?: boolean;
|
|
45
|
+
/** The trace this request joined, when it was traced: search for it in the tracing backend to see what the server did. */
|
|
46
|
+
traceId?: string;
|
|
30
47
|
}
|
|
31
48
|
export interface RequestContext {
|
|
32
49
|
readonly method: Method;
|
|
33
50
|
readonly path: string;
|
|
51
|
+
/** The body as text. For a multipart or other binary body this is a lossy decoding: sign `exactBodyBytes`. */
|
|
34
52
|
readonly exactBody: string;
|
|
53
|
+
/** The exact bytes that are sent. */
|
|
54
|
+
readonly exactBodyBytes: Uint8Array;
|
|
35
55
|
readonly requestId: string;
|
|
36
56
|
readonly attempt: number;
|
|
37
57
|
}
|
|
@@ -47,6 +67,8 @@ export interface HttpEvent {
|
|
|
47
67
|
kind: 'success' | 'network-error' | 'retry';
|
|
48
68
|
error?: string;
|
|
49
69
|
reauthenticated?: boolean;
|
|
70
|
+
/** The trace the request joined, when it was traced. */
|
|
71
|
+
traceId?: string;
|
|
50
72
|
/** Only on 'retry' events: why another attempt follows. */
|
|
51
73
|
reason?: 'status' | 'network' | 'timeout' | 'reauthenticate';
|
|
52
74
|
/** Only on 'retry' events: how long the client waits before the next attempt, in ms. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
|
|
2
|
+
export { formatTraceparent, isTraceId, newSpanId, newTraceId, parseTraceparent } from './http/trace.js';
|
|
3
|
+
export type { ParsedTraceparent, TraceConfig } from './http/trace.js';
|
|
2
4
|
export type { ApiClientConfig, ApiAuth } from './http/api-client.js';
|
|
3
5
|
export { parseRetryAfter } from './http/retry.js';
|
|
4
6
|
export type { RetryConfig, ClientClock } from './http/retry.js';
|
|
@@ -7,10 +9,19 @@ export { TokenManager } from './auth/token-manager.js';
|
|
|
7
9
|
export type { Tokens, TokenProvider, TokenSource } from './auth/token-manager.js';
|
|
8
10
|
export { clientCredentialsProvider, refreshTokenProvider, OAuth2Error } from './auth/oauth2.js';
|
|
9
11
|
export type { OAuth2ClientOptions, OAuth2RefreshOptions, OAuth2EndpointOptions } from './auth/oauth2.js';
|
|
10
|
-
export { expectStatus, expectClientError, expectResponseTime, expectContract } from './contracts/assertions.js';
|
|
12
|
+
export { expectStatus, expectClientError, expectResponseTime, expectContract, expectBody, expectJsonPath, expectHeader } from './contracts/assertions.js';
|
|
13
|
+
export { match, matches, assertMatches, Matcher } from './testing/matchers.js';
|
|
14
|
+
export type { MatchOptions, MatchResult, MatchType } from './testing/matchers.js';
|
|
15
|
+
export { jsonPath } from './testing/json-path.js';
|
|
16
|
+
export { waitFor, WaitTimeoutError } from './testing/wait-for.js';
|
|
17
|
+
export type { WaitForOptions } from './testing/wait-for.js';
|
|
18
|
+
export { CookieJar } from './http/cookies.js';
|
|
19
|
+
export type { CookieSetOptions } from './http/cookies.js';
|
|
20
|
+
export { encodeMultipart } from './http/multipart.js';
|
|
21
|
+
export type { MultipartPart, EncodedMultipart } from './http/multipart.js';
|
|
11
22
|
export type { Validator } from './contracts/assertions.js';
|
|
12
23
|
export { requireEnv, envEnum } from './config/env.js';
|
|
13
|
-
export { redact } from './reporting/redaction.js';
|
|
24
|
+
export { redact, scrubText } from './reporting/redaction.js';
|
|
14
25
|
export { createRunId } from './testing/run-id.js';
|
|
15
26
|
export { validateSchema, assertSchema } from './contracts/schema.js';
|
|
16
27
|
export type { Schema, SchemaResult } from './contracts/schema.js';
|
|
@@ -18,23 +29,38 @@ export { loadProjectConfig } from './config/project-config.js';
|
|
|
18
29
|
export type { ProjectConfig } from './config/project-config.js';
|
|
19
30
|
export { TestDataFactory, TestCleanup } from './testing/data-factory.js';
|
|
20
31
|
export { Semaphore } from './testing/concurrency.js';
|
|
32
|
+
export { MAX_LOAD_CONCURRENCY, MAX_LOAD_REQUESTS, MAX_LOAD_WARMUP, expectLoad, runLoad, summarizeLoad } from './testing/load.js';
|
|
33
|
+
export type { LatencyStats, LoadLimits, LoadOptions, LoadReport } from './testing/load.js';
|
|
21
34
|
export { selectByTags } from './testing/tag-selection.js';
|
|
22
35
|
export { MetricsCollector } from './reporting/metrics.js';
|
|
23
36
|
export type { ApiMetrics } from './reporting/metrics.js';
|
|
24
37
|
export { writeJunit } from './reporting/junit.js';
|
|
25
|
-
export type { TestCaseResult } from './reporting/junit.js';
|
|
38
|
+
export type { JunitOptions, TestCaseResult } from './reporting/junit.js';
|
|
39
|
+
export { renderHtmlReport, writeHtmlReport } from './reporting/html-report.js';
|
|
40
|
+
export type { HtmlReportOptions } from './reporting/html-report.js';
|
|
26
41
|
export { OpenApiValidator } from './contracts/openapi.js';
|
|
27
|
-
export type { OpenApiDocument, JsonSchemaCompiler, ContractCheck, OpenApiValidatorOptions } from './contracts/openapi.js';
|
|
42
|
+
export type { OpenApiDocument, JsonSchemaCompiler, ContractCheck, RequestCheck, OpenApiValidatorOptions } from './contracts/openapi.js';
|
|
28
43
|
export { createAjvCompiler, createOpenApiValidator } from './contracts/ajv.js';
|
|
29
44
|
export type { AjvCompilerOptions } from './contracts/ajv.js';
|
|
30
45
|
export { ExecutionContext } from './testing/execution-context.js';
|
|
31
46
|
export type { ExecutionOptions } from './testing/execution-context.js';
|
|
32
47
|
export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
|
|
48
|
+
export { GraphQLClient, expectGraphQLError, expectGraphQLSuccess, operationKind, parseOperations } from './graphql/graphql.js';
|
|
49
|
+
export type { DocumentOperation, ExpectedGraphQLError, GraphQLAssertOptions, GraphQLClientOptions, GraphQLError, GraphQLRequest, GraphQLResult, GraphQLTransport, OperationKind } from './graphql/graphql.js';
|
|
33
50
|
export type { SecurityPolicy } from './security/policy.js';
|
|
34
51
|
export { attachSafeMetadata } from './reporting/allure-adapter.js';
|
|
35
52
|
export type { AllureWriter } from './reporting/allure-adapter.js';
|
|
36
|
-
export { MochaResultCollector } from './integrations/mocha.js';
|
|
53
|
+
export { MochaResultCollector, failedHooks, failureText } from './integrations/mocha.js';
|
|
54
|
+
export type { MochaTestLike } from './integrations/mocha.js';
|
|
37
55
|
export { CoverageRegistry } from './testing/coverage.js';
|
|
38
56
|
export type { CoverageRecord } from './testing/coverage.js';
|
|
57
|
+
export { OpenApiCases, assertCaseOutcome } from './testing/spec-cases.js';
|
|
58
|
+
export { AuthorizationMatrix } from './security/authorization-matrix.js';
|
|
59
|
+
export type { AuthorizationCell, AuthorizationReport, AuthorizationRule, AuthorizationSubject, AuthorizationMatrixOptions } from './security/authorization-matrix.js';
|
|
60
|
+
export { findSensitiveData, expectNoSensitiveData } from './security/sensitive-data.js';
|
|
61
|
+
export type { SensitiveFinding, SensitiveDataOptions } from './security/sensitive-data.js';
|
|
62
|
+
export { checkSecurityHeaders, expectSecurityHeaders } from './security/headers.js';
|
|
63
|
+
export type { HeaderFinding, SecurityHeaderOptions, Severity } from './security/headers.js';
|
|
64
|
+
export type { GeneratedCase, CaseKind, InjectedProperty, OperationInfo, OperationRef, OpenApiCasesOptions } from './testing/spec-cases.js';
|
|
39
65
|
export { OpenApiCoverage } from './testing/openapi-coverage.js';
|
|
40
66
|
export type { OpenApiCoverageOptions, OpenApiCoverageReport, OpenApiCoverageSnapshot, OperationCoverage, CoverageStat, CoverageThresholds } from './testing/openapi-coverage.js';
|
package/dist/index.js
CHANGED
|
@@ -1,23 +1,36 @@
|
|
|
1
1
|
export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
|
|
2
|
+
export { formatTraceparent, isTraceId, newSpanId, newTraceId, parseTraceparent } from './http/trace.js';
|
|
2
3
|
export { parseRetryAfter } from './http/retry.js';
|
|
3
4
|
export { TokenManager } from './auth/token-manager.js';
|
|
4
5
|
export { clientCredentialsProvider, refreshTokenProvider, OAuth2Error } from './auth/oauth2.js';
|
|
5
|
-
export { expectStatus, expectClientError, expectResponseTime, expectContract } from './contracts/assertions.js';
|
|
6
|
+
export { expectStatus, expectClientError, expectResponseTime, expectContract, expectBody, expectJsonPath, expectHeader } from './contracts/assertions.js';
|
|
7
|
+
export { match, matches, assertMatches, Matcher } from './testing/matchers.js';
|
|
8
|
+
export { jsonPath } from './testing/json-path.js';
|
|
9
|
+
export { waitFor, WaitTimeoutError } from './testing/wait-for.js';
|
|
10
|
+
export { CookieJar } from './http/cookies.js';
|
|
11
|
+
export { encodeMultipart } from './http/multipart.js';
|
|
6
12
|
export { requireEnv, envEnum } from './config/env.js';
|
|
7
|
-
export { redact } from './reporting/redaction.js';
|
|
13
|
+
export { redact, scrubText } from './reporting/redaction.js';
|
|
8
14
|
export { createRunId } from './testing/run-id.js';
|
|
9
15
|
export { validateSchema, assertSchema } from './contracts/schema.js';
|
|
10
16
|
export { loadProjectConfig } from './config/project-config.js';
|
|
11
17
|
export { TestDataFactory, TestCleanup } from './testing/data-factory.js';
|
|
12
18
|
export { Semaphore } from './testing/concurrency.js';
|
|
19
|
+
export { MAX_LOAD_CONCURRENCY, MAX_LOAD_REQUESTS, MAX_LOAD_WARMUP, expectLoad, runLoad, summarizeLoad } from './testing/load.js';
|
|
13
20
|
export { selectByTags } from './testing/tag-selection.js';
|
|
14
21
|
export { MetricsCollector } from './reporting/metrics.js';
|
|
15
22
|
export { writeJunit } from './reporting/junit.js';
|
|
23
|
+
export { renderHtmlReport, writeHtmlReport } from './reporting/html-report.js';
|
|
16
24
|
export { OpenApiValidator } from './contracts/openapi.js';
|
|
17
25
|
export { createAjvCompiler, createOpenApiValidator } from './contracts/ajv.js';
|
|
18
26
|
export { ExecutionContext } from './testing/execution-context.js';
|
|
19
27
|
export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
|
|
28
|
+
export { GraphQLClient, expectGraphQLError, expectGraphQLSuccess, operationKind, parseOperations } from './graphql/graphql.js';
|
|
20
29
|
export { attachSafeMetadata } from './reporting/allure-adapter.js';
|
|
21
|
-
export { MochaResultCollector } from './integrations/mocha.js';
|
|
30
|
+
export { MochaResultCollector, failedHooks, failureText } from './integrations/mocha.js';
|
|
22
31
|
export { CoverageRegistry } from './testing/coverage.js';
|
|
32
|
+
export { OpenApiCases, assertCaseOutcome } from './testing/spec-cases.js';
|
|
33
|
+
export { AuthorizationMatrix } from './security/authorization-matrix.js';
|
|
34
|
+
export { findSensitiveData, expectNoSensitiveData } from './security/sensitive-data.js';
|
|
35
|
+
export { checkSecurityHeaders, expectSecurityHeaders } from './security/headers.js';
|
|
23
36
|
export { OpenApiCoverage } from './testing/openapi-coverage.js';
|