@dlenroc/typed-client 0.1.0 → 0.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.
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-25xWqgvt.js";
2
+ import { c as encodeJson, i as encodeUtf8, n as decodeUrlEncoded, o as prepareHeaders, r as decodeUtf8, t as decodeMultipart } from "./codec-CaVxvHce.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
  }
@@ -1,19 +1,30 @@
1
- import { _ as Transport, f as RequestKindMap, m as ResponseKindMap } from "./types-Cq8XAc1z.js";
2
- import { APIRequestContext } from "playwright-core";
1
+ import { _ as Transport, f as RequestKindMap, m as ResponseKindMap, n as CommonOptions } from "./types-XCe4DTv4.js";
2
+ import { APIRequestContext, APIResponse } from "playwright-core";
3
3
  interface PlaywrightMetadata {
4
- readonly statusText: string;
4
+ readonly timing: ReturnType<APIResponse["timing"]>;
5
+ /**
6
+ * The server IP address and port, or `null` if Playwright does not know
7
+ * them.
8
+ */
9
+ readonly serverAddr: Awaited<ReturnType<APIResponse["serverAddr"]>>;
10
+ /**
11
+ * The TLS certificate and protocol, or `null` for a response that is not
12
+ * HTTPS.
13
+ */
14
+ readonly securityDetails: Awaited<ReturnType<APIResponse["securityDetails"]>>;
5
15
  }
6
16
  type PlaywrightContext = Pick<APIRequestContext, "fetch">;
7
17
  type PlaywrightFetchOptions = NonNullable<Parameters<APIRequestContext["fetch"]>[1]>;
8
- declare const NATIVE_OPTION_KEYS: readonly ["timeout", "maxRedirects", "maxRetries", "ignoreHTTPSErrors", "signal"];
9
- type PlaywrightNativeOptions = Pick<PlaywrightFetchOptions, (typeof NATIVE_OPTION_KEYS)[number]>;
18
+ type PlaywrightNativeOptions = CommonOptions & {
19
+ /** Passed to `fetch`. `maxRedirects` here overrides `follow`. */
20
+ readonly transport?: Pick<PlaywrightFetchOptions, "maxRedirects" | "maxRetries" | "ignoreHTTPSErrors" | "signal">;
21
+ };
10
22
  /**
11
- * Disposes each response after reading or discarding it.
23
+ * Send requests with Playwright and dispose each response after use.
12
24
  *
13
25
  * @remarks
14
- * Use Playwright 1.62 or later. Pass the test's `request` fixture or
15
- * create one with `request.newContext()`. Use a single value per
16
- * request header and keep Content-Type enabled when sending a body.
26
+ * Use Playwright 1.62 or later. Do not set `content-type: null` on a
27
+ * request with a body.
17
28
  *
18
29
  * @example
19
30
  * ```ts
@@ -37,7 +48,10 @@ type PlaywrightNativeOptions = Pick<PlaywrightFetchOptions, (typeof NATIVE_OPTIO
37
48
  * @see {@link https://playwright.dev/docs/api-testing | API testing}
38
49
  */
