@schmock/core 2.2.3 → 2.3.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.
Files changed (94) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +35 -0
  3. package/dist/abort.d.ts +3 -0
  4. package/dist/abort.d.ts.map +1 -0
  5. package/dist/abort.js +30 -0
  6. package/dist/binary.d.ts +8 -0
  7. package/dist/binary.d.ts.map +1 -0
  8. package/dist/binary.js +9 -0
  9. package/dist/builder.d.ts +31 -10
  10. package/dist/builder.d.ts.map +1 -1
  11. package/dist/builder.js +804 -203
  12. package/dist/constants.d.ts +38 -0
  13. package/dist/constants.d.ts.map +1 -1
  14. package/dist/constants.js +123 -2
  15. package/dist/errors.d.ts +14 -3
  16. package/dist/errors.d.ts.map +1 -1
  17. package/dist/errors.js +41 -6
  18. package/dist/helpers.d.ts +9 -0
  19. package/dist/helpers.d.ts.map +1 -1
  20. package/dist/helpers.js +18 -2
  21. package/dist/http-helpers.d.ts +52 -5
  22. package/dist/http-helpers.d.ts.map +1 -1
  23. package/dist/http-helpers.js +153 -37
  24. package/dist/index.d.ts +381 -60
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +9 -3
  27. package/dist/interceptor.d.ts +11 -1
  28. package/dist/interceptor.d.ts.map +1 -1
  29. package/dist/interceptor.js +354 -156
  30. package/dist/parser.d.ts.map +1 -1
  31. package/dist/parser.js +12 -3
  32. package/dist/plugin-pipeline.d.ts +11 -4
  33. package/dist/plugin-pipeline.d.ts.map +1 -1
  34. package/dist/plugin-pipeline.js +117 -39
  35. package/dist/response-normalizer.d.ts +16 -0
  36. package/dist/response-normalizer.d.ts.map +1 -0
  37. package/dist/response-normalizer.js +316 -0
  38. package/dist/response-parser.d.ts.map +1 -1
  39. package/dist/response-parser.js +85 -18
  40. package/dist/route-matcher.d.ts +3 -0
  41. package/dist/route-matcher.d.ts.map +1 -1
  42. package/dist/route-matcher.js +12 -6
  43. package/dist/types.d.ts +7 -2
  44. package/dist/types.d.ts.map +1 -1
  45. package/package.json +18 -8
  46. package/src/audit-core-builder.test.ts +0 -218
  47. package/src/audit-response-guard.test.ts +0 -38
  48. package/src/builder.test.ts +0 -289
  49. package/src/builder.ts +0 -701
  50. package/src/constants.test.ts +0 -99
  51. package/src/constants.ts +0 -73
  52. package/src/debug.test.ts +0 -241
  53. package/src/delay.test.ts +0 -319
  54. package/src/dist-shape.test.ts +0 -35
  55. package/src/errors.test.ts +0 -223
  56. package/src/errors.ts +0 -130
  57. package/src/factory.test.ts +0 -133
  58. package/src/helpers.test.ts +0 -147
  59. package/src/helpers.ts +0 -58
  60. package/src/http-helpers.ts +0 -113
  61. package/src/index.ts +0 -151
  62. package/src/interceptor.test.ts +0 -291
  63. package/src/interceptor.ts +0 -320
  64. package/src/namespace.test.ts +0 -274
  65. package/src/parser.property.test.ts +0 -594
  66. package/src/parser.test.ts +0 -148
  67. package/src/parser.ts +0 -64
  68. package/src/plugin-pipeline.ts +0 -103
  69. package/src/plugin-system.test.ts +0 -602
  70. package/src/response-parser.ts +0 -75
  71. package/src/response-parsing.test.ts +0 -333
  72. package/src/route-matcher.ts +0 -69
  73. package/src/route-matching.test.ts +0 -394
  74. package/src/server.test.ts +0 -165
  75. package/src/smart-defaults.test.ts +0 -361
  76. package/src/steps/async-support.steps.ts +0 -400
  77. package/src/steps/audit-core-builder.steps.ts +0 -188
  78. package/src/steps/audit-onerror-tuple.steps.ts +0 -99
  79. package/src/steps/basic-usage.steps.ts +0 -245
  80. package/src/steps/developer-experience.steps.ts +0 -204
  81. package/src/steps/error-handling.steps.ts +0 -345
  82. package/src/steps/fluent-api.steps.ts +0 -255
  83. package/src/steps/http-methods.steps.ts +0 -331
  84. package/src/steps/interceptor.steps.ts +0 -260
  85. package/src/steps/lifecycle-events.steps.ts +0 -142
  86. package/src/steps/performance-reliability.steps.ts +0 -423
  87. package/src/steps/plugin-integration.steps.ts +0 -280
  88. package/src/steps/request-history.steps.ts +0 -276
  89. package/src/steps/response-delay.steps.ts +0 -88
  90. package/src/steps/route-key-format.steps.ts +0 -99
  91. package/src/steps/standalone-server.steps.ts +0 -233
  92. package/src/steps/state-concurrency.steps.ts +0 -739
  93. package/src/steps/stateful-workflows.steps.ts +0 -353
  94. package/src/types.ts +0 -36
