CoolFace
Datasetpublic

basant307/AI_Governance_Project

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
0likes48downloads
RemoteHttpInterceptor.mjs193 linesDownload Raw Back to node
1import {2  BatchInterceptor3} from "./chunk-RC2XPCC4.mjs";4import {5  ClientRequestInterceptor6} from "./chunk-WA2XMLKW.mjs";7import "./chunk-TJDMZZXE.mjs";8import {9  XMLHttpRequestInterceptor10} from "./chunk-EADPZWWI.mjs";11import "./chunk-6HYIRFX2.mjs";12import {13  FetchInterceptor14} from "./chunk-GL6JCI7E.mjs";15import "./chunk-TX5GBTFY.mjs";16import "./chunk-6YM4PLBI.mjs";17import {18  RequestController,19  handleRequest20} from "./chunk-LGXJ3UUF.mjs";21import {22  FetchResponse,23  Interceptor24} from "./chunk-IHJSPMYM.mjs";25import "./chunk-3GJB4JDF.mjs";26 27// src/RemoteHttpInterceptor.ts28var RemoteHttpInterceptor = class extends BatchInterceptor {29  constructor() {30    super({31      name: "remote-interceptor",32      interceptors: [33        new ClientRequestInterceptor(),34        new XMLHttpRequestInterceptor(),35        new FetchInterceptor()36      ]37    });38  }39  setup() {40    super.setup();41    let handleParentMessage;42    this.on("request", async ({ request, requestId, controller }) => {43      var _a;44      const serializedRequest = JSON.stringify({45        id: requestId,46        method: request.method,47        url: request.url,48        headers: Array.from(request.headers.entries()),49        credentials: request.credentials,50        body: ["GET", "HEAD"].includes(request.method) ? null : await request.text()51      });52      this.logger.info(53        "sent serialized request to the child:",54        serializedRequest55      );56      (_a = process.send) == null ? void 0 : _a.call(process, `request:${serializedRequest}`);57      const responsePromise = new Promise((resolve) => {58        handleParentMessage = (message) => {59          if (typeof message !== "string") {60            return resolve();61          }62          if (message.startsWith(`response:${requestId}`)) {63            const [, serializedResponse] = message.match(/^response:.+?:(.+)$/) || [];64            if (!serializedResponse) {65              return resolve();66            }67            const responseInit = JSON.parse(68              serializedResponse69            );70            const mockedResponse = new FetchResponse(responseInit.body, {71              url: request.url,72              status: responseInit.status,73              statusText: responseInit.statusText,74              headers: responseInit.headers75            });76            controller.respondWith(mockedResponse);77            return resolve();78          }79        };80      });81      this.logger.info(82        'add "message" listener to the parent process',83        handleParentMessage84      );85      process.addListener("message", handleParentMessage);86      return responsePromise;87    });88    this.subscriptions.push(() => {89      process.removeListener("message", handleParentMessage);90    });91  }92};93function requestReviver(key, value) {94  switch (key) {95    case "url":96      return new URL(value);97    case "headers":98      return new Headers(value);99    default:100      return value;101  }102}103var _RemoteHttpResolver = class extends Interceptor {104  constructor(options) {105    super(_RemoteHttpResolver.symbol);106    this.process = options.process;107  }108  setup() {109    const logger = this.logger.extend("setup");110    const handleChildMessage = async (message) => {111      logger.info("received message from child!", message);112      if (typeof message !== "string" || !message.startsWith("request:")) {113        logger.info("unknown message, ignoring...");114        return;115      }116      const [, serializedRequest] = message.match(/^request:(.+)$/) || [];117      if (!serializedRequest) {118        return;119      }120      const requestJson = JSON.parse(121        serializedRequest,122        requestReviver123      );124      logger.info("parsed intercepted request", requestJson);125      const request = new Request(requestJson.url, {126        method: requestJson.method,127        headers: new Headers(requestJson.headers),128        credentials: requestJson.credentials,129        body: requestJson.body130      });131      const controller = new RequestController(request);132      await handleRequest({133        request,134        requestId: requestJson.id,135        controller,136        emitter: this.emitter,137        onResponse: async (response) => {138          this.logger.info("received mocked response!", { response });139          const responseClone = response.clone();140          const responseText = await responseClone.text();141          const serializedResponse = JSON.stringify({142            status: response.status,143            statusText: response.statusText,144            headers: Array.from(response.headers.entries()),145            body: responseText146          });147          this.process.send(148            `response:${requestJson.id}:${serializedResponse}`,149            (error) => {150              if (error) {151                return;152              }153              this.emitter.emit("response", {154                request,155                requestId: requestJson.id,156                response: responseClone,157                isMockedResponse: true158              });159            }160          );161          logger.info(162            "sent serialized mocked response to the parent:",163            serializedResponse164          );165        },166        onRequestError: (response) => {167          this.logger.info("received a network error!", { response });168          throw new Error("Not implemented");169        },170        onError: (error) => {171          this.logger.info("request has errored!", { error });172          throw new Error("Not implemented");173        }174      });175    };176    this.subscriptions.push(() => {177      this.process.removeListener("message", handleChildMessage);178      logger.info('removed the "message" listener from the child process!');179    });180    logger.info('adding a "message" listener to the child process');181    this.process.addListener("message", handleChildMessage);182    this.process.once("error", () => this.dispose());183    this.process.once("exit", () => this.dispose());184  }185};186var RemoteHttpResolver = _RemoteHttpResolver;187RemoteHttpResolver.symbol = Symbol("remote-resolver");188export {189  RemoteHttpInterceptor,190  RemoteHttpResolver,191  requestReviver192};193//# sourceMappingURL=RemoteHttpInterceptor.mjs.map
basant307/AI_Governance_Project · CoolFace