@nikhil-qeas/api-core 0.4.2 → 0.5.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 +57 -0
- package/README.md +133 -16
- package/bin/qe-api.js +99 -26
- package/dist/auth/oauth2.d.ts +40 -0
- package/dist/auth/oauth2.js +138 -0
- package/dist/auth/token-manager.d.ts +13 -2
- package/dist/auth/token-manager.js +13 -1
- package/dist/contracts/ajv.d.ts +15 -0
- package/dist/contracts/ajv.js +37 -0
- package/dist/contracts/openapi.d.ts +19 -5
- package/dist/contracts/openapi.js +109 -26
- package/dist/http/api-client.d.ts +20 -2
- package/dist/http/api-client.js +68 -11
- package/dist/http/retry.d.ts +42 -0
- package/dist/http/retry.js +53 -0
- package/dist/http/types.d.ts +11 -1
- package/dist/index.d.ts +11 -3
- package/dist/index.js +4 -0
- package/dist/reporting/allure-adapter.d.ts +3 -3
- package/dist/reporting/metrics.d.ts +3 -0
- package/dist/reporting/metrics.js +6 -4
- package/dist/reporting/redaction.js +50 -2
- package/dist/testing/openapi-coverage.d.ts +116 -0
- package/dist/testing/openapi-coverage.js +296 -0
- package/package.json +25 -3
- package/templates/project/README.md +53 -0
- package/templates/project/__dot__env.example +14 -0
- package/templates/project/__dot__gitignore +7 -0
- package/templates/project/__dot__gitlab-ci.yml +25 -0
- package/templates/project/config/mocha.config.json +8 -0
- package/templates/project/eslint.config.mjs +27 -0
- package/templates/project/openapi/openapi.json +83 -0
- package/templates/project/src/clients/api.ts +32 -0
- package/templates/project/src/config/environment.ts +29 -0
- package/templates/project/src/contracts/openapi.ts +15 -0
- package/templates/project/src/observability.ts +15 -0
- package/templates/project/tests/contract/openapi.contract.spec.ts +33 -0
- package/templates/project/tests/security/authentication.spec.ts +36 -0
- package/templates/project/tests/setup/hooks.ts +17 -0
- package/templates/project/tests/smoke/health.spec.ts +17 -0
- package/templates/project/tests/support/mock-api.ts +66 -0
- package/templates/project/tsconfig.json +14 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { OpenApiValidator } from './openapi.js';
|
|
2
|
+
import type { JsonSchemaCompiler, OpenApiDocument, OpenApiValidatorOptions } from './openapi.js';
|
|
3
|
+
export interface AjvCompilerOptions {
|
|
4
|
+
/** JSON Schema dialect. '2020-12' suits OpenAPI 3.1, 'draft-07' suits OpenAPI 3.0. Default 'draft-07'. */
|
|
5
|
+
dialect?: 'draft-07' | '2020-12' | undefined;
|
|
6
|
+
/** Load `ajv-formats` (uuid, date-time, email, int32, ...). Default true. */
|
|
7
|
+
formats?: boolean | undefined;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Ajv-backed compiler for OpenApiValidator. Configured for OpenAPI documents: unknown keywords and formats
|
|
11
|
+
* (example, discriminator, x-*) are tolerated, all errors are collected, and recursive `$defs` references resolve natively.
|
|
12
|
+
*/
|
|
13
|
+
export declare function createAjvCompiler(options?: AjvCompilerOptions): Promise<JsonSchemaCompiler>;
|
|
14
|
+
/** Builds an OpenApiValidator backed by Ajv, picking the dialect from the document version unless overridden. */
|
|
15
|
+
export declare function createOpenApiValidator(doc: OpenApiDocument, options?: AjvCompilerOptions & OpenApiValidatorOptions): Promise<OpenApiValidator>;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { OpenApiValidator } from './openapi.js';
|
|
2
|
+
/** `ajv` and `ajv-formats` are optional peers: the core stays dependency-free until this module is used. */
|
|
3
|
+
async function load(specifier) {
|
|
4
|
+
try {
|
|
5
|
+
return await import(specifier);
|
|
6
|
+
}
|
|
7
|
+
catch (error) {
|
|
8
|
+
throw new Error(`Cannot load "${specifier}". Install it with: npm install --save-dev ajv ajv-formats`, { cause: error });
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** Ajv is CommonJS with a `default` property; depending on interop the function sits at `.default` or `.default.default`. */
|
|
12
|
+
function callable(module, specifier) {
|
|
13
|
+
let value = module?.default ?? module;
|
|
14
|
+
if (typeof value !== 'function')
|
|
15
|
+
value = value?.default;
|
|
16
|
+
if (typeof value !== 'function')
|
|
17
|
+
throw new Error(`Unexpected module shape for "${specifier}"`);
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Ajv-backed compiler for OpenApiValidator. Configured for OpenAPI documents: unknown keywords and formats
|
|
22
|
+
* (example, discriminator, x-*) are tolerated, all errors are collected, and recursive `$defs` references resolve natively.
|
|
23
|
+
*/
|
|
24
|
+
export async function createAjvCompiler(options = {}) {
|
|
25
|
+
const specifier = options.dialect === '2020-12' ? 'ajv/dist/2020.js' : 'ajv';
|
|
26
|
+
const Ajv = callable(await load(specifier), specifier);
|
|
27
|
+
const ajv = new Ajv({ strict: false, allErrors: true, logger: false });
|
|
28
|
+
if (options.formats !== false)
|
|
29
|
+
callable(await load('ajv-formats'), 'ajv-formats')(ajv);
|
|
30
|
+
return { supportsRefs: true, compile: schema => ajv.compile(schema) };
|
|
31
|
+
}
|
|
32
|
+
/** Builds an OpenApiValidator backed by Ajv, picking the dialect from the document version unless overridden. */
|
|
33
|
+
export async function createOpenApiValidator(doc, options = {}) {
|
|
34
|
+
const dialect = options.dialect ?? (typeof doc.openapi === 'string' && doc.openapi.startsWith('3.1.') ? '2020-12' : 'draft-07');
|
|
35
|
+
const compiler = await createAjvCompiler({ dialect, formats: options.formats });
|
|
36
|
+
return new OpenApiValidator(doc, compiler, { errorDetail: options.errorDetail });
|
|
37
|
+
}
|
|
@@ -1,15 +1,26 @@
|
|
|
1
1
|
import type { ApiResult, Method } from '../http/types.js';
|
|
2
|
-
|
|
2
|
+
type CompiledValidator = ((data: unknown) => boolean) & {
|
|
3
|
+
errors?: readonly unknown[] | null;
|
|
4
|
+
};
|
|
5
|
+
/** JSON Schema compiler adapter. `createAjvCompiler()` provides an Ajv-backed one; any compatible compiler works. */
|
|
3
6
|
export interface JsonSchemaCompiler {
|
|
4
|
-
compile(schema: Record<string, unknown>):
|
|
5
|
-
|
|
6
|
-
|
|
7
|
+
compile(schema: Record<string, unknown>): CompiledValidator;
|
|
8
|
+
/** True when the compiler resolves `$ref` / `$defs` itself. Enables validating recursive component schemas. */
|
|
9
|
+
readonly supportsRefs?: boolean | undefined;
|
|
10
|
+
}
|
|
11
|
+
export interface OpenApiValidatorOptions {
|
|
12
|
+
/**
|
|
13
|
+
* 'none' (default): failures never include response data.
|
|
14
|
+
* 'schema': failures list the violated schema locations and rule messages. Response values and property names are never included.
|
|
15
|
+
*/
|
|
16
|
+
errorDetail?: 'none' | 'schema' | undefined;
|
|
7
17
|
}
|
|
8
18
|
export interface OpenApiDocument {
|
|
9
19
|
openapi: string;
|
|
10
20
|
paths: Record<string, unknown>;
|
|
11
21
|
components?: {
|
|
12
22
|
schemas?: Record<string, unknown>;
|
|
23
|
+
responses?: Record<string, unknown>;
|
|
13
24
|
};
|
|
14
25
|
}
|
|
15
26
|
export interface ContractCheck {
|
|
@@ -24,6 +35,9 @@ export interface ContractCheck {
|
|
|
24
35
|
export declare class OpenApiValidator {
|
|
25
36
|
private readonly doc;
|
|
26
37
|
private readonly compiler;
|
|
27
|
-
|
|
38
|
+
private readonly compiled;
|
|
39
|
+
private readonly errorDetail;
|
|
40
|
+
constructor(doc: OpenApiDocument, compiler: JsonSchemaCompiler, options?: OpenApiValidatorOptions);
|
|
28
41
|
assertResponse(check: ContractCheck): void;
|
|
29
42
|
}
|
|
43
|
+
export {};
|
|
@@ -1,57 +1,132 @@
|
|
|
1
1
|
import assert from 'node:assert/strict';
|
|
2
|
+
const SCHEMA_REF_PREFIX = '#/components/schemas/';
|
|
3
|
+
const RESPONSE_REF_PREFIX = '#/components/responses/';
|
|
2
4
|
function object(value, label) {
|
|
3
5
|
if (value === null || typeof value !== 'object' || Array.isArray(value))
|
|
4
6
|
throw new Error(`Invalid OpenAPI ${label}`);
|
|
5
7
|
return value;
|
|
6
8
|
}
|
|
9
|
+
function unescapePointer(token) { return token.replace(/~1/g, '/').replace(/~0/g, '~'); }
|
|
7
10
|
function localRef(doc, ref) {
|
|
8
|
-
if (!ref.startsWith(
|
|
11
|
+
if (!ref.startsWith(SCHEMA_REF_PREFIX))
|
|
9
12
|
throw new Error('Only local component schema references are permitted');
|
|
10
|
-
const name = ref.slice(
|
|
13
|
+
const name = unescapePointer(ref.slice(SCHEMA_REF_PREFIX.length));
|
|
11
14
|
if (!name || !Object.prototype.hasOwnProperty.call(doc.components?.schemas ?? {}, name))
|
|
12
15
|
throw new Error('Unresolved component schema');
|
|
13
16
|
return doc.components.schemas[name];
|
|
14
17
|
}
|
|
15
|
-
/**
|
|
16
|
-
function
|
|
18
|
+
/** Resolves a response object, following local `#/components/responses/*` references. Fails closed on anything else. */
|
|
19
|
+
function resolveResponse(doc, raw) {
|
|
20
|
+
const seen = new Set();
|
|
21
|
+
let current = object(raw, 'response');
|
|
22
|
+
while (typeof current.$ref === 'string') {
|
|
23
|
+
const ref = current.$ref;
|
|
24
|
+
if (!ref.startsWith(RESPONSE_REF_PREFIX))
|
|
25
|
+
throw new Error('Only local component response references are permitted');
|
|
26
|
+
if (seen.has(ref))
|
|
27
|
+
throw new Error('Cyclic response reference');
|
|
28
|
+
seen.add(ref);
|
|
29
|
+
const name = unescapePointer(ref.slice(RESPONSE_REF_PREFIX.length));
|
|
30
|
+
if (!name || !Object.prototype.hasOwnProperty.call(doc.components?.responses ?? {}, name))
|
|
31
|
+
throw new Error('Unresolved component response');
|
|
32
|
+
current = object(doc.components.responses[name], 'response');
|
|
33
|
+
}
|
|
34
|
+
return current;
|
|
35
|
+
}
|
|
36
|
+
const SCHEMA_KEYWORDS = ['items', 'additionalProperties', 'additionalItems', 'not', 'contains', 'propertyNames', 'if', 'then', 'else', 'unevaluatedProperties', 'unevaluatedItems'];
|
|
37
|
+
const SCHEMA_LIST_KEYWORDS = ['oneOf', 'anyOf', 'allOf', 'prefixItems'];
|
|
38
|
+
const SCHEMA_MAP_KEYWORDS = ['properties', 'patternProperties', 'dependentSchemas'];
|
|
39
|
+
/**
|
|
40
|
+
* OpenAPI 3.0 dialect -> JSON Schema (nullable, boolean exclusiveMinimum/Maximum); 3.1 passes through.
|
|
41
|
+
* Component references are inlined. A recursive reference is emitted as a `$defs` reference when the compiler supports refs, otherwise it throws.
|
|
42
|
+
*/
|
|
43
|
+
function normalizeSchema(doc, raw, ctx, depth, refs) {
|
|
17
44
|
if (depth > 30)
|
|
18
45
|
throw new Error('Contract schema nesting exceeds limit');
|
|
19
46
|
const schema = object(raw, 'schema');
|
|
20
47
|
if (typeof schema.$ref === 'string') {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
48
|
+
const ref = schema.$ref;
|
|
49
|
+
const target = localRef(doc, ref); // rejects remote and unresolved references before anything else
|
|
50
|
+
if (refs.has(ref)) {
|
|
51
|
+
if (!ctx.supportsRefs)
|
|
52
|
+
throw new Error('Cyclic schema reference (use createAjvCompiler, or a compiler with supportsRefs, for recursive schemas)');
|
|
53
|
+
const token = ref.slice(SCHEMA_REF_PREFIX.length);
|
|
54
|
+
ctx.defs.add(token);
|
|
55
|
+
return { $ref: `#/$defs/${token}` };
|
|
56
|
+
}
|
|
57
|
+
return normalizeSchema(doc, target, ctx, depth + 1, new Set(refs).add(ref));
|
|
26
58
|
}
|
|
27
59
|
const out = { ...schema };
|
|
28
|
-
if (doc.openapi.startsWith('3.0.')
|
|
29
|
-
out.
|
|
30
|
-
|
|
60
|
+
if (doc.openapi.startsWith('3.0.')) {
|
|
61
|
+
if (out.nullable === true && typeof out.type === 'string') {
|
|
62
|
+
out.type = [out.type, 'null'];
|
|
63
|
+
delete out.nullable;
|
|
64
|
+
}
|
|
65
|
+
for (const [flag, limit] of [['exclusiveMinimum', 'minimum'], ['exclusiveMaximum', 'maximum']]) {
|
|
66
|
+
if (out[flag] === true && typeof out[limit] === 'number') {
|
|
67
|
+
out[flag] = out[limit];
|
|
68
|
+
delete out[limit];
|
|
69
|
+
}
|
|
70
|
+
else if (out[flag] === false)
|
|
71
|
+
delete out[flag];
|
|
72
|
+
}
|
|
31
73
|
}
|
|
32
|
-
|
|
33
|
-
|
|
74
|
+
const child = (value) => typeof value === 'boolean' ? value : normalizeSchema(doc, value, ctx, depth + 1, refs);
|
|
75
|
+
for (const keyword of SCHEMA_KEYWORDS) {
|
|
76
|
+
const value = out[keyword];
|
|
77
|
+
if (value === undefined)
|
|
78
|
+
continue;
|
|
79
|
+
out[keyword] = Array.isArray(value) ? value.map(child) : child(value);
|
|
34
80
|
}
|
|
35
|
-
|
|
36
|
-
out.items = normalizeSchema(doc, out.items, depth + 1, refs);
|
|
37
|
-
for (const keyword of ['oneOf', 'anyOf', 'allOf']) {
|
|
81
|
+
for (const keyword of SCHEMA_LIST_KEYWORDS) {
|
|
38
82
|
if (Array.isArray(out[keyword]))
|
|
39
|
-
out[keyword] = out[keyword].map(
|
|
83
|
+
out[keyword] = out[keyword].map(child);
|
|
84
|
+
}
|
|
85
|
+
for (const keyword of SCHEMA_MAP_KEYWORDS) {
|
|
86
|
+
if (out[keyword] !== undefined)
|
|
87
|
+
out[keyword] = Object.fromEntries(Object.entries(object(out[keyword], keyword)).map(([key, value]) => [key, child(value)]));
|
|
40
88
|
}
|
|
41
|
-
if (out.additionalProperties && typeof out.additionalProperties === 'object')
|
|
42
|
-
out.additionalProperties = normalizeSchema(doc, out.additionalProperties, depth + 1, refs);
|
|
43
89
|
return out;
|
|
44
90
|
}
|
|
91
|
+
function normalizeRoot(doc, raw, supportsRefs) {
|
|
92
|
+
const ctx = { supportsRefs, defs: new Set() };
|
|
93
|
+
const root = normalizeSchema(doc, raw, ctx, 0, new Set());
|
|
94
|
+
if (!ctx.defs.size)
|
|
95
|
+
return root;
|
|
96
|
+
const defs = {};
|
|
97
|
+
const done = new Set();
|
|
98
|
+
for (let pending = [...ctx.defs]; pending.length; pending = [...ctx.defs].filter(token => !done.has(token))) {
|
|
99
|
+
const token = pending[0];
|
|
100
|
+
done.add(token);
|
|
101
|
+
const ref = `${SCHEMA_REF_PREFIX}${token}`;
|
|
102
|
+
defs[unescapePointer(token)] = normalizeSchema(doc, localRef(doc, ref), ctx, 0, new Set([ref]));
|
|
103
|
+
}
|
|
104
|
+
return { ...root, $defs: { ...(root.$defs !== undefined ? object(root.$defs, '$defs') : {}), ...defs } };
|
|
105
|
+
}
|
|
45
106
|
function mediaType(value) { return value.split(';', 1)[0].trim().toLowerCase(); }
|
|
107
|
+
/** Schema locations and rule messages only. Never instance paths or values, which may contain response data. */
|
|
108
|
+
function describeViolations(errors) {
|
|
109
|
+
const list = errors ?? [];
|
|
110
|
+
const shown = list.slice(0, 10).map(error => {
|
|
111
|
+
const item = typeof error === 'object' && error !== null ? error : {};
|
|
112
|
+
const where = typeof item.schemaPath === 'string' ? item.schemaPath : '#';
|
|
113
|
+
const what = typeof item.message === 'string' ? item.message : typeof item.keyword === 'string' ? `violates ${item.keyword}` : 'violation';
|
|
114
|
+
return `${where}: ${what}`;
|
|
115
|
+
});
|
|
116
|
+
return `${shown.join('; ') || 'no details reported'}${list.length > shown.length ? ` (+${list.length - shown.length} more)` : ''}`;
|
|
117
|
+
}
|
|
46
118
|
/** Validates a response against an OpenAPI 3.x response schema with a supplied JSON Schema compiler (e.g. Ajv). */
|
|
47
119
|
export class OpenApiValidator {
|
|
48
120
|
doc;
|
|
49
121
|
compiler;
|
|
50
|
-
|
|
122
|
+
compiled = new Map();
|
|
123
|
+
errorDetail;
|
|
124
|
+
constructor(doc, compiler, options = {}) {
|
|
51
125
|
this.doc = doc;
|
|
52
126
|
this.compiler = compiler;
|
|
53
127
|
if (!/^3\.[01]\./.test(doc.openapi))
|
|
54
128
|
throw new Error('Expected OpenAPI 3.0 or 3.1 document');
|
|
129
|
+
this.errorDetail = options.errorDetail ?? 'none';
|
|
55
130
|
}
|
|
56
131
|
assertResponse(check) {
|
|
57
132
|
const operation = object(this.doc.paths[check.path], 'path')[check.method.toLowerCase()];
|
|
@@ -60,10 +135,10 @@ export class OpenApiValidator {
|
|
|
60
135
|
throw new Error('OpenAPI operationId mismatch');
|
|
61
136
|
const responses = object(op.responses, 'responses');
|
|
62
137
|
const key = String(check.status);
|
|
63
|
-
const
|
|
64
|
-
if (
|
|
138
|
+
const matchedKey = [key, `${key.charAt(0)}XX`, 'default'].find(candidate => responses[candidate] !== undefined);
|
|
139
|
+
if (matchedKey === undefined)
|
|
65
140
|
throw new Error(`OpenAPI response ${key} not declared`);
|
|
66
|
-
const response =
|
|
141
|
+
const response = resolveResponse(this.doc, responses[matchedKey]);
|
|
67
142
|
const content = response.content;
|
|
68
143
|
if (!content)
|
|
69
144
|
return; // e.g. 204
|
|
@@ -75,7 +150,15 @@ export class OpenApiValidator {
|
|
|
75
150
|
const schema = object(selected, 'media type').schema;
|
|
76
151
|
if (!schema)
|
|
77
152
|
return;
|
|
78
|
-
|
|
79
|
-
|
|
153
|
+
// Compile once per operation/response/media type: Ajv compilation is expensive and caches by schema identity.
|
|
154
|
+
const cacheKey = `${check.method}|${check.path}|${matchedKey}|${actualType}`;
|
|
155
|
+
let validate = this.compiled.get(cacheKey);
|
|
156
|
+
if (!validate) {
|
|
157
|
+
validate = this.compiler.compile(normalizeRoot(this.doc, schema, this.compiler.supportsRefs === true));
|
|
158
|
+
this.compiled.set(cacheKey, validate);
|
|
159
|
+
}
|
|
160
|
+
const base = `OpenAPI response contract failed (${check.method} ${check.path}, HTTP ${key}).`;
|
|
161
|
+
const valid = validate(check.response.body);
|
|
162
|
+
assert.ok(valid, this.errorDetail === 'schema' ? `${base} Violations: ${describeViolations(validate.errors)}` : `${base} Error details suppressed to protect response data`);
|
|
80
163
|
}
|
|
81
164
|
}
|
|
@@ -1,13 +1,30 @@
|
|
|
1
|
+
import type { TokenSource } from '../auth/token-manager.js';
|
|
2
|
+
import type { RetryConfig } from './retry.js';
|
|
1
3
|
import type { ApiRequest, ApiResult, EventSink, RequestSigner } from './types.js';
|
|
2
4
|
export declare class ApiTransportError extends Error {
|
|
3
5
|
readonly kind: 'network' | 'timeout';
|
|
4
6
|
constructor(message: string, kind: 'network' | 'timeout', options?: ErrorOptions);
|
|
5
7
|
}
|
|
6
|
-
|
|
8
|
+
/** Attaches an access token to every request and, on HTTP 401, renews it and resends the request once. */
|
|
9
|
+
export interface ApiAuth {
|
|
10
|
+
/** Usually a `TokenManager`. */
|
|
11
|
+
tokens: TokenSource;
|
|
12
|
+
/** Header to set. Default 'Authorization'. */
|
|
13
|
+
header?: string;
|
|
14
|
+
/** Prefix before the token. Default 'Bearer'; use '' to send the bare token. */
|
|
15
|
+
scheme?: string;
|
|
16
|
+
/** Renew and resend once after a 401. Default true. A 401 means the request was not processed, so this is applied to every method. */
|
|
17
|
+
refreshOnUnauthorized?: boolean;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Retries use exponential backoff with jitter (see `RetryConfig`) and obey Retry-After. Only GET, HEAD, OPTIONS and
|
|
21
|
+
* requests marked `idempotent` are retried after a network failure or a 408/429/502/503/504 response.
|
|
22
|
+
*/
|
|
23
|
+
export interface ApiClientConfig extends RetryConfig {
|
|
7
24
|
baseUrl: string;
|
|
25
|
+
auth?: ApiAuth;
|
|
8
26
|
timeoutMs?: number;
|
|
9
27
|
maxSafeRetries?: number;
|
|
10
|
-
retryDelayMs?: number;
|
|
11
28
|
signer?: RequestSigner;
|
|
12
29
|
defaultHeaders?: Record<string, string>;
|
|
13
30
|
onEvent?: EventSink;
|
|
@@ -19,6 +36,7 @@ export declare class ApiClient {
|
|
|
19
36
|
private readonly cfg;
|
|
20
37
|
private readonly url;
|
|
21
38
|
private readonly fetcher;
|
|
39
|
+
private readonly retryPolicy;
|
|
22
40
|
constructor(cfg: ApiClientConfig);
|
|
23
41
|
request<T = unknown>(req: ApiRequest): Promise<ApiResult<T>>;
|
|
24
42
|
}
|
package/dist/http/api-client.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { backoffDelay, resolveRetryPolicy, retryDelay } from './retry.js';
|
|
2
3
|
export class ApiTransportError extends Error {
|
|
3
4
|
kind;
|
|
4
5
|
constructor(message, kind, options) {
|
|
@@ -13,10 +14,29 @@ function formEncode(value) {
|
|
|
13
14
|
export function encodeForm(fields) {
|
|
14
15
|
return fields.map(([k, v]) => `${formEncode(k)}=${formEncode(v)}`).join('&');
|
|
15
16
|
}
|
|
17
|
+
function rejectPath() {
|
|
18
|
+
throw new Error('API path must be a local absolute path without query, fragments or parent traversal');
|
|
19
|
+
}
|
|
16
20
|
function assertPath(path) {
|
|
17
|
-
if (!path.startsWith('/') || path.startsWith('//') || path.includes('#') || path.includes('?') ||
|
|
18
|
-
|
|
21
|
+
if (!path.startsWith('/') || path.startsWith('//') || path.includes('#') || path.includes('?') || path.includes('\\'))
|
|
22
|
+
rejectPath();
|
|
23
|
+
// The WHATWG URL parser (and many servers) treat %2e as '.', so judge the path as it will be interpreted:
|
|
24
|
+
// decode up to three layers (also catches %252e) and treat '\' (e.g. from %5c) as a separator.
|
|
25
|
+
let decoded = path;
|
|
26
|
+
for (let layer = 0; layer < 3; layer++) {
|
|
27
|
+
let next = decoded;
|
|
28
|
+
try {
|
|
29
|
+
next = decodeURIComponent(decoded);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
rejectPath();
|
|
33
|
+
}
|
|
34
|
+
if (next === decoded)
|
|
35
|
+
break;
|
|
36
|
+
decoded = next;
|
|
19
37
|
}
|
|
38
|
+
if (/(^|[\\/])\.\.?($|[\\/])/.test(decoded))
|
|
39
|
+
rejectPath();
|
|
20
40
|
}
|
|
21
41
|
function parse(text, contentType) {
|
|
22
42
|
if (!text)
|
|
@@ -31,22 +51,27 @@ function parse(text, contentType) {
|
|
|
31
51
|
}
|
|
32
52
|
return text;
|
|
33
53
|
}
|
|
34
|
-
function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
|
|
35
54
|
function retryAllowed(method, idempotent) {
|
|
36
55
|
return ['GET', 'HEAD', 'OPTIONS'].includes(method) || idempotent;
|
|
37
56
|
}
|
|
38
57
|
function shouldRetryStatus(status) { return [408, 429, 502, 503, 504].includes(status); }
|
|
58
|
+
function hasHeader(headers, name) {
|
|
59
|
+
const wanted = name.toLowerCase();
|
|
60
|
+
return Object.keys(headers).some(key => key.toLowerCase() === wanted);
|
|
61
|
+
}
|
|
39
62
|
/** Browserless, dependency-light HTTP engine. Keeps signed request bytes identical to transmitted bytes. */
|
|
40
63
|
export class ApiClient {
|
|
41
64
|
cfg;
|
|
42
65
|
url;
|
|
43
66
|
fetcher;
|
|
67
|
+
retryPolicy;
|
|
44
68
|
constructor(cfg) {
|
|
45
69
|
this.cfg = cfg;
|
|
46
70
|
this.url = new URL(cfg.baseUrl.endsWith('/') ? cfg.baseUrl : `${cfg.baseUrl}/`);
|
|
47
71
|
if (!['http:', 'https:'].includes(this.url.protocol) || this.url.username || this.url.password || this.url.search || this.url.hash)
|
|
48
72
|
throw new Error('Clean HTTP(S) baseUrl required');
|
|
49
73
|
this.fetcher = cfg.fetchImpl ?? fetch;
|
|
74
|
+
this.retryPolicy = resolveRetryPolicy(cfg);
|
|
50
75
|
}
|
|
51
76
|
async request(req) {
|
|
52
77
|
assertPath(req.path);
|
|
@@ -66,13 +91,29 @@ export class ApiClient {
|
|
|
66
91
|
const retryCount = canRetry ? Math.min(Math.max(0, req.retry ?? this.cfg.maxSafeRetries ?? 1), 5) : 0;
|
|
67
92
|
const requestId = randomUUID();
|
|
68
93
|
const started = performance.now();
|
|
69
|
-
|
|
94
|
+
const auth = this.cfg.auth;
|
|
95
|
+
const authHeader = auth?.header ?? 'Authorization';
|
|
96
|
+
let transientRetries = 0; // network failures and retryable statuses; separate from the single re-authentication
|
|
97
|
+
let reauthenticated = false;
|
|
98
|
+
const policy = this.retryPolicy;
|
|
99
|
+
// Reports an attempt that is followed by another one, so retries are visible instead of hidden inside `attempts`.
|
|
100
|
+
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 });
|
|
102
|
+
};
|
|
103
|
+
for (let attempt = 1;; attempt++) {
|
|
104
|
+
const attemptStarted = performance.now();
|
|
70
105
|
const headers = { ...this.cfg.defaultHeaders, ...req.headers };
|
|
71
106
|
const hasContentType = Object.keys(headers).some(k => k.toLowerCase() === 'content-type');
|
|
72
107
|
if (!hasContentType && req.json !== undefined)
|
|
73
108
|
headers['Content-Type'] = 'application/json';
|
|
74
109
|
else if (!hasContentType && req.form !== undefined)
|
|
75
110
|
headers['Content-Type'] = 'application/x-www-form-urlencoded';
|
|
111
|
+
// A header the caller set explicitly (e.g. a deliberately bad token) is never replaced or renewed.
|
|
112
|
+
let usedToken;
|
|
113
|
+
if (auth && req.skipAuth !== true && !hasHeader(headers, authHeader)) {
|
|
114
|
+
usedToken = (await auth.tokens.tokens()).accessToken;
|
|
115
|
+
headers[authHeader] = auth.scheme === '' ? usedToken : `${auth.scheme ?? 'Bearer'} ${usedToken}`;
|
|
116
|
+
}
|
|
76
117
|
// Signature is regenerated each attempt; pass the exact body bytes, never a reserialized object.
|
|
77
118
|
Object.assign(headers, await this.cfg.signer?.({ method: req.method, path: req.path, exactBody: raw, requestId, attempt }));
|
|
78
119
|
const timeoutMs = req.timeoutMs ?? this.cfg.timeoutMs ?? 15_000;
|
|
@@ -85,8 +126,11 @@ export class ApiClient {
|
|
|
85
126
|
}
|
|
86
127
|
catch (error) {
|
|
87
128
|
const isTimeout = error instanceof Error && ['TimeoutError', 'AbortError'].includes(error.name);
|
|
88
|
-
if (canRetry &&
|
|
89
|
-
|
|
129
|
+
if (canRetry && transientRetries < retryCount) {
|
|
130
|
+
transientRetries++;
|
|
131
|
+
const wait = backoffDelay(policy, transientRetries);
|
|
132
|
+
emitRetry(attempt, attemptStarted, isTimeout ? 'timeout' : 'network', wait, { error: isTimeout ? 'timeout' : 'network' });
|
|
133
|
+
await policy.clock.sleep(wait);
|
|
90
134
|
continue;
|
|
91
135
|
}
|
|
92
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 });
|
|
@@ -100,15 +144,28 @@ export class ApiClient {
|
|
|
100
144
|
catch {
|
|
101
145
|
throw new ApiTransportError(`${req.method} ${req.path} response read failed`, 'network');
|
|
102
146
|
}
|
|
103
|
-
if (
|
|
104
|
-
|
|
147
|
+
if (response.status === 401 && auth && usedToken !== undefined && !reauthenticated && auth.refreshOnUnauthorized !== false) {
|
|
148
|
+
// The server rejected the token we sent. Tell the cache which one, so a burst of 401s renews once.
|
|
149
|
+
auth.tokens.invalidate(usedToken);
|
|
150
|
+
reauthenticated = true;
|
|
151
|
+
emitRetry(attempt, attemptStarted, 'reauthenticate', 0, { status: response.status });
|
|
105
152
|
continue;
|
|
106
153
|
}
|
|
154
|
+
if (canRetry && transientRetries < retryCount && shouldRetryStatus(response.status)) {
|
|
155
|
+
// undefined: the server asked for a longer Retry-After than we will wait, so hand the response back now.
|
|
156
|
+
const wait = retryDelay(policy, transientRetries + 1, response.headers.get('retry-after'));
|
|
157
|
+
if (wait !== undefined) {
|
|
158
|
+
transientRetries++;
|
|
159
|
+
emitRetry(attempt, attemptStarted, 'status', wait, { status: response.status });
|
|
160
|
+
await policy.clock.sleep(wait);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
107
164
|
const elapsed = Math.round(performance.now() - started);
|
|
108
|
-
|
|
109
|
-
|
|
165
|
+
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 };
|
|
110
168
|
}
|
|
111
169
|
}
|
|
112
|
-
throw new Error('Unreachable retry state');
|
|
113
170
|
}
|
|
114
171
|
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Time and randomness behind retry waits. Replace in tests to run retries instantly and deterministically. */
|
|
2
|
+
export interface ClientClock {
|
|
3
|
+
now(): number;
|
|
4
|
+
sleep(ms: number): Promise<void>;
|
|
5
|
+
/** A number in [0, 1), like Math.random. */
|
|
6
|
+
random(): number;
|
|
7
|
+
}
|
|
8
|
+
export interface RetryConfig {
|
|
9
|
+
/** First retry wait in ms; doubles on each further retry. Default 100. */
|
|
10
|
+
retryDelayMs?: number | undefined;
|
|
11
|
+
/** Upper bound for the doubling wait in ms. Default 5000. */
|
|
12
|
+
maxRetryDelayMs?: number | undefined;
|
|
13
|
+
/** Randomize each wait between half and all of its value, so parallel workers do not retry in lockstep. Default true. */
|
|
14
|
+
jitter?: boolean | undefined;
|
|
15
|
+
/** Obey a Retry-After response header (seconds or HTTP date). Default true. */
|
|
16
|
+
respectRetryAfter?: boolean | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* Longest Retry-After wait in ms that is honored. A longer request is not waited out: the response is returned
|
|
19
|
+
* immediately so the test fails fast with the 429/503 visible. Default 10000.
|
|
20
|
+
*/
|
|
21
|
+
maxRetryAfterMs?: number | undefined;
|
|
22
|
+
clock?: ClientClock | undefined;
|
|
23
|
+
}
|
|
24
|
+
export interface RetryPolicy {
|
|
25
|
+
readonly baseDelayMs: number;
|
|
26
|
+
readonly maxDelayMs: number;
|
|
27
|
+
readonly jitter: boolean;
|
|
28
|
+
readonly respectRetryAfter: boolean;
|
|
29
|
+
readonly maxRetryAfterMs: number;
|
|
30
|
+
readonly clock: ClientClock;
|
|
31
|
+
}
|
|
32
|
+
export declare const systemClock: ClientClock;
|
|
33
|
+
export declare function resolveRetryPolicy(config: RetryConfig): RetryPolicy;
|
|
34
|
+
/**
|
|
35
|
+
* Parses a Retry-After value into milliseconds from now: delta-seconds ("120") or an HTTP date.
|
|
36
|
+
* A date in the past gives 0. Returns undefined for anything else, so a malformed header is ignored.
|
|
37
|
+
*/
|
|
38
|
+
export declare function parseRetryAfter(value: string | null | undefined, now: number): number | undefined;
|
|
39
|
+
/** Exponential wait for the given retry (1-based), capped, optionally jittered. */
|
|
40
|
+
export declare function backoffDelay(policy: RetryPolicy, retryNumber: number): number;
|
|
41
|
+
/** How long to wait before the given retry, or undefined when the server asked for longer than we are willing to wait. */
|
|
42
|
+
export declare function retryDelay(policy: RetryPolicy, retryNumber: number, retryAfter: string | null): number | undefined;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
export const systemClock = {
|
|
2
|
+
now: () => Date.now(),
|
|
3
|
+
sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
|
|
4
|
+
random: () => Math.random()
|
|
5
|
+
};
|
|
6
|
+
function milliseconds(value, fallback, name) {
|
|
7
|
+
const resolved = value ?? fallback;
|
|
8
|
+
if (!Number.isFinite(resolved) || resolved < 0)
|
|
9
|
+
throw new Error(`Invalid retry configuration: ${name} must be a non-negative number`);
|
|
10
|
+
return resolved;
|
|
11
|
+
}
|
|
12
|
+
export function resolveRetryPolicy(config) {
|
|
13
|
+
return {
|
|
14
|
+
baseDelayMs: milliseconds(config.retryDelayMs, 100, 'retryDelayMs'),
|
|
15
|
+
maxDelayMs: milliseconds(config.maxRetryDelayMs, 5_000, 'maxRetryDelayMs'),
|
|
16
|
+
jitter: config.jitter !== false,
|
|
17
|
+
respectRetryAfter: config.respectRetryAfter !== false,
|
|
18
|
+
maxRetryAfterMs: milliseconds(config.maxRetryAfterMs, 10_000, 'maxRetryAfterMs'),
|
|
19
|
+
clock: config.clock ?? systemClock
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Parses a Retry-After value into milliseconds from now: delta-seconds ("120") or an HTTP date.
|
|
24
|
+
* A date in the past gives 0. Returns undefined for anything else, so a malformed header is ignored.
|
|
25
|
+
*/
|
|
26
|
+
export function parseRetryAfter(value, now) {
|
|
27
|
+
if (value === null || value === undefined)
|
|
28
|
+
return undefined;
|
|
29
|
+
const text = value.trim();
|
|
30
|
+
if (/^\d+$/.test(text))
|
|
31
|
+
return Number(text) * 1000; // an absurdly long digit string becomes Infinity: "do not wait"
|
|
32
|
+
if (!/[A-Za-z]{3}/.test(text))
|
|
33
|
+
return undefined; // a date names its month; rejects "-5", "1.5" and the like
|
|
34
|
+
const at = Date.parse(text);
|
|
35
|
+
return Number.isNaN(at) ? undefined : Math.max(0, at - now);
|
|
36
|
+
}
|
|
37
|
+
/** Exponential wait for the given retry (1-based), capped, optionally jittered. */
|
|
38
|
+
export function backoffDelay(policy, retryNumber) {
|
|
39
|
+
const raw = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (retryNumber - 1));
|
|
40
|
+
if (!policy.jitter)
|
|
41
|
+
return raw;
|
|
42
|
+
const random = Math.min(1, Math.max(0, policy.clock.random()));
|
|
43
|
+
return Math.round(raw / 2 + (random * raw) / 2);
|
|
44
|
+
}
|
|
45
|
+
/** How long to wait before the given retry, or undefined when the server asked for longer than we are willing to wait. */
|
|
46
|
+
export function retryDelay(policy, retryNumber, retryAfter) {
|
|
47
|
+
if (policy.respectRetryAfter) {
|
|
48
|
+
const asked = parseRetryAfter(retryAfter, policy.clock.now());
|
|
49
|
+
if (asked !== undefined)
|
|
50
|
+
return asked <= policy.maxRetryAfterMs ? asked : undefined;
|
|
51
|
+
}
|
|
52
|
+
return backoffDelay(policy, retryNumber);
|
|
53
|
+
}
|
package/dist/http/types.d.ts
CHANGED
|
@@ -13,6 +13,8 @@ export interface ApiRequest {
|
|
|
13
13
|
idempotent?: boolean;
|
|
14
14
|
retry?: number;
|
|
15
15
|
followRedirects?: boolean;
|
|
16
|
+
/** Send this request without the client's configured `auth` (login, public endpoints, negative authentication tests). */
|
|
17
|
+
skipAuth?: boolean;
|
|
16
18
|
}
|
|
17
19
|
export interface ApiResult<T = unknown> {
|
|
18
20
|
status: number;
|
|
@@ -23,6 +25,8 @@ export interface ApiResult<T = unknown> {
|
|
|
23
25
|
durationMs: number;
|
|
24
26
|
attempts: number;
|
|
25
27
|
requestId: string;
|
|
28
|
+
/** Present and true when a 401 made the client renew its token and resend the request once. */
|
|
29
|
+
reauthenticated?: boolean;
|
|
26
30
|
}
|
|
27
31
|
export interface RequestContext {
|
|
28
32
|
readonly method: Method;
|
|
@@ -39,7 +43,13 @@ export interface HttpEvent {
|
|
|
39
43
|
durationMs: number;
|
|
40
44
|
attempts: number;
|
|
41
45
|
requestId: string;
|
|
42
|
-
|
|
46
|
+
/** 'retry' is emitted for every attempt that is followed by another one; 'success' and 'network-error' are the final outcome. */
|
|
47
|
+
kind: 'success' | 'network-error' | 'retry';
|
|
43
48
|
error?: string;
|
|
49
|
+
reauthenticated?: boolean;
|
|
50
|
+
/** Only on 'retry' events: why another attempt follows. */
|
|
51
|
+
reason?: 'status' | 'network' | 'timeout' | 'reauthenticate';
|
|
52
|
+
/** Only on 'retry' events: how long the client waits before the next attempt, in ms. */
|
|
53
|
+
retryInMs?: number;
|
|
44
54
|
}
|
|
45
55
|
export type EventSink = (event: HttpEvent) => void;
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
|
|
2
|
-
export type { ApiClientConfig } from './http/api-client.js';
|
|
2
|
+
export type { ApiClientConfig, ApiAuth } from './http/api-client.js';
|
|
3
|
+
export { parseRetryAfter } from './http/retry.js';
|
|
4
|
+
export type { RetryConfig, ClientClock } from './http/retry.js';
|
|
3
5
|
export type { Method, ApiRequest, ApiResult, Query, RequestContext, RequestSigner, HttpEvent, EventSink } from './http/types.js';
|
|
4
6
|
export { TokenManager } from './auth/token-manager.js';
|
|
5
|
-
export type { Tokens, TokenProvider } from './auth/token-manager.js';
|
|
7
|
+
export type { Tokens, TokenProvider, TokenSource } from './auth/token-manager.js';
|
|
8
|
+
export { clientCredentialsProvider, refreshTokenProvider, OAuth2Error } from './auth/oauth2.js';
|
|
9
|
+
export type { OAuth2ClientOptions, OAuth2RefreshOptions, OAuth2EndpointOptions } from './auth/oauth2.js';
|
|
6
10
|
export { expectStatus, expectClientError, expectResponseTime, expectContract } from './contracts/assertions.js';
|
|
7
11
|
export type { Validator } from './contracts/assertions.js';
|
|
8
12
|
export { requireEnv, envEnum } from './config/env.js';
|
|
@@ -20,7 +24,9 @@ export type { ApiMetrics } from './reporting/metrics.js';
|
|
|
20
24
|
export { writeJunit } from './reporting/junit.js';
|
|
21
25
|
export type { TestCaseResult } from './reporting/junit.js';
|
|
22
26
|
export { OpenApiValidator } from './contracts/openapi.js';
|
|
23
|
-
export type { OpenApiDocument, JsonSchemaCompiler, ContractCheck } from './contracts/openapi.js';
|
|
27
|
+
export type { OpenApiDocument, JsonSchemaCompiler, ContractCheck, OpenApiValidatorOptions } from './contracts/openapi.js';
|
|
28
|
+
export { createAjvCompiler, createOpenApiValidator } from './contracts/ajv.js';
|
|
29
|
+
export type { AjvCompilerOptions } from './contracts/ajv.js';
|
|
24
30
|
export { ExecutionContext } from './testing/execution-context.js';
|
|
25
31
|
export type { ExecutionOptions } from './testing/execution-context.js';
|
|
26
32
|
export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
|
|
@@ -30,3 +36,5 @@ export type { AllureWriter } from './reporting/allure-adapter.js';
|
|
|
30
36
|
export { MochaResultCollector } from './integrations/mocha.js';
|
|
31
37
|
export { CoverageRegistry } from './testing/coverage.js';
|
|
32
38
|
export type { CoverageRecord } from './testing/coverage.js';
|
|
39
|
+
export { OpenApiCoverage } from './testing/openapi-coverage.js';
|
|
40
|
+
export type { OpenApiCoverageOptions, OpenApiCoverageReport, OpenApiCoverageSnapshot, OperationCoverage, CoverageStat, CoverageThresholds } from './testing/openapi-coverage.js';
|