@@ -1,90 +1,206 @@
1
+ import { isBinaryBody } from "./binary.js";
2
+ import { serializeResponseBody } from "./response-normalizer.js";
3
+ /** An HTTP client error raised while collecting an incoming request body. */
4
+ export class HttpIngressError extends Error {
5
+ status;
6
+ code;
7
+ constructor(status, code, message) {
8
+ super(message);
9
+ this.status = status;
10
+ this.code = code;
11
+ this.name = "HttpIngressError";
12
+ }
13
+ }
1
14
  /**
2
15
  * Convert Node.js IncomingMessage headers to a flat Record<string, string>.
3
16
  * Drops array-valued headers (keeps only string values).
4
17
  */
5
18
  export function parseNodeHeaders(req) {
6
- const headers = {};
7
- for (const [key, value] of Object.entries(req.headers)) {
8
- if (typeof value === "string") {
9
- headers[key] = value;
10
- }
11
- }
12
- return headers;
19
+ // Object.fromEntries defines own properties, so a header literally named
20
+ // `__proto__` is preserved instead of being swallowed by the prototype
21
+ // setter. The prototype is retained so consumers keep Object.prototype.
22
+ return Object.fromEntries(Object.entries(req.headers).filter((entry) => typeof entry[1] === "string"));
13
23
  }
14
24
  /**
15
25
  * Extract query parameters from a URL as a flat Record<string, string>.
16
26
  */
17
27
  export function parseNodeQuery(url) {
18
- const query = {};
19
- url.searchParams.forEach((value, key) => {
20
- query[key] = value;
21
- });
22
- return query;
28
+ // Own-property definition for the same reason as parseNodeHeaders, and it
29
+ // matches how the fetch interceptor builds its query record.
30
+ return Object.fromEntries(url.searchParams);
23
31
  }
24
32
  /** Default body size limit: 10 MB */
25
33
  const DEFAULT_MAX_BODY_SIZE = 10 * 1024 * 1024;
34
+ const DECIMAL_CONTENT_LENGTH = /^\d+$/;
35
+ function payloadTooLargeError() {
36
+ return new HttpIngressError(413, "PAYLOAD_TOO_LARGE", "Request body too large");
37
+ }
38
+ function requestAbortedError() {
39
+ const error = new Error("Request body collection aborted");
40
+ error.name = "AbortError";
41
+ return error;
42
+ }
43
+ function isJsonMediaType(contentType) {
44
+ const baseMediaType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
45
+ return (baseMediaType === "application/json" || baseMediaType.endsWith("+json"));
46
+ }
26
47
  /**
27
48
  * Collect and parse the request body from a Node.js IncomingMessage.
28
- * Returns parsed JSON if content-type includes "json", otherwise the raw string.
49
+ * Returns parsed JSON for application/json and +json media types, otherwise the
50
+ * raw string.
29
51
  * Returns undefined for empty bodies.
30
52
  * @param req - Node.js IncomingMessage
31
53
  * @param headers - Parsed request headers
32
54
  * @param maxBodySize - Maximum body size in bytes (default: 10 MB)
33
55
  */
