fatsify核心功能示例测试!!!

This commit is contained in:
2025-09-21 14:50:41 +08:00
commit 9145aea047
1958 changed files with 230098 additions and 0 deletions

2
node_modules/@fastify/error/.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/@fastify/error/.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: "monthly"
open-pull-requests-limit: 10

28
node_modules/@fastify/error/.github/workflows/ci.yml generated vendored Normal file
View File

@@ -0,0 +1,28 @@
name: CI
on:
push:
branches:
- main
- next
- 'v*'
paths-ignore:
- 'docs/**'
- '*.md'
pull_request:
paths-ignore:
- 'docs/**'
- '*.md'
permissions:
contents: read
jobs:
test:
permissions:
contents: write
pull-requests: write
uses: fastify/workflows/.github/workflows/plugins-ci.yml@v5
with:
license-check: true
lint: true

21
node_modules/@fastify/error/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Fastify
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

140
node_modules/@fastify/error/README.md generated vendored Normal file
View File

@@ -0,0 +1,140 @@
# @fastify/error
[![CI](https://github.com/fastify/fastify-error/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-error/actions/workflows/ci.yml)
[![NPM version](https://img.shields.io/npm/v/@fastify/error.svg?style=flat)](https://www.npmjs.com/package/@fastify/error)
[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)
A small utility, used by Fastify itself, for generating consistent error objects across your codebase and plugins.
### Install
```
npm i @fastify/error
```
### Usage
The module exports a function that you can use for consistent error objects, it takes 4 parameters:
```js
createError(code, message [, statusCode [, Base [, captureStackTrace]]])
```
- `code` (`string`, required) - The error code, you can access it later with `error.code`. For consistency, we recommend prefixing plugin error codes with `FST_`
- `message` (`string`, required) - The error message. You can also use interpolated strings for formatting the message.
- `statusCode` (`number`, optional) - The status code that Fastify will use if the error is sent via HTTP.
- `Base` (`ErrorConstructor`, optional) - The base error object that will be used. (eg `TypeError`, `RangeError`)
- `captureStackTrace` (`boolean`, optional) - Whether to capture the stack trace or not.
```js
const createError = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello')
console.log(new CustomError()) // error.message => 'Hello'
```
How to use an interpolated string:
```js
const createError = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello %s')
console.log(new CustomError('world')) // error.message => 'Hello world'
```
How to add cause:
```js
const createError = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello %s')
console.log(new CustomError('world', {cause: new Error('cause')}))
// error.message => 'Hello world'
// error.cause => Error('cause')
```
### TypeScript
It is possible to limit your error constructor with a generic type using TypeScript:
```ts
const CustomError = createError<[string]>('ERROR_CODE', 'Hello %s')
new CustomError('world')
//@ts-expect-error
new CustomError(1)
```
### instanceof
All errors created with `createError` will be instances of the base error constructor you provided, or `Error` if none was provided.
```js
const createError = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
const customError = new CustomError('world')
console.log(customError instanceof CustomError) // true
console.log(customError instanceof TypeError) // true
console.log(customError instanceof Error) // true
```
All instantiated errors are instances of the `FastifyError` class, which can be required directly from the module.
```js
const { createError, FastifyError } = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
const customError = new CustomError('world')
console.log(customError instanceof FastifyError) // true
```
A `FastifyError` created by `createError` can extend another `FastifyError` while maintaining correct `instanceof` behavior.
```js
const { createError, FastifyError } = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
const ChildCustomError = createError('CHILD_ERROR_CODE', 'Hello %s', 500, CustomError)
const customError = new ChildCustomError('world')
console.log(customError instanceof ChildCustomError) // true
console.log(customError instanceof CustomError) // true
console.log(customError instanceof FastifyError) // true
console.log(customError instanceof TypeError) // true
console.log(customError instanceof Error) // true
```
If `fastify-error` is installed multiple times directly or as a transitive dependency, `instanceof` checks for errors created by `createError` will still work correctly across these installations, as long as their error codes (e.g., `FST_ERR_CUSTOM_ERROR`) are identical.
```js
const { createError, FastifyError } = require('@fastify/error')
// CustomError from `@fastify/some-plugin` is created with `createError` and
// has its own `@fastify/error` installation as dependency. CustomError has
// FST_ERR_CUSTOM_ERROR as code.
const { CustomError: CustomErrorFromPlugin } = require('@fastify/some-plugin')
const CustomError = createError('FST_ERR_CUSTOM_ERROR', 'Hello %s', 500)
const customError = new CustomError('world')
const customErrorFromPlugin = new CustomErrorFromPlugin('world')
console.log(customError instanceof CustomError) // true
console.log(customError instanceof CustomErrorFromPlugin) // true
console.log(customErrorFromPlugin instanceof CustomError) // true
console.log(customErrorFromPlugin instanceof CustomErrorFromPlugin) // true
```
Changing the code of an instantiated Error will not change the result of the `instanceof` operator.
```js
const { createError, FastifyError } = require('@fastify/error')
const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
const AnotherCustomError = createError('ANOTHER_ERROR_CODE', 'Hello %s', 500, CustomError)
const customError = new CustomError('world')
customError.code = 'ANOTHER_ERROR_CODE'
console.log(customError instanceof CustomError) // true
console.log(customError instanceof AnotherCustomError) // false
```
## License
Licensed under [MIT](./LICENSE).

9
node_modules/@fastify/error/benchmarks/create.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
'use strict'
const benchmark = require('benchmark')
const createError = require('..')
new benchmark.Suite()
.add('create FastifyError', function () { createError('CODE', 'Not available') }, { minSamples: 100 })
.on('cycle', function onCycle (event) { console.log(String(event.target)) })
.run({ async: false })

18
node_modules/@fastify/error/benchmarks/instantiate.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
'use strict'
const benchmark = require('benchmark')
const createError = require('..')
const FastifyError = createError('CODE', 'Not available')
const FastifyError1 = createError('CODE', 'Not %s available')
const FastifyError2 = createError('CODE', 'Not %s available %s')
const cause = new Error('cause')
new benchmark.Suite()
.add('instantiate Error', function () { new Error() }, { minSamples: 100 }) // eslint-disable-line no-new
.add('instantiate FastifyError', function () { new FastifyError() }, { minSamples: 100 }) // eslint-disable-line no-new
.add('instantiate FastifyError arg 1', function () { new FastifyError1('q') }, { minSamples: 100 }) // eslint-disable-line no-new
.add('instantiate FastifyError arg 2', function () { new FastifyError2('qq', 'ss') }, { minSamples: 100 }) // eslint-disable-line no-new
.add('instantiate FastifyError cause', function () { new FastifyError2({ cause }) }, { minSamples: 100 }) // eslint-disable-line no-new
.on('cycle', function onCycle (event) { console.log(String(event.target)) })
.run({ async: false })

13
node_modules/@fastify/error/benchmarks/no-stack.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
'use strict'
const benchmark = require('benchmark')
const createError = require('..')
const FastifyError = createError('CODE', 'Not available')
Error.stackTraceLimit = 0
new benchmark.Suite()
.add('no-stack instantiate Error', function () { new Error() }, { minSamples: 100 }) // eslint-disable-line no-new
.add('no-stack instantiate FastifyError', function () { new FastifyError() }, { minSamples: 100 }) // eslint-disable-line no-new
.on('cycle', function onCycle (event) { console.log(String(event.target)) })
.run({ async: false })

11
node_modules/@fastify/error/benchmarks/toString.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
'use strict'
const benchmark = require('benchmark')
const createError = require('..')
const FastifyError = createError('CODE', 'Not available')
new benchmark.Suite()
.add('FastifyError toString', function () { new FastifyError().toString() }, { minSamples: 100 })
.on('cycle', function onCycle (event) { console.log(String(event.target)) })
.run({ async: false })

6
node_modules/@fastify/error/eslint.config.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
'use strict'
module.exports = require('neostandard')({
ignores: require('neostandard').resolveIgnoresFromGitignore(),
ts: true
})

100
node_modules/@fastify/error/index.js generated vendored Normal file
View File

@@ -0,0 +1,100 @@
'use strict'
const { format } = require('node:util')
function toString () {
return `${this.name} [${this.code}]: ${this.message}`
}
const FastifyGenericErrorSymbol = Symbol.for('fastify-error-generic')
function createError (code, message, statusCode = 500, Base = Error, captureStackTrace = createError.captureStackTrace) {
const shouldCreateFastifyGenericError = code === FastifyGenericErrorSymbol
if (shouldCreateFastifyGenericError) {
code = 'FST_ERR'
}
if (!code) throw new Error('Fastify error code must not be empty')
if (!message) throw new Error('Fastify error message must not be empty')
code = code.toUpperCase()
!statusCode && (statusCode = undefined)
const FastifySpecificErrorSymbol = Symbol.for(`fastify-error ${code}`)
function FastifyError (...args) {
if (!new.target) {
return new FastifyError(...args)
}
this.code = code
this.name = 'FastifyError'
this.statusCode = statusCode
const lastElement = args.length - 1
if (lastElement !== -1 && args[lastElement] && typeof args[lastElement] === 'object' && 'cause' in args[lastElement]) {
this.cause = args.pop().cause
}
this.message = format(message, ...args)
Error.stackTraceLimit && captureStackTrace && Error.captureStackTrace(this, FastifyError)
}
FastifyError.prototype = Object.create(Base.prototype, {
constructor: {
value: FastifyError,
enumerable: false,
writable: true,
configurable: true
},
[FastifyGenericErrorSymbol]: {
value: true,
enumerable: false,
writable: false,
configurable: false
},
[FastifySpecificErrorSymbol]: {
value: true,
enumerable: false,
writable: false,
configurable: false
}
})
if (shouldCreateFastifyGenericError) {
Object.defineProperty(FastifyError, Symbol.hasInstance, {
value (instance) {
return instance && instance[FastifyGenericErrorSymbol]
},
configurable: false,
writable: false,
enumerable: false
})
} else {
Object.defineProperty(FastifyError, Symbol.hasInstance, {
value (instance) {
return instance && instance[FastifySpecificErrorSymbol]
},
configurable: false,
writable: false,
enumerable: false
})
}
FastifyError.prototype[Symbol.toStringTag] = 'Error'
FastifyError.prototype.toString = toString
return FastifyError
}
createError.captureStackTrace = true
const FastifyErrorConstructor = createError(FastifyGenericErrorSymbol, 'Fastify Error', 500, Error)
module.exports = createError
module.exports.FastifyError = FastifyErrorConstructor
module.exports.default = createError
module.exports.createError = createError

75
node_modules/@fastify/error/package.json generated vendored Normal file
View File

@@ -0,0 +1,75 @@
{
"name": "@fastify/error",
"version": "4.2.0",
"description": "A small utility, used by Fastify itself, for generating consistent error objects across your codebase and plugins.",
"main": "index.js",
"type": "commonjs",
"types": "types/index.d.ts",
"scripts": {
"lint": "eslint",
"lint:fix": "eslint --fix",
"test": "npm run test:unit && npm run test:typescript",
"test:unit": "c8 --100 node --test",
"test:typescript": "tsd"
},
"repository": {
"type": "git",
"url": "git+https://github.com/fastify/fastify-error.git"
},
"keywords": [
"fastify",
"error",
"utility",
"plugin"
],
"author": "Tomas Della Vedova",
"contributors": [
{
"name": "Matteo Collina",
"email": "hello@matteocollina.com"
},
{
"name": "James Sumners",
"url": "https://james.sumners.info"
},
{
"name": "Aras Abbasi",
"email": "aras.abbasi@gmail.com"
},
{
"name": "Frazer Smith",
"email": "frazer.dev@icloud.com",
"url": "https://github.com/fdawgs"
}
],
"license": "MIT",
"bugs": {
"url": "https://github.com/fastify/fastify-error/issues"
},
"homepage": "https://github.com/fastify/fastify-error#readme",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"devDependencies": {
"benchmark": "^2.1.4",
"c8": "^10.1.2",
"eslint": "^9.17.0",
"neostandard": "^0.12.0",
"tsd": "^0.32.0"
},
"tsd": {
"compilerOptions": {
"esModuleInterop": true
}
},
"publishConfig": {
"access": "public"
}
}

232
node_modules/@fastify/error/test/index.test.js generated vendored Normal file
View File

@@ -0,0 +1,232 @@
'use strict'
const test = require('node:test')
const { createError, FastifyError } = require('..')
test('Create error with zero parameter', (t) => {
t.plan(6)
const NewError = createError('CODE', 'Not available')
const err = new NewError()
t.assert.ok(err instanceof Error)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.message, 'Not available')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.ok(err.stack)
})
test('Create error with 1 parameter', (t) => {
t.plan(6)
const NewError = createError('CODE', 'hey %s')
const err = new NewError('alice')
t.assert.equal(err.name, 'FastifyError')
t.assert.ok(err instanceof Error)
t.assert.equal(err.message, 'hey alice')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.ok(err.stack)
})
test('Create error with 1 parameter set to undefined', (t) => {
t.plan(1)
const NewError = createError('CODE', 'hey %s')
const err = new NewError(undefined)
t.assert.equal(err.message, 'hey undefined')
})
test('Create error with 2 parameters', (t) => {
t.plan(6)
const NewError = createError('CODE', 'hey %s, I like your %s')
const err = new NewError('alice', 'attitude')
t.assert.ok(err instanceof Error)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.message, 'hey alice, I like your attitude')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.ok(err.stack)
})
test('Create error with 2 parameters set to undefined', (t) => {
t.plan(1)
const NewError = createError('CODE', 'hey %s, I like your %s')
const err = new NewError(undefined, undefined)
t.assert.equal(err.message, 'hey undefined, I like your undefined')
})
test('Create error with 3 parameters', (t) => {
t.plan(6)
const NewError = createError('CODE', 'hey %s, I like your %s %s')
const err = new NewError('alice', 'attitude', 'see you')
t.assert.ok(err instanceof Error)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.message, 'hey alice, I like your attitude see you')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.ok(err.stack)
})
test('Create error with 3 parameters set to undefined', (t) => {
t.plan(4)
const NewError = createError('CODE', 'hey %s, I like your %s %s')
const err = new NewError(undefined, undefined, undefined)
t.assert.equal(err.message, 'hey undefined, I like your undefined undefined')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.ok(err.stack)
})
test('Create error with 4 parameters set to undefined', (t) => {
t.plan(4)
const NewError = createError('CODE', 'hey %s, I like your %s %s and %s')
const err = new NewError(undefined, undefined, undefined, undefined)
t.assert.equal(
err.message,
'hey undefined, I like your undefined undefined and undefined'
)
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.ok(err.stack)
})
test('Create error with no statusCode property', (t) => {
t.plan(6)
const NewError = createError('CODE', 'hey %s', 0)
const err = new NewError('dude')
t.assert.ok(err instanceof Error)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.message, 'hey dude')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, undefined)
t.assert.ok(err.stack)
})
test('Should throw when error code has no fastify code', (t) => {
t.plan(1)
t.assert.throws(
() => createError(),
new Error('Fastify error code must not be empty')
)
})
test('Should throw when error code has no message', (t) => {
t.assert.throws(
() => createError('code'),
new Error('Fastify error message must not be empty')
)
})
test('Create error with different base', (t) => {
t.plan(7)
const NewError = createError('CODE', 'hey %s', 500, TypeError)
const err = new NewError('dude')
t.assert.ok(err instanceof Error)
t.assert.ok(err instanceof TypeError)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.message, 'hey dude')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.ok(err.stack)
})
test('Create error with different base (no stack) (global)', (t) => {
t.plan(7)
createError.captureStackTrace = false
const NewError = createError('CODE', 'hey %s', 500, TypeError)
const err = new NewError('dude')
t.assert.ok(err instanceof Error)
t.assert.ok(err instanceof TypeError)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.message, 'hey dude')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.equal(err.stack, undefined)
createError.captureStackTrace = true
})
test('Create error with different base (no stack) (parameter)', (t) => {
t.plan(7)
const NewError = createError('CODE', 'hey %s', 500, TypeError, false)
const err = new NewError('dude')
t.assert.ok(err instanceof Error)
t.assert.ok(err instanceof TypeError)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.message, 'hey dude')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.equal(err.stack, undefined)
})
test('FastifyError.toString returns code', (t) => {
t.plan(1)
const NewError = createError('CODE', 'foo')
const err = new NewError()
t.assert.equal(err.toString(), 'FastifyError [CODE]: foo')
})
test('Create the error without the new keyword', (t) => {
t.plan(6)
const NewError = createError('CODE', 'Not available')
const err = NewError()
t.assert.ok(err instanceof Error)
t.assert.equal(err.name, 'FastifyError')
t.assert.equal(err.message, 'Not available')
t.assert.equal(err.code, 'CODE')
t.assert.equal(err.statusCode, 500)
t.assert.ok(err.stack)
})
test('Create an error with cause', (t) => {
t.plan(2)
const cause = new Error('HEY')
const NewError = createError('CODE', 'Not available')
const err = NewError({ cause })
t.assert.ok(err instanceof Error)
t.assert.equal(err.cause, cause)
})
test('Create an error with cause and message', (t) => {
t.plan(2)
const cause = new Error('HEY')
const NewError = createError('CODE', 'Not available: %s')
const err = NewError('foo', { cause })
t.assert.ok(err instanceof Error)
t.assert.equal(err.cause, cause)
})
test('Create an error with last argument null', (t) => {
t.plan(2)
const cause = new Error('HEY')
const NewError = createError('CODE', 'Not available')
const err = NewError({ cause }, null)
t.assert.ok(err instanceof Error)
t.assert.ifError(err.cause)
})
test('check if FastifyError is instantiable', (t) => {
t.plan(2)
const err = new FastifyError()
t.assert.ok(err instanceof FastifyError)
t.assert.ok(err instanceof Error)
})

