UNPKG

@types/hapi

Version:
1,042 lines (919 loc) 226 kB
/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + WARNING: BACKWARDS INCOMPATIBLE + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ /// <reference types='node' /> import * as Boom from "boom"; import * as http from "http"; import * as https from "https"; import * as Shot from "shot"; import * as stream from "stream"; import * as url from "url"; import * as zlib from "zlib"; import { SealOptions, SealOptionsSub } from "iron"; import { Schema, SchemaMap, ValidationOptions } from "joi"; import { MimosOptions } from "mimos"; import Podium = require("podium"); import { ClientApi, ClientOptions, EnginePrototype, EnginePrototypeOrObject, Policy, PolicyOptions, PolicyOptionVariants, } from "catbox"; /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Plugin + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ /** * one of * a single plugin name string. * an array of plugin name strings. * an object where each key is a plugin name and each matching value is a * {@link https://www.npmjs.com/package/semver version range string} which must match the registered * plugin version. */ export type Dependencies = string | string[] | { [key: string]: string; }; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) */ /* eslint-disable-next-line @typescript-eslint/no-empty-interface */ 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; } /* eslint-disable-next-line @typescript-eslint/no-empty-interface */ export interface PluginsStates { } /* eslint-disable-next-line @typescript-eslint/no-empty-interface */ 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 | undefined; } 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<T> { /** * (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) => void | Promise<void>; /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */ multiple?: boolean | undefined; /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */ dependencies?: Dependencies | undefined; /** * Allows defining semver requirements for node and hapi. * @default Allows all. */ requirements?: { node?: string | undefined; hapi?: string | undefined; } | undefined; /** 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 | undefined; } export type Plugin<T> = PluginBase<T> & (PluginNameVersion | PluginPackage); /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Request + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ /** * User extensible types user credentials. */ // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface UserCredentials { } /** * User extensible types app credentials. */ // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface AppCredentials { } /** * User-extensible type for request.auth credentials. */ export interface AuthCredentials { /** * The application scopes to be granted. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) */ scope?: string[] | undefined; /** * If set, will only work with routes that set `access.entity` to `user`. */ user?: UserCredentials | undefined; /** * If set, will only work with routes that set `access.entity` to `app`. */ app?: AppCredentials | undefined; } /** * 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; } /** * '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: (data: undefined) => void): 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: (data: undefined) => void): void; } /** * 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 | undefined; }; /** 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; /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}') */ id: 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; /** request processing completion timestamp (0 is still processing). */ completed: number; } /** * 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[] | undefined; /** 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; }; } /** * 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; } export interface RequestQuery { [key: string]: string | 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<string>; /** * 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<string>; /** * 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<any>; /** * 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. * In case of an aborted request the status code will be set to `disconnectStatusCode`. */ response: ResponseObject | Boom; /** * Same as pre but represented as the response object created by the pre method. */ readonly preResponses: Util.Dictionary<any>; /** * By default the object outputted from node's URL parse() method. */ readonly query: RequestQuery; /** * 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<any>; /** * The parsed request URI. */ readonly url: url.URL; /** * Returns `true` when the request is active and processing should continue and `false` when the * request terminated early or completed its lifecycle. Useful when request processing is a * resource-intensive operation and should be terminated early if the request is no longer active * (e.g. client disconnected or aborted early). */ active(): boolean; /** * 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 | undefined; prepare?: ((response: ResponseObject) => Promise<ResponseObject>) | undefined; marshal?: ((response: ResponseObject) => Promise<ResponseValue>) | undefined; close?: ((response: ResponseObject) => void) | undefined; }, ): 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; } /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Response + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ /** * 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: (data: undefined) => void): 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: (data: undefined) => void): void; } /** * 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 | undefined; separator?: string | undefined; override?: boolean | undefined; duplicate?: boolean | undefined; } /** * 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<string | string[]>; /** * 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 HTTP status code where: * @param statusCode - the HTTP status code (e.g. 200). * @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; } /** * 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; } /** * See more about Lifecycle * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle */ export type ResponseValue = string | object; export interface AuthenticationData { credentials: AuthCredentials; artifacts?: object | undefined; } export interface Auth { readonly isAuth: true; readonly error?: Error | null | undefined; readonly data?: AuthenticationData | undefined; } /** * 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<Request>; /** * 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): Auth; /** * 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 hea