fastify 4.11.0 → 4.13.0

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.
package/fastify.d.ts CHANGED
@@ -1,26 +1,197 @@
1
1
  import * as http from 'http'
2
2
  import * as http2 from 'http2'
3
3
  import * as https from 'https'
4
- import { ConstraintStrategy, HTTPVersion } from 'find-my-way'
4
+ import { Socket } from 'net'
5
5
 
6
- import { FastifyRequest, RequestGenericInterface } from './types/request'
7
- import { RawServerBase, RawServerDefault, RawRequestDefaultExpression, RawReplyDefaultExpression } from './types/utils'
8
- import { FastifyBaseLogger, FastifyLoggerInstance, FastifyLoggerOptions, PinoLoggerOptions } from './types/logger'
9
- import { FastifyInstance } from './types/instance'
10
- import { FastifyServerFactory } from './types/serverFactory'
11
- import { Options as AjvOptions } from '@fastify/ajv-compiler'
12
- import { Options as FJSOptions } from '@fastify/fast-json-stringify-compiler'
6
+ import { Options as AjvOptions, ValidatorCompiler } from '@fastify/ajv-compiler'
13
7
  import { FastifyError } from '@fastify/error'
8
+ import { Options as FJSOptions, SerializerCompiler } from '@fastify/fast-json-stringify-compiler'
9
+ import { ConstraintStrategy, HTTPVersion } from 'find-my-way'
10
+ import { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, CallbackFunc as LightMyRequestCallback } from 'light-my-request'
11
+
12
+ import { FastifyBodyParser, FastifyContentTypeParser, AddContentTypeParser, hasContentTypeParser, getDefaultJsonParser, ProtoAction, ConstructorAction } from './types/content-type-parser'
13
+ import { FastifyContext, FastifyContextConfig } from './types/context'
14
+ import { FastifyErrorCodes } from './types/errors'
15
+ import { DoneFuncWithErrOrRes, HookHandlerDoneFunction, RequestPayload, onCloseAsyncHookHandler, onCloseHookHandler, onErrorAsyncHookHandler, onErrorHookHandler, onReadyAsyncHookHandler, onReadyHookHandler, onRegisterHookHandler, onRequestAsyncHookHandler, onRequestHookHandler, onResponseAsyncHookHandler, onResponseHookHandler, onRouteHookHandler, onSendAsyncHookHandler, onSendHookHandler, onTimeoutAsyncHookHandler, onTimeoutHookHandler, preHandlerAsyncHookHandler, preHandlerHookHandler, preParsingAsyncHookHandler, preParsingHookHandler, preSerializationAsyncHookHandler, preSerializationHookHandler, preValidationAsyncHookHandler, preValidationHookHandler } from './types/hooks'
16
+ import { FastifyListenOptions, FastifyInstance, PrintRoutesOptions } from './types/instance'
17
+ import { FastifyBaseLogger, FastifyLoggerInstance, FastifyLoggerOptions, PinoLoggerOptions, FastifyLogFn, LogLevel } from './types/logger'
18
+ import { FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin } from './types/plugin'
19
+ import { FastifyRegister, FastifyRegisterOptions, RegisterOptions } from './types/register'
14
20
  import { FastifyReply } from './types/reply'
15
- import { FastifySchemaValidationError } from './types/schema'
16
- import { ConstructorAction, ProtoAction } from "./types/content-type-parser";
17
- import { Socket } from 'net'
18
- import { ValidatorCompiler } from '@fastify/ajv-compiler'
19
- import { SerializerCompiler } from '@fastify/fast-json-stringify-compiler'
20
- import { FastifySchema } from './types/schema'
21
- import { FastifyContextConfig } from './types/context'
21
+ import { FastifyRequest, RequestGenericInterface } from './types/request'
22
+ import { RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler, RouteGenericInterface } from './types/route'
23
+ import { FastifySchema, FastifySchemaCompiler, FastifySchemaValidationError } from './types/schema'
24
+ import { FastifyServerFactory, FastifyServerFactoryHandler } from './types/serverFactory'
22
25
  import { FastifyTypeProvider, FastifyTypeProviderDefault } from './types/type-provider'
