@nikhil-qeas/api-core 0.0.0-stage → 0.3.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 (44) hide show
  1. package/README.md +109 -2
  2. package/dist/auth/token-manager.d.ts +22 -0
  3. package/dist/auth/token-manager.js +34 -0
  4. package/dist/config/env.d.ts +2 -0
  5. package/dist/config/env.js +12 -0
  6. package/dist/config/project-config.d.ts +9 -0
  7. package/dist/config/project-config.js +15 -0
  8. package/dist/contracts/assertions.d.ts +6 -0
  9. package/dist/contracts/assertions.js +14 -0
  10. package/dist/contracts/openapi.d.ts +29 -0
  11. package/dist/contracts/openapi.js +81 -0
  12. package/dist/contracts/schema.d.ts +23 -0
  13. package/dist/contracts/schema.js +60 -0
  14. package/dist/http/api-client.d.ts +24 -0
  15. package/dist/http/api-client.js +114 -0
  16. package/dist/http/types.d.ts +45 -0
  17. package/dist/http/types.js +1 -0
  18. package/dist/index.d.ts +32 -0
  19. package/dist/index.js +19 -0
  20. package/dist/integrations/mocha.d.ts +9 -0
  21. package/dist/integrations/mocha.js +13 -0
  22. package/dist/reporting/allure-adapter.d.ts +6 -0
  23. package/dist/reporting/allure-adapter.js +7 -0
  24. package/dist/reporting/junit.d.ts +9 -0
  25. package/dist/reporting/junit.js +15 -0
  26. package/dist/reporting/metrics.d.ts +15 -0
  27. package/dist/reporting/metrics.js +13 -0
  28. package/dist/reporting/redaction.d.ts +2 -0
  29. package/dist/reporting/redaction.js +12 -0
  30. package/dist/security/policy.d.ts +9 -0
  31. package/dist/security/policy.js +16 -0
  32. package/dist/testing/concurrency.d.ts +8 -0
  33. package/dist/testing/concurrency.js +23 -0
  34. package/dist/testing/coverage.d.ts +20 -0
  35. package/dist/testing/coverage.js +11 -0
  36. package/dist/testing/data-factory.d.ts +17 -0
  37. package/dist/testing/data-factory.js +33 -0
  38. package/dist/testing/execution-context.d.ts +20 -0
  39. package/dist/testing/execution-context.js +30 -0
  40. package/dist/testing/run-id.d.ts +2 -0
  41. package/dist/testing/run-id.js +3 -0
  42. package/dist/testing/tag-selection.d.ts +4 -0
  43. package/dist/testing/tag-selection.js +4 -0
  44. package/package.json +43 -4
