counterfact 1.4.9 → 1.6.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.
@@ -0,0 +1,164 @@
1
+ import net from "net";
2
+ const colors = {
3
+ reset: "\x1b[0m",
4
+ dim: "\x1b[2m",
5
+ cyan: "\x1b[36m",
6
+ green: "\x1b[32m",
7
+ yellow: "\x1b[33m",
8
+ red: "\x1b[31m",
9
+ bold: "\x1b[1m",
10
+ magenta: "\x1b[35m",
11
+ blue: "\x1b[34m",
12
+ };
13
+ function isLikelyJson(headersBlock, body) {
14
+ const m = headersBlock.match(/^content-type:\s*([^\r\n;]+)/im);
15
+ const ct = (m?.[1] ?? "").toLowerCase();
16
+ if (ct.includes("application/json") || ct.includes("+json"))
17
+ return true;
18
+ const s = body.trim();
19
+ if (!s)
20
+ return false;
21
+ return ((s.startsWith("{") && s.endsWith("}")) ||
22
+ (s.startsWith("[") && s.endsWith("]")));
23
+ }
24
+ function highlightJson(text) {
25
+ let obj;
26
+ try {
27
+ obj = JSON.parse(text);
28
+ }
29
+ catch {
30
+ return text;
31
+ }
32
+ const pretty = JSON.stringify(obj, null, 2);
33
+ return pretty.replace(/("(?:\\.|[^"\\])*")(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g, (match, str, colon, boolOrNull) => {
34
+ if (str) {
35
+ if (colon)
36
+ return `${colors.blue}${str}${colors.reset}${colon}`;
37
+ return `${colors.green}${str}${colors.reset}`;
38
+ }
39
+ if (boolOrNull) {
40
+ return `${colors.magenta}${match}${colors.reset}`;
41
+ }
42
+ return `${colors.yellow}${match}${colors.reset}`;
43
+ });
44
+ }
45
+ function stringifyBody(body) {
46
+ if (typeof body === "string") {
47
+ return body;
48
+ }
49
+ if (typeof body === "undefined") {
50
+ return body;
51
+ }
52
+ return JSON.stringify(body);
53
+ }
54
+ export class RawHttpClient {
55
+ host;
56
+ port;
57
+ requestNumber = 0;
58
+ constructor(host = "localhost", port = 80) {
59
+ this.host = host;
60
+ this.port = port;
61
+ }
62
+ get(path, headers = {}) {
63
+ this.#send("GET", path, "", headers);
64
+ }
65
+ head(path, headers = {}) {
66
+ this.#send("HEAD", path, "", headers);
67
+ }
68
+ post(path, body = "", headers = {}) {
69
+ this.#send("POST", path, body, headers);
70
+ }
71
+ put(path, body = "", headers = {}) {
72
+ this.#send("PUT", path, body, headers);
73
+ }
74
+ delete(path, headers = {}) {
75
+ this.#send("DELETE", path, "", headers);
76
+ }
77
+ connect(path, headers = {}) {
78
+ this.#send("CONNECT", path, "", headers);
79
+ }
80
+ options(path, headers = {}) {
81
+ this.#send("OPTIONS", path, "", headers);
82
+ }
83
+ trace(path, headers = {}) {
84
+ this.#send("TRACE", path, "", headers);
85
+ }
86
+ patch(path, body = "", headers = {}) {
87
+ this.#send("PATCH", path, body, headers);
88
+ }
89
+ #send(method, path, bodyAsStringOrObject, headers) {
90
+ const requestNumber = ++this.requestNumber;
91
+ const body = stringifyBody(bodyAsStringOrObject);
92
+ return new Promise((resolve, reject) => {
93
+ const socket = net.createConnection({ host: this.host, port: this.port }, () => {
94
+ let request = `${method} ${path} HTTP/1.1\r\n`;
95
+ request += `Host: ${this.host}\r\n`;
96
+ request += `Connection: close\r\n`;
97
+ if (body != null) {
98
+ request += `Content-Length: ${Buffer.byteLength(body)}\r\n`;
99
+ }
100
+ for (const [key, value] of Object.entries(headers)) {
101
+ request += `${key}: ${value}\r\n`;
102
+ }
103
+ request += `\r\n`;
104
+ if (body != null)
105
+ request += body;
106
+ this.#printRequest(request, requestNumber);
107
+ socket.write(request);
108
+ });
109
+ const chunks = [];
110
+ socket.on("data", (chunk) => {
111
+ chunks.push(chunk);
112
+ });
113
+ socket.on("end", () => {
114
+ const raw = Buffer.concat(chunks).toString("utf8");
115
+ this.#printResponse(raw, requestNumber);
116
+ process.stdout.write(`${colors.bold}⬣> ${colors.reset}`);
117
+ resolve(raw);
118
+ });
119
+ socket.on("error", reject);
120
+ });
121
+ }
122
+ #printRequest(raw, requestNumber) {
123
+ const [head = "", body = ""] = raw.split("\r\n\r\n");
124
+ const lines = head.split("\r\n");
125
+ process.stdout.write(`${colors.cyan}\n----- REQUEST #${requestNumber} -----${colors.reset}\n`);
126
+ process.stdout.write(`${colors.cyan}${lines[0]}${colors.reset}\n`);
127
+ for (const line of lines.slice(1)) {
128
+ process.stdout.write(`${colors.dim}${line}${colors.reset}\n`);
129
+ }
130
+ if (body) {
131
+ process.stdout.write("\n");
132
+ const outBody = isLikelyJson(head.toLowerCase(), body)
133
+ ? highlightJson(body)
134
+ : body;
135
+ process.stdout.write(outBody + "\n");
136
+ }
137
+ }
138
+ #printResponse(raw, requestNumber) {
139
+ const [head = "", body = ""] = raw.split("\r\n\r\n");
140
+ const lines = head.split("\r\n");
141
+ const statusLine = lines[0] ?? "";
142
+ let statusColor = colors.green;
143
+ const match = statusLine.match(/HTTP\/\d+\.\d+\s+(\d+)/);
144
+ if (match) {
145
+ const code = Number(match[1]);
146
+ if (code >= 400)
147
+ statusColor = colors.red;
148
+ else if (code >= 300)
149
+ statusColor = colors.yellow;
150
+ }
151
+ process.stdout.write(`\n${statusColor}----- RESPONSE #${requestNumber} -----${colors.reset}\n`);
152
+ process.stdout.write(`${statusColor}${statusLine}${colors.reset}\n`);
153
+ for (const line of lines.slice(1)) {
154
+ process.stdout.write(`${colors.dim}${line}${colors.reset}\n`);
155
+ }
156
+ if (body) {
157
+ process.stdout.write("\n");
158
+ const outBody = isLikelyJson(head.toLowerCase(), body)
159
+ ? highlightJson(body)
160
+ : body;
161
+ process.stdout.write(outBody + "\n");
162
+ }
163
+ }
164
+ }
package/dist/repl/repl.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import repl from "node:repl";
2
+ import { RawHttpClient } from "./RawHttpClient.js";
2
3
  function printToStdout(line) {
3
4
  process.stdout.write(`${line}\n`);
4
5
  }
