@apifn/mock 0.0.1
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/index.cjs +440 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +61 -0
- package/dist/index.d.ts +61 -0
- package/dist/index.js +398 -0
- package/dist/index.js.map +1 -0
- package/package.json +47 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
createMockServer: () => createMockServer,
|
|
34
|
+
generateFromSchema: () => generateFromSchema,
|
|
35
|
+
generateRandom: () => generateRandom,
|
|
36
|
+
generateResponse: () => generateResponse,
|
|
37
|
+
validateParameters: () => validateParameters,
|
|
38
|
+
validateRequestBody: () => validateRequestBody
|
|
39
|
+
});
|
|
40
|
+
module.exports = __toCommonJS(index_exports);
|
|
41
|
+
|
|
42
|
+
// src/server.ts
|
|
43
|
+
var import_node_http = __toESM(require("http"), 1);
|
|
44
|
+
var import_node_url = require("url");
|
|
45
|
+
|
|
46
|
+
// src/response-generator.ts
|
|
47
|
+
function generateFromSchema(schema) {
|
|
48
|
+
if (!schema) return null;
|
|
49
|
+
const type = schema.type;
|
|
50
|
+
const primaryType = Array.isArray(type) ? type[0] : type;
|
|
51
|
+
switch (primaryType) {
|
|
52
|
+
case "string": {
|
|
53
|
+
if (schema.enum) return schema.enum[0];
|
|
54
|
+
if (schema.format === "date-time") return "2026-01-01T00:00:00Z";
|
|
55
|
+
if (schema.format === "date") return "2026-01-01";
|
|
56
|
+
if (schema.format === "email") return "user@example.com";
|
|
57
|
+
if (schema.format === "uri" || schema.format === "url") return "https://example.com";
|
|
58
|
+
if (schema.format === "uuid") return "00000000-0000-0000-0000-000000000000";
|
|
59
|
+
return "string";
|
|
60
|
+
}
|
|
61
|
+
case "integer":
|
|
62
|
+
case "number":
|
|
63
|
+
return 0;
|
|
64
|
+
case "boolean":
|
|
65
|
+
return true;
|
|
66
|
+
case "null":
|
|
67
|
+
return null;
|
|
68
|
+
case "array": {
|
|
69
|
+
const itemSchema = schema.items;
|
|
70
|
+
return [generateFromSchema(itemSchema)];
|
|
71
|
+
}
|
|
72
|
+
case "object":
|
|
73
|
+
default: {
|
|
74
|
+
if (schema.properties) {
|
|
75
|
+
const obj = {};
|
|
76
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
77
|
+
obj[key] = generateFromSchema(propSchema);
|
|
78
|
+
}
|
|
79
|
+
return obj;
|
|
80
|
+
}
|
|
81
|
+
return {};
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function randomString(length = 8) {
|
|
86
|
+
const chars = "abcdefghijklmnopqrstuvwxyz";
|
|
87
|
+
let s = "";
|
|
88
|
+
for (let i = 0; i < length; i++) {
|
|
89
|
+
s += chars[Math.floor(Math.random() * chars.length)];
|
|
90
|
+
}
|
|
91
|
+
return s;
|
|
92
|
+
}
|
|
93
|
+
function generateRandom(schema) {
|
|
94
|
+
if (!schema) return null;
|
|
95
|
+
const type = schema.type;
|
|
96
|
+
const primaryType = Array.isArray(type) ? type[0] : type;
|
|
97
|
+
switch (primaryType) {
|
|
98
|
+
case "string": {
|
|
99
|
+
if (schema.enum) {
|
|
100
|
+
const enums = schema.enum;
|
|
101
|
+
return enums[Math.floor(Math.random() * enums.length)];
|
|
102
|
+
}
|
|
103
|
+
if (schema.format === "date-time") return new Date(Date.now() + Math.random() * 1e10).toISOString();
|
|
104
|
+
if (schema.format === "email") return `${randomString(5)}@example.com`;
|
|
105
|
+
return randomString();
|
|
106
|
+
}
|
|
107
|
+
case "integer":
|
|
108
|
+
return Math.floor(Math.random() * 1e3);
|
|
109
|
+
case "number":
|
|
110
|
+
return Math.random() * 1e3;
|
|
111
|
+
case "boolean":
|
|
112
|
+
return Math.random() > 0.5;
|
|
113
|
+
case "null":
|
|
114
|
+
return null;
|
|
115
|
+
case "array": {
|
|
116
|
+
const itemSchema = schema.items;
|
|
117
|
+
return [generateRandom(itemSchema)];
|
|
118
|
+
}
|
|
119
|
+
case "object":
|
|
120
|
+
default: {
|
|
121
|
+
if (schema.properties) {
|
|
122
|
+
const obj = {};
|
|
123
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
124
|
+
obj[key] = generateRandom(propSchema);
|
|
125
|
+
}
|
|
126
|
+
return obj;
|
|
127
|
+
}
|
|
128
|
+
return {};
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function getResponseSchema(response) {
|
|
133
|
+
return response.content?.["application/json"]?.schema;
|
|
134
|
+
}
|
|
135
|
+
function getResponseExample(response) {
|
|
136
|
+
const json = response.content?.["application/json"];
|
|
137
|
+
if (!json) return void 0;
|
|
138
|
+
if (json.example !== void 0) return json.example;
|
|
139
|
+
if (json.examples) {
|
|
140
|
+
const first = Object.values(json.examples)[0];
|
|
141
|
+
if (first && !("$ref" in first)) return first.value;
|
|
142
|
+
}
|
|
143
|
+
const schema = json.schema;
|
|
144
|
+
if (schema?.example !== void 0) return schema.example;
|
|
145
|
+
return void 0;
|
|
146
|
+
}
|
|
147
|
+
function generateResponse(operation, mode) {
|
|
148
|
+
const responses = operation.responses ?? {};
|
|
149
|
+
const codes = Object.keys(responses).sort();
|
|
150
|
+
const successCode = codes.find((c) => c.startsWith("2")) ?? codes[0];
|
|
151
|
+
const statusCode = successCode ? parseInt(successCode, 10) : 200;
|
|
152
|
+
const responseObj = successCode ? responses[successCode] : void 0;
|
|
153
|
+
if (!responseObj || "$ref" in responseObj) {
|
|
154
|
+
return { statusCode: statusCode || 200, body: null };
|
|
155
|
+
}
|
|
156
|
+
const response = responseObj;
|
|
157
|
+
if (mode === "examples") {
|
|
158
|
+
const example = getResponseExample(response);
|
|
159
|
+
if (example !== void 0) {
|
|
160
|
+
return { statusCode, body: example };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (mode === "random") {
|
|
164
|
+
const schema2 = getResponseSchema(response);
|
|
165
|
+
return { statusCode, body: schema2 ? generateRandom(schema2) : null };
|
|
166
|
+
}
|
|
167
|
+
const schema = getResponseSchema(response);
|
|
168
|
+
return { statusCode, body: schema ? generateFromSchema(schema) : null };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/request-validator.ts
|
|
172
|
+
function validateValue(value, schema, path, errors) {
|
|
173
|
+
const type = schema.type;
|
|
174
|
+
const types = Array.isArray(type) ? type : type ? [type] : [];
|
|
175
|
+
if (types.length > 0) {
|
|
176
|
+
const actualType = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
|
|
177
|
+
const matches = types.some((t) => {
|
|
178
|
+
if (t === "integer") return typeof value === "number" && Number.isInteger(value);
|
|
179
|
+
return actualType === t;
|
|
180
|
+
});
|
|
181
|
+
if (!matches) {
|
|
182
|
+
errors.push({ path, message: `Expected type ${types.join("|")} but got ${actualType}` });
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (schema.enum) {
|
|
187
|
+
if (!schema.enum.includes(value)) {
|
|
188
|
+
errors.push({ path, message: `Value not in enum: ${JSON.stringify(schema.enum)}` });
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (typeof value === "string") {
|
|
192
|
+
const minLen = schema.minLength !== void 0 && schema.minLength !== null ? Number(schema.minLength) : void 0;
|
|
193
|
+
const maxLen = schema.maxLength !== void 0 && schema.maxLength !== null ? Number(schema.maxLength) : void 0;
|
|
194
|
+
if (minLen !== void 0 && value.length < minLen) {
|
|
195
|
+
errors.push({ path, message: `String too short (min ${minLen})` });
|
|
196
|
+
}
|
|
197
|
+
if (maxLen !== void 0 && value.length > maxLen) {
|
|
198
|
+
errors.push({ path, message: `String too long (max ${maxLen})` });
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (typeof value === "number") {
|
|
202
|
+
const schMin = schema.minimum !== void 0 && schema.minimum !== null ? Number(schema.minimum) : void 0;
|
|
203
|
+
const schMax = schema.maximum !== void 0 && schema.maximum !== null ? Number(schema.maximum) : void 0;
|
|
204
|
+
if (schMin !== void 0 && value < schMin) {
|
|
205
|
+
errors.push({ path, message: `Value ${value} below minimum ${schMin}` });
|
|
206
|
+
}
|
|
207
|
+
if (schMax !== void 0 && value > schMax) {
|
|
208
|
+
errors.push({ path, message: `Value ${value} above maximum ${schMax}` });
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
212
|
+
const obj = value;
|
|
213
|
+
if (schema.required) {
|
|
214
|
+
for (const req of schema.required) {
|
|
215
|
+
if (!(req in obj)) {
|
|
216
|
+
errors.push({ path: `${path}.${req}`, message: `Required field '${req}' is missing` });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
if (schema.properties) {
|
|
221
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
222
|
+
if (key in obj) {
|
|
223
|
+
validateValue(obj[key], propSchema, `${path}.${key}`, errors);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (Array.isArray(value) && schema.items) {
|
|
229
|
+
for (let i = 0; i < value.length; i++) {
|
|
230
|
+
validateValue(value[i], schema.items, `${path}[${i}]`, errors);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
function validateRequestBody(body, operation) {
|
|
235
|
+
const errors = [];
|
|
236
|
+
const reqBody = operation.requestBody;
|
|
237
|
+
if (!reqBody || "$ref" in reqBody) {
|
|
238
|
+
return { valid: true, errors: [] };
|
|
239
|
+
}
|
|
240
|
+
if (reqBody.required && (body === null || body === void 0)) {
|
|
241
|
+
errors.push({ path: "body", message: "Request body is required" });
|
|
242
|
+
return { valid: false, errors };
|
|
243
|
+
}
|
|
244
|
+
if (body === null || body === void 0) {
|
|
245
|
+
return { valid: true, errors: [] };
|
|
246
|
+
}
|
|
247
|
+
const schema = reqBody.content?.["application/json"]?.schema;
|
|
248
|
+
if (schema) {
|
|
249
|
+
validateValue(body, schema, "body", errors);
|
|
250
|
+
}
|
|
251
|
+
return { valid: errors.length === 0, errors };
|
|
252
|
+
}
|
|
253
|
+
function validateParameters(queryParams, pathParams, operation) {
|
|
254
|
+
const errors = [];
|
|
255
|
+
const params = operation.parameters ?? [];
|
|
256
|
+
for (const param of params) {
|
|
257
|
+
if ("$ref" in param) continue;
|
|
258
|
+
let rawValue;
|
|
259
|
+
if (param.in === "query") {
|
|
260
|
+
rawValue = queryParams[param.name];
|
|
261
|
+
} else if (param.in === "path") {
|
|
262
|
+
rawValue = pathParams[param.name];
|
|
263
|
+
}
|
|
264
|
+
if (rawValue === void 0) {
|
|
265
|
+
if (param.required) {
|
|
266
|
+
errors.push({
|
|
267
|
+
path: `${param.in}.${param.name}`,
|
|
268
|
+
message: `Required parameter '${param.name}' is missing`
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
continue;
|
|
272
|
+
}
|
|
273
|
+
if (param.schema) {
|
|
274
|
+
const schema = param.schema;
|
|
275
|
+
const typeVal = schema.type;
|
|
276
|
+
if (typeVal === "integer" || typeVal === "number") {
|
|
277
|
+
const num = Number(rawValue);
|
|
278
|
+
if (isNaN(num)) {
|
|
279
|
+
errors.push({ path: `${param.in}.${param.name}`, message: `Expected ${typeVal}` });
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { valid: errors.length === 0, errors };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// src/server.ts
|
|
288
|
+
function compilePath(apiPath) {
|
|
289
|
+
const paramNames = [];
|
|
290
|
+
const regex = apiPath.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
291
|
+
paramNames.push(name);
|
|
292
|
+
return "([^/]+)";
|
|
293
|
+
});
|
|
294
|
+
return { pattern: new RegExp(`^${regex}$`), paramNames };
|
|
295
|
+
}
|
|
296
|
+
function applyCors(res, cors) {
|
|
297
|
+
if (!cors) return;
|
|
298
|
+
const origins = cors === true ? "*" : typeof cors === "object" && cors.origin ? Array.isArray(cors.origin) ? cors.origin.join(", ") : String(cors.origin) : "*";
|
|
299
|
+
res.setHeader("Access-Control-Allow-Origin", origins);
|
|
300
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD");
|
|
301
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-API-Key");
|
|
302
|
+
if (cors !== true && typeof cors === "object" && cors.credentials) {
|
|
303
|
+
res.setHeader("Access-Control-Allow-Credentials", "true");
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
function readBody(req) {
|
|
307
|
+
return new Promise((resolve, reject) => {
|
|
308
|
+
const chunks = [];
|
|
309
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
310
|
+
req.on("end", () => {
|
|
311
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
312
|
+
if (!raw) {
|
|
313
|
+
resolve(void 0);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
try {
|
|
317
|
+
resolve(JSON.parse(raw));
|
|
318
|
+
} catch {
|
|
319
|
+
reject(new Error("Invalid JSON body"));
|
|
320
|
+
}
|
|
321
|
+
});
|
|
322
|
+
req.on("error", reject);
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
function sendJson(res, statusCode, body) {
|
|
326
|
+
const payload = body !== null && body !== void 0 ? JSON.stringify(body) : "";
|
|
327
|
+
res.setHeader("Content-Type", "application/json");
|
|
328
|
+
res.writeHead(statusCode);
|
|
329
|
+
res.end(payload);
|
|
330
|
+
}
|
|
331
|
+
var HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
|
|
332
|
+
function createMockServer(options) {
|
|
333
|
+
const spec = options.spec;
|
|
334
|
+
const port = options.port ?? 4010;
|
|
335
|
+
const mode = options.responseMode ?? "schema";
|
|
336
|
+
const validateReqs = options.validateRequests ?? false;
|
|
337
|
+
const delay = options.delay ?? 0;
|
|
338
|
+
const cors = options.cors;
|
|
339
|
+
const routes = [];
|
|
340
|
+
for (const [apiPath, pathItem] of Object.entries(spec.paths ?? {})) {
|
|
341
|
+
if (!pathItem) continue;
|
|
342
|
+
const { pattern, paramNames } = compilePath(apiPath);
|
|
343
|
+
for (const method of HTTP_METHODS) {
|
|
344
|
+
const op = pathItem[method];
|
|
345
|
+
if (op) {
|
|
346
|
+
routes.push({ method, pattern, paramNames, operation: op });
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
const server = import_node_http.default.createServer(async (req, res) => {
|
|
351
|
+
const rawMethod = (req.method ?? "GET").toLowerCase();
|
|
352
|
+
const urlObj = new import_node_url.URL(req.url ?? "/", "http://localhost");
|
|
353
|
+
const pathname = urlObj.pathname;
|
|
354
|
+
const queryParams = {};
|
|
355
|
+
for (const [k, v] of urlObj.searchParams.entries()) {
|
|
356
|
+
queryParams[k] = v;
|
|
357
|
+
}
|
|
358
|
+
applyCors(res, cors);
|
|
359
|
+
if (rawMethod === "options") {
|
|
360
|
+
res.writeHead(204);
|
|
361
|
+
res.end();
|
|
362
|
+
return;
|
|
363
|
+
}
|
|
364
|
+
const match = routes.find((r) => {
|
|
365
|
+
return r.method === rawMethod && r.pattern.test(pathname);
|
|
366
|
+
});
|
|
367
|
+
if (!match) {
|
|
368
|
+
sendJson(res, 404, { error: "Not Found", path: pathname });
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
const pathParamValues = pathname.match(match.pattern) ?? [];
|
|
372
|
+
const pathParams = {};
|
|
373
|
+
match.paramNames.forEach((name, i) => {
|
|
374
|
+
pathParams[name] = pathParamValues[i + 1] ?? "";
|
|
375
|
+
});
|
|
376
|
+
if (delay > 0) {
|
|
377
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
378
|
+
}
|
|
379
|
+
if (validateReqs) {
|
|
380
|
+
const paramValidation = validateParameters(queryParams, pathParams, match.operation);
|
|
381
|
+
if (!paramValidation.valid) {
|
|
382
|
+
sendJson(res, 400, { error: "Validation Error", errors: paramValidation.errors });
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
if (rawMethod === "post" || rawMethod === "put" || rawMethod === "patch") {
|
|
386
|
+
let body2;
|
|
387
|
+
try {
|
|
388
|
+
body2 = await readBody(req);
|
|
389
|
+
} catch {
|
|
390
|
+
sendJson(res, 400, { error: "Invalid JSON body" });
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const bodyValidation = validateRequestBody(body2, match.operation);
|
|
394
|
+
if (!bodyValidation.valid) {
|
|
395
|
+
sendJson(res, 400, { error: "Validation Error", errors: bodyValidation.errors });
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
const { statusCode, body } = generateResponse(match.operation, mode);
|
|
401
|
+
sendJson(res, statusCode, body);
|
|
402
|
+
});
|
|
403
|
+
let boundPort = port;
|
|
404
|
+
return {
|
|
405
|
+
server,
|
|
406
|
+
get port() {
|
|
407
|
+
return boundPort;
|
|
408
|
+
},
|
|
409
|
+
start() {
|
|
410
|
+
return new Promise((resolve, reject) => {
|
|
411
|
+
server.listen(port, () => {
|
|
412
|
+
const addr = server.address();
|
|
413
|
+
if (addr && typeof addr === "object") {
|
|
414
|
+
boundPort = addr.port;
|
|
415
|
+
}
|
|
416
|
+
resolve();
|
|
417
|
+
});
|
|
418
|
+
server.once("error", reject);
|
|
419
|
+
});
|
|
420
|
+
},
|
|
421
|
+
stop() {
|
|
422
|
+
return new Promise((resolve, reject) => {
|
|
423
|
+
server.close((err) => {
|
|
424
|
+
if (err) reject(err);
|
|
425
|
+
else resolve();
|
|
426
|
+
});
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
432
|
+
0 && (module.exports = {
|
|
433
|
+
createMockServer,
|
|
434
|
+
generateFromSchema,
|
|
435
|
+
generateRandom,
|
|
436
|
+
generateResponse,
|
|
437
|
+
validateParameters,
|
|
438
|
+
validateRequestBody
|
|
439
|
+
});
|
|
440
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/server.ts","../src/response-generator.ts","../src/request-validator.ts"],"sourcesContent":["/**\n * @apifn/mock — public API\n */\n\nexport { createMockServer } from \"./server.js\";\nexport type { MockServer } from \"./server.js\";\nexport { generateFromSchema, generateRandom, generateResponse } from \"./response-generator.js\";\nexport type { ResponseMode } from \"./response-generator.js\";\nexport { validateRequestBody, validateParameters } from \"./request-validator.js\";\nexport type { ValidationError, ValidationResult } from \"./request-validator.js\";\n","/**\n * Mock server implementation.\n *\n * Implements MOCK-001 (all paths served), MOCK-006 (delay), MOCK-007 (CORS).\n * Uses Node's built-in `http` module — no external HTTP framework required.\n */\n\nimport http from \"node:http\";\nimport { URL } from \"node:url\";\nimport type { OpenAPIDocument, MockServerOptions, OperationObject } from \"@apifn/core\";\nimport type { ResponseMode } from \"./response-generator.js\";\nimport { generateResponse } from \"./response-generator.js\";\nimport { validateRequestBody, validateParameters } from \"./request-validator.js\";\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\ninterface RouteHandler {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n operation: OperationObject;\n}\n\nexport interface MockServer {\n /** Start the server on the configured port */\n start(): Promise<void>;\n /** Stop the server */\n stop(): Promise<void>;\n /** The underlying http.Server */\n server: http.Server;\n /** The port actually bound to */\n port: number;\n}\n\n// ─── Path pattern conversion ──────────────────────────────────────────────────\n\n/**\n * Convert OpenAPI path `/users/{id}` to a regex and extract param names.\n */\nfunction compilePath(apiPath: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const regex = apiPath.replace(/\\{([^}]+)\\}/g, (_, name: string) => {\n paramNames.push(name);\n return \"([^/]+)\";\n });\n return { pattern: new RegExp(`^${regex}$`), paramNames };\n}\n\n// ─── CORS headers ─────────────────────────────────────────────────────────────\n\nfunction applyCors(\n res: http.ServerResponse,\n cors: MockServerOptions[\"cors\"]\n): void {\n if (!cors) return;\n\n const origins = cors === true ? \"*\"\n : typeof cors === \"object\" && cors.origin\n ? Array.isArray(cors.origin) ? cors.origin.join(\", \") : String(cors.origin)\n : \"*\";\n\n res.setHeader(\"Access-Control-Allow-Origin\", origins);\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, X-API-Key\");\n if (cors !== true && typeof cors === \"object\" && cors.credentials) {\n res.setHeader(\"Access-Control-Allow-Credentials\", \"true\");\n }\n}\n\n// ─── Request body reader ──────────────────────────────────────────────────────\n\nfunction readBody(req: http.IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => {\n const raw = Buffer.concat(chunks).toString(\"utf8\");\n if (!raw) {\n resolve(undefined);\n return;\n }\n try {\n resolve(JSON.parse(raw));\n } catch {\n reject(new Error(\"Invalid JSON body\"));\n }\n });\n req.on(\"error\", reject);\n });\n}\n\n// ─── JSON response helper ─────────────────────────────────────────────────────\n\nfunction sendJson(\n res: http.ServerResponse,\n statusCode: number,\n body: unknown\n): void {\n const payload = body !== null && body !== undefined\n ? JSON.stringify(body)\n : \"\";\n res.setHeader(\"Content-Type\", \"application/json\");\n res.writeHead(statusCode);\n res.end(payload);\n}\n\n// ─── createMockServer ─────────────────────────────────────────────────────────\n\nconst HTTP_METHODS = [\"get\", \"put\", \"post\", \"delete\", \"options\", \"head\", \"patch\", \"trace\"] as const;\n\n/**\n * Create a mock server from an OpenAPI spec.\n *\n * @returns MockServer with start() and stop() lifecycle methods.\n */\nexport function createMockServer(options: MockServerOptions): MockServer {\n const spec = options.spec as OpenAPIDocument;\n const port = options.port ?? 4010;\n const mode: ResponseMode = options.responseMode ?? \"schema\";\n const validateReqs = options.validateRequests ?? false;\n const delay = options.delay ?? 0;\n const cors = options.cors;\n\n // Build route table\n const routes: RouteHandler[] = [];\n\n for (const [apiPath, pathItem] of Object.entries(spec.paths ?? {})) {\n if (!pathItem) continue;\n const { pattern, paramNames } = compilePath(apiPath);\n\n for (const method of HTTP_METHODS) {\n const op = pathItem[method] as OperationObject | undefined;\n if (op) {\n routes.push({ method, pattern, paramNames, operation: op });\n }\n }\n }\n\n // Node HTTP server\n const server = http.createServer(async (req, res) => {\n const rawMethod = (req.method ?? \"GET\").toLowerCase();\n\n // Parse URL\n const urlObj = new URL(req.url ?? \"/\", \"http://localhost\");\n const pathname = urlObj.pathname;\n const queryParams: Record<string, string> = {};\n for (const [k, v] of urlObj.searchParams.entries()) {\n queryParams[k] = v;\n }\n\n // Apply CORS\n applyCors(res, cors);\n\n // Handle CORS preflight\n if (rawMethod === \"options\") {\n res.writeHead(204);\n res.end();\n return;\n }\n\n // Find matching route\n const match = routes.find((r) => {\n return r.method === rawMethod && r.pattern.test(pathname);\n });\n\n if (!match) {\n sendJson(res, 404, { error: \"Not Found\", path: pathname });\n return;\n }\n\n // Extract path params\n const pathParamValues = pathname.match(match.pattern) ?? [];\n const pathParams: Record<string, string> = {};\n match.paramNames.forEach((name, i) => {\n pathParams[name] = pathParamValues[i + 1] ?? \"\";\n });\n\n // Optional delay (MOCK-006)\n if (delay > 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, delay));\n }\n\n // Optional request validation (MOCK-005)\n if (validateReqs) {\n const paramValidation = validateParameters(queryParams, pathParams, match.operation);\n if (!paramValidation.valid) {\n sendJson(res, 400, { error: \"Validation Error\", errors: paramValidation.errors });\n return;\n }\n\n // Read body for validation\n if (rawMethod === \"post\" || rawMethod === \"put\" || rawMethod === \"patch\") {\n let body: unknown;\n try {\n body = await readBody(req);\n } catch {\n sendJson(res, 400, { error: \"Invalid JSON body\" });\n return;\n }\n const bodyValidation = validateRequestBody(body, match.operation);\n if (!bodyValidation.valid) {\n sendJson(res, 400, { error: \"Validation Error\", errors: bodyValidation.errors });\n return;\n }\n }\n }\n\n // Generate response\n const { statusCode, body } = generateResponse(match.operation, mode);\n sendJson(res, statusCode, body);\n });\n\n let boundPort = port;\n\n return {\n server,\n get port() {\n return boundPort;\n },\n start() {\n return new Promise((resolve, reject) => {\n server.listen(port, () => {\n const addr = server.address();\n if (addr && typeof addr === \"object\") {\n boundPort = addr.port;\n }\n resolve();\n });\n server.once(\"error\", reject);\n });\n },\n stop() {\n return new Promise((resolve, reject) => {\n server.close((err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n },\n };\n}\n","/**\n * Response generator for the mock server.\n *\n * Implements MOCK-002 (schema mode), MOCK-003 (examples mode), MOCK-004 (random mode).\n * Per SPEC Section 7.6.\n */\n\nimport type { OperationObject, SchemaObject, ResponseObject } from \"@apifn/core\";\n\nexport type ResponseMode = \"schema\" | \"examples\" | \"random\";\n\n// ---------------------------------------------------------------------------\n// Schema-based generation (MOCK-002)\n// Deterministic: given same schema → same output\n// ---------------------------------------------------------------------------\n\nexport function generateFromSchema(schema: SchemaObject | undefined): unknown {\n if (!schema) return null;\n\n const type = schema.type as string | string[] | undefined;\n const primaryType = Array.isArray(type) ? type[0] : type;\n\n switch (primaryType) {\n case \"string\": {\n if (schema.enum) return (schema.enum as unknown[])[0];\n if (schema.format === \"date-time\") return \"2026-01-01T00:00:00Z\";\n if (schema.format === \"date\") return \"2026-01-01\";\n if (schema.format === \"email\") return \"user@example.com\";\n if (schema.format === \"uri\" || schema.format === \"url\") return \"https://example.com\";\n if (schema.format === \"uuid\") return \"00000000-0000-0000-0000-000000000000\";\n return \"string\";\n }\n case \"integer\":\n case \"number\":\n return 0;\n case \"boolean\":\n return true;\n case \"null\":\n return null;\n case \"array\": {\n const itemSchema = schema.items as SchemaObject | undefined;\n return [generateFromSchema(itemSchema)];\n }\n case \"object\":\n default: {\n if (schema.properties) {\n const obj: Record<string, unknown> = {};\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n obj[key] = generateFromSchema(propSchema as SchemaObject);\n }\n return obj;\n }\n return {};\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Random mode (MOCK-004)\n// Valid against schema but with randomized values\n// ---------------------------------------------------------------------------\n\nfunction randomString(length = 8): string {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let s = \"\";\n for (let i = 0; i < length; i++) {\n s += chars[Math.floor(Math.random() * chars.length)];\n }\n return s;\n}\n\nexport function generateRandom(schema: SchemaObject | undefined): unknown {\n if (!schema) return null;\n\n const type = schema.type as string | string[] | undefined;\n const primaryType = Array.isArray(type) ? type[0] : type;\n\n switch (primaryType) {\n case \"string\": {\n if (schema.enum) {\n const enums = schema.enum as unknown[];\n return enums[Math.floor(Math.random() * enums.length)];\n }\n if (schema.format === \"date-time\") return new Date(Date.now() + Math.random() * 1e10).toISOString();\n if (schema.format === \"email\") return `${randomString(5)}@example.com`;\n return randomString();\n }\n case \"integer\":\n return Math.floor(Math.random() * 1000);\n case \"number\":\n return Math.random() * 1000;\n case \"boolean\":\n return Math.random() > 0.5;\n case \"null\":\n return null;\n case \"array\": {\n const itemSchema = schema.items as SchemaObject | undefined;\n return [generateRandom(itemSchema)];\n }\n case \"object\":\n default: {\n if (schema.properties) {\n const obj: Record<string, unknown> = {};\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n obj[key] = generateRandom(propSchema as SchemaObject);\n }\n return obj;\n }\n return {};\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Examples mode (MOCK-003)\n// Falls back to schema generation if no examples found\n// ---------------------------------------------------------------------------\n\nfunction getResponseSchema(\n response: ResponseObject\n): SchemaObject | undefined {\n return response.content?.[\"application/json\"]?.schema as SchemaObject | undefined;\n}\n\nfunction getResponseExample(\n response: ResponseObject\n): unknown {\n const json = response.content?.[\"application/json\"];\n if (!json) return undefined;\n if (json.example !== undefined) return json.example;\n if (json.examples) {\n const first = Object.values(json.examples)[0];\n if (first && !(\"$ref\" in first)) return (first as { value?: unknown }).value;\n }\n // schema-level example\n const schema = json.schema as (SchemaObject & { example?: unknown }) | undefined;\n if (schema?.example !== undefined) return schema.example;\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Main: pick the right generation strategy\n// ---------------------------------------------------------------------------\n\nexport function generateResponse(\n operation: OperationObject,\n mode: ResponseMode\n): { statusCode: number; body: unknown } {\n const responses = operation.responses ?? {};\n const codes = Object.keys(responses).sort();\n\n // Pick first successful status code (2xx), fall back to first\n const successCode = codes.find((c) => c.startsWith(\"2\")) ?? codes[0];\n const statusCode = successCode ? parseInt(successCode, 10) : 200;\n\n const responseObj = successCode ? responses[successCode] : undefined;\n\n // Handle $ref (skip, return null body)\n if (!responseObj || \"$ref\" in responseObj) {\n return { statusCode: statusCode || 200, body: null };\n }\n\n const response = responseObj as ResponseObject;\n\n if (mode === \"examples\") {\n const example = getResponseExample(response);\n if (example !== undefined) {\n return { statusCode, body: example };\n }\n // fallback to schema\n }\n\n if (mode === \"random\") {\n const schema = getResponseSchema(response);\n return { statusCode, body: schema ? generateRandom(schema) : null };\n }\n\n // schema mode (default + examples fallback)\n const schema = getResponseSchema(response);\n return { statusCode, body: schema ? generateFromSchema(schema) : null };\n}\n","/**\n * Request validator for the mock server.\n *\n * Implements MOCK-005: validates incoming request bodies and parameters against\n * their operation schemas. Returns 400 with validation errors when invalid.\n */\n\nimport type { OperationObject, SchemaObject } from \"@apifn/core\";\n\nexport interface ValidationError {\n path: string;\n message: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n}\n\n// ---------------------------------------------------------------------------\n// Simple JSON Schema validator (no external deps)\n// Handles: type, required, properties, minimum/maximum,\n// minLength/maxLength, enum\n// ---------------------------------------------------------------------------\n\nfunction validateValue(\n value: unknown,\n schema: SchemaObject,\n path: string,\n errors: ValidationError[]\n): void {\n const type = schema.type as string | string[] | undefined;\n const types = Array.isArray(type) ? type : type ? [type] : [];\n\n if (types.length > 0) {\n const actualType = value === null ? \"null\"\n : Array.isArray(value) ? \"array\"\n : typeof value;\n\n const matches = types.some((t) => {\n if (t === \"integer\") return typeof value === \"number\" && Number.isInteger(value);\n return actualType === t;\n });\n\n if (!matches) {\n errors.push({ path, message: `Expected type ${types.join(\"|\")} but got ${actualType}` });\n return; // no further checks on wrong type\n }\n }\n\n if (schema.enum) {\n if (!(schema.enum as unknown[]).includes(value)) {\n errors.push({ path, message: `Value not in enum: ${JSON.stringify(schema.enum)}` });\n }\n }\n\n if (typeof value === \"string\") {\n const minLen = schema.minLength !== undefined && schema.minLength !== null ? Number(schema.minLength) : undefined;\n const maxLen = schema.maxLength !== undefined && schema.maxLength !== null ? Number(schema.maxLength) : undefined;\n if (minLen !== undefined && value.length < minLen) {\n errors.push({ path, message: `String too short (min ${minLen})` });\n }\n if (maxLen !== undefined && value.length > maxLen) {\n errors.push({ path, message: `String too long (max ${maxLen})` });\n }\n }\n\n if (typeof value === \"number\") {\n const schMin = schema.minimum !== undefined && schema.minimum !== null ? Number(schema.minimum) : undefined;\n const schMax = schema.maximum !== undefined && schema.maximum !== null ? Number(schema.maximum) : undefined;\n if (schMin !== undefined && value < schMin) {\n errors.push({ path, message: `Value ${value} below minimum ${schMin}` });\n }\n if (schMax !== undefined && value > schMax) {\n errors.push({ path, message: `Value ${value} above maximum ${schMax}` });\n }\n }\n\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n const obj = value as Record<string, unknown>;\n\n // required fields\n if (schema.required) {\n for (const req of schema.required as string[]) {\n if (!(req in obj)) {\n errors.push({ path: `${path}.${req}`, message: `Required field '${req}' is missing` });\n }\n }\n }\n\n // properties\n if (schema.properties) {\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n if (key in obj) {\n validateValue(obj[key], propSchema as SchemaObject, `${path}.${key}`, errors);\n }\n }\n }\n }\n\n if (Array.isArray(value) && schema.items) {\n for (let i = 0; i < value.length; i++) {\n validateValue(value[i], schema.items as SchemaObject, `${path}[${i}]`, errors);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Validate body against requestBody schema\n// ---------------------------------------------------------------------------\n\nexport function validateRequestBody(\n body: unknown,\n operation: OperationObject\n): ValidationResult {\n const errors: ValidationError[] = [];\n\n const reqBody = operation.requestBody;\n if (!reqBody || \"$ref\" in reqBody) {\n return { valid: true, errors: [] };\n }\n\n if (reqBody.required && (body === null || body === undefined)) {\n errors.push({ path: \"body\", message: \"Request body is required\" });\n return { valid: false, errors };\n }\n\n if (body === null || body === undefined) {\n return { valid: true, errors: [] };\n }\n\n const schema = reqBody.content?.[\"application/json\"]?.schema as SchemaObject | undefined;\n if (schema) {\n validateValue(body, schema, \"body\", errors);\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n// ---------------------------------------------------------------------------\n// Validate query/path parameters\n// ---------------------------------------------------------------------------\n\nexport function validateParameters(\n queryParams: Record<string, string | string[]>,\n pathParams: Record<string, string>,\n operation: OperationObject\n): ValidationResult {\n const errors: ValidationError[] = [];\n\n const params = (operation.parameters ?? []) as Array<{\n name: string;\n in: string;\n required?: boolean;\n schema?: SchemaObject;\n }>;\n\n for (const param of params) {\n if (\"$ref\" in param) continue;\n\n let rawValue: string | string[] | undefined;\n if (param.in === \"query\") {\n rawValue = queryParams[param.name];\n } else if (param.in === \"path\") {\n rawValue = pathParams[param.name];\n }\n\n if (rawValue === undefined) {\n if (param.required) {\n errors.push({\n path: `${param.in}.${param.name}`,\n message: `Required parameter '${param.name}' is missing`,\n });\n }\n continue;\n }\n\n // Basic schema validation on the string value\n if (param.schema) {\n const schema = param.schema;\n const typeVal = schema.type as string | undefined;\n\n if (typeVal === \"integer\" || typeVal === \"number\") {\n const num = Number(rawValue);\n if (isNaN(num)) {\n errors.push({ path: `${param.in}.${param.name}`, message: `Expected ${typeVal}` });\n }\n }\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,uBAAiB;AACjB,sBAAoB;;;ACQb,SAAS,mBAAmB,QAA2C;AAC1E,MAAI,CAAC,OAAQ,QA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AAS,UAAU;AAClC,wBAAY,KAAK;AAAA,UACrB;AACA,kBAAQ;AAAA,QACZ,CAAC;AACD,eAAO,KAAK,SAAS,MAAM;AAAA,MAC/B,CAAC;AAAA,IACL;AAAA,IACA,OAAO;AACH,aAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACpC,eAAO,MAAM,CAAC,QAAQ;AAClB,cAAI,IAAK,QAAO,GAAG;AAAA,cACd,SAAQ;AAAA,QACjB,CAAC;AAAA,MACL,CAAC;AAAA,IACL;AAAA,EACJ;AACJ;","names":["schema","http","body"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { MockServerOptions, SchemaObject, OperationObject } from '@apifn/core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Mock server implementation.
|
|
6
|
+
*
|
|
7
|
+
* Implements MOCK-001 (all paths served), MOCK-006 (delay), MOCK-007 (CORS).
|
|
8
|
+
* Uses Node's built-in `http` module — no external HTTP framework required.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
interface MockServer {
|
|
12
|
+
/** Start the server on the configured port */
|
|
13
|
+
start(): Promise<void>;
|
|
14
|
+
/** Stop the server */
|
|
15
|
+
stop(): Promise<void>;
|
|
16
|
+
/** The underlying http.Server */
|
|
17
|
+
server: http.Server;
|
|
18
|
+
/** The port actually bound to */
|
|
19
|
+
port: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Create a mock server from an OpenAPI spec.
|
|
23
|
+
*
|
|
24
|
+
* @returns MockServer with start() and stop() lifecycle methods.
|
|
25
|
+
*/
|
|
26
|
+
declare function createMockServer(options: MockServerOptions): MockServer;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Response generator for the mock server.
|
|
30
|
+
*
|
|
31
|
+
* Implements MOCK-002 (schema mode), MOCK-003 (examples mode), MOCK-004 (random mode).
|
|
32
|
+
* Per SPEC Section 7.6.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
type ResponseMode = "schema" | "examples" | "random";
|
|
36
|
+
declare function generateFromSchema(schema: SchemaObject | undefined): unknown;
|
|
37
|
+
declare function generateRandom(schema: SchemaObject | undefined): unknown;
|
|
38
|
+
declare function generateResponse(operation: OperationObject, mode: ResponseMode): {
|
|
39
|
+
statusCode: number;
|
|
40
|
+
body: unknown;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Request validator for the mock server.
|
|
45
|
+
*
|
|
46
|
+
* Implements MOCK-005: validates incoming request bodies and parameters against
|
|
47
|
+
* their operation schemas. Returns 400 with validation errors when invalid.
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
interface ValidationError {
|
|
51
|
+
path: string;
|
|
52
|
+
message: string;
|
|
53
|
+
}
|
|
54
|
+
interface ValidationResult {
|
|
55
|
+
valid: boolean;
|
|
56
|
+
errors: ValidationError[];
|
|
57
|
+
}
|
|
58
|
+
declare function validateRequestBody(body: unknown, operation: OperationObject): ValidationResult;
|
|
59
|
+
declare function validateParameters(queryParams: Record<string, string | string[]>, pathParams: Record<string, string>, operation: OperationObject): ValidationResult;
|
|
60
|
+
|
|
61
|
+
export { type MockServer, type ResponseMode, type ValidationError, type ValidationResult, createMockServer, generateFromSchema, generateRandom, generateResponse, validateParameters, validateRequestBody };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import { MockServerOptions, SchemaObject, OperationObject } from '@apifn/core';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Mock server implementation.
|
|
6
|
+
*
|
|
7
|
+
* Implements MOCK-001 (all paths served), MOCK-006 (delay), MOCK-007 (CORS).
|
|
8
|
+
* Uses Node's built-in `http` module — no external HTTP framework required.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
interface MockServer {
|
|
12
|
+
/** Start the server on the configured port */
|
|
13
|
+
start(): Promise<void>;
|
|
14
|
+
/** Stop the server */
|
|
15
|
+
stop(): Promise<void>;
|
|
16
|
+
/** The underlying http.Server */
|
|
17
|
+
server: http.Server;
|
|
18
|
+
/** The port actually bound to */
|
|
19
|
+
port: number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Create a mock server from an OpenAPI spec.
|
|
23
|
+
*
|
|
24
|
+
* @returns MockServer with start() and stop() lifecycle methods.
|
|
25
|
+
*/
|
|
26
|
+
declare function createMockServer(options: MockServerOptions): MockServer;
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Response generator for the mock server.
|
|
30
|
+
*
|
|
31
|
+
* Implements MOCK-002 (schema mode), MOCK-003 (examples mode), MOCK-004 (random mode).
|
|
32
|
+
* Per SPEC Section 7.6.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
type ResponseMode = "schema" | "examples" | "random";
|
|
36
|
+
declare function generateFromSchema(schema: SchemaObject | undefined): unknown;
|
|
37
|
+
declare function generateRandom(schema: SchemaObject | undefined): unknown;
|
|
38
|
+
declare function generateResponse(operation: OperationObject, mode: ResponseMode): {
|
|
39
|
+
statusCode: number;
|
|
40
|
+
body: unknown;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Request validator for the mock server.
|
|
45
|
+
*
|
|
46
|
+
* Implements MOCK-005: validates incoming request bodies and parameters against
|
|
47
|
+
* their operation schemas. Returns 400 with validation errors when invalid.
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
interface ValidationError {
|
|
51
|
+
path: string;
|
|
52
|
+
message: string;
|
|
53
|
+
}
|
|
54
|
+
interface ValidationResult {
|
|
55
|
+
valid: boolean;
|
|
56
|
+
errors: ValidationError[];
|
|
57
|
+
}
|
|
58
|
+
declare function validateRequestBody(body: unknown, operation: OperationObject): ValidationResult;
|
|
59
|
+
declare function validateParameters(queryParams: Record<string, string | string[]>, pathParams: Record<string, string>, operation: OperationObject): ValidationResult;
|
|
60
|
+
|
|
61
|
+
export { type MockServer, type ResponseMode, type ValidationError, type ValidationResult, createMockServer, generateFromSchema, generateRandom, generateResponse, validateParameters, validateRequestBody };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
// src/server.ts
|
|
2
|
+
import http from "http";
|
|
3
|
+
import { URL } from "url";
|
|
4
|
+
|
|
5
|
+
// src/response-generator.ts
|
|
6
|
+
function generateFromSchema(schema) {
|
|
7
|
+
if (!schema) return null;
|
|
8
|
+
const type = schema.type;
|
|
9
|
+
const primaryType = Array.isArray(type) ? type[0] : type;
|
|
10
|
+
switch (primaryType) {
|
|
11
|
+
case "string": {
|
|
12
|
+
if (schema.enum) return schema.enum[0];
|
|
13
|
+
if (schema.format === "date-time") return "2026-01-01T00:00:00Z";
|
|
14
|
+
if (schema.format === "date") return "2026-01-01";
|
|
15
|
+
if (schema.format === "email") return "user@example.com";
|
|
16
|
+
if (schema.format === "uri" || schema.format === "url") return "https://example.com";
|
|
17
|
+
if (schema.format === "uuid") return "00000000-0000-0000-0000-000000000000";
|
|
18
|
+
return "string";
|
|
19
|
+
}
|
|
20
|
+
case "integer":
|
|
21
|
+
case "number":
|
|
22
|
+
return 0;
|
|
23
|
+
case "boolean":
|
|
24
|
+
return true;
|
|
25
|
+
case "null":
|
|
26
|
+
return null;
|
|
27
|
+
case "array": {
|
|
28
|
+
const itemSchema = schema.items;
|
|
29
|
+
return [generateFromSchema(itemSchema)];
|
|
30
|
+
}
|
|
31
|
+
case "object":
|
|
32
|
+
default: {
|
|
33
|
+
if (schema.properties) {
|
|
34
|
+
const obj = {};
|
|
35
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
36
|
+
obj[key] = generateFromSchema(propSchema);
|
|
37
|
+
}
|
|
38
|
+
return obj;
|
|
39
|
+
}
|
|
40
|
+
return {};
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function randomString(length = 8) {
|
|
45
|
+
const chars = "abcdefghijklmnopqrstuvwxyz";
|
|
46
|
+
let s = "";
|
|
47
|
+
for (let i = 0; i < length; i++) {
|
|
48
|
+
s += chars[Math.floor(Math.random() * chars.length)];
|
|
49
|
+
}
|
|
50
|
+
return s;
|
|
51
|
+
}
|
|
52
|
+
function generateRandom(schema) {
|
|
53
|
+
if (!schema) return null;
|
|
54
|
+
const type = schema.type;
|
|
55
|
+
const primaryType = Array.isArray(type) ? type[0] : type;
|
|
56
|
+
switch (primaryType) {
|
|
57
|
+
case "string": {
|
|
58
|
+
if (schema.enum) {
|
|
59
|
+
const enums = schema.enum;
|
|
60
|
+
return enums[Math.floor(Math.random() * enums.length)];
|
|
61
|
+
}
|
|
62
|
+
if (schema.format === "date-time") return new Date(Date.now() + Math.random() * 1e10).toISOString();
|
|
63
|
+
if (schema.format === "email") return `${randomString(5)}@example.com`;
|
|
64
|
+
return randomString();
|
|
65
|
+
}
|
|
66
|
+
case "integer":
|
|
67
|
+
return Math.floor(Math.random() * 1e3);
|
|
68
|
+
case "number":
|
|
69
|
+
return Math.random() * 1e3;
|
|
70
|
+
case "boolean":
|
|
71
|
+
return Math.random() > 0.5;
|
|
72
|
+
case "null":
|
|
73
|
+
return null;
|
|
74
|
+
case "array": {
|
|
75
|
+
const itemSchema = schema.items;
|
|
76
|
+
return [generateRandom(itemSchema)];
|
|
77
|
+
}
|
|
78
|
+
case "object":
|
|
79
|
+
default: {
|
|
80
|
+
if (schema.properties) {
|
|
81
|
+
const obj = {};
|
|
82
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
83
|
+
obj[key] = generateRandom(propSchema);
|
|
84
|
+
}
|
|
85
|
+
return obj;
|
|
86
|
+
}
|
|
87
|
+
return {};
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
function getResponseSchema(response) {
|
|
92
|
+
return response.content?.["application/json"]?.schema;
|
|
93
|
+
}
|
|
94
|
+
function getResponseExample(response) {
|
|
95
|
+
const json = response.content?.["application/json"];
|
|
96
|
+
if (!json) return void 0;
|
|
97
|
+
if (json.example !== void 0) return json.example;
|
|
98
|
+
if (json.examples) {
|
|
99
|
+
const first = Object.values(json.examples)[0];
|
|
100
|
+
if (first && !("$ref" in first)) return first.value;
|
|
101
|
+
}
|
|
102
|
+
const schema = json.schema;
|
|
103
|
+
if (schema?.example !== void 0) return schema.example;
|
|
104
|
+
return void 0;
|
|
105
|
+
}
|
|
106
|
+
function generateResponse(operation, mode) {
|
|
107
|
+
const responses = operation.responses ?? {};
|
|
108
|
+
const codes = Object.keys(responses).sort();
|
|
109
|
+
const successCode = codes.find((c) => c.startsWith("2")) ?? codes[0];
|
|
110
|
+
const statusCode = successCode ? parseInt(successCode, 10) : 200;
|
|
111
|
+
const responseObj = successCode ? responses[successCode] : void 0;
|
|
112
|
+
if (!responseObj || "$ref" in responseObj) {
|
|
113
|
+
return { statusCode: statusCode || 200, body: null };
|
|
114
|
+
}
|
|
115
|
+
const response = responseObj;
|
|
116
|
+
if (mode === "examples") {
|
|
117
|
+
const example = getResponseExample(response);
|
|
118
|
+
if (example !== void 0) {
|
|
119
|
+
return { statusCode, body: example };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (mode === "random") {
|
|
123
|
+
const schema2 = getResponseSchema(response);
|
|
124
|
+
return { statusCode, body: schema2 ? generateRandom(schema2) : null };
|
|
125
|
+
}
|
|
126
|
+
const schema = getResponseSchema(response);
|
|
127
|
+
return { statusCode, body: schema ? generateFromSchema(schema) : null };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// src/request-validator.ts
|
|
131
|
+
function validateValue(value, schema, path, errors) {
|
|
132
|
+
const type = schema.type;
|
|
133
|
+
const types = Array.isArray(type) ? type : type ? [type] : [];
|
|
134
|
+
if (types.length > 0) {
|
|
135
|
+
const actualType = value === null ? "null" : Array.isArray(value) ? "array" : typeof value;
|
|
136
|
+
const matches = types.some((t) => {
|
|
137
|
+
if (t === "integer") return typeof value === "number" && Number.isInteger(value);
|
|
138
|
+
return actualType === t;
|
|
139
|
+
});
|
|
140
|
+
if (!matches) {
|
|
141
|
+
errors.push({ path, message: `Expected type ${types.join("|")} but got ${actualType}` });
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (schema.enum) {
|
|
146
|
+
if (!schema.enum.includes(value)) {
|
|
147
|
+
errors.push({ path, message: `Value not in enum: ${JSON.stringify(schema.enum)}` });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (typeof value === "string") {
|
|
151
|
+
const minLen = schema.minLength !== void 0 && schema.minLength !== null ? Number(schema.minLength) : void 0;
|
|
152
|
+
const maxLen = schema.maxLength !== void 0 && schema.maxLength !== null ? Number(schema.maxLength) : void 0;
|
|
153
|
+
if (minLen !== void 0 && value.length < minLen) {
|
|
154
|
+
errors.push({ path, message: `String too short (min ${minLen})` });
|
|
155
|
+
}
|
|
156
|
+
if (maxLen !== void 0 && value.length > maxLen) {
|
|
157
|
+
errors.push({ path, message: `String too long (max ${maxLen})` });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (typeof value === "number") {
|
|
161
|
+
const schMin = schema.minimum !== void 0 && schema.minimum !== null ? Number(schema.minimum) : void 0;
|
|
162
|
+
const schMax = schema.maximum !== void 0 && schema.maximum !== null ? Number(schema.maximum) : void 0;
|
|
163
|
+
if (schMin !== void 0 && value < schMin) {
|
|
164
|
+
errors.push({ path, message: `Value ${value} below minimum ${schMin}` });
|
|
165
|
+
}
|
|
166
|
+
if (schMax !== void 0 && value > schMax) {
|
|
167
|
+
errors.push({ path, message: `Value ${value} above maximum ${schMax}` });
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
|
|
171
|
+
const obj = value;
|
|
172
|
+
if (schema.required) {
|
|
173
|
+
for (const req of schema.required) {
|
|
174
|
+
if (!(req in obj)) {
|
|
175
|
+
errors.push({ path: `${path}.${req}`, message: `Required field '${req}' is missing` });
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
if (schema.properties) {
|
|
180
|
+
for (const [key, propSchema] of Object.entries(schema.properties)) {
|
|
181
|
+
if (key in obj) {
|
|
182
|
+
validateValue(obj[key], propSchema, `${path}.${key}`, errors);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
if (Array.isArray(value) && schema.items) {
|
|
188
|
+
for (let i = 0; i < value.length; i++) {
|
|
189
|
+
validateValue(value[i], schema.items, `${path}[${i}]`, errors);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function validateRequestBody(body, operation) {
|
|
194
|
+
const errors = [];
|
|
195
|
+
const reqBody = operation.requestBody;
|
|
196
|
+
if (!reqBody || "$ref" in reqBody) {
|
|
197
|
+
return { valid: true, errors: [] };
|
|
198
|
+
}
|
|
199
|
+
if (reqBody.required && (body === null || body === void 0)) {
|
|
200
|
+
errors.push({ path: "body", message: "Request body is required" });
|
|
201
|
+
return { valid: false, errors };
|
|
202
|
+
}
|
|
203
|
+
if (body === null || body === void 0) {
|
|
204
|
+
return { valid: true, errors: [] };
|
|
205
|
+
}
|
|
206
|
+
const schema = reqBody.content?.["application/json"]?.schema;
|
|
207
|
+
if (schema) {
|
|
208
|
+
validateValue(body, schema, "body", errors);
|
|
209
|
+
}
|
|
210
|
+
return { valid: errors.length === 0, errors };
|
|
211
|
+
}
|
|
212
|
+
function validateParameters(queryParams, pathParams, operation) {
|
|
213
|
+
const errors = [];
|
|
214
|
+
const params = operation.parameters ?? [];
|
|
215
|
+
for (const param of params) {
|
|
216
|
+
if ("$ref" in param) continue;
|
|
217
|
+
let rawValue;
|
|
218
|
+
if (param.in === "query") {
|
|
219
|
+
rawValue = queryParams[param.name];
|
|
220
|
+
} else if (param.in === "path") {
|
|
221
|
+
rawValue = pathParams[param.name];
|
|
222
|
+
}
|
|
223
|
+
if (rawValue === void 0) {
|
|
224
|
+
if (param.required) {
|
|
225
|
+
errors.push({
|
|
226
|
+
path: `${param.in}.${param.name}`,
|
|
227
|
+
message: `Required parameter '${param.name}' is missing`
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
if (param.schema) {
|
|
233
|
+
const schema = param.schema;
|
|
234
|
+
const typeVal = schema.type;
|
|
235
|
+
if (typeVal === "integer" || typeVal === "number") {
|
|
236
|
+
const num = Number(rawValue);
|
|
237
|
+
if (isNaN(num)) {
|
|
238
|
+
errors.push({ path: `${param.in}.${param.name}`, message: `Expected ${typeVal}` });
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return { valid: errors.length === 0, errors };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// src/server.ts
|
|
247
|
+
function compilePath(apiPath) {
|
|
248
|
+
const paramNames = [];
|
|
249
|
+
const regex = apiPath.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
250
|
+
paramNames.push(name);
|
|
251
|
+
return "([^/]+)";
|
|
252
|
+
});
|
|
253
|
+
return { pattern: new RegExp(`^${regex}$`), paramNames };
|
|
254
|
+
}
|
|
255
|
+
function applyCors(res, cors) {
|
|
256
|
+
if (!cors) return;
|
|
257
|
+
const origins = cors === true ? "*" : typeof cors === "object" && cors.origin ? Array.isArray(cors.origin) ? cors.origin.join(", ") : String(cors.origin) : "*";
|
|
258
|
+
res.setHeader("Access-Control-Allow-Origin", origins);
|
|
259
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD");
|
|
260
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-API-Key");
|
|
261
|
+
if (cors !== true && typeof cors === "object" && cors.credentials) {
|
|
262
|
+
res.setHeader("Access-Control-Allow-Credentials", "true");
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
function readBody(req) {
|
|
266
|
+
return new Promise((resolve, reject) => {
|
|
267
|
+
const chunks = [];
|
|
268
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
269
|
+
req.on("end", () => {
|
|
270
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
271
|
+
if (!raw) {
|
|
272
|
+
resolve(void 0);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
resolve(JSON.parse(raw));
|
|
277
|
+
} catch {
|
|
278
|
+
reject(new Error("Invalid JSON body"));
|
|
279
|
+
}
|
|
280
|
+
});
|
|
281
|
+
req.on("error", reject);
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
function sendJson(res, statusCode, body) {
|
|
285
|
+
const payload = body !== null && body !== void 0 ? JSON.stringify(body) : "";
|
|
286
|
+
res.setHeader("Content-Type", "application/json");
|
|
287
|
+
res.writeHead(statusCode);
|
|
288
|
+
res.end(payload);
|
|
289
|
+
}
|
|
290
|
+
var HTTP_METHODS = ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
|
|
291
|
+
function createMockServer(options) {
|
|
292
|
+
const spec = options.spec;
|
|
293
|
+
const port = options.port ?? 4010;
|
|
294
|
+
const mode = options.responseMode ?? "schema";
|
|
295
|
+
const validateReqs = options.validateRequests ?? false;
|
|
296
|
+
const delay = options.delay ?? 0;
|
|
297
|
+
const cors = options.cors;
|
|
298
|
+
const routes = [];
|
|
299
|
+
for (const [apiPath, pathItem] of Object.entries(spec.paths ?? {})) {
|
|
300
|
+
if (!pathItem) continue;
|
|
301
|
+
const { pattern, paramNames } = compilePath(apiPath);
|
|
302
|
+
for (const method of HTTP_METHODS) {
|
|
303
|
+
const op = pathItem[method];
|
|
304
|
+
if (op) {
|
|
305
|
+
routes.push({ method, pattern, paramNames, operation: op });
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
const server = http.createServer(async (req, res) => {
|
|
310
|
+
const rawMethod = (req.method ?? "GET").toLowerCase();
|
|
311
|
+
const urlObj = new URL(req.url ?? "/", "http://localhost");
|
|
312
|
+
const pathname = urlObj.pathname;
|
|
313
|
+
const queryParams = {};
|
|
314
|
+
for (const [k, v] of urlObj.searchParams.entries()) {
|
|
315
|
+
queryParams[k] = v;
|
|
316
|
+
}
|
|
317
|
+
applyCors(res, cors);
|
|
318
|
+
if (rawMethod === "options") {
|
|
319
|
+
res.writeHead(204);
|
|
320
|
+
res.end();
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
const match = routes.find((r) => {
|
|
324
|
+
return r.method === rawMethod && r.pattern.test(pathname);
|
|
325
|
+
});
|
|
326
|
+
if (!match) {
|
|
327
|
+
sendJson(res, 404, { error: "Not Found", path: pathname });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
const pathParamValues = pathname.match(match.pattern) ?? [];
|
|
331
|
+
const pathParams = {};
|
|
332
|
+
match.paramNames.forEach((name, i) => {
|
|
333
|
+
pathParams[name] = pathParamValues[i + 1] ?? "";
|
|
334
|
+
});
|
|
335
|
+
if (delay > 0) {
|
|
336
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
337
|
+
}
|
|
338
|
+
if (validateReqs) {
|
|
339
|
+
const paramValidation = validateParameters(queryParams, pathParams, match.operation);
|
|
340
|
+
if (!paramValidation.valid) {
|
|
341
|
+
sendJson(res, 400, { error: "Validation Error", errors: paramValidation.errors });
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
if (rawMethod === "post" || rawMethod === "put" || rawMethod === "patch") {
|
|
345
|
+
let body2;
|
|
346
|
+
try {
|
|
347
|
+
body2 = await readBody(req);
|
|
348
|
+
} catch {
|
|
349
|
+
sendJson(res, 400, { error: "Invalid JSON body" });
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
const bodyValidation = validateRequestBody(body2, match.operation);
|
|
353
|
+
if (!bodyValidation.valid) {
|
|
354
|
+
sendJson(res, 400, { error: "Validation Error", errors: bodyValidation.errors });
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
const { statusCode, body } = generateResponse(match.operation, mode);
|
|
360
|
+
sendJson(res, statusCode, body);
|
|
361
|
+
});
|
|
362
|
+
let boundPort = port;
|
|
363
|
+
return {
|
|
364
|
+
server,
|
|
365
|
+
get port() {
|
|
366
|
+
return boundPort;
|
|
367
|
+
},
|
|
368
|
+
start() {
|
|
369
|
+
return new Promise((resolve, reject) => {
|
|
370
|
+
server.listen(port, () => {
|
|
371
|
+
const addr = server.address();
|
|
372
|
+
if (addr && typeof addr === "object") {
|
|
373
|
+
boundPort = addr.port;
|
|
374
|
+
}
|
|
375
|
+
resolve();
|
|
376
|
+
});
|
|
377
|
+
server.once("error", reject);
|
|
378
|
+
});
|
|
379
|
+
},
|
|
380
|
+
stop() {
|
|
381
|
+
return new Promise((resolve, reject) => {
|
|
382
|
+
server.close((err) => {
|
|
383
|
+
if (err) reject(err);
|
|
384
|
+
else resolve();
|
|
385
|
+
});
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
};
|
|
389
|
+
}
|
|
390
|
+
export {
|
|
391
|
+
createMockServer,
|
|
392
|
+
generateFromSchema,
|
|
393
|
+
generateRandom,
|
|
394
|
+
generateResponse,
|
|
395
|
+
validateParameters,
|
|
396
|
+
validateRequestBody
|
|
397
|
+
};
|
|
398
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/response-generator.ts","../src/request-validator.ts"],"sourcesContent":["/**\n * Mock server implementation.\n *\n * Implements MOCK-001 (all paths served), MOCK-006 (delay), MOCK-007 (CORS).\n * Uses Node's built-in `http` module — no external HTTP framework required.\n */\n\nimport http from \"node:http\";\nimport { URL } from \"node:url\";\nimport type { OpenAPIDocument, MockServerOptions, OperationObject } from \"@apifn/core\";\nimport type { ResponseMode } from \"./response-generator.js\";\nimport { generateResponse } from \"./response-generator.js\";\nimport { validateRequestBody, validateParameters } from \"./request-validator.js\";\n\n// ─── Internal types ───────────────────────────────────────────────────────────\n\ninterface RouteHandler {\n method: string;\n pattern: RegExp;\n paramNames: string[];\n operation: OperationObject;\n}\n\nexport interface MockServer {\n /** Start the server on the configured port */\n start(): Promise<void>;\n /** Stop the server */\n stop(): Promise<void>;\n /** The underlying http.Server */\n server: http.Server;\n /** The port actually bound to */\n port: number;\n}\n\n// ─── Path pattern conversion ──────────────────────────────────────────────────\n\n/**\n * Convert OpenAPI path `/users/{id}` to a regex and extract param names.\n */\nfunction compilePath(apiPath: string): { pattern: RegExp; paramNames: string[] } {\n const paramNames: string[] = [];\n const regex = apiPath.replace(/\\{([^}]+)\\}/g, (_, name: string) => {\n paramNames.push(name);\n return \"([^/]+)\";\n });\n return { pattern: new RegExp(`^${regex}$`), paramNames };\n}\n\n// ─── CORS headers ─────────────────────────────────────────────────────────────\n\nfunction applyCors(\n res: http.ServerResponse,\n cors: MockServerOptions[\"cors\"]\n): void {\n if (!cors) return;\n\n const origins = cors === true ? \"*\"\n : typeof cors === \"object\" && cors.origin\n ? Array.isArray(cors.origin) ? cors.origin.join(\", \") : String(cors.origin)\n : \"*\";\n\n res.setHeader(\"Access-Control-Allow-Origin\", origins);\n res.setHeader(\"Access-Control-Allow-Methods\", \"GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD\");\n res.setHeader(\"Access-Control-Allow-Headers\", \"Content-Type, Authorization, X-API-Key\");\n if (cors !== true && typeof cors === \"object\" && cors.credentials) {\n res.setHeader(\"Access-Control-Allow-Credentials\", \"true\");\n }\n}\n\n// ─── Request body reader ──────────────────────────────────────────────────────\n\nfunction readBody(req: http.IncomingMessage): Promise<unknown> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n req.on(\"data\", (chunk: Buffer) => chunks.push(chunk));\n req.on(\"end\", () => {\n const raw = Buffer.concat(chunks).toString(\"utf8\");\n if (!raw) {\n resolve(undefined);\n return;\n }\n try {\n resolve(JSON.parse(raw));\n } catch {\n reject(new Error(\"Invalid JSON body\"));\n }\n });\n req.on(\"error\", reject);\n });\n}\n\n// ─── JSON response helper ─────────────────────────────────────────────────────\n\nfunction sendJson(\n res: http.ServerResponse,\n statusCode: number,\n body: unknown\n): void {\n const payload = body !== null && body !== undefined\n ? JSON.stringify(body)\n : \"\";\n res.setHeader(\"Content-Type\", \"application/json\");\n res.writeHead(statusCode);\n res.end(payload);\n}\n\n// ─── createMockServer ─────────────────────────────────────────────────────────\n\nconst HTTP_METHODS = [\"get\", \"put\", \"post\", \"delete\", \"options\", \"head\", \"patch\", \"trace\"] as const;\n\n/**\n * Create a mock server from an OpenAPI spec.\n *\n * @returns MockServer with start() and stop() lifecycle methods.\n */\nexport function createMockServer(options: MockServerOptions): MockServer {\n const spec = options.spec as OpenAPIDocument;\n const port = options.port ?? 4010;\n const mode: ResponseMode = options.responseMode ?? \"schema\";\n const validateReqs = options.validateRequests ?? false;\n const delay = options.delay ?? 0;\n const cors = options.cors;\n\n // Build route table\n const routes: RouteHandler[] = [];\n\n for (const [apiPath, pathItem] of Object.entries(spec.paths ?? {})) {\n if (!pathItem) continue;\n const { pattern, paramNames } = compilePath(apiPath);\n\n for (const method of HTTP_METHODS) {\n const op = pathItem[method] as OperationObject | undefined;\n if (op) {\n routes.push({ method, pattern, paramNames, operation: op });\n }\n }\n }\n\n // Node HTTP server\n const server = http.createServer(async (req, res) => {\n const rawMethod = (req.method ?? \"GET\").toLowerCase();\n\n // Parse URL\n const urlObj = new URL(req.url ?? \"/\", \"http://localhost\");\n const pathname = urlObj.pathname;\n const queryParams: Record<string, string> = {};\n for (const [k, v] of urlObj.searchParams.entries()) {\n queryParams[k] = v;\n }\n\n // Apply CORS\n applyCors(res, cors);\n\n // Handle CORS preflight\n if (rawMethod === \"options\") {\n res.writeHead(204);\n res.end();\n return;\n }\n\n // Find matching route\n const match = routes.find((r) => {\n return r.method === rawMethod && r.pattern.test(pathname);\n });\n\n if (!match) {\n sendJson(res, 404, { error: \"Not Found\", path: pathname });\n return;\n }\n\n // Extract path params\n const pathParamValues = pathname.match(match.pattern) ?? [];\n const pathParams: Record<string, string> = {};\n match.paramNames.forEach((name, i) => {\n pathParams[name] = pathParamValues[i + 1] ?? \"\";\n });\n\n // Optional delay (MOCK-006)\n if (delay > 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, delay));\n }\n\n // Optional request validation (MOCK-005)\n if (validateReqs) {\n const paramValidation = validateParameters(queryParams, pathParams, match.operation);\n if (!paramValidation.valid) {\n sendJson(res, 400, { error: \"Validation Error\", errors: paramValidation.errors });\n return;\n }\n\n // Read body for validation\n if (rawMethod === \"post\" || rawMethod === \"put\" || rawMethod === \"patch\") {\n let body: unknown;\n try {\n body = await readBody(req);\n } catch {\n sendJson(res, 400, { error: \"Invalid JSON body\" });\n return;\n }\n const bodyValidation = validateRequestBody(body, match.operation);\n if (!bodyValidation.valid) {\n sendJson(res, 400, { error: \"Validation Error\", errors: bodyValidation.errors });\n return;\n }\n }\n }\n\n // Generate response\n const { statusCode, body } = generateResponse(match.operation, mode);\n sendJson(res, statusCode, body);\n });\n\n let boundPort = port;\n\n return {\n server,\n get port() {\n return boundPort;\n },\n start() {\n return new Promise((resolve, reject) => {\n server.listen(port, () => {\n const addr = server.address();\n if (addr && typeof addr === \"object\") {\n boundPort = addr.port;\n }\n resolve();\n });\n server.once(\"error\", reject);\n });\n },\n stop() {\n return new Promise((resolve, reject) => {\n server.close((err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n },\n };\n}\n","/**\n * Response generator for the mock server.\n *\n * Implements MOCK-002 (schema mode), MOCK-003 (examples mode), MOCK-004 (random mode).\n * Per SPEC Section 7.6.\n */\n\nimport type { OperationObject, SchemaObject, ResponseObject } from \"@apifn/core\";\n\nexport type ResponseMode = \"schema\" | \"examples\" | \"random\";\n\n// ---------------------------------------------------------------------------\n// Schema-based generation (MOCK-002)\n// Deterministic: given same schema → same output\n// ---------------------------------------------------------------------------\n\nexport function generateFromSchema(schema: SchemaObject | undefined): unknown {\n if (!schema) return null;\n\n const type = schema.type as string | string[] | undefined;\n const primaryType = Array.isArray(type) ? type[0] : type;\n\n switch (primaryType) {\n case \"string\": {\n if (schema.enum) return (schema.enum as unknown[])[0];\n if (schema.format === \"date-time\") return \"2026-01-01T00:00:00Z\";\n if (schema.format === \"date\") return \"2026-01-01\";\n if (schema.format === \"email\") return \"user@example.com\";\n if (schema.format === \"uri\" || schema.format === \"url\") return \"https://example.com\";\n if (schema.format === \"uuid\") return \"00000000-0000-0000-0000-000000000000\";\n return \"string\";\n }\n case \"integer\":\n case \"number\":\n return 0;\n case \"boolean\":\n return true;\n case \"null\":\n return null;\n case \"array\": {\n const itemSchema = schema.items as SchemaObject | undefined;\n return [generateFromSchema(itemSchema)];\n }\n case \"object\":\n default: {\n if (schema.properties) {\n const obj: Record<string, unknown> = {};\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n obj[key] = generateFromSchema(propSchema as SchemaObject);\n }\n return obj;\n }\n return {};\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Random mode (MOCK-004)\n// Valid against schema but with randomized values\n// ---------------------------------------------------------------------------\n\nfunction randomString(length = 8): string {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let s = \"\";\n for (let i = 0; i < length; i++) {\n s += chars[Math.floor(Math.random() * chars.length)];\n }\n return s;\n}\n\nexport function generateRandom(schema: SchemaObject | undefined): unknown {\n if (!schema) return null;\n\n const type = schema.type as string | string[] | undefined;\n const primaryType = Array.isArray(type) ? type[0] : type;\n\n switch (primaryType) {\n case \"string\": {\n if (schema.enum) {\n const enums = schema.enum as unknown[];\n return enums[Math.floor(Math.random() * enums.length)];\n }\n if (schema.format === \"date-time\") return new Date(Date.now() + Math.random() * 1e10).toISOString();\n if (schema.format === \"email\") return `${randomString(5)}@example.com`;\n return randomString();\n }\n case \"integer\":\n return Math.floor(Math.random() * 1000);\n case \"number\":\n return Math.random() * 1000;\n case \"boolean\":\n return Math.random() > 0.5;\n case \"null\":\n return null;\n case \"array\": {\n const itemSchema = schema.items as SchemaObject | undefined;\n return [generateRandom(itemSchema)];\n }\n case \"object\":\n default: {\n if (schema.properties) {\n const obj: Record<string, unknown> = {};\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n obj[key] = generateRandom(propSchema as SchemaObject);\n }\n return obj;\n }\n return {};\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Examples mode (MOCK-003)\n// Falls back to schema generation if no examples found\n// ---------------------------------------------------------------------------\n\nfunction getResponseSchema(\n response: ResponseObject\n): SchemaObject | undefined {\n return response.content?.[\"application/json\"]?.schema as SchemaObject | undefined;\n}\n\nfunction getResponseExample(\n response: ResponseObject\n): unknown {\n const json = response.content?.[\"application/json\"];\n if (!json) return undefined;\n if (json.example !== undefined) return json.example;\n if (json.examples) {\n const first = Object.values(json.examples)[0];\n if (first && !(\"$ref\" in first)) return (first as { value?: unknown }).value;\n }\n // schema-level example\n const schema = json.schema as (SchemaObject & { example?: unknown }) | undefined;\n if (schema?.example !== undefined) return schema.example;\n return undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Main: pick the right generation strategy\n// ---------------------------------------------------------------------------\n\nexport function generateResponse(\n operation: OperationObject,\n mode: ResponseMode\n): { statusCode: number; body: unknown } {\n const responses = operation.responses ?? {};\n const codes = Object.keys(responses).sort();\n\n // Pick first successful status code (2xx), fall back to first\n const successCode = codes.find((c) => c.startsWith(\"2\")) ?? codes[0];\n const statusCode = successCode ? parseInt(successCode, 10) : 200;\n\n const responseObj = successCode ? responses[successCode] : undefined;\n\n // Handle $ref (skip, return null body)\n if (!responseObj || \"$ref\" in responseObj) {\n return { statusCode: statusCode || 200, body: null };\n }\n\n const response = responseObj as ResponseObject;\n\n if (mode === \"examples\") {\n const example = getResponseExample(response);\n if (example !== undefined) {\n return { statusCode, body: example };\n }\n // fallback to schema\n }\n\n if (mode === \"random\") {\n const schema = getResponseSchema(response);\n return { statusCode, body: schema ? generateRandom(schema) : null };\n }\n\n // schema mode (default + examples fallback)\n const schema = getResponseSchema(response);\n return { statusCode, body: schema ? generateFromSchema(schema) : null };\n}\n","/**\n * Request validator for the mock server.\n *\n * Implements MOCK-005: validates incoming request bodies and parameters against\n * their operation schemas. Returns 400 with validation errors when invalid.\n */\n\nimport type { OperationObject, SchemaObject } from \"@apifn/core\";\n\nexport interface ValidationError {\n path: string;\n message: string;\n}\n\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n}\n\n// ---------------------------------------------------------------------------\n// Simple JSON Schema validator (no external deps)\n// Handles: type, required, properties, minimum/maximum,\n// minLength/maxLength, enum\n// ---------------------------------------------------------------------------\n\nfunction validateValue(\n value: unknown,\n schema: SchemaObject,\n path: string,\n errors: ValidationError[]\n): void {\n const type = schema.type as string | string[] | undefined;\n const types = Array.isArray(type) ? type : type ? [type] : [];\n\n if (types.length > 0) {\n const actualType = value === null ? \"null\"\n : Array.isArray(value) ? \"array\"\n : typeof value;\n\n const matches = types.some((t) => {\n if (t === \"integer\") return typeof value === \"number\" && Number.isInteger(value);\n return actualType === t;\n });\n\n if (!matches) {\n errors.push({ path, message: `Expected type ${types.join(\"|\")} but got ${actualType}` });\n return; // no further checks on wrong type\n }\n }\n\n if (schema.enum) {\n if (!(schema.enum as unknown[]).includes(value)) {\n errors.push({ path, message: `Value not in enum: ${JSON.stringify(schema.enum)}` });\n }\n }\n\n if (typeof value === \"string\") {\n const minLen = schema.minLength !== undefined && schema.minLength !== null ? Number(schema.minLength) : undefined;\n const maxLen = schema.maxLength !== undefined && schema.maxLength !== null ? Number(schema.maxLength) : undefined;\n if (minLen !== undefined && value.length < minLen) {\n errors.push({ path, message: `String too short (min ${minLen})` });\n }\n if (maxLen !== undefined && value.length > maxLen) {\n errors.push({ path, message: `String too long (max ${maxLen})` });\n }\n }\n\n if (typeof value === \"number\") {\n const schMin = schema.minimum !== undefined && schema.minimum !== null ? Number(schema.minimum) : undefined;\n const schMax = schema.maximum !== undefined && schema.maximum !== null ? Number(schema.maximum) : undefined;\n if (schMin !== undefined && value < schMin) {\n errors.push({ path, message: `Value ${value} below minimum ${schMin}` });\n }\n if (schMax !== undefined && value > schMax) {\n errors.push({ path, message: `Value ${value} above maximum ${schMax}` });\n }\n }\n\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n const obj = value as Record<string, unknown>;\n\n // required fields\n if (schema.required) {\n for (const req of schema.required as string[]) {\n if (!(req in obj)) {\n errors.push({ path: `${path}.${req}`, message: `Required field '${req}' is missing` });\n }\n }\n }\n\n // properties\n if (schema.properties) {\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n if (key in obj) {\n validateValue(obj[key], propSchema as SchemaObject, `${path}.${key}`, errors);\n }\n }\n }\n }\n\n if (Array.isArray(value) && schema.items) {\n for (let i = 0; i < value.length; i++) {\n validateValue(value[i], schema.items as SchemaObject, `${path}[${i}]`, errors);\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Validate body against requestBody schema\n// ---------------------------------------------------------------------------\n\nexport function validateRequestBody(\n body: unknown,\n operation: OperationObject\n): ValidationResult {\n const errors: ValidationError[] = [];\n\n const reqBody = operation.requestBody;\n if (!reqBody || \"$ref\" in reqBody) {\n return { valid: true, errors: [] };\n }\n\n if (reqBody.required && (body === null || body === undefined)) {\n errors.push({ path: \"body\", message: \"Request body is required\" });\n return { valid: false, errors };\n }\n\n if (body === null || body === undefined) {\n return { valid: true, errors: [] };\n }\n\n const schema = reqBody.content?.[\"application/json\"]?.schema as SchemaObject | undefined;\n if (schema) {\n validateValue(body, schema, \"body\", errors);\n }\n\n return { valid: errors.length === 0, errors };\n}\n\n// ---------------------------------------------------------------------------\n// Validate query/path parameters\n// ---------------------------------------------------------------------------\n\nexport function validateParameters(\n queryParams: Record<string, string | string[]>,\n pathParams: Record<string, string>,\n operation: OperationObject\n): ValidationResult {\n const errors: ValidationError[] = [];\n\n const params = (operation.parameters ?? []) as Array<{\n name: string;\n in: string;\n required?: boolean;\n schema?: SchemaObject;\n }>;\n\n for (const param of params) {\n if (\"$ref\" in param) continue;\n\n let rawValue: string | string[] | undefined;\n if (param.in === \"query\") {\n rawValue = queryParams[param.name];\n } else if (param.in === \"path\") {\n rawValue = pathParams[param.name];\n }\n\n if (rawValue === undefined) {\n if (param.required) {\n errors.push({\n path: `${param.in}.${param.name}`,\n message: `Required parameter '${param.name}' is missing`,\n });\n }\n continue;\n }\n\n // Basic schema validation on the string value\n if (param.schema) {\n const schema = param.schema;\n const typeVal = schema.type as string | undefined;\n\n if (typeVal === \"integer\" || typeVal === \"number\") {\n const num = Number(rawValue);\n if (isNaN(num)) {\n errors.push({ path: `${param.in}.${param.name}`, message: `Expected ${typeVal}` });\n }\n }\n }\n }\n\n return { valid: errors.length === 0, errors };\n}\n"],"mappings":";AAOA,OAAO,UAAU;AACjB,SAAS,WAAW;;;ACQb,SAAS,mBAAmB,QAA2C;AAC1E,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,OAAO,OAAO;AACpB,QAAM,cAAc,MAAM,QAAQ,IAAI,IAAI,KAAK,CAAC,IAAI;AAEpD,UAAQ,aAAa;AAAA,IACjB,KAAK,UAAU;AACX,UAAI,OAAO,KAAM,QAAQ,OAAO,KAAmB,CAAC;AACpD,UAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,UAAI,OAAO,WAAW,OAAQ,QAAO;AACrC,UAAI,OAAO,WAAW,QAAS,QAAO;AACtC,UAAI,OAAO,WAAW,SAAS,OAAO,WAAW,MAAO,QAAO;AAC/D,UAAI,OAAO,WAAW,OAAQ,QAAO;AACrC,aAAO;AAAA,IACX;AAAA,IACA,KAAK;AAAA,IACL,KAAK;AACD,aAAO;AAAA,IACX,KAAK;AACD,aAAO;AAAA,IACX,KAAK;AACD,aAAO;AAAA,IACX,KAAK,SAAS;AACV,YAAM,aAAa,OAAO;AAC1B,aAAO,CAAC,mBAAmB,UAAU,CAAC;AAAA,IAC1C;AAAA,IACA,KAAK;AAAA,IACL,SAAS;AACL,UAAI,OAAO,YAAY;AACnB,cA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AA,QACJ;AACA,cAAM,iBAAiB,oBAAoBA,OAAM,MAAM,SAAS;AAChE,YAAI,CAAC,eAAe,OAAO;AACvB,mBAAS,KAAK,KAAK,EAAE,OAAO,oBAAoB,QAAQ,eAAe,OAAO,CAAC;AAC/E;AAAA,QACJ;AAAA,MACJ;AAAA,IACJ;AAGA,UAAM,EAAE,YAAY,KAAK,IAAI,iBAAiB,MAAM,WAAW,IAAI;AACnE,aAAS,KAAK,YAAY,IAAI;AAAA,EAClC,CAAC;AAED,MAAI,YAAY;AAEhB,SAAO;AAAA,IACH;AAAA,IACA,IAAI,OAAO;AACP,aAAO;AAAA,IACX;AAAA,IACA,QAAQ;AACJ,aAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACpC,eAAO,OAAO,MAAM,MAAM;AACtB,gBAAM,OAAO,OAAO,QAAQ;AAC5B,cAAI,QAAQ,OAAO,SAAS,UAAU;AAClC,wBAAY,KAAK;AAAA,UACrB;AACA,kBAAQ;AAAA,QACZ,CAAC;AACD,eAAO,KAAK,SAAS,MAAM;AAAA,MAC/B,CAAC;AAAA,IACL;AAAA,IACA,OAAO;AACH,aAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACpC,eAAO,MAAM,CAAC,QAAQ;AAClB,cAAI,IAAK,QAAO,GAAG;AAAA,cACd,SAAQ;AAAA,QACjB,CAAC;AAAA,MACL,CAAC;AAAA,IACL;AAAA,EACJ;AACJ;","names":["schema","body"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@apifn/mock",
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Mock server for ApiFn",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.cjs",
|
|
7
|
+
"module": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "tsup",
|
|
18
|
+
"dev": "tsup --watch",
|
|
19
|
+
"test": "vitest run",
|
|
20
|
+
"lint": "tsc --noEmit"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"@apifn/core": "0.0.1"
|
|
24
|
+
},
|
|
25
|
+
"devDependencies": {
|
|
26
|
+
"@types/node": "^20.0.0",
|
|
27
|
+
"tsup": "^8.0.0",
|
|
28
|
+
"typescript": "^5.3.0",
|
|
29
|
+
"vitest": "^1.0.0"
|
|
30
|
+
},
|
|
31
|
+
"author": "21n",
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"bugs": {
|
|
34
|
+
"url": "https://github.com/21nCo/super-functions/issues"
|
|
35
|
+
},
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/21nCo/super-functions.git",
|
|
39
|
+
"directory": "apifn/mock"
|
|
40
|
+
},
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"files": [
|
|
45
|
+
"dist"
|
|
46
|
+
]
|
|
47
|
+
}
|