package/README.md CHANGED
@@ -1,3 +1,110 @@
1
- # Temporary Holding Version
1
+ # QE API Automation Core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Shared **browserless** TypeScript API testing foundation consumed by Helios, EAB, Reflect, BaaS and other independent projects. `@qe-automation/api-core` has no runtime WebdriverIO or Mocha dependency: those belong in the **consuming** project's test runner. It can be called from Mocha API tests and from WDIO + Mocha/Healix UI flows. This separation avoids fake browser sessions in API pipelines.
4
+
5
+ ## What is included
6
+
7
+ - `ApiClient`: Node fetch, typed results, timeouts, exact-byte request signer hook, safe read-only retries, correlation and timing events.
8
+ - `TokenManager`: refresh or reacquire, concurrent call deduplication, explicit invalidation.
9
+ - `expectStatus`, `expectClientError`, `expectResponseTime`, `expectContract`: lightweight assertions (a consuming service can adapt AJV/OpenAPI validators).
10
+ - `redact`: metadata redaction helper. **Not a guarantee that arbitrary unstructured text or bank responses are safe to log.** Do not attach raw bodies.
11
+ - Environment validation and run IDs.
12
+ - Node built-in unit tests, versioned npm package metadata, sample GitLab publish pipeline and consuming-project pipeline.
13
+
14
+ ## Design boundaries
15
+
16
+ **Shared core:** HTTP abstraction, auth provider interfaces, safe utilities, contract assertion interface, standard observability.
17
+ **Project-specific:** Helios HMAC canonicalization, PKCE/RSA/login workflows, endpoints, payment/transfer safety gates, test user accounts, schemas, fixtures, Mocha specs, Allure adapters, WDIO/Healix setup, and GitLab deployment policy.
18
+
19
+ ## First run
20
+
21
+ ```bash
22
+ npm install # initial local setup; generate and commit package-lock.json
23
+ npm run check
24
+ npm pack --dry-run
25
+ ```
26
+
27
+ If no lockfile is present, use `npm install` once and commit the generated `package-lock.json` before enabling CI.
28
+
29
+ ## Private GitLab package publishing
30
+
31
+ 1. Create an **internal/private GitLab repository** `QE-API-Automation-Core`, push this source and configure a GitLab runner.
32
+ 2. Run `npm ci && npm run check`; protect release tags and require approval/review.
33
+ 3. Tag a commit matching `package.json` version: `v0.1.0`. The publish job uses `CI_JOB_TOKEN` to push package to that GitLab project's npm registry.
34
+ 4. In every consuming repo, configure `CORE_PROJECT_ID` and the npm scope registry. Ensure the core project permits the consumer CI job token in its allowlist (or use an appropriately scoped, masked registry token).
35
+ 5. Install with `npm install --save-dev @qe-automation/api-core@0.1.0` and commit the resulting lockfile. Never commit secrets or a filled `.npmrc`.
36
+ 6. Version and pin core releases; validate all adopter projects before promoting a breaking release. The GitLab file under `ci/` is a reference, not an immediately enforced enterprise deployment policy.
37
+
38
+ ## Helios adoption strategy
39
+
40
+ **Do not replace the working Helios-Plc-API repository.** First add this package as a dev dependency. Wrap the existing `ApiClient` and signing implementation through the `RequestSigner` interface; introduce module-level usage progressively. Maintain existing workflow logic and test titles. Preserve `HELIOS_ALLOW_MONEY_MOVEMENT` default-deny behavior. Run `npm run typecheck && npm run test:offline` before/after every extraction, then perform dedicated real-environment verification. The included `examples/helios-adoption/` shows a consumer wiring example, not a verified live Helios API integration.
41
+
42
+ ## Current verification scope
43
+
44
+ The unit suite covers safe retry classification, exact-body signing, bearer token deduplication, redaction, invalid config, response assertions and request path constraints. Real Helios, EAB, GitLab runners, npm package publication and browser/device runs require separate live verification. The framework contains no credentials or banking endpoint details.
45
+
46
+ ## Security notes
47
+
48
+ - Never retry POST/payment instructions just because a transport timeout occurred. `idempotent: true` is an explicit opt-in only after server-side idempotency is demonstrated and approved.
49
+ - Default HTTP event metadata excludes headers and bodies. Avoid logging `ApiTransportError.cause`, which can contain native transport information.
50
+ - Contract validation is provided through validator functions; use each product's existing Ajv schemas or OpenAPI tooling in its project.
51
+ - No API calls should run against production without approved non-destructive data and an explicit gated execution policy.
52
+
53
+ ## v0.3.0 enterprise candidate
54
+
55
+ Adds schema subset validation (`validateSchema`/`assertSchema`), synthetic test data with LIFO cleanup, scoped concurrency controls, runner-agnostic tag selection, JUnit metadata output, API metrics aggregation and environment configuration with non-destructive defaults. See `docs/ARCHITECTURE.md` and `docs/RELEASE.md`.
56
+
57
+ **Important:** This is a framework component, not an end-to-end test platform. Full OpenAPI 3.x validation requires an application-approved Ajv/OpenAPI validator. WDIO, Mocha, Allure and GitLab policies live at the project or CI integration layer. Real banking endpoints and GitLab registry publish must be independently verified.
58
+
59
+
60
+ ## Additional v0.3.0 capabilities
61
+
62
+ - `OpenApiValidator(document, compiler)`: OpenAPI 3.0/3.1 response lookup with a supplied Ajv-compatible JSON Schema compiler; local schema refs supported. This is not a built-in full Ajv distribution.
63
+ - `ExecutionContext`: per-run synthetic data, cleanup, bounded in-process account allocation, default-deny mutations.
64
+ - `assertRequestPolicy` / `rejectUnsafeEnvironment`: explicit host and mutation controls (wire them into each project's clients).
65
+ - `attachSafeMetadata`: allowlisted attachments for Allure integrations; no request/response bodies.
66
+ - `MochaResultCollector`: collect test metadata in consuming Mocha hooks; `writeJunit` provides sanitized GitLab-compatible JUnit.
67
+ - `CoverageRegistry`: registered scenario and endpoint execution coverage, not discovery of all real services.
68
+ - `npm run test:ci`: generates JUnit test results for GitLab.
69
+
70
+ ### Verification and limitations
71
+
72
+ The 30 local tests cover existing HTTP/auth features and v0.3.0 adapters. Real bank API tests, complete OpenAPI/Ajv dialect behavior, concurrency across separate CI jobs, security penetration testing, package-registry publishing, and actual GitLab pipeline execution remain external integration gates. Do not represent them as completed based on offline unit tests.
73
+
74
+ See `docs/ARCHITECTURE.md` and `docs/RELEASE.md`.
75
+
76
+
77
+ ## GitHub Packages release and installation
78
+
79
+ The published npm package is `@nikhil197610/api-core` (GitHub repository owner is `nikhil197610`). The shared TypeScript API remains unchanged.
80
+
81
+ ### Maintainer: first release
82
+
83
+ 1. Merge the GitHub Packages publishing pull request into `main`.
84
+ 2. Run `npm ci && npm run check && npm run test:ci` from updated `main`.
85
+ 3. Confirm repository Actions permissions permit workflows to write packages (the workflow requests `packages: write`).
86
+ 4. Tag the verified main commit `v0.3.0` and push it. The tag triggers `.github/workflows/publish.yml`.
87
+ 5. Verify the GitHub Actions workflow succeeded and the package appears under GitHub Packages.
88
+
89
+ ```bash
90
+ git pull origin main
91
+ git tag v0.3.0
92
+ git push origin v0.3.0
93
+ ```
94
+
95
+ Never tag an unmerged feature branch, and do not reuse an existing version tag. A failed workflow does not imply successful publication.
96
+
97
+ ### Team: install from GitHub Packages
98
+
99
+ Create a GitHub Personal Access Token (classic) with `read:packages` and access to this private package. Keep the token in the local environment or an approved secret manager; **never commit a filled .npmrc**.
100
+
101
+ ```bash
102
+ # In each consuming project:
103
+ printf '@nikhil197610:registry=https://npm.pkg.github.com\\n' >> .npmrc
104
+ printf '//npm.pkg.github.com/:_authToken=${GH_PACKAGES_TOKEN}\\n' >> .npmrc
105
+ npm install --save-dev @nikhil197610/api-core@0.3.0
106
+ ```
107
+
108
+ The sample `.npmrc` must contain the literal environment placeholder, not an expanded token. Set `GH_PACKAGES_TOKEN` in the shell before installation. For GitLab CI, configure the token as a masked/protected CI variable. Ensure its account is authorized to read the private GitHub package. Use `npm ci` and the committed consumer lockfile for reproducible builds.
109
+
110
+ The GitLab pipelines can install this GitHub-hosted package, but GitLab's `CI_JOB_TOKEN` cannot authenticate directly to GitHub Packages.
@@ -0,0 +1,22 @@
1
+ export interface Tokens {
2
+ accessToken: string;
3
+ expiresAt?: number;
4
+ refreshToken?: string;
5
+ }
6
+ export interface TokenProvider {
7
+ acquire(): Promise<Tokens>;
8
+ refresh?(old: Tokens): Promise<Tokens>;
9
+ }
10
+ /** Caches tokens and deduplicates concurrent renewals within a worker. */
11
+ export declare class TokenManager {
12
+ private readonly provider;
13
+ private readonly skewMs;
14
+ private readonly now;
15
+ private current;
16
+ private inflight;
17
+ constructor(provider: TokenProvider, skewMs?: number, now?: () => number);
18
+ tokens(): Promise<Tokens>;
19
+ header(): Promise<Record<string, string>>;
20
+ invalidate(): void;
21
+ private renew;
22
+ }
@@ -0,0 +1,34 @@
1
+ /** Caches tokens and deduplicates concurrent renewals within a worker. */
2
+ export class TokenManager {
3
+ provider;
4
+ skewMs;
5
+ now;
6
+ current;
7
+ inflight;
8
+ constructor(provider, skewMs = 30_000, now = Date.now) {
9
+ this.provider = provider;
10
+ this.skewMs = skewMs;
11
+ this.now = now;
12
+ }
13
+ async tokens() {
14
+ if (this.current && (this.current.expiresAt === undefined || this.current.expiresAt - this.skewMs > this.now()))
15
+ return this.current;
16
+ if (!this.inflight) {
17
+ this.inflight = this.renew().finally(() => { this.inflight = undefined; });
18
+ }
19
+ return this.inflight;
20
+ }
21
+ async header() { return { Authorization: `Bearer ${(await this.tokens()).accessToken}` }; }
22
+ invalidate() { this.current = undefined; }
23
+ async renew() {
24
+ if (this.current?.refreshToken && this.provider.refresh) {
25
+ try {
26
+ this.current = await this.provider.refresh(this.current);
27
+ return this.current;
28
+ }
29
+ catch { /* full login */ }
30
+ }
31
+ this.current = await this.provider.acquire();
32
+ return this.current;
33
+ }
34
+ }
@@ -0,0 +1,2 @@
1
+ export declare function requireEnv(names: readonly string[], source?: NodeJS.ProcessEnv): Record<string, string>;
2
+ export declare function envEnum<T extends string>(name: string, choices: readonly T[], defaultValue: T, source?: NodeJS.ProcessEnv): T;
@@ -0,0 +1,12 @@
1
+ export function requireEnv(names, source = process.env) {
2
+ const missing = names.filter(n => !source[n]?.trim());
3
+ if (missing.length)
4
+ throw new Error(`Missing environment variables: ${missing.join(', ')}`);
5
+ return Object.fromEntries(names.map(n => [n, source[n]]));
6
+ }
7
+ export function envEnum(name, choices, defaultValue, source = process.env) {
8
+ const value = source[name] ?? defaultValue;
9
+ if (!choices.includes(value))
10
+ throw new Error(`Invalid ${name}; expected one of: ${choices.join(', ')}`);
11
+ return value;
12
+ }
@@ -0,0 +1,9 @@
1
+ export interface ProjectConfig {
2
+ name: string;
3
+ environment: string;
4
+ baseUrl: string;
5
+ timeoutMs: number;
6
+ allowMutations: boolean;
7
+ }
8
+ /** Strict defaults: side-effecting financial tests must be separately authorised by the consuming project. */
9
+ export declare function loadProjectConfig(env?: Record<string, string | undefined>): ProjectConfig;
@@ -0,0 +1,15 @@
1
+ /** Strict defaults: side-effecting financial tests must be separately authorised by the consuming project. */
2
+ export function loadProjectConfig(env = process.env) {
3
+ const name = env.QE_PROJECT?.trim() || 'api-project';
4
+ const environment = env.QE_ENV?.trim() || 'local';
5
+ const baseUrl = env.QE_BASE_URL?.trim();
6
+ if (!baseUrl)
7
+ throw new Error('Missing QE_BASE_URL');
8
+ const url = new URL(baseUrl);
9
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash)
10
+ throw new Error('Invalid QE_BASE_URL');
11
+ const timeoutMs = Number(env.QE_TIMEOUT_MS ?? 15_000);
12
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 120_000)
13
+ throw new Error('Invalid QE_TIMEOUT_MS');
14
+ return { name, environment, baseUrl, timeoutMs, allowMutations: env.QE_ALLOW_MUTATIONS === 'true' && environment !== 'prod' };
15
+ }
@@ -0,0 +1,6 @@
1
+ import type { ApiResult } from '../http/types.js';
2
+ export declare function expectStatus(response: ApiResult, status: number): void;
3
+ export declare function expectClientError(response: ApiResult): void;
4
+ export declare function expectResponseTime(response: ApiResult, budgetMs: number): void;
5
+ export type Validator<T> = (value: unknown) => value is T;
6
+ export declare function expectContract<T>(response: ApiResult, validator: Validator<T>): T;
@@ -0,0 +1,14 @@
1
+ import assert from 'node:assert/strict';
2
+ export function expectStatus(response, status) {
3
+ assert.equal(response.status, status, `Expected HTTP ${status}, received ${response.status}`);
4
+ }
5
+ export function expectClientError(response) {
6
+ assert.ok(response.status >= 400 && response.status < 500, `Expected 4xx, received ${response.status}`);
7
+ }
8
+ export function expectResponseTime(response, budgetMs) {
9
+ assert.ok(response.durationMs <= budgetMs, `Expected <= ${budgetMs}ms, received ${response.durationMs}ms`);
10
+ }
11
+ export function expectContract(response, validator) {
12
+ assert.ok(validator(response.body), 'Response contract validation failed');
13
+ return response.body;
14
+ }
@@ -0,0 +1,29 @@
1
+ import type { ApiResult, Method } from '../http/types.js';
2
+ /** JSON Schema compiler adapter: pass a preconfigured Ajv instance via its compile() method. */
3
+ export interface JsonSchemaCompiler {
4
+ compile(schema: Record<string, unknown>): ((data: unknown) => boolean) & {
5
+ errors?: readonly unknown[] | null;
6
+ };
7
+ }
8
+ export interface OpenApiDocument {
9
+ openapi: string;
10
+ paths: Record<string, unknown>;
11
+ components?: {
12
+ schemas?: Record<string, unknown>;
13
+ };
14
+ }
15
+ export interface ContractCheck {
16
+ operationId?: string;
17
+ path: string;
18
+ method: Method;
19
+ status: number;
20
+ contentType?: string;
21
+ response: Pick<ApiResult, 'status' | 'body' | 'headers'>;
22
+ }
23
+ /** Validates a response against an OpenAPI 3.x response schema with a supplied JSON Schema compiler (e.g. Ajv). */
24
+ export declare class OpenApiValidator {
25
+ private readonly doc;
26
+ private readonly compiler;
27
+ constructor(doc: OpenApiDocument, compiler: JsonSchemaCompiler);
28
+ assertResponse(check: ContractCheck): void;
29
+ }
@@ -0,0 +1,81 @@
1
+ import assert from 'node:assert/strict';
2
+ function object(value, label) {
3
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
4
+ throw new Error(`Invalid OpenAPI ${label}`);
5
+ return value;
6
+ }
7
+ function localRef(doc, ref) {
8
+ if (!ref.startsWith('#/components/schemas/'))
9
+ throw new Error('Only local component schema references are permitted');
10
+ const name = ref.slice('#/components/schemas/'.length).replace(/~1/g, '/').replace(/~0/g, '~');
11
+ if (!name || !Object.prototype.hasOwnProperty.call(doc.components?.schemas ?? {}, name))
12
+ throw new Error('Unresolved component schema');
13
+ return doc.components.schemas[name];
14
+ }
15
+ /** OpenAPI 3.0 nullable -> JSON Schema; 3.1 passes through. Ref resolution is local-only and cycle-limited. */
16
+ function normalizeSchema(doc, raw, depth = 0, refs = new Set()) {
17
+ if (depth > 30)
18
+ throw new Error('Contract schema nesting exceeds limit');
19
+ const schema = object(raw, 'schema');
20
+ if (typeof schema.$ref === 'string') {
21
+ if (refs.has(schema.$ref))
22
+ throw new Error('Cyclic schema reference (use a precompiled validator for recursive schemas)');
23
+ const next = new Set(refs);
24
+ next.add(schema.$ref);
25
+ return normalizeSchema(doc, localRef(doc, schema.$ref), depth + 1, next);
26
+ }
27
+ const out = { ...schema };
28
+ if (doc.openapi.startsWith('3.0.') && out.nullable === true && typeof out.type === 'string') {
29
+ out.type = [out.type, 'null'];
30
+ delete out.nullable;
31
+ }
32
+ if (out.properties) {
33
+ out.properties = Object.fromEntries(Object.entries(object(out.properties, 'properties')).map(([key, value]) => [key, normalizeSchema(doc, value, depth + 1, refs)]));
34
+ }
35
+ if (out.items)
36
+ out.items = normalizeSchema(doc, out.items, depth + 1, refs);
37
+ for (const keyword of ['oneOf', 'anyOf', 'allOf']) {
38
+ if (Array.isArray(out[keyword]))
39
+ out[keyword] = out[keyword].map(value => normalizeSchema(doc, value, depth + 1, refs));
40
+ }
41
+ if (out.additionalProperties && typeof out.additionalProperties === 'object')
42
+ out.additionalProperties = normalizeSchema(doc, out.additionalProperties, depth + 1, refs);
43
+ return out;
44
+ }
45
+ function mediaType(value) { return value.split(';', 1)[0].trim().toLowerCase(); }
46
+ /** Validates a response against an OpenAPI 3.x response schema with a supplied JSON Schema compiler (e.g. Ajv). */
47
+ export class OpenApiValidator {
48
+ doc;
49
+ compiler;
50
+ constructor(doc, compiler) {
51
+ this.doc = doc;
52
+ this.compiler = compiler;
53
+ if (!/^3\.[01]\./.test(doc.openapi))
54
+ throw new Error('Expected OpenAPI 3.0 or 3.1 document');
55
+ }
56
+ assertResponse(check) {
57
+ const operation = object(this.doc.paths[check.path], 'path')[check.method.toLowerCase()];
58
+ const op = object(operation, 'operation');
59
+ if (check.operationId && op.operationId !== check.operationId)
60
+ throw new Error('OpenAPI operationId mismatch');
61
+ const responses = object(op.responses, 'responses');
62
+ const key = String(check.status);
63
+ const matched = responses[key] ?? responses[`${key.charAt(0)}XX`] ?? responses.default;
64
+ if (!matched)
65
+ throw new Error(`OpenAPI response ${key} not declared`);
66
+ const response = object(matched, 'response');
67
+ const content = response.content;
68
+ if (!content)
69
+ return; // e.g. 204
70
+ const types = object(content, 'response content');
71
+ const actualType = mediaType(check.contentType ?? check.response.headers['content-type'] ?? 'application/json');
72
+ const selected = types[actualType] ?? (actualType.endsWith('+json') ? types['application/json'] : undefined);
73
+ if (!selected)
74
+ throw new Error(`Undeclared content type ${actualType}`);
75
+ const schema = object(selected, 'media type').schema;
76
+ if (!schema)
77
+ return;
78
+ const validate = this.compiler.compile(normalizeSchema(this.doc, schema));
79
+ assert.ok(validate(check.response.body), `OpenAPI response contract failed (${check.method} ${check.path}, HTTP ${key}). Error details suppressed to protect response data`);
80
+ }
81
+ }
@@ -0,0 +1,23 @@
1
+ /** Minimal JSON Schema 2020-12 subset for self-contained runtime validation.
2
+ * For full OpenAPI / $ref / format support, plug in an externally audited Ajv validator.
3
+ */
4
+ export type Schema = {
5
+ type?: 'object' | 'array' | 'string' | 'number' | 'integer' | 'boolean' | 'null';
6
+ required?: string[];
7
+ properties?: Record<string, Schema>;
8
+ items?: Schema;
9
+ enum?: readonly unknown[];
10
+ additionalProperties?: boolean;
11
+ minLength?: number;
12
+ maxLength?: number;
13
+ minimum?: number;
14
+ maximum?: number;
15
+ minItems?: number;
16
+ maxItems?: number;
17
+ };
18
+ export interface SchemaResult {
19
+ valid: boolean;
20
+ errors: string[];
21
+ }
22
+ export declare function validateSchema(schema: Schema, value: unknown): SchemaResult;
23
+ export declare function assertSchema(schema: Schema, value: unknown): void;
@@ -0,0 +1,60 @@
1
+ import assert from 'node:assert/strict';
2
+ export function validateSchema(schema, value) {
3
+ const errors = [];
4
+ const visit = (rule, data, loc, depth) => {
5
+ if (depth > 50) {
6
+ errors.push(`${loc}: maximum nesting exceeded`);
7
+ return;
8
+ }
9
+ if (rule.type) {
10
+ const ok = rule.type === 'null' ? data === null : rule.type === 'array' ? Array.isArray(data)
11
+ : rule.type === 'integer' ? typeof data === 'number' && Number.isInteger(data)
12
+ : rule.type === 'object' ? data !== null && typeof data === 'object' && !Array.isArray(data)
13
+ : typeof data === rule.type;
14
+ if (!ok) {
15
+ errors.push(`${loc}: expected ${rule.type}`);
16
+ return;
17
+ }
18
+ }
19
+ if (rule.enum && !rule.enum.some(v => Object.is(v, data)))
20
+ errors.push(`${loc}: not one of allowed values`);
21
+ if (typeof data === 'string') {
22
+ if (rule.minLength !== undefined && data.length < rule.minLength)
23
+ errors.push(`${loc}: too short`);
24
+ if (rule.maxLength !== undefined && data.length > rule.maxLength)
25
+ errors.push(`${loc}: too long`);
26
+ }
27
+ if (typeof data === 'number') {
28
+ if (rule.minimum !== undefined && data < rule.minimum)
29
+ errors.push(`${loc}: below minimum`);
30
+ if (rule.maximum !== undefined && data > rule.maximum)
31
+ errors.push(`${loc}: above maximum`);
32
+ }
33
+ if (Array.isArray(data)) {
34
+ if (rule.minItems !== undefined && data.length < rule.minItems)
35
+ errors.push(`${loc}: too few items`);
36
+ if (rule.maxItems !== undefined && data.length > rule.maxItems)
37
+ errors.push(`${loc}: too many items`);
38
+ if (rule.items)
39
+ data.forEach((v, i) => visit(rule.items, v, `${loc}[${i}]`, depth + 1));
40
+ }
41
+ if (data !== null && typeof data === 'object' && !Array.isArray(data)) {
42
+ const obj = data;
43
+ for (const key of rule.required ?? [])
44
+ if (!Object.prototype.hasOwnProperty.call(obj, key))
45
+ errors.push(`${loc}.${key}: missing`);
46
+ for (const [key, val] of Object.entries(obj)) {
47
+ if (rule.properties?.[key])
48
+ visit(rule.properties[key], val, `${loc}.${key}`, depth + 1);
49
+ else if (rule.additionalProperties === false)
50
+ errors.push(`${loc}.${key}: not allowed`);
51
+ }
52
+ }
53
+ };
54
+ visit(schema, value, '$', 0);
55
+ return { valid: errors.length === 0, errors };
56
+ }
57
+ export function assertSchema(schema, value) {
58
+ const r = validateSchema(schema, value);
59
+ assert.ok(r.valid, `Schema validation failed: ${r.errors.join('; ')}`);
60
+ }
@@ -0,0 +1,24 @@
1
+ import type { ApiRequest, ApiResult, EventSink, RequestSigner } from './types.js';
2
+ export declare class ApiTransportError extends Error {
3
+ readonly kind: 'network' | 'timeout';
4
+ constructor(message: string, kind: 'network' | 'timeout', options?: ErrorOptions);
5
+ }
6
+ export interface ApiClientConfig {
7
+ baseUrl: string;
8
+ timeoutMs?: number;
9
+ maxSafeRetries?: number;
10
+ retryDelayMs?: number;
11
+ signer?: RequestSigner;
12
+ defaultHeaders?: Record<string, string>;
13
+ onEvent?: EventSink;
14
+ fetchImpl?: typeof fetch;
15
+ }
16
+ export declare function encodeForm(fields: ReadonlyArray<readonly [string, string]>): string;
17
+ /** Browserless, dependency-light HTTP engine. Keeps signed request bytes identical to transmitted bytes. */
18
+ export declare class ApiClient {
19
+ private readonly cfg;
20
+ private readonly url;
21
+ private readonly fetcher;
22
+ constructor(cfg: ApiClientConfig);
23
+ request<T = unknown>(req: ApiRequest): Promise<ApiResult<T>>;
24
+ }
@@ -0,0 +1,114 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ export class ApiTransportError extends Error {
3
+ kind;
4
+ constructor(message, kind, options) {
5
+ super(message, options);
6
+ this.kind = kind;
7
+ this.name = 'ApiTransportError';
8
+ }
9
+ }
10
+ function formEncode(value) {
11
+ return encodeURIComponent(value).replace(/[!'()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
12
+ }
13
+ export function encodeForm(fields) {
14
+ return fields.map(([k, v]) => `${formEncode(k)}=${formEncode(v)}`).join('&');
15
+ }
16
+ function assertPath(path) {
17
+ if (!path.startsWith('/') || path.startsWith('//') || path.includes('#') || path.includes('?') || /(^|\/)\.\.?($|\/)/.test(path)) {
18
+ throw new Error('API path must be a local absolute path without query, fragments or parent traversal');
19
+ }
20
+ }
21
+ function parse(text, contentType) {
22
+ if (!text)
23
+ return '';
24
+ if (contentType?.includes('json')) {
25
+ try {
26
+ return JSON.parse(text);
27
+ }
28
+ catch {
29
+ return text;
30
+ }
31
+ }
32
+ return text;
33
+ }
34
+ function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }
35
+ function retryAllowed(method, idempotent) {
36
+ return ['GET', 'HEAD', 'OPTIONS'].includes(method) || idempotent;
37
+ }
38
+ function shouldRetryStatus(status) { return [408, 429, 502, 503, 504].includes(status); }
39
+ /** Browserless, dependency-light HTTP engine. Keeps signed request bytes identical to transmitted bytes. */
40
+ export class ApiClient {
41
+ cfg;
42
+ url;
43
+ fetcher;
44
+ constructor(cfg) {
45
+ this.cfg = cfg;
46
+ this.url = new URL(cfg.baseUrl.endsWith('/') ? cfg.baseUrl : `${cfg.baseUrl}/`);
47
+ if (!['http:', 'https:'].includes(this.url.protocol) || this.url.username || this.url.password || this.url.search || this.url.hash)
48
+ throw new Error('Clean HTTP(S) baseUrl required');
49
+ this.fetcher = cfg.fetchImpl ?? fetch;
50
+ }
51
+ async request(req) {
52
+ assertPath(req.path);
53
+ const bodyKinds = [req.json !== undefined, req.form !== undefined, req.rawBody !== undefined].filter(Boolean).length;
54
+ if (bodyKinds > 1)
55
+ throw new Error('Supply only one body representation');
56
+ const raw = req.rawBody ?? (req.form ? encodeForm(req.form) : (req.json === undefined ? '' : JSON.stringify(req.json)));
57
+ const url = new URL(this.url.href);
58
+ url.pathname = `${this.url.pathname.replace(/\/$/, '')}${req.path}`;
59
+ for (const [key, value] of Object.entries(req.query ?? {})) {
60
+ if (value === undefined)
61
+ continue;
62
+ for (const entry of Array.isArray(value) ? value : [value])
63
+ url.searchParams.append(key, String(entry));
64
+ }
65
+ const canRetry = retryAllowed(req.method, req.idempotent === true);
66
+ const retryCount = canRetry ? Math.min(Math.max(0, req.retry ?? this.cfg.maxSafeRetries ?? 1), 5) : 0;
67
+ const requestId = randomUUID();
68
+ const started = performance.now();
69
+ for (let attempt = 1; attempt <= retryCount + 1; attempt++) {
70
+ const headers = { ...this.cfg.defaultHeaders, ...req.headers };
71
+ const hasContentType = Object.keys(headers).some(k => k.toLowerCase() === 'content-type');
72
+ if (!hasContentType && req.json !== undefined)
73
+ headers['Content-Type'] = 'application/json';
74
+ else if (!hasContentType && req.form !== undefined)
75
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
76
+ // Signature is regenerated each attempt; pass the exact body bytes, never a reserialized object.
77
+ Object.assign(headers, await this.cfg.signer?.({ method: req.method, path: req.path, exactBody: raw, requestId, attempt }));
78
+ const timeoutMs = req.timeoutMs ?? this.cfg.timeoutMs ?? 15_000;
79
+ let response;
80
+ try {
81
+ response = await this.fetcher(url, {
82
+ method: req.method, headers, ...(raw ? { body: raw } : {}),
83
+ redirect: req.followRedirects ? 'follow' : 'manual', signal: AbortSignal.timeout(timeoutMs),
84
+ });
85
+ }
86
+ catch (error) {
87
+ const isTimeout = error instanceof Error && ['TimeoutError', 'AbortError'].includes(error.name);
88
+ if (canRetry && attempt <= retryCount) {
89
+ await delay((this.cfg.retryDelayMs ?? 100) * attempt);
90
+ continue;
91
+ }
92
+ 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 });
93
+ throw new ApiTransportError(`${req.method} ${req.path} ${isTimeout ? 'timed out' : 'failed to connect'}`, isTimeout ? 'timeout' : 'network');
94
+ }
95
+ {
96
+ let text;
97
+ try {
98
+ text = await response.text();
99
+ }
100
+ catch {
101
+ throw new ApiTransportError(`${req.method} ${req.path} response read failed`, 'network');
102
+ }
103
+ if (canRetry && attempt <= retryCount && shouldRetryStatus(response.status)) {
104
+ await delay((this.cfg.retryDelayMs ?? 100) * attempt);
105
+ continue;
106
+ }
107
+ const elapsed = Math.round(performance.now() - started);
108
+ this.cfg.onEvent?.({ kind: 'success', method: req.method, path: req.path, status: response.status, durationMs: elapsed, attempts: attempt, requestId });
109
+ 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 };
110
+ }
111
+ }
112
+ throw new Error('Unreachable retry state');
113
+ }
114
+ }
@@ -0,0 +1,45 @@
1
+ export type Method = 'GET' | 'HEAD' | 'OPTIONS' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
2
+ export type Query = Record<string, string | number | boolean | readonly (string | number | boolean)[] | undefined>;
3
+ export interface ApiRequest {
4
+ method: Method;
5
+ path: string;
6
+ query?: Query;
7
+ headers?: Record<string, string>;
8
+ json?: unknown;
9
+ form?: ReadonlyArray<readonly [string, string]>;
10
+ rawBody?: string;
11
+ timeoutMs?: number;
12
+ /** Explicitly mark mutation safe to repeat; obtain server-side idempotency support first. */
13
+ idempotent?: boolean;
14
+ retry?: number;
15
+ followRedirects?: boolean;
16
+ }
17
+ export interface ApiResult<T = unknown> {
18
+ status: number;
19
+ statusText: string;
20
+ headers: Record<string, string>;
21
+ body: T;
22
+ text: string;
23
+ durationMs: number;
24
+ attempts: number;
25
+ requestId: string;
26
+ }
27
+ export interface RequestContext {
28
+ readonly method: Method;
29
+ readonly path: string;
30
+ readonly exactBody: string;
31
+ readonly requestId: string;
32
+ readonly attempt: number;
33
+ }
34
+ export type RequestSigner = (context: RequestContext) => Record<string, string> | Promise<Record<string, string>>;
35
+ export interface HttpEvent {
36
+ method: Method;
37
+ path: string;
38
+ status?: number;
39
+ durationMs: number;
40
+ attempts: number;
41
+ requestId: string;
42
+ kind: 'success' | 'network-error';
43
+ error?: string;
44
+ }
45
+ export type EventSink = (event: HttpEvent) => void;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,32 @@
1
+ export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
2
+ export type { ApiClientConfig } from './http/api-client.js';
3
+ export type { Method, ApiRequest, ApiResult, Query, RequestContext, RequestSigner, HttpEvent, EventSink } from './http/types.js';
4
+ export { TokenManager } from './auth/token-manager.js';
5
+ export type { Tokens, TokenProvider } from './auth/token-manager.js';
6
+ export { expectStatus, expectClientError, expectResponseTime, expectContract } from './contracts/assertions.js';
7
+ export type { Validator } from './contracts/assertions.js';
8
+ export { requireEnv, envEnum } from './config/env.js';
9
+ export { redact } from './reporting/redaction.js';
10
+ export { createRunId } from './testing/run-id.js';
11
+ export { validateSchema, assertSchema } from './contracts/schema.js';
12
+ export type { Schema, SchemaResult } from './contracts/schema.js';
13
+ export { loadProjectConfig } from './config/project-config.js';
14
+ export type { ProjectConfig } from './config/project-config.js';
15
+ export { TestDataFactory, TestCleanup } from './testing/data-factory.js';
16
+ export { Semaphore } from './testing/concurrency.js';
17
+ export { selectByTags } from './testing/tag-selection.js';
18
+ export { MetricsCollector } from './reporting/metrics.js';
19
+ export type { ApiMetrics } from './reporting/metrics.js';
20
+ export { writeJunit } from './reporting/junit.js';
21
+ export type { TestCaseResult } from './reporting/junit.js';
22
+ export { OpenApiValidator } from './contracts/openapi.js';
23
+ export type { OpenApiDocument, JsonSchemaCompiler, ContractCheck } from './contracts/openapi.js';
24
+ export { ExecutionContext } from './testing/execution-context.js';
25
+ export type { ExecutionOptions } from './testing/execution-context.js';
26
+ export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
27
+ export type { SecurityPolicy } from './security/policy.js';
28
+ export { attachSafeMetadata } from './reporting/allure-adapter.js';
29
+ export type { AllureWriter } from './reporting/allure-adapter.js';
30
+ export { MochaResultCollector } from './integrations/mocha.js';
31
+ export { CoverageRegistry } from './testing/coverage.js';
32
+ export type { CoverageRecord } from './testing/coverage.js';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ export { ApiClient, ApiTransportError, encodeForm } from './http/api-client.js';
2
+ export { TokenManager } from './auth/token-manager.js';
3
+ export { expectStatus, expectClientError, expectResponseTime, expectContract } from './contracts/assertions.js';
4
+ export { requireEnv, envEnum } from './config/env.js';
5
+ export { redact } from './reporting/redaction.js';
6
+ export { createRunId } from './testing/run-id.js';
7
+ export { validateSchema, assertSchema } from './contracts/schema.js';
8
+ export { loadProjectConfig } from './config/project-config.js';
9
+ export { TestDataFactory, TestCleanup } from './testing/data-factory.js';
10
+ export { Semaphore } from './testing/concurrency.js';
11
+ export { selectByTags } from './testing/tag-selection.js';
12
+ export { MetricsCollector } from './reporting/metrics.js';
13
+ export { writeJunit } from './reporting/junit.js';
14
+ export { OpenApiValidator } from './contracts/openapi.js';
15
+ export { ExecutionContext } from './testing/execution-context.js';
16
+ export { assertRequestPolicy, rejectUnsafeEnvironment } from './security/policy.js';
17
+ export { attachSafeMetadata } from './reporting/allure-adapter.js';
18
+ export { MochaResultCollector } from './integrations/mocha.js';
19
+ export { CoverageRegistry } from './testing/coverage.js';
@@ -0,0 +1,9 @@
1
+ import type { TestCaseResult } from '../reporting/junit.js';
2
+ /** No dependency on Mocha itself; register this callback from mocha root hooks. */
3
+ export declare class MochaResultCollector {
4
+ private readonly rows;
5
+ private readonly starts;
6
+ start(fullTitle: string): void;
7
+ finish(fullTitle: string, suite: string, status: TestCaseResult['status']): void;
8
+ results(): readonly TestCaseResult[];
9
+ }
@@ -0,0 +1,13 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ /** No dependency on Mocha itself; register this callback from mocha root hooks. */
3
+ export class MochaResultCollector {
4
+ rows = [];
5
+ starts = new Map();
6
+ start(fullTitle) { this.starts.set(fullTitle, performance.now()); }
7
+ finish(fullTitle, suite, status) {
8
+ const began = this.starts.get(fullTitle);
9
+ this.starts.delete(fullTitle);
10
+ this.rows.push({ name: fullTitle, suite, status, durationMs: began === undefined ? 0 : Math.round(performance.now() - began) });
11
+ }
12
+ results() { return this.rows.map(row => ({ ...row })); }
13
+ }
@@ -0,0 +1,6 @@
1
+ /** Inversion of control: consumers pass allure-js-commons or their framework's reporter object. */
2
+ export interface AllureWriter {
3
+ attachment(name: string, content: string, type: string): Promise<unknown> | unknown;
4
+ label?(name: string, value: string): Promise<unknown> | unknown;
5
+ }
6
+ export declare function attachSafeMetadata(writer: AllureWriter, name: string, metadata: Record<string, unknown>): Promise<void>;
@@ -0,0 +1,7 @@
1
+ import { redact } from './redaction.js';
2
+ export async function attachSafeMetadata(writer, name, metadata) {
3
+ // Restrict attachment to metadata; deny bodies, raw headers, and credential-ish values.
4
+ const permitted = ['method', 'path', 'status', 'durationMs', 'attempts', 'requestId', 'environment', 'service'];
5
+ const safe = Object.fromEntries(Object.entries(metadata).filter(([key]) => permitted.includes(key)));
6
+ await writer.attachment(name, JSON.stringify(redact(safe)), 'application/json');
7
+ }
@@ -0,0 +1,9 @@
1
+ export interface TestCaseResult {
2
+ name: string;
3
+ suite: string;
4
+ durationMs: number;
5
+ status: 'passed' | 'failed' | 'skipped';
6
+ message?: string;
7
+ }
8
+ /** Metadata-only JUnit writer; never include request payloads, secrets or response bodies in messages. */
9
+ export declare function writeJunit(path: string, cases: readonly TestCaseResult[]): Promise<void>;
@@ -0,0 +1,15 @@
1
+ import { mkdir, writeFile } from 'node:fs/promises';
2
+ import { dirname } from 'node:path';
3
+ function escapeXml(input) { return input.replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' })[c]); }
4
+ /** Metadata-only JUnit writer; never include request payloads, secrets or response bodies in messages. */
5
+ export async function writeJunit(path, cases) {
6
+ const failed = cases.filter(c => c.status === 'failed').length;
7
+ const skipped = cases.filter(c => c.status === 'skipped').length;
8
+ const rows = cases.map(c => {
9
+ const content = c.status === 'failed' ? '<failure message="Test failed"/>' : c.status === 'skipped' ? '<skipped/>' : '';
10
+ return `<testcase classname="${escapeXml(c.suite)}" name="${escapeXml(c.name)}" time="${(c.durationMs / 1000).toFixed(3)}">${content}</testcase>`;
11
+ }).join('');
12
+ const xml = `<?xml version="1.0" encoding="UTF-8"?><testsuite name="qe-api" tests="${cases.length}" failures="${failed}" skipped="${skipped}">${rows}</testsuite>`;
13
+ await mkdir(dirname(path), { recursive: true });
14
+ await writeFile(path, xml, { encoding: 'utf8', mode: 0o600 });
15
+ }
@@ -0,0 +1,15 @@
1
+ import type { HttpEvent } from '../http/types.js';
2
+ export interface ApiMetrics {
3
+ total: number;
4
+ networkErrors: number;
5
+ httpErrors: number;
6
+ averageMs: number;
7
+ maxMs: number;
8
+ p95Ms: number;
9
+ }
10
+ /** Aggregates sanitized API event metadata; no request/response bodies are retained. */
11
+ export declare class MetricsCollector {
12
+ private readonly events;
13
+ record: (event: HttpEvent) => void;
14
+ summary(): ApiMetrics;
15
+ }
@@ -0,0 +1,13 @@
1
+ /** Aggregates sanitized API event metadata; no request/response bodies are retained. */
2
+ export class MetricsCollector {
3
+ events = [];
4
+ record = (event) => { this.events.push({ ...event }); };
5
+ summary() {
6
+ const values = this.events.map(e => e.durationMs).sort((a, b) => a - b);
7
+ 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,
10
+ 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
+ }
13
+ }
@@ -0,0 +1,2 @@
1
+ /** For structured event metadata only. Never attach raw banking payloads to test reports. */
2
+ export declare function redact(value: unknown, depth?: number): unknown;
@@ -0,0 +1,12 @@
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
+ const REDACTED = '[REDACTED]';
3
+ /** For structured event metadata only. Never attach raw banking payloads to test reports. */
4
+ export function redact(value, depth = 0) {
5
+ if (depth > 15)
6
+ return '[MAX_DEPTH]';
7
+ if (Array.isArray(value))
8
+ return value.map(x => redact(x, depth + 1));
9
+ 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)]));
11
+ return value;
12
+ }
@@ -0,0 +1,9 @@
1
+ import type { ApiRequest } from '../http/types.js';
2
+ export interface SecurityPolicy {
3
+ allowedHosts?: readonly string[];
4
+ production?: boolean;
5
+ allowDestructive?: boolean;
6
+ }
7
+ /** Fail-closed guard; cannot replace banking authorization or environment approval. */
8
+ export declare function assertRequestPolicy(baseUrl: string, request: ApiRequest, policy: SecurityPolicy): void;
9
+ export declare function rejectUnsafeEnvironment(env?: Record<string, string | undefined>): void;
@@ -0,0 +1,16 @@
1
+ /** Fail-closed guard; cannot replace banking authorization or environment approval. */
2
+ export function assertRequestPolicy(baseUrl, request, policy) {
3
+ const url = new URL(baseUrl);
4
+ if (policy.allowedHosts && !policy.allowedHosts.includes(url.hostname))
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.
8
+ throw new Error('Write-capable HTTP request is blocked by the execution policy');
9
+ }
10
+ }
11
+ export function rejectUnsafeEnvironment(env = process.env) {
12
+ if (env.QE_ALLOW_MUTATIONS === 'true' && (env.QE_ENV === 'prod' || env.QE_ENV === 'production'))
13
+ throw new Error('Mutations are forbidden in production');
14
+ if (env.QE_ALLOW_MUTATIONS === 'true' && env.QE_APPROVAL !== 'approved')
15
+ throw new Error('Explicit QE_APPROVAL=approved required for mutations');
16
+ }
@@ -0,0 +1,8 @@
1
+ /** Lightweight local-process limit. For shared test users across CI jobs, use GitLab resource_group. */
2
+ export declare class Semaphore {
3
+ readonly limit: number;
4
+ private running;
5
+ private readonly queue;
6
+ constructor(limit: number);
7
+ withPermit<T>(fn: () => Promise<T>): Promise<T>;
8
+ }
@@ -0,0 +1,23 @@
1
+ /** Lightweight local-process limit. For shared test users across CI jobs, use GitLab resource_group. */
2
+ export class Semaphore {
3
+ limit;
4
+ running = 0;
5
+ queue = [];
6
+ constructor(limit) {
7
+ this.limit = limit;
8
+ if (!Number.isSafeInteger(limit) || limit < 1)
9
+ throw new Error('Positive concurrency limit required');
10
+ }
11
+ async withPermit(fn) {
12
+ if (this.running >= this.limit)
13
+ await new Promise(resolve => this.queue.push(resolve));
14
+ this.running++;
15
+ try {
16
+ return await fn();
17
+ }
18
+ finally {
19
+ this.running--;
20
+ this.queue.shift()?.();
21
+ }
22
+ }
23
+ }
@@ -0,0 +1,20 @@
1
+ export interface CoverageRecord {
2
+ service: string;
3
+ method: string;
4
+ path: string;
5
+ scenario: string;
6
+ executed: boolean;
7
+ passed?: boolean;
8
+ }
9
+ /** Scenario coverage is not endpoint coverage; provides both, without guessing about unregistered endpoints. */
10
+ export declare class CoverageRegistry {
11
+ private readonly records;
12
+ register(record: CoverageRecord): void;
13
+ summary(): {
14
+ endpoints: number;
15
+ exercisedEndpoints: number;
16
+ scenarios: number;
17
+ executedScenarios: number;
18
+ passedScenarios: number;
19
+ };
20
+ }
@@ -0,0 +1,11 @@
1
+ /** Scenario coverage is not endpoint coverage; provides both, without guessing about unregistered endpoints. */
2
+ export class CoverageRegistry {
3
+ records = [];
4
+ register(record) { this.records.push({ ...record }); }
5
+ summary() {
6
+ const keys = new Set(this.records.map(r => `${r.service}:${r.method}:${r.path}`));
7
+ const exercised = new Set(this.records.filter(r => r.executed).map(r => `${r.service}:${r.method}:${r.path}`));
8
+ return { endpoints: keys.size, exercisedEndpoints: exercised.size, scenarios: this.records.length,
9
+ executedScenarios: this.records.filter(r => r.executed).length, passedScenarios: this.records.filter(r => r.executed && r.passed).length };
10
+ }
11
+ }
@@ -0,0 +1,17 @@
1
+ /** Deterministic, fake-only generators; never derive synthetic values from production customer data. */
2
+ export declare class TestDataFactory {
3
+ readonly runId: `${string}-${string}-${string}-${string}-${string}`;
4
+ constructor(runId?: `${string}-${string}-${string}-${string}-${string}`);
5
+ unique(prefix?: string): string;
6
+ email(): string;
7
+ positiveAmount(minorUnits?: number): {
8
+ amount: string;
9
+ currency: string;
10
+ };
11
+ }
12
+ /** LIFO cleanup, reports failures without discarding other teardown actions. */
13
+ export declare class TestCleanup {
14
+ private tasks;
15
+ register(action: () => Promise<void> | void): void;
16
+ execute(): Promise<void>;
17
+ }
@@ -0,0 +1,33 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ /** Deterministic, fake-only generators; never derive synthetic values from production customer data. */
3
+ export class TestDataFactory {
4
+ runId;
5
+ constructor(runId = randomUUID()) {
6
+ this.runId = runId;
7
+ }
8
+ unique(prefix = 'qa') { return `${prefix}-${this.runId}-${randomUUID()}`; }
9
+ email() { return `${this.unique('test')}@example.invalid`; }
10
+ positiveAmount(minorUnits = 100) {
11
+ if (!Number.isSafeInteger(minorUnits) || minorUnits <= 0)
12
+ throw new Error('Positive safe integer minor units required');
13
+ return { amount: (minorUnits / 100).toFixed(2), currency: 'USD' };
14
+ }
15
+ }
16
+ /** LIFO cleanup, reports failures without discarding other teardown actions. */
17
+ export class TestCleanup {
18
+ tasks = [];
19
+ register(action) { this.tasks.push(action); }
20
+ async execute() {
21
+ const failures = [];
22
+ while (this.tasks.length) {
23
+ try {
24
+ await this.tasks.pop()();
25
+ }
26
+ catch (error) {
27
+ failures.push(error);
28
+ }
29
+ }
30
+ if (failures.length)
31
+ throw new AggregateError(failures, `${failures.length} cleanup operation(s) failed`);
32
+ }
33
+ }
@@ -0,0 +1,20 @@
1
+ import { TestCleanup, TestDataFactory } from './data-factory.js';
2
+ export interface ExecutionOptions {
3
+ accountPool?: readonly string[];
4
+ concurrency?: number;
5
+ allowDestructive?: boolean;
6
+ }
7
+ /** Per-test context with unique synthetic data and guaranteed teardown. */
8
+ export declare class ExecutionContext {
9
+ readonly runId: `${string}-${string}-${string}-${string}-${string}`;
10
+ readonly data: TestDataFactory;
11
+ readonly cleanup: TestCleanup;
12
+ private readonly limiter;
13
+ private readonly accounts;
14
+ readonly allowDestructive: boolean;
15
+ constructor(options?: ExecutionOptions);
16
+ withIsolatedAccount<T>(fn: (accountId: string) => Promise<T>): Promise<T>;
17
+ private nextAccount;
18
+ assertDestructiveAllowed(): void;
19
+ finish(): Promise<void>;
20
+ }
@@ -0,0 +1,30 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { TestCleanup, TestDataFactory } from './data-factory.js';
3
+ import { Semaphore } from './concurrency.js';
4
+ /** Per-test context with unique synthetic data and guaranteed teardown. */
5
+ export class ExecutionContext {
6
+ runId = randomUUID();
7
+ data = new TestDataFactory(this.runId);
8
+ cleanup = new TestCleanup();
9
+ limiter;
10
+ accounts;
11
+ allowDestructive;
12
+ constructor(options = {}) {
13
+ this.accounts = options.accountPool ?? [];
14
+ this.limiter = new Semaphore(Math.min(options.concurrency ?? 1, Math.max(1, this.accounts.length)));
15
+ this.allowDestructive = options.allowDestructive === true && process.env.QE_ALLOW_MUTATIONS === 'true' && !['prod', 'production'].includes(process.env.QE_ENV ?? '');
16
+ }
17
+ async withIsolatedAccount(fn) {
18
+ if (!this.accounts.length)
19
+ throw new Error('No explicitly configured test accounts');
20
+ return this.limiter.withPermit(async () => {
21
+ // Only in-process isolation. Each job needs its own account pool or CI resource_group.
22
+ const index = this.nextAccount++ % this.accounts.length;
23
+ return fn(this.accounts[index]);
24
+ });
25
+ }
26
+ nextAccount = 0;
27
+ assertDestructiveAllowed() { if (!this.allowDestructive)
28
+ throw new Error('Destructive execution is disabled'); }
29
+ async finish() { await this.cleanup.execute(); }
30
+ }
@@ -0,0 +1,2 @@
1
+ /** Correlation ID for independently provisioned, disposable test fixtures. */
2
+ export declare function createRunId(prefix?: string): string;
@@ -0,0 +1,3 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ /** Correlation ID for independently provisioned, disposable test fixtures. */
3
+ export function createRunId(prefix = 'qe') { return `${prefix}-${randomUUID()}`; }
@@ -0,0 +1,4 @@
1
+ /** Simple runner-neutral tag filter; the consuming Mocha/WDIO project handles actual discovery. */
2
+ export declare function selectByTags<T extends {
3
+ tags: readonly string[];
4
+ }>(cases: readonly T[], include?: readonly string[], exclude?: readonly string[]): T[];
@@ -0,0 +1,4 @@
1
+ /** Simple runner-neutral tag filter; the consuming Mocha/WDIO project handles actual discovery. */
2
+ export function selectByTags(cases, include = [], exclude = []) {
3
+ return cases.filter(c => (include.length === 0 || include.some(t => c.tags.includes(t))) && !exclude.some(t => c.tags.includes(t)));
4
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
+
1
2
  {
2
3
  "name": "@nikhil-qeas/api-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "version": "0.3.0",
5
+ "description": "Reusable TypeScript API automation core with HTTP, auth, OpenAPI adapter, test isolation, reporting and CI",
6
+ "private": false,
7
+ "type": "module",
8
+ "engines": {
9
+ "node": ">=22.12.0"
10
+ },
11
+ "main": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md"
22
+ ],
23
+ "scripts": {
24
+ "clean": "node -e \"import('node:fs').then(m=>m.rmSync('dist',{recursive:true,force:true}))\"",
25
+ "build": "tsc -p tsconfig.build.json",
26
+ "typecheck": "tsc --noEmit -p tsconfig.json",
27
+ "test": "npm run build && node --test test/*.test.mjs",
28
+ "check": "npm run typecheck && npm test",
29
+ "prepack": "npm run build",
30
+ "test:ci": "npm run build && node scripts/test-ci.mjs",
31
+ "prepublishOnly": "npm run check && npm pack --dry-run"
32
+ },
33
+ "devDependencies": {
34
+ "typescript": "^5.9.3",
35
+ "@types/node": "^22.0.0"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/nikhil197610/QE-API-Automation-Core.git"
40
+ },
41
+ "publishConfig": {
42
+ "registry": "https://registry.npmjs.org/",
43
+ "access": "public"
44
+ }
45
+ }