fastify 3.27.2 → 4.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/README.md +5 -4
  2. package/build/build-error-serializer.js +27 -0
  3. package/build/build-validation.js +47 -35
  4. package/docs/Migration-Guide-V4.md +12 -0
  5. package/docs/Reference/ContentTypeParser.md +4 -0
  6. package/docs/Reference/Errors.md +51 -6
  7. package/docs/Reference/Hooks.md +4 -7
  8. package/docs/Reference/LTS.md +5 -4
  9. package/docs/Reference/Reply.md +23 -22
  10. package/docs/Reference/Request.md +1 -3
  11. package/docs/Reference/Routes.md +17 -10
  12. package/docs/Reference/Server.md +48 -63
  13. package/docs/Reference/TypeScript.md +11 -13
  14. package/docs/Reference/Validation-and-Serialization.md +28 -53
  15. package/docs/Type-Providers.md +257 -0
  16. package/examples/hooks.js +1 -1
  17. package/examples/simple-stream.js +18 -0
  18. package/fastify.d.ts +34 -22
  19. package/fastify.js +37 -35
  20. package/lib/configValidator.js +902 -1023
  21. package/lib/contentTypeParser.js +6 -16
  22. package/lib/context.js +36 -10
  23. package/lib/decorate.js +3 -1
  24. package/lib/error-handler.js +158 -0
  25. package/lib/error-serializer.js +257 -0
  26. package/lib/errors.js +43 -9
  27. package/lib/fourOhFour.js +31 -20
  28. package/lib/handleRequest.js +10 -13
  29. package/lib/hooks.js +14 -9
  30. package/lib/pluginOverride.js +0 -3
  31. package/lib/pluginUtils.js +3 -2
  32. package/lib/reply.js +28 -157
  33. package/lib/request.js +13 -10
  34. package/lib/route.js +131 -138
  35. package/lib/schema-controller.js +2 -2
  36. package/lib/schemas.js +27 -1
  37. package/lib/server.js +219 -116
  38. package/lib/symbols.js +4 -3
  39. package/lib/validation.js +2 -1
  40. package/lib/warnings.js +2 -12
  41. package/lib/wrapThenable.js +4 -11
  42. package/package.json +31 -35
  43. package/test/404s.test.js +243 -110
  44. package/test/500s.test.js +2 -2
  45. package/test/async-await.test.js +13 -69
  46. package/test/content-parser.test.js +32 -0
  47. package/test/context-config.test.js +52 -0
  48. package/test/custom-http-server.test.js +14 -7
  49. package/test/custom-parser-async.test.js +0 -65
  50. package/test/custom-parser.test.js +54 -121
  51. package/test/decorator.test.js +1 -3
  52. package/test/delete.test.js +5 -5
  53. package/test/encapsulated-error-handler.test.js +50 -0
  54. package/test/esm/index.test.js +0 -14
  55. package/test/fastify-instance.test.js +4 -4
  56. package/test/fluent-schema.test.js +4 -4
  57. package/test/get.test.js +3 -3
  58. package/test/helper.js +18 -3
  59. package/test/hooks-async.test.js +14 -47
  60. package/test/hooks.on-ready.test.js +9 -4
  61. package/test/hooks.test.js +58 -99
  62. package/test/http2/closing.test.js +5 -11
  63. package/test/http2/unknown-http-method.test.js +3 -9
  64. package/test/https/custom-https-server.test.js +12 -6
  65. package/test/input-validation.js +2 -2
  66. package/test/internals/handleRequest.test.js +3 -40
  67. package/test/internals/initialConfig.test.js +33 -12
  68. package/test/internals/reply.test.js +245 -3
  69. package/test/internals/request.test.js +13 -7
  70. package/test/internals/server.test.js +88 -0
  71. package/test/listen.test.js +84 -1
  72. package/test/logger.test.js +80 -40
  73. package/test/maxRequestsPerSocket.test.js +6 -4
  74. package/test/middleware.test.js +2 -25
  75. package/test/nullable-validation.test.js +51 -14
  76. package/test/plugin.test.js +31 -5
  77. package/test/pretty-print.test.js +22 -10
  78. package/test/reply-error.test.js +123 -12
  79. package/test/request-error.test.js +2 -5
  80. package/test/route-hooks.test.js +17 -17
  81. package/test/route-prefix.test.js +2 -1
  82. package/test/route.test.js +204 -20
  83. package/test/router-options.test.js +1 -1
  84. package/test/schema-examples.test.js +11 -5
  85. package/test/schema-feature.test.js +24 -19
  86. package/test/schema-serialization.test.js +9 -9
  87. package/test/schema-special-usage.test.js +14 -81
  88. package/test/schema-validation.test.js +9 -9
  89. package/test/skip-reply-send.test.js +1 -1
  90. package/test/stream.test.js +23 -12
  91. package/test/throw.test.js +8 -5
  92. package/test/type-provider.test.js +20 -0
  93. package/test/types/fastify.test-d.ts +10 -18
  94. package/test/types/import.js +2 -0
  95. package/test/types/import.ts +1 -0
  96. package/test/types/instance.test-d.ts +35 -14
  97. package/test/types/logger.test-d.ts +44 -15
  98. package/test/types/route.test-d.ts +8 -2
  99. package/test/types/schema.test-d.ts +2 -39
  100. package/test/types/type-provider.test-d.ts +417 -0
  101. package/test/validation-error-handling.test.js +8 -8
  102. package/test/versioned-routes.test.js +28 -16
  103. package/test/wrapThenable.test.js +7 -6
  104. package/types/content-type-parser.d.ts +17 -8
  105. package/types/hooks.d.ts +102 -59
  106. package/types/instance.d.ts +124 -104
  107. package/types/logger.d.ts +18 -104
  108. package/types/plugin.d.ts +10 -4
  109. package/types/reply.d.ts +16 -11
  110. package/types/request.d.ts +10 -5
  111. package/types/route.d.ts +42 -31
  112. package/types/schema.d.ts +1 -1
  113. package/types/type-provider.d.ts +99 -0
  114. package/types/utils.d.ts +1 -1
  115. package/lib/schema-compilers.js +0 -12
  116. package/test/emit-warning.test.js +0 -166
