From ce92862988a2b6573b8d64d03de0a436e133a90f Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Wed, 22 Nov 2017 19:46:18 -0300 Subject: [PATCH] HapiJs v17 Typescript Definitions. Recovering the repo. --- types/hapi/v17/definitions/plugin/plugin.d.ts | 50 +++ .../hapi/v17/definitions/request/request.d.ts | 311 ++++++++++++++++++ .../definitions/response/response-object.d.ts | 305 +++++++++++++++++ .../response/response-settings.d.ts | 29 ++ .../route/route-options-access.d.ts | 75 +++++ .../route/route-options-cache.d.ts | 29 ++ .../definitions/route/route-options-cors.d.ts | 20 ++ .../route/route-options-payload.d.ts | 111 +++++++ .../route/route-options-response.d.ts | 67 ++++ .../route/route-options-secure.d.ts | 42 +++ .../route/route-options-validate.d.ts | 86 +++++ .../v17/definitions/route/route-options.d.ts | 224 +++++++++++++ .../server/server-connection-options.d.ts | 54 +++ .../server/server-options-cache.d.ts | 25 ++ .../definitions/server/server-options.d.ts | 184 +++++++++++ .../v17/definitions/server/server-realm.d.ts | 34 ++ .../server/server-state-options.d.ts | 61 ++++ types/hapi/v17/definitions/server/server.d.ts | 45 +++ .../v17/definitions/util/fail-action.d.ts | 4 + types/hapi/v17/definitions/util/util.d.ts | 10 + types/hapi/v17/hapi-tests.ts | 2 + types/hapi/v17/index.d.ts | 49 +++ types/hapi/v17/tsconfig.json | 28 ++ types/hapi/v17/tslint.json | 79 +++++ 24 files changed, 1924 insertions(+) create mode 100644 types/hapi/v17/definitions/plugin/plugin.d.ts create mode 100644 types/hapi/v17/definitions/request/request.d.ts create mode 100644 types/hapi/v17/definitions/response/response-object.d.ts create mode 100644 types/hapi/v17/definitions/response/response-settings.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options-access.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options-cache.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options-cors.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options-payload.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options-response.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options-secure.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options-validate.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options.d.ts create mode 100644 types/hapi/v17/definitions/server/server-connection-options.d.ts create mode 100644 types/hapi/v17/definitions/server/server-options-cache.d.ts create mode 100644 types/hapi/v17/definitions/server/server-options.d.ts create mode 100644 types/hapi/v17/definitions/server/server-realm.d.ts create mode 100644 types/hapi/v17/definitions/server/server-state-options.d.ts create mode 100644 types/hapi/v17/definitions/server/server.d.ts create mode 100644 types/hapi/v17/definitions/util/fail-action.d.ts create mode 100644 types/hapi/v17/definitions/util/util.d.ts create mode 100644 types/hapi/v17/hapi-tests.ts create mode 100644 types/hapi/v17/index.d.ts create mode 100644 types/hapi/v17/tsconfig.json create mode 100644 types/hapi/v17/tslint.json diff --git a/types/hapi/v17/definitions/plugin/plugin.d.ts b/types/hapi/v17/definitions/plugin/plugin.d.ts new file mode 100644 index 0000000000..f781de97bf --- /dev/null +++ b/types/hapi/v17/definitions/plugin/plugin.d.ts @@ -0,0 +1,50 @@ +import {Server} from "../server/server"; + +export interface PluginsStates { + [pluginName: string]: any; +} + +// Similar to v16, using that interface without any definition. +export interface PluginSpecificConfiguration { + +} + +/** + * 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. + */ +export interface Plugin { + + /** + * (required) the registration function with the signature async function(server, options) where: + */ + register: { + /** the server object with a plugin-specific server.realm. */ + server: Server; + /** any options passed to the plugin during registration via server.register(). */ + options: any; // TODO check what kind of object is expected here. + } + + /** + * (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; + + /** (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; + +} + diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts new file mode 100644 index 0000000000..2da1eb27be --- /dev/null +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -0,0 +1,311 @@ +import * as stream from "stream"; +import * as url from "url"; +import * as http from "http"; +import {RouteOptions} from "../route/route-options"; +import {Server} from "../server/server"; +import {ServerRealm} from "../server/server-realm"; +import {ResponseObject} from "../response/response-object"; +import {HttpMethod, Dictionary} from "../util/util"; +import {PluginsStates} from "../plugin/plugin"; + +/** + * TODO both objects ReplyValue and _ReplyValue I found in the v16 TS definition, but I don't found it in the documentation. Need review. + * TODO I think it's not very elegant solution + */ +export type ReplyValue = _ReplyValue | Promise<_ReplyValue>; +export type _ReplyValue = null | undefined | string | number | boolean | Buffer | Error | stream.Stream | Object; // | array; + +export interface RequestAuth { + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: any; + /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ + credentials: any; + /** 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; +} + +export interface RequestInfo { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + /** + * 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. + * 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; +} + +export interface RequestOrig { + params: any; + query: any; + payload: any; +} + +export interface RequestRoute { + /** the route HTTP method. */ + method: HttpMethod; + /** 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; +} + +export interface Request { + + /** + Access: read / write. + 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; + + /** + Access: read only. + 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. + */ + 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. + */ + events: 'peek' | 'finish' | 'disconnect'; + + /** + Access: read only. + The raw request headers (references request.raw.req.headers). + */ + headers: Dictionary; + + /** + Access: read only. + 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. + */ + info: RequestInfo; + + /** + Access: read only. + An array containing the logged request events. + Note that this array will be empty if route log.collect is set to false. + */ + logs: any[]; // TODO check if type any is apropiate here. + + /** + Access: read only. + The request method in lower case (e.g. 'get', 'post'). + */ + method: HttpMethod; + + /** + Access: read only. + The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. + */ + mime: string; + + /** + Access: read only. + An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + */ + orig: RequestOrig; + + /** + Access: read only. + An object where each key is a path parameter name with matching value as described in Path parameters. + */ + params: Dictionary; + + /** + Access: read only. + An array containing all the path params values in the order they appeared in the path. + */ + paramsArray: string[]; + + /** + Access: read only. + The request URI's pathname component. + */ + path: string; + + /** + Access: read only. + 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; + + /** + Access: read / write. + 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; + + /** + Access: read only. + 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. + */ + pre: Object; + + /** + 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; + + /** + Access: read only. + Same as pre but represented as the response object created by the pre method. + */ + preResponses: Object; + + /** + Access: read only. + 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). + */ + query: any; + + /** + Access: read only. + 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. + */ + raw: { + req: http.IncomingMessage; + res: http.ServerResponse; + }; + + /** + Access: read only. + 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. + */ + route: RequestRoute; + + /** + Access: read only and the public server interface. + The server object. + */ + server: Server; // TODO check if this server object should be right. + + /** + Access: read only. + 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; + + /** + Access: read only. + The parsed request URI. + */ + url: url.Url; + + /** + * request.generateResponse(source, [options]) + * Returns a response which you can pass into the reply interface where: + * [See docs] (https://hapijs.com/api/17.0.1#request.generateResponse()) + * @param source - the value to set as the source of the reply interface, optional. + * @param options - options for the method, optional. + */ + generateResponse(source?: ReplyValue, options?: {marshal?: any; prepare?: any; close?: any; variety?: any}): ResponseObject; + + /** + * request.log(tags, [data]) + * 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. + */ + log(tags: string | string[], data?: string | Object | (() => string | Object)): void; + + /** + * request.route.auth.access(request) + * [See docs] (https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) + * Validates a request against the route's authentication access configuration, where: + * @param request - the request object. + * 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. + */ + // TODO how to implement it? It is a function inside route.auth! The v16 doesn't have this option. + + /** + * request.setMethod(method) + * Changes the request method before the router begins processing the request where: + * Can only be called from an 'onRequest' extension method. + * [See docs] (https://hapijs.com/api/17.0.1#-requestsetmethodmethod) + * @param method - is the request HTTP method (e.g. 'GET'). + */ + setMethod(method: HttpMethod): void; + + /** + * request.setUrl(url, [stripTrailingSlash] + * [See docs] (https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) + * 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. + */ + setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; + +} diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts new file mode 100644 index 0000000000..f30c98eb6e --- /dev/null +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -0,0 +1,305 @@ +import {PluginsStates} from "../plugin/plugin"; +import {Dictionary} from "../util/util"; +import {ResponseSettings} from "./response-settings"; +import {ServerStateCookieOptions} from "../server/server-state-options"; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + */ +export interface ResponseObjectHeaderOptions { + /** 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; +} + +/** + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#response-object) + * 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. + */ +export interface ResponseObject { + + /** + 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]. + */ + app: any; + + /** + * [See docs] (https://hapijs.com/api/17.0.1#-responseevents) + * 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 (). + */ + events: any; // TODO need to be implemented. I didn't understand yet. + + /** + Access: read only. + 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. + */ + headers: Dictionary; + + /** + Access: read / write. + 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. + */ + plugins: PluginsStates; + + /** + Access: read only. + Object containing the response handling flags. + */ + settings: ResponseSettings; + + /** + Access: read only. + The raw value returned by the lifecycle method. + */ + source: any; // TODO need to be implemented. + + /** + Access: read only. + Default value: 200. + */ + statusCode: number; + + /** + Access: read only. + 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. + */ + variety: 'plain' | 'buffer' | 'stream'; + + /** + * response.bytes(length) + * [See docs] (https://hapijs.com/api/17.0.1#-responsebyteslength) + * 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. + */ + bytes(length: number): ResponseObject; + + /** + * response.charset(charset) + * [See docs] (https://hapijs.com/api/17.0.1#-responsecharsetcharset) + * Sets the 'Content-Type' HTTP header 'charset' property where: + * @param charset - the charset property value. + * @return Return value: the current response object. + */ + charset(charset: string): ResponseObject; + + /** + * response.code(statusCode) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode) + * Sets the 'Content-Type' HTTP header 'charset' property where: + * $param charset - the charset property value. + * @return Return value: the current response object. + */ + code(statusCode: number): ResponseObject; + + /** + * response.message(httpMessage) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage) + * 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. + */ + message(httpMessage: string): ResponseObject; + + /** + * response.created(uri) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri) + * 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. + */ + created(uri: string): ResponseObject; + + /** + * encoding(encoding) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding) + * 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. + */ + encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject; + + /** + * response.etag(tag, options) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) + * 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. + */ + etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject; + + /** + * response.header(name, value, options) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) + * 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. + */ + header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; + + /** + * response.location(uri) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri) + * 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. + */ + location(uri: string): ResponseObject; + + /** + * response.redirect(uri) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi) + * 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). + */ + redirect(uri: string): ResponseObject; + + /** + * response.replacer(method) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod) + * Sets the JSON.stringify() replacer argument where: + * @param method - the replacer function or array. Defaults to none. + * @return Return value: the current response object. + */ + replacer(method: any): ResponseObject; // TODO check the method object type. In v16 is a Json.StringifyReplacer + + /** + * response.spaces(count) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount) + * 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. + */ + spaces(count: number): ResponseObject; + + /** + * response.state(name, value, [options]) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) + * 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. + */ + state(name: string, value: string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * response.suffix(suffix) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix) + * 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. + */ + suffix(suffix: string): ResponseObject; + + /** + * response.ttl(msec) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec) + * 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. + */ + ttl(msec: number): ResponseObject; + + /** + * response.type(mimeType) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) + * Sets the HTTP 'Content-Type' header where: + * @param value - 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. + */ + type(mimeType: string): ResponseObject; + + /** + * unstate(name, [options]) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) + * 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. + */ + unstate(name: string, options?: ServerStateCookieOptions): ResponseObject; + + /** + * response.vary(header) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader) + * 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. + */ + vary(header: string): ResponseObject; + + /** + * response.takeover() + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover) + * Marks the response object as a takeover response. + * @return Return value: the current response object. + */ + takeover(): ResponseObject; + + /** + * response.temporary(isTemporary) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary) + * 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. + */ + temporary(isTemporary: boolean): ResponseObject; + + /** + * response.permanent(isPermanent) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent) + * 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. + */ + permanent(isPermanent: boolean): ResponseObject; + + /** + * response.rewritable(isRewritable) + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable) + * 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. + */ + rewritable(isRewritable: boolean): ResponseObject; + +} diff --git a/types/hapi/v17/definitions/response/response-settings.d.ts b/types/hapi/v17/definitions/response/response-settings.d.ts new file mode 100644 index 0000000000..f695bb7a07 --- /dev/null +++ b/types/hapi/v17/definitions/response/response-settings.d.ts @@ -0,0 +1,29 @@ +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. + */ + passThrough: boolean; + + /** + Access: read only. + Default value: null (use route defaults). + Override the route json options used when source value requires stringification. + */ + stringify: any; // TODO need to be implemented. + + /** + Access: read only. + Default value: null (use route defaults). + If set, overrides the route cache with an expiration value in milliseconds. + */ + 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/v17/definitions/route/route-options-access.d.ts b/types/hapi/v17/definitions/route/route-options-access.d.ts new file mode 100644 index 0000000000..99d8b0b3cf --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-access.d.ts @@ -0,0 +1,75 @@ +export enum AccessEntityEnum { + Any = 'any', + User = 'user', + App = 'app', +} + +export enum AccessModeEnum { + Required = 'required', + Optional = 'optional', + Try = 'try', +} + +export enum AccessPayloadEnum { + Required = 'required', + Optional = 'optional', +} + +/** 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. + */ + access?: any | any[]; + + /** + 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}'. + */ + scope?: false | string | string[]; + + /** + 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. + */ + entity?: AccessEntityEnum; + + /** + 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. + */ + mode?: AccessModeEnum; + + /** + 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). + */ + payload?: false | AccessPayloadEnum; + + /** + 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. + */ + strategies?: string[]; + + /** + Default value: the default strategy set via server.auth.default(). + A string strategy names. Cannot be used together with strategies. + */ + strategy?: string; + +} diff --git a/types/hapi/v17/definitions/route/route-options-cache.d.ts b/types/hapi/v17/definitions/route/route-options-cache.d.ts new file mode 100644 index 0000000000..d3f10044e3 --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-cache.d.ts @@ -0,0 +1,29 @@ +/** + 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. + */ +export type RouteOptionsCache = { + privacy?: 'default' | 'public' | 'private'; + statuses?: number[]; + otherwise?: string; +} & ( + { + expiresIn?: number; + expiresAt?: undefined; + } | { + expiresIn?: undefined; + expiresAt?: string; + } | { + expiresIn?: undefined; + expiresAt?: undefined; + } +); diff --git a/types/hapi/v17/definitions/route/route-options-cors.d.ts b/types/hapi/v17/definitions/route/route-options-cors.d.ts new file mode 100644 index 0000000000..c85191db8e --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-cors.d.ts @@ -0,0 +1,20 @@ +/** + 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. + */ +export interface RouteOptionsCors { + origin?: string[] | '*'| 'ignore'; + maxAge?: number; + headers?: string[]; + additionalHeaders?: string[]; + exposedHeaders?: string[]; + additionalExposedHeaders?: string[]; + credentials?: boolean; +} diff --git a/types/hapi/v17/definitions/route/route-options-payload.d.ts b/types/hapi/v17/definitions/route/route-options-payload.d.ts new file mode 100644 index 0000000000..15d1611dc9 --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-payload.d.ts @@ -0,0 +1,111 @@ +import {Dictionary} from "../util/util"; +import {FailAction} from "../util/fail-action"; + +export enum PayloadOutputEnum { + Data = 'data', + Stream = 'stream', + File = 'file' +} + +export enum PayloadMultipartOutputEnum { + // TODO not ready. The v16 definition have similar doubts: "// TODO type this?" + // https://github.com/hapijs/hapi/blob/master/API.md#route.options.payload.multipart + Data = 'data', + Stream = 'stream', + File = 'file', + Annotated = 'annotated', +} + +/**Determines how the request payload is processed.*/ +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. + */ + 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. + */ + compression?: Dictionary; + + /** + Default value: 'application/json'. + The default content type if the 'Content-Type' request header is missing. + */ + defaultContentType?: string; + + /** + Default value: 'error' (return a Bad Request (400) error response). + A failAction value which determines how to handle payload parsing errors. + */ + failAction?: 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. + */ + 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: + headers - the part headers. + filename - the part file name. + payload - the processed part payload. + */ + multipart?: false | PayloadOutputEnum | PayloadMultipartOutputEnum ; + + /** + 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. + */ + output?: PayloadOutputEnum; + + /** + Default value: none. + A mime type string overriding the 'Content-Type' header value received. + */ + 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. + */ + 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. + */ + timeout?: false | number; + + /** + Default value: os.tmpdir(). + The directory used for writing file uploads. + */ + uploads?: string; + +} + + + diff --git a/types/hapi/v17/definitions/route/route-options-response.d.ts b/types/hapi/v17/definitions/route/route-options-response.d.ts new file mode 100644 index 0000000000..34293c9117 --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-response.d.ts @@ -0,0 +1,67 @@ +import {FailAction} from "../util/fail-action"; + +export enum EmptyStatusCode { + HTTP_200 = 200, + HTTP_204 = 204, +} + +/**Processing rules for the outgoing response.*/ +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). + */ + emptyStatusCode?: EmptyStatusCode; + + /** + 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. + */ + failAction?: FailAction; + + /** + Default value: false. + If true, applies the validation rule changes to the response payload. + */ + modify?: boolean; + + /** + Default value: none. + 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. + */ + options?: any; // TODO need to implementation. Here is JOI def. + + /** + Default value: true. + If false, payload range support is disabled. + */ + ranges?: boolean; + + /** + Default value: 100 (all responses). + The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. + */ + 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. + */ + schema?: boolean | any; // TODO need to implementation. Here is JOI and more. + + /** + 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. + */ + status?: any; // TODO need to implementation. + +} diff --git a/types/hapi/v17/definitions/route/route-options-secure.d.ts b/types/hapi/v17/definitions/route/route-options-secure.d.ts new file mode 100644 index 0000000000..6c2380fcc0 --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-secure.d.ts @@ -0,0 +1,42 @@ +/** + 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'. + */ +export interface RouteOptionsSecureObject { + hsts?: boolean | number | { + maxAge?: number; + includeSubdomains?: boolean; + preload?: boolean; + }; + xframe?: true | 'deny' | 'sameorigin' | { + rule: 'deny' | 'sameorigin' | 'allow-from'; + source: string; + }; + xss: boolean; + noOpen?: boolean; + noSniff?: boolean; +} + + +export type RouteOptionsSecure = boolean | RouteOptionsSecureObject; diff --git a/types/hapi/v17/definitions/route/route-options-validate.d.ts b/types/hapi/v17/definitions/route/route-options-validate.d.ts new file mode 100644 index 0000000000..7b3c6afda4 --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-validate.d.ts @@ -0,0 +1,86 @@ +import {FailAction} from "../util/fail-action"; + +/** + Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + Request input validation rules for various request components. + */ +export interface RouteOptionsValidate { + + /** + Default value: none. + An optional object with error fields copied into every validation error response. + */ + errorFields?: any; + + /** + 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. + */ + failAction?: 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. + */ + headers?: boolean | any; // TODO need to implementation. Here is JOI and more. + + /** + 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). + */ + options?: any; // TODO need to be implementation + + /** + 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. + */ + params?: boolean | any; // TODO need to implementation. Here is JOI and more. + + /** + 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. + */ + payload?: boolean | any; // TODO need to implementation. Here is JOI and more. + + /** + 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. + */ + query?: boolean | any; // TODO need to implementation. Here is JOI and more. + +} diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts new file mode 100644 index 0000000000..d393e25810 --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -0,0 +1,224 @@ +import {RouteOptionsAccess} from "./route-options-access"; +import {RouteOptionsCache} from "./route-options-cache"; +import {Dictionary} from "../util/util"; +import {RouteOptionsCors} from "./route-options-cors"; +import {RouteOptionsResponse} from "./route-options-response"; +import {RouteOptionsPayload} from "./route-options-payload"; +import {RouteOptionsSecure} from "./route-options-secure"; +import {FailAction} from "../util/fail-action"; +import {RouteOptionsValidate} from "./route-options-validate"; +import {PluginSpecificConfiguration} from "../plugin/plugin"; + +/** Each route can be customized to change the default behavior of the request lifecycle. */ +export interface RouteOptions { + + /** Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead.*/ + 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. + */ + 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. + */ + bind?: any; + + /** + Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. + */ + 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. + */ + compression?: Dictionary; + + /** + Default value: false (no CORS headers). + */ + 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. + */ + 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. + */ + ext?: any; //TODO need to review and rewrite this definition + + /** + Default value: { relativeTo: '.' }. + Defines the behavior for accessing files: + relativeTo - determines the folder relative paths are resolved against. + */ + files?: { + relativeTo: string; + } + + /** + Default value: none. + The route handler function performs the main business logic of the route and sets the respons. 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. + const handler = function (request, h) { + return 'success'; + }; + Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. + */ + handler?: any; //TODO need to review and rewrite this definition + + /** + 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. + */ + 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. + */ + 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. + + TODO this definition in v16 is a bit confuse for me. Need review and maybe rewrite. + */ + json?: { + replaces?: any | any[]; + space?: number | string; + suffix?: string; + escape?: boolean; // TODO boolean only? + }; + + /** + 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(). + */ + 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. + */ + log?: 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. + */ + notes?: string | string[]; + + /** Determines how the request payload is processed. */ + 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. + */ + plugins?: PluginSpecificConfiguration; + + /** + 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. + */ + pre?: any; // TODO is necessary come back here. In v16 we can see the definition but in this moment we don't have all the definitions for make this one. + + /** + * Processing rules for the outgoing response. + */ + 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'. + */ + 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). + */ + state?: { + parse?: boolean; + failAction?: 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. + */ + tags?: string[]; + + /** + Default value: { server: false }. + 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; + }; + + /** + Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + Request input validation rules for various request components. + */ + validate?: RouteOptionsValidate; + + +} diff --git a/types/hapi/v17/definitions/server/server-connection-options.d.ts b/types/hapi/v17/definitions/server/server-connection-options.d.ts new file mode 100644 index 0000000000..383d601dc0 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-connection-options.d.ts @@ -0,0 +1,54 @@ +import {RouteOptions} from "../route/route-options"; + +/** Any connections configuration server defaults can be included to override and customize the individual connection. */ +export interface IServerConnectionOptions extends IConnectionConfigurationServerDefaults { + /** - 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; + /** - 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; + /** - 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; + /** - 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; + /** - 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?: any; + /** - indicates that the connection.listener will be started manually outside the framework.Cannot be specified with a port setting.Defaults to true.*/ + autoListen?: boolean; + /** caching headers configuration: */ + cache?: { + /** - 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 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[]; + /** - 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.Set to true when passing a listener object that has been configured to use TLS directly. */ + tls?: boolean | { key?: string; cert?: string; pfx?: string; } | Object; +} + +export interface IConnectionConfigurationServerDefaults { + /** 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?: any; + /** 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?: RouteOptions; + // state?: IServerState; TODO +} diff --git a/types/hapi/v17/definitions/server/server-options-cache.d.ts b/types/hapi/v17/definitions/server/server-options-cache.d.ts new file mode 100644 index 0000000000..cd71537d85 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-options-cache.d.ts @@ -0,0 +1,25 @@ +import * as Catbox from "catbox"; + +/** + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-cache) + * 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. + */ +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/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts new file mode 100644 index 0000000000..38af02ac44 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -0,0 +1,184 @@ +import {ServerOptionsCache} from "./server-options-cache"; +import * as http from "http"; +import * as https from "https"; +import * as Catbox from "catbox"; +import {MimosOptions} from "mimos"; +import {PluginSpecificConfiguration, RouteOptions} from "hapi"; + + +/** + * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-server-options) + * he 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. + */ +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. + */ + 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. + */ + 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. + */ + 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). + */ + 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; + + /** + Default value: '1024'. + Sets the minimum response payload size in bytes that is required for content encoding compression. If the payload size is under the limit, no compression is performed. + */ + minBytes?: number; + + /** + 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. + */ + 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?: { + 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/v17/definitions/server/server-realm.d.ts b/types/hapi/v17/definitions/server/server-realm.d.ts new file mode 100644 index 0000000000..56b05df36e --- /dev/null +++ b/types/hapi/v17/definitions/server/server-realm.d.ts @@ -0,0 +1,34 @@ +import {PluginsStates} from "../plugin/plugin"; + +/** + Access: read only. + 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). + */ +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: any | null; + /** 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 */ + settings: { + files: { + relativeTo: string; + }; + bind: any; + }; +} diff --git a/types/hapi/v17/definitions/server/server-state-options.d.ts b/types/hapi/v17/definitions/server/server-state-options.d.ts new file mode 100644 index 0000000000..289507b849 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-state-options.d.ts @@ -0,0 +1,61 @@ +import {Request} from "../request/request"; + +/** + * 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?: 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; +} diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts new file mode 100644 index 0000000000..2455151678 --- /dev/null +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -0,0 +1,45 @@ +import Events = require('events'); +import {ServerOptions} from "./server-options"; +import {Dictionary} from "../util/util"; + +/** + * 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). + */ +export class Server extends Events.EventEmitter { + + /** + Creates a new server object where: + @param options - (optional) a server configuration 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. + */ + app?: any; + + /** + * Access: authentication strategy specific. + * 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. + */ + // TODO is that definition right? It's need review. The v16 is very different. + auth?: { + api: Dictionary; + } + + /** + * Access: read only. + * Contains the default authentication configuration is a default strategy was set via server.auth.default(). + */ + // TODO it needs to be implemented. I didn't understand the description yet. + + // TODO It"s not finished + + + +} diff --git a/types/hapi/v17/definitions/util/fail-action.d.ts b/types/hapi/v17/definitions/util/fail-action.d.ts new file mode 100644 index 0000000000..7b2eb4c4b8 --- /dev/null +++ b/types/hapi/v17/definitions/util/fail-action.d.ts @@ -0,0 +1,4 @@ +// TODO It should be replaced by FailAction definition (with lifecycle method) in the future. +// https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-failAction +export type FailAction = 'error' | 'log' | 'ignore' | any; + diff --git a/types/hapi/v17/definitions/util/util.d.ts b/types/hapi/v17/definitions/util/util.d.ts new file mode 100644 index 0000000000..bfe54031e8 --- /dev/null +++ b/types/hapi/v17/definitions/util/util.d.ts @@ -0,0 +1,10 @@ +export interface Dictionary { + [key: string]: T; +} + +export enum HttpMethod { + Get = "get", + Post = "post", + Put = "put", + Delete= "delete", +} diff --git a/types/hapi/v17/hapi-tests.ts b/types/hapi/v17/hapi-tests.ts new file mode 100644 index 0000000000..e0c05909c0 --- /dev/null +++ b/types/hapi/v17/hapi-tests.ts @@ -0,0 +1,2 @@ +import { Server } from "hapi"; +const server = new Server({ port: 3000, host: 'localhost' }); diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts new file mode 100644 index 0000000000..1e3403e4e1 --- /dev/null +++ b/types/hapi/v17/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for hapi 17.0 +// Project: https://github.com/hapijs/hapi +// Definitions by: Marc Bornträger +// Rafael Souza Fijalkowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Note/Disclaimer: None. + +/// + +/** PLUGIN */ +export * from './definitions/plugin/plugin' + +/** REQUEST */ +export * from './definitions/request/request' + +/** RESPONSE */ +export * from './definitions/response/response-object' +export * from './definitions/response/response-settings' + +/** SERVER */ +export * from './definitions/server/server' +export * from './definitions/server/server-connection-options' +export * from './definitions/server/server-options' +export * from './definitions/server/server-options-cache' +export * from './definitions/server/server-realm' +export * from './definitions/server/server-state-options' + +/** 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-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-connection-options' +export * from './definitions/server/server-options' +export * from './definitions/server/server-options-cache' +export * from './definitions/server/server-realm' +export * from './definitions/server/server-state-options' + +/** UTIL */ +export * from './definitions/util/fail-action' +export * from './definitions/util/util' diff --git a/types/hapi/v17/tsconfig.json b/types/hapi/v17/tsconfig.json new file mode 100644 index 0000000000..216332b184 --- /dev/null +++ b/types/hapi/v17/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "hapi": [ + "hapi/v17" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hapi-tests.ts" + ] +} diff --git a/types/hapi/v17/tslint.json b/types/hapi/v17/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/hapi/v17/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 + } +}