File size: 30,547 Bytes
9ada4bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }


var _chunkMQJ3JOOKjs = require('./chunk-MQJ3JOOK.js');







var _chunkE4AC7YACjs = require('./chunk-E4AC7YAC.js');

// src/interceptors/ClientRequest/index.ts
var _http = require('http'); var _http2 = _interopRequireDefault(_http);
var _https = require('https'); var _https2 = _interopRequireDefault(_https);

// src/interceptors/ClientRequest/NodeClientRequest.ts

var _until = require('@open-draft/until');
var _deferredpromise = require('@open-draft/deferred-promise');

// src/interceptors/ClientRequest/utils/normalizeClientRequestEndArgs.ts
var _logger = require('@open-draft/logger');
var logger = new (0, _logger.Logger)("utils getUrlByRequestOptions");
function normalizeClientRequestEndArgs(...args) {
  logger.info("arguments", args);
  const normalizedArgs = new Array(3).fill(null).map((value, index) => args[index] || value);
  normalizedArgs.sort((a, b) => {
    if (typeof a === "function") {
      return 1;
    }
    if (typeof b === "function") {
      return -1;
    }
    if (typeof a === "string" && typeof b === "string") {
      return normalizedArgs.indexOf(a) - normalizedArgs.indexOf(b);
    }
    return 0;
  });
  logger.info("normalized args", normalizedArgs);
  return normalizedArgs;
}

// src/interceptors/ClientRequest/utils/normalizeClientRequestWriteArgs.ts

var logger2 = new (0, _logger.Logger)("http normalizeWriteArgs");
function normalizeClientRequestWriteArgs(args) {
  logger2.info("normalizing ClientRequest.write arguments...", args);
  const chunk = args[0];
  const encoding = typeof args[1] === "string" ? args[1] : void 0;
  const callback = typeof args[1] === "function" ? args[1] : args[2];
  const writeArgs = [
    chunk,
    encoding,
    callback
  ];
  logger2.info(
    "successfully normalized ClientRequest.write arguments:",
    writeArgs
  );
  return writeArgs;
}

// src/interceptors/ClientRequest/utils/cloneIncomingMessage.ts

var _stream = require('stream');
var IS_CLONE = Symbol("isClone");
function cloneIncomingMessage(message) {
  const clone = message.pipe(new (0, _stream.PassThrough)());
  inheritProperties(message, clone);
  const clonedPrototype = Object.create(_http.IncomingMessage.prototype);
  getPrototypes(clone).forEach((prototype) => {
    inheritProperties(prototype, clonedPrototype);
  });
  Object.setPrototypeOf(clone, clonedPrototype);
  Object.defineProperty(clone, IS_CLONE, {
    enumerable: true,
    value: true
  });
  return clone;
}
function getPrototypes(source) {
  const prototypes = [];
  let current = source;
  while (current = Object.getPrototypeOf(current)) {
    prototypes.push(current);
  }
  return prototypes;
}
function inheritProperties(source, target) {
  const properties = [
    ...Object.getOwnPropertyNames(source),
    ...Object.getOwnPropertySymbols(source)
  ];
  for (const property of properties) {
    if (target.hasOwnProperty(property)) {
      continue;
    }
    const descriptor = Object.getOwnPropertyDescriptor(source, property);
    if (!descriptor) {
      continue;
    }
    Object.defineProperty(target, property, descriptor);
  }
}

// src/interceptors/ClientRequest/utils/createResponse.ts
function createResponse(message) {
  const responseBodyOrNull = _chunkE4AC7YACjs.isResponseWithoutBody.call(void 0, message.statusCode || 200) ? null : new ReadableStream({
    start(controller) {
      message.on("data", (chunk) => controller.enqueue(chunk));
      message.on("end", () => controller.close());
    }
  });
  return new Response(responseBodyOrNull, {
    status: message.statusCode,
    statusText: message.statusMessage,
    headers: createHeadersFromIncomingHttpHeaders(message.headers)
  });
}
function createHeadersFromIncomingHttpHeaders(httpHeaders) {
  const headers = new Headers();
  for (const headerName in httpHeaders) {
    const headerValues = httpHeaders[headerName];
    if (typeof headerValues === "undefined") {
      continue;
    }
    if (Array.isArray(headerValues)) {
      headerValues.forEach((headerValue) => {
        headers.append(headerName, headerValue);
      });
      continue;
    }
    headers.set(headerName, headerValues);
  }
  return headers;
}