package/fastify.d.ts CHANGED
@@ -5,18 +5,21 @@ import { ConstraintStrategy, HTTPVersion } from 'find-my-way'
5
5
 
6
6
  import { FastifyRequest, RequestGenericInterface } from './types/request'
7
7
  import { RawServerBase, RawServerDefault, RawRequestDefaultExpression, RawReplyDefaultExpression } from './types/utils'
8
- import { FastifyLoggerInstance, FastifyLoggerOptions } from './types/logger'
8
+ import { FastifyBaseLogger, FastifyLoggerInstance, FastifyLoggerOptions, PinoLoggerOptions } from './types/logger'
9
9
  import { FastifyInstance } from './types/instance'
10
10
  import { FastifyServerFactory } from './types/serverFactory'
11
11
  import { Options as AjvOptions } from '@fastify/ajv-compiler'
12
+ import { Options as FJSOptions } from '@fastify/fast-json-stringify-compiler'
12
13
  import { FastifyError } from 'fastify-error'
13
14
  import { FastifyReply } from './types/reply'
14
15
  import { FastifySchemaValidationError } from './types/schema'
15
16
  import { ConstructorAction, ProtoAction } from "./types/content-type-parser";
16
17
  import { Socket } from 'net'
17
- import { Options as FJSOptions } from 'fast-json-stringify'
18
18
  import { ValidatorCompiler } from '@fastify/ajv-compiler'
19
- import { FastifySerializerCompiler } from './types/schema';
19
+ import { SerializerCompiler } from '@fastify/fast-json-stringify-compiler'
20
+ import { FastifySchema } from './types/schema'
21
+ import { FastifyContextConfig } from './types/context'
22
+ import { FastifyTypeProvider, FastifyTypeProviderDefault } from './types/type-provider'
20
23
 
