@nikhil-qeas/api-core 0.4.1 → 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.
Files changed (42) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +133 -12
  3. package/bin/qe-api.js +99 -26
  4. package/dist/auth/oauth2.d.ts +40 -0
  5. package/dist/auth/oauth2.js +138 -0
  6. package/dist/auth/token-manager.d.ts +13 -2
  7. package/dist/auth/token-manager.js +13 -1
  8. package/dist/contracts/ajv.d.ts +15 -0
  9. package/dist/contracts/ajv.js +37 -0
  10. package/dist/contracts/openapi.d.ts +19 -5
  11. package/dist/contracts/openapi.js +109 -26
  12. package/dist/http/api-client.d.ts +20 -2
  13. package/dist/http/api-client.js +68 -11
  14. package/dist/http/retry.d.ts +42 -0
  15. package/dist/http/retry.js +53 -0
  16. package/dist/http/types.d.ts +11 -1
  17. package/dist/index.d.ts +11 -3
  18. package/dist/index.js +4 -0
  19. package/dist/reporting/allure-adapter.d.ts +3 -3
  20. package/dist/reporting/metrics.d.ts +3 -0
  21. package/dist/reporting/metrics.js +6 -4
  22. package/dist/reporting/redaction.js +50 -2
  23. package/dist/testing/openapi-coverage.d.ts +116 -0
  24. package/dist/testing/openapi-coverage.js +296 -0
  25. package/package.json +25 -3
  26. package/templates/project/README.md +53 -0
  27. package/templates/project/__dot__env.example +14 -0
  28. package/templates/project/__dot__gitignore +7 -0
  29. package/templates/project/__dot__gitlab-ci.yml +25 -0
  30. package/templates/project/config/mocha.config.json +8 -0
  31. package/templates/project/eslint.config.mjs +27 -0
  32. package/templates/project/openapi/openapi.json +83 -0
  33. package/templates/project/src/clients/api.ts +32 -0
  34. package/templates/project/src/config/environment.ts +29 -0
  35. package/templates/project/src/contracts/openapi.ts +15 -0
  36. package/templates/project/src/observability.ts +15 -0
  37. package/templates/project/tests/contract/openapi.contract.spec.ts +33 -0
  38. package/templates/project/tests/security/authentication.spec.ts +36 -0
  39. package/templates/project/tests/setup/hooks.ts +17 -0
  40. package/templates/project/tests/smoke/health.spec.ts +17 -0
  41. package/templates/project/tests/support/mock-api.ts +66 -0
  42. package/templates/project/tsconfig.json +14 -0
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
1
  export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
2
+ export { parseRetryAfter } from './http/retry.js';
2
3
  export { TokenManager } from './auth/token-manager.js';
4
+ export { clientCredentialsProvider, refreshTokenProvider, OAuth2Error } from './auth/oauth2.js';
3
5
  export { expectStatus, expectClientError, expectResponseTime, expectContract } from './contracts/assertions.js';
4
6
  export { requireEnv, envEnum } from './config/env.js';
5
7
  export { redact } from './reporting/redaction.js';
@@ -12,8 +14,10 @@ export { selectByTags } from './testing/tag-selection.js';
12
14
  export { MetricsCollector } from './reporting/metrics.js';
13
15
  export { writeJunit } from './reporting/junit.js';
14
16
  export { OpenApiValidator } from './contracts/openapi.js';
17
+ export { createAjvCompiler, createOpenApiValidator } from './contracts/ajv.js';
15
18
  export { ExecutionContext } from './testing/execution-context.js';
16
19
  export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
17
20
  export { attachSafeMetadata } from './reporting/allure-adapter.js';
18
21
  export { MochaResultCollector } from './integrations/mocha.js';
19
22
  export { CoverageRegistry } from './testing/coverage.js';
23
+ export { OpenApiCoverage } from './testing/openapi-coverage.js';
@@ -1,6 +1,6 @@
1
- /** Inversion of control: consumers pass allure-js-commons or their framework's reporter object. */
1
+ /** Inversion of control: consumers pass allure-js-commons or their framework's reporter object. Methods may be synchronous or return a promise. */
2
2
  export interface AllureWriter {
3
- attachment(name: string, content: string, type: string): Promise<unknown> | unknown;
4
- label?(name: string, value: string): Promise<unknown> | unknown;
3
+ attachment(name: string, content: string, type: string): unknown;
4
+ label?(name: string, value: string): unknown;
5
5
  }
6
6
  export declare function attachSafeMetadata(writer: AllureWriter, name: string, metadata: Record<string, unknown>): Promise<void>;
@@ -1,11 +1,14 @@
1
1
  import type { HttpEvent } from '../http/types.js';
