First commit

This commit is contained in:
2026-01-12 13:12:46 +01:00
parent b2d9501f6d
commit a1fbd8acf5
4413 changed files with 1245183 additions and 0 deletions

2
node_modules/light-my-request/.gitattributes generated vendored Normal file
View File

@@ -0,0 +1,2 @@
# Set default behavior to automatically convert line endings
* text=auto eol=lf

13
node_modules/light-my-request/.github/dependabot.yml generated vendored Normal file
View File

@@ -0,0 +1,13 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
open-pull-requests-limit: 10
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 10

21
node_modules/light-my-request/.github/stale.yml generated vendored Normal file
View File

@@ -0,0 +1,21 @@
# Number of days of inactivity before an issue becomes stale
daysUntilStale: 15
# Number of days of inactivity before a stale issue is closed
daysUntilClose: 7
# Issues with these labels will never be considered stale
exemptLabels:
- "discussion"
- "feature request"
- "bug"
- "help wanted"
- "plugin suggestion"
- "good first issue"
# Label to use when marking an issue as stale
staleLabel: stale
# Comment to post when marking an issue as stale. Set to `false` to disable
markComment: >
This issue has been automatically marked as stale because it has not had
recent activity. It will be closed if no further activity occurs. Thank you
for your contributions.
# Comment to post when closing a stale issue. Set to `false` to disable
closeComment: false

View File

@@ -0,0 +1,30 @@
name: Benchmark PR
on:
pull_request_target:
types:
- labeled
jobs:
benchmark:
if: ${{ github.event.label.name == 'benchmark' }}
uses: fastify/workflows/.github/workflows/plugins-benchmark-pr.yml@main
with:
npm-script: benchmark
remove-label:
if: "always()"
needs:
- benchmark
runs-on: ubuntu-latest
steps:
- name: Remove benchmark label
uses: octokit/request-action@v2.x
id: remove-label
with:
route: DELETE /repos/{repo}/issues/{issue_number}/labels/{name}
repo: ${{ github.event.pull_request.head.repo.full_name }}
issue_number: ${{ github.event.pull_request.number }}
name: benchmark
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

24
node_modules/light-my-request/.github/workflows/ci.yml generated vendored Normal file
View File

@@ -0,0 +1,24 @@
name: CI
on:
push:
branches:
- main
- master
- next
- 'v*'
paths-ignore:
- 'docs/**'
- '*.md'
pull_request:
paths-ignore:
- 'docs/**'
- '*.md'
jobs:
test:
uses: fastify/workflows/.github/workflows/plugins-ci.yml@v3
with:
fastify-dependency-integration: true
license-check: true
lint: true

2
node_modules/light-my-request/.taprc generated vendored Normal file
View File

@@ -0,0 +1,2 @@
files:
- test/**/*.test.js

32
node_modules/light-my-request/LICENSE generated vendored Executable file
View File

@@ -0,0 +1,32 @@
Copyright (c) 2017 The Fastify Team
Copyright (c) 2012-2017, Project contributors
Copyright (c) 2012-2014, Walmart
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* The names of any contributors may not be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* * *
The complete list of contributors can be found at:
- https://github.com/hapijs/shot/graphs/contributors
- https://github.com/fastify/light-my-request/graphs/contributors

260
node_modules/light-my-request/README.md generated vendored Normal file
View File

