wreq-js 2.2.2 → 2.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/wreq-js.js CHANGED
@@ -1,2726 +1,2186 @@
1
- // src/wreq-js.ts
2
- import { randomUUID } from "crypto";
3
- import { STATUS_CODES } from "http";
4
- import { createRequire } from "module";
5
- import { Readable } from "stream";
6
- import { ReadableStream } from "stream/web";
7
-
8
- // src/types.ts
1
+ import { createRequire } from "node:module";
2
+ import { randomUUID } from "node:crypto";
3
+ import { STATUS_CODES } from "node:http";
4
+ import { Readable } from "node:stream";
5
+ import { ReadableStream } from "node:stream/web";
6
+ //#region src/native-require.ts
7
+ const nativeRequire = createRequire(import.meta.url);
8
+ //#endregion
9
+ //#region src/types.ts
10
+ /**
11
+ * Error thrown when a request fails. This can occur due to network errors,
12
+ * timeouts, invalid URLs, or other request-related issues.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * try {
17
+ * const response = await fetch('https://api.example.com');
18
+ * } catch (error) {
19
+ * if (error instanceof RequestError) {
20
+ * console.error('Request failed:', error.message);
21
+ * }
22
+ * }
23
+ * ```
24
+ */
9
25
  var RequestError = class extends TypeError {
10
- constructor(message) {
11
- super(message);
12
- this.name = "RequestError";
13
- }
26
+ constructor(message) {
27
+ super(message);
28
+ this.name = "RequestError";
29
+ }
14
30
  };