21
24
  /**
22
25
  * Fastify factory function for the standard fastify http, https, or http2 server instance.
@@ -30,31 +33,39 @@ declare function fastify<
30
33
  Server extends http2.Http2SecureServer,
31
34
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
32
35
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
33
- Logger extends FastifyLoggerInstance = FastifyLoggerInstance
34
- >(opts: FastifyHttp2SecureOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger>>
36
+ Logger extends FastifyBaseLogger = FastifyLoggerInstance,
37
+ TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
38
+ >(opts: FastifyHttp2SecureOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
39
+
35
40
  declare function fastify<
36
41
  Server extends http2.Http2Server,
37
42
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
38
43
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
39
- Logger extends FastifyLoggerInstance = FastifyLoggerInstance
40
- >(opts: FastifyHttp2Options<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger>>
44
+ Logger extends FastifyBaseLogger = FastifyLoggerInstance,
45
+ TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
46
+ >(opts: FastifyHttp2Options<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
47
+
41
48
  declare function fastify<
42
49
  Server extends https.Server,
43
50
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
44
51
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
45
- Logger extends FastifyLoggerInstance = FastifyLoggerInstance
46
- >(opts: FastifyHttpsOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger>>
52
+ Logger extends FastifyBaseLogger = FastifyLoggerInstance,
53
+ TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
54
+ >(opts: FastifyHttpsOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
55
+
47
56
  declare function fastify<
48
57
  Server extends http.Server,
49
58
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
50
59
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
51
- Logger extends FastifyLoggerInstance = FastifyLoggerInstance
52
- >(opts?: FastifyServerOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger>>
60
+ Logger extends FastifyBaseLogger = FastifyLoggerInstance,
61
+ TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
62
+ >(opts?: FastifyServerOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
63
+
53
64
  export default fastify
54
65
 
55
66
  export type FastifyHttp2SecureOptions<
56
67
  Server extends http2.Http2SecureServer,
57
- Logger extends FastifyLoggerInstance = FastifyLoggerInstance
68
+ Logger extends FastifyBaseLogger = FastifyLoggerInstance
58
69
  > = FastifyServerOptions<Server, Logger> & {
59
70
  http2: true,
60
71
  https: http2.SecureServerOptions,
@@ -63,7 +74,7 @@ export type FastifyHttp2SecureOptions<
63
74
 
64
75
  export type FastifyHttp2Options<
65
76
  Server extends http2.Http2Server,
66
- Logger extends FastifyLoggerInstance = FastifyLoggerInstance
77
+ Logger extends FastifyBaseLogger = FastifyLoggerInstance
67
78
  > = FastifyServerOptions<Server, Logger> & {
68
79
  http2: true,
69
80
  http2SessionTimeout?: number
@@ -71,7 +82,7 @@ export type FastifyHttp2Options<
71
82
 
72
83
  export type FastifyHttpsOptions<
73
84
  Server extends https.Server,
74
- Logger extends FastifyLoggerInstance = FastifyLoggerInstance
85
+ Logger extends FastifyBaseLogger = FastifyLoggerInstance
75
86
  > = FastifyServerOptions<Server, Logger> & {
76
87
  https: https.ServerOptions
77
88
  }
@@ -92,7 +103,7 @@ export interface ConnectionError extends Error {
92
103
  */
93
104
  export type FastifyServerOptions<
94
105
  RawServer extends RawServerBase = RawServerDefault,
