counterfact 1.4.9 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/repl/RawHttpClient.js +164 -0
- package/dist/repl/repl.js +3 -0
- package/dist/server/counterfact-types/index.ts +3 -0
- package/dist/server/dispatcher.js +9 -0
- package/dist/typescript-generator/operation-coder.js +2 -3
- package/dist/typescript-generator/operation-type-coder.js +3 -1
- package/package.json +4 -4
|
@@ -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
|
}
|
|
@@ -67,6 +67,7 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
67
67
|
script.comments = READ_ONLY_COMMENTS;
|
|
68
68
|
const xType = script.importSharedType("WideOperationArgument");
|
|
69
69
|
script.importSharedType("OmitValueWhenNever");
|
|
70
|
+
script.importSharedType("MaybePromise");
|
|
70
71
|
script.importSharedType("COUNTERFACT_RESPONSE");
|
|
71
72
|
const contextTypeImportName = script.importExternalType("Context", CONTEXT_FILE_TOKEN);
|
|
72
73
|
const parameters = this.requirement.get("parameters");
|
|
@@ -85,6 +86,7 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
85
86
|
const responseType = new ResponsesTypeCoder(this.requirement.get("responses"), this.requirement.get("produces")?.data ??
|
|
86
87
|
this.requirement.specification?.rootRequirement?.get("produces")?.data).write(script);
|
|
87
88
|
const proxyType = "(url: string) => COUNTERFACT_RESPONSE";
|
|
88
|
-
|
|
89
|
+
const delayType = "(milliseconds: number, maxMilliseconds?: number) => Promise<void>";
|
|
90
|
+
return `($: OmitValueWhenNever<{ query: ${queryType}, path: ${pathType}, headers: ${headersType}, 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
91
|
}
|
|
90
92
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "counterfact",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.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",
|
|
@@ -105,7 +105,7 @@
|
|
|
105
105
|
"eslint-plugin-jest-dom": "5.5.0",
|
|
106
106
|
"eslint-plugin-n": "^17.23.2",
|
|
107
107
|
"eslint-plugin-no-explicit-type-exports": "0.12.1",
|
|
108
|
-
"eslint-plugin-prettier": "5.5.
|
|
108
|
+
"eslint-plugin-prettier": "5.5.5",
|
|
109
109
|
"eslint-plugin-promise": "^7.2.1",
|
|
110
110
|
"eslint-plugin-regexp": "^2.10.0",
|
|
111
111
|
"eslint-plugin-security": "^3.0.1",
|
|
@@ -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.
|
|
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.
|
|
146
|
+
"prettier": "3.8.0",
|
|
147
147
|
"typescript": "5.9.3"
|
|
148
148
|
},
|
|
149
149
|
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
|