263
node_modules/@fastify/error/test/instanceof.test.js generated vendored Normal file
View File

@@ -0,0 +1,263 @@
'use strict'
const cp = require('node:child_process')
const fs = require('node:fs')
const path = require('node:path')
const os = require('node:os')
const test = require('node:test')
const { createError, FastifyError } = require('..')
test('Readme: All errors created with `createError` will be instances of the base error constructor you provided, or `Error` if none was provided.', (t) => {
t.plan(3)
const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
const customError = new CustomError('world')
t.assert.ok(customError instanceof CustomError)
t.assert.ok(customError instanceof TypeError)
t.assert.ok(customError instanceof Error)
})
test('Readme: All instantiated errors will be instances of the `FastifyError` class. The `FastifyError` class can be required from the module directly.', (t) => {
t.plan(1)
const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
const customError = new CustomError('world')
t.assert.ok(customError instanceof FastifyError)
})
test('Readme: It is possible to create a `FastifyError` that extends another `FastifyError`, created by `createError`, while instanceof working correctly.', (t) => {
t.plan(5)
const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
const ChildCustomError = createError('CHILD_ERROR_CODE', 'Hello %s', 500, CustomError)
const customError = new ChildCustomError('world')
t.assert.ok(customError instanceof ChildCustomError)
t.assert.ok(customError instanceof CustomError)
t.assert.ok(customError instanceof FastifyError)
t.assert.ok(customError instanceof TypeError)
t.assert.ok(customError instanceof Error)
})
test('Readme: Changing the code of an instantiated Error will not change the result of the `instanceof` operator.', (t) => {
t.plan(3)
const CustomError = createError('ERROR_CODE', 'Hello %s', 500, TypeError)
const AnotherCustomError = createError('ANOTHER_ERROR_CODE', 'Hello %s', 500, CustomError)
const customError = new CustomError('world')
customError.code = 'ANOTHER_ERROR_CODE'
t.assert.ok(customError instanceof CustomError)
t.assert.ok(customError instanceof AnotherCustomError === false)
t.assert.ok(customError instanceof FastifyError)
})
test('check if createError creates an Error which is instanceof Error', (t) => {
t.plan(3)
const CustomFastifyError = createError('CODE', 'Not available')
const err = CustomFastifyError()
t.assert.ok(err instanceof Error)
t.assert.ok(err instanceof SyntaxError === false)
t.assert.ok(err instanceof TypeError === false)
})
test('check if createError creates an Error which is instanceof FastifyError', (t) => {
t.plan(4)
const CustomFastifyError = createError('CODE', 'Not available')
const err = CustomFastifyError()
t.assert.ok(err instanceof Error)
t.assert.ok(err instanceof FastifyError)
t.assert.ok(err instanceof SyntaxError === false)
t.assert.ok(err instanceof TypeError === false)
})
test('check if createError creates an Error with the right BaseConstructor', (t) => {
t.plan(2)
const CustomFastifyError = createError('CODE', 'Not available', 500, TypeError)
const err = CustomFastifyError()
t.assert.ok(err instanceof Error)
t.assert.ok(err instanceof TypeError)
})
test('check if createError creates an Error with the right BaseConstructor, which is a FastifyError', (t) => {
t.plan(6)
const BaseFastifyError = createError('CODE', 'Not available', 500, TypeError)
const CustomFastifyError = createError('CODE', 'Not available', 500, BaseFastifyError)
const err = CustomFastifyError()
t.assert.ok(err instanceof Error)
t.assert.ok(err instanceof TypeError)
t.assert.ok(err instanceof FastifyError)
t.assert.ok(err instanceof BaseFastifyError)
t.assert.ok(err instanceof CustomFastifyError)
t.assert.ok(err instanceof SyntaxError === false)
})
// for more information see https://github.com/fastify/fastify-error/pull/86#issuecomment-1301466407
test('ensure that instanceof works accross different installations of the fastify-error module', async (t) => {
const assertsPlanned = 5
t.plan(assertsPlanned)
// We need to create a test environment where fastify-error is installed in two different locations
// and then we will check if the error created in one location is instanceof the error created in the other location
// This is done by creating a test directory with the following structure:
// /
// ├── index.js
// └── node_modules/
// ├── fastify-error/
// │ └── index.js
// └── dep/
// ├── index.js
// └── node_modules/
// └── fastify-error/
// └── index.js
const testDirectoryPrefix = 'fastify-error-instanceof-test-'
const testCwd = path.resolve(os.tmpdir(), `${testDirectoryPrefix}${Math.random().toString(36).substring(2, 15)}`)
fs.mkdirSync(testCwd, { recursive: true })
// Create the index.js. It will be executed as a forked process, so we need to
// use process.send to send messages back to the parent process.
fs.writeFileSync(path.resolve(testCwd, 'index.js'), `
'use strict'
const path = require('node:path')
const { createError, FastifyError } = require('fastify-error')
const { foo } = require('dep')
const actualPathOfFastifyError = require.resolve('fastify-error')
const expectedPathOfFastifyError = path.resolve('node_modules', 'fastify-error', 'index.js')
// Ensure that fastify-error is required from the node_modules directory of the test-project
if (actualPathOfFastifyError !== expectedPathOfFastifyError) {
console.error('actualPathOfFastifyError', actualPathOfFastifyError)
console.error('expectedPathOfFastifyError', expectedPathOfFastifyError)
throw new Error('fastify-error should be required from the node_modules directory of the test-project')
}
const Boom = createError('Boom', 'Boom', 500)
const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom)
const NotChildBoom = createError('NotChildBoom', 'NotChildBoom', 500, Boom)
try {
foo()
} catch (err) {
process.send(err instanceof Error)
process.send(err instanceof FastifyError)
process.send(err instanceof NotChildBoom)
process.send(err instanceof Boom)
process.send(err instanceof ChildBoom)
}
`)
// Create /node_modules/fastify-error directory
// Copy the index.js file to the fastify-error directory
fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'fastify-error'), { recursive: true })
fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'fastify-error', 'index.js'))
// Create /node_modules/dep/node_modules/fastify-error directory
// Copy the index.js to the fastify-error directory
fs.mkdirSync(path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error'), { recursive: true })
fs.copyFileSync(path.resolve(process.cwd(), 'index.js'), path.resolve(testCwd, 'node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js'))
// Create /node_modules/dep/index.js. It will export a function foo which will
// throw an error when called. The error will be an instance of ChildBoom, created
// by the fastify-error module in the node_modules directory of dep.
fs.writeFileSync(path.resolve(testCwd, 'node_modules', 'dep', 'index.js'), `
'use strict'
const path = require('node:path')
const { createError } = require('fastify-error')
const actualPathOfFastifyError = require.resolve('fastify-error')
const expectedPathOfFastifyError = path.resolve('node_modules', 'dep', 'node_modules', 'fastify-error', 'index.js')
// Ensure that fastify-error is required from the node_modules directory of the test-project
if (actualPathOfFastifyError !== expectedPathOfFastifyError) {
console.error('actualPathOfFastifyError', actualPathOfFastifyError)
console.error('expectedPathOfFastifyError', expectedPathOfFastifyError)
throw new Error('fastify-error should be required from the node_modules directory of dep')
}
const Boom = createError('Boom', 'Boom', 500)
const ChildBoom = createError('ChildBoom', 'Boom', 500, Boom)
module.exports.foo = function foo () {
throw new ChildBoom('foo go Boom')
}
`)
const finishedPromise = {
promise: undefined,
reject: undefined,
resolve: undefined,
}
finishedPromise.promise = new Promise((resolve, reject) => {
finishedPromise.resolve = resolve
finishedPromise.reject = reject
})
const child = cp.fork(path.resolve(testCwd, 'index.js'), {
cwd: testCwd,
stdio: 'inherit',
env: {
...process.env,
NODE_OPTIONS: '--no-warnings'
},
})
let messageCount = 0
child.on('message', message => {
try {
switch (messageCount) {
case 0:
t.assert.strictEqual(message, true, 'instanceof Error')
break
case 1:
t.assert.strictEqual(message, true, 'instanceof FastifyError')
break
case 2:
t.assert.strictEqual(message, false, 'instanceof NotChildBoom')
break
case 3:
t.assert.strictEqual(message, true, 'instanceof Boom')
break
case 4:
t.assert.strictEqual(message, true, 'instanceof ChildBoom')
break
}
if (++messageCount === assertsPlanned) {
finishedPromise.resolve()
}
} catch (err) {
finishedPromise.reject(err)
}
})
child.on('error', err => {
finishedPromise.reject(err)
})
await finishedPromise.promise
// Cleanup
// As we are creating the test-setup on the fly in the /tmp directory, we can remove it
// safely when we are done. It is not relevant for the test if the deletion fails.
try {
fs.rmSync(testCwd, { recursive: true, force: true })
} catch {}
})