// src/interceptors/ClientRequest/utils/createRequest.ts
function createRequest(clientRequest) {
  const headers = new Headers();
  const outgoingHeaders = clientRequest.getHeaders();
  for (const headerName in outgoingHeaders) {
    const headerValue = outgoingHeaders[headerName];
    if (typeof headerValue === "undefined") {
      continue;
    }
    const valuesList = Array.prototype.concat([], headerValue);
    for (const value of valuesList) {
      headers.append(headerName, value.toString());
    }
  }
  if (clientRequest.url.username || clientRequest.url.password) {
    const username = decodeURIComponent(clientRequest.url.username || "");
    const password = decodeURIComponent(clientRequest.url.password || "");
    const auth = `${username}:${password}`;
    headers.set("Authorization", `Basic ${btoa(auth)}`);
    clientRequest.url.username = "";
    clientRequest.url.password = "";
  }
  const method = clientRequest.method || "GET";
  return new Request(clientRequest.url, {
    method,
    headers,
    credentials: "same-origin",
    body: method === "HEAD" || method === "GET" ? null : clientRequest.requestBuffer
  });
}

// src/utils/getValueBySymbol.ts
function getValueBySymbol(symbolName, source) {
  const ownSymbols = Object.getOwnPropertySymbols(source);
  const symbol = ownSymbols.find((symbol2) => {
    return symbol2.description === symbolName;
  });
  if (symbol) {
    return Reflect.get(source, symbol);
  }
  return;
}

// src/utils/isObject.ts
function isObject(value, loose = false) {
  return loose ? Object.prototype.toString.call(value).startsWith("[object ") : Object.prototype.toString.call(value) === "[object Object]";
}

// src/utils/getRawFetchHeaders.ts
function getRawFetchHeaders(headers) {
  const headersList = getValueBySymbol("headers list", headers);
  if (!headersList) {
    return;
  }
  const headersMap = getValueBySymbol("headers map", headersList);
  if (!headersMap || !isHeadersMapWithRawHeaderNames(headersMap)) {
    return;
  }
  const rawHeaders = /* @__PURE__ */ new Map();
  headersMap.forEach(({ name, value }) => {
    rawHeaders.set(name, value);
  });
  return rawHeaders;
}
function isHeadersMapWithRawHeaderNames(headersMap) {
  return Array.from(
    headersMap.values()
  ).every((value) => {
    return isObject(value) && "name" in value;
  });
}

// src/utils/isNodeLikeError.ts
function isNodeLikeError(error) {
  if (error == null) {
    return false;
  }
  if (!(error instanceof Error)) {
    return false;
  }
  return "code" in error && "errno" in error;
}

