@counterfact/client 0.1.1 → 0.2.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/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # @counterfact/client
2
2
 
3
+ ## 0.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 96b565d: Add simulator.reset() to reconstruct stores, dependent contexts, source routes and startup state without restarting HTTP, and simulator.scenario(path, group?) to await named scenarios with the REPL arguments. Document request gating, reset failure recovery, reference lifetimes, and worker-scoped Playwright integration.
8
+
9
+ ## 0.2.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 13155b0: Display complete multipart request bodies in the REPL client output, and write
14
+ route help directly to the console.
15
+
16
+ ### Patch Changes
17
+
18
+ - 04d67bb: Validate and send required OpenAPI cookie, body, and form inputs through the immutable route builder, including REPL completions for the new methods.
19
+
3
20
  ## 0.1.1
4
21
 
5
22
  ### Patch Changes
package/README.md CHANGED
@@ -34,13 +34,23 @@ const route = createRouteFunction(3000, "localhost", catalog);
34
34
  const pet = route("/pets/{petId}").method("get").path({ petId: 42 });
35
35
 
36
36
  console.log(pet.ready());
37
- console.log(pet.help());
37
+ pet.help();
38
38
  await pet.send();
39
39
  ```
40
40
 
41
41
  Builder methods are immutable: calling `path()`, `query()`, `headers()`,
42
- `body()`, or `method()` returns a new builder, so a common request can be
43
- safely branched into reusable variants.
42
+ `cookies()`, `body()`, `form()`, or `method()` returns a new builder, so a
43
+ common request can be safely branched into reusable variants.
44
+
45
+ The builder validates required OpenAPI path, query, header, cookie, body, and
46
+ form inputs. Use `cookies()` to merge percent-encoded cookie pairs with an
47
+ existing `Cookie` header. Use `form()` for OpenAPI form content; it sends
48
+ URL-encoded data by default and text-only multipart data when
49
+ `multipart/form-data` is the sole declared form type. Binary and file form
50
+ parts are not supported.
51
+
52
+ Only one request entity is active. Calling `body()` after `form()`, or `form()`
53
+ after `body()`, clears the earlier entity so the last method wins.
44
54
 
45
55
  See [`examples/reusable-request.mjs`](./examples/reusable-request.mjs) for a
46
56
  complete example with a local HTTP server.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  export { RawHttpClient } from "./raw-http-client.js";
2
2
  export { RouteBuilder, createRouteFunction, type MissingParam, type MissingParams, type RouteBuilderOptions, type RouteParams, } from "./route-builder.js";
3
- export { createOpenApiRouteCatalog, type OpenApiRouteDocument, type RouteCatalog, type RouteOperation, type RouteParameter, } from "./route-catalog.js";
3
+ export { createOpenApiRouteCatalog, type OpenApiRouteDocument, type RouteCatalog, type RouteOperation, type RouteParameter, type RouteRequestBody, } from "./route-catalog.js";
@@ -44,6 +44,23 @@ function highlightJson(text) {
44
44
  return `${colors.yellow}${match}${colors.reset}`;
45
45
  });
46
46
  }
47
+ /**
48
+ * Splits an HTTP message at its first head/body separator.
49
+ *
50
+ * Request and response bodies can themselves contain `\r\n\r\n`, notably in
51
+ * multipart form data, so splitting every occurrence would truncate the
52
+ * displayed body after its first part.
53
+ */
54
+ function splitHttpMessage(raw) {
55
+ const separator = "\r\n\r\n";
56
+ const separatorIndex = raw.indexOf(separator);
57
+ if (separatorIndex === -1)
58
+ return [raw, ""];
59
+ return [
60
+ raw.slice(0, separatorIndex),
61
+ raw.slice(separatorIndex + separator.length),
62
+ ];
63
+ }
47
64
  function stringifyBody(body) {
48
65
  if (typeof body === "string") {
49
66
  return body;
@@ -147,7 +164,7 @@ export class RawHttpClient {
147
164
  });
148
165
  }
149
166
  #printRequest(raw, requestNumber) {
150
- const [head = "", body = ""] = raw.split("\r\n\r\n");
167
+ const [head, body] = splitHttpMessage(raw);
151
168
  const lines = head.split("\r\n");
152
169
  process.stdout.write(`${colors.cyan}\n----- REQUEST #${requestNumber} -----${colors.reset}\n`);