23
- import { FastifyErrorCodes } from './types/errors'
26
+ import { HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault } from './types/utils'
27
+
28
+ declare module '@fastify/error' {
29
+ interface FastifyError {
30
+ validation?: fastify.ValidationResult[];
31
+ validationContext?: 'body' | 'headers' | 'parameters' | 'querystring';
32
+ }
33
+ }
34
+
35
+ type Fastify = typeof fastify
36
+
37
+ declare namespace fastify {
38
+ export const errorCodes: FastifyErrorCodes;
39
+
40
+ export type FastifyHttp2SecureOptions<
41
+ Server extends http2.Http2SecureServer,
42
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
43
+ > = FastifyServerOptions<Server, Logger> & {
44
+ http2: true,
45
+ https: http2.SecureServerOptions,
46
+ http2SessionTimeout?: number
47
+ }
48
+
49
+ export type FastifyHttp2Options<
50
+ Server extends http2.Http2Server,
51
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
52
+ > = FastifyServerOptions<Server, Logger> & {
53
+ http2: true,
54
+ http2SessionTimeout?: number
55
+ }
56
+
57
+ export type FastifyHttpsOptions<
58
+ Server extends https.Server,
59
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
60
+ > = FastifyServerOptions<Server, Logger> & {
61
+ https: https.ServerOptions | null
62
+ }
63
+
64
+ export type FastifyHttpOptions<
65
+ Server extends http.Server,
66
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
67
+ > = FastifyServerOptions<Server, Logger> & {
68
+ http?: http.ServerOptions | null
69
+ }
70
+
71
+ type FindMyWayVersion<RawServer extends RawServerBase> = RawServer extends http.Server ? HTTPVersion.V1 : HTTPVersion.V2
72
+
73
+ export interface ConnectionError extends Error {
74
+ code: string,
75
+ bytesParsed: number,
76
+ rawPacket: {
77
+ type: string,
78
+ data: number[]
79
+ }
80
+ }
81
+
82
+ type TrustProxyFunction = (address: string, hop: number) => boolean
83
+
84
+ /**
85
+ * Options for a fastify server instance. Utilizes conditional logic on the generic server parameter to enforce certain https and http2
86
+ */
87
+ export type FastifyServerOptions<
88
+ RawServer extends RawServerBase = RawServerDefault,
89
+ Logger extends FastifyBaseLogger = FastifyBaseLogger
90
+ > = {
91
+ ignoreTrailingSlash?: boolean,
92
+ ignoreDuplicateSlashes?: boolean,
93
+ connectionTimeout?: number,
94
+ keepAliveTimeout?: number,
95
+ maxRequestsPerSocket?: number,
96
+ forceCloseConnections?: boolean | 'idle',
97
+ requestTimeout?: number,
98
+ pluginTimeout?: number,
99
+ bodyLimit?: number,
100
+ maxParamLength?: number,
101
+ disableRequestLogging?: boolean,
102
+ exposeHeadRoutes?: boolean,
103
+ onProtoPoisoning?: ProtoAction,
104
+ onConstructorPoisoning?: ConstructorAction,
105
+ logger?: boolean | FastifyLoggerOptions<RawServer> & PinoLoggerOptions | Logger,
106
+ serializerOpts?: FJSOptions | Record<string, unknown>,
107
+ serverFactory?: FastifyServerFactory<RawServer>,
108
+ caseSensitive?: boolean,
109
+ requestIdHeader?: string | false,
110
+ requestIdLogLabel?: string;
111
+ jsonShorthand?: boolean;
112
+ genReqId?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault>(req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>) => string,
113
+ trustProxy?: boolean | string | string[] | number | TrustProxyFunction,
114
+ querystringParser?: (str: string) => { [key: string]: unknown },
115
+ /**
116
+ * @deprecated Prefer using the `constraints.version` property
117
+ */
118
+ versioning?: {
119
+ storage(): {
120
+ get(version: string): string | null,
121
+ set(version: string, store: Function): void
122
+ del(version: string): void,
123
+ empty(): void
124
+ },
125
+ deriveVersion<Context>(req: Object, ctx?: Context): string // not a fan of using Object here. Also what is Context? Can either of these be better defined?
126
+ },
127
+ constraints?: {
128
+ [name: string]: ConstraintStrategy<FindMyWayVersion<RawServer>, unknown>,
129
+ },
130
+ schemaController?: {
131
+ bucket?: (parentSchemas?: unknown) => {
132
+ add(schema: unknown): FastifyInstance;
133
+ getSchema(schemaId: string): unknown;
134
+ getSchemas(): Record<string, unknown>;
135
+ };
136
+ compilersFactory?: {
137
+ buildValidator?: ValidatorCompiler;
138
+ buildSerializer?: SerializerCompiler;
139
+ };
140
+ };
141
+ return503OnClosing?: boolean,
142
+ ajv?: {
143
+ customOptions?: AjvOptions,
144
+ plugins?: (Function | [Function, unknown])[]
145
+ },
146
+ frameworkErrors?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema>(
147
+ error: FastifyError,
148
+ req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>,
149
+ res: FastifyReply<RawServer, RawRequestDefaultExpression<RawServer>, RawReplyDefaultExpression<RawServer>, RequestGeneric, FastifyContextConfig, SchemaCompiler, TypeProvider>
150
+ ) => void,
151
+ rewriteUrl?: (req: RawRequestDefaultExpression<RawServer>) => string,
152
+ schemaErrorFormatter?: (errors: FastifySchemaValidationError[], dataVar: string) => Error,
153
+ /**
154
+ * listener to error events emitted by client connections
155
+ */
156
+ clientErrorHandler?: (error: ConnectionError, socket: Socket) => void
157
+ }
158
+
159
+ export interface ValidationResult {
160
+ keyword: string;
161
+ instancePath: string;
162
+ schemaPath: string;
163
+ params: Record<string, string | string[]>;
164
+ message?: string;
165
+ }
166
+
167
+ /* Export additional types */
168
+ export type {
169
+ LightMyRequestChain, InjectOptions, LightMyRequestResponse, LightMyRequestCallback, // 'light-my-request'
170
+ FastifyRequest, RequestGenericInterface, // './types/request'
171
+ FastifyReply, // './types/reply'
172
+ FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin, // './types/plugin'
173
+ FastifyListenOptions, FastifyInstance, PrintRoutesOptions, // './types/instance'
174
+ FastifyLoggerOptions, FastifyBaseLogger, FastifyLoggerInstance, FastifyLogFn, LogLevel, // './types/logger'
175
+ FastifyContext, FastifyContextConfig, // './types/context'
176
+ RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler, RouteGenericInterface, // './types/route'
177
+ FastifyRegister, FastifyRegisterOptions, RegisterOptions, // './types/register'
178
+ FastifyBodyParser, FastifyContentTypeParser, AddContentTypeParser, hasContentTypeParser, getDefaultJsonParser, ProtoAction, ConstructorAction, // './types/content-type-parser'
179
+ FastifyError, // '@fastify/error'
180
+ FastifySchema, FastifySchemaCompiler, // './types/schema'
181
+ HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault, // './types/utils'
182
+ DoneFuncWithErrOrRes, HookHandlerDoneFunction, RequestPayload, onCloseAsyncHookHandler, onCloseHookHandler, onErrorAsyncHookHandler, onErrorHookHandler, onReadyAsyncHookHandler, onReadyHookHandler, onRegisterHookHandler, onRequestAsyncHookHandler, onRequestHookHandler, onResponseAsyncHookHandler, onResponseHookHandler, onRouteHookHandler, onSendAsyncHookHandler, onSendHookHandler, onTimeoutAsyncHookHandler, onTimeoutHookHandler, preHandlerAsyncHookHandler, preHandlerHookHandler, preParsingAsyncHookHandler, preParsingHookHandler, preSerializationAsyncHookHandler, preSerializationHookHandler, preValidationAsyncHookHandler, preValidationHookHandler, // './types/hooks'
183
+ FastifyServerFactory, FastifyServerFactoryHandler, // './types/serverFactory'
184
+ FastifyTypeProvider, FastifyTypeProviderDefault, // './types/type-provider'
185
+ FastifyErrorCodes, // './types/errors'
186
+ }
187
+ // named export
188
+ // import { plugin } from 'plugin'
189
+ // const { plugin } = require('plugin')
190
+ export const fastify: Fastify
191
+ // default export
192
+ // import plugin from 'plugin'
193
+ export { fastify as default }
194
+ }
24
195
 