@@ -0,0 +1,260 @@
# Light my Request
![CI](https://github.com/fastify/light-my-request/workflows/CI/badge.svg)
[![NPM version](https://img.shields.io/npm/v/light-my-request.svg?style=flat)](https://www.npmjs.com/package/light-my-request)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/)
Injects a fake HTTP request/response into a node HTTP server for simulating server logic, writing tests, or debugging.
Does not use a socket connection so can be run against an inactive server (server not in listen mode).
## Example
```javascript
const http = require('node:http')
const inject = require('light-my-request')
const dispatch = function (req, res) {
const reply = 'Hello World'
res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })
res.end(reply)
}
const server = http.createServer(dispatch)
inject(dispatch, { method: 'get', url: '/' }, (err, res) => {
console.log(res.payload)
})
```
Note how `server.listen` is never called.
Async await and promises are supported as well!
```javascript
// promises
inject(dispatch, { method: 'get', url: '/' })
.then(res => console.log(res.payload))
.catch(console.log)
// async-await
try {
const res = await inject(dispatch, { method: 'get', url: '/' })
console.log(res.payload)
} catch (err) {
console.log(err)
}
```
You can also use chaining methods if you do not pass the callback function. Check [here](#method-chaining) for details.
```js
// chaining methods
inject(dispatch)
.get('/') // set the request method to GET, and request URL to '/'
.headers({ foo: 'bar' }) // set the request headers
.query({ foo: 'bar' }) // set the query parameters
.end((err, res) => {
console.log(res.payload)
})
inject(dispatch)
.post('/') // set the request method to POST, and request URL to '/'
.payload('request payload') // set the request payload
.body('request body') // alias for payload
.end((err, res) => {
console.log(res.payload)
})
// async-await is also supported
try {
const chain = inject(dispatch).get('/')
const res = await chain.end()
console.log(res.payload)
} catch (err) {
console.log(err)
}
```
File 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:
```js
const formAutoContent = require('form-auto-content')
const fs = require('node:fs')
try {
const form = formAutoContent({
myField: 'hello',
myFile: fs.createReadStream(`./path/to/file`)
})
const res = await inject(dispatch, {
method: 'post',
url: '/upload',
...form
})
console.log(res.payload)
} catch (err) {
console.log(err)
}
```
This 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:
```typescript
import * as LightMyRequest from 'light-my-request'
const dispatch: LightMyRequest.DispatchFunc = function (req, res) {
const reply = 'Hello World'
res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })
res.end(reply)
}
LightMyRequest.inject(dispatch, { method: 'get', url: '/' }, (err, res) => {
console.log(res.payload)
})
// or
import { inject, DispatchFunc } from 'light-my-request'
const dispatch: DispatchFunc = function (req, res) {
const reply = 'Hello World'
res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })
res.end(reply)
}
inject(dispatch, { method: 'get', url: '/' }, (err, res) => {
console.log(res.payload)
})
```
The declaration file exports types for the following parts of the API:
- `inject` - standard light-my-request `inject` method
- `DispatchFunc` - the fake HTTP dispatch function
- `InjectPayload` - a union type for valid payload types
- `isInjection` - standard light-my-request `isInjection` method
- `InjectOptions` - options object for `inject` method
- `Request` - custom light-my-request `request` object interface. Extends
Node.js `stream.Readable` type by default. This behavior can be changed by
setting the `Request` option in the `inject` method's options
- `Response` - custom light-my-request `response` object interface. Extends Node.js `http.ServerResponse` type
## API
#### `inject(dispatchFunc[, options, callback])`
Injects a fake request into an HTTP server.
- `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:
- `req` - a simulated request object. Inherits from `Stream.Readable` by
default. Optionally inherits from another class, set in
`options.Request`
- `res` - a simulated response object. Inherits from node's `Http.ServerResponse`.
- `options` - request options object where:
- `url` | `path` - a string specifying the request URL.
- `method` - a string specifying the HTTP request method, defaulting to `'GET'`.
- `authority` - a string specifying the HTTP HOST header value to be used if no header is provided, and the `url`
does not include an authority component. Defaults to `'localhost'`.
- `headers` - an optional object containing request headers.
- `cookies` - an optional object containing key-value pairs that will be encoded and added to `cookie` header. If the header is already set, the data will be appended.
- `remoteAddress` - an optional string specifying the client remote address. Defaults to `'127.0.0.1'`.
- `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. Oherwise it is serialized with `JSON.stringify` forcing the request to have the `Content-type` equal to `application/json`
- `query` - an optional object or string containing query parameters.
- `body` - alias for payload.
- `simulate` - an object containing flags to simulate various conditions:
- `end` - indicates whether the request will fire an `end` event. Defaults to `undefined`, meaning an `end` event will fire.
- `split` - indicates whether the request payload will be split into chunks. Defaults to `undefined`, meaning payload will not be chunked.
- `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'`.
- `close` - whether the request will emit a `close` event. Defaults to `undefined`, meaning no `close` event will be emitted.
- `validate` - Optional flag to validate this options object. Defaults to `true`.
- `server` - Optional http server. It is used for binding the `dispatchFunc`.
- `autoStart` - Automatically start the request as soon as the method
is called. It is only valid when not passing a callback. Defaults to `true`.
- `signal` - An `AbortSignal` that may be used to abort an ongoing request. Requires Node v16+.
- `Request` - Optional type from which the `request` object should inherit
instead of `stream.Readable`
- `callback` - the callback function using the signature `function (err, res)` where:
- `err` - error object
- `res` - a response object where:
- `raw` - an object containing the raw request and response objects where:
- `req` - the simulated request object.
- `res` - the simulated response object.
- `headers` - an object containing the response headers.
- `statusCode` - the HTTP status code.
- `statusMessage` - the HTTP status message.
- `payload` - the payload as a UTF-8 encoded string.
- `body` - alias for payload.
- `rawPayload` - the raw payload as a Buffer.
- `trailers` - an object containing the response trailers.
- `json` - a function that parses a json response payload and returns an object.
- `stream` - a function that provides a `Readable` stream of the response payload.
- `cookies` - a getter that parses the `set-cookie` response header and returns an array with all the cookies and their metadata.
Notes:
- You can also pass a string in place of the `options` object as a shorthand
for `{url: string, method: 'GET'}`.
- Beware when using the `Request` option. That might make _light-my-request_
slower. Sample benchmark result run on an i5-8600K CPU with `Request` set to
`http.IncomingMessage`:
```
Request x 155,018 ops/sec ±0.47% (94 runs sampled)
Custom Request x 30,373 ops/sec ±0.64% (90 runs sampled)
Request With Cookies x 125,696 ops/sec ±0.29% (96 runs sampled)
Request With Cookies n payload x 114,391 ops/sec ±0.33% (97 runs sampled)
ParseUrl x 255,790 ops/sec ±0.23% (99 runs sampled)
ParseUrl and query x 194,479 ops/sec ±0.16% (99 runs sampled)
```
#### `inject.isInjection(obj)`
Checks if given object `obj` is a *light-my-request* `Request` object.
#### Method chaining
There are following methods you can used as chaining:
- `delete`, `get`, `head`, `options`, `patch`, `post`, `put`, `trace`. They will set the HTTP request method and the request URL.
- `body`, `headers`, `payload`, `query`, `cookies`. They can be used to set the request options object.
And finally you need to call `end`. It has the signature `function (callback)`.
If you invoke `end` without a callback function, the method will return a promise, thus you can:
```js
const chain = inject(dispatch).get('/')
try {
const res = await chain.end()
console.log(res.payload)
} catch (err) {
// handle error
}
// or
chain.end()
.then(res => {
console.log(res.payload)
})
.catch(err => {
// handle error
})
```
By the way, you can also use promises without calling `end`!
```js
inject(dispatch)
.get('/')
.then(res => {
console.log(res.payload)
})
.catch(err => {
// handle error
})
```
Note: The application would not respond multiple times. If you try to invoking any method after the application has responded, the application would throw an error.
## Acknowledgements
This project has been forked from [`hapi/shot`](https://github.com/hapijs/shot) because we wanted to support *Node ≥ v4* and not only *Node ≥ v8*.
All the credits before the commit [00a2a82](https://github.com/fastify/light-my-request/commit/00a2a82eb773b765003b6085788cc3564cd08326) goes to the `hapi/shot` project [contributors](https://github.com/hapijs/shot/graphs/contributors).
Since the commit [db8bced](https://github.com/fastify/light-my-request/commit/db8bced10b4367731688c8738621d42f39680efc) the project will be maintained by the Fastify team.
## License
Licensed under [BSD-3-Clause](./LICENSE).

164
node_modules/light-my-request/benchmark/benchmark.js generated vendored Normal file
View File

@@ -0,0 +1,164 @@
'use strict'
const http = require('node:http')
const Request = require('../lib/request')
const Response = require('../lib/response')
const inject = require('..')
const parseURL = require('../lib/parse-url')
const { Readable } = require('stream')
const { assert } = require('console')
const { Bench } = require('tinybench')
const suite = new Bench()
const mockReq = {
url: 'http://localhost',
method: 'GET',
headers: {
foo: 'bar',
'content-type': 'html',
accepts: 'json',
authorization: 'granted'
}
}
const mockCustomReq = {
url: 'http://localhost',
method: 'GET',
headers: {
foo: 'bar',
'content-type': 'html',
accepts: 'json',
authorization: 'granted'
},
Request: http.IncomingMessage
}
const mockReqCookies = {
url: 'http://localhost',
method: 'GET',
cookies: { foo: 'bar', grass: 'àìùòlé' },
headers: {
foo: 'bar',
'content-type': 'html',
accepts: 'json',
authorization: 'granted'
}
}
const mockReqCookiesPayload = {
url: 'http://localhost',
method: 'GET',
headers: {
foo: 'bar',
'content-type': 'html',
accepts: 'json',
authorization: 'granted'
},
payload: {
foo: { bar: 'fiz' },
bim: { bar: { boom: 'paf' } }
}
}
const mockReqCookiesPayloadBuffer = {
url: 'http://localhost',
method: 'GET',
headers: {
foo: 'bar',
'content-type': 'html',
accepts: 'json',
authorization: 'granted'
},
payload: Buffer.from('foo')
}
const mockReqCookiesPayloadReadable = () => ({
url: 'http://localhost',
method: 'GET',
headers: {
foo: 'bar',
'content-type': 'html',
accepts: 'json',
authorization: 'granted'
},
payload: Readable.from(['foo', 'bar', 'baz'])
})
suite
.add('Request', function () {
new Request(mockReq) // eslint-disable-line no-new
})
.add('Custom Request', function () {
new Request.CustomRequest(mockCustomReq) // eslint-disable-line no-new
})
.add('Request With Cookies', function () {
new Request(mockReqCookies) // eslint-disable-line no-new
})
.add('Request With Cookies n payload', function () {
new Request(mockReqCookiesPayload) // eslint-disable-line no-new
})
.add('ParseUrl', function () {
parseURL('http://example.com:8080/hello')
})
.add('ParseUrl and query', function () {
parseURL('http://example.com:8080/hello', {
foo: 'bar',
message: 'OK',
xs: ['foo', 'bar']
})
})
.add('read request body JSON', function () {
return new Promise((resolve) => {
const req = new Request(mockReqCookiesPayload)
req.prepare(() => {
req.on('data', () => {})
req.on('end', resolve)
})
})
})
.add('read request body buffer', function () {
return new Promise((resolve) => {
const req = new Request(mockReqCookiesPayloadBuffer)
req.prepare(() => {
req.on('data', () => {})
req.on('end', resolve)
})
})
})
.add('read request body readable', function () {
return new Promise((resolve) => {
const req = new Request(mockReqCookiesPayloadReadable())
req.prepare(() => {
req.on('data', () => {})
req.on('end', resolve)
})
})
})
.add('Response write end', function () {
const req = new Request(mockReq)
return new Promise((resolve) => {
const res = new Response(req, resolve)
res.write('foo')
res.end()
})
})
.add('Response writeHead end', function () {
const req = new Request(mockReq)
return new Promise((resolve) => {
const res = new Response(req, resolve)
res.writeHead(400, { 'content-length': 200 })
res.end()
})
})
.add('base inject', async function () {
const d = await inject((req, res) => {
req.on('data', () => {})
req.on('end', () => { res.end('1') })
}, mockReqCookiesPayload)
assert(d.payload === '1')
})
.run()
.then((tasks) => {
const errors = tasks.map(t => t.result?.error).filter((t) => t)
if (errors.length) {
errors.map((e) => console.error(e))
} else {
console.table(suite.table())
}
})

100
node_modules/light-my-request/build/build-validation.js generated vendored Normal file
View File

@@ -0,0 +1,100 @@
'use strict'
const http = require('node:http')
const AjvStandaloneCompiler = require('@fastify/ajv-compiler/standalone')
const fs = require('node:fs')
const path = require('node:path')
const urlSchema = {
oneOf: [
{ type: 'string' },
{
type: 'object',
properties: {
protocol: { type: 'string' },
hostname: { type: 'string' },
pathname: { type: 'string' }
// port type => any
// query type => any
},
additionalProperties: true,
required: ['pathname']
}
]
}
const schema = {
type: 'object',
properties: {
url: urlSchema,
path: urlSchema,
cookies: {
type: 'object',
additionalProperties: true
},
headers: {
type: 'object',
additionalProperties: true
},
query: {
anyOf: [
{
type: 'object',
additionalProperties: true
},
{
type: 'string'
}
]
},
simulate: {
type: 'object',
properties: {
end: { type: 'boolean' },
split: { type: 'boolean' },
error: { type: 'boolean' },
close: { type: 'boolean' }
}
},
authority: { type: 'string' },
remoteAddress: { type: 'string' },
method: { type: 'string', enum: http.METHODS.concat(http.METHODS.map(toLowerCase)) },
validate: { type: 'boolean' }
// payload type => any
},
additionalProperties: true,
oneOf: [
{ required: ['url'] },
{ required: ['path'] }
]
}
function toLowerCase (m) { return m.toLowerCase() }
const factory = AjvStandaloneCompiler({
readMode: false,
storeFunction (routeOpts, schemaValidationCode) {
const moduleCode = `// This file is autogenerated by ${__filename.replace(__dirname, 'build')}, do not edit
/* istanbul ignore file */
/* eslint-disable */
${schemaValidationCode}
`
const file = path.join(__dirname, '..', 'lib', 'config-validator.js')
fs.writeFileSync(file, moduleCode)
console.log(`Saved ${file} file successfully`)
}
})
const compiler = factory({}, {
customOptions: {
code: {
source: true,
lines: true,
optimize: 3
},
removeAdditional: true,
coerceTypes: true
}
})
compiler({ schema })

167
node_modules/light-my-request/index.js generated vendored Normal file
View File

@@ -0,0 +1,167 @@
'use strict'
const assert = require('node:assert')
const Request = require('./lib/request')
const Response = require('./lib/response')
const errorMessage = 'The dispatch function has already been invoked'
const optsValidator = require('./lib/config-validator')
function inject (dispatchFunc, options, callback) {
if (callback === undefined) {
return new Chain(dispatchFunc, options)
} else {
return doInject(dispatchFunc, options, callback)
}
}
function makeRequest (dispatchFunc, server, req, res) {
req.once('error', function (err) {
if (this.destroyed) res.destroy(err)
})
req.once('close', function () {
if (this.destroyed && !this._error) res.destroy()
})
return req.prepare(() => dispatchFunc.call(server, req, res))
}
function doInject (dispatchFunc, options, callback) {
options = (typeof options === 'string' ? { url: options } : options)
if (options.validate !== false) {
assert(typeof dispatchFunc === 'function', 'dispatchFunc should be a function')
const isOptionValid = optsValidator(options)
if (!isOptionValid) {
throw new Error(optsValidator.errors.map(e => e.message))
}
}
const server = options.server || {}
const RequestConstructor = options.Request
? Request.CustomRequest
: Request
// Express.js detection
if (dispatchFunc.request && dispatchFunc.request.app === dispatchFunc) {
Object.setPrototypeOf(Object.getPrototypeOf(dispatchFunc.request), RequestConstructor.prototype)
Object.setPrototypeOf(Object.getPrototypeOf(dispatchFunc.response), Response.prototype)
}
if (typeof callback === 'function') {
const req = new RequestConstructor(options)
const res = new Response(req, callback)
return makeRequest(dispatchFunc, server, req, res)
} else {
return new Promise((resolve, reject) => {
const req = new RequestConstructor(options)
const res = new Response(req, resolve, reject)
makeRequest(dispatchFunc, server, req, res)
})
}
}
function Chain (dispatch, option) {
if (typeof option === 'string') {
this.option = { url: option }
} else {
this.option = Object.assign({}, option)
}
this.dispatch = dispatch
this._hasInvoked = false
this._promise = null
if (this.option.autoStart !== false) {
process.nextTick(() => {
if (!this._hasInvoked) {
this.end()
}
})
}
}
const httpMethods = [
'delete',
'get',
'head',
'options',
'patch',
'post',
'put',
'trace'
]
httpMethods.forEach(method => {
Chain.prototype[method] = function (url) {
if (this._hasInvoked === true || this._promise) {
throw new Error(errorMessage)
}
this.option.url = url
this.option.method = method.toUpperCase()
return this
}
})
const chainMethods = [
'body',
'cookies',
'headers',
'payload',
'query'
]
chainMethods.forEach(method => {
Chain.prototype[method] = function (value) {
if (this._hasInvoked === true || this._promise) {
throw new Error(errorMessage)
}
this.option[method] = value
return this
}
})
Chain.prototype.end = function (callback) {
if (this._hasInvoked === true || this._promise) {
throw new Error(errorMessage)
}
this._hasInvoked = true
if (typeof callback === 'function') {
doInject(this.dispatch, this.option, callback)
} else {
this._promise = doInject(this.dispatch, this.option)
return this._promise
}
}
Object.getOwnPropertyNames(Promise.prototype).forEach(method => {
if (method === 'constructor') return
Chain.prototype[method] = function (...args) {
if (!this._promise) {
if (this._hasInvoked === true) {
throw new Error(errorMessage)
}
this._hasInvoked = true
this._promise = doInject(this.dispatch, this.option)
}
return this._promise[method](...args)
}
})
function isInjection (obj) {
return (
obj instanceof Request ||
obj instanceof Response ||
(obj && obj.constructor && obj.constructor.name === '_CustomLMRRequest')
)
}
module.exports = inject
module.exports.default = inject
module.exports.inject = inject
module.exports.isInjection = isInjection

919
node_modules/light-my-request/lib/config-validator.js generated vendored Normal file
View File

@@ -0,0 +1,919 @@
// This file is autogenerated by build/build-validation.js, do not edit
/* istanbul ignore file */
/* eslint-disable */
"use strict";
module.exports = validate10;
module.exports.default = validate10;
const schema11 = {"type":"object","properties":{"url":{"oneOf":[{"type":"string"},{"type":"object","properties":{"protocol":{"type":"string"},"hostname":{"type":"string"},"pathname":{"type":"string"}},"additionalProperties":true,"required":["pathname"]}]},"path":{"oneOf":[{"type":"string"},{"type":"object","properties":{"protocol":{"type":"string"},"hostname":{"type":"string"},"pathname":{"type":"string"}},"additionalProperties":true,"required":["pathname"]}]},"cookies":{"type":"object","additionalProperties":true},"headers":{"type":"object","additionalProperties":true},"query":{"anyOf":[{"type":"object","additionalProperties":true},{"type":"string"}]},"simulate":{"type":"object","properties":{"end":{"type":"boolean"},"split":{"type":"boolean"},"error":{"type":"boolean"},"close":{"type":"boolean"}}},"authority":{"type":"string"},"remoteAddress":{"type":"string"},"method":{"type":"string","enum":["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE","acl","bind","checkout","connect","copy","delete","get","head","link","lock","m-search","merge","mkactivity","mkcalendar","mkcol","move","notify","options","patch","post","propfind","proppatch","purge","put","rebind","report","search","source","subscribe","trace","unbind","unlink","unlock","unsubscribe"]},"validate":{"type":"boolean"}},"additionalProperties":true,"oneOf":[{"required":["url"]},{"required":["path"]}]};
function validate10(data, {instancePath="", parentData, parentDataProperty, rootData=data}={}){
let vErrors = null;
let errors = 0;
const _errs1 = errors;
let valid0 = false;
let passing0 = null;
const _errs2 = errors;
if(data && typeof data == "object" && !Array.isArray(data)){
let missing0;
if((data.url === undefined) && (missing0 = "url")){
const err0 = {instancePath,schemaPath:"#/oneOf/0/required",keyword:"required",params:{missingProperty: missing0},message:"must have required property '"+missing0+"'"};
if(vErrors === null){
vErrors = [err0];
}
else {
vErrors.push(err0);
}
errors++;
}
}
var _valid0 = _errs2 === errors;
if(_valid0){
valid0 = true;
passing0 = 0;
}
const _errs3 = errors;
if(data && typeof data == "object" && !Array.isArray(data)){
let missing1;
if((data.path === undefined) && (missing1 = "path")){
const err1 = {instancePath,schemaPath:"#/oneOf/1/required",keyword:"required",params:{missingProperty: missing1},message:"must have required property '"+missing1+"'"};
if(vErrors === null){
vErrors = [err1];
}
else {
vErrors.push(err1);
}
errors++;
}
}
var _valid0 = _errs3 === errors;
if(_valid0 && valid0){
valid0 = false;
passing0 = [passing0, 1];
}
else {
if(_valid0){
valid0 = true;
passing0 = 1;
}
}
if(!valid0){
const err2 = {instancePath,schemaPath:"#/oneOf",keyword:"oneOf",params:{passingSchemas: passing0},message:"must match exactly one schema in oneOf"};
if(vErrors === null){
vErrors = [err2];
}
else {
vErrors.push(err2);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs1;
if(vErrors !== null){
if(_errs1){
vErrors.length = _errs1;
}
else {
vErrors = null;
}
}
}
if(errors === 0){
if(data && typeof data == "object" && !Array.isArray(data)){
if(data.url !== undefined){
let data0 = data.url;
const _errs5 = errors;
const _errs6 = errors;
let valid2 = false;
let passing1 = null;
const _errs7 = errors;
if(typeof data0 !== "string"){
let dataType0 = typeof data0;
let coerced0 = undefined;
if(!(coerced0 !== undefined)){
if(dataType0 == "number" || dataType0 == "boolean"){
coerced0 = "" + data0;
}
else if(data0 === null){
coerced0 = "";
}
else {
const err3 = {instancePath:instancePath+"/url",schemaPath:"#/properties/url/oneOf/0/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err3];
}
else {
vErrors.push(err3);
}
errors++;
}
}
if(coerced0 !== undefined){
data0 = coerced0;
if(data !== undefined){
data["url"] = coerced0;
}
}
}
var _valid1 = _errs7 === errors;
if(_valid1){
valid2 = true;
passing1 = 0;
}
const _errs9 = errors;
if(errors === _errs9){
if(data0 && typeof data0 == "object" && !Array.isArray(data0)){
let missing2;
if((data0.pathname === undefined) && (missing2 = "pathname")){
const err4 = {instancePath:instancePath+"/url",schemaPath:"#/properties/url/oneOf/1/required",keyword:"required",params:{missingProperty: missing2},message:"must have required property '"+missing2+"'"};
if(vErrors === null){
vErrors = [err4];
}
else {
vErrors.push(err4);
}
errors++;
}
else {
if(data0.protocol !== undefined){
let data1 = data0.protocol;
const _errs12 = errors;
if(typeof data1 !== "string"){
let dataType1 = typeof data1;
let coerced1 = undefined;
if(!(coerced1 !== undefined)){
if(dataType1 == "number" || dataType1 == "boolean"){
coerced1 = "" + data1;
}
else if(data1 === null){
coerced1 = "";
}
else {
const err5 = {instancePath:instancePath+"/url/protocol",schemaPath:"#/properties/url/oneOf/1/properties/protocol/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err5];
}
else {
vErrors.push(err5);
}
errors++;
}
}
if(coerced1 !== undefined){
data1 = coerced1;
if(data0 !== undefined){
data0["protocol"] = coerced1;
}
}
}
var valid3 = _errs12 === errors;
}
else {
var valid3 = true;
}
if(valid3){
if(data0.hostname !== undefined){
let data2 = data0.hostname;
const _errs14 = errors;
if(typeof data2 !== "string"){
let dataType2 = typeof data2;
let coerced2 = undefined;
if(!(coerced2 !== undefined)){
if(dataType2 == "number" || dataType2 == "boolean"){
coerced2 = "" + data2;
}
else if(data2 === null){
coerced2 = "";
}
else {
const err6 = {instancePath:instancePath+"/url/hostname",schemaPath:"#/properties/url/oneOf/1/properties/hostname/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err6];
}
else {
vErrors.push(err6);
}
errors++;
}
}
if(coerced2 !== undefined){
data2 = coerced2;
if(data0 !== undefined){
data0["hostname"] = coerced2;
}
}
}
var valid3 = _errs14 === errors;
}
else {
var valid3 = true;
}
if(valid3){
if(data0.pathname !== undefined){
let data3 = data0.pathname;
const _errs16 = errors;
if(typeof data3 !== "string"){
let dataType3 = typeof data3;
let coerced3 = undefined;
if(!(coerced3 !== undefined)){
if(dataType3 == "number" || dataType3 == "boolean"){
coerced3 = "" + data3;
}
else if(data3 === null){
coerced3 = "";
}
else {
const err7 = {instancePath:instancePath+"/url/pathname",schemaPath:"#/properties/url/oneOf/1/properties/pathname/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err7];
}
else {
vErrors.push(err7);
}
errors++;
}
}
if(coerced3 !== undefined){
data3 = coerced3;
if(data0 !== undefined){
data0["pathname"] = coerced3;
}
}
}
var valid3 = _errs16 === errors;
}
else {
var valid3 = true;
}
}
}
}
}
else {
const err8 = {instancePath:instancePath+"/url",schemaPath:"#/properties/url/oneOf/1/type",keyword:"type",params:{type: "object"},message:"must be object"};
if(vErrors === null){
vErrors = [err8];
}
else {
vErrors.push(err8);
}
errors++;
}
}
var _valid1 = _errs9 === errors;
if(_valid1 && valid2){
valid2 = false;
passing1 = [passing1, 1];
}
else {
if(_valid1){
valid2 = true;
passing1 = 1;
}
}
if(!valid2){
const err9 = {instancePath:instancePath+"/url",schemaPath:"#/properties/url/oneOf",keyword:"oneOf",params:{passingSchemas: passing1},message:"must match exactly one schema in oneOf"};
if(vErrors === null){
vErrors = [err9];
}
else {
vErrors.push(err9);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs6;
if(vErrors !== null){
if(_errs6){
vErrors.length = _errs6;
}
else {
vErrors = null;
}
}
}
var valid1 = _errs5 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.path !== undefined){
let data4 = data.path;
const _errs18 = errors;
const _errs19 = errors;
let valid4 = false;
let passing2 = null;
const _errs20 = errors;
if(typeof data4 !== "string"){
let dataType4 = typeof data4;
let coerced4 = undefined;
if(!(coerced4 !== undefined)){
if(dataType4 == "number" || dataType4 == "boolean"){
coerced4 = "" + data4;
}
else if(data4 === null){
coerced4 = "";
}
else {
const err10 = {instancePath:instancePath+"/path",schemaPath:"#/properties/path/oneOf/0/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err10];
}
else {
vErrors.push(err10);
}
errors++;
}
}
if(coerced4 !== undefined){
data4 = coerced4;
if(data !== undefined){
data["path"] = coerced4;
}
}
}
var _valid2 = _errs20 === errors;
if(_valid2){
valid4 = true;
passing2 = 0;
}
const _errs22 = errors;
if(errors === _errs22){
if(data4 && typeof data4 == "object" && !Array.isArray(data4)){
let missing3;
if((data4.pathname === undefined) && (missing3 = "pathname")){
const err11 = {instancePath:instancePath+"/path",schemaPath:"#/properties/path/oneOf/1/required",keyword:"required",params:{missingProperty: missing3},message:"must have required property '"+missing3+"'"};
if(vErrors === null){
vErrors = [err11];
}
else {
vErrors.push(err11);
}
errors++;
}
else {
if(data4.protocol !== undefined){
let data5 = data4.protocol;
const _errs25 = errors;
if(typeof data5 !== "string"){
let dataType5 = typeof data5;
let coerced5 = undefined;
if(!(coerced5 !== undefined)){
if(dataType5 == "number" || dataType5 == "boolean"){
coerced5 = "" + data5;
}
else if(data5 === null){
coerced5 = "";
}
else {
const err12 = {instancePath:instancePath+"/path/protocol",schemaPath:"#/properties/path/oneOf/1/properties/protocol/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err12];
}
else {
vErrors.push(err12);
}
errors++;
}
}
if(coerced5 !== undefined){
data5 = coerced5;
if(data4 !== undefined){
data4["protocol"] = coerced5;
}
}
}
var valid5 = _errs25 === errors;
}
else {
var valid5 = true;
}
if(valid5){
if(data4.hostname !== undefined){
let data6 = data4.hostname;
const _errs27 = errors;
if(typeof data6 !== "string"){
let dataType6 = typeof data6;
let coerced6 = undefined;
if(!(coerced6 !== undefined)){
if(dataType6 == "number" || dataType6 == "boolean"){
coerced6 = "" + data6;
}
else if(data6 === null){
coerced6 = "";
}
else {
const err13 = {instancePath:instancePath+"/path/hostname",schemaPath:"#/properties/path/oneOf/1/properties/hostname/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err13];
}
else {
vErrors.push(err13);
}
errors++;
}
}
if(coerced6 !== undefined){
data6 = coerced6;
if(data4 !== undefined){
data4["hostname"] = coerced6;
}
}
}
var valid5 = _errs27 === errors;
}
else {
var valid5 = true;
}
if(valid5){
if(data4.pathname !== undefined){
let data7 = data4.pathname;
const _errs29 = errors;
if(typeof data7 !== "string"){
let dataType7 = typeof data7;
let coerced7 = undefined;
if(!(coerced7 !== undefined)){
if(dataType7 == "number" || dataType7 == "boolean"){
coerced7 = "" + data7;
}
else if(data7 === null){
coerced7 = "";
}
else {
const err14 = {instancePath:instancePath+"/path/pathname",schemaPath:"#/properties/path/oneOf/1/properties/pathname/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err14];
}
else {
vErrors.push(err14);
}
errors++;
}
}
if(coerced7 !== undefined){
data7 = coerced7;
if(data4 !== undefined){
data4["pathname"] = coerced7;
}
}
}
var valid5 = _errs29 === errors;
}
else {
var valid5 = true;
}
}
}
}
}
else {
const err15 = {instancePath:instancePath+"/path",schemaPath:"#/properties/path/oneOf/1/type",keyword:"type",params:{type: "object"},message:"must be object"};
if(vErrors === null){
vErrors = [err15];
}
else {
vErrors.push(err15);
}
errors++;
}
}
var _valid2 = _errs22 === errors;
if(_valid2 && valid4){
valid4 = false;
passing2 = [passing2, 1];
}
else {
if(_valid2){
valid4 = true;
passing2 = 1;
}
}
if(!valid4){
const err16 = {instancePath:instancePath+"/path",schemaPath:"#/properties/path/oneOf",keyword:"oneOf",params:{passingSchemas: passing2},message:"must match exactly one schema in oneOf"};
if(vErrors === null){
vErrors = [err16];
}
else {
vErrors.push(err16);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs19;
if(vErrors !== null){
if(_errs19){
vErrors.length = _errs19;
}
else {
vErrors = null;
}
}
}
var valid1 = _errs18 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.cookies !== undefined){
let data8 = data.cookies;
const _errs31 = errors;
if(errors === _errs31){
if(!(data8 && typeof data8 == "object" && !Array.isArray(data8))){
validate10.errors = [{instancePath:instancePath+"/cookies",schemaPath:"#/properties/cookies/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid1 = _errs31 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.headers !== undefined){
let data9 = data.headers;
const _errs34 = errors;
if(errors === _errs34){
if(!(data9 && typeof data9 == "object" && !Array.isArray(data9))){
validate10.errors = [{instancePath:instancePath+"/headers",schemaPath:"#/properties/headers/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid1 = _errs34 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.query !== undefined){
let data10 = data.query;
const _errs37 = errors;
const _errs38 = errors;
let valid6 = false;
const _errs39 = errors;
if(errors === _errs39){
if(!(data10 && typeof data10 == "object" && !Array.isArray(data10))){
const err17 = {instancePath:instancePath+"/query",schemaPath:"#/properties/query/anyOf/0/type",keyword:"type",params:{type: "object"},message:"must be object"};
if(vErrors === null){
vErrors = [err17];
}
else {
vErrors.push(err17);
}
errors++;
}
}
var _valid3 = _errs39 === errors;
valid6 = valid6 || _valid3;
if(!valid6){
const _errs42 = errors;
if(typeof data10 !== "string"){
let dataType8 = typeof data10;
let coerced8 = undefined;
if(!(coerced8 !== undefined)){
if(dataType8 == "number" || dataType8 == "boolean"){
coerced8 = "" + data10;
}
else if(data10 === null){
coerced8 = "";
}
else {
const err18 = {instancePath:instancePath+"/query",schemaPath:"#/properties/query/anyOf/1/type",keyword:"type",params:{type: "string"},message:"must be string"};
if(vErrors === null){
vErrors = [err18];
}
else {
vErrors.push(err18);
}
errors++;
}
}
if(coerced8 !== undefined){
data10 = coerced8;
if(data !== undefined){
data["query"] = coerced8;
}
}
}
var _valid3 = _errs42 === errors;
valid6 = valid6 || _valid3;
}
if(!valid6){
const err19 = {instancePath:instancePath+"/query",schemaPath:"#/properties/query/anyOf",keyword:"anyOf",params:{},message:"must match a schema in anyOf"};
if(vErrors === null){
vErrors = [err19];
}
else {
vErrors.push(err19);
}
errors++;
validate10.errors = vErrors;
return false;
}
else {
errors = _errs38;
if(vErrors !== null){
if(_errs38){
vErrors.length = _errs38;
}
else {
vErrors = null;
}
}
}
var valid1 = _errs37 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.simulate !== undefined){
let data11 = data.simulate;
const _errs44 = errors;
if(errors === _errs44){
if(data11 && typeof data11 == "object" && !Array.isArray(data11)){
if(data11.end !== undefined){
let data12 = data11.end;
const _errs46 = errors;
if(typeof data12 !== "boolean"){
let coerced9 = undefined;
if(!(coerced9 !== undefined)){
if(data12 === "false" || data12 === 0 || data12 === null){
coerced9 = false;
}
else if(data12 === "true" || data12 === 1){
coerced9 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate/end",schemaPath:"#/properties/simulate/properties/end/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced9 !== undefined){
data12 = coerced9;
if(data11 !== undefined){
data11["end"] = coerced9;
}
}
}
var valid7 = _errs46 === errors;
}
else {
var valid7 = true;
}
if(valid7){
if(data11.split !== undefined){
let data13 = data11.split;
const _errs48 = errors;
if(typeof data13 !== "boolean"){
let coerced10 = undefined;
if(!(coerced10 !== undefined)){
if(data13 === "false" || data13 === 0 || data13 === null){
coerced10 = false;
}
else if(data13 === "true" || data13 === 1){
coerced10 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate/split",schemaPath:"#/properties/simulate/properties/split/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced10 !== undefined){
data13 = coerced10;
if(data11 !== undefined){
data11["split"] = coerced10;
}
}
}
var valid7 = _errs48 === errors;
}
else {
var valid7 = true;
}
if(valid7){
if(data11.error !== undefined){
let data14 = data11.error;
const _errs50 = errors;
if(typeof data14 !== "boolean"){
let coerced11 = undefined;
if(!(coerced11 !== undefined)){
if(data14 === "false" || data14 === 0 || data14 === null){
coerced11 = false;
}
else if(data14 === "true" || data14 === 1){
coerced11 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate/error",schemaPath:"#/properties/simulate/properties/error/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced11 !== undefined){
data14 = coerced11;
if(data11 !== undefined){
data11["error"] = coerced11;
}
}
}
var valid7 = _errs50 === errors;
}
else {
var valid7 = true;
}
if(valid7){
if(data11.close !== undefined){
let data15 = data11.close;
const _errs52 = errors;
if(typeof data15 !== "boolean"){
let coerced12 = undefined;
if(!(coerced12 !== undefined)){
if(data15 === "false" || data15 === 0 || data15 === null){
coerced12 = false;
}
else if(data15 === "true" || data15 === 1){
coerced12 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate/close",schemaPath:"#/properties/simulate/properties/close/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced12 !== undefined){
data15 = coerced12;
if(data11 !== undefined){
data11["close"] = coerced12;
}
}
}
var valid7 = _errs52 === errors;
}
else {
var valid7 = true;
}
}
}
}
}
else {
validate10.errors = [{instancePath:instancePath+"/simulate",schemaPath:"#/properties/simulate/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
var valid1 = _errs44 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.authority !== undefined){
let data16 = data.authority;
const _errs54 = errors;
if(typeof data16 !== "string"){
let dataType13 = typeof data16;
let coerced13 = undefined;
if(!(coerced13 !== undefined)){
if(dataType13 == "number" || dataType13 == "boolean"){
coerced13 = "" + data16;
}
else if(data16 === null){
coerced13 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/authority",schemaPath:"#/properties/authority/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced13 !== undefined){
data16 = coerced13;
if(data !== undefined){
data["authority"] = coerced13;
}
}
}
var valid1 = _errs54 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.remoteAddress !== undefined){
let data17 = data.remoteAddress;
const _errs56 = errors;
if(typeof data17 !== "string"){
let dataType14 = typeof data17;
let coerced14 = undefined;
if(!(coerced14 !== undefined)){
if(dataType14 == "number" || dataType14 == "boolean"){
coerced14 = "" + data17;
}
else if(data17 === null){
coerced14 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/remoteAddress",schemaPath:"#/properties/remoteAddress/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced14 !== undefined){
data17 = coerced14;
if(data !== undefined){
data["remoteAddress"] = coerced14;
}
}
}
var valid1 = _errs56 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.method !== undefined){
let data18 = data.method;
const _errs58 = errors;
if(typeof data18 !== "string"){
let dataType15 = typeof data18;
let coerced15 = undefined;
if(!(coerced15 !== undefined)){
if(dataType15 == "number" || dataType15 == "boolean"){
coerced15 = "" + data18;
}
else if(data18 === null){
coerced15 = "";
}
else {
validate10.errors = [{instancePath:instancePath+"/method",schemaPath:"#/properties/method/type",keyword:"type",params:{type: "string"},message:"must be string"}];
return false;
}
}
if(coerced15 !== undefined){
data18 = coerced15;
if(data !== undefined){
data["method"] = coerced15;
}
}
}
if(!((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((data18 === "ACL") || (data18 === "BIND")) || (data18 === "CHECKOUT")) || (data18 === "CONNECT")) || (data18 === "COPY")) || (data18 === "DELETE")) || (data18 === "GET")) || (data18 === "HEAD")) || (data18 === "LINK")) || (data18 === "LOCK")) || (data18 === "M-SEARCH")) || (data18 === "MERGE")) || (data18 === "MKACTIVITY")) || (data18 === "MKCALENDAR")) || (data18 === "MKCOL")) || (data18 === "MOVE")) || (data18 === "NOTIFY")) || (data18 === "OPTIONS")) || (data18 === "PATCH")) || (data18 === "POST")) || (data18 === "PROPFIND")) || (data18 === "PROPPATCH")) || (data18 === "PURGE")) || (data18 === "PUT")) || (data18 === "REBIND")) || (data18 === "REPORT")) || (data18 === "SEARCH")) || (data18 === "SOURCE")) || (data18 === "SUBSCRIBE")) || (data18 === "TRACE")) || (data18 === "UNBIND")) || (data18 === "UNLINK")) || (data18 === "UNLOCK")) || (data18 === "UNSUBSCRIBE")) || (data18 === "acl")) || (data18 === "bind")) || (data18 === "checkout")) || (data18 === "connect")) || (data18 === "copy")) || (data18 === "delete")) || (data18 === "get")) || (data18 === "head")) || (data18 === "link")) || (data18 === "lock")) || (data18 === "m-search")) || (data18 === "merge")) || (data18 === "mkactivity")) || (data18 === "mkcalendar")) || (data18 === "mkcol")) || (data18 === "move")) || (data18 === "notify")) || (data18 === "options")) || (data18 === "patch")) || (data18 === "post")) || (data18 === "propfind")) || (data18 === "proppatch")) || (data18 === "purge")) || (data18 === "put")) || (data18 === "rebind")) || (data18 === "report")) || (data18 === "search")) || (data18 === "source")) || (data18 === "subscribe")) || (data18 === "trace")) || (data18 === "unbind")) || (data18 === "unlink")) || (data18 === "unlock")) || (data18 === "unsubscribe"))){
validate10.errors = [{instancePath:instancePath+"/method",schemaPath:"#/properties/method/enum",keyword:"enum",params:{allowedValues: schema11.properties.method.enum},message:"must be equal to one of the allowed values"}];
return false;
}
var valid1 = _errs58 === errors;
}
else {
var valid1 = true;
}
if(valid1){
if(data.validate !== undefined){
let data19 = data.validate;
const _errs60 = errors;
if(typeof data19 !== "boolean"){
let coerced16 = undefined;
if(!(coerced16 !== undefined)){
if(data19 === "false" || data19 === 0 || data19 === null){
coerced16 = false;
}
else if(data19 === "true" || data19 === 1){
coerced16 = true;
}
else {
validate10.errors = [{instancePath:instancePath+"/validate",schemaPath:"#/properties/validate/type",keyword:"type",params:{type: "boolean"},message:"must be boolean"}];
return false;
}
}
if(coerced16 !== undefined){
data19 = coerced16;
if(data !== undefined){
data["validate"] = coerced16;
}
}
}
var valid1 = _errs60 === errors;
}
else {
var valid1 = true;
}
}
}
}
}
}
}
}
}
}
}
else {
validate10.errors = [{instancePath,schemaPath:"#/type",keyword:"type",params:{type: "object"},message:"must be object"}];
return false;
}
}
validate10.errors = vErrors;
return errors === 0;
}