// src/interceptors/ClientRequest/NodeClientRequest.ts
var _NodeClientRequest = class extends _http.ClientRequest {
  constructor([url, requestOptions, callback], options) {
    super(requestOptions, callback);
    this.chunks = [];
    this.logger = options.logger.extend(
      `request ${requestOptions.method} ${url.href}`
    );
    this.logger.info("constructing ClientRequest using options:", {
      url,
      requestOptions,
      callback
    });
    this.state = 0 /* Idle */;
    this.url = url;
    this.emitter = options.emitter;
    this.requestBuffer = null;
    this.response = new (0, _http.IncomingMessage)(this.socket);
  }
  writeRequestBodyChunk(chunk, encoding) {
    if (chunk == null) {
      return;
    }
    if (this.requestBuffer == null) {
      this.requestBuffer = Buffer.from([]);
    }
    const resolvedChunk = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding);
    this.requestBuffer = Buffer.concat([this.requestBuffer, resolvedChunk]);
  }
  write(...args) {
    var _a;
    const [chunk, encoding, callback] = normalizeClientRequestWriteArgs(args);
    this.logger.info("write:", { chunk, encoding, callback });
    this.chunks.push({ chunk, encoding });
    this.writeRequestBodyChunk(chunk, encoding);
    this.logger.info(
      "chunk successfully stored!",
      (_a = this.requestBuffer) == null ? void 0 : _a.byteLength
    );
    if (!chunk || chunk.length === 0) {
      this.logger.info("written chunk is empty, skipping callback...");
    } else {
      callback == null ? void 0 : callback();
    }
    return true;
  }
  end(...args) {
    this.logger.info("end", args);
    const requestId = _chunkE4AC7YACjs.createRequestId.call(void 0, );
    const [chunk, encoding, callback] = normalizeClientRequestEndArgs(...args);
    this.logger.info("normalized arguments:", { chunk, encoding, callback });
    this.writeRequestBodyChunk(chunk, encoding || void 0);
    this.state = 2 /* Sent */;
    const capturedRequest = createRequest(this);
    const { interactiveRequest, requestController } = _chunkMQJ3JOOKjs.toInteractiveRequest.call(void 0, capturedRequest);
    Object.defineProperty(capturedRequest, "respondWith", {
      value: requestController.respondWith.bind(requestController)
    });
    if (this.hasHeader(_chunkE4AC7YACjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {
      this.removeHeader(_chunkE4AC7YACjs.INTERNAL_REQUEST_ID_HEADER_NAME);
      return this.passthrough(chunk, encoding, callback);
    }
    this.emitter.once("request", ({ requestId: pendingRequestId }) => {
      if (pendingRequestId !== requestId) {
        return;
      }
      if (requestController.responsePromise.state === "pending") {
        this.logger.info(
          "request has not been handled in listeners, executing fail-safe listener..."
        );
        requestController.responsePromise.resolve(void 0);
      }
    });
    _until.until.call(void 0, async () => {
      this.logger.info(
        'emitting the "request" event for %d listener(s)...',
        this.emitter.listenerCount("request")
      );
      this.state = 3 /* MockLookupStart */;
      await _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "request", {
        request: interactiveRequest,
        requestId
      });
      this.logger.info('all "request" listeners done!');
      const mockedResponse = await requestController.responsePromise;
      this.logger.info("event.respondWith called with:", mockedResponse);
      return mockedResponse;
    }).then((resolverResult) => {
      this.logger.info("the listeners promise awaited!");
      this.state = 4 /* MockLookupEnd */;
      if (!this.headersSent) {
        for (const [headerName, headerValue] of capturedRequest.headers) {
          this.setHeader(headerName, headerValue);
        }
      }
      if (resolverResult.error) {
        this.logger.info(
          "unhandled resolver exception, coercing to an error response...",
          resolverResult.error
        );
        if (resolverResult.error instanceof Response) {
          if (_chunkE4AC7YACjs.isResponseError.call(void 0, resolverResult.error)) {
            this.logger.info(
              "received network error response, erroring request..."
            );
            this.errorWith(new TypeError("Network error"));
          } else {
            this.respondWith(resolverResult.error);
          }
          return;
        }
        if (isNodeLikeError(resolverResult.error)) {
          this.errorWith(resolverResult.error);
          return this;
        }
        _until.until.call(void 0, async () => {
          if (this.emitter.listenerCount("unhandledException") > 0) {
            await _chunkMQJ3JOOKjs.emitAsync.call(void 0, this.emitter, "unhandledException", {
              error: resolverResult.error,
              request: capturedRequest,
              requestId,
              controller: {
                respondWith: this.respondWith.bind(this),
                errorWith: this.errorWith.bind(this)
              }
            });
            if (this.writableEnded || this.destroyed) {
              return;
            }
          }
          this.respondWith(_chunkE4AC7YACjs.createServerErrorResponse.call(void 0, resolverResult.error));
        });
        return this;
      }
      const mockedResponse = resolverResult.data;
      if (mockedResponse) {
        this.logger.info(
          "received mocked response:",
          mockedResponse.status,
          mockedResponse.statusText
        );
        this.destroyed = false;
        if (_chunkE4AC7YACjs.isResponseError.call(void 0, mockedResponse)) {
          this.logger.info(
            "received network error response, erroring request..."
          );
          this.errorWith(new TypeError("Network error"));
          return this;
        }
        const responseClone = mockedResponse.clone();
        this.respondWith(mockedResponse);
        this.logger.info(
          mockedResponse.status,
          mockedResponse.statusText,
          "(MOCKED)"
        );
        callback == null ? void 0 : callback();
        this.logger.info('emitting the custom "response" event...');
        this.emitter.emit("response", {
          response: responseClone,
          isMockedResponse: true,
          request: capturedRequest,
          requestId
        });
        this.logger.info("request (mock) is completed");
        return this;
      }
      this.logger.info("no mocked response received!");
      this.once("response-internal", (message) => {
        this.logger.info(message.statusCode, message.statusMessage);
        this.logger.info("original response headers:", message.headers);
        this.logger.info('emitting the custom "response" event...');
        this.emitter.emit("response", {
          response: createResponse(message),
          isMockedResponse: false,
          request: capturedRequest,
          requestId
        });
      });
      return this.passthrough(chunk, encoding, callback);
    });
    return this;
  }
  emit(event, ...data) {
    this.logger.info("emit: %s", event);
    if (event === "response") {
      this.logger.info('found "response" event, cloning the response...');
      try {
        const response = data[0];
        const firstClone = cloneIncomingMessage(response);
        const secondClone = cloneIncomingMessage(response);
        this.emit("response-internal", secondClone);
        this.logger.info(
          'response successfully cloned, emitting "response" event...'
        );
        return super.emit(event, firstClone, ...data.slice(1));
      } catch (error) {
        this.logger.info("error when cloning response:", error);
        return super.emit(event, ...data);
      }
    }
    if (event === "error") {
      const error = data[0];
      const errorCode = error.code || "";
      this.logger.info("error:\n", error);
      if (_NodeClientRequest.suppressErrorCodes.includes(errorCode)) {
        if (this.state < 4 /* MockLookupEnd */) {
          if (!this.capturedError) {
            this.capturedError = error;
            this.logger.info("captured the first error:", this.capturedError);
          }
          return false;
        }
        if (this.state === 5 /* ResponseReceived */ && this.responseType === "mock") {
          return false;
        }
      }
    }
    return super.emit(event, ...data);
  }
  /**
   * Performs the intercepted request as-is.
   * Replays the captured request body chunks,
   * still emits the internal events, and wraps
   * up the request with `super.end()`.
   */
  passthrough(chunk, encoding, callback) {
    this.state = 5 /* ResponseReceived */;
    this.responseType = "passthrough";
    if (this.capturedError) {
      this.emit("error", this.capturedError);
      return this;
    }
    this.logger.info("writing request chunks...", this.chunks);
    for (const { chunk: chunk2, encoding: encoding2 } of this.chunks) {
      if (encoding2) {
        super.write(chunk2, encoding2);
      } else {
        super.write(chunk2);
      }
    }
    this.once("error", (error) => {
      this.logger.info("original request error:", error);
    });
    this.once("abort", () => {
      this.logger.info("original request aborted!");
    });
    this.once("response-internal", (message) => {
      this.logger.info(message.statusCode, message.statusMessage);
      this.logger.info("original response headers:", message.headers);
    });
    this.logger.info("performing original request...");
    return super.end(...[chunk, encoding, callback].filter(Boolean));
  }
  /**
   * Responds to this request instance using a mocked response.
   */
  respondWith(mockedResponse) {
    this.logger.info("responding with a mocked response...", mockedResponse);
    this.state = 5 /* ResponseReceived */;
    this.responseType = "mock";
    Object.defineProperties(this, {
      writableFinished: { value: true },
      writableEnded: { value: true }
    });
    this.emit("finish");
    const { status, statusText, headers, body } = mockedResponse;
    this.response.statusCode = status;
    this.response.statusMessage = statusText || _http.STATUS_CODES[status];
    const rawHeaders = getRawFetchHeaders(headers) || headers;
    if (rawHeaders) {
      this.response.headers = {};
      rawHeaders.forEach((headerValue, headerName) => {
        this.response.rawHeaders.push(headerName, headerValue);
        const insensitiveHeaderName = headerName.toLowerCase();
        const prevHeaders = this.response.headers[insensitiveHeaderName];
        this.response.headers[insensitiveHeaderName] = prevHeaders ? Array.prototype.concat([], prevHeaders, headerValue) : headerValue;
      });
    }
    this.logger.info("mocked response headers ready:", headers);
    this.res = this.response;
    this.emit("response", this.response);
    const isResponseStreamFinished = new (0, _deferredpromise.DeferredPromise)();
    const finishResponseStream = () => {
      this.logger.info("finished response stream!");
      this.response.push(null);
      this.response.complete = true;
      isResponseStreamFinished.resolve();
    };
    if (body) {
      const bodyReader = body.getReader();
      const readNextChunk = async () => {
        const { done, value } = await bodyReader.read();
        if (done) {
          finishResponseStream();
          return;
        }
        this.response.emit("data", value);
        return readNextChunk();
      };
      readNextChunk();
    } else {
      finishResponseStream();
    }
    isResponseStreamFinished.then(() => {
      this.logger.info("finalizing response...");
      this.response.emit("end");
      this.terminate();
      this.logger.info("request complete!");
    });
  }
  errorWith(error) {
    this.destroyed = true;
    this.emit("error", error);
    this.terminate();
  }
  /**
   * Terminates a pending request.
   */
  terminate() {
    var _a;
    (_a = this.agent) == null ? void 0 : _a.destroy();
  }
};
var NodeClientRequest = _NodeClientRequest;
/**
 * The list of internal Node.js errors to suppress while
 * using the "mock" response source.
 */
