{"name":"node-request-interceptor","description":"Low-level HTTP/HTTPS/XHR request interception library for NodeJS","version":"0.4.0","main":"lib/index.js","typings":"lib/index.d.ts","author":{"name":"Artem Zakharchenko"},"license":"MIT","scripts":{"start":"tsc --build -w","test":"jest --no-cache --runInBand","clean":"rimraf lib","build":"yarn clean && tsc --build","prepublishOnly":"yarn test && yarn build"},"repository":{"type":"git","url":"https://github.com/mswjs/node-request-interceptor"},"devDependencies":{"@types/express":"^4.17.7","@types/jest":"^25.2.1","@types/node":"^13.13.2","@types/node-fetch":"^2.5.7","@types/supertest":"^2.0.10","axios":"^0.19.2","body-parser":"^1.19.0","express":"^4.17.1","jest":"^25.4.0","node-fetch":"^2.6.0","rimraf":"^3.0.2","supertest":"^4.0.2","ts-jest":"^25.4.0","typescript":"^3.8.3"},"dependencies":{"@open-draft/until":"^1.0.3","debug":"^4.1.1","headers-utils":"^1.2.0"},"keywords":["request","intercept","http","https","xmlhttprequest","xhr","fetch","low-level","mock"],"_id":"node-request-interceptor@0.4.0","dist":{"shasum":"d881db1e4ed4ba5ba85a87b359a3824e8016429a","integrity":"sha512-FA52GRuLaZjeZjKxK7yAddeKpG6T0M01cDdJITGPSp+dIrn9uumaecjzBTZ4IkCtDacVmYGjMl/m1rvYNiYfBw==","tarball":"http://registry-npm.ywwl.com/node-request-interceptor/download/node-request-interceptor-0.4.0.tgz","fileCount":53,"unpackedSize":80599,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfPjfVCRA9TVsSAnZWagAAHSoP/15ZyeXKwBvCWsLFTOqo\nD2T4IpSrOT+tU0RpKtzmJK6DcJodx3w91UhHBFN9Apl+/x+HMiNAaOQxtd0/\nPbwCp8qidAOSVyo7bQAktIWHh3NTTkTGuaTEDvX4uSGb/1CahGJIYRpdAEqc\nUcPnbUtdxyEWNxRuMoFjizY7f3cljFFLBIKihPGEW8XBl8NaKYo7CM3Eri43\napb4ShpE/EP0h80wh+gBCeYgkyukWhvpaG/y49MdkPi1VabJa9DZPizxrJ0D\n67pPG2+S9cJscMJmD5N6ArwtO5u2cmAwN4zB8OUIaNVvzY6o/Efhcx/REb7O\ncpAHR/nh6NWuLGNkaTs+t2eFa/yDsZ/9GeBuyHpHG9ls++/KjtP861m7xu2m\nhwSldcBBEBZp1/Rn1DxYksQz/eGXAARYqld/Ag3YMxCd6Bx8pBw8vPR2P7IL\n56JM+qn+Luvuwhjne/UwzPV6ON3zAgixtz62oklhPc4t11+vJR31Nf4CB94N\nVFrEBTk/Cj7eSGyurRG5wpvoZn3xkvQ8n2IBEjQlmgSvkTfoHnfQWYXmgp5N\nUq2ekgY3qFTx2OYwQEoLIVHawdp3o6+lwRgHP0i1OpW349G4ul9gOtGRsVUe\nGfNIuRjcJUiTSkK4r1d55/0Wqe08DGNKjawZzqmwJFMi53avu1pL7cEwu8vW\nLfxv\r\n=z1pq\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIFiYylGgtO4feT/E8J/NQq9BKUiMlzOXHIMOdvf6kbqPAiBBIklek0h+3hv+l8qD2WodwvMC8nppACbSAkPYrS3toQ=="}],"size":18683,"noattachment":false,"key":"/node-request-interceptor/-/node-request-interceptor-0.4.0.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.4.0_1597913044598_0.2776299840188734"},"_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":1597913044697,"_cnpm_publish_time":1597913044697,"dist-tags":{"latest":"0.6.3"}}