2
2
  export interface ApiMetrics {
3
+ /** Requests that reached a final outcome. Retried attempts are counted in `retries`, not here. */
3
4
  total: number;
4
5
  networkErrors: number;
5
6
  httpErrors: number;
6
7
  averageMs: number;
7
8
  maxMs: number;
8
9
  p95Ms: number;
10
+ /** Attempts that were followed by another attempt (network failures, 408/429/5xx responses, re-authentication). */
11
+ retries: number;
9
12
  }
10
13
  /** Aggregates sanitized API event metadata; no request/response bodies are retained. */
11
14
  export declare class MetricsCollector {
@@ -3,11 +3,13 @@ export class MetricsCollector {
3
3
  events = [];
4
4
  record = (event) => { this.events.push({ ...event }); };
5
5
  summary() {
6
- const values = this.events.map(e => e.durationMs).sort((a, b) => a - b);
6
+ const finals = this.events.filter(e => e.kind !== 'retry');
7
+ const values = finals.map(e => e.durationMs).sort((a, b) => a - b);
7
8
  const total = values.length;
8
- return { total, networkErrors: this.events.filter(e => e.kind === 'network-error').length,
9
- httpErrors: this.events.filter(e => e.status !== undefined && e.status >= 400).length,
9
+ return { total, networkErrors: finals.filter(e => e.kind === 'network-error').length,
10
+ httpErrors: finals.filter(e => e.status !== undefined && e.status >= 400).length,
10
11
  averageMs: total ? Math.round(values.reduce((a, b) => a + b, 0) / total) : 0,
11
- maxMs: total ? values[total - 1] : 0, p95Ms: total ? values[Math.ceil(total * 0.95) - 1] : 0 };
12
+ maxMs: total ? values[total - 1] : 0, p95Ms: total ? values[Math.ceil(total * 0.95) - 1] : 0,
13
+ retries: this.events.length - total };
12
14
  }
13
15
  }
@@ -1,12 +1,60 @@
1
- const SECRET_KEY = /authorization|cookie|password|passphrase|secret|token|assertion|signature|private.?key|otp|pin|message-id|account.?number|iban|customer.?id/i;
2
1
  const REDACTED = '[REDACTED]';
2
+ // Matched against the key with separators removed ("account_number" -> "accountnumber"). Long, unambiguous names only.
3
+ const SECRET_COMPOUNDS = [
4
+ 'authorization', 'cookie', 'password', 'passwd', 'passphrase', 'secret', 'token', 'assertion', 'signature',
5
+ 'privatekey', 'apikey', 'credential', 'accountnumber', 'cardnumber', 'customerid', 'messageid'
6
+ ];
7
+ // Short names are matched as whole words only, so "shipping", "mapping" and "footprint" are not masked.
8
+ const SECRET_WORDS = new Set(['pin', 'otp', 'cvv', 'cvc', 'pan', 'iban', 'ssn']);
9
+ const BEARER_OR_BASIC = /\b(Bearer|Basic)\s+[A-Za-z0-9\-._~+/]+=*/gi;
10
+ const JWT = /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]*/g;
11
+ const CARD_NUMBER = /\b[2-6](?:[ -]?\d){12,18}\b/g;
12
+ function isSecretKey(key) {
13
+ const words = key
14
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
15
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')
16
+ .toLowerCase()
17
+ .split(/[^a-z0-9]+/)
18
+ .filter(Boolean);
19
+ if (words.some(word => SECRET_WORDS.has(word)))
20
+ return true;
21
+ const compact = words.join('');
22
+ return SECRET_COMPOUNDS.some(name => compact.includes(name));
23
+ }
24
+ function passesLuhn(digits) {
25
+ let sum = 0;
26
+ let double = false;
27
+ for (let i = digits.length - 1; i >= 0; i--) {
28
+ let n = digits.charCodeAt(i) - 48;
29
+ if (double) {
30
+ n *= 2;
31
+ if (n > 9)
32
+ n -= 9;
33
+ }
34
+ sum += n;
35
+ double = !double;
36
+ }
37
+ return sum % 10 === 0;
38
+ }
39
+ /** Masks credentials that appear inside free text: Authorization-style values, JWTs and Luhn-valid card numbers. */
40
+ function scrubString(text) {
41
+ return text
42
+ .replace(BEARER_OR_BASIC, `$1 ${REDACTED}`)
43
+ .replace(JWT, REDACTED)
44
+ .replace(CARD_NUMBER, match => {
45
+ const digits = match.replace(/[ -]/g, '');
46
+ return digits.length >= 13 && digits.length <= 19 && passesLuhn(digits) ? REDACTED : match;
47
+ });
48
+ }
3
49
  /** For structured event metadata only. Never attach raw banking payloads to test reports. */
4
50
  export function redact(value, depth = 0) {
5
51
  if (depth > 15)
6
52
  return '[MAX_DEPTH]';
53
+ if (typeof value === 'string')
54
+ return scrubString(value);
7
55
  if (Array.isArray(value))
8
56
  return value.map(x => redact(x, depth + 1));
9
57
  if (value !== null && typeof value === 'object')
10
- return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, SECRET_KEY.test(k) ? REDACTED : redact(v, depth + 1)]));
58
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, isSecretKey(k) ? REDACTED : redact(v, depth + 1)]));
11
59
  return value;