95
- Logger extends FastifyLoggerInstance = FastifyLoggerInstance
106
+ Logger extends FastifyBaseLogger = FastifyLoggerInstance
96
107
  > = {
97
108
  ignoreTrailingSlash?: boolean,
98
109
  connectionTimeout?: number,
@@ -107,14 +118,14 @@ export type FastifyServerOptions<
107
118
  exposeHeadRoutes?: boolean,
108
119
  onProtoPoisoning?: ProtoAction,
109
120
  onConstructorPoisoning?: ConstructorAction,
110
- logger?: boolean | FastifyLoggerOptions<RawServer> | Logger,
121
+ logger?: boolean | FastifyLoggerOptions<RawServer> & PinoLoggerOptions | Logger,
111
122
  serializerOpts?: FJSOptions | Record<string, unknown>,
112
123
  serverFactory?: FastifyServerFactory<RawServer>,
113
124
  caseSensitive?: boolean,
114
125
  requestIdHeader?: string,
115
126
  requestIdLogLabel?: string;
116
127
  jsonShorthand?: boolean;
117
- genReqId?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface>(req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>>) => string,
128
+ genReqId?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault>(req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>) => string,
118
129
  trustProxy?: boolean | string | string[] | number | TrustProxyFunction,
119
130
  querystringParser?: (str: string) => { [key: string]: unknown },
120
131
  /**
@@ -140,7 +151,7 @@ export type FastifyServerOptions<
140
151
  };
141
152
  compilersFactory?: {
142
153
  buildValidator?: ValidatorCompiler;
143
- buildSerializer?: (externalSchemas: unknown, serializerOptsServerOption: FastifyServerOptions["serializerOpts"]) => FastifySerializerCompiler<unknown>;
154
+ buildSerializer?: SerializerCompiler;
144
155
  };
145
156
  };
146
157
  return503OnClosing?: boolean,
@@ -148,10 +159,10 @@ export type FastifyServerOptions<
148
159
  customOptions?: AjvOptions,
149
160
  plugins?: (Function | [Function, unknown])[]
150
161
  },
151
- frameworkErrors?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface>(
162
+ frameworkErrors?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema>(
152
163
  error: FastifyError,
153
- req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>>,
154
- res: FastifyReply<RawServer, RawRequestDefaultExpression<RawServer>, RawReplyDefaultExpression<RawServer>>
164
+ req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>,
165
+ res: FastifyReply<RawServer, RawRequestDefaultExpression<RawServer>, RawReplyDefaultExpression<RawServer>, RequestGeneric, FastifyContextConfig, SchemaCompiler, TypeProvider>
155
166
  ) => void,
156
167
  rewriteUrl?: (req: RawRequestDefaultExpression<RawServer>) => string,
157
168
  schemaErrorFormatter?: (errors: FastifySchemaValidationError[], dataVar: string) => Error,
@@ -183,7 +194,7 @@ export { FastifyRequest, RequestGenericInterface } from './types/request'
183
194
  export { FastifyReply } from './types/reply'
184
195
  export { FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin } from './types/plugin'
185
196
  export { FastifyInstance, PrintRoutesOptions } from './types/instance'
186
- export { FastifyLoggerOptions, FastifyLoggerInstance, FastifyLogFn, LogLevel } from './types/logger'
197
+ export { FastifyLoggerOptions, FastifyBaseLogger, FastifyLoggerInstance, FastifyLogFn, LogLevel } from './types/logger'
187
198
  export { FastifyContext, FastifyContextConfig } from './types/context'
188
199
  export { RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler } from './types/route'
189
200
  export * from './types/register'
@@ -193,4 +204,5 @@ export { FastifySchema, FastifySchemaCompiler } from './types/schema'
193
204
  export { HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault } from './types/utils'
194
205
  export * from './types/hooks'
195
206
  export { FastifyServerFactory, FastifyServerFactoryHandler } from './types/serverFactory'
207
+ export { FastifyTypeProvider, FastifyTypeProviderDefault } from './types/type-provider'
196
208
  export { fastify }
package/fastify.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict'
2
2
 
3
- const VERSION = '3.27.2'
3
+ const VERSION = '4.0.0-alpha.1'
4
4
 
5
5
  const Avvio = require('avvio')
6
6
  const http = require('http')
@@ -10,6 +10,7 @@ let lightMyRequest
10
10
  const {
11
11
  kAvvioBoot,
12
12
  kChildren,
13
+ kServerBindings,
13
14
  kBodyLimit,
14
15
  kRoutePrefix,
15
16
  kLogLevel,
@@ -31,7 +32,7 @@ const {
31
32
  kFourOhFourContext
32
33
  } = require('./lib/symbols.js')
33
34
 
34
- const { createServer } = require('./lib/server')
35
+ const createServer = require('./lib/server')
35
36
  const Reply = require('./lib/reply')
36
37
  const Request = require('./lib/request')
37
38
  const supportedMethods = ['DELETE', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'OPTIONS']
@@ -52,9 +53,12 @@ const { defaultInitOptions } = getSecuredInitialConfig
52
53
 
53
54
  const {
54
55
  FST_ERR_BAD_URL,
55
- FST_ERR_MISSING_MIDDLEWARE
56
+ AVVIO_ERRORS_MAP,
57
+ appendStackTrace
56
58
  } = require('./lib/errors')
57
59
 
60
+ const { buildErrorHandler } = require('./lib/error-handler.js')
61
+
58
62
  const onBadUrlContext = {
59
63
  config: {
60
64
  },
@@ -76,21 +80,6 @@ function defaultBuildPrettyMeta (route) {
76
80
  return Object.assign({}, cleanKeys)
77
81
  }
78
82
 
79
- function defaultErrorHandler (error, request, reply) {
80
- if (reply.statusCode < 500) {
81
- reply.log.info(
82
- { res: reply, err: error },
83
- error && error.message
84
- )
85
- } else {
86
- reply.log.error(
87
- { req: request, res: reply, err: error },
88
- error && error.message
89
- )
90
- }
91
- reply.send(error)
92
- }
93
-
94
83
  function fastify (options) {
95
84
  // Options validations
96
85
  options = options || {}
@@ -115,7 +104,6 @@ function fastify (options) {
115
104
  const requestIdLogLabel = options.requestIdLogLabel || 'reqId'
116
105
  const bodyLimit = options.bodyLimit || defaultInitOptions.bodyLimit
117
106
  const disableRequestLogging = options.disableRequestLogging || false
118
- const exposeHeadRoutes = options.exposeHeadRoutes != null ? options.exposeHeadRoutes : false
119
107
 
120
108
  const ajvOptions = Object.assign({
121
109
  customOptions: {},
@@ -148,11 +136,13 @@ function fastify (options) {
148
136
  options.disableRequestLogging = disableRequestLogging
149
137
  options.ajv = ajvOptions
150
138
  options.clientErrorHandler = options.clientErrorHandler || defaultClientErrorHandler
151
- options.exposeHeadRoutes = exposeHeadRoutes
152
139
 
153
140
  const initialConfig = getSecuredInitialConfig(options)
154
141
  const keepAliveConnections = options.forceCloseConnections === true ? new Set() : noopSet()
155
142
 
143
+ // exposeHeadRoutes have its defult set from the validatorfrom the validatorfrom the validatorfrom the validator
144
+ options.exposeHeadRoutes = initialConfig.exposeHeadRoutes
145
+
156
146
  let constraints = options.constraints
157
147
  if (options.versioning) {
158
148
  warning.emit('FSTDEP009')
@@ -210,6 +200,7 @@ function fastify (options) {
210
200
  [kKeepAliveConnections]: keepAliveConnections,
211
201
  [kOptions]: options,
212
202
  [kChildren]: [],
203
+ [kServerBindings]: [],
213
204
  [kBodyLimit]: bodyLimit,
214
205
  [kRoutePrefix]: '',
215
206
  [kLogLevel]: '',
@@ -217,7 +208,7 @@ function fastify (options) {
217
208
  [kHooks]: new Hooks(),
218
209
  [kSchemaController]: schemaController,
219
210
  [kSchemaErrorFormatter]: null,
220
- [kErrorHandler]: defaultErrorHandler,
211
+ [kErrorHandler]: buildErrorHandler(),
221
212
  [kReplySerializerDefault]: null,
222
213
  [kContentTypeParser]: new ContentTypeParser(
223
214
  bodyLimit,
@@ -267,6 +258,8 @@ function fastify (options) {
267
258
  },
268
259
  // expose logger instance
269
260
  log: logger,
261
+ // type provider
262
+ withTypeProvider,
270
263
  // hooks
271
264
  addHook,
272
265
  // schemas
@@ -295,6 +288,12 @@ function fastify (options) {
295
288
  // http server
296
289
  listen,
297
290
  server,
291
+ addresses: function () {
292
+ /* istanbul ignore next */
293
+ const binded = this[kServerBindings].map(b => b.address())
294
+ binded.push(this.server.address())
295
+ return binded.filter(adr => adr)
296
+ },
298
297
  // extend fastify objects