25
196
  /**
26
197
  * Fastify factory function for the standard fastify http, https, or http2 server instance.
@@ -34,183 +205,34 @@ declare function fastify<
34
205
  Server extends http2.Http2SecureServer,
35
206
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
36
207
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
37
- Logger extends FastifyBaseLogger = FastifyLoggerInstance,
208
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
38
209
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
39
- >(opts: FastifyHttp2SecureOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
210
+ >(opts: fastify.FastifyHttp2SecureOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
40
211
 
41
212
  declare function fastify<
42
213
  Server extends http2.Http2Server,
43
214
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
44
215
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
45
- Logger extends FastifyBaseLogger = FastifyLoggerInstance,
216
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
46
217
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
47
- >(opts: FastifyHttp2Options<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
218
+ >(opts: fastify.FastifyHttp2Options<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
48
219
 
49
220
  declare function fastify<
50
221
  Server extends https.Server,
51
222
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
52
223
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
53
- Logger extends FastifyBaseLogger = FastifyLoggerInstance,
224
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
54
225
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
55
- >(opts: FastifyHttpsOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
226
+ >(opts: fastify.FastifyHttpsOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
56
227
 
57
228
  declare function fastify<
58
229
  Server extends http.Server,
59
230
  Request extends RawRequestDefaultExpression<Server> = RawRequestDefaultExpression<Server>,
60
231
  Reply extends RawReplyDefaultExpression<Server> = RawReplyDefaultExpression<Server>,
61
- Logger extends FastifyBaseLogger = FastifyLoggerInstance,
232
+ Logger extends FastifyBaseLogger = FastifyBaseLogger,
62
233
  TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault,
63
- >(opts?: FastifyServerOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
64
-
65
- declare namespace fastify {
66
- export const errorCodes: FastifyErrorCodes;
67
- }
68
-
69
- export default fastify
70
-
71
- export type FastifyHttp2SecureOptions<
72
- Server extends http2.Http2SecureServer,
73
- Logger extends FastifyBaseLogger = FastifyLoggerInstance
74
- > = FastifyServerOptions<Server, Logger> & {
75
- http2: true,
76
- https: http2.SecureServerOptions,
77
- http2SessionTimeout?: number
78
- }
79
-
80
- export type FastifyHttp2Options<
81
- Server extends http2.Http2Server,
82
- Logger extends FastifyBaseLogger = FastifyLoggerInstance
83
- > = FastifyServerOptions<Server, Logger> & {
84
- http2: true,
85
- http2SessionTimeout?: number
86
- }
87
-
88
- export type FastifyHttpsOptions<
89
- Server extends https.Server,
90
- Logger extends FastifyBaseLogger = FastifyLoggerInstance
91
- > = FastifyServerOptions<Server, Logger> & {
92
- https: https.ServerOptions | null
93
- }
94
-
95
- type FindMyWayVersion<RawServer extends RawServerBase> = RawServer extends http.Server ? HTTPVersion.V1 : HTTPVersion.V2
96
-
97
- export interface ConnectionError extends Error {
98
- code: string,
99
- bytesParsed: number,
100
- rawPacket: {
101
- type: string,
102
- data: number[]
103
- }
104
- }
105
-
106
- /**
107
- * Options for a fastify server instance. Utilizes conditional logic on the generic server parameter to enforce certain https and http2
108
- */
109
- export type FastifyServerOptions<
110
- RawServer extends RawServerBase = RawServerDefault,
111
- Logger extends FastifyBaseLogger = FastifyLoggerInstance
112
- > = {
113
- ignoreTrailingSlash?: boolean,
114
- ignoreDuplicateSlashes?: boolean,
115
- connectionTimeout?: number,
116
- keepAliveTimeout?: number,
117
- maxRequestsPerSocket?: number,
118
- forceCloseConnections?: boolean | 'idle',
119
- requestTimeout?: number,
120
- pluginTimeout?: number,
121
- bodyLimit?: number,
122
- maxParamLength?: number,
123
- disableRequestLogging?: boolean,
124
- exposeHeadRoutes?: boolean,
125
- onProtoPoisoning?: ProtoAction,
126
- onConstructorPoisoning?: ConstructorAction,
127
- logger?: boolean | FastifyLoggerOptions<RawServer> & PinoLoggerOptions | Logger,
128
- serializerOpts?: FJSOptions | Record<string, unknown>,
129
- serverFactory?: FastifyServerFactory<RawServer>,
130
- caseSensitive?: boolean,
131
- requestIdHeader?: string | false,
132
- requestIdLogLabel?: string;
133
- jsonShorthand?: boolean;
134
- genReqId?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault>(req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>) => string,
135
- trustProxy?: boolean | string | string[] | number | TrustProxyFunction,
136
- querystringParser?: (str: string) => { [key: string]: unknown },
137
- /**
138
- * @deprecated Prefer using the `constraints.version` property
139
- */
140
- versioning?: {
141
- storage(): {
142
- get(version: string): string | null,
143
- set(version: string, store: Function): void
144
- del(version: string): void,
145
- empty(): void
146
- },
147
- deriveVersion<Context>(req: Object, ctx?: Context): string // not a fan of using Object here. Also what is Context? Can either of these be better defined?
148
- },
149
- constraints?: {
150
- [name: string]: ConstraintStrategy<FindMyWayVersion<RawServer>, unknown>,
151
- },
152
- schemaController?: {
153
- bucket?: (parentSchemas?: unknown) => {
154
- add(schema: unknown): FastifyInstance;
155
- getSchema(schemaId: string): unknown;
156
- getSchemas(): Record<string, unknown>;
157
- };
158
- compilersFactory?: {
159
- buildValidator?: ValidatorCompiler;
160
- buildSerializer?: SerializerCompiler;
161
- };
162
- };
163
- return503OnClosing?: boolean,
164
- ajv?: {
165
- customOptions?: AjvOptions,
166
- plugins?: (Function | [Function, unknown])[]
167
- },
168
- frameworkErrors?: <RequestGeneric extends RequestGenericInterface = RequestGenericInterface, TypeProvider extends FastifyTypeProvider = FastifyTypeProviderDefault, SchemaCompiler extends FastifySchema = FastifySchema>(
169
- error: FastifyError,
170
- req: FastifyRequest<RequestGeneric, RawServer, RawRequestDefaultExpression<RawServer>, FastifySchema, TypeProvider>,
171
- res: FastifyReply<RawServer, RawRequestDefaultExpression<RawServer>, RawReplyDefaultExpression<RawServer>, RequestGeneric, FastifyContextConfig, SchemaCompiler, TypeProvider>
172
- ) => void,
173
- rewriteUrl?: (req: RawRequestDefaultExpression<RawServer>) => string,
174
- schemaErrorFormatter?: (errors: FastifySchemaValidationError[], dataVar: string) => Error,
175
- /**
176
- * listener to error events emitted by client connections
177
- */
178
- clientErrorHandler?: (error: ConnectionError, socket: Socket) => void
179
- }
180
-
181
- type TrustProxyFunction = (address: string, hop: number) => boolean
182
-
183
- declare module '@fastify/error' {
184
- interface FastifyError {
185
- validation?: ValidationResult[];
186
- validationContext?: 'body' | 'headers' | 'parameters' | 'querystring';
187
- }
188
- }
189
-
190
- export interface ValidationResult {
191
- keyword: string;
192
- instancePath: string;
193
- schemaPath: string;
194
- params: Record<string, string | string[]>;
195
- message?: string;
196
- }
234
+ >(opts?: fastify.FastifyHttpOptions<Server, Logger>): FastifyInstance<Server, Request, Reply, Logger, TypeProvider> & PromiseLike<FastifyInstance<Server, Request, Reply, Logger, TypeProvider>>
197
235
 