153
170
  process.stdout.write(`${colors.cyan}${lines[0]}${colors.reset}\n`);
@@ -163,7 +180,7 @@ export class RawHttpClient {
163
180
  }
164
181
  }
165
182
  #printResponse(raw, requestNumber) {
166
- const [head = "", body = ""] = raw.split("\r\n\r\n");
183
+ const [head, body] = splitHttpMessage(raw);
167
184
  const lines = head.split("\r\n");
168
185
  const statusLine = lines[0] ?? "";
169
186
  let statusColor = colors.green;
@@ -6,17 +6,22 @@ export interface MissingParam {
6
6
  type?: string;
7
7
  }
8
8
  export interface MissingParams {
9
+ body?: MissingParam[];
10
+ cookie?: MissingParam[];
11
+ formData?: MissingParam[];
9
12
  header?: MissingParam[];
10
13
  path?: MissingParam[];
11
14
  query?: MissingParam[];
12
15
  }
13
16
  export interface RouteBuilderOptions {
14
17
  body?: unknown;
18
+ cookieParams?: RouteParams;
19
+ formParams?: RouteParams;
15
20
  headerParams?: RouteParams;
16
21
  host?: string;
17
22
  method?: string;
18
23
  pathParams?: RouteParams;
19
- port: number;
24
+ port: number | (() => number);
20
25
  queryParams?: RouteParams;
21
26
  routeCatalog?: RouteCatalog;
22
27
  }