49
node_modules/@fastify/error/types/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,49 @@
declare function createError<C extends string, SC extends number, Arg extends unknown[] = [any?, any?, any?]> (
code: C,
message: string,
statusCode: SC,
Base?: ErrorConstructor,
captureStackTrace?: boolean
): createError.FastifyErrorConstructor<{ code: C, statusCode: SC }, Arg>
declare function createError<C extends string, Arg extends unknown[] = [any?, any?, any?]> (
code: C,
message: string,
statusCode?: number,
Base?: ErrorConstructor,
captureStackTrace?: boolean
): createError.FastifyErrorConstructor<{ code: C }, Arg>
declare function createError<Arg extends unknown[] = [any?, any?, any?]> (
code: string,
message: string,
statusCode?: number,
Base?: ErrorConstructor,
captureStackTrace?: boolean
): createError.FastifyErrorConstructor<{ code: string }, Arg>
type CreateError = typeof createError
declare namespace createError {
export interface FastifyError extends Error {
code: string
name: string
statusCode?: number
}
export interface FastifyErrorConstructor<
E extends { code: string, statusCode?: number } = { code: string, statusCode?: number },
T extends unknown[] = [any?, any?, any?]
> {
new(...arg: T): FastifyError & E
(...arg: T): FastifyError & E
readonly prototype: FastifyError & E
}
export const FastifyError: FastifyErrorConstructor
export const createError: CreateError
export { createError as default }
}
export = createError