198
- /* Export all additional types */
199
- export type { Chain as LightMyRequestChain, InjectOptions, Response as LightMyRequestResponse, CallbackFunc as LightMyRequestCallback } from 'light-my-request'
200
- export { FastifyRequest, RequestGenericInterface } from './types/request'
201
- export { FastifyReply } from './types/reply'
202
- export { FastifyPluginCallback, FastifyPluginAsync, FastifyPluginOptions, FastifyPlugin } from './types/plugin'
203
- export { FastifyListenOptions, FastifyInstance, PrintRoutesOptions } from './types/instance'
204
- export { FastifyLoggerOptions, FastifyBaseLogger, FastifyLoggerInstance, FastifyLogFn, LogLevel } from './types/logger'
205
- export { FastifyContext, FastifyContextConfig } from './types/context'
206
- export { RouteHandler, RouteHandlerMethod, RouteOptions, RouteShorthandMethod, RouteShorthandOptions, RouteShorthandOptionsWithHandler, RouteGenericInterface } from './types/route'
207
- export * from './types/register'
208
- export { FastifyBodyParser, FastifyContentTypeParser, AddContentTypeParser, hasContentTypeParser, getDefaultJsonParser, ProtoAction, ConstructorAction } from './types/content-type-parser'
209
- export { FastifyError } from '@fastify/error'
210
- export { FastifySchema, FastifySchemaCompiler } from './types/schema'
211
- export { HTTPMethods, RawServerBase, RawRequestDefaultExpression, RawReplyDefaultExpression, RawServerDefault, ContextConfigDefault, RequestBodyDefault, RequestQuerystringDefault, RequestParamsDefault, RequestHeadersDefault } from './types/utils'
212
- export * from './types/hooks'
213
- export { FastifyServerFactory, FastifyServerFactoryHandler } from './types/serverFactory'
214
- export { FastifyTypeProvider, FastifyTypeProviderDefault } from './types/type-provider'
215
- export { FastifyErrorCodes } from './types/errors'
216
- export { fastify }
236
+ // CJS export
237
+ // const fastify = require('fastify')
238
+ export = fastify
package/fastify.js CHANGED
@@ -1,6 +1,6 @@
1
1
  'use strict'
