diff --git a/types/h2o2/tsconfig.json b/types/h2o2/tsconfig.json index b0d5bbf160..4b4260bc21 100644 --- a/types/h2o2/tsconfig.json +++ b/types/h2o2/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "h2o2-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi-auth-basic/tsconfig.json b/types/hapi-auth-basic/tsconfig.json index 7448e829c4..6d16801a90 100644 --- a/types/hapi-auth-basic/tsconfig.json +++ b/types/hapi-auth-basic/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "hapi-auth-basic-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi-auth-jwt2/tsconfig.json b/types/hapi-auth-jwt2/tsconfig.json index 7d06e7c818..cca5383217 100644 --- a/types/hapi-auth-jwt2/tsconfig.json +++ b/types/hapi-auth-jwt2/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "hapi-auth-jwt2-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi-decorators/tsconfig.json b/types/hapi-decorators/tsconfig.json index 645122114e..fa86375121 100644 --- a/types/hapi-decorators/tsconfig.json +++ b/types/hapi-decorators/tsconfig.json @@ -18,7 +18,8 @@ "paths": { "boom": [ "boom/v4" - ] + ], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -28,4 +29,4 @@ "index.d.ts", "hapi-decorators-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/hapi/definitions/plugin/plugin-registered.d.ts b/types/hapi/definitions/plugin/plugin-registered.d.ts new file mode 100644 index 0000000000..6ce68e5e85 --- /dev/null +++ b/types/hapi/definitions/plugin/plugin-registered.d.ts @@ -0,0 +1,32 @@ +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ +export interface PluginsListRegistered { +} + +/** + * An object of the currently registered plugins where each key is a registered plugin name and the value is an + * object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ +export interface PluginRegistered { + + /** + * the plugin version. + */ + version: string; + + /** + * the plugin name. + */ + name: string; + + /** + * options used to register the plugin. + */ + options: object; + +} diff --git a/types/hapi/definitions/plugin/plugin.d.ts b/types/hapi/definitions/plugin/plugin.d.ts new file mode 100644 index 0000000000..925ac02205 --- /dev/null +++ b/types/hapi/definitions/plugin/plugin.d.ts @@ -0,0 +1,58 @@ +import {Server, ServerRegisterOptions} from "hapi"; + +export interface PluginsStates { +} + +export interface PluginSpecificConfiguration { + +} + +export interface PluginNameVersion { + /** + * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm + * registry) should use the same name as the name field in their 'package.json' file. Names must be + * unique within each application. + */ + name: string; + + /** optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's 'package.json' file. */ + version?: string; +} + +export interface PluginPackage { + + /** + * Alternatively, the name and version can be included via the pkg property containing the 'package.json' file for the module which already has the name and version included + */ + pkg: any; +} + +/** + * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each + * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox + * certain properties. For example, setting a file path in one plugin doesn't affect the file path set + * in another plugin. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins) + * + * The type T is the type of the plugin options. + */ +export interface PluginBase { + + /** + * (required) the registration function with the signature async function(server, options) where: + * * server - the server object with a plugin-specific server.realm. + * * options - any options passed to the plugin during registration via server.register(). + */ + register: (server: Server, options: T) => Promise; + + /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ + multiple?: boolean; + + /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ + dependencies?: string | string[]; + + /** once - (optional) if true, will only register the plugin once per server. If set, overrides the once option passed to server.register(). Defaults to no override. */ + once?: boolean; +} + +export type Plugin = PluginBase & (PluginNameVersion | PluginPackage); diff --git a/types/hapi/definitions/request/request-auth.d.ts b/types/hapi/definitions/request/request-auth.d.ts new file mode 100644 index 0000000000..d2f22e81cd --- /dev/null +++ b/types/hapi/definitions/request/request-auth.d.ts @@ -0,0 +1,34 @@ +/** + * User-extensible type for request.auth credentials. + */ +export interface AuthCredentials { + user?: string; +} + +/** + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ +export interface RequestAuth { + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: object; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: AuthCredentials; + /** the authentication error is failed and mode set to 'try'. */ + error: Error; + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, set to false. */ + isAuthorized: boolean; + /** the route authentication mode. */ + mode: string; + /** the name of the strategy used. */ + strategy: string; +} diff --git a/types/hapi/definitions/request/request-events.d.ts b/types/hapi/definitions/request/request-events.d.ts new file mode 100644 index 0000000000..dfcb004d24 --- /dev/null +++ b/types/hapi/definitions/request/request-events.d.ts @@ -0,0 +1,45 @@ +import * as Podium from "podium"; +import {PeekListener} from "hapi"; + +/** + * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export type RequestEventType = "peek" | "finish" | "disconnect"; + +/** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export interface RequestEvents extends Podium { + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + on(criteria: "peek", listener: PeekListener): void; + on(criteria: "finish" | "disconnect", listener: () => void): void; + on(criteria: RequestEventType, listener: Function): void; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + once(criteria: "peek", listener: PeekListener): void; + once(criteria: "finish" | "disconnect", listener: () => void): void; + once(criteria: RequestEventType, listener: Function): void; +} diff --git a/types/hapi/definitions/request/request-info.d.ts b/types/hapi/definitions/request/request-info.d.ts new file mode 100644 index 0000000000..a4892438a2 --- /dev/null +++ b/types/hapi/definitions/request/request-info.d.ts @@ -0,0 +1,41 @@ +/** + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ +export interface RequestInfo { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + /** + * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + */ + isOriginMatch?: boolean; + }; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com'). */ + hostname: string; + /** request reception timestamp. */ + received: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** remote client IP address. */ + remoteAddress: string; + /** remote client port. */ + remotePort: string; + /** request response timestamp (0 is not responded yet). */ + responded: number; +} diff --git a/types/hapi/definitions/request/request-route.d.ts b/types/hapi/definitions/request/request-route.d.ts new file mode 100644 index 0000000000..fbafd033a6 --- /dev/null +++ b/types/hapi/definitions/request/request-route.d.ts @@ -0,0 +1,45 @@ +import {Request, RouteOptions, ServerRealm, Util} from "hapi"; + +/** + * The request route information object, where: + * * method - the route HTTP method. + * * path - the route path. + * * vhost - the route vhost option if configured. + * * realm - the active realm associated with the route. + * * settings - the route options object with all defaults applied. + * * fingerprint - the route internal normalized string representing the normalized path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + */ +export interface RequestRoute { + + /** the route HTTP method. */ + method: Util.HTTP_METHODS_PARTIAL; + + /** the route path. */ + path: string; + + /** the route vhost option if configured. */ + vhost?: string | string[]; + + /** the active realm associated with the route.*/ + realm: ServerRealm; + + /** the route options object with all defaults applied. */ + settings: RouteOptions; + + /** the route internal normalized string representing the normalized path. */ + fingerprint: string; + + auth: { + /** + * Validates a request against the route's authentication access configuration, where: + * @param request - the request object. + * @return Return value: true if the request would have passed the route's access requirements. + * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. + * If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route requires any authentication. + * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) + */ + access(request: Request): boolean; + } + +} diff --git a/types/hapi/definitions/request/request.d.ts b/types/hapi/definitions/request/request.d.ts new file mode 100644 index 0000000000..f04a57be96 --- /dev/null +++ b/types/hapi/definitions/request/request.d.ts @@ -0,0 +1,224 @@ +import * as stream from "stream"; +import * as url from "url"; +import * as http from "http"; +import * as Podium from "podium"; +import {ApplicationState, PluginsStates, RequestAuth, RequestEvents, RequestInfo, RequestRoute, ResponseObject, ResponseValue, Server, Util} from "hapi"; + +/** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig) + */ +export interface RequestOrig { + params: object; + query: object; + payload: object; +} + +export interface RequestLog { + request: string; + timestamp: number; + tags: string[]; + data: string | object; + channel: string; +} + +/** + * The request object is created internally for each incoming request. It is not the same object received from the node + * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout + * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle). + */ +export interface Request extends Podium { + + /** + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp) + */ + app: ApplicationState; + + /** + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ + readonly auth: RequestAuth; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + events: RequestEvents; + + /** + * The raw request headers (references request.raw.req.headers). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) + */ + readonly headers: Util.Dictionary; + + /** + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ + readonly info: RequestInfo; + + /** + * An array containing the logged request events. + * Note that this array will be empty if route log.collect is set to false. + */ + readonly logs: RequestLog[]; + + /** + * The request method in lower case (e.g. 'get', 'post'). + */ + readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE; + + /** + * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. + */ + readonly mime: string; + + /** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + */ + readonly orig: RequestOrig; + + /** + * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). + */ + readonly params: Util.Dictionary; + + /** + * An array containing all the path params values in the order they appeared in the path. + */ + readonly paramsArray: string[]; + + /** + * The request URI's pathname component. + */ + readonly path: string; + + /** + * The request payload based on the route payload.output and payload.parse settings. + * TODO check this typing and add references / links. + */ + readonly payload: stream.Readable | Buffer | string | object; + + /** + * Plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. + */ + plugins: PluginsStates; + + /** + * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses. + */ + readonly pre: Util.Dictionary; + + /** + * Access: read / write (see limitations below). + * The response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). + */ + response: ResponseObject | null; + + /** + * Same as pre but represented as the response object created by the pre method. + */ + readonly preResponses: Util.Dictionary; + + /** + * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query attribute as an unparsed string). + */ + readonly query: any; + + /** + * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. + * * req - the node request object. + * * res - the node response object. + */ + readonly raw: { + req: http.IncomingMessage; + res: http.ServerResponse; + }; + + /** + * The request route information object and method + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest) + */ + readonly route: RequestRoute; + + /** + * Access: read only and the public server interface. + * The server object. + */ + server: Server; + + /** + * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. + */ + readonly state: Util.Dictionary; + + /** + * The parsed request URI. + */ + readonly url: url.Url; + + /** + * Returns a response which you can pass into the reply interface where: + * @param source - the value to set as the source of the reply interface, optional. + * @param options - options for the method, optional. + * @return ResponseObject + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options) + */ + generateResponse(source: string | object | null, options?: {variety?: string; prepare?: (response: ResponseObject) => Promise; marshal?: (response: ResponseObject) => Promise; close?: (response: ResponseObject) => void; }): ResponseObject; + + /** + * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: + * @param tags - a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. + * Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) + */ + log(tags: string | string[], data?: string | object | (() => string | object)): void; + + /** + * Changes the request method before the router begins processing the request where: + * @param method - is the request HTTP method (e.g. 'GET'). + * @return void + * Can only be called from an 'onRequest' extension method. + * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod) + */ + setMethod(method: Util.HTTP_METHODS_PARTIAL): void; + + /** + * Changes the request URI before the router begins processing the request where: + * Can only be called from an 'onRequest' extension method. + * @param url - the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL parse() method output. + * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false. + * @return void + * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) + */ + setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; + +} diff --git a/types/hapi/definitions/response/response-events.d.ts b/types/hapi/definitions/response/response-events.d.ts new file mode 100644 index 0000000000..b31fe0c21e --- /dev/null +++ b/types/hapi/definitions/response/response-events.d.ts @@ -0,0 +1,29 @@ +import * as Podium from "podium"; +import {PeekListener} from "hapi"; + +/** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseEvents extends Podium { + + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + on(criteria: 'peek', listener: PeekListener): void; + on(criteria: 'finish', listener: () => void): void; + on(criteria: 'peek' | 'finish', listener: Function): void; + + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + once(criteria: 'peek', listener: PeekListener): void; + once(criteria: 'finish', listener: () => void): void; + once(criteria: 'peek' | 'finish', listener: Function): void; + +} diff --git a/types/hapi/definitions/response/response-object.d.ts b/types/hapi/definitions/response/response-object.d.ts new file mode 100644 index 0000000000..4382338551 --- /dev/null +++ b/types/hapi/definitions/response/response-object.d.ts @@ -0,0 +1,288 @@ +import * as Podium from "podium"; +import {ApplicationState, Json, Lifecycle, PluginsStates, ResponseEvents, ResponseSettings, ServerStateCookieOptions, Util} from "hapi"; + +/** + * Object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + */ +export interface ResponseObjectHeaderOptions { + append?: boolean; + separator?: string; + override?: boolean; + duplicate?: boolean; +} + +/** + * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle + * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status + * code). In order to customize a response before it is returned, the h.response() method is provided. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseObject extends Podium { + + /** + * Default value: {}. + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp) + */ + app: ApplicationState; + + /** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ + readonly events: ResponseEvents; + + /** + * Default value: {}. + * An object containing the response headers where each key is a header field name and the value is the string header value or array of string. + * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) + */ + readonly headers: Util.Dictionary; + + /** + * Default value: {}. + * Plugin-specific state. Provides a place to store and pass request-level plugin data. plugins is an object where each key is a plugin name and the value is the state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins) + */ + plugins: PluginsStates; + + /** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ + readonly settings: ResponseSettings; + + /** + * The raw value returned by the lifecycle method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource) + */ + readonly source: Lifecycle.ReturnValue; + + /** + * Default value: 200. + * The HTTP response status code. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode) + */ + readonly statusCode: number; + + /** + * A string indicating the type of source with available values: + * * 'plain' - a plain response such as string, number, null, or simple object. + * * 'buffer' - a Buffer. + * * 'stream' - a Stream. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety) + */ + readonly variety: 'plain' | 'buffer' | 'stream'; + + /** + * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where: + * @param length - the header value. Must match the actual payload size. + * @return Return value: the current response object. + * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength) + */ + bytes(length: number): ResponseObject; + + /** + * Sets the 'Content-Type' HTTP header 'charset' property where: + * @param charset - the charset property value. + * @return Return value: the current response object. + * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset) + */ + charset(charset: string): ResponseObject; + + /** + * Sets the 'Content-Type' HTTP header 'charset' property where: + * $param charset - the charset property value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode) + */ + code(statusCode: number): ResponseObject; + + /** + * Sets the HTTP status message where: + * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200). + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage) + */ + message(httpMessage: string): ResponseObject; + + /** + * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where: + * @param uri - an absolute or relative URI used as the 'Location' header value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri) + */ + created(uri: string): ResponseObject; + + /** + * Sets the string encoding scheme used to serial data into the HTTP payload where: + * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). + * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. + * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. + * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. + * * 'ucs2' - Alias of 'utf16le'. + * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. + * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). + * * 'binary' - Alias for 'latin1'. + * * 'hex' - Encode each byte as two hexadecimal characters. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding) + */ + encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject; + + /** + * Sets the representation entity tag where: + * @param tag - the entity tag string without the double-quote. + * @param options - (optional) settings where: + * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) + */ + etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject; + + /** + * Sets an HTTP header where: + * @param name - the header name. + * @param value - the header value. + * @param options - (optional) object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + */ + header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; + + /** + * Sets the HTTP 'Location' header where: + * @param uri - an absolute or relative URI used as the 'Location' header value. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri) + */ + location(uri: string): ResponseObject; + + /** + * Sets an HTTP redirection response (302) and decorates the response with additional methods, where: + * @param uri - an absolute or relative URI used to redirect the client to another resource. + * @return Return value: the current response object. + * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi) + */ + redirect(uri: string): ResponseObject; + + /** + * Sets the JSON.stringify() replacer argument where: + * @param method - the replacer function or array. Defaults to none. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod) + */ + replacer(method: Json.StringifyReplacer): ResponseObject; + + /** + * Sets the JSON.stringify() space argument where: + * @param count - the number of spaces to indent nested object keys. Defaults to no indentation. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount) + */ + spaces(count: number): ResponseObject; + + /** + * Sets an HTTP cookie where: + * @param name - the cookie name. + * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values. + * @param options - (optional) configuration. If the state was previously registered with the server using server.state(), the specified keys in options are merged with the default server definition. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) + */ + state(name: string, value: object | string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * Sets a string suffix when the response is process via JSON.stringify() where: + * @param suffix - the string suffix. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix) + */ + suffix(suffix: string): ResponseObject; + + /** + * Overrides the default route cache expiration rule for this response instance where: + * @param msec - the time-to-live value in milliseconds. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec) + */ + ttl(msec: number): ResponseObject; + + /** + * Sets the HTTP 'Content-Type' header where: + * @param mimeType - is the mime type. + * @return Return value: the current response object. + * Should only be used to override the built-in default for each response type. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) + */ + type(mimeType: string): ResponseObject; + + /** + * Clears the HTTP cookie by setting an expired value where: + * @param name - the cookie name. + * @param options - (optional) configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified options are merged with the server definition. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) + */ + unstate(name: string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: + * @param header - the HTTP request header name. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader) + */ + vary(header: string): ResponseObject; + + /** + * Marks the response object as a takeover response. + * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover) + */ + takeover(): ResponseObject; + + /** + * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where: + * @param isTemporary - if false, sets status to permanent. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary) + */ + temporary(isTemporary: boolean): ResponseObject; + + /** + * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where: + * @param isPermanent - if false, sets status to temporary. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent) + */ + permanent(isPermanent: boolean): ResponseObject; + + /** + * Sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments: + * @param isRewritable - if false, sets to non-rewritable. Defaults to true. + * @return Return value: the current response object. + * Only available after calling the response.redirect() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable) + */ + rewritable(isRewritable: boolean): ResponseObject; + +} diff --git a/types/hapi/definitions/response/response-settings.d.ts b/types/hapi/definitions/response/response-settings.d.ts new file mode 100644 index 0000000000..0926878d1c --- /dev/null +++ b/types/hapi/definitions/response/response-settings.d.ts @@ -0,0 +1,33 @@ +import {Json} from "hapi"; + +/** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ +export interface ResponseSettings { + + /** + * Defaults value: true. + * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response. + */ + readonly passThrough: boolean; + + /** + * Default value: null (use route defaults). + * Override the route json options used when source value requires stringification. + */ + readonly stringify: Json.StringifyArguments; + + /** + * Default value: null (use route defaults). + * If set, overrides the route cache with an expiration value in milliseconds. + */ + readonly ttl: number; + + /** + * Default value: false. + * If true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. + */ + varyEtag: boolean; + +} diff --git a/types/hapi/definitions/response/response-toolkit.d.ts b/types/hapi/definitions/response/response-toolkit.d.ts new file mode 100644 index 0000000000..8fb64a6ea3 --- /dev/null +++ b/types/hapi/definitions/response/response-toolkit.d.ts @@ -0,0 +1,139 @@ +import {Request, ResponseObject, ServerRealm, ServerStateCookieOptions} from "hapi"; + +/** + * See more about Lifecycle + * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle + * + */ + +export type ResponseValue = string | object; + +export interface AuthenticationData { + credentials: object; + artifacts?: object; +} + +/** + * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the + * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this + * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) + */ +export interface ResponseToolkit { + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step + * without further interaction with the node response stream. It is the developer's responsibility to write + * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw). + */ + readonly abandon: symbol; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after + * calling request.raw.res.end()) to close the the node response stream. + */ + readonly close: symbol; + + /** + * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind) + * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()). + */ + readonly context: any; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. + */ + readonly continue: symbol; + + /** + * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching + * route. Defaults to the root server realm in the onRequest step. + */ + readonly realm: ServerRealm; + + /** + * Access: read only and public request interface. + * The [request] object. This is a duplication of the request lifecycle method argument used by + * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. + */ + readonly request: Readonly + + /** + * Used by the [authentication] method to pass back valid credentials where: + * @param data - an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return Return value: an internal authentication object. + */ + authenticated(data: AuthenticationData): object; + + /** + * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if + * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request + * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will + * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined. + * The method argumetns are: + * @param options - a required configuration object with: + * * etag - the ETag string. Required if modified is not present. Defaults to no header. + * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. + * * vary - same as the response.etag() option. Defaults to true. + * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed. + * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned, + * it should be used as the return value (but may be customize using the response methods). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions) + */ + entity(options?: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; + + /** + * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). + * @param url + * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) + */ + redirect(uri?: string): ResponseObject; + + /** + * Wraps the provided value and returns a response object which allows customizing the response + * (e.g. setting the HTTP status code, custom headers, etc.), where: + * @param value - (optional) return value. Defaults to null. + * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue) + */ + response(value?: ResponseValue): ResponseObject; + + /** + * Sets a response cookie using the same arguments as response.state(). + * @param name of the cookie + * @param value of the cookie + * @param (optional) ServerStateCookieOptions object. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options) + */ + state(name: string, value: string, options?: ServerStateCookieOptions): void; + + /** + * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: + * @param error - (required) the authentication error. + * @param data - (optional) an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return void. + * The method is used to pass both the authentication error and the credentials. For example, if a request included + * expired credentials, it allows the method to pass back the user information (combined with a 'try' + * authentication mode) for error customization. + * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) + */ + unauthenticated(error: Error, data?: AuthenticationData): void; + + /** + * Clears a response cookie using the same arguments as + * @param name of the cookie + * @param options (optional) ServerStateCookieOptions object. + * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options) + */ + unstate(name: string, options?: ServerStateCookieOptions): void; + +} diff --git a/types/hapi/definitions/route/route-options-access.d.ts b/types/hapi/definitions/route/route-options-access.d.ts new file mode 100644 index 0000000000..2446d7b1c4 --- /dev/null +++ b/types/hapi/definitions/route/route-options-access.d.ts @@ -0,0 +1,82 @@ + +export type RouteOptionsAccessScope = false | string | string[]; + +export type RouteOptionsAccessEntity = 'any' | 'user' | 'app'; + +export interface RouteOptionsAccessScopeObject { + scope: RouteOptionsAccessScope; +} + +export interface RouteOptionsAccessEntityObject { + entity: RouteOptionsAccessEntity; +} + +export type RouteOptionsAccessObject = RouteOptionsAccessScopeObject | RouteOptionsAccessEntityObject | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject); + +/** + * Route Authentication Options + */ +export interface RouteOptionsAccess { + + /** + * Default value: none. + * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object must include at least one of scope or entity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess) + */ + access?: RouteOptionsAccessObject | RouteOptionsAccessObject[]; + + /** + * Default value: false (no scope requirements). + * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least one of the scopes defined to access the route. + * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. + * You may also access properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) + */ + scope?: RouteOptionsAccessScope; + + /** + * Default value: 'any'. + * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values: + * * 'any' - the authentication can be on behalf of a user or application. + * * 'user' - the authentication must be on behalf of a user which is identified by the presence of a 'user' attribute in the credentials object returned by the authentication strategy. + * * 'app' - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) + */ + entity?: RouteOptionsAccessEntity; + + /** + * Default value: 'required'. + * The authentication mode. Available values: + * * 'required' - authentication is required. + * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all. + * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode) + */ + mode?: 'required' | 'optional' | 'try'; + + /** + * Default value: false, unless the scheme requires payload authentication. + * If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' when the scheme sets the authentication options.payload to true. + * Available values: + * * false - no payload authentication. + * * 'required' - payload authentication required. + * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload) + */ + payload?: false | 'required' | 'optional'; + + /** + * Default value: the default strategy set via server.auth.default(). + * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies) + */ + strategies?: string[]; + + /** + * Default value: the default strategy set via server.auth.default(). + * A string strategy names. Cannot be used together with strategies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy) + */ + strategy?: string; + +} diff --git a/types/hapi/definitions/route/route-options-cache.d.ts b/types/hapi/definitions/route/route-options-cache.d.ts new file mode 100644 index 0000000000..1b17ee4e96 --- /dev/null +++ b/types/hapi/definitions/route/route-options-cache.d.ts @@ -0,0 +1,27 @@ +/** + * Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) + */ +export type RouteOptionsCache = { + privacy?: 'default' | 'public' | 'privacy'; + statuses?: number[]; + otherwise?: string; +} & ( + { + expiresIn?: number; + expiresAt?: undefined; + } | { + expiresIn?: undefined; + expiresAt?: string; + } | { + expiresIn?: undefined; + expiresAt?: undefined; + } +); diff --git a/types/hapi/definitions/route/route-options-cors.d.ts b/types/hapi/definitions/route/route-options-cors.d.ts new file mode 100644 index 0000000000..8264680ec8 --- /dev/null +++ b/types/hapi/definitions/route/route-options-cors.d.ts @@ -0,0 +1,42 @@ +/** + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) + */ +export interface RouteOptionsCors { + /** + * an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any origin ['*']. + */ + origin?: string[] | '*'| 'ignore'; + /** + * number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). + */ + maxAge?: number; + /** + * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + */ + headers?: string[]; + /** + * a strings array of additional headers to headers. Use this to keep the default headers in place. + */ + additionalHeaders?: string[]; + /** + * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + */ + exposedHeaders?: string[]; + /** + * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + */ + additionalExposedHeaders?: string[]; + /** + * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + */ + credentials?: boolean; +} diff --git a/types/hapi/definitions/route/route-options-payload.d.ts b/types/hapi/definitions/route/route-options-payload.d.ts new file mode 100644 index 0000000000..a13db35c32 --- /dev/null +++ b/types/hapi/definitions/route/route-options-payload.d.ts @@ -0,0 +1,122 @@ +import {Lifecycle, Util} from "hapi"; + +/** + * The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ +export type PayloadOutput = 'data' | 'stream' | 'file'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ +export type PayloadCompressionDecoderSettings = object; + +/** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ +export interface RouteOptionsPayload { + + /** + * Default value: allows parsing of the following mime types: + * * application/json + * * application/*+json + * * application/octet-stream + * * application/x-www-form-urlencoded + * * multipart/form-data + * * text/* + * A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed above will not enable them to be parsed, and if parse is true, the request will result in an error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow) + */ + allow?: string | string[]; + + /** + * Default value: none. + * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ + compression?: Util.Dictionary; + + /** + * Default value: 'application/json'. + * The default content type if the 'Content-Type' request header is missing. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype) + */ + defaultContentType?: string; + + /** + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle payload parsing errors. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: 1048576 (1MB). + * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes) + */ + maxBytes?: number; + + /** + * Default value: none. + * Overrides payload processing for multipart requests. Value can be one of: + * * false - disable multipart processing. + * an object with the following required options: + * * output - same as the output option with an additional value option: + * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? + * * * * headers - the part headers. + * * * * filename - the part file name. + * * * * payload - the processed part payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart) + */ + multipart?: false | { + output: PayloadOutput | 'annotated'; + }; + + /** + * Default value: 'data'. + * The processed payload format. The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ + output?: PayloadOutput; + + /** + * Default value: none. + * A mime type string overriding the 'Content-Type' header value received. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride) + */ + override?: string; + + /** + * Default value: true. + * Determines if the incoming payload is processed or presented raw. Available values: + * * true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. + * * false - the raw payload is returned unmodified. + * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse) + */ + parse?: boolean | 'gunzip'; + + /** + * Default value: to 10000 (10 seconds). + * Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. + * Set to false to disable. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout) + */ + timeout?: false | number; + + /** + * Default value: os.tmpdir(). + * The directory used for writing file uploads. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads) + */ + uploads?: string; + +} diff --git a/types/hapi/definitions/route/route-options-pre.d.ts b/types/hapi/definitions/route/route-options-pre.d.ts new file mode 100644 index 0000000000..8745bf5a00 --- /dev/null +++ b/types/hapi/definitions/route/route-options-pre.d.ts @@ -0,0 +1,33 @@ +import {Lifecycle} from "hapi"; + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreArray = RouteOptionsPreAllOptions[]; + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method; + +/** + * An object with: + * * method - a lifecycle method. + * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export interface RouteOptionsPreObject { + /** + * a lifecycle method. + */ + method: Lifecycle.Method; + /** + * key name used to assign the response of the method to in request.pre and request.preResponses. + */ + assign: string; + /** + * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + */ + failAction?: Lifecycle.FailAction; +} diff --git a/types/hapi/definitions/route/route-options-response.d.ts b/types/hapi/definitions/route/route-options-response.d.ts new file mode 100644 index 0000000000..b0c3925bfe --- /dev/null +++ b/types/hapi/definitions/route/route-options-response.d.ts @@ -0,0 +1,76 @@ +import {Lifecycle, Util} from "hapi"; +import {ValidationOptions} from "joi"; + +export type RouteOptionsResponseSchema = boolean | ValidationOptions | ((value: object | Buffer | string, options: ValidationOptions) => Promise); + +/** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ +export interface RouteOptionsResponse { + + /** + * Default value: 200. + * The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the response status code will remain 200 throughout the request lifecycle unless manually set). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode) + */ + emptyStatusCode?: 200 | 204; + + /** + * Default value: 'error' (return an Internal Server Error (500) error response). + * A failAction value which defines what to do when a response fails payload validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: false. + * If true, applies the validation rule changes to the response payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify) + */ + modify?: boolean; + + /** + * Default value: none. + * [joi](http://github.com/hapijs/joi) options object pass to the validation function. Useful to set global options such as stripUnknown or abortEarly (the complete list is available here). If a custom validation function is defined via schema or status then options can an arbitrary object that will be passed to this function as the second argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions) + */ + options?: ValidationOptions; // TODO needs validation + + /** + * Default value: true. + * If false, payload range support is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges) + */ + ranges?: boolean; + + /** + * Default value: 100 (all responses). + * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample) + */ + sample?: number; + + /** + * Default value: true (no validation). + * The default response payload validation rules (for all non-error responses) expressed as one of: + * * true - any payload allowed (no validation). + * * false - no payload allowed. + * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function. + * * a validation function using the signature async function(value, options) where: + * * * value - the pending response payload. + * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }). + * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error output.payload. If an error is thrown, the error is processed according to failAction. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema) + */ + schema?: RouteOptionsResponseSchema; + + /** + * Default value: none. + * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema. + * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) + */ + status?: Util.Dictionary; + +} diff --git a/types/hapi/definitions/route/route-options-secure.d.ts b/types/hapi/definitions/route/route-options-secure.d.ts new file mode 100644 index 0000000000..669d1371ed --- /dev/null +++ b/types/hapi/definitions/route/route-options-secure.d.ts @@ -0,0 +1,74 @@ +/** + * Default value: false (security headers disabled). + * Sets common security headers. To enable, set security to true or to an object with the following options: + * * hsts - controls the 'Strict-Transport-Security' header, where: + * * * true - the header will be set to max-age=15768000. This is the default value. + * * * a number - the maxAge parameter will be set to the provided value. + * * * an object with the following fields: + * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. + * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. + * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + * * xframe - controls the 'X-Frame-Options' header, where: + * * * true - the header will be set to 'DENY'. This is the default value. + * * * 'deny' - the headers will be set to 'DENY'. + * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. + * * * an object for specifying the 'allow-from' rule, where: + * * * * rule - one of: + * * * * * 'deny' + * * * * * 'sameorigin' + * * * * * 'allow-from' + * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. + * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. + * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) + */ +export interface RouteOptionsSecureObject { + /** + * hsts - controls the 'Strict-Transport-Security' header + */ + hsts?: boolean | number | { + /** + * the max-age portion of the header, as a number. Default is 15768000. + */ + maxAge: number; + /** + * a boolean specifying whether to add the includeSubDomains flag to the header. + */ + includeSubdomains: boolean; + /** + * a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + */ + preload: boolean; + }; + /** + * controls the 'X-Frame-Options' header + */ + xframe?: true | 'deny' | 'sameorigin' | { + /** + * an object for specifying the 'allow-from' rule, + */ + rule: 'deny' | 'sameorigin' | 'allow-from'; + /** + * when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. + */ + source: string; + }; + /** + * boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. + */ + xss: boolean; + /** + * boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + */ + noOpen?: boolean; + /** + * boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + */ + noSniff?: boolean; +} + + +export type RouteOptionsSecure = boolean | RouteOptionsSecureObject; diff --git a/types/hapi/definitions/route/route-options-validate.d.ts b/types/hapi/definitions/route/route-options-validate.d.ts new file mode 100644 index 0000000000..7fa61d5bef --- /dev/null +++ b/types/hapi/definitions/route/route-options-validate.d.ts @@ -0,0 +1,92 @@ +import {Lifecycle, RouteOptionsResponseSchema} from "hapi"; +import {ValidationOptions} from "joi"; + +/** + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) + */ +export interface RouteOptionsValidate { + + /** + * Default value: none. + * An optional object with error fields copied into every validation error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields) + */ + errorFields?: object; + + /** + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle failed validations. When set to a function, the err argument includes the type of validation error under err.output.payload.validation.source. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction) + */ + failAction?: Lifecycle.FailAction; + + /** + * Default value: true (no validation). + * Validation rules for incoming request headers: + * * true - any headers allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.headers object containing the request headers. + * * * options - options. + * * * if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error is thrown, the error is handled according to failAction. + * Note that all header field names must be in lowercase to match the headers normalized by node. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) + */ + headers?: RouteOptionsResponseSchema; + + /** + * Default value: none. + * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). + * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. + * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as Joi.ref('$query.key')). + * Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. + * If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the individual route settings override the routes defaults (the rules are not merged). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + */ + options?: ValidationOptions | object; + + /** + * Default value: true (no validation). + * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: + * * true - any path parameter value allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.params object containing the request path parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an error is thrown, the error is handled according to failAction. + * Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) + */ + params?: RouteOptionsResponseSchema; + + /** + * Default value: true (no validation). + * Validation rules for incoming request payload (request body), where: + * * true - any payload allowed (no validation performed). false - no payload allowed. + * * a joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by setting the rule to a joi schema with null allowed (e.g. Joi.object({ keys here }).allow(null)). + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is thrown, the error is handled according to failAction. + * Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well as the significant performance cost of validating large amounts of data. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) + */ + payload?: RouteOptionsResponseSchema; + + /** + * Default value: true (no validation). + * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in request.query prior to validation. Where: + * * true - any query parameter value allowed (no validation performed). false - no query parameter value allowed. + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. If an error is thrown, the error is handled according to failAction. + * Note that changes to the query parameters will not be reflected in request.url. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) + */ + query?: RouteOptionsResponseSchema; + +} diff --git a/types/hapi/definitions/route/route-options.d.ts b/types/hapi/definitions/route/route-options.d.ts new file mode 100644 index 0000000000..e66668c75c --- /dev/null +++ b/types/hapi/definitions/route/route-options.d.ts @@ -0,0 +1,284 @@ +import { + Json, + Lifecycle, + PluginSpecificConfiguration, + RouteOptionsAccess, + RouteOptionsCache, + RouteOptionsCors, + RouteOptionsPayload, + RouteOptionsPreArray, + RouteOptionsResponse, + RouteOptionsSecure, + RouteOptionsValidate, + Util +} from "hapi"; + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ +export type RouteCompressionEncoderSettings = object; + +/** + * Each route can be customized to change the default behavior of the request lifecycle. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options) + */ +export interface RouteOptions { + + /** + * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ + app?: any; + + /** + * Route authentication configuration. Value can be: + * false to disable authentication if a default strategy is set. + * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode. + * an authentication configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ + auth?: false | string | RouteOptionsAccess; + + /** + * Default value: null. + * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind) + */ + bind?: object | null; + + /** + * Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. + * If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options: + * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * The default Cache-Control: no-cache header can be disabled by setting cache to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) + */ + cache?: false | RouteOptionsCache; + + /** + * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + */ + compression?: Util.Dictionary; + + /** + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) + */ + cors?: false | RouteOptionsCors; + + /** + * Default value: none. + * Route description used for generating documentation (string). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription) + */ + description?: string; + + /** + * Default value: none. + * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the server.ext(events) event argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ + ext?: object; + + /** + * Default value: { relativeTo: '.' }. + * Defines the behavior for accessing files: + * * relativeTo - determines the folder relative paths are resolved against. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles) + */ + files?: { + relativeTo: string; + } + + /** + * Default value: none. + * The route handler function performs the main business logic of the route and sets the response. handler can be assigned: + * * a lifecycle method. + * * an object with a single property using the name of a handler type registred with the server.handler() method. The matching property value is passed as options to the registered handler generator. + * Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) + */ + handler?: Lifecycle.Method | object; + + /** + * Default value: none. + * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid) + */ + id?: string; + + /** + * Default value: false. + * If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should not be accessible to the outside world. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal) + */ + isInternal?: boolean; + + /** + * Default value: none. + * Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following: + * * replacer - the replacer function or array. Defaults to no action. + * * space - number of spaces to indent nested object keys. Defaults to no indentation. + * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix. + * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + json?: Json.StringifyArguments; + + /** + * Default value: none. + * Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. + * For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Cannot be used with stream responses. + * The 'Content-Type' response header is set to 'text/javascript' and the 'X-Content-Type-Options' response header is set to 'nosniff', and will override those headers even if explicitly set by response.type(). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjsonp) + */ + jsonp?: string; + + /** + * Default value: { collect: false }. + * Request logging options: + * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog) + */ + log?: { + collect: boolean; + } + + /** + * Default value: none. + * Route notes used for generating documentation (string or array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes) + */ + notes?: string | string[]; + + /** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ + payload?: RouteOptionsPayload; + + /** + * Default value: {}. + * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) + */ + plugins?: Util.Dictionary; + + /** + * Default value: none. + * The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared ascross routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). + * pre is assigned an ordered array of methods which are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. + * pre can be assigned a mixed array of: + * * an array containing the elements listed below, which are executed in parallel. + * * an object with: + * * * method - a lifecycle method. + * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + * * a method function - same as including an object with a single method key. + * Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other lifecycle methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ + pre?: RouteOptionsPreArray; + + /** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ + response?: RouteOptionsResponse; + + /** + * Default value: false (security headers disabled). + * Sets common security headers. To enable, set security to true or to an object with the following options: + * * hsts - controls the 'Strict-Transport-Security' header, where: + * * * true - the header will be set to max-age=15768000. This is the default value. + * * * a number - the maxAge parameter will be set to the provided value. + * * * an object with the following fields: + * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. + * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. + * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + * * xframe - controls the 'X-Frame-Options' header, where: + * * * true - the header will be set to 'DENY'. This is the default value. + * * * 'deny' - the headers will be set to 'DENY'. + * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. + * * * an object for specifying the 'allow-from' rule, where: + * * * * rule - one of: + * * * * * 'deny' + * * * * * 'sameorigin' + * * * * * 'allow-from' + * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. + * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. + * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) + */ + security?: RouteOptionsSecure; + + /** + * Default value: { parse: true, failAction: 'error' }. + * HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following options: + * parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. + * failAction - A failAction value which determines how to handle cookie parsing errors. Defaults to 'error' (return a Bad Request (400) error response). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate) + */ + state?: { + parse?: boolean; + failAction?: Lifecycle.FailAction; + } + + /** + * Default value: none. + * Route tags used for generating documentation (array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags) + */ + tags?: string[]; + + /** + * Default value: { server: false }. + * Timeouts for processing durations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout) + */ + timeout?: { + + /** + * Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error response. + */ + server?: boolean | number; + + /** + * Default value: none (use node default of 2 minutes). + * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts. + */ + socket?: boolean | number; + + }; + + /** + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) + */ + validate?: RouteOptionsValidate; + +} diff --git a/types/hapi/definitions/server/server-auth-scheme.d.ts b/types/hapi/definitions/server/server-auth-scheme.d.ts new file mode 100644 index 0000000000..5eed01f0a0 --- /dev/null +++ b/types/hapi/definitions/server/server-auth-scheme.d.ts @@ -0,0 +1,74 @@ +import {Lifecycle, Request, ResponseToolkit, Server} from "hapi"; + +/** + * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ +export type ServerAuthSchemeOptions = object; + +/** + * the method implementing the scheme with signature function(server, options) where: + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + * @param server - a reference to the server object the scheme is added to. + * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + */ +export interface ServerAuthScheme { + (server: Server, options?: ServerAuthSchemeOptions): ServerAuthSchemeObject; +} + +export interface ServerAuthSchemeObjectApi { +} + +/** + * The scheme method must return an object with the following + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme) + */ +export interface ServerAuthSchemeObject { + + /** + * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object. + */ + api?: ServerAuthSchemeObjectApi; + + /** + * A lifecycle method function called for each incoming request configured with the authentication scheme. The + * method is provided with two special toolkit methods for returning an authenticated or an unauthenticate result: + * * h.authenticated() - indicate request authenticated successfully. + * * h.unauthenticated() - indicate request failed to authenticate. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + authenticate(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * A lifecycle method to authenticate the request payload. + * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad + * payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), + * authentication may still be successful if the route auth.payload configuration is set to 'optional'. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + payload?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. + * @param request the request object. + * @param h the ResponseToolkit + * @return the Lifecycle.ReturnValue + */ + response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; + + /** + * An object with the following keys: + * * payload + */ + options?: { + /** + * if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. + */ + payload?: boolean; + }; + +} diff --git a/types/hapi/definitions/server/server-auth.d.ts b/types/hapi/definitions/server/server-auth.d.ts new file mode 100644 index 0000000000..92cb0c4c98 --- /dev/null +++ b/types/hapi/definitions/server/server-auth.d.ts @@ -0,0 +1,82 @@ +import {Request, RouteOptionsAccess, ServerAuthScheme, Util} from "hapi"; + +/** + * An authentication configuration object using the same format as the route auth handler options. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ +export interface ServerAuthConfig extends RouteOptionsAccess { + +} + +export interface ServerAuth { + + /** + * An object where each key is an authentication strategy name and the value is the exposed strategy API. + * Available only when the authentication scheme exposes an API by returning an api key in the object + * returned from its implementation function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) + */ + api: Util.Dictionary; + + /** + * Contains the default authentication configuration is a default strategy was set via + * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). + */ + readonly settings: { + default: ServerAuthConfig; + } + + /** + * Sets a default strategy which is applied to every route where: + * @param options - one of: + * * a string with the default strategy name + * * an authentication configuration object using the same format as the route auth handler options. + * @return void. + * The default does not apply when a route config specifies auth as false, or has an authentication strategy + * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication + * config is applied to the defaults. + * Note that if the route has authentication configured, the default only applies at the time of adding the route, + * not at runtime. This means that calling server.auth.default() after adding a route with some authentication + * config will have no impact on the routes added prior. However, the default will apply to routes added + * before server.auth.default() is called if those routes lack any authentication config. + * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active + * authentication configuration of a route, use server.auth.lookup(request.route). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ + default(options: string | ServerAuthConfig): void; + + /** + * Registers an authentication scheme where: + * @param name the scheme name. + * @param scheme - the method implementing the scheme with signature function(server, options) where: + * * server - a reference to the server object the scheme is added to. + * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ + scheme(name: string, scheme: ServerAuthScheme): void; + + /** + * Registers an authentication strategy where: + * @param name - the strategy name. + * @param scheme - the scheme name (must be previously registered using server.auth.scheme()). + * @param options - scheme options based on the scheme requirements. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) + */ + strategy(name: string, scheme: string, options?: object): void; + + /** + * Tests a request against an authentication strategy where: + * @param strategy - the strategy name registered with server.auth.strategy(). + * @param request - the request object. + * @return Return value: the authentication credentials object if authentication was successful, otherwise throws an error. + * Note that the test() method does not take into account the route authentication configuration. It also does not + * perform payload authentication. It is limited to the basic strategy authentication execution. It does not + * include verifying scope, entity, or other route properties. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) + */ + test(strategy: string, request: Request): Promise; + +} + diff --git a/types/hapi/definitions/server/server-cache.d.ts b/types/hapi/definitions/server/server-cache.d.ts new file mode 100644 index 0000000000..730f5e8675 --- /dev/null +++ b/types/hapi/definitions/server/server-cache.d.ts @@ -0,0 +1,42 @@ +import * as catbox from "catbox"; +import {ServerOptionsCache} from "hapi"; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerCache { + + /** + * Provisions a cache segment within the server cache facility where: + * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: + * - `id` - the `id` string or object provided to the `get()` method. + * - `flags` - an object used to pass back additional flags to the cache where: + * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. + * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + * * staleTimeout - number of milliseconds to wait before checking if an item is stale. + * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. + * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. + * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. + * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. + * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). + * * cache - the cache name configured in server.cache. Defaults to the default cache. + * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. + * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. + * @return Catbox Policy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + (options: ServerOptionsCache): catbox.Policy; + + /** + * Provisions a server cache as described in server.cache where: + * @param options - same as the server cache configuration options. + * @return Return value: none. + * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) + */ + provision(options: ServerOptionsCache): Promise; + +} diff --git a/types/hapi/definitions/server/server-events.d.ts b/types/hapi/definitions/server/server-events.d.ts new file mode 100644 index 0000000000..b1e0c05405 --- /dev/null +++ b/types/hapi/definitions/server/server-events.d.ts @@ -0,0 +1,146 @@ +import * as Podium from "podium"; + +/** + * an event name string. + * an event options object. + * a podium emitter object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + */ +export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium; + +/** + * Object that it will be used in Event + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + */ +export interface ServerEventsApplicationObject { + /** the event name string (required). */ + name: string; + /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ + channels?: string | string[]; + /** if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). */ + clone?: boolean; + /** if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). */ + spread?: boolean; + /** if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. */ + tags?: boolean; + /** if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). */ + shared?: boolean; +} + +/** + * A criteria object with the following optional keys (unless noted otherwise): + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + */ +export interface ServerEventCriteria { + /** (required) the event name string. */ + name: string; + /** a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. */ + channels?: string | string[]; + /** if true, the data object passed to server.event.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ + clone?: boolean; + /** a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.events.once(). Defaults to no limit. */ + count?: number; + /** + * filter - the event tags (if present) to subscribe to which can be one of: + * * a tag string. + * * an array of tag strings. + * * an object with the following: + * * * tags - a tag string or array of tag strings. + * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). + */ + filter?: string | string[] | {tags: string | string[], all?: boolean}; + /** if true, and the data object passed to server.event.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). */ + spread?: boolean; + /** if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. Defaults to the event registration option (which defaults to false). */ + tags?: boolean; +} + +/** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events. + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ +export interface ServerEvents extends Podium { + + /** + * Emits a custom application event to all the subscribed listeners where: + * @param criteria - the event update criteria which must be one of: + * * the event name string. + * * an object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channel - the channel name string. + * * * tags - a tag string or array of tag strings. + * @param data - the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @return Return value: none. + * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) + */ + emit(criteria: string, data: any | Function): Promise; + emit(criteria: {name: string, channel?: string, tags?: string | string[]}, data: any): Promise; + + /** + * Subscribe to an event where: + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) + * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) + * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) + * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) + * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) + * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) + */ + on(criteria: string | ServerEventsApplicationObject | ServerEventCriteria, listener: Function): void; + + /** + * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) + */ + once(criteria: string | ServerEventsApplicationObject | ServerEventCriteria, listener: Function): void; + + /** + * Same as calling server.events.on() with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @return Return value: a promise that resolves when the event is emitted. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) + */ + once(criteria: string | ServerEventsApplicationObject | ServerEventCriteria): Promise; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeListener(name: string, listener: Podium.Listener): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeAllListeners(name: string): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + hasListeners(name: string): boolean; + +} diff --git a/types/hapi/definitions/server/server-ext.d.ts b/types/hapi/definitions/server/server-ext.d.ts new file mode 100644 index 0000000000..8bd29cbb18 --- /dev/null +++ b/types/hapi/definitions/server/server-ext.d.ts @@ -0,0 +1,146 @@ +import {Lifecycle, Server} from "hapi"; + +/** + * The extension point event name. The available extension points include the request extension points as well as the following server extension points: + * 'onPreStart' - called before the connection listeners are started. + * 'onPostStart' - called after the connection listeners are started. + * 'onPreStop' - called before the connection listeners are stopped. + * 'onPostStop' - called after the connection listeners are stopped. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ +export type ServerExtType = 'onRequest' | 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'| 'onPreResponse'; + +/** + * The extension point event name for Request + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ +export type ServerExtRequestType = 'onRequest'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsObject { + /** + * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + */ + type: ServerExtType; + /** + * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * server extension points: async function(server) where: + * * * server - the server object. + * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * request extension points: a lifecycle method. + */ + method: ServerExtPointFunction | ServerExtPointFunction[] | Function; + /** + * options - (optional) an object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + options?: ServerExtOptions; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsRequestObject { + /** + * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + * * 'onPostStop' - called after the connection listeners are stopped. + */ + type: ServerExtRequestType; + /** + * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * server extension points: async function(server) where: + * * * server - the server object. + * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * request extension points: a lifecycle method. + */ + method: Lifecycle.Method | Lifecycle.Method[]; + /** + * (optional) an object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + options?: ServerExtOptions; +} + +export interface ServerExtPointFunction { + (server: Server): void; +} + +/** + * An object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ +export interface ServerExtOptions { + /** + * a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + */ + before: string | string[]; + /** + * a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + */ + after: string | string[]; + /** + * a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + */ + bind: object; + /** + * if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + */ + sandbox?: 'server' | 'plugin'; +} + diff --git a/types/hapi/definitions/server/server-info.d.ts b/types/hapi/definitions/server/server-info.d.ts new file mode 100644 index 0000000000..399543e08e --- /dev/null +++ b/types/hapi/definitions/server/server-info.d.ts @@ -0,0 +1,55 @@ +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + * An object containing information about the server where: + */ +export interface ServerInfo { + + /** + * a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + */ + id: string; + + /** + * server creation timestamp. + */ + created: number; + + /** + * server start timestamp (0 when stopped). + */ + started: number; + + /** + * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules: + * * before the server has been started: the configured port value. + * * after the server has been started: the actual port assigned when no port is configured or was set to 0. + */ + port: number | string; + + /** + * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value. + */ + host: string; + + /** + * the active IP address the connection was bound to after starting. Set to undefined until the server has been + * started or when using a non TCP port (e.g. UNIX domain socket). + */ + address: undefined | string; + + /** + * the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + */ + protocol: 'http' | 'https' | 'socket'; + + /** + * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains + * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set + * to 0, the uri will not include a port component until the server is started. + */ + uri: string; + +} diff --git a/types/hapi/definitions/server/server-inject.d.ts b/types/hapi/definitions/server/server-inject.d.ts new file mode 100644 index 0000000000..99789febfe --- /dev/null +++ b/types/hapi/definitions/server/server-inject.d.ts @@ -0,0 +1,71 @@ +import {AuthCredentials, PluginsStates, Request} from "hapi"; +import * as Shot from "shot"; + +/** + * An object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested separately. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectOptions extends Shot.RequestOptions { + /** + * an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. + */ + credentials?: AuthCredentials; + /** + * (an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + */ + artifacts?: object; + /** + * sets the initial value of request.app, defaults to {}. + */ + app?: any; + /** + * sets the initial value of request.plugins, defaults to {}. + */ + plugins?: PluginsStates; + /** + * allows access to routes with config.isInternal set to true. Defaults to false. + */ + allowInternals?: boolean; +} + +/** + * A response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + * * request - the request object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectResponse extends Shot.ResponseObject { + /** + * the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + */ + result: object | undefined; + /** + * the request object. + */ + request: Request; +} diff --git a/types/hapi/definitions/server/server-method.d.ts b/types/hapi/definitions/server/server-method.d.ts new file mode 100644 index 0000000000..920560086a --- /dev/null +++ b/types/hapi/definitions/server/server-method.d.ts @@ -0,0 +1,64 @@ +import * as catbox from "catbox"; + +/** + * The method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export type ServerMethod = (...args: any[]) => Promise; + +/** + * The same cache configuration used in server.cache(). + * The generateTimeout option is required. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerMethodCache extends catbox.PolicyOptions { + generateTimeout: number | false; +} + +/** + * Configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export interface ServerMethodOptions { + /** + * a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. + */ + bind?: object; + /** + * the same cache configuration used in server.cache(). The generateTimeout option is required. + */ + cache?: ServerMethodCache; + /** + * a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). + */ + generateKey?: Function; +} + +/** + * An object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ +export interface ServerMethodConfigurationObject { + /** + * the method name. + */ + name: string; + /** + * the method function. + */ + method: ServerMethod; + /** + * (optional) settings. + */ + options?: ServerMethodOptions; +} diff --git a/types/hapi/definitions/server/server-options-cache.d.ts b/types/hapi/definitions/server/server-options-cache.d.ts new file mode 100644 index 0000000000..1e75ebe857 --- /dev/null +++ b/types/hapi/definitions/server/server-options-cache.d.ts @@ -0,0 +1,25 @@ +import * as Catbox from "catbox"; + +/** + * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, + * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) + */ +export interface ServerOptionsCache extends Catbox.PolicyOptions { + + /** a class, a prototype function, or a catbox engine object. */ + engine?: Catbox.EnginePrototypeOrObject; + + /** an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. */ + name?: string; + + /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */ + shared?: boolean; + + /** (optional) string used to isolate cached data. Defaults to 'hapi-cache'. */ + partition?: string; + + /** other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). */ + [s: string]: any; + +} diff --git a/types/hapi/definitions/server/server-options.d.ts b/types/hapi/definitions/server/server-options.d.ts new file mode 100644 index 0000000000..2f74c17bb4 --- /dev/null +++ b/types/hapi/definitions/server/server-options.d.ts @@ -0,0 +1,186 @@ +import * as http from "http"; +import * as https from "https"; +import * as catbox from "catbox"; +import {MimosOptions} from "mimos"; +import {PluginSpecificConfiguration, RouteOptions, ServerOptionsCache} from "hapi"; + +export interface ServerOptionsCompression { + minBytes: number; +} + +/** + * The server options control the behavior of the server object. Note that the options object is deeply cloned + * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on. + * All options are optionals. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options) + */ +export interface ServerOptions { + + /** + * Default value: '0.0.0.0' (all available network interfaces). + * Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to restrict the server to only those coming from the same host. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress) + */ + address?: string; + + /** + * Default value: {}. + * Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available anywhere a server reference is provided. + * Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) + */ + app?: any; + + /** + * Default value: true. + * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework. + * Cannot be set to true along with a port value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten) + */ + autoListen?: boolean; + + /** + * Default value: { engine: require('catbox-memory' }. + * Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. + * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. + * The server cache configuration only defines the storage container itself. The configuration can be assigned one or more (array): + * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. + * * a configuration object with the following: + * * * engine - a class, a prototype function, or a catbox engine object. + * * * name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * * * shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'. + * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) + */ + cache?: catbox.EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; + + /** + * Default value: { minBytes: 1024 }. + * Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server. + */ + compression?: boolean | ServerOptionsCompression; + + /** + * Default value: { request: ['implementation'] }. + * Determines which logged events are sent to the console. This should only be used for development and does not affect which events are actually logged internally and recorded. Set to false to disable all console logging, or to an object with: + * * log - a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. Defaults to no output. + * * request - a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. To display all request logs, set it to '*'. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. + * For example, to display all errors, set the log or request to ['error']. To turn off all output set the log or request to false. To display all server logs, set the log or request to '*'. To disable all debug information, set debug to false. + */ + debug?: false | { + log?: string[] | false; + request?: string[] | false; + }; + + /** + * Default value: the operating system hostname and if not available, to 'localhost'. + * The public hostname or IP address. Used to set server.info.host and server.info.uri and as address is none provided. + */ + host?: string; + + /** + * Default value: none. + * An optional node HTTP (or HTTPS) http.Server object (or an object with a compatible interface). + * If the listener needs to be manually started, set autoListen to false. + * If the listener uses TLS, set tls to true. + */ + listener?: http.Server; + + /** + * Default value: { sampleInterval: 0 }. + * Server excessive load handling limits where: + * * sampleInterval - the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). + * * maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + * * maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + * * maxEventLoopDelay - maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). + */ + load?: { + /** the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). */ + sampleInterval?: number; + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes?: number; + /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).*/ + maxRssBytes?: number; + /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).*/ + maxEventLoopDelay?: number; + }; + + /** + * Default value: none. + * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime): + * * override - an object hash that is merged into the built in mime information specified here. Each key value pair represents a single mime object. Each override value must contain: + * * key - the lower-cased mime-type string (e.g. 'application/javascript'). + * * value - an object following the specifications outlined here. Additional values include: + * * * type - specify the type value of result objects, defaults to key. + * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime) + */ + mime?: MimosOptions; + + /** + * Default value: {}. + * Plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. + */ + plugins?: PluginSpecificConfiguration; + + /** + * Default value: 0 (an ephemeral port). + * The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to server.info.port). + * If port is a string containing a '/' character, it is used as a UNIX domain socket path. If it starts with '\.\pipe', it is used as a Windows named pipe. + */ + port?: number | string; + + /** + * Default value: { isCaseSensitive: true, stripTrailingSlash: false }. + * Controls how incoming request URIs are matched against the routing table: + * * isCaseSensitive - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. + * * stripTrailingSlash - removes trailing slashes on incoming paths. Defaults to false. + */ + router?: { + isCaseSensitive?: boolean; + stripTrailingSlash?: boolean; + }; + + /** + * Default value: none. + * A route options object used as the default configuration for every route. + */ + routes?: RouteOptions; + + /** + Default value: + { + strictHeader: true, + ignoreErrors: false, + isSecure: true, + isHttpOnly: true, + isSameSite: 'Strict', + encoding: 'none' + } + Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object. + */ + // TODO I am not sure if I need to use all the server.state() definition (like the default value) OR only the options below. The v16 use "any" here. + // state?: ServerStateCookieOptions; + state?: { + strictHeader?: boolean, + ignoreErrors?: boolean, + isSecure?: boolean, + isHttpOnly?: boolean, + isSameSite?: false | 'Strict' | 'Lax', + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron' + }; + + /** + * Default value: none. + * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation. + */ + tls?: true | https.RequestOptions; + + /** + * Default value: constructed from runtime server information. + * The full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the server server.info.uri, otherwise constructed from the server settings. + */ + uri?: string; + +} diff --git a/types/hapi/definitions/server/server-realm.d.ts b/types/hapi/definitions/server/server-realm.d.ts new file mode 100644 index 0000000000..eb921a1699 --- /dev/null +++ b/types/hapi/definitions/server/server-realm.d.ts @@ -0,0 +1,35 @@ +import {PluginsStates} from "hapi"; + +/** + * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. + * For example, a plugin can set a default file path for local resources without breaking other plugins' configured paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). + * + * https://github.com/hapijs/hapi/blob/master/API.md#server.realm + */ +export interface ServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ + modifiers: { + /** routes preferences: */ + route: { + /** the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include the trailing slash. */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + } + }; + /** the realm of the parent server object, or null for the root server. */ + parent: ServerRealm | null; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** the plugin options object passed at registration. */ + pluginOptions: object; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: PluginsStates; + /** settings overrides */ + settings: { + files: { + relativeTo: string; + }; + bind: object; + }; +} diff --git a/types/hapi/definitions/server/server-register.d.ts b/types/hapi/definitions/server/server-register.d.ts new file mode 100644 index 0000000000..313a3c164e --- /dev/null +++ b/types/hapi/definitions/server/server-register.d.ts @@ -0,0 +1,62 @@ +import {Plugin} from "hapi"; + +/** + * Registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ +export interface ServerRegisterOptions { + /** + * if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. + */ + once?: boolean; + /** + * modifiers applied to each route added by the plugin: + */ + routes?: { + /** + * string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + */ + prefix: string; + /** + * virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + */ + vhost: string | string[]; + }; +} + +/** + * An object with the following: + * * plugin - a plugin object. + * * options - (optional) options passed to the plugin during registration. + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + * + * The type parameter T is the type of the plugin configuration options. + */ +export interface ServerRegisterPluginObject extends ServerRegisterOptions { + /** + * a plugin object. + */ + plugin: Plugin; + /** + * options passed to the plugin during registration. + */ + options?: T; +} + +export interface ServerRegisterPluginObjectArray extends Array | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | ServerRegisterPluginObject | undefined> { + 0: ServerRegisterPluginObject; + 1?: ServerRegisterPluginObject; + 2?: ServerRegisterPluginObject; + 3?: ServerRegisterPluginObject; + 4?: ServerRegisterPluginObject; + 5?: ServerRegisterPluginObject; + 6?: ServerRegisterPluginObject; +} diff --git a/types/hapi/definitions/server/server-route.d.ts b/types/hapi/definitions/server/server-route.d.ts new file mode 100644 index 0000000000..7c9087bddd --- /dev/null +++ b/types/hapi/definitions/server/server-route.d.ts @@ -0,0 +1,55 @@ +import {Lifecycle, RouteOptions, Server, Util} from "hapi"; + +export interface ServerRouteConfig { +} + +/** + * A route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ +export interface ServerRoute { + + /** + * (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters) + */ + path: string; + + /** + * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. + */ + method: Util.HTTP_METHODS_PARTIAL | Util.HTTP_METHODS_PARTIAL[] | string | string[]; + + /** + * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. + */ + vhost?: string | string[]; + + /** + * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + */ + handler?: Lifecycle.Method | object; + + /** + * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. + */ + options?: RouteOptions | ((server: Server) => RouteOptions); + + /** + * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + */ + rules?: object; + + /** + * Missing documentation. Exist only in examples and test files. + */ + config?: ServerRouteConfig; + +} diff --git a/types/hapi/definitions/server/server-state-options.d.ts b/types/hapi/definitions/server/server-state-options.d.ts new file mode 100644 index 0000000000..f95eb4b794 --- /dev/null +++ b/types/hapi/definitions/server/server-state-options.d.ts @@ -0,0 +1,63 @@ +import { Request } from "hapi"; +import { SealOptions, SealOptionsSub } from "iron"; + +/** + * Optional cookie settings + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ +export interface ServerStateCookieOptions { + /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */ + ttl?: number | null; + /** sets the 'Secure' flag. Defaults to true. */ + isSecure?: boolean; + /** sets the 'HttpOnly' flag. Defaults to true. */ + isHttpOnly?: boolean; + /** + * sets the 'SameSite' flag. The value must be one of: + * * false - no flag. + * * 'Strict' - sets the value to 'Strict' (this is the default value). + * * 'Lax' - sets the value to 'Lax'. + */ + isSameSite?: false | 'Strict' | 'Lax'; + /** the path scope. Defaults to null (no path). */ + path?: string | null; + /** the domain scope. Defaults to null (no domain). */ + domain?: string | null; + /** + * if present and the cookie was not received from the client or explicitly set by the route handler, the + * cookie is automatically added to the response with the provided value. The value can be + * a function with signature async function(request) where: + */ + autoValue?(request: Request): void; + /** + * encoding performs on the provided value before serialization. Options are: + * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + * * 'base64' - string value is encoded using Base64. + * * 'base64json' - object value is JSON-stringified then encoded using Base64. + * * 'form' - object value is encoded using the x-www-form-urlencoded method. + * * 'iron' - Encrypts and sign the value using iron. + */ + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'; + /** + * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean + * to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are: + * * integrity - algorithm options. Defaults to require('iron').defaults.integrity. + * * password - password used for HMAC key generation (must be at least 32 characters long). + */ + sign?: { + integrity?: SealOptionsSub; + password: string; + }; + /** password used for 'iron' encoding (must be at least 32 characters long). */ + password?: string; + /** options for 'iron' encoding. Defaults to require('iron').defaults. */ + iron?: SealOptions; + /** if true, errors are ignored and treated as missing cookies. */ + ignoreErrors?: boolean; + /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */ + clearInvalid?: boolean; + /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */ + strictHeader?: boolean; + /** used by proxy plugins (e.g. h2o2). */ + passThrough?: any; +} diff --git a/types/hapi/definitions/server/server-state.d.ts b/types/hapi/definitions/server/server-state.d.ts new file mode 100644 index 0000000000..119e06073c --- /dev/null +++ b/types/hapi/definitions/server/server-state.d.ts @@ -0,0 +1,67 @@ +import { ServerStateCookieOptions, Util } from "hapi"; + +/** + * A single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + */ +export interface ServerStateFormat { + name: string; + value: string; + options: ServerStateCookieOptions; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate) + */ +export interface ServerState { + /** + * The server cookies manager. + * Access: read only and statehood public interface. + */ + readonly states: object; + + /** + * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state). + */ + readonly settings: ServerStateCookieOptions; + + /** + * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the + * cookie name and value is the configuration object. + */ + readonly cookies: object; + + /** + * An array containing the names of all configued cookies. + */ + readonly names: string[]; + + /** + * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). + */ + add(name: string, options?: ServerStateCookieOptions): void; + + /** + * Formats an HTTP 'Set-Cookie' header based on the server.options.state where: + * @param cookies - a single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + * @return Return value: a header string. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formating (e.g. when headers are set manually). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies) + */ + format(cookies: ServerStateFormat | ServerStateFormat[]): string; + + /** + * Parses an HTTP 'Cookies' header based on the server.options.state where: + * @param header - the HTTP header. + * @return Return value: an object where each key is a cookie name and value is the parsed cookie. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) + */ + parse(header: string): Util.Dictionary; +} diff --git a/types/hapi/definitions/server/server.d.ts b/types/hapi/definitions/server/server.d.ts new file mode 100644 index 0000000000..0133a35775 --- /dev/null +++ b/types/hapi/definitions/server/server.d.ts @@ -0,0 +1,563 @@ +import * as http from "http"; +import * as zlib from "zlib"; +import * as Podium from "podium"; +import { + ApplicationState, + Lifecycle, + PayloadCompressionDecoderSettings, + Plugin, + PluginsListRegistered, + Request, + RequestRoute, + ResponseToolkit, + RouteCompressionEncoderSettings, + ServerAuth, + ServerCache, + ServerEvents, + ServerEventsApplication, + ServerExtEventsObject, + ServerExtEventsRequestObject, + ServerExtOptions, + ServerExtPointFunction, + ServerExtType, + ServerInfo, + ServerInjectOptions, + ServerInjectResponse, + ServerMethod, + ServerMethodConfigurationObject, + ServerMethodOptions, + ServerOptions, + ServerRealm, + ServerRegisterOptions, + ServerRegisterPluginObject, + ServerRegisterPluginObjectArray, + ServerRoute, + ServerState, + ServerStateCookieOptions, + Util, +} from "hapi"; + +/** + * The server object is the main application container. The server manages all incoming requests along with all + * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) + */ +export class Server extends Podium { + + /** + * Creates a new server object + * @constructor + */ + constructor(); + + /** + * Creates a new server object where: + * @constructor + * @param options server configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions) + */ + constructor(options: ServerOptions); + + /** + * Provides a safe place to store server-specific run-time application data without potential conflicts with + * the framework internals. The data can be accessed whenever the server is accessible. + * Initialized with an empty object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) + */ + app?: ApplicationState; + + /** + * Server Auth: properties and methods + */ + auth: ServerAuth; + + /** + * Provides access to the decorations already applied to various framework interfaces. The object must not be + * modified directly, but only through server.decorate. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations) + */ + readonly decorations: { + /** + * decorations on the request object. + */ + request: string[], + /** + * decorations on the response toolkit. + */ + toolkit: string[], + /** + * decorations on the server object. + */ + server: string[] + }; + + /** + * Register custom application events where: + * @param events must be one of: + * * an event name string. + * * an event options object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). + * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). + * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). + * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). + * * a podium emitter object. + * * an array containing any of the above. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + event(events: ServerEventsApplication | ServerEventsApplication[]): void; + + /** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + events: ServerEvents; + + /** + * An object containing information about the server where: + * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + * * created - server creation timestamp. + * * started - server start timestamp (0 when stopped). + * * port - the connection port based on the following rules: + * * host - The host configuration value. + * * address - the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). + * * protocol - the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + */ + readonly info: ServerInfo; + + /** + * Access: read only and listener public interface. + * The node HTTP server object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener) + */ + listener: http.Server; + + /** + * An object containing the process load metrics (when load.sampleInterval is enabled): + * * eventLoopDelay - event loop delay milliseconds. + * * heapUsed - V8 heap usage. + * * rss - RSS memory usage. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload) + */ + readonly load: { + /** + * event loop delay milliseconds. + */ + eventLoopDelay: number; + /** + * V8 heap usage. + */ + heapUsed: number; + /** + * RSS memory usage. + */ + rss: number; + }; + + /** + * Server methods are functions registered with the server and used throughout the application as a common utility. + * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request + * handlers without having to create a common module. + * sever.methods is an object which provides access to the methods registered via server.method() where each + * server method name is an object property. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods + */ + readonly methods: Util.Dictionary; + + /** + * Provides access to the server MIME database used for setting content-type information. The object must not be + * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime) + */ + mime: any; + + /** + * An object containing the values exposed by each registered plugin where each key is a plugin name and the values + * are the exposed properties by each plugin using server.expose(). Plugins may set the value of + * the server.plugins[name] object directly or via the server.expose() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) + */ + plugins: any; + + /** + * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When + * registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm + * container specific to that registration. It allows each plugin to maintain its own settings without leaking + * and affecting other plugins. + * For example, a plugin can set a default file path for local resources without breaking other plugins' configured + * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by + * routes and extensions added at the same level (server root or plugin). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) + */ + readonly realm: ServerRealm; + + /** + * An object of the currently registered plugins where each key is a registered plugin name and the value is + * an object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ + readonly registrations: PluginsListRegistered; + + /** + * The server configuration object after defaults applied. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings) + */ + readonly settings: ServerOptions; + + /** + * The server cookies manager. + * Access: read only and statehood public interface. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates) + */ + readonly states: ServerState; + + /** + * A string indicating the listener type where: + * * 'socket' - UNIX domain socket or Windows named pipe. + * * 'tcp' - an HTTP listener. + */ + readonly type: 'socket' | 'tcp'; + + /** + * The hapi module version number. + */ + readonly version: string; + + /** + * Sets a global context used as the default bind object when adding a route or an extension where: + * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context. + * @return Return value: none. + * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) + */ + bind(context: object): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + cache: ServerCache; + + /** + * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the decoder name string. + * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the return value is an object compatible with the output of node's zlib.createGunzip(). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) + */ + decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void; + + /** + * Extends various framework interfaces with custom methods where: + * @param type - the interface being decorated. Supported types: + * 'handler' - adds a new handler type to be used in routes handlers. + * 'request' - adds methods to the Request object. + * 'server' - adds methods to the Server object. + * 'toolkit' - adds methods to the response toolkit. + * @param property - the object decoration key name. + * @param method - the extension function or other value. + * @param options - (optional) supports the following optional settings: + * apply - when the type is 'request', if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. + * extend - if true, overrides an existing decoration. The method must be a function with the signature function(existing) where: + * existing - is the previously set decoration method value. + * must return the new decoration function or value. + * cannot be used to extend handler decorations. + * @return void; + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) + */ + decorate(type: 'request', property: string, method: ((request: Request) => Function), options?: {apply: true; extend: false} ): void; + decorate(type: 'handler' | 'request' | 'server' | 'toolkit', property: string, method: Function, options?: {apply: boolean; extend: boolean} ): void; + + /** + * Used within a plugin to declare a required dependency on other plugins where: + * @param dependencies - a single string or an array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is initialized or started. + * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. The function signature is async function(server) where: + * server - the server the dependency() method was called on. + * @return Return value: none. + * The after method is identical to setting a server extension point on 'onPreStart'. + * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). + * The method does not provide version dependency which should be implemented using npm peer dependencies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) + */ + dependency(dependencies: string | string[], after?: ((server: Server) => void)): void; + + /** + * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the encoder name string. + * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object compatible with the output of node's zlib.createGzip(). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ + encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void; + + /** + * Used within a plugin to expose a property via server.plugins[name] where: + * @param key - the key assigned (server.plugins[name][key]). + * @param value - the value assigned. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) + */ + expose(key: string, value: any): void; + + /** + * Merges an object into to the existing content of server.plugins[name] where: + * @param obj - the object merged into the exposed properties container. + * @return Return value: none. + * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method + * for exposing large objects that may be expensive to clone or singleton objects such as database client + * objects. Instead favor server.expose(key, value), which only copies a reference to value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) + */ + expose(obj: object): void; + + /** + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ + ext(events: ServerExtEventsObject | ServerExtEventsObject[]): void; + ext(events: ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; + + /** + * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) + */ + ext(event: ServerExtType, method: ServerExtPointFunction | Lifecycle.Method | Function, options?: ServerExtOptions): void; + + /** + * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and + * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and + * other event listeners will get confused by repeated attempts to start the server or make assumptions about the + * healthy state of the environment. It is recommended to abort the process when the server fails to start properly. + * If you must try to resume after an error, call server.stop() first to reset the server state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) + */ + initialize(): Promise; + + /** + * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead and limitations of the network stack. + * The method utilizes the shot module for performing injections, with some additional options and response properties: + * @param options - can be assigned a string with the requested URI, or an object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested separately. + * @return Return value: a response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + * * request - the request object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + */ + inject(options: string | ServerInjectOptions): Promise; + + /** + * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: + * @param tags - (required) a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) + */ + log(tags: string | string[], data?: string | object | (() => any), timestamp?: number): void; + + /** + * Looks up a route configuration where: + * @param id - the route identifier. + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid) + */ + lookup(id: string): RequestRoute | null; + + /** + * Looks up a route configuration where: + * @param method - the HTTP method (e.g. 'GET', 'POST'). + * @param path - the requested path (must begin with '/'). + * @param host - (optional) hostname (to match against routes with vhost). + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) + */ + match(method: Util.HTTP_METHODS, path: string, host?: string): RequestRoute | null; + + /** + * Registers a server method where: + * @param name - a unique method name used to invoke the method via server.methods[name]. + * @param method - the method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * @param options - (optional) configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). + * @return Return value: none. + * Method names can be nested (e.g. utils.users.get) which will automatically create the full path under server.methods (e.g. accessed via server.methods.utils.users.get). + * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ + method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; + + /** + * Registers a server method function as described in server.method() using a configuration object where: + * @param methods - an object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ + method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void; + + /** + * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + * @param relativeTo - the path prefix added to any relative file path starting with '.'. + * @return Return value: none. + * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files.relativeTo settings is used. The path only applies to routes added after it has been set. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto) + */ + path(relativeTo: string): void; + + /** + * Registers a plugin where: + * @param plugins - one or an array of: + * * a plugin object. + * * an object with the following: + * * * plugin - a plugin object. + * * * options - (optional) options passed to the plugin during registration. + * * * once, routes - (optional) plugin-specific registration options as defined below. + * @param options - (optional) registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ + register(plugins: Plugin | Plugin[], options?: ServerRegisterOptions): Promise; + register(plugins: ServerRegisterPluginObject | ServerRegisterPluginObjectArray, options?: ServerRegisterOptions): Promise; + + /** + * Adds a route where: + * @param route - a route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * @return Return value: none. + * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ + route(route: ServerRoute | ServerRoute[]): void; + + /** + * Defines a route rules processor for converting route rules object into route configuration where: + * @param processor - a function using the signature function(rules, info) where: + * * rules - + * * info - an object with the following properties: + * * * method - the route method. + * * * path - the route path. + * * * vhost - the route virtual host (if any defined). + * * returns a route config object. + * @param options - optional settings: + * * validate - rules object validation: + * * * schema - joi schema. + * * * options - optional joi validation options. Defaults to { allowUnknown: true }. + * Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin override the config generated by the root processor if they overlap. The route config overrides the rules config if the overlap. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) + */ + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options?: {validate: object}): void; // TODO needs implementation + + /** + * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. + * If a started server is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart) + */ + start(): Promise; + + /** + * HTTP state management uses client cookies to persist a state across multiple requests. + * @param name - the cookie name string. + * @param options - are the optional cookie settings + * @return Return value: none. + * State defaults can be modified via the server default state configuration option. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ + state(name: string, options?: ServerStateCookieOptions): void; + + /** + * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + * @param options - (optional) object with: + * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions) + */ + stop(options?: {timeout: number}): Promise; + + /** + * Returns a copy of the routing table where: + * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + * @return Return value: an array of routes where each route contains: + * * settings - the route config with defaults applied. + * * method - the HTTP method in lower case. + * * path - the route path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) + */ + table(host?: string): {settings: ServerRoute; method: Util.HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; // TODO I am not sure if the ServerRoute is the object expected here + +} diff --git a/types/hapi/definitions/util/common.d.ts b/types/hapi/definitions/util/common.d.ts new file mode 100644 index 0000000000..3873cc6900 --- /dev/null +++ b/types/hapi/definitions/util/common.d.ts @@ -0,0 +1,8 @@ + +/** + * User-extensible type for application specific state. + */ +export interface ApplicationState { +} + +export type PeekListener = (chunk: string, encoding: string) => void; \ No newline at end of file diff --git a/types/hapi/definitions/util/json.d.ts b/types/hapi/definitions/util/json.d.ts new file mode 100644 index 0000000000..116f6bdf9a --- /dev/null +++ b/types/hapi/definitions/util/json.d.ts @@ -0,0 +1,27 @@ +export namespace Json { + + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; + + /** + * Any value greater than 10 is truncated. + */ + export type StringifySpace = number | string; + + /** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + export interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + /** tring suffix added after conversion to JSON string. Defaults to no suffix. **/ + suffix?: string; + /** calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. **/ + escape?: boolean; + } + +} diff --git a/types/hapi/definitions/util/lifecycle.d.ts b/types/hapi/definitions/util/lifecycle.d.ts new file mode 100644 index 0000000000..35f347dcd5 --- /dev/null +++ b/types/hapi/definitions/util/lifecycle.d.ts @@ -0,0 +1,59 @@ +import * as Boom from "boom"; +import * as stream from "stream"; +import {Request, ResponseToolkit} from "hapi"; + +export namespace Lifecycle { + + /** + * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: + * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods + * provided by the developer and executed by the framework. + * Each lifecycle method is a function with the signature await function(request, h, [err]) where: + * * request - the request object. + * * h - the response toolkit the handler must call to set a response and return control back to the framework. + * * err - an error object availble only when the method is used as a failAction value. + */ + export interface Method { + (request: Request, h: ResponseToolkit): ReturnValue; + (request: Request, h: ResponseToolkit, err: Error): ReturnValue; + } + + /** + * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns + * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. + * The return value must be one of: + * * Plain value: null, string, number, boolean + * * Buffer object + * * Error object: plain Error OR a Boom object. + * * Stream object + * * any object or array + * * a toolkit signal: + * * a toolkit method response: + * * a promise object that resolve to any of the above values + * For more info please [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + */ + export type ReturnValue = ReturnValueTypes | (Promise); + export type ReturnValueTypes = + (null | string | number | boolean) | + (Buffer) | + (Error | Boom.BoomError) | + (stream.Stream) | + (object | object[]) | + Object | + ResponseToolkit; + + /** + * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be configured to perform another action. When supported the failAction option supports the following values: + * * 'error' - return the error object as the response. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action and continue processing the request. + * * a lifecycle method with the signature async function(request, h, err) where: + * * * request - the request object. + * * * h - the response toolkit. + * * * err - the error object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration) + */ + export type FailAction = 'error' | 'log' | 'ignore' | Method; + +} + diff --git a/types/hapi/definitions/util/util.d.ts b/types/hapi/definitions/util/util.d.ts new file mode 100644 index 0000000000..fc9bc97a7c --- /dev/null +++ b/types/hapi/definitions/util/util.d.ts @@ -0,0 +1,8 @@ +export namespace Util { + interface Dictionary { + [key: string]: T; + } + type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; + type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_LOWERCASE; + type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; +} diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index a97a9f1edb..46d4d07ca3 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for hapi 16.1 +// Type definitions for hapi 17.0 // Project: https://github.com/hapijs/hapi -// Definitions by: Jason Swearingen , AJP +// Definitions by: Marc Bornträger +// Rafael Souza Fijalkowski +// Justin Simms // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -12,2712 +14,58 @@ + + + + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + * - * - * Removal of IPromise replaced with Promise - * Removal of IReplyStrict<> - * Removal of IReply replaced with different interfaces like: - * ReplyWithContinue - * ReplyNoContinue, etc. - * Renaming of all interfaces to remove preceding I in preparation of dtslint - */ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ /// -import Events = require("events"); -import stream = require("stream"); -import http = require("http"); -import https = require("https"); -import url = require("url"); -import zlib = require("zlib"); -import domain = require("domain"); - -import * as Boom from 'boom'; -import { - ValidationOptions as JoiValidationOptions, - SchemaMap as JoiSchemaMap, - Schema as JoiSchema, -} from 'joi'; -// TODO check JoiValidationObject is correct for "a Joi validation object" -type JoiValidationObject = JoiSchema | JoiSchemaMap | (JoiSchema | JoiSchemaMap)[]; - -import * as Catbox from 'catbox'; -import { MimosOptions } from 'mimos'; -import Podium = require('podium'); -import * as Shot from 'shot'; - -export interface Dictionary { - [key: string]: T; -} - -/** - * Server - * The Server object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). - * [See docs](https://hapijs.com/api/16.1.1#server) - * [See docs](https://hapijs.com/api/16.1.1#server-properties) - * [See docs](https://hapijs.com/api/16.1.1#server-events) - */ -export class Server extends Podium { - /** - * Creates a new Server object - */ - constructor(options?: ServerOptions); - - /** - * Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. - * [See docs](https://hapijs.com/api/16.1.1#serverapp) - */ - app?: any; - /** - * An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. - * [See docs](https://hapijs.com/api/16.1.1#serverconnections) - */ - connections: ServerConnection[]; - /** - * When the server contains exactly one connection, info is an object containing information about the sole connection - * When the server contains more than one connection, each server.connections array member provides its own connection.info. - * [See docs](https://hapijs.com/api/16.1.1#serverinfo) - */ - info: ServerConnectionInfo | null; - /** - * An object containing the process load metrics (when load.sampleInterval is enabled): - * [See docs](https://hapijs.com/api/16.1.1#serverload) - */ - load: { - /** event loop delay milliseconds. */ - eventLoopDelay: number; - /** V8 heap usage. */ - heapUsed: number; - /** RSS memory usage. */ - rss: number; - }; - /** - * When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. - * When the server contains more than one connection, each server.connections array member provides its own connection.listener. - * [See docs](https://hapijs.com/api/16.1.1#serverlistener) - */ - listener: ServerListener | null; - /** - * An object providing access to the server methods cs://hapijs.com/api/16.1.1#servermethodname-method-options} where each server method name is an object property. - * [See docs](https://hapijs.com/api/16.1.1#servermethods) - */ - methods: Dictionary; - /** - * Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. - * [See docs](https://hapijs.com/api/16.1.1#servermime) - */ - readonly mime: {path(path: string): {type: string}}; - /** - * An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. - * [See docs](https://hapijs.com/api/16.1.1#serverplugins) - */ - plugins: PluginsStates; - /** - * The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. - * [See docs](https://hapijs.com/api/16.1.1#serverrealm) - */ - readonly realm: ServerRealm; - /** - * When the server contains exactly one connection, registrations is an object where each key is a registered plugin name - * When the server contains more than one connection, each server.connections array member provides its own connection.registrations. - * TODO check and offer PR to update Hapi docs: Assuming readonly. - * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) - */ - readonly registrations: ServerRegisteredPlugins; - /** - * The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()). - * TODO, check and offer PR to update Hapi docs: Marked as optional as presumably root server does not reference itself. - * [See docs](https://hapijs.com/api/16.1.1#serverroot) - */ - root?: Server; - /** - * The server configuration object after defaults applied. - * [See docs](https://hapijs.com/api/16.1.1#serversettings) - */ - settings: ServerOptions; - /** - * The hapi module version number. - * [See docs](https://hapijs.com/api/16.1.1#serverversion) - */ - version: string; - - /** - * [See docs](https://hapijs.com/api/16.1.1#serverauthapi) - * [See docs](https://hapijs.com/api/16.1.1#serverauthdefaultoptions) - * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) - * [See docs](https://hapijs.com/api/16.1.1#serverauthstrategyname-scheme-mode-options) - * [See docs](https://hapijs.com/api/16.1.1#serverauthteststrategy-request-next) - */ - auth: ServerAuth; - - /** - * Sets a global context used as the default bind object when adding a route or an extension - * When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. - * @param context the object used to bind this in handler and extension methods. - * [See docs](https://hapijs.com/api/16.1.1#serverbindcontext) - */ - bind(context: any): void; - /** - * [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) - * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) - */ - cache: ServerCacheMethod; - /** - * Adds an incoming server connection - * Returns a server object with the new connections selected. - * Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()) - * Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. - * - * [See docs](https://hapijs.com/api/16.1.1#serverconnectionoptions) for various advantage topics covering usage and caveats around use of the function in plugin register(), connectionless plugins calling connection(), etc. - * @param connection a connection configuration object or array of objects - */ - connection(options?: ServerConnectionOptions[]): Server; - connection(options?: ServerConnectionOptions): Server; - // connection: (options: ServerConnectionOptions[] | ServerConnectionOptions) => Server; - /** - * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' - * [See docs](https://hapijs.com/api/16.1.1#serverdecoderencoding-decoder) - * @param encoding the decoder name string. - * @param decoder a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the return value is an object compatible with the output of node's zlib.createGunzip(). - */ - decoder(encoding: string, decoder: ((options: CompressionDecoderSettings) => zlib.Gunzip)): void; - /** - * Extends various framework interfaces with custom methods - * Note that decorations apply to the entire server and all its connections regardless of current selection. - * [See docs](https://hapijs.com/api/16.1.1#serverdecoratetype-property-method-options) - * - * NOTE: it's not possible to type the result of this action. - * It's advised that in a custom definition file, you extend the ReplyNoContinue - * and ReplyWithContinue functions. See Inert `.file` for an example. - * Or if it is not part of a library / plugin then you use a namespace within - * your code to type the request, server and or reply. See - * [tests/server/decorate.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/hapi/tests/server/decorate.ts) - * for examples. - * @param type the interface being decorated. Supported types: - * * 'request' - adds methods to the Request object. - * * 'reply' - adds methods to the reply interface. - * * 'server' - adds methods to the Server object. - * @param property the object decoration key name. - * @param method the extension function or other value. - * @param options if the type is 'request', supports the following optional settings: - * * apply - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. - */ - decorate(type: 'request' | 'reply' | 'server', property: string, method: Function): void; - decorate(type: 'request', property: string, method: Function, options?: {apply: false}): void; - decorate(type: 'request', property: string, method: (request: Request) => Function, options: {apply: true}): void; - /** - * The server.decorate('server', ...) method can modify this prototype/interface. - * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts - * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) - */ - // [index: string]: any; - /** - * Used within a plugin to declare a required dependency on other plugins - * The after method is identical to setting a server extension point on 'onPreStart'. Connectionless plugins (those with attributes.connections set to false) can only depend on other connectionless plugins (server initialization will fail even of the dependency is loaded but is not connectionless). - * Dependencies can also be set via the register attributes property (does not support setting after). - * [See docs](https://hapijs.com/api/16.1.1#serverdependencydependencies-after) - * @param dependencies a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is initialized or started. Does not provide version dependency which should be implemented using npm peer dependencies. - * @param after an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) - */ - dependency(dependencies: string | string[], after?: AfterDependencyLoadCallback): void; - /** - * Emits a custom application event update to all the subscribed listeners - * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. - * [See docs](https://hapijs.com/api/16.1.1#serveremitcriteria-data-callback) - * @param criteria the event update criteria which if an object can have the following optional keys (unless noted otherwise): - * * name - the event name string (required). - * * channel - the channel name string. - * * tags - a tag string or array of tag strings. - * @param data the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. - * @param callback an optional callback method invoked when all subscribers have been notified using the signature function(). The callback is called only after all the listeners have been notified, including any event updates emitted earlier (the order of event updates are guaranteed to be in the order they were emitted). - */ - emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any, callback?: () => void): void; - /** - * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' - * [See docs](https://hapijs.com/api/16.1.1#serverencoderencoding-encoder) - * @param encoding the encoder name string. - * @param encoder a function using the signature function(options) where options are the encoding specific options configured in the route compression configuration option, and the return value is an object compatible with the output of node's zlib.createGzip(). - */ - encoder(encoding: string, encoder: ((options: CompressionEncoderSettings) => zlib.Gzip)): void; - /** - * Register custom application events - * [See docs](https://hapijs.com/api/16.1.1#servereventevents) - * @param events see ApplicationEvent - */ - event(events: ApplicationEvent[]): void; - event(events: ApplicationEvent): void; - /** - * Used within a plugin to expose a property via server.plugins[name] - * [See docs](https://hapijs.com/api/16.1.1#serverexposekey-value) - * @param key the key assigned (server.plugins[name][key]). - * @param value the value assigned. - */ - expose(key: string, value: any): void; - /** - * Merges an object into to the existing content of server.plugins[name] - * Note that all properties of obj are deeply cloned into server.plugins[name], so you should avoid using this method for exposing large objects that may be expensive to clone or singleton objects such as database client objects. Instead favor the server.expose(key, value) form, which only copies a reference to value. - * [See docs](https://hapijs.com/api/16.1.1#serverexposeobj) - * @param obj the object merged into the exposed properties container. - */ - expose(obj: Object): void; - /** - * Registers an extension function in one of the available extension points - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) - * @param events see @ServerExtConfigurationObject - */ - ext(events: ServerStartExtConfigurationObject): void; - ext(events: ServerStartExtConfigurationObject[]): void; - ext(events: ServerRequestExtConfigurationObjectWithRequest): void; - ext(events: ServerRequestExtConfigurationObjectWithRequest[]): void; - /** - * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. - * [See docs](https://hapijs.com/api/16.1.1#serverextevent-method-options) - * @param event the extension point event name. - * @param method a function or an array of functions to be executed at a specified point during request processing. - * @param options - */ - ext(event: ServerStartExtPoints, method: ServerExtFunction[], options?: ServerExtOptions): void; - ext(event: ServerStartExtPoints, method: ServerExtFunction, options?: ServerExtOptions): void; - ext(event: ServerRequestExtPoints, method: ServerExtRequestHandler[], options?: ServerExtOptions): void; - ext(event: ServerRequestExtPoints, method: ServerExtRequestHandler, options?: ServerExtOptions): void; - /** - * Registers a new handler type to be used in routes - * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. - * [See docs](https://hapijs.com/api/16.1.1#serverhandlername-method) - * @param name string name for the handler being registered. Cannot override any previously registered type. - * @param method the function used to generate the route handler using the signature function(route, options) where: - * * route - the route public interface object. - * * options - the configuration object provided in the handler config. - */ - handler(name: string, method: MakeRouteHandler): void; - /** - * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection ports - * Note that if the method fails and the callback includes an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to assert that no error has been returned after calling initialize() to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. - * [See docs](https://hapijs.com/api/16.1.1#serverinitializecallback) - * @param callback the callback method when server initialization is completed or failed with the signature function(err) - */ - initialize(callback: (err: Error) => void): void; - initialize(): Promise; - /** - * When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. Utilizes the shot module for performing injections, with some additional options and response properties - * If no callback is provided, a Promise object is returned. - * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). - * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) - * @param options can be assigned a string with the requested URI, or an object - * @param callback the callback function with signature function(res) - */ - inject(options: string | InjectedRequestOptions, callback: (res: InjectedResponseObject) => void): void; - inject(options: string | InjectedRequestOptions, ): Promise; - /** - * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. - * [See docs](https://hapijs.com/api/16.1.1#serverlogtags-data-timestamp) - * @param tags a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. - * @param data an optional message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. - * @param timestamp an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). - */ - log(tags: string | string[], data?: string | Object | Function, timestamp?: number): void; - /** - * When the server contains exactly one connection, looks up a route configuration. - * When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method. - * [See docs](https://hapijs.com/api/16.1.1#serverlookupid) - * @param id the route identifier as set in the route options. - * @return the route public interface object if found, otherwise null. - */ - lookup(id: string): RoutePublicInterface | null; - /** - * When the server contains exactly one connection, looks up a route configuration - * When the server contains more than one connection, each server.connections array member provides its own connection.match() method. - * [See docs](https://hapijs.com/api/16.1.1#servermatchmethod-path-host) - * @param method the HTTP method (e.g. 'GET', 'POST'). TODO check if it allows HEAD - * @param path the requested path (must begin with '/'). - * @param host optional hostname (to match against routes with vhost). - * @return the route public interface object if found, otherwise null. - */ - match(method: HTTP_METHODS, path: string, host?: string): RoutePublicInterface | null; - /** - * Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. - * [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) - * @param name a unique method name used to invoke the method via server.methods[name]. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get. When configured with caching enabled, server.methods[name].cache will be an object see ServerMethodNameCacheObject - * @param method the method function - * @param options optional configuration - */ - method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; - /** - * Registers a server method function as described in server.method() using a configuration object - * [See docs](https://hapijs.com/api/16.1.1#servermethodmethods) - */ - method(methods: ServerMethodConfigurationObject[]): void; - method(methods: ServerMethodConfigurationObject): void; - /** - * Subscribe a handler to an event - * [See docs](https://hapijs.com/api/16.1.1#serveroncriteria-listener) - * @param criteria the subscription criteria which can be an event name string which can be any of the built-in server events or a custom application event registered with server.event(events). - * Or an see ServerEventCriteria. - * If 'start' - emitted when the server is started using server.start(). - * If 'stop' - emitted when the server is stopped using server.stop(). - * @param listener - */ - on(criteria: 'start' | 'stop' | string | ServerEventCriteria, listener: Function): void; - /** - * The 'log' event includes the event object and a tags object (where each tag is a key with the value true) - * [See docs](https://hapijs.com/api/16.1.1#server-events) - */ - on(criteria: 'log', listener: (event: ServerEventObject, tags: Podium.Tags) => void): void; - /** - * The 'request' and 'request-internal' events include the request object, the event object, and a tags object (where each tag is a key with the value true) - * [See docs](https://hapijs.com/api/16.1.1#server-events) - * TODO submit issue to TypeScript. Using 'request' | 'request-internal' removes the type - * interference when using code like: `server.on('request', (request, event, tags) => {...}` - * Same for 'response' | 'tail'. - */ - on(criteria: 'request', listener: (request: Request, event: ServerEventObject, tags: Podium.Tags) => void): void; - on(criteria: 'request-internal', listener: (request: Request, event: ServerEventObject, tags: Podium.Tags) => void): void; - /** - * The 'request-error' event includes the request object and the causing error err object - * [See docs](https://hapijs.com/api/16.1.1#server-events) - */ - on(criteria: 'request-error', listener: (request: Request, err: Error) => void): void; - /** - * The 'response' and 'tail' events include the request object - * [See docs](https://hapijs.com/api/16.1.1#server-events) - * See 'request' and 'request-internal' - */ - on(criteria: 'response', listener: (request: Request) => void): void; - on(criteria: 'tail', listener: (request: Request) => void): void; - /** - * The 'route' event includes the route public interface, the connection, and the server object used to add the route (e.g. the result of a plugin select operation) - * [See docs](https://hapijs.com/api/16.1.1#server-events) - */ - on(criteria: 'route', listener: (route: RoutePublicInterface, connection: ServerConnection, server: Server) => void): void; - /** - * Same as calling server.on() with the count option set to 1. - * TODO type this to copy the server.on specific types for 'route', 'tail', etc. - * [See docs](https://hapijs.com/api/16.1.1#serveroncecriteria-listener) - * @param criteria - * @param listener - */ - once(criteria: string | ServerEventCriteria, listener: Function): void; - /** - * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used - * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. - * [See docs](https://hapijs.com/api/16.1.1#serverpathrelativeto) - * @param relativeTo the path prefix added to any relative file path starting with '.'. - */ - path(relativeTo: string): void; - /** - * Registers a plugin - * If no callback is provided, a Promise object is returned. - * Note that plugin registration are recorded on each of the available connections. When plugins express a dependency on other plugins, both have to be loaded into the same connections for the dependency requirement to be fulfilled. It is recommended that plugin registration happen after all the server connections are created via server.connection(). - * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) - * @param plugins - * @param options - * @param callback with signature function(err) where err an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. - * A note on typings. Common use case is: - * register(Plugin, (err) => {// do more stuff}) - * so these typings save passing empty `options` object or having to - * explicity type the Error in the Callback e.g.: - * register(Plugin, {}, (err) => {// do more stuff}) or - * register(Plugin, (err: Error) => {// do more stuff}) - */ - register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, callback: (err: Error | null) => void): void; - register(plugins: Array<(PluginFunction | PluginRegistrationObject)>): Promise; - register(plugins: PluginFunction | PluginRegistrationObject, callback: (err: Error | null) => void): void; - register(plugins: PluginFunction | PluginRegistrationObject): Promise; - register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, options: PluginRegistrationOptions, callback: (err: Error | null) => void): void; - register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, options: PluginRegistrationOptions): Promise; - register(plugins: PluginFunction | PluginRegistrationObject, options: PluginRegistrationOptions, callback: (err: Error | null) => void): void; - register(plugins: PluginFunction | PluginRegistrationObject, options: PluginRegistrationOptions): Promise; - /** - * Adds a connection route - * [See docs](https://hapijs.com/api/16.1.1#serverrouteoptions) - * @param options a route configuration object [See docs](https://hapijs.com/api/16.1.1#route-configuration) or an array of configuration objects. - */ - route(options: RouteConfiguration[]): void; - route(options: RouteConfiguration): void; - /** - * Selects a subset of the server's connections - * Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. - * [See docs](https://hapijs.com/api/16.1.1#serverselectlabels) - * @param labels a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. - */ - select(labels: string | string[]): Server; - /** - * Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false) - * If no callback is provided, a Promise object is returned. - * Note that if the method fails and the callback includes an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to assert that no error has been returned after calling start() to abort the process when the server fails to start properly. If you must try to resume after a start error, call server.stop() first to reset the server state. - * If a started server is started again, the second call to start() will only start new connections added after the initial start() was called. No events will be emitted and no extension points invoked. - * [See docs](https://hapijs.com/api/16.1.1#serverstartcallback) - * @param callback the callback method when server startup is completed or failed with the signature function(err) where: - * * err - any startup error condition. - */ - start(callback: (err?: Error) => void): void; - start(): Promise; - /** - * HTTP state management [See docs](https://tools.ietf.org/html/rfc6265) uses client cookies to persist a state across multiple requests. Registers a cookie definitions - * [See docs](https://hapijs.com/api/16.1.1#serverstatename-options) - * @param name the cookie name string. - * @param options optional cookie settings - */ - state(name: string, options?: ServerStateCookieConfiguationObject): void; - /** - * Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout) - * If no callback is provided, a Promise object is returned. - * [See docs](https://hapijs.com/api/16.1.1#serverstopoptions-callback) - * @param options options object with: - * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). - * @param callback optional callback method which is called once all the connections have ended and it is safe to exit the process with signature function(err) where: - * * err - any termination error condition. - */ - stop(options: {timeout: number} | null, callback: (err?: Error) => void): void; - stop(options?: {timeout: number}): Promise; - /** - * Returns a copy of the routing table - * Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. - * When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection - * [See docs](https://hapijs.com/api/16.1.1#servertablehost) - * @param host optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. - */ - table(host?: string): RoutingTableEntry[]; -} - -export interface PluginSpecificConfiguration {} - -/** - * Server Options - * Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on. - * [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) - */ -export interface ServerOptions { - /** app - application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ - app?: any; - /** - * cache - sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: - * * a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. - * * a CatboxServerOptionsCacheConfiguration configuration object - * * an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. - */ - cache?: Catbox.EnginePrototype | CatboxServerOptionsCacheConfiguration | CatboxServerOptionsCacheConfiguration[]; - /** sets the default connections configuration which can be overridden by each connection */ - connections?: ConnectionConfigurationServerDefaults; - /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object with: */ - debug?: false | { - /** a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ - log?: string[] | false; - /** a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ - request?: string[] | false; - }; - /** process load monitoring */ - load?: { - /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling). */ - sampleInterval?: number; - }; - /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime. */ - mime?: MimosOptions; - /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}. */ - plugins?: PluginSpecificConfiguration; - /** if false, will not use node domains to protect against exceptions thrown in handlers and other external code. Defaults to true. */ - useDomains?: boolean; -} - -/** - * The server event object - * [See docs](https://hapijs.com/api/16.1.1#server-events) - */ -export interface ServerEventObject { - /** the event timestamp. */ - timestamp: number; - /** if the event relates to a request, the request id. */ - request: string; - /** if the event relates to a server, the server.info.uri. */ - server: string; - /** an array of tags (e.g. ['error', 'http']). */ - tags: string[]; - /** optional event-specific information. */ - data: any; - /** true if the event was generated internally by the framework. */ - internal: boolean; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serveroncriteria-listener) - */ -export interface ServerEventCriteria { - /** the event name string (required). */ - name: string; - /** if true, the listener method receives an additional callback argument which must be called when the method completes. No other event will be emitted until the callback methods is called. The method signature is function(). If block is set to a positive integer, the value is used to set a timeout after which any pending events will be emitted, ignoring the eventual call to callback. Defaults to false (non blocking). */ - block?: boolean; - /** a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. */ - channels?: string | string[]; - /** if true, the data object passed to server.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ - clone?: boolean; - /** a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.once(). Defaults to no limit. */ - count?: number; - /** - * the event tags (if present) to subscribe to - * If the object is given: - * * tags - a tag string or array of tag strings. - * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). - */ - filter?: string | string[] | {tags: string | string[], all?: boolean}; - /** if true, and the data object passed to server.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). */ - spread?: boolean; - /** if true and the criteria object passed to server.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end (but before the callback argument if block is set). Defaults to the event registration option (which defaults to false). */ - tags?: boolean; -} - -/** - * Server methods, user configured - * Related to [See docs](https://hapijs.com/api/16.1.1#servermethods) - * Related to [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) - */ -export interface ServerMethod { - /** the method must return a value (result, Error, or a promise) or throw an Error. */ - (...args: any[]): any | Error | Promise; - /** Not possible to improve this typing due to this unresolvable issue: https://github.com/Microsoft/TypeScript/issues/15190 */ - (...args: (any | ServerMethodNext)[]): void; - /** When configured with caching enabled, server.methods[name].cache will be an object see ServerMethodNameCacheObject */ - cache?: ServerMethodNameCacheObject; -} - -/** - * Related to [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) - * @param err error response if the method failed. - * @param result the return value. - * @param ttl 0 if result is valid but cannot be cached. Defaults to cache policy. - */ -export interface ServerMethodNext { - (err: Error | null, result: any, ttl?: number): void; -} - -/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) */ -export interface ServerMethodNameCacheObject { - /** - * function that can be used to clear the cache for a given key. - * @param ...args any number of string, number or boolean. If other types then generateKey function must be specified. - * @param callback last argument is a callback. - * Not possible to improve this typing due to this unresolvable issue: https://github.com/Microsoft/TypeScript/issues/15190 - */ - drop(...args: (any | Function)[]): void; - /** an object with cache statistics, see stats documentation for catbox. */ - stats: Catbox.CacheStatisticsObject; -} - -/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) */ -export interface ServerMethodOptions { - /** a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. */ - bind?: any; - /** the same cache configuration used in server.cache(). The generateTimeout option is required. */ - cache?: CatboxServerCacheConfiguration; - /** - * if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. - * TODO: understand and type "an additional argument with the signature function(err, result, cached, report)" if appropriate. - */ - callback?: boolean; - /** a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). */ - generateKey?(args: any[]): string | null; -} - -/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodmethods) */ -export interface ServerMethodConfigurationObject { - name: string; - method: ServerMethod; - options: ServerMethodOptions; -} - -/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + - + + - + Caching with Catbox + - + + - + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -// TODO: move to separate file http://stackoverflow.com/questions/43276921 - -/** - * TODO confirm this is the same as CatboxServerCacheConfiguration - * - * ** - * Server instantiation options configuration for Catbox cache - * TODO: check it extends Catbox.PolicyOptions and this is what "other options passed to the catbox strategy used." means. - * For context [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) under: options > cache > a configuration object - * ** - * export interface CatboxServerOptionsCacheConfiguration extends Catbox.IPolicyOptions { - * // a prototype function or catbox engine object. - * engine: Catbox.EnginePrototypeOrObject; - * // an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. - * name?: string; - * // if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. - * shared?: boolean; - * } - */ -export type CatboxServerOptionsCacheConfiguration = CatboxServerCacheConfiguration; - -/** - * Server cache method configuration for Catbox cache - * Used for "Provisions a cache segment within the server cache facility" - * For context [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) - * Also used in [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) > options.cache - */ -export interface CatboxServerCacheConfiguration extends Catbox.PolicyOptions { - /** the cache name configured in server.cache. Defaults to the default cache. */ - cache?: string; - /** string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. */ - segment?: string; - /** if true, allows multiple cache provisions to share the same segment. Default to false. */ - shared?: boolean; - /** - * a prototype function or catbox engine object. - * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) example code includes use of `engine` option. But server.cache.provision of `options` says "same as the server cache configuration options.". - * TODO confirm once PR to hapi docs accepted / rejected. - */ - engine?: Catbox.EnginePrototypeOrObject; - /** - * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. - * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) example code includes use of `name` option. But server.cache.provision of `options` says "same as the server cache configuration options.". - */ - name?: string; - /** - * Additional options to be passed to the Catbox strategy - */ - [s: string]: any; -} - -/** - * Additional notes - * payload - In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. - * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) - */ -export interface InjectedRequestOptions extends Shot.RequestOptions { - /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. */ - credentials?: any; - /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. */ - artifacts?: any; - /** sets the initial value of request.app. */ - app?: any; - /** sets the initial value of request.plugins. */ - plugins?: PluginsStates; - /** allows access to routes with config.isInternal set to true. Defaults to false. */ - allowInternals?: boolean; -} - -/** - * the response object from server.inject - * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) - */ -export interface InjectedResponseObject extends Shot.ResponseObject { - /** the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). */ - result: Object | string; - /** the request object. */ - request: InjectedRequestOptions; -} - -/** - * For context [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) under: options > connections - */ -export interface ConnectionConfigurationServerDefaults { - /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ - app?: any; - /** if false, response content encoding is disabled. Defaults to true */ - compression?: boolean; - /** connection load limits configuration where: */ - load?: { - /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxHeapUsedBytes?: number; - /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxRssBytes?: number; - /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ - maxEventLoopDelay?: number; - }; - /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ - plugins?: PluginSpecificConfiguration; - /** controls how incoming request URIs are matched against the routing table: */ - router?: { - /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ - isCaseSensitive?: boolean; - /** removes trailing slashes on incoming paths. Defaults to false. */ - stripTrailingSlash?: boolean; - }; - /** a route options object used to set the default configuration for every route. */ - routes?: RouteAdditionalConfigurationOptions; - /** sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the [state configuration object](https://hapijs.com/api/16.1.1#serverstatename-options). */ - state?: ServerStateCookieConfiguationObject; -} - -/** - * a connection configuration object or array of objects with the following optional keys. - * Any connections configuration server defaults can be included to override and customize the individual connection. - * [See docs](https://hapijs.com/api/16.1.1#serverconnectionoptions) - */ -export interface ServerConnectionOptions extends ConnectionConfigurationServerDefaults { - /** host - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'. */ - host?: string; - /** address - sets the host name or IP address the connection will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0'). Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine. */ - address?: string; - /** port - the TCP port the connection will listen to. Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port). If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe. */ - port?: string | number; - /** uri - the full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the connection info.uri otherwise constructed from the connection settings. */ - uri?: string; - /** listener - optional node.js HTTP (or HTTPS) http.Server object or any compatible object. If the listener needs to be manually started, set autoListen to false. If the listener uses TLS, set tls to true. */ - listener?: http.Server; - /** autoListen - indicates that the connection.listener will be started manually outside the framework. Cannot be specified with a port setting. Defaults to true. */ - autoListen?: boolean; - /** labels - a string or string array of labels used to server.select() specific connections matching the specified labels. Defaults to an empty array [] (no labels). */ - labels?: string | string[]; - /** tls - used to create an HTTPS connection. The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS [documentation](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener}) . Set to true when passing a listener object that has been configured to use TLS directly. */ - tls?: true | https.RequestOptions; -} - -/** - * For context see RouteAdditionalConfigurationOptions > compression - * For context [See docs](https://hapijs.com/api/16.1.1#serverencoderencoding-encoder) - */ -export type CompressionEncoderSettings = any; - -/** - * For context see RouteAdditionalConfigurationOptions > payload > compression - * For context [See docs](https://hapijs.com/api/16.1.1#serverdecoderencoding-decoder) - */ -export type CompressionDecoderSettings = any; - -/** - * an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: - * [See docs](https://hapijs.com/api/16.1.1#serverdependencydependencies-after) - * Also see Server.dependency - * @param server the server the dependency() method was called on. - * @param next the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: - * * err - internal error condition, which is returned back via the server.initialize() or server.start() callback. - */ -export interface AfterDependencyLoadCallback { - (server: Server, next: (err?: Error) => void): void; -} - -/** For context see RouteAdditionalConfigurationOptions > auth */ -export interface AuthOptions { - /** - * the authentication mode. Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication. Available values: - * * 'required' - authentication is required. - * * 'optional' - authentication is optional (must be valid if present). - * * 'try' - same as 'optional' but allows for invalid authentication. - */ - mode?: 'required' | 'optional' | 'try'; - /** a string array of strategy names in order they should be attempted. If only one strategy is used, strategy can be used instead with the single string value. Defaults to the default authentication strategy which is available only when a single strategy is configured. */ - strategies?: string[]; - strategy?: string; - /** - * if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' when the scheme sets the options.payload to true. Available values: - * * false - no payload authentication. This is the default value. - * * 'required' - payload authentication required. This is the default value when the scheme sets options.payload to true. - * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). - */ - payload?: false | 'required' | 'optional'; - /** specifying the route access rules. */ - access?: RouteAuthAccessConfiguationObject | RouteAuthAccessConfiguationObject[]; - /** (undocumented) Convenience way of setting access.scope, will over write all values in `access` */ - scope?: false | string | string[]; - /** (undocumented) Convenience way of setting access.entity, will over write all values in `access` */ - entity?: 'any' | 'user' | 'app'; -} - -/** - * Each rule is evaluated against an incoming request and access is granted if at least one rule matches. Each rule object must include at least one of: - * For context see RouteAdditionalConfigurationOptions > auth > an object > access - */ -export interface RouteAuthAccessConfiguationObject { - /** the application scope required to access the route. Value can be a scope string or an array of scope strings. The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access properties on the request object (query and params) to populate a dynamic scope by using {} characters around the property name, such as 'user-{params.id}'. Defaults to false (no scope requirements). */ - scope?: false | string | string[]; - /** - * the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: - * * any - the authentication can be on behalf of a user or application. This is the default value. - * * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. - * * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. - */ - entity?: 'any' | 'user' | 'app'; -} - -/** - * For context see RouteAdditionalConfigurationOptions > cache - */ -export type RouteCacheOptions = { - /** - * determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: - * * 'default' - no privacy flag. This is the default setting. - * * 'public' - mark the response as suitable for public caching. - * * 'private' - mark the response as suitable only for private caching. - */ - privacy?: 'default' | 'public' | 'private'; - /** an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive. Defaults to [200]. */ - statuses?: number[]; - /** a string with the value of the 'Cache-Control' header when caching is disabled. Defaults to 'no-cache'. */ - otherwise?: string; -} & ({ - /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ - expiresIn?: number; - /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ - expiresAt?: undefined; -} | { - /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ - expiresIn?: undefined; - /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ - expiresAt?: string; -} | { - /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ - expiresIn?: undefined; - /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ - expiresAt?: undefined; -}); - -/** - * For context see RouteAdditionalConfigurationOptions > cors - */ -export interface CorsConfigurationObject { - /** a strings array of allowed origin servers ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. Defaults to any origin ['*']. */ - origin?: string[] | '*'; - /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). */ - maxAge?: number; - /** a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'] */ - headers?: string[]; - /** a strings array of additional headers to headers. Use this to keep the default headers in place. */ - additionalHeaders?: string[]; - /** a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ - exposedHeaders?: string[]; - /** a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. */ - additionalExposedHeaders?: string[]; - /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. */ - credentials?: boolean; -} - -/** - * An object describing the extension function used whilst registering the extension function in one of the available extension points - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) - * For context see RouteAdditionalConfigurationOptions > ext - */ -export interface ServerStartExtConfigurationObject { - /** the extension point event name. */ - type: ServerStartExtPoints; - /** - * a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is see ServerExtFunction or see ServerExtRequestHandler - */ - method: ServerExtFunction | ServerExtFunction[]; - options?: ServerExtOptions; -} - -/** - * An object describing the extension function used whilst registering the extension function in one of the available extension points - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) - * For context see RouteAdditionalConfigurationOptions > ext - */ -export interface ServerRequestExtConfigurationObject { - /** the extension point event name. */ - type: ServerRequestExtPointsBase; - /** - * a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is see ServerExtFunction or see ServerExtRequestHandler - */ - method: ServerExtRequestHandler | ServerExtRequestHandler[] - options?: ServerExtOptions; -} - -/** - * An object describing the extension function used whilst registering the extension function in one of the available extension points - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) - * For context see RouteAdditionalConfigurationOptions > ext - */ -export interface ServerRequestExtConfigurationObjectWithRequest { - /** the extension point event name. */ - type: ServerRequestExtPoints; - /** - * a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is see ServerExtFunction or see ServerExtRequestHandler - */ - method: ServerExtRequestHandler | ServerExtRequestHandler[]; - options?: ServerExtOptions; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#route-configuration) > ext - */ -export type RouteExtConfigurationObject = ServerStartExtConfigurationObject | ServerRequestExtConfigurationObject; - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > method - */ -export type ServerExtMethod = ServerExtFunction | ServerExtRequestHandler; - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > options - */ -export interface ServerExtOptions { - /** before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. */ - before: string | string[]; - /** after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. */ - after: string | string[]; - /** bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. */ - bind: any; - /** sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'connection' which applies to any route added to the connection the extension is added to. */ - sandbox?: 'connection' | 'plugin'; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > type - * * 'onPreStart' - called before the connection listeners are started. - * * 'onPostStart' - called after the connection listeners are started. - * * 'onPreStop' - called before the connection listeners are stopped. - * * 'onPostStop' - called after the connection listeners are stopped. - */ -export type ServerStartExtPoints = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; -/** - * [See docs](https://hapijs.com/api/16.1.1#request-lifecycle) - * * The available extension points include the request extension points as well as the following server extension points: - */ -export type ServerRequestExtPointsBase = 'onPreResponse' | 'onPreAuth' | 'onPostAuth' | 'onPreHandler' | 'onPostHandler' | 'onPreResponse'; - -export type ServerRequestExtPoints = ServerRequestExtPointsBase | 'onRequest'; - -/** - * Server extension function registered an one of the server extension points - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) - * For context see ServerExtConfigurationObject - * @param server - the server object. - * @param next - the continuation method with signature function(err). - * @param this - the object provided via options.bind or the current active context set with server.bind(). - */ -export interface ServerExtFunction { - (server: Server, next: ContinuationFunction): void; -} - -/** - * For context see RouteAdditionalConfigurationOptions > payload - */ -export interface RoutePayloadConfigurationObject { - /** - * the type of payload representation requested. The value must be one of: - * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, the raw Buffer is returned. This is the default value except when a proxy handler is used. - * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. - * * 'file' - the incoming payload is written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleanup. - */ - output?: PayLoadOutputOption; - /** - * can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: - * * 'application/json' - * * 'application/x-www-form-urlencoded' - * * 'application/octet-stream' - * * 'text/*' - * * 'multipart/form-data' - */ - parse?: 'gunzip' | boolean; - /** - * overrides payload processing for multipart requests. Value can be one of: - * * false - disables multipart processing. - * * object with the following required options: - * * output - same as the payload.output option with an additional value option: - * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? - * * headers - the part headers. - * * filename - the part file name. - * * payload - the processed part payload. - */ - multipart?: false | { - output: PayLoadOutputOption | 'annotated'; - }; - /** a string or an array of strings with the allowed mime types for the endpoint. Defaults to any of the supported mime types listed above. Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ - allow?: string | string[]; - /** a mime type string overriding the 'Content-Type' header value received. Defaults to no override. */ - override?: string; - /** limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. Defaults to 1048576 (1MB). */ - maxBytes?: number; - /** payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. Set to false to disable. Defaults to 10000 (10 seconds). */ - timeout?: number | false; - /** the directory used for writing file uploads. Defaults to os.tmpdir(). */ - uploads?: string; - /** - * determines how to handle payload parsing errors. Allowed values are: - * * 'error' - return a Bad Request (400) error response. This is the default value. - * * 'log' - report the error but continue processing the request. - * * 'ignore' - take no action and continue processing the request. - */ - failAction?: 'error' | 'log' | 'ignore'; - /** the default 'Content-Type' HTTP header value is not present. Defaults to 'application/json'. */ - defaultContentType?: string; - /** an object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in the root option compression. */ - compression?: Dictionary; -} - -export type PayLoadOutputOption = 'data' | 'stream' | 'file'; - -/** - * events must be one of: - * * an event name string. - * * an event options object see ApplicationEventOptionsObject - * * a podium [See docs](https://github.com/hapijs/podium) emitter object. - * For context [See docs](https://hapijs.com/api/16.1.1#servereventevents) > events parameter - */ -export type ApplicationEvent = string | ApplicationEventOptionsObject | Podium; - -/** - * an event options object - * For context see ApplicationEvent - * For context [See docs](https://hapijs.com/api/16.1.1#servereventevents) > events parameter - */ -export interface ApplicationEventOptionsObject { - /** the event name string (required). */ - name: string; - /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ - channels?: string | string[]; - /** if true, the data object passed to server.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). */ - clone?: boolean; - /** if true, the data object passed to server.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). */ - spread?: boolean; - /** if true and the criteria object passed to server.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end (but before the callback argument if block is set). A configuration override can be set by each listener. Defaults to false. */ - tags?: boolean; - /** if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). */ - shared?: boolean; -} - -/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + - + + - + Route + - + + - + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -// TODO: move to separate file http://stackoverflow.com/questions/43276921 - -/** - * Route configuration - * The route configuration object - * - * [See docs](https://hapijs.com/api/16.1.1#route-configuration) - * - * TODO typings check that the following refers to RouteAdditionalConfigurationOptions "Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on." - */ -export interface RouteConfiguration { - /** the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. */ - path: string; - /** the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. */ - method: HTTP_METHODS_PARTIAL | '*' | (HTTP_METHODS_PARTIAL | '*')[]; - /** an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. */ - vhost?: string; - /** the function called to generate the response after successful authentication and validation. The handler function is described in Route handler. If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed. Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler. */ - handler?: string | RouteHandler | RouteHandlerPlugins; - /** additional route options. The config value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. */ - config?: RouteAdditionalConfigurationOptions | ((server: Server) => RouteAdditionalConfigurationOptions); -} - -/** - * Route options - * Each route can be customize to change the default behavior of the request lifecycle using the following options: - * [See docs](https://hapijs.com/api/16.1.1#route-options) - */ -export interface RouteAdditionalConfigurationOptions { - /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ - app?: any; - /** - * Authentication configuration. Value can be: - * * false to disable authentication if a default strategy is set. - * * a string with the name of an authentication strategy registered with server.auth.strategy(). - * * an object - */ - auth?: false | string | AuthOptions; - /** an object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. */ - bind?: any; - /** - * Route cache options - * if the route method is 'GET', the route can be configured to include caching directives in the response. The default Cache-Control: no-cache header can be disabled by setting cache to false. Caching can be customized using an object - * TODO check: the default is to have 'Cache-Control: no-cache', but on first reading is a contridiction as you can disabled cache and disabled no-cache by setting RouteCacheOptions to false? - */ - cache?: boolean | RouteCacheOptions; - /** an object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in payload.compression. */ - compression?: Dictionary; - /** the Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. CORS headers are disabled by default (false). To enable, set cors to true, or to an object */ - cors?: boolean | CorsConfigurationObject; - /** defined a route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the [server.ext(events)](https://hapijs.com/api/16.1.1#serverextevents) event argument. */ - ext?: RouteExtConfigurationObject | RouteExtConfigurationObject[]; - /** defines the behavior for accessing files: */ - files?: { - /** determines the folder relative paths are resolved against. */ - relativeTo: string; - }; - /** an alternative location for the route.handler option. */ - handler?: string | RouteHandler; - /** an optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes with an array of methods. */ - id?: string; - /** if true, the route cannot be accessed through the HTTP connection but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should not be accessible to the outside world. Defaults to false. */ - isInternal?: boolean; - /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload. Supports the following: */ - json?: Json.StringifyArguments & { - /** string suffix added after conversion to JSON string. Defaults to no suffix. */ - suffix?: string; - }; - /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Does not work with stream responses. Headers content-type and x-content-type-options are set to text/javascript and nosniff respectively, and will override those headers even if explicitly set by response.type() */ - jsonp?: string; - /** if true, request level logging is enabled (accessible via request.getLog()). */ - log?: boolean; - /** - * determines how the request payload is processed - * [See docs](https://hapijs.com/api/16.1.1#route-options) - */ - payload?: RoutePayloadConfigurationObject; - /** plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. */ - plugins?: PluginSpecificConfiguration; - /** an array with [route prerequisites](https://hapijs.com/api/16.1.1#route-prerequisites) methods which are executed in serial or in parallel before the handler is called. */ - pre?: RoutePrerequisitesArray; - /** processing rules for the outgoing response */ - response?: RouteResponseConfigurationObject; - /** sets common security headers (disabled by default). To enable set security to true or to an object with the following options: See RouteSecurityConfigurationObject */ - security?: boolean | RouteSecurityConfigurationObject; - /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following options: */ - state?: { - /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object. Defaults to true. */ - parse?: boolean; - /** - * determines how to handle cookie parsing errors. Allowed values are: - * * 'error' - return a Bad Request (400) error response. This is the default value. - * * 'log' - report the error but continue processing the request. - * * 'ignore' - take no action. - */ - failAction: 'error' | 'log' | 'ignore'; - }; - /** request input validation rules for various request components. When using a Joi validation object, the values of the other inputs (i.e. headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')). Note that validation is performed in order (i.e. headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the routes defaults level and an individual route, the individual route settings override the routes defaults (the rules are not merged). The validate object supports: */ - validate?: RouteValidationConfigurationObject; - /** define timeouts for processing durations: */ - timeout?: { - /** response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response. Disabled by default (false). */ - server?: boolean | number; - /** by default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Defaults to undefined which leaves the node default unchanged. Set to false to disable socket timeouts. */ - socket?: boolean | number; - }; - - /** - * TODO decide on moving these to an extended interface of RouteAdditionalConfigurationOptions - */ - /** - * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - * route description used for generating documentation - */ - description?: string; - /** - * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - * route notes used for generating documentation - */ - notes?: string | string[]; - /** - * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). - * route tags used for generating documentation - */ - tags?: string[]; -} - -/** - * Route public interface - * When route information is returned or made available as a property, it is an object with the following: - * [See docs](https://hapijs.com/api/16.1.1#route-public-interface) - */ -export interface RoutePublicInterface { - /** the route HTTP method. */ - method: string; - /** the route path. */ - path: string; - /** the route vhost option if configured. */ - vhost?: string | string[]; - /** the [active realm] [See docs](https://hapijs.com/api/16.1.1#serverrealm) associated with the route.*/ - realm: ServerRealm; - /** the [route options] [See docs](https://hapijs.com/api/16.1.1#route-options) object with all defaults applied. */ - settings: RouteAdditionalConfigurationOptions; - /** the route internal normalized string representing the normalized path. */ - fingerprint: string; - /** route authentication utilities: */ - auth: { - /** authenticates the passed request argument against the route's authentication access configuration. Returns true if the request would have passed the route's access requirements. Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. Also, if the route uses dynamic scopes, the scopes are constructed against the request.query and request.params which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or at all), it will return false if the route requires any authentication. */ - access(request: Request): boolean; - }; -} - -export type RouteHandlerConfig = any; - -/** - * For context [See docs](https://hapijs.com/api/16.1.1#serverhandlername-method) - * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/handler.js#L103) - * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/route.js#L56-L60) - * TODO check the type of `RouteHandlerConfig` is correct for `defaults`. - */ -export interface MakeRouteHandler { - (route: RoutePublicInterface, options: RouteHandlerConfig): RouteHandler; - defaults?: RouteHandlerConfig | ((method: HTTP_METHODS_PARTIAL_lowercase) => RouteHandlerConfig); -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#servertablehost) > return value - */ -export interface RoutingTableEntry { - /** the connection.info the connection the table was generated for. */ - info: ServerConnectionInfo; - /** the connection labels. */ - labels: string[]; - /** an array of routes where each route contains: */ - table: Route[]; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#servertablehost) > return value - * For source [See source](https://github.com/hapijs/hapi/blob/v16.1.1/lib/route.js#L71) - */ -export interface Route { - /** - * the route config with defaults applied. - * TODO check type of RouteConfiguration here is correct - */ - settings: RouteAdditionalConfigurationOptions; - /** - * the HTTP method in lower case. - * TODO, check if it can contain 'head' or not. - */ - method: HTTP_METHODS_PARTIAL_lowercase; - /** the route path. */ - path: string; - - params: string[]; - - connection: ServerConnection; - - fingerprint: string; - - plugin?: any; - - public: RoutePublicInterface; - - server: Server; -} - -/** - * Route Prerequisites - * It is often necessary to perform prerequisite actions before the handler is called (e.g. load required reference data from a database). The route pre option allows defining such pre-handler methods. The methods are called in order. If the pre array contains another array, those methods are called in parallel. pre can be assigned a mixed array of: - * * arrays containing the elements listed below, which are executed in parallel. - * * objects see RoutePrerequisiteObjects - * * functions - same as including an object with a single method key. - * * strings - special short-hand notation for registered server methods using the format 'name(args)' (e.g. 'user(params.id)') where: - * * 'name' - the method name. The name is also used as the default value of assign. - * * 'args' - the method arguments (excluding next) where each argument is a property of the request object - * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) - * For context see RouteAdditionalConfigurationOptions > pre - * - * TODO follow up on "server methods" in "special short-hand notation for registered server methods" at https://hapijs.com/api/16.1.1#servermethodname-method-options - * TODO follow up on "request object" in "each argument is a property of the request object" at https://hapijs.com/api/16.1.1#request-object - */ -export type RoutePrerequisitesArray = RoutePrerequisitesPart[] | (RoutePrerequisitesPart[] | RoutePrerequisitesPart)[]; -export type RoutePrerequisitesPart = RoutePrerequisiteObjects | RoutePrerequisiteRequestHandler | string; - -/** - * see RoutePrerequisites > objects - */ -export interface RoutePrerequisiteObjects { - /** the function to call (or short-hand method string as described below [see RoutePrerequisitesArray]). the function signature is identical to a route handler as described in Route handler. */ - method: RoutePrerequisiteRequestHandler | string; - /** key name to assign the result of the function to within request.pre. */ - assign: string; - /* - * determines how to handle errors returned by the method. Allowed values are: - * * 'error' - returns the error response back to the client. This is the default value. - * * 'log' - logs the error but continues processing the request. If assign is used, the error will be assigned. - * * 'ignore' - takes no special action. If assign is used, the error will be assigned. - */ - failAction?: 'error' | 'log' | 'ignore'; -} - -/** - * For context see RouteAdditionalConfigurationOptions > response - */ -export interface RouteResponseConfigurationObject { - /** the default HTTP status code when the payload is empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time or response transmission (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ - emptyStatusCode?: number; - /** - * defines what to do when a response fails payload validation. Options are: - * * 'error' - return an Internal Server Error (500) error response. This is the default value. - * * 'log' - log the error but send the response. - * * a custom error handler function with the signature function(request, reply, source, error) where: - * * 'request' - the request object. - * * 'reply' - the continuation reply interface. - * * 'error' - the error returned from the validation schema. - * TODO update type of source once PR to hapi is concluded. - */ - failAction?: 'error' | 'log' | ((request: Request, reply: ReplyWithContinue, source: string, error: Boom.BoomError) => void); - /** if true, applies the validation rule changes to the response payload. Defaults to false. */ - modify?: boolean; - /** - * options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is available [here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback) ). - * If a custom validation function (see `schema` or `status` below) is defined then `options` can an arbitrary object that will be passed to this function as the second parameter. - * Defaults to no options. - */ - options?: ValidationOptions; - /** if false, payload range support is disabled. Defaults to true. */ - ranges?: boolean; - /** the percent of response payloads validated (0 - 100). Set to 0 to disable all validation. Defaults to 100 (all response payloads). */ - sample?: number; - /** the default response payload validation rules (for all non-error responses) */ - schema?: RouteResponseConfigurationScheme; - /** HTTP status-code-specific payload validation rules. The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. If a response status code is not present in the status object, the schema definition is used, except for errors which are not validated by default. */ - status?: Dictionary>; -} - -/** - * the default response payload validation rules (for all non-error responses) expressed as one of: - * * true - any payload allowed (no validation performed). This is the default. - * * false - no payload allowed. - * * a Joi validation object. This will receive the request's headers, params, query, payload, and auth credentials and isAuthenticated flags as context. - * * a validation function - * - * TODO check JoiValidationObject is correct for "a Joi validation object" - * - * For context see RouteAdditionalConfigurationOptions > response > schema - * and - * For context see RouteAdditionalConfigurationOptions > response > status - */ -export type RouteResponseConfigurationScheme = boolean | JoiValidationObject | ValidationFunctionForRouteResponse; - -/** - * see RouteResponseConfigurationScheme - * - * a validation function using the signature function(value, options, next) where: - * * value - the value of the response passed to `reply(value)` in the handler. - * * options - the server validation options, merged with an object containing the request's headers, params, payload, and auth credentials object and `isAuthenticated` flag. - * * next([err, [value]]) - the callback function called when validation is completed. `value` will be used as the response value when `err` is falsy, when `value` is not `undefined`, and when `route.settings.response.modify` is `true`. If the response is already a `Boom` error it will be set as its `message` value. - */ -export interface ValidationFunctionForRouteResponse { - (value: any, options: RouteResponseValidationContext & ValidationOptions, next: ContinuationValueFunction): void; -} - -/** - * A context for route input validation via a Joi schema or validation function. - * - * This object is merged with the route response options and passed into the validation function. - * - * See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L217 - */ -export interface RouteResponseValidationContext { - context: { - /** The request headers */ - headers: Dictionary; - /** The request path parameters */ - params: any; - /** The request query parameters */ - query: any; - /** The request payload parameters */ - payload: any; - - /** Partial request authentication information */ - auth: { - /** true if the request has been successfully authenticated, otherwise false. */ - isAuthenticated: boolean; - /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ - credentials: AuthenticatedCredentials; - }; - } -} - -/** - * For context see RouteAdditionalConfigurationOptions > security - */ -export interface RouteSecurityConfigurationObject { - /** controls the 'Strict-Transport-Security' header. If set to true the header will be set to max-age=15768000, if specified as a number the maxAge parameter will be set to that number. Defaults to true. You may also specify an object with the following fields: */ - hsts?: boolean | number | { - /** the max-age portion of the header, as a number. Default is 15768000. */ - maxAge?: number; - /** a boolean specifying whether to add the includeSubDomains flag to the header. */ - includeSubdomains?: boolean; - /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ - preload?: boolean; - }; - /** controls the 'X-Frame-Options' header. When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'. Defaults to true. To use the 'allow-from' rule, you must set this to an object with the following fields: */ - xframe?: true | 'deny' | 'sameorigin' | { - /** may also be 'deny' or 'sameorigin' but set directly as a string for xframe */ - rule: 'allow-from'; - /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ - source: string; - }; - /** boolean that controls the 'X-XSS-PROTECTION' header for IE. Defaults to true which sets the header to equal '1; mode=block'. NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8. See [here](https://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/) and [here](https://technet.microsoft.com/library/security/ms10-002) for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. [Kept typing non optional to force this security related documentation to be read.] */ - xss: boolean; - /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. */ - noOpen?: boolean; - /** boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff' */ - noSniff?: boolean; -} - -/** - * request input validation rules for various request components. When using a Joi validation object, the values of the other inputs (i.e. headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')). Note that validation is performed in order (i.e. headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the routes defaults level and an individual route, the individual route settings override the routes defaults (the rules are not merged). The validate object supports: - * For context see RouteAdditionalConfigurationOptions > validate - * TODO check JoiValidationObject is correct for "a Joi validation object" - */ -export interface RouteValidationConfigurationObject { - /** - * validation rules for incoming request headers (note that all header field names must be in lowercase to match the headers normalized by node). Values allowed: - * * true - any headers allowed (no validation performed). This is the default. - * * false - no headers allowed (this will cause all valid HTTP requests to fail). - * * a Joi validation object. - * * a validation function using the signature function(value, options, next) where: - * * value - the object containing the request headers. - * * options - the server validation options. - * * next(err, value) - the callback function called when validation is completed. `value` will be used as the `headers` value when `err` is falsy. If `next` is called with `undefined` or no arguments then the original value of `value` will be used. - */ - headers?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; - /** - * validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params. Values allowed: - * Same as `headers`, see above. - */ - params?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; - /** - * validation rules for an incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs and stored in request.query prior to validation. Values allowed: - * Same as `headers`, see above. - */ - query?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; - /** - * validation rules for an incoming request payload (request body). Values allowed: - * Same as `headers`, see above, with the addition that: - * * a Joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are supported, it must be explicitly defined by setting the payload value to a joi schema with null allowed (e.g. Joi.object({ /* keys here * / }).allow(null)). - */ - payload?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; - /** an optional object with error fields copied into every validation error response. */ - errorFields?: any; - /** - * determines how to handle invalid requests. Allowed values are: - * * 'error' - return a Bad Request (400) error response. This is the default value. - * * 'log' - log the error but continue processing the request. - * * 'ignore' - take no action. - * * a custom error handler function with the signature function(request, reply, source, error) see RouteFailFunction - */ - failAction?: 'error' | 'log' | 'ignore' | RouteFailFunction; - /** - * options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is [available here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback)). - * If a custom validation function (see `headers`, `params`, `query`, or `payload` above) is defined then `options` can an arbitrary object that will be passed to this function as the second parameter. - * Defaults to no options. - */ - options?: ValidationOptions; -} - -/** - * a validation function using the signature function(value, options, next) where: - * For context see RouteAdditionalConfigurationOptions > validate (RouteValidationConfigurationObject) - * - * Also see ValidationFunctionForRouteResponse - * @param value - the object containing the request headers, query, path params or payload. - * @param options - the server validation options. - * @param next([err, [value]]) - the callback function called when validation is completed. - */ -export interface ValidationFunctionForRouteInput { - (value: any, options: RouteInputValidationContext & ValidationOptions, next: ContinuationValueFunction): void; -} - -/** - * A context for route input validation via a Joi schema or validation function. - * - * This object is merged with the route validation options and passed into the validation function. - * - * See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L122 - */ -export interface RouteInputValidationContext { - context: { - // These are only set when *not* validating the respective source (e.g. params, query and payload are set when validating headers): - // See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L132 - headers?: Dictionary; - params?: any; - query?: any; - payload?: any; - - /** The request authentication information */ - auth: RequestAuthenticationInformation; - } -} - -/** - * a custom error handler function with the signature 'function(request, reply, source, error)` - * @param request - the request object. - * @param reply - the continuation reply interface. - * @param source - the source of the invalid field (e.g. 'headers', 'params', 'query', 'payload'). - * @param error - the error object prepared for the client response (including the validation function error under error.data). - */ -export interface RouteFailFunction { - (request: Request, reply: ReplyWithContinue, source: string, error: any): void; -} - -/** - * optional cookie settings - * [See docs](https://hapijs.com/api/16.1.1#serverstatename-options) - * Related to see ConnectionConfigurationServerDefaults - */ -export interface ServerStateCookieConfiguationObject { - /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */ - ttl?: number | null; - /** sets the 'Secure' flag. Defaults to true. */ - isSecure?: boolean; - /** sets the 'HttpOnly' flag. Defaults to true. */ - isHttpOnly?: boolean; - /** - * sets the 'SameSite' flag where the value must be one of: - * * false - no flag. - * * 'Strict' - sets the value to 'Strict' (this is the default value). - * * 'Lax' - sets the value to 'Lax'. - */ - isSameSite?: false | 'Strict' | 'Lax'; - /** the path scope. Defaults to null (no path). */ - path?: string | null; - /** the domain scope. Defaults to null (no domain). */ - domain?: string | null; - /** - * if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: - * * request - the request object. - * * next - the continuation function using the function(err, value) signature. - */ - autoValue?(request: Request, next: ContinuationValueFunction): void; - /** - * encoding performs on the provided value before serialization. Options are: - * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value. - * * 'base64' - string value is encoded using Base64. - * * 'base64json' - object value is JSON-stringified then encoded using Base64. - * * 'form' - object value is encoded using the x-www-form-urlencoded method. - * * 'iron' - Encrypts and sign the value using iron. - */ - encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'; - /** - * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are: - * * integrity - algorithm options. Defaults to require('iron').defaults.integrity. - * * password - password used for HMAC key generation (must be at least 32 characters long). - */ - sign?: { - integrity?: any; // TODO make iron definitions and getting typing from iron - password: string; - }; - /** password used for 'iron' encoding (must be at least 32 characters long). */ - password?: string; - /** options for 'iron' encoding. Defaults to require('iron').defaults. */ - iron?: any; // TODO make iron definitions and getting typing from iron - /** if true, errors are ignored and treated as missing cookies. */ - ignoreErrors?: boolean; - /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */ - clearInvalid?: boolean; - /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */ - strictHeader?: boolean; - /** used by proxy plugins (e.g. h2o2). */ - passThrough?: any; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverconnections) - */ -export interface ServerConnection { - /** settings - the connection configuration object passed to server.connection() after applying the server defaults. */ - settings: ServerConnectionOptions; - /** server - the connection's Server object. */ - server: Server; - /** type - set to 'tcp' is the connection is listening on a TCP port, otherwise to 'socket'(a UNIX domain socket or a Windows named pipe). */ - type: 'tcp' | 'socket'; - /** - * registrations - * Described [See docs](https://hapijs.com/api/16.1.1#serverregistrations) "When the server contains more than one connection, each server.connections array member provides its own connection.registrations." - */ - registrations: ServerRegisteredPlugins; - /** states - TODO contribute docs to hapi if they want, and then update type here */ - states: any; - /** auth - TODO contribute docs to hapi if they want, and then update type here */ - auth: any; - /** - * plugins - * TODO contribute docs to hapi if they want. Assuming similar to `registrations`, `listener`, `info`, etc - */ - plugins: PluginsStates; - /** - * app - * TODO contribute docs to hapi if they want. Assuming similar to `registrations`, `listener`, `info`, etc - */ - app: any; - /** Described in server.listener [See docs](https://hapijs.com/api/16.1.1#serverlistener) */ - listener: ServerListener; - /** Described in server.info [See docs](https://hapijs.com/api/16.1.1#serverinfo) */ - info: ServerConnectionInfo; - /** Described in server.inject [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) */ - inject(options: string | InjectedRequestOptions, callback: (res: InjectedResponseObject) => void): void; - inject(options: string | InjectedRequestOptions, ): Promise; - /** Mentioned but not documented under server.connections [See docs](https://hapijs.com/api/16.1.1#serverconnections) */ - table(host?: string): Route[]; - /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#serverlookupid) */ - lookup(id: string): RoutePublicInterface | null; - /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#servermatchmethod-path-host) */ - match(method: HTTP_METHODS, path: string, host?: string): RoutePublicInterface | null; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverinfo) - */ -export interface ServerConnectionInfo { - /** a unique connection identifier (using the format '{hostname}:{pid}:{now base36}'). */ - id: string; - /** the connection creation timestamp. */ - created: number; - /** the connection start timestamp (0 when stopped). */ - started: number; - /** - * the connection port based on the following rules: - * * the configured port value before the server has been started. - * * the actual port assigned when no port is configured or set to 0 after the server has been started. - * TODO check this type. What happens when socket is a UNIX domain socket or Windows named pipe? - */ - port: number | string; - /** the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'. */ - host: string; - /** the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). */ - address: undefined | string; - /** the protocol used. 'socket' when UNIX domain socket or Windows named pipe. */ - protocol: 'http' | 'https' | 'socket'; - /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component. */ - uri: string; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverlistener) - */ -export type ServerListener = http.Server; - -/** - * server.realm - * The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. - * [See docs](https://hapijs.com/api/16.1.1#serverrealm) - */ -export interface ServerRealm { - /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ - modifiers: { - /** routes preferences: */ - route: { - /** the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include the trailing slash. */ - prefix: string; - /** the route virtual host settings used by any calls to server.route() from the server. */ - vhost: string; - } - }; - /** the active plugin name (empty string if at the server root). */ - plugin: string; - /** the plugin options object passed at registration. */ - pluginOptions: any; // OptionsPassedToPlugin; - /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ - plugins: PluginsStates; - /** settings overrides (from RouteAdditionalConfigurationOptions) */ - settings: { - files: { - relativeTo: string; - }; - bind: any; - }; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) - */ -export interface ServerRegisteredPlugins { - [pluginName: string]: ServerRegisteredPlugin; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) - */ -export interface ServerRegisteredPlugin { - /** the plugin version. */ - version: string; - /** the plugin name. */ - name: string; - /** - * options used to register the plugin. - * TODO update with outcome of: https://github.com/hapijs/hapi/pull/3479 - */ - options: any; // OptionsPassedToPlugin; - /** plugin registration attributes. */ - attributes: PluginAttributes; -} - -export interface ServerAuth { - /** - * server.auth.api - * An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function. - * When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object. - * [See docs](https://hapijs.com/api/16.1.1#serverauthapi) - */ - api: Dictionary; - /** - * server.auth.default - * Sets a default strategy which is applied to every route - * The default does not apply when the route config specifies auth as false, or has an authentication strategy configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication config is applied to the defaults. - * Note that if the route has authentication config, the default only applies at the time of adding the route, not at runtime. This means that calling default() after adding a route with some authentication config will have no impact on the routes added prior. However, the default will apply to routes added before default() is called if those routes lack any authentication config. - * The default auth strategy configuration can be accessed via connection.auth.settings.default. To obtain the active authentication configuration of a route, use connection.auth.lookup(request.route). - * [See docs](https://hapijs.com/api/16.1.1#serverauthdefaultoptions) - */ - default(options: string | AuthOptions): void; - /** - * server.auth.scheme - * Registers an authentication scheme - * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) - * @param name the scheme name. - * @param scheme the method implementing the scheme with signature function(server, options) see ServerAuthScheme - */ - scheme(name: string, scheme: ServerAuthScheme): void; - /** - * Registers an authentication strategy - * [See docs](https://hapijs.com/api/16.1.1#serverauthstrategyname-scheme-mode-options) - * @param name the strategy name. - * @param scheme the scheme name (must be previously registered using server.auth.scheme()). - * @param mode if set to true (which is the same as 'required') or to a valid authentication mode ('required', 'optional', 'try'), the scheme is automatically assigned as the default strategy for any route without an auth config. Can only be assigned to a single server strategy. Defaults to false (no default settings). - * @param options scheme options based on the scheme requirements. - */ - strategy(name: string, scheme: string, options?: any): void; - strategy(name: string, scheme: string, mode: boolean | 'required' | 'optional' | 'try', options?: any): void; - /** - * Tests a request against an authentication strategy - * Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. - * [See docs](https://hapijs.com/api/16.1.1#serverauthteststrategy-request-next) - * @param strategy - the strategy name registered with server.auth.strategy(). - * @param request - the request object. - * @param next - the callback function with signature function(err, credentials) where: - * * err - the error if authentication failed. - * * credentials - the authentication credentials object if authentication was successful. - */ - test(strategy: string, request: Request, next: (err: Error | null, credentials: AuthenticatedCredentials) => void): void; -} - -export type Strategy = any; -export type SchemeSettings = any; - -/** - * the method implementing the scheme with signature function(server, options) where: - * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) - * @param server a reference to the server object the scheme is added to. - * @param options optional scheme settings used to instantiate a strategy. - */ -export interface ServerAuthScheme { - (server: Server, options: SchemeSettings): SchemeMethodResult; -} - -/** - * The scheme method must return an object with the following - * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) - */ -export interface SchemeMethodResult { - /** optional object which is exposed via the server.auth.api object. */ - api?: Strategy; - /** - * required function called on each incoming request configured with the authentication scheme - * When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted (if configured for the route). If the err passed to the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include the scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in the order of preference (defined in the route configuration). If authentication fails the scheme names will be present in the 'WWW-Authenticate' header. - * @param request the request object. - * @param reply the reply interface the authentication method must call when done authenticating the request - */ - authenticate(request: Request, reply: ReplySchemeAuth): void; - /** - * optional function called to authenticate the request payload - * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. - * @param request the request object. - * @param reply is called if authentication failed - */ - payload?(request: Request, reply: ReplySchemeAuthOfPayload): void; - /** - * optional function called to decorate the response with authentication headers before the response headers or payload is written where: - * @param request the request object. - * @param reply is called if an error occured - */ - response?(request: Request, reply: ReplySchemeAuthDecorateResponse): void; - /** an optional object with the following keys: */ - options?: { - /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. */ - payload?: boolean; - }; -} - -export interface ServerCacheMethod { - /** - * Provisions a cache segment within the server cache facility - * [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) - */ - (options: CatboxServerCacheConfiguration): Catbox.Policy; - /** - * Provisions a server cache as described in server.cache - * If no callback is provided, a Promise object is returned. - * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. - * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) - * @param options same as the server cache configuration options. - * @param callback the callback method when cache provisioning is completed or failed with the signature function(err) where: - * * err - any cache startup error condition. - */ - provision(options: CatboxServerCacheConfiguration): Promise; - provision(options: CatboxServerCacheConfiguration, callback: (err?: Error) => void): void; -} - -/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + - + + - + Request + - + + - + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -// TODO: move to separate file http://stackoverflow.com/questions/43276921 - -/** - * Request object - * The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. - * [See docs](https://hapijs.com/api/16.1.1#request-object) - * [See docs](https://hapijs.com/api/16.1.1#request-properties) - */ -export class Request extends Podium { - /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. */ - app: any; - /** authentication information */ - auth: RequestAuthenticationInformation; - /** the connection the request was received by. */ - connection: ServerConnection; - /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains. Set to null when the server useDomains options is false. */ - domain: domain.Domain | null; - /** the raw request headers (references request.raw.headers). */ - headers: Dictionary; - /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ - id: string; - /** request information */ - info: { - /** the request preferred encoding. */ - acceptEncoding: string; - /** if CORS is enabled for the route, contains the following: */ - cors: { - /** - * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. - * Note: marking as optional as "... this is only available after ..." - */ - isOriginMatch?: boolean; - }; - /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ - host: string; - /** the hostname part of the 'Host' header (e.g. 'example.com'). */ - hostname: string; - /** request reception timestamp. */ - received: number; - /** content of the HTTP 'Referrer' (or 'Referer') header. */ - referrer: string; - /** remote client IP address. */ - remoteAddress: string; - /** - * remote client port. - * Set to string in casethey're requesting from a UNIX domain socket. - * TODO, what type does Hapi return, should this be number | string? - */ - remotePort: string; - /** request response timestamp (0 is not responded yet). */ - responded: number; - }; - /** the request method in lower case (e.g. 'get', 'post'). */ - method: string; - /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ - mime: string; - /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. */ - orig: { - params: any; - query: any; - payload: any; - }; - /** an object where each key is a path parameter name with matching value as described in Path parameters [See docs](https://hapijs.com/api/16.1.1#path-parameters). */ - params: Dictionary; - /** an array containing all the path params values in the order they appeared in the path. */ - paramsArray: string[]; - /** the request URI's pathname [See docs](https://nodejs.org/api/url.html#url_urlobject_pathname) component. */ - path: string; - /** - * the request payload based on the route payload.output and payload.parse settings. - * TODO check this typing and add references / links. - */ - payload: stream.Readable | Buffer | any; - /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ - plugins: PluginsStates; - /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses. */ - pre: Object; - /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). */ - response: Response | null; - /** same as pre but represented as the response object created by the pre method. */ - preResponses: Object; - /** - * by default the object outputted from [node's URL parse()](https://nodejs.org/docs/latest/api/url.html#url_urlobject_query) method. - * Might also be set indirectly via [request.setUrl](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/17354#requestseturlurl-striptrailingslash) in which case it may be - * a string (if url is set to an object with the query attribute as an unparsed string). - */ - query: any; - /** an object containing the Node HTTP server objects. **Direct interaction with these raw objects is not recommended.** */ - raw: { - req: http.IncomingMessage; // Or http.ClientRequest http://www.apetuts.com/tutorial/node-js-http-client-request-class/ ? - res: http.ServerResponse; - }; - /** - * the route public interface. - * Optional due to "request.route is not yet populated at this point." [See docs](https://hapijs.com/api/16.1.1#request-lifecycle) - */ - route?: RoutePublicInterface; - /** the server object. */ - server: Server; - /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ - state: Dictionary; - /** the parsed request URI */ - url: url.Url; - - /** - * request.setUrl(url, [stripTrailingSlash]) - * Available only in 'onRequest' extension methods. - * Changes the request URI before the router begins processing the request - * [See docs](https://hapijs.com/api/16.1.1#requestseturlurl-striptrailingslash) - * @param url the new request URI. If url is a string, it is parsed with node's URL parse() method. url can also be set to an object compatible with node's URL parse() method output. - * @param stripTrailingSlash if true, strip the trailing slash from the path. Defaults to false. - */ - setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; - /** - * request.setMethod(method) - * Available only in 'onRequest' extension methods. - * Changes the request method before the router begins processing the request - * [See docs](https://hapijs.com/api/16.1.1#requestsetmethodmethod) - * @param method is the request HTTP method (e.g. 'GET'). - */ - setMethod(method: HTTP_METHODS): void; - /** - * request.generateResponse(source, [options]) - * Always available. - * Returns a response which you can pass into the reply interface where: - * [See docs](https://hapijs.com/api/16.1.1#requestgenerateresponsesource-options) - * @param source the object to set as the source of the reply interface. TODO, submit a PR to clarify this doc, from the source code it's clear that "the object to set" refers to something of type `ReplyValue` i.e. that can be null, string, number, object, Stream, Promise, or Buffer. - * @param options options for the method, optional. Not documented yet, perhaps not very important. - */ - generateResponse(source?: ReplyValue, options?: {marshal?: any; prepare?: any; close?: any; variety?: any}): Response; - /** - * request.log(tags, [data, [timestamp]]) - * Always available. - * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. - * Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. - * [See docs](https://hapijs.com/api/16.1.1#requestlogtags-data-timestamp) - * @param tags a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. - * @param data an optional message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. - * @param timestamp an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). - */ - log(tags: string | string[], data?: string | Object | (() => string | Object), timestamp?: number): void; - /** - * request.getLog([tags], [internal]) - * Always available. - * Returns an array containing the events matching any of the tags specified (logical OR) - * Note that this methods requires the route log configuration set to true. - * [See docs](https://hapijs.com/api/16.1.1#requestgetlogtags-internal) - * @param tags is a single tag string or array of tag strings. If no tags specified, returns all events. - * @param internal filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined). - */ - getLog(tags?: string | string[], internal?: boolean): string[]; - getLog(internal?: boolean): string[]; - /** - * request.tail([name]) - * Available until immediately after the 'response' event is emitted. - * Adds a request tail which has to complete before the request lifecycle is complete. - * Returns a tail function which must be called when the tail activity is completed. - * Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). - * When all tails completed, the server emits a 'tail' event. - * [See docs](https://hapijs.com/api/16.1.1#requesttailname) - * @param name an optional tail name used for logging purposes. - */ - tail(name?: string): (() => void); - /** - * The server.decorate('request', ...) method can modify this prototype/interface. - * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts - * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) - */ - // [index: string]: any; -} - -export interface RequestAuthenticationInformation { - /** true if the request has been successfully authenticated, otherwise false. */ - isAuthenticated: boolean; - /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ - credentials: any; - /** an artifact object received from the authentication strategy and used in authentication-related actions. */ - artifacts: any; - /** the route authentication mode. */ - mode: string; - /** the authentication error is failed and mode set to 'try'. */ - error: Error; -} - -export type HTTP_METHODS_PARTIAL_lowercase = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; -export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_lowercase; -export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; - -/** - * Request events - * The request object supports the following events: - * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). - * * 'disconnect' - emitted when a request errors or aborts unexpectedly. - * [See docs](https://hapijs.com/api/16.1.1#request-events) - */ -export type RequestEventTypes = 'peek' | 'finish' | 'disconnect'; - -/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + - + + - + Handler functions + - + + - + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -// TODO: move to separate file http://stackoverflow.com/questions/43276921 - -/** - * Extending RouteConfiguration.handler - * - * The hapi documentation allows for the RouteConfiguration.handler type to have - * `{[pluginName: string]: pluginOptions}` - * "handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler" - * This can be provided by extending the hapi module definition as follows, - * see h2o2 for example: - * - * declare module 'hapi' { - * interface RouteHandlerPlugins { - * proxy?: ... - */ -export interface RouteHandlerPlugins { -} -/** - * The route handler function uses the signature function(request, reply) (NOTE: do not use a fat arrow style function for route handlers as they do not allow context binding and will cause problems when used in conjunction with server.bind) where: - * * request - is the incoming request object (this is not the node.js request object). - * * reply - the reply interface the handler must call to set a response and return control back to the framework. - * [See docs](https://hapijs.com/api/16.1.1#route-handler) - * Same function signature used by request extension point used in server.ext(event), see ServerExtConfigurationObject.method - */ -export interface RouteHandler { - (request: Request, reply: ReplyNoContinue): void; - // (request: Request, reply: StrictReply): void; -} - -/** - * "the function to call, the function signature is identical to a route handler as described in Route handler." - * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) Route prerequisites - */ -export type RoutePrerequisiteRequestHandler = RouteHandler; - -/** - * request extension points: function(request, reply) where - * this - the object provided via options.bind or the current active context set with server.bind(). - * [See docs](https://hapijs.com/api/16.1.1#serverextevents) - * @param request the request object. - * @param reply the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. If the extension type is 'onPostHandler' or 'onPreResponse', a single argument passed to reply.continue() will override the current set response (including all headers) but will not stop the request lifecycle execution. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. - */ -export interface ServerExtRequestHandler { - (request: Request, reply: ReplyWithContinue): void; -} - -/** - * Used by various extensions to handle a request and - * synchronously return a result of some form. - * - * Left in for backwards compatibility of typings but according to the - * [DefinitelyTyped Readme under common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes) - * it talks about not using generic types unless the type was used in typing one - * or more of the function arguments. Using it to type the return was suggested - * to be the same as a type assertion. - */ -export interface RequestHandler { - (request: Request): T; -} - -/** - * Used by server extension points - * err can be `Boom` error or Error that will be wrapped as a `Boom` error - * For source [See code](https://github.com/hapijs/hapi/blob/v16.1.1/lib/reply.js#L109-L118) - * For source [See code](https://github.com/hapijs/hapi/blob/v16.1.1/lib/response.js#L60-L65) - */ -export interface ContinuationFunction { - (err?: Boom.BoomError): void; -} -/** - * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/response.js#L60-L65) - * TODO Can value be typed with a useful generic? - */ -export interface ContinuationValueFunction { - (err: Boom.BoomError): void; - (err: null | undefined, value: any): void; - (): void; -} - -/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + - + + - + Reply functions + - + + - + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -// TODO: move to separate file http://stackoverflow.com/questions/43276921 - -/** - * Typings listed explicitly here [See docs](https://hapijs.com/api/16.1.1#replyerr-result) - * Typings also described in part here [See docs](https://hapijs.com/api/16.1.1#response-object) - */ -export type ReplyValue = _ReplyValue | Promise<_ReplyValue>; -export type _ReplyValue = null | undefined | string | number | boolean | Buffer | Error | stream.Stream | Object; // | array; - -/** - * Reply interface - * reply([err], [result]) - * Concludes the handler activity by setting a response and returning control over to the framework - * When reply() is called with an error or result response, that value is used as the response sent to the client. When reply() is called within a prerequisite, the value is saved for future use and is not used as the response. In all other places except for the handler, calling reply() will be considered an error and will abort the request lifecycle, jumping directly to the 'onPreResponse' event. - * To return control to the framework within an extension or other places other than the handler, without setting a response, the method reply.continue() must be called. Except when used within an authentication strategy, or in an 'onPostHandler' or 'onPreResponse' extension, the reply.continue() must not be passed any argument or an exception is thrown. - * [See docs](https://hapijs.com/api/16.1.1#reply-interface) - * [See docs](https://hapijs.com/api/16.1.1#replyerr-result) - * - * NOTE: modules should extend this interface to expose reply.Nnn methods - */ -export interface Base_Reply { - (err?: ReplyValue): Response; - (err: null, result?: ReplyValue): Response; - /** the active realm associated with the route. */ - realm: ServerRealm; - /** the request object */ - request: Request; - - /** - * reply.entity(options) - * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request conditions, reply.entity() returns control back to the framework with a 304 response. Otherwise, it sets the provided entity headers and returns null. - * Returns a response object if the reply is unmodified or null if the response has changed. If null is returned, the developer must call reply() to continue execution. If the response is not null, the developer must not call reply(). - * [See docs](https://hapijs.com/api/16.1.1#replyentityoptions) - * @param options a required configuration object with: - * * etag - the ETag string. Required if modified is not present. Defaults to no header. - * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. - * * vary - same as the response.etag() option. Defaults to true. - */ - entity(options: {etag?: string, modified?: string, vary?: boolean}): Response | null; - /** - * reply.close([options]) - * Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed. Supports the following optional options: - * The response flow control rules do not apply. - * [See docs](https://hapijs.com/api/16.1.1#replycloseoptions) - * @param options options object: - * * end - if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. - */ - close(options?: {end?: boolean}): void; - /** - * reply.redirect(uri) - * Redirects the client to the specified uri. Same as calling reply().redirect(uri). - * The response flow control rules apply. - * Sets an HTTP redirection response (302) and decorates the response with additional methods for - * changing to a permanent or non-rewritable redirect is also available see response object redirect for more information. - * [See docs](https://hapijs.com/api/16.1.1#replyredirecturi) - * @param uri an absolute or relative URI used to redirect the client to another resource. - */ - redirect(uri: string): ResponseRedirect; - /** - * reply.response(result) - * Shorthand for calling `reply(null, result)`, replies with the response set to `result`. - * [See docs](https://hapijs.com/api/16.1.1#replyresponseresult) - * TODO likely to change. Await approval of pull request to Hapi docs. - */ - response(result: ReplyValue): Response; - /** - * Sets a cookie on the response - * [See docs](https://hapijs.com/api/16.1.1#reply) - * TODO likely to change. Await approval of pull request to Hapi docs. - */ - state(name: string, value: any, options?: any): void; - /** - * Clears a cookie on the response - * [See docs](https://hapijs.com/api/16.1.1#reply) - * TODO likely to change. Await approval of pull request to Hapi docs. - */ - unstate(name: string, options?: any): void; - /** - * The server.decorate('reply', ...) method can modify this prototype/interface. - * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts - * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) - */ - // [index: string]: any; -} -/** - * reply.continue([result]) - * Returns control back to the framework without ending the request lifecycle - * [See docs](https://hapijs.com/api/16.1.1#replycontinueresult) - * [See docs](https://hapijs.com/api/16.1.1#replyerr-result) "With the exception of the handler function, all other methods provide the reply.continue() method which instructs the framework to continue processing the request without setting a response." - * @param result if called in the handler, prerequisites, or extension points other than the 'onPreHandler' and 'onPreResponse', the result argument is not allowed and will throw an exception if present. If called within an authentication strategy, it sets the authenticated credentials. If called by the 'onPreHandler' or 'onPreResponse' extensions, the result argument overrides the current response including all headers, and returns control back to the framework to continue processing any remaining extensions. - */ -export interface Continue_Reply { - continue(result?: ReplyValue): Response | undefined; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > authenticate. - * Also [See docs](https://hapijs.com/api/16.1.1#replyerr-result). - * TODO check it has Base_Reply methods and properties - */ -export interface ReplySchemeAuth extends Base_Reply { - /** - * This function is called if authentication failed. - * TODO, check type the `response` parameter. In https://hapijs.com/api/16.1.1#replyerr-result it is referred to as "null" but this seems to be for a third scenario where it is "used to return both an error and credentials in the authentication methods" then "reply() must be called with three arguments function(err, null, data)" - * @param err any authentication error. - * @param response any authentication response action such as redirection. Ignored if err is present, otherwise required. - * @param result an object containing: - * * credentials the authenticated credentials. - * * artifacts optional authentication artifacts. - */ - (err: Error | null, response: AnyAuthenticationResponseAction | null, result: AuthenticationResult): void; - /** - * is called if authentication succeeded - * @param result same object as result above. - */ - continue(result: AuthenticationResult): void; -} -/** - * Typing as any as it's not yet clear what type this argument takes. - * "any authentication response action such as redirection" is it equivalent to - * `ReplyValue` ? - * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) - * TODO research hapi source and type this. - */ -export type AnyAuthenticationResponseAction = any; -/** [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) */ -export interface AuthenticationResult { - credentials?: AuthenticatedCredentials; - artifacts?: any; -} -export interface AuthenticatedCredentials { - // Disabled to allow typing within a project - // [index: string]: any; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > payload - * TODO check it has Base_Reply methods and properties - */ -export interface ReplySchemeAuthOfPayload extends Base_Reply { - /** - * function called to authenticate the request payload where: - * @param err any authentication error. - * @param response any authentication response action such as redirection. Ignored if err is present, otherwise required. - */ - (err: Error | null, response: AnyAuthenticationResponseAction): void; - /** is called if payload authentication succeeded */ - continue(): void; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > response - * TODO check it has Base_Reply methods and properties - */ -export interface ReplySchemeAuthDecorateResponse extends Base_Reply { - /** - * is called if an error occurred - * @param err any authentication error. - * @param response any authentication response to send instead of the current response. Ignored if err is present, otherwise required. - */ - (err?: Error, response?: ReplyValue): void; - /** is called if the operation succeeded. */ - continue(): void; -} - -export interface ReplyWithContinue extends Continue_Reply, Base_Reply {} - -export interface ReplyNoContinue extends Base_Reply {} - -// TODO assess use and usefulness of StrictReply - -// Concludes the handler activity by setting a response and returning control over to the framework where: -// erran optional error response. -// result an optional response payload. -// Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. -// FLOW CONTROL: -// When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() -/** - * - */ -// export interface Reply { // extends ReplyMethods { -// (err: Error, -// result?: string | number | boolean | Buffer | stream.Stream | Promise | T, -// /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ -// credentialData?: any): BoomError; -// /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ -// (result: string | number | boolean | Buffer | stream.Stream | Promise | T): Response; -// } - -/** Concludes the handler activity by setting a response and returning control over to the framework where: - erran optional error response. - result an optional response payload. - Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. - FLOW CONTROL: - When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ -// export interface StrictReply extends ReplyMethods { -// (err: Error, -// result?: Promise | T, -// /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ -// credentialData?: any): BoomError; -// /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ -// (result: Promise | T): Response; -// } - -/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + - + + - + Response + - + + - + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -// TODO: move to separate file http://stackoverflow.com/questions/43276921 - -/** - * Response object - * [See docs](https://hapijs.com/api/16.1.1#response-object) - * - * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/16.1.1#response-events) - * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). - */ -export interface Response extends Podium { - /** the HTTP response status code. Defaults to 200 (except for errors). */ - statusCode: number; - /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. */ - headers: Dictionary; - /** the value provided using the reply interface. */ - source: ReplyValue; - /** - * a string indicating the type of source with available values: - * * 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). - * * 'buffer' - a Buffer. - * * 'stream' - a Stream. - * * 'promise' - a Promise object. - */ - variety: 'plain' | 'buffer' | 'stream' | 'promise'; - /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. */ - app: any; - /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ - plugins: PluginsStates; - /** response handling flags: */ - settings: { - /** the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. */ - charset: string; - /** the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. */ - encoding: string; - /** if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. */ - passThrough: boolean; - /** options used for source value requiring stringification. Defaults to no replacer and no space padding. */ - stringify: Json.StringifyArguments; - /** if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. */ - ttl: number | null; - /** if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. */ - varyEtag: boolean; - }; - - /** - * The following attribute is present in one or more of the examples - * TODO update once Hapi docs describes explicitly - */ - isBoom?: boolean; - /** - * The following attribute is present in one or more of the examples - * TODO update once Hapi docs describes explicitly - */ - isMissing?: boolean; - /** - * The following attribute is present in one or more of the examples - * TODO update once Hapi docs describes explicitly - */ - output?: Boom.Output; - - /** - * sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) - * @param length the header value. Must match the actual payload size. - */ - bytes(length: number): Response; - /** - * sets the 'Content-Type' HTTP header 'charset' property - * @param charset the charset property value. - */ - charset(charset: string): Response; - /** - * sets the HTTP status code - * @param statusCode the HTTP status code (e.g. 200). - */ - code(statusCode: number): Response; - /** - * sets the HTTP status message - * @param httpMessage the HTTP status message (e.g. 'Ok' for status code 200). - */ - message(httpMessage: string): Response; - /** - * sets the HTTP status code to Created (201) and the HTTP 'Location' header - * @param uri an absolute or relative URI used as the 'Location' header value. - */ - created(uri: string): Response; - /** - * sets the string encoding scheme used to serial data into the HTTP payload - * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). - * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. - * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. - * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. - * * 'ucs2' - Alias of 'utf16le'. - * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. - * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). - * * 'binary' - Alias for 'latin1'. - * * 'hex' - Encode each byte as two hexadecimal characters. - */ - encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): Response; - /** - * sets the representation entity tag - * @param tag the entity tag string without the double-quote. - * @param options options object - * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. - * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true. - */ - etag(tag: string, options?: {weak: boolean, vary: boolean}): Response; - /** - * sets an HTTP header - * @param name the header name. - * @param value the header value. - */ - header(name: string, value: string, options?: ResponseHeaderOptionsObject): Response; - /** - * sets the HTTP 'Location' header - * @param uri an absolute or relative URI used as the 'Location' header value. - */ - location(uri: string): Response; - /** - * sets an HTTP redirection response (302) and decorates the response with additional methods listed below, - * @param uri an absolute or relative URI used to redirect the client to another resource. - */ - redirect(uri: string): Response; - /** - * sets the JSON.stringify() replacer argument - * @param method the replacer function or array. Defaults to none. - */ - replacer(method: Json.StringifyReplacer): Response; - /** - * sets the JSON.stringify() space argument - * @param count the number of spaces to indent nested object keys. Defaults to no indentation. - */ - spaces(count: Json.StringifySpace): Response; - /** - * sets an HTTP cookie - * @param name the cookie name. - * @param value the cookie value. If no encoding is defined, must be a string. - * @param options optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others). - */ - state(name: string, value: string | Object | any[], options?: ServerStateCookieConfiguationObject): Response; - /** - * sets a string suffix when the response is process via JSON.stringify(). - */ - suffix(suffix: string): Response; - /** - * overrides the default route cache expiration rule for this response instance - * @param msec the time-to-live value in milliseconds. - */ - ttl(msec: number): Response; - /** - * sets the HTTP 'Content-Type' header - * @param mimeType is the mime type. Should only be used to override the built-in default for each response type. - */ - type(mimeType: string): Response; - /** - * clears the HTTP cookie by setting an expired value - * @param name the cookie name. - * @param options optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others). - */ - unstate(name: string, options?: ServerStateCookieConfiguationObject): Response; - /** - * adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header - * @param header the HTTP request header name. - */ - vary(header: string): Response; - - /** - * Flow control - hold() - * When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: - * puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. - * [See docs](https://hapijs.com/api/16.1.1#flow-control) - */ - hold(): Response; - /** - * Flow control - send() - * When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: - * immediately resume the response. Available only after response.hold() is called and until response.send() is invoked once. - * [See docs](https://hapijs.com/api/16.1.1#flow-control) - */ - send(): Response; - - /** - * Mentioned here: "Note that prerequisites do not follow the same rules of the normal reply interface. In all other cases, calling reply() with or without a value will use the result as the response sent back to the client. In a prerequisite method, calling reply() will assign the returned value to the provided assign key. If the returned value is an error, the failAction setting determines the behavior. To force the return value as the response and skip any other prerequisites and the handler, use the reply().takeover() method." - * TODO prepare documentation PR and submit to hapi. - * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) - */ - takeover(): Response; -} - -/** - * Response Object Redirect Methods - * When using the redirect() method, the response object provides these additional methods: - * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) - */ -export interface ResponseRedirect extends Response { - /** - * temporary - * sets the status code to 302 or 307 (based on the rewritable() setting) where: - * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) - * @param isTemporary if false, sets status to permanent. Defaults to true. - */ - temporary(isTemporary: boolean): Response; - /** - * permanent - * sets the status code to 301 or 308 (based on the rewritable() setting) where: - * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) - * @param isPermanent if false, sets status to temporary. Defaults to true. - */ - permanent(isPermanent: boolean): Response; - /** - * rewritable - * sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: - * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) - * @param isRewritable if false, sets to non-rewritable. Defaults to true. - */ - rewritable(isRewritable: boolean): Response; -} - -/** - * [See docs](https://hapijs.com/api/16.1.1#response-object) under "response object provides the following methods" > header > options - */ -export interface ResponseHeaderOptionsObject { - /** if true, the value is appended to any existing header value using separator. Defaults to false. */ - append?: boolean; - /** string used as separator when appending to an existing value. Defaults to ','. */ - separator?: string; - /** if false, the header value is not set if an existing value present. Defaults to true. */ - override?: boolean; - /** if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. */ - duplicate?: boolean; -} - -/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + - + + - + Plugins and register + - + + - + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -// TODO: move to separate file http://stackoverflow.com/questions/43276921 - -/** - * Plugins - * Plugins provide a way to organize the application code by splitting the server logic into smaller components. Each plugin can manipulate the server and its connections through the standard server interface, but with the added ability to sandbox certain properties. - * [See docs](https://hapijs.com/api/16.1.1#plugins) - * @param server the server object the plugin is being registered to. - * @param options an options object passed to the plugin during registration. - * @param next a callback method the function must call to return control back to the framework to complete the registration process with signature function(err) - */ -export interface PluginFunction { - (server: Server, options: OptionsPassedToPlugin, next: (err?: Error) => void): void; - /** - * Note attributes is NOT optional but this type is easier to use. - */ - attributes?: PluginAttributes; -} - -/** - * see Plugin - * [See docs](https://hapijs.com/api/16.1.1#plugins) - */ -export interface PluginAttributes { - /** - * required plugin name string. The name is used as a unique key. Published plugins should use the same name as the name field in the 'package.json' file. Names must be unique within each application. - * NOTE: marked as optional as `pkg` can be used instead. - */ - name?: string; - /** optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's 'package.json' file. */ - version?: string; - /** Alternatively, the name and version can be included via the pkg attribute containing the 'package.json' file for the module which already has the name and version included */ - pkg?: any; - /** if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ - multiple?: boolean; - /** optional string or array of string indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ - dependencies?: string | string[]; - /** if false, does not allow the plugin to call server APIs that modify the connections such as adding a route or configuring state. This flag allows the plugin to be registered before connections are added and to pass dependency requirements. When set to 'conditional', the mode is based on the presence of selected connections (if the server has connections, it is the same as true, but if no connections are available, it is the same as false). Defaults to true. */ - connections?: boolean | 'conditional'; - /** if true, will only register the plugin once per connection (or once per server for a connectionless plugin). If set, overrides the once option passed to server.register(). Defaults to undefined (registration will be based on the server.register() option once). */ - once?: boolean; -} - -/** - * Plugins State - * Related [See docs](https://hapijs.com/api/16.1.1#serverplugins) - * Related [See docs](https://hapijs.com/api/16.1.1#serverrealm) - */ -export interface PluginsStates { - [pluginName: string]: any; -} - -/** - * once, select, routes - optional plugin-specific registration options as defined see PluginRegistrationOptions - * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) - */ -export interface PluginRegistrationObject extends PluginRegistrationOptions { - /** the plugin registration function. */ - register: PluginFunction; - /** optional options passed to the registration function when called. */ - options?: OptionsPassedToPlugin; -} - -/** - * registration options (different from the options passed to the registration function): - * * once - if true, the registration is skipped for any connection already registered with. Cannot be used with plugin options. If the plugin does not have a connections attribute set to false and the registration selection is empty, registration will be skipped as no connections are available to register once. Defaults to false. - * * routes - modifiers applied to each route added by the plugin: - * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. - * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. - * * select - a string or array of string labels used to pre-select connections for plugin registration. - * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) - */ -export interface PluginRegistrationOptions { - once?: boolean; - routes?: {prefix?: string, vhost?: string | string[]}; - select?: string | string[]; -} - -/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + - + + - + + - + JSON + - + + - + + - + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ -// This was in a seperate file and perhaps should move to some of the lib typings? -// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16065#issuecomment-299443673 -// -// json/json-tests.ts -// -// import * as JSON from './index'; -// -// var a: JSON.StringifyReplacer = function(key, value) { -// if (key === "do not include") { -// return undefined; -// } -// return value; -// }; -// - -export namespace Json { - /** - * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} - */ - export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; - - /** - * Any value greater than 10 is truncated. - */ - export type StringifySpace = number | string; - - export interface StringifyArguments { - /** the replacer function or array. Defaults to no action. */ - replacer?: StringifyReplacer; - /** number of spaces to indent nested object keys. Defaults to no indentation. */ - space?: StringifySpace; - } -} +/** PLUGIN */ +export * from './definitions/plugin/plugin'; +export * from './definitions/plugin/plugin-registered'; + +/** REQUEST */ +export * from './definitions/request/request'; +export * from './definitions/request/request-auth'; +export * from './definitions/request/request-events'; +export * from './definitions/request/request-info'; +export * from './definitions/request/request-route'; + +/** RESPONSE */ +export * from './definitions/response/response-events'; +export * from './definitions/response/response-object'; +export * from './definitions/response/response-settings'; +export * from './definitions/response/response-toolkit'; + +/** ROUTE */ +export * from './definitions/route/route-options'; +export * from './definitions/route/route-options-access'; +export * from './definitions/route/route-options-cache'; +export * from './definitions/route/route-options-cors'; +export * from './definitions/route/route-options-payload'; +export * from './definitions/route/route-options-pre'; +export * from './definitions/route/route-options-response'; +export * from './definitions/route/route-options-secure'; +export * from './definitions/route/route-options-validate'; + +/** SERVER */ +export * from './definitions/server/server'; +export * from './definitions/server/server-auth'; +export * from './definitions/server/server-auth-scheme'; +export * from './definitions/server/server-cache'; +export * from './definitions/server/server-events'; +export * from './definitions/server/server-ext'; +export * from './definitions/server/server-info'; +export * from './definitions/server/server-inject'; +export * from './definitions/server/server-method'; +export * from './definitions/server/server-options'; +export * from './definitions/server/server-options-cache'; +export * from './definitions/server/server-realm'; +export * from './definitions/server/server-register'; +export * from './definitions/server/server-route'; +export * from './definitions/server/server-state'; +export * from './definitions/server/server-state-options'; + +/** UTIL */ +export * from './definitions/util/common'; +export * from './definitions/util/json'; +export * from './definitions/util/lifecycle'; +export * from './definitions/util/util'; diff --git a/types/hapi/test/request/catch-all.ts b/types/hapi/test/request/catch-all.ts new file mode 100644 index 0000000000..55db8a548b --- /dev/null +++ b/types/hapi/test/request/catch-all.ts @@ -0,0 +1,15 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route +import { Request, ResponseToolkit, Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; +const server = new Server(options); + +const handler = (request: Request, h: ResponseToolkit) => { + return h.response('The page was not found').code(404); +}; +server.route({ method: '*', path: '/{p*}', handler }); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/request/event-types.ts b/types/hapi/test/request/event-types.ts index 0946f0a0ed..b963340bb5 100644 --- a/types/hapi/test/request/event-types.ts +++ b/types/hapi/test/request/event-types.ts @@ -1,30 +1,65 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +// https://github.com/hapijs/hapi/blob/master/API.md#-requestevents +import { Lifecycle, Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Crypto from 'crypto'; -// From https://hapijs.com/api/16.1.1#requestsetmethodmethod +const options: ServerOptions = { + port: 8000, +}; -import * as Hapi from 'hapi'; -const Crypto = require('crypto'); -const server = new Hapi.Server(); -server.connection({ port: 80 }); +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + } +}; -const onRequest: Hapi.ServerExtRequestHandler = function (request, reply) { +const onRequest: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { + /* + * Server events + */ + request.server.events.on('request', (request: Request, event: any, tags: any) => { + console.log(request.paramsArray); + console.log(event); + console.log(tags); + }); + request.server.events.on('response', (request: Request) => { + console.log('Response sent for request: ' + request.path); + }); + + request.server.events.on('start', (route: RouteOptions) => { + console.log('Server started'); + }); + + request.server.events.once('stop', (route: RouteOptions) => { + console.log('Server stoped'); + }); + + /* + * Request events + */ const hash = Crypto.createHash('sha1'); - request.on('peek', (chunk) => { + request.events.on("peek", (chunk: any) => { hash.update(chunk); }); - request.once('finish', () => { - + request.events.once("finish", () => { console.log(hash.digest('hex')); }); - request.once('disconnect', () => { - + request.events.once("disconnect", () => { console.error('request aborted'); }); - return reply.continue(); + return h.continue; }; +const server = new Server(options); +server.route(serverRoute); server.ext('onRequest', onRequest); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/request/get-log.ts b/types/hapi/test/request/get-log.ts index 289bdd3282..731e8ea35c 100644 --- a/types/hapi/test/request/get-log.ts +++ b/types/hapi/test/request/get-log.ts @@ -1,12 +1,29 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data +import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; -// From https://hapijs.com/api/16.1.1#requestgetlogtags-internal +const options: ServerOptions = { + port: 8000, +}; -import * as Hapi from 'hapi'; +const handlerFn: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { + request.log(['test', 'error'], 'Test event'); + return 'path: ' + request.path; +}; -var request: Hapi.Request = {}; +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: handlerFn +}; -request.getLog(); -request.getLog('error'); -request.getLog(['error', 'auth']); -request.getLog(['error'], true); -request.getLog(false); +const server = new Server(options); +server.route(serverRoute); +server.start(); +console.log('Server started at: ' + server.info.uri); + +server.events.on('request', (request: Request, event: any, tags: any) => { + console.log(tags); + if (tags.error) { + console.log(event); + } +}); diff --git a/types/hapi/test/request/parameters.ts b/types/hapi/test/request/parameters.ts new file mode 100644 index 0000000000..1dadbcc1eb --- /dev/null +++ b/types/hapi/test/request/parameters.ts @@ -0,0 +1,37 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-requestparams +import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +// Example 1 +// http://localhost:8000/album-name/song-optional +const getAlbum: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { + console.log(request.params); + return 'ok: ' + request.path; +}; +const serverRoute1: ServerRoute = { + path: '/{album}/{song?}', + method: 'GET', + handler: getAlbum +}; + +// Example 2 +// http://localhost:8000/person/rafael/fijalkowski +const getPerson: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { + const nameParts = request.params.name.split('/'); + return { first: nameParts[0], last: nameParts[1] }; +}; +const serverRoute2: ServerRoute = { + path: '/person/{name*2}', + method: 'GET', + handler: getPerson +}; + +const server = new Server(options); +server.route(serverRoute1); +server.route(serverRoute2); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/request/query.ts b/types/hapi/test/request/query.ts index c6507c2da0..1f8ea89c1b 100644 --- a/types/hapi/test/request/query.ts +++ b/types/hapi/test/request/query.ts @@ -1,14 +1,27 @@ // Added test in addition to docs, for request.query +import { Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; -import * as Hapi from 'hapi'; +const options: ServerOptions = { + port: 8000, +}; + +const handlerFn: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { + const query = request.query as GetThingQuery; + // http://localhost:8000/?name=test + return `You asked for ${query.name}`; +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: handlerFn +}; interface GetThingQuery { name: string; } -const handler: Hapi.RouteHandler = function (request, reply) { - - const query = request.query as GetThingQuery; - - return reply(`You asked for ${query.name}`); -}; +const server = new Server(options); +server.route(serverRoute); +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/response/continue.ts b/types/hapi/test/response/continue.ts new file mode 100644 index 0000000000..00bdbc9ff2 --- /dev/null +++ b/types/hapi/test/response/continue.ts @@ -0,0 +1,25 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/test', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + } +}; + +const server = new Server(options); +server.route(serverRoute); + +server.ext("onRequest", (request: Request, h: ResponseToolkit) => { + request.setUrl('/test'); + return h.continue; +}); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/response/error.ts b/types/hapi/test/response/error.ts index 0ef503df12..52937eaa4a 100644 --- a/types/hapi/test/response/error.ts +++ b/types/hapi/test/response/error.ts @@ -1,25 +1,30 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#errors +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Boom from "boom"; -// From https://hapijs.com/api/16.1.1#error-response +const options: ServerOptions = { + port: 8000, +}; -import * as Hapi from 'hapi'; -const Boom = require('boom'); +const serverRoutes: ServerRoute[] = [ + { + path: '/badRequest', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + throw Boom.badRequest('Unsupported parameter'); + } + }, + { + path: '/internal', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + throw new Error('unexpect error'); + } + }, +]; -const server = new Hapi.Server(); +const server = new Server(options); +server.route(serverRoutes); -server.route({ - method: 'GET', - path: '/badRequest', - handler: function (request, reply) { - - return reply(Boom.badRequest('Unsupported parameter')); - } -}); - -server.route({ - method: 'GET', - path: '/internal', - handler: function (request, reply) { - - return reply(new Error('unexpect error')); - } -}); +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/response/redirect.ts b/types/hapi/test/response/redirect.ts new file mode 100644 index 0000000000..d7503fd5f9 --- /dev/null +++ b/types/hapi/test/response/redirect.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return h.redirect('http://example.com'); + } +}; + +const server = new Server(options); +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/response/response-events.ts b/types/hapi/test/response/response-events.ts new file mode 100644 index 0000000000..0680f7f7f8 --- /dev/null +++ b/types/hapi/test/response/response-events.ts @@ -0,0 +1,28 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-responseevents +import { Request, ResponseObject, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Crypto from "crypto"; + +const preResponse = (request: Request, h: ResponseToolkit) => { + // In onPreResponse, the response object will be defined. + const response: ResponseObject = request.response!; + + const hash = Crypto.createHash('sha1'); + response.events.on('peek', (chunk: any) => { + hash.update(chunk); + }); + + response.events.once('finish', () => { + console.log(hash.digest('hex')); + }); + + return h.continue; +}; + +const server = new Server({ + port: 8000, +}); + +server.ext('onPreResponse', preResponse); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/response/response.ts b/types/hapi/test/response/response.ts new file mode 100644 index 0000000000..593eddb0fb --- /dev/null +++ b/types/hapi/test/response/response.ts @@ -0,0 +1,36 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoutes: ServerRoute[] = [ + // Detailed notation + { + path: '/test1', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + const response = h.response('success'); + response.type('text/plain'); + response.header('X-Custom', 'some-value'); + return response; + } + }, + // Chained notation + { + path: '/test2', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return h.response('success') + .type('text/plain') + .header('X-Custom', 'some-value'); + } + }, +]; + +const server = new Server(options); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/route/adding-routes.ts b/types/hapi/test/route/adding-routes.ts new file mode 100644 index 0000000000..55c58d1437 --- /dev/null +++ b/types/hapi/test/route/adding-routes.ts @@ -0,0 +1,38 @@ +// from https://hapijs.com/tutorials/getting-started#adding-routes +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + } +}; + +const serverRoutes: ServerRoute[] = [ + { + path: '/test1', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + } + }, + { + path: '/test2', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + } + }, +]; + +const server = new Server(options); +server.route(serverRoute); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/route/config.ts b/types/hapi/test/route/config.ts index 16457395f8..8272e767f1 100644 --- a/types/hapi/test/route/config.ts +++ b/types/hapi/test/route/config.ts @@ -1,46 +1,52 @@ -'use strict'; +import { Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute } from "hapi"; -import * as Hapi from 'hapi'; +const options: ServerOptions = { + port: 8000, +}; // different methods -var routeConfig: Hapi.RouteConfiguration = { +const routeConfig: ServerRoute = { path: '/signin', method: 'PUT', vhost: 'site.coms', }; -var routeConfig: Hapi.RouteConfiguration = { +const routeConfigTest1: ServerRoute = { path: '/signin', method: '*' }; -var routeConfig: Hapi.RouteConfiguration = { +const routeConfigTest2: ServerRoute = { path: '/signin', method: ['OPTIONS', '*'] }; // different handlers -var routeConfig: Hapi.RouteConfiguration = { +const routeConfigTest3: ServerRoute = { path: '/signin', method: 'PUT', - handler: 'some registered handler' + handler: (request: Request, h: ResponseToolkit) => { + return 'ok'; + } }; -var routeConfig: Hapi.RouteConfiguration = { +const routeConfigTest4: ServerRoute = { path: '/signin', method: 'PUT', - handler: function (request, reply) { - return reply('ok'); + handler: (request: Request, h: ResponseToolkit) => { + return 'ok'; } }; -const server = new Hapi.Server(); +const server = new Server(options); server.route(routeConfig); // Handler in config -const user: Hapi.RouteAdditionalConfigurationOptions = { +const user: RouteOptions = { cache: { expiresIn: 5000 }, - handler: function (request, reply) { - - return reply({ name: 'John' }); + handler: (request: Request, h: ResponseToolkit) => { + return { name: 'John' }; } }; -server.route({method: 'GET', path: '/user', config: user }); +server.route({method: 'GET', path: '/user', options: user }); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/route/handler.ts b/types/hapi/test/route/handler.ts index c66d17018e..b9354f00d8 100644 --- a/types/hapi/test/route/handler.ts +++ b/types/hapi/test/route/handler.ts @@ -1,10 +1,9 @@ -'use strict'; +import { Lifecycle, Request, ResponseToolkit } from "hapi"; -import * as Hapi from 'hapi'; +const handler: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { + return 'success'; +}; -var handler: Hapi.RouteHandler = function(request, reply) { - reply('success'); -} -var strictHandler: Hapi.RouteHandler = function(request, reply) { - reply(123); -} +const strictHandler: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { + return 123; +}; diff --git a/types/hapi/test/route/route-options-pre.ts b/types/hapi/test/route/route-options-pre.ts new file mode 100644 index 0000000000..139e93a0f8 --- /dev/null +++ b/types/hapi/test/route/route-options-pre.ts @@ -0,0 +1,42 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre +import { Request, ResponseToolkit, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const pre1 = (request: Request, h: ResponseToolkit) => { + return 'Hello'; +}; + +const pre2 = (request: Request, h: ResponseToolkit) => { + return 'World'; +}; + +const pre3 = (request: Request, h: ResponseToolkit) => { + return `request.pre.m1 request.pre.m2`; +}; + +server.route({ + method: 'GET', + path: '/', + config: { + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + handler: (request: Request, h: ResponseToolkit) => { + return request.pre.m3 + '!\n'; + } + } +}); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/test/route/route-options.ts b/types/hapi/test/route/route-options.ts new file mode 100644 index 0000000000..b5a9f87ce1 --- /dev/null +++ b/types/hapi/test/route/route-options.ts @@ -0,0 +1,168 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#route-options +import { + Request, + ResponseToolkit, + RouteOptions, + RouteOptionsAccess, + RouteOptionsCors, + RouteOptionsPayload, + RouteOptionsResponse, + RouteOptionsValidate, + Server +} from "hapi"; + +const routeOptionsAccess: RouteOptionsAccess = { + access: [ + { + scope: false + }, + { + entity: 'user' + } + ], + scope: false, + entity: 'user', + mode: 'optional', + payload: 'optional', + strategies: ['', ''], + strategy: '' +}; + +const corsOption: RouteOptionsCors = { + origin: 'ignore', + maxAge: 5000, + headers: ['test', 'test', 'test'], + additionalHeaders: ['test', 'test', 'test'], + exposedHeaders: ['test', 'test', 'test'], + additionalExposedHeaders: ['test', 'test', 'test'], + credentials: false +}; + +const payloadOptions: RouteOptionsPayload = { + allow: 'string', + compression: { + test1: { + test: 2 + } + }, + defaultContentType: 'application/json', + failAction: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + maxBytes: 1048576, + multipart: { + output: 'annotated' + }, + output: 'stream', + override: '', + parse: 'gunzip', + timeout: 5000, + uploads: 'dir/' +}; + +const pre1 = (request: Request, h: ResponseToolkit) => { + return 'Hello'; +}; + +const pre2 = (request: Request, h: ResponseToolkit) => { + return 'World'; +}; + +const pre3 = (request: Request, h: ResponseToolkit) => { + return `request.pre.m1 request.pre.m2`; +}; + +const routeOptionsResponse: RouteOptionsResponse = { + emptyStatusCode: 200, + failAction: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + modify: false, + options: undefined, + ranges: true, + sample: 100, + schema: true, + status: { + 200: true, + 302: true, + 404: false, + } +}; + +const routeOptionsValidate: RouteOptionsValidate = { + errorFields: {}, + failAction: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + headers: false, + options: {}, + params: false, + payload: true, + query: true, +}; + +const routeOptions: RouteOptions = { + app: {}, + auth: routeOptionsAccess, + bind: null, + cache: { + privacy: 'default', + statuses: [200], + otherwise: 'no-cache' + }, + compression: { + test1: { + test: 2 + } + }, + cors: corsOption, + description: 'description here', + ext: undefined, + files: { relativeTo: '.' }, + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + id: 'test', + isInternal: false, + json: undefined, + jsonp: 'callback', + log: { collect: false }, + notes: ['test', 'test', 'test'], + payload: payloadOptions, + plugins: { + plugin1: {}, + plugin2: {}, + }, + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + response: routeOptionsResponse, + security: false, + state: { + parse: true, + failAction: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + }, + tags: ['test', 'test', 'test'], + timeout: { + server: 10000, + socket: false + }, + validate: routeOptionsValidate +}; + +const server = new Server({ + port: 8000, + routes: routeOptions +}); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/test/route/validation.ts b/types/hapi/test/route/validation.ts new file mode 100644 index 0000000000..5296183e87 --- /dev/null +++ b/types/hapi/test/route/validation.ts @@ -0,0 +1,30 @@ +// from https://hapijs.com/tutorials/validation?lang=en_US +import { ServerRouteConfig, Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; +import * as Joi from "joi"; + +const options: ServerOptions = { + port: 8000, +}; + +const configObject: ServerRouteConfig = { + validate: { + params: { + name: Joi.string().min(3).max(10) + } + } +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + config: configObject +}; + +const server = new Server(options); +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/server/server-app.ts b/types/hapi/test/server/server-app.ts new file mode 100644 index 0000000000..57298a4672 --- /dev/null +++ b/types/hapi/test/server/server-app.ts @@ -0,0 +1,29 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverapp +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +declare module "hapi" { + // Demonstrate augmenting the application state. + interface ApplicationState { + key: string; + } +} + +const server = new Server(options); +server.app!.key = 'value2'; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'key: ' + request.server.app!.key; + } +}; + +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/server/server-auth-api.ts b/types/hapi/test/server/server-auth-api.ts new file mode 100644 index 0000000000..3b80dc7e47 --- /dev/null +++ b/types/hapi/test/server/server-auth-api.ts @@ -0,0 +1,36 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi +import { + Request, + ResponseToolkit, + Server, + ServerAuthScheme, + ServerAuthSchemeObject, + ServerAuthSchemeOptions +} from "hapi"; +import * as Boom from "boom"; + +const scheme: ServerAuthScheme = (server: Server, options: ServerAuthSchemeOptions): ServerAuthSchemeObject => { + return { + api: { + settings: { + x: 5 + } + }, + authenticate: (request: Request, h: ResponseToolkit) => { + const authorization = request.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: 'john' } }); + } + }; +}; + +const server = new Server({ + port: 8000, +}); +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); +server.start(); + +console.log(server.auth.api.default.settings.x); // 5 diff --git a/types/hapi/test/server/server-auth-default.ts b/types/hapi/test/server/server-auth-default.ts new file mode 100644 index 0000000000..3ec9919150 --- /dev/null +++ b/types/hapi/test/server/server-auth-default.ts @@ -0,0 +1,35 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme +import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; +import * as Boom from "boom"; + +const server = new Server({ + port: 8000, +}); + +const scheme: ServerAuthScheme = (server: Server, options: ServerAuthSchemeOptions) => { + return { + authenticate: (request: Request, h: ResponseToolkit) => { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: 'john' } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); +server.auth.default('default'); + +server.route({ + method: 'GET', + path: '/', + handler: (request: Request, h: ResponseToolkit) => { + return request.auth.credentials.user; + } +}); + +server.start(); diff --git a/types/hapi/test/server/server-auth-test.ts b/types/hapi/test/server/server-auth-test.ts new file mode 100644 index 0000000000..ae77089ddf --- /dev/null +++ b/types/hapi/test/server/server-auth-test.ts @@ -0,0 +1,39 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme +import { Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions } from "hapi"; +import * as Boom from "boom"; + +const server = new Server({ + port: 8000, +}); + +const scheme: ServerAuthScheme = (server: Server, options: ServerAuthSchemeOptions) => { + return { + authenticate: (request: Request, h: ResponseToolkit) => { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: 'john' } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + handler: async (request: Request, h: ResponseToolkit) => { + try { + const credentials = await request.server.auth.test('default', request); + return { status: true, user: credentials.name }; + } catch (err) { + return { status: false }; + } + } +}); + +server.start(); diff --git a/types/hapi/test/server/server-bind.ts b/types/hapi/test/server/server-bind.ts new file mode 100644 index 0000000000..9bec0ec5f9 --- /dev/null +++ b/types/hapi/test/server/server-bind.ts @@ -0,0 +1,27 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext +import { Plugin, Request, ResponseToolkit, Server, ServerRegisterOptions } from "hapi"; + +const server = new Server({ + port: 8000, +}); +const handler = (request: Request, h: ResponseToolkit) => { + return h.context.message; // Or h.context.message +}; + +const plugin: Plugin = { + name: 'example', + register: async (server: Server, options: ServerRegisterOptions) => { + const bind = { + message: 'hello' + }; + server.bind(bind); + server.route({ method: 'GET', path: '/', handler }); + } +}; + +server.start(); +server.register(plugin); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/test/server/server-cache-provision.ts b/types/hapi/test/server/server-cache-provision.ts new file mode 100644 index 0000000000..f30ce65cd6 --- /dev/null +++ b/types/hapi/test/server/server-cache-provision.ts @@ -0,0 +1,19 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions +import { Server } from "hapi"; +import * as catbox from "catbox"; + +const server = new Server({ + port: 8000, +}); +server.initialize(); +server.cache.provision({engine: require('catbox-memory'), name: 'countries' }); + +const cache: catbox.Policy = server.cache({segment: 'countries', cache: 'countries', expiresIn: 60 * 60 * 1000 }); +cache.set('norway', 'oslo', 10 * 1000, () => {}); +const value = cache.get('norway', () => {}); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/test/server/server-cache.ts b/types/hapi/test/server/server-cache.ts new file mode 100644 index 0000000000..64f8c85e80 --- /dev/null +++ b/types/hapi/test/server/server-cache.ts @@ -0,0 +1,23 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions +import { Server, ServerOptionsCache } from "hapi"; +import * as catbox from "catbox"; + +const server = new Server({ + port: 8000, +}); + +const catboxOptions: ServerOptionsCache = { + segment: 'countries', + expiresIn: 60 * 60 * 1000 +}; +const cache: catbox.Policy = server.cache(catboxOptions); +cache.set('norway', 'oslo', 10 * 1000, () => {}); + +const value = cache.get('norway', () => {}); +console.log("Value: " + value); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/test/server/server-decoder.ts b/types/hapi/test/server/server-decoder.ts new file mode 100644 index 0000000000..965745ee7c --- /dev/null +++ b/types/hapi/test/server/server-decoder.ts @@ -0,0 +1,8 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder +import { Server } from "hapi"; +import * as Zlib from "zlib"; + +const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); +server.decoder('special', (options) => Zlib.createGunzip(options)); + +server.start(); diff --git a/types/hapi/test/server/server-decorations.ts b/types/hapi/test/server/server-decorations.ts new file mode 100644 index 0000000000..8ee7dfaaa3 --- /dev/null +++ b/types/hapi/test/server/server-decorations.ts @@ -0,0 +1,15 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options +import { ResponseToolkit, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const success = (h: ResponseToolkit) => { + return h.response({ status: 'ok' }); +}; + +server.start(); +server.decorate('toolkit', 'success', success); + +console.log(server.decorations.toolkit); diff --git a/types/hapi/test/server/server-encoder.ts b/types/hapi/test/server/server-encoder.ts new file mode 100644 index 0000000000..dd9f12f4db --- /dev/null +++ b/types/hapi/test/server/server-encoder.ts @@ -0,0 +1,8 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder +import { Server } from "hapi"; +import * as Zlib from "zlib"; + +const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); +server.encoder('special', (options) => Zlib.createGzip(options)); + +server.start(); diff --git a/types/hapi/test/server/server-events-once.ts b/types/hapi/test/server/server-events-once.ts new file mode 100644 index 0000000000..06261e8aae --- /dev/null +++ b/types/hapi/test/server/server-events-once.ts @@ -0,0 +1,24 @@ +// from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener +import { Request, ResponseToolkit, Server, ServerRoute } from "hapi"; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'oks: ' + request.path; + } +}; + +const server = new Server({ + port: 8000, +}); +server.route(serverRoute); +server.event('test1'); +server.event('test2'); +server.events.once('test1', (update: any) => { console.log(update); }); +server.events.once('test2', (...args: any[]) => { console.log(args); }); +server.events.emit('test1', 'hello-1'); +server.events.emit('test2', 'hello-2'); // Ignored + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/server/server-events.ts b/types/hapi/test/server/server-events.ts new file mode 100644 index 0000000000..d17af569ae --- /dev/null +++ b/types/hapi/test/server/server-events.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.event('test'); +server.events.on('test', (update: any) => console.log(update)); +server.events.emit('test', 'hello'); + +server.start(); diff --git a/types/hapi/test/server/server-expose.ts b/types/hapi/test/server/server-expose.ts new file mode 100644 index 0000000000..2f1424b2ba --- /dev/null +++ b/types/hapi/test/server/server-expose.ts @@ -0,0 +1,24 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +import { Plugin, Server, ServerRegisterOptions } from "hapi"; + +const plugin1: Plugin = { + name: 'example1', + register: async (server: Server, options: ServerRegisterOptions) => { + server.expose('util', () => console.log('something')); + } +}; + +const plugin2: Plugin = { + name: 'example2', + register: async (server: Server, options: ServerRegisterOptions) => { + server.expose('util', () => console.log('something')); + } +}; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.register(plugin1); +server.register(plugin2); diff --git a/types/hapi/test/server/server-info.ts b/types/hapi/test/server/server-info.ts new file mode 100644 index 0000000000..58045b19da --- /dev/null +++ b/types/hapi/test/server/server-info.ts @@ -0,0 +1,10 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +console.log(server.info); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/server/server-inject.ts b/types/hapi/test/server/server-inject.ts new file mode 100644 index 0000000000..477a3b2ec4 --- /dev/null +++ b/types/hapi/test/server/server-inject.ts @@ -0,0 +1,19 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions +import { Request, ResponseToolkit, Server, ServerRoute } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'Success!'; + } +}; + +server.route(serverRoute); +server.start(); + +server.inject('/').then(res => console.log(res.result)); diff --git a/types/hapi/test/server/server-listener.ts b/types/hapi/test/server/server-listener.ts new file mode 100644 index 0000000000..160821f505 --- /dev/null +++ b/types/hapi/test/server/server-listener.ts @@ -0,0 +1,14 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener +import { Server } from "hapi"; +import * as SocketIO from "socket.io"; + +const server = new Server({ + port: 8000, +}); + +const io = SocketIO.listen(server.listener); +io.sockets.on('connection', (socket) => { + socket.emit('welcome'); +}); + +server.start(); diff --git a/types/hapi/test/server/server-load.ts b/types/hapi/test/server/server-load.ts new file mode 100644 index 0000000000..d2ae11848a --- /dev/null +++ b/types/hapi/test/server/server-load.ts @@ -0,0 +1,14 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverload +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, + load: { sampleInterval: 1000 } +}); +server.start(); + +setTimeout(() => { + console.log(server.load.rss); + console.log(server.load.eventLoopDelay); + console.log(server.load.heapUsed); +}, 5 * 1000); diff --git a/types/hapi/test/server/server-lookup.ts b/types/hapi/test/server/server-lookup.ts new file mode 100644 index 0000000000..651ba0cd8b --- /dev/null +++ b/types/hapi/test/server/server-lookup.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid +import { RequestRoute, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.route({ + path: '/', + method: 'GET', + config: { + id: 'root', + handler: () => 'ok' + } +}); + +const route: RequestRoute | null = server.lookup('root'); +console.log(route); + +server.start(); diff --git a/types/hapi/test/server/server-match.ts b/types/hapi/test/server/server-match.ts new file mode 100644 index 0000000000..27f59991b5 --- /dev/null +++ b/types/hapi/test/server/server-match.ts @@ -0,0 +1,23 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host +import { RequestRoute, Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.route({ + path: '/', + method: 'GET', + config: { + id: 'root', + handler: () => 'ok' + } +}); + +const route: RequestRoute | null = server.match('get', '/'); + +if (route !== null) { + console.log(route.path); +} + +server.start(); diff --git a/types/hapi/test/server/server-method.ts b/types/hapi/test/server/server-method.ts new file mode 100644 index 0000000000..2d2b3bdf58 --- /dev/null +++ b/types/hapi/test/server/server-method.ts @@ -0,0 +1,24 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods +import { Server, ServerMethodConfigurationObject } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +const add = (a: any, b: any) => { + return a + b; +}; + +const methodObject: ServerMethodConfigurationObject = { + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000, + generateTimeout: 100 + } + } +}; + +server.method(methodObject); diff --git a/types/hapi/test/server/server-methods.ts b/types/hapi/test/server/server-methods.ts new file mode 100644 index 0000000000..f9a2d08e6c --- /dev/null +++ b/types/hapi/test/server/server-methods.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethods +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +server.method('add', (a, b) => (a + b)); +const result = server.methods.add(1, 2); // 3 +console.log(result); diff --git a/types/hapi/test/server/server-mime.ts b/types/hapi/test/server/server-mime.ts new file mode 100644 index 0000000000..3a50da2154 --- /dev/null +++ b/types/hapi/test/server/server-mime.ts @@ -0,0 +1,22 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermime +import { Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } +}; + +const server = new Server(options); +console.log(server.mime.path('code.js').type); // 'application/javascript' +console.log(server.mime.path('file.npm').type); // 'node/module' + +server.start(); diff --git a/types/hapi/test/server/server-options.ts b/types/hapi/test/server/server-options.ts new file mode 100644 index 0000000000..ce487bbb20 --- /dev/null +++ b/types/hapi/test/server/server-options.ts @@ -0,0 +1,106 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-server-options +import { Plugin, RouteOptions, Server, ServerOptions, ServerRegisterOptions } from "hapi"; +import { MimosOptions, MimosOptionsValue } from "mimos"; + +const mimeOptions: MimosOptions = { + override: { + 'node/module': { + source: 'iana', + compressible: true, + extensions: ['node', 'modsule', 'npm'], + type: 'node/module' + }, + 'application/javascript': { + source: 'iana', + charset: 'UTF-8', + compressible: true, + extensions: ['js', 'javascript'], + type: 'text/javascript' + }, + 'text/html': { + predicate: (mime: MimosOptionsValue) => { + if (1 === 1) { + // mime.foo = 'test'; + } else { + // mime.foo = 'bar'; + } + return mime; + } + } + } +}; + +const plugin: Plugin = { + name: 'example', + register: async (server: Server, options: ServerRegisterOptions) => { + server.expose('key', 'value'); + server.plugins.example.other = 'other'; + console.log(server.plugins.example.key); // 'value' + console.log(server.plugins.example.other); // 'other' + } +}; + +const routeOptions: RouteOptions = { + compression: { + test: { + some: 'option' + } + }, + files: { + relativeTo: __dirname + }, + cors: { + origin: ['http://test.example.com', 'http://www.example.com', 'http://*.a.com'] + }, +}; + +const options: ServerOptions = { + address: '0.0.0.0', + app: { + key1: 'value1', + key2: 'value2', + any_thing: 'any_value', + }, + autoListen: true, + cache: { + engine: require('catbox-memory'), + name: 'test', + shared: true, + partition: 'hapi-cache', + any_thing_1: 'any_thing_1', + any_thing_2: 'any_thing_2' + }, + compression: { + minBytes: 1024 + }, + debug: { + request: ['implementation'] + }, + host: 'localhost', + listener: undefined, + load: { sampleInterval: 0 }, + mime: mimeOptions, + plugins: plugin, + port: 8000, + router: { + isCaseSensitive: true, + stripTrailingSlash: false + }, + routes: routeOptions, + state: { + strictHeader: true, + ignoreErrors: false, + isSecure: true, + isHttpOnly: true, + isSameSite: 'Strict', + encoding: 'none' + }, + tls: undefined +}; + +const server = new Server(options); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/test/server/server-path.ts b/types/hapi/test/server/server-path.ts new file mode 100644 index 0000000000..36f346cb10 --- /dev/null +++ b/types/hapi/test/server/server-path.ts @@ -0,0 +1,30 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto +import { Plugin, Server, ServerRegisterOptions, ServerRoute } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const serverRouteOption: ServerRoute = { + path: '/file', + method: 'GET', + handler: { + file: './test.html' + } +}; + +const plugin: Plugin = { + name: 'example', + register: async (server: Server, options: ServerRegisterOptions) => { + // Assuming the Inert plugin was registered previously + server.path(__dirname + '../static'); + server.route(serverRouteOption); + } +}; + +server.start(); +server.register(plugin); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/test/server/server-plugins.ts b/types/hapi/test/server/server-plugins.ts new file mode 100644 index 0000000000..970b53fb6d --- /dev/null +++ b/types/hapi/test/server/server-plugins.ts @@ -0,0 +1,85 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +import { Plugin, Server, ServerRegisterOptions } from "hapi"; + +interface Plugin1 { + one: 1; +} + +interface Plugin2 { + two: 2; +} + +interface Plugin3 { + three: 3; +} + +const plugin1: Plugin = { + name: 'plugin1', + register: async (server: Server, options: Plugin1) => { + server.expose('key', 'value'); + server.plugins.example.other = 'other'; + console.log(server.plugins.example.key); // 'value' + console.log(server.plugins.example.other); // 'other' + } +}; + +const plugin2: Plugin = { + name: 'plugin2', + register: async (server: Server, options: Plugin2) => {} +}; + +const plugin3: Plugin = { + name: 'plugin3', + register: async (server: Server, options: Plugin3) => {} +}; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.register(plugin1); + +server.register({ + plugin: plugin1, + options: {one: 1} +}); + +server.register([ + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + }, + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + }, + { + plugin: plugin2, + options: {two: 2} + }, + { + plugin: plugin3, + options: {three: 3} + }, + { + plugin: plugin1, + options: {one: 1} + } +]); diff --git a/types/hapi/test/server/server-settings.ts b/types/hapi/test/server/server-settings.ts new file mode 100644 index 0000000000..488e31629b --- /dev/null +++ b/types/hapi/test/server/server-settings.ts @@ -0,0 +1,12 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serversettings +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, + app: { + key: 'value' + } +}); +server.start(); + +console.log(server.settings.app); // { key: 'value' } diff --git a/types/hapi/test/server/server-start.ts b/types/hapi/test/server/server-start.ts new file mode 100644 index 0000000000..f41349e88c --- /dev/null +++ b/types/hapi/test/server/server-start.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/test/server/server-state.ts b/types/hapi/test/server/server-state.ts new file mode 100644 index 0000000000..9c51ee4748 --- /dev/null +++ b/types/hapi/test/server/server-state.ts @@ -0,0 +1,27 @@ +// from https://hapijs.com/tutorials/cookies?lang=en_US +import { Request, ResponseToolkit, Server, ServerOptions, ServerRoute, ServerStateCookieOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/say-hello', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return h.response('Hello').state('data', { firstVisit: false }); + } +}; + +const server = new Server(options); +server.route(serverRoute); + +const stateOption: ServerStateCookieOptions = { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: false, + isHttpOnly: false, + encoding: 'base64json', +}; +server.state('data', stateOption); +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/server/server-stop.ts b/types/hapi/test/server/server-stop.ts new file mode 100644 index 0000000000..7922fa944e --- /dev/null +++ b/types/hapi/test/server/server-stop.ts @@ -0,0 +1,17 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); +server.events.on('stop', () => { + console.log('Server stoped.'); +}); +setTimeout(() => { + server.stop({ timeout: 10 * 1000 }); +}, 5 * 1000); diff --git a/types/hapi/test/server/server-table.ts b/types/hapi/test/server/server-table.ts new file mode 100644 index 0000000000..02f83e90fd --- /dev/null +++ b/types/hapi/test/server/server-table.ts @@ -0,0 +1,22 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost +import { Request, ResponseToolkit, Server, ServerOptions } from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const server = new Server(options); +server.app!.key = 'value2'; + +server.route({ + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return h.response("Hello World"); + } +}); + +server.start(); +const table = server.table(); +console.log(table); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/test/server/server-version.ts b/types/hapi/test/server/server-version.ts new file mode 100644 index 0000000000..b8e59497fc --- /dev/null +++ b/types/hapi/test/server/server-version.ts @@ -0,0 +1,9 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverversion +import { Server } from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.start(); +console.log(server.version); // 17.x.x diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index 53f8f2ece6..fd19f07bf6 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -24,80 +24,52 @@ }, "files": [ "index.d.ts", - "test/connection/table.ts", - "test/continuation/errors.ts", - "test/getting-started/01-creating-a-server.ts", - "test/getting-started/02-adding-routes.ts", - "test/getting-started/03-serving-static-content.ts", - "test/getting-started/04-using-plugins.ts", - "test/path/catch-all.ts", - "test/path/parameters.ts", - "test/plugins/options.ts", - "test/reply/continue.ts", - "test/reply/entity.ts", - "test/reply/redirect.ts", - "test/reply/reply.ts", - "test/reply/state_cookie.ts", + "test/request/catch-all.ts", "test/request/event-types.ts", - "test/request/generate-response.ts", "test/request/get-log.ts", - "test/request/log.ts", + "test/request/parameters.ts", "test/request/query.ts", - "test/request/set-method.ts", - "test/request/set-url.ts", - "test/request/tail.ts", - "test/response/error-representation.ts", + "test/response/continue.ts", "test/response/error.ts", - "test/response/events.ts", - "test/response/flow-control.ts", - "test/route/additional-options.ts", - "test/route/auth.ts", + "test/response/redirect.ts", + "test/response/response.ts", + "test/response/response-events.ts", + "test/route/adding-routes.ts", "test/route/config.ts", "test/route/handler.ts", - "test/route/plugins.ts", - "test/route/prerequisites.ts", - "test/route/public-interface.ts", - "test/route/validate.ts", - "test/server/app.ts", - "test/server/auth.ts", - "test/server/bind.ts", - "test/server/cache.ts", - "test/server/connection-options.ts", - "test/server/connections.ts", - "test/server/decoder.ts", - "test/server/decorate.ts", - "test/server/dependency.ts", - "test/server/emit.ts", - "test/server/encoder.ts", - "test/server/event.ts", - "test/server/expose.ts", - "test/server/ext.ts", - "test/server/handler.ts", - "test/server/info.ts", - "test/server/initialize.ts", - "test/server/inject.ts", - "test/server/listener.ts", - "test/server/load.ts", - "test/server/log.ts", - "test/server/lookup.ts", - "test/server/match.ts", - "test/server/method.ts", - "test/server/methods.ts", - "test/server/mime.ts", - "test/server/new.ts", - "test/server/on.ts", - "test/server/once.ts", - "test/server/path.ts", - "test/server/plugins.ts", - "test/server/realm.ts", - "test/server/register.ts", - "test/server/route.ts", - "test/server/select.ts", - "test/server/settings.ts", - "test/server/start.ts", - "test/server/state.ts", - "test/server/stop.ts", - "test/server/table.ts", - "test/server/version.ts" + "test/route/route-options.ts", + "test/route/route-options-pre.ts", + "test/route/validation.ts", + "test/server/server-app.ts", + "test/server/server-auth-api.ts", + "test/server/server-auth-default.ts", + "test/server/server-auth-test.ts", + "test/server/server-bind.ts", + "test/server/server-cache.ts", + "test/server/server-cache-provision.ts", + "test/server/server-decoder.ts", + "test/server/server-decorations.ts", + "test/server/server-encoder.ts", + "test/server/server-events.ts", + "test/server/server-events-once.ts", + "test/server/server-expose.ts", + "test/server/server-info.ts", + "test/server/server-inject.ts", + "test/server/server-listener.ts", + "test/server/server-load.ts", + "test/server/server-lookup.ts", + "test/server/server-match.ts", + "test/server/server-method.ts", + "test/server/server-methods.ts", + "test/server/server-mime.ts", + "test/server/server-options.ts", + "test/server/server-path.ts", + "test/server/server-plugins.ts", + "test/server/server-settings.ts", + "test/server/server-start.ts", + "test/server/server-state.ts", + "test/server/server-stop.ts", + "test/server/server-table.ts", + "test/server/server-version.ts" ] } \ No newline at end of file diff --git a/types/hapi/tslint.json b/types/hapi/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/hapi/tslint.json +++ b/types/hapi/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/hapi/v16/index.d.ts b/types/hapi/v16/index.d.ts new file mode 100644 index 0000000000..ee22f1dea7 --- /dev/null +++ b/types/hapi/v16/index.d.ts @@ -0,0 +1,2723 @@ +// Type definitions for hapi 16.1 +// Project: https://github.com/hapijs/hapi +// Definitions by: Jason Swearingen , AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WARNING: BACKWARDS INCOMPATIBLE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + * + * + * Removal of IPromise replaced with Promise + * Removal of IReplyStrict<> + * Removal of IReply replaced with different interfaces like: + * ReplyWithContinue + * ReplyNoContinue, etc. + * Renaming of all interfaces to remove preceding I in preparation of dtslint + */ + +/// + +import Events = require("events"); +import stream = require("stream"); +import http = require("http"); +import https = require("https"); +import url = require("url"); +import zlib = require("zlib"); +import domain = require("domain"); + +import * as Boom from 'boom'; +import { + ValidationOptions as JoiValidationOptions, + SchemaMap as JoiSchemaMap, + Schema as JoiSchema, +} from 'joi'; +// TODO check JoiValidationObject is correct for "a Joi validation object" +type JoiValidationObject = JoiSchema | JoiSchemaMap | (JoiSchema | JoiSchemaMap)[]; + +import * as Catbox from 'catbox'; +import { MimosOptions } from 'mimos'; +import Podium = require('podium'); +import * as Shot from 'shot'; + +export interface Dictionary { + [key: string]: T; +} + +/** + * Server + * The Server object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). + * [See docs](https://hapijs.com/api/16.1.1#server) + * [See docs](https://hapijs.com/api/16.1.1#server-properties) + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ +export class Server extends Podium { + /** + * Creates a new Server object + */ + constructor(options?: ServerOptions); + + /** + * Provides a safe place to store server-specific run-time application data without potential conflicts with the framework internals. The data can be accessed whenever the server is accessible. Initialized with an empty object. + * [See docs](https://hapijs.com/api/16.1.1#serverapp) + */ + app?: any; + /** + * An array containing the server's connections. When the server object is returned from server.select(), the connections array only includes the connections matching the selection criteria. + * [See docs](https://hapijs.com/api/16.1.1#serverconnections) + */ + connections: ServerConnection[]; + /** + * When the server contains exactly one connection, info is an object containing information about the sole connection + * When the server contains more than one connection, each server.connections array member provides its own connection.info. + * [See docs](https://hapijs.com/api/16.1.1#serverinfo) + */ + info: ServerConnectionInfo | null; + /** + * An object containing the process load metrics (when load.sampleInterval is enabled): + * [See docs](https://hapijs.com/api/16.1.1#serverload) + */ + load: { + /** event loop delay milliseconds. */ + eventLoopDelay: number; + /** V8 heap usage. */ + heapUsed: number; + /** RSS memory usage. */ + rss: number; + }; + /** + * When the server contains exactly one connection, listener is the node HTTP server object of the sole connection. + * When the server contains more than one connection, each server.connections array member provides its own connection.listener. + * [See docs](https://hapijs.com/api/16.1.1#serverlistener) + */ + listener: ServerListener | null; + /** + * An object providing access to the server methods cs://hapijs.com/api/16.1.1#servermethodname-method-options} where each server method name is an object property. + * [See docs](https://hapijs.com/api/16.1.1#servermethods) + */ + methods: Dictionary; + /** + * Provides access to the server MIME database used for setting content-type information. The object must not be modified directly but only through the mime server setting. + * [See docs](https://hapijs.com/api/16.1.1#servermime) + */ + readonly mime: {path(path: string): {type: string}}; + /** + * An object containing the values exposed by each plugin registered where each key is a plugin name and the values are the exposed properties by each plugin using server.expose(). Plugins may set the value of the server.plugins[name] object directly or via the server.expose() method. + * [See docs](https://hapijs.com/api/16.1.1#serverplugins) + */ + plugins: PluginsStates; + /** + * The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + * [See docs](https://hapijs.com/api/16.1.1#serverrealm) + */ + readonly realm: ServerRealm; + /** + * When the server contains exactly one connection, registrations is an object where each key is a registered plugin name + * When the server contains more than one connection, each server.connections array member provides its own connection.registrations. + * TODO check and offer PR to update Hapi docs: Assuming readonly. + * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) + */ + readonly registrations: ServerRegisteredPlugins; + /** + * The root server object containing all the connections and the root server methods (e.g. start(), stop(), connection()). + * TODO, check and offer PR to update Hapi docs: Marked as optional as presumably root server does not reference itself. + * [See docs](https://hapijs.com/api/16.1.1#serverroot) + */ + root?: Server; + /** + * The server configuration object after defaults applied. + * [See docs](https://hapijs.com/api/16.1.1#serversettings) + */ + settings: ServerOptions; + /** + * The hapi module version number. + * [See docs](https://hapijs.com/api/16.1.1#serverversion) + */ + version: string; + + /** + * [See docs](https://hapijs.com/api/16.1.1#serverauthapi) + * [See docs](https://hapijs.com/api/16.1.1#serverauthdefaultoptions) + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + * [See docs](https://hapijs.com/api/16.1.1#serverauthstrategyname-scheme-mode-options) + * [See docs](https://hapijs.com/api/16.1.1#serverauthteststrategy-request-next) + */ + auth: ServerAuth; + + /** + * Sets a global context used as the default bind object when adding a route or an extension + * When setting context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. + * @param context the object used to bind this in handler and extension methods. + * [See docs](https://hapijs.com/api/16.1.1#serverbindcontext) + */ + bind(context: any): void; + /** + * [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) + * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) + */ + cache: ServerCacheMethod; + /** + * Adds an incoming server connection + * Returns a server object with the new connections selected. + * Must be called before any other server method that modifies connections is called for it to apply to the new connection (e.g. server.state()) + * Note that the options object is deeply cloned (with the exception of listener which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + * + * [See docs](https://hapijs.com/api/16.1.1#serverconnectionoptions) for various advantage topics covering usage and caveats around use of the function in plugin register(), connectionless plugins calling connection(), etc. + * @param connection a connection configuration object or array of objects + */ + connection(options?: ServerConnectionOptions[]): Server; + connection(options?: ServerConnectionOptions): Server; + // connection: (options: ServerConnectionOptions[] | ServerConnectionOptions) => Server; + /** + * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' + * [See docs](https://hapijs.com/api/16.1.1#serverdecoderencoding-decoder) + * @param encoding the decoder name string. + * @param decoder a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the return value is an object compatible with the output of node's zlib.createGunzip(). + */ + decoder(encoding: string, decoder: ((options: CompressionDecoderSettings) => zlib.Gunzip)): void; + /** + * Extends various framework interfaces with custom methods + * Note that decorations apply to the entire server and all its connections regardless of current selection. + * [See docs](https://hapijs.com/api/16.1.1#serverdecoratetype-property-method-options) + * + * NOTE: it's not possible to type the result of this action. + * It's advised that in a custom definition file, you extend the ReplyNoContinue + * and ReplyWithContinue functions. See Inert `.file` for an example. + * Or if it is not part of a library / plugin then you use a namespace within + * your code to type the request, server and or reply. See + * [tests/server/decorate.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/hapi/tests/server/decorate.ts) + * for examples. + * @param type the interface being decorated. Supported types: + * * 'request' - adds methods to the Request object. + * * 'reply' - adds methods to the reply interface. + * * 'server' - adds methods to the Server object. + * @param property the object decoration key name. + * @param method the extension function or other value. + * @param options if the type is 'request', supports the following optional settings: + * * apply - if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. + */ + decorate(type: 'request' | 'reply' | 'server', property: string, method: Function): void; + decorate(type: 'request', property: string, method: Function, options?: {apply: false}): void; + decorate(type: 'request', property: string, method: (request: Request) => Function, options: {apply: true}): void; + /** + * The server.decorate('server', ...) method can modify this prototype/interface. + * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts + * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) + */ + // [index: string]: any; + /** + * Used within a plugin to declare a required dependency on other plugins + * The after method is identical to setting a server extension point on 'onPreStart'. Connectionless plugins (those with attributes.connections set to false) can only depend on other connectionless plugins (server initialization will fail even of the dependency is loaded but is not connectionless). + * Dependencies can also be set via the register attributes property (does not support setting after). + * [See docs](https://hapijs.com/api/16.1.1#serverdependencydependencies-after) + * @param dependencies a single string or array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is initialized or started. Does not provide version dependency which should be implemented using npm peer dependencies. + * @param after an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) + */ + dependency(dependencies: string | string[], after?: AfterDependencyLoadCallback): void; + /** + * Emits a custom application event update to all the subscribed listeners + * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. + * [See docs](https://hapijs.com/api/16.1.1#serveremitcriteria-data-callback) + * @param criteria the event update criteria which if an object can have the following optional keys (unless noted otherwise): + * * name - the event name string (required). + * * channel - the channel name string. + * * tags - a tag string or array of tag strings. + * @param data the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param callback an optional callback method invoked when all subscribers have been notified using the signature function(). The callback is called only after all the listeners have been notified, including any event updates emitted earlier (the order of event updates are guaranteed to be in the order they were emitted). + */ + emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any, callback?: () => void): void; + /** + * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' + * [See docs](https://hapijs.com/api/16.1.1#serverencoderencoding-encoder) + * @param encoding the encoder name string. + * @param encoder a function using the signature function(options) where options are the encoding specific options configured in the route compression configuration option, and the return value is an object compatible with the output of node's zlib.createGzip(). + */ + encoder(encoding: string, encoder: ((options: CompressionEncoderSettings) => zlib.Gzip)): void; + /** + * Register custom application events + * [See docs](https://hapijs.com/api/16.1.1#servereventevents) + * @param events see ApplicationEvent + */ + event(events: ApplicationEvent[]): void; + event(events: ApplicationEvent): void; + /** + * Used within a plugin to expose a property via server.plugins[name] + * [See docs](https://hapijs.com/api/16.1.1#serverexposekey-value) + * @param key the key assigned (server.plugins[name][key]). + * @param value the value assigned. + */ + expose(key: string, value: any): void; + /** + * Merges an object into to the existing content of server.plugins[name] + * Note that all properties of obj are deeply cloned into server.plugins[name], so you should avoid using this method for exposing large objects that may be expensive to clone or singleton objects such as database client objects. Instead favor the server.expose(key, value) form, which only copies a reference to value. + * [See docs](https://hapijs.com/api/16.1.1#serverexposeobj) + * @param obj the object merged into the exposed properties container. + */ + expose(obj: Object): void; + /** + * Registers an extension function in one of the available extension points + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * @param events see @ServerExtConfigurationObject + */ + ext(events: ServerStartExtConfigurationObject): void; + ext(events: ServerStartExtConfigurationObject[]): void; + ext(events: ServerRequestExtConfigurationObjectWithRequest): void; + ext(events: ServerRequestExtConfigurationObjectWithRequest[]): void; + /** + * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. + * [See docs](https://hapijs.com/api/16.1.1#serverextevent-method-options) + * @param event the extension point event name. + * @param method a function or an array of functions to be executed at a specified point during request processing. + * @param options + */ + ext(event: ServerStartExtPoints, method: ServerExtFunction[], options?: ServerExtOptions): void; + ext(event: ServerStartExtPoints, method: ServerExtFunction, options?: ServerExtOptions): void; + ext(event: ServerRequestExtPoints, method: ServerExtRequestHandler[], options?: ServerExtOptions): void; + ext(event: ServerRequestExtPoints, method: ServerExtRequestHandler, options?: ServerExtOptions): void; + /** + * Registers a new handler type to be used in routes + * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler. If the property is set to a function, the function uses the signature function(method) and returns the route default configuration. + * [See docs](https://hapijs.com/api/16.1.1#serverhandlername-method) + * @param name string name for the handler being registered. Cannot override any previously registered type. + * @param method the function used to generate the route handler using the signature function(route, options) where: + * * route - the route public interface object. + * * options - the configuration object provided in the handler config. + */ + handler(name: string, method: MakeRouteHandler): void; + /** + * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection ports + * Note that if the method fails and the callback includes an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to assert that no error has been returned after calling initialize() to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. + * [See docs](https://hapijs.com/api/16.1.1#serverinitializecallback) + * @param callback the callback method when server initialization is completed or failed with the signature function(err) + */ + initialize(callback: (err: Error) => void): void; + initialize(): Promise; + /** + * When the server contains exactly one connection, injects a request into the sole connection simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead or limitations of the network stack. Utilizes the shot module for performing injections, with some additional options and response properties + * If no callback is provided, a Promise object is returned. + * When the server contains more than one connection, each server.connections array member provides its own connection.inject(). + * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) + * @param options can be assigned a string with the requested URI, or an object + * @param callback the callback function with signature function(res) + */ + inject(options: string | InjectedRequestOptions, callback: (res: InjectedResponseObject) => void): void; + inject(options: string | InjectedRequestOptions, ): Promise; + /** + * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. + * [See docs](https://hapijs.com/api/16.1.1#serverlogtags-data-timestamp) + * @param tags a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + * @param data an optional message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param timestamp an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + */ + log(tags: string | string[], data?: string | Object | Function, timestamp?: number): void; + /** + * When the server contains exactly one connection, looks up a route configuration. + * When the server contains more than one connection, each server.connections array member provides its own connection.lookup() method. + * [See docs](https://hapijs.com/api/16.1.1#serverlookupid) + * @param id the route identifier as set in the route options. + * @return the route public interface object if found, otherwise null. + */ + lookup(id: string): RoutePublicInterface | null; + /** + * When the server contains exactly one connection, looks up a route configuration + * When the server contains more than one connection, each server.connections array member provides its own connection.match() method. + * [See docs](https://hapijs.com/api/16.1.1#servermatchmethod-path-host) + * @param method the HTTP method (e.g. 'GET', 'POST'). TODO check if it allows HEAD + * @param path the requested path (must begin with '/'). + * @param host optional hostname (to match against routes with vhost). + * @return the route public interface object if found, otherwise null. + */ + match(method: HTTP_METHODS, path: string, host?: string): RoutePublicInterface | null; + /** + * Registers a server method. Server methods are functions registered with the server and used throughout the application as a common utility. Their advantage is in the ability to configure them to use the built-in cache and share across multiple request handlers without having to create a common module. + * [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) + * @param name a unique method name used to invoke the method via server.methods[name]. Supports using nested names such as utils.users.get which will automatically create the missing path under server.methods and can be accessed for the previous example via server.methods.utils.users.get. When configured with caching enabled, server.methods[name].cache will be an object see ServerMethodNameCacheObject + * @param method the method function + * @param options optional configuration + */ + method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; + /** + * Registers a server method function as described in server.method() using a configuration object + * [See docs](https://hapijs.com/api/16.1.1#servermethodmethods) + */ + method(methods: ServerMethodConfigurationObject[]): void; + method(methods: ServerMethodConfigurationObject): void; + /** + * Subscribe a handler to an event + * [See docs](https://hapijs.com/api/16.1.1#serveroncriteria-listener) + * @param criteria the subscription criteria which can be an event name string which can be any of the built-in server events or a custom application event registered with server.event(events). + * Or an see ServerEventCriteria. + * If 'start' - emitted when the server is started using server.start(). + * If 'stop' - emitted when the server is stopped using server.stop(). + * @param listener + */ + on(criteria: 'start' | 'stop' | string | ServerEventCriteria, listener: Function): void; + /** + * The 'log' event includes the event object and a tags object (where each tag is a key with the value true) + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ + on(criteria: 'log', listener: (event: ServerEventObject, tags: Podium.Tags) => void): void; + /** + * The 'request' and 'request-internal' events include the request object, the event object, and a tags object (where each tag is a key with the value true) + * [See docs](https://hapijs.com/api/16.1.1#server-events) + * TODO submit issue to TypeScript. Using 'request' | 'request-internal' removes the type + * interference when using code like: `server.on('request', (request, event, tags) => {...}` + * Same for 'response' | 'tail'. + */ + on(criteria: 'request', listener: (request: Request, event: ServerEventObject, tags: Podium.Tags) => void): void; + on(criteria: 'request-internal', listener: (request: Request, event: ServerEventObject, tags: Podium.Tags) => void): void; + /** + * The 'request-error' event includes the request object and the causing error err object + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ + on(criteria: 'request-error', listener: (request: Request, err: Error) => void): void; + /** + * The 'response' and 'tail' events include the request object + * [See docs](https://hapijs.com/api/16.1.1#server-events) + * See 'request' and 'request-internal' + */ + on(criteria: 'response', listener: (request: Request) => void): void; + on(criteria: 'tail', listener: (request: Request) => void): void; + /** + * The 'route' event includes the route public interface, the connection, and the server object used to add the route (e.g. the result of a plugin select operation) + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ + on(criteria: 'route', listener: (route: RoutePublicInterface, connection: ServerConnection, server: Server) => void): void; + /** + * Same as calling server.on() with the count option set to 1. + * TODO type this to copy the server.on specific types for 'route', 'tail', etc. + * [See docs](https://hapijs.com/api/16.1.1#serveroncecriteria-listener) + * @param criteria + * @param listener + */ + once(criteria: string | ServerEventCriteria, listener: Function): void; + /** + * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used + * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the connection files.relativeTo configuration is used. The path only applies to routes added after it has been set. + * [See docs](https://hapijs.com/api/16.1.1#serverpathrelativeto) + * @param relativeTo the path prefix added to any relative file path starting with '.'. + */ + path(relativeTo: string): void; + /** + * Registers a plugin + * If no callback is provided, a Promise object is returned. + * Note that plugin registration are recorded on each of the available connections. When plugins express a dependency on other plugins, both have to be loaded into the same connections for the dependency requirement to be fulfilled. It is recommended that plugin registration happen after all the server connections are created via server.connection(). + * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) + * @param plugins + * @param options + * @param callback with signature function(err) where err an error returned from the registration function. Note that exceptions thrown by the registration function are not handled by the framework. + * A note on typings. Common use case is: + * register(Plugin, (err) => {// do more stuff}) + * so these typings save passing empty `options` object or having to + * explicity type the Error in the Callback e.g.: + * register(Plugin, {}, (err) => {// do more stuff}) or + * register(Plugin, (err: Error) => {// do more stuff}) + */ + register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, callback: (err: Error | null) => void): void; + register(plugins: Array<(PluginFunction | PluginRegistrationObject)>): Promise; + register(plugins: PluginFunction | PluginRegistrationObject, callback: (err: Error | null) => void): void; + register(plugins: PluginFunction | PluginRegistrationObject): Promise; + register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, options: PluginRegistrationOptions, callback: (err: Error | null) => void): void; + register(plugins: Array<(PluginFunction | PluginRegistrationObject)>, options: PluginRegistrationOptions): Promise; + register(plugins: PluginFunction | PluginRegistrationObject, options: PluginRegistrationOptions, callback: (err: Error | null) => void): void; + register(plugins: PluginFunction | PluginRegistrationObject, options: PluginRegistrationOptions): Promise; + /** + * Adds a connection route + * [See docs](https://hapijs.com/api/16.1.1#serverrouteoptions) + * @param options a route configuration object [See docs](https://hapijs.com/api/16.1.1#route-configuration) or an array of configuration objects. + */ + route(options: RouteConfiguration[]): void; + route(options: RouteConfiguration): void; + /** + * Selects a subset of the server's connections + * Returns a server object with connections set to the requested subset. Selecting again on a selection operates as a logic AND statement between the individual selections. + * [See docs](https://hapijs.com/api/16.1.1#serverselectlabels) + * @param labels a single string or array of strings of labels used as a logical OR statement to select all the connections with matching labels in their configuration. + */ + select(labels: string | string[]): Server; + /** + * Starts the server connections by listening for incoming requests on the configured port of each listener (unless the connection was configured with autoListen set to false) + * If no callback is provided, a Promise object is returned. + * Note that if the method fails and the callback includes an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to assert that no error has been returned after calling start() to abort the process when the server fails to start properly. If you must try to resume after a start error, call server.stop() first to reset the server state. + * If a started server is started again, the second call to start() will only start new connections added after the initial start() was called. No events will be emitted and no extension points invoked. + * [See docs](https://hapijs.com/api/16.1.1#serverstartcallback) + * @param callback the callback method when server startup is completed or failed with the signature function(err) where: + * * err - any startup error condition. + */ + start(callback: (err?: Error) => void): void; + start(): Promise; + /** + * HTTP state management [See docs](https://tools.ietf.org/html/rfc6265) uses client cookies to persist a state across multiple requests. Registers a cookie definitions + * [See docs](https://hapijs.com/api/16.1.1#serverstatename-options) + * @param name the cookie name string. + * @param options optional cookie settings + */ + state(name: string, options?: ServerStateCookieConfiguationObject): void; + /** + * Stops the server's connections by refusing to accept any new connections or requests (existing connections will continue until closed or timeout) + * If no callback is provided, a Promise object is returned. + * [See docs](https://hapijs.com/api/16.1.1#serverstopoptions-callback) + * @param options options object with: + * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + * @param callback optional callback method which is called once all the connections have ended and it is safe to exit the process with signature function(err) where: + * * err - any termination error condition. + */ + stop(options: {timeout: number} | null, callback: (err?: Error) => void): void; + stop(options?: {timeout: number}): Promise; + /** + * Returns a copy of the routing table + * Note that if the server has not been started and multiple connections use port 0, the table items will override each other and will produce an incomplete result. + * When calling connection.table() directly on each connection, the return value is the same as the array table item value of an individual connection + * [See docs](https://hapijs.com/api/16.1.1#servertablehost) + * @param host optional host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + */ + table(host?: string): RoutingTableEntry[]; +} + +export interface PluginSpecificConfiguration {} + +/** + * Server Options + * Note that the options object is deeply cloned and cannot contain any values that are unsafe to perform deep copy on. + * [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) + */ +export interface ServerOptions { + /** app - application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ + app?: any; + /** + * cache - sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: + * * a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. + * * a CatboxServerOptionsCacheConfiguration configuration object + * * an array of the above object for configuring multiple cache instances, each with a unique name. When an array of objects is provided, multiple cache connections are established and each array item (except one) must include a name. + */ + cache?: Catbox.EnginePrototype | CatboxServerOptionsCacheConfiguration | CatboxServerOptionsCacheConfiguration[]; + /** sets the default connections configuration which can be overridden by each connection */ + connections?: ConnectionConfigurationServerDefaults; + /** determines which logged events are sent to the console (this should only be used for development and does not affect which events are actually logged internally and recorded). Set to false to disable all console logging, or to an object with: */ + debug?: false | { + /** a string array of server log tags to be displayed via console.error() when the events are logged via server.log() as well as internally generated server logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + log?: string[] | false; + /** a string array of request log tags to be displayed via console.error() when the events are logged via request.log() as well as internally generated request logs. For example, to display all errors, set the option to ['error']. To turn off all console debug messages set it to false. Defaults to uncaught errors thrown in external code (these errors are handled automatically and result in an Internal Server Error response) or runtime errors due to developer error. */ + request?: string[] | false; + }; + /** process load monitoring */ + load?: { + /** the frequency of sampling in milliseconds. Defaults to 0 (no sampling). */ + sampleInterval?: number; + }; + /** options passed to the mimos module (https://github.com/hapijs/mimos) when generating the mime database used by the server and accessed via server.mime. */ + mime?: MimosOptions; + /** plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. Defaults to {}. */ + plugins?: PluginSpecificConfiguration; + /** if false, will not use node domains to protect against exceptions thrown in handlers and other external code. Defaults to true. */ + useDomains?: boolean; +} + +/** + * The server event object + * [See docs](https://hapijs.com/api/16.1.1#server-events) + */ +export interface ServerEventObject { + /** the event timestamp. */ + timestamp: number; + /** if the event relates to a request, the request id. */ + request: string; + /** if the event relates to a server, the server.info.uri. */ + server: string; + /** an array of tags (e.g. ['error', 'http']). */ + tags: string[]; + /** optional event-specific information. */ + data: any; + /** true if the event was generated internally by the framework. */ + internal: boolean; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serveroncriteria-listener) + */ +export interface ServerEventCriteria { + /** the event name string (required). */ + name: string; + /** if true, the listener method receives an additional callback argument which must be called when the method completes. No other event will be emitted until the callback methods is called. The method signature is function(). If block is set to a positive integer, the value is used to set a timeout after which any pending events will be emitted, ignoring the eventual call to callback. Defaults to false (non blocking). */ + block?: boolean; + /** a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. */ + channels?: string | string[]; + /** if true, the data object passed to server.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ + clone?: boolean; + /** a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.once(). Defaults to no limit. */ + count?: number; + /** + * the event tags (if present) to subscribe to + * If the object is given: + * * tags - a tag string or array of tag strings. + * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). + */ + filter?: string | string[] | {tags: string | string[], all?: boolean}; + /** if true, and the data object passed to server.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). */ + spread?: boolean; + /** if true and the criteria object passed to server.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end (but before the callback argument if block is set). Defaults to the event registration option (which defaults to false). */ + tags?: boolean; +} + +/** + * Server methods, user configured + * Related to [See docs](https://hapijs.com/api/16.1.1#servermethods) + * Related to [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) + */ +export interface ServerMethod { + /** the method must return a value (result, Error, or a promise) or throw an Error. */ + (...args: any[]): any | Error | Promise; + /** Not possible to improve this typing due to this unresolvable issue: https://github.com/Microsoft/TypeScript/issues/15190 */ + (...args: (any | ServerMethodNext)[]): void; + /** When configured with caching enabled, server.methods[name].cache will be an object see ServerMethodNameCacheObject */ + cache?: ServerMethodNameCacheObject; +} + +/** + * Related to [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) + * @param err error response if the method failed. + * @param result the return value. + * @param ttl 0 if result is valid but cannot be cached. Defaults to cache policy. + */ +export interface ServerMethodNext { + (err: Error | null, result: any, ttl?: number): void; +} + +/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) */ +export interface ServerMethodNameCacheObject { + /** + * function that can be used to clear the cache for a given key. + * @param ...args any number of string, number or boolean. If other types then generateKey function must be specified. + * @param callback last argument is a callback. + * Not possible to improve this typing due to this unresolvable issue: https://github.com/Microsoft/TypeScript/issues/15190 + */ + drop(...args: (any | Function)[]): void; + /** an object with cache statistics, see stats documentation for catbox. */ + stats: Catbox.CacheStatisticsObject; +} + +/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) */ +export interface ServerMethodOptions { + /** a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. */ + bind?: any; + /** the same cache configuration used in server.cache(). The generateTimeout option is required. */ + cache?: CatboxServerCacheConfiguration; + /** + * if false, expects the method to be a synchronous function. Note that using a synchronous function with caching will convert the method interface to require a callback as an additional argument with the signature function(err, result, cached, report) since the cache interface cannot return values synchronously. Defaults to true. + * TODO: understand and type "an additional argument with the signature function(err, result, cached, report)" if appropriate. + */ + callback?: boolean; + /** a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). */ + generateKey?(args: any[]): string | null; +} + +/** For context [See docs](https://hapijs.com/api/16.1.1#servermethodmethods) */ +export interface ServerMethodConfigurationObject { + name: string; + method: ServerMethod; + options: ServerMethodOptions; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Caching with Catbox + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * TODO confirm this is the same as CatboxServerCacheConfiguration + * + * ** + * Server instantiation options configuration for Catbox cache + * TODO: check it extends Catbox.PolicyOptions and this is what "other options passed to the catbox strategy used." means. + * For context [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) under: options > cache > a configuration object + * ** + * export interface CatboxServerOptionsCacheConfiguration extends Catbox.IPolicyOptions { + * // a prototype function or catbox engine object. + * engine: Catbox.EnginePrototypeOrObject; + * // an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * name?: string; + * // if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + * shared?: boolean; + * } + */ +export type CatboxServerOptionsCacheConfiguration = CatboxServerCacheConfiguration; + +/** + * Server cache method configuration for Catbox cache + * Used for "Provisions a cache segment within the server cache facility" + * For context [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) + * Also used in [See docs](https://hapijs.com/api/16.1.1#servermethodname-method-options) > options.cache + */ +export interface CatboxServerCacheConfiguration extends Catbox.PolicyOptions { + /** the cache name configured in server.cache. Defaults to the default cache. */ + cache?: string; + /** string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. */ + segment?: string; + /** if true, allows multiple cache provisions to share the same segment. Default to false. */ + shared?: boolean; + /** + * a prototype function or catbox engine object. + * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) example code includes use of `engine` option. But server.cache.provision of `options` says "same as the server cache configuration options.". + * TODO confirm once PR to hapi docs accepted / rejected. + */ + engine?: Catbox.EnginePrototypeOrObject; + /** + * an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) example code includes use of `name` option. But server.cache.provision of `options` says "same as the server cache configuration options.". + */ + name?: string; + /** + * Additional options to be passed to the Catbox strategy + */ + [s: string]: any; +} + +/** + * Additional notes + * payload - In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. + * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) + */ +export interface InjectedRequestOptions extends Shot.RequestOptions { + /** an optional credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. */ + credentials?: any; + /** an optional artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. */ + artifacts?: any; + /** sets the initial value of request.app. */ + app?: any; + /** sets the initial value of request.plugins. */ + plugins?: PluginsStates; + /** allows access to routes with config.isInternal set to true. Defaults to false. */ + allowInternals?: boolean; +} + +/** + * the response object from server.inject + * [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) + */ +export interface InjectedResponseObject extends Shot.ResponseObject { + /** the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). */ + result: Object | string; + /** the request object. */ + request: InjectedRequestOptions; +} + +/** + * For context [See docs](https://hapijs.com/api/16.1.1#new-serveroptions) under: options > connections + */ +export interface ConnectionConfigurationServerDefaults { + /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ + app?: any; + /** if false, response content encoding is disabled. Defaults to true */ + compression?: boolean; + /** connection load limits configuration where: */ + load?: { + /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxHeapUsedBytes?: number; + /** maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxRssBytes?: number; + /** maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ + maxEventLoopDelay?: number; + }; + /** plugin-specific configuration which can later be accessed via connection.settings.plugins. Provides a place to store and pass connection-specific plugin configuration. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between connection.settings.plugins which is used to store configuration values and connection.plugins which is meant for storing run-time state. */ + plugins?: PluginSpecificConfiguration; + /** controls how incoming request URIs are matched against the routing table: */ + router?: { + /** determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true. */ + isCaseSensitive?: boolean; + /** removes trailing slashes on incoming paths. Defaults to false. */ + stripTrailingSlash?: boolean; + }; + /** a route options object used to set the default configuration for every route. */ + routes?: RouteAdditionalConfigurationOptions; + /** sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the [state configuration object](https://hapijs.com/api/16.1.1#serverstatename-options). */ + state?: ServerStateCookieConfiguationObject; +} + +/** + * a connection configuration object or array of objects with the following optional keys. + * Any connections configuration server defaults can be included to override and customize the individual connection. + * [See docs](https://hapijs.com/api/16.1.1#serverconnectionoptions) + */ +export interface ServerConnectionOptions extends ConnectionConfigurationServerDefaults { + /** host - the public hostname or IP address. Used only to set server.info.host and server.info.uri. If not configured, defaults to the operating system hostname and if not available, to 'localhost'. */ + host?: string; + /** address - sets the host name or IP address the connection will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces (i.e. '0.0.0.0'). Set to 127.0.0.1 or localhost to restrict connection to only those coming from the same machine. */ + address?: string; + /** port - the TCP port the connection will listen to. Defaults to an ephemeral port (0) which uses an available port when the server is started (and assigned to server.info.port). If port is a string containing a '/' character, it is used as a UNIX domain socket path and if it starts with '\.\pipe' as a Windows named pipe. */ + port?: string | number; + /** uri - the full public URI without the path (e.g. 'http://example.com:8080'). If present, used as the connection info.uri otherwise constructed from the connection settings. */ + uri?: string; + /** listener - optional node.js HTTP (or HTTPS) http.Server object or any compatible object. If the listener needs to be manually started, set autoListen to false. If the listener uses TLS, set tls to true. */ + listener?: http.Server; + /** autoListen - indicates that the connection.listener will be started manually outside the framework. Cannot be specified with a port setting. Defaults to true. */ + autoListen?: boolean; + /** labels - a string or string array of labels used to server.select() specific connections matching the specified labels. Defaults to an empty array [] (no labels). */ + labels?: string | string[]; + /** tls - used to create an HTTPS connection. The tls object is passed unchanged as options to the node.js HTTPS server as described in the node.js HTTPS [documentation](https://nodejs.org/api/https.html#https_https_createserver_options_requestlistener}) . Set to true when passing a listener object that has been configured to use TLS directly. */ + tls?: true | https.RequestOptions; +} + +/** + * For context see RouteAdditionalConfigurationOptions > compression + * For context [See docs](https://hapijs.com/api/16.1.1#serverencoderencoding-encoder) + */ +export type CompressionEncoderSettings = any; + +/** + * For context see RouteAdditionalConfigurationOptions > payload > compression + * For context [See docs](https://hapijs.com/api/16.1.1#serverdecoderencoding-decoder) + */ +export type CompressionDecoderSettings = any; + +/** + * an optional function called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). The function signature is function(server, next) where: + * [See docs](https://hapijs.com/api/16.1.1#serverdependencydependencies-after) + * Also see Server.dependency + * @param server the server the dependency() method was called on. + * @param next the callback function the method must call to return control over to the application and complete the registration process. The function signature is function(err) where: + * * err - internal error condition, which is returned back via the server.initialize() or server.start() callback. + */ +export interface AfterDependencyLoadCallback { + (server: Server, next: (err?: Error) => void): void; +} + +/** For context see RouteAdditionalConfigurationOptions > auth */ +export interface AuthOptions { + /** + * the authentication mode. Defaults to 'required' if a server authentication strategy is configured, otherwise defaults to no authentication. Available values: + * * 'required' - authentication is required. + * * 'optional' - authentication is optional (must be valid if present). + * * 'try' - same as 'optional' but allows for invalid authentication. + */ + mode?: 'required' | 'optional' | 'try'; + /** a string array of strategy names in order they should be attempted. If only one strategy is used, strategy can be used instead with the single string value. Defaults to the default authentication strategy which is available only when a single strategy is configured. */ + strategies?: string[]; + strategy?: string; + /** + * if set, the payload (in requests other than 'GET' and 'HEAD') is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' when the scheme sets the options.payload to true. Available values: + * * false - no payload authentication. This is the default value. + * * 'required' - payload authentication required. This is the default value when the scheme sets options.payload to true. + * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). + */ + payload?: false | 'required' | 'optional'; + /** specifying the route access rules. */ + access?: RouteAuthAccessConfiguationObject | RouteAuthAccessConfiguationObject[]; + /** (undocumented) Convenience way of setting access.scope, will over write all values in `access` */ + scope?: false | string | string[]; + /** (undocumented) Convenience way of setting access.entity, will over write all values in `access` */ + entity?: 'any' | 'user' | 'app'; +} + +/** + * Each rule is evaluated against an incoming request and access is granted if at least one rule matches. Each rule object must include at least one of: + * For context see RouteAdditionalConfigurationOptions > auth > an object > access + */ +export interface RouteAuthAccessConfiguationObject { + /** the application scope required to access the route. Value can be a scope string or an array of scope strings. The authenticated credentials object scope property must contain at least one of the scopes defined to access the route. If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. You may also access properties on the request object (query and params) to populate a dynamic scope by using {} characters around the property name, such as 'user-{params.id}'. Defaults to false (no scope requirements). */ + scope?: false | string | string[]; + /** + * the required authenticated entity type. If set, must match the entity value of the authentication credentials. Available values: + * * any - the authentication can be on behalf of a user or application. This is the default value. + * * user - the authentication must be on behalf of a user which is identified by the presence of a user attribute in the credentials object returned by the authentication strategy. + * * app - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. + */ + entity?: 'any' | 'user' | 'app'; +} + +/** + * For context see RouteAdditionalConfigurationOptions > cache + */ +export type RouteCacheOptions = { + /** + * determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: + * * 'default' - no privacy flag. This is the default setting. + * * 'public' - mark the response as suitable for public caching. + * * 'private' - mark the response as suitable only for private caching. + */ + privacy?: 'default' | 'public' | 'private'; + /** an array of HTTP response status codes (e.g. 200) which are allowed to include a valid caching directive. Defaults to [200]. */ + statuses?: number[]; + /** a string with the value of the 'Cache-Control' header when caching is disabled. Defaults to 'no-cache'. */ + otherwise?: string; +} & ({ + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: number; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ + expiresAt?: undefined; +} | { + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: undefined; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ + expiresAt?: string; +} | { + /** relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ + expiresIn?: undefined; + /** time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. */ + expiresAt?: undefined; +}); + +/** + * For context see RouteAdditionalConfigurationOptions > cors + */ +export interface CorsConfigurationObject { + /** a strings array of allowed origin servers ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. Defaults to any origin ['*']. */ + origin?: string[] | '*'; + /** number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). */ + maxAge?: number; + /** a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'] */ + headers?: string[]; + /** a strings array of additional headers to headers. Use this to keep the default headers in place. */ + additionalHeaders?: string[]; + /** a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. */ + exposedHeaders?: string[]; + /** a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. */ + additionalExposedHeaders?: string[]; + /** if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. */ + credentials?: boolean; +} + +/** + * An object describing the extension function used whilst registering the extension function in one of the available extension points + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * For context see RouteAdditionalConfigurationOptions > ext + */ +export interface ServerStartExtConfigurationObject { + /** the extension point event name. */ + type: ServerStartExtPoints; + /** + * a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is see ServerExtFunction or see ServerExtRequestHandler + */ + method: ServerExtFunction | ServerExtFunction[]; + options?: ServerExtOptions; +} + +/** + * An object describing the extension function used whilst registering the extension function in one of the available extension points + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * For context see RouteAdditionalConfigurationOptions > ext + */ +export interface ServerRequestExtConfigurationObject { + /** the extension point event name. */ + type: ServerRequestExtPointsBase; + /** + * a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is see ServerExtFunction or see ServerExtRequestHandler + */ + method: ServerExtRequestHandler | ServerExtRequestHandler[] + options?: ServerExtOptions; +} + +/** + * An object describing the extension function used whilst registering the extension function in one of the available extension points + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * For context see RouteAdditionalConfigurationOptions > ext + */ +export interface ServerRequestExtConfigurationObjectWithRequest { + /** the extension point event name. */ + type: ServerRequestExtPoints; + /** + * a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is see ServerExtFunction or see ServerExtRequestHandler + */ + method: ServerExtRequestHandler | ServerExtRequestHandler[]; + options?: ServerExtOptions; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#route-configuration) > ext + */ +export type RouteExtConfigurationObject = ServerStartExtConfigurationObject | ServerRequestExtConfigurationObject; + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > method + */ +export type ServerExtMethod = ServerExtFunction | ServerExtRequestHandler; + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > options + */ +export interface ServerExtOptions { + /** before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. */ + before: string | string[]; + /** after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. */ + after: string | string[]; + /** bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. */ + bind: any; + /** sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'connection' which applies to any route added to the connection the extension is added to. */ + sandbox?: 'connection' | 'plugin'; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) > events > type + * * 'onPreStart' - called before the connection listeners are started. + * * 'onPostStart' - called after the connection listeners are started. + * * 'onPreStop' - called before the connection listeners are stopped. + * * 'onPostStop' - called after the connection listeners are stopped. + */ +export type ServerStartExtPoints = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; +/** + * [See docs](https://hapijs.com/api/16.1.1#request-lifecycle) + * * The available extension points include the request extension points as well as the following server extension points: + */ +export type ServerRequestExtPointsBase = 'onPreResponse' | 'onPreAuth' | 'onPostAuth' | 'onPreHandler' | 'onPostHandler' | 'onPreResponse'; + +export type ServerRequestExtPoints = ServerRequestExtPointsBase | 'onRequest'; + +/** + * Server extension function registered an one of the server extension points + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * For context see ServerExtConfigurationObject + * @param server - the server object. + * @param next - the continuation method with signature function(err). + * @param this - the object provided via options.bind or the current active context set with server.bind(). + */ +export interface ServerExtFunction { + (server: Server, next: ContinuationFunction): void; +} + +/** + * For context see RouteAdditionalConfigurationOptions > payload + */ +export interface RoutePayloadConfigurationObject { + /** + * the type of payload representation requested. The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, the raw Buffer is returned. This is the default value except when a proxy handler is used. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a property hapi containing filename and headers properties. + * * 'file' - the incoming payload is written to temporary file in the directory specified by the server's payload.uploads settings. If the payload is 'multipart/form-data' and parse is true, fields values are presented as text while files are saved. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform any needed cleanup. + */ + output?: PayLoadOutputOption; + /** + * can be true, false, or gunzip; determines if the incoming payload is processed or presented raw. true and gunzip includes gunzipping when the appropriate 'Content-Encoding' is specified on the received request. If parsing is enabled and the 'Content-Type' is known (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Defaults to true, except when a proxy handler is used. The supported mime types are: + * * 'application/json' + * * 'application/x-www-form-urlencoded' + * * 'application/octet-stream' + * * 'text/*' + * * 'multipart/form-data' + */ + parse?: 'gunzip' | boolean; + /** + * overrides payload processing for multipart requests. Value can be one of: + * * false - disables multipart processing. + * * object with the following required options: + * * output - same as the payload.output option with an additional value option: + * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? + * * headers - the part headers. + * * filename - the part file name. + * * payload - the processed part payload. + */ + multipart?: false | { + output: PayLoadOutputOption | 'annotated'; + }; + /** a string or an array of strings with the allowed mime types for the endpoint. Defaults to any of the supported mime types listed above. Note that allowing other mime types not listed will not enable them to be parsed, and that if parsing mode is 'parse', the request will result in an error response. */ + allow?: string | string[]; + /** a mime type string overriding the 'Content-Type' header value received. Defaults to no override. */ + override?: string; + /** limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. Defaults to 1048576 (1MB). */ + maxBytes?: number; + /** payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. Set to false to disable. Defaults to 10000 (10 seconds). */ + timeout?: number | false; + /** the directory used for writing file uploads. Defaults to os.tmpdir(). */ + uploads?: string; + /** + * determines how to handle payload parsing errors. Allowed values are: + * * 'error' - return a Bad Request (400) error response. This is the default value. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action and continue processing the request. + */ + failAction?: 'error' | 'log' | 'ignore'; + /** the default 'Content-Type' HTTP header value is not present. Defaults to 'application/json'. */ + defaultContentType?: string; + /** an object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in the root option compression. */ + compression?: Dictionary; +} + +export type PayLoadOutputOption = 'data' | 'stream' | 'file'; + +/** + * events must be one of: + * * an event name string. + * * an event options object see ApplicationEventOptionsObject + * * a podium [See docs](https://github.com/hapijs/podium) emitter object. + * For context [See docs](https://hapijs.com/api/16.1.1#servereventevents) > events parameter + */ +export type ApplicationEvent = string | ApplicationEventOptionsObject | Podium; + +/** + * an event options object + * For context see ApplicationEvent + * For context [See docs](https://hapijs.com/api/16.1.1#servereventevents) > events parameter + */ +export interface ApplicationEventOptionsObject { + /** the event name string (required). */ + name: string; + /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ + channels?: string | string[]; + /** if true, the data object passed to server.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). */ + clone?: boolean; + /** if true, the data object passed to server.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). */ + spread?: boolean; + /** if true and the criteria object passed to server.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end (but before the callback argument if block is set). A configuration override can be set by each listener. Defaults to false. */ + tags?: boolean; + /** if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). */ + shared?: boolean; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Route + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Route configuration + * The route configuration object + * + * [See docs](https://hapijs.com/api/16.1.1#route-configuration) + * + * TODO typings check that the following refers to RouteAdditionalConfigurationOptions "Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on." + */ +export interface RouteConfiguration { + /** the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. */ + path: string; + /** the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. */ + method: HTTP_METHODS_PARTIAL | '*' | (HTTP_METHODS_PARTIAL | '*')[]; + /** an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. */ + vhost?: string; + /** the function called to generate the response after successful authentication and validation. The handler function is described in Route handler. If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed. Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler. */ + handler?: string | RouteHandler | RouteHandlerPlugins; + /** additional route options. The config value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. */ + config?: RouteAdditionalConfigurationOptions | ((server: Server) => RouteAdditionalConfigurationOptions); +} + +/** + * Route options + * Each route can be customize to change the default behavior of the request lifecycle using the following options: + * [See docs](https://hapijs.com/api/16.1.1#route-options) + */ +export interface RouteAdditionalConfigurationOptions { + /** application specific configuration.Should not be used by plugins which should use plugins[name] instead. */ + app?: any; + /** + * Authentication configuration. Value can be: + * * false to disable authentication if a default strategy is set. + * * a string with the name of an authentication strategy registered with server.auth.strategy(). + * * an object + */ + auth?: false | string | AuthOptions; + /** an object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. */ + bind?: any; + /** + * Route cache options + * if the route method is 'GET', the route can be configured to include caching directives in the response. The default Cache-Control: no-cache header can be disabled by setting cache to false. Caching can be customized using an object + * TODO check: the default is to have 'Cache-Control: no-cache', but on first reading is a contridiction as you can disabled cache and disabled no-cache by setting RouteCacheOptions to false? + */ + cache?: boolean | RouteCacheOptions; + /** an object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in payload.compression. */ + compression?: Dictionary; + /** the Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. CORS headers are disabled by default (false). To enable, set cors to true, or to an object */ + cors?: boolean | CorsConfigurationObject; + /** defined a route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the [server.ext(events)](https://hapijs.com/api/16.1.1#serverextevents) event argument. */ + ext?: RouteExtConfigurationObject | RouteExtConfigurationObject[]; + /** defines the behavior for accessing files: */ + files?: { + /** determines the folder relative paths are resolved against. */ + relativeTo: string; + }; + /** an alternative location for the route.handler option. */ + handler?: string | RouteHandler; + /** an optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes with an array of methods. */ + id?: string; + /** if true, the route cannot be accessed through the HTTP connection but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should not be accessible to the outside world. Defaults to false. */ + isInternal?: boolean; + /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload. Supports the following: */ + json?: Json.StringifyArguments & { + /** string suffix added after conversion to JSON string. Defaults to no suffix. */ + suffix?: string; + }; + /** enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Does not work with stream responses. Headers content-type and x-content-type-options are set to text/javascript and nosniff respectively, and will override those headers even if explicitly set by response.type() */ + jsonp?: string; + /** if true, request level logging is enabled (accessible via request.getLog()). */ + log?: boolean; + /** + * determines how the request payload is processed + * [See docs](https://hapijs.com/api/16.1.1#route-options) + */ + payload?: RoutePayloadConfigurationObject; + /** plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. */ + plugins?: PluginSpecificConfiguration; + /** an array with [route prerequisites](https://hapijs.com/api/16.1.1#route-prerequisites) methods which are executed in serial or in parallel before the handler is called. */ + pre?: RoutePrerequisitesArray; + /** processing rules for the outgoing response */ + response?: RouteResponseConfigurationObject; + /** sets common security headers (disabled by default). To enable set security to true or to an object with the following options: See RouteSecurityConfigurationObject */ + security?: boolean | RouteSecurityConfigurationObject; + /** HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following options: */ + state?: { + /** determines if incoming 'Cookie' headers are parsed and stored in the request.state object. Defaults to true. */ + parse?: boolean; + /** + * determines how to handle cookie parsing errors. Allowed values are: + * * 'error' - return a Bad Request (400) error response. This is the default value. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action. + */ + failAction: 'error' | 'log' | 'ignore'; + }; + /** request input validation rules for various request components. When using a Joi validation object, the values of the other inputs (i.e. headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')). Note that validation is performed in order (i.e. headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the routes defaults level and an individual route, the individual route settings override the routes defaults (the rules are not merged). The validate object supports: */ + validate?: RouteValidationConfigurationObject; + /** define timeouts for processing durations: */ + timeout?: { + /** response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response. Disabled by default (false). */ + server?: boolean | number; + /** by default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Defaults to undefined which leaves the node default unchanged. Set to false to disable socket timeouts. */ + socket?: boolean | number; + }; + + /** + * TODO decide on moving these to an extended interface of RouteAdditionalConfigurationOptions + */ + /** + * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + * route description used for generating documentation + */ + description?: string; + /** + * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + * route notes used for generating documentation + */ + notes?: string | string[]; + /** + * ONLY WHEN ADDING NEW ROUTES (not when setting defaults). + * route tags used for generating documentation + */ + tags?: string[]; +} + +/** + * Route public interface + * When route information is returned or made available as a property, it is an object with the following: + * [See docs](https://hapijs.com/api/16.1.1#route-public-interface) + */ +export interface RoutePublicInterface { + /** the route HTTP method. */ + method: string; + /** the route path. */ + path: string; + /** the route vhost option if configured. */ + vhost?: string | string[]; + /** the [active realm] [See docs](https://hapijs.com/api/16.1.1#serverrealm) associated with the route.*/ + realm: ServerRealm; + /** the [route options] [See docs](https://hapijs.com/api/16.1.1#route-options) object with all defaults applied. */ + settings: RouteAdditionalConfigurationOptions; + /** the route internal normalized string representing the normalized path. */ + fingerprint: string; + /** route authentication utilities: */ + auth: { + /** authenticates the passed request argument against the route's authentication access configuration. Returns true if the request would have passed the route's access requirements. Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. Also, if the route uses dynamic scopes, the scopes are constructed against the request.query and request.params which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or at all), it will return false if the route requires any authentication. */ + access(request: Request): boolean; + }; +} + +export type RouteHandlerConfig = any; + +/** + * For context [See docs](https://hapijs.com/api/16.1.1#serverhandlername-method) + * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/handler.js#L103) + * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/route.js#L56-L60) + * TODO check the type of `RouteHandlerConfig` is correct for `defaults`. + */ +export interface MakeRouteHandler { + (route: RoutePublicInterface, options: RouteHandlerConfig): RouteHandler; + defaults?: RouteHandlerConfig | ((method: HTTP_METHODS_PARTIAL_lowercase) => RouteHandlerConfig); +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#servertablehost) > return value + */ +export interface RoutingTableEntry { + /** the connection.info the connection the table was generated for. */ + info: ServerConnectionInfo; + /** the connection labels. */ + labels: string[]; + /** an array of routes where each route contains: */ + table: Route[]; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#servertablehost) > return value + * For source [See source](https://github.com/hapijs/hapi/blob/v16.1.1/lib/route.js#L71) + */ +export interface Route { + /** + * the route config with defaults applied. + * TODO check type of RouteConfiguration here is correct + */ + settings: RouteAdditionalConfigurationOptions; + /** + * the HTTP method in lower case. + * TODO, check if it can contain 'head' or not. + */ + method: HTTP_METHODS_PARTIAL_lowercase; + /** the route path. */ + path: string; + + params: string[]; + + connection: ServerConnection; + + fingerprint: string; + + plugin?: any; + + public: RoutePublicInterface; + + server: Server; +} + +/** + * Route Prerequisites + * It is often necessary to perform prerequisite actions before the handler is called (e.g. load required reference data from a database). The route pre option allows defining such pre-handler methods. The methods are called in order. If the pre array contains another array, those methods are called in parallel. pre can be assigned a mixed array of: + * * arrays containing the elements listed below, which are executed in parallel. + * * objects see RoutePrerequisiteObjects + * * functions - same as including an object with a single method key. + * * strings - special short-hand notation for registered server methods using the format 'name(args)' (e.g. 'user(params.id)') where: + * * 'name' - the method name. The name is also used as the default value of assign. + * * 'args' - the method arguments (excluding next) where each argument is a property of the request object + * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) + * For context see RouteAdditionalConfigurationOptions > pre + * + * TODO follow up on "server methods" in "special short-hand notation for registered server methods" at https://hapijs.com/api/16.1.1#servermethodname-method-options + * TODO follow up on "request object" in "each argument is a property of the request object" at https://hapijs.com/api/16.1.1#request-object + */ +export type RoutePrerequisitesArray = RoutePrerequisitesPart[] | (RoutePrerequisitesPart[] | RoutePrerequisitesPart)[]; +export type RoutePrerequisitesPart = RoutePrerequisiteObjects | RoutePrerequisiteRequestHandler | string; + +/** + * see RoutePrerequisites > objects + */ +export interface RoutePrerequisiteObjects { + /** the function to call (or short-hand method string as described below [see RoutePrerequisitesArray]). the function signature is identical to a route handler as described in Route handler. */ + method: RoutePrerequisiteRequestHandler | string; + /** key name to assign the result of the function to within request.pre. */ + assign: string; + /* + * determines how to handle errors returned by the method. Allowed values are: + * * 'error' - returns the error response back to the client. This is the default value. + * * 'log' - logs the error but continues processing the request. If assign is used, the error will be assigned. + * * 'ignore' - takes no special action. If assign is used, the error will be assigned. + */ + failAction?: 'error' | 'log' | 'ignore'; +} + +/** + * For context see RouteAdditionalConfigurationOptions > response + */ +export interface RouteResponseConfigurationObject { + /** the default HTTP status code when the payload is empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time or response transmission (the response status code will remain 200 throughout the request lifecycle unless manually set). Defaults to 200. */ + emptyStatusCode?: number; + /** + * defines what to do when a response fails payload validation. Options are: + * * 'error' - return an Internal Server Error (500) error response. This is the default value. + * * 'log' - log the error but send the response. + * * a custom error handler function with the signature function(request, reply, source, error) where: + * * 'request' - the request object. + * * 'reply' - the continuation reply interface. + * * 'error' - the error returned from the validation schema. + * TODO update type of source once PR to hapi is concluded. + */ + failAction?: 'error' | 'log' | ((request: Request, reply: ReplyWithContinue, source: string, error: Boom.BoomError) => void); + /** if true, applies the validation rule changes to the response payload. Defaults to false. */ + modify?: boolean; + /** + * options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is available [here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback) ). + * If a custom validation function (see `schema` or `status` below) is defined then `options` can an arbitrary object that will be passed to this function as the second parameter. + * Defaults to no options. + */ + options?: ValidationOptions; + /** if false, payload range support is disabled. Defaults to true. */ + ranges?: boolean; + /** the percent of response payloads validated (0 - 100). Set to 0 to disable all validation. Defaults to 100 (all response payloads). */ + sample?: number; + /** the default response payload validation rules (for all non-error responses) */ + schema?: RouteResponseConfigurationScheme; + /** HTTP status-code-specific payload validation rules. The status key is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. If a response status code is not present in the status object, the schema definition is used, except for errors which are not validated by default. */ + status?: Dictionary>; +} + +/** + * the default response payload validation rules (for all non-error responses) expressed as one of: + * * true - any payload allowed (no validation performed). This is the default. + * * false - no payload allowed. + * * a Joi validation object. This will receive the request's headers, params, query, payload, and auth credentials and isAuthenticated flags as context. + * * a validation function + * + * TODO check JoiValidationObject is correct for "a Joi validation object" + * + * For context see RouteAdditionalConfigurationOptions > response > schema + * and + * For context see RouteAdditionalConfigurationOptions > response > status + */ +export type RouteResponseConfigurationScheme = boolean | JoiValidationObject | ValidationFunctionForRouteResponse; + +/** + * see RouteResponseConfigurationScheme + * + * a validation function using the signature function(value, options, next) where: + * * value - the value of the response passed to `reply(value)` in the handler. + * * options - the server validation options, merged with an object containing the request's headers, params, payload, and auth credentials object and `isAuthenticated` flag. + * * next([err, [value]]) - the callback function called when validation is completed. `value` will be used as the response value when `err` is falsy, when `value` is not `undefined`, and when `route.settings.response.modify` is `true`. If the response is already a `Boom` error it will be set as its `message` value. + */ +export interface ValidationFunctionForRouteResponse { + (value: any, options: RouteResponseValidationContext & ValidationOptions, next: ContinuationValueFunction): void; +} + +/** + * A context for route input validation via a Joi schema or validation function. + * + * This object is merged with the route response options and passed into the validation function. + * + * See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L217 + */ +export interface RouteResponseValidationContext { + context: { + /** The request headers */ + headers: Dictionary; + /** The request path parameters */ + params: any; + /** The request query parameters */ + query: any; + /** The request payload parameters */ + payload: any; + + /** Partial request authentication information */ + auth: { + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: AuthenticatedCredentials; + }; + } +} + +/** + * For context see RouteAdditionalConfigurationOptions > security + */ +export interface RouteSecurityConfigurationObject { + /** controls the 'Strict-Transport-Security' header. If set to true the header will be set to max-age=15768000, if specified as a number the maxAge parameter will be set to that number. Defaults to true. You may also specify an object with the following fields: */ + hsts?: boolean | number | { + /** the max-age portion of the header, as a number. Default is 15768000. */ + maxAge?: number; + /** a boolean specifying whether to add the includeSubDomains flag to the header. */ + includeSubdomains?: boolean; + /** a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. */ + preload?: boolean; + }; + /** controls the 'X-Frame-Options' header. When set to true the header will be set to DENY, you may also specify a string value of 'deny' or 'sameorigin'. Defaults to true. To use the 'allow-from' rule, you must set this to an object with the following fields: */ + xframe?: true | 'deny' | 'sameorigin' | { + /** may also be 'deny' or 'sameorigin' but set directly as a string for xframe */ + rule: 'allow-from'; + /** when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. */ + source: string; + }; + /** boolean that controls the 'X-XSS-PROTECTION' header for IE. Defaults to true which sets the header to equal '1; mode=block'. NOTE: This setting can create a security vulnerability in versions of IE below 8, as well as unpatched versions of IE8. See [here](https://hackademix.net/2009/11/21/ies-xss-filter-creates-xss-vulnerabilities/) and [here](https://technet.microsoft.com/library/security/ms10-002) for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. [Kept typing non optional to force this security related documentation to be read.] */ + xss: boolean; + /** boolean controlling the 'X-Download-Options' header for IE, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. */ + noOpen?: boolean; + /** boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff' */ + noSniff?: boolean; +} + +/** + * request input validation rules for various request components. When using a Joi validation object, the values of the other inputs (i.e. headers, query, params, payload, and auth) are made available under the validation context (accessible in rules as Joi.ref('$query.key')). Note that validation is performed in order (i.e. headers, params, query, payload) and if type casting is used (converting a string to number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. If the validation rules for headers, params, query, and payload are defined at both the routes defaults level and an individual route, the individual route settings override the routes defaults (the rules are not merged). The validate object supports: + * For context see RouteAdditionalConfigurationOptions > validate + * TODO check JoiValidationObject is correct for "a Joi validation object" + */ +export interface RouteValidationConfigurationObject { + /** + * validation rules for incoming request headers (note that all header field names must be in lowercase to match the headers normalized by node). Values allowed: + * * true - any headers allowed (no validation performed). This is the default. + * * false - no headers allowed (this will cause all valid HTTP requests to fail). + * * a Joi validation object. + * * a validation function using the signature function(value, options, next) where: + * * value - the object containing the request headers. + * * options - the server validation options. + * * next(err, value) - the callback function called when validation is completed. `value` will be used as the `headers` value when `err` is falsy. If `next` is called with `undefined` or no arguments then the original value of `value` will be used. + */ + headers?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; + /** + * validation rules for incoming request path parameters, after matching the path against the route and extracting any parameters then stored in request.params. Values allowed: + * Same as `headers`, see above. + */ + params?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; + /** + * validation rules for an incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs and stored in request.query prior to validation. Values allowed: + * Same as `headers`, see above. + */ + query?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; + /** + * validation rules for an incoming request payload (request body). Values allowed: + * Same as `headers`, see above, with the addition that: + * * a Joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are supported, it must be explicitly defined by setting the payload value to a joi schema with null allowed (e.g. Joi.object({ /* keys here * / }).allow(null)). + */ + payload?: boolean | JoiValidationObject | ValidationFunctionForRouteInput; + /** an optional object with error fields copied into every validation error response. */ + errorFields?: any; + /** + * determines how to handle invalid requests. Allowed values are: + * * 'error' - return a Bad Request (400) error response. This is the default value. + * * 'log' - log the error but continue processing the request. + * * 'ignore' - take no action. + * * a custom error handler function with the signature function(request, reply, source, error) see RouteFailFunction + */ + failAction?: 'error' | 'log' | 'ignore' | RouteFailFunction; + /** + * options to pass to Joi. Useful to set global options such as stripUnknown or abortEarly (the complete list is [available here](https://github.com/hapijs/joi/blob/master/API.md#validatevalue-schema-options-callback)). + * If a custom validation function (see `headers`, `params`, `query`, or `payload` above) is defined then `options` can an arbitrary object that will be passed to this function as the second parameter. + * Defaults to no options. + */ + options?: ValidationOptions; +} + +/** + * a validation function using the signature function(value, options, next) where: + * For context see RouteAdditionalConfigurationOptions > validate (RouteValidationConfigurationObject) + * + * Also see ValidationFunctionForRouteResponse + * @param value - the object containing the request headers, query, path params or payload. + * @param options - the server validation options. + * @param next([err, [value]]) - the callback function called when validation is completed. + */ +export interface ValidationFunctionForRouteInput { + (value: any, options: RouteInputValidationContext & ValidationOptions, next: ContinuationValueFunction): void; +} + +/** + * A context for route input validation via a Joi schema or validation function. + * + * This object is merged with the route validation options and passed into the validation function. + * + * See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L122 + */ +export interface RouteInputValidationContext { + context: { + // These are only set when *not* validating the respective source (e.g. params, query and payload are set when validating headers): + // See https://github.com/hapijs/hapi/blob/v16.1.1/lib/validation.js#L132 + headers?: Dictionary; + params?: any; + query?: any; + payload?: any; + + /** The request authentication information */ + auth: RequestAuthenticationInformation; + } +} + +/** + * a custom error handler function with the signature 'function(request, reply, source, error)` + * @param request - the request object. + * @param reply - the continuation reply interface. + * @param source - the source of the invalid field (e.g. 'headers', 'params', 'query', 'payload'). + * @param error - the error object prepared for the client response (including the validation function error under error.data). + */ +export interface RouteFailFunction { + (request: Request, reply: ReplyWithContinue, source: string, error: any): void; +} + +/** + * optional cookie settings + * [See docs](https://hapijs.com/api/16.1.1#serverstatename-options) + * Related to see ConnectionConfigurationServerDefaults + */ +export interface ServerStateCookieConfiguationObject { + /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */ + ttl?: number | null; + /** sets the 'Secure' flag. Defaults to true. */ + isSecure?: boolean; + /** sets the 'HttpOnly' flag. Defaults to true. */ + isHttpOnly?: boolean; + /** + * sets the 'SameSite' flag where the value must be one of: + * * false - no flag. + * * 'Strict' - sets the value to 'Strict' (this is the default value). + * * 'Lax' - sets the value to 'Lax'. + */ + isSameSite?: false | 'Strict' | 'Lax'; + /** the path scope. Defaults to null (no path). */ + path?: string | null; + /** the domain scope. Defaults to null (no domain). */ + domain?: string | null; + /** + * if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: + * * request - the request object. + * * next - the continuation function using the function(err, value) signature. + */ + autoValue?(request: Request, next: ContinuationValueFunction): void; + /** + * encoding performs on the provided value before serialization. Options are: + * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value. + * * 'base64' - string value is encoded using Base64. + * * 'base64json' - object value is JSON-stringified then encoded using Base64. + * * 'form' - object value is encoded using the x-www-form-urlencoded method. + * * 'iron' - Encrypts and sign the value using iron. + */ + encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron'; + /** + * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are: + * * integrity - algorithm options. Defaults to require('iron').defaults.integrity. + * * password - password used for HMAC key generation (must be at least 32 characters long). + */ + sign?: { + integrity?: any; // TODO make iron definitions and getting typing from iron + password: string; + }; + /** password used for 'iron' encoding (must be at least 32 characters long). */ + password?: string; + /** options for 'iron' encoding. Defaults to require('iron').defaults. */ + iron?: any; // TODO make iron definitions and getting typing from iron + /** if true, errors are ignored and treated as missing cookies. */ + ignoreErrors?: boolean; + /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */ + clearInvalid?: boolean; + /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */ + strictHeader?: boolean; + /** used by proxy plugins (e.g. h2o2). */ + passThrough?: any; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverconnections) + */ +export interface ServerConnection { + /** settings - the connection configuration object passed to server.connection() after applying the server defaults. */ + settings: ServerConnectionOptions; + /** server - the connection's Server object. */ + server: Server; + /** type - set to 'tcp' is the connection is listening on a TCP port, otherwise to 'socket'(a UNIX domain socket or a Windows named pipe). */ + type: 'tcp' | 'socket'; + /** + * registrations + * Described [See docs](https://hapijs.com/api/16.1.1#serverregistrations) "When the server contains more than one connection, each server.connections array member provides its own connection.registrations." + */ + registrations: ServerRegisteredPlugins; + /** states - TODO contribute docs to hapi if they want, and then update type here */ + states: any; + /** auth - TODO contribute docs to hapi if they want, and then update type here */ + auth: any; + /** + * plugins + * TODO contribute docs to hapi if they want. Assuming similar to `registrations`, `listener`, `info`, etc + */ + plugins: PluginsStates; + /** + * app + * TODO contribute docs to hapi if they want. Assuming similar to `registrations`, `listener`, `info`, etc + */ + app: any; + /** Described in server.listener [See docs](https://hapijs.com/api/16.1.1#serverlistener) */ + listener: ServerListener; + /** Described in server.info [See docs](https://hapijs.com/api/16.1.1#serverinfo) */ + info: ServerConnectionInfo; + /** Described in server.inject [See docs](https://hapijs.com/api/16.1.1#serverinjectoptions-callback) */ + inject(options: string | InjectedRequestOptions, callback: (res: InjectedResponseObject) => void): void; + inject(options: string | InjectedRequestOptions, ): Promise; + /** Mentioned but not documented under server.connections [See docs](https://hapijs.com/api/16.1.1#serverconnections) */ + table(host?: string): Route[]; + /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#serverlookupid) */ + lookup(id: string): RoutePublicInterface | null; + /** Described in server.table [See docs](https://hapijs.com/api/16.1.1#servermatchmethod-path-host) */ + match(method: HTTP_METHODS, path: string, host?: string): RoutePublicInterface | null; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverinfo) + */ +export interface ServerConnectionInfo { + /** a unique connection identifier (using the format '{hostname}:{pid}:{now base36}'). */ + id: string; + /** the connection creation timestamp. */ + created: number; + /** the connection start timestamp (0 when stopped). */ + started: number; + /** + * the connection port based on the following rules: + * * the configured port value before the server has been started. + * * the actual port assigned when no port is configured or set to 0 after the server has been started. + * TODO check this type. What happens when socket is a UNIX domain socket or Windows named pipe? + */ + port: number | string; + /** the host name the connection was configured to. Defaults to the operating system hostname when available, otherwise 'localhost'. */ + host: string; + /** the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). */ + address: undefined | string; + /** the protocol used. 'socket' when UNIX domain socket or Windows named pipe. */ + protocol: 'http' | 'https' | 'socket'; + /** a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri setting if provided, otherwise constructed from the available settings. If no port is available or set to 0, the uri will not include a port component. */ + uri: string; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverlistener) + */ +export type ServerListener = http.Server; + +/** + * server.realm + * The realm object contains server-wide or plugin-specific state that can be shared across various methods. For example, when calling server.bind(), the active realm settings.bind property is set which is then used by routes and extensions added at the same level (server root or plugin). Realms are a limited version of a sandbox where plugins can maintain state used by the framework when adding routes, extensions, and other properties. + * [See docs](https://hapijs.com/api/16.1.1#serverrealm) + */ +export interface ServerRealm { + /** when the server object is provided as an argument to the plugin register() method, modifiers provides the registration preferences passed the server.register() method and includes: */ + modifiers: { + /** routes preferences: */ + route: { + /** the route path prefix used by any calls to server.route() from the server. Note that if a prefix is used and the route path is set to '/', the resulting path will not include the trailing slash. */ + prefix: string; + /** the route virtual host settings used by any calls to server.route() from the server. */ + vhost: string; + } + }; + /** the active plugin name (empty string if at the server root). */ + plugin: string; + /** the plugin options object passed at registration. */ + pluginOptions: any; // OptionsPassedToPlugin; + /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ + plugins: PluginsStates; + /** settings overrides (from RouteAdditionalConfigurationOptions) */ + settings: { + files: { + relativeTo: string; + }; + bind: any; + }; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) + */ +export interface ServerRegisteredPlugins { + [pluginName: string]: ServerRegisteredPlugin; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverregistrations) + */ +export interface ServerRegisteredPlugin { + /** the plugin version. */ + version: string; + /** the plugin name. */ + name: string; + /** + * options used to register the plugin. + * TODO update with outcome of: https://github.com/hapijs/hapi/pull/3479 + */ + options: any; // OptionsPassedToPlugin; + /** plugin registration attributes. */ + attributes: PluginAttributes; +} + +export interface ServerAuth { + /** + * server.auth.api + * An object where each key is a strategy name and the value is the exposed strategy API. Available on when the authentication scheme exposes an API by returning an api key in the object returned from its implementation function. + * When the server contains more than one connection, each server.connections array member provides its own connection.auth.api object. + * [See docs](https://hapijs.com/api/16.1.1#serverauthapi) + */ + api: Dictionary; + /** + * server.auth.default + * Sets a default strategy which is applied to every route + * The default does not apply when the route config specifies auth as false, or has an authentication strategy configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication config is applied to the defaults. + * Note that if the route has authentication config, the default only applies at the time of adding the route, not at runtime. This means that calling default() after adding a route with some authentication config will have no impact on the routes added prior. However, the default will apply to routes added before default() is called if those routes lack any authentication config. + * The default auth strategy configuration can be accessed via connection.auth.settings.default. To obtain the active authentication configuration of a route, use connection.auth.lookup(request.route). + * [See docs](https://hapijs.com/api/16.1.1#serverauthdefaultoptions) + */ + default(options: string | AuthOptions): void; + /** + * server.auth.scheme + * Registers an authentication scheme + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + * @param name the scheme name. + * @param scheme the method implementing the scheme with signature function(server, options) see ServerAuthScheme + */ + scheme(name: string, scheme: ServerAuthScheme): void; + /** + * Registers an authentication strategy + * [See docs](https://hapijs.com/api/16.1.1#serverauthstrategyname-scheme-mode-options) + * @param name the strategy name. + * @param scheme the scheme name (must be previously registered using server.auth.scheme()). + * @param mode if set to true (which is the same as 'required') or to a valid authentication mode ('required', 'optional', 'try'), the scheme is automatically assigned as the default strategy for any route without an auth config. Can only be assigned to a single server strategy. Defaults to false (no default settings). + * @param options scheme options based on the scheme requirements. + */ + strategy(name: string, scheme: string, options?: any): void; + strategy(name: string, scheme: string, mode: boolean | 'required' | 'optional' | 'try', options?: any): void; + /** + * Tests a request against an authentication strategy + * Note that the test() method does not take into account the route authentication configuration. It also does not perform payload authentication. It is limited to the basic strategy authentication execution. It does not include verifying scope, entity, or other route properties. + * [See docs](https://hapijs.com/api/16.1.1#serverauthteststrategy-request-next) + * @param strategy - the strategy name registered with server.auth.strategy(). + * @param request - the request object. + * @param next - the callback function with signature function(err, credentials) where: + * * err - the error if authentication failed. + * * credentials - the authentication credentials object if authentication was successful. + */ + test(strategy: string, request: Request, next: (err: Error | null, credentials: AuthenticatedCredentials) => void): void; +} + +export type Strategy = any; +export type SchemeSettings = any; + +/** + * the method implementing the scheme with signature function(server, options) where: + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + * @param server a reference to the server object the scheme is added to. + * @param options optional scheme settings used to instantiate a strategy. + */ +export interface ServerAuthScheme { + (server: Server, options: SchemeSettings): SchemeMethodResult; +} + +/** + * The scheme method must return an object with the following + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + */ +export interface SchemeMethodResult { + /** optional object which is exposed via the server.auth.api object. */ + api?: Strategy; + /** + * required function called on each incoming request configured with the authentication scheme + * When the scheme authenticate() method implementation calls reply() with an error condition, the specifics of the error affect whether additional authentication strategies will be attempted (if configured for the route). If the err passed to the reply() method includes a message, no additional strategies will be attempted. If the err does not include a message but does include the scheme name (e.g. Boom.unauthorized(null, 'Custom')), additional strategies will be attempted in the order of preference (defined in the route configuration). If authentication fails the scheme names will be present in the 'WWW-Authenticate' header. + * @param request the request object. + * @param reply the reply interface the authentication method must call when done authenticating the request + */ + authenticate(request: Request, reply: ReplySchemeAuth): void; + /** + * optional function called to authenticate the request payload + * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), authentication may still be successful if the route auth.payload configuration is set to 'optional'. + * @param request the request object. + * @param reply is called if authentication failed + */ + payload?(request: Request, reply: ReplySchemeAuthOfPayload): void; + /** + * optional function called to decorate the response with authentication headers before the response headers or payload is written where: + * @param request the request object. + * @param reply is called if an error occured + */ + response?(request: Request, reply: ReplySchemeAuthDecorateResponse): void; + /** an optional object with the following keys: */ + options?: { + /** if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. */ + payload?: boolean; + }; +} + +export interface ServerCacheMethod { + /** + * Provisions a cache segment within the server cache facility + * [See docs](https://hapijs.com/api/16.1.1#servercacheoptions) + */ + (options: CatboxServerCacheConfiguration): Catbox.Policy; + /** + * Provisions a server cache as described in server.cache + * If no callback is provided, a Promise object is returned. + * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + * [See docs](https://hapijs.com/api/16.1.1#servercacheprovisionoptions-callback) + * @param options same as the server cache configuration options. + * @param callback the callback method when cache provisioning is completed or failed with the signature function(err) where: + * * err - any cache startup error condition. + */ + provision(options: CatboxServerCacheConfiguration): Promise; + provision(options: CatboxServerCacheConfiguration, callback: (err?: Error) => void): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Request + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Request object + * The request object is created internally for each incoming request. It is different from the node.js request object received from the HTTP server callback (which is available in request.raw.req). The request object methods and properties change throughout the request lifecycle. + * [See docs](https://hapijs.com/api/16.1.1#request-object) + * [See docs](https://hapijs.com/api/16.1.1#request-properties) + */ +export class Request extends Podium { + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. */ + app: any; + /** authentication information */ + auth: RequestAuthenticationInformation; + /** the connection the request was received by. */ + connection: ServerConnection; + /** the node domain object used to protect against exceptions thrown in extensions, handlers and route prerequisites. Can be used to manually bind callback functions otherwise bound to other domains. Set to null when the server useDomains options is false. */ + domain: domain.Domain | null; + /** the raw request headers (references request.raw.headers). */ + headers: Dictionary; + /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').*/ + id: string; + /** request information */ + info: { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + /** + * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * Note: marking as optional as "... this is only available after ..." + */ + isOriginMatch?: boolean; + }; + /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */ + host: string; + /** the hostname part of the 'Host' header (e.g. 'example.com'). */ + hostname: string; + /** request reception timestamp. */ + received: number; + /** content of the HTTP 'Referrer' (or 'Referer') header. */ + referrer: string; + /** remote client IP address. */ + remoteAddress: string; + /** + * remote client port. + * Set to string in casethey're requesting from a UNIX domain socket. + * TODO, what type does Hapi return, should this be number | string? + */ + remotePort: string; + /** request response timestamp (0 is not responded yet). */ + responded: number; + }; + /** the request method in lower case (e.g. 'get', 'post'). */ + method: string; + /** the parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ + mime: string; + /** an object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. */ + orig: { + params: any; + query: any; + payload: any; + }; + /** an object where each key is a path parameter name with matching value as described in Path parameters [See docs](https://hapijs.com/api/16.1.1#path-parameters). */ + params: Dictionary; + /** an array containing all the path params values in the order they appeared in the path. */ + paramsArray: string[]; + /** the request URI's pathname [See docs](https://nodejs.org/api/url.html#url_urlobject_pathname) component. */ + path: string; + /** + * the request payload based on the route payload.output and payload.parse settings. + * TODO check this typing and add references / links. + */ + payload: stream.Readable | Buffer | any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: PluginsStates; + /** an object where each key is the name assigned by a route prerequisites function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses. */ + pre: Object; + /** the response object when set. The object can be modified but must not be assigned another object. To replace the response with another from within an extension point, use reply(response) to override with a different response. Contains null when no response has been set (e.g. when a request terminates prematurely when the client disconnects). */ + response: Response | null; + /** same as pre but represented as the response object created by the pre method. */ + preResponses: Object; + /** + * by default the object outputted from [node's URL parse()](https://nodejs.org/docs/latest/api/url.html#url_urlobject_query) method. + * Might also be set indirectly via [request.setUrl](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/17354#requestseturlurl-striptrailingslash) in which case it may be + * a string (if url is set to an object with the query attribute as an unparsed string). + */ + query: any; + /** an object containing the Node HTTP server objects. **Direct interaction with these raw objects is not recommended.** */ + raw: { + req: http.IncomingMessage; // Or http.ClientRequest http://www.apetuts.com/tutorial/node-js-http-client-request-class/ ? + res: http.ServerResponse; + }; + /** + * the route public interface. + * Optional due to "request.route is not yet populated at this point." [See docs](https://hapijs.com/api/16.1.1#request-lifecycle) + */ + route?: RoutePublicInterface; + /** the server object. */ + server: Server; + /** an object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ + state: Dictionary; + /** the parsed request URI */ + url: url.Url; + + /** + * request.setUrl(url, [stripTrailingSlash]) + * Available only in 'onRequest' extension methods. + * Changes the request URI before the router begins processing the request + * [See docs](https://hapijs.com/api/16.1.1#requestseturlurl-striptrailingslash) + * @param url the new request URI. If url is a string, it is parsed with node's URL parse() method. url can also be set to an object compatible with node's URL parse() method output. + * @param stripTrailingSlash if true, strip the trailing slash from the path. Defaults to false. + */ + setUrl(url: string | url.Url, stripTrailingSlash?: boolean): void; + /** + * request.setMethod(method) + * Available only in 'onRequest' extension methods. + * Changes the request method before the router begins processing the request + * [See docs](https://hapijs.com/api/16.1.1#requestsetmethodmethod) + * @param method is the request HTTP method (e.g. 'GET'). + */ + setMethod(method: HTTP_METHODS): void; + /** + * request.generateResponse(source, [options]) + * Always available. + * Returns a response which you can pass into the reply interface where: + * [See docs](https://hapijs.com/api/16.1.1#requestgenerateresponsesource-options) + * @param source the object to set as the source of the reply interface. TODO, submit a PR to clarify this doc, from the source code it's clear that "the object to set" refers to something of type `ReplyValue` i.e. that can be null, string, number, object, Stream, Promise, or Buffer. + * @param options options for the method, optional. Not documented yet, perhaps not very important. + */ + generateResponse(source?: ReplyValue, options?: {marshal?: any; prepare?: any; close?: any; variety?: any}): Response; + /** + * request.log(tags, [data, [timestamp]]) + * Always available. + * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. + * Any logs generated by the server internally will be emitted only on the 'request-internal' channel and will include the event.internal flag set to true. + * [See docs](https://hapijs.com/api/16.1.1#requestlogtags-data-timestamp) + * @param tags a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. + * @param data an optional message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. + * @param timestamp an optional timestamp expressed in milliseconds. Defaults to Date.now() (now). + */ + log(tags: string | string[], data?: string | Object | (() => string | Object), timestamp?: number): void; + /** + * request.getLog([tags], [internal]) + * Always available. + * Returns an array containing the events matching any of the tags specified (logical OR) + * Note that this methods requires the route log configuration set to true. + * [See docs](https://hapijs.com/api/16.1.1#requestgetlogtags-internal) + * @param tags is a single tag string or array of tag strings. If no tags specified, returns all events. + * @param internal filters the events to only those with a matching event.internal value. If true, only internal logs are included. If false, only user event are included. Defaults to all events (undefined). + */ + getLog(tags?: string | string[], internal?: boolean): string[]; + getLog(internal?: boolean): string[]; + /** + * request.tail([name]) + * Available until immediately after the 'response' event is emitted. + * Adds a request tail which has to complete before the request lifecycle is complete. + * Returns a tail function which must be called when the tail activity is completed. + * Tails are actions performed throughout the request lifecycle, but which may end after a response is sent back to the client. For example, a request may trigger a database update which should not delay sending back a response. However, it is still desirable to associate the activity with the request when logging it (or an error associated with it). + * When all tails completed, the server emits a 'tail' event. + * [See docs](https://hapijs.com/api/16.1.1#requesttailname) + * @param name an optional tail name used for logging purposes. + */ + tail(name?: string): (() => void); + /** + * The server.decorate('request', ...) method can modify this prototype/interface. + * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts + * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) + */ + // [index: string]: any; +} + +export interface RequestAuthenticationInformation { + /** true if the request has been successfully authenticated, otherwise false. */ + isAuthenticated: boolean; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: any; + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: any; + /** the route authentication mode. */ + mode: string; + /** the authentication error is failed and mode set to 'try'. */ + error: Error; +} + +export type HTTP_METHODS_PARTIAL_lowercase = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; +export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_lowercase; +export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; + +/** + * Request events + * The request object supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://hapijs.com/api/16.1.1#request-events) + */ +export type RequestEventTypes = 'peek' | 'finish' | 'disconnect'; + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Handler functions + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Extending RouteConfiguration.handler + * + * The hapi documentation allows for the RouteConfiguration.handler type to have + * `{[pluginName: string]: pluginOptions}` + * "handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler" + * This can be provided by extending the hapi module definition as follows, + * see h2o2 for example: + * + * declare module 'hapi' { + * interface RouteHandlerPlugins { + * proxy?: ... + */ +export interface RouteHandlerPlugins { +} +/** + * The route handler function uses the signature function(request, reply) (NOTE: do not use a fat arrow style function for route handlers as they do not allow context binding and will cause problems when used in conjunction with server.bind) where: + * * request - is the incoming request object (this is not the node.js request object). + * * reply - the reply interface the handler must call to set a response and return control back to the framework. + * [See docs](https://hapijs.com/api/16.1.1#route-handler) + * Same function signature used by request extension point used in server.ext(event), see ServerExtConfigurationObject.method + */ +export interface RouteHandler { + (request: Request, reply: ReplyNoContinue): void; + // (request: Request, reply: StrictReply): void; +} + +/** + * "the function to call, the function signature is identical to a route handler as described in Route handler." + * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) Route prerequisites + */ +export type RoutePrerequisiteRequestHandler = RouteHandler; + +/** + * request extension points: function(request, reply) where + * this - the object provided via options.bind or the current active context set with server.bind(). + * [See docs](https://hapijs.com/api/16.1.1#serverextevents) + * @param request the request object. + * @param reply the reply interface which is used to return control back to the framework. To continue normal execution of the request lifecycle, reply.continue() must be called. If the extension type is 'onPostHandler' or 'onPreResponse', a single argument passed to reply.continue() will override the current set response (including all headers) but will not stop the request lifecycle execution. To abort processing and return a response to the client, call reply(value) where value is an error or any other valid response. + */ +export interface ServerExtRequestHandler { + (request: Request, reply: ReplyWithContinue): void; +} + +/** + * Used by various extensions to handle a request and + * synchronously return a result of some form. + * + * Left in for backwards compatibility of typings but according to the + * [DefinitelyTyped Readme under common mistakes](https://github.com/DefinitelyTyped/DefinitelyTyped#common-mistakes) + * it talks about not using generic types unless the type was used in typing one + * or more of the function arguments. Using it to type the return was suggested + * to be the same as a type assertion. + */ +export interface RequestHandler { + (request: Request): T; +} + +/** + * Used by server extension points + * err can be `Boom` error or Error that will be wrapped as a `Boom` error + * For source [See code](https://github.com/hapijs/hapi/blob/v16.1.1/lib/reply.js#L109-L118) + * For source [See code](https://github.com/hapijs/hapi/blob/v16.1.1/lib/response.js#L60-L65) + */ +export interface ContinuationFunction { + (err?: Boom.BoomError): void; +} +/** + * For source [See docs](https://github.com/hapijs/hapi/blob/v16.1.1/lib/response.js#L60-L65) + * TODO Can value be typed with a useful generic? + */ +export interface ContinuationValueFunction { + (err: Boom.BoomError): void; + (err: null | undefined, value: any): void; + (): void; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Reply functions + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Typings listed explicitly here [See docs](https://hapijs.com/api/16.1.1#replyerr-result) + * Typings also described in part here [See docs](https://hapijs.com/api/16.1.1#response-object) + */ +export type ReplyValue = _ReplyValue | Promise<_ReplyValue>; +export type _ReplyValue = null | undefined | string | number | boolean | Buffer | Error | stream.Stream | Object; // | array; + +/** + * Reply interface + * reply([err], [result]) + * Concludes the handler activity by setting a response and returning control over to the framework + * When reply() is called with an error or result response, that value is used as the response sent to the client. When reply() is called within a prerequisite, the value is saved for future use and is not used as the response. In all other places except for the handler, calling reply() will be considered an error and will abort the request lifecycle, jumping directly to the 'onPreResponse' event. + * To return control to the framework within an extension or other places other than the handler, without setting a response, the method reply.continue() must be called. Except when used within an authentication strategy, or in an 'onPostHandler' or 'onPreResponse' extension, the reply.continue() must not be passed any argument or an exception is thrown. + * [See docs](https://hapijs.com/api/16.1.1#reply-interface) + * [See docs](https://hapijs.com/api/16.1.1#replyerr-result) + * + * NOTE: modules should extend this interface to expose reply.Nnn methods + */ +export interface Base_Reply { + (err?: ReplyValue): Response; + (err: null, result?: ReplyValue): Response; + /** the active realm associated with the route. */ + realm: ServerRealm; + /** the request object */ + request: Request; + + /** + * reply.entity(options) + * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request conditions, reply.entity() returns control back to the framework with a 304 response. Otherwise, it sets the provided entity headers and returns null. + * Returns a response object if the reply is unmodified or null if the response has changed. If null is returned, the developer must call reply() to continue execution. If the response is not null, the developer must not call reply(). + * [See docs](https://hapijs.com/api/16.1.1#replyentityoptions) + * @param options a required configuration object with: + * * etag - the ETag string. Required if modified is not present. Defaults to no header. + * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. + * * vary - same as the response.etag() option. Defaults to true. + */ + entity(options: {etag?: string, modified?: string, vary?: boolean}): Response | null; + /** + * reply.close([options]) + * Concludes the handler activity by returning control over to the router and informing the router that a response has already been sent back directly via request.raw.res and that no further response action is needed. Supports the following optional options: + * The response flow control rules do not apply. + * [See docs](https://hapijs.com/api/16.1.1#replycloseoptions) + * @param options options object: + * * end - if false, the router will not call request.raw.res.end()) to ensure the response was ended. Defaults to true. + */ + close(options?: {end?: boolean}): void; + /** + * reply.redirect(uri) + * Redirects the client to the specified uri. Same as calling reply().redirect(uri). + * The response flow control rules apply. + * Sets an HTTP redirection response (302) and decorates the response with additional methods for + * changing to a permanent or non-rewritable redirect is also available see response object redirect for more information. + * [See docs](https://hapijs.com/api/16.1.1#replyredirecturi) + * @param uri an absolute or relative URI used to redirect the client to another resource. + */ + redirect(uri: string): ResponseRedirect; + /** + * reply.response(result) + * Shorthand for calling `reply(null, result)`, replies with the response set to `result`. + * [See docs](https://hapijs.com/api/16.1.1#replyresponseresult) + * TODO likely to change. Await approval of pull request to Hapi docs. + */ + response(result: ReplyValue): Response; + /** + * Sets a cookie on the response + * [See docs](https://hapijs.com/api/16.1.1#reply) + * TODO likely to change. Await approval of pull request to Hapi docs. + */ + state(name: string, value: any, options?: any): void; + /** + * Clears a cookie on the response + * [See docs](https://hapijs.com/api/16.1.1#reply) + * TODO likely to change. Await approval of pull request to Hapi docs. + */ + unstate(name: string, options?: any): void; + /** + * The server.decorate('reply', ...) method can modify this prototype/interface. + * Have disabled these typings as there is a better alternative, see example in: tests/server/decorate.ts + * [And discussion here](https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14517#issuecomment-298891630) + */ + // [index: string]: any; +} +/** + * reply.continue([result]) + * Returns control back to the framework without ending the request lifecycle + * [See docs](https://hapijs.com/api/16.1.1#replycontinueresult) + * [See docs](https://hapijs.com/api/16.1.1#replyerr-result) "With the exception of the handler function, all other methods provide the reply.continue() method which instructs the framework to continue processing the request without setting a response." + * @param result if called in the handler, prerequisites, or extension points other than the 'onPreHandler' and 'onPreResponse', the result argument is not allowed and will throw an exception if present. If called within an authentication strategy, it sets the authenticated credentials. If called by the 'onPreHandler' or 'onPreResponse' extensions, the result argument overrides the current response including all headers, and returns control back to the framework to continue processing any remaining extensions. + */ +export interface Continue_Reply { + continue(result?: ReplyValue): Response | undefined; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > authenticate. + * Also [See docs](https://hapijs.com/api/16.1.1#replyerr-result). + * TODO check it has Base_Reply methods and properties + */ +export interface ReplySchemeAuth extends Base_Reply { + /** + * This function is called if authentication failed. + * TODO, check type the `response` parameter. In https://hapijs.com/api/16.1.1#replyerr-result it is referred to as "null" but this seems to be for a third scenario where it is "used to return both an error and credentials in the authentication methods" then "reply() must be called with three arguments function(err, null, data)" + * @param err any authentication error. + * @param response any authentication response action such as redirection. Ignored if err is present, otherwise required. + * @param result an object containing: + * * credentials the authenticated credentials. + * * artifacts optional authentication artifacts. + */ + (err: Error | null, response: AnyAuthenticationResponseAction | null, result: AuthenticationResult): void; + /** + * is called if authentication succeeded + * @param result same object as result above. + */ + continue(result: AuthenticationResult): void; +} +/** + * Typing as any as it's not yet clear what type this argument takes. + * "any authentication response action such as redirection" is it equivalent to + * `ReplyValue` ? + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) + * TODO research hapi source and type this. + */ +export type AnyAuthenticationResponseAction = any; +/** [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) */ +export interface AuthenticationResult { + credentials?: AuthenticatedCredentials; + artifacts?: any; +} +export interface AuthenticatedCredentials { + // Disabled to allow typing within a project + // [index: string]: any; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > payload + * TODO check it has Base_Reply methods and properties + */ +export interface ReplySchemeAuthOfPayload extends Base_Reply { + /** + * function called to authenticate the request payload where: + * @param err any authentication error. + * @param response any authentication response action such as redirection. Ignored if err is present, otherwise required. + */ + (err: Error | null, response: AnyAuthenticationResponseAction): void; + /** is called if payload authentication succeeded */ + continue(): void; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#serverauthschemename-scheme) > response + * TODO check it has Base_Reply methods and properties + */ +export interface ReplySchemeAuthDecorateResponse extends Base_Reply { + /** + * is called if an error occurred + * @param err any authentication error. + * @param response any authentication response to send instead of the current response. Ignored if err is present, otherwise required. + */ + (err?: Error, response?: ReplyValue): void; + /** is called if the operation succeeded. */ + continue(): void; +} + +export interface ReplyWithContinue extends Continue_Reply, Base_Reply {} + +export interface ReplyNoContinue extends Base_Reply {} + +// TODO assess use and usefulness of StrictReply + +// Concludes the handler activity by setting a response and returning control over to the framework where: +// erran optional error response. +// result an optional response payload. +// Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. +// FLOW CONTROL: +// When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() +/** + * + */ +// export interface Reply { // extends ReplyMethods { +// (err: Error, +// result?: string | number | boolean | Buffer | stream.Stream | Promise | T, +// /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ +// credentialData?: any): BoomError; +// /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ +// (result: string | number | boolean | Buffer | stream.Stream | Promise | T): Response; +// } + +/** Concludes the handler activity by setting a response and returning control over to the framework where: + erran optional error response. + result an optional response payload. + Since an request can only have one response regardless if it is an error or success, the reply() method can only result in a single response value. This means that passing both an err and result will only use the err. There is no requirement for either err or result to be (or not) an Error object. The framework will simply use the first argument if present, otherwise the second. The method supports two arguments to be compatible with the common callback pattern of error first. + FLOW CONTROL: + When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: hold(), send() */ +// export interface StrictReply extends ReplyMethods { +// (err: Error, +// result?: Promise | T, +// /** Note that when used to return both an error and credentials in the authentication methods, reply() must be called with three arguments function(err, null, data) where data is the additional authentication information. */ +// credentialData?: any): BoomError; +// /** Note that if result is a Stream with a statusCode property, that status code will be used as the default response code. */ +// (result: Promise | T): Response; +// } + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Response + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Response object + * [See docs](https://hapijs.com/api/16.1.1#response-object) + * + * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/16.1.1#response-events) + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ +export interface Response extends Podium { + /** the HTTP response status code. Defaults to 200 (except for errors). */ + statusCode: number; + /** an object containing the response headers where each key is a header field name. Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. */ + headers: Dictionary; + /** the value provided using the reply interface. */ + source: ReplyValue; + /** + * a string indicating the type of source with available values: + * * 'plain' - a plain response such as string, number, null, or simple object (e.g. not a Stream, Buffer, or view). + * * 'buffer' - a Buffer. + * * 'stream' - a Stream. + * * 'promise' - a Promise object. + */ + variety: 'plain' | 'buffer' | 'stream' | 'promise'; + /** application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. */ + app: any; + /** plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. */ + plugins: PluginsStates; + /** response handling flags: */ + settings: { + /** the 'Content-Type' HTTP header 'charset' property. Defaults to 'utf-8'. */ + charset: string; + /** the string encoding scheme used to serial data into the HTTP payload when source is a string or marshals into a string. Defaults to 'utf8'. */ + encoding: string; + /** if true and source is a Stream, copies the statusCode and headers of the stream to the outbound response. Defaults to true. */ + passThrough: boolean; + /** options used for source value requiring stringification. Defaults to no replacer and no space padding. */ + stringify: Json.StringifyArguments; + /** if set, overrides the route cache expiration milliseconds value set in the route config. Defaults to no override. */ + ttl: number | null; + /** if true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. */ + varyEtag: boolean; + }; + + /** + * The following attribute is present in one or more of the examples + * TODO update once Hapi docs describes explicitly + */ + isBoom?: boolean; + /** + * The following attribute is present in one or more of the examples + * TODO update once Hapi docs describes explicitly + */ + isMissing?: boolean; + /** + * The following attribute is present in one or more of the examples + * TODO update once Hapi docs describes explicitly + */ + output?: Boom.Output; + + /** + * sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) + * @param length the header value. Must match the actual payload size. + */ + bytes(length: number): Response; + /** + * sets the 'Content-Type' HTTP header 'charset' property + * @param charset the charset property value. + */ + charset(charset: string): Response; + /** + * sets the HTTP status code + * @param statusCode the HTTP status code (e.g. 200). + */ + code(statusCode: number): Response; + /** + * sets the HTTP status message + * @param httpMessage the HTTP status message (e.g. 'Ok' for status code 200). + */ + message(httpMessage: string): Response; + /** + * sets the HTTP status code to Created (201) and the HTTP 'Location' header + * @param uri an absolute or relative URI used as the 'Location' header value. + */ + created(uri: string): Response; + /** + * sets the string encoding scheme used to serial data into the HTTP payload + * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)). + * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set. + * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. + * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported. + * * 'ucs2' - Alias of 'utf16le'. + * * 'base64' - Base64 encoding. When creating a Buffer from a string, this encoding will also correctly accept "URL and Filename Safe Alphabet" as specified in RFC4648, Section 5. + * * 'latin1' - A way of encoding the Buffer into a one-byte encoded string (as defined by the IANA in RFC1345, page 63, to be the Latin-1 supplement block and C0/C1 control codes). + * * 'binary' - Alias for 'latin1'. + * * 'hex' - Encode each byte as two hexadecimal characters. + */ + encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): Response; + /** + * sets the representation entity tag + * @param tag the entity tag string without the double-quote. + * @param options options object + * * weak - if true, the tag will be prefixed with the 'W/' weak signifier. Weak tags will fail to match identical tags for the purpose of determining 304 response status. Defaults to false. + * * vary - if true and content encoding is set or applied to the response (e.g 'gzip' or 'deflate'), the encoding name will be automatically added to the tag at transmission time (separated by a '-' character). Ignored when weak is true. Defaults to true. + */ + etag(tag: string, options?: {weak: boolean, vary: boolean}): Response; + /** + * sets an HTTP header + * @param name the header name. + * @param value the header value. + */ + header(name: string, value: string, options?: ResponseHeaderOptionsObject): Response; + /** + * sets the HTTP 'Location' header + * @param uri an absolute or relative URI used as the 'Location' header value. + */ + location(uri: string): Response; + /** + * sets an HTTP redirection response (302) and decorates the response with additional methods listed below, + * @param uri an absolute or relative URI used to redirect the client to another resource. + */ + redirect(uri: string): Response; + /** + * sets the JSON.stringify() replacer argument + * @param method the replacer function or array. Defaults to none. + */ + replacer(method: Json.StringifyReplacer): Response; + /** + * sets the JSON.stringify() space argument + * @param count the number of spaces to indent nested object keys. Defaults to no indentation. + */ + spaces(count: Json.StringifySpace): Response; + /** + * sets an HTTP cookie + * @param name the cookie name. + * @param value the cookie value. If no encoding is defined, must be a string. + * @param options optional configuration. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others). + */ + state(name: string, value: string | Object | any[], options?: ServerStateCookieConfiguationObject): Response; + /** + * sets a string suffix when the response is process via JSON.stringify(). + */ + suffix(suffix: string): Response; + /** + * overrides the default route cache expiration rule for this response instance + * @param msec the time-to-live value in milliseconds. + */ + ttl(msec: number): Response; + /** + * sets the HTTP 'Content-Type' header + * @param mimeType is the mime type. Should only be used to override the built-in default for each response type. + */ + type(mimeType: string): Response; + /** + * clears the HTTP cookie by setting an expired value + * @param name the cookie name. + * @param options optional configuration for expiring cookie. If the state was previously registered with the server using server.state(), the specified keys in options override those same keys in the server definition (but not others). + */ + unstate(name: string, options?: ServerStateCookieConfiguationObject): Response; + /** + * adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header + * @param header the HTTP request header name. + */ + vary(header: string): Response; + + /** + * Flow control - hold() + * When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: + * puts the response on hold until response.send() is called. Available only after reply() is called and until response.hold() is invoked once. + * [See docs](https://hapijs.com/api/16.1.1#flow-control) + */ + hold(): Response; + /** + * Flow control - send() + * When calling reply(), the framework waits until process.nextTick() to continue processing the request and transmit the response. This enables making changes to the returned response object before the response is sent. This means the framework will resume as soon as the handler method exits. To suspend this behavior, the returned response object supports the following methods: + * immediately resume the response. Available only after response.hold() is called and until response.send() is invoked once. + * [See docs](https://hapijs.com/api/16.1.1#flow-control) + */ + send(): Response; + + /** + * Mentioned here: "Note that prerequisites do not follow the same rules of the normal reply interface. In all other cases, calling reply() with or without a value will use the result as the response sent back to the client. In a prerequisite method, calling reply() will assign the returned value to the provided assign key. If the returned value is an error, the failAction setting determines the behavior. To force the return value as the response and skip any other prerequisites and the handler, use the reply().takeover() method." + * TODO prepare documentation PR and submit to hapi. + * [See docs](https://hapijs.com/api/16.1.1#route-prerequisites) + */ + takeover(): Response; +} + +/** + * Response Object Redirect Methods + * When using the redirect() method, the response object provides these additional methods: + * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) + */ +export interface ResponseRedirect extends Response { + /** + * temporary + * sets the status code to 302 or 307 (based on the rewritable() setting) where: + * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) + * @param isTemporary if false, sets status to permanent. Defaults to true. + */ + temporary(isTemporary: boolean): Response; + /** + * permanent + * sets the status code to 301 or 308 (based on the rewritable() setting) where: + * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) + * @param isPermanent if false, sets status to temporary. Defaults to true. + */ + permanent(isPermanent: boolean): Response; + /** + * rewritable + * sets the status code to 301/302 for rewritable (allows changing the request method from 'POST' to 'GET') or 307/308 for non-rewritable (does not allow changing the request method from 'POST' to 'GET'). Exact code based on the temporary() or permanent() setting. Arguments: + * [See docs](https://hapijs.com/api/16.1.1#response-object-redirect-methods) + * @param isRewritable if false, sets to non-rewritable. Defaults to true. + */ + rewritable(isRewritable: boolean): Response; +} + +/** + * [See docs](https://hapijs.com/api/16.1.1#response-object) under "response object provides the following methods" > header > options + */ +export interface ResponseHeaderOptionsObject { + /** if true, the value is appended to any existing header value using separator. Defaults to false. */ + append?: boolean; + /** string used as separator when appending to an existing value. Defaults to ','. */ + separator?: string; + /** if false, the header value is not set if an existing value present. Defaults to true. */ + override?: boolean; + /** if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. */ + duplicate?: boolean; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Plugins and register + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// TODO: move to separate file http://stackoverflow.com/questions/43276921 + +/** + * Plugins + * Plugins provide a way to organize the application code by splitting the server logic into smaller components. Each plugin can manipulate the server and its connections through the standard server interface, but with the added ability to sandbox certain properties. + * [See docs](https://hapijs.com/api/16.1.1#plugins) + * @param server the server object the plugin is being registered to. + * @param options an options object passed to the plugin during registration. + * @param next a callback method the function must call to return control back to the framework to complete the registration process with signature function(err) + */ +export interface PluginFunction { + (server: Server, options: OptionsPassedToPlugin, next: (err?: Error) => void): void; + /** + * Note attributes is NOT optional but this type is easier to use. + */ + attributes?: PluginAttributes; +} + +/** + * see Plugin + * [See docs](https://hapijs.com/api/16.1.1#plugins) + */ +export interface PluginAttributes { + /** + * required plugin name string. The name is used as a unique key. Published plugins should use the same name as the name field in the 'package.json' file. Names must be unique within each application. + * NOTE: marked as optional as `pkg` can be used instead. + */ + name?: string; + /** optional plugin version. The version is only used informatively to enable other plugins to find out the versions loaded. The version should be the same as the one specified in the plugin's 'package.json' file. */ + version?: string; + /** Alternatively, the name and version can be included via the pkg attribute containing the 'package.json' file for the module which already has the name and version included */ + pkg?: any; + /** if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ + multiple?: boolean; + /** optional string or array of string indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ + dependencies?: string | string[]; + /** if false, does not allow the plugin to call server APIs that modify the connections such as adding a route or configuring state. This flag allows the plugin to be registered before connections are added and to pass dependency requirements. When set to 'conditional', the mode is based on the presence of selected connections (if the server has connections, it is the same as true, but if no connections are available, it is the same as false). Defaults to true. */ + connections?: boolean | 'conditional'; + /** if true, will only register the plugin once per connection (or once per server for a connectionless plugin). If set, overrides the once option passed to server.register(). Defaults to undefined (registration will be based on the server.register() option once). */ + once?: boolean; +} + +/** + * Plugins State + * Related [See docs](https://hapijs.com/api/16.1.1#serverplugins) + * Related [See docs](https://hapijs.com/api/16.1.1#serverrealm) + */ +export interface PluginsStates { + [pluginName: string]: any; +} + +/** + * once, select, routes - optional plugin-specific registration options as defined see PluginRegistrationOptions + * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) + */ +export interface PluginRegistrationObject extends PluginRegistrationOptions { + /** the plugin registration function. */ + register: PluginFunction; + /** optional options passed to the registration function when called. */ + options?: OptionsPassedToPlugin; +} + +/** + * registration options (different from the options passed to the registration function): + * * once - if true, the registration is skipped for any connection already registered with. Cannot be used with plugin options. If the plugin does not have a connections attribute set to false and the registration selection is empty, registration will be skipped as no connections are available to register once. Defaults to false. + * * routes - modifiers applied to each route added by the plugin: + * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * * select - a string or array of string labels used to pre-select connections for plugin registration. + * [See docs](https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback) + */ +export interface PluginRegistrationOptions { + once?: boolean; + routes?: {prefix?: string, vhost?: string | string[]}; + select?: string | string[]; +} + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + JSON + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// This was in a seperate file and perhaps should move to some of the lib typings? +// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16065#issuecomment-299443673 +// +// json/json-tests.ts +// +// import * as JSON from './index'; +// +// var a: JSON.StringifyReplacer = function(key, value) { +// if (key === "do not include") { +// return undefined; +// } +// return value; +// }; +// + +export namespace Json { + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; + + /** + * Any value greater than 10 is truncated. + */ + export type StringifySpace = number | string; + + export interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + } +} diff --git a/types/hapi/test/connection/table.ts b/types/hapi/v16/test/connection/table.ts similarity index 94% rename from types/hapi/test/connection/table.ts rename to types/hapi/v16/test/connection/table.ts index 24eaa28ddc..3ead170c90 100644 --- a/types/hapi/test/connection/table.ts +++ b/types/hapi/v16/test/connection/table.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#servertablehost -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80, host: 'example.com' }); server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); diff --git a/types/hapi/test/continuation/errors.ts b/types/hapi/v16/test/continuation/errors.ts similarity index 100% rename from types/hapi/test/continuation/errors.ts rename to types/hapi/v16/test/continuation/errors.ts diff --git a/types/hapi/test/getting-started/01-creating-a-server.ts b/types/hapi/v16/test/getting-started/01-creating-a-server.ts similarity index 100% rename from types/hapi/test/getting-started/01-creating-a-server.ts rename to types/hapi/v16/test/getting-started/01-creating-a-server.ts diff --git a/types/hapi/test/getting-started/02-adding-routes.ts b/types/hapi/v16/test/getting-started/02-adding-routes.ts similarity index 100% rename from types/hapi/test/getting-started/02-adding-routes.ts rename to types/hapi/v16/test/getting-started/02-adding-routes.ts diff --git a/types/hapi/test/getting-started/03-serving-static-content.ts b/types/hapi/v16/test/getting-started/03-serving-static-content.ts similarity index 100% rename from types/hapi/test/getting-started/03-serving-static-content.ts rename to types/hapi/v16/test/getting-started/03-serving-static-content.ts diff --git a/types/hapi/test/getting-started/04-using-plugins.ts b/types/hapi/v16/test/getting-started/04-using-plugins.ts similarity index 100% rename from types/hapi/test/getting-started/04-using-plugins.ts rename to types/hapi/v16/test/getting-started/04-using-plugins.ts diff --git a/types/hapi/test/path/catch-all.ts b/types/hapi/v16/test/path/catch-all.ts similarity index 89% rename from types/hapi/test/path/catch-all.ts rename to types/hapi/v16/test/path/catch-all.ts index c9002392b1..e38a67ec96 100644 --- a/types/hapi/test/path/catch-all.ts +++ b/types/hapi/v16/test/path/catch-all.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#catch-all-route -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/path/parameters.ts b/types/hapi/v16/test/path/parameters.ts similarity index 95% rename from types/hapi/test/path/parameters.ts rename to types/hapi/v16/test/path/parameters.ts index 62bbfcc638..6bbba522db 100644 --- a/types/hapi/test/path/parameters.ts +++ b/types/hapi/v16/test/path/parameters.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#path-parameters -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/plugins/options.ts b/types/hapi/v16/test/plugins/options.ts similarity index 95% rename from types/hapi/test/plugins/options.ts rename to types/hapi/v16/test/plugins/options.ts index cd192f1996..7f6ad6c13c 100644 --- a/types/hapi/test/plugins/options.ts +++ b/types/hapi/v16/test/plugins/options.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverinfo -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; // added in addition to code from docs interface PluginOptions { diff --git a/types/hapi/test/reply/continue.ts b/types/hapi/v16/test/reply/continue.ts similarity index 91% rename from types/hapi/test/reply/continue.ts rename to types/hapi/v16/test/reply/continue.ts index de6994fbd0..5f23cb039a 100644 --- a/types/hapi/test/reply/continue.ts +++ b/types/hapi/v16/test/reply/continue.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#replycontinueresult -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/reply/entity.ts b/types/hapi/v16/test/reply/entity.ts similarity index 93% rename from types/hapi/test/reply/entity.ts rename to types/hapi/v16/test/reply/entity.ts index cfcce6de25..5cb187fa1e 100644 --- a/types/hapi/test/reply/entity.ts +++ b/types/hapi/v16/test/reply/entity.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#replyentityoptions -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/reply/redirect.ts b/types/hapi/v16/test/reply/redirect.ts similarity index 84% rename from types/hapi/test/reply/redirect.ts rename to types/hapi/v16/test/reply/redirect.ts index 5baf892ac1..934092868b 100644 --- a/types/hapi/test/reply/redirect.ts +++ b/types/hapi/v16/test/reply/redirect.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#replyredirecturi -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const handler: Hapi.RouteHandler = function (request, reply) { return reply.redirect('http://example.com'); diff --git a/types/hapi/test/reply/reply.ts b/types/hapi/v16/test/reply/reply.ts similarity index 92% rename from types/hapi/test/reply/reply.ts rename to types/hapi/v16/test/reply/reply.ts index 31f3bff9b4..bf92621986 100644 --- a/types/hapi/test/reply/reply.ts +++ b/types/hapi/v16/test/reply/reply.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#replyerr-result -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; // verbose notation @@ -19,4 +19,4 @@ const handler2: Hapi.RouteHandler = function (request, reply) { return reply('success') .type('text/plain') .header('X-Custom', 'some-value'); -}; \ No newline at end of file +}; diff --git a/types/hapi/test/reply/state_cookie.ts b/types/hapi/v16/test/reply/state_cookie.ts similarity index 95% rename from types/hapi/test/reply/state_cookie.ts rename to types/hapi/v16/test/reply/state_cookie.ts index bf94219311..8a0be7da34 100644 --- a/types/hapi/test/reply/state_cookie.ts +++ b/types/hapi/v16/test/reply/state_cookie.ts @@ -1,7 +1,7 @@ // from https://hapijs.com/tutorials/cookies?lang=en_US -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/v16/test/request/event-types.ts b/types/hapi/v16/test/request/event-types.ts new file mode 100644 index 0000000000..d9ee4dab33 --- /dev/null +++ b/types/hapi/v16/test/request/event-types.ts @@ -0,0 +1,30 @@ + +// From https://hapijs.com/api/16.1.1#requestsetmethodmethod + +import * as Hapi from '../../'; +const Crypto = require('crypto'); +const server = new Hapi.Server(); +server.connection({ port: 80 }); + +const onRequest: Hapi.ServerExtRequestHandler = function (request, reply) { + + const hash = Crypto.createHash('sha1'); + request.on('peek', (chunk) => { + + hash.update(chunk); + }); + + request.once('finish', () => { + + console.log(hash.digest('hex')); + }); + + request.once('disconnect', () => { + + console.error('request aborted'); + }); + + return reply.continue(); +}; + +server.ext('onRequest', onRequest); diff --git a/types/hapi/test/request/generate-response.ts b/types/hapi/v16/test/request/generate-response.ts similarity index 93% rename from types/hapi/test/request/generate-response.ts rename to types/hapi/v16/test/request/generate-response.ts index c30c3a7be5..f731961a68 100644 --- a/types/hapi/test/request/generate-response.ts +++ b/types/hapi/v16/test/request/generate-response.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#requestgenerateresponsesource-options -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; // Added in addition to code from docs function promiseMethod() { diff --git a/types/hapi/v16/test/request/get-log.ts b/types/hapi/v16/test/request/get-log.ts new file mode 100644 index 0000000000..53568ba734 --- /dev/null +++ b/types/hapi/v16/test/request/get-log.ts @@ -0,0 +1,12 @@ + +// From https://hapijs.com/api/16.1.1#requestgetlogtags-internal + +import * as Hapi from '../../'; + +var request: Hapi.Request = {}; + +request.getLog(); +request.getLog('error'); +request.getLog(['error', 'auth']); +request.getLog(['error'], true); +request.getLog(false); diff --git a/types/hapi/test/request/log.ts b/types/hapi/v16/test/request/log.ts similarity index 93% rename from types/hapi/test/request/log.ts rename to types/hapi/v16/test/request/log.ts index 1c2da1f3b0..f9b044eafc 100644 --- a/types/hapi/test/request/log.ts +++ b/types/hapi/v16/test/request/log.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#requestlogtags-data-timestamp -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80, routes: { log: true, security: false } }); diff --git a/types/hapi/v16/test/request/query.ts b/types/hapi/v16/test/request/query.ts new file mode 100644 index 0000000000..1aa801b69d --- /dev/null +++ b/types/hapi/v16/test/request/query.ts @@ -0,0 +1,14 @@ +// Added test in addition to docs, for request.query + +import * as Hapi from '../../'; + +interface GetThingQuery { + name: string; +} + +const handler: Hapi.RouteHandler = function (request, reply) { + + const query = request.query as GetThingQuery; + + return reply(`You asked for ${query.name}`); +}; diff --git a/types/hapi/test/request/set-method.ts b/types/hapi/v16/test/request/set-method.ts similarity index 91% rename from types/hapi/test/request/set-method.ts rename to types/hapi/v16/test/request/set-method.ts index 7269e6255f..aa78eeaecf 100644 --- a/types/hapi/test/request/set-method.ts +++ b/types/hapi/v16/test/request/set-method.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#requestsetmethodmethod -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/request/set-url.ts b/types/hapi/v16/test/request/set-url.ts similarity index 90% rename from types/hapi/test/request/set-url.ts rename to types/hapi/v16/test/request/set-url.ts index 4add3c5a17..1c3a0a047b 100644 --- a/types/hapi/test/request/set-url.ts +++ b/types/hapi/v16/test/request/set-url.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#requestseturlurl-striptrailingslash -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); @@ -17,7 +17,7 @@ server.ext('onRequest', onRequest); // Example 2 const Url = require('url'); -const Qs = require('qs'); +const Qs = require('../../../../qs'); onRequest = function (request, reply) { diff --git a/types/hapi/test/request/tail.ts b/types/hapi/v16/test/request/tail.ts similarity index 94% rename from types/hapi/test/request/tail.ts rename to types/hapi/v16/test/request/tail.ts index 9c68ccb8f2..426c0cd835 100644 --- a/types/hapi/test/request/tail.ts +++ b/types/hapi/v16/test/request/tail.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#requestsetmethodmethod -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/response/error-representation.ts b/types/hapi/v16/test/response/error-representation.ts similarity index 84% rename from types/hapi/test/response/error-representation.ts rename to types/hapi/v16/test/response/error-representation.ts index f0fb62eb30..7eacfdfaf3 100644 --- a/types/hapi/test/response/error-representation.ts +++ b/types/hapi/v16/test/response/error-representation.ts @@ -1,13 +1,13 @@ // From https://hapijs.com/api/16.1.1#error-transformation -import * as Hapi from 'hapi'; -import Vision from 'vision'; +import * as Hapi from '../../'; +import Vision from '../../../../vision'; const server = new Hapi.Server(); server.register(Vision, {}, (err) => { server.views({ engines: { - html: require('handlebars') + html: require('../../../../handlebars') } }); }); diff --git a/types/hapi/v16/test/response/error.ts b/types/hapi/v16/test/response/error.ts new file mode 100644 index 0000000000..f426de66e0 --- /dev/null +++ b/types/hapi/v16/test/response/error.ts @@ -0,0 +1,25 @@ + +// From https://hapijs.com/api/16.1.1#error-response + +import * as Hapi from '../../'; +const Boom = require('../../../../boom'); + +const server = new Hapi.Server(); + +server.route({ + method: 'GET', + path: '/badRequest', + handler: function (request, reply) { + + return reply(Boom.badRequest('Unsupported parameter')); + } +}); + +server.route({ + method: 'GET', + path: '/internal', + handler: function (request, reply) { + + return reply(new Error('unexpect error')); + } +}); diff --git a/types/hapi/test/response/events.ts b/types/hapi/v16/test/response/events.ts similarity index 95% rename from types/hapi/test/response/events.ts rename to types/hapi/v16/test/response/events.ts index 2d1658087b..07d4e0a65b 100644 --- a/types/hapi/test/response/events.ts +++ b/types/hapi/v16/test/response/events.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#response-events -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const Crypto = require('crypto'); const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/response/flow-control.ts b/types/hapi/v16/test/response/flow-control.ts similarity index 88% rename from types/hapi/test/response/flow-control.ts rename to types/hapi/v16/test/response/flow-control.ts index bc18a36aff..321d198825 100644 --- a/types/hapi/test/response/flow-control.ts +++ b/types/hapi/v16/test/response/flow-control.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#flow-control -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const handler = function (request: Hapi.Request, reply: Hapi.ReplyWithContinue) { diff --git a/types/hapi/test/route/additional-options.ts b/types/hapi/v16/test/route/additional-options.ts similarity index 98% rename from types/hapi/test/route/additional-options.ts rename to types/hapi/v16/test/route/additional-options.ts index 189dc488de..ccbb36af15 100644 --- a/types/hapi/test/route/additional-options.ts +++ b/types/hapi/v16/test/route/additional-options.ts @@ -1,6 +1,6 @@ 'use strict'; -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var authConfig: Hapi.RouteAdditionalConfigurationOptions = { app: {}, diff --git a/types/hapi/test/route/auth.ts b/types/hapi/v16/test/route/auth.ts similarity index 94% rename from types/hapi/test/route/auth.ts rename to types/hapi/v16/test/route/auth.ts index e5239322da..e8d41cf47d 100644 --- a/types/hapi/test/route/auth.ts +++ b/types/hapi/v16/test/route/auth.ts @@ -1,6 +1,6 @@ 'use strict'; -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var routeMoreConfig: Hapi.RouteAdditionalConfigurationOptions = { auth: false, diff --git a/types/hapi/v16/test/route/config.ts b/types/hapi/v16/test/route/config.ts new file mode 100644 index 0000000000..680ee4c043 --- /dev/null +++ b/types/hapi/v16/test/route/config.ts @@ -0,0 +1,46 @@ +'use strict'; + +import * as Hapi from '../../'; + +// different methods +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: 'PUT', + vhost: 'site.coms', +}; +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: '*' +}; +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: ['OPTIONS', '*'] +}; + +// different handlers +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: 'PUT', + handler: 'some registered handler' +}; +var routeConfig: Hapi.RouteConfiguration = { + path: '/signin', + method: 'PUT', + handler: function (request, reply) { + return reply('ok'); + } +}; + +const server = new Hapi.Server(); +server.route(routeConfig); + +// Handler in config +const user: Hapi.RouteAdditionalConfigurationOptions = { + cache: { expiresIn: 5000 }, + handler: function (request, reply) { + + return reply({ name: 'John' }); + } +}; + +server.route({method: 'GET', path: '/user', config: user }); diff --git a/types/hapi/v16/test/route/handler.ts b/types/hapi/v16/test/route/handler.ts new file mode 100644 index 0000000000..401bf35eab --- /dev/null +++ b/types/hapi/v16/test/route/handler.ts @@ -0,0 +1,10 @@ +'use strict'; + +import * as Hapi from '../../'; + +var handler: Hapi.RouteHandler = function(request, reply) { + reply('success'); +} +var strictHandler: Hapi.RouteHandler = function(request, reply) { + reply(123); +} diff --git a/types/hapi/test/route/plugins.ts b/types/hapi/v16/test/route/plugins.ts similarity index 92% rename from types/hapi/test/route/plugins.ts rename to types/hapi/v16/test/route/plugins.ts index 2449fc84c0..ba7abdb777 100644 --- a/types/hapi/test/route/plugins.ts +++ b/types/hapi/v16/test/route/plugins.ts @@ -1,9 +1,9 @@ // Added in addition to code from https://hapijs.com/api/16.1.1#route-options > plugins -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; // In the plugin code -declare module 'hapi' { +declare module '../../' { interface PluginSpecificConfiguration { coolPlugin: { optionA: string; diff --git a/types/hapi/test/route/prerequisites.ts b/types/hapi/v16/test/route/prerequisites.ts similarity index 97% rename from types/hapi/test/route/prerequisites.ts rename to types/hapi/v16/test/route/prerequisites.ts index c4ca7650fa..15a16af2c0 100644 --- a/types/hapi/test/route/prerequisites.ts +++ b/types/hapi/v16/test/route/prerequisites.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#route-prerequisites -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/route/public-interface.ts b/types/hapi/v16/test/route/public-interface.ts similarity index 93% rename from types/hapi/test/route/public-interface.ts rename to types/hapi/v16/test/route/public-interface.ts index e61fb8275f..f3878cea48 100644 --- a/types/hapi/test/route/public-interface.ts +++ b/types/hapi/v16/test/route/public-interface.ts @@ -1,6 +1,6 @@ 'use strict'; -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var route = {}; diff --git a/types/hapi/test/route/validate.ts b/types/hapi/v16/test/route/validate.ts similarity index 96% rename from types/hapi/test/route/validate.ts rename to types/hapi/v16/test/route/validate.ts index cb5c5527ee..06fefcc62e 100644 --- a/types/hapi/test/route/validate.ts +++ b/types/hapi/v16/test/route/validate.ts @@ -1,8 +1,8 @@ // Added from: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16065#issuecomment-302216131 -import * as Hapi from 'hapi'; -import * as Joi from 'joi'; +import * as Hapi from '../../'; +import * as Joi from '../../../../joi'; const validate: Hapi.RouteValidationConfigurationObject = { headers: true, diff --git a/types/hapi/test/server/app.ts b/types/hapi/v16/test/server/app.ts similarity index 87% rename from types/hapi/test/server/app.ts rename to types/hapi/v16/test/server/app.ts index dac8921c20..7ed57fe6e8 100644 --- a/types/hapi/test/server/app.ts +++ b/types/hapi/v16/test/server/app.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverapp -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var server = new Hapi.Server(); server.app.key = 'value'; diff --git a/types/hapi/test/server/auth.ts b/types/hapi/v16/test/server/auth.ts similarity index 96% rename from types/hapi/test/server/auth.ts rename to types/hapi/v16/test/server/auth.ts index 3f28732d42..c699a63c1b 100644 --- a/types/hapi/test/server/auth.ts +++ b/types/hapi/v16/test/server/auth.ts @@ -1,8 +1,8 @@ // From https://hapijs.com/api/16.1.1#serverauthapi -import * as Hapi from 'hapi'; -import * as Boom from 'boom'; +import * as Hapi from '../../'; +import * as Boom from '../../../../boom'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/bind.ts b/types/hapi/v16/test/server/bind.ts similarity index 93% rename from types/hapi/test/server/bind.ts rename to types/hapi/v16/test/server/bind.ts index 2741e16c82..c8e0ba0016 100644 --- a/types/hapi/test/server/bind.ts +++ b/types/hapi/v16/test/server/bind.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverbindcontext -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; interface HandlerThis { message: string; diff --git a/types/hapi/test/server/cache.ts b/types/hapi/v16/test/server/cache.ts similarity index 96% rename from types/hapi/test/server/cache.ts rename to types/hapi/v16/test/server/cache.ts index 4cb9eaa4b7..18d7cbbd3a 100644 --- a/types/hapi/test/server/cache.ts +++ b/types/hapi/v16/test/server/cache.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#servercacheoptions -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/connection-options.ts b/types/hapi/v16/test/server/connection-options.ts similarity index 96% rename from types/hapi/test/server/connection-options.ts rename to types/hapi/v16/test/server/connection-options.ts index 3a526307db..e4b5582598 100644 --- a/types/hapi/test/server/connection-options.ts +++ b/types/hapi/v16/test/server/connection-options.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverconnectionoptions -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); const web = server.connection({ port: 8000, host: 'example.com', labels: ['web'] }); diff --git a/types/hapi/test/server/connections.ts b/types/hapi/v16/test/server/connections.ts similarity index 89% rename from types/hapi/test/server/connections.ts rename to types/hapi/v16/test/server/connections.ts index fb2f9f303e..0674c3b72f 100644 --- a/types/hapi/test/server/connections.ts +++ b/types/hapi/v16/test/server/connections.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverconnections -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var server = new Hapi.Server(); server.connection({ port: 80, labels: 'a' }); server.connection({ port: 8080, labels: 'b' }); diff --git a/types/hapi/test/server/decoder.ts b/types/hapi/v16/test/server/decoder.ts similarity index 90% rename from types/hapi/test/server/decoder.ts rename to types/hapi/v16/test/server/decoder.ts index edd52485ea..7a9eadd1e6 100644 --- a/types/hapi/test/server/decoder.ts +++ b/types/hapi/v16/test/server/decoder.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverdecoderencoding-decoder -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; import * as Zlib from 'zlib'; const server = new Hapi.Server(); server.connection({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); diff --git a/types/hapi/test/server/decorate.ts b/types/hapi/v16/test/server/decorate.ts similarity index 92% rename from types/hapi/test/server/decorate.ts rename to types/hapi/v16/test/server/decorate.ts index 540e29c951..d946f6132e 100644 --- a/types/hapi/test/server/decorate.ts +++ b/types/hapi/v16/test/server/decorate.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverdecoratetype-property-method-options -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); @@ -12,7 +12,7 @@ const success = function (this: Hapi.ReplyNoContinue) { server.decorate('reply', 'success', success); -declare module 'hapi' { +declare module '../../' { interface Base_Reply { success: () => Response; } @@ -36,7 +36,7 @@ server.decorate('request', 'some_request_method', (request) => { } }, {apply: true}); -declare module 'hapi' { +declare module '../../' { interface Request { some_request_method(): void; } @@ -59,7 +59,7 @@ server.decorate('server', 'some_server_method', (server: Hapi.Server) => { } }); -declare module 'hapi' { +declare module '../../' { interface Server { some_server_method(arg1: number): string; } diff --git a/types/hapi/test/server/dependency.ts b/types/hapi/v16/test/server/dependency.ts similarity index 93% rename from types/hapi/test/server/dependency.ts rename to types/hapi/v16/test/server/dependency.ts index 1d63397cf2..175b3242b9 100644 --- a/types/hapi/test/server/dependency.ts +++ b/types/hapi/v16/test/server/dependency.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverdependencydependencies-after -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const after: Hapi.AfterDependencyLoadCallback = function (server, next) { diff --git a/types/hapi/test/server/emit.ts b/types/hapi/v16/test/server/emit.ts similarity index 90% rename from types/hapi/test/server/emit.ts rename to types/hapi/v16/test/server/emit.ts index d248f7d4ab..0f1f37de2d 100644 --- a/types/hapi/test/server/emit.ts +++ b/types/hapi/v16/test/server/emit.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serveremitcriteria-data-callback -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/encoder.ts b/types/hapi/v16/test/server/encoder.ts similarity index 90% rename from types/hapi/test/server/encoder.ts rename to types/hapi/v16/test/server/encoder.ts index f35102b776..cacc5f2c8b 100644 --- a/types/hapi/test/server/encoder.ts +++ b/types/hapi/v16/test/server/encoder.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverencoderencoding-encoder -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; import * as Zlib from 'zlib'; const server = new Hapi.Server(); server.connection({ port: 80, routes: { compression: { special: { chunkSize: 16 * 1024 } } } }); diff --git a/types/hapi/test/server/event.ts b/types/hapi/v16/test/server/event.ts similarity index 90% rename from types/hapi/test/server/event.ts rename to types/hapi/v16/test/server/event.ts index f0c2215f12..cbe7128de3 100644 --- a/types/hapi/test/server/event.ts +++ b/types/hapi/v16/test/server/event.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#servereventevents -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/expose.ts b/types/hapi/v16/test/server/expose.ts similarity index 92% rename from types/hapi/test/server/expose.ts rename to types/hapi/v16/test/server/expose.ts index effbc1ae49..abaade677c 100644 --- a/types/hapi/test/server/expose.ts +++ b/types/hapi/v16/test/server/expose.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverexposekey-value -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var register: Hapi.PluginFunction<{}> = function (server, options, next) { server.expose('util', function () { console.log('something'); }); diff --git a/types/hapi/test/server/ext.ts b/types/hapi/v16/test/server/ext.ts similarity index 96% rename from types/hapi/test/server/ext.ts rename to types/hapi/v16/test/server/ext.ts index 500ac1d4af..318fe3fe0b 100644 --- a/types/hapi/test/server/ext.ts +++ b/types/hapi/v16/test/server/ext.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverextevents -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/handler.ts b/types/hapi/v16/test/server/handler.ts similarity index 94% rename from types/hapi/test/server/handler.ts rename to types/hapi/v16/test/server/handler.ts index 713fe7f114..20fb003ce4 100644 --- a/types/hapi/test/server/handler.ts +++ b/types/hapi/v16/test/server/handler.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverhandlername-method -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ host: 'localhost', port: 8000 }); @@ -20,7 +20,7 @@ interface TestPluginConfig { msg: string; } -declare module 'hapi' { +declare module '../../' { interface RouteHandlerPlugins { test?: TestPluginConfig; } diff --git a/types/hapi/test/server/info.ts b/types/hapi/v16/test/server/info.ts similarity index 92% rename from types/hapi/test/server/info.ts rename to types/hapi/v16/test/server/info.ts index eaf1b39747..aa0bc7014d 100644 --- a/types/hapi/test/server/info.ts +++ b/types/hapi/v16/test/server/info.ts @@ -2,7 +2,7 @@ // From https://hapijs.com/api/16.1.1#serverinfo import assert = require('assert'); -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); var options: Hapi.ServerConnectionOptions = { port: 80 }; server.connection(options); diff --git a/types/hapi/test/server/initialize.ts b/types/hapi/v16/test/server/initialize.ts similarity index 72% rename from types/hapi/test/server/initialize.ts rename to types/hapi/v16/test/server/initialize.ts index 7ef4b51527..f7a1482fac 100644 --- a/types/hapi/test/server/initialize.ts +++ b/types/hapi/v16/test/server/initialize.ts @@ -1,8 +1,8 @@ // From https://hapijs.com/api/16.1.1#serverinitializecallback -import * as Hapi from 'hapi'; -const Hoek = require('hoek'); +import * as Hapi from '../../'; +const Hoek = require('../../../../hoek'); const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/inject.ts b/types/hapi/v16/test/server/inject.ts similarity index 93% rename from types/hapi/test/server/inject.ts rename to types/hapi/v16/test/server/inject.ts index 7010faa3dc..a9fc0bdf5e 100644 --- a/types/hapi/test/server/inject.ts +++ b/types/hapi/v16/test/server/inject.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverinjectoptions-callback -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/listener.ts b/types/hapi/v16/test/server/listener.ts similarity index 95% rename from types/hapi/test/server/listener.ts rename to types/hapi/v16/test/server/listener.ts index d7bb6fc5ea..85ddb18bc6 100644 --- a/types/hapi/test/server/listener.ts +++ b/types/hapi/v16/test/server/listener.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverlistener -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; import SocketIO = require('socket.io'); const server = new Hapi.Server(); diff --git a/types/hapi/test/server/load.ts b/types/hapi/v16/test/server/load.ts similarity index 82% rename from types/hapi/test/server/load.ts rename to types/hapi/v16/test/server/load.ts index ee204c864f..7ecb25fce7 100644 --- a/types/hapi/test/server/load.ts +++ b/types/hapi/v16/test/server/load.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverload -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server({ load: { sampleInterval: 1000 } }); var d: number = server.load.rss; diff --git a/types/hapi/test/server/log.ts b/types/hapi/v16/test/server/log.ts similarity index 89% rename from types/hapi/test/server/log.ts rename to types/hapi/v16/test/server/log.ts index 4507358d60..1a89b2149b 100644 --- a/types/hapi/test/server/log.ts +++ b/types/hapi/v16/test/server/log.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverlogtags-data-timestamp -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/lookup.ts b/types/hapi/v16/test/server/lookup.ts similarity index 91% rename from types/hapi/test/server/lookup.ts rename to types/hapi/v16/test/server/lookup.ts index 89ce852700..2d3729b210 100644 --- a/types/hapi/test/server/lookup.ts +++ b/types/hapi/v16/test/server/lookup.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverlookupid -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection(); server.route({ diff --git a/types/hapi/test/server/match.ts b/types/hapi/v16/test/server/match.ts similarity index 91% rename from types/hapi/test/server/match.ts rename to types/hapi/v16/test/server/match.ts index f322a31494..f446dd0e7e 100644 --- a/types/hapi/test/server/match.ts +++ b/types/hapi/v16/test/server/match.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#servermatchmethod-path-host -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection(); server.route({ diff --git a/types/hapi/test/server/method.ts b/types/hapi/v16/test/server/method.ts similarity index 98% rename from types/hapi/test/server/method.ts rename to types/hapi/v16/test/server/method.ts index e1cc2ce487..9e3efbf7c7 100644 --- a/types/hapi/test/server/method.ts +++ b/types/hapi/v16/test/server/method.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#servermethodname-method-options -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/methods.ts b/types/hapi/v16/test/server/methods.ts similarity index 91% rename from types/hapi/test/server/methods.ts rename to types/hapi/v16/test/server/methods.ts index 1e2060c3e8..0595d522de 100644 --- a/types/hapi/test/server/methods.ts +++ b/types/hapi/v16/test/server/methods.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#servermethods -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); const add = function (a: number, b: number, next: (err: Error | null, result: number) => void) { diff --git a/types/hapi/test/server/mime.ts b/types/hapi/v16/test/server/mime.ts similarity index 94% rename from types/hapi/test/server/mime.ts rename to types/hapi/v16/test/server/mime.ts index e2dd25529b..a97af5de7a 100644 --- a/types/hapi/test/server/mime.ts +++ b/types/hapi/v16/test/server/mime.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#servermime -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const options: Hapi.ServerOptions = { mime: { diff --git a/types/hapi/test/server/new.ts b/types/hapi/v16/test/server/new.ts similarity index 96% rename from types/hapi/test/server/new.ts rename to types/hapi/v16/test/server/new.ts index 95f1ce9006..59f0a8f189 100644 --- a/types/hapi/test/server/new.ts +++ b/types/hapi/v16/test/server/new.ts @@ -1,6 +1,6 @@ 'use strict'; -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; new Hapi.Server(); new Hapi.Server({ @@ -45,7 +45,7 @@ new Hapi.Server({ }); //+ Code added in addition to docs -declare module 'hapi' { +declare module '../../' { interface PluginSpecificConfiguration { // Set this to non optional if plugin config is non optional 'some-plugin-name'?: {options: string;}; diff --git a/types/hapi/test/server/on.ts b/types/hapi/v16/test/server/on.ts similarity index 96% rename from types/hapi/test/server/on.ts rename to types/hapi/v16/test/server/on.ts index 08802fda96..301cc0b423 100644 --- a/types/hapi/test/server/on.ts +++ b/types/hapi/v16/test/server/on.ts @@ -2,7 +2,7 @@ // From https://hapijs.com/api/16.1.1#serveroncriteria-listener // From https://hapijs.com/api/16.1.1#server-events -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/once.ts b/types/hapi/v16/test/server/once.ts similarity index 91% rename from types/hapi/test/server/once.ts rename to types/hapi/v16/test/server/once.ts index 55fdb08ec2..59465a41ec 100644 --- a/types/hapi/test/server/once.ts +++ b/types/hapi/v16/test/server/once.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serveroncecriteria-listener -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/path.ts b/types/hapi/v16/test/server/path.ts similarity index 91% rename from types/hapi/test/server/path.ts rename to types/hapi/v16/test/server/path.ts index 20479a795f..cdbf8a14a9 100644 --- a/types/hapi/test/server/path.ts +++ b/types/hapi/v16/test/server/path.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverpathrelativeto -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var register: Hapi.PluginFunction<{}> = function (server, options, next) { diff --git a/types/hapi/test/server/plugins.ts b/types/hapi/v16/test/server/plugins.ts similarity index 90% rename from types/hapi/test/server/plugins.ts rename to types/hapi/v16/test/server/plugins.ts index 2ce13ffb2f..02488a1d5a 100644 --- a/types/hapi/test/server/plugins.ts +++ b/types/hapi/v16/test/server/plugins.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverplugins -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var registerFunction: Hapi.PluginFunction<{}> = function(server, options, next) { diff --git a/types/hapi/test/server/realm.ts b/types/hapi/v16/test/server/realm.ts similarity index 86% rename from types/hapi/test/server/realm.ts rename to types/hapi/v16/test/server/realm.ts index 31f764b7ef..4a2eceffd0 100644 --- a/types/hapi/test/server/realm.ts +++ b/types/hapi/v16/test/server/realm.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverrealm -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; var registerFunction: Hapi.PluginFunction<{}> = function(server, options, next) { diff --git a/types/hapi/test/server/register.ts b/types/hapi/v16/test/server/register.ts similarity index 90% rename from types/hapi/test/server/register.ts rename to types/hapi/v16/test/server/register.ts index c04e0b16bc..1d0ab5a2e7 100644 --- a/types/hapi/test/server/register.ts +++ b/types/hapi/v16/test/server/register.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverregisterplugins-options-callback -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); diff --git a/types/hapi/test/server/route.ts b/types/hapi/v16/test/server/route.ts similarity index 93% rename from types/hapi/test/server/route.ts rename to types/hapi/v16/test/server/route.ts index 0402fd3e89..0fa9fd8cc8 100644 --- a/types/hapi/test/server/route.ts +++ b/types/hapi/v16/test/server/route.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverrouteoptions -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/select.ts b/types/hapi/v16/test/server/select.ts similarity index 91% rename from types/hapi/test/server/select.ts rename to types/hapi/v16/test/server/select.ts index 8a25f45abd..03af599fcc 100644 --- a/types/hapi/test/server/select.ts +++ b/types/hapi/v16/test/server/select.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverselectlabels -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80, labels: ['a', 'b'] }); server.connection({ port: 8080, labels: ['a', 'c'] }); diff --git a/types/hapi/test/server/settings.ts b/types/hapi/v16/test/server/settings.ts similarity index 84% rename from types/hapi/test/server/settings.ts rename to types/hapi/v16/test/server/settings.ts index c2ec9ce3ed..f250c8e8fd 100644 --- a/types/hapi/test/server/settings.ts +++ b/types/hapi/v16/test/server/settings.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serversettings -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server({ app: { key: 'value' diff --git a/types/hapi/test/server/start.ts b/types/hapi/v16/test/server/start.ts similarity index 76% rename from types/hapi/test/server/start.ts rename to types/hapi/v16/test/server/start.ts index a15bb79740..a9408a57aa 100644 --- a/types/hapi/test/server/start.ts +++ b/types/hapi/v16/test/server/start.ts @@ -1,8 +1,8 @@ // From https://hapijs.com/api/16.1.1#serverstartcallback -import * as Hapi from 'hapi'; -import * as Hoek from 'hoek'; +import * as Hapi from '../../'; +import * as Hoek from '../../../../hoek'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/state.ts b/types/hapi/v16/test/server/state.ts similarity index 95% rename from types/hapi/test/server/state.ts rename to types/hapi/v16/test/server/state.ts index 2035343a17..19c10cfae3 100644 --- a/types/hapi/test/server/state.ts +++ b/types/hapi/v16/test/server/state.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverstatename-options -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/stop.ts b/types/hapi/v16/test/server/stop.ts similarity index 87% rename from types/hapi/test/server/stop.ts rename to types/hapi/v16/test/server/stop.ts index ddfd07aa8f..ca14a70dfa 100644 --- a/types/hapi/test/server/stop.ts +++ b/types/hapi/v16/test/server/stop.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#serverstopoptions-callback -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80 }); diff --git a/types/hapi/test/server/table.ts b/types/hapi/v16/test/server/table.ts similarity index 89% rename from types/hapi/test/server/table.ts rename to types/hapi/v16/test/server/table.ts index abe0707c76..c1410f95db 100644 --- a/types/hapi/test/server/table.ts +++ b/types/hapi/v16/test/server/table.ts @@ -1,7 +1,7 @@ // From https://hapijs.com/api/16.1.1#servertablehost -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.connection({ port: 80, host: 'example.com' }); server.route({ method: 'GET', path: '/example', handler: function (request, reply) { return reply(); } }); diff --git a/types/hapi/test/server/version.ts b/types/hapi/v16/test/server/version.ts similarity index 77% rename from types/hapi/test/server/version.ts rename to types/hapi/v16/test/server/version.ts index 064e87e3cd..2ee1f57841 100644 --- a/types/hapi/test/server/version.ts +++ b/types/hapi/v16/test/server/version.ts @@ -1,6 +1,6 @@ // From http://hapijs.com/api#serversettings -import * as Hapi from 'hapi'; +import * as Hapi from '../../'; const server = new Hapi.Server(); server.version === '8.0.0' diff --git a/types/hapi/v16/tsconfig.json b/types/hapi/v16/tsconfig.json new file mode 100644 index 0000000000..e54c0e1e63 --- /dev/null +++ b/types/hapi/v16/tsconfig.json @@ -0,0 +1,104 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "boom": ["boom/v4"], + "hapi": [ + "hapi/v16" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "test/connection/table.ts", + "test/continuation/errors.ts", + "test/getting-started/01-creating-a-server.ts", + "test/getting-started/02-adding-routes.ts", + "test/getting-started/03-serving-static-content.ts", + "test/getting-started/04-using-plugins.ts", + "test/path/catch-all.ts", + "test/path/parameters.ts", + "test/plugins/options.ts", + "test/reply/continue.ts", + "test/reply/entity.ts", + "test/reply/redirect.ts", + "test/reply/reply.ts", + "test/reply/state_cookie.ts", + "test/request/event-types.ts", + "test/request/generate-response.ts", + "test/request/get-log.ts", + "test/request/log.ts", + "test/request/query.ts", + "test/request/set-method.ts", + "test/request/set-url.ts", + "test/request/tail.ts", + "test/response/error-representation.ts", + "test/response/error.ts", + "test/response/events.ts", + "test/response/flow-control.ts", + "test/route/additional-options.ts", + "test/route/auth.ts", + "test/route/config.ts", + "test/route/handler.ts", + "test/route/plugins.ts", + "test/route/prerequisites.ts", + "test/route/public-interface.ts", + "test/route/validate.ts", + "test/server/app.ts", + "test/server/auth.ts", + "test/server/bind.ts", + "test/server/cache.ts", + "test/server/connection-options.ts", + "test/server/connections.ts", + "test/server/decoder.ts", + "test/server/decorate.ts", + "test/server/dependency.ts", + "test/server/emit.ts", + "test/server/encoder.ts", + "test/server/event.ts", + "test/server/expose.ts", + "test/server/ext.ts", + "test/server/handler.ts", + "test/server/info.ts", + "test/server/initialize.ts", + "test/server/inject.ts", + "test/server/listener.ts", + "test/server/load.ts", + "test/server/log.ts", + "test/server/lookup.ts", + "test/server/match.ts", + "test/server/method.ts", + "test/server/methods.ts", + "test/server/mime.ts", + "test/server/new.ts", + "test/server/on.ts", + "test/server/once.ts", + "test/server/path.ts", + "test/server/plugins.ts", + "test/server/realm.ts", + "test/server/register.ts", + "test/server/route.ts", + "test/server/select.ts", + "test/server/settings.ts", + "test/server/start.ts", + "test/server/state.ts", + "test/server/stop.ts", + "test/server/table.ts", + "test/server/version.ts" + ] +} diff --git a/types/hapi/v16/tslint.json b/types/hapi/v16/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/hapi/v16/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/inert/tsconfig.json b/types/inert/tsconfig.json index feda976404..4aba3d080a 100644 --- a/types/inert/tsconfig.json +++ b/types/inert/tsconfig.json @@ -16,7 +16,8 @@ "paths": { "boom": [ "boom/v4" - ] + ], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +27,4 @@ "index.d.ts", "inert-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/nes/tsconfig.json b/types/nes/tsconfig.json index f9e07170b3..5fe10888ae 100644 --- a/types/nes/tsconfig.json +++ b/types/nes/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -39,4 +38,4 @@ "test/subscriptions-client.ts", "test/subscriptions-server.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-express-mw/tsconfig.json b/types/swagger-express-mw/tsconfig.json index 10ebc4ed97..49e10dbf21 100644 --- a/types/swagger-express-mw/tsconfig.json +++ b/types/swagger-express-mw/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "swagger-express-mw-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-hapi/tsconfig.json b/types/swagger-hapi/tsconfig.json index 5b917e2121..5fd0c591fb 100644 --- a/types/swagger-hapi/tsconfig.json +++ b/types/swagger-hapi/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "swagger-hapi-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-node-runner/tsconfig.json b/types/swagger-node-runner/tsconfig.json index 9aa6ec5364..e349e4cc6a 100644 --- a/types/swagger-node-runner/tsconfig.json +++ b/types/swagger-node-runner/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "swagger-node-runner-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-restify-mw/tsconfig.json b/types/swagger-restify-mw/tsconfig.json index d561204c42..e80378cda0 100644 --- a/types/swagger-restify-mw/tsconfig.json +++ b/types/swagger-restify-mw/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "swagger-restify-mw-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/swagger-sails-hook/tsconfig.json b/types/swagger-sails-hook/tsconfig.json index 17d598916d..4e48ad232d 100644 --- a/types/swagger-sails-hook/tsconfig.json +++ b/types/swagger-sails-hook/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "swagger-sails-hook-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/vision/tsconfig.json b/types/vision/tsconfig.json index 77092f0ff4..2457f046cf 100644 --- a/types/vision/tsconfig.json +++ b/types/vision/tsconfig.json @@ -14,9 +14,8 @@ ], "types": [], "paths": { - "boom": [ - "boom/v4" - ] + "boom": ["boom/v4"], + "hapi": ["hapi/v16"] }, "noEmit": true, "forceConsistentCasingInFileNames": true, @@ -26,4 +25,4 @@ "index.d.ts", "vision-tests.ts" ] -} \ No newline at end of file +}