NodeClientRequest.suppressErrorCodes = [
  "ENOTFOUND",
  "ECONNREFUSED",
  "ECONNRESET",
  "EAI_AGAIN",
  "ENETUNREACH",
  "EHOSTUNREACH"
];

// src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts








var _url = require('url');


// src/utils/getRequestOptionsByUrl.ts
function getRequestOptionsByUrl(url) {
  const options = {
    method: "GET",
    protocol: url.protocol,
    hostname: typeof url.hostname === "string" && url.hostname.startsWith("[") ? url.hostname.slice(1, -1) : url.hostname,
    host: url.host,
    path: `${url.pathname}${url.search || ""}`
  };
  if (!!url.port) {
    options.port = Number(url.port);
  }
  if (url.username || url.password) {
    options.auth = `${url.username}:${url.password}`;
  }
  return options;
}

// src/utils/getUrlByRequestOptions.ts


var logger3 = new (0, _logger.Logger)("utils getUrlByRequestOptions");
var DEFAULT_PATH = "/";
var DEFAULT_PROTOCOL = "http:";
var DEFAULT_HOSTNAME = "localhost";
var SSL_PORT = 443;
function getAgent(options) {
  return options.agent instanceof _http.Agent ? options.agent : void 0;
}
function getProtocolByRequestOptions(options) {
  var _a;
  if (options.protocol) {
    return options.protocol;
  }
  const agent = getAgent(options);
  const agentProtocol = agent == null ? void 0 : agent.protocol;
  if (agentProtocol) {
    return agentProtocol;
  }
  const port = getPortByRequestOptions(options);
  const isSecureRequest = options.cert || port === SSL_PORT;
  return isSecureRequest ? "https:" : ((_a = options.uri) == null ? void 0 : _a.protocol) || DEFAULT_PROTOCOL;
}
function getPortByRequestOptions(options) {
  if (options.port) {
    return Number(options.port);
  }
  const agent = getAgent(options);
  if (agent == null ? void 0 : agent.options.port) {
    return Number(agent.options.port);
  }
  if (agent == null ? void 0 : agent.defaultPort) {
    return Number(agent.defaultPort);
  }
  return void 0;
}
function getAuthByRequestOptions(options) {
  if (options.auth) {
    const [username, password] = options.auth.split(":");
    return { username, password };
  }
}
function isRawIPv6Address(host) {
  return host.includes(":") && !host.startsWith("[") && !host.endsWith("]");
}
function getHostname(options) {
  let host = options.hostname || options.host;
  if (host) {
    if (isRawIPv6Address(host)) {
      host = `[${host}]`;
    }
    return new URL(`http://${host}`).hostname;
  }
  return DEFAULT_HOSTNAME;
}
function getUrlByRequestOptions(options) {
  logger3.info("request options", options);
  if (options.uri) {
    logger3.info(
      'constructing url from explicitly provided "options.uri": %s',
      options.uri
    );
    return new URL(options.uri.href);
  }
  logger3.info("figuring out url from request options...");
  const protocol = getProtocolByRequestOptions(options);
  logger3.info("protocol", protocol);
  const port = getPortByRequestOptions(options);
  logger3.info("port", port);
  const hostname = getHostname(options);
  logger3.info("hostname", hostname);
  const path = options.path || DEFAULT_PATH;
  logger3.info("path", path);
  const credentials = getAuthByRequestOptions(options);
  logger3.info("credentials", credentials);
  const authString = credentials ? `${credentials.username}:${credentials.password}@` : "";
  logger3.info("auth string:", authString);
  const portString = typeof port !== "undefined" ? `:${port}` : "";
  const url = new URL(`${protocol}//${hostname}${portString}${path}`);
  url.username = (credentials == null ? void 0 : credentials.username) || "";
  url.password = (credentials == null ? void 0 : credentials.password) || "";
  logger3.info("created url:", url);
  return url;
}