299
298
  decorate: decorator.add,
300
299
  hasDecorator: decorator.exist,
@@ -313,9 +312,6 @@ function fastify (options) {
313
312
  initialConfig
314
313
  }
315
314
 
316
- fastify[kReply].prototype.server = fastify
317
- fastify[kRequest].prototype.server = fastify
318
-
319
315
  Object.defineProperties(fastify, {
320
316
  pluginName: {
321
317
  get () {
@@ -339,16 +335,11 @@ function fastify (options) {
339
335
  },
340
336
  errorHandler: {
341
337
  get () {
342
- return this[kErrorHandler]
338
+ return this[kErrorHandler].func
343
339
  }
344
340
  }
345
341
  })
346
342
 
347
- // We are adding `use` to the fastify prototype so the user
348
- // can still access it (and get the expected error), but `decorate`
349
- // will not detect it, and allow the user to override it.
350
- Object.setPrototypeOf(fastify, { use })
351
-
352
343
  if (options.schemaErrorFormatter) {
353
344
  validateSchemaErrorFormatter(options.schemaErrorFormatter)
354
345
  fastify[kSchemaErrorFormatter] = options.schemaErrorFormatter.bind(fastify)
@@ -500,6 +491,13 @@ function fastify (options) {
500
491
  }
501
492
 
502
493
  function manageErr (err) {
494
+ // If the error comes out of Avvio's Error codes
495
+ // We create a make and preserve the previous error
496
+ // as cause
497
+ err = err != null && AVVIO_ERRORS_MAP[err.code] != null
498
+ ? appendStackTrace(err, new AVVIO_ERRORS_MAP[err.code](err.message))
499
+ : err
500
+
503
501
  if (cb) {
504
502
  if (err) {
505
503
  cb(err)
@@ -515,15 +513,16 @@ function fastify (options) {
515
513
  }
516
514
  }
517
515
 
518
- function use () {
519
- throw new FST_ERR_MISSING_MIDDLEWARE()
516
+ // Used exclusively in TypeScript contexts to enable auto type inference from JSON schema.
517
+ function withTypeProvider () {
518
+ return this
520
519
  }
521
520
 
522
521
  // wrapper that we expose to the user for hooks handling
523
522
  function addHook (name, fn) {
524
523
  throwIfAlreadyStarted('Cannot call "addHook" when fastify instance is already started!')
525
524
 
526
- if (name === 'onSend' || name === 'preSerialization' || name === 'onError') {
525
+ if (name === 'onSend' || name === 'preSerialization' || name === 'onError' || name === 'preParsing') {
527
526
  if (fn.constructor.name === 'AsyncFunction' && fn.length === 4) {
528
527
  throw new Error('Async function has too many arguments. Async hooks should not use the \'done\' argument.')
529
528
  }
@@ -531,7 +530,7 @@ function fastify (options) {
531
530
  if (fn.constructor.name === 'AsyncFunction' && fn.length !== 0) {
532
531
  throw new Error('Async function has too many arguments. Async hooks should not use the \'done\' argument.')
533
532
  }
534
- } else if (name !== 'preParsing') {
533
+ } else {
535
534
  if (fn.constructor.name === 'AsyncFunction' && fn.length === 3) {
536
535
  throw new Error('Async function has too many arguments. Async hooks should not use the \'done\' argument.')
537
536
  }
@@ -541,6 +540,9 @@ function fastify (options) {
541
540
  this.onClose(fn)
542
541
  } else if (name === 'onReady') {
543
542
  this[kHooks].add(name, fn)
543
+ } else if (name === 'onRoute') {
544
+ this[kHooks].validate(name, fn)
545
+ this[kHooks].add(name, fn)
544
546
  } else {
545
547
  this.after((err, done) => {
546
548
  _addHook.call(this, name, fn)
@@ -669,7 +671,7 @@ function fastify (options) {
669
671
  function setErrorHandler (func) {
670
672
  throwIfAlreadyStarted('Cannot call "setErrorHandler" when fastify instance is already started!')
671
673
 
672
- this[kErrorHandler] = func.bind(this)
674
+ this[kErrorHandler] = buildErrorHandler(this[kErrorHandler], func.bind(this))
673
675
  return this
674
676
  }
675
677