@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.
Files changed (66) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +216 -5
  3. package/bin/qe-api.js +3 -0
  4. package/dist/contracts/assertions.d.ts +11 -0
  5. package/dist/contracts/assertions.js +31 -0
  6. package/dist/contracts/openapi.d.ts +28 -1
  7. package/dist/contracts/openapi.js +113 -0
  8. package/dist/graphql/graphql.d.ts +86 -0
  9. package/dist/graphql/graphql.js +312 -0
  10. package/dist/http/api-client.d.ts +20 -0
  11. package/dist/http/api-client.js +70 -9
  12. package/dist/http/cookies.d.ts +32 -0
  13. package/dist/http/cookies.js +116 -0
  14. package/dist/http/multipart.d.ts +20 -0
  15. package/dist/http/multipart.js +48 -0
  16. package/dist/http/trace.d.ts +26 -0
  17. package/dist/http/trace.js +43 -0
  18. package/dist/http/types.d.ts +22 -0
  19. package/dist/index.d.ts +31 -5
  20. package/dist/index.js +16 -3
  21. package/dist/integrations/mocha.d.ts +32 -0
  22. package/dist/integrations/mocha.js +81 -0
  23. package/dist/reporting/html-report.d.ts +23 -0
  24. package/dist/reporting/html-report.js +118 -0
  25. package/dist/reporting/junit.d.ts +11 -2
  26. package/dist/reporting/junit.js +9 -3
  27. package/dist/reporting/redaction.d.ts +10 -0
  28. package/dist/reporting/redaction.js +36 -2
  29. package/dist/security/authorization-matrix.d.ts +55 -0
  30. package/dist/security/authorization-matrix.js +102 -0
  31. package/dist/security/headers.d.ts +21 -0
  32. package/dist/security/headers.js +45 -0
  33. package/dist/security/policy.js +3 -2
  34. package/dist/security/sensitive-data.d.ts +22 -0
  35. package/dist/security/sensitive-data.js +76 -0
  36. package/dist/testing/json-path.d.ts +6 -0
  37. package/dist/testing/json-path.js +97 -0
  38. package/dist/testing/load.d.ts +85 -0
  39. package/dist/testing/load.js +134 -0
  40. package/dist/testing/matchers.d.ts +63 -0
  41. package/dist/testing/matchers.js +164 -0
  42. package/dist/testing/spec-cases.d.ts +136 -0
  43. package/dist/testing/spec-cases.js +1065 -0
  44. package/dist/testing/wait-for.d.ts +40 -0
  45. package/dist/testing/wait-for.js +82 -0
  46. package/package.json +1 -1
  47. package/templates/project/README.md +80 -5
  48. package/templates/project/__dot__env.example +4 -0
  49. package/templates/project/__dot__gitlab-ci.yml +1 -0
  50. package/templates/project/openapi/openapi.json +476 -19
  51. package/templates/project/src/clients/api.ts +4 -2
  52. package/templates/project/src/environment.ts +8 -0
  53. package/templates/project/src/observability.ts +15 -1
  54. package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
  55. package/templates/project/tests/performance/health.spec.ts +22 -0
  56. package/templates/project/tests/security/authentication.spec.ts +3 -1
  57. package/templates/project/tests/security/authorization.spec.ts +29 -0
  58. package/templates/project/tests/security/hygiene.spec.ts +37 -0
  59. package/templates/project/tests/security/spec-cases.spec.ts +61 -0
  60. package/templates/project/tests/security/write-protection.spec.ts +2 -2
  61. package/templates/project/tests/setup/hooks.ts +32 -5
  62. package/templates/project/tests/smoke/health.spec.ts +3 -3
  63. package/templates/project/tests/smoke/tracing.spec.ts +48 -0
  64. package/templates/project/tests/support/approved-writes.ts +27 -0
  65. package/templates/project/tests/support/identities.ts +24 -0
  66. package/templates/project/tests/support/mock-api.ts +166 -3