// src/utils/cloneObject.ts

var logger4 = new (0, _logger.Logger)("cloneObject");
function isPlainObject(obj) {
  var _a;
  logger4.info("is plain object?", obj);
  if (obj == null || !((_a = obj.constructor) == null ? void 0 : _a.name)) {
    logger4.info("given object is undefined, not a plain object...");
    return false;
  }
  logger4.info("checking the object constructor:", obj.constructor.name);
  return obj.constructor.name === "Object";
}
function cloneObject(obj) {
  logger4.info("cloning object:", obj);
  const enumerableProperties = Object.entries(obj).reduce(
    (acc, [key, value]) => {
      logger4.info("analyzing key-value pair:", key, value);
      acc[key] = isPlainObject(value) ? cloneObject(value) : value;
      return acc;
    },
    {}
  );
  return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties);
}

// src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts
var logger5 = new (0, _logger.Logger)("http normalizeClientRequestArgs");
function resolveRequestOptions(args, url) {
  if (typeof args[1] === "undefined" || typeof args[1] === "function") {
    logger5.info("request options not provided, deriving from the url", url);
    return getRequestOptionsByUrl(url);
  }
  if (args[1]) {
    logger5.info("has custom RequestOptions!", args[1]);
    const requestOptionsFromUrl = getRequestOptionsByUrl(url);
    logger5.info("derived RequestOptions from the URL:", requestOptionsFromUrl);
    logger5.info("cloning RequestOptions...");
    const clonedRequestOptions = cloneObject(args[1]);
    logger5.info("successfully cloned RequestOptions!", clonedRequestOptions);
    return {
      ...requestOptionsFromUrl,
      ...clonedRequestOptions
    };
  }
  logger5.info("using an empty object as request options");
  return {};
}
function overrideUrlByRequestOptions(url, options) {
  url.host = options.host || url.host;
  url.hostname = options.hostname || url.hostname;
  url.port = options.port ? options.port.toString() : url.port;
  if (options.path) {
    const parsedOptionsPath = _url.parse.call(void 0, options.path, false);
    url.pathname = parsedOptionsPath.pathname || "";
    url.search = parsedOptionsPath.search || "";
  }
  return url;
}
function resolveCallback(args) {
  return typeof args[1] === "function" ? args[1] : args[2];
}
function normalizeClientRequestArgs(defaultProtocol, ...args) {
  let url;
  let options;
  let callback;
  logger5.info("arguments", args);
  logger5.info("using default protocol:", defaultProtocol);
  if (args.length === 0) {
    const url2 = new URL("http://localhost");
    const options2 = resolveRequestOptions(args, url2);
    return [url2, options2];
  }
  if (typeof args[0] === "string") {
    logger5.info("first argument is a location string:", args[0]);
    url = new URL(args[0]);
    logger5.info("created a url:", url);
    const requestOptionsFromUrl = getRequestOptionsByUrl(url);
    logger5.info("request options from url:", requestOptionsFromUrl);
    options = resolveRequestOptions(args, url);
    logger5.info("resolved request options:", options);
    callback = resolveCallback(args);
  } else if (args[0] instanceof URL) {
    url = args[0];
    logger5.info("first argument is a URL:", url);
    if (typeof args[1] !== "undefined" && isObject(args[1])) {
      url = overrideUrlByRequestOptions(url, args[1]);
    }
    options = resolveRequestOptions(args, url);
    logger5.info("derived request options:", options);
    callback = resolveCallback(args);
  } else if ("hash" in args[0] && !("method" in args[0])) {
    const [legacyUrl] = args;
    logger5.info("first argument is a legacy URL:", legacyUrl);
    if (legacyUrl.hostname === null) {
      logger5.info("given legacy URL is relative (no hostname)");
      return isObject(args[1]) ? normalizeClientRequestArgs(
        defaultProtocol,
        { path: legacyUrl.path, ...args[1] },
        args[2]
      ) : normalizeClientRequestArgs(
        defaultProtocol,
        { path: legacyUrl.path },
        args[1]
      );
    }
    logger5.info("given legacy url is absolute");
    const resolvedUrl = new URL(legacyUrl.href);
    return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, resolvedUrl, args[1]) : normalizeClientRequestArgs(
      defaultProtocol,
      resolvedUrl,
      args[1],
      args[2]
    );
  } else if (isObject(args[0])) {
    options = args[0];
    logger5.info("first argument is RequestOptions:", options);
    options.protocol = options.protocol || defaultProtocol;
    logger5.info("normalized request options:", options);
    url = getUrlByRequestOptions(options);
    logger5.info("created a URL from RequestOptions:", url.href);
    callback = resolveCallback(args);
  } else {
    throw new Error(
      `Failed to construct ClientRequest with these parameters: ${args}`
    );
  }
  options.protocol = options.protocol || url.protocol;
  options.method = options.method || "GET";
  if (typeof options.agent === "undefined") {
    const agent = options.protocol === "https:" ? new (0, _https.Agent)({
      rejectUnauthorized: options.rejectUnauthorized
    }) : new (0, _http.Agent)();
    options.agent = agent;
    logger5.info("resolved fallback agent:", agent);
  }
  if (!options._defaultAgent) {
    logger5.info(
      'has no default agent, setting the default agent for "%s"',
      options.protocol
    );
    options._defaultAgent = options.protocol === "https:" ? _https.globalAgent : _http.globalAgent;
  }
  logger5.info("successfully resolved url:", url.href);
  logger5.info("successfully resolved options:", options);
  logger5.info("successfully resolved callback:", callback);
  return [url, options, callback];
}