@@ -80,5 +81,7 @@ export function startRepl(contextRegistry, config, print = printToStdout) {
80
81
  });
81
82
  replServer.context.loadContext = (path) => contextRegistry.find(path);
82
83
  replServer.context.context = replServer.context.loadContext("/");
84
+ replServer.context.client = new RawHttpClient("localhost", config.port);
85
+ replServer.context.RawHttpClient = RawHttpClient;
83
86
  return replServer;
84
87
  }
@@ -20,6 +20,8 @@ type COUNTERFACT_RESPONSE = typeof counterfactResponseObject;
20
20
 
21
21
  type MediaType = `${string}/${string}`;
22
22
 
23
+ type MaybePromise<T> = T | Promise<T>;
24
+
23
25
  type OmitAll<T, K extends readonly string[]> = {
24
26
  [P in keyof T as P extends `${string}${K[number]}${string}`
25
27
  ? never
@@ -273,6 +275,7 @@ export type { COUNTERFACT_RESPONSE };
273
275
 
274
276
  export type {
275
277
  HttpStatusCode,
278
+ MaybePromise,
276
279
  MediaType,
277
280
  OmitValueWhenNever,
278
281
  OpenApiOperation,
@@ -121,10 +121,19 @@ export class Dispatcher {
121
121
  }
122
122
  const { matchedPath } = this.registry.handler(path, method);
123
123
  const operation = this.operationForPathAndMethod(matchedPath, method);
124
+ const continuousDistribution = (min, max) => {
125
+ return min + Math.random() * (max - min);
126
+ };
124
127
  const response = await this.registry.endpoint(method, path, this.parameterTypes(operation?.parameters))({
125
128
  auth,
126
129
  body,
127
130
  context: this.contextRegistry.find(matchedPath),
131
+ async delay(milliseconds = 0, maxMilliseconds = 0) {
132
+ const delayInMs = maxMilliseconds - milliseconds <= 0
133
+ ? milliseconds
134
+ : continuousDistribution(milliseconds, maxMilliseconds);
135
+ return new Promise((resolve) => setTimeout(resolve, delayInMs));
136
+ },
128
137
  headers,
129
138
  proxy: async (url) => {
130
139
  if (body !== undefined && headers.contentType !== "application/json") {
@@ -1,7 +1,6 @@
1
1
  import nodePath from "node:path";
2
2
  import { Coder } from "./coder.js";
3
3
  import { OperationTypeCoder } from "./operation-type-coder.js";
4
- import path from "node:path";
5
4
  export class OperationCoder extends Coder {
6
5
  constructor(requirement, requestMethod, securitySchemes = {}) {
7
6
  super(requirement);
@@ -19,11 +18,11 @@ export class OperationCoder extends Coder {
19
18
  const [firstStatusCode] = responses.map((response, statusCode) => statusCode);
20
19
  const [firstResponse] = responses.map((response) => response.data);
21
20
  if (!("content" in firstResponse || "schema" in firstResponse)) {
22
- return `($) => {
21
+ return `async ($) => {
23
22
  return $.response[${firstStatusCode === "default" ? 200 : firstStatusCode}];
24
23
  }`;
25
24
  }
26
- return `($) => {
25
+ return `async ($) => {
27
26
  return $.response[${firstStatusCode === "default" ? 200 : firstStatusCode}].random();
28
27
  }`;
29
28
  }
@@ -5,6 +5,7 @@ import { READ_ONLY_COMMENTS } from "./read-only-comments.js";
5
5
  import { ResponsesTypeCoder } from "./responses-type-coder.js";
6
6
  import { SchemaTypeCoder } from "./schema-type-coder.js";
7
7
  import { TypeCoder } from "./type-coder.js";
8
+ import { ParameterExportTypeCoder } from "./parameter-export-type-coder.js";
8
9
  export class OperationTypeCoder extends TypeCoder {
9
10
  constructor(requirement, requestMethod, securitySchemes = []) {
10
11
  super(requirement);
@@ -14,9 +15,23 @@ export class OperationTypeCoder extends TypeCoder {
14
15
  this.requestMethod = requestMethod;
15
16
  this.securitySchemes = securitySchemes;
16
17
  }
18
+ getOperationBaseName() {
19
+ const operationId = this.requirement.get("operationId")?.data;
20
+ return operationId || `HTTP_${this.requestMethod.toUpperCase()}`;
21
+ }
17
22
  names() {
18
23
  return super.names(`HTTP_${this.requestMethod.toUpperCase()}`);
19
24
  }
25
+ exportParameterType(script, parameterKind, inlineType, baseName, modulePath) {
26
+ if (inlineType === "never") {
27
+ return "never";
28
+ }
29
+ const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
30
+ const typeName = `${baseName}_${capitalize(parameterKind)}`;
31
+ const coder = new ParameterExportTypeCoder(this.requirement, typeName, inlineType, parameterKind);
32
+ coder._modulePath = modulePath;
33
+ return script.export(coder, true);
34
+ }
20
35
  responseTypes(script) {
21
36
  return this.requirement
22
37
  .get("responses")
@@ -67,6 +82,7 @@ export class OperationTypeCoder extends TypeCoder {
67
82
  script.comments = READ_ONLY_COMMENTS;
68
83
  const xType = script.importSharedType("WideOperationArgument");
69
84
  script.importSharedType("OmitValueWhenNever");
85
+ script.importSharedType("MaybePromise");
70
86
  script.importSharedType("COUNTERFACT_RESPONSE");
71
87
  const contextTypeImportName = script.importExternalType("Context", CONTEXT_FILE_TOKEN);
72
88
  const parameters = this.requirement.get("parameters");
@@ -85,6 +101,13 @@ export class OperationTypeCoder extends TypeCoder {
85
101
  const responseType = new ResponsesTypeCoder(this.requirement.get("responses"), this.requirement.get("produces")?.data ??
86
102
  this.requirement.specification?.rootRequirement?.get("produces")?.data).write(script);
87
103
  const proxyType = "(url: string) => COUNTERFACT_RESPONSE";
88
- return `($: OmitValueWhenNever<{ query: ${queryType}, path: ${pathType}, headers: ${headersType}, body: ${bodyType}, context: ${contextTypeImportName}, response: ${responseType}, x: ${xType}, proxy: ${proxyType}, user: ${this.userType()} }>) => ${this.responseTypes(script)} | { status: 415, contentType: "text/plain", body: string } | COUNTERFACT_RESPONSE | { ALL_REMAINING_HEADERS_ARE_OPTIONAL: COUNTERFACT_RESPONSE }`;
104
+ const delayType = "(milliseconds: number, maxMilliseconds?: number) => Promise<void>";
105
+ // Get the base name for this operation and export parameter types
106
+ const baseName = this.getOperationBaseName();
107
+ const modulePath = this.modulePath();
108
+ const queryTypeName = this.exportParameterType(script, "query", queryType, baseName, modulePath);
109
+ const pathTypeName = this.exportParameterType(script, "path", pathType, baseName, modulePath);
110
+ const headersTypeName = this.exportParameterType(script, "headers", headersType, baseName, modulePath);
111
+ return `($: OmitValueWhenNever<{ query: ${queryTypeName}, path: ${pathTypeName}, headers: ${headersTypeName}, body: ${bodyType}, context: ${contextTypeImportName}, response: ${responseType}, x: ${xType}, proxy: ${proxyType}, user: ${this.userType()}, delay: ${delayType} }>) => MaybePromise<${this.responseTypes(script)} | { status: 415, contentType: "text/plain", body: string } | COUNTERFACT_RESPONSE | { ALL_REMAINING_HEADERS_ARE_OPTIONAL: COUNTERFACT_RESPONSE }>`;
89
112
  }
90
113
  }
@@ -0,0 +1,24 @@
1
+ import { TypeCoder } from "./type-coder.js";
2
+ // Helper class for exporting parameter types
3
+ export class ParameterExportTypeCoder extends TypeCoder {
4
+ constructor(requirement, typeName, typeCode, parameterKind) {
5
+ super(requirement);
6
+ this._typeName = typeName;
7
+ this._typeCode = typeCode;
8
+ this._parameterKind = parameterKind;
9
+ }
10
+ get id() {
11
+ // Make the id unique by including the parameter kind
12
+ return `${super.id}:${this._parameterKind}`;
13
+ }
14
+ *names() {
15
+ yield this._typeName;
16
+ }
17
+ writeCode() {
18
+ return this._typeCode;
19
+ }
20
+ modulePath() {
21
+ // Use the same module path as the parent operation
22
+ return this._modulePath;
23
+ }
24
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "counterfact",
3
- "version": "1.4.9",
3
+ "version": "1.6.0",
4
4
  "description": "Generate a TypeScript-based mock server from an OpenAPI spec in seconds — with stateful routes, hot reload, and REPL support.",
5
5
  "type": "module",
6
6
  "main": "./dist/app.js",
@@ -78,10 +78,10 @@
78
78
  },
79
79
  "devDependencies": {
80
80
  "@changesets/cli": "2.29.8",
81
- "@stryker-mutator/core": "9.4.0",
82
- "@stryker-mutator/jest-runner": "9.4.0",
83
- "@stryker-mutator/typescript-checker": "9.4.0",
84
- "@swc/core": "1.15.8",
81
+ "@stryker-mutator/core": "9.5.1",
82
+ "@stryker-mutator/jest-runner": "9.5.1",
83
+ "@stryker-mutator/typescript-checker": "9.5.1",
84
+ "@swc/core": "1.15.11",
85
85
  "@swc/jest": "0.2.39",
86
86
  "@testing-library/dom": "10.4.1",
87
87
  "@types/debug": "^4.1.12",
@@ -95,26 +95,26 @@
95
95
  "@typescript-eslint/eslint-plugin": "^8.53.0",
96
96
  "@typescript-eslint/parser": "^8.53.0",
97
97
  "copyfiles": "2.4.1",
98
- "eslint": "9.39.2",
98
+ "eslint": "9.39.3",
99
99
  "eslint-formatter-github-annotations": "0.1.0",
100
100
  "eslint-import-resolver-typescript": "4.4.4",
101
101
  "eslint-plugin-etc": "2.0.3",
102
102
  "eslint-plugin-file-progress": "3.0.2",
103
103
  "eslint-plugin-import": "2.32.0",
104
- "eslint-plugin-jest": "29.12.1",
104
+ "eslint-plugin-jest": "29.15.0",
105
105
  "eslint-plugin-jest-dom": "5.5.0",
106
- "eslint-plugin-n": "^17.23.2",
106
+ "eslint-plugin-n": "^17.24.0",
107
107
  "eslint-plugin-no-explicit-type-exports": "0.12.1",
108
- "eslint-plugin-prettier": "5.5.4",
108
+ "eslint-plugin-prettier": "5.5.5",
109
109
  "eslint-plugin-promise": "^7.2.1",
110
- "eslint-plugin-regexp": "^2.10.0",
111
- "eslint-plugin-security": "^3.0.1",
112
- "eslint-plugin-unused-imports": "4.3.0",
110
+ "eslint-plugin-regexp": "^3.0.0",
111
+ "eslint-plugin-security": "^4.0.0",
112
+ "eslint-plugin-unused-imports": "4.4.1",
113
113
  "husky": "9.1.7",
114
114
  "jest": "30.2.0",
115
115
  "jest-retries": "1.0.1",
116
116
  "node-mocks-http": "1.17.2",
117
- "rimraf": "6.1.2",
117
+ "rimraf": "6.1.3",
118
118
  "stryker-cli": "1.1.0",
119
119
  "supertest": "7.2.2",
120
120
  "tsd": "0.33.0",
@@ -125,7 +125,7 @@
125
125
  "@hapi/accept": "6.0.3",
126
126
  "@types/json-schema": "7.0.15",
127
127
  "chokidar": "5.0.0",
128
- "commander": "14.0.2",
128
+ "commander": "14.0.3",
129
129
  "debug": "4.4.3",
130
130
  "fetch": "1.1.0",
131
131
  "fs-extra": "11.3.3",
@@ -138,12 +138,12 @@
138
138
  "koa-bodyparser": "4.4.1",
139
139
  "koa-proxies": "0.12.4",
140
140
  "koa2-swagger-ui": "5.12.0",
141
- "lodash": "4.17.21",
141
+ "lodash": "4.17.23",
142
142
  "node-fetch": "3.3.2",
143
143
  "open": "11.0.0",
144
144
  "patch-package": "8.0.1",
145
145
  "precinct": "12.2.0",
146
- "prettier": "3.7.4",
146
+ "prettier": "3.8.1",
147
147
  "typescript": "5.9.3"
148
148
  },
149
149
  "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",