{"_id":"light-my-request@6.8.0","bugs":{"url":"https://github.com/fastify/light-my-request/issues"},"dist":{"shasum":"332b19888b40988eca169bb67b465fb2f5418cc3","tarball":"http://registry-npm.ywwl.com/light-my-request/download/light-my-request-6.8.0.tgz","fileCount":27,"integrity":"sha512-5Q8PjoSEdtGIB8fikZsTem5vgRo4F2mR6vUKTDW/H1g6MtAt8e3duQbg/QxL5yzg6BZhor2KOUm3hhWMWLTZwg==","signatures":[{"sig":"MEQCIG1d+ui+z/syOmoi3knq+l463ECVgzUUZ1mRRaPDhi7OAiBhSQlIOOAR9KvdzicNzk5s5yXqK++8eNJNaQiXqO9B/w==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"},{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCID1TqJKrsPLNAze4xAt3TztNge4SO8Vgh8q/IjnVd42aAiEA7AJDA2Jl5SPhKdMWPBVLXNfILTwAl55q5Qr7BJr0BJQ="}],"attestations":{"url":"https://registry.npmjs.org/-/npm/v1/attestations/light-my-request@6.8.0","provenance":{"predicateType":"https://slsa.dev/provenance/v1"}},"unpackedSize":182479,"size":36625,"noattachment":false,"key":"/light-my-request/-/light-my-request-6.8.0.tgz"},"main":"index.js","name":"light-my-request","type":"commonjs","types":"types/index.d.ts","author":{"url":"https://delvedor.dev","name":"Tomas Della Vedova - @delvedor"},"funding":[{"url":"https://github.com/sponsors/fastify","type":"github"},{"url":"https://opencollective.com/fastify","type":"opencollective"}],"gitHead":"6b17587fd5cc0daa6bf7b58daf747c030b0c949f","license":"BSD-3-Clause","scripts":{"lint":"eslint","test":"npm run lint && npm run test:unit && npm run test:typescript","coverage":"npm run unit -- --cov --coverage-report=html","lint:fix":"eslint --fix","benchmark":"node benchmark/benchmark.js","test:unit":"c8 --100 node --test","test:typescript":"tstyche"},"version":"6.8.0","_npmUser":{"name":"GitHub Actions","email":"npm-oidc-no-reply@github.com","trustedPublisher":{"id":"github","oidcConfigId":"3b297e64-a87d-4987-989c-bfbdef3826ce"}},"homepage":"https://github.com/fastify/light-my-request#readme","keywords":["http","inject","fake","request","server"],"repository":{"url":"git+https://github.com/fastify/light-my-request.git","type":"git"},"_npmVersion":"11.19.0","description":"Fake HTTP injection library","directories":{},"maintainers":[{"name":"jsumners","email":"james.sumners@gmail.com"},{"name":"delvedor","email":"tommydelved@gmail.com"},{"name":"matteo.collina","email":"hello@matteocollina.com"},{"name":"eomm","email":"behemoth89@gmail.com"},{"name":"climba03003","email":"kaka@kakawebsitedemo.com"}],"_nodeVersion":"24.21.0","contributors":[{"name":"Matteo Collina","email":"hello@matteocollina.com"},{"name":"Manuel Spigolon","email":"behemoth89@gmail.com"},{"name":"Aras Abbasi","email":"aras.abbasi@gmail.com"},{"url":"https://github.com/fdawgs","name":"Frazer Smith","email":"frazer.dev@icloud.com"}],"dependencies":{"cookie":"^2.0.0","process-warning":"^5.0.0","set-cookie-parser":"^3.0.1","@fastify/deepmerge":"^3.1.0"},"_hasShrinkwrap":false,"devDependencies":{"c8":"^12.0.0","eslint":"^9.39.2","multer":"^2.0.2","undici":"^7.18.2","express":"^5.2.1","tstyche":"^7.0.0","form-data":"^4.0.5","@types/node":"^26.0.0","neostandard":"^0.13.0","end-of-stream":"^1.4.5","formdata-node":"^6.0.3","form-auto-content":"^3.2.1","@fastify/ajv-compiler":"^4.0.5"},"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/light-my-request_6.8.0_1791624221657_0.9099283178944042"},"readme":"# Light my Request\n\n[![CI](https://github.com/fastify/light-my-request/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/light-my-request/actions/workflows/ci.yml)\n[![NPM version](https://img.shields.io/npm/v/light-my-request.svg?style=flat)](https://www.npmjs.com/package/light-my-request)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nInjects a fake HTTP request/response into a node HTTP server for simulating server logic, writing tests, or debugging.\nDoes not use a socket connection so can be run against an inactive server (server not in listen mode).\n\n## Example\n\n```javascript\nconst http = require('node:http')\nconst inject = require('light-my-request')\n\nconst dispatch = function (req, res) {\n  const reply = 'Hello World'\n  res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })\n  res.end(reply)\n}\n\nconst server = http.createServer(dispatch)\n\ninject(dispatch, { method: 'get', url: '/' }, (err, res) => {\n  console.log(res.payload)\n})\n```\nNote how `server.listen` is never called.\n\nAsync await and promises are supported as well!\n```javascript\n// promises\ninject(dispatch, { method: 'get', url: '/' })\n  .then(res => console.log(res.payload))\n  .catch(console.log)\n\n// async-await\ntry {\n  const res = await inject(dispatch, { method: 'get', url: '/' })\n  console.log(res.payload)\n} catch (err) {\n  console.log(err)\n}\n```\n\nYou can also use chaining methods if you do not pass the callback function. Check [here](#method-chaining) for details.\n\n```js\n// chaining methods\ninject(dispatch)\n  .get('/')                   // set the request method to GET, and request URL to '/'\n  .headers({ foo: 'bar' })    // set the request headers\n  .query({ foo: 'bar' })      // set the query parameters\n  .end((err, res) => {\n    console.log(res.payload)\n  })\n\ninject(dispatch)\n  .post('/')                  // set the request method to POST, and request URL to '/'\n  .payload('request payload') // set the request payload\n  .body('request body')       // alias for payload\n  .end((err, res) => {\n    console.log(res.payload)\n  })\n\n// async-await is also supported\ntry {\n  const chain = inject(dispatch).get('/')\n  const res = await chain.end()\n  console.log(res.payload)\n} catch (err) {\n  console.log(err)\n}\n```\n\nFile uploads (`multipart/form-data`) or form submit (`x-www-form-urlencoded`) can be achieved by using [form-auto-content](https://github.com/Eomm/form-auto-content) package as shown below:\n\n```js\nconst formAutoContent = require('form-auto-content')\nconst fs = require('node:fs')\n\ntry {\n  const form = formAutoContent({\n    myField: 'hello',\n    myFile: fs.createReadStream(`./path/to/file`)\n  })\n\n  const res = await inject(dispatch, {\n    method: 'post',\n    url: '/upload',\n    ...form\n  })\n  console.log(res.payload)\n} catch (err) {\n  console.log(err)\n}\n```\n\nThis module ships with a handwritten TypeScript declaration file for TS support. The declaration exports a single namespace `LightMyRequest`. You can import it one of two ways:\n```typescript\nimport * as LightMyRequest from 'light-my-request'\n\nconst dispatch: LightMyRequest.DispatchFunc = function (req, res) {\n  const reply = 'Hello World'\n  res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })\n  res.end(reply)\n}\n\nLightMyRequest.inject(dispatch, { method: 'get', url: '/' }, (err, res) => {\n  console.log(res.payload)\n})\n\n// or\nimport { inject, DispatchFunc } from 'light-my-request'\n\nconst dispatch: DispatchFunc = function (req, res) {\n  const reply = 'Hello World'\n  res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })\n  res.end(reply)\n}\n\ninject(dispatch, { method: 'get', url: '/' }, (err, res) => {\n  console.log(res.payload)\n})\n```\nThe declaration file exports types for the following parts of the API:\n- `inject` - standard light-my-request `inject` method\n- `bindInject` - creates a new inject function with pre-configured default options\n- `BoundInjectFunction` - the return type of `bindInject`\n- `DispatchFunc` - the fake HTTP dispatch function\n- `InjectPayload` - a union type for valid payload types\n- `isInjection` - standard light-my-request `isInjection` method\n- `InjectOptions` - options object for `inject` method\n- `Request` - custom light-my-request `request` object interface. Extends\n  Node.js `stream.Readable` type by default. This behavior can be changed by\n  setting the `Request` option in the `inject` method's options\n- `Response` - custom light-my-request `response` object interface. Extends Node.js `http.ServerResponse` type\n\n## API\n\n#### `inject(dispatchFunc[, options, callback])`\n\nInjects a fake request into an HTTP server.\n\n- `dispatchFunc` - listener function. The same as you would pass to `Http.createServer` when making a node HTTP server. Has the signature `function (req, res)` where:\n    - `req` - a simulated request object. Inherits from `Stream.Readable` by\n      default. Optionally inherits from another class, set in\n      `options.Request`\n    - `res` - a simulated response object. Inherits from node's `Http.ServerResponse`.\n- `options` - request options object where:\n  - `url` | `path` - a string specifying the request URL.\n  - `method` - a string specifying the HTTP request method, defaulting to `'GET'`.\n  - `authority` - a string specifying the HTTP HOST header value to be used if no header is provided, and the `url`\n    does not include an authority component. Defaults to `'localhost'`.\n  - `headers` - an optional object containing request headers. A header value may be an array of strings to simulate the same header being sent multiple times; the values are aggregated exactly as a Node.js HTTP server would expose them on `request.headers` (`set-cookie` is kept as an array, `cookie` values are joined with `'; '`, other values with `', '`), while every individual value is preserved in `request.rawHeaders`.\n  - `cookies` - cookies to encode onto the `Cookie` request header. See [Cookies](docs/cookies.md).\n  - `remoteAddress` - an optional string specifying the client remote address. Defaults to `'127.0.0.1'`.\n  - `payload` - an optional request payload. Can be a string, Buffer, Stream, or object. If the payload is string, Buffer or Stream is used as is as the request payload. Otherwise, it is serialized with `JSON.stringify` forcing the request to have the `Content-type` equal to `application/json`\n  - `query` - an optional object or string containing query parameters.\n  - `body` - alias for payload.\n  - `simulate` - an object containing flags to simulate various conditions:\n    - `end` - indicates whether the request will fire an `end` event. Defaults to `undefined`, meaning an `end` event will fire.\n    - `split` - indicates whether the request payload will be split into chunks. Defaults to `undefined`, meaning payload will not be chunked.\n    - `error` - whether the request will emit an `error` event. Defaults to `undefined`, meaning no `error` event will be emitted. If set to `true`, the emitted error will have a message of `'Simulated'`.\n    - `close` - whether the request will emit a `close` event. Defaults to `undefined`, meaning no `close` event will be emitted.\n  - `validate` - Optional flag to validate this options object. Defaults to `true`.\n  - `server` - Optional http server. It is used for binding the `dispatchFunc`.\n  - `autoStart` - Automatically start the request as soon as the method\n    is called. It is only valid when not passing a callback. Defaults to `true`.\n  - `signal` - An `AbortSignal` that may be used to abort an ongoing request. Requires Node v16+.\n  - `Request` - Optional type from which the `request` object should inherit\n    instead of `stream.Readable`\n  - `payloadAsStream` - if set to `true`, the response will be streamed and not accumulated; in this case `res.payload`, `res.rawPayload` will be undefined.\n- `callback` - the callback function using the signature `function (err, res)` where:\n  - `err` - error object\n  - `res` - a response object where:\n    - `raw` - an object containing the raw request and response objects where:\n      - `req` - the simulated request object.\n      - `res` - the simulated response object.\n    - `headers` - an object containing the response headers.\n    - `statusCode` - the HTTP status code.\n    - `statusMessage` - the HTTP status message.\n    - `payload` - the payload as a UTF-8 encoded string.\n    - `body` - alias for payload.\n    - `rawPayload` - the raw payload as a Buffer.\n    - `trailers` - an object containing the response trailers.\n    - `json` - a function that parses a json response payload and returns an object.\n    - `stream` - a function that provides a `Readable` stream of the response payload.\n    - `cookies` - a getter that parses the `set-cookie` response header and returns an array with all the cookies and their metadata.\n\nNotes:\n\n- You can also pass a string in place of the `options` object as a shorthand\n  for `{url: string, method: 'GET'}`.\n- Beware when using the `Request` option. That might make _light-my-request_\n  slower. Sample benchmark result run on an i5-8600K CPU with `Request` set to\n  `http.IncomingMessage`:\n\n```\nRequest x 155,018 ops/sec ±0.47% (94 runs sampled)\nCustom Request x 30,373 ops/sec ±0.64% (90 runs sampled)\nRequest With Cookies x 125,696 ops/sec ±0.29% (96 runs sampled)\nRequest With Cookies n payload x 114,391 ops/sec ±0.33% (97 runs sampled)\nParseUrl x 255,790 ops/sec ±0.23% (99 runs sampled)\nParseUrl and query x 194,479 ops/sec ±0.16% (99 runs sampled)\n```\n\n#### `inject.isInjection(obj)`\n\nChecks if given object `obj` is a *light-my-request* `Request` object.\n\n#### `bindInject(dispatchFunc, defaults)`\n\nCreates a new inject function with pre-configured default options. This is useful when you want to reuse common options like authentication headers across multiple requests.\n\n- `dispatchFunc` - listener function. Same as `inject`.\n- `defaults` - default options object that will be merged with each request. Supports all options from `inject`. They are deeply merged with request's options, which take precedence.\n\nReturns a function with the same signature as `inject(options[, callback])`.\n\n```js\nconst { bindInject } = require('light-my-request')\n\n// Create a bound inject function with default authorization header\nconst boundInject = bindInject(dispatch, {\n  headers: { authorization: 'Bearer my-token' }\n})\n\n// All requests will include the authorization header\nconst res1 = await boundInject({ method: 'get', url: '/protected' })\nconst res2 = await boundInject({ method: 'post', url: '/api/data', payload: { foo: 'bar' } })\n\n// You can still add additional headers per request\nconst res3 = await boundInject({\n  method: 'get',\n  url: '/admin',\n  headers: { 'x-custom': 'value' } // authorization header is also included\n})\n\n// Method chaining also works, but it overwrites the default options\nconst res4 = await boundInject()\n  .get('/users')\n  .headers({ 'x-request-id': '123' })\n```\n\nExample with authentication flow:\n```js\nconst { inject, bindInject } = require('light-my-request')\n\n// Login request\nconst loginResponse = await inject(dispatch, {\n  method: 'post',\n  url: '/auth/login',\n  payload: { username: 'user', password: 'pass' }\n})\n\nconst { accessToken } = loginResponse.json()\n\n// Create bound inject with the access token\nconst authenticatedInject = bindInject(dispatch, {\n  headers: { authorization: `Bearer ${accessToken}` }\n})\n\n// All subsequent requests are authenticated\nconst userResponse = await authenticatedInject({ method: 'get', url: '/api/user' })\nconst dataResponse = await authenticatedInject({ method: 'get', url: '/api/data' })\n```\n\n#### Method chaining\n\nThe following methods can be used in chaining:\n- `delete`, `get`, `head`, `options`, `patch`, `post`, `put`, `trace`. They will set the HTTP request method and the request URL.\n- `body`, `headers`, `payload`, `query`, `cookies`. They can be used to set the request options object.\n\nAnd finally, you need to call `end`. It has the signature `function (callback)`.\nIf you invoke `end` without a callback function, the method will return a promise, thus you can:\n\n```js\nconst chain = inject(dispatch).get('/')\n\ntry {\n  const res = await chain.end()\n  console.log(res.payload)\n} catch (err) {\n  // handle error\n}\n\n// or\nchain.end()\n  .then(res => {\n    console.log(res.payload)\n  })\n  .catch(err => {\n    // handle error\n  })\n```\n\nBy the way, you can also use promises without calling `end`!\n\n```js\ninject(dispatch)\n  .get('/')\n  .then(res => {\n    console.log(res.payload)\n  })\n  .catch(err => {\n    // handle error\n  })\n```\n\nNote: The application would not respond multiple times. If you try to invoke any method after the application has responded, the application would throw an error.\n\n#### Inspect if Request or Response orignated from `light-my-request`\n\nBoth `request` and `response` added `isLightMyRequest` property to inspect if it is originated by\n`light-my-request`.\n\n```js\nimport { inject, DispatchFunc } from 'light-my-request'\n\nconst dispatch: DispatchFunc = function (req, res) {\n  req.isLightMyRequest // true\n  res.isLightMyRequest // true\n  const reply = 'Hello World'\n  res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })\n  res.end(reply)\n}\n\ninject(dispatch, { method: 'get', url: '/' }, (err, res) => {\n  console.log(res.payload)\n})\n```\n\n\n## Acknowledgments\nThis project has been forked from [`hapi/shot`](https://github.com/hapijs/shot) because we wanted to support *Node ≥ v4* and not only *Node ≥ v8*.\nAll credits prior to commit [00a2a82](https://github.com/fastify/light-my-request/commit/00a2a82eb773b765003b6085788cc3564cd08326) go to the `hapi/shot` project [contributors](https://github.com/hapijs/shot/graphs/contributors).\nSince commit [db8bced](https://github.com/fastify/light-my-request/commit/db8bced10b4367731688c8738621d42f39680efc) the project will be maintained by the Fastify team.\n\n## License\n\nLicensed under [BSD-3-Clause](./LICENSE).\n","publish_time":1791624221747,"_cnpm_publish_time":1791624221747,"dist-tags":{"five":"5.14.0","latest":"6.8.0","next":"6.0.0-pre.fv5.1"}}