81
node_modules/light-my-request/lib/form-data.js generated vendored Normal file
View File

@@ -0,0 +1,81 @@
'use strict'
const { randomUUID } = require('node:crypto')
const { Readable } = require('node:stream')
let textEncoder
function isFormDataLike (payload) {
return (
payload &&
typeof payload === 'object' &&
typeof payload.append === 'function' &&
typeof payload.delete === 'function' &&
typeof payload.get === 'function' &&
typeof payload.getAll === 'function' &&
typeof payload.has === 'function' &&
typeof payload.set === 'function' &&
payload[Symbol.toStringTag] === 'FormData'
)
}
/*
partial code extraction and refactoring of `undici`.
MIT License. https://github.com/nodejs/undici/blob/043d8f1a89f606b1db259fc71f4c9bc8eb2aa1e6/lib/web/fetch/LICENSE
Reference https://github.com/nodejs/undici/blob/043d8f1a89f606b1db259fc71f4c9bc8eb2aa1e6/lib/web/fetch/body.js#L102-L168
*/
function formDataToStream (formdata) {
// lazy creation of TextEncoder
textEncoder = textEncoder ?? new TextEncoder()
// we expect the function argument must be FormData
const boundary = `----formdata-${randomUUID()}`
const prefix = `--${boundary}\r\nContent-Disposition: form-data`
/*! formdata-polyfill. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> */
const escape = (str) =>
str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22')
const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n')
const linebreak = new Uint8Array([13, 10]) // '\r\n'
async function * asyncIterator () {
for (const [name, value] of formdata) {
if (typeof value === 'string') {
// header
yield textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"\r\n\r\n`)
// body
yield textEncoder.encode(`${normalizeLinefeeds(value)}\r\n`)
} else {
let header = `${prefix}; name="${escape(normalizeLinefeeds(name))}"`
value.name && (header += `; filename="${escape(value.name)}"`)
header += `\r\nContent-Type: ${value.type || 'application/octet-stream'}\r\n\r\n`
// header
yield textEncoder.encode(header)
// body
/* istanbul ignore else */
if (value.stream) {
yield * value.stream()
} else {
// shouldn't be here since Blob / File should provide .stream
// and FormData always convert to USVString
/* istanbul ignore next */
yield value
}
yield linebreak
}
}
// end
yield textEncoder.encode(`--${boundary}--`)
}
const stream = Readable.from(asyncIterator())
return {
stream,
contentType: `multipart/form-data; boundary=${boundary}`
}
}
module.exports.isFormDataLike = isFormDataLike
module.exports.formDataToStream = formDataToStream