39
50
  export declare function playwrightTransport(config: {
40
- /** Dispose contexts you create. */
51
+ /**
52
+ * The `request` fixture or a context from `request.newContext()`.
53
+ * Dispose contexts you create.
54
+ */
41
55
  readonly context: PlaywrightContext;
42
56
  /** Relative endpoints append to this URL's path. */
43
57
  readonly baseUrl?: string;
@@ -1,14 +1,7 @@
1
- import { a as TransportFailure, i as ResponseCleanupError, l as encodeFields, n as FailureWithCleanupError, r as RequestPreparationError, s as createUrlResolver } from "./errors-D1bIeOq9.js";
2
- import { a as appendResponseHeader, c as asFormData, n as decodeUrlEncoded, s as prepareHeaders, t as decodeMultipart, u as encodeJson } from "./codec-BWlr5T5u.js";
1
+ import { a as transportError, l as encodeFields, n as FailureWithCleanupError, r as ResponseCleanupError, s as createUrlResolver } from "./errors-25xWqgvt.js";
2
+ import { a as appendResponseHeader, c as encodeJson, n as decodeUrlEncoded, o as prepareHeaders, s as asFormData, t as decodeMultipart } from "./codec-CaVxvHce.js";
3
3
  import { Buffer } from "node:buffer";
4
4
  // src/transports/playwright.ts
5
- const NATIVE_OPTION_KEYS = [
6
- "timeout",
7
- "maxRedirects",
8
- "maxRetries",
9
- "ignoreHTTPSErrors",
10
- "signal"
11
- ];
12
5
  async function disposeAfterFailure(response, cause) {
13
6
  try {
14
7
  await response.dispose();
@@ -24,18 +17,27 @@ var PlaywrightResponseHandle = class PlaywrightResponseHandle {
24
17
  headers;
25
18
  transport;
26
19
  consumed = false;
27
- constructor(native, headers) {
20
+ constructor(native, headers, transport) {
28
21
  this.native = native;
29
22
  this.headers = headers;
30
23
  this.status = native.status();
31
24
  this.url = native.url();
32
- this.transport = { statusText: native.statusText() };
25
+ this.transport = transport;
33
26
  }
34
27
  static async create(native) {
35
28
  try {
36
29
  const headers = Object.create(null);
37
- for (const { name, value } of native.headersArray()) appendResponseHeader(headers, name, value);
38
- return new PlaywrightResponseHandle(native, headers);
30
+ const entries = native.headersArray();
31
+ for (let i = 0; i < entries.length; i++) {
32
+ const entry = entries[i];
33
+ appendResponseHeader(headers, entry.name, entry.value);
34
+ }
35
+ const transport = {
36
+ timing: native.timing(),
37
+ serverAddr: await native.serverAddr(),
38
+ securityDetails: await native.securityDetails()
39
+ };
40
+ return new PlaywrightResponseHandle(native, headers, transport);
39
41
  } catch (cause) {
40
42
  return disposeAfterFailure(native, cause);
41
43
  }
@@ -53,7 +55,7 @@ var PlaywrightResponseHandle = class PlaywrightResponseHandle {
53
55
  else if (kind === "multipart") {
54
56
  const bytes = await this.native.body();
55
57
  result = decodeMultipart(bytes, this.headers["content-type"]);
56
- } else throw new TypeError(`Unsupported Playwright response kind: ${String(kind)}`);
58
+ } else throw new TypeError(`Unsupported response kind: ${String(kind)}`);
57
59
  } catch (cause) {
58
60
  return disposeAfterFailure(this.native, cause);
59
61
  }
@@ -90,12 +92,11 @@ function playwrightMultipart(fields) {
90
92
  return result;
91
93
  }
92
94
  /**
93
- * Disposes each response after reading or discarding it.
95
+ * Send requests with Playwright and dispose each response after use.
94
96
  *
95
97
  * @remarks
96
- * Use Playwright 1.62 or later. Pass the test's `request` fixture or
97
- * create one with `request.newContext()`. Use a single value per
98
- * request header and keep Content-Type enabled when sending a body.
98
+ * Use Playwright 1.62 or later. Do not set `content-type: null` on a
99
+ * request with a body.
99
100
  *
100
101
  * @example
101
102
  * ```ts
@@ -122,56 +123,54 @@ function playwrightTransport(config) {
122
123
  const resolveUrl = createUrlResolver(config.baseUrl);
123
124
  return async (request) => {
124
125
  const url = resolveUrl(request.url);
126
+ let prepared = false;
125
127
  try {
128
+ const input = request.input;
129
+ const native = input?.transport;
126
130
  const options = {
131
+ ...native,
127
132
  method: request.method,
128
133
  failOnStatusCode: false
129
134
  };
130
- try {
131
- const body = request.body;
132
- if (body !== void 0) switch (request.bodyKind) {
133
- case "none": throw new RequestPreparationError("none request body kind cannot have a body");
134
- case "json":
135
- options.data = encodeJson(body);
136
- break;
137
- case "text":
138
- options.data = body;
139
- break;
140
- case "binary":
141
- options.data = asBuffer(body);
142
- break;
143
- case "urlencoded":
144
- options.data = encodeFields(body);
145
- break;
146
- case "multipart":
147
- options.multipart = playwrightMultipart(body);
148
- break;
149
- default: throw new RequestPreparationError(`Unsupported Playwright body kind: ${String(request.bodyKind)}`);
150
- }
151
- } catch (cause) {
152
- if (cause instanceof RequestPreparationError) throw cause;
153
- throw new RequestPreparationError("Failed to serialize Playwright request", { cause });
135
+ if (native !== void 0) {
136
+ delete options.headers;
137
+ delete options.data;
138
+ delete options.form;
139
+ delete options.multipart;
140
+ delete options.params;
154
141
  }
155
- if (request.headers !== void 0 || request.body !== void 0) {
156
- let suppressContentType = false;
157
- const preparedHeaders = prepareHeaders(request.headers, request.bodyKind, request.body !== void 0, (suppressed) => {
158
- suppressContentType = suppressed;
159
- });
160
- if (suppressContentType && request.body !== void 0) throw new RequestPreparationError("Playwright cannot suppress Content-Type for a request with a body");
161
- if (options.multipart !== void 0 && request.input?.unchecked !== true) delete preparedHeaders["content-type"];
162
- for (const name in preparedHeaders) if (typeof preparedHeaders[name] !== "string") throw new RequestPreparationError(`Playwright cannot preserve repeated request header: ${name}`);
163
- const contentType = preparedHeaders["content-type"];
164
- if (request.bodyKind !== "json" && typeof options.data === "string" && typeof contentType === "string" && contentType.split(";", 1)[0].trim().toLowerCase() === "application/json") options.data = Buffer.from(options.data);
165
- options.headers = preparedHeaders;
142
+ const body = request.body;
143
+ if (body !== void 0) switch (request.bodyKind) {
144
+ case "none": throw new TypeError("Request body kind none does not allow a body");
145
+ case "json":
146
+ options.data = Buffer.from(encodeJson(body));
147
+ break;
148
+ case "text":
149
+ options.data = Buffer.from(body);
150
+ break;
151
+ case "binary":
152
+ options.data = asBuffer(body);
153
+ break;
154
+ case "urlencoded":
155
+ options.data = Buffer.from(encodeFields(body));
156
+ break;
157
+ case "multipart":
158
+ options.multipart = playwrightMultipart(body);
159
+ break;
160
+ default: throw new TypeError(`Unsupported request body kind: ${String(request.bodyKind)}`);
166
161
  }
167
- for (const key of NATIVE_OPTION_KEYS) {
168
- const value = request.input?.[key];
169
- if (value !== void 0) options[key] = value;
162
+ if (request.headers !== void 0 || request.body !== void 0) {
163
+ const selected = prepareHeaders(request.headers, request.bodyKind, request.body !== void 0, input?.unchecked === true);
164
+ if (selected.contentTypeSuppressed && request.body !== void 0) throw new TypeError("Playwright cannot suppress Content-Type for a request with a body");
165
+ options.headers = selected.fields;
170
166
  }
167
+ if (options.maxRedirects === void 0 && input?.follow !== true) options.maxRedirects = 0;
168
+ if (input?.timeout !== void 0) options.timeout = input.timeout;
169
+ prepared = true;
171
170
  const response = await config.context.fetch(url, options);
172
171
  return await PlaywrightResponseHandle.create(response);
173
- } catch (cause) {
174
- throw new TransportFailure(url, cause);
172
+ } catch (failure) {
173
+ throw transportError(prepared, request.method, url, request.meta, failure);
175
174
  }
176
175
  };
177
176
  }