34
56
  export function collectBody(req, headers, maxBodySize = DEFAULT_MAX_BODY_SIZE) {
57
+ const contentLength = headers["content-length"];
58
+ const declaredBodyTooLarge = contentLength !== undefined &&
59
+ DECIMAL_CONTENT_LENGTH.test(contentLength) &&
60
+ Number(contentLength) > maxBodySize;
35
61
  return new Promise((resolve, reject) => {
36
62
  const chunks = [];
37
63
  let totalSize = 0;
38
- req.on("error", reject);
64
+ let settled = false;
65
+ const rejectOnce = (error) => {
66
+ if (settled)
67
+ return;
68
+ settled = true;
69
+ chunks.length = 0;
70
+ reject(error);
71
+ };
72
+ const resolveOnce = (body) => {
73
+ if (settled)
74
+ return;
75
+ settled = true;
76
+ chunks.length = 0;
77
+ resolve(body);
78
+ };
79
+ if (declaredBodyTooLarge) {
80
+ rejectOnce(payloadTooLargeError());
81
+ }
82
+ req.on("error", rejectOnce);
83
+ req.on("aborted", () => rejectOnce(requestAbortedError()));
84
+ req.on("close", () => rejectOnce(requestAbortedError()));
39
85
  req.on("data", (chunk) => {
40
- totalSize += chunk.length;
86
+ if (settled)
87
+ return;
88
+ totalSize += chunk.byteLength;
41
89
  if (totalSize > maxBodySize) {
42
- req.destroy();
43
- reject(Object.assign(new Error("Request body too large"), { status: 413 }));
90
+ rejectOnce(payloadTooLargeError());
44
91
  return;
45
92
  }
46
93
  chunks.push(chunk);
47
94
  });
48
95
  req.on("end", () => {
96
+ if (settled)
97
+ return;
49
98
  const raw = Buffer.concat(chunks).toString();
50
99
  if (!raw) {
51
- resolve(undefined);
100
+ resolveOnce(undefined);
52
101
  return;
53
102
  }
54
103
  const contentType = headers["content-type"] ?? "";
55
- if (contentType.includes("json")) {
104
+ if (isJsonMediaType(contentType)) {
56
105
  try {
57
- resolve(JSON.parse(raw));
106
+ resolveOnce(JSON.parse(raw));
58
107
  }
59
108
  catch {
60
- resolve(raw);
109
+ rejectOnce(new HttpIngressError(400, "MALFORMED_JSON", "Malformed JSON request body"));
61
110
  }
62
111
  }
63
112
  else {
64
- resolve(raw);
113
+ resolveOnce(raw);
65
114
  }
66
115
  });
67
116
  });
68
117
  }
118
+ /** How long a rejected request may stay silent before the response ends. */
119
+ const REJECTED_REQUEST_IDLE_MS = 400;
120
+ /** Hard cap for a client that keeps streaming after a rejected request. */
121
+ const REJECTED_REQUEST_DRAIN_GRACE_MS = 5_000;
122
+ function prepareWriteableResponse(response, extraHeaders) {
123
+ const responseHeaders = { ...response.headers };
124
+ if (extraHeaders) {
125
+ const names = new Map(Object.keys(responseHeaders).map((name) => [name.toLowerCase(), name]));
126
+ for (const [name, value] of Object.entries(extraHeaders)) {
127
+ const previousName = names.get(name.toLowerCase());
128
+ if (previousName !== undefined)
129
+ delete responseHeaders[previousName];
130
+ responseHeaders[name] = value;
131
+ names.set(name.toLowerCase(), name);
132
+ }
133
+ }
134
+ const hasContentType = Object.keys(responseHeaders).some((header) => header.toLowerCase() === "content-type");
135
+ if (!hasContentType &&
136
+ response.body !== undefined &&
137
+ isBinaryBody(response.body)) {
138
+ responseHeaders["content-type"] = "application/octet-stream";
139
+ }
140
+ else if (!hasContentType &&
141
+ response.body !== undefined &&
142
+ typeof response.body !== "string") {
143
+ responseHeaders["content-type"] = "application/json";
144
+ }
145
+ const body = serializeResponseBody({
146
+ ...response,
147
+ headers: responseHeaders,
148
+ });
149
+ return { headers: responseHeaders, body };
150
+ }
69
151
  /**
70
152
  * Write a Schmock Response to a Node.js ServerResponse.
71
153
  * Serializes non-string bodies as JSON and sets content-type when missing.
72
154
  */
73
155
  export function writeSchmockResponse(res, response, extraHeaders) {
74
- const responseHeaders = {
75
- ...response.headers,
76
- ...extraHeaders,
156
+ const { headers, body } = prepareWriteableResponse(response, extraHeaders);
157
+ res.writeHead(response.status, headers);
158
+ res.end(body);
159
+ }
160
+ /**
161
+ * Write a rejection (e.g. 413) while the client may still be uploading.
162
+ *
163
+ * Ending the response immediately makes Node tear the socket down while
164
+ * request bytes are in flight; the resulting TCP reset discards the
165
+ * already-written error from the client's receive buffer, so the client
166
+ * observes ECONNRESET instead of the response. Instead the response body is
167
+ * flushed right away and the end is deferred — a lingering close — until the
168
+ * request finishes, goes idle, or exhausts the grace cap.
169
+ */
170
+ export function writeRejectedSchmockResponse(req, res, response, extraHeaders) {
171
+ const { headers, body } = prepareWriteableResponse(response, extraHeaders);
172
+ res.writeHead(response.status, headers);
173
+ if (body !== undefined)
174
+ res.write(body);
175
+ let idleTimer;
176
+ let graceTimer;
177
+ let finished = false;
178
+ const onData = () => {
179
+ // The client is still sending: keep the socket open so its bytes have
180
+ // somewhere to go, pushing the deferred end out with every chunk.
181
+ if (idleTimer !== undefined)
182
+ clearTimeout(idleTimer);
183
+ idleTimer = setTimeout(finish, REJECTED_REQUEST_IDLE_MS);
184
+ idleTimer.unref?.();
77
185
  };
78
- if (!responseHeaders["content-type"] &&
79
- response.body !== undefined &&
80
- typeof response.body !== "string") {
81
- responseHeaders["content-type"] = "application/json";
82
- }
83
- const responseBody = response.body === undefined
84
- ? undefined
85
- : typeof response.body === "string"
86
- ? response.body
87
- : JSON.stringify(response.body);
88
- res.writeHead(response.status, responseHeaders);
89
- res.end(responseBody);
186
+ const finish = () => {
187
+ if (finished)
188
+ return;
189
+ finished = true;
190
+ req.off("data", onData);
191
+ if (idleTimer !== undefined)
192
+ clearTimeout(idleTimer);
193
+ if (graceTimer !== undefined)
194
+ clearTimeout(graceTimer);
195
+ if (!res.writableEnded)
196
+ res.end();
197
+ };
198
+ req.on("data", onData);
199
+ req.once("end", finish);
200
+ req.once("close", finish);
201
+ res.once("close", finish);
202
+ onData();
203
+ graceTimer = setTimeout(finish, REJECTED_REQUEST_DRAIN_GRACE_MS);
204
+ graceTimer.unref?.();
205
+ req.resume();
90
206
  }