47
node_modules/light-my-request/lib/parse-url.js generated vendored Normal file
View File

@@ -0,0 +1,47 @@
'use strict'
const { URL } = require('node:url')
const BASE_URL = 'http://localhost'
/**
* Parse URL
*
* @param {(Object|String)} url
* @param {Object} [query]
* @return {URL}
*/
module.exports = function parseURL (url, query) {
if ((typeof url === 'string' || Object.prototype.toString.call(url) === '[object String]') && url.startsWith('//')) {
url = BASE_URL + url
}
const result = typeof url === 'object'
? Object.assign(new URL(BASE_URL), url)
: new URL(url, BASE_URL)
if (typeof query === 'string') {
query = new URLSearchParams(query)
for (const key of query.keys()) {
result.searchParams.delete(key)
for (const value of query.getAll(key)) {
result.searchParams.append(key, value)
}
}
} else {
const merged = Object.assign({}, url.query, query)
for (const key in merged) {
const value = merged[key]
if (Array.isArray(value)) {
result.searchParams.delete(key)
for (const param of value) {
result.searchParams.append(key, param)
}
} else {
result.searchParams.set(key, value)
}
}
}
return result
}

268
node_modules/light-my-request/lib/request.js generated vendored Normal file
View File

@@ -0,0 +1,268 @@
'use strict'
/* eslint no-prototype-builtins: 0 */
const { Readable, addAbortSignal } = require('node:stream')
const util = require('node:util')
const cookie = require('cookie')
const assert = require('node:assert')
const { createDeprecation } = require('process-warning')
const parseURL = require('./parse-url')
const { isFormDataLike, formDataToStream } = require('./form-data')
const { EventEmitter } = require('node:events')
// request.connectin deprecation https://nodejs.org/api/http.html#http_request_connection
const FST_LIGHTMYREQUEST_DEP01 = createDeprecation({ name: 'FastifyDeprecationLightMyRequest', code: 'FST_LIGHTMYREQUEST_DEP01', message: 'You are accessing "request.connection", use "request.socket" instead.' })
/**
* Get hostname:port
*
* @param {URL} parsedURL
* @return {String}
*/
function hostHeaderFromURL (parsedURL) {
return parsedURL.port
? parsedURL.host
: parsedURL.hostname + (parsedURL.protocol === 'https:' ? ':443' : ':80')
}
/**
* Mock socket object used to fake access to a socket for a request
*
* @constructor
* @param {String} remoteAddress the fake address to show consumers of the socket
*/
class MockSocket extends EventEmitter {
constructor (remoteAddress) {
super()
this.remoteAddress = remoteAddress
}
}
/**
* CustomRequest
*
* @constructor
* @param {Object} options
* @param {(Object|String)} options.url || options.path
* @param {String} [options.method='GET']
* @param {String} [options.remoteAddress]
* @param {Object} [options.cookies]
* @param {Object} [options.headers]
* @param {Object} [options.query]
* @param {Object} [options.Request]
* @param {any} [options.payload]
*/
function CustomRequest (options) {
return new _CustomLMRRequest(this)
function _CustomLMRRequest (obj) {
Request.call(obj, {
...options,
Request: undefined
})
Object.assign(this, obj)
for (const fn of Object.keys(Request.prototype)) {
this.constructor.prototype[fn] = Request.prototype[fn]
}
util.inherits(this.constructor, options.Request)
return this
}
}
/**
* Request
*
* @constructor
* @param {Object} options
* @param {(Object|String)} options.url || options.path
* @param {String} [options.method='GET']
* @param {String} [options.remoteAddress]
* @param {Object} [options.cookies]
* @param {Object} [options.headers]
* @param {Object} [options.query]
* @param {any} [options.payload]
*/
function Request (options) {
Readable.call(this, {
autoDestroy: false
})
const parsedURL = parseURL(options.url || options.path, options.query)
this.url = parsedURL.pathname + parsedURL.search
this.aborted = false
this.httpVersionMajor = 1
this.httpVersionMinor = 1
this.httpVersion = '1.1'
this.method = options.method ? options.method.toUpperCase() : 'GET'
this.headers = {}
this.rawHeaders = []
const headers = options.headers || {}
for (const field in headers) {
const fieldLowerCase = field.toLowerCase()
if (
(
fieldLowerCase === 'user-agent' ||
fieldLowerCase === 'content-type'
) && headers[field] === undefined
) {
this.headers[fieldLowerCase] = undefined
continue
}
const value = headers[field]
assert(value !== undefined, 'invalid value "undefined" for header ' + field)
this.headers[fieldLowerCase] = '' + value
}
if (('user-agent' in this.headers) === false) {
this.headers['user-agent'] = 'lightMyRequest'
}
this.headers.host = this.headers.host || options.authority || hostHeaderFromURL(parsedURL)
if (options.cookies) {
const { cookies } = options
const cookieValues = Object.keys(cookies).map(key => cookie.serialize(key, cookies[key]))
if (this.headers.cookie) {
cookieValues.unshift(this.headers.cookie)
}
this.headers.cookie = cookieValues.join('; ')
}
this.socket = new MockSocket(options.remoteAddress || '127.0.0.1')
Object.defineProperty(this, 'connection', {
get () {
FST_LIGHTMYREQUEST_DEP01()
return this.socket
},
configurable: true
})
// we keep both payload and body for compatibility reasons
let payload = options.payload || options.body || null
let payloadResume = payload && typeof payload.resume === 'function'
if (isFormDataLike(payload)) {
const stream = formDataToStream(payload)
payload = stream.stream
payloadResume = true
// we override the content-type
this.headers['content-type'] = stream.contentType
}
if (payload && typeof payload !== 'string' && !payloadResume && !Buffer.isBuffer(payload)) {
payload = JSON.stringify(payload)
if (('content-type' in this.headers) === false) {
this.headers['content-type'] = 'application/json'
}
}
// Set the content-length for the corresponding payload if none set
if (payload && !payloadResume && !Object.prototype.hasOwnProperty.call(this.headers, 'content-length')) {
this.headers['content-length'] = (Buffer.isBuffer(payload) ? payload.length : Buffer.byteLength(payload)).toString()
}
for (const header of Object.keys(this.headers)) {
this.rawHeaders.push(header, this.headers[header])
}
// Use _lightMyRequest namespace to avoid collision with Node
this._lightMyRequest = {
payload,
isDone: false,
simulate: options.simulate || {}
}
const signal = options.signal
/* istanbul ignore if */
if (signal) {
addAbortSignal(signal, this)
}
return this
}
util.inherits(Request, Readable)
util.inherits(CustomRequest, Request)
Request.prototype.prepare = function (next) {
const payload = this._lightMyRequest.payload
if (!payload || typeof payload.resume !== 'function') { // does not quack like a stream
return next()
}
const chunks = []
payload.on('data', (chunk) => chunks.push(Buffer.from(chunk)))
payload.on('end', () => {
const payload = Buffer.concat(chunks)
this.headers['content-length'] = this.headers['content-length'] || ('' + payload.length)
this._lightMyRequest.payload = payload
return next()
})
// Force to resume the stream. Needed for Stream 1
payload.resume()
}
Request.prototype._read = function (size) {
setImmediate(() => {
if (this._lightMyRequest.isDone) {
// 'end' defaults to true
if (this._lightMyRequest.simulate.end !== false) {
this.push(null)
}
return
}
this._lightMyRequest.isDone = true
if (this._lightMyRequest.payload) {
if (this._lightMyRequest.simulate.split) {
this.push(this._lightMyRequest.payload.slice(0, 1))
this.push(this._lightMyRequest.payload.slice(1))
} else {
this.push(this._lightMyRequest.payload)
}
}
if (this._lightMyRequest.simulate.error) {
this.emit('error', new Error('Simulated'))
}
if (this._lightMyRequest.simulate.close) {
this.emit('close')
}
// 'end' defaults to true
if (this._lightMyRequest.simulate.end !== false) {
this.push(null)
}
})
}
Request.prototype.destroy = function (error) {
if (this.destroyed || this._lightMyRequest.isDone) return
this.destroyed = true
if (error) {
this._error = true
process.nextTick(() => this.emit('error', error))
}
process.nextTick(() => this.emit('close'))
}
module.exports = Request
module.exports.Request = Request
module.exports.CustomRequest = CustomRequest