92
node_modules/@fastify/error/types/index.test-d.ts generated vendored Normal file
View File

@@ -0,0 +1,92 @@
import createError, { FastifyError, FastifyErrorConstructor } from '..'
import { expectType, expectError } from 'tsd'
const CustomError = createError('ERROR_CODE', 'message')
expectType<FastifyErrorConstructor<{ code: 'ERROR_CODE' }>>(CustomError)
const err = new CustomError()
expectType<FastifyError & { code: 'ERROR_CODE' }>(err)
expectType<'ERROR_CODE'>(err.code)
expectType<string>(err.message)
expectType<number | undefined>(err.statusCode)
const CustomErrorNoStackTrace = createError('ERROR_CODE', 'message', undefined, undefined, false)
expectType<FastifyErrorConstructor<{ code: 'ERROR_CODE' }>>(CustomErrorNoStackTrace)
const errNoStackTrace = new CustomErrorNoStackTrace()
expectType<FastifyError & { code: 'ERROR_CODE' }>(errNoStackTrace)
expectType<'ERROR_CODE'>(errNoStackTrace.code)
expectType<string>(errNoStackTrace.message)
expectType<number | undefined>(errNoStackTrace.statusCode)
const CustomTypedError = createError('OTHER_CODE', 'message', 400)
expectType<FastifyErrorConstructor<{ code: 'OTHER_CODE', statusCode: 400 }>>(CustomTypedError)
const typed = new CustomTypedError()
expectType<FastifyError & { code: 'OTHER_CODE', statusCode: 400 }>(typed)
expectType<'OTHER_CODE'>(typed.code)
expectType<string>(typed.message)
expectType<400>(typed.statusCode)
/* eslint-disable no-new */
const CustomTypedArgError = createError<[string]>('OTHER_CODE', 'expect %s message', 400)
CustomTypedArgError('a')
expectError(CustomTypedArgError('a', 'b'))
expectError(new CustomTypedArgError('a', 'b'))
expectError(CustomTypedArgError(1))
expectError(new CustomTypedArgError(1))
const CustomTypedArgError2 = createError<string, number, [string]>('OTHER_CODE', 'expect %s message', 400)
CustomTypedArgError2('a')
expectError(CustomTypedArgError2('a', 'b'))
expectError(new CustomTypedArgError2('a', 'b'))
expectError(CustomTypedArgError2(1))
expectError(new CustomTypedArgError2(1))
const CustomTypedArgError3 = createError<string, number, [string, string]>('OTHER_CODE', 'expect %s message but got %s', 400)
expectError(CustomTypedArgError3('a'))
CustomTypedArgError3('a', 'b')
new CustomTypedArgError3('a', 'b')
expectError(CustomTypedArgError3(1))
expectError(new CustomTypedArgError3(1))
expectError(new CustomTypedArgError3(1, 2))
expectError(new CustomTypedArgError3('1', 2))
expectError(new CustomTypedArgError3(1, '2'))
const CustomTypedArgError4 = createError<string, number, [string, string]>('OTHER_CODE', 'expect %s message but got %s', 400)
expectError(CustomTypedArgError4('a'))
CustomTypedArgError4('a', 'b')
new CustomTypedArgError4('a', 'b')
expectError(CustomTypedArgError4(1))
expectError(new CustomTypedArgError4(1))
expectError(new CustomTypedArgError4(1, 2))
expectError(new CustomTypedArgError4('1', 2))
expectError(new CustomTypedArgError4(1, '2'))
const CustomTypedArgError5 = createError<[string, string, string, string]>('OTHER_CODE', 'expect %s message but got %s. Please contact %s by emailing to %s', 400)
expectError(CustomTypedArgError5('a'))
expectError(new CustomTypedArgError5('a', 'b'))
expectError(new CustomTypedArgError5('a', 'b', 'c'))
CustomTypedArgError5('a', 'b', 'c', 'd')
expectError(new CustomTypedArgError5('a', 'b', 'c', 'd', 'e'))
const CustomTypedArgError6 = createError<string, number, [string, string, string, string]>('OTHER_CODE', 'expect %s message but got %s. Please contact %s by emailing to %s', 400)
expectError(CustomTypedArgError6('a'))
expectError(new CustomTypedArgError6('a', 'b'))
expectError(new CustomTypedArgError6('a', 'b', 'c'))
CustomTypedArgError6('a', 'b', 'c', 'd')
expectError(new CustomTypedArgError6('a', 'b', 'c', 'd', 'e'))
const CustomErrorWithErrorConstructor = createError('ERROR_CODE', 'message', 500, TypeError)
expectType<FastifyErrorConstructor<{ code: 'ERROR_CODE', statusCode: 500 }>>(CustomErrorWithErrorConstructor)
CustomErrorWithErrorConstructor({ cause: new Error('Error') })
const customErrorWithErrorConstructor = CustomErrorWithErrorConstructor()
if (customErrorWithErrorConstructor instanceof FastifyError) {
expectType<'ERROR_CODE'>(customErrorWithErrorConstructor.code)
expectType<string>(customErrorWithErrorConstructor.message)
expectType<500>(customErrorWithErrorConstructor.statusCode)
}
const error = new FastifyError('ERROR_CODE', 'message', 500)
if (error instanceof FastifyError) {
expectType<string>(error.code)
expectType<string>(error.message)
expectType<number | undefined>(error.statusCode)
}