@@ -36,6 +41,10 @@ export interface RouteBuilderOptions {
36
41
  export declare class RouteBuilder {
37
42
  readonly routePath: string;
38
43
  private readonly _body;
44
+ private readonly _bodySet;
45
+ private readonly _cookieParams;
46
+ private readonly _formParams;
47
+ private readonly _formSet;
39
48
  private readonly _headerParams;
40
49
  private readonly _host;
41
50
  private readonly _method;
@@ -71,13 +80,34 @@ export declare class RouteBuilder {
71
80
  * @param params - Key/value map of header names to values.
72
81
  */
73
82
  headers(params: RouteParams): RouteBuilder;
83
+ /**
84
+ * Returns a new builder with additional request cookies merged in.
85
+ *
86
+ * Cookie names and values are percent-encoded when the request is sent.
87
+ *
88
+ * @param params - Key/value map of cookie names to values.
89
+ */
90
+ cookies(params: RouteParams): RouteBuilder;
74
91
  /**
75
92
  * Returns a new builder with the request body set.
76
93
  *
77
94
  * @param body - The request body (will be serialised to JSON or sent as-is).
78
95
  */
79
96
  body(body: unknown): RouteBuilder;
97
+ /**
98
+ * Returns a new builder with additional text form fields merged in.
99
+ *
100
+ * Calling `form()` after `body()` clears the body. Calling `body()` after
101
+ * `form()` clears the form, so the last entity method wins.
102
+ *
103
+ * @param params - Key/value map of form field names to text values.
104
+ */
105
+ form(params: RouteParams): RouteBuilder;
80
106
  private getOperation;
107
+ private getHeaderValue;
108
+ private getHeaderCookies;
109
+ private getCookieValue;
110
+ private requestBodyIsSet;
81
111
  /**
82
112
  * Returns `true` when a method is set and no required parameters are
83
113
  * missing.
@@ -86,14 +116,14 @@ export declare class RouteBuilder {
86
116
  /**
87
117
  * Returns a {@link MissingParams} object describing all required parameters
88
118
  * that have not yet been set, or `undefined` when nothing is missing (or
89
- * when the operation has no parameters).
119
+ * when the operation has no required inputs).
90
120
  */
91
121
  missing(): MissingParams | undefined;
92
122
  /**
93
- * Returns a human-readable help string describing the operation, its
123
+ * Writes human-readable help describing the operation, its
94
124
  * parameters, and the expected responses.
95
125
  */
96
- help(): string;
126
+ help(): void;
97
127
  /**
98
128
  * Executes the HTTP request and returns the parsed response body.
99
129
  *
@@ -108,9 +138,9 @@ export declare class RouteBuilder {
108
138
  * given route path, pre-configured with the server's host, port, and OpenAPI
109
139
  * route catalog.
110
140
  *
111
- * @param port - The port the Counterfact server is listening on.
141
+ * @param port - The listening port, or a getter resolved when sending a request.
112
142
  * @param host - The server hostname (default `"localhost"`).
113
143
  * @param routeCatalog - Optional route catalog for parameter introspection.
114
144
  * @returns A function `(routePath: string) => RouteBuilder`.
115
145
  */
116
- export declare function createRouteFunction(port: number, host?: string, routeCatalog?: RouteCatalog): (routePath: string) => RouteBuilder;
146
+ export declare function createRouteFunction(port: number | (() => number), host?: string, routeCatalog?: RouteCatalog): (routePath: string) => RouteBuilder;
@@ -1,4 +1,54 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import { RawHttpClient } from "./raw-http-client.js";
3
+ const FORM_URLENCODED = "application/x-www-form-urlencoded";
4
+ const FORM_MULTIPART = "multipart/form-data";
5
+ function isFormContentType(contentType) {
6
+ const normalized = contentType.toLowerCase();
7
+ return normalized === FORM_URLENCODED || normalized === FORM_MULTIPART;
8
+ }
9
+ function getRequestBodyContentTypes(operation) {
10
+ return Object.keys(operation.requestBody?.content ?? {});
11
+ }
12
+ function getFormContentType(operation) {
13
+ if (!operation)
14
+ return FORM_URLENCODED;
15
+ const declared = [
16
+ ...(operation.consumes ?? []),
17
+ ...getRequestBodyContentTypes(operation),
18
+ ].map((contentType) => contentType.toLowerCase());
19
+ if (declared.includes(FORM_URLENCODED))
20
+ return FORM_URLENCODED;
21
+ if (declared.includes(FORM_MULTIPART))
22
+ return FORM_MULTIPART;
23
+ return FORM_URLENCODED;
24
+ }
25
+ function findHeaderKey(headers, target) {
26
+ const normalizedTarget = target.toLowerCase();
27
+ return Object.keys(headers).find((name) => name.toLowerCase() === normalizedTarget);
28
+ }
29
+ function setHeader(headers, name, value) {
30
+ const existing = Object.keys(headers).find((headerName) => headerName.toLowerCase() === name.toLowerCase());
31
+ headers[existing ?? name] = value;
32
+ }
33
+ function decodeCookieName(name) {
34
+ try {
35
+ return decodeURIComponent(name);
36
+ }
37
+ catch {
38
+ return name;
39
+ }
40
+ }
41
+ function escapeMultipartName(name) {
42
+ return name
43
+ .replaceAll("\\", "\\\\")
44
+ .replaceAll('"', '\\"')
45
+ .replaceAll("\r", "%0D")
46
+ .replaceAll("\n", "%0A");
47
+ }
48
+ function encodeMultipartForm(params, boundary) {
49
+ const parts = Object.entries(params).map(([name, value]) => `--${boundary}\r\nContent-Disposition: form-data; name="${escapeMultipartName(name)}"\r\n\r\n${String(value)}\r\n`);
50
+ return `${parts.join("")}--${boundary}--\r\n`;
51
+ }
2
52
  /**
3
53
  * Immutable fluent builder for constructing and sending HTTP requests from the
4
54
  * Counterfact REPL.
@@ -15,6 +65,10 @@ import { RawHttpClient } from "./raw-http-client.js";
15
65
  export class RouteBuilder {
16
66
  routePath;
17
67
  _body;
68
+ _bodySet;
69
+ _cookieParams;
70
+ _formParams;
71
+ _formSet;
18
72
  _headerParams;
19
73
  _host;
20
74
  _method;
@@ -29,7 +83,11 @@ export class RouteBuilder {
29
83
  this._pathParams = options.pathParams ?? {};
30
84
  this._queryParams = options.queryParams ?? {};
31
85
  this._headerParams = options.headerParams ?? {};
86
+ this._cookieParams = options.cookieParams ?? {};
32
87
  this._body = options.body;
88
+ this._formParams = options.formParams ?? {};
89
+ this._formSet = "formParams" in options;
90
+ this._bodySet = options.body !== undefined && !this._formSet;
33
91
  this._port = options.port;
34
92
  this._host = options.host ?? "localhost";
35
93
  this._routeCatalog = options.routeCatalog;
@@ -41,8 +99,8 @@ export class RouteBuilder {
41
99
  return this._routeCatalog.getOperation(this.routePath, this._method);
42
100
  }
43
101
  clone(overrides) {
44
- return new RouteBuilder(this.routePath, {
45
- body: "body" in overrides ? overrides.body : this._body,
102
+ const options = {
103
+ cookieParams: overrides.cookieParams ?? this._cookieParams,
46
104
  headerParams: overrides.headerParams ?? this._headerParams,
47
105
  host: this._host,
48
106
  method: overrides.method ?? this._method,
@@ -50,7 +108,20 @@ export class RouteBuilder {
50
108
  port: this._port,
51
109
  queryParams: overrides.queryParams ?? this._queryParams,
52
110
  routeCatalog: this._routeCatalog,
53
- });
111
+ };
112
+ if ("formParams" in overrides) {
113
+ options.formParams = overrides.formParams;
114
+ }
115
+ else if ("body" in overrides) {
116
+ options.body = overrides.body;
117
+ }
118
+ else if (this._formSet) {
119
+ options.formParams = this._formParams;
120
+ }
121
+ else if (this._bodySet) {
122
+ options.body = this._body;
123
+ }
124
+ return new RouteBuilder(this.routePath, options);
54
125
  }
55
126
  /**
56
127
  * Returns a new builder with the HTTP method set.
@@ -84,6 +155,16 @@ export class RouteBuilder {
84
155
  headers(params) {
85
156
  return this.clone({ headerParams: { ...this._headerParams, ...params } });
86
157
  }
158
+ /**
159
+ * Returns a new builder with additional request cookies merged in.
160
+ *
161
+ * Cookie names and values are percent-encoded when the request is sent.
162
+ *
163
+ * @param params - Key/value map of cookie names to values.
164
+ */
165
+ cookies(params) {
166
+ return this.clone({ cookieParams: { ...this._cookieParams, ...params } });
167
+ }
87
168
  /**
88
169
  * Returns a new builder with the request body set.
89
170
  *
@@ -92,9 +173,56 @@ export class RouteBuilder {
92
173
  body(body) {
93
174
  return this.clone({ body });
94
175
  }
176
+ /**
177
+ * Returns a new builder with additional text form fields merged in.
178
+ *
179
+ * Calling `form()` after `body()` clears the body. Calling `body()` after
180
+ * `form()` clears the form, so the last entity method wins.
181
+ *
182
+ * @param params - Key/value map of form field names to text values.
183
+ */
184
+ form(params) {
185
+ const current = this._formSet ? this._formParams : {};
186
+ return this.clone({ formParams: { ...current, ...params } });
187
+ }
95
188
  getOperation() {
96
189
  return this._operation;
97
190
  }
191
+ getHeaderValue(name) {
192
+ const key = findHeaderKey(this._headerParams, name);
193
+ return key === undefined ? undefined : this._headerParams[key];
194
+ }
195
+ getHeaderCookies() {
196
+ const cookieHeader = this.getHeaderValue("cookie");
197
+ const cookies = new Map();
198
+ if (cookieHeader === undefined)
199
+ return cookies;
200
+ for (const pair of String(cookieHeader).split(";")) {
201
+ const separator = pair.indexOf("=");
202
+ if (separator === -1)
203
+ continue;
204
+ const name = decodeCookieName(pair.slice(0, separator).trim());
205
+ const value = pair.slice(separator + 1).trim();
206
+ cookies.set(name, value);
207
+ }
208
+ return cookies;
209
+ }
210
+ getCookieValue(name) {
211
+ if (name in this._cookieParams)
212
+ return this._cookieParams[name];
213
+ return this.getHeaderCookies().get(name);
214
+ }
215
+ requestBodyIsSet(operation) {
216
+ const contentTypes = getRequestBodyContentTypes(operation);
217
+ if (this._formSet) {
218
+ return contentTypes.some(isFormContentType);
219
+ }
220
+ if (this._bodySet) {
221
+ return (contentTypes.length === 0 ||
222
+ contentTypes.some((contentType) => !isFormContentType(contentType)));
223
+ }
224
+ return false;
225
+ }
98
226
  /**
99
227
  * Returns `true` when a method is set and no required parameters are
100
228
  * missing.
@@ -107,17 +235,19 @@ export class RouteBuilder {
107
235
  /**
108
236
  * Returns a {@link MissingParams} object describing all required parameters
109
237
  * that have not yet been set, or `undefined` when nothing is missing (or
110
- * when the operation has no parameters).
238
+ * when the operation has no required inputs).
111
239
  */
112
240
  missing() {
113
241
  const operation = this.getOperation();
114
- if (!operation?.parameters)
242
+ if (!operation)
115
243
  return undefined;
116
244
  const missingParams = {};
117
- for (const param of operation.parameters) {
245
+ for (const param of operation.parameters ?? []) {
118
246
  if (!param.required)
119
247
  continue;
120
- const paramType = param.type ?? param.schema?.type ?? "string";
248
+ const paramType = param.type ??
249
+ param.schema?.type ??
250
+ (param.in === "body" ? "object" : "string");
121
251
  const paramInfo = {
122
252
  description: param.description,
123
253
  name: param.name,
@@ -130,16 +260,39 @@ export class RouteBuilder {
130
260
  missingParams.query = [...(missingParams.query ?? []), paramInfo];
131
261
  }
132
262
  else if (param.in === "header" &&
133
- !Object.keys(this._headerParams).some((name) => name.toLowerCase() === param.name.toLowerCase())) {
263
+ this.getHeaderValue(param.name) === undefined) {
134
264
  missingParams.header = [...(missingParams.header ?? []), paramInfo];
135
265
  }
266
+ else if (param.in === "cookie" &&
267
+ this.getCookieValue(param.name) === undefined) {
268
+ missingParams.cookie = [...(missingParams.cookie ?? []), paramInfo];
269
+ }
270
+ else if (param.in === "body" && !this._bodySet) {
271
+ missingParams.body = [...(missingParams.body ?? []), paramInfo];
272
+ }
273
+ else if (param.in === "formData" &&
274
+ (!this._formSet || !(param.name in this._formParams))) {
275
+ missingParams.formData = [...(missingParams.formData ?? []), paramInfo];
276
+ }
277
+ }
278
+ if (operation.requestBody?.required && !this.requestBodyIsSet(operation)) {
279
+ const schemas = Object.values(operation.requestBody.content ?? {});
280
+ missingParams.body = [
281
+ ...(missingParams.body ?? []),
282
+ {
283
+ description: operation.requestBody.description,
284
+ name: "requestBody",
285
+ type: schemas.find((media) => media.schema?.type)?.schema?.type ??
286
+ "object",
287
+ },
288
+ ];
136
289
  }
137
290
  if (Object.keys(missingParams).length === 0)
138
291
  return undefined;
139
292
  return missingParams;
140
293
  }
141
294
  /**
142
- * Returns a human-readable help string describing the operation, its
295
+ * Writes human-readable help describing the operation, its
143
296
  * parameters, and the expected responses.
144
297
  */
145
298
  help() {
@@ -161,6 +314,9 @@ export class RouteBuilder {
161
314
  const pathParams = operation.parameters.filter((p) => p.in === "path");
162
315
  const queryParams = operation.parameters.filter((p) => p.in === "query");
163
316
  const headerParams = operation.parameters.filter((p) => p.in === "header");
317
+ const cookieParams = operation.parameters.filter((p) => p.in === "cookie");
318
+ const bodyParams = operation.parameters.filter((p) => p.in === "body");
319
+ const formParams = operation.parameters.filter((p) => p.in === "formData");
164
320
  if (pathParams.length > 0) {
165
321
  lines.push("");
166
322
  lines.push("Path Parameters:");
@@ -199,6 +355,52 @@ export class RouteBuilder {
199
355
  lines.push(` Description: ${p.description}`);
200
356
  }
201
357
  }
358
+ if (cookieParams.length > 0) {
359
+ lines.push("");
360
+ lines.push("Cookies:");
361
+ for (const p of cookieParams) {
362
+ const paramType = p.type ?? p.schema?.type ?? "string";
363
+ const required = p.required ? "required" : "optional";
364
+ lines.push(` ${p.name} (${paramType}, ${required})`);
365
+ if (p.description)
366
+ lines.push(` Description: ${p.description}`);
367
+ }
368
+ }
369
+ if (formParams.length > 0) {
370
+ lines.push("");
371
+ lines.push("Form Fields:");
372
+ for (const p of formParams) {
373
+ const paramType = p.type ?? p.schema?.type ?? "string";
374
+ const required = p.required ? "required" : "optional";
375
+ lines.push(` ${p.name} (${paramType}, ${required})`);
376
+ if (p.description)
377
+ lines.push(` Description: ${p.description}`);
378
+ }
379
+ }
380
+ if (bodyParams.length > 0) {
381
+ lines.push("");
382
+ lines.push("Request Body:");
383
+ for (const p of bodyParams) {
384
+ const paramType = p.type ?? p.schema?.type ?? "object";
385
+ const required = p.required ? "required" : "optional";
386
+ lines.push(` ${p.name} (${paramType}, ${required})`);
387
+ if (p.description)
388
+ lines.push(` Description: ${p.description}`);
389
+ }
390
+ }
391
+ }
392
+ if (operation?.requestBody) {
393
+ const required = operation.requestBody.required ? "required" : "optional";
394
+ const contentTypes = getRequestBodyContentTypes(operation);
395
+ lines.push("");
396
+ lines.push("Request Body:");
397
+ lines.push(` requestBody (${required})`);
398
+ if (operation.requestBody.description) {
399
+ lines.push(` Description: ${operation.requestBody.description}`);
400
+ }
401
+ if (contentTypes.length > 0) {
402
+ lines.push(` Content types: ${contentTypes.join(" | ")}`);
403
+ }
202
404
  }
203
405
  if (operation?.responses) {
204
406
  lines.push("");
@@ -210,7 +412,7 @@ export class RouteBuilder {
210
412
  }
211
413
  }
212
414
  }
213
- return lines.join("\n");
415
+ console.log(lines.join("\n"));
214
416
  }
215
417
  /**
216
418
  * Executes the HTTP request and returns the parsed response body.
@@ -248,6 +450,24 @@ export class RouteBuilder {
248
450
  lines.push(` - ${p.name} (${p.type ?? "string"})`);
249
451
  }
250
452
  }
453
+ if (missing.cookie) {
454
+ lines.push(" cookie:");
455
+ for (const p of missing.cookie) {
456
+ lines.push(` - ${p.name} (${p.type ?? "string"})`);
457
+ }
458
+ }
459
+ if (missing.formData) {
460
+ lines.push(" formData:");
461
+ for (const p of missing.formData) {
462
+ lines.push(` - ${p.name} (${p.type ?? "string"})`);
463
+ }
464
+ }
465
+ if (missing.body) {
466
+ lines.push(" body:");
467
+ for (const p of missing.body) {
468
+ lines.push(` - ${p.name} (${p.type ?? "object"})`);
469
+ }
470
+ }
251
471
  throw new Error(lines.join("\n"));
252
472
  }
253
473
  // Build URL with path parameters substituted
@@ -261,8 +481,32 @@ export class RouteBuilder {
261
481
  const qs = new URLSearchParams(queryEntries.map(([k, v]) => [k, String(v)])).toString();
262
482
  url = `${url}?${qs}`;
263
483
  }
264
- const client = new RawHttpClient(this._host, this._port);
484
+ const port = typeof this._port === "function" ? this._port() : this._port;
485
+ const client = new RawHttpClient(this._host, port);
265
486
  const headers = Object.fromEntries(Object.entries(this._headerParams).map(([k, v]) => [k, String(v)]));
487
+ const cookiePairs = Object.entries(this._cookieParams).map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`);
488
+ if (cookiePairs.length > 0) {
489
+ const cookieHeaderKey = Object.keys(headers).find((name) => name.toLowerCase() === "cookie");
490
+ let existingCookies;
491
+ if (cookieHeaderKey !== undefined) {
492
+ // eslint-disable-next-line security/detect-object-injection -- The key was selected from this inert header map.
493
+ existingCookies = headers[cookieHeaderKey];
494
+ }
495
+ setHeader(headers, "Cookie", [existingCookies, ...cookiePairs].filter(Boolean).join("; "));
496
+ }
497
+ let entity = this._body;
498
+ if (this._formSet) {
499
+ const formContentType = getFormContentType(this.getOperation());
500
+ if (formContentType === FORM_MULTIPART) {
501
+ const boundary = `counterfact-${randomBytes(16).toString("hex")}`;
502
+ entity = encodeMultipartForm(this._formParams, boundary);
503
+ setHeader(headers, "Content-Type", `${FORM_MULTIPART}; boundary=${boundary}`);
504
+ }
505
+ else {
506
+ entity = new URLSearchParams(Object.entries(this._formParams).map(([name, value]) => [name, String(value)])).toString();
507
+ setHeader(headers, "Content-Type", FORM_URLENCODED);
508
+ }
509
+ }
266
510
  const method = this._method.toLowerCase();
267
511
  switch (method) {
268
512
  case "get":
@@ -276,11 +520,11 @@ export class RouteBuilder {
276
520
  case "trace":
277
521
  return client.trace(url, headers);
278
522
  case "post":
279
- return client.post(url, this._body, headers);
523
+ return client.post(url, entity, headers);
280
524
  case "put":
281
- return client.put(url, this._body, headers);
525
+ return client.put(url, entity, headers);
282
526
  case "patch":
283
- return client.patch(url, this._body, headers);
527
+ return client.patch(url, entity, headers);
284
528
  default:
285
529
  throw new Error(`Unsupported HTTP method: ${this._method}`);
286
530
  }
@@ -293,6 +537,10 @@ export class RouteBuilder {
293
537
  if (operation?.parameters) {
294
538
  const pathParams = operation.parameters.filter((p) => p.in === "path");
295
539
  const queryParams = operation.parameters.filter((p) => p.in === "query");
540
+ const headerParams = operation.parameters.filter((p) => p.in === "header");
541
+ const cookieParams = operation.parameters.filter((p) => p.in === "cookie");
542
+ const formParams = operation.parameters.filter((p) => p.in === "formData");
543
+ const bodyParams = operation.parameters.filter((p) => p.in === "body");
296
544
  if (pathParams.length > 0) {
297
545
  lines.push("");
298
546
  lines.push("Path:");
@@ -310,6 +558,48 @@ export class RouteBuilder {
310
558
  lines.push(` ${p.name}: ${value !== undefined ? String(value) : label}`);
311
559
  }
312
560
  }
561
+ if (headerParams.length > 0) {
562
+ lines.push("");
563
+ lines.push("Headers:");
564
+ for (const p of headerParams) {
565
+ const value = this.getHeaderValue(p.name);
566
+ const label = p.required ? "[missing]" : "[optional]";
567
+ lines.push(` ${p.name}: ${value !== undefined ? String(value) : label}`);
568
+ }
569
+ }
570
+ if (cookieParams.length > 0) {
571
+ lines.push("");
572
+ lines.push("Cookies:");
573
+ for (const p of cookieParams) {
574
+ const value = this.getCookieValue(p.name);
575
+ const label = p.required ? "[missing]" : "[optional]";
576
+ lines.push(` ${p.name}: ${value !== undefined ? String(value) : label}`);
577
+ }
578
+ }
579
+ if (formParams.length > 0) {
580
+ lines.push("");
581
+ lines.push("Form:");
582
+ for (const p of formParams) {
583
+ const value = this._formSet ? this._formParams[p.name] : undefined;
584
+ const label = p.required ? "[missing]" : "[optional]";
585
+ lines.push(` ${p.name}: ${value !== undefined ? String(value) : label}`);
586
+ }
587
+ }
588
+ if (bodyParams.length > 0) {
589
+ lines.push("");
590
+ lines.push("Body:");
591
+ for (const p of bodyParams) {
592
+ const label = p.required ? "[missing]" : "[optional]";
593
+ lines.push(` ${p.name}: ${this._bodySet ? "[set]" : label}`);
594
+ }
595
+ }
596
+ }
597
+ if (operation?.requestBody) {
598
+ const label = operation.requestBody.required ? "[missing]" : "[optional]";
599
+ const entityKind = this._formSet ? "form" : "body";
600
+ lines.push("");
601
+ lines.push("Body:");
602
+ lines.push(` requestBody: ${this.requestBodyIsSet(operation) ? `[set with ${entityKind}()]` : label}`);
313
603
  }
314
604
  lines.push("");
315
605
  lines.push(`Ready: ${this.ready()}`);
@@ -321,7 +611,7 @@ export class RouteBuilder {
321
611
  * given route path, pre-configured with the server's host, port, and OpenAPI
322
612
  * route catalog.
323
613
  *
324
- * @param port - The port the Counterfact server is listening on.
614
+ * @param port - The listening port, or a getter resolved when sending a request.
325
615
  * @param host - The server hostname (default `"localhost"`).
326
616
  * @param routeCatalog - Optional route catalog for parameter introspection.
327
617
  * @returns A function `(routePath: string) => RouteBuilder`.
@@ -11,10 +11,22 @@ export interface RouteParameter {
11
11
  };
12
12
  type?: string;
13
13
  }
14
+ /** OpenAPI 3 request-body metadata consumed by request validation and help. */
15
+ export interface RouteRequestBody {
16
+ content?: Readonly<Record<string, {
17
+ schema?: {
18
+ type?: string;
19
+ };
20
+ }>>;
21
+ description?: string;
22
+ required?: boolean;
23
+ }
14
24
  /** Operation metadata consumed by request help and validation. */
15
25
  export interface RouteOperation {
26
+ consumes?: readonly string[];
16
27
  description?: string;
17
28
  parameters?: readonly RouteParameter[];
29
+ requestBody?: RouteRequestBody;
18
30
  responses?: Readonly<Record<string, {
19
31
  description?: string;
20
32
  }>>;
@@ -30,6 +42,7 @@ export interface RouteCatalog {
30
42
  }
31
43
  /** The only OpenAPI document shape needed to create a route catalog. */
32
44
  export interface OpenApiRouteDocument {
45
+ readonly consumes?: readonly string[];
33
46
  readonly paths: Readonly<Record<string, object>>;
34
47
  }
35
48
  /**
@@ -34,10 +34,12 @@ export function createOpenApiRouteCatalog(document) {
34
34
  }
35
35
  const pathItemParameters = pathItem?.parameters;
36
36
  const parameters = mergeParameters(pathItemParameters, operation.parameters);
37
- if (!pathItemParameters || pathItemParameters.length === 0) {
37
+ const consumes = operation.consumes ?? document.consumes;
38
+ if ((!pathItemParameters || pathItemParameters.length === 0) &&
39
+ consumes === operation.consumes) {
38
40
  return operation;
39
41
  }
40
- return { ...operation, parameters };
42
+ return { ...operation, consumes, parameters };
41
43
  },
42
44
  listPaths() {
43
45
  return Object.keys(document.paths);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@counterfact/client",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Build and send reusable OpenAPI-aware HTTP requests without starting Counterfact.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",