189
node_modules/light-my-request/lib/response.js generated vendored Normal file
View File

@@ -0,0 +1,189 @@
'use strict'
const http = require('node:http')
const { Writable, Readable } = require('node:stream')
const util = require('node:util')
const setCookie = require('set-cookie-parser')
function Response (req, onEnd, reject) {
http.ServerResponse.call(this, req)
this._lightMyRequest = { headers: null, trailers: {}, payloadChunks: [] }
// This forces node@8 to always render the headers
this.setHeader('foo', 'bar'); this.removeHeader('foo')
this.assignSocket(getNullSocket())
this._promiseCallback = typeof reject === 'function'
let called = false
const onEndSuccess = (payload) => {
// no need to early-return if already called because this handler is bound `once`
called = true
if (this._promiseCallback) {
return process.nextTick(() => onEnd(payload))
}
process.nextTick(() => onEnd(null, payload))
}
const onEndFailure = (err) => {
if (called) return
called = true
if (this._promiseCallback) {
return process.nextTick(() => reject(err))
}
process.nextTick(() => onEnd(err, null))
}
this.once('finish', () => {
const res = generatePayload(this)
res.raw.req = req
onEndSuccess(res)
})
this.connection.once('error', onEndFailure)
this.once('error', onEndFailure)
this.once('close', onEndFailure)
}
util.inherits(Response, http.ServerResponse)
Response.prototype.setTimeout = function (msecs, callback) {
this.timeoutHandle = setTimeout(() => {
this.emit('timeout')
}, msecs)
this.on('timeout', callback)
return this
}
Response.prototype.writeHead = function () {
const result = http.ServerResponse.prototype.writeHead.apply(this, arguments)
copyHeaders(this)
return result
}
Response.prototype.write = function (data, encoding, callback) {
if (this.timeoutHandle) {
clearTimeout(this.timeoutHandle)
}
http.ServerResponse.prototype.write.call(this, data, encoding, callback)
this._lightMyRequest.payloadChunks.push(Buffer.from(data, encoding))
return true
}
Response.prototype.end = function (data, encoding, callback) {
if (data) {
this.write(data, encoding)
}
http.ServerResponse.prototype.end.call(this, callback)
this.emit('finish')
// We need to emit 'close' otherwise stream.finished() would
// not pick it up on Node v16
this.destroy()
}
Response.prototype.destroy = function (error) {
if (this.destroyed) return
this.destroyed = true
if (error) {
process.nextTick(() => this.emit('error', error))
}
process.nextTick(() => this.emit('close'))
}
Response.prototype.addTrailers = function (trailers) {
for (const key in trailers) {
this._lightMyRequest.trailers[key.toLowerCase().trim()] = trailers[key].toString().trim()
}
}
function generatePayload (response) {
// This seems only to happen when using `fastify-express` - see https://github.com/fastify/fastify-express/issues/47
/* istanbul ignore if */
if (response._lightMyRequest.headers === null) {
copyHeaders(response)
}
serializeHeaders(response)
// Prepare response object
const res = {
raw: {
res: response
},
headers: response._lightMyRequest.headers,
statusCode: response.statusCode,
statusMessage: response.statusMessage,
trailers: {},
get cookies () {
return setCookie.parse(this)
}
}
// Prepare payload and trailers
const rawBuffer = Buffer.concat(response._lightMyRequest.payloadChunks)
res.rawPayload = rawBuffer
// we keep both of them for compatibility reasons
res.payload = rawBuffer.toString()
res.body = res.payload
res.trailers = response._lightMyRequest.trailers
// Prepare payload parsers
res.json = function parseJsonPayload () {
return JSON.parse(res.payload)
}
// Provide stream Readable for advanced user
res.stream = function streamPayload () {
return Readable.from(response._lightMyRequest.payloadChunks)
}
return res
}
// Throws away all written data to prevent response from buffering payload
function getNullSocket () {
return new Writable({
write (chunk, encoding, callback) {
setImmediate(callback)
}
})
}
function serializeHeaders (response) {
const headers = response._lightMyRequest.headers
for (const headerName of Object.keys(headers)) {
const headerValue = headers[headerName]
if (Array.isArray(headerValue)) {
headers[headerName] = headerValue.map(value => '' + value)
} else {
headers[headerName] = '' + headerValue
}
}
}
function copyHeaders (response) {
response._lightMyRequest.headers = Object.assign({}, response.getHeaders())
// Add raw headers
;['Date', 'Connection', 'Transfer-Encoding'].forEach((name) => {
const regex = new RegExp('\\r\\n' + name + ': ([^\\r]*)\\r\\n')
const field = response._header.match(regex)
if (field) {
response._lightMyRequest.headers[name.toLowerCase()] = field[1]
}
})
}
module.exports = Response