2
2
 
3
- const VERSION = '4.11.0'
3
+ const VERSION = '4.13.0'
4
4
 
5
5
  const Avvio = require('avvio')
6
6
  const http = require('http')
@@ -59,7 +59,17 @@ const { defaultInitOptions } = getSecuredInitialConfig
59
59
  const {
60
60
  FST_ERR_ASYNC_CONSTRAINT,
61
61
  FST_ERR_BAD_URL,
62
- FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE
62
+ FST_ERR_FORCE_CLOSE_CONNECTIONS_IDLE_NOT_AVAILABLE,
63
+ FST_ERR_OPTIONS_NOT_OBJ,
64
+ FST_ERR_QSP_NOT_FN,
65
+ FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN,
66
+ FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ,
67
+ FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR,
68
+ FST_ERR_VERSION_CONSTRAINT_NOT_STR,
69
+ FST_ERR_INSTANCE_ALREADY_LISTENING,
70
+ FST_ERR_REOPENED_CLOSE_SERVER,
71
+ FST_ERR_ROUTE_REWRITE_NOT_STR,
72
+ FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN
63
73
  } = errorCodes
64
74
 
65
75
  const { buildErrorHandler } = require('./lib/error-handler.js')
@@ -90,15 +100,15 @@ function fastify (options) {
90
100
  options = options || {}
91
101
 
92
102
  if (typeof options !== 'object') {
93
- throw new TypeError('Options must be an object')
103
+ throw new FST_ERR_OPTIONS_NOT_OBJ()
94
104
  }
95
105
 
96
106
  if (options.querystringParser && typeof options.querystringParser !== 'function') {
97
- throw new Error(`querystringParser option should be a function, instead got '${typeof options.querystringParser}'`)
107
+ throw new FST_ERR_QSP_NOT_FN(typeof options.querystringParser)
98
108
  }
99
109
 
100
110
  if (options.schemaController && options.schemaController.bucket && typeof options.schemaController.bucket !== 'function') {
101
- throw new Error(`schemaController.bucket option should be a function, instead got '${typeof options.schemaController.bucket}'`)
111
+ throw new FST_ERR_SCHEMA_CONTROLLER_BUCKET_OPT_NOT_FN(typeof options.schemaController.bucket)
102
112
  }
103
113
 
104
114
  validateBodyLimitOption(options.bodyLimit)
@@ -117,10 +127,10 @@ function fastify (options) {
117
127
 
118
128
  // Ajv options
119
129
  if (!ajvOptions.customOptions || Object.prototype.toString.call(ajvOptions.customOptions) !== '[object Object]') {
120
- throw new Error(`ajv.customOptions option should be an object, instead got '${typeof ajvOptions.customOptions}'`)
130
+ throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_OBJ(typeof ajvOptions.customOptions)
121
131
  }
122
132
  if (!ajvOptions.plugins || !Array.isArray(ajvOptions.plugins)) {
123
- throw new Error(`ajv.plugins option should be an array, instead got '${typeof ajvOptions.plugins}'`)
133
+ throw new FST_ERR_AJV_CUSTOM_OPTIONS_OPT_NOT_ARR(typeof ajvOptions.plugins)
124
134
  }
125
135
 
126
136
  // Instance Fastify components
@@ -156,7 +166,7 @@ function fastify (options) {
156
166
  deriveConstraint: options.versioning.deriveVersion,
157
167
  validate (value) {
158
168
  if (typeof value !== 'string') {
159
- throw new Error('Version constraint should be a string.')
169
+ throw new FST_ERR_VERSION_CONSTRAINT_NOT_STR()
160
170
  }
161
171
  }
162
172
  }
@@ -463,7 +473,7 @@ function fastify (options) {
463
473
  return fastify
464
474
 
465
475
  function throwIfAlreadyStarted (msg) {
466
- if (fastify[kState].started) throw new Error(msg)
476
+ if (fastify[kState].started) throw new FST_ERR_INSTANCE_ALREADY_LISTENING(msg)
467
477
  }
468
478
 
469
479
  // HTTP injection handling
@@ -479,7 +489,7 @@ function fastify (options) {
479
489
  if (fastify[kState].started) {
480
490
  if (fastify[kState].closing) {
481
491
  // Force to return an error
482
- const error = new Error('Server is closed')
492
+ const error = new FST_ERR_REOPENED_CLOSE_SERVER()
483
493
  if (cb) {
484
494
  cb(error)
485
495
  return
@@ -564,7 +574,7 @@ function fastify (options) {
564
574
 
565
575
  // wrapper that we expose to the user for hooks handling
566
576
  function addHook (name, fn) {
567
- throwIfAlreadyStarted('Cannot call "addHook" when fastify instance is already started!')
577
+ throwIfAlreadyStarted('Cannot call "addHook"!')
568
578
 
569
579
  if (fn == null) {
570
580
  throw new errorCodes.FST_ERR_HOOK_INVALID_HANDLER(name, fn)
@@ -607,7 +617,7 @@ function fastify (options) {
607
617
 
608
618
  // wrapper that we expose to the user for schemas handling
609
619
  function addSchema (schema) {
610
- throwIfAlreadyStarted('Cannot call "addSchema" when fastify instance is already started!')
620
+ throwIfAlreadyStarted('Cannot call "addSchema"!')
611
621
  this[kSchemaController].add(schema)
612
622
  this[kChildren].forEach(child => child.addSchema(schema))
613
623
  return this
@@ -620,22 +630,30 @@ function fastify (options) {
620
630
  return
621
631
  }
622
632
 
623
- const body = JSON.stringify({
624
- error: http.STATUS_CODES['400'],
625
- message: 'Client Error',
626
- statusCode: 400
627
- })
633
+ let body, errorCode, errorStatus, errorLabel
634
+
635
+ if (err.code === 'ERR_HTTP_REQUEST_TIMEOUT') {
636
+ errorCode = '408'
637
+ errorStatus = http.STATUS_CODES[errorCode]
638
+ body = `{"error":"${errorStatus}","message":"Client Timeout","statusCode":408}`
639
+ errorLabel = 'timeout'
640
+ } else {
641
+ errorCode = '400'
642
+ errorStatus = http.STATUS_CODES[errorCode]
643
+ body = `{"error":"${errorStatus}","message":"Client Error","statusCode":400}`
644
+ errorLabel = 'error'
645
+ }
628
646
 
629
647
  // Most devs do not know what to do with this error.
630
648
  // In the vast majority of cases, it's a network error and/or some
631
649
  // config issue on the load balancer side.
632
- this.log.trace({ err }, 'client error')
650
+ this.log.trace({ err }, `client ${errorLabel}`)
633
651
  // Copying standard node behaviour
634
652
  // https://github.com/nodejs/node/blob/6ca23d7846cb47e84fd344543e394e50938540be/lib/_http_server.js#L666
635
653
 
636
654
  // If the socket is not writable, there is no reason to try to send data.
637
655
  if (socket.writable) {
638
- socket.write(`HTTP/1.1 400 Bad Request\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
656
+ socket.write(`HTTP/1.1 ${errorCode} ${errorStatus}\r\nContent-Length: ${body.length}\r\nContent-Type: application/json\r\n\r\n${body}`)
639
657
  }
640
658
  socket.destroy(err)
641
659
  }
@@ -697,33 +715,33 @@ function fastify (options) {
697
715
  }
698
716
 
699
717
  function setNotFoundHandler (opts, handler) {
700
- throwIfAlreadyStarted('Cannot call "setNotFoundHandler" when fastify instance is already started!')
718
+ throwIfAlreadyStarted('Cannot call "setNotFoundHandler"!')
701
719
 
702
720
  fourOhFour.setNotFoundHandler.call(this, opts, handler, avvio, router.routeHandler)
703
721
  return this
704
722
  }
705
723
 
706
724
  function setValidatorCompiler (validatorCompiler) {
707
- throwIfAlreadyStarted('Cannot call "setValidatorCompiler" when fastify instance is already started!')
725
+ throwIfAlreadyStarted('Cannot call "setValidatorCompiler"!')
708
726
  this[kSchemaController].setValidatorCompiler(validatorCompiler)
709
727
  return this
710
728
  }
711
729
 
712
730
  function setSchemaErrorFormatter (errorFormatter) {
713
- throwIfAlreadyStarted('Cannot call "setSchemaErrorFormatter" when fastify instance is already started!')
731
+ throwIfAlreadyStarted('Cannot call "setSchemaErrorFormatter"!')
714
732
  validateSchemaErrorFormatter(errorFormatter)
715
733
  this[kSchemaErrorFormatter] = errorFormatter.bind(this)
716
734
  return this
717
735
  }
718
736
 
719
737
  function setSerializerCompiler (serializerCompiler) {
720
- throwIfAlreadyStarted('Cannot call "setSerializerCompiler" when fastify instance is already started!')
738
+ throwIfAlreadyStarted('Cannot call "setSerializerCompiler"!')
721
739
  this[kSchemaController].setSerializerCompiler(serializerCompiler)
722
740
  return this
723
741
  }
724
742
 
725
743
  function setSchemaController (schemaControllerOpts) {
726
- throwIfAlreadyStarted('Cannot call "setSchemaController" when fastify instance is already started!')
744
+ throwIfAlreadyStarted('Cannot call "setSchemaController"!')
727
745
  const old = this[kSchemaController]
728
746
  const schemaController = SchemaController.buildSchemaController(old, Object.assign({}, old.opts, schemaControllerOpts))
729
747
  this[kSchemaController] = schemaController
@@ -733,7 +751,7 @@ function fastify (options) {
733
751
  }
734
752
 
735
753
  function setReplySerializer (replySerializer) {
736
- throwIfAlreadyStarted('Cannot call "setReplySerializer" when fastify instance is already started!')
754
+ throwIfAlreadyStarted('Cannot call "setReplySerializer"!')
737
755
 
738
756
  this[kReplySerializerDefault] = replySerializer
739
757
  return this
@@ -741,7 +759,7 @@ function fastify (options) {
741
759
 
742
760
  // wrapper that we expose to the user for configure the custom error handler
743
761
  function setErrorHandler (func) {
744
- throwIfAlreadyStarted('Cannot call "setErrorHandler" when fastify instance is already started!')
762
+ throwIfAlreadyStarted('Cannot call "setErrorHandler"!')
745
763
 
746
764
  this[kErrorHandler] = buildErrorHandler(this[kErrorHandler], func.bind(this))
747
765
  return this
@@ -766,7 +784,8 @@ function fastify (options) {
766
784
  if (typeof url === 'string') {
767
785
  req.url = url
768
786
  } else {
769
- req.destroy(new Error(`Rewrite url for "${req.url}" needs to be of type "string" but received "${typeof url}"`))
787
+ const err = new FST_ERR_ROUTE_REWRITE_NOT_STR(req.url, typeof url)
788
+ req.destroy(err)
770
789
  }
771
790
  }
772
791
  }
@@ -779,9 +798,9 @@ fastify.errorCodes = errorCodes
779
798
 
780
799
  function validateSchemaErrorFormatter (schemaErrorFormatter) {
781
800
  if (typeof schemaErrorFormatter !== 'function') {
782
- throw new Error(`schemaErrorFormatter option should be a function, instead got ${typeof schemaErrorFormatter}`)
801
+ throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN(typeof schemaErrorFormatter)
783
802
  } else if (schemaErrorFormatter.constructor.name === 'AsyncFunction') {
784
- throw new Error('schemaErrorFormatter option should not be an async function')
803
+ throw new FST_ERR_SCHEMA_ERROR_FORMATTER_NOT_FN('AsyncFunction')
785
804
  }
786
805
  }
787
806