basant307/AI_Governance_Project
048
1"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }2 3var _chunk4YBV77DGjs = require('./chunk-4YBV77DG.js');4 5 6 7 8 9 10 11var _chunkC2JSMMHYjs = require('./chunk-C2JSMMHY.js');12 13 14 15 16 17var _chunkA7U44ARPjs = require('./chunk-A7U44ARP.js');18 19 20var _chunkSMXZPJEAjs = require('./chunk-SMXZPJEA.js');21 22// src/interceptors/ClientRequest/index.ts23var _http = require('http'); var _http2 = _interopRequireDefault(_http);24var _https = require('https'); var _https2 = _interopRequireDefault(_https);25 26// src/interceptors/ClientRequest/MockHttpSocket.ts27var _net = require('net'); var _net2 = _interopRequireDefault(_net);28 29 30var __http_common = require('_http_common');31 32var _stream = require('stream');33var _outvariant = require('outvariant');34 35// src/interceptors/Socket/MockSocket.ts36 37 38// src/interceptors/Socket/utils/normalizeSocketWriteArgs.ts39function normalizeSocketWriteArgs(args) {40 const normalized = [args[0], void 0, void 0];41 if (typeof args[1] === "string") {42 normalized[1] = args[1];43 } else if (typeof args[1] === "function") {44 normalized[2] = args[1];45 }46 if (typeof args[2] === "function") {47 normalized[2] = args[2];48 }49 return normalized;50}51 52// src/interceptors/Socket/MockSocket.ts53var MockSocket = class extends _net2.default.Socket {54 constructor(options) {55 super();56 this.options = options;57 this.connecting = false;58 this.connect();59 this._final = (callback) => {60 callback(null);61 };62 }63 connect() {64 this.connecting = true;65 return this;66 }67 write(...args) {68 const [chunk, encoding, callback] = normalizeSocketWriteArgs(69 args70 );71 this.options.write(chunk, encoding, callback);72 return true;73 }74 end(...args) {75 const [chunk, encoding, callback] = normalizeSocketWriteArgs(76 args77 );78 this.options.write(chunk, encoding, callback);79 return super.end.apply(this, args);80 }81 push(chunk, encoding) {82 this.options.read(chunk, encoding);83 return super.push(chunk, encoding);84 }85};86 87// src/interceptors/Socket/utils/baseUrlFromConnectionOptions.ts88function baseUrlFromConnectionOptions(options) {89 if ("href" in options) {90 return new URL(options.href);91 }92 const protocol = options.port === 443 ? "https:" : "http:";93 const host = options.host;94 const url = new URL(`${protocol}//${host}`);95 if (options.port) {96 url.port = options.port.toString();97 }98 if (options.path) {99 url.pathname = options.path;100 }101 if (options.auth) {102 const [username, password] = options.auth.split(":");103 url.username = username;104 url.password = password;105 }106 return url;107}108 109// src/interceptors/ClientRequest/utils/recordRawHeaders.ts110var kRawHeaders = Symbol("kRawHeaders");111var kRestorePatches = Symbol("kRestorePatches");112function recordRawHeader(headers, args, behavior) {113 ensureRawHeadersSymbol(headers, []);114 const rawHeaders = Reflect.get(headers, kRawHeaders);115 if (behavior === "set") {116 for (let index = rawHeaders.length - 1; index >= 0; index--) {117 if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {118 rawHeaders.splice(index, 1);119 }120 }121 }122 rawHeaders.push(args);123}124function ensureRawHeadersSymbol(headers, rawHeaders) {125 if (Reflect.has(headers, kRawHeaders)) {126 return;127 }128 defineRawHeadersSymbol(headers, rawHeaders);129}130function defineRawHeadersSymbol(headers, rawHeaders) {131 Object.defineProperty(headers, kRawHeaders, {132 value: rawHeaders,133 enumerable: false,134 // Mark the symbol as configurable so its value can be overridden.135 // Overrides happen when merging raw headers from multiple sources.136 // E.g. new Request(new Request(url, { headers }), { headers })137 configurable: true138 });139}140function recordRawFetchHeaders() {141 if (Reflect.get(Headers, kRestorePatches)) {142 return Reflect.get(Headers, kRestorePatches);143 }144 const {145 Headers: OriginalHeaders,146 Request: OriginalRequest,147 Response: OriginalResponse148 } = globalThis;149 const { set, append, delete: headersDeleteMethod } = Headers.prototype;150 Object.defineProperty(Headers, kRestorePatches, {151 value: () => {152 Headers.prototype.set = set;153 Headers.prototype.append = append;154 Headers.prototype.delete = headersDeleteMethod;155 globalThis.Headers = OriginalHeaders;156 globalThis.Request = OriginalRequest;157 globalThis.Response = OriginalResponse;158 Reflect.deleteProperty(Headers, kRestorePatches);159 },160 enumerable: false,161 /**162 * @note Mark this property as configurable163 * so we can delete it using `Reflect.delete` during cleanup.164 */165 configurable: true166 });167 Object.defineProperty(globalThis, "Headers", {168 enumerable: true,169 writable: true,170 value: new Proxy(Headers, {171 construct(target, args, newTarget) {172 const headersInit = args[0] || [];173 if (headersInit instanceof Headers && Reflect.has(headersInit, kRawHeaders)) {174 const headers2 = Reflect.construct(175 target,176 [Reflect.get(headersInit, kRawHeaders)],177 newTarget178 );179 ensureRawHeadersSymbol(headers2, [180 /**181 * @note Spread the retrieved headers to clone them.182 * This prevents multiple Headers instances from pointing183 * at the same internal "rawHeaders" array.184 */185 ...Reflect.get(headersInit, kRawHeaders)186 ]);187 return headers2;188 }189 const headers = Reflect.construct(target, args, newTarget);190 if (!Reflect.has(headers, kRawHeaders)) {191 const rawHeadersInit = Array.isArray(headersInit) ? headersInit : Object.entries(headersInit);192 ensureRawHeadersSymbol(headers, rawHeadersInit);193 }194 return headers;195 }196 })197 });198 Headers.prototype.set = new Proxy(Headers.prototype.set, {199 apply(target, thisArg, args) {200 recordRawHeader(thisArg, args, "set");201 return Reflect.apply(target, thisArg, args);202 }203 });204 Headers.prototype.append = new Proxy(Headers.prototype.append, {205 apply(target, thisArg, args) {206 recordRawHeader(thisArg, args, "append");207 return Reflect.apply(target, thisArg, args);208 }209 });210 Headers.prototype.delete = new Proxy(Headers.prototype.delete, {211 apply(target, thisArg, args) {212 const rawHeaders = Reflect.get(thisArg, kRawHeaders);213 if (rawHeaders) {214 for (let index = rawHeaders.length - 1; index >= 0; index--) {215 if (rawHeaders[index][0].toLowerCase() === args[0].toLowerCase()) {216 rawHeaders.splice(index, 1);217 }218 }219 }220 return Reflect.apply(target, thisArg, args);221 }222 });223 Object.defineProperty(globalThis, "Request", {224 enumerable: true,225 writable: true,226 value: new Proxy(Request, {227 construct(target, args, newTarget) {228 const request = Reflect.construct(target, args, newTarget);229 const inferredRawHeaders = [];230 if (typeof args[0] === "object" && args[0].headers != null) {231 inferredRawHeaders.push(...inferRawHeaders(args[0].headers));232 }233 if (typeof args[1] === "object" && args[1].headers != null) {234 inferredRawHeaders.push(...inferRawHeaders(args[1].headers));235 }236 if (inferredRawHeaders.length > 0) {237 ensureRawHeadersSymbol(request.headers, inferredRawHeaders);238 }239 return request;240 }241 })242 });243 Object.defineProperty(globalThis, "Response", {244 enumerable: true,245 writable: true,246 value: new Proxy(Response, {247 construct(target, args, newTarget) {248 const response = Reflect.construct(target, args, newTarget);249 if (typeof args[1] === "object" && args[1].headers != null) {250 ensureRawHeadersSymbol(251 response.headers,252 inferRawHeaders(args[1].headers)253 );254 }255 return response;256 }257 })258 });259}260function restoreHeadersPrototype() {261 if (!Reflect.get(Headers, kRestorePatches)) {262 return;263 }264 Reflect.get(Headers, kRestorePatches)();265}266function getRawFetchHeaders(headers) {267 if (!Reflect.has(headers, kRawHeaders)) {268 return Array.from(headers.entries());269 }270 const rawHeaders = Reflect.get(headers, kRawHeaders);271 return rawHeaders.length > 0 ? rawHeaders : Array.from(headers.entries());272}273function inferRawHeaders(headers) {274 if (headers instanceof Headers) {275 return Reflect.get(headers, kRawHeaders) || [];276 }277 return Reflect.get(new Headers(headers), kRawHeaders);278}279 280// src/interceptors/ClientRequest/MockHttpSocket.ts281var kRequestId = Symbol("kRequestId");282var MockHttpSocket = class extends MockSocket {283 constructor(options) {284 super({285 write: (chunk, encoding, callback) => {286 var _a;287 if (this.socketState !== "passthrough") {288 this.writeBuffer.push([chunk, encoding, callback]);289 }290 if (chunk) {291 if (this.socketState === "passthrough") {292 (_a = this.originalSocket) == null ? void 0 : _a.write(chunk, encoding, callback);293 }294 this.requestParser.execute(295 Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding)296 );297 }298 },299 read: (chunk) => {300 if (chunk !== null) {301 this.responseParser.execute(302 Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)303 );304 }305 }306 });307 this.requestRawHeadersBuffer = [];308 this.responseRawHeadersBuffer = [];309 this.writeBuffer = [];310 this.socketState = "unknown";311 /**312 * This callback might be called when the request is "slow":313 * - Request headers were fragmented across multiple TCP packages;314 * - Request headers were too large to be processed in a single run315 * (e.g. more than 30 request headers).316 * @note This is called before request start.317 */318 this.onRequestHeaders = (rawHeaders) => {319 this.requestRawHeadersBuffer.push(...rawHeaders);320 };321 this.onRequestStart = (versionMajor, versionMinor, rawHeaders, _, path, __, ___, ____, shouldKeepAlive) => {322 var _a;323 this.shouldKeepAlive = shouldKeepAlive;324 const url = new URL(path || "", this.baseUrl);325 const method = ((_a = this.connectionOptions.method) == null ? void 0 : _a.toUpperCase()) || "GET";326 const headers = _chunkA7U44ARPjs.FetchResponse.parseRawHeaders([327 ...this.requestRawHeadersBuffer,328 ...rawHeaders || []329 ]);330 this.requestRawHeadersBuffer.length = 0;331 const canHaveBody = method !== "GET" && method !== "HEAD";332 if (url.username || url.password) {333 if (!headers.has("authorization")) {334 headers.set("authorization", `Basic ${url.username}:${url.password}`);335 }336 url.username = "";337 url.password = "";338 }339 this.requestStream = new (0, _stream.Readable)({340 /**341 * @note Provide the `read()` method so a `Readable` could be342 * used as the actual request body (the stream calls "read()").343 * We control the queue in the onRequestBody/End functions.344 */345 read: () => {346 this.flushWriteBuffer();347 }348 });349 const requestId = _chunkA7U44ARPjs.createRequestId.call(void 0, );350 this.request = new Request(url, {351 method,352 headers,353 credentials: "same-origin",354 // @ts-expect-error Undocumented Fetch property.355 duplex: canHaveBody ? "half" : void 0,356 body: canHaveBody ? _stream.Readable.toWeb(this.requestStream) : null357 });358 Reflect.set(this.request, kRequestId, requestId);359 _chunkSMXZPJEAjs.setRawRequest.call(void 0, this.request, Reflect.get(this, "_httpMessage"));360 _chunk4YBV77DGjs.setRawRequestBodyStream.call(void 0, this.request, this.requestStream);361 if (this.request.headers.has(_chunkA7U44ARPjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {362 this.passthrough();363 return;364 }365 this.onRequest({366 requestId,367 request: this.request,368 socket: this369 });370 };371 /**372 * This callback might be called when the response is "slow":373 * - Response headers were fragmented across multiple TCP packages;374 * - Response headers were too large to be processed in a single run375 * (e.g. more than 30 response headers).376 * @note This is called before response start.377 */378 this.onResponseHeaders = (rawHeaders) => {379 this.responseRawHeadersBuffer.push(...rawHeaders);380 };381 this.onResponseStart = (versionMajor, versionMinor, rawHeaders, method, url, status, statusText) => {382 const headers = _chunkA7U44ARPjs.FetchResponse.parseRawHeaders([383 ...this.responseRawHeadersBuffer,384 ...rawHeaders || []385 ]);386 this.responseRawHeadersBuffer.length = 0;387 const response = new (0, _chunkA7U44ARPjs.FetchResponse)(388 /**389 * @note The Fetch API response instance exposed to the consumer390 * is created over the response stream of the HTTP parser. It is NOT391 * related to the Socket instance. This way, you can read response body392 * in response listener while the Socket instance delays the emission393 * of "end" and other events until those response listeners are finished.394 */395 _chunkA7U44ARPjs.FetchResponse.isResponseWithBody(status) ? _stream.Readable.toWeb(396 this.responseStream = new (0, _stream.Readable)({ read() {397 } })398 ) : null,399 {400 url,401 status,402 statusText,403 headers404 }405 );406 _outvariant.invariant.call(void 0, 407 this.request,408 "Failed to handle a response: request does not exist"409 );410 _chunkA7U44ARPjs.FetchResponse.setUrl(this.request.url, response);411 if (this.request.headers.has(_chunkA7U44ARPjs.INTERNAL_REQUEST_ID_HEADER_NAME)) {412 return;413 }414 this.responseListenersPromise = this.onResponse({415 response,416 isMockedResponse: this.socketState === "mock",417 requestId: Reflect.get(this.request, kRequestId),418 request: this.request,419 socket: this420 });421 };422 this.connectionOptions = options.connectionOptions;423 this.createConnection = options.createConnection;424 this.onRequest = options.onRequest;425 this.onResponse = options.onResponse;426 this.baseUrl = baseUrlFromConnectionOptions(this.connectionOptions);427 this.requestParser = new (0, __http_common.HTTPParser)();428 this.requestParser.initialize(__http_common.HTTPParser.REQUEST, {});429 this.requestParser[__http_common.HTTPParser.kOnHeaders] = this.onRequestHeaders.bind(this);430 this.requestParser[__http_common.HTTPParser.kOnHeadersComplete] = this.onRequestStart.bind(this);431 this.requestParser[__http_common.HTTPParser.kOnBody] = this.onRequestBody.bind(this);432 this.requestParser[__http_common.HTTPParser.kOnMessageComplete] = this.onRequestEnd.bind(this);433 this.responseParser = new (0, __http_common.HTTPParser)();434 this.responseParser.initialize(__http_common.HTTPParser.RESPONSE, {});435 this.responseParser[__http_common.HTTPParser.kOnHeaders] = this.onResponseHeaders.bind(this);436 this.responseParser[__http_common.HTTPParser.kOnHeadersComplete] = this.onResponseStart.bind(this);437 this.responseParser[__http_common.HTTPParser.kOnBody] = this.onResponseBody.bind(this);438 this.responseParser[__http_common.HTTPParser.kOnMessageComplete] = this.onResponseEnd.bind(this);439 this.once("finish", () => this.requestParser.free());440 if (this.baseUrl.protocol === "https:") {441 Reflect.set(this, "encrypted", true);442 Reflect.set(this, "authorized", false);443 Reflect.set(this, "getProtocol", () => "TLSv1.3");444 Reflect.set(this, "getSession", () => void 0);445 Reflect.set(this, "isSessionReused", () => false);446 }447 }448 emit(event, ...args) {449 const emitEvent = super.emit.bind(this, event, ...args);450 if (this.responseListenersPromise) {451 this.responseListenersPromise.finally(emitEvent);452 return this.listenerCount(event) > 0;453 }454 return emitEvent();455 }456 destroy(error) {457 this.responseParser.free();458 if (error) {459 this.emit("error", error);460 }461 return super.destroy(error);462 }463 /**464 * Establish this Socket connection as-is and pipe465 * its data/events through this Socket.466 */467 passthrough() {468 this.socketState = "passthrough";469 if (this.destroyed) {470 return;471 }472 const socket = this.createConnection();473 this.originalSocket = socket;474 if ("_handle" in socket) {475 Object.defineProperty(this, "_handle", {476 value: socket._handle,477 enumerable: true,478 writable: true479 });480 }481 this.once("error", (error) => {482 socket.destroy(error);483 });484 this.address = socket.address.bind(socket);485 let writeArgs;486 let headersWritten = false;487 while (writeArgs = this.writeBuffer.shift()) {488 if (writeArgs !== void 0) {489 if (!headersWritten) {490 const [chunk, encoding, callback] = writeArgs;491 const chunkString = chunk.toString();492 const chunkBeforeRequestHeaders = chunkString.slice(493 0,494 chunkString.indexOf("\r\n") + 2495 );496 const chunkAfterRequestHeaders = chunkString.slice(497 chunk.indexOf("\r\n\r\n")498 );499 const rawRequestHeaders = getRawFetchHeaders(this.request.headers);500 const requestHeadersString = rawRequestHeaders.filter(([name]) => {501 return name.toLowerCase() !== _chunkA7U44ARPjs.INTERNAL_REQUEST_ID_HEADER_NAME;502 }).map(([name, value]) => `${name}: ${value}`).join("\r\n");503 const headersChunk = `${chunkBeforeRequestHeaders}${requestHeadersString}${chunkAfterRequestHeaders}`;504 socket.write(headersChunk, encoding, callback);505 headersWritten = true;506 continue;507 }508 socket.write(...writeArgs);509 }510 }511 if (Reflect.get(socket, "encrypted")) {512 const tlsProperties = [513 "encrypted",514 "authorized",515 "getProtocol",516 "getSession",517 "isSessionReused"518 ];519 tlsProperties.forEach((propertyName) => {520 Object.defineProperty(this, propertyName, {521 enumerable: true,522 get: () => {523 const value = Reflect.get(socket, propertyName);524 return typeof value === "function" ? value.bind(socket) : value;525 }526 });527 });528 }529 socket.on("lookup", (...args) => this.emit("lookup", ...args)).on("connect", () => {530 this.connecting = socket.connecting;531 this.emit("connect");532 }).on("secureConnect", () => this.emit("secureConnect")).on("secure", () => this.emit("secure")).on("session", (session) => this.emit("session", session)).on("ready", () => this.emit("ready")).on("drain", () => this.emit("drain")).on("data", (chunk) => {533 this.push(chunk);534 }).on("error", (error) => {535 Reflect.set(this, "_hadError", Reflect.get(socket, "_hadError"));536 this.emit("error", error);537 }).on("resume", () => this.emit("resume")).on("timeout", () => this.emit("timeout")).on("prefinish", () => this.emit("prefinish")).on("finish", () => this.emit("finish")).on("close", (hadError) => this.emit("close", hadError)).on("end", () => this.emit("end"));538 }539 /**540 * Convert the given Fetch API `Response` instance to an541 * HTTP message and push it to the socket.542 */543 async respondWith(response) {544 var _a;545 if (this.destroyed) {546 return;547 }548 if (_chunkC2JSMMHYjs.isPropertyAccessible.call(void 0, response, "type") && response.type === "error") {549 this.errorWith(new TypeError("Network error"));550 return;551 }552 this.mockConnect();553 this.socketState = "mock";554 this.flushWriteBuffer();555 const serverResponse = new (0, _http.ServerResponse)(new (0, _http.IncomingMessage)(this));556 serverResponse.assignSocket(557 new MockSocket({558 write: (chunk, encoding, callback) => {559 this.push(chunk, encoding);560 callback == null ? void 0 : callback();561 },562 read() {563 }564 })565 );566 serverResponse.removeHeader("connection");567 serverResponse.removeHeader("date");568 const rawResponseHeaders = getRawFetchHeaders(response.headers);569 serverResponse.writeHead(570 response.status,571 response.statusText || _http.STATUS_CODES[response.status],572 rawResponseHeaders573 );574 this.once("error", () => {575 serverResponse.destroy();576 });577 if (response.body) {578 try {579 const reader = response.body.getReader();580 while (true) {581 const { done, value } = await reader.read();582 if (done) {583 serverResponse.end();584 break;585 }586 serverResponse.write(value);587 }588 } catch (error) {589 this.respondWith(_chunkC2JSMMHYjs.createServerErrorResponse.call(void 0, error));590 return;591 }592 } else {593 serverResponse.end();594 }595 if (!this.shouldKeepAlive) {596 this.emit("readable");597 (_a = this.responseStream) == null ? void 0 : _a.push(null);598 this.push(null);599 }600 }601 /**602 * Close this socket connection with the given error.603 */604 errorWith(error) {605 this.destroy(error);606 }607 mockConnect() {608 this.connecting = false;609 const isIPv6 = _net2.default.isIPv6(this.connectionOptions.hostname) || this.connectionOptions.family === 6;610 const addressInfo = {611 address: isIPv6 ? "::1" : "127.0.0.1",612 family: isIPv6 ? "IPv6" : "IPv4",613 port: this.connectionOptions.port614 };615 this.address = () => addressInfo;616 this.emit(617 "lookup",618 null,619 addressInfo.address,620 addressInfo.family === "IPv6" ? 6 : 4,621 this.connectionOptions.host622 );623 this.emit("connect");624 this.emit("ready");625 if (this.baseUrl.protocol === "https:") {626 this.emit("secure");627 this.emit("secureConnect");628 this.emit(629 "session",630 this.connectionOptions.session || Buffer.from("mock-session-renegotiate")631 );632 this.emit("session", Buffer.from("mock-session-resume"));633 }634 }635 flushWriteBuffer() {636 for (const writeCall of this.writeBuffer) {637 if (typeof writeCall[2] === "function") {638 writeCall[2]();639 writeCall[2] = void 0;640 }641 }642 }643 onRequestBody(chunk) {644 _outvariant.invariant.call(void 0, 645 this.requestStream,646 "Failed to write to a request stream: stream does not exist"647 );648 this.requestStream.push(chunk);649 }650 onRequestEnd() {651 if (this.requestStream) {652 this.requestStream.push(null);653 }654 }655 onResponseBody(chunk) {656 _outvariant.invariant.call(void 0, 657 this.responseStream,658 "Failed to write to a response stream: stream does not exist"659 );660 this.responseStream.push(chunk);661 }662 onResponseEnd() {663 if (this.responseStream) {664 this.responseStream.push(null);665 }666 }667};668 669// src/interceptors/ClientRequest/agents.ts670 671 672var MockAgent = class extends _http2.default.Agent {673 constructor(options) {674 super();675 this.customAgent = options.customAgent;676 this.onRequest = options.onRequest;677 this.onResponse = options.onResponse;678 }679 createConnection(options, callback) {680 const createConnection = this.customAgent instanceof _http2.default.Agent ? this.customAgent.createConnection : super.createConnection;681 const createConnectionOptions = this.customAgent instanceof _http2.default.Agent ? {682 ...options,683 ...this.customAgent.options684 } : options;685 const socket = new MockHttpSocket({686 connectionOptions: options,687 createConnection: createConnection.bind(688 this.customAgent || this,689 createConnectionOptions,690 callback691 ),692 onRequest: this.onRequest.bind(this),693 onResponse: this.onResponse.bind(this)694 });695 return socket;696 }697};698var MockHttpsAgent = class extends _https2.default.Agent {699 constructor(options) {700 super();701 this.customAgent = options.customAgent;702 this.onRequest = options.onRequest;703 this.onResponse = options.onResponse;704 }705 createConnection(options, callback) {706 const createConnection = this.customAgent instanceof _http2.default.Agent ? this.customAgent.createConnection : super.createConnection;707 const createConnectionOptions = this.customAgent instanceof _http2.default.Agent ? {708 ...options,709 ...this.customAgent.options710 } : options;711 const socket = new MockHttpSocket({712 connectionOptions: options,713 createConnection: createConnection.bind(714 this.customAgent || this,715 createConnectionOptions,716 callback717 ),718 onRequest: this.onRequest.bind(this),719 onResponse: this.onResponse.bind(this)720 });721 return socket;722 }723};724 725// src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts726var _url = require('url');727 728 729 730 731 732 733 734 735 736 737var _logger = require('@open-draft/logger');738 739// src/utils/getUrlByRequestOptions.ts740 741 742var logger = new (0, _logger.Logger)("utils getUrlByRequestOptions");743var DEFAULT_PATH = "/";744var DEFAULT_PROTOCOL = "http:";745var DEFAULT_HOSTNAME = "localhost";746var SSL_PORT = 443;747function getAgent(options) {748 return options.agent instanceof _http.Agent ? options.agent : void 0;749}750function getProtocolByRequestOptions(options) {751 var _a;752 if (options.protocol) {753 return options.protocol;754 }755 const agent = getAgent(options);756 const agentProtocol = agent == null ? void 0 : agent.protocol;757 if (agentProtocol) {758 return agentProtocol;759 }760 const port = getPortByRequestOptions(options);761 const isSecureRequest = options.cert || port === SSL_PORT;762 return isSecureRequest ? "https:" : ((_a = options.uri) == null ? void 0 : _a.protocol) || DEFAULT_PROTOCOL;763}764function getPortByRequestOptions(options) {765 if (options.port) {766 return Number(options.port);767 }768 const agent = getAgent(options);769 if (agent == null ? void 0 : agent.options.port) {770 return Number(agent.options.port);771 }772 if (agent == null ? void 0 : agent.defaultPort) {773 return Number(agent.defaultPort);774 }775 return void 0;776}777function getAuthByRequestOptions(options) {778 if (options.auth) {779 const [username, password] = options.auth.split(":");780 return { username, password };781 }782}783function isRawIPv6Address(host) {784 return host.includes(":") && !host.startsWith("[") && !host.endsWith("]");785}786function getHostname(options) {787 let host = options.hostname || options.host;788 if (host) {789 if (isRawIPv6Address(host)) {790 host = `[${host}]`;791 }792 return new URL(`http://${host}`).hostname;793 }794 return DEFAULT_HOSTNAME;795}796function getUrlByRequestOptions(options) {797 logger.info("request options", options);798 if (options.uri) {799 logger.info(800 'constructing url from explicitly provided "options.uri": %s',801 options.uri802 );803 return new URL(options.uri.href);804 }805 logger.info("figuring out url from request options...");806 const protocol = getProtocolByRequestOptions(options);807 logger.info("protocol", protocol);808 const port = getPortByRequestOptions(options);809 logger.info("port", port);810 const hostname = getHostname(options);811 logger.info("hostname", hostname);812 const path = options.path || DEFAULT_PATH;813 logger.info("path", path);814 const credentials = getAuthByRequestOptions(options);815 logger.info("credentials", credentials);816 const authString = credentials ? `${credentials.username}:${credentials.password}@` : "";817 logger.info("auth string:", authString);818 const portString = typeof port !== "undefined" ? `:${port}` : "";819 const url = new URL(`${protocol}//${hostname}${portString}${path}`);820 url.username = (credentials == null ? void 0 : credentials.username) || "";821 url.password = (credentials == null ? void 0 : credentials.password) || "";822 logger.info("created url:", url);823 return url;824}825 826// src/utils/cloneObject.ts827 828var logger2 = new (0, _logger.Logger)("cloneObject");829function isPlainObject(obj) {830 var _a;831 logger2.info("is plain object?", obj);832 if (obj == null || !((_a = obj.constructor) == null ? void 0 : _a.name)) {833 logger2.info("given object is undefined, not a plain object...");834 return false;835 }836 logger2.info("checking the object constructor:", obj.constructor.name);837 return obj.constructor.name === "Object";838}839function cloneObject(obj) {840 logger2.info("cloning object:", obj);841 const enumerableProperties = Object.entries(obj).reduce(842 (acc, [key, value]) => {843 logger2.info("analyzing key-value pair:", key, value);844 acc[key] = isPlainObject(value) ? cloneObject(value) : value;845 return acc;846 },847 {}848 );849 return isPlainObject(obj) ? enumerableProperties : Object.assign(Object.getPrototypeOf(obj), enumerableProperties);850}851 852// src/interceptors/ClientRequest/utils/normalizeClientRequestArgs.ts853var logger3 = new (0, _logger.Logger)("http normalizeClientRequestArgs");854function resolveRequestOptions(args, url) {855 if (typeof args[1] === "undefined" || typeof args[1] === "function") {856 logger3.info("request options not provided, deriving from the url", url);857 return _url.urlToHttpOptions.call(void 0, url);858 }859 if (args[1]) {860 logger3.info("has custom RequestOptions!", args[1]);861 const requestOptionsFromUrl = _url.urlToHttpOptions.call(void 0, url);862 logger3.info("derived RequestOptions from the URL:", requestOptionsFromUrl);863 logger3.info("cloning RequestOptions...");864 const clonedRequestOptions = cloneObject(args[1]);865 logger3.info("successfully cloned RequestOptions!", clonedRequestOptions);866 return {867 ...requestOptionsFromUrl,868 ...clonedRequestOptions869 };870 }871 logger3.info("using an empty object as request options");872 return {};873}874function overrideUrlByRequestOptions(url, options) {875 url.host = options.host || url.host;876 url.hostname = options.hostname || url.hostname;877 url.port = options.port ? options.port.toString() : url.port;878 if (options.path) {879 const parsedOptionsPath = _url.parse.call(void 0, options.path, false);880 url.pathname = parsedOptionsPath.pathname || "";881 url.search = parsedOptionsPath.search || "";882 }883 return url;884}885function resolveCallback(args) {886 return typeof args[1] === "function" ? args[1] : args[2];887}888function normalizeClientRequestArgs(defaultProtocol, args) {889 let url;890 let options;891 let callback;892 logger3.info("arguments", args);893 logger3.info("using default protocol:", defaultProtocol);894 if (args.length === 0) {895 const url2 = new (0, _url.URL)("http://localhost");896 const options2 = resolveRequestOptions(args, url2);897 return [url2, options2];898 }899 if (typeof args[0] === "string") {900 logger3.info("first argument is a location string:", args[0]);901 url = new (0, _url.URL)(args[0]);902 logger3.info("created a url:", url);903 const requestOptionsFromUrl = _url.urlToHttpOptions.call(void 0, url);904 logger3.info("request options from url:", requestOptionsFromUrl);905 options = resolveRequestOptions(args, url);906 logger3.info("resolved request options:", options);907 callback = resolveCallback(args);908 } else if (args[0] instanceof _url.URL) {909 url = args[0];910 logger3.info("first argument is a URL:", url);911 if (typeof args[1] !== "undefined" && _chunkC2JSMMHYjs.isObject.call(void 0, args[1])) {912 url = overrideUrlByRequestOptions(url, args[1]);913 }914 options = resolveRequestOptions(args, url);915 logger3.info("derived request options:", options);916 callback = resolveCallback(args);917 } else if ("hash" in args[0] && !("method" in args[0])) {918 const [legacyUrl] = args;919 logger3.info("first argument is a legacy URL:", legacyUrl);920 if (legacyUrl.hostname === null) {921 logger3.info("given legacy URL is relative (no hostname)");922 return _chunkC2JSMMHYjs.isObject.call(void 0, args[1]) ? normalizeClientRequestArgs(defaultProtocol, [923 { path: legacyUrl.path, ...args[1] },924 args[2]925 ]) : normalizeClientRequestArgs(defaultProtocol, [926 { path: legacyUrl.path },927 args[1]928 ]);929 }930 logger3.info("given legacy url is absolute");931 const resolvedUrl = new (0, _url.URL)(legacyUrl.href);932 return args[1] === void 0 ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl]) : typeof args[1] === "function" ? normalizeClientRequestArgs(defaultProtocol, [resolvedUrl, args[1]]) : normalizeClientRequestArgs(defaultProtocol, [933 resolvedUrl,934 args[1],935 args[2]936 ]);937 } else if (_chunkC2JSMMHYjs.isObject.call(void 0, args[0])) {938 options = { ...args[0] };939 logger3.info("first argument is RequestOptions:", options);940 options.protocol = options.protocol || defaultProtocol;941 logger3.info("normalized request options:", options);942 url = getUrlByRequestOptions(options);943 logger3.info("created a URL from RequestOptions:", url.href);944 callback = resolveCallback(args);945 } else {946 throw new Error(947 `Failed to construct ClientRequest with these parameters: ${args}`948 );949 }950 options.protocol = options.protocol || url.protocol;951 options.method = options.method || "GET";952 if (!options._defaultAgent) {953 logger3.info(954 'has no default agent, setting the default agent for "%s"',955 options.protocol956 );957 options._defaultAgent = options.protocol === "https:" ? _https.globalAgent : _http.globalAgent;958 }959 logger3.info("successfully resolved url:", url.href);960 logger3.info("successfully resolved options:", options);961 logger3.info("successfully resolved callback:", callback);962 if (!(url instanceof _url.URL)) {963 url = url.toString();964 }965 return [url, options, callback];966}967 968// src/interceptors/ClientRequest/index.ts969var _ClientRequestInterceptor = class extends _chunkA7U44ARPjs.Interceptor {970 constructor() {971 super(_ClientRequestInterceptor.symbol);972 this.onRequest = async ({973 request,974 socket975 }) => {976 const requestId = Reflect.get(request, kRequestId);977 const controller = new (0, _chunkC2JSMMHYjs.RequestController)(request);978 const isRequestHandled = await _chunkC2JSMMHYjs.handleRequest.call(void 0, {979 request,980 requestId,981 controller,982 emitter: this.emitter,983 onResponse: (response) => {984 socket.respondWith(response);985 },986 onRequestError: (response) => {987 socket.respondWith(response);988 },989 onError: (error) => {990 if (error instanceof Error) {991 socket.errorWith(error);992 }993 }994 });995 if (!isRequestHandled) {996 return socket.passthrough();997 }998 };999 this.onResponse = async ({1000 requestId,1001 request,1002 response,1003 isMockedResponse1004 }) => {1005 return _chunkC2JSMMHYjs.emitAsync.call(void 0, this.emitter, "response", {1006 requestId,1007 request,1008 response,1009 isMockedResponse1010 });1011 };1012 }1013 setup() {1014 const {1015 ClientRequest: OriginalClientRequest,1016 get: originalGet,1017 request: originalRequest1018 } = _http2.default;1019 const { get: originalHttpsGet, request: originalHttpsRequest } = _https2.default;1020 const onRequest = this.onRequest.bind(this);1021 const onResponse = this.onResponse.bind(this);1022 _http2.default.ClientRequest = new Proxy(_http2.default.ClientRequest, {1023 construct: (target, args) => {1024 const [url, options, callback] = normalizeClientRequestArgs(1025 "http:",1026 args1027 );1028 const Agent2 = options.protocol === "https:" ? MockHttpsAgent : MockAgent;1029 const mockAgent = new Agent2({1030 customAgent: options.agent,1031 onRequest,1032 onResponse1033 });1034 options.agent = mockAgent;1035 return Reflect.construct(target, [url, options, callback]);1036 }1037 });1038 _http2.default.request = new Proxy(_http2.default.request, {1039 apply: (target, thisArg, args) => {1040 const [url, options, callback] = normalizeClientRequestArgs(1041 "http:",1042 args1043 );1044 const mockAgent = new MockAgent({1045 customAgent: options.agent,1046 onRequest,1047 onResponse1048 });1049 options.agent = mockAgent;1050 return Reflect.apply(target, thisArg, [url, options, callback]);1051 }1052 });1053 _http2.default.get = new Proxy(_http2.default.get, {1054 apply: (target, thisArg, args) => {1055 const [url, options, callback] = normalizeClientRequestArgs(1056 "http:",1057 args1058 );1059 const mockAgent = new MockAgent({1060 customAgent: options.agent,1061 onRequest,1062 onResponse1063 });1064 options.agent = mockAgent;1065 return Reflect.apply(target, thisArg, [url, options, callback]);1066 }1067 });1068 _https2.default.request = new Proxy(_https2.default.request, {1069 apply: (target, thisArg, args) => {1070 const [url, options, callback] = normalizeClientRequestArgs(1071 "https:",1072 args1073 );1074 const mockAgent = new MockHttpsAgent({1075 customAgent: options.agent,1076 onRequest,1077 onResponse1078 });1079 options.agent = mockAgent;1080 return Reflect.apply(target, thisArg, [url, options, callback]);1081 }1082 });1083 _https2.default.get = new Proxy(_https2.default.get, {1084 apply: (target, thisArg, args) => {1085 const [url, options, callback] = normalizeClientRequestArgs(1086 "https:",1087 args1088 );1089 const mockAgent = new MockHttpsAgent({1090 customAgent: options.agent,1091 onRequest,1092 onResponse1093 });1094 options.agent = mockAgent;1095 return Reflect.apply(target, thisArg, [url, options, callback]);1096 }1097 });1098 recordRawFetchHeaders();1099 this.subscriptions.push(() => {1100 _http2.default.ClientRequest = OriginalClientRequest;1101 _http2.default.get = originalGet;1102 _http2.default.request = originalRequest;1103 _https2.default.get = originalHttpsGet;1104 _https2.default.request = originalHttpsRequest;1105 restoreHeadersPrototype();1106 });1107 }1108};1109var ClientRequestInterceptor = _ClientRequestInterceptor;1110ClientRequestInterceptor.symbol = Symbol("client-request-interceptor");1111 1112 1113 1114exports.ClientRequestInterceptor = ClientRequestInterceptor;1115//# sourceMappingURL=chunk-ATZKM2BZ.js.map