58
node_modules/light-my-request/package.json generated vendored Normal file
View File

@@ -0,0 +1,58 @@
{
"name": "light-my-request",
"version": "5.14.0",
"description": "Fake HTTP injection library",
"main": "index.js",
"type": "commonjs",
"types": "types/index.d.ts",
"dependencies": {
"cookie": "^0.7.0",
"process-warning": "^3.0.0",
"set-cookie-parser": "^2.4.1"
},
"devDependencies": {
"@fastify/ajv-compiler": "^3.1.0",
"@fastify/pre-commit": "^2.0.2",
"@types/node": "^20.1.0",
"end-of-stream": "^1.4.4",
"express": "^4.17.1",
"form-auto-content": "^3.0.0",
"form-data": "^4.0.0",
"formdata-node": "^4.4.1",
"standard": "^17.0.0",
"tap": "^16.0.0",
"tinybench": "^2.5.1",
"tsd": "^0.31.0",
"undici": "^5.28.4"
},
"scripts": {
"benchmark": "node benchmark/benchmark.js",
"coverage": "npm run unit -- --cov --coverage-report=html",
"lint": "standard",
"test": "npm run lint && npm run test:unit && npm run test:typescript",
"test:typescript": "tsd",
"test:unit": "tap"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fastify/light-my-request.git"
},
"keywords": [
"http",
"inject",
"fake",
"request",
"server"
],
"author": "Tomas Della Vedova - @delvedor (http://delved.org)",
"license": "BSD-3-Clause",
"bugs": {
"url": "https://github.com/fastify/light-my-request/issues"
},
"homepage": "https://github.com/fastify/light-my-request/blob/master/README.md",
"standard": {
"ignore": [
"test/benchmark.js"
]
}
}

