@nikhil-qeas/api-core 0.6.0 → 0.7.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 (47) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +140 -4
  3. package/bin/qe-api.js +2 -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 +5 -0
  11. package/dist/http/api-client.js +30 -6
  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/types.d.ts +16 -0
  17. package/dist/index.d.ts +21 -2
  18. package/dist/index.js +11 -1
  19. package/dist/reporting/redaction.d.ts +4 -0
  20. package/dist/reporting/redaction.js +26 -2
  21. package/dist/security/authorization-matrix.d.ts +55 -0
  22. package/dist/security/authorization-matrix.js +102 -0
  23. package/dist/security/headers.d.ts +21 -0
  24. package/dist/security/headers.js +45 -0
  25. package/dist/security/policy.js +3 -2
  26. package/dist/security/sensitive-data.d.ts +22 -0
  27. package/dist/security/sensitive-data.js +76 -0
  28. package/dist/testing/json-path.d.ts +6 -0
  29. package/dist/testing/json-path.js +97 -0
  30. package/dist/testing/matchers.d.ts +63 -0
  31. package/dist/testing/matchers.js +164 -0
  32. package/dist/testing/spec-cases.d.ts +98 -0
  33. package/dist/testing/spec-cases.js +795 -0
  34. package/dist/testing/wait-for.d.ts +40 -0
  35. package/dist/testing/wait-for.js +82 -0
  36. package/package.json +1 -1
  37. package/templates/project/README.md +44 -2
  38. package/templates/project/openapi/openapi.json +243 -19
  39. package/templates/project/tests/negative/spec-cases.spec.ts +48 -0
  40. package/templates/project/tests/security/authorization.spec.ts +29 -0
  41. package/templates/project/tests/security/hygiene.spec.ts +37 -0
  42. package/templates/project/tests/security/spec-cases.spec.ts +24 -0
  43. package/templates/project/tests/security/write-protection.spec.ts +2 -2
  44. package/templates/project/tests/smoke/health.spec.ts +3 -3
  45. package/templates/project/tests/support/approved-writes.ts +27 -0
  46. package/templates/project/tests/support/identities.ts +24 -0
  47. package/templates/project/tests/support/mock-api.ts +57 -3