12
60
  }
@@ -0,0 +1,116 @@
1
+ import type { OpenApiDocument } from '../contracts/openapi.js';
2
+ import type { HttpEvent, Method } from '../http/types.js';
3
+ export interface OpenApiCoverageOptions {
4
+ /** "METHOD /path/template" or an operationId. Excluded operations are not counted and requests to them are ignored. */
5
+ exclude?: readonly string[] | undefined;
6
+ /** Count deprecated operations. Default true. */
7
+ includeDeprecated?: boolean | undefined;
8
+ }
9
+ export interface CoverageStat {
10
+ total: number;
11
+ covered: number;
12
+ percent: number;
13
+ }
14
+ export interface OperationCoverage {
15
+ method: Method;
16
+ path: string;
17
+ operationId?: string | undefined;
18
+ tags: string[];
19
+ deprecated: boolean;
20
+ /** Requests recorded against this operation, including ones whose status the spec does not declare. */
21
+ requests: number;
22
+ declaredResponses: string[];
23
+ coveredResponses: string[];
24
+ uncoveredResponses: string[];
25
+ /** Statuses the API returned that the spec does not declare (no exact, range or default match). */
26
+ undocumentedStatuses: number[];
27
+ }
28
+ export interface OpenApiCoverageReport {
29
+ operations: CoverageStat;
30
+ responses: CoverageStat;
31
+ byTag: Record<string, CoverageStat>;
32
+ uncoveredOperations: Array<{
33
+ method: Method;
34
+ path: string;
35
+ operationId?: string | undefined;
36
+ }>;
37
+ undocumentedResponses: Array<{
38
+ method: Method;
39
+ path: string;
40
+ status: number;
41
+ count: number;
42
+ }>;
43
+ /** Requests that matched no operation in the spec: spec drift, or tests calling endpoints the spec does not describe. */
44
+ unmatchedRequests: Array<{
45
+ method: string;
46
+ path: string;
47
+ count: number;
48
+ }>;
49
+ /** Distinct unmatched requests beyond the retention cap. */
50
+ unmatchedOverflow: number;
51
+ details: OperationCoverage[];
52
+ }
53
+ export interface OpenApiCoverageSnapshot {
54
+ version: 1;
55
+ responses: Array<{
56
+ method: string;
57
+ path: string;
58
+ response: string;
59
+ count: number;
60
+ }>;
61
+ undocumented: Array<{
62
+ method: string;
63
+ path: string;
64
+ status: number;
65
+ count: number;
66
+ }>;
67
+ unmatched: Array<{
68
+ method: string;
69
+ path: string;
70
+ count: number;
71
+ }>;
72
+ unmatchedOverflow: number;
73
+ }
74
+ export interface CoverageThresholds {
75
+ /** Minimum percentage (0-100) of operations that received at least one request. */
76
+ minOperations?: number | undefined;
77
+ /** Minimum percentage (0-100) of declared response keys observed at least once. */
78
+ minResponses?: number | undefined;
79
+ failOnUndocumented?: boolean | undefined;
80
+ failOnUnmatched?: boolean | undefined;
81
+ }
82
+ /**
83
+ * Endpoint coverage measured against an OpenAPI document instead of hand-registered scenarios.
84
+ * Feed it every request the suite makes (ApiClient `onEvent` -> `recordEvent`); it maps concrete paths such as
85
+ * `/accounts/42` to templates such as `/accounts/{id}` and reports which operations and declared responses were exercised.
86
+ * Operations are counted by request, not by test outcome: this measures what the suite exercised, not what passed.
87
+ */
88
+ export declare class OpenApiCoverage {
89
+ private readonly operations;
90
+ private readonly templates;
91
+ private readonly responseHits;
92
+ private readonly undocumentedHits;
93
+ private readonly unmatchedHits;
94
+ private unmatchedOverflow;
95
+ constructor(doc: OpenApiDocument, options?: OpenApiCoverageOptions);
96
+ /** Records one request. Returns how it was classified. */
97
+ record(hit: {
98
+ method: string;
99
+ path: string;
100
+ status: number;
101
+ }): 'matched' | 'undocumented' | 'unmatched' | 'ignored';
102
+ /** Pass directly as `ApiClient` `onEvent` (or call it from your own sink). Network errors carry no status and are ignored. */
103
+ readonly recordEvent: (event: HttpEvent) => void;
104
+ report(): OpenApiCoverageReport;
105
+ toJSON(): OpenApiCoverageReport;
106
+ /** Throws with an actionable message when coverage falls short, so CI can gate on it. */
107
+ assertCoverage(thresholds?: CoverageThresholds): void;
108
+ /** Raw hit counts, for merging results from parallel workers or sharded CI jobs. Contains paths only, never bodies or headers. */
109
+ snapshot(): OpenApiCoverageSnapshot;
110
+ /** Adds another run's snapshot. Fails closed, changing nothing, if it does not belong to this document. */
111
+ merge(snapshot: unknown): void;
112
+ toMarkdown(): string;
113
+ write(path: string, format?: 'json' | 'markdown'): Promise<void>;
114
+ private find;
115
+ private addUnmatched;
116
+ }
@@ -0,0 +1,296 @@
1
+ import assert from 'node:assert/strict';
2
+ import { mkdir, writeFile } from 'node:fs/promises';
3
+ import { dirname } from 'node:path';
4
+ import { redact } from '../reporting/redaction.js';
5
+ const METHODS = ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'HEAD', 'PATCH'];
6
+ const RESPONSE_KEY = /^(?:[1-5]\d\d|[1-5]XX|default)$/;
7
+ const MAX_UNMATCHED = 500;
8
+ const MAX_LISTED = 50;
9
+ function asObject(value, label) {
10
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
11
+ throw new Error(`Invalid OpenAPI ${label}`);
12
+ return value;
13
+ }
14
+ function bump(map, key, by = 1) { map.set(key, (map.get(key) ?? 0) + by); }
15
+ function percent(covered, total) { return total === 0 ? 100 : Math.round((covered / total) * 1000) / 10; }
16
+ function stat(covered, total) { return { total, covered, percent: percent(covered, total) }; }
17
+ function normalizePath(raw) {
18
+ const cut = raw.search(/[?#]/);
19
+ const path = cut >= 0 ? raw.slice(0, cut) : raw;
20
+ return path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;
21
+ }
22
+ function normalizeExclusion(entry) {
23
+ const match = /^([A-Za-z]+)\s+(\/.*)$/.exec(entry.trim());
24
+ return match ? `${match[1].toUpperCase()} ${match[2]}` : entry.trim();
25
+ }
26
+ function compileTemplate(path) {
27
+ let score = 0;
28
+ const source = normalizePath(path).split(/(\{[^{}/]+\})/).map(part => {
29
+ if (/^\{[^{}/]+\}$/.test(part))
30
+ return '[^/]+';
31
+ score += part.length;
32
+ return part.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
33
+ }).join('');
34
+ return { regex: new RegExp(`^${source}$`), score };
35
+ }
36
+ function positiveCount(value) {
37
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1)
38
+ throw new Error('Invalid coverage snapshot count');
39
+ return value;
40
+ }
41
+ function capped(items) {
42
+ return items.length > MAX_LISTED ? `${items.slice(0, MAX_LISTED).join(', ')} … and ${items.length - MAX_LISTED} more` : items.join(', ');
43
+ }
44
+ /**
45
+ * Endpoint coverage measured against an OpenAPI document instead of hand-registered scenarios.
46
+ * Feed it every request the suite makes (ApiClient `onEvent` -> `recordEvent`); it maps concrete paths such as
47
+ * `/accounts/42` to templates such as `/accounts/{id}` and reports which operations and declared responses were exercised.
48
+ * Operations are counted by request, not by test outcome: this measures what the suite exercised, not what passed.
49
+ */
50
+ export class OpenApiCoverage {
51
+ operations = new Map();
52
+ templates = [];
53
+ responseHits = new Map();
54
+ undocumentedHits = new Map();
55
+ unmatchedHits = new Map();
56
+ unmatchedOverflow = 0;
57
+ constructor(doc, options = {}) {
58
+ if (typeof doc.openapi !== 'string' || !/^3\.[01]\./.test(doc.openapi))
59
+ throw new Error('Expected OpenAPI 3.0 or 3.1 document');
60
+ const excluded = new Set((options.exclude ?? []).map(normalizeExclusion));
61
+ for (const [path, rawItem] of Object.entries(asObject(doc.paths, 'paths'))) {
62
+ if (!path.startsWith('/'))
63
+ continue; // x- extensions
64
+ const item = asObject(rawItem, `path item ${path}`);
65
+ if (typeof item.$ref === 'string')
66
+ throw new Error(`Path item references are not supported (${path})`);
67
+ const compiled = compileTemplate(path);
68
+ const template = { ...compiled, operations: new Map() };
69
+ for (const method of METHODS) {
70
+ const raw = item[method.toLowerCase()];
71
+ if (raw === undefined)
72
+ continue;
73
+ const op = asObject(raw, `operation ${method} ${path}`);
74
+ const responses = Object.keys(asObject(op.responses, `responses of ${method} ${path}`)).map(key => key === 'default' ? key : key.toUpperCase());
75
+ for (const key of responses)
76
+ if (!RESPONSE_KEY.test(key))
77
+ throw new Error(`Invalid response key "${key}" in ${method} ${path}`);
78
+ const operationId = typeof op.operationId === 'string' ? op.operationId : undefined;
79
+ const deprecated = op.deprecated === true;
80
+ const key = `${method} ${path}`;
81
+ const operation = {
82
+ key, method, path, operationId, deprecated, responses,
83
+ tags: Array.isArray(op.tags) ? op.tags.filter((tag) => typeof tag === 'string') : [],
84
+ excluded: excluded.has(key) || (operationId !== undefined && excluded.has(operationId)) || (options.includeDeprecated === false && deprecated)
85
+ };
86
+ this.operations.set(key, operation);
87
+ template.operations.set(method, operation);
88
+ }
89
+ if (template.operations.size)
90
+ this.templates.push(template);
91
+ }
92
+ }
93
+ /** Records one request. Returns how it was classified. */
94
+ record(hit) {
95
+ if (!Number.isInteger(hit.status) || hit.status < 100 || hit.status > 599)
96
+ throw new Error('Invalid HTTP status');
97
+ const method = hit.method.toUpperCase();
98
+ const path = normalizePath(hit.path);
99
+ const operation = this.find(method, path);
100
+ if (!operation) {
101
+ this.addUnmatched(method, path);
102
+ return 'unmatched';
103
+ }
104
+ if (operation.excluded)
105
+ return 'ignored';
106
+ const declared = [String(hit.status), `${String(hit.status).charAt(0)}XX`, 'default'].find(key => operation.responses.includes(key));
107
+ if (declared === undefined) {
108
+ const statuses = this.undocumentedHits.get(operation) ?? new Map();
109
+ bump(statuses, hit.status);
110
+ this.undocumentedHits.set(operation, statuses);
111
+ return 'undocumented';
112
+ }
113
+ const responses = this.responseHits.get(operation) ?? new Map();
114
+ bump(responses, declared);
115
+ this.responseHits.set(operation, responses);
116
+ return 'matched';
117
+ }
118
+ /** Pass directly as `ApiClient` `onEvent` (or call it from your own sink). Network errors carry no status and are ignored. */
119
+ recordEvent = (event) => {
120
+ if (event.status !== undefined)
121
+ this.record({ method: event.method, path: event.path, status: event.status });
122
+ };
123
+ report() {
124
+ const details = [];
125
+ for (const op of this.operations.values()) {
126
+ if (op.excluded)
127
+ continue;
128
+ const responses = this.responseHits.get(op) ?? new Map();
129
+ const undocumented = this.undocumentedHits.get(op) ?? new Map();
130
+ const requests = [...responses.values(), ...undocumented.values()].reduce((sum, count) => sum + count, 0);
131
+ details.push({
132
+ method: op.method, path: op.path, operationId: op.operationId, tags: [...op.tags], deprecated: op.deprecated, requests,
133
+ declaredResponses: [...op.responses],
134
+ coveredResponses: op.responses.filter(key => responses.has(key)),
135
+ uncoveredResponses: op.responses.filter(key => !responses.has(key)),
136
+ undocumentedStatuses: [...undocumented.keys()].sort((a, b) => a - b)
137
+ });
138
+ }
139
+ const tagTotals = new Map();
140
+ for (const detail of details) {
141
+ for (const tag of detail.tags.length ? detail.tags : ['(untagged)']) {
142
+ const entry = tagTotals.get(tag) ?? { covered: 0, total: 0 };
143
+ entry.total++;
144
+ if (detail.requests > 0)
145
+ entry.covered++;
146
+ tagTotals.set(tag, entry);
147
+ }
148
+ }
149
+ return {
150
+ operations: stat(details.filter(d => d.requests > 0).length, details.length),
151
+ responses: stat(details.reduce((sum, d) => sum + d.coveredResponses.length, 0), details.reduce((sum, d) => sum + d.declaredResponses.length, 0)),
152
+ byTag: Object.fromEntries([...tagTotals].map(([tag, value]) => [tag, stat(value.covered, value.total)])),
153
+ uncoveredOperations: details.filter(d => d.requests === 0).map(d => ({ method: d.method, path: d.path, operationId: d.operationId })),
154
+ undocumentedResponses: details.flatMap(d => d.undocumentedStatuses.map(status => ({
155
+ method: d.method, path: d.path, status, count: this.undocumentedHits.get(this.operations.get(`${d.method} ${d.path}`)).get(status)
156
+ }))),
157
+ unmatchedRequests: [...this.unmatchedHits.values()].map(entry => ({ ...entry })),
158
+ unmatchedOverflow: this.unmatchedOverflow,
159
+ details
160
+ };
161
+ }
162
+ toJSON() { return this.report(); }
163
+ /** Throws with an actionable message when coverage falls short, so CI can gate on it. */
164
+ assertCoverage(thresholds = {}) {
165
+ for (const [name, value] of [['minOperations', thresholds.minOperations], ['minResponses', thresholds.minResponses]]) {
166
+ if (value !== undefined && (!Number.isFinite(value) || value < 0 || value > 100))
167
+ throw new Error(`${name} must be between 0 and 100`);
168
+ }
169
+ const report = this.report();
170
+ const problems = [];
171
+ if (thresholds.minOperations !== undefined && report.operations.percent < thresholds.minOperations) {
172
+ problems.push(`Operation coverage ${report.operations.percent}% is below ${thresholds.minOperations}% (${report.operations.covered}/${report.operations.total}). Not exercised: ${capped(report.uncoveredOperations.map(o => `${o.method} ${o.path}`))}`);
173
+ }
174
+ if (thresholds.minResponses !== undefined && report.responses.percent < thresholds.minResponses) {
175
+ problems.push(`Response coverage ${report.responses.percent}% is below ${thresholds.minResponses}% (${report.responses.covered}/${report.responses.total}).`);
176
+ }
177
+ if (thresholds.failOnUndocumented && report.undocumentedResponses.length) {
178
+ problems.push(`Responses missing from the spec: ${capped(report.undocumentedResponses.map(r => `${r.method} ${r.path} -> ${r.status}`))}`);
179
+ }
180
+ if (thresholds.failOnUnmatched && (report.unmatchedRequests.length || report.unmatchedOverflow)) {
181
+ problems.push(`Requests matching no operation in the spec: ${capped(report.unmatchedRequests.map(r => `${r.method} ${r.path}`))}${report.unmatchedOverflow ? ` (+${report.unmatchedOverflow} more)` : ''}`);
182
+ }
183
+ if (problems.length)
184
+ assert.fail(`API coverage check failed:\n- ${problems.join('\n- ')}`);
185
+ }
186
+ /** Raw hit counts, for merging results from parallel workers or sharded CI jobs. Contains paths only, never bodies or headers. */
187
+ snapshot() {
188
+ return {
189
+ version: 1,
190
+ responses: [...this.responseHits].flatMap(([op, hits]) => [...hits].map(([response, count]) => ({ method: op.method, path: op.path, response, count }))),
191
+ undocumented: [...this.undocumentedHits].flatMap(([op, hits]) => [...hits].map(([status, count]) => ({ method: op.method, path: op.path, status, count }))),
192
+ unmatched: [...this.unmatchedHits.values()].map(entry => ({ ...entry })),
193
+ unmatchedOverflow: this.unmatchedOverflow
194
+ };
195
+ }
196
+ /** Adds another run's snapshot. Fails closed, changing nothing, if it does not belong to this document. */
197
+ merge(snapshot) {
198
+ const data = asObject(snapshot, 'coverage snapshot');
199
+ if (data.version !== 1)
200
+ throw new Error('Unsupported coverage snapshot version');
201
+ const list = (value) => {
202
+ if (!Array.isArray(value))
203
+ throw new Error('Invalid coverage snapshot');
204
+ return value.map(item => asObject(item, 'coverage snapshot entry'));
205
+ };
206
+ const operationOf = (entry) => {
207
+ const operation = typeof entry.method === 'string' && typeof entry.path === 'string' ? this.operations.get(`${entry.method} ${entry.path}`) : undefined;
208
+ if (!operation)
209
+ throw new Error('Coverage snapshot does not match this OpenAPI document');
210
+ return operation;
211
+ };
212
+ const updates = [];
213
+ for (const entry of list(data.responses)) {
214
+ const operation = operationOf(entry);
215
+ const count = positiveCount(entry.count);
216
+ if (typeof entry.response !== 'string' || !operation.responses.includes(entry.response))
217
+ throw new Error('Coverage snapshot does not match this OpenAPI document');
218
+ const response = entry.response;
219
+ if (!operation.excluded)
220
+ updates.push(() => { const hits = this.responseHits.get(operation) ?? new Map(); bump(hits, response, count); this.responseHits.set(operation, hits); });
221
+ }
222
+ for (const entry of list(data.undocumented)) {
223
+ const operation = operationOf(entry);
224
+ const count = positiveCount(entry.count);
225
+ const status = entry.status;
226
+ if (typeof status !== 'number' || !Number.isInteger(status) || status < 100 || status > 599)
227
+ throw new Error('Invalid coverage snapshot status');
228
+ if (!operation.excluded)
229
+ updates.push(() => { const hits = this.undocumentedHits.get(operation) ?? new Map(); bump(hits, status, count); this.undocumentedHits.set(operation, hits); });
230
+ }
231
+ for (const entry of list(data.unmatched)) {
232
+ const count = positiveCount(entry.count);
233
+ if (typeof entry.method !== 'string' || typeof entry.path !== 'string')
234
+ throw new Error('Invalid coverage snapshot');
235
+ const { method, path } = entry;
236
+ updates.push(() => this.addUnmatched(method, path, count));
237
+ }
238
+ const overflow = data.unmatchedOverflow ?? 0;
239
+ if (typeof overflow !== 'number' || !Number.isSafeInteger(overflow) || overflow < 0)
240
+ throw new Error('Invalid coverage snapshot');
241
+ for (const update of updates)
242
+ update();
243
+ this.unmatchedOverflow += overflow;
244
+ }
245
+ toMarkdown() {
246
+ const report = this.report();
247
+ const cell = (text) => text.replace(/\|/g, '\\|');
248
+ const row = (label, s) => `| ${cell(label)} | ${s.covered} | ${s.total} | ${s.percent}% |`;
249
+ const lines = [
250
+ '# API endpoint coverage', '',
251
+ '| | Covered | Total | % |', '|---|---:|---:|---:|', row('Operations', report.operations), row('Declared responses', report.responses), ''
252
+ ];
253
+ const tags = Object.entries(report.byTag);
254
+ if (tags.length)
255
+ lines.push('## By tag', '', '| Tag | Covered | Total | % |', '|---|---:|---:|---:|', ...tags.map(([tag, s]) => row(tag, s)), '');
256
+ const section = (title, items) => {
257
+ if (!items.length)
258
+ return;
259
+ lines.push(`## ${title} (${items.length})`, '', ...items.slice(0, MAX_LISTED).map(item => `- ${item}`));
260
+ if (items.length > MAX_LISTED)
261
+ lines.push(`- … and ${items.length - MAX_LISTED} more`);
262
+ lines.push('');
263
+ };
264
+ section('Operations not exercised', report.uncoveredOperations.map(o => `\`${o.method} ${o.path}\``));
265
+ section('Declared responses never observed', report.details.filter(d => d.requests > 0 && d.uncoveredResponses.length).map(d => `\`${d.method} ${d.path}\`: ${d.uncoveredResponses.join(', ')}`));
266
+ section('Responses missing from the spec', report.undocumentedResponses.map(r => `\`${r.method} ${r.path}\` returned ${r.status} (${r.count}x)`));
267
+ section('Requests matching no operation', report.unmatchedRequests.map(r => `\`${r.method} ${r.path}\` (${r.count}x)`));
268
+ return `${lines.join('\n')}\n`;
269
+ }
270
+ async write(path, format = 'json') {
271
+ await mkdir(dirname(path), { recursive: true });
272
+ await writeFile(path, format === 'json' ? `${JSON.stringify(this.report(), null, 2)}\n` : this.toMarkdown(), { encoding: 'utf8', mode: 0o600 });
273
+ }
274
+ find(method, path) {
275
+ let best;
276
+ for (const template of this.templates) {
277
+ // Prefer the most specific template that defines this method: /users/me beats /users/{id}.
278
+ if (!template.operations.has(method) || !template.regex.test(path))
279
+ continue;
280
+ if (!best || template.score > best.score)
281
+ best = template;
282
+ }
283
+ return best?.operations.get(method);
284
+ }
285
+ addUnmatched(method, rawPath, count = 1) {
286
+ const path = String(redact(rawPath.slice(0, 200))); // scrub credentials / card numbers that ended up in a URL
287
+ const key = `${method} ${path}`;
288
+ const existing = this.unmatchedHits.get(key);
289
+ if (existing)
290
+ existing.count += count;
291
+ else if (this.unmatchedHits.size < MAX_UNMATCHED)
292
+ this.unmatchedHits.set(key, { method, path, count });
293
+ else
294
+ this.unmatchedOverflow += count;
295
+ }
296
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nikhil-qeas/api-core",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Reusable TypeScript API automation core with HTTP, auth, OpenAPI adapter, test isolation, reporting and CI",
5
5
  "private": false,
6
6
  "type": "module",
@@ -18,21 +18,31 @@
18
18
  "files": [
19
19
  "dist",
20
20
  "bin",
21
+ "templates",
22
+ "CHANGELOG.md",
21
23
  "README.md"
22
24
  ],
23
25
  "scripts": {
24
26
  "clean": "node -e \"import('node:fs').then(m=>m.rmSync('dist',{recursive:true,force:true}))\"",
25
27
  "build": "tsc -p tsconfig.build.json",
26
28
  "typecheck": "tsc --noEmit -p tsconfig.json",
29
+ "lint": "eslint .",
27
30
  "test": "npm run build && node --test test/*.test.mjs",
28
- "check": "npm run typecheck && npm test",
31
+ "test:e2e": "QE_E2E=1 node --test test/generated-project.test.mjs",
32
+ "check": "npm run typecheck && npm run lint && npm test",
29
33
  "prepack": "npm run build",
30
34
  "test:ci": "npm run build && node scripts/test-ci.mjs",
31
35
  "prepublishOnly": "npm run check && npm pack --dry-run"
32
36
  },
33
37
  "devDependencies": {
38
+ "@eslint/js": "^10.0.1",
39
+ "@types/node": "^22.0.0",
40
+ "ajv": "^8.20.0",
41
+ "ajv-formats": "^3.0.1",
42
+ "eslint": "^10.15.0",
43
+ "globals": "^17.14.0",
34
44
  "typescript": "^5.9.3",
35
- "@types/node": "^22.0.0"
45
+ "typescript-eslint": "^8.73.0"
36
46
  },
37
47
  "repository": {
38
48
  "type": "git",
@@ -44,5 +54,17 @@
44
54
  },
45
55
  "bin": {
46
56
  "qe-api": "./bin/qe-api.js"
57
+ },
58
+ "peerDependencies": {
59
+ "ajv": "^8.20.0",
60
+ "ajv-formats": "^3.0.1"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "ajv": {
64
+ "optional": true
65
+ },
66
+ "ajv-formats": {
67
+ "optional": true
68
+ }
47
69
  }
48
70
  }
@@ -0,0 +1,53 @@
1
+ # __PROJECT_NAME__
2
+
3
+ API automation project generated with `@nikhil-qeas/api-core`: TypeScript, Mocha, OpenAPI contract checks, spec-driven coverage, OAuth2 with automatic token renewal, safe retries, ESLint and GitLab CI.
4
+
5
+ ```bash
6
+ npm install
7
+ npm run check # typecheck + lint + all tests
8
+ ```
9
+
10
+ Commit `package-lock.json`: the CI pipeline uses `npm ci`.
11
+
12
+ The sample tests start a local mock API (`tests/support/mock-api.ts`) and need no environment, credentials or network. Nothing here connects to a real system until you point `API_BASE_URL` at one.
13
+
14
+ ## Layout
15
+
16
+ | Path | Purpose |
17
+ |---|---|
18
+ | `openapi/openapi.json` | The API's OpenAPI document. **Replace it with your API's spec**: contract checks and coverage both read it. |
19
+ | `src/clients/api.ts` | `createApiClient()`: retries with backoff and `Retry-After`, OAuth2 when `OAUTH_*` is set, metrics and coverage hooks. Add production guards and approvals here. |
20
+ | `src/config/environment.ts` | Reads `API_BASE_URL` and the optional `OAUTH_*` settings. |
21
+ | `src/contracts/openapi.ts` | Loads the spec and builds the Ajv-backed contract validator. |
22
+ | `src/observability.ts` | Run-wide metrics and OpenAPI coverage collectors. |
23
+ | `tests/smoke`, `contract`, `security` | Working samples. Add `regression` and `negative` suites beside them. |
24
+ | `tests/setup/hooks.ts` | After the run: writes `reports/coverage/api.md` and `api.json` and can enforce a minimum. |
25
+ | `tests/support/mock-api.ts` | The local mock API and token endpoint the samples use. Delete it once you test a real environment. |
26
+ | `.env.example` | Every setting, with comments. Copy to `.env` locally; use your CI secret store in pipelines. |
27
+
28
+ ## Commands
29
+
30
+ | Command | What it does |
31
+ |---|---|
32
+ | `npm test` | Every test. |
33
+ | `npm run test:smoke` / `test:contract` / `test:security` | Tests whose title contains `@smoke` / `@contract` / `@security`. Tag your own `describe` titles the same way. |
34
+ | `npm run test:ci` | Everything, with JUnit XML in `reports/junit/results.xml` for the pipeline. |
35
+ | `npm run lint` | ESLint with type-aware rules: an unawaited request is a check that silently never runs. |
36
+ | `npm run audit:security` | `npm audit` for high-severity advisories. |
37
+
38
+ ## Contract checks and coverage
39
+
40
+ ```ts
41
+ const contract = await contractValidator();
42
+ contract.assertResponse({ method: 'GET', path: '/accounts/{id}', status: response.status, response });
43
+ ```
44
+
45
+ Use the spec's path template, not the concrete URL. After every run `reports/coverage/api.md` lists the operations and documented responses the suite exercised, responses the API returned that the spec does not declare, and requests that match no operation. Set `QE_COVERAGE_MIN_OPERATIONS=80` on full runs to fail when coverage drops. Coverage counts requests, not passes.
46
+
47
+ ## Authentication
48
+
49
+ Set `OAUTH_TOKEN_URL`, `OAUTH_CLIENT_ID`, `OAUTH_CLIENT_SECRET` (and optionally `OAUTH_SCOPE`) and `createApiClient()` sends a bearer token automatically. When the server answers 401 the client renews the token and resends once. Use `skipAuth: true` or your own `Authorization` header on a request for negative tests. `tests/security/authentication.spec.ts` shows both against the mock API.
50
+
51
+ ## Safety
52
+
53
+ Store credentials in your CI secret store, never in source control or logs. Writes against shared or production-like systems need their own approvals: `QE_ALLOW_MUTATIONS` stays `false` by default, and `createApiClient()` is the place to enforce environment guards. The core library's `assertRequestPolicy` and `rejectUnsafeEnvironment` help.