55
node_modules/light-my-request/test/async-await.test.js generated vendored Normal file
View File

@@ -0,0 +1,55 @@
'use strict'
const { test } = require('tap')
const inject = require('../index')
test('basic async await', async t => {
const dispatch = function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('hello')
}
try {
const res = await inject(dispatch, { method: 'GET', url: 'http://example.com:8080/hello' })
t.equal(res.payload, 'hello')
} catch (err) {
t.fail(err)
}
})
test('basic async await (errored)', async t => {
const dispatch = function (req, res) {
res.connection.destroy(new Error('kaboom'))
}
await t.rejects(inject(dispatch, { method: 'GET', url: 'http://example.com:8080/hello' }))
})
test('chainable api with async await', async t => {
const dispatch = function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('hello')
}
try {
const chain = inject(dispatch).get('http://example.com:8080/hello')
const res = await chain.end()
t.equal(res.payload, 'hello')
} catch (err) {
t.fail(err)
}
})
test('chainable api with async await without end()', async t => {
const dispatch = function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' })
res.end('hello')
}
try {
const res = await inject(dispatch).get('http://example.com:8080/hello')
t.equal(res.payload, 'hello')
} catch (err) {
t.fail(err)
}
})

2110
node_modules/light-my-request/test/index.test.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

16
node_modules/light-my-request/test/request.test.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
'use strict'
const { test } = require('tap')
const Request = require('../lib/request')
test('aborted property should be false', async (t) => {
const mockReq = {
url: 'http://localhost',
method: 'GET',
headers: {}
}
const req = new Request(mockReq)
t.same(req.aborted, false)
})