15
-
16
- // src/wreq-js.ts
17
- var nativeBinding;
18
- var cachedProfiles;
19
- var cachedProfileSet;
20
- var cachedOperatingSystems;
21
- var cachedOperatingSystemSet;
31
+ //#endregion
32
+ //#region src/wreq-js.ts
33
+ let nativeBinding;
34
+ let cachedProfiles;
35
+ let cachedProfileSet;
36
+ let cachedOperatingSystems;
37
+ let cachedOperatingSystemSet;
22
38
  function detectLibc() {
23
- if (process.platform !== "linux") {
24
- return void 0;
25
- }
26
- const envLibc = process.env.LIBC ?? process.env.npm_config_libc;
27
- if (envLibc) {
28
- return envLibc.toLowerCase().includes("musl") ? "musl" : "gnu";
29
- }
30
- try {
31
- const report = process.report?.getReport?.();
32
- const glibcVersion = report?.header?.glibcVersionRuntime;
33
- if (glibcVersion) {
34
- return "gnu";
35
- }
36
- return "musl";
37
- } catch {
38
- return "gnu";
39
- }
40
- }
41
- var require2 = typeof import.meta !== "undefined" && import.meta.url ? createRequire(import.meta.url) : createRequire(__filename);
39
+ if (process.platform !== "linux") return;
40
+ const envLibc = process.env.LIBC ?? process.env.npm_config_libc;
41
+ if (envLibc) return envLibc.toLowerCase().includes("musl") ? "musl" : "gnu";
42
+ try {
43
+ if ((process.report?.getReport?.())?.header?.glibcVersionRuntime) return "gnu";
44
+ return "musl";
45
+ } catch {
46
+ return "gnu";
47
+ }
48
+ }
42
49
  function loadNativeBinding() {
43
- const platform = process.platform;
44
- const arch = process.arch;
45
- const libc = detectLibc();
46
- if (platform === "darwin" && arch === "x64") {
47
- try {
48
- return require2("../rust/wreq-js.darwin-x64.node");
49
- } catch {
50
- try {
51
- return require2("../rust/wreq-js.node");
52
- } catch {
53
- throw new Error(
54
- "Failed to load native module for darwin-x64. Tried: ../rust/wreq-js.darwin-x64.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform."
55
- );
56
- }
57
- }
58
- }
59
- if (platform === "darwin" && arch === "arm64") {
60
- try {
61
- return require2("../rust/wreq-js.darwin-arm64.node");
62
- } catch {
63
- try {
64
- return require2("../rust/wreq-js.node");
65
- } catch {
66
- throw new Error(
67
- "Failed to load native module for darwin-arm64. Tried: ../rust/wreq-js.darwin-arm64.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform."
68
- );
69
- }
70
- }
71
- }
72
- if (platform === "linux" && arch === "x64") {
73
- if (libc === "musl") {
74
- try {
75
- return require2("../rust/wreq-js.linux-x64-musl.node");
76
- } catch {
77
- try {
78
- return require2("../rust/wreq-js.node");
79
- } catch {
80
- throw new Error(
81
- "Failed to load native module for linux-x64-musl. Tried: ../rust/wreq-js.linux-x64-musl.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform."
82
- );
83
- }
84
- }
85
- }
86
- try {
87
- return require2("../rust/wreq-js.linux-x64-gnu.node");
88
- } catch {
89
- try {
90
- return require2("../rust/wreq-js.node");
91
- } catch {
92
- throw new Error(
93
- "Failed to load native module for linux-x64-gnu. Tried: ../rust/wreq-js.linux-x64-gnu.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform."
94
- );
95
- }
96
- }
97
- }
98
- if (platform === "linux" && arch === "arm64") {
99
- try {
100
- return require2("../rust/wreq-js.linux-arm64-gnu.node");
101
- } catch {
102
- try {
103
- return require2("../rust/wreq-js.node");
104
- } catch {
105
- throw new Error(
106
- "Failed to load native module for linux-arm64-gnu. Tried: ../rust/wreq-js.linux-arm64-gnu.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform."
107
- );
108
- }
109
- }
110
- }
111
- if (platform === "win32" && arch === "x64") {
112
- try {
113
- return require2("../rust/wreq-js.win32-x64-msvc.node");
114
- } catch {
115
- try {
116
- return require2("../rust/wreq-js.node");
117
- } catch {
118
- throw new Error(
119
- "Failed to load native module for win32-x64-msvc. Tried: ../rust/wreq-js.win32-x64-msvc.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform."
120
- );
121
- }
122
- }
123
- }
124
- throw new Error(
125
- `Unsupported platform: ${platform}-${arch}${libc ? `-${libc}` : ""}. Supported platforms: darwin-x64, darwin-arm64, linux-x64-gnu, linux-x64-musl, linux-arm64-gnu, win32-x64-msvc`
126
- );
50
+ const platform = process.platform;
51
+ const arch = process.arch;
52
+ const libc = detectLibc();
53
+ if (platform === "darwin" && arch === "x64") try {
54
+ return nativeRequire("../rust/wreq-js.darwin-x64.node");
55
+ } catch {
56
+ try {
57
+ return nativeRequire("../rust/wreq-js.node");
58
+ } catch {
59
+ throw new Error("Failed to load native module for darwin-x64. Tried: ../rust/wreq-js.darwin-x64.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
60
+ }
61
+ }
62
+ if (platform === "darwin" && arch === "arm64") try {
63
+ return nativeRequire("../rust/wreq-js.darwin-arm64.node");
64
+ } catch {
65
+ try {
66
+ return nativeRequire("../rust/wreq-js.node");
67
+ } catch {
68
+ throw new Error("Failed to load native module for darwin-arm64. Tried: ../rust/wreq-js.darwin-arm64.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
69
+ }
70
+ }
71
+ if (platform === "linux" && arch === "x64") {
72
+ if (libc === "musl") try {
73
+ return nativeRequire("../rust/wreq-js.linux-x64-musl.node");
74
+ } catch {
75
+ try {
76
+ return nativeRequire("../rust/wreq-js.node");
77
+ } catch {
78
+ throw new Error("Failed to load native module for linux-x64-musl. Tried: ../rust/wreq-js.linux-x64-musl.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
79
+ }
80
+ }
81
+ try {
82
+ return nativeRequire("../rust/wreq-js.linux-x64-gnu.node");
83
+ } catch {
84
+ try {
85
+ return nativeRequire("../rust/wreq-js.node");
86
+ } catch {
87
+ throw new Error("Failed to load native module for linux-x64-gnu. Tried: ../rust/wreq-js.linux-x64-gnu.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
88
+ }
89
+ }
90
+ }
91
+ if (platform === "linux" && arch === "arm64") try {
92
+ return nativeRequire("../rust/wreq-js.linux-arm64-gnu.node");
93
+ } catch {
94
+ try {
95
+ return nativeRequire("../rust/wreq-js.node");
96
+ } catch {
97
+ throw new Error("Failed to load native module for linux-arm64-gnu. Tried: ../rust/wreq-js.linux-arm64-gnu.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
98
+ }
99
+ }
100
+ if (platform === "win32" && arch === "x64") try {
101
+ return nativeRequire("../rust/wreq-js.win32-x64-msvc.node");
102
+ } catch {
103
+ try {
104
+ return nativeRequire("../rust/wreq-js.node");
105
+ } catch {
106
+ throw new Error("Failed to load native module for win32-x64-msvc. Tried: ../rust/wreq-js.win32-x64-msvc.node and ../rust/wreq-js.node. Make sure the package is installed correctly and the native module is built for your platform.");
107
+ }
108
+ }
109
+ throw new Error(`Unsupported platform: ${platform}-${arch}${libc ? `-${libc}` : ""}. Supported platforms: darwin-x64, darwin-arm64, linux-x64-gnu, linux-x64-musl, linux-arm64-gnu, win32-x64-msvc`);
127
110
  }
128
111
  nativeBinding = loadNativeBinding();
129
- var websocketFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((connection) => {
130
- void nativeBinding.websocketClose(connection).catch(() => void 0);
112
+ const websocketFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((connection) => {
113
+ nativeBinding.websocketClose(connection).catch(() => void 0);
131
114
  }) : void 0;
132
- var bodyHandleFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((handle) => {
133
- if (handle.released) {
134
- return;
135
- }
136
- handle.released = true;
137
- try {
138
- nativeBinding.cancelBody(handle.id);
139
- } catch {
140
- }
115
+ const bodyHandleFinalizer = typeof FinalizationRegistry === "function" ? new FinalizationRegistry((handle) => {
116
+ if (handle.released) return;
117
+ handle.released = true;
118
+ try {
119
+ nativeBinding.cancelBody(handle.id);
120
+ } catch {}
141
121
  }) : void 0;
142
- var DEFAULT_BROWSER = "chrome_142";
143
- var DEFAULT_OS = "macos";
144
- var DEFAULT_REQUEST_TIMEOUT_MS = 3e5;
145
- var SUPPORTED_OSES = ["windows", "macos", "linux", "android", "ios"];
146
- var UTF8_DECODER = new TextDecoder("utf-8");
147
- var ephemeralIdCounter = 0;
122
+ const DEFAULT_BROWSER = "chrome_142";
123
+ const DEFAULT_OS = "macos";
124
+ const DEFAULT_REQUEST_TIMEOUT_MS = 3e5;
125
+ const DEFAULT_TRUST_STORE = "combined";
126
+ const SUPPORTED_OSES = [
127
+ "windows",
128
+ "macos",
129
+ "linux",
130
+ "android",
131
+ "ios"
132
+ ];
133
+ const UTF8_DECODER = new TextDecoder("utf-8");
134
+ let ephemeralIdCounter = 0;
148
135
  function generateEphemeralSessionId() {
149
- return `_e${++ephemeralIdCounter}`;
136
+ return `_e${++ephemeralIdCounter}`;
150
137
  }
151
138
  function generateSessionId() {
152
- return randomUUID();
139
+ return randomUUID();
153
140
  }
154
141
  function normalizeSessionOptions(options) {
155
- const sessionId = options?.sessionId ?? generateSessionId();
156
- const defaults = {
157
- transportMode: resolveEmulationMode(options?.browser, options?.os, options?.emulation)
158
- };
159
- if (options?.proxy !== void 0) {
160
- defaults.proxy = options.proxy;
161
- }
162
- if (options?.timeout !== void 0) {
163
- validateTimeout(options.timeout);
164
- defaults.timeout = options.timeout;
165
- }
166
- if (options?.insecure !== void 0) {
167
- defaults.insecure = options.insecure;
168
- }
169
- if (options?.defaultHeaders !== void 0) {
170
- defaults.defaultHeaders = headersToTuples(options.defaultHeaders);
171
- }
172
- return { sessionId, defaults };
142
+ const sessionId = options?.sessionId ?? generateSessionId();
143
+ const defaults = {
144
+ transportMode: resolveEmulationMode(options?.browser, options?.os, options?.emulation),
145
+ trustStore: DEFAULT_TRUST_STORE
146
+ };
147
+ if (options?.proxy !== void 0) defaults.proxy = options.proxy;
148
+ if (options?.timeout !== void 0) {
149
+ validateTimeout(options.timeout);
150
+ defaults.timeout = options.timeout;
151
+ }
152
+ if (options?.insecure !== void 0) defaults.insecure = options.insecure;
153
+ if (options?.trustStore !== void 0) {
154
+ validateTrustStore(options.trustStore);
155
+ defaults.trustStore = options.trustStore;
156
+ }
157
+ if (options?.defaultHeaders !== void 0) defaults.defaultHeaders = headersToTuples(options.defaultHeaders);
158
+ if (options?.captureDiagnostics !== void 0) defaults.captureDiagnostics = options.captureDiagnostics;
159
+ return {
160
+ sessionId,
161
+ defaults
162
+ };
173
163
  }
174
164
  function isIterable(value) {
175
- return Boolean(value) && typeof value[Symbol.iterator] === "function";
165
+ return Boolean(value) && typeof value[Symbol.iterator] === "function";
176
166
  }
177
167
  function isPlainObject(value) {
178
- if (typeof value !== "object" || value === null) {
179
- return false;
180
- }
181
- const proto = Object.getPrototypeOf(value);
182
- return proto === Object.prototype || proto === null;
168
+ if (typeof value !== "object" || value === null) return false;
169
+ const proto = Object.getPrototypeOf(value);
170
+ return proto === Object.prototype || proto === null;
183
171
  }
184
172
  function coerceHeaderValue(value) {
185
- return String(value);
186
- }
187
- var Headers = class _Headers {
188
- store = /* @__PURE__ */ new Map();
189
- constructor(init) {
190
- if (init) {
191
- this.applyInit(init);
192
- }
193
- }
194
- applyInit(init) {
195
- if (init instanceof _Headers) {
196
- for (const [name, value] of init) {
197
- this.append(name, value);
198
- }
199
- return;
200
- }
201
- if (Array.isArray(init) || isIterable(init)) {
202
- for (const tuple of init) {
203
- if (!tuple) {
204
- continue;
205
- }
206
- const [name, value] = tuple;
207
- this.append(name, value);
208
- }
209
- return;
210
- }
211
- if (isPlainObject(init)) {
212
- for (const [name, value] of Object.entries(init)) {
213
- if (value === void 0 || value === null) {
214
- continue;
215
- }
216
- this.set(name, coerceHeaderValue(value));
217
- }
218
- }
219
- }
220
- normalizeName(name) {
221
- if (typeof name !== "string") {
222
- throw new TypeError("Header name must be a string");
223
- }
224
- const trimmed = name.trim();
225
- if (!trimmed) {
226
- throw new TypeError("Header name must not be empty");
227
- }
228
- return { key: trimmed.toLowerCase(), display: trimmed };
229
- }
230
- assertValue(value) {
231
- if (value === void 0 || value === null) {
232
- throw new TypeError("Header value must not be null or undefined");
233
- }
234
- return coerceHeaderValue(value);
235
- }
236
- append(name, value) {
237
- const normalized = this.normalizeName(name);
238
- const existing = this.store.get(normalized.key);
239
- const coercedValue = this.assertValue(value);
240
- if (existing) {
241
- existing.values.push(coercedValue);
242
- return;
243
- }
244
- this.store.set(normalized.key, {
245
- name: normalized.display,
246
- values: [coercedValue]
247
- });
248
- }
249
- set(name, value) {
250
- const normalized = this.normalizeName(name);
251
- const coercedValue = this.assertValue(value);
252
- this.store.set(normalized.key, {
253
- name: normalized.display,
254
- values: [coercedValue]
255
- });
256
- }
257
- get(name) {
258
- const normalized = this.normalizeName(name);
259
- const entry = this.store.get(normalized.key);
260
- return entry ? entry.values.join(", ") : null;
261
- }
262
- has(name) {
263
- const normalized = this.normalizeName(name);
264
- return this.store.has(normalized.key);
265
- }
266
- delete(name) {
267
- const normalized = this.normalizeName(name);
268
- this.store.delete(normalized.key);
269
- }
270
- entries() {
271
- return this[Symbol.iterator]();
272
- }
273
- *keys() {
274
- for (const [name] of this) {
275
- yield name;
276
- }
277
- }
278
- *values() {
279
- for (const [, value] of this) {
280
- yield value;
281
- }
282
- }
283
- forEach(callback, thisArg) {
284
- for (const [name, value] of this) {
285
- callback.call(thisArg, value, name, this);
286
- }
287
- }
288
- [Symbol.iterator]() {
289
- const generator = function* (store) {
290
- for (const entry of store.values()) {
291
- yield [entry.name, entry.values.join(", ")];
292
- }
293
- };
294
- return generator(this.store);
295
- }
296
- toObject() {
297
- const result = {};
298
- for (const [name, value] of this) {
299
- result[name] = value;
300
- }
301
- return result;
302
- }
303
- toTuples() {
304
- const result = [];
305
- for (const [name, value] of this) {
306
- result.push([name, value]);
307
- }
308
- return result;
309
- }
173
+ return String(value);
174
+ }
175
+ var Headers = class Headers {
176
+ store = /* @__PURE__ */ new Map();
177
+ constructor(init) {
178
+ if (init) this.applyInit(init);
179
+ }
180
+ applyInit(init) {
181
+ if (init instanceof Headers) {
182
+ for (const [name, value] of init) this.append(name, value);
183
+ return;
184
+ }
185
+ if (Array.isArray(init) || isIterable(init)) {
186
+ for (const tuple of init) {
187
+ if (!tuple) continue;
188
+ const [name, value] = tuple;
189
+ this.append(name, value);
190
+ }
191
+ return;
192
+ }
193
+ if (isPlainObject(init)) for (const [name, value] of Object.entries(init)) {
194
+ if (value === void 0 || value === null) continue;
195
+ this.set(name, coerceHeaderValue(value));
196
+ }
197
+ }
198
+ normalizeName(name) {
199
+ if (typeof name !== "string") throw new TypeError("Header name must be a string");
200
+ const trimmed = name.trim();
201
+ if (!trimmed) throw new TypeError("Header name must not be empty");
202
+ return {
203
+ key: trimmed.toLowerCase(),
204
+ display: trimmed
205
+ };
206
+ }
207
+ assertValue(value) {
208
+ if (value === void 0 || value === null) throw new TypeError("Header value must not be null or undefined");
209
+ return coerceHeaderValue(value);
210
+ }
211
+ append(name, value) {
212
+ const normalized = this.normalizeName(name);
213
+ const existing = this.store.get(normalized.key);
214
+ const coercedValue = this.assertValue(value);
215
+ if (existing) {
216
+ existing.values.push(coercedValue);
217
+ return;
218
+ }
219
+ this.store.set(normalized.key, {
220
+ name: normalized.display,
221
+ values: [coercedValue]
222
+ });
223
+ }
224
+ set(name, value) {
225
+ const normalized = this.normalizeName(name);
226
+ const coercedValue = this.assertValue(value);
227
+ this.store.set(normalized.key, {
228
+ name: normalized.display,
229
+ values: [coercedValue]
230
+ });
231
+ }
232
+ get(name) {
233
+ const normalized = this.normalizeName(name);
234
+ const entry = this.store.get(normalized.key);
235
+ return entry ? entry.values.join(", ") : null;
236
+ }
237
+ has(name) {
238
+ const normalized = this.normalizeName(name);
239
+ return this.store.has(normalized.key);
240
+ }
241
+ delete(name) {
242
+ const normalized = this.normalizeName(name);
243
+ this.store.delete(normalized.key);
244
+ }
245
+ entries() {
246
+ return this[Symbol.iterator]();
247
+ }
248
+ *keys() {
249
+ for (const [name] of this) yield name;
250
+ }
251
+ *values() {
252
+ for (const [, value] of this) yield value;
253
+ }
254
+ forEach(callback, thisArg) {
255
+ for (const [name, value] of this) callback.call(thisArg, value, name, this);
256
+ }
257
+ [Symbol.iterator]() {
258
+ const generator = function* (store) {
259
+ for (const entry of store.values()) yield [entry.name, entry.values.join(", ")];
260
+ };
261
+ return generator(this.store);
262
+ }
263
+ toObject() {
264
+ const result = {};
265
+ for (const [name, value] of this) result[name] = value;
266
+ return result;
267
+ }
268
+ toTuples() {
269
+ const result = [];
270
+ for (const [name, value] of this) result.push([name, value]);
271
+ return result;
272
+ }
310
273
  };
311
274
  function headersToTuples(init) {
312
- return new Headers(init).toTuples();
275
+ return new Headers(init).toTuples();
313
276
  }
314
277
  function hasHeaderName(tuples, name) {
315
- if (!tuples) {
316
- return false;
317
- }
318
- const target = name.toLowerCase();
319
- for (const [headerName] of tuples) {
320
- if (headerName.toLowerCase() === target) {
321
- return true;
322
- }
323
- }
324
- return false;
278
+ if (!tuples) return false;
279
+ const target = name.toLowerCase();
280
+ for (const [headerName] of tuples) if (headerName.toLowerCase() === target) return true;
281
+ return false;
325
282
  }
326
283
  function hasWebSocketProtocolHeader(headers) {
327
- const protocolHeaderName = "Sec-WebSocket-Protocol";
328
- if (!headers) {
329
- return false;
330
- }
331
- return hasHeaderName(headersToTuples(headers), protocolHeaderName);
284
+ const protocolHeaderName = "Sec-WebSocket-Protocol";
285
+ if (!headers) return false;
286
+ return hasHeaderName(headersToTuples(headers), protocolHeaderName);
332
287
  }
333
288
  function assertNoManualWebSocketProtocolHeader(headers) {
334
- if (hasWebSocketProtocolHeader(headers)) {
335
- throw new RequestError("Do not set `Sec-WebSocket-Protocol` header manually; use the `protocols` option instead.");
336
- }
289
+ if (hasWebSocketProtocolHeader(headers)) throw new RequestError("Do not set `Sec-WebSocket-Protocol` header manually; use the `protocols` option instead.");
337
290
  }
338
291
  function normalizeWebSocketProtocolList(protocols) {
339
- if (protocols === void 0) {
340
- return void 0;
341
- }
342
- return typeof protocols === "string" ? [protocols] : [...protocols];
292
+ if (protocols === void 0) return;
293
+ return typeof protocols === "string" ? [protocols] : [...protocols];
343
294
  }
344
295
  function mergeHeaderTuples(defaults, overrides) {
345
- if (!defaults) {
346
- return overrides === void 0 ? void 0 : headersToTuples(overrides);
347
- }
348
- if (overrides === void 0) {
349
- return defaults;
350
- }
351
- const overrideTuples = headersToTuples(overrides);
352
- if (overrideTuples.length === 0) {
353
- return defaults;
354
- }
355
- const overrideKeys = /* @__PURE__ */ new Set();
356
- for (const tuple of overrideTuples) {
357
- overrideKeys.add(tuple[0].toLowerCase());
358
- }
359
- const merged = [];
360
- for (const tuple of defaults) {
361
- if (!overrideKeys.has(tuple[0].toLowerCase())) {
362
- merged.push(tuple);
363
- }
364
- }
365
- for (const tuple of overrideTuples) {
366
- merged.push(tuple);
367
- }
368
- return merged;
296
+ if (!defaults) return overrides === void 0 ? void 0 : headersToTuples(overrides);
297
+ if (overrides === void 0) return defaults;
298
+ const overrideTuples = headersToTuples(overrides);
299
+ if (overrideTuples.length === 0) return defaults;
300
+ const overrideKeys = /* @__PURE__ */ new Set();
301
+ for (const tuple of overrideTuples) overrideKeys.add(tuple[0].toLowerCase());
302
+ const merged = [];
303
+ for (const tuple of defaults) if (!overrideKeys.has(tuple[0].toLowerCase())) merged.push(tuple);
304
+ for (const tuple of overrideTuples) merged.push(tuple);
305
+ return merged;
369
306
  }
370
307
  function cloneNativeResponse(payload) {
371
- return {
372
- status: payload.status,
373
- headers: payload.headers.map(([name, value]) => [name, value]),
374
- bodyHandle: payload.bodyHandle,
375
- bodyBytes: payload.bodyBytes,
376
- contentLength: payload.contentLength,
377
- cookies: payload.cookies.map(([name, value]) => [name, value]),
378
- url: payload.url
379
- };
308
+ return {
309
+ status: payload.status,
310
+ headers: payload.headers.map(([name, value]) => [name, value]),
311
+ bodyHandle: payload.bodyHandle,
312
+ bodyBytes: payload.bodyBytes,
313
+ contentLength: payload.contentLength,
314
+ cookies: payload.cookies.map(([name, value]) => [name, value]),
315
+ url: payload.url,
316
+ diagnostics: payload.diagnostics ? { ...payload.diagnostics } : null
317
+ };
380
318
  }
381
319
  function releaseNativeBody(handle) {
382
- if (handle.released) {
383
- return;
384
- }
385
- handle.released = true;
386
- try {
387
- nativeBinding.cancelBody(handle.id);
388
- } catch {
389
- }
390
- bodyHandleFinalizer?.unregister(handle);
320
+ if (handle.released) return;
321
+ handle.released = true;
322
+ try {
323
+ nativeBinding.cancelBody(handle.id);
324
+ } catch {}
325
+ bodyHandleFinalizer?.unregister(handle);
391
326
  }
392
327
  function markNativeBodyReleased(handle) {
393
- if (handle.released) {
394
- return;
395
- }
396
- handle.released = true;
397
- bodyHandleFinalizer?.unregister(handle);
328
+ if (handle.released) return;
329
+ handle.released = true;
330
+ bodyHandleFinalizer?.unregister(handle);
398
331
  }
399
332
  function createNativeBodyStream(handle) {
400
- const stream = new ReadableStream({
401
- async pull(controller) {
402
- try {
403
- const chunk = await nativeBinding.readBodyChunk(handle.id);
404
- if (chunk === null) {
405
- releaseNativeBody(handle);
406
- controller.close();
407
- return;
408
- }
409
- controller.enqueue(chunk);
410
- } catch (error) {
411
- releaseNativeBody(handle);
412
- controller.error(error);
413
- }
414
- },
415
- cancel() {
416
- releaseNativeBody(handle);
417
- }
418
- });
419
- bodyHandleFinalizer?.register(stream, handle, handle);
420
- return stream;
333
+ const stream = new ReadableStream({
334
+ async pull(controller) {
335
+ try {
336
+ const chunk = await nativeBinding.readBodyChunk(handle.id);
337
+ if (chunk === null) {
338
+ releaseNativeBody(handle);
339
+ controller.close();
340
+ return;
341
+ }
342
+ controller.enqueue(chunk);
343
+ } catch (error) {
344
+ releaseNativeBody(handle);
345
+ controller.error(error);
346
+ }
347
+ },
348
+ cancel() {
349
+ releaseNativeBody(handle);
350
+ }
351
+ });
352
+ bodyHandleFinalizer?.register(stream, handle, handle);
353
+ return stream;
421
354
  }
422
355
  function wrapBodyStream(source, onFirstUse) {
423
- let started = false;
424
- let reader = null;
425
- return new ReadableStream({
426
- async pull(controller) {
427
- if (!started) {
428
- started = true;
429
- onFirstUse();
430
- }
431
- if (!reader) {
432
- reader = source.getReader();
433
- }
434
- try {
435
- const { done, value } = await reader.read();
436
- if (done) {
437
- controller.close();
438
- return;
439
- }
440
- controller.enqueue(value);
441
- } catch (error) {
442
- controller.error(error);
443
- }
444
- },
445
- cancel(reason) {
446
- if (!reader) {
447
- return source.cancel(reason);
448
- }
449
- return reader.cancel(reason);
450
- }
451
- });
452
- }
453
- var Response = class _Response {
454
- status;
455
- ok;
456
- contentLength;
457
- url;
458
- type = "basic";
459
- bodyUsed = false;
460
- payload;
461
- requestUrl;
462
- redirectedMemo;
463
- headersInit;
464
- headersInstance;
465
- cookiesInit;
466
- cookiesRecord;
467
- inlineBody;
468
- bodySource;
469
- bodyStream;
470
- // Track if we can use the fast path (native handle not yet wrapped in a stream)
471
- nativeHandleAvailable;
472
- nativeHandle;
473
- constructor(payload, requestUrl, bodySource) {
474
- this.payload = payload;
475
- this.requestUrl = requestUrl;
476
- this.status = this.payload.status;
477
- this.ok = this.status >= 200 && this.status < 300;
478
- this.headersInit = this.payload.headers;
479
- this.headersInstance = null;
480
- this.url = this.payload.url;
481
- this.cookiesInit = this.payload.cookies;
482
- this.cookiesRecord = null;
483
- this.contentLength = this.payload.contentLength ?? null;
484
- this.inlineBody = this.payload.bodyBytes ?? null;
485
- this.nativeHandle = null;
486
- if (typeof bodySource !== "undefined") {
487
- this.bodySource = bodySource;
488
- this.nativeHandleAvailable = false;
489
- } else if (this.inlineBody !== null) {
490
- this.bodySource = null;
491
- this.nativeHandleAvailable = false;
492
- } else if (this.payload.bodyHandle !== null) {
493
- this.bodySource = null;
494
- this.nativeHandleAvailable = true;
495
- this.nativeHandle = { id: this.payload.bodyHandle, released: false };
496
- bodyHandleFinalizer?.register(this, this.nativeHandle, this.nativeHandle);
497
- } else {
498
- this.bodySource = null;
499
- this.nativeHandleAvailable = false;
500
- }
501
- this.bodyStream = void 0;
502
- }
503
- get redirected() {
504
- if (this.redirectedMemo !== void 0) {
505
- return this.redirectedMemo;
506
- }
507
- if (this.url === this.requestUrl) {
508
- this.redirectedMemo = false;
509
- return false;
510
- }
511
- const normalizedRequestUrl = normalizeUrlForComparison(this.requestUrl);
512
- this.redirectedMemo = normalizedRequestUrl ? this.url !== normalizedRequestUrl : true;
513
- return this.redirectedMemo;
514
- }
515
- get statusText() {
516
- return STATUS_CODES[this.status] ?? "";
517
- }
518
- get headers() {
519
- if (!this.headersInstance) {
520
- this.headersInstance = new Headers(this.headersInit);
521
- }
522
- return this.headersInstance;
523
- }
524
- get cookies() {
525
- if (!this.cookiesRecord) {
526
- const record = /* @__PURE__ */ Object.create(null);
527
- for (const [name, value] of this.cookiesInit) {
528
- const existing = record[name];
529
- if (existing === void 0) {
530
- record[name] = value;
531
- } else if (Array.isArray(existing)) {
532
- existing.push(value);
533
- } else {
534
- record[name] = [existing, value];
535
- }
536
- }
537
- this.cookiesRecord = record;
538
- }
539
- return this.cookiesRecord;
540
- }
541
- get body() {
542
- if (this.inlineBody && this.bodySource === null) {
543
- const bytes = this.inlineBody;
544
- this.inlineBody = null;
545
- this.bodySource = new ReadableStream({
546
- start(controller) {
547
- controller.enqueue(bytes);
548
- controller.close();
549
- }
550
- });
551
- }
552
- if (this.inlineBody === null && this.payload.bodyHandle === null && this.bodySource === null) {
553
- return null;
554
- }
555
- if (this.bodySource === null && this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
556
- if (this.nativeHandle) {
557
- bodyHandleFinalizer?.unregister(this.nativeHandle);
558
- }
559
- const handle = this.nativeHandle ?? { id: this.payload.bodyHandle, released: false };
560
- this.nativeHandle = handle;
561
- this.bodySource = createNativeBodyStream(handle);
562
- this.nativeHandleAvailable = false;
563
- }
564
- if (this.bodySource === null) {
565
- return null;
566
- }
567
- if (this.bodyStream === void 0) {
568
- this.bodyStream = wrapBodyStream(this.bodySource, () => {
569
- this.bodyUsed = true;
570
- });
571
- }
572
- return this.bodyStream;
573
- }
574
- async json() {
575
- const text = await this.text();
576
- return JSON.parse(text);
577
- }
578
- async arrayBuffer() {
579
- const bytes = await this.consumeBody();
580
- const { buffer, byteOffset, byteLength } = bytes;
581
- if (buffer instanceof ArrayBuffer) {
582
- if (byteOffset === 0 && byteLength === buffer.byteLength) {
583
- return buffer;
584
- }
585
- return buffer.slice(byteOffset, byteOffset + byteLength);
586
- }
587
- const view = new Uint8Array(byteLength);
588
- view.set(bytes);
589
- return view.buffer;
590
- }
591
- async text() {
592
- const bytes = await this.consumeBody();
593
- return UTF8_DECODER.decode(bytes);
594
- }
595
- async blob() {
596
- const bytes = await this.consumeBody();
597
- const contentType = this.headers.get("content-type") ?? "";
598
- return new Blob([bytes], contentType ? { type: contentType } : void 0);
599
- }
600
- async formData() {
601
- const bytes = await this.consumeBody();
602
- const contentType = this.headers.get("content-type");
603
- const response = new globalThis.Response(
604
- bytes,
605
- contentType ? { headers: { "content-type": contentType } } : void 0
606
- );
607
- return response.formData();
608
- }
609
- readable() {
610
- this.assertBodyAvailable();
611
- this.bodyUsed = true;
612
- const stream = this.body;
613
- if (stream === null) {
614
- return Readable.from([]);
615
- }
616
- return Readable.fromWeb(stream);
617
- }
618
- clone() {
619
- if (this.bodyUsed) {
620
- throw new TypeError("Cannot clone a Response whose body is already used");
621
- }
622
- if (this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
623
- if (this.nativeHandle) {
624
- bodyHandleFinalizer?.unregister(this.nativeHandle);
625
- }
626
- const handle = this.nativeHandle ?? { id: this.payload.bodyHandle, released: false };
627
- this.nativeHandle = handle;
628
- this.bodySource = createNativeBodyStream(handle);
629
- this.nativeHandleAvailable = false;
630
- }
631
- if (this.bodySource === null) {
632
- return new _Response(cloneNativeResponse(this.payload), this.requestUrl, null);
633
- }
634
- const [branchA, branchB] = this.bodySource.tee();
635
- this.bodySource = branchA;
636
- this.bodyStream = void 0;
637
- return new _Response(cloneNativeResponse(this.payload), this.requestUrl, branchB);
638
- }
639
- assertBodyAvailable() {
640
- if (this.bodyUsed) {
641
- throw new TypeError("Response body is already used");
642
- }
643
- }
644
- async consumeBody() {
645
- this.assertBodyAvailable();
646
- this.bodyUsed = true;
647
- if (this.inlineBody) {
648
- const bytes = this.inlineBody;
649
- this.inlineBody = null;
650
- return bytes;
651
- }
652
- if (this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
653
- this.nativeHandleAvailable = false;
654
- try {
655
- return await nativeBinding.readBodyAll(this.payload.bodyHandle);
656
- } catch (error) {
657
- if (String(error).includes("Body handle") && String(error).includes("not found")) {
658
- return Buffer.alloc(0);
659
- }
660
- throw error;
661
- } finally {
662
- if (this.nativeHandle) {
663
- markNativeBodyReleased(this.nativeHandle);
664
- }
665
- }
666
- }
667
- const stream = this.body;
668
- if (!stream) {
669
- return Buffer.alloc(0);
670
- }
671
- const reader = stream.getReader();
672
- const chunks = [];
673
- try {
674
- while (true) {
675
- const { done, value } = await reader.read();
676
- if (done) {
677
- break;
678
- }
679
- if (value && value.byteLength > 0) {
680
- if (Buffer.isBuffer(value)) {
681
- chunks.push(value);
682
- } else {
683
- chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
684
- }
685
- }
686
- }
687
- } finally {
688
- }
689
- return chunks.length === 0 ? Buffer.alloc(0) : Buffer.concat(chunks);
690
- }
356
+ let started = false;
357
+ let reader = null;
358
+ return new ReadableStream({
359
+ async pull(controller) {
360
+ if (!started) {
361
+ started = true;
362
+ onFirstUse();
363
+ }
364
+ if (!reader) reader = source.getReader();
365
+ try {
366
+ const { done, value } = await reader.read();
367
+ if (done) {
368
+ controller.close();
369
+ return;
370
+ }
371
+ controller.enqueue(value);
372
+ } catch (error) {
373
+ controller.error(error);
374
+ }
375
+ },
376
+ cancel(reason) {
377
+ if (!reader) return source.cancel(reason);
378
+ return reader.cancel(reason);
379
+ }
380
+ });
381
+ }
382
+ var Response = class Response {
383
+ status;
384
+ ok;
385
+ contentLength;
386
+ url;
387
+ diagnostics;
388
+ type = "basic";
389
+ bodyUsed = false;
390
+ payload;
391
+ requestUrl;
392
+ redirectedMemo;
393
+ headersInit;
394
+ headersInstance;
395
+ cookiesInit;
396
+ cookiesRecord;
397
+ inlineBody;
398
+ bodySource;
399
+ bodyStream;
400
+ nativeHandleAvailable;
401
+ nativeHandle;
402
+ constructor(payload, requestUrl, bodySource) {
403
+ this.payload = payload;
404
+ this.requestUrl = requestUrl;
405
+ this.status = this.payload.status;
406
+ this.ok = this.status >= 200 && this.status < 300;
407
+ this.headersInit = this.payload.headers;
408
+ this.headersInstance = null;
409
+ this.url = this.payload.url;
410
+ this.diagnostics = this.payload.diagnostics ?? null;
411
+ this.cookiesInit = this.payload.cookies;
412
+ this.cookiesRecord = null;
413
+ this.contentLength = this.payload.contentLength ?? null;
414
+ this.inlineBody = this.payload.bodyBytes ?? null;
415
+ this.nativeHandle = null;
416
+ if (typeof bodySource !== "undefined") {
417
+ this.bodySource = bodySource;
418
+ this.nativeHandleAvailable = false;
419
+ } else if (this.inlineBody !== null) {
420
+ this.bodySource = null;
421
+ this.nativeHandleAvailable = false;
422
+ } else if (this.payload.bodyHandle !== null) {
423
+ this.bodySource = null;
424
+ this.nativeHandleAvailable = true;
425
+ this.nativeHandle = {
426
+ id: this.payload.bodyHandle,
427
+ released: false
428
+ };
429
+ bodyHandleFinalizer?.register(this, this.nativeHandle, this.nativeHandle);
430
+ } else {
431
+ this.bodySource = null;
432
+ this.nativeHandleAvailable = false;
433
+ }
434
+ this.bodyStream = void 0;
435
+ }
436
+ get redirected() {
437
+ if (this.redirectedMemo !== void 0) return this.redirectedMemo;
438
+ if (this.url === this.requestUrl) {
439
+ this.redirectedMemo = false;
440
+ return false;
441
+ }
442
+ const normalizedRequestUrl = normalizeUrlForComparison(this.requestUrl);
443
+ this.redirectedMemo = normalizedRequestUrl ? this.url !== normalizedRequestUrl : true;
444
+ return this.redirectedMemo;
445
+ }
446
+ get statusText() {
447
+ return STATUS_CODES[this.status] ?? "";
448
+ }
449
+ get headers() {
450
+ if (!this.headersInstance) this.headersInstance = new Headers(this.headersInit);
451
+ return this.headersInstance;
452
+ }
453
+ get cookies() {
454
+ if (!this.cookiesRecord) {
455
+ const record = Object.create(null);
456
+ for (const [name, value] of this.cookiesInit) {
457
+ const existing = record[name];
458
+ if (existing === void 0) record[name] = value;
459
+ else if (Array.isArray(existing)) existing.push(value);
460
+ else record[name] = [existing, value];
461
+ }
462
+ this.cookiesRecord = record;
463
+ }
464
+ return this.cookiesRecord;
465
+ }
466
+ get body() {
467
+ if (this.inlineBody && this.bodySource === null) {
468
+ const bytes = this.inlineBody;
469
+ this.inlineBody = null;
470
+ this.bodySource = new ReadableStream({ start(controller) {
471
+ controller.enqueue(bytes);
472
+ controller.close();
473
+ } });
474
+ }
475
+ if (this.inlineBody === null && this.payload.bodyHandle === null && this.bodySource === null) return null;
476
+ if (this.bodySource === null && this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
477
+ if (this.nativeHandle) bodyHandleFinalizer?.unregister(this.nativeHandle);
478
+ const handle = this.nativeHandle ?? {
479
+ id: this.payload.bodyHandle,
480
+ released: false
481
+ };
482
+ this.nativeHandle = handle;
483
+ this.bodySource = createNativeBodyStream(handle);
484
+ this.nativeHandleAvailable = false;
485
+ }
486
+ if (this.bodySource === null) return null;
487
+ if (this.bodyStream === void 0) this.bodyStream = wrapBodyStream(this.bodySource, () => {
488
+ this.bodyUsed = true;
489
+ });
490
+ return this.bodyStream;
491
+ }
492
+ async json() {
493
+ const text = await this.text();
494
+ return JSON.parse(text);
495
+ }
496
+ async arrayBuffer() {
497
+ const bytes = await this.consumeBody();
498
+ const { buffer, byteOffset, byteLength } = bytes;
499
+ if (buffer instanceof ArrayBuffer) {
500
+ if (byteOffset === 0 && byteLength === buffer.byteLength) return buffer;
501
+ return buffer.slice(byteOffset, byteOffset + byteLength);
502
+ }
503
+ const view = new Uint8Array(byteLength);
504
+ view.set(bytes);
505
+ return view.buffer;
506
+ }
507
+ async text() {
508
+ const bytes = await this.consumeBody();
509
+ return UTF8_DECODER.decode(bytes);
510
+ }
511
+ async blob() {
512
+ const bytes = await this.consumeBody();
513
+ const contentType = this.headers.get("content-type") ?? "";
514
+ return new Blob([bytes], contentType ? { type: contentType } : void 0);
515
+ }
516
+ async formData() {
517
+ const bytes = await this.consumeBody();
518
+ const contentType = this.headers.get("content-type");
519
+ return new globalThis.Response(bytes, contentType ? { headers: { "content-type": contentType } } : void 0).formData();
520
+ }
521
+ readable() {
522
+ this.assertBodyAvailable();
523
+ this.bodyUsed = true;
524
+ const stream = this.body;
525
+ if (stream === null) return Readable.from([]);
526
+ return Readable.fromWeb(stream);
527
+ }
528
+ clone() {
529
+ if (this.bodyUsed) throw new TypeError("Cannot clone a Response whose body is already used");
530
+ if (this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
531
+ if (this.nativeHandle) bodyHandleFinalizer?.unregister(this.nativeHandle);
532
+ const handle = this.nativeHandle ?? {
533
+ id: this.payload.bodyHandle,
534
+ released: false
535
+ };
536
+ this.nativeHandle = handle;
537
+ this.bodySource = createNativeBodyStream(handle);
538
+ this.nativeHandleAvailable = false;
539
+ }
540
+ if (this.bodySource === null) return new Response(cloneNativeResponse(this.payload), this.requestUrl, null);
541
+ const [branchA, branchB] = this.bodySource.tee();
542
+ this.bodySource = branchA;
543
+ this.bodyStream = void 0;
544
+ return new Response(cloneNativeResponse(this.payload), this.requestUrl, branchB);
545
+ }
546
+ assertBodyAvailable() {
547
+ if (this.bodyUsed) throw new TypeError("Response body is already used");
548
+ }
549
+ async consumeBody() {
550
+ this.assertBodyAvailable();
551
+ this.bodyUsed = true;
552
+ if (this.inlineBody) {
553
+ const bytes = this.inlineBody;
554
+ this.inlineBody = null;
555
+ return bytes;
556
+ }
557
+ if (this.nativeHandleAvailable && this.payload.bodyHandle !== null) {
558
+ this.nativeHandleAvailable = false;
559
+ try {
560
+ return await nativeBinding.readBodyAll(this.payload.bodyHandle);
561
+ } catch (error) {
562
+ if (String(error).includes("Body handle") && String(error).includes("not found")) return Buffer.alloc(0);
563
+ throw error;
564
+ } finally {
565
+ if (this.nativeHandle) markNativeBodyReleased(this.nativeHandle);
566
+ }
567
+ }
568
+ const stream = this.body;
569
+ if (!stream) return Buffer.alloc(0);
570
+ const reader = stream.getReader();
571
+ const chunks = [];
572
+ try {
573
+ while (true) {
574
+ const { done, value } = await reader.read();
575
+ if (done) break;
576
+ if (value && value.byteLength > 0) if (Buffer.isBuffer(value)) chunks.push(value);
577
+ else chunks.push(Buffer.from(value.buffer, value.byteOffset, value.byteLength));
578
+ }
579
+ } finally {}
580
+ return chunks.length === 0 ? Buffer.alloc(0) : Buffer.concat(chunks);
581
+ }
691
582
  };
692
583
  var Transport = class {
693
- id;
694
- disposed = false;
695
- constructor(id) {
696
- this.id = id;
697
- }
698
- get closed() {
699
- return this.disposed;
700
- }
701
- async close() {
702
- if (this.disposed) {
703
- return;
704
- }
705
- this.disposed = true;
706
- try {
707
- nativeBinding.dropTransport(this.id);
708
- } catch (error) {
709
- throw new RequestError(String(error));
710
- }
711
- }
584
+ id;
585
+ disposed = false;
586
+ constructor(id) {
587
+ this.id = id;
588
+ }
589
+ get closed() {
590
+ return this.disposed;
591
+ }
592
+ async close() {
593
+ if (this.disposed) return;
594
+ this.disposed = true;
595
+ try {
596
+ nativeBinding.dropTransport(this.id);
597
+ } catch (error) {
598
+ throw new RequestError(String(error));
599
+ }
600
+ }
712
601
  };
713
602
  var Session = class {
714
- id;
715
- disposed = false;
716
- defaults;
717
- constructor(id, defaults) {
718
- this.id = id;
719
- this.defaults = defaults;
720
- }
721
- get closed() {
722
- return this.disposed;
723
- }
724
- ensureActive() {
725
- if (this.disposed) {
726
- throw new RequestError("Session has been closed");
727
- }
728
- }
729
- /** @internal */
730
- getDefaults() {
731
- const snapshot = { ...this.defaults };
732
- if (this.defaults.defaultHeaders) {
733
- snapshot.defaultHeaders = [...this.defaults.defaultHeaders];
734
- }
735
- return snapshot;
736
- }
737
- /** @internal */
738
- _defaultsRef() {
739
- return this.defaults;
740
- }
741
- async fetch(input, init) {
742
- this.ensureActive();
743
- const config = init ? { ...init, session: this } : { session: this };
744
- return fetch(input, config);
745
- }
746
- async clearCookies() {
747
- this.ensureActive();
748
- try {
749
- nativeBinding.clearSession(this.id);
750
- } catch (error) {
751
- throw new RequestError(String(error));
752
- }
753
- }
754
- getCookies(url) {
755
- this.ensureActive();
756
- try {
757
- return nativeBinding.getCookies(this.id, String(url));
758
- } catch (error) {
759
- throw new RequestError(String(error));
760
- }
761
- }
762
- setCookie(name, value, url) {
763
- this.ensureActive();
764
- try {
765
- nativeBinding.setCookie(this.id, name, value, String(url));
766
- } catch (error) {
767
- throw new RequestError(String(error));
768
- }
769
- }
770
- async websocket(urlOrOptions, options) {
771
- this.ensureActive();
772
- const normalized = normalizeSessionWebSocketArgs(urlOrOptions, options);
773
- validateWebSocketProtocols(normalized.options.protocols);
774
- assertNoManualWebSocketProtocolHeader(normalized.options.headers);
775
- const protocols = normalizeWebSocketProtocolList(normalized.options.protocols);
776
- const transportId = this.defaults.transportId;
777
- if (!transportId) {
778
- throw new RequestError(
779
- "Session has no transport. Create the session with browser/os options or pass a transport to use session.websocket()."
780
- );
781
- }
782
- return WebSocket._connectWithInit({
783
- _internal: true,
784
- url: normalized.url,
785
- options: normalized.options,
786
- openDispatchMode: "deferred",
787
- connect: (callbacks) => nativeBinding.websocketConnectSession({
788
- url: normalized.url,
789
- sessionId: this.id,
790
- transportId,
791
- headers: headersToTuples(normalized.options.headers ?? {}),
792
- ...protocols && protocols.length > 0 && { protocols },
793
- onMessage: callbacks.onMessage,
794
- onClose: callbacks.onClose,
795
- onError: callbacks.onError
796
- }),
797
- legacyCallbacks: normalized.legacyCallbacks
798
- });
799
- }
800
- async close() {
801
- if (this.disposed) {
802
- return;
803
- }
804
- this.disposed = true;
805
- const transportId = this.defaults.transportId;
806
- const ownsTransport = this.defaults.ownsTransport;
807
- try {
808
- nativeBinding.dropSession(this.id);
809
- } catch (error) {
810
- if (!ownsTransport || !transportId) {
811
- throw new RequestError(String(error));
812
- }
813
- const originalError = error;
814
- try {
815
- nativeBinding.dropTransport(transportId);
816
- } catch {
817
- }
818
- throw new RequestError(String(originalError));
819
- }
820
- if (ownsTransport && transportId) {
821
- try {
822
- nativeBinding.dropTransport(transportId);
823
- } catch (error) {
824
- throw new RequestError(String(error));
825
- }
826
- }
827
- }
603
+ id;
604
+ disposed = false;
605
+ defaults;
606
+ constructor(id, defaults) {
607
+ this.id = id;
608
+ this.defaults = defaults;
609
+ }
610
+ get closed() {
611
+ return this.disposed;
612
+ }
613
+ ensureActive() {
614
+ if (this.disposed) throw new RequestError("Session has been closed");
615
+ }
616
+ /** @internal */
617
+ getDefaults() {
618
+ const snapshot = { ...this.defaults };
619
+ if (this.defaults.defaultHeaders) snapshot.defaultHeaders = [...this.defaults.defaultHeaders];
620
+ return snapshot;
621
+ }
622
+ /** @internal */
623
+ _defaultsRef() {
624
+ return this.defaults;
625
+ }
626
+ async fetch(input, init) {
627
+ this.ensureActive();
628
+ return fetch(input, init ? {
629
+ ...init,
630
+ session: this
631
+ } : { session: this });
632
+ }
633
+ async clearCookies() {
634
+ this.ensureActive();
635
+ try {
636
+ nativeBinding.clearSession(this.id);
637
+ } catch (error) {
638
+ throw new RequestError(String(error));
639
+ }
640
+ }
641
+ getCookies(url) {
642
+ this.ensureActive();
643
+ try {
644
+ return nativeBinding.getCookies(this.id, String(url));
645
+ } catch (error) {
646
+ throw new RequestError(String(error));
647
+ }
648
+ }
649
+ getAllCookies() {
650
+ this.ensureActive();
651
+ try {
652
+ return nativeBinding.getAllCookies(this.id);
653
+ } catch (error) {
654
+ throw new RequestError(String(error));
655
+ }
656
+ }
657
+ setCookie(name, value, url) {
658
+ this.ensureActive();
659
+ try {
660
+ nativeBinding.setCookie(this.id, name, value, String(url));
661
+ } catch (error) {
662
+ throw new RequestError(String(error));
663
+ }
664
+ }
665
+ async websocket(urlOrOptions, options) {
666
+ this.ensureActive();
667
+ const normalized = normalizeSessionWebSocketArgs(urlOrOptions, options);
668
+ validateWebSocketProtocols(normalized.options.protocols);
669
+ assertNoManualWebSocketProtocolHeader(normalized.options.headers);
670
+ const protocols = normalizeWebSocketProtocolList(normalized.options.protocols);
671
+ const transportId = this.defaults.transportId;
672
+ if (!transportId) throw new RequestError("Session has no transport. Create the session with browser/os options or pass a transport to use session.websocket().");
673
+ return WebSocket._connectWithInit({
674
+ _internal: true,
675
+ url: normalized.url,
676
+ options: normalized.options,
677
+ openDispatchMode: "deferred",
678
+ connect: (callbacks) => nativeBinding.websocketConnectSession({
679
+ url: normalized.url,
680
+ sessionId: this.id,
681
+ transportId,
682
+ headers: headersToTuples(normalized.options.headers ?? {}),
683
+ ...protocols && protocols.length > 0 && { protocols },
684
+ ...normalized.options.maxFrameSize !== void 0 && { maxFrameSize: normalized.options.maxFrameSize },
685
+ ...normalized.options.maxMessageSize !== void 0 && { maxMessageSize: normalized.options.maxMessageSize },
686
+ onMessage: callbacks.onMessage,
687
+ onClose: callbacks.onClose,
688
+ onError: callbacks.onError
689
+ }),
690
+ legacyCallbacks: normalized.legacyCallbacks
691
+ });
692
+ }
693
+ async close() {
694
+ if (this.disposed) return;
695
+ this.disposed = true;
696
+ const transportId = this.defaults.transportId;
697
+ const ownsTransport = this.defaults.ownsTransport;
698
+ try {
699
+ nativeBinding.dropSession(this.id);
700
+ } catch (error) {
701
+ if (!ownsTransport || !transportId) throw new RequestError(String(error));
702
+ const originalError = error;
703
+ try {
704
+ nativeBinding.dropTransport(transportId);
705
+ } catch {}
706
+ throw new RequestError(String(originalError));
707
+ }
708
+ if (ownsTransport && transportId) try {
709
+ nativeBinding.dropTransport(transportId);
710
+ } catch (error) {
711
+ throw new RequestError(String(error));
712
+ }
713
+ }
828
714
  };
829
715
  function resolveSessionContext(config) {
830
- const requestedMode = config.cookieMode ?? "ephemeral";
831
- const sessionCandidate = config.session;
832
- const providedSessionId = typeof config.sessionId === "string" ? config.sessionId.trim() : void 0;
833
- if (sessionCandidate && providedSessionId) {
834
- throw new RequestError("Provide either `session` or `sessionId`, not both.");
835
- }
836
- if (sessionCandidate) {
837
- if (!(sessionCandidate instanceof Session)) {
838
- throw new RequestError("`session` must be created via createSession()");
839
- }
840
- if (sessionCandidate.closed) {
841
- throw new RequestError("Session has been closed");
842
- }
843
- return {
844
- sessionId: sessionCandidate.id,
845
- cookieMode: "session",
846
- dropAfterRequest: false,
847
- defaults: sessionCandidate._defaultsRef()
848
- };
849
- }
850
- if (providedSessionId) {
851
- if (!providedSessionId) {
852
- throw new RequestError("sessionId must not be empty");
853
- }
854
- if (requestedMode === "ephemeral") {
855
- throw new RequestError("cookieMode 'ephemeral' cannot be combined with sessionId");
856
- }
857
- return {
858
- sessionId: providedSessionId,
859
- cookieMode: "session",
860
- dropAfterRequest: false
861
- };
862
- }
863
- if (requestedMode === "session") {
864
- throw new RequestError("cookieMode 'session' requires a session or sessionId");
865
- }
866
- return {
867
- sessionId: generateEphemeralSessionId(),
868
- cookieMode: "ephemeral",
869
- dropAfterRequest: true
870
- };
716
+ const requestedMode = config.cookieMode ?? "ephemeral";
717
+ const sessionCandidate = config.session;
718
+ const providedSessionId = typeof config.sessionId === "string" ? config.sessionId.trim() : void 0;
719
+ if (sessionCandidate && providedSessionId) throw new RequestError("Provide either `session` or `sessionId`, not both.");
720
+ if (sessionCandidate) {
721
+ if (!(sessionCandidate instanceof Session)) throw new RequestError("`session` must be created via createSession()");
722
+ if (sessionCandidate.closed) throw new RequestError("Session has been closed");
723
+ return {
724
+ sessionId: sessionCandidate.id,
725
+ cookieMode: "session",
726
+ dropAfterRequest: false,
727
+ defaults: sessionCandidate._defaultsRef()
728
+ };
729
+ }
730
+ if (providedSessionId) {
731
+ if (!providedSessionId) throw new RequestError("sessionId must not be empty");
732
+ if (requestedMode === "ephemeral") throw new RequestError("cookieMode 'ephemeral' cannot be combined with sessionId");
733
+ return {
734
+ sessionId: providedSessionId,
735
+ cookieMode: "session",
736
+ dropAfterRequest: false
737
+ };
738
+ }
739
+ if (requestedMode === "session") throw new RequestError("cookieMode 'session' requires a session or sessionId");
740
+ return {
741
+ sessionId: generateEphemeralSessionId(),
742
+ cookieMode: "ephemeral",
743
+ dropAfterRequest: true
744
+ };
871
745
  }
872
746
  function resolveTransportContext(config, sessionDefaults) {
873
- if (config.transport !== void 0) {
874
- if (!(config.transport instanceof Transport)) {
875
- throw new RequestError("`transport` must be created via createTransport()");
876
- }
877
- if (config.transport.closed) {
878
- throw new RequestError("Transport has been closed");
879
- }
880
- const hasProxy = config.proxy !== void 0;
881
- if (config.browser !== void 0 || config.os !== void 0 || config.emulation !== void 0 || hasProxy || config.insecure !== void 0) {
882
- throw new RequestError("`transport` cannot be combined with browser/os/emulation/proxy/insecure options");
883
- }
884
- return { transportId: config.transport.id };
885
- }
886
- if (sessionDefaults?.transportId) {
887
- if (config.emulation !== void 0) {
888
- throw new RequestError("Session emulation cannot be changed after creation");
889
- }
890
- if (config.browser !== void 0) {
891
- validateBrowserProfile(config.browser);
892
- const lockedBrowser = sessionDefaults.transportMode.kind === "custom" ? void 0 : sessionDefaults.transportMode.browser;
893
- if (config.browser !== lockedBrowser) {
894
- throw new RequestError("Session browser cannot be changed after creation");
895
- }
896
- }
897
- if (config.os !== void 0) {
898
- validateOperatingSystem(config.os);
899
- const lockedOs = sessionDefaults.transportMode.kind === "custom" ? void 0 : sessionDefaults.transportMode.os;
900
- if (config.os !== lockedOs) {
901
- throw new RequestError("Session operating system cannot be changed after creation");
902
- }
903
- }
904
- const initHasProxy = Object.hasOwn(config, "proxy");
905
- const requestedProxy = initHasProxy ? config.proxy : void 0;
906
- if (initHasProxy && requestedProxy !== void 0 && (sessionDefaults.proxy ?? null) !== (requestedProxy ?? null)) {
907
- throw new RequestError("Session proxy cannot be changed after creation");
908
- }
909
- if (config.insecure !== void 0) {
910
- const lockedInsecure = sessionDefaults.insecure ?? false;
911
- if (config.insecure !== lockedInsecure) {
912
- throw new RequestError("Session insecure setting cannot be changed after creation");
913
- }
914
- }
915
- return { transportId: sessionDefaults.transportId };
916
- }
917
- const resolved = {
918
- mode: resolveEmulationMode(config.browser, config.os, config.emulation)
919
- };
920
- if (config.proxy !== void 0) {
921
- resolved.proxy = config.proxy;
922
- }
923
- if (config.insecure !== void 0) {
924
- resolved.insecure = config.insecure;
925
- }
926
- return resolved;
747
+ if (config.transport !== void 0) {
748
+ if (!(config.transport instanceof Transport)) throw new RequestError("`transport` must be created via createTransport()");
749
+ if (config.transport.closed) throw new RequestError("Transport has been closed");
750
+ const hasProxy = config.proxy !== void 0;
751
+ if (config.browser !== void 0 || config.os !== void 0 || config.emulation !== void 0 || hasProxy || config.insecure !== void 0 || config.trustStore !== void 0) throw new RequestError("`transport` cannot be combined with browser/os/emulation/proxy/insecure/trustStore options");
752
+ return {
753
+ transportId: config.transport.id,
754
+ ...config.captureDiagnostics !== void 0 && { captureDiagnostics: config.captureDiagnostics }
755
+ };
756
+ }
757
+ if (sessionDefaults?.transportId) {
758
+ if (config.emulation !== void 0) throw new RequestError("Session emulation cannot be changed after creation");
759
+ if (config.browser !== void 0) {
760
+ validateBrowserProfile(config.browser);
761
+ const lockedBrowser = sessionDefaults.transportMode.kind === "custom" ? void 0 : sessionDefaults.transportMode.browser;
762
+ if (config.browser !== lockedBrowser) throw new RequestError("Session browser cannot be changed after creation");
763
+ }
764
+ if (config.os !== void 0) {
765
+ validateOperatingSystem(config.os);
766
+ const lockedOs = sessionDefaults.transportMode.kind === "custom" ? void 0 : sessionDefaults.transportMode.os;
767
+ if (config.os !== lockedOs) throw new RequestError("Session operating system cannot be changed after creation");
768
+ }
769
+ const initHasProxy = Object.hasOwn(config, "proxy");
770
+ const requestedProxy = initHasProxy ? config.proxy : void 0;
771
+ if (initHasProxy && requestedProxy !== void 0 && (sessionDefaults.proxy ?? null) !== (requestedProxy ?? null)) throw new RequestError("Session proxy cannot be changed after creation");
772
+ if (config.insecure !== void 0) {
773
+ const lockedInsecure = sessionDefaults.insecure ?? false;
774
+ if (config.insecure !== lockedInsecure) throw new RequestError("Session insecure setting cannot be changed after creation");
775
+ }
776
+ if (config.trustStore !== void 0) {
777
+ const lockedTrustStore = sessionDefaults.trustStore ?? DEFAULT_TRUST_STORE;
778
+ if (config.trustStore !== lockedTrustStore) throw new RequestError("Session trustStore setting cannot be changed after creation");
779
+ }
780
+ const captureDiagnostics = config.captureDiagnostics ?? sessionDefaults.captureDiagnostics;
781
+ return {
782
+ transportId: sessionDefaults.transportId,
783
+ ...captureDiagnostics !== void 0 && { captureDiagnostics }
784
+ };
785
+ }
786
+ const resolved = { mode: resolveEmulationMode(config.browser, config.os, config.emulation) };
787
+ if (config.proxy !== void 0) resolved.proxy = config.proxy;
788
+ if (config.insecure !== void 0) resolved.insecure = config.insecure;
789
+ resolved.trustStore = config.trustStore ?? DEFAULT_TRUST_STORE;
790
+ if (config.captureDiagnostics !== void 0) resolved.captureDiagnostics = config.captureDiagnostics;
791
+ return resolved;
927
792
  }
928
793
  function createAbortError(reason) {
929
- const fallbackMessage = typeof reason === "string" ? reason : "The operation was aborted";
930
- if (typeof DOMException !== "undefined" && reason instanceof DOMException) {
931
- return reason.name === "AbortError" ? reason : new DOMException(reason.message || fallbackMessage, "AbortError");
932
- }
933
- if (reason instanceof Error) {
934
- const error2 = new Error(reason.message);
935
- error2.name = "AbortError";
936
- error2.cause = reason;
937
- return error2;
938
- }
939
- if (typeof DOMException !== "undefined") {
940
- return new DOMException(fallbackMessage, "AbortError");
941
- }
942
- const error = new Error(fallbackMessage);
943
- error.name = "AbortError";
944
- return error;
794
+ const fallbackMessage = typeof reason === "string" ? reason : "The operation was aborted";
795
+ if (typeof DOMException !== "undefined" && reason instanceof DOMException) return reason.name === "AbortError" ? reason : new DOMException(reason.message || fallbackMessage, "AbortError");
796
+ if (reason instanceof Error) {
797
+ const error = new Error(reason.message);
798
+ error.name = "AbortError";
799
+ error.cause = reason;
800
+ return error;
801
+ }
802
+ if (typeof DOMException !== "undefined") return new DOMException(fallbackMessage, "AbortError");
803
+ const error = new Error(fallbackMessage);
804
+ error.name = "AbortError";
805
+ return error;
945
806
  }
946
807
  function isAbortError(error) {
947
- return Boolean(error) && typeof error.name === "string" && error.name === "AbortError";
808
+ return Boolean(error) && typeof error.name === "string" && error.name === "AbortError";
948
809
  }
949
- var REQUEST_ID_MAX = 2 ** 48;
950
- var requestIdCounter = Math.trunc(Number(process.hrtime.bigint() % BigInt(REQUEST_ID_MAX - 1))) + 1;
810
+ const REQUEST_ID_MAX = 2 ** 48;
811
+ let requestIdCounter = Math.trunc(Number(process.hrtime.bigint() % BigInt(REQUEST_ID_MAX - 1))) + 1;
951
812
  function generateRequestId() {
952
- requestIdCounter += 1;
953
- if (requestIdCounter >= REQUEST_ID_MAX) {
954
- requestIdCounter = 1;
955
- }
956
- return requestIdCounter;
813
+ requestIdCounter += 1;
814
+ if (requestIdCounter >= REQUEST_ID_MAX) requestIdCounter = 1;
815
+ return requestIdCounter;
957
816
  }
958
817
  function setupAbort(signal, cancelNative) {
959
- if (!signal) {
960
- return null;
961
- }
962
- if (signal.aborted) {
963
- cancelNative();
964
- throw createAbortError(signal.reason);
965
- }
966
- let onAbortListener;
967
- const promise = new Promise((_, reject) => {
968
- onAbortListener = () => {
969
- cancelNative();
970
- reject(createAbortError(signal.reason));
971
- };
972
- signal.addEventListener("abort", onAbortListener, { once: true });
973
- });
974
- const cleanup = () => {
975
- if (onAbortListener) {
976
- signal.removeEventListener("abort", onAbortListener);
977
- onAbortListener = void 0;
978
- }
979
- };
980
- return { promise, cleanup };
818
+ if (!signal) return null;
819
+ if (signal.aborted) {
820
+ cancelNative();
821
+ throw createAbortError(signal.reason);
822
+ }
823
+ let onAbortListener;
824
+ const promise = new Promise((_, reject) => {
825
+ onAbortListener = () => {
826
+ cancelNative();
827
+ reject(createAbortError(signal.reason));
828
+ };
829
+ signal.addEventListener("abort", onAbortListener, { once: true });
830
+ });
831
+ const cleanup = () => {
832
+ if (onAbortListener) {
833
+ signal.removeEventListener("abort", onAbortListener);
834
+ onAbortListener = void 0;
835
+ }
836
+ };
837
+ return {
838
+ promise,
839
+ cleanup
840
+ };
981
841
  }
982
842
  function coerceUrlInput(input) {
983
- if (input instanceof URL) {
984
- return input.href;
985
- }
986
- if (input.length === 0) {
987
- throw new RequestError("URL is required");
988
- }
989
- if (input.charCodeAt(0) > 32 && input.charCodeAt(input.length - 1) > 32) {
990
- return input;
991
- }
992
- const trimmed = input.trim();
993
- if (trimmed.length === 0) {
994
- throw new RequestError("URL is required");
995
- }
996
- return trimmed;
843
+ if (input instanceof URL) return input.href;
844
+ if (input.length === 0) throw new RequestError("URL is required");
845
+ if (input.charCodeAt(0) > 32 && input.charCodeAt(input.length - 1) > 32) return input;
846
+ const trimmed = input.trim();
847
+ if (trimmed.length === 0) throw new RequestError("URL is required");
848
+ return trimmed;
997
849
  }
998
850
  function isRequestLike(input) {
999
- if (!input || typeof input !== "object") {
1000
- return false;
1001
- }
1002
- if (typeof Request !== "undefined" && input instanceof Request) {
1003
- return true;
1004
- }
1005
- const candidate = input;
1006
- return typeof candidate.url === "string" && typeof candidate.method === "string" && typeof candidate.arrayBuffer === "function" && typeof candidate.redirect === "string";
851
+ if (!input || typeof input !== "object") return false;
852
+ if (typeof Request !== "undefined" && input instanceof Request) return true;
853
+ const candidate = input;
854
+ return typeof candidate.url === "string" && typeof candidate.method === "string" && typeof candidate.arrayBuffer === "function" && typeof candidate.redirect === "string";
1007
855
  }
1008
856
  async function resolveFetchArgs(input, init) {
1009
- if (!isRequestLike(input)) {
1010
- return { url: coerceUrlInput(input), init: init ?? {} };
1011
- }
1012
- const mergedInit = init ? { ...init } : {};
1013
- if (mergedInit.method === void 0) {
1014
- mergedInit.method = input.method;
1015
- }
1016
- if (mergedInit.headers === void 0) {
1017
- mergedInit.headers = input.headers;
1018
- }
1019
- if (mergedInit.redirect === void 0 && (input.redirect === "follow" || input.redirect === "manual" || input.redirect === "error")) {
1020
- mergedInit.redirect = input.redirect;
1021
- }
1022
- if (mergedInit.signal === void 0) {
1023
- mergedInit.signal = input.signal;
1024
- }
1025
- if (mergedInit.body === void 0 && input.body !== null) {
1026
- if (input.bodyUsed) {
1027
- throw new TypeError("Request body is already used");
1028
- }
1029
- mergedInit.body = Buffer.from(await input.arrayBuffer());
1030
- }
1031
- return { url: coerceUrlInput(input.url), init: mergedInit };
857
+ if (!isRequestLike(input)) return {
858
+ url: coerceUrlInput(input),
859
+ init: init ?? {}
860
+ };
861
+ const mergedInit = init ? { ...init } : {};
862
+ if (mergedInit.method === void 0) mergedInit.method = input.method;
863
+ if (mergedInit.headers === void 0) mergedInit.headers = input.headers;
864
+ if (mergedInit.redirect === void 0 && (input.redirect === "follow" || input.redirect === "manual" || input.redirect === "error")) mergedInit.redirect = input.redirect;
865
+ if (mergedInit.signal === void 0) mergedInit.signal = input.signal;
866
+ if (mergedInit.body === void 0 && input.body !== null) {
867
+ if (input.bodyUsed) throw new TypeError("Request body is already used");
868
+ mergedInit.body = Buffer.from(await input.arrayBuffer());
869
+ }
870
+ return {
871
+ url: coerceUrlInput(input.url),
872
+ init: mergedInit
873
+ };
1032
874
  }
1033
875
  function normalizeUrlForComparison(value) {
1034
- try {
1035
- return new URL(value).toString();
1036
- } catch {
1037
- return null;
1038
- }
876
+ try {
877
+ return new URL(value).toString();
878
+ } catch {
879
+ return null;
880
+ }
1039
881
  }
1040
882
  function validateRedirectMode(mode) {
1041
- if (mode === void 0 || mode === "follow" || mode === "manual" || mode === "error") {
1042
- return;
1043
- }
1044
- throw new RequestError(`Redirect mode '${mode}' is not supported`);
883
+ if (mode === void 0 || mode === "follow" || mode === "manual" || mode === "error") return;
884
+ throw new RequestError(`Redirect mode '${mode}' is not supported`);
1045
885
  }
1046
886
  async function serializeBody(body) {
1047
- if (body === null || body === void 0) {
1048
- return {};
1049
- }
1050
- if (typeof body === "string") {
1051
- return { body: Buffer.from(body, "utf8") };
1052
- }
1053
- if (Buffer.isBuffer(body)) {
1054
- return { body };
1055
- }
1056
- if (body instanceof URLSearchParams) {
1057
- return {
1058
- body: Buffer.from(body.toString(), "utf8"),
1059
- contentType: "application/x-www-form-urlencoded;charset=UTF-8"
1060
- };
1061
- }
1062
- if (body instanceof ArrayBuffer) {
1063
- return { body: Buffer.from(body) };
1064
- }
1065
- if (ArrayBuffer.isView(body)) {
1066
- return { body: Buffer.from(body.buffer, body.byteOffset, body.byteLength) };
1067
- }
1068
- if (typeof Blob !== "undefined" && body instanceof Blob) {
1069
- const buffer = Buffer.from(await body.arrayBuffer());
1070
- return { body: buffer, ...body.type ? { contentType: body.type } : {} };
1071
- }
1072
- if (typeof FormData !== "undefined" && body instanceof FormData) {
1073
- const encoded = new globalThis.Response(body);
1074
- const contentType = encoded.headers.get("content-type") ?? void 0;
1075
- const buffer = Buffer.from(await encoded.arrayBuffer());
1076
- return { body: buffer, ...contentType ? { contentType } : {} };
1077
- }
1078
- throw new TypeError(
1079
- "Unsupported body type; expected string, Buffer, ArrayBuffer, ArrayBufferView, URLSearchParams, Blob, or FormData"
1080
- );
887
+ if (body === null || body === void 0) return {};
888
+ if (typeof body === "string") return { body: Buffer.from(body, "utf8") };
889
+ if (Buffer.isBuffer(body)) return { body };
890
+ if (body instanceof URLSearchParams) return {
891
+ body: Buffer.from(body.toString(), "utf8"),
892
+ contentType: "application/x-www-form-urlencoded;charset=UTF-8"
893
+ };
894
+ if (body instanceof ArrayBuffer) return { body: Buffer.from(body) };
895
+ if (ArrayBuffer.isView(body)) return { body: Buffer.from(body.buffer, body.byteOffset, body.byteLength) };
896
+ if (typeof Blob !== "undefined" && body instanceof Blob) return {
897
+ body: Buffer.from(await body.arrayBuffer()),
898
+ ...body.type ? { contentType: body.type } : {}
899
+ };
900
+ if (typeof FormData !== "undefined" && body instanceof FormData) {
901
+ const encoded = new globalThis.Response(body);
902
+ const contentType = encoded.headers.get("content-type") ?? void 0;
903
+ return {
904
+ body: Buffer.from(await encoded.arrayBuffer()),
905
+ ...contentType ? { contentType } : {}
906
+ };
907
+ }
908
+ throw new TypeError("Unsupported body type; expected string, Buffer, ArrayBuffer, ArrayBufferView, URLSearchParams, Blob, or FormData");
1081
909
  }
1082
910
  function ensureMethod(method) {
1083
- if (method === void 0 || method.length === 0) {
1084
- return "GET";
1085
- }
1086
- switch (method) {
1087
- case "GET":
1088
- case "POST":
1089
- case "PUT":
1090
- case "DELETE":
1091
- case "PATCH":
1092
- case "HEAD":
1093
- case "OPTIONS":
1094
- return method;
1095
- }
1096
- const normalized = method.trim().toUpperCase();
1097
- return normalized.length > 0 ? normalized : "GET";
911
+ if (method === void 0 || method.length === 0) return "GET";
912
+ switch (method) {
913
+ case "GET":
914
+ case "POST":
915
+ case "PUT":
916
+ case "DELETE":
917
+ case "PATCH":
918
+ case "HEAD":
919
+ case "OPTIONS": return method;
920
+ }
921
+ const normalized = method.trim().toUpperCase();
922
+ return normalized.length > 0 ? normalized : "GET";
1098
923
  }
1099
924
  function ensureBodyAllowed(method, body) {
1100
- if (body === void 0) {
1101
- return;
1102
- }
1103
- if (method === "GET" || method === "HEAD") {
1104
- throw new RequestError(`Request with ${method} method cannot have a body`);
1105
- }
925
+ if (body === void 0) return;
926
+ if (method === "GET" || method === "HEAD") throw new RequestError(`Request with ${method} method cannot have a body`);
1106
927
  }
1107
928
  function validateBrowserProfile(browser) {
1108
- if (browser === void 0) {
1109
- return;
1110
- }
1111
- if (typeof browser !== "string" || browser.trim().length === 0) {
1112
- throw new RequestError("Browser profile must not be empty");
1113
- }
1114
- if (!getProfileSet().has(browser)) {
1115
- throw new RequestError(`Invalid browser profile: ${browser}. Available profiles: ${getProfiles().join(", ")}`);
1116
- }
929
+ if (browser === void 0) return;
930
+ if (typeof browser !== "string" || browser.trim().length === 0) throw new RequestError("Browser profile must not be empty");
931
+ if (!getProfileSet().has(browser)) throw new RequestError(`Invalid browser profile: ${browser}. Available profiles: ${getProfiles().join(", ")}`);
1117
932
  }
1118
933
  function validateOperatingSystem(os) {
1119
- if (os === void 0) {
1120
- return;
1121
- }
1122
- if (typeof os !== "string" || os.trim().length === 0) {
1123
- throw new RequestError("Operating system must not be empty");
1124
- }
1125
- if (!getOperatingSystemSet().has(os)) {
1126
- throw new RequestError(`Invalid operating system: ${os}. Available options: ${getOperatingSystems().join(", ")}`);
1127
- }
934
+ if (os === void 0) return;
935
+ if (typeof os !== "string" || os.trim().length === 0) throw new RequestError("Operating system must not be empty");
936
+ if (!getOperatingSystemSet().has(os)) throw new RequestError(`Invalid operating system: ${os}. Available options: ${getOperatingSystems().join(", ")}`);
1128
937
  }
1129
938
  function validateTimeout(timeout) {
1130
- if (timeout === void 0) {
1131
- return;
1132
- }
1133
- if (typeof timeout !== "number" || !Number.isFinite(timeout)) {
1134
- throw new RequestError("Timeout must be a finite number");
1135
- }
1136
- if (timeout < 0) {
1137
- throw new RequestError("Timeout must be 0 (no timeout) or a positive number");
1138
- }
939
+ if (timeout === void 0) return;
940
+ if (typeof timeout !== "number" || !Number.isFinite(timeout)) throw new RequestError("Timeout must be a finite number");
941
+ if (timeout < 0) throw new RequestError("Timeout must be 0 (no timeout) or a positive number");
942
+ }
943
+ function validateTrustStore(trustStore) {
944
+ if (trustStore === void 0) return;
945
+ if (trustStore !== "combined" && trustStore !== "mozilla" && trustStore !== "defaultPaths") throw new RequestError("trustStore must be one of: combined, mozilla, defaultPaths");
1139
946
  }
1140
947
  function validatePositiveNumber(value, label) {
1141
- if (typeof value !== "number" || !Number.isFinite(value)) {
1142
- throw new RequestError(`${label} must be a finite number`);
1143
- }
1144
- if (value <= 0) {
1145
- throw new RequestError(`${label} must be greater than 0`);
1146
- }
948
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new RequestError(`${label} must be a finite number`);
949
+ if (value <= 0) throw new RequestError(`${label} must be greater than 0`);
1147
950
  }
1148
951
  function validateNonNegativeInteger(value, label) {
1149
- if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
1150
- throw new RequestError(`${label} must be an integer`);
1151
- }
1152
- if (value < 0) {
1153
- throw new RequestError(`${label} must be greater than or equal to 0`);
1154
- }
952
+ if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) throw new RequestError(`${label} must be an integer`);
953
+ if (value < 0) throw new RequestError(`${label} must be greater than or equal to 0`);
1155
954
  }
1156
955
  function validatePositiveInteger(value, label) {
1157
- if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
1158
- throw new RequestError(`${label} must be an integer`);
1159
- }
1160
- if (value <= 0) {
1161
- throw new RequestError(`${label} must be greater than 0`);
1162
- }
956
+ if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) throw new RequestError(`${label} must be an integer`);
957
+ if (value <= 0) throw new RequestError(`${label} must be greater than 0`);
1163
958
  }
1164
959
  function validateIntegerInRange(value, min, max, label) {
1165
- validateNonNegativeInteger(value, label);
1166
- if (value < min || value > max) {
1167
- throw new RequestError(`${label} must be between ${min} and ${max}`);
1168
- }
1169
- }
1170
- var SUPPORTED_ALPN_PROTOCOLS = /* @__PURE__ */ new Set(["HTTP1", "HTTP2", "HTTP3"]);
1171
- var SUPPORTED_ALPS_PROTOCOLS = /* @__PURE__ */ new Set(["HTTP1", "HTTP2", "HTTP3"]);
1172
- var SUPPORTED_CERTIFICATE_COMPRESSION_ALGORITHMS = /* @__PURE__ */ new Set(["zlib", "brotli", "zstd"]);
1173
- var HTTP2_SETTING_IDS = /* @__PURE__ */ new Set([
1174
- "HeaderTableSize",
1175
- "EnablePush",
1176
- "MaxConcurrentStreams",
1177
- "InitialWindowSize",
1178
- "MaxFrameSize",
1179
- "MaxHeaderListSize",
1180
- "EnableConnectProtocol",
1181
- "NoRfc7540Priorities"
960
+ validateNonNegativeInteger(value, label);
961
+ if (value < min || value > max) throw new RequestError(`${label} must be between ${min} and ${max}`);
962
+ }
963
+ const SUPPORTED_ALPN_PROTOCOLS = new Set([
964
+ "HTTP1",
965
+ "HTTP2",
966
+ "HTTP3"
967
+ ]);
968
+ const SUPPORTED_ALPS_PROTOCOLS = new Set([
969
+ "HTTP1",
970
+ "HTTP2",
971
+ "HTTP3"
972
+ ]);
973
+ const SUPPORTED_CERTIFICATE_COMPRESSION_ALGORITHMS = new Set([
974
+ "zlib",
975
+ "brotli",
976
+ "zstd"
977
+ ]);
978
+ const HTTP2_SETTING_IDS = new Set([
979
+ "HeaderTableSize",
980
+ "EnablePush",
981
+ "MaxConcurrentStreams",
982
+ "InitialWindowSize",
983
+ "MaxFrameSize",
984
+ "MaxHeaderListSize",
985
+ "EnableConnectProtocol",
986
+ "NoRfc7540Priorities"
987
+ ]);
988
+ const HTTP2_PSEUDO_HEADER_IDS = new Set([
989
+ "Method",
990
+ "Scheme",
991
+ "Authority",
992
+ "Path",
993
+ "Protocol"
1182
994
  ]);
1183
- var HTTP2_PSEUDO_HEADER_IDS = /* @__PURE__ */ new Set(["Method", "Scheme", "Authority", "Path", "Protocol"]);
1184
- var STANDARD_HTTP2_SETTING_ID_VALUES = /* @__PURE__ */ new Set([1, 2, 3, 4, 5, 6, 8, 9]);
1185
- var MAX_HTTP2_EXPERIMENTAL_SETTING_ID = 15;
1186
- var TLS_VERSION_ALIASES = /* @__PURE__ */ new Map([
1187
- ["1.0", "1.0"],
1188
- ["1.1", "1.1"],
1189
- ["1.2", "1.2"],
1190
- ["1.3", "1.3"],
1191
- ["tls1.0", "1.0"],
1192
- ["tls1.1", "1.1"],
1193
- ["tls1.2", "1.2"],
1194
- ["tls1.3", "1.3"]
995
+ const STANDARD_HTTP2_SETTING_ID_VALUES = new Set([
996
+ 1,
997
+ 2,
998
+ 3,
999
+ 4,
1000
+ 5,
1001
+ 6,
1002
+ 8,
1003
+ 9
1004
+ ]);
1005
+ const MAX_HTTP2_EXPERIMENTAL_SETTING_ID = 15;
1006
+ const TLS_VERSION_ALIASES = new Map([
1007
+ ["1.0", "1.0"],
1008
+ ["1.1", "1.1"],
1009
+ ["1.2", "1.2"],
1010
+ ["1.3", "1.3"],
1011
+ ["tls1.0", "1.0"],
1012
+ ["tls1.1", "1.1"],
1013
+ ["tls1.2", "1.2"],
1014
+ ["tls1.3", "1.3"]
1195
1015
  ]);
1196
1016
  function isNonEmpty(value) {
1197
- for (const _ in value) return true;
1198
- return false;
1017
+ for (const _ in value) return true;
1018
+ return false;
1199
1019
  }
1200
1020
  function normalizeProtocolList(value, label, allowed) {
1201
- if (value === void 0) {
1202
- return void 0;
1203
- }
1204
- if (!Array.isArray(value)) {
1205
- throw new RequestError(`${label} must be an array`);
1206
- }
1207
- for (const protocol of value) {
1208
- if (!allowed.has(protocol)) {
1209
- throw new RequestError(`${label} values must be one of: HTTP1, HTTP2, HTTP3`);
1210
- }
1211
- }
1212
- return [...value];
1021
+ if (value === void 0) return;
1022
+ if (!Array.isArray(value)) throw new RequestError(`${label} must be an array`);
1023
+ for (const protocol of value) if (!allowed.has(protocol)) throw new RequestError(`${label} values must be one of: HTTP1, HTTP2, HTTP3`);
1024
+ return [...value];
1213
1025
  }
1214
1026
  function normalizeTlsVersion(value, label) {
1215
- if (value === void 0) {
1216
- return void 0;
1217
- }
1218
- if (typeof value !== "string") {
1219
- throw new RequestError(`${label} must be a string`);
1220
- }
1221
- const normalized = TLS_VERSION_ALIASES.get(value.trim().toLowerCase());
1222
- if (!normalized) {
1223
- throw new RequestError(`${label} must be one of: 1.0, 1.1, 1.2, 1.3`);
1224
- }
1225
- return normalized;
1027
+ if (value === void 0) return;
1028
+ if (typeof value !== "string") throw new RequestError(`${label} must be a string`);
1029
+ const normalized = TLS_VERSION_ALIASES.get(value.trim().toLowerCase());
1030
+ if (!normalized) throw new RequestError(`${label} must be one of: 1.0, 1.1, 1.2, 1.3`);
1031
+ return normalized;
1226
1032
  }
1227
1033
  function normalizeOrigHeaders(origHeaders) {
1228
- if (origHeaders === void 0) {
1229
- return void 0;
1230
- }
1231
- if (!Array.isArray(origHeaders)) {
1232
- throw new RequestError("emulation.origHeaders must be an array of strings");
1233
- }
1234
- const normalized = [];
1235
- const seen = /* @__PURE__ */ new Set();
1236
- for (const entry of origHeaders) {
1237
- if (typeof entry !== "string" || entry.trim().length === 0) {
1238
- throw new RequestError("emulation.origHeaders entries must be non-empty strings");
1239
- }
1240
- const trimmed = entry.trim();
1241
- const duplicateKey = trimmed.toLowerCase();
1242
- if (seen.has(duplicateKey)) {
1243
- throw new RequestError(`Duplicate emulation.origHeaders entry: ${trimmed}`);
1244
- }
1245
- seen.add(duplicateKey);
1246
- normalized.push(trimmed);
1247
- }
1248
- return normalized.length > 0 ? normalized : void 0;
1034
+ if (origHeaders === void 0) return;
1035
+ if (!Array.isArray(origHeaders)) throw new RequestError("emulation.origHeaders must be an array of strings");
1036
+ const normalized = [];
1037
+ const seen = /* @__PURE__ */ new Set();
1038
+ for (const entry of origHeaders) {
1039
+ if (typeof entry !== "string" || entry.trim().length === 0) throw new RequestError("emulation.origHeaders entries must be non-empty strings");
1040
+ const trimmed = entry.trim();
1041
+ const duplicateKey = trimmed.toLowerCase();
1042
+ if (seen.has(duplicateKey)) throw new RequestError(`Duplicate emulation.origHeaders entry: ${trimmed}`);
1043
+ seen.add(duplicateKey);
1044
+ normalized.push(trimmed);
1045
+ }
1046
+ return normalized.length > 0 ? normalized : void 0;
1249
1047
  }
1250
1048
  function normalizeCustomTlsOptions(options) {
1251
- if (options === void 0) {
1252
- return void 0;
1253
- }
1254
- const normalized = {};
1255
- const alpnProtocols = normalizeProtocolList(
1256
- options.alpnProtocols,
1257
- "emulation.tlsOptions.alpnProtocols",
1258
- SUPPORTED_ALPN_PROTOCOLS
1259
- );
1260
- if (alpnProtocols !== void 0) {
1261
- normalized.alpnProtocols = alpnProtocols;
1262
- }
1263
- const alpsProtocols = normalizeProtocolList(
1264
- options.alpsProtocols,
1265
- "emulation.tlsOptions.alpsProtocols",
1266
- SUPPORTED_ALPS_PROTOCOLS
1267
- );
1268
- if (alpsProtocols !== void 0) {
1269
- normalized.alpsProtocols = alpsProtocols;
1270
- }
1271
- const minTlsVersion = normalizeTlsVersion(options.minTlsVersion, "emulation.tlsOptions.minTlsVersion");
1272
- if (minTlsVersion !== void 0) {
1273
- normalized.minTlsVersion = minTlsVersion;
1274
- }
1275
- const maxTlsVersion = normalizeTlsVersion(options.maxTlsVersion, "emulation.tlsOptions.maxTlsVersion");
1276
- if (maxTlsVersion !== void 0) {
1277
- normalized.maxTlsVersion = maxTlsVersion;
1278
- }
1279
- if (options.alpsUseNewCodepoint !== void 0) {
1280
- normalized.alpsUseNewCodepoint = options.alpsUseNewCodepoint;
1281
- }
1282
- if (options.sessionTicket !== void 0) {
1283
- normalized.sessionTicket = options.sessionTicket;
1284
- }
1285
- if (options.preSharedKey !== void 0) {
1286
- normalized.preSharedKey = options.preSharedKey;
1287
- }
1288
- if (options.enableEchGrease !== void 0) {
1289
- normalized.enableEchGrease = options.enableEchGrease;
1290
- }
1291
- if (options.permuteExtensions !== void 0) {
1292
- normalized.permuteExtensions = options.permuteExtensions;
1293
- }
1294
- if (options.greaseEnabled !== void 0) {
1295
- normalized.greaseEnabled = options.greaseEnabled;
1296
- }
1297
- if (options.enableOcspStapling !== void 0) {
1298
- normalized.enableOcspStapling = options.enableOcspStapling;
1299
- }
1300
- if (options.enableSignedCertTimestamps !== void 0) {
1301
- normalized.enableSignedCertTimestamps = options.enableSignedCertTimestamps;
1302
- }
1303
- if (options.pskSkipSessionTicket !== void 0) {
1304
- normalized.pskSkipSessionTicket = options.pskSkipSessionTicket;
1305
- }
1306
- if (options.pskDheKe !== void 0) {
1307
- normalized.pskDheKe = options.pskDheKe;
1308
- }
1309
- if (options.renegotiation !== void 0) {
1310
- normalized.renegotiation = options.renegotiation;
1311
- }
1312
- if (options.aesHwOverride !== void 0) {
1313
- normalized.aesHwOverride = options.aesHwOverride;
1314
- }
1315
- if (options.preserveTls13CipherList !== void 0) {
1316
- normalized.preserveTls13CipherList = options.preserveTls13CipherList;
1317
- }
1318
- if (options.randomAesHwOverride !== void 0) {
1319
- normalized.randomAesHwOverride = options.randomAesHwOverride;
1320
- }
1321
- if (options.delegatedCredentials !== void 0) {
1322
- normalized.delegatedCredentials = options.delegatedCredentials;
1323
- }
1324
- if (options.curvesList !== void 0) {
1325
- normalized.curvesList = options.curvesList;
1326
- }
1327
- if (options.cipherList !== void 0) {
1328
- normalized.cipherList = options.cipherList;
1329
- }
1330
- if (options.sigalgsList !== void 0) {
1331
- normalized.sigalgsList = options.sigalgsList;
1332
- }
1333
- if (options.recordSizeLimit !== void 0) {
1334
- validateIntegerInRange(options.recordSizeLimit, 0, 65535, "emulation.tlsOptions.recordSizeLimit");
1335
- normalized.recordSizeLimit = options.recordSizeLimit;
1336
- }
1337
- if (options.keySharesLimit !== void 0) {
1338
- validateIntegerInRange(options.keySharesLimit, 0, 255, "emulation.tlsOptions.keySharesLimit");
1339
- normalized.keySharesLimit = options.keySharesLimit;
1340
- }
1341
- if (options.certificateCompressionAlgorithms !== void 0) {
1342
- if (!Array.isArray(options.certificateCompressionAlgorithms)) {
1343
- throw new RequestError("emulation.tlsOptions.certificateCompressionAlgorithms must be an array");
1344
- }
1345
- const algorithms = [];
1346
- const seen = /* @__PURE__ */ new Set();
1347
- for (const algorithm of options.certificateCompressionAlgorithms) {
1348
- if (!SUPPORTED_CERTIFICATE_COMPRESSION_ALGORITHMS.has(algorithm)) {
1349
- throw new RequestError(
1350
- "emulation.tlsOptions.certificateCompressionAlgorithms values must be one of: zlib, brotli, zstd"
1351
- );
1352
- }
1353
- if (seen.has(algorithm)) {
1354
- throw new RequestError(`Duplicate emulation.tlsOptions.certificateCompressionAlgorithms entry: ${algorithm}`);
1355
- }
1356
- seen.add(algorithm);
1357
- algorithms.push(algorithm);
1358
- }
1359
- normalized.certificateCompressionAlgorithms = algorithms;
1360
- }
1361
- if (options.extensionPermutation !== void 0) {
1362
- if (!Array.isArray(options.extensionPermutation)) {
1363
- throw new RequestError("emulation.tlsOptions.extensionPermutation must be an array");
1364
- }
1365
- const permutation = [];
1366
- const seen = /* @__PURE__ */ new Set();
1367
- for (const extensionId of options.extensionPermutation) {
1368
- validateIntegerInRange(extensionId, 0, 65535, "emulation.tlsOptions.extensionPermutation");
1369
- if (seen.has(extensionId)) {
1370
- throw new RequestError(`Duplicate emulation.tlsOptions.extensionPermutation entry: ${extensionId}`);
1371
- }
1372
- seen.add(extensionId);
1373
- permutation.push(extensionId);
1374
- }
1375
- normalized.extensionPermutation = permutation;
1376
- }
1377
- return isNonEmpty(normalized) ? normalized : void 0;
1049
+ if (options === void 0) return;
1050
+ const normalized = {};
1051
+ const alpnProtocols = normalizeProtocolList(options.alpnProtocols, "emulation.tlsOptions.alpnProtocols", SUPPORTED_ALPN_PROTOCOLS);
1052
+ if (alpnProtocols !== void 0) normalized.alpnProtocols = alpnProtocols;
1053
+ const alpsProtocols = normalizeProtocolList(options.alpsProtocols, "emulation.tlsOptions.alpsProtocols", SUPPORTED_ALPS_PROTOCOLS);
1054
+ if (alpsProtocols !== void 0) normalized.alpsProtocols = alpsProtocols;
1055
+ const minTlsVersion = normalizeTlsVersion(options.minTlsVersion, "emulation.tlsOptions.minTlsVersion");
1056
+ if (minTlsVersion !== void 0) normalized.minTlsVersion = minTlsVersion;
1057
+ const maxTlsVersion = normalizeTlsVersion(options.maxTlsVersion, "emulation.tlsOptions.maxTlsVersion");
1058
+ if (maxTlsVersion !== void 0) normalized.maxTlsVersion = maxTlsVersion;
1059
+ if (options.alpsUseNewCodepoint !== void 0) normalized.alpsUseNewCodepoint = options.alpsUseNewCodepoint;
1060
+ if (options.sessionTicket !== void 0) normalized.sessionTicket = options.sessionTicket;
1061
+ if (options.preSharedKey !== void 0) normalized.preSharedKey = options.preSharedKey;
1062
+ if (options.enableEchGrease !== void 0) normalized.enableEchGrease = options.enableEchGrease;
1063
+ if (options.permuteExtensions !== void 0) normalized.permuteExtensions = options.permuteExtensions;
1064
+ if (options.greaseEnabled !== void 0) normalized.greaseEnabled = options.greaseEnabled;
1065
+ if (options.enableOcspStapling !== void 0) normalized.enableOcspStapling = options.enableOcspStapling;
1066
+ if (options.enableSignedCertTimestamps !== void 0) normalized.enableSignedCertTimestamps = options.enableSignedCertTimestamps;
1067
+ if (options.pskSkipSessionTicket !== void 0) normalized.pskSkipSessionTicket = options.pskSkipSessionTicket;
1068
+ if (options.pskDheKe !== void 0) normalized.pskDheKe = options.pskDheKe;
1069
+ if (options.renegotiation !== void 0) normalized.renegotiation = options.renegotiation;
1070
+ if (options.aesHwOverride !== void 0) normalized.aesHwOverride = options.aesHwOverride;
1071
+ if (options.preserveTls13CipherList !== void 0) normalized.preserveTls13CipherList = options.preserveTls13CipherList;
1072
+ if (options.randomAesHwOverride !== void 0) normalized.randomAesHwOverride = options.randomAesHwOverride;
1073
+ if (options.delegatedCredentials !== void 0) normalized.delegatedCredentials = options.delegatedCredentials;
1074
+ if (options.curvesList !== void 0) normalized.curvesList = options.curvesList;
1075
+ if (options.cipherList !== void 0) normalized.cipherList = options.cipherList;
1076
+ if (options.sigalgsList !== void 0) normalized.sigalgsList = options.sigalgsList;
1077
+ if (options.recordSizeLimit !== void 0) {
1078
+ validateIntegerInRange(options.recordSizeLimit, 0, 65535, "emulation.tlsOptions.recordSizeLimit");
1079
+ normalized.recordSizeLimit = options.recordSizeLimit;
1080
+ }
1081
+ if (options.keySharesLimit !== void 0) {
1082
+ validateIntegerInRange(options.keySharesLimit, 0, 255, "emulation.tlsOptions.keySharesLimit");
1083
+ normalized.keySharesLimit = options.keySharesLimit;
1084
+ }
1085
+ if (options.certificateCompressionAlgorithms !== void 0) {
1086
+ if (!Array.isArray(options.certificateCompressionAlgorithms)) throw new RequestError("emulation.tlsOptions.certificateCompressionAlgorithms must be an array");
1087
+ const algorithms = [];
1088
+ const seen = /* @__PURE__ */ new Set();
1089
+ for (const algorithm of options.certificateCompressionAlgorithms) {
1090
+ if (!SUPPORTED_CERTIFICATE_COMPRESSION_ALGORITHMS.has(algorithm)) throw new RequestError("emulation.tlsOptions.certificateCompressionAlgorithms values must be one of: zlib, brotli, zstd");
1091
+ if (seen.has(algorithm)) throw new RequestError(`Duplicate emulation.tlsOptions.certificateCompressionAlgorithms entry: ${algorithm}`);
1092
+ seen.add(algorithm);
1093
+ algorithms.push(algorithm);
1094
+ }
1095
+ normalized.certificateCompressionAlgorithms = algorithms;
1096
+ }
1097
+ if (options.extensionPermutation !== void 0) {
1098
+ if (!Array.isArray(options.extensionPermutation)) throw new RequestError("emulation.tlsOptions.extensionPermutation must be an array");
1099
+ const permutation = [];
1100
+ const seen = /* @__PURE__ */ new Set();
1101
+ for (const extensionId of options.extensionPermutation) {
1102
+ validateIntegerInRange(extensionId, 0, 65535, "emulation.tlsOptions.extensionPermutation");
1103
+ if (seen.has(extensionId)) throw new RequestError(`Duplicate emulation.tlsOptions.extensionPermutation entry: ${extensionId}`);
1104
+ seen.add(extensionId);
1105
+ permutation.push(extensionId);
1106
+ }
1107
+ normalized.extensionPermutation = permutation;
1108
+ }
1109
+ return isNonEmpty(normalized) ? normalized : void 0;
1378
1110
  }
1379
1111
  function normalizeCustomHttp1Options(options) {
1380
- if (options === void 0) {
1381
- return void 0;
1382
- }
1383
- const normalized = {};
1384
- if (options.http09Responses !== void 0) {
1385
- normalized.http09Responses = options.http09Responses;
1386
- }
1387
- if (options.writev !== void 0) {
1388
- normalized.writev = options.writev;
1389
- }
1390
- if (options.ignoreInvalidHeadersInResponses !== void 0) {
1391
- normalized.ignoreInvalidHeadersInResponses = options.ignoreInvalidHeadersInResponses;
1392
- }
1393
- if (options.allowSpacesAfterHeaderNameInResponses !== void 0) {
1394
- normalized.allowSpacesAfterHeaderNameInResponses = options.allowSpacesAfterHeaderNameInResponses;
1395
- }
1396
- if (options.allowObsoleteMultilineHeadersInResponses !== void 0) {
1397
- normalized.allowObsoleteMultilineHeadersInResponses = options.allowObsoleteMultilineHeadersInResponses;
1398
- }
1399
- if (options.maxHeaders !== void 0) {
1400
- validateNonNegativeInteger(options.maxHeaders, "emulation.http1Options.maxHeaders");
1401
- normalized.maxHeaders = options.maxHeaders;
1402
- }
1403
- if (options.readBufExactSize !== void 0) {
1404
- validateNonNegativeInteger(options.readBufExactSize, "emulation.http1Options.readBufExactSize");
1405
- normalized.readBufExactSize = options.readBufExactSize;
1406
- }
1407
- if (options.maxBufSize !== void 0) {
1408
- validateNonNegativeInteger(options.maxBufSize, "emulation.http1Options.maxBufSize");
1409
- if (options.maxBufSize < 8192) {
1410
- throw new RequestError("emulation.http1Options.maxBufSize must be greater than or equal to 8192");
1411
- }
1412
- normalized.maxBufSize = options.maxBufSize;
1413
- }
1414
- if (normalized.readBufExactSize !== void 0 && normalized.maxBufSize !== void 0) {
1415
- throw new RequestError("emulation.http1Options.readBufExactSize and maxBufSize cannot both be set");
1416
- }
1417
- return isNonEmpty(normalized) ? normalized : void 0;
1112
+ if (options === void 0) return;
1113
+ const normalized = {};
1114
+ if (options.http09Responses !== void 0) normalized.http09Responses = options.http09Responses;
1115
+ if (options.writev !== void 0) normalized.writev = options.writev;
1116
+ if (options.ignoreInvalidHeadersInResponses !== void 0) normalized.ignoreInvalidHeadersInResponses = options.ignoreInvalidHeadersInResponses;
1117
+ if (options.allowSpacesAfterHeaderNameInResponses !== void 0) normalized.allowSpacesAfterHeaderNameInResponses = options.allowSpacesAfterHeaderNameInResponses;
1118
+ if (options.allowObsoleteMultilineHeadersInResponses !== void 0) normalized.allowObsoleteMultilineHeadersInResponses = options.allowObsoleteMultilineHeadersInResponses;
1119
+ if (options.maxHeaders !== void 0) {
1120
+ validateNonNegativeInteger(options.maxHeaders, "emulation.http1Options.maxHeaders");
1121
+ normalized.maxHeaders = options.maxHeaders;
1122
+ }
1123
+ if (options.readBufExactSize !== void 0) {
1124
+ validateNonNegativeInteger(options.readBufExactSize, "emulation.http1Options.readBufExactSize");
1125
+ normalized.readBufExactSize = options.readBufExactSize;
1126
+ }
1127
+ if (options.maxBufSize !== void 0) {
1128
+ validateNonNegativeInteger(options.maxBufSize, "emulation.http1Options.maxBufSize");
1129
+ if (options.maxBufSize < 8192) throw new RequestError("emulation.http1Options.maxBufSize must be greater than or equal to 8192");
1130
+ normalized.maxBufSize = options.maxBufSize;
1131
+ }
1132
+ if (normalized.readBufExactSize !== void 0 && normalized.maxBufSize !== void 0) throw new RequestError("emulation.http1Options.readBufExactSize and maxBufSize cannot both be set");
1133
+ return isNonEmpty(normalized) ? normalized : void 0;
1418
1134
  }
1419
1135
  function normalizeHttp2StreamDependency(dependency, label) {
1420
- if (!isPlainObject(dependency)) {
1421
- throw new RequestError(`${label} must be an object`);
1422
- }
1423
- validateIntegerInRange(dependency.dependencyId, 0, 2147483647, `${label}.dependencyId`);
1424
- validateIntegerInRange(dependency.weight, 0, 255, `${label}.weight`);
1425
- const normalized = {
1426
- dependencyId: dependency.dependencyId,
1427
- weight: dependency.weight
1428
- };
1429
- if (dependency.exclusive !== void 0) {
1430
- normalized.exclusive = dependency.exclusive;
1431
- }
1432
- return normalized;
1136
+ if (!isPlainObject(dependency)) throw new RequestError(`${label} must be an object`);
1137
+ validateIntegerInRange(dependency.dependencyId, 0, 2147483647, `${label}.dependencyId`);
1138
+ validateIntegerInRange(dependency.weight, 0, 255, `${label}.weight`);
1139
+ const normalized = {
1140
+ dependencyId: dependency.dependencyId,
1141
+ weight: dependency.weight
1142
+ };
1143
+ if (dependency.exclusive !== void 0) normalized.exclusive = dependency.exclusive;
1144
+ return normalized;
1433
1145
  }
1434
1146
  function normalizeCustomHttp2Options(options) {
1435
- if (options === void 0) {
1436
- return void 0;
1437
- }
1438
- const normalized = {};
1439
- if (options.adaptiveWindow !== void 0) {
1440
- normalized.adaptiveWindow = options.adaptiveWindow;
1441
- }
1442
- if (options.keepAliveWhileIdle !== void 0) {
1443
- normalized.keepAliveWhileIdle = options.keepAliveWhileIdle;
1444
- }
1445
- if (options.enablePush !== void 0) {
1446
- normalized.enablePush = options.enablePush;
1447
- }
1448
- if (options.enableConnectProtocol !== void 0) {
1449
- normalized.enableConnectProtocol = options.enableConnectProtocol;
1450
- }
1451
- if (options.noRfc7540Priorities !== void 0) {
1452
- normalized.noRfc7540Priorities = options.noRfc7540Priorities;
1453
- }
1454
- if (options.initialStreamId !== void 0) {
1455
- validateNonNegativeInteger(options.initialStreamId, "emulation.http2Options.initialStreamId");
1456
- normalized.initialStreamId = options.initialStreamId;
1457
- }
1458
- if (options.initialConnectionWindowSize !== void 0) {
1459
- validateNonNegativeInteger(
1460
- options.initialConnectionWindowSize,
1461
- "emulation.http2Options.initialConnectionWindowSize"
1462
- );
1463
- normalized.initialConnectionWindowSize = options.initialConnectionWindowSize;
1464
- }
1465
- if (options.initialWindowSize !== void 0) {
1466
- validateNonNegativeInteger(options.initialWindowSize, "emulation.http2Options.initialWindowSize");
1467
- normalized.initialWindowSize = options.initialWindowSize;
1468
- }
1469
- if (options.initialMaxSendStreams !== void 0) {
1470
- validateNonNegativeInteger(options.initialMaxSendStreams, "emulation.http2Options.initialMaxSendStreams");
1471
- normalized.initialMaxSendStreams = options.initialMaxSendStreams;
1472
- }
1473
- if (options.maxFrameSize !== void 0) {
1474
- validateNonNegativeInteger(options.maxFrameSize, "emulation.http2Options.maxFrameSize");
1475
- normalized.maxFrameSize = options.maxFrameSize;
1476
- }
1477
- if (options.keepAliveInterval !== void 0) {
1478
- validateNonNegativeInteger(options.keepAliveInterval, "emulation.http2Options.keepAliveInterval");
1479
- normalized.keepAliveInterval = options.keepAliveInterval;
1480
- }
1481
- if (options.keepAliveTimeout !== void 0) {
1482
- validateNonNegativeInteger(options.keepAliveTimeout, "emulation.http2Options.keepAliveTimeout");
1483
- normalized.keepAliveTimeout = options.keepAliveTimeout;
1484
- }
1485
- if (options.maxConcurrentResetStreams !== void 0) {
1486
- validateNonNegativeInteger(options.maxConcurrentResetStreams, "emulation.http2Options.maxConcurrentResetStreams");
1487
- normalized.maxConcurrentResetStreams = options.maxConcurrentResetStreams;
1488
- }
1489
- if (options.maxSendBufferSize !== void 0) {
1490
- validateNonNegativeInteger(options.maxSendBufferSize, "emulation.http2Options.maxSendBufferSize");
1491
- normalized.maxSendBufferSize = options.maxSendBufferSize;
1492
- }
1493
- if (options.maxConcurrentStreams !== void 0) {
1494
- validateNonNegativeInteger(options.maxConcurrentStreams, "emulation.http2Options.maxConcurrentStreams");
1495
- normalized.maxConcurrentStreams = options.maxConcurrentStreams;
1496
- }
1497
- if (options.maxHeaderListSize !== void 0) {
1498
- validateNonNegativeInteger(options.maxHeaderListSize, "emulation.http2Options.maxHeaderListSize");
1499
- normalized.maxHeaderListSize = options.maxHeaderListSize;
1500
- }
1501
- if (options.maxPendingAcceptResetStreams !== void 0) {
1502
- validateNonNegativeInteger(
1503
- options.maxPendingAcceptResetStreams,
1504
- "emulation.http2Options.maxPendingAcceptResetStreams"
1505
- );
1506
- normalized.maxPendingAcceptResetStreams = options.maxPendingAcceptResetStreams;
1507
- }
1508
- if (options.headerTableSize !== void 0) {
1509
- validateNonNegativeInteger(options.headerTableSize, "emulation.http2Options.headerTableSize");
1510
- normalized.headerTableSize = options.headerTableSize;
1511
- }
1512
- if (options.settingsOrder !== void 0) {
1513
- if (!Array.isArray(options.settingsOrder)) {
1514
- throw new RequestError("emulation.http2Options.settingsOrder must be an array");
1515
- }
1516
- const settingsOrder = [];
1517
- const seen = /* @__PURE__ */ new Set();
1518
- for (const settingId of options.settingsOrder) {
1519
- if (!HTTP2_SETTING_IDS.has(settingId)) {
1520
- throw new RequestError("emulation.http2Options.settingsOrder contains an unsupported setting id");
1521
- }
1522
- if (seen.has(settingId)) {
1523
- throw new RequestError(`Duplicate emulation.http2Options.settingsOrder entry: ${settingId}`);
1524
- }
1525
- seen.add(settingId);
1526
- settingsOrder.push(settingId);
1527
- }
1528
- normalized.settingsOrder = settingsOrder;
1529
- }
1530
- if (options.headersPseudoOrder !== void 0) {
1531
- if (!Array.isArray(options.headersPseudoOrder)) {
1532
- throw new RequestError("emulation.http2Options.headersPseudoOrder must be an array");
1533
- }
1534
- const headersPseudoOrder = [];
1535
- const seenPseudo = /* @__PURE__ */ new Set();
1536
- for (const pseudoId of options.headersPseudoOrder) {
1537
- if (!HTTP2_PSEUDO_HEADER_IDS.has(pseudoId)) {
1538
- throw new RequestError("emulation.http2Options.headersPseudoOrder contains an unsupported pseudo-header id");
1539
- }
1540
- if (seenPseudo.has(pseudoId)) {
1541
- throw new RequestError(`Duplicate emulation.http2Options.headersPseudoOrder entry: ${pseudoId}`);
1542
- }
1543
- seenPseudo.add(pseudoId);
1544
- headersPseudoOrder.push(pseudoId);
1545
- }
1546
- normalized.headersPseudoOrder = headersPseudoOrder;
1547
- }
1548
- if (options.headersStreamDependency !== void 0) {
1549
- normalized.headersStreamDependency = normalizeHttp2StreamDependency(
1550
- options.headersStreamDependency,
1551
- "emulation.http2Options.headersStreamDependency"
1552
- );
1553
- }
1554
- if (options.priorities !== void 0) {
1555
- if (!Array.isArray(options.priorities)) {
1556
- throw new RequestError("emulation.http2Options.priorities must be an array");
1557
- }
1558
- const priorities = [];
1559
- const seenStreamIds = /* @__PURE__ */ new Set();
1560
- for (const [index, priority] of options.priorities.entries()) {
1561
- if (!isPlainObject(priority)) {
1562
- throw new RequestError(`emulation.http2Options.priorities[${index}] must be an object`);
1563
- }
1564
- validatePositiveInteger(priority.streamId, `emulation.http2Options.priorities[${index}].streamId`);
1565
- if (seenStreamIds.has(priority.streamId)) {
1566
- throw new RequestError(`Duplicate emulation.http2Options.priorities streamId: ${priority.streamId}`);
1567
- }
1568
- seenStreamIds.add(priority.streamId);
1569
- priorities.push({
1570
- streamId: priority.streamId,
1571
- dependency: normalizeHttp2StreamDependency(
1572
- priority.dependency,
1573
- `emulation.http2Options.priorities[${index}].dependency`
1574
- )
1575
- });
1576
- }
1577
- normalized.priorities = priorities;
1578
- }
1579
- if (options.experimentalSettings !== void 0) {
1580
- if (!Array.isArray(options.experimentalSettings)) {
1581
- throw new RequestError("emulation.http2Options.experimentalSettings must be an array");
1582
- }
1583
- const experimentalSettings = [];
1584
- const seenIds = /* @__PURE__ */ new Set();
1585
- for (const [index, setting] of options.experimentalSettings.entries()) {
1586
- if (!isPlainObject(setting)) {
1587
- throw new RequestError(`emulation.http2Options.experimentalSettings[${index}] must be an object`);
1588
- }
1589
- validateIntegerInRange(
1590
- setting.id,
1591
- 1,
1592
- MAX_HTTP2_EXPERIMENTAL_SETTING_ID,
1593
- `emulation.http2Options.experimentalSettings[${index}].id`
1594
- );
1595
- if (STANDARD_HTTP2_SETTING_ID_VALUES.has(setting.id)) {
1596
- throw new RequestError(
1597
- `emulation.http2Options.experimentalSettings[${index}].id must not be a standard HTTP/2 setting id`
1598
- );
1599
- }
1600
- if (seenIds.has(setting.id)) {
1601
- throw new RequestError(`Duplicate emulation.http2Options.experimentalSettings id: ${setting.id}`);
1602
- }
1603
- seenIds.add(setting.id);
1604
- validateIntegerInRange(
1605
- setting.value,
1606
- 0,
1607
- 4294967295,
1608
- `emulation.http2Options.experimentalSettings[${index}].value`
1609
- );
1610
- experimentalSettings.push({
1611
- id: setting.id,
1612
- value: setting.value
1613
- });
1614
- }
1615
- normalized.experimentalSettings = experimentalSettings;
1616
- }
1617
- return isNonEmpty(normalized) ? normalized : void 0;
1147
+ if (options === void 0) return;
1148
+ const normalized = {};
1149
+ if (options.adaptiveWindow !== void 0) normalized.adaptiveWindow = options.adaptiveWindow;
1150
+ if (options.keepAliveWhileIdle !== void 0) normalized.keepAliveWhileIdle = options.keepAliveWhileIdle;
1151
+ if (options.enablePush !== void 0) normalized.enablePush = options.enablePush;
1152
+ if (options.enableConnectProtocol !== void 0) normalized.enableConnectProtocol = options.enableConnectProtocol;
1153
+ if (options.noRfc7540Priorities !== void 0) normalized.noRfc7540Priorities = options.noRfc7540Priorities;
1154
+ if (options.initialStreamId !== void 0) {
1155
+ validateNonNegativeInteger(options.initialStreamId, "emulation.http2Options.initialStreamId");
1156
+ normalized.initialStreamId = options.initialStreamId;
1157
+ }
1158
+ if (options.initialConnectionWindowSize !== void 0) {
1159
+ validateNonNegativeInteger(options.initialConnectionWindowSize, "emulation.http2Options.initialConnectionWindowSize");
1160
+ normalized.initialConnectionWindowSize = options.initialConnectionWindowSize;
1161
+ }
1162
+ if (options.initialWindowSize !== void 0) {
1163
+ validateNonNegativeInteger(options.initialWindowSize, "emulation.http2Options.initialWindowSize");
1164
+ normalized.initialWindowSize = options.initialWindowSize;
1165
+ }
1166
+ if (options.initialMaxSendStreams !== void 0) {
1167
+ validateNonNegativeInteger(options.initialMaxSendStreams, "emulation.http2Options.initialMaxSendStreams");
1168
+ normalized.initialMaxSendStreams = options.initialMaxSendStreams;
1169
+ }
1170
+ if (options.maxFrameSize !== void 0) {
1171
+ validateNonNegativeInteger(options.maxFrameSize, "emulation.http2Options.maxFrameSize");
1172
+ normalized.maxFrameSize = options.maxFrameSize;
1173
+ }
1174
+ if (options.keepAliveInterval !== void 0) {
1175
+ validateNonNegativeInteger(options.keepAliveInterval, "emulation.http2Options.keepAliveInterval");
1176
+ normalized.keepAliveInterval = options.keepAliveInterval;
1177
+ }
1178
+ if (options.keepAliveTimeout !== void 0) {
1179
+ validateNonNegativeInteger(options.keepAliveTimeout, "emulation.http2Options.keepAliveTimeout");
1180
+ normalized.keepAliveTimeout = options.keepAliveTimeout;
1181
+ }
1182
+ if (options.maxConcurrentResetStreams !== void 0) {
1183
+ validateNonNegativeInteger(options.maxConcurrentResetStreams, "emulation.http2Options.maxConcurrentResetStreams");
1184
+ normalized.maxConcurrentResetStreams = options.maxConcurrentResetStreams;
1185
+ }
1186
+ if (options.maxSendBufferSize !== void 0) {
1187
+ validateNonNegativeInteger(options.maxSendBufferSize, "emulation.http2Options.maxSendBufferSize");
1188
+ normalized.maxSendBufferSize = options.maxSendBufferSize;
1189
+ }
1190
+ if (options.maxConcurrentStreams !== void 0) {
1191
+ validateNonNegativeInteger(options.maxConcurrentStreams, "emulation.http2Options.maxConcurrentStreams");
1192
+ normalized.maxConcurrentStreams = options.maxConcurrentStreams;
1193
+ }
1194
+ if (options.maxHeaderListSize !== void 0) {
1195
+ validateNonNegativeInteger(options.maxHeaderListSize, "emulation.http2Options.maxHeaderListSize");
1196
+ normalized.maxHeaderListSize = options.maxHeaderListSize;
1197
+ }
1198
+ if (options.maxPendingAcceptResetStreams !== void 0) {
1199
+ validateNonNegativeInteger(options.maxPendingAcceptResetStreams, "emulation.http2Options.maxPendingAcceptResetStreams");
1200
+ normalized.maxPendingAcceptResetStreams = options.maxPendingAcceptResetStreams;
1201
+ }
1202
+ if (options.headerTableSize !== void 0) {
1203
+ validateNonNegativeInteger(options.headerTableSize, "emulation.http2Options.headerTableSize");
1204
+ normalized.headerTableSize = options.headerTableSize;
1205
+ }
1206
+ if (options.settingsOrder !== void 0) {
1207
+ if (!Array.isArray(options.settingsOrder)) throw new RequestError("emulation.http2Options.settingsOrder must be an array");
1208
+ const settingsOrder = [];
1209
+ const seen = /* @__PURE__ */ new Set();
1210
+ for (const settingId of options.settingsOrder) {
1211
+ if (!HTTP2_SETTING_IDS.has(settingId)) throw new RequestError("emulation.http2Options.settingsOrder contains an unsupported setting id");
1212
+ if (seen.has(settingId)) throw new RequestError(`Duplicate emulation.http2Options.settingsOrder entry: ${settingId}`);
1213
+ seen.add(settingId);
1214
+ settingsOrder.push(settingId);
1215
+ }
1216
+ normalized.settingsOrder = settingsOrder;
1217
+ }
1218
+ if (options.headersPseudoOrder !== void 0) {
1219
+ if (!Array.isArray(options.headersPseudoOrder)) throw new RequestError("emulation.http2Options.headersPseudoOrder must be an array");
1220
+ const headersPseudoOrder = [];
1221
+ const seenPseudo = /* @__PURE__ */ new Set();
1222
+ for (const pseudoId of options.headersPseudoOrder) {
1223
+ if (!HTTP2_PSEUDO_HEADER_IDS.has(pseudoId)) throw new RequestError("emulation.http2Options.headersPseudoOrder contains an unsupported pseudo-header id");
1224
+ if (seenPseudo.has(pseudoId)) throw new RequestError(`Duplicate emulation.http2Options.headersPseudoOrder entry: ${pseudoId}`);
1225
+ seenPseudo.add(pseudoId);
1226
+ headersPseudoOrder.push(pseudoId);
1227
+ }
1228
+ normalized.headersPseudoOrder = headersPseudoOrder;
1229
+ }
1230
+ if (options.headersStreamDependency !== void 0) normalized.headersStreamDependency = normalizeHttp2StreamDependency(options.headersStreamDependency, "emulation.http2Options.headersStreamDependency");
1231
+ if (options.priorities !== void 0) {
1232
+ if (!Array.isArray(options.priorities)) throw new RequestError("emulation.http2Options.priorities must be an array");
1233
+ const priorities = [];
1234
+ const seenStreamIds = /* @__PURE__ */ new Set();
1235
+ for (const [index, priority] of options.priorities.entries()) {
1236
+ if (!isPlainObject(priority)) throw new RequestError(`emulation.http2Options.priorities[${index}] must be an object`);
1237
+ validatePositiveInteger(priority.streamId, `emulation.http2Options.priorities[${index}].streamId`);
1238
+ if (seenStreamIds.has(priority.streamId)) throw new RequestError(`Duplicate emulation.http2Options.priorities streamId: ${priority.streamId}`);
1239
+ seenStreamIds.add(priority.streamId);
1240
+ priorities.push({
1241
+ streamId: priority.streamId,
1242
+ dependency: normalizeHttp2StreamDependency(priority.dependency, `emulation.http2Options.priorities[${index}].dependency`)
1243
+ });
1244
+ }
1245
+ normalized.priorities = priorities;
1246
+ }
1247
+ if (options.experimentalSettings !== void 0) {
1248
+ if (!Array.isArray(options.experimentalSettings)) throw new RequestError("emulation.http2Options.experimentalSettings must be an array");
1249
+ const experimentalSettings = [];
1250
+ const seenIds = /* @__PURE__ */ new Set();
1251
+ for (const [index, setting] of options.experimentalSettings.entries()) {
1252
+ if (!isPlainObject(setting)) throw new RequestError(`emulation.http2Options.experimentalSettings[${index}] must be an object`);
1253
+ validateIntegerInRange(setting.id, 1, MAX_HTTP2_EXPERIMENTAL_SETTING_ID, `emulation.http2Options.experimentalSettings[${index}].id`);
1254
+ if (STANDARD_HTTP2_SETTING_ID_VALUES.has(setting.id)) throw new RequestError(`emulation.http2Options.experimentalSettings[${index}].id must not be a standard HTTP/2 setting id`);
1255
+ if (seenIds.has(setting.id)) throw new RequestError(`Duplicate emulation.http2Options.experimentalSettings id: ${setting.id}`);
1256
+ seenIds.add(setting.id);
1257
+ validateIntegerInRange(setting.value, 0, 4294967295, `emulation.http2Options.experimentalSettings[${index}].value`);
1258
+ experimentalSettings.push({
1259
+ id: setting.id,
1260
+ value: setting.value
1261
+ });
1262
+ }
1263
+ normalized.experimentalSettings = experimentalSettings;
1264
+ }
1265
+ return isNonEmpty(normalized) ? normalized : void 0;
1618
1266
  }
1619
1267
  function normalizeCustomEmulationOptions(emulation, allowEmpty) {
1620
- if (emulation === void 0) {
1621
- return void 0;
1622
- }
1623
- if (!isPlainObject(emulation)) {
1624
- throw new RequestError("emulation must be an object");
1625
- }
1626
- const source = emulation;
1627
- const normalized = {};
1628
- const tlsOptions = normalizeCustomTlsOptions(source.tlsOptions);
1629
- if (tlsOptions !== void 0) {
1630
- normalized.tlsOptions = tlsOptions;
1631
- }
1632
- const http1Options = normalizeCustomHttp1Options(source.http1Options);
1633
- if (http1Options !== void 0) {
1634
- normalized.http1Options = http1Options;
1635
- }
1636
- const http2Options = normalizeCustomHttp2Options(source.http2Options);
1637
- if (http2Options !== void 0) {
1638
- normalized.http2Options = http2Options;
1639
- }
1640
- if (source.headers !== void 0) {
1641
- const headers = headersToTuples(source.headers);
1642
- if (headers.length > 0) {
1643
- normalized.headers = headers;
1644
- }
1645
- }
1646
- const origHeaders = normalizeOrigHeaders(source.origHeaders);
1647
- if (origHeaders !== void 0) {
1648
- normalized.origHeaders = origHeaders;
1649
- }
1650
- if (!allowEmpty && !isNonEmpty(normalized)) {
1651
- throw new RequestError(
1652
- "Standalone custom emulation requires at least one of tlsOptions, http1Options, http2Options, headers, or origHeaders"
1653
- );
1654
- }
1655
- return isNonEmpty(normalized) ? normalized : void 0;
1268
+ if (emulation === void 0) return;
1269
+ if (!isPlainObject(emulation)) throw new RequestError("emulation must be an object");
1270
+ const source = emulation;
1271
+ const normalized = {};
1272
+ const tlsOptions = normalizeCustomTlsOptions(source.tlsOptions);
1273
+ if (tlsOptions !== void 0) normalized.tlsOptions = tlsOptions;
1274
+ const http1Options = normalizeCustomHttp1Options(source.http1Options);
1275
+ if (http1Options !== void 0) normalized.http1Options = http1Options;
1276
+ const http2Options = normalizeCustomHttp2Options(source.http2Options);
1277
+ if (http2Options !== void 0) normalized.http2Options = http2Options;
1278
+ if (source.headers !== void 0) {
1279
+ const headers = headersToTuples(source.headers);
1280
+ if (headers.length > 0) normalized.headers = headers;
1281
+ }
1282
+ const origHeaders = normalizeOrigHeaders(source.origHeaders);
1283
+ if (origHeaders !== void 0) normalized.origHeaders = origHeaders;
1284
+ if (!allowEmpty && !isNonEmpty(normalized)) throw new RequestError("Standalone custom emulation requires at least one of tlsOptions, http1Options, http2Options, headers, or origHeaders");
1285
+ return isNonEmpty(normalized) ? normalized : void 0;
1656
1286
  }
1657
1287
  function serializeCustomEmulationOptions(emulation, allowEmpty) {
1658
- const normalized = normalizeCustomEmulationOptions(emulation, allowEmpty);
1659
- return normalized ? JSON.stringify(normalized) : void 0;
1288
+ const normalized = normalizeCustomEmulationOptions(emulation, allowEmpty);
1289
+ return normalized ? JSON.stringify(normalized) : void 0;
1660
1290
  }
1661
1291
  function resolveEmulationMode(browser, os, emulation) {
1662
- if (browser !== void 0) {
1663
- validateBrowserProfile(browser);
1664
- if (os !== void 0) {
1665
- validateOperatingSystem(os);
1666
- }
1667
- const emulationJson = serializeCustomEmulationOptions(emulation, true);
1668
- return {
1669
- kind: "preset",
1670
- browser,
1671
- os: os ?? DEFAULT_OS,
1672
- ...emulationJson !== void 0 && { emulationJson }
1673
- };
1674
- }
1675
- if (os !== void 0) {
1676
- validateOperatingSystem(os);
1677
- const emulationJson = serializeCustomEmulationOptions(emulation, true);
1678
- return {
1679
- kind: "preset",
1680
- browser: DEFAULT_BROWSER,
1681
- os,
1682
- ...emulationJson !== void 0 && { emulationJson }
1683
- };
1684
- }
1685
- if (emulation !== void 0) {
1686
- const emulationJson = serializeCustomEmulationOptions(emulation, false);
1687
- if (emulationJson === void 0) {
1688
- throw new RequestError(
1689
- "Standalone custom emulation requires at least one of tlsOptions, http1Options, http2Options, headers, or origHeaders"
1690
- );
1691
- }
1692
- return { kind: "custom", emulationJson };
1693
- }
1694
- return {
1695
- kind: "preset",
1696
- browser: DEFAULT_BROWSER,
1697
- os: DEFAULT_OS
1698
- };
1292
+ if (browser !== void 0) {
1293
+ validateBrowserProfile(browser);
1294
+ if (os !== void 0) validateOperatingSystem(os);
1295
+ const emulationJson = serializeCustomEmulationOptions(emulation, true);
1296
+ return {
1297
+ kind: "preset",
1298
+ browser,
1299
+ os: os ?? DEFAULT_OS,
1300
+ ...emulationJson !== void 0 && { emulationJson }
1301
+ };
1302
+ }
1303
+ if (os !== void 0) {
1304
+ validateOperatingSystem(os);
1305
+ const emulationJson = serializeCustomEmulationOptions(emulation, true);
1306
+ return {
1307
+ kind: "preset",
1308
+ browser: DEFAULT_BROWSER,
1309
+ os,
1310
+ ...emulationJson !== void 0 && { emulationJson }
1311
+ };
1312
+ }
1313
+ if (emulation !== void 0) {
1314
+ const emulationJson = serializeCustomEmulationOptions(emulation, false);
1315
+ if (emulationJson === void 0) throw new RequestError("Standalone custom emulation requires at least one of tlsOptions, http1Options, http2Options, headers, or origHeaders");
1316
+ return {
1317
+ kind: "custom",
1318
+ emulationJson
1319
+ };
1320
+ }
1321
+ return {
1322
+ kind: "preset",
1323
+ browser: DEFAULT_BROWSER,
1324
+ os: DEFAULT_OS
1325
+ };
1699
1326
  }
1700
1327
  function applyNativeEmulationMode(target, mode) {
1701
- if (mode.kind === "custom") {
1702
- target.emulationJson = mode.emulationJson;
1703
- return;
1704
- }
1705
- target.browser = mode.browser;
1706
- target.os = mode.os;
1707
- if (mode.emulationJson !== void 0) {
1708
- target.emulationJson = mode.emulationJson;
1709
- }
1328
+ if (mode.kind === "custom") {
1329
+ target.emulationJson = mode.emulationJson;
1330
+ return;
1331
+ }
1332
+ target.browser = mode.browser;
1333
+ target.os = mode.os;
1334
+ if (mode.emulationJson !== void 0) target.emulationJson = mode.emulationJson;
1710
1335
  }
1711
1336
  async function dispatchRequest(options, requestUrl, signal) {
1712
- if (!signal) {
1713
- const requestId2 = generateRequestId();
1714
- let payload2;
1715
- try {
1716
- payload2 = await nativeBinding.request(options, requestId2, false);
1717
- } catch (error) {
1718
- if (error instanceof RequestError) {
1719
- throw error;
1720
- }
1721
- throw new RequestError(String(error));
1722
- }
1723
- return new Response(payload2, requestUrl);
1724
- }
1725
- const requestId = generateRequestId();
1726
- const cancelNative = () => {
1727
- try {
1728
- nativeBinding.cancelRequest(requestId);
1729
- } catch {
1730
- }
1731
- };
1732
- const abortHandler = setupAbort(signal, cancelNative);
1733
- const pending = Promise.race([nativeBinding.request(options, requestId, true), abortHandler.promise]);
1734
- let payload;
1735
- try {
1736
- payload = await pending;
1737
- } catch (error) {
1738
- if (isAbortError(error)) {
1739
- throw error;
1740
- }
1741
- if (error instanceof RequestError) {
1742
- throw error;
1743
- }
1744
- throw new RequestError(String(error));
1745
- } finally {
1746
- abortHandler.cleanup();
1747
- }
1748
- return new Response(payload, requestUrl);
1749
- }
1337
+ if (!signal) {
1338
+ const requestId = generateRequestId();
1339
+ let payload;
1340
+ try {
1341
+ payload = await nativeBinding.request(options, requestId, false);
1342
+ } catch (error) {
1343
+ if (error instanceof RequestError) throw error;
1344
+ throw new RequestError(String(error));
1345
+ }
1346
+ return new Response(payload, requestUrl);
1347
+ }
1348
+ const requestId = generateRequestId();
1349
+ const cancelNative = () => {
1350
+ try {
1351
+ nativeBinding.cancelRequest(requestId);
1352
+ } catch {}
1353
+ };
1354
+ const abortHandler = setupAbort(signal, cancelNative);
1355
+ const pending = Promise.race([nativeBinding.request(options, requestId, true), abortHandler.promise]);
1356
+ let payload;
1357
+ try {
1358
+ payload = await pending;
1359
+ } catch (error) {
1360
+ if (isAbortError(error)) throw error;
1361
+ if (error instanceof RequestError) throw error;
1362
+ throw new RequestError(String(error));
1363
+ } finally {
1364
+ abortHandler.cleanup();
1365
+ }
1366
+ return new Response(payload, requestUrl);
1367
+ }
1368
+ /**
1369
+ * Fetch-compatible entry point that adds browser impersonation controls.
1370
+ *
1371
+ * **Important:** The default fetch path is isolated and non-persistent by design.
1372
+ * Each call uses an isolated request context, so cookies are not shared across calls.
1373
+ * Connection and TLS reuse behavior is handled by the native layer.
1374
+ *
1375
+ * **Use {@link createSession} or {@link withSession} if you need:**
1376
+ * - Cookie persistence across requests
1377
+ * - Shared session defaults across requests
1378
+ * - A single session context for multi-step flows
1379
+ *
1380
+ * **Concurrency:** The core is unthrottled by design. Callers are expected to implement
1381
+ * their own concurrency control (e.g., p-limit) if needed. Built-in throttling would
1382
+ * reduce performance for high-throughput workloads.
1383
+ *
1384
+ * @param input - Request URL (string or URL) or a Request object
1385
+ * @param init - Fetch-compatible init options
1386
+ *
1387
+ * @example
1388
+ * ```typescript
1389
+ * // Isolated request (no state persistence)
1390
+ * const response = await fetch('https://example.com');
1391
+ *
1392
+ * // For persistent cookies and connection reuse, use a session:
1393
+ * await withSession(async (session) => {
1394
+ * await session.fetch('https://example.com/login', { method: 'POST', body: loginData });
1395
+ * await session.fetch('https://example.com/protected'); // Cookies from login are sent
1396
+ * });
1397
+ * ```
1398
+ */
1750
1399
  async function fetch(input, init) {
1751
- const resolved = await resolveFetchArgs(input, init);
1752
- const url = resolved.url;
1753
- const config = resolved.init;
1754
- const sessionContext = resolveSessionContext(config);
1755
- const sessionDefaults = sessionContext.defaults;
1756
- validateRedirectMode(config.redirect);
1757
- if (config.timeout !== void 0) {
1758
- validateTimeout(config.timeout);
1759
- }
1760
- const method = ensureMethod(config.method);
1761
- const serializedBody = await serializeBody(config.body ?? null);
1762
- const body = serializedBody.body;
1763
- ensureBodyAllowed(method, body);
1764
- let headerTuples = mergeHeaderTuples(sessionDefaults?.defaultHeaders, config.headers);
1765
- if (serializedBody.contentType && !hasHeaderName(headerTuples, "content-type")) {
1766
- if (!headerTuples) {
1767
- headerTuples = [];
1768
- }
1769
- headerTuples.push(["Content-Type", serializedBody.contentType]);
1770
- }
1771
- const transport = resolveTransportContext(config, sessionDefaults);
1772
- const timeout = config.timeout ?? sessionDefaults?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS;
1773
- const requestOptions = {
1774
- url,
1775
- method,
1776
- sessionId: sessionContext.sessionId,
1777
- ephemeral: sessionContext.dropAfterRequest
1778
- };
1779
- if (body !== void 0) {
1780
- requestOptions.body = body;
1781
- }
1782
- if (transport.transportId) {
1783
- requestOptions.transportId = transport.transportId;
1784
- } else {
1785
- if (transport.mode !== void 0) {
1786
- applyNativeEmulationMode(requestOptions, transport.mode);
1787
- }
1788
- if (transport.proxy !== void 0) {
1789
- requestOptions.proxy = transport.proxy;
1790
- }
1791
- if (transport.insecure !== void 0) {
1792
- requestOptions.insecure = transport.insecure;
1793
- }
1794
- }
1795
- requestOptions.timeout = timeout;
1796
- if (config.redirect !== void 0) {
1797
- requestOptions.redirect = config.redirect;
1798
- }
1799
- if (config.disableDefaultHeaders !== void 0) {
1800
- requestOptions.disableDefaultHeaders = config.disableDefaultHeaders;
1801
- }
1802
- if (config.compress !== void 0) {
1803
- requestOptions.compress = config.compress;
1804
- }
1805
- if (headerTuples && headerTuples.length > 0) {
1806
- requestOptions.headers = headerTuples;
1807
- }
1808
- return dispatchRequest(requestOptions, url, config.signal ?? null);
1400
+ const resolved = await resolveFetchArgs(input, init);
1401
+ const url = resolved.url;
1402
+ const config = resolved.init;
1403
+ const sessionContext = resolveSessionContext(config);
1404
+ const sessionDefaults = sessionContext.defaults;
1405
+ validateRedirectMode(config.redirect);
1406
+ if (config.timeout !== void 0) validateTimeout(config.timeout);
1407
+ validateTrustStore(config.trustStore);
1408
+ const method = ensureMethod(config.method);
1409
+ const serializedBody = await serializeBody(config.body ?? null);
1410
+ const body = serializedBody.body;
1411
+ ensureBodyAllowed(method, body);
1412
+ let headerTuples = mergeHeaderTuples(sessionDefaults?.defaultHeaders, config.headers);
1413
+ if (serializedBody.contentType && !hasHeaderName(headerTuples, "content-type")) {
1414
+ if (!headerTuples) headerTuples = [];
1415
+ headerTuples.push(["Content-Type", serializedBody.contentType]);
1416
+ }
1417
+ const transport = resolveTransportContext(config, sessionDefaults);
1418
+ const timeout = config.timeout ?? sessionDefaults?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS;
1419
+ const requestOptions = {
1420
+ url,
1421
+ method,
1422
+ sessionId: sessionContext.sessionId,
1423
+ ephemeral: sessionContext.dropAfterRequest
1424
+ };
1425
+ if (body !== void 0) requestOptions.body = body;
1426
+ if (transport.captureDiagnostics !== void 0) requestOptions.captureDiagnostics = transport.captureDiagnostics;
1427
+ if (config.onRequestEvent !== void 0) requestOptions.onRequestEvent = config.onRequestEvent;
1428
+ if (transport.transportId) requestOptions.transportId = transport.transportId;
1429
+ else {
1430
+ if (transport.mode !== void 0) applyNativeEmulationMode(requestOptions, transport.mode);
1431
+ if (transport.proxy !== void 0) requestOptions.proxy = transport.proxy;
1432
+ if (transport.insecure !== void 0) requestOptions.insecure = transport.insecure;
1433
+ if (transport.trustStore !== void 0) requestOptions.trustStore = transport.trustStore;
1434
+ }
1435
+ requestOptions.timeout = timeout;
1436
+ if (config.redirect !== void 0) requestOptions.redirect = config.redirect;
1437
+ if (config.disableDefaultHeaders !== void 0) requestOptions.disableDefaultHeaders = config.disableDefaultHeaders;
1438
+ if (config.compress !== void 0) requestOptions.compress = config.compress;
1439
+ if (headerTuples && headerTuples.length > 0) requestOptions.headers = headerTuples;
1440
+ return dispatchRequest(requestOptions, url, config.signal ?? null);
1809
1441
  }
1810
1442
  async function createTransport(options) {
1811
- const mode = resolveEmulationMode(options?.browser, options?.os, options?.emulation);
1812
- if (options?.poolIdleTimeout !== void 0) {
1813
- validatePositiveNumber(options.poolIdleTimeout, "poolIdleTimeout");
1814
- }
1815
- if (options?.poolMaxIdlePerHost !== void 0) {
1816
- validateNonNegativeInteger(options.poolMaxIdlePerHost, "poolMaxIdlePerHost");
1817
- }
1818
- if (options?.poolMaxSize !== void 0) {
1819
- validatePositiveInteger(options.poolMaxSize, "poolMaxSize");
1820
- }
1821
- if (options?.connectTimeout !== void 0) {
1822
- validatePositiveNumber(options.connectTimeout, "connectTimeout");
1823
- }
1824
- if (options?.readTimeout !== void 0) {
1825
- validatePositiveNumber(options.readTimeout, "readTimeout");
1826
- }
1827
- try {
1828
- const transportOptions = {
1829
- ...options?.proxy !== void 0 && { proxy: options.proxy },
1830
- ...options?.insecure !== void 0 && { insecure: options.insecure },
1831
- ...options?.poolIdleTimeout !== void 0 && { poolIdleTimeout: options.poolIdleTimeout },
1832
- ...options?.poolMaxIdlePerHost !== void 0 && { poolMaxIdlePerHost: options.poolMaxIdlePerHost },
1833
- ...options?.poolMaxSize !== void 0 && { poolMaxSize: options.poolMaxSize },
1834
- ...options?.connectTimeout !== void 0 && { connectTimeout: options.connectTimeout },
1835
- ...options?.readTimeout !== void 0 && { readTimeout: options.readTimeout }
1836
- };
1837
- applyNativeEmulationMode(transportOptions, mode);
1838
- const id = nativeBinding.createTransport(transportOptions);
1839
- return new Transport(id);
1840
- } catch (error) {
1841
- throw new RequestError(String(error));
1842
- }
1443
+ const mode = resolveEmulationMode(options?.browser, options?.os, options?.emulation);
1444
+ validateTrustStore(options?.trustStore);
1445
+ if (options?.poolIdleTimeout !== void 0) validatePositiveNumber(options.poolIdleTimeout, "poolIdleTimeout");
1446
+ if (options?.poolMaxIdlePerHost !== void 0) validateNonNegativeInteger(options.poolMaxIdlePerHost, "poolMaxIdlePerHost");
1447
+ if (options?.poolMaxSize !== void 0) validatePositiveInteger(options.poolMaxSize, "poolMaxSize");
1448
+ if (options?.connectTimeout !== void 0) validatePositiveNumber(options.connectTimeout, "connectTimeout");
1449
+ if (options?.readTimeout !== void 0) validatePositiveNumber(options.readTimeout, "readTimeout");
1450
+ try {
1451
+ const transportOptions = {
1452
+ ...options?.proxy !== void 0 && { proxy: options.proxy },
1453
+ ...options?.insecure !== void 0 && { insecure: options.insecure },
1454
+ trustStore: options?.trustStore ?? DEFAULT_TRUST_STORE,
1455
+ ...options?.poolIdleTimeout !== void 0 && { poolIdleTimeout: options.poolIdleTimeout },
1456
+ ...options?.poolMaxIdlePerHost !== void 0 && { poolMaxIdlePerHost: options.poolMaxIdlePerHost },
1457
+ ...options?.poolMaxSize !== void 0 && { poolMaxSize: options.poolMaxSize },
1458
+ ...options?.connectTimeout !== void 0 && { connectTimeout: options.connectTimeout },
1459
+ ...options?.readTimeout !== void 0 && { readTimeout: options.readTimeout },
1460
+ ...options?.captureDiagnostics !== void 0 && { captureDiagnostics: options.captureDiagnostics }
1461
+ };
1462
+ applyNativeEmulationMode(transportOptions, mode);
1463
+ return new Transport(nativeBinding.createTransport(transportOptions));
1464
+ } catch (error) {
1465
+ throw new RequestError(String(error));
1466
+ }
1843
1467
  }
1844
1468
  async function createSession(options) {
1845
- const { sessionId, defaults } = normalizeSessionOptions(options);
1846
- let createdId;
1847
- let transportId;
1848
- try {
1849
- const transportOptions = {
1850
- ...defaults.proxy !== void 0 && { proxy: defaults.proxy },
1851
- ...defaults.insecure !== void 0 && { insecure: defaults.insecure }
1852
- };
1853
- applyNativeEmulationMode(transportOptions, defaults.transportMode);
1854
- transportId = nativeBinding.createTransport(transportOptions);
1855
- } catch (error) {
1856
- throw new RequestError(String(error));
1857
- }
1858
- try {
1859
- createdId = nativeBinding.createSession({
1860
- sessionId
1861
- });
1862
- } catch (error) {
1863
- try {
1864
- nativeBinding.dropTransport(transportId);
1865
- } catch {
1866
- }
1867
- throw new RequestError(String(error));
1868
- }
1869
- defaults.transportId = transportId;
1870
- defaults.ownsTransport = true;
1871
- return new Session(createdId, defaults);
1469
+ const { sessionId, defaults } = normalizeSessionOptions(options);
1470
+ let createdId;
1471
+ let transportId;
1472
+ try {
1473
+ const transportOptions = {
1474
+ ...defaults.proxy !== void 0 && { proxy: defaults.proxy },
1475
+ ...defaults.insecure !== void 0 && { insecure: defaults.insecure },
1476
+ trustStore: defaults.trustStore ?? DEFAULT_TRUST_STORE,
1477
+ ...defaults.captureDiagnostics !== void 0 && { captureDiagnostics: defaults.captureDiagnostics }
1478
+ };
1479
+ applyNativeEmulationMode(transportOptions, defaults.transportMode);
1480
+ transportId = nativeBinding.createTransport(transportOptions);
1481
+ } catch (error) {
1482
+ throw new RequestError(String(error));
1483
+ }
1484
+ try {
1485
+ createdId = nativeBinding.createSession({ sessionId });
1486
+ } catch (error) {
1487
+ try {
1488
+ nativeBinding.dropTransport(transportId);
1489
+ } catch {}
1490
+ throw new RequestError(String(error));
1491
+ }
1492
+ defaults.transportId = transportId;
1493
+ defaults.ownsTransport = true;
1494
+ return new Session(createdId, defaults);
1872
1495
  }
1873
1496
  async function withSession(fn, options) {
1874
- const session = await createSession(options);
1875
- try {
1876
- return await fn(session);
1877
- } finally {
1878
- await session.close();
1879
- }
1880
- }
1497
+ const session = await createSession(options);
1498
+ try {
1499
+ return await fn(session);
1500
+ } finally {
1501
+ await session.close();
1502
+ }
1503
+ }
1504
+ /**
1505
+ * @deprecated Use {@link fetch} instead.
1506
+ */
1881
1507
  async function request(options) {
1882
- if (!options.url) {
1883
- throw new RequestError("URL is required");
1884
- }
1885
- const { url, ...rest } = options;
1886
- const init = {};
1887
- const legacy = rest;
1888
- if (rest.method !== void 0) {
1889
- init.method = rest.method;
1890
- }
1891
- if (rest.headers !== void 0) {
1892
- init.headers = rest.headers;
1893
- }
1894
- if (rest.body !== void 0) {
1895
- init.body = rest.body;
1896
- }
1897
- if (rest.browser !== void 0) {
1898
- init.browser = rest.browser;
1899
- }
1900
- if (rest.os !== void 0) {
1901
- init.os = rest.os;
1902
- }
1903
- if (rest.emulation !== void 0) {
1904
- init.emulation = rest.emulation;
1905
- }
1906
- if (rest.proxy !== void 0) {
1907
- init.proxy = rest.proxy;
1908
- }
1909
- if (rest.timeout !== void 0) {
1910
- init.timeout = rest.timeout;
1911
- }
1912
- if (rest.sessionId !== void 0) {
1913
- init.sessionId = rest.sessionId;
1914
- }
1915
- if (rest.transport !== void 0) {
1916
- init.transport = rest.transport;
1917
- }
1918
- if (rest.insecure !== void 0) {
1919
- init.insecure = rest.insecure;
1920
- }
1921
- if (rest.disableDefaultHeaders !== void 0) {
1922
- init.disableDefaultHeaders = rest.disableDefaultHeaders;
1923
- }
1924
- if (rest.redirect !== void 0) {
1925
- init.redirect = rest.redirect;
1926
- }
1927
- if (legacy.signal !== void 0) {
1928
- init.signal = legacy.signal;
1929
- }
1930
- if (legacy.session !== void 0) {
1931
- init.session = legacy.session;
1932
- }
1933
- if (legacy.cookieMode !== void 0) {
1934
- init.cookieMode = legacy.cookieMode;
1935
- } else if (legacy.ephemeral === true) {
1936
- init.cookieMode = "ephemeral";
1937
- }
1938
- return fetch(url, init);
1939
- }
1508
+ if (!options.url) throw new RequestError("URL is required");
1509
+ const { url, ...rest } = options;
1510
+ const init = {};
1511
+ const legacy = rest;
1512
+ if (rest.method !== void 0) init.method = rest.method;
1513
+ if (rest.headers !== void 0) init.headers = rest.headers;
1514
+ if (rest.body !== void 0) init.body = rest.body;
1515
+ if (rest.browser !== void 0) init.browser = rest.browser;
1516
+ if (rest.os !== void 0) init.os = rest.os;
1517
+ if (rest.emulation !== void 0) init.emulation = rest.emulation;
1518
+ if (rest.proxy !== void 0) init.proxy = rest.proxy;
1519
+ if (rest.timeout !== void 0) init.timeout = rest.timeout;
1520
+ if (rest.sessionId !== void 0) init.sessionId = rest.sessionId;
1521
+ if (rest.transport !== void 0) init.transport = rest.transport;
1522
+ if (rest.insecure !== void 0) init.insecure = rest.insecure;
1523
+ if (rest.trustStore !== void 0) init.trustStore = rest.trustStore;
1524
+ if (rest.disableDefaultHeaders !== void 0) init.disableDefaultHeaders = rest.disableDefaultHeaders;
1525
+ if (rest.redirect !== void 0) init.redirect = rest.redirect;
1526
+ if (legacy.signal !== void 0) init.signal = legacy.signal;
1527
+ if (legacy.session !== void 0) init.session = legacy.session;
1528
+ if (legacy.cookieMode !== void 0) init.cookieMode = legacy.cookieMode;
1529
+ else if (legacy.ephemeral === true) init.cookieMode = "ephemeral";
1530
+ if (legacy.onRequestEvent !== void 0) init.onRequestEvent = legacy.onRequestEvent;
1531
+ if (legacy.captureDiagnostics !== void 0) init.captureDiagnostics = legacy.captureDiagnostics;
1532
+ return fetch(url, init);
1533
+ }
1534
+ /**
1535
+ * Get list of available browser profiles
1536
+ *
1537
+ * @returns Array of browser profile names
1538
+ *
1539
+ * @example
1540
+ * ```typescript
1541
+ * import { getProfiles } from 'wreq-js';
1542
+ *
1543
+ * const profiles = getProfiles();
1544
+ * console.log(profiles); // ['chrome_131', 'chrome_142', 'firefox_135', 'safari_18', ...]
1545
+ * ```
1546
+ */
1940
1547
  function getProfiles() {
1941
- if (!cachedProfiles) {
1942
- cachedProfiles = nativeBinding.getProfiles();
1943
- }
1944
- return cachedProfiles;
1548
+ if (!cachedProfiles) cachedProfiles = nativeBinding.getProfiles();
1549
+ return cachedProfiles;
1945
1550
  }
1946
1551
  function getProfileSet() {
1947
- if (!cachedProfileSet) {
1948
- cachedProfileSet = new Set(getProfiles());
1949
- }
1950
- return cachedProfileSet;
1951
- }
1552
+ if (!cachedProfileSet) cachedProfileSet = new Set(getProfiles());
1553
+ return cachedProfileSet;
1554
+ }
1555
+ /**
1556
+ * Get list of supported operating systems for emulation.
1557
+ *
1558
+ * @returns Array of operating system identifiers
1559
+ */
1952
1560
  function getOperatingSystems() {
1953
- if (!cachedOperatingSystems) {
1954
- const fromNative = nativeBinding.getOperatingSystems?.();
1955
- cachedOperatingSystems = fromNative && fromNative.length > 0 ? fromNative : [...SUPPORTED_OSES];
1956
- }
1957
- return cachedOperatingSystems;
1561
+ if (!cachedOperatingSystems) {
1562
+ const fromNative = nativeBinding.getOperatingSystems?.();
1563
+ cachedOperatingSystems = fromNative && fromNative.length > 0 ? fromNative : [...SUPPORTED_OSES];
1564
+ }
1565
+ return cachedOperatingSystems;
1958
1566
  }
1959
1567
  function getOperatingSystemSet() {
1960
- if (!cachedOperatingSystemSet) {
1961
- cachedOperatingSystemSet = new Set(getOperatingSystems());
1962
- }
1963
- return cachedOperatingSystemSet;
1568
+ if (!cachedOperatingSystemSet) cachedOperatingSystemSet = new Set(getOperatingSystems());
1569
+ return cachedOperatingSystemSet;
1964
1570
  }
1571
+ /**
1572
+ * Convenience helper for GET requests using {@link fetch}.
1573
+ */
1965
1574
  async function get(url, init) {
1966
- const config = {};
1967
- if (init) {
1968
- Object.assign(config, init);
1969
- }
1970
- config.method = "GET";
1971
- return fetch(url, config);
1972
- }
1575
+ const config = {};
1576
+ if (init) Object.assign(config, init);
1577
+ config.method = "GET";
1578
+ return fetch(url, config);
1579
+ }
1580
+ /**
1581
+ * Convenience helper for POST requests using {@link fetch}.
1582
+ */
1973
1583
  async function post(url, body, init) {
1974
- const config = {};
1975
- if (init) {
1976
- Object.assign(config, init);
1977
- }
1978
- config.method = "POST";
1979
- if (body !== void 0) {
1980
- config.body = body;
1981
- }
1982
- return fetch(url, config);
1584
+ const config = {};
1585
+ if (init) Object.assign(config, init);
1586
+ config.method = "POST";
1587
+ if (body !== void 0) config.body = body;
1588
+ return fetch(url, config);
1983
1589
  }
1984
1590
  function normalizeWebSocketUrl(url) {
1985
- const normalized = String(url).trim();
1986
- if (!normalized) {
1987
- throw new RequestError("URL is required");
1988
- }
1989
- let parsed;
1990
- try {
1991
- parsed = new URL(normalized);
1992
- } catch (error) {
1993
- throw new RequestError(String(error));
1994
- }
1995
- if (parsed.hash) {
1996
- throw new RequestError("WebSocket URL must not include a hash fragment");
1997
- }
1998
- if (parsed.protocol === "http:") {
1999
- parsed.protocol = "ws:";
2000
- } else if (parsed.protocol === "https:") {
2001
- parsed.protocol = "wss:";
2002
- }
2003
- if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
2004
- throw new RequestError("expected a ws: or wss: url");
2005
- }
2006
- return parsed.toString();
1591
+ const normalized = String(url).trim();
1592
+ if (!normalized) throw new RequestError("URL is required");
1593
+ let parsed;
1594
+ try {
1595
+ parsed = new URL(normalized);
1596
+ } catch (error) {
1597
+ throw new RequestError(String(error));
1598
+ }
1599
+ if (parsed.hash) throw new RequestError("WebSocket URL must not include a hash fragment");
1600
+ if (parsed.protocol === "http:") parsed.protocol = "ws:";
1601
+ else if (parsed.protocol === "https:") parsed.protocol = "wss:";
1602
+ if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") throw new RequestError("expected a ws: or wss: url");
1603
+ return parsed.toString();
2007
1604
  }
2008
1605
  function validateWebSocketProtocols(protocols) {
2009
- if (protocols === void 0) {
2010
- return;
2011
- }
2012
- const protocolList = typeof protocols === "string" ? [protocols] : protocols;
2013
- const seen = /* @__PURE__ */ new Set();
2014
- const validToken = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
2015
- for (const protocol of protocolList) {
2016
- if (typeof protocol !== "string" || protocol.length === 0) {
2017
- throw new RequestError("WebSocket protocol values must be non-empty strings");
2018
- }
2019
- if (!validToken.test(protocol)) {
2020
- throw new RequestError(`Invalid WebSocket protocol value: ${protocol}`);
2021
- }
2022
- if (seen.has(protocol)) {
2023
- throw new RequestError(`Duplicate WebSocket protocol: ${protocol}`);
2024
- }
2025
- seen.add(protocol);
2026
- }
1606
+ if (protocols === void 0) return;
1607
+ const protocolList = typeof protocols === "string" ? [protocols] : protocols;
1608
+ const seen = /* @__PURE__ */ new Set();
1609
+ const validToken = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
1610
+ for (const protocol of protocolList) {
1611
+ if (typeof protocol !== "string" || protocol.length === 0) throw new RequestError("WebSocket protocol values must be non-empty strings");
1612
+ if (!validToken.test(protocol)) throw new RequestError(`Invalid WebSocket protocol value: ${protocol}`);
1613
+ if (seen.has(protocol)) throw new RequestError(`Duplicate WebSocket protocol: ${protocol}`);
1614
+ seen.add(protocol);
1615
+ }
1616
+ }
1617
+ function normalizeWebSocketSizeOption(value, label) {
1618
+ if (value === void 0) return;
1619
+ if (!Number.isSafeInteger(value) || value <= 0) throw new RequestError(`${label} must be a positive safe integer`);
1620
+ return value;
2027
1621
  }
2028
1622
  function normalizeStandaloneWebSocketOptions(options) {
2029
- const normalized = {};
2030
- if (!options) {
2031
- return normalized;
2032
- }
2033
- if (options.browser !== void 0) {
2034
- normalized.browser = options.browser;
2035
- }
2036
- if (options.os !== void 0) {
2037
- normalized.os = options.os;
2038
- }
2039
- if (options.emulation !== void 0) {
2040
- normalized.emulation = options.emulation;
2041
- }
2042
- if (options.headers !== void 0) {
2043
- normalized.headers = options.headers;
2044
- }
2045
- if (options.proxy !== void 0) {
2046
- normalized.proxy = options.proxy;
2047
- }
2048
- if (options.protocols !== void 0) {
2049
- normalized.protocols = options.protocols;
2050
- }
2051
- if (options.binaryType !== void 0) {
2052
- if (options.binaryType !== "nodebuffer" && options.binaryType !== "arraybuffer" && options.binaryType !== "blob") {
2053
- throw new RequestError("binaryType must be one of: 'nodebuffer', 'arraybuffer', 'blob'");
2054
- }
2055
- normalized.binaryType = options.binaryType;
2056
- }
2057
- return normalized;
1623
+ const normalized = {};
1624
+ if (!options) return normalized;
1625
+ if (options.browser !== void 0) normalized.browser = options.browser;
1626
+ if (options.os !== void 0) normalized.os = options.os;
1627
+ if (options.emulation !== void 0) normalized.emulation = options.emulation;
1628
+ if (options.headers !== void 0) normalized.headers = options.headers;
1629
+ if (options.proxy !== void 0) normalized.proxy = options.proxy;
1630
+ if (options.protocols !== void 0) normalized.protocols = options.protocols;
1631
+ if (options.maxFrameSize !== void 0) {
1632
+ const maxFrameSize = normalizeWebSocketSizeOption(options.maxFrameSize, "maxFrameSize");
1633
+ if (maxFrameSize !== void 0) normalized.maxFrameSize = maxFrameSize;
1634
+ }
1635
+ if (options.maxMessageSize !== void 0) {
1636
+ const maxMessageSize = normalizeWebSocketSizeOption(options.maxMessageSize, "maxMessageSize");
1637
+ if (maxMessageSize !== void 0) normalized.maxMessageSize = maxMessageSize;
1638
+ }
1639
+ if (options.binaryType !== void 0) {
1640
+ if (options.binaryType !== "nodebuffer" && options.binaryType !== "arraybuffer" && options.binaryType !== "blob") throw new RequestError("binaryType must be one of: 'nodebuffer', 'arraybuffer', 'blob'");
1641
+ normalized.binaryType = options.binaryType;
1642
+ }
1643
+ return normalized;
2058
1644
  }
2059
1645
  function normalizeSessionWebSocketOptions(options) {
2060
- const normalized = {};
2061
- if (!options) {
2062
- return normalized;
2063
- }
2064
- const optionsWithOverrides = options;
2065
- if (optionsWithOverrides.browser !== void 0) {
2066
- throw new RequestError(
2067
- "`browser` is not supported in session.websocket(); the session controls browser emulation."
2068
- );
2069
- }
2070
- if (optionsWithOverrides.os !== void 0) {
2071
- throw new RequestError("`os` is not supported in session.websocket(); the session controls OS emulation.");
2072
- }
2073
- if (optionsWithOverrides.emulation !== void 0) {
2074
- throw new RequestError(
2075
- "`emulation` is not supported in session.websocket(); the session transport controls emulation."
2076
- );
2077
- }
2078
- if (optionsWithOverrides.proxy !== void 0) {
2079
- throw new RequestError("`proxy` is not supported in session.websocket(); the session transport controls proxying.");
2080
- }
2081
- if (options.headers !== void 0) {
2082
- normalized.headers = options.headers;
2083
- }
2084
- if (options.protocols !== void 0) {
2085
- normalized.protocols = options.protocols;
2086
- }
2087
- if (options.binaryType !== void 0) {
2088
- if (options.binaryType !== "nodebuffer" && options.binaryType !== "arraybuffer" && options.binaryType !== "blob") {
2089
- throw new RequestError("binaryType must be one of: 'nodebuffer', 'arraybuffer', 'blob'");
2090
- }
2091
- normalized.binaryType = options.binaryType;
2092
- }
2093
- return normalized;
1646
+ const normalized = {};
1647
+ if (!options) return normalized;
1648
+ const optionsWithOverrides = options;
1649
+ if (optionsWithOverrides.browser !== void 0) throw new RequestError("`browser` is not supported in session.websocket(); the session controls browser emulation.");
1650
+ if (optionsWithOverrides.os !== void 0) throw new RequestError("`os` is not supported in session.websocket(); the session controls OS emulation.");
1651
+ if (optionsWithOverrides.emulation !== void 0) throw new RequestError("`emulation` is not supported in session.websocket(); the session transport controls emulation.");
1652
+ if (optionsWithOverrides.proxy !== void 0) throw new RequestError("`proxy` is not supported in session.websocket(); the session transport controls proxying.");
1653
+ if (options.headers !== void 0) normalized.headers = options.headers;
1654
+ if (options.protocols !== void 0) normalized.protocols = options.protocols;
1655
+ if (options.maxFrameSize !== void 0) {
1656
+ const maxFrameSize = normalizeWebSocketSizeOption(options.maxFrameSize, "maxFrameSize");
1657
+ if (maxFrameSize !== void 0) normalized.maxFrameSize = maxFrameSize;
1658
+ }
1659
+ if (options.maxMessageSize !== void 0) {
1660
+ const maxMessageSize = normalizeWebSocketSizeOption(options.maxMessageSize, "maxMessageSize");
1661
+ if (maxMessageSize !== void 0) normalized.maxMessageSize = maxMessageSize;
1662
+ }
1663
+ if (options.binaryType !== void 0) {
1664
+ if (options.binaryType !== "nodebuffer" && options.binaryType !== "arraybuffer" && options.binaryType !== "blob") throw new RequestError("binaryType must be one of: 'nodebuffer', 'arraybuffer', 'blob'");
1665
+ normalized.binaryType = options.binaryType;
1666
+ }
1667
+ return normalized;
2094
1668
  }
2095
1669
  function extractLegacyWebSocketCallbacks(options) {
2096
- if (!isPlainObject(options)) {
2097
- return void 0;
2098
- }
2099
- const maybeCallbacks = options;
2100
- const callbacks = {};
2101
- if (typeof maybeCallbacks.onMessage === "function") {
2102
- callbacks.onMessage = maybeCallbacks.onMessage;
2103
- }
2104
- if (typeof maybeCallbacks.onClose === "function") {
2105
- callbacks.onClose = maybeCallbacks.onClose;
2106
- }
2107
- if (typeof maybeCallbacks.onError === "function") {
2108
- callbacks.onError = maybeCallbacks.onError;
2109
- }
2110
- return Object.keys(callbacks).length > 0 ? callbacks : void 0;
1670
+ if (!isPlainObject(options)) return;
1671
+ const maybeCallbacks = options;
1672
+ const callbacks = {};
1673
+ if (typeof maybeCallbacks.onMessage === "function") callbacks.onMessage = maybeCallbacks.onMessage;
1674
+ if (typeof maybeCallbacks.onClose === "function") callbacks.onClose = maybeCallbacks.onClose;
1675
+ if (typeof maybeCallbacks.onError === "function") callbacks.onError = maybeCallbacks.onError;
1676
+ return Object.keys(callbacks).length > 0 ? callbacks : void 0;
2111
1677
  }
2112
1678
  function normalizeWebSocketCloseOptions(code, reason) {
2113
- if (code === void 0 && reason === void 0) {
2114
- return void 0;
2115
- }
2116
- if (code === void 0) {
2117
- throw new RequestError("A close code is required when providing a close reason");
2118
- }
2119
- if (!Number.isInteger(code)) {
2120
- throw new RequestError("Close code must be an integer");
2121
- }
2122
- if (code !== 1e3 && (code < 3e3 || code > 4999)) {
2123
- throw new RequestError("Close code must be 1000 or in range 3000-4999");
2124
- }
2125
- const normalizedReason = reason ?? "";
2126
- if (Buffer.byteLength(normalizedReason, "utf8") > 123) {
2127
- throw new RequestError("Close reason must be 123 bytes or fewer");
2128
- }
2129
- return {
2130
- code,
2131
- reason: normalizedReason
2132
- };
1679
+ if (code === void 0 && reason === void 0) return;
1680
+ if (code === void 0) throw new RequestError("A close code is required when providing a close reason");
1681
+ if (!Number.isInteger(code)) throw new RequestError("Close code must be an integer");
1682
+ if (code !== 1e3 && (code < 3e3 || code > 4999)) throw new RequestError("Close code must be 1000 or in range 3000-4999");
1683
+ const normalizedReason = reason ?? "";
1684
+ if (Buffer.byteLength(normalizedReason, "utf8") > 123) throw new RequestError("Close reason must be 123 bytes or fewer");
1685
+ return {
1686
+ code,
1687
+ reason: normalizedReason
1688
+ };
2133
1689
  }
2134
1690
  function isWebSocketListenerType(type) {
2135
- return type === "open" || type === "message" || type === "close" || type === "error";
2136
- }
2137
- var WebSocket = class _WebSocket {
2138
- static CONNECTING = 0;
2139
- static OPEN = 1;
2140
- static CLOSING = 2;
2141
- static CLOSED = 3;
2142
- url;
2143
- protocol = "";
2144
- extensions = "";
2145
- readyState = _WebSocket.CONNECTING;
2146
- _binaryType = "nodebuffer";
2147
- _bufferedAmount = 0;
2148
- _onopen = null;
2149
- _onmessage = null;
2150
- _onclose = null;
2151
- _onerror = null;
2152
- _onHandlerOrder = {
2153
- open: -1,
2154
- message: -1,
2155
- close: -1,
2156
- error: -1
2157
- };
2158
- _listenerOrderCounter = 0;
2159
- _listeners = {
2160
- open: /* @__PURE__ */ new Map(),
2161
- message: /* @__PURE__ */ new Map(),
2162
- close: /* @__PURE__ */ new Map(),
2163
- error: /* @__PURE__ */ new Map()
2164
- };
2165
- _legacyCallbacks;
2166
- _openDispatchMode;
2167
- _connection;
2168
- _connectPromise;
2169
- _closeOptions;
2170
- _finalizerToken;
2171
- _openEventDispatched = false;
2172
- _openEventQueued = false;
2173
- _closeEventDispatched = false;
2174
- _nativeCloseStarted = false;
2175
- _pendingMessages = [];
2176
- _sendChain = Promise.resolve();
2177
- constructor(urlOrInit, protocolsOrOptions, maybeOptions) {
2178
- let init;
2179
- if (isInternalWebSocketInit(urlOrInit)) {
2180
- init = urlOrInit;
2181
- } else {
2182
- init = _WebSocket.buildStandaloneInit(urlOrInit, protocolsOrOptions, maybeOptions);
2183
- }
2184
- this.url = init.url;
2185
- this.binaryType = init.options.binaryType ?? "nodebuffer";
2186
- this._legacyCallbacks = init.legacyCallbacks;
2187
- this._openDispatchMode = init.openDispatchMode;
2188
- this._connectPromise = this.connect(init.connect);
2189
- void this._connectPromise.catch(() => void 0);
2190
- }
2191
- get binaryType() {
2192
- return this._binaryType;
2193
- }
2194
- set binaryType(value) {
2195
- if (value === "arraybuffer" || value === "blob" || value === "nodebuffer") {
2196
- this._binaryType = value;
2197
- }
2198
- }
2199
- get bufferedAmount() {
2200
- return this._bufferedAmount;
2201
- }
2202
- get onopen() {
2203
- return this._onopen;
2204
- }
2205
- set onopen(listener) {
2206
- this._onopen = listener;
2207
- this._onHandlerOrder.open = listener ? ++this._listenerOrderCounter : -1;
2208
- }
2209
- get onmessage() {
2210
- return this._onmessage;
2211
- }
2212
- set onmessage(listener) {
2213
- this._onmessage = listener;
2214
- this._onHandlerOrder.message = listener ? ++this._listenerOrderCounter : -1;
2215
- }
2216
- get onclose() {
2217
- return this._onclose;
2218
- }
2219
- set onclose(listener) {
2220
- this._onclose = listener;
2221
- this._onHandlerOrder.close = listener ? ++this._listenerOrderCounter : -1;
2222
- }
2223
- get onerror() {
2224
- return this._onerror;
2225
- }
2226
- set onerror(listener) {
2227
- this._onerror = listener;
2228
- this._onHandlerOrder.error = listener ? ++this._listenerOrderCounter : -1;
2229
- }
2230
- static async _connectWithInit(init) {
2231
- const ws = new _WebSocket(init);
2232
- await ws._waitUntilConnected();
2233
- ws.scheduleOpenEventAfterAwait();
2234
- return ws;
2235
- }
2236
- static buildStandaloneInit(url, protocolsOrOptions, maybeOptions) {
2237
- const optionsCandidate = typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? maybeOptions : protocolsOrOptions ?? maybeOptions;
2238
- const normalizedOptions = normalizeStandaloneWebSocketOptions(optionsCandidate);
2239
- validateWebSocketProtocols(
2240
- typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? protocolsOrOptions : normalizedOptions.protocols
2241
- );
2242
- assertNoManualWebSocketProtocolHeader(normalizedOptions.headers);
2243
- const emulationMode = resolveEmulationMode(
2244
- normalizedOptions.browser,
2245
- normalizedOptions.os,
2246
- normalizedOptions.emulation
2247
- );
2248
- const protocols = normalizeWebSocketProtocolList(
2249
- typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? protocolsOrOptions : normalizedOptions.protocols
2250
- );
2251
- return {
2252
- _internal: true,
2253
- url: normalizeWebSocketUrl(url),
2254
- options: normalizedOptions,
2255
- openDispatchMode: "automatic",
2256
- connect: (callbacks) => {
2257
- const nativeOptions = {
2258
- url: normalizeWebSocketUrl(url),
2259
- headers: headersToTuples(normalizedOptions.headers ?? {}),
2260
- ...protocols && protocols.length > 0 && { protocols },
2261
- ...normalizedOptions.proxy !== void 0 && { proxy: normalizedOptions.proxy },
2262
- onMessage: callbacks.onMessage,
2263
- onClose: callbacks.onClose,
2264
- onError: callbacks.onError
2265
- };
2266
- applyNativeEmulationMode(nativeOptions, emulationMode);
2267
- return nativeBinding.websocketConnect(nativeOptions);
2268
- },
2269
- legacyCallbacks: extractLegacyWebSocketCallbacks(optionsCandidate)
2270
- };
2271
- }
2272
- async connect(connectFn) {
2273
- try {
2274
- const connection = await connectFn({
2275
- onMessage: (data) => {
2276
- this.handleNativeMessage(data);
2277
- },
2278
- onClose: (event) => {
2279
- this.handleNativeClose(event);
2280
- },
2281
- onError: (message) => {
2282
- this.handleNativeError(message);
2283
- }
2284
- });
2285
- this._connection = connection;
2286
- this.protocol = connection.protocol ?? "";
2287
- this.extensions = connection.extensions ?? "";
2288
- if (websocketFinalizer) {
2289
- this._finalizerToken = connection;
2290
- websocketFinalizer.register(this, connection, connection);
2291
- }
2292
- if (this.readyState === _WebSocket.CLOSING) {
2293
- this.startNativeClose();
2294
- return;
2295
- }
2296
- this.readyState = _WebSocket.OPEN;
2297
- if (this._openDispatchMode === "automatic") {
2298
- this.scheduleOpenEventAfterConnect();
2299
- }
2300
- } catch (error) {
2301
- this.handleNativeError(String(error));
2302
- this.finalizeClosed({ code: 1006, reason: "" }, false);
2303
- throw new RequestError(String(error));
2304
- }
2305
- }
2306
- _waitUntilConnected() {
2307
- return this._connectPromise;
2308
- }
2309
- scheduleOpenEventAfterConnect() {
2310
- this.scheduleOpenEventWithDepth(2);
2311
- }
2312
- scheduleOpenEventAfterAwait() {
2313
- this.scheduleOpenEventWithDepth(3);
2314
- }
2315
- scheduleOpenEventWithDepth(depth) {
2316
- if (this._openEventDispatched || this._openEventQueued || this.readyState !== _WebSocket.OPEN) {
2317
- return;
2318
- }
2319
- this._openEventQueued = true;
2320
- const queue = (remaining) => {
2321
- if (remaining === 0) {
2322
- this._openEventQueued = false;
2323
- if (this._openEventDispatched || this.readyState !== _WebSocket.OPEN) {
2324
- return;
2325
- }
2326
- this._openEventDispatched = true;
2327
- this.dispatchOpenEvent();
2328
- return;
2329
- }
2330
- queueMicrotask(() => {
2331
- queue(remaining - 1);
2332
- });
2333
- };
2334
- queue(depth);
2335
- }
2336
- releaseConnectionTracking() {
2337
- if (!this._finalizerToken || !websocketFinalizer) {
2338
- return;
2339
- }
2340
- websocketFinalizer.unregister(this._finalizerToken);
2341
- this._finalizerToken = void 0;
2342
- }
2343
- toMessageEventData(data) {
2344
- if (typeof data === "string") {
2345
- return data;
2346
- }
2347
- if (this._binaryType === "arraybuffer") {
2348
- const arrayBuffer = new ArrayBuffer(data.byteLength);
2349
- new Uint8Array(arrayBuffer).set(data);
2350
- return arrayBuffer;
2351
- }
2352
- if (this._binaryType === "blob") {
2353
- return new Blob([data]);
2354
- }
2355
- return data;
2356
- }
2357
- invokeListener(listener, event) {
2358
- try {
2359
- if (typeof listener === "function") {
2360
- listener.call(this, event);
2361
- } else {
2362
- listener.handleEvent(event);
2363
- }
2364
- } catch {
2365
- }
2366
- }
2367
- createBaseEvent(type) {
2368
- return {
2369
- type,
2370
- isTrusted: false,
2371
- timeStamp: Date.now(),
2372
- target: this,
2373
- currentTarget: this
2374
- };
2375
- }
2376
- getOnHandler(type) {
2377
- switch (type) {
2378
- case "open":
2379
- return this._onopen;
2380
- case "message":
2381
- return this._onmessage;
2382
- case "close":
2383
- return this._onclose;
2384
- case "error":
2385
- return this._onerror;
2386
- default:
2387
- return null;
2388
- }
2389
- }
2390
- getOnHandlerOrder(type) {
2391
- return this._onHandlerOrder[type];
2392
- }
2393
- getListenerMap(type) {
2394
- return this._listeners[type];
2395
- }
2396
- dispatchEvent(type, event) {
2397
- const listenerMap = this.getListenerMap(type);
2398
- const onHandler = this.getOnHandler(type);
2399
- if (listenerMap.size === 0 && !onHandler) {
2400
- return;
2401
- }
2402
- const ordered = [];
2403
- for (const descriptor of listenerMap.values()) {
2404
- ordered.push({
2405
- order: descriptor.order,
2406
- listener: descriptor.listener,
2407
- once: descriptor.once
2408
- });
2409
- }
2410
- if (onHandler) {
2411
- ordered.push({
2412
- order: this.getOnHandlerOrder(type),
2413
- listener: onHandler,
2414
- once: false
2415
- });
2416
- }
2417
- ordered.sort((a, b) => a.order - b.order);
2418
- for (const entry of ordered) {
2419
- if (entry.once) {
2420
- this.removeEventListener(type, entry.listener);
2421
- }
2422
- this.invokeListener(entry.listener, event);
2423
- }
2424
- }
2425
- dispatchOpenEvent() {
2426
- const event = this.createBaseEvent("open");
2427
- this.dispatchEvent("open", event);
2428
- if (!this._closeEventDispatched && this._pendingMessages.length > 0) {
2429
- const pending = this._pendingMessages;
2430
- this._pendingMessages = [];
2431
- for (const data of pending) {
2432
- this.dispatchMessageEvent(this.toMessageEventData(data));
2433
- }
2434
- }
2435
- }
2436
- dispatchMessageEvent(data) {
2437
- const event = {
2438
- ...this.createBaseEvent("message"),
2439
- data
2440
- };
2441
- this.dispatchEvent("message", event);
2442
- }
2443
- dispatchCloseEvent(event) {
2444
- this.dispatchEvent("close", event);
2445
- }
2446
- dispatchErrorEvent(message) {
2447
- const event = {
2448
- ...this.createBaseEvent("error"),
2449
- ...message !== void 0 && { message }
2450
- };
2451
- this.dispatchEvent("error", event);
2452
- }
2453
- handleNativeMessage(data) {
2454
- if (this._closeEventDispatched) {
2455
- return;
2456
- }
2457
- this._legacyCallbacks?.onMessage?.(data);
2458
- if (!this._openEventDispatched && this.readyState === _WebSocket.OPEN) {
2459
- this._pendingMessages.push(data);
2460
- return;
2461
- }
2462
- this.dispatchMessageEvent(this.toMessageEventData(data));
2463
- }
2464
- handleNativeError(message) {
2465
- this._legacyCallbacks?.onError?.(message);
2466
- this.dispatchErrorEvent(message);
2467
- }
2468
- handleNativeClose(event) {
2469
- const wasClean = this.readyState === _WebSocket.CLOSING || event.code === 1e3;
2470
- this.finalizeClosed(event, wasClean);
2471
- }
2472
- finalizeClosed(event, wasClean) {
2473
- if (this._closeEventDispatched) {
2474
- return;
2475
- }
2476
- this.readyState = _WebSocket.CLOSED;
2477
- this._closeEventDispatched = true;
2478
- this._pendingMessages = [];
2479
- this.releaseConnectionTracking();
2480
- const closeEvent = {
2481
- ...this.createBaseEvent("close"),
2482
- code: event.code,
2483
- reason: event.reason,
2484
- wasClean
2485
- };
2486
- this._legacyCallbacks?.onClose?.(closeEvent);
2487
- this.dispatchCloseEvent(closeEvent);
2488
- }
2489
- startNativeClose() {
2490
- if (this._nativeCloseStarted || !this._connection) {
2491
- return;
2492
- }
2493
- this._nativeCloseStarted = true;
2494
- const connection = this._connection;
2495
- const closeOptions = this._closeOptions;
2496
- void nativeBinding.websocketClose(connection, closeOptions).catch((error) => {
2497
- this.handleNativeError(String(error));
2498
- this.finalizeClosed({ code: 1006, reason: "" }, false);
2499
- });
2500
- }
2501
- addEventListener(type, listener, options) {
2502
- if (!listener || !isWebSocketListenerType(type)) {
2503
- return;
2504
- }
2505
- const normalizedListener = listener;
2506
- if (typeof normalizedListener !== "function" && (typeof normalizedListener !== "object" || normalizedListener === null || typeof normalizedListener.handleEvent !== "function")) {
2507
- return;
2508
- }
2509
- const listenerMap = this.getListenerMap(type);
2510
- if (listenerMap.has(normalizedListener)) {
2511
- return;
2512
- }
2513
- const parsedOptions = typeof options === "boolean" ? {} : options ?? {};
2514
- const once = parsedOptions.once === true;
2515
- const signal = parsedOptions.signal;
2516
- if (signal?.aborted) {
2517
- return;
2518
- }
2519
- const descriptor = {
2520
- listener: normalizedListener,
2521
- order: ++this._listenerOrderCounter,
2522
- once
2523
- };
2524
- if (signal) {
2525
- const onAbort = () => {
2526
- this.removeEventListener(type, normalizedListener);
2527
- };
2528
- descriptor.abortSignal = signal;
2529
- descriptor.abortHandler = onAbort;
2530
- signal.addEventListener("abort", onAbort, { once: true });
2531
- }
2532
- listenerMap.set(normalizedListener, descriptor);
2533
- }
2534
- removeEventListener(type, listener) {
2535
- if (!listener || !isWebSocketListenerType(type)) {
2536
- return;
2537
- }
2538
- const normalizedListener = listener;
2539
- if (typeof normalizedListener !== "function" && typeof normalizedListener !== "object") {
2540
- return;
2541
- }
2542
- const listenerMap = this.getListenerMap(type);
2543
- const descriptor = listenerMap.get(normalizedListener);
2544
- if (!descriptor) {
2545
- return;
2546
- }
2547
- if (descriptor.abortSignal && descriptor.abortHandler) {
2548
- descriptor.abortSignal.removeEventListener("abort", descriptor.abortHandler);
2549
- }
2550
- listenerMap.delete(normalizedListener);
2551
- }
2552
- getSendByteLength(data) {
2553
- if (typeof data === "string") {
2554
- return Buffer.byteLength(data);
2555
- }
2556
- if (Buffer.isBuffer(data)) {
2557
- return data.byteLength;
2558
- }
2559
- if (data instanceof ArrayBuffer) {
2560
- return data.byteLength;
2561
- }
2562
- if (ArrayBuffer.isView(data)) {
2563
- return data.byteLength;
2564
- }
2565
- if (typeof Blob !== "undefined" && data instanceof Blob) {
2566
- return data.size;
2567
- }
2568
- throw new TypeError("WebSocket data must be a string, Buffer, ArrayBuffer, ArrayBufferView, or Blob");
2569
- }
2570
- async normalizeSendPayload(data) {
2571
- if (typeof data === "string") {
2572
- return data;
2573
- }
2574
- if (Buffer.isBuffer(data)) {
2575
- return data;
2576
- }
2577
- if (data instanceof ArrayBuffer) {
2578
- return Buffer.from(data);
2579
- }
2580
- if (ArrayBuffer.isView(data)) {
2581
- return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
2582
- }
2583
- if (typeof Blob !== "undefined" && data instanceof Blob) {
2584
- return Buffer.from(await data.arrayBuffer());
2585
- }
2586
- throw new TypeError("WebSocket data must be a string, Buffer, ArrayBuffer, ArrayBufferView, or Blob");
2587
- }
2588
- send(data) {
2589
- if (this.readyState !== _WebSocket.OPEN || !this._connection) {
2590
- throw new RequestError("WebSocket is not open");
2591
- }
2592
- const queuedBytes = this.getSendByteLength(data);
2593
- const connection = this._connection;
2594
- this._bufferedAmount += queuedBytes;
2595
- const sendTask = async () => {
2596
- try {
2597
- const payload = await this.normalizeSendPayload(data);
2598
- await nativeBinding.websocketSend(connection, payload);
2599
- } catch (error) {
2600
- this.handleNativeError(String(error));
2601
- this.finalizeClosed({ code: 1006, reason: "" }, false);
2602
- } finally {
2603
- this._bufferedAmount = Math.max(0, this._bufferedAmount - queuedBytes);
2604
- }
2605
- };
2606
- this._sendChain = this._sendChain.then(sendTask, sendTask);
2607
- }
2608
- close(code, reason) {
2609
- if (this.readyState === _WebSocket.CLOSING || this.readyState === _WebSocket.CLOSED) {
2610
- return;
2611
- }
2612
- this._closeOptions = normalizeWebSocketCloseOptions(code, reason);
2613
- this.readyState = _WebSocket.CLOSING;
2614
- this.startNativeClose();
2615
- }
1691
+ return type === "open" || type === "message" || type === "close" || type === "error";
1692
+ }
1693
+ /**
1694
+ * WHATWG-style WebSocket API with async connection establishment.
1695
+ */
1696
+ var WebSocket = class WebSocket {
1697
+ static CONNECTING = 0;
1698
+ static OPEN = 1;
1699
+ static CLOSING = 2;
1700
+ static CLOSED = 3;
1701
+ url;
1702
+ protocol = "";
1703
+ extensions = "";
1704
+ readyState = WebSocket.CONNECTING;
1705
+ _binaryType = "nodebuffer";
1706
+ _bufferedAmount = 0;
1707
+ _onopen = null;
1708
+ _onmessage = null;
1709
+ _onclose = null;
1710
+ _onerror = null;
1711
+ _onHandlerOrder = {
1712
+ open: -1,
1713
+ message: -1,
1714
+ close: -1,
1715
+ error: -1
1716
+ };
1717
+ _listenerOrderCounter = 0;
1718
+ _listeners = {
1719
+ open: /* @__PURE__ */ new Map(),
1720
+ message: /* @__PURE__ */ new Map(),
1721
+ close: /* @__PURE__ */ new Map(),
1722
+ error: /* @__PURE__ */ new Map()
1723
+ };
1724
+ _legacyCallbacks;
1725
+ _openDispatchMode;
1726
+ _connection;
1727
+ _connectPromise;
1728
+ _closeOptions;
1729
+ _finalizerToken;
1730
+ _openEventDispatched = false;
1731
+ _openEventQueued = false;
1732
+ _closeEventDispatched = false;
1733
+ _nativeCloseStarted = false;
1734
+ _pendingMessages = [];
1735
+ _sendChain = Promise.resolve();
1736
+ constructor(urlOrInit, protocolsOrOptions, maybeOptions) {
1737
+ let init;
1738
+ if (isInternalWebSocketInit(urlOrInit)) init = urlOrInit;
1739
+ else init = WebSocket.buildStandaloneInit(urlOrInit, protocolsOrOptions, maybeOptions);
1740
+ this.url = init.url;
1741
+ this.binaryType = init.options.binaryType ?? "nodebuffer";
1742
+ this._legacyCallbacks = init.legacyCallbacks;
1743
+ this._openDispatchMode = init.openDispatchMode;
1744
+ this._connectPromise = this.connect(init.connect);
1745
+ this._connectPromise.catch(() => void 0);
1746
+ }
1747
+ get binaryType() {
1748
+ return this._binaryType;
1749
+ }
1750
+ set binaryType(value) {
1751
+ if (value === "arraybuffer" || value === "blob" || value === "nodebuffer") this._binaryType = value;
1752
+ }
1753
+ get bufferedAmount() {
1754
+ return this._bufferedAmount;
1755
+ }
1756
+ get onopen() {
1757
+ return this._onopen;
1758
+ }
1759
+ set onopen(listener) {
1760
+ this._onopen = listener;
1761
+ this._onHandlerOrder.open = listener ? ++this._listenerOrderCounter : -1;
1762
+ }
1763
+ get onmessage() {
1764
+ return this._onmessage;
1765
+ }
1766
+ set onmessage(listener) {
1767
+ this._onmessage = listener;
1768
+ this._onHandlerOrder.message = listener ? ++this._listenerOrderCounter : -1;
1769
+ }
1770
+ get onclose() {
1771
+ return this._onclose;
1772
+ }
1773
+ set onclose(listener) {
1774
+ this._onclose = listener;
1775
+ this._onHandlerOrder.close = listener ? ++this._listenerOrderCounter : -1;
1776
+ }
1777
+ get onerror() {
1778
+ return this._onerror;
1779
+ }
1780
+ set onerror(listener) {
1781
+ this._onerror = listener;
1782
+ this._onHandlerOrder.error = listener ? ++this._listenerOrderCounter : -1;
1783
+ }
1784
+ static async _connectWithInit(init) {
1785
+ const ws = new WebSocket(init);
1786
+ await ws._waitUntilConnected();
1787
+ ws.scheduleOpenEventAfterAwait();
1788
+ return ws;
1789
+ }
1790
+ static buildStandaloneInit(url, protocolsOrOptions, maybeOptions) {
1791
+ const optionsCandidate = typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? maybeOptions : protocolsOrOptions ?? maybeOptions;
1792
+ const normalizedOptions = normalizeStandaloneWebSocketOptions(optionsCandidate);
1793
+ validateWebSocketProtocols(typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? protocolsOrOptions : normalizedOptions.protocols);
1794
+ assertNoManualWebSocketProtocolHeader(normalizedOptions.headers);
1795
+ const emulationMode = resolveEmulationMode(normalizedOptions.browser, normalizedOptions.os, normalizedOptions.emulation);
1796
+ const protocols = normalizeWebSocketProtocolList(typeof protocolsOrOptions === "string" || Array.isArray(protocolsOrOptions) ? protocolsOrOptions : normalizedOptions.protocols);
1797
+ return {
1798
+ _internal: true,
1799
+ url: normalizeWebSocketUrl(url),
1800
+ options: normalizedOptions,
1801
+ openDispatchMode: "automatic",
1802
+ connect: (callbacks) => {
1803
+ const nativeOptions = {
1804
+ url: normalizeWebSocketUrl(url),
1805
+ headers: headersToTuples(normalizedOptions.headers ?? {}),
1806
+ ...protocols && protocols.length > 0 && { protocols },
1807
+ ...normalizedOptions.proxy !== void 0 && { proxy: normalizedOptions.proxy },
1808
+ ...normalizedOptions.maxFrameSize !== void 0 && { maxFrameSize: normalizedOptions.maxFrameSize },
1809
+ ...normalizedOptions.maxMessageSize !== void 0 && { maxMessageSize: normalizedOptions.maxMessageSize },
1810
+ onMessage: callbacks.onMessage,
1811
+ onClose: callbacks.onClose,
1812
+ onError: callbacks.onError
1813
+ };
1814
+ applyNativeEmulationMode(nativeOptions, emulationMode);
1815
+ return nativeBinding.websocketConnect(nativeOptions);
1816
+ },
1817
+ legacyCallbacks: extractLegacyWebSocketCallbacks(optionsCandidate)
1818
+ };
1819
+ }
1820
+ async connect(connectFn) {
1821
+ try {
1822
+ const connection = await connectFn({
1823
+ onMessage: (data) => {
1824
+ this.handleNativeMessage(data);
1825
+ },
1826
+ onClose: (event) => {
1827
+ this.handleNativeClose(event);
1828
+ },
1829
+ onError: (message) => {
1830
+ this.handleNativeError(message);
1831
+ }
1832
+ });
1833
+ this._connection = connection;
1834
+ this.protocol = connection.protocol ?? "";
1835
+ this.extensions = connection.extensions ?? "";
1836
+ if (websocketFinalizer) {
1837
+ this._finalizerToken = connection;
1838
+ websocketFinalizer.register(this, connection, connection);
1839
+ }
1840
+ if (this.readyState === WebSocket.CLOSING) {
1841
+ this.startNativeClose();
1842
+ return;
1843
+ }
1844
+ this.readyState = WebSocket.OPEN;
1845
+ if (this._openDispatchMode === "automatic") this.scheduleOpenEventAfterConnect();
1846
+ } catch (error) {
1847
+ this.handleNativeError(String(error));
1848
+ this.finalizeClosed({
1849
+ code: 1006,
1850
+ reason: ""
1851
+ }, false);
1852
+ throw new RequestError(String(error));
1853
+ }
1854
+ }
1855
+ _waitUntilConnected() {
1856
+ return this._connectPromise;
1857
+ }
1858
+ scheduleOpenEventAfterConnect() {
1859
+ this.scheduleOpenEventWithDepth(2);
1860
+ }
1861
+ scheduleOpenEventAfterAwait() {
1862
+ this.scheduleOpenEventWithDepth(3);
1863
+ }
1864
+ scheduleOpenEventWithDepth(depth) {
1865
+ if (this._openEventDispatched || this._openEventQueued || this.readyState !== WebSocket.OPEN) return;
1866
+ this._openEventQueued = true;
1867
+ const queue = (remaining) => {
1868
+ if (remaining === 0) {
1869
+ this._openEventQueued = false;
1870
+ if (this._openEventDispatched || this.readyState !== WebSocket.OPEN) return;
1871
+ this._openEventDispatched = true;
1872
+ this.dispatchOpenEvent();
1873
+ return;
1874
+ }
1875
+ queueMicrotask(() => {
1876
+ queue(remaining - 1);
1877
+ });
1878
+ };
1879
+ queue(depth);
1880
+ }
1881
+ releaseConnectionTracking() {
1882
+ if (!this._finalizerToken || !websocketFinalizer) return;
1883
+ websocketFinalizer.unregister(this._finalizerToken);
1884
+ this._finalizerToken = void 0;
1885
+ }
1886
+ toMessageEventData(data) {
1887
+ if (typeof data === "string") return data;
1888
+ if (this._binaryType === "arraybuffer") {
1889
+ const arrayBuffer = new ArrayBuffer(data.byteLength);
1890
+ new Uint8Array(arrayBuffer).set(data);
1891
+ return arrayBuffer;
1892
+ }
1893
+ if (this._binaryType === "blob") return new Blob([data]);
1894
+ return data;
1895
+ }
1896
+ invokeListener(listener, event) {
1897
+ try {
1898
+ if (typeof listener === "function") listener.call(this, event);
1899
+ else listener.handleEvent(event);
1900
+ } catch {}
1901
+ }
1902
+ createBaseEvent(type) {
1903
+ return {
1904
+ type,
1905
+ isTrusted: false,
1906
+ timeStamp: Date.now(),
1907
+ target: this,
1908
+ currentTarget: this
1909
+ };
1910
+ }
1911
+ getOnHandler(type) {
1912
+ switch (type) {
1913
+ case "open": return this._onopen;
1914
+ case "message": return this._onmessage;
1915
+ case "close": return this._onclose;
1916
+ case "error": return this._onerror;
1917
+ default: return null;
1918
+ }
1919
+ }
1920
+ getOnHandlerOrder(type) {
1921
+ return this._onHandlerOrder[type];
1922
+ }
1923
+ getListenerMap(type) {
1924
+ return this._listeners[type];
1925
+ }
1926
+ dispatchEvent(type, event) {
1927
+ const listenerMap = this.getListenerMap(type);
1928
+ const onHandler = this.getOnHandler(type);
1929
+ if (listenerMap.size === 0 && !onHandler) return;
1930
+ const ordered = [];
1931
+ for (const descriptor of listenerMap.values()) ordered.push({
1932
+ order: descriptor.order,
1933
+ listener: descriptor.listener,
1934
+ once: descriptor.once
1935
+ });
1936
+ if (onHandler) ordered.push({
1937
+ order: this.getOnHandlerOrder(type),
1938
+ listener: onHandler,
1939
+ once: false
1940
+ });
1941
+ ordered.sort((a, b) => a.order - b.order);
1942
+ for (const entry of ordered) {
1943
+ if (entry.once) this.removeEventListener(type, entry.listener);
1944
+ this.invokeListener(entry.listener, event);
1945
+ }
1946
+ }
1947
+ dispatchOpenEvent() {
1948
+ const event = this.createBaseEvent("open");
1949
+ this.dispatchEvent("open", event);
1950
+ if (!this._closeEventDispatched && this._pendingMessages.length > 0) {
1951
+ const pending = this._pendingMessages;
1952
+ this._pendingMessages = [];
1953
+ for (const data of pending) this.dispatchMessageEvent(this.toMessageEventData(data));
1954
+ }
1955
+ }
1956
+ dispatchMessageEvent(data) {
1957
+ const event = {
1958
+ ...this.createBaseEvent("message"),
1959
+ data
1960
+ };
1961
+ this.dispatchEvent("message", event);
1962
+ }
1963
+ dispatchCloseEvent(event) {
1964
+ this.dispatchEvent("close", event);
1965
+ }
1966
+ dispatchErrorEvent(message) {
1967
+ const event = {
1968
+ ...this.createBaseEvent("error"),
1969
+ ...message !== void 0 && { message }
1970
+ };
1971
+ this.dispatchEvent("error", event);
1972
+ }
1973
+ handleNativeMessage(data) {
1974
+ if (this._closeEventDispatched) return;
1975
+ this._legacyCallbacks?.onMessage?.(data);
1976
+ if (!this._openEventDispatched && this.readyState === WebSocket.OPEN) {
1977
+ this._pendingMessages.push(data);
1978
+ return;
1979
+ }
1980
+ this.dispatchMessageEvent(this.toMessageEventData(data));
1981
+ }
1982
+ handleNativeError(message) {
1983
+ this._legacyCallbacks?.onError?.(message);
1984
+ this.dispatchErrorEvent(message);
1985
+ }
1986
+ handleNativeClose(event) {
1987
+ const wasClean = this.readyState === WebSocket.CLOSING || event.code === 1e3;
1988
+ this.finalizeClosed(event, wasClean);
1989
+ }
1990
+ finalizeClosed(event, wasClean) {
1991
+ if (this._closeEventDispatched) return;
1992
+ this.readyState = WebSocket.CLOSED;
1993
+ this._closeEventDispatched = true;
1994
+ this._pendingMessages = [];
1995
+ this.releaseConnectionTracking();
1996
+ const closeEvent = {
1997
+ ...this.createBaseEvent("close"),
1998
+ code: event.code,
1999
+ reason: event.reason,
2000
+ wasClean
2001
+ };
2002
+ this._legacyCallbacks?.onClose?.(closeEvent);
2003
+ this.dispatchCloseEvent(closeEvent);
2004
+ }
2005
+ startNativeClose() {
2006
+ if (this._nativeCloseStarted || !this._connection) return;
2007
+ this._nativeCloseStarted = true;
2008
+ const connection = this._connection;
2009
+ const closeOptions = this._closeOptions;
2010
+ nativeBinding.websocketClose(connection, closeOptions).catch((error) => {
2011
+ this.handleNativeError(String(error));
2012
+ this.finalizeClosed({
2013
+ code: 1006,
2014
+ reason: ""
2015
+ }, false);
2016
+ });
2017
+ }
2018
+ addEventListener(type, listener, options) {
2019
+ if (!listener || !isWebSocketListenerType(type)) return;
2020
+ const normalizedListener = listener;
2021
+ if (typeof normalizedListener !== "function" && (typeof normalizedListener !== "object" || normalizedListener === null || typeof normalizedListener.handleEvent !== "function")) return;
2022
+ const listenerMap = this.getListenerMap(type);
2023
+ if (listenerMap.has(normalizedListener)) return;
2024
+ const parsedOptions = typeof options === "boolean" ? {} : options ?? {};
2025
+ const once = parsedOptions.once === true;
2026
+ const signal = parsedOptions.signal;
2027
+ if (signal?.aborted) return;
2028
+ const descriptor = {
2029
+ listener: normalizedListener,
2030
+ order: ++this._listenerOrderCounter,
2031
+ once
2032
+ };
2033
+ if (signal) {
2034
+ const onAbort = () => {
2035
+ this.removeEventListener(type, normalizedListener);
2036
+ };
2037
+ descriptor.abortSignal = signal;
2038
+ descriptor.abortHandler = onAbort;
2039
+ signal.addEventListener("abort", onAbort, { once: true });
2040
+ }
2041
+ listenerMap.set(normalizedListener, descriptor);
2042
+ }
2043
+ removeEventListener(type, listener) {
2044
+ if (!listener || !isWebSocketListenerType(type)) return;
2045
+ const normalizedListener = listener;
2046
+ if (typeof normalizedListener !== "function" && typeof normalizedListener !== "object") return;
2047
+ const listenerMap = this.getListenerMap(type);
2048
+ const descriptor = listenerMap.get(normalizedListener);
2049
+ if (!descriptor) return;
2050
+ if (descriptor.abortSignal && descriptor.abortHandler) descriptor.abortSignal.removeEventListener("abort", descriptor.abortHandler);
2051
+ listenerMap.delete(normalizedListener);
2052
+ }
2053
+ getSendByteLength(data) {
2054
+ if (typeof data === "string") return Buffer.byteLength(data);
2055
+ if (Buffer.isBuffer(data)) return data.byteLength;
2056
+ if (data instanceof ArrayBuffer) return data.byteLength;
2057
+ if (ArrayBuffer.isView(data)) return data.byteLength;
2058
+ if (typeof Blob !== "undefined" && data instanceof Blob) return data.size;
2059
+ throw new TypeError("WebSocket data must be a string, Buffer, ArrayBuffer, ArrayBufferView, or Blob");
2060
+ }
2061
+ async normalizeSendPayload(data) {
2062
+ if (typeof data === "string") return data;
2063
+ if (Buffer.isBuffer(data)) return data;
2064
+ if (data instanceof ArrayBuffer) return Buffer.from(data);
2065
+ if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
2066
+ if (typeof Blob !== "undefined" && data instanceof Blob) return Buffer.from(await data.arrayBuffer());
2067
+ throw new TypeError("WebSocket data must be a string, Buffer, ArrayBuffer, ArrayBufferView, or Blob");
2068
+ }
2069
+ send(data) {
2070
+ if (this.readyState !== WebSocket.OPEN || !this._connection) throw new RequestError("WebSocket is not open");
2071
+ const queuedBytes = this.getSendByteLength(data);
2072
+ const connection = this._connection;
2073
+ this._bufferedAmount += queuedBytes;
2074
+ const sendTask = async () => {
2075
+ try {
2076
+ const payload = await this.normalizeSendPayload(data);
2077
+ await nativeBinding.websocketSend(connection, payload);
2078
+ } catch (error) {
2079
+ this.handleNativeError(String(error));
2080
+ this.finalizeClosed({
2081
+ code: 1006,
2082
+ reason: ""
2083
+ }, false);
2084
+ } finally {
2085
+ this._bufferedAmount = Math.max(0, this._bufferedAmount - queuedBytes);
2086
+ }
2087
+ };
2088
+ this._sendChain = this._sendChain.then(sendTask, sendTask);
2089
+ }
2090
+ close(code, reason) {
2091
+ if (this.readyState === WebSocket.CLOSING || this.readyState === WebSocket.CLOSED) return;
2092
+ this._closeOptions = normalizeWebSocketCloseOptions(code, reason);
2093
+ this.readyState = WebSocket.CLOSING;
2094
+ this.startNativeClose();
2095
+ }
2616
2096
  };
2617
2097
  function isInternalWebSocketInit(value) {
2618
- if (!isPlainObject(value)) {
2619
- return false;
2620
- }
2621
- const candidate = value;
2622
- return candidate._internal === true && typeof candidate.url === "string" && typeof candidate.connect === "function";
2098
+ if (!isPlainObject(value)) return false;
2099
+ const candidate = value;
2100
+ return candidate._internal === true && typeof candidate.url === "string" && typeof candidate.connect === "function";
2623
2101
  }
2624
2102
  function normalizeStandaloneWebSocketArgs(urlOrOptions, options) {
2625
- if (typeof urlOrOptions === "string" || urlOrOptions instanceof URL) {
2626
- const normalizedOptions2 = normalizeStandaloneWebSocketOptions(options);
2627
- return {
2628
- url: normalizeWebSocketUrl(urlOrOptions),
2629
- options: normalizedOptions2,
2630
- legacyCallbacks: extractLegacyWebSocketCallbacks(options)
2631
- };
2632
- }
2633
- const legacy = urlOrOptions;
2634
- const normalizedOptions = normalizeStandaloneWebSocketOptions(legacy);
2635
- return {
2636
- url: normalizeWebSocketUrl(legacy.url),
2637
- options: normalizedOptions,
2638
- legacyCallbacks: extractLegacyWebSocketCallbacks(legacy)
2639
- };
2103
+ if (typeof urlOrOptions === "string" || urlOrOptions instanceof URL) {
2104
+ const normalizedOptions = normalizeStandaloneWebSocketOptions(options);
2105
+ return {
2106
+ url: normalizeWebSocketUrl(urlOrOptions),
2107
+ options: normalizedOptions,
2108
+ legacyCallbacks: extractLegacyWebSocketCallbacks(options)
2109
+ };
2110
+ }
2111
+ const legacy = urlOrOptions;
2112
+ const normalizedOptions = normalizeStandaloneWebSocketOptions(legacy);
2113
+ return {
2114
+ url: normalizeWebSocketUrl(legacy.url),
2115
+ options: normalizedOptions,
2116
+ legacyCallbacks: extractLegacyWebSocketCallbacks(legacy)
2117
+ };
2640
2118
  }
2641
2119
  function normalizeSessionWebSocketArgs(urlOrOptions, options) {
2642
- if (typeof urlOrOptions === "string" || urlOrOptions instanceof URL) {
2643
- const normalizedOptions2 = normalizeSessionWebSocketOptions(options);
2644
- return {
2645
- url: normalizeWebSocketUrl(urlOrOptions),
2646
- options: normalizedOptions2,
2647
- legacyCallbacks: extractLegacyWebSocketCallbacks(options)
2648
- };
2649
- }
2650
- const legacy = urlOrOptions;
2651
- const normalizedOptions = normalizeSessionWebSocketOptions(legacy);
2652
- return {
2653
- url: normalizeWebSocketUrl(legacy.url),
2654
- options: normalizedOptions,
2655
- legacyCallbacks: extractLegacyWebSocketCallbacks(legacy)
2656
- };
2120
+ if (typeof urlOrOptions === "string" || urlOrOptions instanceof URL) {
2121
+ const normalizedOptions = normalizeSessionWebSocketOptions(options);
2122
+ return {
2123
+ url: normalizeWebSocketUrl(urlOrOptions),
2124
+ options: normalizedOptions,
2125
+ legacyCallbacks: extractLegacyWebSocketCallbacks(options)
2126
+ };
2127
+ }
2128
+ const legacy = urlOrOptions;
2129
+ const normalizedOptions = normalizeSessionWebSocketOptions(legacy);
2130
+ return {
2131
+ url: normalizeWebSocketUrl(legacy.url),
2132
+ options: normalizedOptions,
2133
+ legacyCallbacks: extractLegacyWebSocketCallbacks(legacy)
2134
+ };
2657
2135
  }
2658
2136
  async function websocket(urlOrOptions, options) {
2659
- const normalized = normalizeStandaloneWebSocketArgs(urlOrOptions, options);
2660
- validateWebSocketProtocols(normalized.options.protocols);
2661
- assertNoManualWebSocketProtocolHeader(normalized.options.headers);
2662
- const emulationMode = resolveEmulationMode(
2663
- normalized.options.browser,
2664
- normalized.options.os,
2665
- normalized.options.emulation
2666
- );
2667
- const protocols = normalizeWebSocketProtocolList(normalized.options.protocols);
2668
- return WebSocket._connectWithInit({
2669
- _internal: true,
2670
- url: normalized.url,
2671
- options: normalized.options,
2672
- openDispatchMode: "deferred",
2673
- connect: (callbacks) => {
2674
- const nativeOptions = {
2675
- url: normalized.url,
2676
- headers: headersToTuples(normalized.options.headers ?? {}),
2677
- ...protocols && protocols.length > 0 && { protocols },
2678
- ...normalized.options.proxy !== void 0 && { proxy: normalized.options.proxy },
2679
- onMessage: callbacks.onMessage,
2680
- onClose: callbacks.onClose,
2681
- onError: callbacks.onError
2682
- };
2683
- applyNativeEmulationMode(nativeOptions, emulationMode);
2684
- return nativeBinding.websocketConnect(nativeOptions);
2685
- },
2686
- legacyCallbacks: normalized.legacyCallbacks
2687
- });
2137
+ const normalized = normalizeStandaloneWebSocketArgs(urlOrOptions, options);
2138
+ validateWebSocketProtocols(normalized.options.protocols);
2139
+ assertNoManualWebSocketProtocolHeader(normalized.options.headers);
2140
+ const emulationMode = resolveEmulationMode(normalized.options.browser, normalized.options.os, normalized.options.emulation);
2141
+ const protocols = normalizeWebSocketProtocolList(normalized.options.protocols);
2142
+ return WebSocket._connectWithInit({
2143
+ _internal: true,
2144
+ url: normalized.url,
2145
+ options: normalized.options,
2146
+ openDispatchMode: "deferred",
2147
+ connect: (callbacks) => {
2148
+ const nativeOptions = {
2149
+ url: normalized.url,
2150
+ headers: headersToTuples(normalized.options.headers ?? {}),
2151
+ ...protocols && protocols.length > 0 && { protocols },
2152
+ ...normalized.options.proxy !== void 0 && { proxy: normalized.options.proxy },
2153
+ ...normalized.options.maxFrameSize !== void 0 && { maxFrameSize: normalized.options.maxFrameSize },
2154
+ ...normalized.options.maxMessageSize !== void 0 && { maxMessageSize: normalized.options.maxMessageSize },
2155
+ onMessage: callbacks.onMessage,
2156
+ onClose: callbacks.onClose,
2157
+ onError: callbacks.onError
2158
+ };
2159
+ applyNativeEmulationMode(nativeOptions, emulationMode);
2160
+ return nativeBinding.websocketConnect(nativeOptions);
2161
+ },
2162
+ legacyCallbacks: normalized.legacyCallbacks
2163
+ });
2688
2164
  }
2689
2165
  var wreq_js_default = {
2690
- fetch,
2691
- request,
2692
- get,
2693
- post,
2694
- getProfiles,
2695
- getOperatingSystems,
2696
- createTransport,
2697
- createSession,
2698
- withSession,
2699
- websocket,
2700
- WebSocket,
2701
- Headers,
2702
- Response,
2703
- Transport,
2704
- Session,
2705
- RequestError
2706
- };
2707
- export {
2708
- Headers,
2709
- RequestError,
2710
- Response,
2711
- Session,
2712
- Transport,
2713
- WebSocket,
2714
- createSession,
2715
- createTransport,
2716
- wreq_js_default as default,
2717
- fetch,
2718
- get,
2719
- getOperatingSystems,
2720
- getProfiles,
2721
- post,
2722
- request,
2723
- websocket,
2724
- withSession
2166
+ fetch,
2167
+ request,
2168
+ get,
2169
+ post,
2170
+ getProfiles,
2171
+ getOperatingSystems,
2172
+ createTransport,
2173
+ createSession,
2174
+ withSession,
2175
+ websocket,
2176
+ WebSocket,
2177
+ Headers,
2178
+ Response,
2179
+ Transport,
2180
+ Session,
2181
+ RequestError
2725
2182
  };
2183
+ //#endregion
2184
+ export { Headers, RequestError, Response, Session, Transport, WebSocket, createSession, createTransport, wreq_js_default as default, fetch, get, getOperatingSystems, getProfiles, post, request, websocket, withSession };
2185
+
2726
2186
  //# sourceMappingURL=wreq-js.js.map