{"name":"node-request-interceptor","description":"Low-level HTTP/HTTPS/XHR request interception library for NodeJS","version":"0.2.3","main":"lib/index.js","typings":"lib/index.d.ts","author":{"name":"Artem Zakharchenko"},"license":"MIT","scripts":{"test":"jest","clean":"rimraf lib","build":"yarn clean && tsc --build","prepublishOnly":"yarn test && yarn build"},"devDependencies":{"@types/jest":"^25.2.1","@types/node":"^13.13.2","@types/node-fetch":"^2.5.7","jest":"^25.4.0","node-fetch":"^2.6.0","rimraf":"^3.0.2","ts-jest":"^25.4.0","typescript":"^3.8.3"},"dependencies":{"debug":"^4.1.1","headers-utils":"^1.1.3"},"_id":"node-request-interceptor@0.2.3","dist":{"shasum":"f75b93e68a8813caad0e1b1725d46904ba38fec2","integrity":"sha512-ckz31iMCw0S9vFk3IJvO/jXc0plMHvfcvmbobuJzNN931qy3PH8P0t9wPaB1ny13dCXUZJoRVBFoxl3/wb1+hw==","tarball":"http://registry-npm.ywwl.com/node-request-interceptor/download/node-request-interceptor-0.2.3.tgz","fileCount":35,"unpackedSize":57278,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJev8yqCRA9TVsSAnZWagAAgGoP+wdKlWZirHh/BC4R8U2n\nnsw7BZxzBBxF0KPDrEQezw4bHrRw7gAWLbjiVS0iv6tmZjdwLbC9ygWmi0P2\n5ZTRRb4twkyJf/dlgsPHI6KPrB2b/fB6XrIYddrkQEzPTg0Q1fHAQmiFNBrz\nbA6UlT993VIdg9GfrRL7Mdg5jM9cYWek0RhU1smToviaoMmdlqturc7WZm2Q\nESilHZYKm3s1l1SsquuTH+uDM/l3XlCRFFZ3og2mh4DgVun1voTpmjcAMl+e\nFlP4gXiD3K+EvnuncuX4DigqdgB1h4TG61k/tbuq32an75brdlJhVz7lVsWs\nf0hz5Hi9PxH/dRWoPFyaCNSIWbzFdlLKaNK6JW2qJlWKStM8c4e9i2jfQAKM\nJ/b0QhaUXyEmDeyMInrrYbQQSzZ8vbUAKsnxloGwin3IKd5Ihs3Ac9ZqJkns\nV1yzfTEXAPBsx/5trzPc12al3/Aq2DBP+cWCkSrEqAknXxaamG/GOpRGfPrF\nsK9C9PUTEKJHdqs31m3D+D17GSZRp9dxaXSLIcPjbluLpFS4tCLU27CzlB8Q\naTmXRF4XKUt3uioVs/wjBiHje8cVhqNyGuOULNEfgpVWsdQaIYg0/8RnWHKm\nsgKRWfUfoZg+AsxaT+yYitJ4ni2B8LN2QvfZXRQ36O0vrHjCAhLihlE+Upzw\nTcj9\r\n=lfvu\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIQDGGd6WoW/fAwTeEZoEKSWkq8Krcyl7Wh0sDYZFW/k34wIgFTMoTmpw/0Qh4DOduclmAKA0lYFsGiDfQ68xqlEP9RU="}],"size":14491,"noattachment":false,"key":"/node-request-interceptor/-/node-request-interceptor-0.2.3.tgz"},"maintainers":[{"name":"kettanaito","email":"kettanaito@gmail.com"}],"_npmUser":{"name":"kettanaito","email":"kettanaito@gmail.com"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/node-request-interceptor_0.2.3_1589628074302_0.9175387346414059"},"_hasShrinkwrap":false,"readme":"[![Latest version](https://img.shields.io/npm/v/node-request-interceptor.svg)](https://www.npmjs.com/package/node-request-interceptor)\n[![Build status](https://img.shields.io/circleci/project/github/mswjs/node-request-interceptor/master.svg)](https://app.circleci.com/pipelines/github/mswjs/node-request-interceptor)\n\n# `node-request-interceptor`\n\nLow-level HTTP/HTTPS/XHR request interception library for NodeJS.\n\n**Intercepts any requests issued by:**\n\n- `http.get`/`http.request`\n- `https.get`/`https.request`\n- `fetch`\n- `XMLHttpRequest`\n- Any third-party libraries that utilize the modules above (i.e. `request`, `node-fetch`, etc.)\n\n## Motivation\n\nWhile there are a lot of network communication mocking libraries, they tend to use request interception as an implementation detail, exposing you a high-level API that includes request matching, timeouts, retries, and so forth.\n\nThis library is a strip-to-bone implementation that provides as little abstraction as possible to execute arbitrary logic upon any request in NodeJS. It's primarily designed as an underlying component for a high-level API mocking solutions.\n\n### How is this library different?\n\nAs interception is often combined with request route matching, some libraries can determine whether a request should be mocked _before_ it actually happens. This approach is not suitable for this library, as it rather _intercepts all requests_ and then let's you decide which ones should be mocked. This affects the level at which interception happens, and also the way mocked/original response is constructed, in comparison to other solutions.\n\n### Why XMLHttpRequest?\n\nAlthough NodeJS has no `XMLHttpRequest` implementation, this library covers it for the sake of processes that still run in NodeJS, but emulate a browser-like environment (i.e. `jsdom` when running tests in Jest).\n\n## What this library does\n\nThis library monkey-patches the following native modules:\n\n- `http.get`/`http.request`\n- `https.get`/`https.request`\n- `XMLHttpRequest`\n\nOnce patched, it provides an interface to execute an arbitrary logic upon any outgoing request using a request middleware function.\n\n- Bypasses all requests by default, so your network channel is not affected.\n- Handles an abstract response object returned from the request middleware as an actual response for the occurred request (taking into account the difference in constructing a response for different clients).\n\n## What this library doesn't do\n\n- Does **not** provide any request matching logic.\n- Does **not** decide how to handle requests.\n- Does **not** run in a browser (although supports `jsdom`).\n\n## Getting started\n\n```bash\nnpm install node-request-interceptor\n```\n\n## API\n\n### `RequestInterceptor(interceptors: Interceptor[])`\n\n```js\nimport { RequestInterceptor } from 'node-request-interceptor'\nimport withDefaultInterceptors from 'node-request-interceptor/presets/default'\n\nconst interceptor = new RequestInterceptor(withDefaultInterceptors)\n```\n\n> Using the `/presets/default` interceptors preset is the recommended way to ensure all requests get intercepted, regardless of their origin.\n\n### Interceptors\n\nThis library utilizes a concept of an _interceptor_–a module that performs necessary patching, handles a mocked response, and restores patched instances.\n\n**The list of interceptors:**\n\n- `/interceptors/ClientRequest`\n- `/interceptors/XMLHttpRequest`\n\nTo use one, or multiple interceptors, import and provide them to the `RequestInterceptor` constructor.\n\n```js\nimport { RequestInterceptors } from 'node-request-interceptor'\nimport { interceptXMLHttpRequest } from 'node-request-interceptor/interceptors/XMLHttpRequest'\n\n// This `interceptor` instance would handle only XMLHttpRequest,\n// ignoring requests issued via `http`/`https` modules.\nconst interceptor = new RequestInterceptors([interceptXMLHttpRequest])\n```\n\n> Interceptors are crucial in leveraging environment-specific module overrides. Certain environments (i.e. React Native) do not have access to native NodeJS modules (like `http`). Importing such modules raises an exception, and must be avoided.\n\n### Methods\n\n#### `.use(middleware: (req: InterceptedRequest, ref: IncomingMessage | XMLHttpRequest) => MockedResponse): void`\n\nApplies a given middleware function to an intercepted request. May return a [`MockedResponse`](#MockedResponse) object that is going to be used to respond to an intercepted request.\n\n##### Requests monitoring\n\n```js\ninterceptor.use((req) => {\n  // Will print to stdout any outgoing requests\n  // without affecting their responses\n  console.log('%s %s', req.method, req.url.href)\n})\n```\n\n##### Response mocking\n\nWhen a request middleware returns a [`MockedResponse`](#MockedResponse) object, it will be returned as the response to the intercepted request. This library automatically creates a proper response instance according to the request issuing module (`http`/`XMLHttpRequest`).\n\n```js\ninterceptor.use((req) => {\n  if (['https://google.com'].includes(req.url.origin)) {\n    // Will return a mocked response for any request\n    // that is issued from the \"https://google.com\" origin.\n    return {\n      status: 301,\n      headers: {\n        'x-powered-by': 'node-request-interceptor',\n      },\n      body: JSON.stringify({\n        message: 'Hey, I am a mocked response',\n      }),\n    }\n  }\n})\n```\n\n#### `.restore(): void`\n\nRestores all patched modules and stops the interception of any future requests.\n\n```js\ninterceptor.restore()\n```\n\n---\n\n### `InterceptedRequest`\n\n```ts\ninterface InterceptedRequest {\n  url: URL\n  method: string\n  headers?: http.OutgoingHttpHeaders\n  body?: string\n}\n```\n\n---\n\n### `MockedResponse`\n\nWhenever a `MockedResponse` object is returned from the request middleware function, it's being used to constructs a relevant response for the intercepted request.\n\n```ts\ninterface MockedResponse {\n  status?: number\n  statusText?: string\n  headers?: Record<string, string | string[]>\n  body?: string\n}\n```\n\n## Special mention\n\nThe following libraries were used as an inspiration to write this low-level API:\n\n- [`node`](https://github.com/nodejs/node)\n- [`nock`](https://github.com/nock/nock)\n- [`mock-xmlhttprequest`](https://github.com/berniegp/mock-xmlhttprequest)\n","publish_time":1589628074405,"_cnpm_publish_time":1589628074405,"dist-tags":{"latest":"0.6.3"}}