17
node_modules/light-my-request/test/response.test.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
'use strict'
const { test } = require('tap')
const Response = require('../lib/response')
test('multiple calls to res.destroy should not be called', (t) => {
t.plan(1)
const mockReq = {}
const res = new Response(mockReq, (err, response) => {
t.error(err)
})
res.destroy()
res.destroy()
})

127
node_modules/light-my-request/types/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,127 @@
import * as http from 'http'
import { Readable } from 'stream'
type HTTPMethods = 'DELETE' | 'delete' |
'GET' | 'get' |
'HEAD' | 'head' |
'PATCH' | 'patch' |
'POST' | 'post' |
'PUT' | 'put' |
'OPTIONS' | 'options'
type Inject = typeof inject
declare namespace inject {
export type DispatchFunc = http.RequestListener
export type CallbackFunc = (err: Error | undefined, response: Response | undefined) => void
export type InjectPayload = string | object | Buffer | NodeJS.ReadableStream
export function isInjection (obj: http.IncomingMessage | http.ServerResponse): boolean
export interface AbortSignal {
readonly aborted: boolean;
}
export interface InjectOptions {
url?: string | {
pathname: string
protocol?: string
hostname?: string
port?: string | number
query?: string | { [k: string]: string | string[] }
}
path?: string | {
pathname: string
protocol?: string
hostname?: string
port?: string | number
query?: string | { [k: string]: string | string[] }
}
headers?: http.IncomingHttpHeaders | http.OutgoingHttpHeaders
query?: string | { [k: string]: string | string[] }
simulate?: {
end: boolean,
split: boolean,
error: boolean,
close: boolean
}
authority?: string
remoteAddress?: string
method?: HTTPMethods
validate?: boolean
payload?: InjectPayload
body?: InjectPayload
server?: http.Server
autoStart?: boolean
cookies?: { [k: string]: string },
signal?: AbortSignal,
Request?: object,
}
/**
* https://github.com/nfriedly/set-cookie-parser/blob/3eab8b7d5d12c8ed87832532861c1a35520cf5b3/lib/set-cookie.js#L41
*/
interface Cookie {
name: string;
value: string;
expires?: Date;
maxAge?: number;
secure?: boolean;
httpOnly?: boolean;
sameSite?: string;
[name: string]: unknown
}
export interface Response {
raw: {
res: http.ServerResponse,
req: http.IncomingMessage
}
rawPayload: Buffer
headers: http.OutgoingHttpHeaders
statusCode: number
statusMessage: string
trailers: { [key: string]: string }
payload: string
body: string
json: <T = any>() => T
stream: () => Readable
cookies: Array<Cookie>
}
export interface Chain extends Promise<Response> {
delete: (url: string) => Chain
get: (url: string) => Chain
head: (url: string) => Chain
options: (url: string) => Chain
patch: (url: string) => Chain
post: (url: string) => Chain
put: (url: string) => Chain
trace: (url: string) => Chain
body: (body: InjectPayload) => Chain
headers: (headers: http.IncomingHttpHeaders | http.OutgoingHttpHeaders) => Chain
payload: (payload: InjectPayload) => Chain
query: (query: string | { [k: string]: string | string[] } ) => Chain
cookies: (query: object) => Chain
end(): Promise<Response>
end(callback: CallbackFunc): void
}
export const inject: Inject
export { inject as default }
}
declare function inject (
dispatchFunc: inject.DispatchFunc,
options?: string | inject.InjectOptions
): inject.Chain
declare function inject (
dispatchFunc: inject.DispatchFunc,
options: string | inject.InjectOptions,
callback: inject.CallbackFunc
): void
export = inject

144
node_modules/light-my-request/types/index.test-d.ts generated vendored Normal file
View File

@@ -0,0 +1,144 @@
import * as http from 'http'
import { inject, isInjection, Response, DispatchFunc, InjectOptions, Chain } from '..'
import { expectType, expectAssignable, expectNotAssignable } from 'tsd'
import { Readable } from 'stream'
expectAssignable<InjectOptions>({ url: '/' })
expectAssignable<InjectOptions>({ autoStart: true })
expectAssignable<InjectOptions>({ autoStart: false })
expectAssignable<InjectOptions>({ validate: true })
expectAssignable<InjectOptions>({ validate: false })
const dispatch: http.RequestListener = function (req, res) {
expectAssignable<http.IncomingMessage>(req)
expectAssignable<http.ServerResponse>(res)
expectType<boolean>(isInjection(req))
expectType<boolean>(isInjection(res))
const reply = 'Hello World'
res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })
res.end(reply)
}
const expectResponse = function (res: Response | undefined) {
if (!res) {
return;
}
expectType<Response>(res)
console.log(res.payload)
expectAssignable<Function>(res.json)
expectAssignable<Function>(res.stream)
expectAssignable<http.ServerResponse>(res.raw.res)
expectAssignable<http.IncomingMessage>(res.raw.req)
expectType<Readable>(res.stream())
expectType<string>(res.payload)
expectType<string>(res.body)
expectAssignable<Array<any>>(res.cookies)
const cookie = res.cookies[0]
expectType<string>(cookie.name)
expectType<string>(cookie.value)
expectType<Date | undefined>(cookie.expires)
expectType<number | undefined>(cookie.maxAge)
expectType<boolean | undefined>(cookie.httpOnly)
expectType<boolean | undefined>(cookie.secure)
expectType<string | undefined>(cookie.sameSite)
expectType<unknown | undefined>(cookie.additional)
}
expectType<DispatchFunc>(dispatch)
inject(dispatch, { method: 'get', url: '/' }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})
const url = {
protocol: 'http',
hostname: 'example.com',
port: '8080',
pathname: 'hello',
query: {
test: '1234'
}
}
inject(dispatch, { method: 'get', url }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})
inject(dispatch, { method: 'get', url: '/', cookies: { name1: 'value1', value2: 'value2' } }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})
inject(dispatch, { method: 'get', url: '/', query: { name1: 'value1', value2: 'value2' } }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})
inject(dispatch, { method: 'get', url: '/', query: { name1: ['value1', 'value2'] } }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})
inject(dispatch, { method: 'get', url: '/', query: 'name1=value1' }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})
inject(dispatch, { method: 'post', url: '/', payload: { name1: 'value1', value2: 'value2' } }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})
inject(dispatch, { method: 'post', url: '/', body: { name1: 'value1', value2: 'value2' } }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})
expectType<void>(
inject(dispatch)
.get('/')
.end((err, res) => {
expectType<Error | undefined>(err)
expectType<Response | undefined>(res)
console.log(res?.payload)
})
)
inject(dispatch)
.get('/')
.then((value) => {
expectType<Response>(value)
})
expectType<Chain>(inject(dispatch))
expectType<Promise<Response>>(inject(dispatch).end())
expectType<Chain>(inject(dispatch, { method: 'get', url: '/' }))
// @ts-ignore tsd supports top-level await, but normal ts does not so ignore
expectType<Response>(await inject(dispatch, { method: 'get', url: '/' }))
type ParsedValue = { field: string }
// @ts-ignore tsd supports top-level await, but normal ts does not so ignore
const response: Response = await inject(dispatch)
const parsedValue: ParsedValue = response.json()
expectType<ParsedValue>(parsedValue)
const parsedValueUsingGeneric = response.json<ParsedValue>()
expectType<ParsedValue>(parsedValueUsingGeneric)
expectNotAssignable<http.ServerResponse>(response)
const httpDispatch = function (req: http.IncomingMessage, res: http.ServerResponse) {
expectType<boolean>(isInjection(req))
expectType<boolean>(isInjection(res))
const reply = 'Hello World'
res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length })
res.end(reply)
}
inject(httpDispatch, { method: 'get', url: '/' }, (err, res) => {
expectType<Error | undefined>(err)
expectResponse(res)
})