@dlenroc/typed-client 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,22 +1,21 @@
1
- import { a as TransportFailure, i as ResponseCleanupError, n as FailureWithCleanupError, o as appendQuery, r as RequestPreparationError, t as ClientError } from "./errors-D1bIeOq9.js";
1
+ import { a as transportError, i as preserveCleanupError, n as FailureWithCleanupError, o as appendQuery, r as ResponseCleanupError, t as ClientError } from "./errors-Dcje8BxZ.js";
2
2
  // src/core/endpoint.ts
3
3
  function compilePath(url) {
4
4
  const suffixStart = url.search(/[?#]/);
5
- const pathnameEnd = suffixStart < 0 ? url.length : suffixStart;
5
+ const path = suffixStart < 0 ? url : url.slice(0, suffixStart);
6
6
  const names = [];
7
7
  const parts = [];
8
- let segmentStart = 0;
9
8
  let literalStart = 0;
10
- while (segmentStart < pathnameEnd) {
11
- const slash = url.indexOf("/", segmentStart);
12
- const segmentEnd = slash < 0 || slash >= pathnameEnd ? pathnameEnd : slash;
13
- if (url[segmentStart] === ":" && segmentStart + 1 < segmentEnd) {
14
- parts.push(url.slice(literalStart, segmentStart));
15
- names.push(url.slice(segmentStart + 1, segmentEnd));
16
- literalStart = segmentEnd;
9
+ let open = path.indexOf("{");
10
+ while (open >= 0) {
11
+ const close = path.indexOf("}", open + 1);
12
+ if (close < 0) break;
13
+ if (close > open + 1) {
14
+ parts.push(url.slice(literalStart, open));
15
+ names.push(url.slice(open + 1, close));
16
+ literalStart = close + 1;
17
17
  }
18
- if (segmentEnd === pathnameEnd) break;
19
- segmentStart = segmentEnd + 1;
18
+ open = path.indexOf("{", close + 1);
20
19
  }
21
20
  if (names.length === 0) return url;
22
21
  parts.push(url.slice(literalStart));
@@ -94,27 +93,9 @@ function endpoint(url, definition = {}) {
94
93
  }
95
94
  // src/core/client.ts
96
95
  const ONLY_NONE = ["none"];
97
- function schemaError(origin, field, context, failure, response) {
98
- const details = "issues" in failure ? {
99
- reason: "issues",
100
- issues: failure.issues
101
- } : {
102
- reason: "exception",
103
- cause: failure.cause
104
- };
105
- return new ClientError(origin === "request" ? {
106
- ...context,
107
- ...details,
108
- code: "request-schema",
109
- field
110
- } : {
111
- ...context,
112
- ...details,
113
- code: "response-schema",
114
- field,
115
- status: response.status,
116
- headers: response.headers
117
- });
96
+ function schemaError(method, url, meta, status, schema, issues, cause) {
97
+ const outcome = issues === void 0 ? "threw" : `reported ${issues.length} issue${issues.length === 1 ? "" : "s"}`;
98
+ return status === void 0 ? new ClientError("request", `Request ${schema} schema ${outcome}`, method, url, meta, void 0, schema, issues, cause) : new ClientError("response", `Response ${schema} schema ${outcome} (status ${status})`, method, url, meta, status, schema, issues, cause);
118
99
  }
119
100
  function selectResponseKinds(endpoint, expectation, discard) {
120
101
  if (discard) return ONLY_NONE;
@@ -122,36 +103,28 @@ function selectResponseKinds(endpoint, expectation, discard) {
122
103
  if (typeof expectation === "number") return endpoint.responses[expectation]?.responseKinds ?? ONLY_NONE;
123
104
  if (expectation.length === 1) return endpoint.responses[expectation[0]]?.responseKinds ?? ONLY_NONE;
124
105
  const kinds = /* @__PURE__ */ new Set();
125
- for (const status of expectation) kinds.add(endpoint.responses[status]?.kind ?? "none");
106
+ for (let i = 0; i < expectation.length; i++) {
107
+ const status = expectation[i];
108
+ kinds.add(endpoint.responses[status]?.kind ?? "none");
109
+ }
126
110
  return [...kinds];
127
111
  }
128
112
  async function rejectResponse(handle, primary, bodyWasRead = false) {
129
113
  try {
130
- if (handle.discard) await handle.discard();
131
- else if (!bodyWasRead) await handle.read("none");
114
+ if (!bodyWasRead) await handle.read("none");
115
+ else if (handle.discard) await handle.discard();
132
116
  } catch (cleanupError) {
133
117
  primary.cleanupError = cleanupError;
134
118
  }
135
119
  throw primary;
136
120
  }
137
- function preserveCleanupError(error, failure) {
138
- if (failure !== null && (typeof failure === "object" || typeof failure === "function") && "cleanupError" in failure) error.cleanupError = failure.cleanupError;
139
- return error;
140
- }
141
121
  async function invoke(endpoint, transport, input) {
142
122
  const unchecked = input?.unchecked === true;
143
123
  const discard = input?.discard === true;
144
124
  const expectedStatus = input?.status;
145
125
  const method = unchecked ? input?.method ?? endpoint.method : endpoint.method;
146
- const context = {
147
- method,
148
- meta: endpoint.meta
149
- };
150
- if (Array.isArray(expectedStatus) && expectedStatus.length === 0) throw new ClientError({
151
- ...context,
152
- code: "request-input",
153
- cause: /* @__PURE__ */ new TypeError("status must not be empty")
154
- });
126
+ const meta = endpoint.meta;
127
+ if (Array.isArray(expectedStatus) && expectedStatus.length === 0) throw new ClientError("request", "Invalid call input", method, void 0, meta, void 0, void 0, void 0, /* @__PURE__ */ new TypeError("status must not be empty"));
155
128
  let path = input?.path;
156
129
  let query = input?.query;
157
130
  let headers = input?.headers;
@@ -163,9 +136,9 @@ async function invoke(endpoint, transport, input) {
163
136
  result = endpoint.pathSchema["~standard"].validate(path);
164
137
  if ("then" in result) result = await result;
165
138
  } catch (cause) {
166
- throw schemaError("request", "path", context, { cause });
139
+ throw schemaError(method, void 0, meta, void 0, "path", void 0, cause);
167
140
  }
168
- if (result.issues) throw schemaError("request", "path", context, { issues: result.issues });
141
+ if (result.issues) throw schemaError(method, void 0, meta, void 0, "path", result.issues, void 0);
169
142
  path = result.value;
170
143
  }
171
144
  if (endpoint.querySchema !== void 0) {
@@ -174,9 +147,9 @@ async function invoke(endpoint, transport, input) {
174
147
  result = endpoint.querySchema["~standard"].validate(query);
175
148
  if ("then" in result) result = await result;
176
149
  } catch (cause) {
177
- throw schemaError("request", "query", context, { cause });
150
+ throw schemaError(method, void 0, meta, void 0, "query", void 0, cause);
178
151
  }
179
- if (result.issues) throw schemaError("request", "query", context, { issues: result.issues });
152
+ if (result.issues) throw schemaError(method, void 0, meta, void 0, "query", result.issues, void 0);
180
153
  query = result.value;
181
154
  }
182
155
  if (endpoint.headersSchema !== void 0) {
@@ -185,9 +158,9 @@ async function invoke(endpoint, transport, input) {
185
158
  result = endpoint.headersSchema["~standard"].validate(headers);
186
159
  if ("then" in result) result = await result;
187
160
  } catch (cause) {
188
- throw schemaError("request", "headers", context, { cause });
161
+ throw schemaError(method, void 0, meta, void 0, "headers", void 0, cause);
189
162
  }
190
- if (result.issues) throw schemaError("request", "headers", context, { issues: result.issues });
163
+ if (result.issues) throw schemaError(method, void 0, meta, void 0, "headers", result.issues, void 0);
191
164
  headers = result.value;
192
165
  }
193
166
  if (endpoint.body.schema !== void 0) {
@@ -196,9 +169,9 @@ async function invoke(endpoint, transport, input) {
196
169
  result = endpoint.body.schema["~standard"].validate(body);
197
170
  if ("then" in result) result = await result;
198
171
  } catch (cause) {
199
- throw schemaError("request", "body", context, { cause });
172
+ throw schemaError(method, void 0, meta, void 0, "body", void 0, cause);
200
173
  }
201
- if (result.issues) throw schemaError("request", "body", context, { issues: result.issues });
174
+ if (result.issues) throw schemaError(method, void 0, meta, void 0, "body", result.issues, void 0);
202
175
  body = result.value;
203
176
  }
204
177
  }
@@ -206,11 +179,7 @@ async function invoke(endpoint, transport, input) {
206
179
  try {
207
180
  url = appendQuery(unchecked && typeof path === "string" ? path : renderPath(endpoint.path, path), query);
208
181
  } catch (cause) {
209
- throw new ClientError({
210
- ...context,
211
- code: "request-url",
212
- cause
213
- });
182
+ throw new ClientError("request", "Request URL construction failed", method, void 0, meta, void 0, void 0, void 0, cause);
214
183
  }
215
184
  const bodyKind = unchecked ? input?.bodyKind ?? endpoint.body.kind : endpoint.body.kind;
216
185
  const responseKinds = selectResponseKinds(endpoint, expectedStatus, discard);
@@ -221,38 +190,22 @@ async function invoke(endpoint, transport, input) {
221
190
  bodyKind,
222
191
  body,
223
192
  responseKinds,
224
- meta: endpoint.meta,
193
+ meta,
225
194
  input
226
195
  };
227
196
  let handle;
228
197
  try {
229
198
  handle = await transport(transportRequest);
230
199
  } catch (failure) {
231
- context.url = failure instanceof TransportFailure ? failure.url : transportRequest.url;
232
- const attempt = failure instanceof TransportFailure ? failure.cause : failure;
233
- const cause = attempt instanceof FailureWithCleanupError ? attempt.cause : attempt;
234
- throw preserveCleanupError(cause instanceof RequestPreparationError ? new ClientError({
235
- ...context,
236
- code: "request-prepare",
237
- cause
238
- }) : new ClientError({
239
- ...context,
240
- code: "transport",
241
- cause
242
- }), attempt);
200
+ if (failure instanceof ClientError && failure.meta === meta) throw failure;
201
+ throw transportError(true, method, transportRequest.url, meta, failure);
243
202
  }
244
- context.url = handle.url;
203
+ const responseUrl = handle.url;
245
204
  const status = handle.status;
246
205
  const responseSpec = endpoint.responses[status];
247
206
  if (!(expectedStatus === void 0 ? responseSpec !== void 0 : typeof expectedStatus === "number" ? status === expectedStatus : expectedStatus.includes(status))) {
248
- const expectedStatuses = expectedStatus === void 0 ? Object.keys(endpoint.responses).map(Number) : typeof expectedStatus === "number" ? [expectedStatus] : expectedStatus;
249
- return rejectResponse(handle, new ClientError({
250
- ...context,
251
- code: "status",
252
- status,
253
- expectedStatuses,
254
- headers: handle.headers
255
- }));
207
+ const expected = expectedStatus === void 0 ? Object.keys(endpoint.responses).join(", ") : typeof expectedStatus === "number" ? expectedStatus : expectedStatus.join(", ");
208
+ return rejectResponse(handle, new ClientError("status", `Unexpected status ${status} (expected ${expected})`, method, responseUrl, meta, status, void 0, void 0, void 0));
256
209
  }
257
210
  let responseHeaders = handle.headers;
258
211
  if (responseSpec?.headersSchema) {
@@ -261,9 +214,9 @@ async function invoke(endpoint, transport, input) {
261
214
  result = responseSpec.headersSchema["~standard"].validate(responseHeaders);
262
215
  if ("then" in result) result = await result;
263
216
  } catch (cause) {
264
- return rejectResponse(handle, schemaError("response", "headers", context, { cause }, handle));
217
+ return rejectResponse(handle, schemaError(method, responseUrl, meta, status, "headers", void 0, cause));
265
218
  }
266
- if (result.issues) return rejectResponse(handle, schemaError("response", "headers", context, { issues: result.issues }, handle));
219
+ if (result.issues) return rejectResponse(handle, schemaError(method, responseUrl, meta, status, "headers", result.issues, void 0));
267
220
  responseHeaders = result.value;
268
221
  }
269
222
  const kind = discard || responseSpec === void 0 ? "none" : responseSpec.kind;
@@ -273,21 +226,8 @@ async function invoke(endpoint, transport, input) {
273
226
  } catch (failure) {
274
227
  const cause = failure instanceof FailureWithCleanupError ? failure.cause : failure;
275
228
  const cleanupFailed = cause instanceof ResponseCleanupError;
276
- const diagnostics = {
277
- ...context,
278
- status,
279
- headers: handle.headers
280
- };
281
- throw preserveCleanupError(kind === "none" || cleanupFailed ? new ClientError({
282
- ...diagnostics,
283
- code: "response-cleanup",
284
- cause: cleanupFailed ? cause.cause : cause
285
- }) : new ClientError({
286
- ...diagnostics,
287
- code: "response-decode",
288
- kind,
289
- cause
290
- }), failure);
229
+ const wrapped = kind === "none" || cleanupFailed ? new ClientError("transport", `Response cleanup failed (status ${status})`, method, responseUrl, meta, status, void 0, void 0, cleanupFailed ? cause.cause : cause) : new ClientError("response", `Cannot decode ${kind} response (status ${status})`, method, responseUrl, meta, status, void 0, void 0, cause);
230
+ throw preserveCleanupError(wrapped, failure);
291
231
  }
292
232
  if (!discard && responseSpec?.bodySchema !== void 0) {
293
233
  let result;
@@ -295,20 +235,20 @@ async function invoke(endpoint, transport, input) {
295
235
  result = responseSpec.bodySchema["~standard"].validate(responseBody);
296
236
  if ("then" in result) result = await result;
297
237
  } catch (cause) {
298
- return rejectResponse(handle, schemaError("response", "body", context, { cause }, handle), true);
238
+ return rejectResponse(handle, schemaError(method, responseUrl, meta, status, "body", void 0, cause), true);
299
239
  }
300
- if (result.issues) return rejectResponse(handle, schemaError("response", "body", context, { issues: result.issues }, handle), true);
240
+ if (result.issues) return rejectResponse(handle, schemaError(method, responseUrl, meta, status, "body", result.issues, void 0), true);
301
241
  responseBody = result.value;
302
242
  }
303
243
  if (handle.transport === void 0) return {
304
244
  status,
305
- url: handle.url,
245
+ url: responseUrl,
306
246
  headers: responseHeaders,
307
247
  body: responseBody
308
248
  };
309
249
  return {
310
250
  status,
311
- url: handle.url,
251
+ url: responseUrl,
312
252
  headers: responseHeaders,
313
253
  body: responseBody,
314
254
  transport: handle.transport
@@ -321,7 +261,11 @@ function bind(contract, transport) {
321
261
  if (typeof endpoint?.method === "string") return (input) => invoke(endpoint, adapter, input);
322
262
  const group = {};
323
263
  const entries = node;
324
- for (const key of Object.keys(entries)) group[key] = visit(entries[key]);
264
+ const keys = Object.keys(entries);
265
+ for (let i = 0; i < keys.length; i++) {
266
+ const key = keys[i];
267
+ group[key] = visit(entries[key]);
268
+ }
325
269
  return group;
326
270
  }
327
271
  return visit(contract);
@@ -329,13 +273,16 @@ function bind(contract, transport) {
329
273
  // src/index.ts
330
274
  const c = {
331
275
  /**
332
- * Use a full `:name` segment for a required path parameter.
276
+ * Declare an HTTP endpoint with its request and response types.
333
277
  *
334
278
  * @defaultValue GET with an optional JSON body.
335
279
  *
336
280
  * @remarks
337
- * Path values are URL-escaped.
338
- * With an empty or omitted response map, pass `status` on each call.
281
+ * Each `{name}` before `?` or `#` is a required path parameter. A
282
+ * parameter can be part of a segment, for example `/files/{name}.json`
283
+ * or `/jobs/{id}:cancel`. `{}` is literal text. The client escapes path
284
+ * values with `encodeURIComponent`. If there are no declared responses,
285
+ * pass `status` on each call.
339
286
  *
340
287
  * @example
341
288
  * ```ts
@@ -350,7 +297,8 @@ const c = {
350
297
  */
351
298
  endpoint,
352
299
  /**
353
- * Supply a type without runtime validation. A bare body hint uses JSON.
300
+ * Supply a type without runtime validation. As a body declaration, it
301
+ * selects JSON.
354
302
  *
355
303
  * @see {@link https://standardschema.dev/ | Standard Schema} for validation.
356
304
  */
@@ -359,7 +307,7 @@ const c = {
359
307
  * Bind an endpoint to get a callable function. Groups keep their keys.
360
308
  *
361
309
  * @remarks
362
- * Import an adapter from `/fetch`, `/playwright`, or `/k6`.
310
+ * Import a transport from `/fetch`, `/playwright`, or `/k6`.
363
311
  * See {@link Transport} to implement or wrap one.
364
312
  *
365
313
  * @example
package/dist/k6.d.ts CHANGED
@@ -1,25 +1,57 @@
1
- import { _ as Transport, c as MultipartFile, f as RequestKindMap, i as Fields, m as ResponseKindMap, r as FieldScalar } from "./types-Cq8XAc1z.js";
1
+ import { _ as Transport, a as Fields, c as MultipartFile, f as RequestKindMap, i as FieldScalar, m as ResponseKindMap, n as CommonOptions } from "./types-XCe4DTv4.js";
2
2
  import { FileData, Params, Response } from "k6/http";
3
3
  interface K6RequestKinds extends Omit<RequestKindMap, "multipart"> {
4
4
  readonly multipart: Fields<FieldScalar | MultipartFile | FileData>;
5
5
  }
6
6
  type K6Http = Pick<typeof import("k6/http"), "asyncRequest" | "file">;
7
+ /** A cookie that k6 parsed from `Set-Cookie`, with the k6 field names. */
8
+ interface K6Cookie {
9
+ readonly name: string;
10
+ readonly value: string;
11
+ readonly domain: string;
12
+ readonly path: string;
13
+ readonly http_only: boolean;
14
+ readonly secure: boolean;
15
+ readonly max_age: number;
16
+ readonly expires: number;
17
+ }
18
+ /**
19
+ * The k6 response as k6 gives it. `@types/k6` names two cookie fields
20
+ * `httpOnly` and `maxAge`, and its `tls_cipher_suite` type has no `""`.
21
+ */
22
+ type K6Response = Omit<Response, "cookies" | "tls_cipher_suite"> & {
23
+ readonly cookies: Readonly<Record<string, readonly K6Cookie[]>>;
24
+ readonly tls_cipher_suite: Response["tls_cipher_suite"] | "";
25
+ };
7
26
  interface K6ResponseMetadata {
8
- readonly timings: Response["timings"];
9
- readonly proto: Response["proto"];
10
- readonly remote_ip: Response["remote_ip"];
11
- readonly error: Response["error"];
12
- readonly error_code: Response["error_code"];
27
+ /** Parsed `Set-Cookie` values by cookie name. */
28
+ readonly cookies: K6Response["cookies"];
29
+ readonly timings: K6Response["timings"];
30
+ readonly proto: K6Response["proto"];
31
+ readonly remote_ip: K6Response["remote_ip"];
32
+ readonly remote_port: K6Response["remote_port"];
33
+ /** The TLS version, or `""` if the connection does not use TLS. */
34
+ readonly tls_version: K6Response["tls_version"];
35
+ /** The TLS cipher suite, or `""` if the connection does not use TLS. */
36
+ readonly tls_cipher_suite: K6Response["tls_cipher_suite"];
37
+ readonly error: K6Response["error"];
38
+ readonly error_code: K6Response["error_code"];
13
39
  }
14
- declare const NATIVE_OPTION_KEYS: readonly ["cookies", "timeout", "redirects", "auth", "compression", "tags", "jar", "responseCallback"];
15
- type K6NativeOptions = Pick<Params, (typeof NATIVE_OPTION_KEYS)[number]>;
40
+ type K6NativeOptions = CommonOptions & {
41
+ /**
42
+ * Passed to k6 as params. `redirects` here overrides `follow`.
43
+ * `timeout` here overrides `timeout`.
44
+ */
45
+ readonly transport?: Omit<Params, "headers" | "responseType">;
46
+ };
16
47
  /**
17
- * Capture response bodies according to the expected response kinds.
48
+ * Send requests with `k6/http`.
18
49
  *
19
50
  * @remarks
20
- * Use k6 2.2 or later and add `@types/k6` for TypeScript. Bundle npm
21
- * imports for k6. Multipart fields accept `http.file()` values. Use a
22
- * single value per request header.
51
+ * Use k6 2.2 or later and add `@types/k6` for TypeScript. k6 does not
52
+ * load npm packages directly. Bundle the script first. The transport
53
+ * captures response bodies only for the expected response kinds.
54
+ * Multipart fields accept `http.file()` values.
23
55
  *
24
56
  * @example
25
57
  * ```ts
@@ -30,7 +62,7 @@ type K6NativeOptions = Pick<Params, (typeof NATIVE_OPTION_KEYS)[number]>;
30
62
  * const health = c.bind(c.endpoint("/health"), transport);
31
63
  *
32
64
  * export default async function () {
33
- * await health({ status: 204, tags: { name: "health" } });
65
+ * await health({ status: 204, transport: { tags: { name: "health" } } });
34
66
  * }
35
67
  * ```
36
68
  *
package/dist/k6.js CHANGED
@@ -1,17 +1,11 @@
1
- import { a as TransportFailure, l as encodeFields, r as RequestPreparationError, s as createUrlResolver, u as forEachField } from "./errors-D1bIeOq9.js";
2
- import { i as encodeUtf8, l as binaryView, n as decodeUrlEncoded, r as decodeUtf8, s as prepareHeaders, t as decodeMultipart, u as encodeJson } from "./codec-BWlr5T5u.js";
1
+ import { a as transportError, l as encodeFields, s as createUrlResolver, u as forEachField } from "./errors-Dcje8BxZ.js";
2
+ import { c as encodeJson, i as encodeUtf8, n as decodeUrlEncoded, o as prepareHeaders, r as decodeUtf8, t as decodeMultipart } from "./codec-DpNVlh9j.js";
3
3
  import http from "k6/http";
4
4
  // src/transports/k6.ts
5
- const NATIVE_OPTION_KEYS = [
6
- "cookies",
7
- "timeout",
8
- "redirects",
9
- "auth",
10
- "compression",
11
- "tags",
12
- "jar",
13
- "responseCallback"
14
- ];
5
+ function binaryView(input) {
6
+ if (input instanceof Uint8Array) return input;
7
+ return input instanceof ArrayBuffer ? new Uint8Array(input) : new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
8
+ }
15
9
  function toK6ArrayBuffer(data) {
16
10
  if (data instanceof ArrayBuffer) return data;
17
11
  const bytes = binaryView(data);
@@ -51,14 +45,16 @@ function manualMultipart() {
51
45
  };
52
46
  const encodedChunks = [];
53
47
  let length = 0;
54
- for (const chunk of chunks) {
48
+ for (let i = 0; i < chunks.length; i++) {
49
+ const chunk = chunks[i];
55
50
  const bytes = typeof chunk === "string" ? encodeUtf8(chunk) : chunk;
56
51
  encodedChunks.push(bytes);
57
52
  length += bytes.byteLength;
58
53
  }
59
54
  const encoded = new Uint8Array(length);
60
55
  let offset = 0;
61
- for (const chunk of encodedChunks) {
56
+ for (let i = 0; i < encodedChunks.length; i++) {
57
+ const chunk = encodedChunks[i];
62
58
  encoded.set(chunk, offset);
63
59
  offset += chunk.length;
64
60
  }
@@ -83,7 +79,10 @@ function k6Multipart(body, httpApi, forceManual) {
83
79
  if (typeof part !== "string") containsFile = true;
84
80
  if (manualEncoder === void 0 && nativeParts[name] !== void 0) {
85
81
  manualEncoder = manualMultipart();
86
- for (const priorName of fieldNames) manualEncoder.append(priorName, nativeParts[priorName]);
82
+ for (let i = 0; i < fieldNames.length; i++) {
83
+ const priorName = fieldNames[i];
84
+ manualEncoder.append(priorName, nativeParts[priorName]);
85
+ }
87
86
  }
88
87
  if (manualEncoder !== void 0) manualEncoder.append(name, part);
89
88
  else {
@@ -93,10 +92,14 @@ function k6Multipart(body, httpApi, forceManual) {
93
92
  });
94
93
  if (manualEncoder === void 0 && !containsFile) {
95
94
  manualEncoder = manualMultipart();
96
- for (const name of fieldNames) manualEncoder.append(name, nativeParts[name]);
95
+ for (let i = 0; i < fieldNames.length; i++) {
96
+ const name = fieldNames[i];
97
+ manualEncoder.append(name, nativeParts[name]);
98
+ }
97
99
  }
98
100
  if (manualEncoder !== void 0) return manualEncoder.finish();
99
- for (const name of fieldNames) {
101
+ for (let i = 0; i < fieldNames.length; i++) {
102
+ const name = fieldNames[i];
100
103
  const part = nativeParts[name];
101
104
  if (typeof part === "object" && !("content_type" in part || typeof part.data === "string")) nativeParts[name] = httpApi.file(toK6ArrayBuffer(part.data), part.filename ?? "blob", part.mediaType ?? "application/octet-stream");
102
105
  }
@@ -112,7 +115,10 @@ function normalizeHeaders(source) {
112
115
  else {
113
116
  const combined = typeof previous === "string" ? [previous] : [...previous];
114
117
  if (typeof value === "string") combined.push(value);
115
- else for (const part of value) combined.push(part);
118
+ else for (let i = 0; i < value.length; i++) {
119
+ const part = value[i];
120
+ combined.push(part);
121
+ }
116
122
  target[key] = combined;
117
123
  }
118
124
  }
@@ -130,8 +136,12 @@ var K6ResponseHandle = class {
130
136
  this.status = native.status;
131
137
  this.url = native.url;
132
138
  this.headers = normalizeHeaders(native.headers);
139
+ const nativeCookies = native.cookies;
140
+ const cookies = Object.create(null);
141
+ for (const name in nativeCookies) cookies[name] = nativeCookies[name];
133
142
  const timings = native.timings;
134
143
  this.transport = {
144
+ cookies,
135
145
  timings: {
136
146
  blocked: timings.blocked,
137
147
  connecting: timings.connecting,
@@ -143,6 +153,9 @@ var K6ResponseHandle = class {
143
153
  },
144
154
  proto: native.proto,
145
155
  remote_ip: native.remote_ip,
156
+ remote_port: native.remote_port,
157
+ tls_version: native.tls_version,
158
+ tls_cipher_suite: native.tls_cipher_suite,
146
159
  error: native.error,
147
160
  error_code: native.error_code
148
161
  };
@@ -153,25 +166,26 @@ var K6ResponseHandle = class {
153
166
  if (kind === "none") return;
154
167
  if (kind === "json") return this.native.json();
155
168
  const captured = this.native.body;
156
- if (captured === null) throw new TypeError("k6 discarded response body");
169
+ if (captured === null) throw new TypeError("k6 discarded the response body");
157
170
  if (kind === "binary" || kind === "multipart") {
158
- if (!(captured instanceof ArrayBuffer)) throw new TypeError("k6 did not capture binary body");
171
+ if (!(captured instanceof ArrayBuffer)) throw new TypeError("k6 did not capture the binary response body");
159
172
  const bytes = new Uint8Array(captured);
160
173
  return kind === "binary" ? bytes : decodeMultipart(bytes, this.headers["content-type"]);
161
174
  }
162
175
  const text = typeof captured === "string" ? captured : decodeUtf8(captured);
163
176
  if (kind === "text") return text;
164
177
  if (kind === "urlencoded") return decodeUrlEncoded(text);
165
- throw new TypeError(`Unsupported k6 response kind: ${String(kind)}`);
178
+ throw new TypeError(`Unsupported response kind: ${String(kind)}`);
166
179
  }
167
180
  };
168
181
  /**
169
- * Capture response bodies according to the expected response kinds.
182
+ * Send requests with `k6/http`.
170
183
  *
171
184
  * @remarks
172
- * Use k6 2.2 or later and add `@types/k6` for TypeScript. Bundle npm
173
- * imports for k6. Multipart fields accept `http.file()` values. Use a
174
- * single value per request header.
185
+ * Use k6 2.2 or later and add `@types/k6` for TypeScript. k6 does not
186
+ * load npm packages directly. Bundle the script first. The transport
187
+ * captures response bodies only for the expected response kinds.
188
+ * Multipart fields accept `http.file()` values.
175
189
  *
176
190
  * @example
177
191
  * ```ts
@@ -182,7 +196,7 @@ var K6ResponseHandle = class {
182
196
  * const health = c.bind(c.endpoint("/health"), transport);
183
197
  *
184
198
  * export default async function () {
185
- * await health({ status: 204, tags: { name: "health" } });
199
+ * await health({ status: 204, transport: { tags: { name: "health" } } });
186
200
  * }
187
201
  * ```
188
202
  *
@@ -193,65 +207,58 @@ function k6Transport(config = {}) {
193
207
  const resolveUrl = createUrlResolver(config.baseUrl);
194
208
  return async (request) => {
195
209
  const url = resolveUrl(request.url);
210
+ let prepared = false;
196
211
  try {
197
- let contentTypeSuppressed = false;
198
- const selectedHeaders = request.headers === void 0 && request.body === void 0 ? void 0 : prepareHeaders(request.headers, request.bodyKind, request.body !== void 0, (suppressed) => {
199
- contentTypeSuppressed = suppressed;
200
- });
212
+ const input = request.input;
213
+ const selected = request.headers === void 0 && request.body === void 0 ? void 0 : prepareHeaders(request.headers, request.bodyKind, request.body !== void 0, input?.unchecked === true);
214
+ const contentTypeSuppressed = selected?.contentTypeSuppressed === true;
201
215
  let body = null;
202
- try {
203
- if (request.body !== void 0) switch (request.bodyKind) {
204
- case "none": throw new RequestPreparationError("none request body kind cannot have a body");
205
- case "json":
206
- body = encodeJson(request.body);
207
- break;
208
- case "text":
209
- body = request.body;
210
- break;
211
- case "binary":
212
- body = request.body instanceof ArrayBuffer ? request.body : binaryView(request.body);
213
- break;
214
- case "urlencoded":
215
- body = encodeFields(request.body);
216
- break;
217
- case "multipart": {
218
- const multipart = k6Multipart(request.body, httpApi, contentTypeSuppressed);
219
- body = multipart.body;
220
- if (selectedHeaders !== void 0 && !contentTypeSuppressed) {
221
- const supplied = selectedHeaders["content-type"];
222
- if (supplied === void 0 || request.input?.unchecked !== true) {
223
- if (multipart.contentType !== void 0) selectedHeaders["content-type"] = multipart.contentType;
224
- else if (supplied !== void 0) delete selectedHeaders["content-type"];
225
- }
226
- }
227
- break;
228
- }
229
- default: throw new RequestPreparationError(`Unsupported k6 body kind: ${String(request.bodyKind)}`);
216
+ if (request.body !== void 0) switch (request.bodyKind) {
217
+ case "none": throw new TypeError("Request body kind none does not allow a body");
218
+ case "json":
219
+ body = encodeJson(request.body);
220
+ break;
221
+ case "text":
222
+ body = request.body;
223
+ break;
224
+ case "binary":
225
+ body = request.body instanceof ArrayBuffer ? request.body : binaryView(request.body);
226
+ break;
227
+ case "urlencoded":
228
+ body = encodeFields(request.body);
229
+ break;
230
+ case "multipart": {
231
+ const multipart = k6Multipart(request.body, httpApi, contentTypeSuppressed);
232
+ body = multipart.body;
233
+ if (selected !== void 0 && selected.contentType === void 0 && !contentTypeSuppressed && multipart.contentType !== void 0) selected.fields["content-type"] = multipart.contentType;
234
+ break;
230
235
  }
231
- } catch (cause) {
232
- if (cause instanceof RequestPreparationError) throw cause;
233
- throw new RequestPreparationError("Failed to prepare k6 request", { cause });
234
- }
235
- if (selectedHeaders !== void 0) {
236
- for (const name in selectedHeaders) if (typeof selectedHeaders[name] !== "string") throw new RequestPreparationError(`k6 cannot preserve repeated request header: ${name}`);
236
+ default: throw new TypeError(`Unsupported request body kind: ${String(request.bodyKind)}`);
237
237
  }
238
238
  let responseType = "none";
239
- for (const kind of request.responseKinds) {
239
+ const kinds = request.responseKinds;
240
+ for (let i = 0; i < kinds.length; i++) {
241
+ const kind = kinds[i];
240
242
  if (kind === "binary" || kind === "multipart") {
241
243
  responseType = "binary";
242
244
  break;
243
245
  }
244
246
  if (kind !== "none") responseType = "text";
245
247
  }
246
- const params = { responseType };
247
- if (selectedHeaders !== void 0) params.headers = selectedHeaders;
248
- if (request.input != null) for (const key of NATIVE_OPTION_KEYS) {
249
- const value = request.input[key];
250
- if (value !== void 0) params[key] = value;
251
- }
248
+ const native = input?.transport;
249
+ const params = native === void 0 ? { responseType } : {
250
+ ...native,
251
+ headers: void 0,
252
+ responseType
253
+ };
254
+ const timeout = input?.timeout;
255
+ if (timeout !== void 0 && params.timeout === void 0) params.timeout = timeout;
256
+ if (input?.follow !== true && (native === void 0 || params.redirects === void 0)) params.redirects = 0;
257
+ if (selected !== void 0) params.headers = selected.fields;
258
+ prepared = true;
252
259
  return new K6ResponseHandle(await httpApi.asyncRequest(request.method, url, body, params));
253
- } catch (cause) {
254
- throw new TransportFailure(url, cause);
260
+ } catch (failure) {
261
+ throw transportError(prepared, request.method, url, request.meta, failure);
255
262
  }
256
263
  };
257
264
  }