@@ -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 {};
@@ -0,0 +1,164 @@
1
+ import assert from 'node:assert/strict';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ /** An expectation that is more than equality. Build one with `match.*`; plain values and objects can be mixed with them. */
4
+ export class Matcher {
5
+ description;
6
+ check;
7
+ absent;
8
+ constructor(description, check, absent = false) {
9
+ this.description = description;
10
+ this.check = check;
11
+ this.absent = absent;
12
+ }
13
+ }
14
+ function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); }
15
+ function hasOwn(value, key) { return Object.prototype.hasOwnProperty.call(value, key); }
16
+ function kindOf(value) {
17
+ if (value === null)
18
+ return 'null';
19
+ if (Array.isArray(value))
20
+ return 'array';
21
+ return typeof value;
22
+ }
23
+ function describeActual(value, context) {
24
+ if (context.showValues) {
25
+ try {
26
+ const text = JSON.stringify(value) ?? String(value);
27
+ return text.length > 80 ? `${text.slice(0, 77)}...` : text;
28
+ }
29
+ catch {
30
+ return '[not serializable]';
31
+ }
32
+ }
33
+ if (value === null)
34
+ return 'null';
35
+ if (Array.isArray(value))
36
+ return `an array of ${value.length} item${value.length === 1 ? '' : 's'}`;
37
+ const kind = typeof value;
38
+ return kind === 'object' ? 'an object' : kind === 'undefined' ? 'nothing' : `a ${kind}`;
39
+ }
40
+ function describeExpected(expected) {
41
+ if (expected instanceof Matcher)
42
+ return expected.description;
43
+ const text = JSON.stringify(expected) ?? String(expected);
44
+ return text.length > 80 ? `${text.slice(0, 77)}...` : text;
45
+ }
46
+ function isType(value, type) {
47
+ if (type === 'integer')
48
+ return typeof value === 'number' && Number.isInteger(value);
49
+ if (type === 'object')
50
+ return isRecord(value);
51
+ return kindOf(value) === type;
52
+ }
53
+ function matchValue(actual, expected, path, context) {
54
+ if (expected instanceof Matcher)
55
+ return expected.check(actual, path, context);
56
+ if (Array.isArray(expected)) {
57
+ if (!Array.isArray(actual))
58
+ return [`${path}: expected an array but got ${describeActual(actual, context)}`];
59
+ if (actual.length !== expected.length)
60
+ return [`${path}: expected ${expected.length} item${expected.length === 1 ? '' : 's'} but got ${actual.length}`];
61
+ return expected.flatMap((item, index) => matchValue(actual[index], item, `${path}[${index}]`, context));
62
+ }
63
+ if (isRecord(expected)) {
64
+ if (!isRecord(actual))
65
+ return [`${path}: expected an object but got ${describeActual(actual, context)}`];
66
+ const problems = [];
67
+ for (const [key, value] of Object.entries(expected)) {
68
+ const at = `${path}.${key}`;
69
+ const present = hasOwn(actual, key);
70
+ if (value instanceof Matcher && value.absent) {
71
+ if (present)
72
+ problems.push(`${at}: should be absent`);
73
+ continue;
74
+ }
75
+ if (!present) {
76
+ problems.push(`${at}: is missing`);
77
+ continue;
78
+ }
79
+ problems.push(...matchValue(actual[key], value, at, context));
80
+ }
81
+ return problems;
82
+ }
83
+ if (Object.is(actual, expected) || actual === expected)
84
+ return [];
85
+ const sameKind = kindOf(actual) === kindOf(expected);
86
+ return [`${path}: expected ${describeExpected(expected)} but got ${context.showValues || !sameKind ? describeActual(actual, context) : `a different ${kindOf(actual)}`}`];
87
+ }
88
+ /** Matchers for the parts of a response that are not fixed values. */
89
+ export const match = {
90
+ /** Any value, as long as the property is present. */
91
+ anything: () => new Matcher('anything', () => []),
92
+ any: (type) => new Matcher(`any ${type}`, (actual, path, context) => isType(actual, type) ? [] : [`${path}: expected a ${type} but got ${describeActual(actual, context)}`]),
93
+ /** A string, optionally matching a pattern. */
94
+ string: (pattern) => {
95
+ const safe = pattern === undefined ? undefined : new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
96
+ return new Matcher(safe ? `a string matching ${String(pattern)}` : 'any string', (actual, path, context) => {
97
+ if (typeof actual !== 'string')
98
+ return [`${path}: expected a string but got ${describeActual(actual, context)}`];
99
+ return safe && !safe.test(actual) ? [`${path}: expected a string matching ${String(pattern)} but it does not`] : [];
100
+ });
101
+ },
102
+ /** A number, optionally within a range (inclusive). */
103
+ number: (range = {}) => new Matcher('a number in range', (actual, path, context) => {
104
+ if (typeof actual !== 'number')
105
+ return [`${path}: expected a number but got ${describeActual(actual, context)}`];
106
+ if (range.min !== undefined && actual < range.min)
107
+ return [`${path}: expected at least ${range.min} but it is below`];
108
+ if (range.max !== undefined && actual > range.max)
109
+ return [`${path}: expected at most ${range.max} but it is above`];
110
+ return [];
111
+ }),
112
+ oneOf: (...values) => new Matcher(`one of ${describeExpected(values)}`, (actual, path, context) => values.some(value => isDeepStrictEqual(actual, value)) ? [] : [`${path}: expected one of ${describeExpected(values)} but got ${describeActual(actual, context)}`]),
113
+ /** An array whose every item matches. */
114
+ arrayOf: (expected, options = {}) => new Matcher(`an array of ${describeExpected(expected)}`, (actual, path, context) => {
115
+ if (!Array.isArray(actual))
116
+ return [`${path}: expected an array but got ${describeActual(actual, context)}`];
117
+ const problems = options.minLength !== undefined && actual.length < options.minLength ? [`${path}: expected at least ${options.minLength} items but got ${actual.length}`] : [];
118
+ return [...problems, ...actual.flatMap((item, index) => matchValue(item, expected, `${path}[${index}]`, context))];
119
+ }),
120
+ /** An array that holds, in any order and among others, an item matching each of these. */
121
+ arrayContaining: (...expected) => new Matcher(`an array containing ${describeExpected(expected)}`, (actual, path, context) => {
122
+ if (!Array.isArray(actual))
123
+ return [`${path}: expected an array but got ${describeActual(actual, context)}`];
124
+ return expected.filter(item => !actual.some(candidate => matchValue(candidate, item, path, context).length === 0)).map(item => `${path}: no item matches ${describeExpected(item)}`);
125
+ }),
126
+ /** A string or array of this length, or within these limits. */
127
+ length: (expected) => new Matcher('a given length', (actual, path, context) => {
128
+ if (typeof actual !== 'string' && !Array.isArray(actual))
129
+ return [`${path}: expected a string or array but got ${describeActual(actual, context)}`];
130
+ const range = typeof expected === 'number' ? { min: expected, max: expected } : expected;
131
+ if (range.min !== undefined && actual.length < range.min)
132
+ return [`${path}: expected a length of at least ${range.min} but got ${actual.length}`];
133
+ if (range.max !== undefined && actual.length > range.max)
134
+ return [`${path}: expected a length of at most ${range.max} but got ${actual.length}`];
135
+ return [];
136
+ }),
137
+ /** Deep equality with no extra properties allowed, unlike a plain object which only has to be contained. */
138
+ exactly: (expected) => new Matcher(`exactly ${describeExpected(expected)}`, (actual, path, context) => isDeepStrictEqual(actual, expected) ? [] : [`${path}: expected exactly ${describeExpected(expected)} but got ${describeActual(actual, context)}`]),
139
+ not: (expected) => new Matcher(`not ${describeExpected(expected)}`, (actual, path, context) => matchValue(actual, expected, path, context).length === 0 ? [`${path}: should not match ${describeExpected(expected)}`] : []),
140
+ /** The property must not be present. */
141
+ absent: () => new Matcher('absent', () => [], true),
142
+ uuid: () => match.string(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i),
143
+ /** An ISO 8601 date-time with a timezone, such as 2026-01-02T03:04:05Z. */
144
+ dateTime: () => new Matcher('an ISO 8601 date-time', (actual, path, context) => typeof actual === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/.test(actual) && !Number.isNaN(Date.parse(actual))
145
+ ? [] : [`${path}: expected an ISO 8601 date-time but got ${describeActual(actual, context)}`])
146
+ };
147
+ /**
148
+ * Compares a value with an expectation. Objects only have to contain the expected properties; arrays must have the same length
149
+ * item for item; use `match.*` for anything flexible. Problems carry their path, e.g. `$.accounts[0].status`.
150
+ */
151
+ export function matches(actual, expected, options = {}) {
152
+ const problems = matchValue(actual, expected, '$', { showValues: options.showValues === true });
153
+ return { pass: problems.length === 0, problems };
154
+ }
155
+ /** Throws listing every problem (at most ten). Actual values are described by type unless `showValues` is set. */
156
+ export function assertMatches(actual, expected, options = {}) {
157
+ const { problems } = matches(actual, expected, options);
158
+ if (!problems.length)
159
+ return;
160
+ const shown = problems.slice(0, 10).map(problem => `- ${problem}`);
161
+ if (problems.length > 10)
162
+ shown.push(`- ... and ${problems.length - 10} more`);
163
+ assert.fail(`${options.label ?? 'The value'} does not match what was expected:\n${shown.join('\n')}`);
164
+ }
@@ -0,0 +1,98 @@
1
+ import type { OpenApiDocument, RequestCheck } from '../contracts/openapi.js';
2
+ import type { ApiRequest, ApiResult, Method, Query } from '../http/types.js';
3
+ type Primitive = string | number | boolean;
4
+ export type CaseKind = 'valid' | 'negative' | 'fuzz' | 'security';
5
+ export interface OperationRef {
6
+ method: Method;
7
+ path: string;
8
+ }
9
+ export interface OperationInfo extends OperationRef {
10
+ operationId?: string | undefined;
11
+ tags: string[];
12
+ /** True when the operation takes a JSON request body, which is the only kind of body cases are generated for. */
13
+ jsonBody: boolean;
14
+ /** True when the operation needs credentials: it (or the document) declares a security requirement and none of the alternatives is optional. */
15
+ protected: boolean;
16
+ /** Request body content types the generator cannot build bodies for (multipart, form, XML, ...). */
17
+ unsupportedBody: string[];
18
+ }
19
+ export interface GeneratedCase {
20
+ /** Stable and unique, e.g. "POST /accounts negative #3". */
21
+ id: string;
22
+ /** Ready to use as a test title. */
23
+ name: string;
24
+ kind: CaseKind;
25
+ method: Method;
26
+ /** The OpenAPI path template. The concrete path is in `request.path`. */
27
+ path: string;
28
+ description: string;
29
+ /** What a conforming API does: accept ('success'), reject with a 4xx ('rejected'), or at least not fail with a 5xx ('survives'). */
30
+ expect: 'success' | 'rejected' | 'survives' | 'denied';
31
+ /** For 'denied': the statuses that count as a proper refusal. Usually 401 and 403; 400 is also accepted for malformed credentials. */
32
+ accept?: readonly number[] | undefined;
33
+ /** True when the request breaks a rule the schema states, so `OpenApiValidator.assertRequest(check)` throws. False for transport-level breakage such as malformed JSON. */
34
+ violatesSchema: boolean;
35
+ /** What was done to the otherwise valid request, e.g. "body.name: minLength". */
36
+ violates?: string | undefined;
37
+ /** Send this with `ApiClient.request`. */
38
+ request: ApiRequest;
39
+ /** The same request as spec-checkable parts, for `OpenApiValidator.assertRequest`. Present when the request is JSON-describable. */
40
+ check?: RequestCheck | undefined;
41
+ }
42
+ export interface OpenApiCasesOptions {
43
+ /** Known-good values per operation ("METHOD /path/template"): used instead of generated ones. Needed when a schema cannot be sampled (complex patterns, business rules). */
44
+ baselines?: Readonly<Record<string, {
45
+ pathParams?: Readonly<Record<string, Primitive>> | undefined;
46
+ query?: Query | undefined;
47
+ headers?: Readonly<Record<string, string>> | undefined;
48
+ json?: unknown;
49
+ }>> | undefined;
50
+ /** At most this many fuzz cases per operation, chosen deterministically. Default 60. */
51
+ maxFuzzCases?: number | undefined;
52
+ /** Makes the choice of fuzz cases reproducible. Default 1. */
53
+ seed?: number | undefined;
54
+ }
55
+ /**
56
+ * Builds test cases from an OpenAPI document: a valid request per operation, requests that break the spec's rules one at a time
57
+ * (negative), and hostile or extreme values (fuzz). Every negative case names the rule it breaks, and can be confirmed against the
58
+ * spec with `OpenApiValidator.assertRequest(case.check)`. Cases for POST, PUT, PATCH and DELETE send writes: run them only
59
+ * against an environment that may be written to.
60
+ */
61
+ export declare class OpenApiCases {
62
+ private readonly doc;
63
+ private readonly options;
64
+ private readonly operationsByKey;
65
+ constructor(doc: OpenApiDocument, options?: OpenApiCasesOptions);
66
+ operations(filter?: {
67
+ methods?: readonly Method[];
68
+ tags?: readonly string[];
69
+ }): OperationInfo[];
70
+ /** One request that satisfies the spec. Expect it to be accepted. */
71
+ valid(reference: OperationRef): GeneratedCase;
72
+ /** Requests that each break exactly one rule of the spec. Expect a 4xx for every one. */
73
+ negative(reference: OperationRef): GeneratedCase[];
74
+ /** Hostile and extreme values in every string and number field. Expect the API to answer without failing (no 5xx); 2xx and 4xx are both acceptable. */
75
+ fuzz(reference: OperationRef): GeneratedCase[];
76
+ /**
77
+ * Authentication cases for a protected operation: no credentials, invalid credentials of each kind the spec declares (bearer, Basic,
78
+ * API key in a header, query or cookie), an empty bearer token and credentials of the wrong type. Each must be refused with a 401 or
79
+ * 403 (a 400 is also accepted for malformed credentials). An operation without a security requirement, or with optional
80
+ * authentication, has none. The requests are sent without the client's own credentials (`skipAuth`).
81
+ */
82
+ security(reference: OperationRef): GeneratedCase[];
83
+ private buildOperation;
84
+ /** The wrong credentials worth trying for the schemes the requirements name. */
85
+ private credentialsFor;
86
+ private find;
87
+ /** A request that satisfies the spec: required parameters, an example or sampled body, and any known-good values the caller supplied. */
88
+ private baseline;
89
+ private makeCase;
90
+ /** Picks `limit` of `count` candidates reproducibly (seeded shuffle), keeping their original order. */
91
+ private choose;
92
+ }
93
+ /**
94
+ * Judges a response to a generated case. The message names the case and the rule it broke, and never includes the response body.
95
+ * 'success': 2xx. 'rejected': 4xx (accepting invalid input, or failing with a 5xx, is a defect). 'survives': anything below 500.
96
+ */
97
+ export declare function assertCaseOutcome(response: Pick<ApiResult, 'status'>, testCase: Pick<GeneratedCase, 'expect' | 'description' | 'method' | 'path' | 'violates' | 'accept'>): void;
98
+ export {};