@@ -3,8 +3,9 @@ export function assertRequestPolicy(baseUrl, request, policy) {
3
3
  const url = new URL(baseUrl);
4
4
  if (policy.allowedHosts && !policy.allowedHosts.includes(url.hostname))
5
5
  throw new Error('Target hostname is not allowlisted');
6
- if ((policy.production || !policy.allowDestructive) && !['GET', 'HEAD', 'OPTIONS'].includes(request.method)) {
7
- // POST may be a read-only query in some APIs; explicitly approve it at project level.
6
+ // A POST is a read only when the request says so (`readOnly`, e.g. a GraphQL query). PUT, PATCH and DELETE never are.
7
+ const reads = ['GET', 'HEAD', 'OPTIONS'].includes(request.method) || (request.method === 'POST' && request.readOnly === true);
8
+ if ((policy.production || !policy.allowDestructive) && !reads) {
8
9
  throw new Error('Write-capable HTTP request is blocked by the execution policy');
9
10
  }
10
11
  }
@@ -0,0 +1,22 @@
1
+ import type { ApiResult } from '../http/types.js';
2
+ export interface SensitiveFinding {
3
+ /** Where it was found, e.g. `$.users[0].password`. Never includes the value. */
4
+ path: string;
5
+ reason: string;
6
+ }
7
+ export interface SensitiveDataOptions {
8
+ /** Property names (any case or style) that belong in the response, e.g. `access_token` on a login response. */
9
+ allowKeys?: readonly string[] | undefined;
10
+ /** Paths that belong in the response, e.g. `$.access_token` or `$.items[*].apiKey`. A concrete index `[0]` matches `[*]`. */
11
+ allowPaths?: readonly string[] | undefined;
12
+ /** Also look inside string values for credentials: JWTs, private keys, cloud keys, Authorization values, card numbers. Default true. */
13
+ checkValues?: boolean | undefined;
14
+ }
15
+ /**
16
+ * Finds secrets that a response should not expose (excessive data exposure): properties whose names suggest a password, token,
17
+ * key or similar and that carry a value, and string values that look like credentials. Findings name the path and the reason,
18
+ * never the value.
19
+ */
20
+ export declare function findSensitiveData(value: unknown, options?: SensitiveDataOptions): SensitiveFinding[];
21
+ /** Fails when the response body exposes something sensitive. The message lists paths and reasons, never values. */
22
+ export declare function expectNoSensitiveData(response: Pick<ApiResult, 'status' | 'body'>, options?: SensitiveDataOptions): void;
@@ -0,0 +1,76 @@
1
+ import assert from 'node:assert/strict';
2
+ import { credentialIn, keyWords } from '../reporting/redaction.js';
3
+ const WORDS = new Set(['password', 'passwd', 'passphrase', 'secret', 'pin', 'otp', 'cvv', 'cvc', 'ssn', 'token']);
4
+ const COMPOUNDS = ['password', 'passwd', 'passphrase', 'secret', 'privatekey', 'apikey', 'credential', 'token'];
5
+ /** Names that contain a trigger word but are ordinary: `token_type`, pagination cursors. */
6
+ const HARMLESS = new Set(['tokentype', 'nextpagetoken', 'pagetoken', 'nexttoken', 'continuationtoken', 'expiresin']);
7
+ const MAX_DEPTH = 30;
8
+ function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
9
+ function compactName(key) { return keyWords(key).join(''); }
10
+ function suggestsSecret(key) {
11
+ const compact = compactName(key);
12
+ if (HARMLESS.has(compact))
13
+ return false;
14
+ return keyWords(key).some(word => WORDS.has(word)) || COMPOUNDS.some(name => compact.includes(name));
15
+ }
16
+ /** A secret-looking property only matters when it carries something: null, a boolean flag ("hasPassword") and "" expose nothing. */
17
+ function carriesValue(value) {
18
+ if (value === null || value === undefined || typeof value === 'boolean')
19
+ return false;
20
+ if (typeof value === 'string')
21
+ return value.length > 0;
22
+ if (Array.isArray(value))
23
+ return value.length > 0;
24
+ if (isRecord(value))
25
+ return Object.keys(value).length > 0;
26
+ return true;
27
+ }
28
+ function normalizePath(path) { return path.replace(/\[\d+\]/g, '[*]'); }
29
+ /**
30
+ * Finds secrets that a response should not expose (excessive data exposure): properties whose names suggest a password, token,
31
+ * key or similar and that carry a value, and string values that look like credentials. Findings name the path and the reason,
32
+ * never the value.
33
+ */
34
+ export function findSensitiveData(value, options = {}) {
35
+ const allowedKeys = new Set((options.allowKeys ?? []).map(compactName));
36
+ const allowedPaths = new Set((options.allowPaths ?? []).map(normalizePath));
37
+ const checkValues = options.checkValues !== false;
38
+ const findings = [];
39
+ const visit = (node, path, normalized, depth) => {
40
+ if (depth > MAX_DEPTH)
41
+ return;
42
+ if (Array.isArray(node)) {
43
+ node.forEach((item, index) => visit(item, `${path}[${index}]`, `${normalized}[*]`, depth + 1));
44
+ }
45
+ else if (isRecord(node)) {
46
+ for (const [key, child] of Object.entries(node)) {
47
+ const here = `${path}.${key}`;
48
+ const generic = `${normalized}.${key}`;
49
+ if (allowedPaths.has(generic) || allowedKeys.has(compactName(key)))
50
+ continue;
51
+ if (suggestsSecret(key) && carriesValue(child)) {
52
+ findings.push({ path: here, reason: 'the property name suggests a secret' });
53
+ continue;
54
+ }
55
+ visit(child, here, generic, depth + 1);
56
+ }
57
+ }
58
+ else if (typeof node === 'string' && checkValues && !allowedPaths.has(normalized)) {
59
+ const kind = credentialIn(node);
60
+ if (kind !== undefined)
61
+ findings.push({ path, reason: `the value looks like ${kind}` });
62
+ }
63
+ };
64
+ visit(value, '$', '$', 0);
65
+ return findings;
66
+ }
67
+ /** Fails when the response body exposes something sensitive. The message lists paths and reasons, never values. */
68
+ export function expectNoSensitiveData(response, options = {}) {
69
+ const findings = findSensitiveData(response.body, options);
70
+ if (!findings.length)
71
+ return;
72
+ const shown = findings.slice(0, 10).map(finding => `- ${finding.path}: ${finding.reason}`);
73
+ if (findings.length > 10)
74
+ shown.push(`- ... and ${findings.length - 10} more`);
75
+ assert.fail(`The response body (HTTP ${response.status}) exposes sensitive data:\n${shown.join('\n')}`);
76
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Evaluates a small JSONPath subset against parsed JSON and returns every match, in document order:
3
+ * `$`, `.name`, `['name']`, `[0]`, `[-1]`, `[*]`, `.*`, `..name`, `..*`. Filters, slices and unions throw: a path the library cannot
4
+ * evaluate must not silently match nothing. Only a value's own properties are read, never inherited ones.
5
+ */
6
+ export declare function jsonPath(value: unknown, path: string): unknown[];
@@ -0,0 +1,97 @@
1
+ const NAME = /^[A-Za-z0-9_$-]+/;
2
+ const MAX_DEPTH = 100;
3
+ function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
4
+ function hasOwn(value, key) { return Object.prototype.hasOwnProperty.call(value, key); }
5
+ function childrenOf(node) { return Array.isArray(node) ? node : isRecord(node) ? Object.values(node) : []; }
6
+ function parse(path) {
7
+ if (!path.startsWith('$'))
8
+ throw new Error('A JSONPath must start with $');
9
+ const steps = [];
10
+ let index = 1;
11
+ const unsupported = () => { throw new Error(`Unsupported JSONPath syntax at position ${index} in "${path}"`); };
12
+ while (index < path.length) {
13
+ if (path[index] === '.') {
14
+ const descendant = path[index + 1] === '.';
15
+ index += descendant ? 2 : 1;
16
+ if (path[index] === '*') {
17
+ steps.push(descendant ? { kind: 'descendant', name: '*' } : { kind: 'wildcard' });
18
+ index++;
19
+ continue;
20
+ }
21
+ const name = NAME.exec(path.slice(index))?.[0];
22
+ if (name === undefined)
23
+ return unsupported();
24
+ steps.push(descendant ? { kind: 'descendant', name } : { kind: 'child', name });
25
+ index += name.length;
26
+ }
27
+ else if (path[index] === '[') {
28
+ const rest = path.slice(index + 1);
29
+ const wildcard = /^\*\]/.exec(rest);
30
+ const numeric = /^(-?\d+)\]/.exec(rest);
31
+ const single = /^'((?:[^'\\]|\\.)*)'\]/.exec(rest);
32
+ const double = /^"((?:[^"\\]|\\.)*)"\]/.exec(rest);
33
+ const text = single ?? double;
34
+ if (wildcard) {
35
+ steps.push({ kind: 'wildcard' });
36
+ index += 1 + wildcard[0].length;
37
+ }
38
+ else if (numeric?.[1] !== undefined) {
39
+ steps.push({ kind: 'index', index: Number(numeric[1]) });
40
+ index += 1 + numeric[0].length;
41
+ }
42
+ else if (text?.[1] !== undefined) {
43
+ steps.push({ kind: 'child', name: text[1].replace(/\\(.)/g, '$1') });
44
+ index += 1 + text[0].length;
45
+ }
46
+ else
47
+ return unsupported(); // filters, slices and unions
48
+ }
49
+ else {
50
+ return unsupported();
51
+ }
52
+ }
53
+ return steps;
54
+ }
55
+ function descend(node, name, out, depth) {
56
+ if (depth > MAX_DEPTH)
57
+ return;
58
+ if (isRecord(node) && name !== '*' && hasOwn(node, name))
59
+ out.push(node[name]);
60
+ for (const child of childrenOf(node)) {
61
+ if (name === '*')
62
+ out.push(child);
63
+ descend(child, name, out, depth + 1);
64
+ }
65
+ }
66
+ /**
67
+ * Evaluates a small JSONPath subset against parsed JSON and returns every match, in document order:
68
+ * `$`, `.name`, `['name']`, `[0]`, `[-1]`, `[*]`, `.*`, `..name`, `..*`. Filters, slices and unions throw: a path the library cannot
69
+ * evaluate must not silently match nothing. Only a value's own properties are read, never inherited ones.
70
+ */
71
+ export function jsonPath(value, path) {
72
+ let nodes = [value];
73
+ for (const step of parse(path)) {
74
+ const next = [];
75
+ for (const node of nodes) {
76
+ if (step.kind === 'child') {
77
+ if (isRecord(node) && hasOwn(node, step.name))
78
+ next.push(node[step.name]);
79
+ }
80
+ else if (step.kind === 'index') {
81
+ if (Array.isArray(node)) {
82
+ const position = step.index < 0 ? node.length + step.index : step.index;
83
+ if (position >= 0 && position < node.length)
84
+ next.push(node[position]);
85
+ }
86
+ }
87
+ else if (step.kind === 'wildcard') {
88
+ next.push(...childrenOf(node));
89
+ }
90
+ else {
91
+ descend(node, step.name, next, 0);
92
+ }
93
+ }
94
+ nodes = next;
95
+ }
96
+ return nodes;
97
+ }
@@ -0,0 +1,85 @@
1
+ /** A performance smoke test is not a load generator: these limits are fixed. Use a dedicated tool (k6, Gatling) for real load. */
2
+ export declare const MAX_LOAD_REQUESTS = 1000;
3
+ export declare const MAX_LOAD_CONCURRENCY = 50;
4
+ export declare const MAX_LOAD_WARMUP = 20;
5
+ export interface LoadOptions {
6
+ /** Requests that are measured. Default 50, at most 1000. */
7
+ requests?: number | undefined;
8
+ /** Requests in flight at once. Default 5, at most 50. */
9
+ concurrency?: number | undefined;
10
+ /** Requests sent first, one phase before the measured ones, and left out of the figures (connections, caches, cold starts). Default 3, at most 20. */
11
+ warmup?: number | undefined;
12
+ /** Stop sending once this many requests (warm-up included) have failed, so a broken endpoint is not hammered. Default 25 or the total, whichever is smaller. */
13
+ abortAfterFailures?: number | undefined;
14
+ /** What counts as success. Default: a status below 400. A request that throws always fails. */
15
+ isSuccess?: ((status: number) => boolean) | undefined;
16
+ /** Stop sending when this signal aborts. */
17
+ signal?: AbortSignal | undefined;
18
+ /** Milliseconds from any fixed origin, for tests with a fake clock. Default `performance.now`. */
19
+ now?: (() => number) | undefined;
20
+ }
21
+ export interface LatencyStats {
22
+ min: number;
23
+ mean: number;
24
+ p50: number;
25
+ p90: number;
26
+ p95: number;
27
+ p99: number;
28
+ max: number;
29
+ }
30
+ export interface LoadReport {
31
+ /** Measured requests that finished (warm-up is not counted). */
32
+ requests: number;
33
+ succeeded: number;
34
+ failed: number;
35
+ /** failed / requests, from 0 to 1; 0 when nothing was measured. */
36
+ errorRate: number;
37
+ concurrency: number;
38
+ warmup: number;
39
+ /** Warm-up requests that failed. They count towards `abortAfterFailures` but not towards the figures. */
40
+ warmupFailures: number;
41
+ /** From the first measured request starting to the last one finishing, in ms. */
42
+ durationMs: number;
43
+ /** Measured requests per second over `durationMs`; 0 when that is 0. */
44
+ throughput: number;
45
+ /** In ms, measured around each call to `send`. Percentiles use the nearest-rank method. */
46
+ latency: LatencyStats;
47
+ /** Measured responses by status, e.g. `{ '200': 48, '503': 2 }`. */
48
+ statuses: Record<string, number>;
49
+ /** Measured requests that threw, by error name. */
50
+ errors: Record<string, number>;
51
+ /** True when sending stopped before the planned number of requests. */
52
+ aborted: boolean;
53
+ abortReason?: string | undefined;
54
+ }
55
+ export interface LoadLimits {
56
+ /** Latency ceilings in ms: the figure must be at or below the limit. */
57
+ p50Ms?: number | undefined;
58
+ p90Ms?: number | undefined;
59
+ p95Ms?: number | undefined;
60
+ p99Ms?: number | undefined;
61
+ meanMs?: number | undefined;
62
+ maxMs?: number | undefined;
63
+ /** The highest share of failed requests allowed, from 0 to 1. Default 0: no failures. */
64
+ maxErrorRate?: number | undefined;
65
+ /** The lowest throughput allowed, in requests per second. */
66
+ minThroughput?: number | undefined;
67
+ }
68
+ /**
69
+ * Sends `send()` many times, a few at once, and measures how long each takes: a performance smoke test. It runs a warm-up phase that is
70
+ * not counted, then the measured requests, and reports latency percentiles, throughput, statuses and error names (never bodies).
71
+ * `send` is yours: pass `() => api.request(...)` with a client that enforces your execution policy and a read-only run cannot produce
72
+ * write traffic, because every refused request throws and the run stops after `abortAfterFailures` of them.
73
+ * Latency is measured around each call to `send`, so it includes the client's own work and any retries.
74
+ */
75
+ export declare function runLoad(send: () => Promise<{
76
+ status: number;
77
+ }>, options?: LoadOptions): Promise<LoadReport>;
78
+ /** One line for the log: what ran, how fast, and what came back. */
79
+ export declare function summarizeLoad(report: LoadReport): string;
80
+ /**
81
+ * Fails when the report breaks a limit, and lists every limit it breaks. No failures are allowed unless `maxErrorRate` says otherwise;
82
+ * a run that stopped early or measured nothing always fails. A limit that is not a finite number of at least 0 throws, because a
83
+ * comparison with it would silently pass. Returns the report.
84
+ */
85
+ export declare function expectLoad(report: LoadReport, limits?: LoadLimits): LoadReport;
@@ -0,0 +1,134 @@
1
+ import assert from 'node:assert/strict';
2
+ import { performance } from 'node:perf_hooks';
3
+ /** A performance smoke test is not a load generator: these limits are fixed. Use a dedicated tool (k6, Gatling) for real load. */
4
+ export const MAX_LOAD_REQUESTS = 1000;
5
+ export const MAX_LOAD_CONCURRENCY = 50;
6
+ export const MAX_LOAD_WARMUP = 20;
7
+ const DEFAULT_REQUESTS = 50;
8
+ const DEFAULT_CONCURRENCY = 5;
9
+ const DEFAULT_WARMUP = 3;
10
+ const DEFAULT_ABORT_AFTER = 25;
11
+ function bounded(name, value, min, max) {
12
+ if (!Number.isInteger(value) || value < min || value > max)
13
+ throw new Error(`${name} must be a whole number from ${min} to ${max}${name === 'requests' || name === 'concurrency' || name === 'warmup' ? ' (a smoke test is not a load generator: use k6 or Gatling for real load)' : ''}`);
14
+ return value;
15
+ }
16
+ function nearestRank(sorted, percentile) {
17
+ const rank = Math.max(1, Math.ceil(percentile / 100 * sorted.length));
18
+ return sorted[Math.min(rank, sorted.length) - 1] ?? 0;
19
+ }
20
+ const tenth = (value) => Math.round(value * 10) / 10;
21
+ /**
22
+ * Sends `send()` many times, a few at once, and measures how long each takes: a performance smoke test. It runs a warm-up phase that is
23
+ * not counted, then the measured requests, and reports latency percentiles, throughput, statuses and error names (never bodies).
24
+ * `send` is yours: pass `() => api.request(...)` with a client that enforces your execution policy and a read-only run cannot produce
25
+ * write traffic, because every refused request throws and the run stops after `abortAfterFailures` of them.
26
+ * Latency is measured around each call to `send`, so it includes the client's own work and any retries.
27
+ */
28
+ export async function runLoad(send, options = {}) {
29
+ const requests = bounded('requests', options.requests ?? DEFAULT_REQUESTS, 1, MAX_LOAD_REQUESTS);
30
+ const warmup = bounded('warmup', options.warmup ?? DEFAULT_WARMUP, 0, MAX_LOAD_WARMUP);
31
+ const concurrency = bounded('concurrency', options.concurrency ?? DEFAULT_CONCURRENCY, 1, MAX_LOAD_CONCURRENCY);
32
+ const abortAfter = bounded('abortAfterFailures', options.abortAfterFailures ?? Math.min(requests + warmup, DEFAULT_ABORT_AFTER), 1, requests + warmup);
33
+ const isSuccess = options.isSuccess ?? ((status) => status < 400);
34
+ const now = options.now ?? (() => performance.now());
35
+ const samples = [];
36
+ let failures = 0;
37
+ let warmupFailures = 0;
38
+ let abortReason;
39
+ const phase = async (count, measured) => {
40
+ let next = 0;
41
+ const worker = async () => {
42
+ while (next < count && abortReason === undefined && options.signal?.aborted !== true) {
43
+ next += 1;
44
+ const started = now();
45
+ let status;
46
+ let error;
47
+ try {
48
+ status = (await send()).status;
49
+ if (typeof status !== 'number')
50
+ error = 'NoStatus';
51
+ }
52
+ catch (caught) {
53
+ error = caught instanceof Error ? caught.name : 'Error';
54
+ }
55
+ const ended = now();
56
+ const ok = error === undefined && status !== undefined && isSuccess(status);
57
+ if (!ok) {
58
+ failures += 1;
59
+ if (!measured)
60
+ warmupFailures += 1;
61
+ if (failures >= abortAfter && abortReason === undefined)
62
+ abortReason = `stopped after ${failures} failure${failures === 1 ? '' : 's'}`;
63
+ }
64
+ if (measured)
65
+ samples.push({ started, ended, status, error, ok });
66
+ }
67
+ };
68
+ await Promise.all(Array.from({ length: Math.min(concurrency, count) }, worker));
69
+ };
70
+ if (warmup > 0)
71
+ await phase(warmup, false);
72
+ await phase(requests, true);
73
+ if (abortReason === undefined && options.signal?.aborted === true && samples.length < requests)
74
+ abortReason = 'aborted by the caller';
75
+ const latencies = samples.map(sample => sample.ended - sample.started).sort((a, b) => a - b);
76
+ const statuses = {};
77
+ const errors = {};
78
+ for (const sample of samples) {
79
+ if (sample.error !== undefined)
80
+ errors[sample.error] = (errors[sample.error] ?? 0) + 1;
81
+ else if (sample.status !== undefined)
82
+ statuses[String(sample.status)] = (statuses[String(sample.status)] ?? 0) + 1;
83
+ }
84
+ const failed = samples.filter(sample => !sample.ok).length;
85
+ const durationMs = samples.length ? Math.max(...samples.map(sample => sample.ended)) - Math.min(...samples.map(sample => sample.started)) : 0;
86
+ return {
87
+ requests: samples.length, succeeded: samples.length - failed, failed, errorRate: samples.length ? failed / samples.length : 0,
88
+ concurrency, warmup, warmupFailures, durationMs: tenth(durationMs), throughput: durationMs > 0 ? tenth(samples.length / (durationMs / 1000)) : 0,
89
+ latency: latencies.length
90
+ ? { min: tenth(latencies[0] ?? 0), mean: tenth(latencies.reduce((sum, value) => sum + value, 0) / latencies.length), p50: tenth(nearestRank(latencies, 50)), p90: tenth(nearestRank(latencies, 90)), p95: tenth(nearestRank(latencies, 95)), p99: tenth(nearestRank(latencies, 99)), max: tenth(latencies[latencies.length - 1] ?? 0) }
91
+ : { min: 0, mean: 0, p50: 0, p90: 0, p95: 0, p99: 0, max: 0 },
92
+ statuses, errors, aborted: abortReason !== undefined, abortReason
93
+ };
94
+ }
95
+ const percent = (rate) => `${tenth(rate * 100)}%`;
96
+ const counts = (table) => Object.entries(table).map(([name, count]) => `${name}×${count}`).join(', ');
97
+ /** One line for the log: what ran, how fast, and what came back. */
98
+ export function summarizeLoad(report) {
99
+ const { latency } = report;
100
+ const outcome = [Object.keys(report.statuses).length ? `statuses ${counts(report.statuses)}` : '', Object.keys(report.errors).length ? `errors ${counts(report.errors)}` : ''].filter(Boolean).join('; ');
101
+ return `${report.requests} requests (${report.warmup} warm-up), ${report.concurrency} at a time, ${report.durationMs} ms, ${report.throughput} requests/s; latency ms: min ${latency.min}, mean ${latency.mean}, p50 ${latency.p50}, p90 ${latency.p90}, p95 ${latency.p95}, p99 ${latency.p99}, max ${latency.max}${outcome ? `; ${outcome}` : ''}${report.aborted ? `; ${report.abortReason ?? 'stopped early'}` : ''}`;
102
+ }
103
+ const LATENCY_LIMITS = [['p50', 'p50Ms'], ['p90', 'p90Ms'], ['p95', 'p95Ms'], ['p99', 'p99Ms'], ['mean', 'meanMs'], ['max', 'maxMs']];
104
+ /**
105
+ * Fails when the report breaks a limit, and lists every limit it breaks. No failures are allowed unless `maxErrorRate` says otherwise;
106
+ * a run that stopped early or measured nothing always fails. A limit that is not a finite number of at least 0 throws, because a
107
+ * comparison with it would silently pass. Returns the report.
108
+ */
109
+ export function expectLoad(report, limits = {}) {
110
+ for (const [name, value] of Object.entries(limits)) {
111
+ if (value !== undefined && (!Number.isFinite(value) || value < 0))
112
+ throw new Error(`Load limit ${name} must be a number of at least 0`);
113
+ }
114
+ if (limits.maxErrorRate !== undefined && limits.maxErrorRate > 1)
115
+ throw new Error('Load limit maxErrorRate is a share from 0 to 1');
116
+ const problems = [];
117
+ if (report.aborted)
118
+ problems.push(`the run ${report.abortReason ?? 'stopped early'}`);
119
+ else if (report.requests === 0)
120
+ problems.push('no request was measured');
121
+ const allowed = limits.maxErrorRate ?? 0;
122
+ if (report.errorRate > allowed)
123
+ problems.push(`error rate ${percent(report.errorRate)} (${report.failed} of ${report.requests}) is above ${percent(allowed)}`);
124
+ for (const [label, key] of LATENCY_LIMITS) {
125
+ const limit = limits[key];
126
+ if (limit !== undefined && report.latency[label] > limit)
127
+ problems.push(`${label} latency ${report.latency[label]} ms is above ${limit} ms`);
128
+ }
129
+ if (limits.minThroughput !== undefined && report.throughput < limits.minThroughput)
130
+ problems.push(`throughput ${report.throughput} requests/s is below ${limits.minThroughput}`);
131
+ if (problems.length)
132
+ assert.fail(`Load check failed:\n- ${problems.join('\n- ')}\n${summarizeLoad(report)}`);
133
+ return report;
134
+ }
@@ -0,0 +1,63 @@
1
+ export interface MatchOptions {
2
+ /** Include the actual values in failure messages. Off by default: responses may hold sensitive data, so messages describe the type instead. */
3
+ showValues?: boolean | undefined;
4
+ }
5
+ export interface MatchResult {
6
+ pass: boolean;
7
+ problems: string[];
8
+ }
9
+ export type MatchType = 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null';
10
+ interface Context {
11
+ showValues: boolean;
12
+ }
13
+ type Check = (actual: unknown, path: string, context: Context) => string[];
14
+ /** An expectation that is more than equality. Build one with `match.*`; plain values and objects can be mixed with them. */
15
+ export declare class Matcher {
16
+ readonly description: string;
17
+ readonly check: Check;
18
+ readonly absent: boolean;
19
+ constructor(description: string, check: Check, absent?: boolean);
20
+ }
21
+ /** Matchers for the parts of a response that are not fixed values. */
22
+ export declare const match: {
23
+ /** Any value, as long as the property is present. */
24
+ anything: () => Matcher;
25
+ any: (type: MatchType) => Matcher;
26
+ /** A string, optionally matching a pattern. */
27
+ string: (pattern?: RegExp) => Matcher;
28
+ /** A number, optionally within a range (inclusive). */
29
+ number: (range?: {
30
+ min?: number;
31
+ max?: number;
32
+ }) => Matcher;
33
+ oneOf: (...values: unknown[]) => Matcher;
34
+ /** An array whose every item matches. */
35
+ arrayOf: (expected: unknown, options?: {
36
+ minLength?: number;
37
+ }) => Matcher;
38
+ /** An array that holds, in any order and among others, an item matching each of these. */
39
+ arrayContaining: (...expected: unknown[]) => Matcher;
40
+ /** A string or array of this length, or within these limits. */
41
+ length: (expected: number | {
42
+ min?: number;
43
+ max?: number;
44
+ }) => Matcher;
45
+ /** Deep equality with no extra properties allowed, unlike a plain object which only has to be contained. */
46
+ exactly: (expected: unknown) => Matcher;
47
+ not: (expected: unknown) => Matcher;
48
+ /** The property must not be present. */
49
+ absent: () => Matcher;
50
+ uuid: () => Matcher;
51
+ /** An ISO 8601 date-time with a timezone, such as 2026-01-02T03:04:05Z. */
52
+ dateTime: () => Matcher;
53
+ };
54
+ /**
55
+ * Compares a value with an expectation. Objects only have to contain the expected properties; arrays must have the same length
56
+ * item for item; use `match.*` for anything flexible. Problems carry their path, e.g. `$.accounts[0].status`.
57
+ */
58
+ export declare function matches(actual: unknown, expected: unknown, options?: MatchOptions): MatchResult;
59
+ /** Throws listing every problem (at most ten). Actual values are described by type unless `showValues` is set. */
60
+ export declare function assertMatches(actual: unknown, expected: unknown, options?: MatchOptions & {
61
+ label?: string | undefined;
62
+ }): void;
63
+ export {};