// src/interceptors/ClientRequest/http.get.ts
function get(protocol, options) {
  return function interceptorsHttpGet(...args) {
    const clientRequestArgs = normalizeClientRequestArgs(
      `${protocol}:`,
      ...args
    );
    const request2 = new NodeClientRequest(clientRequestArgs, options);
    request2.end();
    return request2;
  };
}

// src/interceptors/ClientRequest/http.request.ts

var logger6 = new (0, _logger.Logger)("http request");
function request(protocol, options) {
  return function interceptorsHttpRequest(...args) {
    logger6.info('request call (protocol "%s"):', protocol, args);
    const clientRequestArgs = normalizeClientRequestArgs(
      `${protocol}:`,
      ...args
    );
    return new NodeClientRequest(clientRequestArgs, options);
  };
}

// src/interceptors/ClientRequest/index.ts
var _ClientRequestInterceptor = class extends _chunkE4AC7YACjs.Interceptor {
  constructor() {
    super(_ClientRequestInterceptor.interceptorSymbol);
    this.modules = /* @__PURE__ */ new Map();
    this.modules.set("http", _http2.default);
    this.modules.set("https", _https2.default);
  }
  setup() {
    const logger7 = this.logger.extend("setup");
    for (const [protocol, requestModule] of this.modules) {
      const { request: pureRequest, get: pureGet } = requestModule;
      this.subscriptions.push(() => {
        requestModule.request = pureRequest;
        requestModule.get = pureGet;
        logger7.info('native "%s" module restored!', protocol);
      });
      const options = {
        emitter: this.emitter,
        logger: this.logger
      };
      requestModule.request = // Force a line break.
      request(protocol, options);
      requestModule.get = // Force a line break.
      get(protocol, options);
      logger7.info('native "%s" module patched!', protocol);
    }
  }
};
var ClientRequestInterceptor = _ClientRequestInterceptor;
ClientRequestInterceptor.interceptorSymbol = Symbol("http");



exports.ClientRequestInterceptor = ClientRequestInterceptor;
//# sourceMappingURL=chunk-SXGRMPXP.js.map