From ce92862988a2b6573b8d64d03de0a436e133a90f Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Wed, 22 Nov 2017 19:46:18 -0300 Subject: [PATCH 01/79] 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 + } +} From 803f500d22b30b6ecfbd210768693ae4b5776a92 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 23 Nov 2017 01:01:00 -0300 Subject: [PATCH 02/79] More Server Definitions. --- .../v17/definitions/server/server-events.d.ts | 12 +++ .../v17/definitions/server/server-info.d.ts | 55 ++++++++++++++ types/hapi/v17/definitions/server/server.d.ts | 74 ++++++++++++++++++- 3 files changed, 137 insertions(+), 4 deletions(-) create mode 100644 types/hapi/v17/definitions/server/server-events.d.ts create mode 100644 types/hapi/v17/definitions/server/server-info.d.ts diff --git a/types/hapi/v17/definitions/server/server-events.d.ts b/types/hapi/v17/definitions/server/server-events.d.ts new file mode 100644 index 0000000000..4aca038e7f --- /dev/null +++ b/types/hapi/v17/definitions/server/server-events.d.ts @@ -0,0 +1,12 @@ +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + */ +// TODO it needs to be implemented +export interface ServerEvents { + + + + +} diff --git a/types/hapi/v17/definitions/server/server-info.d.ts b/types/hapi/v17/definitions/server/server-info.d.ts new file mode 100644 index 0000000000..399543e08e --- /dev/null +++ b/types/hapi/v17/definitions/server/server-info.d.ts @@ -0,0 +1,55 @@ +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + * An object containing information about the server where: + */ +export interface ServerInfo { + + /** + * a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + */ + id: string; + + /** + * server creation timestamp. + */ + created: number; + + /** + * server start timestamp (0 when stopped). + */ + started: number; + + /** + * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules: + * * before the server has been started: the configured port value. + * * after the server has been started: the actual port assigned when no port is configured or was set to 0. + */ + port: number | string; + + /** + * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value. + */ + host: string; + + /** + * the active IP address the connection was bound to after starting. Set to undefined until the server has been + * started or when using a non TCP port (e.g. UNIX domain socket). + */ + address: undefined | string; + + /** + * the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + */ + protocol: 'http' | 'https' | 'socket'; + + /** + * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains + * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set + * to 0, the uri will not include a port component until the server is started. + */ + uri: string; + +} diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 2455151678..c47fef7855 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -1,12 +1,16 @@ -import Events = require('events'); import {ServerOptions} from "./server-options"; +import {ServerInfo} from "./server-info"; import {Dictionary} from "../util/util"; +import {Request} from "../request/request"; +import * as http from "http"; +import * as events from 'events'; + /** * 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 { +export class Server extends events.EventEmitter { /** Creates a new server object where: @@ -28,15 +32,77 @@ export class Server extends Events.EventEmitter { * returned from its implementation function. */ // TODO is that definition right? It's need review. The v16 is very different. - auth?: { + auth: { api: Dictionary; } /** * Access: read only. - * Contains the default authentication configuration is a default strategy was set via server.auth.default(). + * Contains the default authentication configuration is a default strategy was set via [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). */ // TODO it needs to be implemented. I didn't understand the description yet. + //server.auth.settings.default + + + /** + * Provides access to the decorations already applied to various framework interfaces. The object must not be + * modified directly, but only through server.decorate. Contains: + * * request - decorations on the request object. + * * toolkit - decorations on the response toolkit. + * * server - decorations on the server object. + */ + decorations: { + request: Request, + toolkit: any, // TODO Request Toolkit (https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) needs to be implemented. + server: Server + } + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) + * An object containing information about the server where: + * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). + * * created - server creation timestamp. + * * started - server start timestamp (0 when stopped). + * * port - the connection port based on the following rules: + * * host - The host configuration value. + * * address - the active IP address the connection was bound to after starting. Set to undefined until the server has been started or when using a non TCP port (e.g. UNIX domain socket). + * * protocol - the protocol used: + * * 'http' - HTTP. + * * 'https' - HTTPS. + * * 'socket' - UNIX domain socket or Windows named pipe. + * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. + */ + info: ServerInfo; + + /** + * Access: read only and listener public interface. + * The node HTTP server object. + */ + listener: http.Server; + + /** + * An object containing the process load metrics (when load.sampleInterval is enabled): + * * eventLoopDelay - event loop delay milliseconds. + * * heapUsed - V8 heap usage. + * * rss - RSS memory usage. + */ + load: { + eventLoopDelay: number; + heapUsed: number; + rss: number; + }; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods + * Server methods are functions registered with the server and used throughout the application as a common utility. + * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request + * handlers without having to create a common module. + * sever.methods is an object which provides access to the methods registered via server.method() where each + * server method name is an object property. + */ + //methods: Dictionary; + methods: any; // TODO come back here after implements the server.method() + // TODO It"s not finished From d979e41cbc3fcca1fec677e360af2c72f135305e Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 23 Nov 2017 11:49:27 -0300 Subject: [PATCH 03/79] Added more Server and Plugins definitions. --- .../definitions/plugin/plugin-registered.d.ts | 33 ++++++++ .../definitions/server/server-options.d.ts | 1 + .../v17/definitions/server/server-realm.d.ts | 1 - .../v17/definitions/server/server-state.d.ts | 29 +++++++ types/hapi/v17/definitions/server/server.d.ts | 82 +++++++++++++++++-- 5 files changed, 139 insertions(+), 7 deletions(-) create mode 100644 types/hapi/v17/definitions/plugin/plugin-registered.d.ts create mode 100644 types/hapi/v17/definitions/server/server-state.d.ts diff --git a/types/hapi/v17/definitions/plugin/plugin-registered.d.ts b/types/hapi/v17/definitions/plugin/plugin-registered.d.ts new file mode 100644 index 0000000000..eb96b70537 --- /dev/null +++ b/types/hapi/v17/definitions/plugin/plugin-registered.d.ts @@ -0,0 +1,33 @@ +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + */ +export interface PluginsListRegistered { + [pluginName: string]: PluginRegistered; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) + * An object of the currently registered plugins where each key is a registered plugin name and the value is an + * object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + */ +export interface PluginRegistered { + + /** + * the plugin version. + */ + version: string; + + /** + * the plugin name. + */ + name: string; + + /** + * options used to register the plugin. + */ + options: any; // OptionsPassedToPlugin; + +} diff --git a/types/hapi/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts index 38af02ac44..3638531930 100644 --- a/types/hapi/v17/definitions/server/server-options.d.ts +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -160,6 +160,7 @@ export interface ServerOptions { Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object. */ // TODO I am not sure if I need to use all the server.state() definition (like the default value) OR only the options below. The v16 use "any" here. + // state?: ServerStateCookieOptions; state?: { strictHeader?: boolean, ignoreErrors?: boolean, diff --git a/types/hapi/v17/definitions/server/server-realm.d.ts b/types/hapi/v17/definitions/server/server-realm.d.ts index 56b05df36e..289ea48018 100644 --- a/types/hapi/v17/definitions/server/server-realm.d.ts +++ b/types/hapi/v17/definitions/server/server-realm.d.ts @@ -1,7 +1,6 @@ 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). */ diff --git a/types/hapi/v17/definitions/server/server-state.d.ts b/types/hapi/v17/definitions/server/server-state.d.ts new file mode 100644 index 0000000000..796dda8cad --- /dev/null +++ b/types/hapi/v17/definitions/server/server-state.d.ts @@ -0,0 +1,29 @@ +import {ServerStateCookieOptions} from "hapi"; +import {Dictionary} from "../util/util"; + +export interface ServerState { + + /** + * The server cookies manager. + * Access: read only and statehood public interface. + */ + readonly states: any; + + /** + * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state). + */ + readonly settings: ServerStateCookieOptions; + + /** + * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the + * cookie name and value is the configuration object. + */ + readonly cookies: any; // TODO what the difference between this one and the settings above? This one should be an array? + + /** + * An array containing the names of all configued cookies. + */ + readonly names: Dictionary; + + +} diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index c47fef7855..af1bc0d160 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -1,9 +1,13 @@ import {ServerOptions} from "./server-options"; +import {ServerRealm} from "./server-realm"; import {ServerInfo} from "./server-info"; import {Dictionary} from "../util/util"; import {Request} from "../request/request"; import * as http from "http"; import * as events from 'events'; +import {PluginsListRegistered} from "../plugin/plugin-registered"; +import {ServerState} from "./server-state"; +import {MimosOptions} from "../../../../mimos/index"; /** @@ -16,7 +20,7 @@ export class Server extends events.EventEmitter { Creates a new server object where: @param options - (optional) a server configuration object. */ - constructor(options: ServerOptions); + constructor(options: ServerOptions); /** * Provides a safe place to store server-specific run-time application data without potential conflicts with @@ -41,7 +45,7 @@ export class Server extends events.EventEmitter { * Contains the default authentication configuration is a default strategy was set via [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). */ // TODO it needs to be implemented. I didn't understand the description yet. - //server.auth.settings.default + //readonly server.auth.settings.default /** @@ -51,7 +55,7 @@ export class Server extends events.EventEmitter { * * toolkit - decorations on the response toolkit. * * server - decorations on the server object. */ - decorations: { + readonly decorations: { request: Request, toolkit: any, // TODO Request Toolkit (https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) needs to be implemented. server: Server @@ -72,7 +76,7 @@ export class Server extends events.EventEmitter { * * 'socket' - UNIX domain socket or Windows named pipe. * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. */ - info: ServerInfo; + readonly info: ServerInfo; /** * Access: read only and listener public interface. @@ -86,7 +90,7 @@ export class Server extends events.EventEmitter { * * heapUsed - V8 heap usage. * * rss - RSS memory usage. */ - load: { + readonly load: { eventLoopDelay: number; heapUsed: number; rss: number; @@ -101,7 +105,73 @@ export class Server extends events.EventEmitter { * server method name is an object property. */ //methods: Dictionary; - methods: any; // TODO come back here after implements the server.method() + readonly methods: any; // TODO come back here after implements the server.method() + + /** + * Provides access to the server MIME database used for setting content-type information. The object must not be + * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. + */ + mime: MimosOptions; + + /** + * An object containing the values exposed by each registered plugin where each key is a plugin name and the values + * are the exposed properties by each plugin using server.expose(). Plugins may set the value of + * the server.plugins[name] object directly or via the server.expose() method. + */ + plugins: any; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) + * 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). + */ + readonly realm: ServerRealm; + + /** + * An object of the currently registered plugins where each key is a registered plugin name and the value is + * an object containing: + * * version - the plugin version. + * * name - the plugin name. + * * options - (optional) options passed to the plugin during registration. + */ + readonly registrations: PluginsListRegistered; + + /** + * The server configuration object after defaults applied. + */ + readonly settings: ServerOptions; + + /** + * The server cookies manager. + * Access: read only and statehood public interface. + */ + readonly states: ServerState; + + /** + * A string indicating the listener type where: + * * 'socket' - UNIX domain socket or Windows named pipe. + * * 'tcp' - an HTTP listener. + */ + readonly type: 'socket' | 'tcp'; + + /** + * The hapi module version number. + */ + readonly version: string; + + + + + + + + + // TODO It"s not finished From dd1526d33567a66b50bfb86af1554aaff28f78c8 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 23 Nov 2017 11:53:27 -0300 Subject: [PATCH 04/79] Updated imports with new definitions --- types/hapi/v17/index.d.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index 1e3403e4e1..c2ca44d7d4 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -10,6 +10,7 @@ /** PLUGIN */ export * from './definitions/plugin/plugin' +export * from './definitions/plugin/plugin-registered' /** REQUEST */ export * from './definitions/request/request' @@ -18,14 +19,6 @@ export * from './definitions/request/request' 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' @@ -39,9 +32,12 @@ 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-events' +export * from './definitions/server/server-info' 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' export * from './definitions/server/server-state-options' /** UTIL */ From a2503ea3dc27ace22bb605df48787de44caa41cb Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 23 Nov 2017 17:22:08 -0300 Subject: [PATCH 05/79] Added ResponseToolkit def. --- .../response/response-toolkit.d.ts | 130 ++++++++++++++++++ types/hapi/v17/index.d.ts | 1 + 2 files changed, 131 insertions(+) create mode 100644 types/hapi/v17/definitions/response/response-toolkit.d.ts diff --git a/types/hapi/v17/definitions/response/response-toolkit.d.ts b/types/hapi/v17/definitions/response/response-toolkit.d.ts new file mode 100644 index 0000000000..a4cabf3785 --- /dev/null +++ b/types/hapi/v17/definitions/response/response-toolkit.d.ts @@ -0,0 +1,130 @@ +import {ServerRealm, ServerStateCookieOptions} from "hapi"; +import {Request} from "../request/request"; +import {ResponseObject} from "./response-object"; + +/** + * See more about Lifecycle + * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle + * + */ + + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) + * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the + * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this + * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi. + */ +export interface ResponseToolkit { + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step + * without further interaction with the node response stream. It is the developer's responsibility to write + * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw). + */ + readonly abandon: Object; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after + * calling request.raw.res.end()) to close the the node response stream. + */ + readonly close: Object; + + /** + * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind) + * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()). + */ + readonly context: Object; + + /** + * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. + */ + readonly continue: Object; + + /** + * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching + * route. Defaults to the root server realm in the onRequest step. + */ + readonly realm: ServerRealm; + + /** + * Access: read only and public request interface. + * The [request] object. This is a duplication of the request lifecycle method argument used by + * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. + */ + request: Request; + + /** + * Used by the [authentication] method to pass back valid credentials where: + * @param data - an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return Return value: an internal authentication object. + */ + authenticated(data: {credentials: any, artifacts?: any}): any; + + /** + * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if + * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request + * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will + * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined. + * The method argumetns are: + * @param options - a required configuration object with: + * * etag - the ETag string. Required if modified is not present. Defaults to no header. + * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header. + * * vary - same as the response.etag() option. Defaults to true. + * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed. + * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned, + * it should be used as the return value (but may be customize using the response methods). + */ + entity(options: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; + + /** + * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). + * @param url + * @return Returns a response object. + */ + redirect(uri: string): ResponseObject; + + /** + * Wraps the provided value and returns a response object which allows customizing the response + * (e.g. setting the HTTP status code, custom headers, etc.), where: + * @param value - (optional) return value. Defaults to null. + * @return Returns a response object. + */ + response(value?: string): ResponseObject; + + /** + * Sets a response cookie using the same arguments as response.state(). + * @param name of the cookie + * @param value of the cookie + * @param (optional) ServerStateCookieOptions object. + * @return Return value: none. + */ + state(name: string, value: string, options?: ServerStateCookieOptions): void; + + /** + * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: + * @param error - (required) the authentication error. + * @param data - (optional) an object with: + * * credentials - (required) object representing the authenticated entity. + * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. + * @return void. + * The method is used to pass both the authentication error and the credentials. For example, if a request included + * expired credentials, it allows the method to pass back the user information (combined with a 'try' + * authentication mode) for error customization. + * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. + */ + unauthenticated(error: Error, data?: {credentials: any, artifacts?: any}): void; + + /** + * Clears a response cookie using the same arguments as + * [response.unstate()](https://github.com/hapijs/hapi/blob/master/API.md#response.unstate()). + * @param name of the cookie + * @param options (optional) ServerStateCookieOptions object. + * @return void. + */ + unstate(name: string, options?: ServerStateCookieOptions): void; + +} diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index c2ca44d7d4..e8ff80b1c6 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -18,6 +18,7 @@ export * from './definitions/request/request' /** RESPONSE */ export * from './definitions/response/response-object' export * from './definitions/response/response-settings' +export * from './definitions/response/response-toolkit' /** ROUTE */ export * from './definitions/route/route-options' From 5e3bbdfd3a7c9eeeb56832b2d887688d17eb5a5b Mon Sep 17 00:00:00 2001 From: rsouza Date: Fri, 24 Nov 2017 16:51:53 -0300 Subject: [PATCH 06/79] Added some events in ServerEvents interface. Not ready yet. --- .../v17/definitions/server/server-events.d.ts | 162 +++++++++++++++++- 1 file changed, 161 insertions(+), 1 deletion(-) diff --git a/types/hapi/v17/definitions/server/server-events.d.ts b/types/hapi/v17/definitions/server/server-events.d.ts index 4aca038e7f..cb86ca8245 100644 --- a/types/hapi/v17/definitions/server/server-events.d.ts +++ b/types/hapi/v17/definitions/server/server-events.d.ts @@ -1,12 +1,172 @@ +import Podium = require("../../../../podium/index"); + +/** + * an event name string. + * an event options object. + * a podium emitter object. + */ +export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) + * Object that it will be used in Event + */ +export interface ServerEventsApplicationObject { + /** the event name string (required). */ + name: string; + /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */ + channels?: string | string[]; + /** if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). */ + clone?: boolean; + /** if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). */ + spread?: boolean; + /** if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. */ + tags?: boolean; + /** if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). */ + shared?: boolean; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * a criteria object with the following optional keys (unless noted otherwise): + */ +export interface ServerEventCriteria { + /** (required) the event name string. */ + name: string; + /** a string or array of strings specifying the event channels to subscribe to. If the event registration specified a list of allowed channels, the channels array must match the allowed channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter. */ + channels?: string | string[]; + /** if true, the data object passed to server.event.emit() is cloned before it is passed to the listener method. Defaults to the event registration option (which defaults to false). */ + clone?: boolean; + /** a positive integer indicating the number of times the listener can be called after which the subscription is automatically removed. A count of 1 is the same as calling server.events.once(). Defaults to no limit. */ + count?: number; + /** + * filter - the event tags (if present) to subscribe to which can be one of: + * * a tag string. + * * an array of tag strings. + * * an object with the following: + * * * tags - a tag string or array of tag strings. + * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). + */ + filter?: string | string[] | {tags: string | string[], all?: boolean}; + /** if true, and the data object passed to server.event.emit() is an array, the listener method is called with each array element passed as a separate argument. This should only be used when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false). */ + spread?: boolean; + /** if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. Defaults to the event registration option (which defaults to false). */ + tags?: boolean; +} + /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) * Access: podium public interface. * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. */ -// TODO it needs to be implemented export interface ServerEvents { + /** + * Register custom application events where: + * @param events - must be one of: + * * an event name string. + * * an event options object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). + * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). + * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). + * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). + * * a podium emitter object. + * * an array containing any of the above. + * @return Return value: none. + */ + event(events: ServerEventsApplication): void; + event(events: ServerEventsApplication[]): void; + events: { + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) + * Emits a custom application event to all the subscribed listeners where: + * @param criteria - the event update criteria which must be one of: + * * the event name string. + * * an object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channel - the channel name string. + * * * tags - a tag string or array of tag strings. + * @param data - the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @return Return value: none. + * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. + */ + emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any): void; + + /** + *[See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * Subscribe to an event where: + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + */ + on(criteria: string, listener: Function): void; + on(criteria: ServerEventsApplicationObject, listener: Function): void; + on(criteria: ServerEventCriteria, listener: Function): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) + * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + */ + once(criteria: string, listener: Function): void; + once(criteria: ServerEventsApplicationObject, listener: Function): void; + once(criteria: ServerEventCriteria, listener: Function): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) + * Same as calling server.events.on() with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: a promise that resolves when the event is emitted. + */ + once(criteria: string): any; + once(criteria: ServerEventsApplicationObject): any; + once(criteria: ServerEventCriteria): any; + + } + + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) + * Used within a plugin to expose a property via server.plugins[name] where: + * @param key - the key assigned (server.plugins[name][key]). + * @param value - the value assigned. + * @return Return value: none. + */ + expose(key: string, value: any): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) + * Merges an object into to the existing content of server.plugins[name] where: + * @param obj - the object merged into the exposed properties container. + * @return Return value: none. + * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method + * for exposing large objects that may be expensive to clone or singleton objects such as database client + * objects. Instead favor server.expose(key, value), which only copies a reference to value. + */ + expose(obj: Object): void; + + + + + + + // TODO not ready yet } From f863e0c6cf9b476dca1ab9ebbdb54e6b894ff417 Mon Sep 17 00:00:00 2001 From: rsouza Date: Fri, 24 Nov 2017 16:54:29 -0300 Subject: [PATCH 07/79] Removing unused param from JSDoc. --- types/hapi/v17/definitions/server/server-events.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/hapi/v17/definitions/server/server-events.d.ts b/types/hapi/v17/definitions/server/server-events.d.ts index cb86ca8245..d5920c2b3a 100644 --- a/types/hapi/v17/definitions/server/server-events.d.ts +++ b/types/hapi/v17/definitions/server/server-events.d.ts @@ -131,7 +131,6 @@ export interface ServerEvents { * * event name string which can be any of the built-in server events * * a custom application event registered with server.event(). * * a criteria object - * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. * @return Return value: a promise that resolves when the event is emitted. */ once(criteria: string): any; From b00083ac4342de05a53c36c669fa502fd53de506 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 12:52:56 -0300 Subject: [PATCH 08/79] Added more Server definitions. Moved the events from ServerEvents.d.ts to Server.d.ts. --- .../route/route-options-payload.d.ts | 7 +- .../v17/definitions/server/server-events.d.ts | 116 --------- types/hapi/v17/definitions/server/server.d.ts | 236 ++++++++++++++++++ 3 files changed, 242 insertions(+), 117 deletions(-) diff --git a/types/hapi/v17/definitions/route/route-options-payload.d.ts b/types/hapi/v17/definitions/route/route-options-payload.d.ts index 15d1611dc9..fc5a7b10c4 100644 --- a/types/hapi/v17/definitions/route/route-options-payload.d.ts +++ b/types/hapi/v17/definitions/route/route-options-payload.d.ts @@ -16,6 +16,11 @@ export enum PayloadMultipartOutputEnum { Annotated = 'annotated', } +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) + */ +export type PayloadCompressionDecoderSettings = any; + /**Determines how the request payload is processed.*/ export interface RouteOptionsPayload { @@ -35,7 +40,7 @@ export interface RouteOptionsPayload { 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; + compression?: Dictionary; /** Default value: 'application/json'. diff --git a/types/hapi/v17/definitions/server/server-events.d.ts b/types/hapi/v17/definitions/server/server-events.d.ts index d5920c2b3a..c08bf4057a 100644 --- a/types/hapi/v17/definitions/server/server-events.d.ts +++ b/types/hapi/v17/definitions/server/server-events.d.ts @@ -53,119 +53,3 @@ export interface ServerEventCriteria { /** if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. Defaults to the event registration option (which defaults to false). */ tags?: boolean; } - -/** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - * Access: podium public interface. - * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. - */ -export interface ServerEvents { - - /** - * Register custom application events where: - * @param events - must be one of: - * * an event name string. - * * an event options object with the following optional keys (unless noted otherwise): - * * * name - the event name string (required). - * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). - * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). - * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). - * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. - * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). - * * a podium emitter object. - * * an array containing any of the above. - * @return Return value: none. - */ - event(events: ServerEventsApplication): void; - event(events: ServerEventsApplication[]): void; - - events: { - - /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) - * Emits a custom application event to all the subscribed listeners where: - * @param criteria - the event update criteria which must be one of: - * * the event name string. - * * an object with the following optional keys (unless noted otherwise): - * * * name - the event name string (required). - * * * channel - the channel name string. - * * * tags - a tag string or array of tag strings. - * @param data - the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. - * @return Return value: none. - * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. - */ - emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any): void; - - /** - *[See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) - * Subscribe to an event where: - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. - * @return Return value: none. - */ - on(criteria: string, listener: Function): void; - on(criteria: ServerEventsApplicationObject, listener: Function): void; - on(criteria: ServerEventCriteria, listener: Function): void; - - /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) - * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. - * @return Return value: none. - */ - once(criteria: string, listener: Function): void; - once(criteria: ServerEventsApplicationObject, listener: Function): void; - once(criteria: ServerEventCriteria, listener: Function): void; - - /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) - * Same as calling server.events.on() with the count option set to 1. - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @return Return value: a promise that resolves when the event is emitted. - */ - once(criteria: string): any; - once(criteria: ServerEventsApplicationObject): any; - once(criteria: ServerEventCriteria): any; - - } - - - /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) - * Used within a plugin to expose a property via server.plugins[name] where: - * @param key - the key assigned (server.plugins[name][key]). - * @param value - the value assigned. - * @return Return value: none. - */ - expose(key: string, value: any): void; - - /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) - * Merges an object into to the existing content of server.plugins[name] where: - * @param obj - the object merged into the exposed properties container. - * @return Return value: none. - * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method - * for exposing large objects that may be expensive to clone or singleton objects such as database client - * objects. Instead favor server.expose(key, value), which only copies a reference to value. - */ - expose(obj: Object): void; - - - - - - - // TODO not ready yet - - -} diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index af1bc0d160..6ad62c63b6 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -5,9 +5,15 @@ import {Dictionary} from "../util/util"; import {Request} from "../request/request"; import * as http from "http"; import * as events from 'events'; +import * as catbox from "catbox"; +import * as zlib from "zlib"; import {PluginsListRegistered} from "../plugin/plugin-registered"; import {ServerState} from "./server-state"; import {MimosOptions} from "../../../../mimos/index"; +import { + ServerOptionsCache, ServerEventCriteria, ServerEventsApplication, ServerEventsApplicationObject, + PayloadCompressionDecoderSettings +} from "hapi"; /** @@ -61,6 +67,172 @@ export class Server extends events.EventEmitter { server: Server } + /** + * Register custom application events where: + * @param events - must be one of: + * * an event name string. + * * an event options object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channels - a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). + * * * clone - if true, the data object passed to server.events.emit() is cloned before it is passed to the listeners (unless an override specified by each listener). Defaults to false (data is passed as-is). + * * * spread - if true, the data object passed to server.event.emit() must be an array and the listener method is called with each array element passed as a separate argument (unless an override specified by each listener). This should only be used when the emitted data structure is known and predictable. Defaults to false (data is emitted as a single argument regardless of its type). + * * * tags - if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false. + * * * shared - if true, the same event name can be registered multiple times where the second registration is ignored. Note that if the registration config is changed between registrations, only the first configuration is used. Defaults to false (a duplicate registration will throw an error). + * * a podium emitter object. + * * an array containing any of the above. + * @return Return value: none. + */ + event(events: ServerEventsApplication): void; + event(events: ServerEventsApplication[]): void; + + events: { + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) + * Emits a custom application event to all the subscribed listeners where: + * @param criteria - the event update criteria which must be one of: + * * the event name string. + * * an object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channel - the channel name string. + * * * tags - a tag string or array of tag strings. + * @param data - the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @return Return value: none. + * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. + */ + emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any): void; + + /** + *[See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * Subscribe to an event where: + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + */ + on(criteria: string, listener: Function): void; + on(criteria: ServerEventsApplicationObject, listener: Function): void; + on(criteria: ServerEventCriteria, listener: Function): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) + * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + */ + once(criteria: string, listener: Function): void; + once(criteria: ServerEventsApplicationObject, listener: Function): void; + once(criteria: ServerEventCriteria, listener: Function): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) + * Same as calling server.events.on() with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @return Return value: a promise that resolves when the event is emitted. + */ + once(criteria: string): any; + once(criteria: ServerEventsApplicationObject): any; + once(criteria: ServerEventCriteria): any; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) + */ + removeListener(name: string, listener: Function): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) + */ + removeAllListeners(name: string): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) + */ + hasListeners(name: string): boolean; + + /** + * The 'log' event type emits internal server events generated by the framework as well as application events + * logged with server.log(). + * The 'log' event handler uses the function signature function(event, tags) where: + * @param event - an object with the following properties: + * * timestamp - the event timestamp. + * * tags - an array of tags identifying the event (e.g. ['error', 'http']). + * * channel - set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log(). + * * data - event-specific information. Available when event data was provided and is not an error. Errors are passed via error. + * * error - the error object related to the event if applicable. Cannot appear together with data. + * @param tags - an object where each event.tag is a key and the value is true. Useful for quick identification of events. + * + */ + + + // TODO not ready yet + + + + } + + + + + + + + + + + + + + + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) + * Used within a plugin to expose a property via server.plugins[name] where: + * @param key - the key assigned (server.plugins[name][key]). + * @param value - the value assigned. + * @return Return value: none. + */ + expose(key: string, value: any): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) + * Merges an object into to the existing content of server.plugins[name] where: + * @param obj - the object merged into the exposed properties container. + * @return Return value: none. + * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method + * for exposing large objects that may be expensive to clone or singleton objects such as database client + * objects. Instead favor server.expose(key, value), which only copies a reference to value. + */ + expose(obj: Object): void; + + + + + + + + + + + + + + + + + + /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) * An object containing information about the server where: @@ -168,6 +340,70 @@ export class Server extends events.EventEmitter { + // TODO Put SERVER AUTH here + + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) + * Sets a global context used as the default bind object when adding a route or an extension where: + * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context. + * @return Return value: none. + * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. + */ + bind(context: any): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + cache: { + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + * Provisions a cache segment within the server cache facility where: + * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: + * - `id` - the `id` string or object provided to the `get()` method. + * - `flags` - an object used to pass back additional flags to the cache where: + *- `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. + * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + * * staleTimeout - number of milliseconds to wait before checking if an item is stale. + * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. + * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. + * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. + * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. + * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). + * * cache - the cache name configured in server.cache. Defaults to the default cache. + * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. + * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. + * @return Catbox Policy. + */ + (options: catbox.PolicyOptions): catbox.Policy; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) + * Provisions a server cache as described in server.cache where: + * @param options - same as the server cache configuration options. + * @return Return value: none. + * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + */ + provision(options: ServerOptionsCache): void; + + } + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) + * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the decoder name string. + * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the return value is an object compatible with the output of node's zlib.createGunzip(). + * @return Return value: none. + */ + decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void; + + + + From c6edf56209d507e738150b31eaef1acc28060743 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 18:10:44 -0300 Subject: [PATCH 09/79] Removed legacy definitions. --- .../server/server-connection-options.d.ts | 54 ------------------- types/hapi/v17/index.d.ts | 1 - 2 files changed, 55 deletions(-) delete mode 100644 types/hapi/v17/definitions/server/server-connection-options.d.ts diff --git a/types/hapi/v17/definitions/server/server-connection-options.d.ts b/types/hapi/v17/definitions/server/server-connection-options.d.ts deleted file mode 100644 index 383d601dc0..0000000000 --- a/types/hapi/v17/definitions/server/server-connection-options.d.ts +++ /dev/null @@ -1,54 +0,0 @@ -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/index.d.ts b/types/hapi/v17/index.d.ts index e8ff80b1c6..9efde0895d 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -32,7 +32,6 @@ 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-events' export * from './definitions/server/server-info' export * from './definitions/server/server-options' From 42fbf80a213f1865234ffe77405995c40b784dfa Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 18:50:39 -0300 Subject: [PATCH 10/79] Replaced enum HttpMethod to types like v16. Not very elegant solution but works easily with lower/upper case :) --- types/hapi/v17/definitions/util/util.d.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/types/hapi/v17/definitions/util/util.d.ts b/types/hapi/v17/definitions/util/util.d.ts index bfe54031e8..f1c6d0c39e 100644 --- a/types/hapi/v17/definitions/util/util.d.ts +++ b/types/hapi/v17/definitions/util/util.d.ts @@ -2,9 +2,6 @@ export interface Dictionary { [key: string]: T; } -export enum HttpMethod { - Get = "get", - Post = "post", - Put = "put", - Delete= "delete", -} +export type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; +export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_LOWERCASE; +export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; From 0f1dbd0f9d77c1d95296f697ce4978d6ff646a36 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 18:52:44 -0300 Subject: [PATCH 11/79] Separating request auth, server and route in different files to better understanding. --- .../v17/definitions/request/request-auth.d.ts | 20 +++++ .../v17/definitions/request/request-info.d.ts | 35 ++++++++ .../definitions/request/request-route.d.ts | 20 +++++ .../hapi/v17/definitions/request/request.d.ts | 81 +++---------------- 4 files changed, 84 insertions(+), 72 deletions(-) create mode 100644 types/hapi/v17/definitions/request/request-auth.d.ts create mode 100644 types/hapi/v17/definitions/request/request-info.d.ts create mode 100644 types/hapi/v17/definitions/request/request-route.d.ts diff --git a/types/hapi/v17/definitions/request/request-auth.d.ts b/types/hapi/v17/definitions/request/request-auth.d.ts new file mode 100644 index 0000000000..cc5fe1ec0a --- /dev/null +++ b/types/hapi/v17/definitions/request/request-auth.d.ts @@ -0,0 +1,20 @@ +/** + * Authentication information + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + */ +export interface RequestAuth { + /** an artifact object received from the authentication strategy and used in authentication-related actions. */ + artifacts: 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; +} diff --git a/types/hapi/v17/definitions/request/request-info.d.ts b/types/hapi/v17/definitions/request/request-info.d.ts new file mode 100644 index 0000000000..035b36cba0 --- /dev/null +++ b/types/hapi/v17/definitions/request/request-info.d.ts @@ -0,0 +1,35 @@ +/** + * Request information + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) + */ +export interface RequestInfo { + /** the request preferred encoding. */ + acceptEncoding: string; + /** if CORS is enabled for the route, contains the following: */ + cors: { + /** + * 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; +} diff --git a/types/hapi/v17/definitions/request/request-route.d.ts b/types/hapi/v17/definitions/request/request-route.d.ts new file mode 100644 index 0000000000..1b5e79d03b --- /dev/null +++ b/types/hapi/v17/definitions/request/request-route.d.ts @@ -0,0 +1,20 @@ +import {RouteOptions, ServerRealm, HTTP_METHODS_PARTIAL} from "hapi"; + +/** + * The request route information object + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + */ +export interface RequestRoute { + /** the route HTTP method. */ + method: HTTP_METHODS_PARTIAL; + /** the route path. */ + path: string; + /** the route vhost option if configured. */ + vhost?: string | string[]; + /** the active realm associated with the route.*/ + realm: ServerRealm; + /** the route options object with all defaults applied. */ + settings: RouteOptions; + /** the route internal normalized string representing the normalized path. */ + fingerprint: string; +} diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 2da1eb27be..84212bfacf 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -1,12 +1,13 @@ 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 {Dictionary, HTTP_METHODS_PARTIAL, HTTP_METHODS_PARTIAL_LOWERCASE} from "../util/util"; import {PluginsStates} from "../plugin/plugin"; +import {RequestRoute} from "./request-route"; +import {RequestAuth} from "./request-auth"; +import {RequestInfo} from "./request-info"; /** * TODO both objects ReplyValue and _ReplyValue I found in the v16 TS definition, but I don't found it in the documentation. Need review. @@ -15,76 +16,12 @@ import {PluginsStates} from "../plugin/plugin"; 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 { /** @@ -104,7 +41,7 @@ export interface Request { mode - the route authentication mode. strategy - the name of the strategy used. */ - auth: RequestAuth; + readonly auth: RequestAuth; /** Access: read only and the public podium interface. @@ -137,7 +74,7 @@ export interface Request { responded - request response timestamp (0 is not responded yet). Note that the request.info object is not meant to be modified. */ - info: RequestInfo; + readonly info: RequestInfo; /** Access: read only. @@ -150,7 +87,7 @@ export interface Request { Access: read only. The request method in lower case (e.g. 'get', 'post'). */ - method: HttpMethod; + method: HTTP_METHODS_PARTIAL_LOWERCASE; /** Access: read only. @@ -292,11 +229,11 @@ export interface Request { /** * request.setMethod(method) * Changes the request method before the router begins processing the request where: + * @param method - is the request HTTP method (e.g. 'GET'). * 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; + setMethod(method: HTTP_METHODS_PARTIAL): void; /** * request.setUrl(url, [stripTrailingSlash] From 0e0de0dc95301e00d24443ecbea67d213c0a3bff Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 18:55:26 -0300 Subject: [PATCH 12/79] Added more Server definitions: ServerExt, ServerInject and others. --- .../v17/definitions/server/server-ext.d.ts | 97 ++++++++ .../v17/definitions/server/server-inject.d.ts | 50 ++++ types/hapi/v17/definitions/server/server.d.ts | 230 ++++++++++++++---- 3 files changed, 324 insertions(+), 53 deletions(-) create mode 100644 types/hapi/v17/definitions/server/server-ext.d.ts create mode 100644 types/hapi/v17/definitions/server/server-inject.d.ts diff --git a/types/hapi/v17/definitions/server/server-ext.d.ts b/types/hapi/v17/definitions/server/server-ext.d.ts new file mode 100644 index 0000000000..960a342998 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-ext.d.ts @@ -0,0 +1,97 @@ +import {Server, Request, ResponseToolkit} from "hapi"; + +/** + * The extension point event name. The available extension points include the request extension points as well as the following server extension points: + * 'onPreStart' - called before the connection listeners are started. + * 'onPostStart' - called after the connection listeners are started. + * 'onPreStop' - called before the connection listeners are stopped. + * 'onPostStop' - called after the connection listeners are stopped. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ +export type ServerExtType = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; + +/** + * The extension point event name for Request + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) + */ +export type ServerExtRequestType = 'onRequest'; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsObject { + type: ServerExtType; + method: ServerExtPointFunction | ServerExtPointFunction[]; + options?: ServerExtOptions; +} + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ +export interface ServerExtEventsRequestObject { + type: ServerExtRequestType; + method: RequestExtPointFunction | RequestExtPointFunction[]; + options?: ServerExtOptions; +} + +export interface ServerExtPointFunction { + (server: Server): void; +} + +export interface RequestExtPointFunction { + (request: Request, h: ResponseToolkit): void; +} + +/** + * An object with the following: + * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + */ +export interface ServerExtOptions { + before: string | string[]; + after: string | string[]; + bind: any; + sandbox?: 'server' | 'plugin'; +} + diff --git a/types/hapi/v17/definitions/server/server-inject.d.ts b/types/hapi/v17/definitions/server/server-inject.d.ts new file mode 100644 index 0000000000..cb04ba3aab --- /dev/null +++ b/types/hapi/v17/definitions/server/server-inject.d.ts @@ -0,0 +1,50 @@ +import {Request, PluginsStates} from "hapi"; +import * as Shot from "shot"; + +/** + * An object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested separately. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectOptions extends Shot.RequestOptions { + credentials?: any; + artifacts?: any; + app?: any; + plugins?: PluginsStates; + allowInternals?: boolean; +} + +/** + * A response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + * * request - the request object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * For context [Shot module](https://github.com/hapijs/shot) + */ +export interface ServerInjectResponse extends Shot.ResponseObject { + result: any; + request: Request; +} diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 6ad62c63b6..741279629b 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -12,9 +12,14 @@ import {ServerState} from "./server-state"; import {MimosOptions} from "../../../../mimos/index"; import { ServerOptionsCache, ServerEventCriteria, ServerEventsApplication, ServerEventsApplicationObject, - PayloadCompressionDecoderSettings + PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, HTTP_METHODS } from "hapi"; - +import { + RequestExtPointFunction, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, + ServerExtPointFunction, ServerExtRequestType, ServerExtType +} from "./server-ext"; +import {ServerInjectOptions, ServerInjectResponse} from "./server-inject"; +import {RequestRoute} from "../request/request-route"; /** * The server object is the main application container. The server manages all incoming requests along with all @@ -182,57 +187,6 @@ export class Server extends events.EventEmitter { } - - - - - - - - - - - - - - - /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) - * Used within a plugin to expose a property via server.plugins[name] where: - * @param key - the key assigned (server.plugins[name][key]). - * @param value - the value assigned. - * @return Return value: none. - */ - expose(key: string, value: any): void; - - /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) - * Merges an object into to the existing content of server.plugins[name] where: - * @param obj - the object merged into the exposed properties container. - * @return Return value: none. - * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method - * for exposing large objects that may be expensive to clone or singleton objects such as database client - * objects. Instead favor server.expose(key, value), which only copies a reference to value. - */ - expose(obj: Object): void; - - - - - - - - - - - - - - - - - - /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) * An object containing information about the server where: @@ -401,6 +355,176 @@ export class Server extends events.EventEmitter { */ decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void; + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) + * Extends various framework interfaces with custom methods where: + * @param type - the interface being decorated. Supported types: + * 'handler' - adds a new handler type to be used in routes handlers. + * 'request' - adds methods to the Request object. + * 'server' - adds methods to the Server object. + * 'toolkit' - adds methods to the response toolkit. + * @param property - the object decoration key name. + * @param method - the extension function or other value. + * @param options - (optional) supports the following optional settings: + * apply - when the type is 'request', if true, the method function is invoked using the signature function(request) where request is the current request object and the returned value is assigned as the decoration. + * extend - if true, overrides an existing decoration. The method must be a function with the signature function(existing) where: + * existing - is the previously set decoration method value. + * must return the new decoration function or value. + * cannot be used to extend handler decorations. + * @return void; + */ + decorate(type: 'request', property: string, method: ((request: Request) => Function), options?: {apply: true; extend: false} ): void; + decorate(type: 'handler' | 'request' | 'reply' | 'server', property: string, method: Function, options?: {apply: boolean; extend: boolean} ): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) + * Used within a plugin to declare a required dependency on other plugins where: + * @param dependencies - a single string or an array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is initialized or started. + * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. The function signature is async function(server) where: + * server - the server the dependency() method was called on. + * @return Return value: none. + * The after method is identical to setting a server extension point on 'onPreStart'. + * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). + * The method does not provide version dependency which should be implemented using npm peer dependencies. + */ + dependency(dependencies: string | string[], after?: ((server: Server) => Function)): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: + * @param encoding - the encoder name string. + * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object compatible with the output of node's zlib.createGzip(). + * @return Return value: none. + */ + encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) + * Used within a plugin to expose a property via server.plugins[name] where: + * @param key - the key assigned (server.plugins[name][key]). + * @param value - the value assigned. + * @return Return value: none. + */ + expose(key: string, value: any): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) + * Merges an object into to the existing content of server.plugins[name] where: + * @param obj - the object merged into the exposed properties container. + * @return Return value: none. + * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method + * for exposing large objects that may be expensive to clone or singleton objects such as database client + * objects. Instead favor server.expose(key, value), which only copies a reference to value. + */ + expose(obj: Object): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) + * Registers an extension function in one of the request lifecycle extension points where: + * @param events - an object or array of objects with the following: + * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: + * * * 'onPreStart' - called before the connection listeners are started. + * * * 'onPostStart' - called after the connection listeners are started. + * * * 'onPreStop' - called before the connection listeners are stopped. + * * * 'onPostStop' - called after the connection listeners are stopped. + * * method - (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is: + * * * server extension points: async function(server) where: + * * * * server - the server object. + * * * * this - the object provided via options.bind or the current active context set with server.bind(). + * * * request extension points: a lifecycle method. + * * options - (optional) an object with the following: + * * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. + * * * after - a string or array of strings of plugin names this method must execute after (on the same event). Otherwise, extension methods are executed in the order added. + * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. + * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. + * @return void + */ + ext(events: ServerExtEventsObject | ServerExtEventsObject[]): void; + ext(events: ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) + * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. + * @return Return value: none. + */ + ext(event: ServerExtType, method: ServerExtPointFunction, options?: ServerExtOptions): void; + ext(event: ServerExtRequestType, method: RequestExtPointFunction, options?: ServerExtOptions): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) + * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and + * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and + * other event listeners will get confused by repeated attempts to start the server or make assumptions about the + * healthy state of the environment. It is recommended to abort the process when the server fails to start properly. + * If you must try to resume after an error, call server.stop() first to reset the server state. + */ + initialize(): void; + + /** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) + * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead and limitations of the network stack. + * The method utilizes the shot module for performing injections, with some additional options and response properties: + * @param options - can be assigned a string with the requested URI, or an object with: + * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'. + * * url - (required) the request URL. If the URI includes an authority (e.g. 'example.com:8080'), it is used to automatically set an HTTP 'Host' header, unless one was specified in headers. + * * headers - (optional) an object with optional request headers where each key is the header name and the value is the header content. Defaults to no additions to the default shot headers. + * * payload - (optional) an string, buffer or object containing the request payload. In case of an object it will be converted to a string for you. Defaults to no payload. Note that payload processing defaults to 'application/json' if no 'Content-Type' header provided. + * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Defaults to no credentials. + * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts. + * * app - (optional) sets the initial value of request.app, defaults to {}. + * * plugins - (optional) sets the initial value of request.plugins, defaults to {}. + * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false. + * * remoteAddress - (optional) sets the remote address for the incoming connection. + * * simulate - (optional) an object with options used to simulate client request stream conditions for testing: + * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false. + * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false. + * * end - if false, does not end the stream. Defaults to true. + * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked. + * * validate - (optional) if false, the options inputs are not validated. This is recommended for run-time usage of inject() to make it perform faster where input validation can be tested separately. + * @return Return value: a response object with the following properties: + * * statusCode - the HTTP status code. + * * headers - an object containing the headers set. + * * payload - the response payload string. + * * rawPayload - the raw response payload buffer. + * * raw - an object with the injection request and response objects: + * * req - the simulated node request object. + * * res - the simulated node response object. + * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). + * * request - the request object. + */ + inject(options: string | ServerInjectOptions): ServerInjectResponse; + + /** + * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: + * @param tags - (required) a string or an array of strings (e.g. ['error', 'database', 'read']) used to identify the event. Tags are used instead of log levels and provide a much more expressive mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information. + * @param data - (optional) an message string or object with the application data being logged. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) + */ + log(tags: string | string[], data?: string | Object | (() => Function), timestamp?: number): void; + + /** + * Looks up a route configuration where: + * @param id - the route identifier. + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid) + */ + lookup(id: string): RequestRoute | null; + + /** + * Looks up a route configuration where: + * @param method - the HTTP method (e.g. 'GET', 'POST'). + * @param path - the requested path (must begin with '/'). + * @param host - (optional) hostname (to match against routes with vhost). + * @return Return value: the route information if found, otherwise null. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) + */ + match(method: HTTP_METHODS, path: string, host?: string): RequestRoute | null; + + From 6a2a84d017a422109d2352067d7a3b01b7780b1a Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 18:56:34 -0300 Subject: [PATCH 13/79] Replaced "any" type to "RouteCompressionEncoderSettings" type to better understanding because is shared with other interface. --- types/hapi/v17/definitions/route/route-options.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index d393e25810..db012ed3ce 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -9,6 +9,12 @@ import {FailAction} from "../util/fail-action"; import {RouteOptionsValidate} from "./route-options-validate"; import {PluginSpecificConfiguration} from "../plugin/plugin"; +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) + */ +export type RouteCompressionEncoderSettings = any; + /** Each route can be customized to change the default behavior of the request lifecycle. */ export interface RouteOptions { @@ -37,7 +43,7 @@ export interface RouteOptions { /** 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; + compression?: Dictionary; /** Default value: false (no CORS headers). From a03205797eee83cb76a682b3add2c2faacd50d96 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 19:04:41 -0300 Subject: [PATCH 14/79] Updated index with last file definitions. --- types/hapi/v17/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index 9efde0895d..98f8377102 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -14,6 +14,9 @@ export * from './definitions/plugin/plugin-registered' /** REQUEST */ export * from './definitions/request/request' +export * from './definitions/request/request-auth' +export * from './definitions/request/request-info' +export * from './definitions/request/request-route' /** RESPONSE */ export * from './definitions/response/response-object' @@ -33,7 +36,9 @@ export * from './definitions/route/route-options-validate' /** SERVER */ export * from './definitions/server/server' export * from './definitions/server/server-events' +export * from './definitions/server/server-ext' export * from './definitions/server/server-info' +export * from './definitions/server/server-inject' export * from './definitions/server/server-options' export * from './definitions/server/server-options-cache' export * from './definitions/server/server-realm' From 544cf39a2d424612d51e1dbc8b90caf0b86cb98b Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 23:18:12 -0300 Subject: [PATCH 15/79] Added generic LifeCycle interfaces. --- .../hapi/v17/definitions/util/lifecycle.d.ts | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 types/hapi/v17/definitions/util/lifecycle.d.ts diff --git a/types/hapi/v17/definitions/util/lifecycle.d.ts b/types/hapi/v17/definitions/util/lifecycle.d.ts new file mode 100644 index 0000000000..9dba7980d4 --- /dev/null +++ b/types/hapi/v17/definitions/util/lifecycle.d.ts @@ -0,0 +1,28 @@ +/** + * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: + * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods + * provided by the developer and executed by the framework. + * Each lifecycle method is a function with the signature await function(request, h, [err]) where: + * * request - the request object. + * * h - the response toolkit the handler must call to set a response and return control back to the framework. + * * err - an error object availble only when the method is used as a failAction value. + */ +export interface LifecycleMethod { + + // TODO need to be implemented. Ideally with Generics types. + +} + +/** + * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns + * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + */ +export interface LifecycleReturnValue { + + + +} + + + From 1d687c3144c2285fff960071128afaf544f1e437 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 23:19:58 -0300 Subject: [PATCH 16/79] Added Server Auth definitions. --- .../server/server-auth-scheme.d.ts | 71 ++++++++++++++ .../v17/definitions/server/server-auth.d.ts | 95 +++++++++++++++++++ types/hapi/v17/definitions/server/server.d.ts | 27 +----- 3 files changed, 169 insertions(+), 24 deletions(-) create mode 100644 types/hapi/v17/definitions/server/server-auth-scheme.d.ts create mode 100644 types/hapi/v17/definitions/server/server-auth.d.ts diff --git a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts new file mode 100644 index 0000000000..db21ed6111 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts @@ -0,0 +1,71 @@ +import {Server} from "./server"; +import {LifecycleReturnValue} from "../util/lifecycle"; +import {ResponseToolkit} from "../response/response-toolkit"; +import {Request} from "../request/request"; + +/** + * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + */ +export type ServerAuthSchemeOptions = any; + +/** + * the method implementing the scheme with signature function(server, options) where: + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + * @param server - a reference to the server object the scheme is added to. + * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + */ +export interface ServerAuthScheme { + (server: Server, options?: ServerAuthSchemeOptions): ServerAuthSchemeObject; +} + +/** + * The scheme method must return an object with the following + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme) + */ +export interface ServerAuthSchemeObject { + + /** + * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object. + */ + api?: any; + + /** + * A lifecycle method function called for each incoming request configured with the authentication scheme. The + * method is provided with two special toolkit methods for returning an authenticated or an unauthenticate result: + * * h.authenticated() - indicate request authenticated successfully. + * * h.unauthenticated() - indicate request failed to authenticate. + * @param request the request object. + * @param h the ResponseToolkit + * @return the LifecycleReturnValue + */ + authenticate(request: Request, h: ResponseToolkit): LifecycleReturnValue; + + /** + * A lifecycle method to authenticate the request payload. + * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad + * payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')), + * authentication may still be successful if the route auth.payload configuration is set to 'optional'. + * @param request the request object. + * @param h the ResponseToolkit + * @return the LifecycleReturnValue + */ + payload?(request: Request, h: ResponseToolkit): LifecycleReturnValue; + + /** + * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. + * @param request the request object. + * @param h the ResponseToolkit + * @return the LifecycleReturnValue + */ + response?(request: Request, h: ResponseToolkit): LifecycleReturnValue; + + /** + * An object with the following keys: + * * payload - if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false. + */ + options?: { + payload?: boolean; + }; + +} diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts new file mode 100644 index 0000000000..370e16be6b --- /dev/null +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -0,0 +1,95 @@ +import {ServerAuthScheme} from "./server-auth-scheme"; +import {Request} from "../request/request"; +import {RouteOptionsAccess} from "hapi"; +import {Dictionary} from "../util/util"; + +/** + * The authentication credentials object + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) + */ +export interface ServerAuthenticatedCredentials { + +} + +/** + * An authentication configuration object using the same format as the route auth handler options. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + */ +export interface ServerAuthConfig extends RouteOptionsAccess { + +} + +export interface ServerAuth { + + /** + * An object where each key is an authentication strategy name and the value is the exposed strategy API. + * Available only when the authentication scheme exposes an API by returning an api key in the object + * returned from its implementation function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) + */ + api: Dictionary; + + /** + * Contains the default authentication configuration is a default strategy was set via + * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). + */ + readonly settings: { + default: ServerAuthConfig; + } + + /** + * server.auth.default + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) + * Sets a default strategy which is applied to every route where: + * @param options - one of: + * * a string with the default strategy name + * * an authentication configuration object using the same format as the route auth handler options. + * @return void. + * The default does not apply when a route config specifies auth as false, or has an authentication strategy + * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication + * config is applied to the defaults. + * Note that if the route has authentication configured, the default only applies at the time of adding the route, + * not at runtime. This means that calling server.auth.default() after adding a route with some authentication + * config will have no impact on the routes added prior. However, the default will apply to routes added + * before server.auth.default() is called if those routes lack any authentication config. + * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active + * authentication configuration of a route, use server.auth.lookup(request.route). + */ + default(options: string | ServerAuthConfig): void; + + /** + * server.auth.scheme + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) + * Registers an authentication scheme where: + * @param name the scheme name. + * @param scheme - the method implementing the scheme with signature function(server, options) where: + * * server - a reference to the server object the scheme is added to. + * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. + * @return void. + */ + scheme(name: string, scheme: ServerAuthScheme): void; + + /** + * Registers an authentication strategy where: + * @param name - the strategy name. + * @param scheme - the scheme name (must be previously registered using server.auth.scheme()). + * @param options - scheme options based on the scheme requirements. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) + */ + strategy(name: string, scheme: string, options?: any): void; + + /** + * Tests a request against an authentication strategy where: + * @param strategy - the strategy name registered with server.auth.strategy(). + * @param request - the request object. + * @return Return value: the authentication credentials object if authentication was successful, otherwise throws an error. + * Note that the test() method does not take into account the route authentication configuration. It also does not + * perform payload authentication. It is limited to the basic strategy authentication execution. It does not + * include verifying scope, entity, or other route properties. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) + */ + test(strategy: string, request: Request): ServerAuthenticatedCredentials; + +} + diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 741279629b..92fc4ac961 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -1,7 +1,6 @@ import {ServerOptions} from "./server-options"; import {ServerRealm} from "./server-realm"; import {ServerInfo} from "./server-info"; -import {Dictionary} from "../util/util"; import {Request} from "../request/request"; import * as http from "http"; import * as events from 'events'; @@ -20,6 +19,7 @@ import { } from "./server-ext"; import {ServerInjectOptions, ServerInjectResponse} from "./server-inject"; import {RequestRoute} from "../request/request-route"; +import {ServerAuth, ServerAuthConfig} from "./server-auth"; /** * The server object is the main application container. The server manages all incoming requests along with all @@ -41,23 +41,9 @@ export class Server extends events.EventEmitter { 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. + * Server Auth: properties and methods */ - // 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()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()). - */ - // TODO it needs to be implemented. I didn't understand the description yet. - //readonly server.auth.settings.default - + auth: ServerAuth; /** * Provides access to the decorations already applied to various framework interfaces. The object must not be @@ -290,13 +276,6 @@ export class Server extends events.EventEmitter { */ readonly version: string; - - - - - // TODO Put SERVER AUTH here - - /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) * Sets a global context used as the default bind object when adding a route or an extension where: From c4d48d6542ae324a9f47bc3c482e17dee6542870 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 26 Nov 2017 23:21:04 -0300 Subject: [PATCH 17/79] Updated index with last file definitions. --- types/hapi/v17/index.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index 98f8377102..fa8569c974 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -35,6 +35,8 @@ export * from './definitions/route/route-options-validate' /** SERVER */ export * from './definitions/server/server' +export * from './definitions/server/server-auth' +export * from './definitions/server/server-auth-scheme' export * from './definitions/server/server-events' export * from './definitions/server/server-ext' export * from './definitions/server/server-info' @@ -47,4 +49,5 @@ export * from './definitions/server/server-state-options' /** UTIL */ export * from './definitions/util/fail-action' +export * from './definitions/util/lifecycle' export * from './definitions/util/util' From 6799c6506dda1f95148616fd5009fab60d573228 Mon Sep 17 00:00:00 2001 From: rsouza Date: Mon, 27 Nov 2017 13:12:09 -0300 Subject: [PATCH 18/79] Added more Server definitions. --- types/hapi/v17/definitions/server/server.d.ts | 34 +++++++++++++++++-- types/hapi/v17/hapi-tests.ts | 14 ++++++-- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 92fc4ac961..89169e0e2e 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -21,6 +21,10 @@ import {ServerInjectOptions, ServerInjectResponse} from "./server-inject"; import {RequestRoute} from "../request/request-route"; import {ServerAuth, ServerAuthConfig} from "./server-auth"; +export interface ServerMethod { + // (...args: any[], ttl?: number): any; +} + /** * 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). @@ -31,6 +35,7 @@ export class Server extends events.EventEmitter { Creates a new server object where: @param options - (optional) a server configuration object. */ + constructor(); constructor(options: ServerOptions); /** @@ -503,8 +508,23 @@ export class Server extends events.EventEmitter { */ match(method: HTTP_METHODS, path: string, host?: string): RequestRoute | null; - - + /** + * Registers a server method where: + * @param name - a unique method name used to invoke the method via server.methods[name]. + * @param method - the method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * @param options - (optional) configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). + * @return Return value: none. + * Method names can be nested (e.g. utils.users.get) which will automatically create the full path under server.methods (e.g. accessed via server.methods.utils.users.get). + * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ + // method(name: string, method: Function, options?: any): void; @@ -516,5 +536,15 @@ export class Server extends events.EventEmitter { // TODO It"s not finished + /** + * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). + * @return Return value: none. + * Note that if the method fails and throws an error, the server is considered to be in an undefined state and should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and other event listeners will get confused by repeated attempts to start the server or make assumptions about the healthy state of the environment. It is recommended to abort the process when the server fails to start properly. If you must try to resume after an error, call server.stop() first to reset the server state. + * If a started server is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart) + */ + start(): void; + + } diff --git a/types/hapi/v17/hapi-tests.ts b/types/hapi/v17/hapi-tests.ts index e0c05909c0..06e2cdf175 100644 --- a/types/hapi/v17/hapi-tests.ts +++ b/types/hapi/v17/hapi-tests.ts @@ -1,2 +1,12 @@ -import { Server } from "hapi"; -const server = new Server({ port: 3000, host: 'localhost' }); +import {Server, ServerOptions} from "hapi"; + +const options:ServerOptions = { + port: 8000 +} + +const server = new Server(options); +server.start(); + +console.log('Server started at: ' + server.info.uri); + + From 3907d25ab74bf09b890e32c7e85ed188848eb23a Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Mon, 27 Nov 2017 20:58:46 -0300 Subject: [PATCH 19/79] Added more Server types --- types/hapi/v17/definitions/plugin/plugin.d.ts | 3 +- .../v17/definitions/server/server-method.d.ts | 51 +++++++++++++ .../definitions/server/server-options.d.ts | 4 +- .../definitions/server/server-register.d.ts | 36 ++++++++++ types/hapi/v17/definitions/server/server.d.ts | 71 ++++++++++++++++--- types/hapi/v17/index.d.ts | 2 + 6 files changed, 155 insertions(+), 12 deletions(-) create mode 100644 types/hapi/v17/definitions/server/server-method.d.ts create mode 100644 types/hapi/v17/definitions/server/server-register.d.ts diff --git a/types/hapi/v17/definitions/plugin/plugin.d.ts b/types/hapi/v17/definitions/plugin/plugin.d.ts index f781de97bf..df31c2c449 100644 --- a/types/hapi/v17/definitions/plugin/plugin.d.ts +++ b/types/hapi/v17/definitions/plugin/plugin.d.ts @@ -4,7 +4,6 @@ export interface PluginsStates { [pluginName: string]: any; } -// Similar to v16, using that interface without any definition. export interface PluginSpecificConfiguration { } @@ -32,7 +31,7 @@ export interface Plugin { * registry) should use the same name as the name field in their 'package.json' file. Names must be * unique within each application. */ - name?: string; + 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; diff --git a/types/hapi/v17/definitions/server/server-method.d.ts b/types/hapi/v17/definitions/server/server-method.d.ts new file mode 100644 index 0000000000..216fd6ce6f --- /dev/null +++ b/types/hapi/v17/definitions/server/server-method.d.ts @@ -0,0 +1,51 @@ +import * as catbox from "catbox"; + +/** + * The method function with a signature async function(...args, [flags]) where: + * * ...args - the method function arguments (can be any number of arguments or none). + * * flags - when caching is enabled, an object used to set optional method result flags: + * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export interface ServerMethod { + (args: any[], flags: {ttl?: number}): any; +} + +/** + * The same cache configuration used in server.cache(). + * The generateTimeout option is required. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerMethodCache extends catbox.PolicyOptions { + /** + * Required + */ + generateTimeout: number | false; +} + +/** + * Configuration object: + * * bind - a context object passed back to the method function (via this) when called. Defaults to active context (set via server.bind() when the method is registered. Ignored if the method is an arrow function. + * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required. + * * generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the flags argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated). + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) + */ +export interface ServerMethodOptions { + bind: any; + cache: ServerMethodCache; + generateKey: Function; +} + +/** + * An object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ +export interface ServerMethodConfigurationObject { + name: string; + method: ServerMethod; + options?: ServerMethodOptions; +} diff --git a/types/hapi/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts index 3638531930..5b2b364f8c 100644 --- a/types/hapi/v17/definitions/server/server-options.d.ts +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -1,7 +1,7 @@ import {ServerOptionsCache} from "./server-options-cache"; import * as http from "http"; import * as https from "https"; -import * as Catbox from "catbox"; +import * as catbox from "catbox"; import {MimosOptions} from "mimos"; import {PluginSpecificConfiguration, RouteOptions} from "hapi"; @@ -47,7 +47,7 @@ export interface ServerOptions { 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[]; + cache?: catbox.EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; /** Default value: { minBytes: 1024 }. diff --git a/types/hapi/v17/definitions/server/server-register.d.ts b/types/hapi/v17/definitions/server/server-register.d.ts new file mode 100644 index 0000000000..34685cbde2 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-register.d.ts @@ -0,0 +1,36 @@ +import {Plugin} from "hapi"; + +/** + * Registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ +export interface ServerRegisterOptions { + + once?: boolean; + routes?: { + prefix: string; + vhost: string | string[]; + }; + +} + +/** + * An object with the following: + * * plugin - a plugin object. + * * options - (optional) options passed to the plugin during registration. + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ +export interface ServerRegisterPluginObject extends ServerRegisterOptions { + + plugin: Plugin; + options?: any; + +} diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 89169e0e2e..0866db9f6f 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -11,7 +11,9 @@ import {ServerState} from "./server-state"; import {MimosOptions} from "../../../../mimos/index"; import { ServerOptionsCache, ServerEventCriteria, ServerEventsApplication, ServerEventsApplicationObject, - PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, HTTP_METHODS + PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, HTTP_METHODS, ServerMethodOptions, ServerMethod, + ServerMethodConfigurationObject, + Plugin, } from "hapi"; import { RequestExtPointFunction, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, @@ -20,10 +22,7 @@ import { import {ServerInjectOptions, ServerInjectResponse} from "./server-inject"; import {RequestRoute} from "../request/request-route"; import {ServerAuth, ServerAuthConfig} from "./server-auth"; - -export interface ServerMethod { - // (...args: any[], ttl?: number): any; -} +import {ServerRegisterPluginObject, ServerRegisterOptions} from "./server-register"; /** * The server object is the main application container. The server manages all incoming requests along with all @@ -524,7 +523,65 @@ export class Server extends events.EventEmitter { * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ - // method(name: string, method: Function, options?: any): void; + method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; + + /** + * Registers a server method function as described in server.method() using a configuration object where: + * @param methods - an object or an array of objects where each one contains: + * * name - the method name. + * * method - the method function. + * * options - (optional) settings. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) + */ + method(methods: ServerMethodConfigurationObject): void; + method(methods: ServerMethodConfigurationObject[]): void; + + /** + * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: + * @param relativeTo - the path prefix added to any relative file path starting with '.'. + * @return Return value: none. + * Note that setting a path within a plugin only applies to resources accessed by plugin methods. If no path is set, the server default route configuration files.relativeTo settings is used. The path only applies to routes added after it has been set. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto) + */ + path(relativeTo: string): void; + + /** + * Registers a plugin where: + * @param plugins - one or an array of: + * * a plugin object. + * * an object with the following: + * * * plugin - a plugin object. + * * * options - (optional) options passed to the plugin during registration. + * * * once, routes - (optional) plugin-specific registration options as defined below. + * @paramoptions - (optional) registration options (different from the options passed to the registration function): + * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. + * * routes - modifiers applied to each route added by the plugin: + * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. + * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) + */ + register(plugins: Plugin | ServerRegisterPluginObject): void; + register(plugins: Plugin | ServerRegisterPluginObject, options: ServerRegisterOptions): void; + register(plugins: Plugin[] | ServerRegisterPluginObject[]): void; + register(plugins: Plugin[] | ServerRegisterPluginObject[], options: ServerRegisterOptions): void; + + /** + * Adds a route where: + * @param route - a route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * @return Return value: none. + * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ + route(route: any): void; // TODO needs to be implemented. Depends of the route options TODO as well. + @@ -545,6 +602,4 @@ export class Server extends events.EventEmitter { */ start(): void; - - } diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index fa8569c974..e6ec85e659 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -41,9 +41,11 @@ export * from './definitions/server/server-events' export * from './definitions/server/server-ext' export * from './definitions/server/server-info' export * from './definitions/server/server-inject' +export * from './definitions/server/server-method' export * from './definitions/server/server-options' export * from './definitions/server/server-options-cache' export * from './definitions/server/server-realm' +export * from './definitions/server/server-register' export * from './definitions/server/server-state' export * from './definitions/server/server-state-options' From 55e66bcf7d8eb112071087ced4f60cf145b88989 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Tue, 28 Nov 2017 21:44:54 -0300 Subject: [PATCH 20/79] Creating namespace Lifecycle and moving FailAction to inside. --- .../v17/definitions/util/fail-action.d.ts | 4 -- .../hapi/v17/definitions/util/lifecycle.d.ts | 63 ++++++++++++------- 2 files changed, 39 insertions(+), 28 deletions(-) delete mode 100644 types/hapi/v17/definitions/util/fail-action.d.ts diff --git a/types/hapi/v17/definitions/util/fail-action.d.ts b/types/hapi/v17/definitions/util/fail-action.d.ts deleted file mode 100644 index 7b2eb4c4b8..0000000000 --- a/types/hapi/v17/definitions/util/fail-action.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -// 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/lifecycle.d.ts b/types/hapi/v17/definitions/util/lifecycle.d.ts index 9dba7980d4..41864a6bdf 100644 --- a/types/hapi/v17/definitions/util/lifecycle.d.ts +++ b/types/hapi/v17/definitions/util/lifecycle.d.ts @@ -1,28 +1,43 @@ -/** - * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: - * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods - * provided by the developer and executed by the framework. - * Each lifecycle method is a function with the signature await function(request, h, [err]) where: - * * request - the request object. - * * h - the response toolkit the handler must call to set a response and return control back to the framework. - * * err - an error object availble only when the method is used as a failAction value. - */ -export interface LifecycleMethod { +export namespace Lifecycle { - // TODO need to be implemented. Ideally with Generics types. + /** + * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps: + * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecyle methods + * provided by the developer and executed by the framework. + * Each lifecycle method is a function with the signature await function(request, h, [err]) where: + * * request - the request object. + * * h - the response toolkit the handler must call to set a response and return control back to the framework. + * * err - an error object availble only when the method is used as a failAction value. + */ + export interface LifecycleMethod { + + // TODO needs to be implemented. + + } + + /** + * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns + * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) + */ + export interface LifecycleReturnValue { + + // TODO needs to be implemented. + + } + + /** + * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be configured to perform another action. When supported the failAction option supports the following values: + * * 'error' - return the error object as the response. + * * 'log' - report the error but continue processing the request. + * * 'ignore' - take no action and continue processing the request. + * * a lifecycle method with the signature async function(request, h, err) where: + * * * request - the request object. + * * * h - the response toolkit. + * * * err - the error object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration) + */ + export type FailAction = 'error' | 'log' | 'ignore' | LifecycleMethod; } -/** - * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns - * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) - */ -export interface LifecycleReturnValue { - - - -} - - - From c26417bb5955ef013ea43efe5e21fb27b6d1743c Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Tue, 28 Nov 2017 21:46:35 -0300 Subject: [PATCH 21/79] Reviewing Route types and getting better. Not finished yet. --- .../route/route-options-access-scope.d.ts | 28 +++ .../route/route-options-access.d.ts | 98 +++++---- .../route/route-options-cache.d.ts | 20 +- .../definitions/route/route-options-cors.d.ts | 19 +- .../route/route-options-payload.d.ts | 136 +++++++------ .../definitions/route/route-options-pre.d.ts | 26 +++ .../route/route-options-response.d.ts | 75 ++++--- .../route/route-options-validate.d.ts | 4 +- .../v17/definitions/route/route-options.d.ts | 192 +++++++++++------- 9 files changed, 370 insertions(+), 228 deletions(-) create mode 100644 types/hapi/v17/definitions/route/route-options-access-scope.d.ts create mode 100644 types/hapi/v17/definitions/route/route-options-pre.d.ts diff --git a/types/hapi/v17/definitions/route/route-options-access-scope.d.ts b/types/hapi/v17/definitions/route/route-options-access-scope.d.ts new file mode 100644 index 0000000000..4ed76fe9c6 --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-access-scope.d.ts @@ -0,0 +1,28 @@ +import {RouteOptionsAccessEntity} from "hapi"; + +/** + * 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](https://github.com/hapijs/hapi/blob/master/API.md#route.options.auth.access.scope) or [entity](https://github.com/hapijs/hapi/blob/master/API.md#route.options.auth.access.entity). + */ +export interface RouteOptionsAccessObject { + + /** + * Default value: false (no scope requirements). + * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least one of the scopes defined to access the route. + * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. + * You may also access properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) + */ + scope?: 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) + */ + entity?: RouteOptionsAccessEntity; + +} diff --git a/types/hapi/v17/definitions/route/route-options-access.d.ts b/types/hapi/v17/definitions/route/route-options-access.d.ts index 99d8b0b3cf..8bc175b10a 100644 --- a/types/hapi/v17/definitions/route/route-options-access.d.ts +++ b/types/hapi/v17/definitions/route/route-options-access.d.ts @@ -1,74 +1,104 @@ -export enum AccessEntityEnum { +/** + * 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. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) + */ +export enum RouteOptionsAccessEntity { Any = 'any', User = 'user', - App = 'app', + App = 'app' } -export enum AccessModeEnum { +/** + * 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. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode) + */ +export enum RouteOptionsAccessMode { Required = 'required', Optional = 'optional', Try = 'try', } -export enum AccessPayloadEnum { +/** + * 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). + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload) + */ +export enum RouteOptionsAccessPayload { Required = 'required', Optional = 'optional', } -/** Authentication options */ +/** + * Route Authentication Options + */ export interface RouteOptionsAccess { /** - Default value: none. - An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object must include at least one of scope or entity. + * Default value: none. + * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object must include at least one of scope or entity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess) */ access?: 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}'. + * Default value: false (no scope requirements). + * The application scope required to access the route. Value can be a scope string or an array of scope strings. When authenticated, the credentials object scope property must contain at least one of the scopes defined to access the route. + * If a scope string begins with a + character, that scope is required. If a scope string begins with a ! character, that scope is forbidden. For example, the scope ['!a', '+b', 'c', 'd'] means the incoming request credentials' scope must not include 'a', must include 'b', and must include one of 'c' or 'd'. + * You may also access properties on the request object (query, params, payload, and credentials) to populate a dynamic scope by using the '{' and '}' characters around the property name, such as 'user-{params.id}'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope) */ scope?: 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. + * Default value: 'any'. + * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values: + * * 'any' - the authentication can be on behalf of a user or application. + * * 'user' - the authentication must be on behalf of a user which is identified by the presence of a 'user' attribute in the credentials object returned by the authentication strategy. + * * 'app' - the authentication must be on behalf of an application which is identified by the lack of presence of a user attribute in the credentials object returned by the authentication strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity) */ - entity?: AccessEntityEnum; + entity?: RouteOptionsAccessEntity; /** - Default value: 'required'. - The authentication mode. Available values: - 'required' - authentication is required. - 'optional' - authentication is optional - the request must include valid credentials or no credentials at all. - 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. + * Default value: 'required'. + * The authentication mode. Available values: + * * 'required' - authentication is required. + * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all. + * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode) */ - mode?: AccessModeEnum; + mode?: RouteOptionsAccessMode; /** - 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). + * Default value: false, unless the scheme requires payload authentication. + * If set, the incoming request payload is authenticated after it is processed. Requires a strategy with payload authentication support (e.g. Hawk). Cannot be set to a value other than 'required' when the scheme sets the authentication options.payload to true. + * Available values: + * * false - no payload authentication. + * * 'required' - payload authentication required. + * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload) */ - payload?: false | AccessPayloadEnum; + payload?: false | RouteOptionsAccessPayload; /** - 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. + * Default value: the default strategy set via server.auth.default(). + * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies) */ strategies?: string[]; /** - Default value: the default strategy set via server.auth.default(). - A string strategy names. Cannot be used together with strategies. + * Default value: the default strategy set via server.auth.default(). + * A string strategy names. Cannot be used together with strategies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy) */ strategy?: string; diff --git a/types/hapi/v17/definitions/route/route-options-cache.d.ts b/types/hapi/v17/definitions/route/route-options-cache.d.ts index d3f10044e3..91df550ad4 100644 --- a/types/hapi/v17/definitions/route/route-options-cache.d.ts +++ b/types/hapi/v17/definitions/route/route-options-cache.d.ts @@ -1,15 +1,13 @@ /** - 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. + * Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) */ export type RouteOptionsCache = { privacy?: 'default' | 'public' | 'private'; diff --git a/types/hapi/v17/definitions/route/route-options-cors.d.ts b/types/hapi/v17/definitions/route/route-options-cors.d.ts index c85191db8e..d19e6a5774 100644 --- a/types/hapi/v17/definitions/route/route-options-cors.d.ts +++ b/types/hapi/v17/definitions/route/route-options-cors.d.ts @@ -1,13 +1,14 @@ /** - 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. + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) */ export interface RouteOptionsCors { origin?: string[] | '*'| 'ignore'; diff --git a/types/hapi/v17/definitions/route/route-options-payload.d.ts b/types/hapi/v17/definitions/route/route-options-payload.d.ts index fc5a7b10c4..b7baaac182 100644 --- a/types/hapi/v17/definitions/route/route-options-payload.d.ts +++ b/types/hapi/v17/definitions/route/route-options-payload.d.ts @@ -1,116 +1,122 @@ -import {Dictionary} from "../util/util"; -import {FailAction} from "../util/fail-action"; +import {Dictionary, Lifecycle} from "hapi"; -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', -} +/** + * The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) + */ +export type PayloadOutput = 'data' | 'stream' | 'file'; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) */ export type PayloadCompressionDecoderSettings = any; -/**Determines how the request payload is processed.*/ +/** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ export interface RouteOptionsPayload { /** - Default value: allows parsing of the following mime types: - application/json - application/*+json - application/octet-stream - application/x-www-form-urlencoded - multipart/form-data - text/* - A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed above will not enable them to be parsed, and if parse is true, the request will result in an error response. + * Default value: allows parsing of the following mime types: + * * application/json + * * application/*+json + * * application/octet-stream + * * application/x-www-form-urlencoded + * * multipart/form-data + * * text/* + * A string or an array of strings with the allowed mime types for the endpoint. Use this settings to limit the set of allowed mime types. Note that allowing additional mime types not listed above will not enable them to be parsed, and if parse is true, the request will result in an error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow) */ allow?: string | string[]; /** - Default value: none. - An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. + * Default value: none. + * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) */ compression?: Dictionary; /** - Default value: 'application/json'. - The default content type if the 'Content-Type' request header is missing. + * Default value: 'application/json'. + * The default content type if the 'Content-Type' request header is missing. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype) */ defaultContentType?: string; /** - Default value: 'error' (return a Bad Request (400) error response). - A failAction value which determines how to handle payload parsing errors. + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle payload parsing errors. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction) */ - failAction?: FailAction; + failAction?: Lifecycle.FailAction; /** - Default value: 1048576 (1MB). - Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. + * Default value: 1048576 (1MB). + * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes) */ maxBytes?: number; /** - Default value: none. - Overrides payload processing for multipart requests. Value can be one of: - false - disable multipart processing. - an object with the following required options: - output - same as the output option with an additional value option: - annotated - wraps each multipart part in an object with the following keys: - headers - the part headers. - filename - the part file name. - payload - the processed part payload. + * Default value: none. + * Overrides payload processing for multipart requests. Value can be one of: + * * false - disable multipart processing. + * an object with the following required options: + * * output - same as the output option with an additional value option: + * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this? + * * * * headers - the part headers. + * * * * filename - the part file name. + * * * * payload - the processed part payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart) */ - multipart?: false | PayloadOutputEnum | PayloadMultipartOutputEnum ; + multipart?: false | { + output: PayloadOutput | 'annotated'; + }; /** - Default value: 'data'. - The processed payload format. The value must be one of: - 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw Buffer is returned. - 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser (e.g. pez). - 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. + * Default value: 'data'. + * The processed payload format. The value must be one of: + * * 'data' - the incoming payload is read fully into memory. If parse is true, the payload is parsed (JSON, form-decoded, multipart) based on the 'Content-Type' header. If parse is false, a raw Buffer is returned. + * * 'stream' - the incoming payload is made available via a Stream.Readable interface. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are provided as streams. File streams from a 'multipart/form-data' upload will also have a hapi property containing the filename and headers properties. Note that payload streams for multipart payloads are a synthetic interface created on top of the entire mutlipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the multipart payload in the handler using a streaming parser (e.g. pez). + * * 'file' - the incoming payload is written to temporary file in the directory specified by the uploads settings. If the payload is 'multipart/form-data' and parse is true, field values are presented as text while files are saved to disk. Note that it is the sole responsibility of the application to clean up the files generated by the framework. This can be done by keeping track of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput) */ - output?: PayloadOutputEnum; + output?: PayloadOutput; /** - Default value: none. - A mime type string overriding the 'Content-Type' header value received. + * Default value: none. + * A mime type string overriding the 'Content-Type' header value received. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride) */ override?: string; /** - Default value: true. - Determines if the incoming payload is processed or presented raw. Available values: - true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. - false - the raw payload is returned unmodified. - 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded. + * Default value: true. + * Determines if the incoming payload is processed or presented raw. Available values: + * * true - if the request 'Content-Type' matches the allowed mime types set by allow (for the whole payload as well as parts), the payload is converted into an object when possible. If the format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded. + * * false - the raw payload is returned unmodified. + * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse) */ parse?: boolean | 'gunzip'; /** - Default value: to 10000 (10 seconds). - Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. - Set to false to disable. + * Default value: to 10000 (10 seconds). + * Payload reception timeout in milliseconds. Sets the maximum time allowed for the client to transmit the request payload (body) before giving up and responding with a Request Timeout (408) error response. + * Set to false to disable. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout) */ timeout?: false | number; /** - Default value: os.tmpdir(). - The directory used for writing file uploads. + * Default value: os.tmpdir(). + * The directory used for writing file uploads. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads) */ uploads?: string; } - - - diff --git a/types/hapi/v17/definitions/route/route-options-pre.d.ts b/types/hapi/v17/definitions/route/route-options-pre.d.ts new file mode 100644 index 0000000000..95b458d490 --- /dev/null +++ b/types/hapi/v17/definitions/route/route-options-pre.d.ts @@ -0,0 +1,26 @@ +import {Lifecycle} from "hapi"; + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreArray = RouteOptionsPreAllOptions[]; + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.LifecycleMethod; + +/** + * An object with: + * * method - a lifecycle method. + * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) + */ +export interface RouteOptionsPreObject { + method: Lifecycle.LifecycleMethod; + assign: string; + failAction?: Lifecycle.FailAction; +} + + diff --git a/types/hapi/v17/definitions/route/route-options-response.d.ts b/types/hapi/v17/definitions/route/route-options-response.d.ts index 34293c9117..39db5e4574 100644 --- a/types/hapi/v17/definitions/route/route-options-response.d.ts +++ b/types/hapi/v17/definitions/route/route-options-response.d.ts @@ -1,67 +1,82 @@ -import {FailAction} from "../util/fail-action"; +import {Lifecycle, Dictionary} from "hapi"; +import {ValidationOptions} from "joi"; +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode) + */ export enum EmptyStatusCode { HTTP_200 = 200, HTTP_204 = 204, } -/**Processing rules for the outgoing response.*/ +/** + * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) + */ export interface RouteOptionsResponse { /** - Default value: 200. - The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the response status code will remain 200 throughout the request lifecycle unless manually set). + * Default value: 200. + * The default HTTP status code when the payload is considered empty. Value can be 200 or 204. Note that a 200 status code is converted to a 204 only at the time of response transmission (the response status code will remain 200 throughout the request lifecycle unless manually set). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode) */ emptyStatusCode?: 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. + * Default value: 'error' (return an Internal Server Error (500) error response). + * A failAction value which defines what to do when a response fails payload validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction) */ - failAction?: FailAction; + failAction?: Lifecycle.FailAction; /** - Default value: false. - If true, applies the validation rule changes to the response payload. + * Default value: false. + * If true, applies the validation rule changes to the response payload. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify) */ modify?: boolean; /** - Default value: none. - joi 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. + * Default value: none. + * [joi](http://github.com/hapijs/joi) options object pass to the validation function. Useful to set global options such as stripUnknown or abortEarly (the complete list is available here). If a custom validation function is defined via schema or status then options can an arbitrary object that will be passed to this function as the second argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions) */ - options?: any; // TODO need to implementation. Here is JOI def. + options?: ValidationOptions; // TODO needs validation /** - Default value: true. - If false, payload range support is disabled. + * Default value: true. + * If false, payload range support is disabled. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges) */ ranges?: boolean; /** - Default value: 100 (all responses). - The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. + * Default value: 100 (all responses). + * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample) */ sample?: number; /** - Default value: true (no validation). - The default response payload validation rules (for all non-error responses) expressed as one of: - true - any payload allowed (no validation). - false - no payload allowed. - a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function. - a validation function using the signature async function(value, options) where: - value - the pending response payload. - options - The options along with the request context ({ headers, params, query, payload, app, auth }). - if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error output.payload. If an error is thrown, the error is processed according to failAction. + * Default value: true (no validation). + * The default response payload validation rules (for all non-error responses) expressed as one of: + * * true - any payload allowed (no validation). + * * false - no payload allowed. + * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function. + * * a validation function using the signature async function(value, options) where: + * * * value - the pending response payload. + * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }). + * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error output.payload. If an error is thrown, the error is processed according to failAction. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema) */ - schema?: boolean | any; // TODO need to implementation. Here is JOI and more. + schema?: boolean | ValidationOptions | ((value: any, options: any) => Function); // TODO it must be better /** - 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. + * Default value: none. + * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema. + * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) */ - status?: any; // TODO need to implementation. + status?: Dictionary; // TODO it must be better } diff --git a/types/hapi/v17/definitions/route/route-options-validate.d.ts b/types/hapi/v17/definitions/route/route-options-validate.d.ts index 7b3c6afda4..4e4a8351cd 100644 --- a/types/hapi/v17/definitions/route/route-options-validate.d.ts +++ b/types/hapi/v17/definitions/route/route-options-validate.d.ts @@ -1,4 +1,4 @@ -import {FailAction} from "../util/fail-action"; +import {Lifecycle} from "hapi"; /** Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. @@ -16,7 +16,7 @@ export interface RouteOptionsValidate { 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; + failAction?: Lifecycle.FailAction; /** Default value: true (no validation). diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index db012ed3ce..7b62764f0f 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -5,9 +5,11 @@ 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"; +import {Json} from "../util/util"; +import {RouteOptionsPreArray} from "./route-options-pre"; +import {Lifecycle} from "hapi"; /** * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) @@ -15,152 +17,189 @@ import {PluginSpecificConfiguration} from "../plugin/plugin"; */ export type RouteCompressionEncoderSettings = any; -/** Each route can be customized to change the default behavior of the request lifecycle. */ +/** + * Each route can be customized to change the default behavior of the request lifecycle. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options) + */ export interface RouteOptions { - /** Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead.*/ + /** + * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) + */ app?: any; /** - Route authentication configuration. Value can be: - false to disable authentication if a default strategy is set. - a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode. - an authentication configuration object. + * Route authentication configuration. Value can be: + * false to disable authentication if a default strategy is set. + * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode. + * an authentication configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) */ auth?: false | string | RouteOptionsAccess; /** - Default value: null. - An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. + * Default value: null. + * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind) */ bind?: any; /** - Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. + * Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. + * If the route method is 'GET', the route can be configured to include HTTP caching directives in the response. Caching can be customized using an object with the following options: + * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are: + * * * 'default' - no privacy flag. + * * * 'public' - mark the response as suitable for public caching. + * * * 'private' - mark the response as suitable only for private caching. + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Cannot be used together with expiresIn. + * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive. + * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled. + * The default Cache-Control: no-cache header can be disabled by setting cache to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache) */ cache?: false | RouteOptionsCache; /** - An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. + * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) */ compression?: Dictionary; /** - Default value: false (no CORS headers). + * Default value: false (no CORS headers). + * The Cross-Origin Resource Sharing protocol allows browsers to make cross-origin API calls. CORS is required by web applications running inside a browser which are loaded from a different domain than the API server. To enable, set cors to true, or to an object with the following options: + * * origin - an array of allowed origin servers strings ('Access-Control-Allow-Origin'). The array can contain any combination of fully qualified origins along with origin strings containing a wildcard '*' character, or a single '*' origin string. If set to 'ignore', any incoming Origin header is ignored (present or not) and the 'Access-Control-Allow-Origin' header is set to '*'. Defaults to any origin ['*']. + * * maxAge - number of seconds the browser should cache the CORS response ('Access-Control-Max-Age'). The greater the value, the longer it will take before the browser checks for changes in policy. Defaults to 86400 (one day). + * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match']. + * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place. + * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization']. + * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place. + * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors) */ cors?: false | RouteOptionsCors; /** - Default value: none. - Route description used for generating documentation (string). - This setting is not available when setting server route defaults using server.options.routes. + * Default value: none. + * Route description used for generating documentation (string). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription) */ description?: string; /** - Default value: none. - Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the server.ext(events) event argument. + * Default value: none. + * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the server.ext(events) event argument. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext) */ - ext?: any; //TODO need to review and rewrite this definition + ext?: any; //TODO need to review and rewrite this definition // I saw again and I keep not understanding. /** - Default value: { relativeTo: '.' }. - Defines the behavior for accessing files: - relativeTo - determines the folder relative paths are resolved against. + * Default value: { relativeTo: '.' }. + * Defines the behavior for accessing files: + * * relativeTo - determines the folder relative paths are resolved against. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles) */ files?: { relativeTo: string; } /** - Default value: none. - The route handler function performs the main business logic of the route and sets the 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. + * Default value: none. + * The route handler function performs the main business logic of the route and sets the response. handler can be assigned: + * * a lifecycle method. + * * an object with a single property using the name of a handler type registred with the server.handler() method. The matching property value is passed as options to the registered handler generator. + * Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) */ - handler?: any; //TODO need to review and rewrite this definition + handler?: Lifecycle.LifecycleMethod | Object; //TODO need to review /** - 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. + * Default value: none. + * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid) */ id?: string; /** - Default value: false. - If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should not be accessible to the outside world. + * Default value: false. + * If true, the route cannot be accessed through the HTTP listener but only through the server.inject() interface with the allowInternals option set to true. Used for internal routes that should not be accessible to the outside world. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal) */ isInternal?: boolean; /** - Default value: none. - Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following: - replacer - the replacer function or array. Defaults to no action. - space - number of spaces to indent nested object keys. Defaults to no indentation. - suffix - string suffix added after conversion to JSON string. Defaults to no suffix. - escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. - - TODO this definition in v16 is a bit confuse for me. Need review and maybe rewrite. + * Default value: none. + * Optional arguments passed to JSON.stringify() when converting an object or error response to a string payload or escaping it after stringification. Supports the following: + * * replacer - the replacer function or array. Defaults to no action. + * * space - number of spaces to indent nested object keys. Defaults to no indentation. + * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix. + * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) */ - json?: { - replaces?: any | any[]; - space?: number | string; - suffix?: string; - escape?: boolean; // TODO boolean only? - }; + json?: Json.StringifyArguments; /** - Default value: none. - Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. - For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Cannot be used with stream responses. - The 'Content-Type' response header is set to 'text/javascript' and the 'X-Content-Type-Options' response header is set to 'nosniff', and will override those headers even if explicitly set by response.type(). + * Default value: none. + * Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload. + * For example, if the value is 'callback', a request comes in with 'callback=me', and the JSON response is '{ "a":"b" }', the payload will be 'me({ "a":"b" });'. Cannot be used with stream responses. + * The 'Content-Type' response header is set to 'text/javascript' and the 'X-Content-Type-Options' response header is set to 'nosniff', and will override those headers even if explicitly set by response.type(). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjsonp) */ jsonp?: string; /** - Default value: { collect: false }. - Request logging options: - collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs. + * Default value: { collect: false }. + * Request logging options: + * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog) */ - log?: boolean; + log?: { + collect: boolean; + } /** - Default value: none. - Route notes used for generating documentation (string or array of strings). - This setting is not available when setting server route defaults using server.options.routes. + * Default value: none. + * Route notes used for generating documentation (string or array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes) */ notes?: string | string[]; - /** Determines how the request payload is processed. */ + /** + * Determines how the request payload is processed. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload) + */ payload?: RouteOptionsPayload; /** - Default value: {}. - Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. + * Default value: {}. + * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) */ - plugins?: PluginSpecificConfiguration; + plugins?: Dictionary; /** - Default value: none. - The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared ascross routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). - pre is assigned an ordered array of methods which are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. - pre can be assigned a mixed array of: - an array containing the elements listed below, which are executed in parallel. - an object with: - method - a lifecycle method. - assign - key name used to assign the response of the method to in request.pre and request.preResponses. - failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. - a method function - same as including an object with a single method key. - Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other lifecycle methods. + * Default value: none. + * The pre option allows defining methods for performing actions before the handler is called. These methods allow breaking the handler logic into smaller, reusable components that can be shared ascross routes, as well as provide a cleaner error handling of prerequisite operations (e.g. load required reference data from a database). + * pre is assigned an ordered array of methods which are called serially in order. If the pre array contains another array of methods as one of its elements, those methods are called in parallel. Note that during parallel execution, if any of the methods error, return a takeover response, or abort signal, the other parallel methods will continue to execute but will be ignored once completed. + * pre can be assigned a mixed array of: + * * an array containing the elements listed below, which are executed in parallel. + * * an object with: + * * * method - a lifecycle method. + * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses. + * * * failAction - A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. + * * a method function - same as including an object with a single method key. + * Note that pre-handler methods do not behave the same way other lifecycle methods do when a value is returned. Instead of the return value becoming the new response payload, the value is used to assign the corresponding request.pre and request.preResponses properties. Otherwise, the handling of errors, takeover response response, or abort signal behave the same as any other lifecycle methods. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) */ - pre?: 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. + pre?: RouteOptionsPreArray; /** * Processing rules for the outgoing response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) */ response?: RouteOptionsResponse; @@ -199,7 +238,7 @@ export interface RouteOptions { */ state?: { parse?: boolean; - failAction?: FailAction; + failAction?: Lifecycle.FailAction; } /** @@ -226,5 +265,4 @@ export interface RouteOptions { */ validate?: RouteOptionsValidate; - } From 00b0f483af93b7234fafe9b5cc355114f3e6dbe1 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Tue, 28 Nov 2017 21:48:32 -0300 Subject: [PATCH 22/79] Added Json namespace. Cloned to v16 types. --- types/hapi/v17/definitions/util/util.d.ts | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/types/hapi/v17/definitions/util/util.d.ts b/types/hapi/v17/definitions/util/util.d.ts index f1c6d0c39e..ae473d89ac 100644 --- a/types/hapi/v17/definitions/util/util.d.ts +++ b/types/hapi/v17/definitions/util/util.d.ts @@ -5,3 +5,34 @@ export interface Dictionary { export type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_LOWERCASE; export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; + +/** + * Json properties + */ +export namespace Json { + + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; + + /** + * Any value greater than 10 is truncated. + */ + export type StringifySpace = number | string; + + /** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + export interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + /** tring suffix added after conversion to JSON string. Defaults to no suffix. **/ + suffix?: string; + /** calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. **/ + escape?: boolean; + } + +} From d75c57e480257aac4fd000d2772b292ea4531c81 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Tue, 28 Nov 2017 21:49:02 -0300 Subject: [PATCH 23/79] Using new Lifecycle namespace. --- types/hapi/v17/definitions/server/server-auth-scheme.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts index db21ed6111..ea0b7817d0 100644 --- a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts +++ b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts @@ -1,7 +1,7 @@ import {Server} from "./server"; -import {LifecycleReturnValue} from "../util/lifecycle"; import {ResponseToolkit} from "../response/response-toolkit"; import {Request} from "../request/request"; +import {Lifecycle} from "hapi"; /** * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. @@ -39,7 +39,7 @@ export interface ServerAuthSchemeObject { * @param h the ResponseToolkit * @return the LifecycleReturnValue */ - authenticate(request: Request, h: ResponseToolkit): LifecycleReturnValue; + authenticate(request: Request, h: ResponseToolkit): Lifecycle.LifecycleReturnValue; /** * A lifecycle method to authenticate the request payload. @@ -50,7 +50,7 @@ export interface ServerAuthSchemeObject { * @param h the ResponseToolkit * @return the LifecycleReturnValue */ - payload?(request: Request, h: ResponseToolkit): LifecycleReturnValue; + payload?(request: Request, h: ResponseToolkit): Lifecycle.LifecycleReturnValue; /** * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. @@ -58,7 +58,7 @@ export interface ServerAuthSchemeObject { * @param h the ResponseToolkit * @return the LifecycleReturnValue */ - response?(request: Request, h: ResponseToolkit): LifecycleReturnValue; + response?(request: Request, h: ResponseToolkit): Lifecycle.LifecycleReturnValue; /** * An object with the following keys: From 81b7abd1d49ce724540e4bec913fcf6149875385 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Tue, 28 Nov 2017 21:49:37 -0300 Subject: [PATCH 24/79] Solved some TODO's --- types/hapi/v17/definitions/server/server.d.ts | 46 ++++++++----------- 1 file changed, 18 insertions(+), 28 deletions(-) diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 0866db9f6f..abe6d8c313 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -13,7 +13,7 @@ import { ServerOptionsCache, ServerEventCriteria, ServerEventsApplication, ServerEventsApplicationObject, PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, HTTP_METHODS, ServerMethodOptions, ServerMethod, ServerMethodConfigurationObject, - Plugin, + Plugin, ResponseToolkit, Dictionary, } from "hapi"; import { RequestExtPointFunction, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, @@ -32,9 +32,13 @@ export class Server extends events.EventEmitter { /** Creates a new server object where: - @param options - (optional) a server configuration object. */ constructor(); + + /** + Creates a new server object where: + @param options server configuration object. + */ constructor(options: ServerOptions); /** @@ -58,9 +62,9 @@ export class Server extends events.EventEmitter { */ readonly decorations: { request: Request, - toolkit: any, // TODO Request Toolkit (https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) needs to be implemented. + toolkit: ResponseToolkit, server: Server - } + }; /** * Register custom application events where: @@ -98,7 +102,6 @@ export class Server extends events.EventEmitter { emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any): void; /** - *[See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) * Subscribe to an event where: * @param criteria - the subscription criteria which must be one of: * * event name string which can be any of the built-in server events @@ -106,6 +109,13 @@ export class Server extends events.EventEmitter { * * a criteria object * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) + * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) + * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) + * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) + * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) + * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) */ on(criteria: string, listener: Function): void; on(criteria: ServerEventsApplicationObject, listener: Function): void; @@ -156,26 +166,7 @@ export class Server extends events.EventEmitter { */ hasListeners(name: string): boolean; - /** - * The 'log' event type emits internal server events generated by the framework as well as application events - * logged with server.log(). - * The 'log' event handler uses the function signature function(event, tags) where: - * @param event - an object with the following properties: - * * timestamp - the event timestamp. - * * tags - an array of tags identifying the event (e.g. ['error', 'http']). - * * channel - set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log(). - * * data - event-specific information. Available when event data was provided and is not an error. Errors are passed via error. - * * error - the error object related to the event if applicable. Cannot appear together with data. - * @param tags - an object where each event.tag is a key and the value is true. Useful for quick identification of events. - * - */ - - - // TODO not ready yet - - - - } + }; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) @@ -220,8 +211,7 @@ export class Server extends events.EventEmitter { * sever.methods is an object which provides access to the methods registered via server.method() where each * server method name is an object property. */ - //methods: Dictionary; - readonly methods: any; // TODO come back here after implements the server.method() + readonly methods: Dictionary; /** * Provides access to the server MIME database used for setting content-type information. The object must not be @@ -327,7 +317,7 @@ export class Server extends events.EventEmitter { */ provision(options: ServerOptionsCache): void; - } + }; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) From 4098227016919c35cd7ae8fa7705f088dcbade61 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Tue, 28 Nov 2017 21:50:00 -0300 Subject: [PATCH 25/79] Updated with new types. --- types/hapi/v17/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index e6ec85e659..fa2e6cac25 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -26,9 +26,11 @@ export * from './definitions/response/response-toolkit' /** ROUTE */ export * from './definitions/route/route-options' export * from './definitions/route/route-options-access' +export * from './definitions/route/route-options-access-scope' export * from './definitions/route/route-options-cache' export * from './definitions/route/route-options-cors' export * from './definitions/route/route-options-payload' +export * from './definitions/route/route-options-pre' export * from './definitions/route/route-options-response' export * from './definitions/route/route-options-secure' export * from './definitions/route/route-options-validate' @@ -50,6 +52,5 @@ export * from './definitions/server/server-state' export * from './definitions/server/server-state-options' /** UTIL */ -export * from './definitions/util/fail-action' export * from './definitions/util/lifecycle' export * from './definitions/util/util' From 9a5c7a31040a2a74f278bb3c205a5e3c4ae9ec8a Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Tue, 28 Nov 2017 21:57:18 -0300 Subject: [PATCH 26/79] Renamed Lifecycle methods for better understanding. --- .../v17/definitions/route/route-options-pre.d.ts | 4 ++-- types/hapi/v17/definitions/route/route-options.d.ts | 2 +- .../v17/definitions/server/server-auth-scheme.d.ts | 12 ++++++------ types/hapi/v17/definitions/util/lifecycle.d.ts | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/types/hapi/v17/definitions/route/route-options-pre.d.ts b/types/hapi/v17/definitions/route/route-options-pre.d.ts index 95b458d490..1cd980fc16 100644 --- a/types/hapi/v17/definitions/route/route-options-pre.d.ts +++ b/types/hapi/v17/definitions/route/route-options-pre.d.ts @@ -8,7 +8,7 @@ export type RouteOptionsPreArray = RouteOptionsPreAllOptions[]; /** * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) */ -export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.LifecycleMethod; +export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreObject[] | Lifecycle.Method; /** * An object with: @@ -18,7 +18,7 @@ export type RouteOptionsPreAllOptions = RouteOptionsPreObject | RouteOptionsPreO * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre) */ export interface RouteOptionsPreObject { - method: Lifecycle.LifecycleMethod; + method: Lifecycle.Method; assign: string; failAction?: Lifecycle.FailAction; } diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index 7b62764f0f..c1fc5267a8 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -114,7 +114,7 @@ export interface RouteOptions { * Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) */ - handler?: Lifecycle.LifecycleMethod | Object; //TODO need to review + handler?: Lifecycle.Method | Object; //TODO need to review /** * Default value: none. diff --git a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts index ea0b7817d0..52a7b732a3 100644 --- a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts +++ b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts @@ -37,9 +37,9 @@ export interface ServerAuthSchemeObject { * * h.unauthenticated() - indicate request failed to authenticate. * @param request the request object. * @param h the ResponseToolkit - * @return the LifecycleReturnValue + * @return the Lifecycle.ReturnValue */ - authenticate(request: Request, h: ResponseToolkit): Lifecycle.LifecycleReturnValue; + authenticate(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; /** * A lifecycle method to authenticate the request payload. @@ -48,17 +48,17 @@ export interface ServerAuthSchemeObject { * authentication may still be successful if the route auth.payload configuration is set to 'optional'. * @param request the request object. * @param h the ResponseToolkit - * @return the LifecycleReturnValue + * @return the Lifecycle.ReturnValue */ - payload?(request: Request, h: ResponseToolkit): Lifecycle.LifecycleReturnValue; + payload?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; /** * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written. * @param request the request object. * @param h the ResponseToolkit - * @return the LifecycleReturnValue + * @return the Lifecycle.ReturnValue */ - response?(request: Request, h: ResponseToolkit): Lifecycle.LifecycleReturnValue; + response?(request: Request, h: ResponseToolkit): Lifecycle.ReturnValue; /** * An object with the following keys: diff --git a/types/hapi/v17/definitions/util/lifecycle.d.ts b/types/hapi/v17/definitions/util/lifecycle.d.ts index 41864a6bdf..6501e8edd1 100644 --- a/types/hapi/v17/definitions/util/lifecycle.d.ts +++ b/types/hapi/v17/definitions/util/lifecycle.d.ts @@ -9,7 +9,7 @@ export namespace Lifecycle { * * h - the response toolkit the handler must call to set a response and return control back to the framework. * * err - an error object availble only when the method is used as a failAction value. */ - export interface LifecycleMethod { + export interface Method { // TODO needs to be implemented. @@ -20,7 +20,7 @@ export namespace Lifecycle { * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) */ - export interface LifecycleReturnValue { + export interface ReturnValue { // TODO needs to be implemented. @@ -37,7 +37,7 @@ export namespace Lifecycle { * * * err - the error object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration) */ - export type FailAction = 'error' | 'log' | 'ignore' | LifecycleMethod; + export type FailAction = 'error' | 'log' | 'ignore' | Method; } From c8874b4a152f701f098151c0b04509856e87f5eb Mon Sep 17 00:00:00 2001 From: rsouza Date: Wed, 29 Nov 2017 15:23:43 -0300 Subject: [PATCH 27/79] Reviewing Routes type implementation. --- .../route/route-options-secure.d.ts | 53 ++++---- .../route/route-options-validate.d.ts | 118 +++++++++--------- .../v17/definitions/route/route-options.d.ts | 85 +++++++------ 3 files changed, 138 insertions(+), 118 deletions(-) diff --git a/types/hapi/v17/definitions/route/route-options-secure.d.ts b/types/hapi/v17/definitions/route/route-options-secure.d.ts index 6c2380fcc0..8c68f25dfe 100644 --- a/types/hapi/v17/definitions/route/route-options-secure.d.ts +++ b/types/hapi/v17/definitions/route/route-options-secure.d.ts @@ -1,33 +1,34 @@ /** - 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'. + * Default value: false (security headers disabled). + * Sets common security headers. To enable, set security to true or to an object with the following options: + * * hsts - controls the 'Strict-Transport-Security' header, where: + * * * true - the header will be set to max-age=15768000. This is the default value. + * * * a number - the maxAge parameter will be set to the provided value. + * * * an object with the following fields: + * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. + * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. + * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + * * xframe - controls the 'X-Frame-Options' header, where: + * * * true - the header will be set to 'DENY'. This is the default value. + * * * 'deny' - the headers will be set to 'DENY'. + * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. + * * * an object for specifying the 'allow-from' rule, where: + * * * * rule - one of: + * * * * * 'deny' + * * * * * 'sameorigin' + * * * * * 'allow-from' + * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. + * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. + * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) */ export interface RouteOptionsSecureObject { hsts?: boolean | number | { - maxAge?: number; - includeSubdomains?: boolean; - preload?: boolean; + maxAge: number; + includeSubdomains: boolean; + preload: boolean; }; xframe?: true | 'deny' | 'sameorigin' | { rule: 'deny' | 'sameorigin' | 'allow-from'; diff --git a/types/hapi/v17/definitions/route/route-options-validate.d.ts b/types/hapi/v17/definitions/route/route-options-validate.d.ts index 4e4a8351cd..6fba5dfc67 100644 --- a/types/hapi/v17/definitions/route/route-options-validate.d.ts +++ b/types/hapi/v17/definitions/route/route-options-validate.d.ts @@ -1,86 +1,92 @@ import {Lifecycle} from "hapi"; +import {ValidationOptions} from "joi"; /** - Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. - Request input validation rules for various request components. + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) */ export interface RouteOptionsValidate { /** - Default value: none. - An optional object with error fields copied into every validation error response. + * Default value: none. + * An optional object with error fields copied into every validation error response. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields) */ errorFields?: 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. + * Default value: 'error' (return a Bad Request (400) error response). + * A failAction value which determines how to handle failed validations. When set to a function, the err argument includes the type of validation error under err.output.payload.validation.source. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction) */ failAction?: Lifecycle.FailAction; /** - Default value: true (no validation). - Validation rules for incoming request headers: - true - any headers allowed (no validation performed). - a joi validation object. - a validation function using the signature async function(value, options) where: - value - the request.headers object containing the request headers. - options - options. - if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error is thrown, the error is handled according to failAction. - Note that all header field names must be in lowercase to match the headers normalized by node. + * Default value: true (no validation). + * Validation rules for incoming request headers: + * * true - any headers allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.headers object containing the request headers. + * * * options - options. + * * * if a value is returned, the value is used as the new request.headers value and the original value is stored in request.orig.headers. Otherwise, the headers are left unchanged. If an error is thrown, the error is handled according to failAction. + * Note that all header field names must be in lowercase to match the headers normalized by node. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) */ - headers?: boolean | any; // TODO need to implementation. Here is JOI and more. + headers?: boolean | ValidationOptions | ((value: any, option: any) => Function); /** - 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). + * Default value: none. + * An options object passed to the joi rules or the custom validation methods. Used for setting global options such as stripUnknown or abortEarly (the complete list is available here). + * If a custom validation function (see headers, params, query, or payload above) is defined then options can an arbitrary object that will be passed to this function as the second parameter. + * The values of the other inputs (i.e. headers, query, params, payload, app, and auth) are added to the options object under the validation context (accessible in rules as Joi.ref('$query.key')). + * Note that validation is performed in order (i.e. headers, params, query, and payload) and if type casting is used (e.g. converting a string to a number), the value of inputs not yet validated will reflect the raw, unvalidated and unmodified values. + * If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the individual route settings override the routes defaults (the rules are not merged). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) */ - options?: any; // TODO need to be implementation + options?: ValidationOptions | Object; // TODO need review /** - 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. + * Default value: true (no validation). + * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where: + * * true - any path parameter value allowed (no validation performed). + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.params object containing the request path parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.params value and the original value is stored in request.orig.params. Otherwise, the path parameters are left unchanged. If an error is thrown, the error is handled according to failAction. + * Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) */ - params?: boolean | any; // TODO need to implementation. Here is JOI and more. + params?: boolean | ValidationOptions | ((value: any, option: any) => Function); // TODO need review /** - 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. + * Default value: true (no validation). + * Validation rules for incoming request payload (request body), where: + * * true - any payload allowed (no validation performed). false - no payload allowed. + * * a joi validation object. Note that empty payloads are represented by a null value. If a validation schema is provided and empty payload are allowed, the schema must be explicitly defined by setting the rule to a joi schema with null allowed (e.g. Joi.object({ keys here }).allow(null)). + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.payload value and the original value is stored in request.orig.payload. Otherwise, the payload is left unchanged. If an error is thrown, the error is handled according to failAction. + * Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well as the significant performance cost of validating large amounts of data. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) */ - payload?: boolean | any; // TODO need to implementation. Here is JOI and more. + payload?: boolean | ValidationOptions | ((value: any, option: any) => Function); // TODO need review /** - 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. + * Default value: true (no validation). + * Validation rules for incoming request URI query component (the key-value part of the URI between '?' and '#'). The query is parsed into its individual key-value pairs, decoded, and stored in request.query prior to validation. Where: + * * true - any query parameter value allowed (no validation performed). false - no query parameter value allowed. + * * a joi validation object. + * * a validation function using the signature async function(value, options) where: + * * * value - the request.query object containing the request query parameters. + * * * options - options. + * if a value is returned, the value is used as the new request.query value and the original value is stored in request.orig.query. Otherwise, the query parameters are left unchanged. If an error is thrown, the error is handled according to failAction. + * Note that changes to the query parameters will not be reflected in request.url. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) */ - query?: boolean | any; // TODO need to implementation. Here is JOI and more. + query?: boolean | ValidationOptions | ((value: any, option: any) => Function); // TODO need review } diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index c1fc5267a8..e01d1a4cd3 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -204,37 +204,39 @@ export interface RouteOptions { 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'. + * Default value: false (security headers disabled). + * Sets common security headers. To enable, set security to true or to an object with the following options: + * * hsts - controls the 'Strict-Transport-Security' header, where: + * * * true - the header will be set to max-age=15768000. This is the default value. + * * * a number - the maxAge parameter will be set to the provided value. + * * * an object with the following fields: + * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000. + * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header. + * * * * preload - a boolean specifying whether to add the 'preload' flag (used to submit domains inclusion in Chrome's HTTP Strict Transport Security (HSTS) preload list) to the header. + * * xframe - controls the 'X-Frame-Options' header, where: + * * * true - the header will be set to 'DENY'. This is the default value. + * * * 'deny' - the headers will be set to 'DENY'. + * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'. + * * * an object for specifying the 'allow-from' rule, where: + * * * * rule - one of: + * * * * * 'deny' + * * * * * 'sameorigin' + * * * * * 'allow-from' + * * * * source - when rule is 'allow-from' this is used to form the rest of the header, otherwise this field is ignored. If rule is 'allow-from' but source is unset, the rule will be automatically changed to 'sameorigin'. + * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'. + * Note: this setting can create a security vulnerability in versions of Internet Exploere below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively support old versions of IE, it may be wise to explicitly set this flag to false. + * * noOpen - boolean controlling the 'X-Download-Options' header for Internet Explorer, preventing downloads from executing in your context. Defaults to true setting the header to 'noopen'. + * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity) */ security?: RouteOptionsSecure; /** - Default value: { parse: true, failAction: 'error' }. - HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following options: - parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. - failAction - A failAction value which determines how to handle cookie parsing errors. Defaults to 'error' (return a Bad Request (400) error response). + * Default value: { parse: true, failAction: 'error' }. + * HTTP state management (cookies) allows the server to store information on the client which is sent back to the server with every request (as defined in RFC 6265). state supports the following options: + * parse - determines if incoming 'Cookie' headers are parsed and stored in the request.state object. + * failAction - A failAction value which determines how to handle cookie parsing errors. Defaults to 'error' (return a Bad Request (400) error response). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate) */ state?: { parse?: boolean; @@ -242,26 +244,37 @@ export interface RouteOptions { } /** - 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. + * Default value: none. + * Route tags used for generating documentation (array of strings). + * This setting is not available when setting server route defaults using server.options.routes. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags) */ tags?: string[]; /** - Default value: { server: false }. - Timeouts for processing durations. + * Default value: { server: false }. + * Timeouts for processing durations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout) */ timeout?: { - /** response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming client request before giving up and responding with a Service Unavailable (503) error response. Disabled by default (false). */ + + /** + * Response timeout in milliseconds. Sets the maximum time allowed for the server to respond to an incoming request before giving up and responding with a Service Unavailable (503) error response. + */ server?: boolean | number; - /** 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. */ + + /** + * Default value: none (use node default of 2 minutes). + * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts. + */ socket?: boolean | number; + }; /** - Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. - Request input validation rules for various request components. + * Default value: { headers: true, params: true, query: true, payload: true, failAction: 'error' }. + * Request input validation rules for various request components. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate) */ validate?: RouteOptionsValidate; From 12d64487d41076f45d1b3181561ff40765731397 Mon Sep 17 00:00:00 2001 From: rsouza Date: Wed, 29 Nov 2017 16:33:59 -0300 Subject: [PATCH 28/79] Added some Lifecycle definitions. --- .../hapi/v17/definitions/util/lifecycle.d.ts | 25 +++++++++++++------ 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/types/hapi/v17/definitions/util/lifecycle.d.ts b/types/hapi/v17/definitions/util/lifecycle.d.ts index 6501e8edd1..3cf2840199 100644 --- a/types/hapi/v17/definitions/util/lifecycle.d.ts +++ b/types/hapi/v17/definitions/util/lifecycle.d.ts @@ -1,3 +1,8 @@ +import * as Boom from "../../../../boom/index"; +import * as stream from "stream"; +import {ResponseToolkit, Request} from "hapi"; + + export namespace Lifecycle { /** @@ -10,9 +15,8 @@ export namespace Lifecycle { * * err - an error object availble only when the method is used as a failAction value. */ export interface Method { - - // TODO needs to be implemented. - + (request: Request, h: ResponseToolkit): void; + (request: Request, h: ResponseToolkit, err: Error): void; } /** @@ -20,11 +24,16 @@ export namespace Lifecycle { * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) */ - export interface ReturnValue { - - // TODO needs to be implemented. - - } + export type ReturnValue = ReturnValueTypes | (Promise); + export type ReturnValueTypes = + (null | undefined | string | number | boolean) | + (Buffer) | + (Error | Boom.BoomError) | + (stream.Stream) | + (Object | Object[]) | + // a toolkit signal: + // a toolkit method response: + any; // TODO need review /** * Various configuration options allows defining how errors are handled. For example, when invalid payload is received or malformed cookie, instead of returning an error, the framework can be configured to perform another action. When supported the failAction option supports the following values: From 3eb657d0308fa679dd189bab11f615ab6bb035e3 Mon Sep 17 00:00:00 2001 From: rsouza Date: Wed, 29 Nov 2017 16:37:04 -0300 Subject: [PATCH 29/79] Fix. Each lifecycle method must return a value or a promise. --- types/hapi/v17/definitions/util/lifecycle.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/hapi/v17/definitions/util/lifecycle.d.ts b/types/hapi/v17/definitions/util/lifecycle.d.ts index 3cf2840199..568b45b181 100644 --- a/types/hapi/v17/definitions/util/lifecycle.d.ts +++ b/types/hapi/v17/definitions/util/lifecycle.d.ts @@ -15,8 +15,8 @@ export namespace Lifecycle { * * err - an error object availble only when the method is used as a failAction value. */ export interface Method { - (request: Request, h: ResponseToolkit): void; - (request: Request, h: ResponseToolkit, err: Error): void; + (request: Request, h: ResponseToolkit): ReturnValue; + (request: Request, h: ResponseToolkit, err: Error): ReturnValue; } /** From 304bf7ff45113d70fc07dc2c85ac3f1b43d69fbe Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 30 Nov 2017 11:26:55 -0300 Subject: [PATCH 30/79] Reviewed Response declarations. --- .../definitions/response/response-object.d.ts | 157 +++++++++--------- .../response/response-settings.d.ts | 30 ++-- .../response/response-toolkit.d.ts | 25 ++- 3 files changed, 108 insertions(+), 104 deletions(-) diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index f30c98eb6e..b913237571 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -2,132 +2,134 @@ import {PluginsStates} from "../plugin/plugin"; import {Dictionary} from "../util/util"; import {ResponseSettings} from "./response-settings"; import {ServerStateCookieOptions} from "../server/server-state-options"; +import * as Podium from "podium"; +import {Json, Lifecycle} from "hapi"; /** + * Object where: + * * append - if true, the value is appended to any existing header value using separator. Defaults to false. + * * separator - string used as separator when appending to an existing value. Defaults to ','. + * * override - if false, the header value is not set if an existing value present. Defaults to true. + * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) */ export interface ResponseObjectHeaderOptions { - /** 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. + * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle + * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status + * code). In order to customize a response before it is returned, the h.response() method is provided. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object) + * TODO, check extending from Podium is correct. Extending because of "The response object supports the following events" [See docs](https://hapijs.com/api/17.0.1#-responseevents) */ -export interface ResponseObject { +export interface ResponseObject extends Podium { /** - Default value: {}. - Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * Default value: {}. + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp) */ app: 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 (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) */ - events: any; // TODO need to be implemented. I didn't understand yet. + readonly 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. + * Default value: {}. + * An object containing the response headers where each key is a header field name and the value is the string header value or array of string. + * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) */ - headers: Dictionary; + readonly 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. + * Default value: {}. + * Plugin-specific state. Provides a place to store and pass request-level plugin data. plugins is an object where each key is a plugin name and the value is the state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins) */ plugins: PluginsStates; /** - Access: read only. - Object containing the response handling flags. + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) */ - settings: ResponseSettings; + readonly settings: ResponseSettings; /** - Access: read only. - The raw value returned by the lifecycle method. + * The raw value returned by the lifecycle method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource) */ - source: any; // TODO need to be implemented. + readonly source: Lifecycle.ReturnValue; /** - Access: read only. - Default value: 200. + * Default value: 200. + * The HTTP response status code. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode) */ - statusCode: number; + readonly 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. + * A string indicating the type of source with available values: + * * 'plain' - a plain response such as string, number, null, or simple object. + * * 'buffer' - a Buffer. + * * 'stream' - a Stream. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety) */ - variety: 'plain' | 'buffer' | 'stream'; + readonly 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. + * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength) */ 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. + * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri) */ 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. @@ -139,24 +141,23 @@ export interface ResponseObject { * * 'binary' - Alias for 'latin1'. * * 'hex' - Encode each byte as two hexadecimal characters. * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding) */ encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject; /** - * 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) */ - etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject; + etag(tag: string): ResponseObject; + 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. @@ -166,139 +167,129 @@ export interface ResponseObject { * * override - if false, the header value is not set if an existing value present. Defaults to true. * * duplicate - if false, the header value is not modified if the provided value is already included. Does not apply when append is false or if the name is 'set-cookie'. Defaults to true. * @return Return value: the current response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) */ - header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; + header(name: string, value: string): ResponseObject; + 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri) */ 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). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod) */ - replacer(method: any): ResponseObject; // TODO check the method object type. In v16 is a Json.StringifyReplacer + replacer(method: Json.StringifyReplacer): ResponseObject; /** - * 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) */ - state(name: string, value: string, options?: ServerStateCookieOptions): ResponseObject; + state(name: string, value: string): ResponseObject; + 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) */ - unstate(name: string, options?: ServerStateCookieOptions): ResponseObject; + unstate(name: string): ResponseObject; + 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent) */ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable) */ 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 index f695bb7a07..0926878d1c 100644 --- a/types/hapi/v17/definitions/response/response-settings.d.ts +++ b/types/hapi/v17/definitions/response/response-settings.d.ts @@ -1,28 +1,32 @@ +import {Json} from "hapi"; + +/** + * Object containing the response handling flags. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings) + */ export interface ResponseSettings { /** - Defaults value: true. - If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response. + * 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; + readonly passThrough: boolean; /** - Access: read only. - Default value: null (use route defaults). - Override the route json options used when source value requires stringification. + * Default value: null (use route defaults). + * Override the route json options used when source value requires stringification. */ - stringify: any; // TODO need to be implemented. + readonly stringify: Json.StringifyArguments; /** - Access: read only. - Default value: null (use route defaults). - If set, overrides the route cache with an expiration value in milliseconds. + * Default value: null (use route defaults). + * If set, overrides the route cache with an expiration value in milliseconds. */ - ttl: number; + readonly ttl: number; /** - Default value: false. - If true, a suffix will be automatically added to the 'ETag' header at transmission time (separated by a '-' character) when the HTTP 'Vary' header is present. + * 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/response/response-toolkit.d.ts b/types/hapi/v17/definitions/response/response-toolkit.d.ts index a4cabf3785..a421f7c1a1 100644 --- a/types/hapi/v17/definitions/response/response-toolkit.d.ts +++ b/types/hapi/v17/definitions/response/response-toolkit.d.ts @@ -1,5 +1,4 @@ import {ServerRealm, ServerStateCookieOptions} from "hapi"; -import {Request} from "../request/request"; import {ResponseObject} from "./response-object"; /** @@ -10,11 +9,11 @@ import {ResponseObject} from "./response-object"; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) * The response toolkit is a collection of properties and utilities passed to every [lifecycle method](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods) * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit) */ export interface ResponseToolkit { @@ -53,7 +52,7 @@ export interface ResponseToolkit { * The [request] object. This is a duplication of the request lifecycle method argument used by * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. */ - request: Request; + request: any; // TODO needs review /** * Used by the [authentication] method to pass back valid credentials where: @@ -77,13 +76,16 @@ export interface ResponseToolkit { * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed. * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned, * it should be used as the return value (but may be customize using the response methods). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions) */ + entity(): ResponseObject | undefined; entity(options: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; /** * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). * @param url * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) */ redirect(uri: string): ResponseObject; @@ -92,8 +94,10 @@ export interface ResponseToolkit { * (e.g. setting the HTTP status code, custom headers, etc.), where: * @param value - (optional) return value. Defaults to null. * @return Returns a response object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue) */ - response(value?: string): ResponseObject; + response(): ResponseObject; + response(value: string): ResponseObject; /** * Sets a response cookie using the same arguments as response.state(). @@ -101,8 +105,10 @@ export interface ResponseToolkit { * @param value of the cookie * @param (optional) ServerStateCookieOptions object. * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options) */ - state(name: string, value: string, options?: ServerStateCookieOptions): void; + state(name: string, value: string): void; + state(name: string, value: string, options: ServerStateCookieOptions): void; /** * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: @@ -115,16 +121,19 @@ export interface ResponseToolkit { * expired credentials, it allows the method to pass back the user information (combined with a 'try' * authentication mode) for error customization. * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) */ - unauthenticated(error: Error, data?: {credentials: any, artifacts?: any}): void; + unauthenticated(error: Error): void; + unauthenticated(error: Error, data: {credentials: any, artifacts?: any}): void; /** * Clears a response cookie using the same arguments as - * [response.unstate()](https://github.com/hapijs/hapi/blob/master/API.md#response.unstate()). * @param name of the cookie * @param options (optional) ServerStateCookieOptions object. * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options) */ - unstate(name: string, options?: ServerStateCookieOptions): void; + unstate(name: string): void; + unstate(name: string, options: ServerStateCookieOptions): void; } From 7d6c5756865f2f52040d4554077887b47946afd0 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 30 Nov 2017 15:15:14 -0300 Subject: [PATCH 31/79] Reviewed Request declarations. --- .../v17/definitions/request/request-auth.d.ts | 11 +- .../v17/definitions/request/request-info.d.ts | 24 +- .../definitions/request/request-route.d.ts | 8 +- .../hapi/v17/definitions/request/request.d.ts | 208 +++++++++--------- 4 files changed, 133 insertions(+), 118 deletions(-) diff --git a/types/hapi/v17/definitions/request/request-auth.d.ts b/types/hapi/v17/definitions/request/request-auth.d.ts index cc5fe1ec0a..2382697da0 100644 --- a/types/hapi/v17/definitions/request/request-auth.d.ts +++ b/types/hapi/v17/definitions/request/request-auth.d.ts @@ -1,6 +1,13 @@ /** - * Authentication information - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) */ export interface RequestAuth { /** an artifact object received from the authentication strategy and used in authentication-related actions. */ diff --git a/types/hapi/v17/definitions/request/request-info.d.ts b/types/hapi/v17/definitions/request/request-info.d.ts index 035b36cba0..a4892438a2 100644 --- a/types/hapi/v17/definitions/request/request-info.d.ts +++ b/types/hapi/v17/definitions/request/request-info.d.ts @@ -1,5 +1,17 @@ /** - * Request information + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) */ export interface RequestInfo { @@ -8,9 +20,7 @@ export interface RequestInfo { /** 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. + * true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. */ isOriginMatch?: boolean; }; @@ -24,11 +34,7 @@ export interface RequestInfo { 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? - */ + /** remote client port. */ remotePort: string; /** request response timestamp (0 is not responded yet). */ responded: number; diff --git a/types/hapi/v17/definitions/request/request-route.d.ts b/types/hapi/v17/definitions/request/request-route.d.ts index 1b5e79d03b..b93132e66c 100644 --- a/types/hapi/v17/definitions/request/request-route.d.ts +++ b/types/hapi/v17/definitions/request/request-route.d.ts @@ -1,7 +1,13 @@ import {RouteOptions, ServerRealm, HTTP_METHODS_PARTIAL} from "hapi"; /** - * The request route information object + * The request route information object, where: + * * method - the route HTTP method. + * * path - the route path. + * * vhost - the route vhost option if configured. + * * realm - the active realm associated with the route. + * * settings - the route options object with all defaults applied. + * * fingerprint - the route internal normalized string representing the normalized path. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) */ export interface RequestRoute { diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 84212bfacf..4eff44dea0 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -8,6 +8,7 @@ import {PluginsStates} from "../plugin/plugin"; import {RequestRoute} from "./request-route"; import {RequestAuth} from "./request-auth"; import {RequestInfo} from "./request-info"; +import * as Podium from "podium"; /** * TODO both objects ReplyValue and _ReplyValue I found in the v16 TS definition, but I don't found it in the documentation. Need review. @@ -16,232 +17,227 @@ import {RequestInfo} from "./request-info"; export type ReplyValue = _ReplyValue | Promise<_ReplyValue>; export type _ReplyValue = null | undefined | string | number | boolean | Buffer | Error | stream.Stream | Object; // | array; +/** + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig) + */ export interface RequestOrig { params: any; query: any; payload: any; } -export interface Request { +/** + * The request object is created internally for each incoming request. It is not the same object received from the node + * HTTP server callback (which is available via [request.raw.req](https://github.com/hapijs/hapi/blob/master/API.md#request.raw)). The request properties change throughout + * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle). + */ +export interface Request extends Podium { /** - 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]. + * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp) */ app: 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. + * Authentication information: + * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions. + * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication. + * * error - the authentication error is failed and mode set to 'try'. + * * isAuthenticated - true if the request has been successfully authenticated, otherwise false. + * * isAuthorized - true is the request has been successfully authorized against the route authentication access configuration. If the route has not access rules defined or if the request failed authorization, set to false. + * * mode - the route authentication mode. + * * strategy - the name of the strategy used. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth) */ readonly auth: RequestAuth; /** - Access: read only and the public podium interface. - The request.events supports the following events: - 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). - 'finish' - emitted when the request payload finished reading. The event method signature is function (). - 'disconnect' - emitted when a request errors or aborts unexpectedly. + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) */ - events: 'peek' | 'finish' | 'disconnect'; + events: 'peek' | 'finish' | 'disconnect'; // TODO I think it's wrong. Maybe is events.on(' ', ' '). It needs revision. /** - Access: read only. - The raw request headers (references request.raw.req.headers). + * The raw request headers (references request.raw.req.headers). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) */ - headers: Dictionary; + readonly 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. + * Request information: + * * acceptEncoding - the request preferred encoding. + * * cors - if CORS is enabled for the route, contains the following: + * * isOriginMatch - true if the request 'Origin' header matches the configured CORS restrictions. Set to false if no 'Origin' header is found or if it does not match. Note that this is only available after the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle. + * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080'). + * * hostname - the hostname part of the 'Host' header (e.g. 'example.com'). + * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}'). + * * received - request reception timestamp. + * * referrer - content of the HTTP 'Referrer' (or 'Referer') header. + * * remoteAddress - remote client IP address. + * * remotePort - remote client port. + * * responded - request response timestamp (0 is not responded yet). + * Note that the request.info object is not meant to be modified. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo) */ readonly info: RequestInfo; /** - 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. + * 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. + readonly logs: any[]; /** - Access: read only. - The request method in lower case (e.g. 'get', 'post'). + * The request method in lower case (e.g. 'get', 'post'). */ - method: HTTP_METHODS_PARTIAL_LOWERCASE; + readonly method: HTTP_METHODS_PARTIAL_LOWERCASE; /** - Access: read only. - The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. + * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. */ - mime: string; + readonly 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. + * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. */ - orig: RequestOrig; + readonly orig: RequestOrig; /** - Access: read only. - An object where each key is a path parameter name with matching value as described in Path parameters. + * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). */ - params: Dictionary; + readonly params: Dictionary; /** - Access: read only. - An array containing all the path params values in the order they appeared in the path. + * An array containing all the path params values in the order they appeared in the path. */ - paramsArray: string[]; + readonly paramsArray: string[]; /** - Access: read only. - The request URI's pathname component. + * The request URI's pathname component. */ - path: string; + readonly path: string; /** - Access: read only. - The request payload based on the route payload.output and payload.parse settings. + * 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; + readonly 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. + * 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. + * 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; + readonly 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). + * 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. + * Same as pre but represented as the response object created by the pre method. */ - preResponses: Object; + readonly 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). + * 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; + readonly 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. + * 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: { + readonly 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. + * The request route information object, where: + * * method - the route HTTP method. + * * path - the route path. + * * vhost - the route vhost option if configured. + * * realm - the active realm associated with the route. + * * settings - the route options object with all defaults applied. + * * fingerprint - the route internal normalized string representing the normalized path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) */ - route: RequestRoute; + readonly route: RequestRoute; /** - Access: read only and the public server interface. - The server object. + * Access: read only and the public server interface. + * The server object. */ - server: Server; // TODO check if this server object should be right. + server: Server; /** - 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. + * 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; + readonly state: Dictionary; /** - Access: read only. - The parsed request URI. + * The parsed request URI. */ - url: url.Url; + readonly 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. + * @return ResponseObject + * [See docs] (https://hapijs.com/api/17.0.1#request.generateResponse()) */ 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. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) */ log(tags: string | string[], data?: string | Object | (() => string | Object)): void; /** - * 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. + * @return Return value: true if the request would have passed the route's access requirements. * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. * If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route requires any authentication. + * [See docs] (https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) */ - // TODO how to implement it? It is a function inside route.auth! The v16 doesn't have this option. + // TODO how to implement it? It is a function inside route.auth! We have another "route" properti in this file. (The v16 doesn't have this option) /** - * request.setMethod(method) * Changes the request method before the router begins processing the request where: * @param method - is the request HTTP method (e.g. 'GET'). + * @return void * Can only be called from an 'onRequest' extension method. * [See docs] (https://hapijs.com/api/17.0.1#-requestsetmethodmethod) */ setMethod(method: HTTP_METHODS_PARTIAL): 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. + * @return void + * [See docs] (https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) */ setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; From b5a3441be2339cf610916d181c840cfa9e3fb15c Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 30 Nov 2017 20:25:27 -0300 Subject: [PATCH 32/79] Fix in JsDocs. --- types/hapi/v17/definitions/plugin/plugin-registered.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/hapi/v17/definitions/plugin/plugin-registered.d.ts b/types/hapi/v17/definitions/plugin/plugin-registered.d.ts index eb96b70537..9ee3987a10 100644 --- a/types/hapi/v17/definitions/plugin/plugin-registered.d.ts +++ b/types/hapi/v17/definitions/plugin/plugin-registered.d.ts @@ -6,12 +6,12 @@ export interface PluginsListRegistered { } /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) * An object of the currently registered plugins where each key is a registered plugin name and the value is an * object containing: * * version - the plugin version. * * name - the plugin name. * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) */ export interface PluginRegistered { From 6bc069990613c44263d74f98880f7e005d88517e Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 30 Nov 2017 20:26:11 -0300 Subject: [PATCH 33/79] Solved TODO about plugin, --- types/hapi/v17/definitions/plugin/plugin.d.ts | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/types/hapi/v17/definitions/plugin/plugin.d.ts b/types/hapi/v17/definitions/plugin/plugin.d.ts index df31c2c449..cda5c37f4a 100644 --- a/types/hapi/v17/definitions/plugin/plugin.d.ts +++ b/types/hapi/v17/definitions/plugin/plugin.d.ts @@ -1,4 +1,5 @@ import {Server} from "../server/server"; +import {ServerRegisterOptions} from "hapi"; export interface PluginsStates { [pluginName: string]: any; @@ -13,18 +14,16 @@ export interface PluginSpecificConfiguration { * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox * certain properties. For example, setting a file path in one plugin doesn't affect the file path set * in another plugin. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins) */ export interface Plugin { /** * (required) the registration function with the signature async function(server, options) where: + * * server - the server object with a plugin-specific server.realm. + * * options - any options passed to the plugin during registration via server.register(). */ - register: { - /** 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. - } + register: (server: Server, options: ServerRegisterOptions) => Function; /** * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm From 84cd35512e25cbe528812cb064d2cc2b605593e4 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 30 Nov 2017 20:26:37 -0300 Subject: [PATCH 34/79] Fix in JsDocs. --- types/hapi/v17/definitions/request/request.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 4eff44dea0..87d53c73a3 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -198,7 +198,7 @@ export interface Request extends Podium { * @param source - the value to set as the source of the reply interface, optional. * @param options - options for the method, optional. * @return ResponseObject - * [See docs] (https://hapijs.com/api/17.0.1#request.generateResponse()) + * [See docs](https://hapijs.com/api/17.0.1#request.generateResponse()) */ generateResponse(source?: ReplyValue, options?: {marshal?: any; prepare?: any; close?: any; variety?: any}): ResponseObject; @@ -218,7 +218,7 @@ export interface Request extends Podium { * @return Return value: true if the request would have passed the route's access requirements. * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. * If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route requires any authentication. - * [See docs] (https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) + * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) */ // TODO how to implement it? It is a function inside route.auth! We have another "route" properti in this file. (The v16 doesn't have this option) @@ -227,7 +227,7 @@ export interface Request extends Podium { * @param method - is the request HTTP method (e.g. 'GET'). * @return void * Can only be called from an 'onRequest' extension method. - * [See docs] (https://hapijs.com/api/17.0.1#-requestsetmethodmethod) + * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod) */ setMethod(method: HTTP_METHODS_PARTIAL): void; @@ -237,7 +237,7 @@ export interface Request extends Podium { * @param url - the new request URI. If url is a string, it is parsed with node's URL parse() method with parseQueryString set to true. url can also be set to an object compatible with node's URL parse() method output. * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false. * @return void - * [See docs] (https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) + * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash) */ setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void; From 4d8024908f6ede582b212c04884935669af1587d Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 30 Nov 2017 20:28:35 -0300 Subject: [PATCH 35/79] Added more Server types. --- .../server/server-options-cache.d.ts | 2 +- .../definitions/server/server-options.d.ts | 2 +- .../definitions/server/server-register.d.ts | 4 -- .../v17/definitions/server/server-route.d.ts | 47 +++++++++++++ .../v17/definitions/server/server-state.d.ts | 45 ++++++++++++- types/hapi/v17/definitions/server/server.d.ts | 67 +++++++++++++++---- types/hapi/v17/index.d.ts | 1 + 7 files changed, 149 insertions(+), 19 deletions(-) create mode 100644 types/hapi/v17/definitions/server/server-route.d.ts diff --git a/types/hapi/v17/definitions/server/server-options-cache.d.ts b/types/hapi/v17/definitions/server/server-options-cache.d.ts index cd71537d85..13b4df499a 100644 --- a/types/hapi/v17/definitions/server/server-options-cache.d.ts +++ b/types/hapi/v17/definitions/server/server-options-cache.d.ts @@ -1,7 +1,7 @@ import * as Catbox from "catbox"; /** - * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-cache) + * [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. */ diff --git a/types/hapi/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts index 5b2b364f8c..41b21e01fd 100644 --- a/types/hapi/v17/definitions/server/server-options.d.ts +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -7,7 +7,7 @@ import {PluginSpecificConfiguration, RouteOptions} from "hapi"; /** - * [See docs] (https://github.com/hapijs/hapi/blob/master/API.md#-server-options) + * [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. diff --git a/types/hapi/v17/definitions/server/server-register.d.ts b/types/hapi/v17/definitions/server/server-register.d.ts index 34685cbde2..14746bc85a 100644 --- a/types/hapi/v17/definitions/server/server-register.d.ts +++ b/types/hapi/v17/definitions/server/server-register.d.ts @@ -9,13 +9,11 @@ import {Plugin} from "hapi"; * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) */ export interface ServerRegisterOptions { - once?: boolean; routes?: { prefix: string; vhost: string | string[]; }; - } /** @@ -29,8 +27,6 @@ export interface ServerRegisterOptions { * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) */ export interface ServerRegisterPluginObject extends ServerRegisterOptions { - plugin: Plugin; options?: any; - } diff --git a/types/hapi/v17/definitions/server/server-route.d.ts b/types/hapi/v17/definitions/server/server-route.d.ts new file mode 100644 index 0000000000..0a6fce8ed0 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-route.d.ts @@ -0,0 +1,47 @@ +import {HTTP_METHODS_PARTIAL, Lifecycle, Server} from "hapi"; + +/** + * A route configuration object or an array of configuration objects where each object contains: + * * path - (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * * method - (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. + * * vhost - (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. + * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + * * options - additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. + * * rules - route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + */ +export interface ServerRoute { + + /** + * (required) the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the server's router configuration. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters) + */ + path: string; + + /** + * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. + */ + method: HTTP_METHODS_PARTIAL | HTTP_METHODS_PARTIAL[] | string | string[]; + + /** + * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. + */ + vhost?: string | string[]; + + /** + * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. + */ + handler?: Lifecycle.Method; + + /** + * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. + */ + options?: Object | ((server: Server) => Function); + + /** + * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. + */ + rules?: any; + +} diff --git a/types/hapi/v17/definitions/server/server-state.d.ts b/types/hapi/v17/definitions/server/server-state.d.ts index 796dda8cad..4b8a234718 100644 --- a/types/hapi/v17/definitions/server/server-state.d.ts +++ b/types/hapi/v17/definitions/server/server-state.d.ts @@ -1,6 +1,22 @@ import {ServerStateCookieOptions} from "hapi"; -import {Dictionary} from "../util/util"; +import {Dictionary} from "hapi"; +/** + * A single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + */ +export interface ServerStateFormat { + name: string; + value: string; + options: ServerStateCookieOptions; +} + +/** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate) + */ export interface ServerState { /** @@ -25,5 +41,32 @@ export interface ServerState { */ readonly names: Dictionary; + /** + * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). + */ + add(name: string): void; + add(name: string, options: ServerStateCookieOptions): void; + + /** + * Formats an HTTP 'Set-Cookie' header based on the server.options.state where: + * @param cookies - a single object or an array of object where each contains: + * * name - the cookie name. + * * value - the cookie value. + * * options - cookie configuration to override the server settings. + * @return Return value: a header string. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formating (e.g. when headers are set manually). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies) + */ + format(cookies: ServerStateFormat): string; + format(cookies: ServerStateFormat[]): string; + + /** + * Parses an HTTP 'Cookies' header based on the server.options.state where: + * @param header - the HTTP header. + * @return Return value: an object where each key is a cookie name and value is the parsed cookie. + * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) + */ + parse(header: string): Dictionary; } diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index abe6d8c313..849d1b15b4 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -13,7 +13,7 @@ import { ServerOptionsCache, ServerEventCriteria, ServerEventsApplication, ServerEventsApplicationObject, PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, HTTP_METHODS, ServerMethodOptions, ServerMethod, ServerMethodConfigurationObject, - Plugin, ResponseToolkit, Dictionary, + Plugin, ResponseToolkit, Dictionary, ServerStateCookieOptions, HTTP_METHODS_PARTIAL_LOWERCASE, } from "hapi"; import { RequestExtPointFunction, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, @@ -23,6 +23,7 @@ import {ServerInjectOptions, ServerInjectResponse} from "./server-inject"; import {RequestRoute} from "../request/request-route"; import {ServerAuth, ServerAuthConfig} from "./server-auth"; import {ServerRegisterPluginObject, ServerRegisterOptions} from "./server-register"; +import {ServerRoute} from "./server-route"; /** * The server object is the main application container. The server manages all incoming requests along with all @@ -570,18 +571,27 @@ export class Server extends events.EventEmitter { * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) */ - route(route: any): void; // TODO needs to be implemented. Depends of the route options TODO as well. - - - - - - - - - - // TODO It"s not finished + route(route: ServerRoute | ServerRoute[]): void; + /** + * Defines a route rules processor for converting route rules object into route configuration where: + * @param processor - a function using the signature function(rules, info) where: + * * rules - + * * info - an object with the following properties: + * * * method - the route method. + * * * path - the route path. + * * *vhost - the route virtual host (if any defined). + * * returns a route config object. + * @param options - optional settings: + * * validate - rules object validation: + * * * schema - joi schema. + * * * options - optional joi validation options. Defaults to { allowUnknown: true }. + * Note that the root server and each plugin server instance can only register one rules processor. If a route is added after the rules are configured, it will not include the rules config. Routes added by plugins apply the rules to each of the parent realms' rules from the root to the route's realm. This means the processor defined by the plugin override the config generated by the root processor if they overlap. The route config overrides the rules config if the overlap. + * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) + */ + rules(processor: (rules: any, info: {method: string, path: string, vhost?: string}) => Function): void; + rules(processor: (rules: any, info: {method: string, path: string, vhost?: string}) => Function, options: {validate: any}): void; // TODO needs implementation /** * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). @@ -592,4 +602,37 @@ export class Server extends events.EventEmitter { */ start(): void; + /** + * HTTP state management uses client cookies to persist a state across multiple requests. + * @param name - the cookie name string. + * @param options - are the optional cookie settings + * @return Return value: none. + * State defaults can be modified via the server default state configuration option. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) + */ + state(name: string): void; + state(name: string, options: ServerStateCookieOptions): void; + + /** + * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: + * @param options - (optional) object with: + * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds). + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions) + */ + stop(): void; + stop(options: {timeout: number}): void; + + /** + * Returns a copy of the routing table where: + * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts. + * @return Return value: an array of routes where each route contains: + * * settings - the route config with defaults applied. + * * method - the HTTP method in lower case. + * * path - the route path. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) + */ + table(): {settings: ServerRoute; method: HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; // TODO I am not sure if the ServerRoute is the object expected here + table(host: string): {settings: ServerRoute; method: HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; + } diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index fa2e6cac25..3e890253c4 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -48,6 +48,7 @@ export * from './definitions/server/server-options' export * from './definitions/server/server-options-cache' export * from './definitions/server/server-realm' export * from './definitions/server/server-register' +export * from './definitions/server/server-route' export * from './definitions/server/server-state' export * from './definitions/server/server-state-options' From c424efdbe7181553efc8c9d952965287268cf24c Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 3 Dec 2017 10:27:26 -0300 Subject: [PATCH 36/79] Reviewed and added sonme Function Overloading to follow best practices: http://definitelytyped.org/guides/best-practices.html --- types/hapi/v17/definitions/server/server.d.ts | 81 ++++++++++++------- 1 file changed, 52 insertions(+), 29 deletions(-) diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 849d1b15b4..a18fcb7dc7 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -28,17 +28,19 @@ import {ServerRoute} from "./server-route"; /** * The server object is the main application container. The server manages all incoming requests along with all * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) */ export class Server extends events.EventEmitter { /** - Creates a new server object where: + Creates a new server object */ constructor(); /** - Creates a new server object where: - @param options server configuration object. + * Creates a new server object where: + * @param options server configuration object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions) */ constructor(options: ServerOptions); @@ -46,6 +48,7 @@ export class Server extends events.EventEmitter { * Provides a safe place to store server-specific run-time application data without potential conflicts with * the framework internals. The data can be accessed whenever the server is accessible. * Initialized with an empty object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) */ app?: any; @@ -60,6 +63,7 @@ export class Server extends events.EventEmitter { * * request - decorations on the request object. * * toolkit - decorations on the response toolkit. * * server - decorations on the server object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations) */ readonly decorations: { request: Request, @@ -81,6 +85,7 @@ export class Server extends events.EventEmitter { * * a podium emitter object. * * an array containing any of the above. * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ event(events: ServerEventsApplication): void; event(events: ServerEventsApplication[]): void; @@ -170,7 +175,6 @@ export class Server extends events.EventEmitter { }; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) * An object containing information about the server where: * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}'). * * created - server creation timestamp. @@ -183,12 +187,14 @@ export class Server extends events.EventEmitter { * * 'https' - HTTPS. * * 'socket' - UNIX domain socket or Windows named pipe. * * uri - a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains the uri value if set, otherwise constructed from the available settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo) */ readonly info: ServerInfo; /** * Access: read only and listener public interface. * The node HTTP server object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener) */ listener: http.Server; @@ -197,6 +203,7 @@ export class Server extends events.EventEmitter { * * eventLoopDelay - event loop delay milliseconds. * * heapUsed - V8 heap usage. * * rss - RSS memory usage. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload) */ readonly load: { eventLoopDelay: number; @@ -205,18 +212,19 @@ export class Server extends events.EventEmitter { }; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods * Server methods are functions registered with the server and used throughout the application as a common utility. * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request * handlers without having to create a common module. * sever.methods is an object which provides access to the methods registered via server.method() where each * server method name is an object property. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods */ readonly methods: Dictionary; /** * Provides access to the server MIME database used for setting content-type information. The object must not be * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime) */ mime: MimosOptions; @@ -224,11 +232,11 @@ export class Server extends events.EventEmitter { * An object containing the values exposed by each registered plugin where each key is a plugin name and the values * are the exposed properties by each plugin using server.expose(). Plugins may set the value of * the server.plugins[name] object directly or via the server.expose() method. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) */ plugins: any; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) * 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 @@ -236,6 +244,7 @@ export class Server extends events.EventEmitter { * For example, a plugin can set a default file path for local resources without breaking other plugins' configured * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by * routes and extensions added at the same level (server root or plugin). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm) */ readonly realm: ServerRealm; @@ -245,17 +254,20 @@ export class Server extends events.EventEmitter { * * version - the plugin version. * * name - the plugin name. * * options - (optional) options passed to the plugin during registration. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations) */ readonly registrations: PluginsListRegistered; /** * The server configuration object after defaults applied. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings) */ readonly settings: ServerOptions; /** * The server cookies manager. * Access: read only and statehood public interface. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates) */ readonly states: ServerState; @@ -272,11 +284,11 @@ export class Server extends events.EventEmitter { readonly version: string; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) * Sets a global context used as the default bind object when adding a route or an extension where: * @param context - the object used to bind this in lifecycle methods such as the route handler and extension methods. The context is also made available as h.context. * @return Return value: none. * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) */ bind(context: any): void; @@ -286,7 +298,6 @@ export class Server extends events.EventEmitter { cache: { /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) * Provisions a cache segment within the server cache facility where: * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. @@ -294,7 +305,7 @@ export class Server extends events.EventEmitter { * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: * - `id` - the `id` string or object provided to the `get()` method. * - `flags` - an object used to pass back additional flags to the cache where: - *- `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. + * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. * * staleTimeout - number of milliseconds to wait before checking if an item is stale. * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. @@ -306,31 +317,31 @@ export class Server extends events.EventEmitter { * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. * @return Catbox Policy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) */ (options: catbox.PolicyOptions): catbox.Policy; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) * Provisions a server cache as described in server.cache where: * @param options - same as the server cache configuration options. * @return Return value: none. * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) */ provision(options: ServerOptionsCache): void; }; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: * @param encoding - the decoder name string. * @param decoder - a function using the signature function(options) where options are the encoding specific options configured in the route payload.compression configuration option, and the return value is an object compatible with the output of node's zlib.createGunzip(). * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder) */ decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) * Extends various framework interfaces with custom methods where: * @param type - the interface being decorated. Supported types: * 'handler' - adds a new handler type to be used in routes handlers. @@ -346,12 +357,12 @@ export class Server extends events.EventEmitter { * must return the new decoration function or value. * cannot be used to extend handler decorations. * @return void; + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) */ decorate(type: 'request', property: string, method: ((request: Request) => Function), options?: {apply: true; extend: false} ): void; decorate(type: 'handler' | 'request' | 'reply' | 'server', property: string, method: Function, options?: {apply: boolean; extend: boolean} ): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) * Used within a plugin to declare a required dependency on other plugins where: * @param dependencies - a single string or an array of plugin name strings which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is initialized or started. * @param after - (optional) a function that is called after all the specified dependencies have been registered and before the server starts. The function is only called if the server is initialized or started. The function signature is async function(server) where: @@ -360,40 +371,43 @@ export class Server extends events.EventEmitter { * The after method is identical to setting a server extension point on 'onPreStart'. * If a circular dependency is detected, an exception is thrown (e.g. two plugins each has an after function to be called after the other). * The method does not provide version dependency which should be implemented using npm peer dependencies. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) */ - dependency(dependencies: string | string[], after?: ((server: Server) => Function)): void; + dependency(dependencies: string): void; + dependency(dependencies: string, after: ((server: Server) => Function)): void; + dependency(dependencies: string[]): void; + dependency(dependencies: string[], after: ((server: Server) => Function)): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: * @param encoding - the encoder name string. * @param encoder - a function using the signature function(options) where options are the encoding specific options configured in the route compression option, and the return value is an object compatible with the output of node's zlib.createGzip(). * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) */ encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) * Used within a plugin to expose a property via server.plugins[name] where: * @param key - the key assigned (server.plugins[name][key]). * @param value - the value assigned. * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value) */ expose(key: string, value: any): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) * Merges an object into to the existing content of server.plugins[name] where: * @param obj - the object merged into the exposed properties container. * @return Return value: none. * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method * for exposing large objects that may be expensive to clone or singleton objects such as database client * objects. Instead favor server.expose(key, value), which only copies a reference to value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) */ expose(obj: Object): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) * Registers an extension function in one of the request lifecycle extension points where: * @param events - an object or array of objects with the following: * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points: @@ -412,20 +426,24 @@ export class Server extends events.EventEmitter { * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function. * * * sandbox - if set to 'plugin' when adding a request extension points the extension is only added to routes defined by the current plugin. Not allowed when configuring route-level extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. * @return void + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) */ - ext(events: ServerExtEventsObject | ServerExtEventsObject[]): void; - ext(events: ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; + ext(events: ServerExtEventsObject): void; + ext(events: ServerExtEventsObject[]): void; + ext(events: ServerExtEventsRequestObject): void; + ext(events: ServerExtEventsRequestObject[]): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) */ - ext(event: ServerExtType, method: ServerExtPointFunction, options?: ServerExtOptions): void; - ext(event: ServerExtRequestType, method: RequestExtPointFunction, options?: ServerExtOptions): void; + ext(event: ServerExtType, method: ServerExtPointFunction): void; + ext(event: ServerExtType, method: ServerExtPointFunction, options: ServerExtOptions): void; + ext(event: ServerExtRequestType, method: RequestExtPointFunction): void; + ext(event: ServerExtRequestType, method: RequestExtPointFunction, options: ServerExtOptions): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. * @return Return value: none. * Note that if the method fails and throws an error, the server is considered to be in an undefined state and @@ -433,11 +451,11 @@ export class Server extends events.EventEmitter { * other event listeners will get confused by repeated attempts to start the server or make assumptions about the * healthy state of the environment. It is recommended to abort the process when the server fails to start properly. * If you must try to resume after an error, call server.stop() first to reset the server state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize) */ initialize(): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) * Injects a request into the server simulating an incoming HTTP request without making an actual socket connection. Injection is useful for testing purposes as well as for invoking routing logic internally without the overhead and limitations of the network stack. * The method utilizes the shot module for performing injections, with some additional options and response properties: * @param options - can be assigned a string with the requested URI, or an object with: @@ -467,8 +485,10 @@ export class Server extends events.EventEmitter { * * res - the simulated node response object. * * result - the raw handler response (e.g. when not a stream or a view) before it is serialized for transmission. If not available, the value is set to payload. Useful for inspection and reuse of the internal objects returned (instead of parsing the response string). * * request - the request object. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) */ - inject(options: string | ServerInjectOptions): ServerInjectResponse; + inject(options: string): ServerInjectResponse; + inject(options: ServerInjectOptions): ServerInjectResponse; /** * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: @@ -496,7 +516,8 @@ export class Server extends events.EventEmitter { * @return Return value: the route information if found, otherwise null. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) */ - match(method: HTTP_METHODS, path: string, host?: string): RequestRoute | null; + match(method: HTTP_METHODS, path: string): RequestRoute | null; + match(method: HTTP_METHODS, path: string, host: string): RequestRoute | null; /** * Registers a server method where: @@ -514,7 +535,8 @@ export class Server extends events.EventEmitter { * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ - method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; + method(name: string, method: ServerMethod): void; + method(name: string, method: ServerMethod, options: ServerMethodOptions): void; /** * Registers a server method function as described in server.method() using a configuration object where: @@ -571,7 +593,8 @@ export class Server extends events.EventEmitter { * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) */ - route(route: ServerRoute | ServerRoute[]): void; + route(route: ServerRoute): void; + route(route: ServerRoute[]): void; /** * Defines a route rules processor for converting route rules object into route configuration where: From f7e3fc1e8d42dab607bb4fec24c0fb0f921e92f2 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 3 Dec 2017 15:57:40 -0300 Subject: [PATCH 37/79] Reviewed some server types. --- .../v17/definitions/server/server-auth.d.ts | 12 +- .../v17/definitions/server/server-method.d.ts | 3 - .../server/server-options-cache.d.ts | 2 +- .../definitions/server/server-options.d.ts | 132 +++++++++--------- types/hapi/v17/definitions/server/server.d.ts | 26 ++-- 5 files changed, 83 insertions(+), 92 deletions(-) diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts index 370e16be6b..6b86c0e8a4 100644 --- a/types/hapi/v17/definitions/server/server-auth.d.ts +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -38,8 +38,6 @@ export interface ServerAuth { } /** - * server.auth.default - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) * Sets a default strategy which is applied to every route where: * @param options - one of: * * a string with the default strategy name @@ -54,18 +52,19 @@ export interface ServerAuth { * before server.auth.default() is called if those routes lack any authentication config. * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active * authentication configuration of a route, use server.auth.lookup(request.route). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) */ - default(options: string | ServerAuthConfig): void; + default(options: string): void; + default(options: ServerAuthConfig): void; /** - * server.auth.scheme - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) * Registers an authentication scheme where: * @param name the scheme name. * @param scheme - the method implementing the scheme with signature function(server, options) where: * * server - a reference to the server object the scheme is added to. * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy. * @return void. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) */ scheme(name: string, scheme: ServerAuthScheme): void; @@ -77,7 +76,8 @@ export interface ServerAuth { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) */ - strategy(name: string, scheme: string, options?: any): void; + strategy(name: string, scheme: string): void; + strategy(name: string, scheme: string, options: any): void; /** * Tests a request against an authentication strategy where: diff --git a/types/hapi/v17/definitions/server/server-method.d.ts b/types/hapi/v17/definitions/server/server-method.d.ts index 216fd6ce6f..9806ffc5cb 100644 --- a/types/hapi/v17/definitions/server/server-method.d.ts +++ b/types/hapi/v17/definitions/server/server-method.d.ts @@ -18,9 +18,6 @@ export interface ServerMethod { * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) */ export interface ServerMethodCache extends catbox.PolicyOptions { - /** - * Required - */ generateTimeout: number | false; } diff --git a/types/hapi/v17/definitions/server/server-options-cache.d.ts b/types/hapi/v17/definitions/server/server-options-cache.d.ts index 13b4df499a..1e75ebe857 100644 --- a/types/hapi/v17/definitions/server/server-options-cache.d.ts +++ b/types/hapi/v17/definitions/server/server-options-cache.d.ts @@ -1,9 +1,9 @@ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache) */ export interface ServerOptionsCache extends Catbox.PolicyOptions { diff --git a/types/hapi/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts index 41b21e01fd..4273a01988 100644 --- a/types/hapi/v17/definitions/server/server-options.d.ts +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -5,68 +5,71 @@ 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. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options) */ export interface ServerOptions { /** - Default value: '0.0.0.0' (all available network interfaces). - Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to restrict the server to only those coming from the same host. + * Default value: '0.0.0.0' (all available network interfaces). + * Sets the hostname or IP address the server will listen on. If not configured, defaults to host if present, otherwise to all available network interfaces. Set to '127.0.0.1' or 'localhost' to restrict the server to only those coming from the same host. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress) */ address?: string; /** - Default value: {}. - Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available anywhere a server reference is provided. - Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. + * Default value: {}. + * Provides application-specific configuration which can later be accessed via server.settings.app. The framework does not interact with this object. It is simply a reference made available anywhere a server reference is provided. + * Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) */ app?: any; /** - Default value: true. - Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework. - Cannot be set to true along with a port value. + * Default value: true. + * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework. + * Cannot be set to true along with a port value. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten) */ autoListen?: boolean; /** - Default value: { engine: require('catbox-memory' }. - Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. - hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. - The server cache configuration only defines the storage container itself. The configuration can be assigned one or more (array): - a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. - a configuration object with the following: - engine - a class, a prototype function, or a catbox engine object. - name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. - shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. - partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'. - other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). + * Default value: { engine: require('catbox-memory' }. + * Sets up server-side caching providers. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. + * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. + * The server cache configuration only defines the storage container itself. The configuration can be assigned one or more (array): + * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. + * * a configuration object with the following: + * * * engine - a class, a prototype function, or a catbox engine object. + * * * name - an identifier used later when provisioning or configuring caching for server methods or plugins. Each cache name must be unique. A single item may omit the name option which defines the default cache. If every cache includes a name, a default memory cache is provisioned as well. + * * * shared - if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. + * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'. + * * * other options passed to the catbox strategy used. Other options are only passed to catbox when engine above is a class or function and ignored if engine is a catbox engine object). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache) */ cache?: catbox.EnginePrototype | ServerOptionsCache | ServerOptionsCache[]; /** - Default value: { minBytes: 1024 }. - Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server. + * 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. + * 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. + * 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; @@ -74,26 +77,26 @@ export interface ServerOptions { }; /** - 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. + * 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. + * 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). + * 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). */ @@ -107,34 +110,35 @@ export interface ServerOptions { }; /** - 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. + * Default value: none. + * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime): + * * override - an object hash that is merged into the built in mime information specified here. Each key value pair represents a single mime object. Each override value must contain: + * * key - the lower-cased mime-type string (e.g. 'application/javascript'). + * * value - an object following the specifications outlined here. Additional values include: + * * * type - specify the type value of result objects, defaults to key. + * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime) */ mime?: MimosOptions; /** - Default value: {}. - Plugin-specific configuration which can later be accessed via server.settings.plugins. plugins is an object where each key is a plugin name and the value is the configuration. Note the difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state. + * 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. + * 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. + * 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; @@ -142,8 +146,8 @@ export interface ServerOptions { }; /** - Default value: none. - A route options object used as the default configuration for every route. + * Default value: none. + * A route options object used as the default configuration for every route. */ routes?: RouteOptions; @@ -171,14 +175,14 @@ export interface ServerOptions { }; /** - 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. + * 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. + * 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.d.ts b/types/hapi/v17/definitions/server/server.d.ts index a18fcb7dc7..8045317d37 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -1,36 +1,26 @@ -import {ServerOptions} from "./server-options"; -import {ServerRealm} from "./server-realm"; -import {ServerInfo} from "./server-info"; -import {Request} from "../request/request"; import * as http from "http"; -import * as events from 'events'; import * as catbox from "catbox"; import * as zlib from "zlib"; -import {PluginsListRegistered} from "../plugin/plugin-registered"; -import {ServerState} from "./server-state"; -import {MimosOptions} from "../../../../mimos/index"; +import * as Podium from "podium"; +import {MimosOptions} from "mimos"; import { + ServerOptions, ServerRealm, ServerInfo, Request, PluginsListRegistered, ServerState, ServerOptionsCache, ServerEventCriteria, ServerEventsApplication, ServerEventsApplicationObject, PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, HTTP_METHODS, ServerMethodOptions, ServerMethod, ServerMethodConfigurationObject, + RequestExtPointFunction, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, + ServerExtPointFunction, ServerExtRequestType, ServerExtType, + ServerInjectOptions, ServerInjectResponse, + RequestRoute, ServerAuth, ServerRegisterPluginObject, ServerRegisterOptions, ServerRoute, Plugin, ResponseToolkit, Dictionary, ServerStateCookieOptions, HTTP_METHODS_PARTIAL_LOWERCASE, } from "hapi"; -import { - RequestExtPointFunction, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, - ServerExtPointFunction, ServerExtRequestType, ServerExtType -} from "./server-ext"; -import {ServerInjectOptions, ServerInjectResponse} from "./server-inject"; -import {RequestRoute} from "../request/request-route"; -import {ServerAuth, ServerAuthConfig} from "./server-auth"; -import {ServerRegisterPluginObject, ServerRegisterOptions} from "./server-register"; -import {ServerRoute} from "./server-route"; /** * The server object is the main application container. The server manages all incoming requests along with all * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server) */ -export class Server extends events.EventEmitter { +export class Server extends Podium { /** Creates a new server object From 4b5b1390fd8ba1fbabf8ef7983548f2c5b01cd1c Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 3 Dec 2017 16:09:52 -0300 Subject: [PATCH 38/79] Refactored Json and Util namespaces. --- .../definitions/request/request-route.d.ts | 4 +- .../hapi/v17/definitions/request/request.d.ts | 12 +++--- .../definitions/response/response-object.d.ts | 4 +- .../route/route-options-payload.d.ts | 4 +- .../route/route-options-response.d.ts | 4 +- .../v17/definitions/route/route-options.d.ts | 8 ++-- .../v17/definitions/server/server-auth.d.ts | 4 +- .../v17/definitions/server/server-route.d.ts | 4 +- .../v17/definitions/server/server-state.d.ts | 6 +-- types/hapi/v17/definitions/server/server.d.ts | 14 +++---- types/hapi/v17/definitions/util/json.d.ts | 27 ++++++++++++ .../hapi/v17/definitions/util/lifecycle.d.ts | 1 - types/hapi/v17/definitions/util/util.d.ts | 41 ++++--------------- types/hapi/v17/index.d.ts | 1 + 14 files changed, 67 insertions(+), 67 deletions(-) create mode 100644 types/hapi/v17/definitions/util/json.d.ts diff --git a/types/hapi/v17/definitions/request/request-route.d.ts b/types/hapi/v17/definitions/request/request-route.d.ts index b93132e66c..531b60f796 100644 --- a/types/hapi/v17/definitions/request/request-route.d.ts +++ b/types/hapi/v17/definitions/request/request-route.d.ts @@ -1,4 +1,4 @@ -import {RouteOptions, ServerRealm, HTTP_METHODS_PARTIAL} from "hapi"; +import {RouteOptions, ServerRealm, Util} from "hapi"; /** * The request route information object, where: @@ -12,7 +12,7 @@ import {RouteOptions, ServerRealm, HTTP_METHODS_PARTIAL} from "hapi"; */ export interface RequestRoute { /** the route HTTP method. */ - method: HTTP_METHODS_PARTIAL; + method: Util.HTTP_METHODS_PARTIAL; /** the route path. */ path: string; /** the route vhost option if configured. */ diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 87d53c73a3..c77614ee9d 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -3,7 +3,7 @@ import * as url from "url"; import * as http from "http"; import {Server} from "../server/server"; import {ResponseObject} from "../response/response-object"; -import {Dictionary, HTTP_METHODS_PARTIAL, HTTP_METHODS_PARTIAL_LOWERCASE} from "../util/util"; +import {Util} from "../util/util"; import {PluginsStates} from "../plugin/plugin"; import {RequestRoute} from "./request-route"; import {RequestAuth} from "./request-auth"; @@ -67,7 +67,7 @@ export interface Request extends Podium { * The raw request headers (references request.raw.req.headers). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) */ - readonly headers: Dictionary; + readonly headers: Util.Dictionary; /** * Request information: @@ -96,7 +96,7 @@ export interface Request extends Podium { /** * The request method in lower case (e.g. 'get', 'post'). */ - readonly method: HTTP_METHODS_PARTIAL_LOWERCASE; + readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE; /** * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred. @@ -111,7 +111,7 @@ export interface Request extends Podium { /** * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). */ - readonly params: Dictionary; + readonly params: Util.Dictionary; /** * An array containing all the path params values in the order they appeared in the path. @@ -186,7 +186,7 @@ export interface Request extends Podium { /** * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ - readonly state: Dictionary; + readonly state: Util.Dictionary; /** * The parsed request URI. @@ -229,7 +229,7 @@ export interface Request extends Podium { * Can only be called from an 'onRequest' extension method. * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod) */ - setMethod(method: HTTP_METHODS_PARTIAL): void; + setMethod(method: Util.HTTP_METHODS_PARTIAL): void; /** * Changes the request URI before the router begins processing the request where: diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index b913237571..a0f7abdf97 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -1,5 +1,5 @@ import {PluginsStates} from "../plugin/plugin"; -import {Dictionary} from "../util/util"; +import {Util} from "../util/util"; import {ResponseSettings} from "./response-settings"; import {ServerStateCookieOptions} from "../server/server-state-options"; import * as Podium from "podium"; @@ -52,7 +52,7 @@ export interface ResponseObject extends Podium { * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) */ - readonly headers: Dictionary; + readonly headers: Util.Dictionary; /** * Default value: {}. diff --git a/types/hapi/v17/definitions/route/route-options-payload.d.ts b/types/hapi/v17/definitions/route/route-options-payload.d.ts index b7baaac182..c07bf45fd4 100644 --- a/types/hapi/v17/definitions/route/route-options-payload.d.ts +++ b/types/hapi/v17/definitions/route/route-options-payload.d.ts @@ -1,4 +1,4 @@ -import {Dictionary, Lifecycle} from "hapi"; +import {Util, Lifecycle} from "hapi"; /** * The value must be one of: @@ -38,7 +38,7 @@ export interface RouteOptionsPayload { * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) */ - compression?: Dictionary; + compression?: Util.Dictionary; /** * Default value: 'application/json'. diff --git a/types/hapi/v17/definitions/route/route-options-response.d.ts b/types/hapi/v17/definitions/route/route-options-response.d.ts index 39db5e4574..cbf389e862 100644 --- a/types/hapi/v17/definitions/route/route-options-response.d.ts +++ b/types/hapi/v17/definitions/route/route-options-response.d.ts @@ -1,4 +1,4 @@ -import {Lifecycle, Dictionary} from "hapi"; +import {Lifecycle, Util} from "hapi"; import {ValidationOptions} from "joi"; /** @@ -77,6 +77,6 @@ export interface RouteOptionsResponse { * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) */ - status?: Dictionary; // TODO it must be better + status?: Util.Dictionary; // TODO it must be better } diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index e01d1a4cd3..5f8523b322 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -1,13 +1,13 @@ import {RouteOptionsAccess} from "./route-options-access"; import {RouteOptionsCache} from "./route-options-cache"; -import {Dictionary} from "../util/util"; +import {Util} 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 {RouteOptionsValidate} from "./route-options-validate"; import {PluginSpecificConfiguration} from "../plugin/plugin"; -import {Json} from "../util/util"; +import {Json} from "../util/json"; import {RouteOptionsPreArray} from "./route-options-pre"; import {Lifecycle} from "hapi"; @@ -65,7 +65,7 @@ export interface RouteOptions { * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) */ - compression?: Dictionary; + compression?: Util.Dictionary; /** * Default value: false (no CORS headers). @@ -179,7 +179,7 @@ export interface RouteOptions { * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) */ - plugins?: Dictionary; + plugins?: Util.Dictionary; /** * Default value: none. diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts index 6b86c0e8a4..785cee3a9d 100644 --- a/types/hapi/v17/definitions/server/server-auth.d.ts +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -1,7 +1,7 @@ import {ServerAuthScheme} from "./server-auth-scheme"; import {Request} from "../request/request"; import {RouteOptionsAccess} from "hapi"; -import {Dictionary} from "../util/util"; +import {Util} from "../util/util"; /** * The authentication credentials object @@ -27,7 +27,7 @@ export interface ServerAuth { * returned from its implementation function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) */ - api: Dictionary; + api: Util.Dictionary; /** * Contains the default authentication configuration is a default strategy was set via diff --git a/types/hapi/v17/definitions/server/server-route.d.ts b/types/hapi/v17/definitions/server/server-route.d.ts index 0a6fce8ed0..70e0bf1d34 100644 --- a/types/hapi/v17/definitions/server/server-route.d.ts +++ b/types/hapi/v17/definitions/server/server-route.d.ts @@ -1,4 +1,4 @@ -import {HTTP_METHODS_PARTIAL, Lifecycle, Server} from "hapi"; +import {Util, Lifecycle, Server} from "hapi"; /** * A route configuration object or an array of configuration objects where each object contains: @@ -22,7 +22,7 @@ export interface ServerRoute { /** * (required) the HTTP method. Typically one of 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', or 'OPTIONS'. Any HTTP method is allowed, except for 'HEAD'. Use '*' to match against any HTTP method (only when an exact match was not found, and any match with a specific method will be given a higher priority over a wildcard match). Can be assigned an array of methods which has the same result as adding the same route with different methods manually. */ - method: HTTP_METHODS_PARTIAL | HTTP_METHODS_PARTIAL[] | string | string[]; + method: Util.HTTP_METHODS_PARTIAL | Util.HTTP_METHODS_PARTIAL[] | string | string[]; /** * (optional) a domain string or an array of domain strings for limiting the route to only requests with a matching host header field. Matching is done against the hostname part of the header only (excluding the port). Defaults to all hosts. diff --git a/types/hapi/v17/definitions/server/server-state.d.ts b/types/hapi/v17/definitions/server/server-state.d.ts index 4b8a234718..1331d32e4a 100644 --- a/types/hapi/v17/definitions/server/server-state.d.ts +++ b/types/hapi/v17/definitions/server/server-state.d.ts @@ -1,5 +1,5 @@ import {ServerStateCookieOptions} from "hapi"; -import {Dictionary} from "hapi"; +import {Util} from "hapi"; /** * A single object or an array of object where each contains: @@ -39,7 +39,7 @@ export interface ServerState { /** * An array containing the names of all configued cookies. */ - readonly names: Dictionary; + readonly names: Util.Dictionary; /** * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). @@ -67,6 +67,6 @@ export interface ServerState { * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) */ - parse(header: string): Dictionary; + parse(header: string): Util.Dictionary; } diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 8045317d37..1d765d425b 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -6,13 +6,13 @@ import {MimosOptions} from "mimos"; import { ServerOptions, ServerRealm, ServerInfo, Request, PluginsListRegistered, ServerState, ServerOptionsCache, ServerEventCriteria, ServerEventsApplication, ServerEventsApplicationObject, - PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, HTTP_METHODS, ServerMethodOptions, ServerMethod, + PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, ServerMethodOptions, ServerMethod, ServerMethodConfigurationObject, RequestExtPointFunction, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, ServerExtPointFunction, ServerExtRequestType, ServerExtType, ServerInjectOptions, ServerInjectResponse, RequestRoute, ServerAuth, ServerRegisterPluginObject, ServerRegisterOptions, ServerRoute, - Plugin, ResponseToolkit, Dictionary, ServerStateCookieOptions, HTTP_METHODS_PARTIAL_LOWERCASE, + Plugin, ResponseToolkit, Util, ServerStateCookieOptions, } from "hapi"; /** @@ -209,7 +209,7 @@ export class Server extends Podium { * server method name is an object property. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods */ - readonly methods: Dictionary; + readonly methods: Util.Dictionary; /** * Provides access to the server MIME database used for setting content-type information. The object must not be @@ -506,8 +506,8 @@ export class Server extends Podium { * @return Return value: the route information if found, otherwise null. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) */ - match(method: HTTP_METHODS, path: string): RequestRoute | null; - match(method: HTTP_METHODS, path: string, host: string): RequestRoute | null; + match(method: Util.HTTP_METHODS, path: string): RequestRoute | null; + match(method: Util.HTTP_METHODS, path: string, host: string): RequestRoute | null; /** * Registers a server method where: @@ -645,7 +645,7 @@ export class Server extends Podium { * * path - the route path. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) */ - table(): {settings: ServerRoute; method: HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; // TODO I am not sure if the ServerRoute is the object expected here - table(host: string): {settings: ServerRoute; method: HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; + table(): {settings: ServerRoute; method: Util.HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; // TODO I am not sure if the ServerRoute is the object expected here + table(host: string): {settings: ServerRoute; method: Util.HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; } diff --git a/types/hapi/v17/definitions/util/json.d.ts b/types/hapi/v17/definitions/util/json.d.ts new file mode 100644 index 0000000000..116f6bdf9a --- /dev/null +++ b/types/hapi/v17/definitions/util/json.d.ts @@ -0,0 +1,27 @@ +export namespace Json { + + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; + + /** + * Any value greater than 10 is truncated. + */ + export type StringifySpace = number | string; + + /** + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) + */ + export interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + /** tring suffix added after conversion to JSON string. Defaults to no suffix. **/ + suffix?: string; + /** calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. **/ + escape?: boolean; + } + +} diff --git a/types/hapi/v17/definitions/util/lifecycle.d.ts b/types/hapi/v17/definitions/util/lifecycle.d.ts index 568b45b181..583fdf3c28 100644 --- a/types/hapi/v17/definitions/util/lifecycle.d.ts +++ b/types/hapi/v17/definitions/util/lifecycle.d.ts @@ -2,7 +2,6 @@ import * as Boom from "../../../../boom/index"; import * as stream from "stream"; import {ResponseToolkit, Request} from "hapi"; - export namespace Lifecycle { /** diff --git a/types/hapi/v17/definitions/util/util.d.ts b/types/hapi/v17/definitions/util/util.d.ts index ae473d89ac..f92b23bb4d 100644 --- a/types/hapi/v17/definitions/util/util.d.ts +++ b/types/hapi/v17/definitions/util/util.d.ts @@ -1,38 +1,11 @@ -export interface Dictionary { - [key: string]: T; -} +export namespace Util { -export type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; -export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_LOWERCASE; -export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; - -/** - * Json properties - */ -export namespace Json { - - /** - * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} - */ - export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; - - /** - * Any value greater than 10 is truncated. - */ - export type StringifySpace = number | string; - - /** - * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson) - */ - export interface StringifyArguments { - /** the replacer function or array. Defaults to no action. */ - replacer?: StringifyReplacer; - /** number of spaces to indent nested object keys. Defaults to no indentation. */ - space?: StringifySpace; - /** tring suffix added after conversion to JSON string. Defaults to no suffix. **/ - suffix?: string; - /** calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. **/ - escape?: boolean; + export interface Dictionary { + [key: string]: T; } + export type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; + export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_LOWERCASE; + export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; + } diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index 3e890253c4..de0cb95cca 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -53,5 +53,6 @@ export * from './definitions/server/server-state' export * from './definitions/server/server-state-options' /** UTIL */ +export * from './definitions/util/json' export * from './definitions/util/lifecycle' export * from './definitions/util/util' From cb083b4d692c3bd7541e751324b28cfc21703c5a Mon Sep 17 00:00:00 2001 From: Cameron Taggart Date: Sun, 3 Dec 2017 18:26:13 -0300 Subject: [PATCH 39/79] examples replacing any with object --- types/hapi/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index a97a9f1edb..5eff9b7e9b 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -231,7 +231,7 @@ export class Server extends Podium { * @param data the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. * @param callback an optional callback method invoked when all subscribers have been notified using the signature function(). The callback is called only after all the listeners have been notified, including any event updates emitted earlier (the order of event updates are guaranteed to be in the order they were emitted). */ - emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any, callback?: () => void): void; + emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: object, callback?: () => void): void; /** * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' * [See docs](https://hapijs.com/api/16.1.1#serverencoderencoding-encoder) @@ -489,7 +489,7 @@ export interface PluginSpecificConfiguration {} */ export interface ServerOptions { /** app - application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ - app?: any; + app?: object; /** * cache - sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: * * a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. @@ -533,7 +533,7 @@ export interface ServerEventObject { /** an array of tags (e.g. ['error', 'http']). */ tags: string[]; /** optional event-specific information. */ - data: any; + data?: object; /** true if the event was generated internally by the framework. */ internal: boolean; } From cb5d8da22f4db19d4fd0c3c205dbc9d6bd3019f3 Mon Sep 17 00:00:00 2001 From: BorntraegerMarc Date: Mon, 4 Dec 2017 09:34:47 +0100 Subject: [PATCH 40/79] Added first hapi TS tests --- types/hapi/v17/hapi-tests.ts | 12 ------------ .../v17/test/getting-started/01-creating-a-server.ts | 11 +++++++++++ types/hapi/v17/test/index.test.d.ts | 12 ++++++++++++ types/hapi/v17/tsconfig.json | 2 +- 4 files changed, 24 insertions(+), 13 deletions(-) delete mode 100644 types/hapi/v17/hapi-tests.ts create mode 100644 types/hapi/v17/test/getting-started/01-creating-a-server.ts create mode 100644 types/hapi/v17/test/index.test.d.ts diff --git a/types/hapi/v17/hapi-tests.ts b/types/hapi/v17/hapi-tests.ts deleted file mode 100644 index 06e2cdf175..0000000000 --- a/types/hapi/v17/hapi-tests.ts +++ /dev/null @@ -1,12 +0,0 @@ -import {Server, ServerOptions} from "hapi"; - -const options:ServerOptions = { - port: 8000 -} - -const server = new Server(options); -server.start(); - -console.log('Server started at: ' + server.info.uri); - - diff --git a/types/hapi/v17/test/getting-started/01-creating-a-server.ts b/types/hapi/v17/test/getting-started/01-creating-a-server.ts new file mode 100644 index 0000000000..b45aca4564 --- /dev/null +++ b/types/hapi/v17/test/getting-started/01-creating-a-server.ts @@ -0,0 +1,11 @@ +// From https://hapijs.com/tutorials/getting-started#creating-a-server +import { Server, ServerOptions } from 'hapi'; + +const options: ServerOptions = { + port: 8000, +}; + +const server = new Server(options); +server.start(); + +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts new file mode 100644 index 0000000000..ce156ebbdb --- /dev/null +++ b/types/hapi/v17/test/index.test.d.ts @@ -0,0 +1,12 @@ +// 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. + +/// + +/** Getting Started */ +export * from './getting-started/01-creating-a-server'; diff --git a/types/hapi/v17/tsconfig.json b/types/hapi/v17/tsconfig.json index 216332b184..8ce2562c61 100644 --- a/types/hapi/v17/tsconfig.json +++ b/types/hapi/v17/tsconfig.json @@ -23,6 +23,6 @@ }, "files": [ "index.d.ts", - "hapi-tests.ts" + "test/index.test.d.ts" ] } From c0337babb663374cc72862bcc6cb69309240043b Mon Sep 17 00:00:00 2001 From: rsouza Date: Mon, 4 Dec 2017 15:53:37 -0300 Subject: [PATCH 41/79] Revert "examples replacing any with object" This reverts commit cb083b4 It was my mistake. The example code is outside of v17 folder. --- types/hapi/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 5eff9b7e9b..a97a9f1edb 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -231,7 +231,7 @@ export class Server extends Podium { * @param data the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. * @param callback an optional callback method invoked when all subscribers have been notified using the signature function(). The callback is called only after all the listeners have been notified, including any event updates emitted earlier (the order of event updates are guaranteed to be in the order they were emitted). */ - emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: object, callback?: () => void): void; + emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any, callback?: () => void): void; /** * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' * [See docs](https://hapijs.com/api/16.1.1#serverencoderencoding-encoder) @@ -489,7 +489,7 @@ export interface PluginSpecificConfiguration {} */ export interface ServerOptions { /** app - application-specific configuration which can later be accessed via server.settings.app. Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. Defaults to {}. */ - app?: object; + app?: any; /** * cache - sets up server-side caching. Every server includes a default cache for storing application state. By default, a simple memory-based cache is created which has limited capacity and capabilities. hapi uses catbox for its cache which includes support for common storage solutions (e.g. Redis, MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache. The server cache configuration only defines the storage container itself. cache can be assigned: * * a prototype function (usually obtained by calling require() on a catbox strategy such as require('catbox-redis')). A new catbox client will be created internally using this function. @@ -533,7 +533,7 @@ export interface ServerEventObject { /** an array of tags (e.g. ['error', 'http']). */ tags: string[]; /** optional event-specific information. */ - data?: object; + data: any; /** true if the event was generated internally by the framework. */ internal: boolean; } From 5334e6bf7e19a5f92318789f9129b7ce41fe4af7 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Mon, 4 Dec 2017 20:22:31 -0300 Subject: [PATCH 42/79] Reviewed some server types. --- .../v17/definitions/server/server-events.d.ts | 5 +- types/hapi/v17/definitions/server/server.d.ts | 63 +++++++++++++------ 2 files changed, 48 insertions(+), 20 deletions(-) diff --git a/types/hapi/v17/definitions/server/server-events.d.ts b/types/hapi/v17/definitions/server/server-events.d.ts index c08bf4057a..7d0d600e6b 100644 --- a/types/hapi/v17/definitions/server/server-events.d.ts +++ b/types/hapi/v17/definitions/server/server-events.d.ts @@ -4,12 +4,13 @@ import Podium = require("../../../../podium/index"); * an event name string. * an event options object. * a podium emitter object. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) */ export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) * Object that it will be used in Event + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents) */ export interface ServerEventsApplicationObject { /** the event name string (required). */ @@ -27,8 +28,8 @@ export interface ServerEventsApplicationObject { } /** + * A criteria object with the following optional keys (unless noted otherwise): * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) - * a criteria object with the following optional keys (unless noted otherwise): */ export interface ServerEventCriteria { /** (required) the event name string. */ diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 1d765d425b..de63cc3125 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -4,15 +4,39 @@ import * as zlib from "zlib"; import * as Podium from "podium"; import {MimosOptions} from "mimos"; import { - ServerOptions, ServerRealm, ServerInfo, Request, PluginsListRegistered, ServerState, - ServerOptionsCache, ServerEventCriteria, ServerEventsApplication, ServerEventsApplicationObject, - PayloadCompressionDecoderSettings, RouteCompressionEncoderSettings, ServerMethodOptions, ServerMethod, + PayloadCompressionDecoderSettings, + Plugin, + PluginsListRegistered, + Request, + RequestExtPointFunction, + RequestRoute, + ResponseToolkit, + RouteCompressionEncoderSettings, + ServerAuth, + ServerEventCriteria, + ServerEventsApplication, + ServerEventsApplicationObject, + ServerExtEventsObject, + ServerExtEventsRequestObject, + ServerExtOptions, + ServerExtPointFunction, + ServerExtRequestType, + ServerExtType, + ServerInfo, + ServerInjectOptions, + ServerInjectResponse, + ServerMethod, ServerMethodConfigurationObject, - RequestExtPointFunction, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, - ServerExtPointFunction, ServerExtRequestType, ServerExtType, - ServerInjectOptions, ServerInjectResponse, - RequestRoute, ServerAuth, ServerRegisterPluginObject, ServerRegisterOptions, ServerRoute, - Plugin, ResponseToolkit, Util, ServerStateCookieOptions, + ServerMethodOptions, + ServerOptions, + ServerOptionsCache, + ServerRealm, + ServerRegisterOptions, + ServerRegisterPluginObject, + ServerRoute, + ServerState, + ServerStateCookieOptions, + Util, } from "hapi"; /** @@ -23,12 +47,14 @@ import { export class Server extends Podium { /** - Creates a new server object - */ + * Creates a new server object + * @constructor + */ constructor(); /** * Creates a new server object where: + * @constructor * @param options server configuration object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions) */ @@ -63,7 +89,7 @@ export class Server extends Podium { /** * Register custom application events where: - * @param events - must be one of: + * @param events must be one of: * * an event name string. * * an event options object with the following optional keys (unless noted otherwise): * * * name - the event name string (required). @@ -83,7 +109,6 @@ export class Server extends Podium { events: { /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) * Emits a custom application event to all the subscribed listeners where: * @param criteria - the event update criteria which must be one of: * * the event name string. @@ -94,8 +119,10 @@ export class Server extends Podium { * @param data - the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. * @return Return value: none. * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) */ - emit(criteria: string | {name: string, channel?: string, tags?: string | string[]}, data: any): void; + emit(criteria: string, data: any): void; + emit(criteria: {name: string, channel?: string, tags?: string | string[]}, data: any): void; /** * Subscribe to an event where: @@ -118,7 +145,6 @@ export class Server extends Podium { on(criteria: ServerEventCriteria, listener: Function): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. * @param criteria - the subscription criteria which must be one of: * * event name string which can be any of the built-in server events @@ -126,39 +152,40 @@ export class Server extends Podium { * * a criteria object * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) */ once(criteria: string, listener: Function): void; once(criteria: ServerEventsApplicationObject, listener: Function): void; once(criteria: ServerEventCriteria, listener: Function): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) * Same as calling server.events.on() with the count option set to 1. * @param criteria - the subscription criteria which must be one of: * * event name string which can be any of the built-in server events * * a custom application event registered with server.event(). * * a criteria object * @return Return value: a promise that resolves when the event is emitted. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) */ once(criteria: string): any; once(criteria: ServerEventsApplicationObject): any; once(criteria: ServerEventCriteria): any; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ removeListener(name: string, listener: Function): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ removeAllListeners(name: string): void; /** - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ hasListeners(name: string): boolean; From 88a3292c9dd870f034ba9be24722a7e117bd6c26 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Wed, 6 Dec 2017 00:11:51 -0300 Subject: [PATCH 43/79] Added some test files. --- .../test/getting-started/02-adding-routes.ts | 41 +++++++++++++++++++ types/hapi/v17/test/index.test.d.ts | 7 ++++ types/hapi/v17/test/path/catch-all.ts | 15 +++++++ types/hapi/v17/test/server/app.ts | 22 ++++++++++ types/hapi/v17/test/server/info.ts | 15 +++++++ types/hapi/v17/test/server/table.ts | 22 ++++++++++ 6 files changed, 122 insertions(+) create mode 100644 types/hapi/v17/test/getting-started/02-adding-routes.ts create mode 100644 types/hapi/v17/test/path/catch-all.ts create mode 100644 types/hapi/v17/test/server/app.ts create mode 100644 types/hapi/v17/test/server/info.ts create mode 100644 types/hapi/v17/test/server/table.ts diff --git a/types/hapi/v17/test/getting-started/02-adding-routes.ts b/types/hapi/v17/test/getting-started/02-adding-routes.ts new file mode 100644 index 0000000000..be46f20efc --- /dev/null +++ b/types/hapi/v17/test/getting-started/02-adding-routes.ts @@ -0,0 +1,41 @@ +// from https://hapijs.com/tutorials/getting-started#adding-routes +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; +const server = new Server(options); + +const serverRoute: ServerRoute = { + path: '/user', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + console.log(request); + return 'ok: ' + request.path; + } +} + +const serverRoutes: ServerRoute[] = [ + { + path: '/test1', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + console.log(request); + return 'ok: ' + request.path; + } + }, + { + path: '/test2', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + console.log(request); + return 'ok: ' + request.path; + } + }, +]; + +server.route(serverRoute); +server.route(serverRoutes); + +server.start(); +console.log(`Server running at: ${server.info!.uri}`); diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index ce156ebbdb..89ddbd9ece 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -10,3 +10,10 @@ /** Getting Started */ export * from './getting-started/01-creating-a-server'; +export * from './getting-started/02-adding-routes'; +export * from './path/catch-all'; +export * from './server/app'; +export * from './server/info'; +export * from './server/table'; + + diff --git a/types/hapi/v17/test/path/catch-all.ts b/types/hapi/v17/test/path/catch-all.ts new file mode 100644 index 0000000000..87ddfec8be --- /dev/null +++ b/types/hapi/v17/test/path/catch-all.ts @@ -0,0 +1,15 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; +const server = new Server(options); + +const handler = function (request: Request, h: ResponseToolkit) { + return h.response('The page was not found').code(404); +}; +server.route({ method: '*', path: '/{p*}', handler }); + +server.start(); +console.log(`Server running at: ${server.info!.uri}`); diff --git a/types/hapi/v17/test/server/app.ts b/types/hapi/v17/test/server/app.ts new file mode 100644 index 0000000000..ea376560b7 --- /dev/null +++ b/types/hapi/v17/test/server/app.ts @@ -0,0 +1,22 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-serverapp +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const server = new Server(options); +server.app.key = 'value2'; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return 'key: ' + request.server.app.key; + } +} + +server.route(serverRoute); + +server.start(); +console.log(`Server running at: ${server.info!.uri}`); diff --git a/types/hapi/v17/test/server/info.ts b/types/hapi/v17/test/server/info.ts new file mode 100644 index 0000000000..522b234c75 --- /dev/null +++ b/types/hapi/v17/test/server/info.ts @@ -0,0 +1,15 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; +import assert = require('assert'); + +let options: ServerOptions = { + port: 8000, +}; +const server = new Server(options); + +// check the correct port +if(server.info) assert(server.info.port === 8000); +assert(server.info !== null); + +server.start(); +console.log(`Server running at: ${server.info!.uri}`); diff --git a/types/hapi/v17/test/server/table.ts b/types/hapi/v17/test/server/table.ts new file mode 100644 index 0000000000..f6dee501c7 --- /dev/null +++ b/types/hapi/v17/test/server/table.ts @@ -0,0 +1,22 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const server = new Server(options); +server.app.key = 'value2'; + +server.route({ + path: '/', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return h.response("Hello World"); + } +}); + +server.start(); +const table = server.table(); +console.log(table); +console.log(`Server running at: ${server.info!.uri}`); From ffad3c7f82707b349e3e4e65b3e928293f424c2a Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Wed, 6 Dec 2017 22:18:06 -0300 Subject: [PATCH 44/79] Changed state() method param from string to object. --- types/hapi/v17/definitions/response/response-object.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index a0f7abdf97..c2ffd457fa 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -213,8 +213,8 @@ export interface ResponseObject extends Podium { * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) */ - state(name: string, value: string): ResponseObject; - state(name: string, value: string, options: ServerStateCookieOptions): ResponseObject; + state(name: string, value: object): ResponseObject; + state(name: string, value: object, options: ServerStateCookieOptions): ResponseObject; /** * Sets a string suffix when the response is process via JSON.stringify() where: @@ -234,7 +234,7 @@ export interface ResponseObject extends Podium { /** * Sets the HTTP 'Content-Type' header where: - * @param value - is the mime type. + * @param mimeType - is the mime type. * @return Return value: the current response object. * Should only be used to override the built-in default for each response type. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype) From c159a74456332cf93141f66d5a25ac1915befbd8 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Wed, 6 Dec 2017 22:19:33 -0300 Subject: [PATCH 45/79] Added more tests files. --- .../getting-started/01-creating-a-server.ts | 2 +- .../test/getting-started/02-adding-routes.ts | 8 ++-- types/hapi/v17/test/index.test.d.ts | 6 +++ types/hapi/v17/test/path/catch-all.ts | 4 +- types/hapi/v17/test/path/parameters.ts | 38 +++++++++++++++++++ types/hapi/v17/test/reply/redirect.ts | 20 ++++++++++ types/hapi/v17/test/reply/reply.ts | 37 ++++++++++++++++++ types/hapi/v17/test/reply/state_cookie.ts | 29 ++++++++++++++ types/hapi/v17/test/response/error.ts | 31 +++++++++++++++ types/hapi/v17/test/server/info.ts | 6 +-- types/hapi/v17/test/server/table.ts | 4 +- 11 files changed, 173 insertions(+), 12 deletions(-) create mode 100644 types/hapi/v17/test/path/parameters.ts create mode 100644 types/hapi/v17/test/reply/redirect.ts create mode 100644 types/hapi/v17/test/reply/reply.ts create mode 100644 types/hapi/v17/test/reply/state_cookie.ts create mode 100644 types/hapi/v17/test/response/error.ts diff --git a/types/hapi/v17/test/getting-started/01-creating-a-server.ts b/types/hapi/v17/test/getting-started/01-creating-a-server.ts index b45aca4564..995cac708c 100644 --- a/types/hapi/v17/test/getting-started/01-creating-a-server.ts +++ b/types/hapi/v17/test/getting-started/01-creating-a-server.ts @@ -1,5 +1,5 @@ // From https://hapijs.com/tutorials/getting-started#creating-a-server -import { Server, ServerOptions } from 'hapi'; +import {Server, ServerOptions} from 'hapi'; const options: ServerOptions = { port: 8000, diff --git a/types/hapi/v17/test/getting-started/02-adding-routes.ts b/types/hapi/v17/test/getting-started/02-adding-routes.ts index be46f20efc..4f383c15dc 100644 --- a/types/hapi/v17/test/getting-started/02-adding-routes.ts +++ b/types/hapi/v17/test/getting-started/02-adding-routes.ts @@ -4,16 +4,15 @@ import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi const options: ServerOptions = { port: 8000, }; -const server = new Server(options); const serverRoute: ServerRoute = { - path: '/user', + path: '/test', method: 'GET', handler: function (request: Request, h: ResponseToolkit) { console.log(request); return 'ok: ' + request.path; } -} +}; const serverRoutes: ServerRoute[] = [ { @@ -34,8 +33,9 @@ const serverRoutes: ServerRoute[] = [ }, ]; +const server = new Server(options); server.route(serverRoute); server.route(serverRoutes); server.start(); -console.log(`Server running at: ${server.info!.uri}`); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index 89ddbd9ece..a97dcf8ff0 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -12,6 +12,12 @@ export * from './getting-started/01-creating-a-server'; export * from './getting-started/02-adding-routes'; export * from './path/catch-all'; +export * from './path/parameters'; +export * from './reply/redirect'; +export * from './reply/reply'; +export * from './reply/state_cookie'; +export * from './response/error'; + export * from './server/app'; export * from './server/info'; export * from './server/table'; diff --git a/types/hapi/v17/test/path/catch-all.ts b/types/hapi/v17/test/path/catch-all.ts index 87ddfec8be..a5292d4b7e 100644 --- a/types/hapi/v17/test/path/catch-all.ts +++ b/types/hapi/v17/test/path/catch-all.ts @@ -1,5 +1,5 @@ // From https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route -import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; +import {Request, ResponseToolkit, Server, ServerOptions} from "hapi"; const options: ServerOptions = { port: 8000, @@ -12,4 +12,4 @@ const handler = function (request: Request, h: ResponseToolkit) { server.route({ method: '*', path: '/{p*}', handler }); server.start(); -console.log(`Server running at: ${server.info!.uri}`); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/path/parameters.ts b/types/hapi/v17/test/path/parameters.ts new file mode 100644 index 0000000000..11684555db --- /dev/null +++ b/types/hapi/v17/test/path/parameters.ts @@ -0,0 +1,38 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-requestparams +import {Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +// Example 1 +// http://localhost:8000/album-name/song-optional +const getAlbum: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { + console.log(request.params); + return 'ok: ' + request.path; +} +const serverRoute1: ServerRoute = { + path: '/{album}/{song?}', + method: 'GET', + handler: getAlbum +} + +// Example 2 +// http://localhost:8000/person/rafael/fijalkowski +const getPerson: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { + const nameParts = request.params.name.split('/'); + return { first: nameParts[0], last: nameParts[1] }; +} +const serverRoute2: ServerRoute = { + path: '/person/{name*2}', + method: 'GET', + handler: getPerson +} + + +const server = new Server(options); +server.route(serverRoute1); +server.route(serverRoute2); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/reply/redirect.ts b/types/hapi/v17/test/reply/redirect.ts new file mode 100644 index 0000000000..37af39707e --- /dev/null +++ b/types/hapi/v17/test/reply/redirect.ts @@ -0,0 +1,20 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return h.redirect('http://example.com'); + } +} + +const server = new Server(options); +server.route(serverRoute); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/reply/reply.ts b/types/hapi/v17/test/reply/reply.ts new file mode 100644 index 0000000000..185f80ed3d --- /dev/null +++ b/types/hapi/v17/test/reply/reply.ts @@ -0,0 +1,37 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoutes: ServerRoute[] = [ + // verbose notation + { + path: '/test1', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + const response = h.response('success'); + response.type('text/plain'); + response.header('X-Custom', 'some-value'); + return response; + } + }, + // Chained notation + { + path: '/test2', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return h.response('success') + .type('text/plain') + .header('X-Custom', 'some-value'); + } + }, +]; + + +const server = new Server(options); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); \ No newline at end of file diff --git a/types/hapi/v17/test/reply/state_cookie.ts b/types/hapi/v17/test/reply/state_cookie.ts new file mode 100644 index 0000000000..4ef420915e --- /dev/null +++ b/types/hapi/v17/test/reply/state_cookie.ts @@ -0,0 +1,29 @@ +// from https://hapijs.com/tutorials/cookies?lang=en_US +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute, ServerStateCookieOptions} from "hapi"; + + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/say-hello', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return h.response('Hello').state('data', { firstVisit: false }); + } +} + +const server = new Server(options); +server.route(serverRoute); + +const stateOption: ServerStateCookieOptions = { + ttl: 24 * 60 * 60 * 1000, // One day + isSecure: false, + isHttpOnly: false, + encoding: 'base64json', +} +server.state('data', stateOption); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/error.ts b/types/hapi/v17/test/response/error.ts new file mode 100644 index 0000000000..c9c5e3e822 --- /dev/null +++ b/types/hapi/v17/test/response/error.ts @@ -0,0 +1,31 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#errors +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; +import * as Boom from "boom"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoutes: ServerRoute[] = [ + { + path: '/badRequest', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + throw Boom.badRequest('Unsupported parameter'); + } + }, + { + path: '/internal', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + throw new Error('unexpect error'); + } + }, +]; + + +const server = new Server(options); +server.route(serverRoutes); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/info.ts b/types/hapi/v17/test/server/info.ts index 522b234c75..1fd15b240b 100644 --- a/types/hapi/v17/test/server/info.ts +++ b/types/hapi/v17/test/server/info.ts @@ -1,8 +1,8 @@ // From https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo -import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; +import {Server, ServerOptions} from "hapi"; import assert = require('assert'); -let options: ServerOptions = { +const options: ServerOptions = { port: 8000, }; const server = new Server(options); @@ -12,4 +12,4 @@ if(server.info) assert(server.info.port === 8000); assert(server.info !== null); server.start(); -console.log(`Server running at: ${server.info!.uri}`); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/table.ts b/types/hapi/v17/test/server/table.ts index f6dee501c7..58c8e4c52d 100644 --- a/types/hapi/v17/test/server/table.ts +++ b/types/hapi/v17/test/server/table.ts @@ -1,5 +1,5 @@ // From https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost -import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; +import {Request, ResponseToolkit, Server, ServerOptions} from "hapi"; const options: ServerOptions = { port: 8000, @@ -19,4 +19,4 @@ server.route({ server.start(); const table = server.table(); console.log(table); -console.log(`Server running at: ${server.info!.uri}`); +console.log('Server started at: ' + server.info.uri); From fd6f26dcd095c7294e97d7e2dc7ce9044b074199 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Wed, 6 Dec 2017 22:52:47 -0300 Subject: [PATCH 46/79] RequestExtPointFunction should inherit from Lifecycle.Method --- types/hapi/v17/definitions/server/server-ext.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/hapi/v17/definitions/server/server-ext.d.ts b/types/hapi/v17/definitions/server/server-ext.d.ts index 960a342998..40d0969f09 100644 --- a/types/hapi/v17/definitions/server/server-ext.d.ts +++ b/types/hapi/v17/definitions/server/server-ext.d.ts @@ -1,4 +1,4 @@ -import {Server, Request, ResponseToolkit} from "hapi"; +import {Server, Lifecycle} from "hapi"; /** * The extension point event name. The available extension points include the request extension points as well as the following server extension points: @@ -76,8 +76,8 @@ export interface ServerExtPointFunction { (server: Server): void; } -export interface RequestExtPointFunction { - (request: Request, h: ResponseToolkit): void; +export interface RequestExtPointFunction extends Lifecycle.Method { + } /** From 18e4f83a2481f63085a63952adb48e9bd3e77d40 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Wed, 6 Dec 2017 22:54:33 -0300 Subject: [PATCH 47/79] Added "continue.ts" test file. --- types/hapi/v17/test/index.test.d.ts | 1 + types/hapi/v17/test/reply/continue.ts | 25 +++++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 types/hapi/v17/test/reply/continue.ts diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index a97dcf8ff0..9e98fa9c31 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -13,6 +13,7 @@ export * from './getting-started/01-creating-a-server'; export * from './getting-started/02-adding-routes'; export * from './path/catch-all'; export * from './path/parameters'; +export * from './reply/continue'; export * from './reply/redirect'; export * from './reply/reply'; export * from './reply/state_cookie'; diff --git a/types/hapi/v17/test/reply/continue.ts b/types/hapi/v17/test/reply/continue.ts new file mode 100644 index 0000000000..5a0b37b5f9 --- /dev/null +++ b/types/hapi/v17/test/reply/continue.ts @@ -0,0 +1,25 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/test', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return 'ok: ' + request.path; + } +}; + +const server = new Server(options); +server.route(serverRoute); + +server.ext("onRequest", (request: Request, h: ResponseToolkit) => { + request.setUrl('/test'); + return h.continue; +}); + +server.start(); +console.log('Server started at: ' + server.info.uri); From c739273012528ec666398c5366ecdc55861794e9 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Thu, 7 Dec 2017 21:36:04 -0300 Subject: [PATCH 48/79] Add overloaded function "response(value: object)" to work with hapijs test: https://github.com/hapijs/hapi/blob/4144f9397cf639e22379699cdfc967d2c84e8509/test/response.js#L220 Following suggestion of @gitawego --- types/hapi/v17/definitions/response/response-toolkit.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/hapi/v17/definitions/response/response-toolkit.d.ts b/types/hapi/v17/definitions/response/response-toolkit.d.ts index a421f7c1a1..ae737bf085 100644 --- a/types/hapi/v17/definitions/response/response-toolkit.d.ts +++ b/types/hapi/v17/definitions/response/response-toolkit.d.ts @@ -98,6 +98,7 @@ export interface ResponseToolkit { */ response(): ResponseObject; response(value: string): ResponseObject; + response(value: object): ResponseObject; /** * Sets a response cookie using the same arguments as response.state(). From fddcaebffad884da18b7e398b27b90a6763ca701 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 11:43:06 -0300 Subject: [PATCH 49/79] Add object arguments (...args) instead of Function. Is it good idea? TODO created. --- types/hapi/v17/definitions/server/server.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index de63cc3125..8c6a37baeb 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -154,7 +154,7 @@ export class Server extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) */ - once(criteria: string, listener: Function): void; + once(criteria: string, listener: (...args: any[]) => void): void; // TODO I am not sure if the best way is use Function or (...args: any[]) => void) considering the JSDocs "The function signature depends on the event argument" once(criteria: ServerEventsApplicationObject, listener: Function): void; once(criteria: ServerEventCriteria, listener: Function): void; From 43152aaabd6d3aae6537e8f79279fc816ed11c87 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 11:46:45 -0300 Subject: [PATCH 50/79] Add new RequestEvents type. --- .../definitions/request/request-events.d.ts | 45 +++++++++++++++++++ .../hapi/v17/definitions/request/request.d.ts | 3 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 types/hapi/v17/definitions/request/request-events.d.ts diff --git a/types/hapi/v17/definitions/request/request-events.d.ts b/types/hapi/v17/definitions/request/request-events.d.ts new file mode 100644 index 0000000000..c61b3ed65c --- /dev/null +++ b/types/hapi/v17/definitions/request/request-events.d.ts @@ -0,0 +1,45 @@ +import * as Podium from "podium"; + +/** + * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export type RequestEventType = "peek" | "finish" | "disconnect"; + +/** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ +export interface RequestEvents extends Podium { + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + on(criteria: RequestEventType, listener: Function): void; + + /** + * Access: read only and the public podium interface. + * The request.events supports the following events: + * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the request payload finished reading. The event method signature is function (). + * * 'disconnect' - emitted when a request errors or aborts unexpectedly. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) + */ + once(criteria: RequestEventType, listener: Function): void; + + + + // TODO is it necessary to implement "emmit" event here? + +} diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index c77614ee9d..8d004553da 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -9,6 +9,7 @@ import {RequestRoute} from "./request-route"; import {RequestAuth} from "./request-auth"; import {RequestInfo} from "./request-info"; import * as Podium from "podium"; +import {RequestEvents} from "hapi"; /** * TODO both objects ReplyValue and _ReplyValue I found in the v16 TS definition, but I don't found it in the documentation. Need review. @@ -61,7 +62,7 @@ export interface Request extends Podium { * * 'disconnect' - emitted when a request errors or aborts unexpectedly. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents) */ - events: 'peek' | 'finish' | 'disconnect'; // TODO I think it's wrong. Maybe is events.on(' ', ' '). It needs revision. + events: RequestEvents; /** * The raw request headers (references request.raw.req.headers). From eebddd8c141ec345589273af7b19aeff510fce34 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 11:47:33 -0300 Subject: [PATCH 51/79] Add RequestEvents type in index.d.ts --- types/hapi/v17/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index de0cb95cca..f2b0f40c22 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -15,6 +15,7 @@ export * from './definitions/plugin/plugin-registered' /** REQUEST */ export * from './definitions/request/request' export * from './definitions/request/request-auth' +export * from './definitions/request/request-events' export * from './definitions/request/request-info' export * from './definitions/request/request-route' From 81a8109fede35a74225b79f7d03dd7cf01af1041 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 12:19:12 -0300 Subject: [PATCH 52/79] Separate ServerEvents in a new file. Fixed method overriding from Podium interface. I hope. --- .../v17/definitions/server/server-events.d.ts | 98 ++++++++++++++++++- types/hapi/v17/definitions/server/server.d.ts | 98 +++---------------- 2 files changed, 109 insertions(+), 87 deletions(-) diff --git a/types/hapi/v17/definitions/server/server-events.d.ts b/types/hapi/v17/definitions/server/server-events.d.ts index 7d0d600e6b..16e81f34ef 100644 --- a/types/hapi/v17/definitions/server/server-events.d.ts +++ b/types/hapi/v17/definitions/server/server-events.d.ts @@ -1,4 +1,4 @@ -import Podium = require("../../../../podium/index"); +import * as Podium from "podium"; /** * an event name string. @@ -54,3 +54,99 @@ export interface ServerEventCriteria { /** if true and the criteria object passed to server.event.emit() includes tags, the tags are mapped to an object (where each tag string is the key and the value is true) which is appended to the arguments list at the end. Defaults to the event registration option (which defaults to false). */ tags?: boolean; } + +/** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events. + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ +export interface ServerEvents extends Podium { + + /** + * Emits a custom application event to all the subscribed listeners where: + * @param criteria - the event update criteria which must be one of: + * * the event name string. + * * an object with the following optional keys (unless noted otherwise): + * * * name - the event name string (required). + * * * channel - the channel name string. + * * * tags - a tag string or array of tag strings. + * @param data - the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. + * @return Return value: none. + * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) + */ + emit(criteria: string, data: any): void; + emit(criteria: {name: string, channel?: string, tags?: string | string[]}, data: any): void; + + /** + * Subscribe to an event where: + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) + * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) + * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) + * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) + * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) + * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) + * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) + */ + on(criteria: string, listener: Function): void; + on(criteria: ServerEventsApplicationObject, listener: Function): void; + on(criteria: ServerEventCriteria, listener: Function): void; + + /** + * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. + * @return Return value: none. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) + */ + once(criteria: string, listener: (...args: any[]) => void): void; // TODO I am not sure if the best way (here and the functions above/below) is use Function or (...args: any[]) => void) considering the JSDocs "The function signature depends on the event argument" + once(criteria: ServerEventsApplicationObject, listener: Function): void; + once(criteria: ServerEventCriteria, listener: Function): void; + + /** + * Same as calling server.events.on() with the count option set to 1. + * @param criteria - the subscription criteria which must be one of: + * * event name string which can be any of the built-in server events + * * a custom application event registered with server.event(). + * * a criteria object + * @return Return value: a promise that resolves when the event is emitted. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) + */ + once(criteria: string): any; + once(criteria: ServerEventsApplicationObject): any; + once(criteria: ServerEventCriteria): any; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeListener(name: string, listener: Podium.Listener): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + removeAllListeners(name: string): Podium; + + /** + * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + hasListeners(name: string): boolean; + +} diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 8c6a37baeb..8f0e792a06 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -13,9 +13,8 @@ import { ResponseToolkit, RouteCompressionEncoderSettings, ServerAuth, - ServerEventCriteria, + ServerEvents, ServerEventsApplication, - ServerEventsApplicationObject, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, @@ -106,90 +105,17 @@ export class Server extends Podium { event(events: ServerEventsApplication): void; event(events: ServerEventsApplication[]): void; - events: { - - /** - * Emits a custom application event to all the subscribed listeners where: - * @param criteria - the event update criteria which must be one of: - * * the event name string. - * * an object with the following optional keys (unless noted otherwise): - * * * name - the event name string (required). - * * * channel - the channel name string. - * * * tags - a tag string or array of tag strings. - * @param data - the value emitted to the subscribers. If data is a function, the function signature is function() and it called once to generate (return value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked. - * @return Return value: none. - * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) - */ - emit(criteria: string, data: any): void; - emit(criteria: {name: string, channel?: string, tags?: string | string[]}, data: any): void; - - /** - * Subscribe to an event where: - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener) - * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event) - * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event) - * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event) - * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event) - * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) - * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) - */ - on(criteria: string, listener: Function): void; - on(criteria: ServerEventsApplicationObject, listener: Function): void; - on(criteria: ServerEventCriteria, listener: Function): void; - - /** - * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options. - * @return Return value: none. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) - */ - once(criteria: string, listener: (...args: any[]) => void): void; // TODO I am not sure if the best way is use Function or (...args: any[]) => void) considering the JSDocs "The function signature depends on the event argument" - once(criteria: ServerEventsApplicationObject, listener: Function): void; - once(criteria: ServerEventCriteria, listener: Function): void; - - /** - * Same as calling server.events.on() with the count option set to 1. - * @param criteria - the subscription criteria which must be one of: - * * event name string which can be any of the built-in server events - * * a custom application event registered with server.event(). - * * a criteria object - * @return Return value: a promise that resolves when the event is emitted. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) - */ - once(criteria: string): any; - once(criteria: ServerEventsApplicationObject): any; - once(criteria: ServerEventCriteria): any; - - /** - * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ - removeListener(name: string, listener: Function): void; - - /** - * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovealllistenersname) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ - removeAllListeners(name: string): void; - - /** - * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumhaslistenersname) - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) - */ - hasListeners(name: string): boolean; - - }; + /** + * Access: podium public interface. + * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. + * Use the following methods to interact with server.events: + * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events. + * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events. + * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to + * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name). + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) + */ + events: ServerEvents; /** * An object containing information about the server where: From bbfeda585bd4ae6ddaa413d705e34a176f7bad30 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 12:22:32 -0300 Subject: [PATCH 53/79] Add events (server and request) test files. --- types/hapi/v17/test/index.test.d.ts | 5 ++ types/hapi/v17/test/request/event-types.ts | 71 +++++++++++++++++++ .../v17/test/server/server-events-once.ts | 26 +++++++ 3 files changed, 102 insertions(+) create mode 100644 types/hapi/v17/test/request/event-types.ts create mode 100644 types/hapi/v17/test/server/server-events-once.ts diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index 9e98fa9c31..35555aa057 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -17,10 +17,15 @@ export * from './reply/continue'; export * from './reply/redirect'; export * from './reply/reply'; export * from './reply/state_cookie'; + +export * from './request/event-types'; + export * from './response/error'; export * from './server/app'; export * from './server/info'; +export * from './server/server-events-once'; export * from './server/table'; + diff --git a/types/hapi/v17/test/request/event-types.ts b/types/hapi/v17/test/request/event-types.ts new file mode 100644 index 0000000000..ae1c0ac081 --- /dev/null +++ b/types/hapi/v17/test/request/event-types.ts @@ -0,0 +1,71 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +// From https://github.com/hapijs/hapi/blob/master/API.md#-requestevents +import { + Request, RequestExtPointFunction, ResponseToolkit, RouteOptions, Server, ServerOptions, + ServerRoute +} from "hapi"; +import * as Crypto from 'crypto'; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return 'ok: ' + request.path; + } +}; + +const onRequest: RequestExtPointFunction = function (request: Request, h: ResponseToolkit) { + + /* + * Server events + */ + request.server.events.on('request', (request: Request, event: any, tags: any) => { + console.log(request.paramsArray); + console.log(event); + console.log(tags); + }); + + request.server.events.on('response', (request: Request) => { + console.log('Response sent for request: ' + request.path); + }); + + request.server.events.on('start', (route: RouteOptions) => { + console.log('Server started'); + }); + + request.server.events.once('stop', (route: RouteOptions) => { + console.log('Server stoped'); + }); + + /* + * Request events + */ + const hash = Crypto.createHash('sha1'); + + request.events.on("peek", (chunk: any) => { + hash.update(chunk); + }); + + request.events.once("finish", () => { + console.log(hash.digest('hex')); + }); + + request.events.once("disconnect", () => { + console.error('request aborted'); + }); + + return h.continue; + +}; + +const server = new Server(options); +server.route(serverRoute); +server.ext('onRequest', onRequest); + +server.start(); +console.log('Server started at: ' + server.info.uri); + diff --git a/types/hapi/v17/test/server/server-events-once.ts b/types/hapi/v17/test/server/server-events-once.ts new file mode 100644 index 0000000000..d36deb10bb --- /dev/null +++ b/types/hapi/v17/test/server/server-events-once.ts @@ -0,0 +1,26 @@ +// from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return 'oks: ' + request.path; + } +}; + +const server = new Server(options); +server.route(serverRoute); +server.event('test1'); +server.event('test2'); +server.events.once('test1', function(update: any) {console.log(update);}); +server.events.once('test2', function(...args: any[]) {console.log(args);}); +server.events.emit('test1', 'hello-1'); +server.events.emit('test2', 'hello-2'); // Ignored + +server.start(); +console.log('Server started at: ' + server.info.uri); From e189cf6b5e09901f6c068fc78960e37fa129ec77 Mon Sep 17 00:00:00 2001 From: "Rafael S. Fijalkowski" Date: Fri, 8 Dec 2017 19:10:47 -0300 Subject: [PATCH 54/79] Replacing any with object. Following the idea of @ctaggart (#4) Review of TS types using 'object' and 'any' mainly. --- .../definitions/plugin/plugin-registered.d.ts | 2 +- .../v17/definitions/request/request-auth.d.ts | 4 +-- .../hapi/v17/definitions/request/request.d.ts | 36 +++++++++---------- .../definitions/response/response-object.d.ts | 4 +-- .../response/response-toolkit.d.ts | 6 ++-- .../route/route-options-access.d.ts | 2 +- .../route/route-options-payload.d.ts | 2 +- .../route/route-options-response.d.ts | 6 ++-- .../route/route-options-validate.d.ts | 14 ++++---- .../v17/definitions/route/route-options.d.ts | 11 +++--- .../server/server-auth-scheme.d.ts | 4 +-- .../v17/definitions/server/server-auth.d.ts | 2 +- .../v17/definitions/server/server-ext.d.ts | 2 +- .../v17/definitions/server/server-inject.d.ts | 8 ++--- .../v17/definitions/server/server-method.d.ts | 5 +-- .../definitions/server/server-options.d.ts | 2 +- .../v17/definitions/server/server-realm.d.ts | 10 +++--- .../definitions/server/server-register.d.ts | 2 +- .../v17/definitions/server/server-route.d.ts | 4 +-- .../server/server-state-options.d.ts | 4 +-- .../v17/definitions/server/server-state.d.ts | 4 +-- types/hapi/v17/definitions/server/server.d.ts | 16 ++++----- 22 files changed, 75 insertions(+), 75 deletions(-) diff --git a/types/hapi/v17/definitions/plugin/plugin-registered.d.ts b/types/hapi/v17/definitions/plugin/plugin-registered.d.ts index 9ee3987a10..e83eb81a63 100644 --- a/types/hapi/v17/definitions/plugin/plugin-registered.d.ts +++ b/types/hapi/v17/definitions/plugin/plugin-registered.d.ts @@ -28,6 +28,6 @@ export interface PluginRegistered { /** * options used to register the plugin. */ - options: any; // OptionsPassedToPlugin; + options: object; } diff --git a/types/hapi/v17/definitions/request/request-auth.d.ts b/types/hapi/v17/definitions/request/request-auth.d.ts index 2382697da0..a11dd07467 100644 --- a/types/hapi/v17/definitions/request/request-auth.d.ts +++ b/types/hapi/v17/definitions/request/request-auth.d.ts @@ -11,9 +11,9 @@ */ export interface RequestAuth { /** an artifact object received from the authentication strategy and used in authentication-related actions. */ - artifacts: any; + artifacts: object; /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ - credentials: any; + credentials: object; /** the authentication error is failed and mode set to 'try'. */ error: Error; /** true if the request has been successfully authenticated, otherwise false. */ diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 8d004553da..2a92b8a142 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -11,21 +11,14 @@ import {RequestInfo} from "./request-info"; import * as Podium from "podium"; import {RequestEvents} from "hapi"; -/** - * 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; - /** * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig) */ export interface RequestOrig { - params: any; - query: any; - payload: any; + params: object; + query: object; + payload: object; } /** @@ -39,7 +32,7 @@ export interface Request extends Podium { * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp) */ - app: any; + app: object; /** * Authentication information: @@ -92,7 +85,7 @@ export interface Request extends Podium { * An array containing the logged request events. * Note that this array will be empty if route log.collect is set to false. */ - readonly logs: any[]; + readonly logs: object[]; /** * The request method in lower case (e.g. 'get', 'post'). @@ -128,7 +121,7 @@ export interface Request extends Podium { * The request payload based on the route payload.output and payload.parse settings. * TODO check this typing and add references / links. */ - readonly payload: stream.Readable | Buffer | any; + readonly payload: stream.Readable | Buffer | string | object; /** * Plugin-specific state. Provides a place to store and pass request-level plugin data. The plugins is an object where each key is a plugin name and the value is the state. @@ -138,7 +131,7 @@ export interface Request extends Podium { /** * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses. */ - readonly pre: Object; + readonly pre: Util.Dictionary; /** * Access: read / write (see limitations below). @@ -149,12 +142,12 @@ export interface Request extends Podium { /** * Same as pre but represented as the response object created by the pre method. */ - readonly preResponses: Object; + readonly preResponses: Util.Dictionary; /** * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query attribute as an unparsed string). */ - readonly query: any; + readonly query: object; /** * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. @@ -187,7 +180,7 @@ export interface Request extends Podium { /** * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ - readonly state: Util.Dictionary; + readonly state: Map; /** * The parsed request URI. @@ -199,9 +192,11 @@ export interface Request extends Podium { * @param source - the value to set as the source of the reply interface, optional. * @param options - options for the method, optional. * @return ResponseObject - * [See docs](https://hapijs.com/api/17.0.1#request.generateResponse()) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options) */ - generateResponse(source?: ReplyValue, options?: {marshal?: any; prepare?: any; close?: any; variety?: any}): ResponseObject; + generateResponse(source: object, options?: {variety?: string; prepare?: Function; marshal?: Function; close?: Function; }): ResponseObject; + generateResponse(source: string, options?: {variety?: string; prepare?: Function; marshal?: Function; close?: Function; }): ResponseObject; + generateResponse(source: null, options?: {variety?: string; prepare?: Function; marshal?: Function; close?: Function; }): ResponseObject; /** * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: @@ -211,7 +206,8 @@ export interface Request extends Podium { * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) */ - log(tags: string | string[], data?: string | Object | (() => string | Object)): void; + log(tags: string, data?: string | object | (() => string | object)): void; + log(tags: string[], data?: string | object | (() => string | object)): void; /** * Validates a request against the route's authentication access configuration, where: diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index c2ffd457fa..71415c0b33 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -35,7 +35,7 @@ export interface ResponseObject extends Podium { * Application-specific state. Provides a safe place to store application data without potential conflicts with the framework. Should not be used by plugins which should use plugins[name]. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp) */ - app: any; + app: object; /** * Access: read only and the public podium interface. @@ -44,7 +44,7 @@ export interface ResponseObject extends Podium { * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). * [See docs](https://hapijs.com/api/17.0.1#-responseevents) */ - readonly events: any; // TODO need to be implemented. I didn't understand yet. + readonly events: object; // TODO need to be implemented. I didn't understand yet. /** * Default value: {}. diff --git a/types/hapi/v17/definitions/response/response-toolkit.d.ts b/types/hapi/v17/definitions/response/response-toolkit.d.ts index ae737bf085..0ab64f10b0 100644 --- a/types/hapi/v17/definitions/response/response-toolkit.d.ts +++ b/types/hapi/v17/definitions/response/response-toolkit.d.ts @@ -52,7 +52,7 @@ export interface ResponseToolkit { * The [request] object. This is a duplication of the request lifecycle method argument used by * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request. */ - request: any; // TODO needs review + request: object; // TODO needs review /** * Used by the [authentication] method to pass back valid credentials where: @@ -61,7 +61,7 @@ export interface ResponseToolkit { * * artifacts - (optional) authentication artifacts object specific to the authentication scheme. * @return Return value: an internal authentication object. */ - authenticated(data: {credentials: any, artifacts?: any}): any; + authenticated(data: {credentials: object, artifacts?: object}): object; /** * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if @@ -125,7 +125,7 @@ export interface ResponseToolkit { * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) */ unauthenticated(error: Error): void; - unauthenticated(error: Error, data: {credentials: any, artifacts?: any}): void; + unauthenticated(error: Error, data: {credentials: object, artifacts?: object}): void; /** * Clears a response cookie using the same arguments as diff --git a/types/hapi/v17/definitions/route/route-options-access.d.ts b/types/hapi/v17/definitions/route/route-options-access.d.ts index 8bc175b10a..57cd13e405 100644 --- a/types/hapi/v17/definitions/route/route-options-access.d.ts +++ b/types/hapi/v17/definitions/route/route-options-access.d.ts @@ -46,7 +46,7 @@ export interface RouteOptionsAccess { * An object or array of objects specifying the route access rules. Each rule is evaluated against an incoming request and access is granted if at least one of the rules matches. Each rule object must include at least one of scope or entity. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess) */ - access?: any | any[]; + access?: object | object[]; /** * Default value: false (no scope requirements). diff --git a/types/hapi/v17/definitions/route/route-options-payload.d.ts b/types/hapi/v17/definitions/route/route-options-payload.d.ts index c07bf45fd4..c48d09aa0c 100644 --- a/types/hapi/v17/definitions/route/route-options-payload.d.ts +++ b/types/hapi/v17/definitions/route/route-options-payload.d.ts @@ -12,7 +12,7 @@ export type PayloadOutput = 'data' | 'stream' | 'file'; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) */ -export type PayloadCompressionDecoderSettings = any; +export type PayloadCompressionDecoderSettings = object; /** * Determines how the request payload is processed. diff --git a/types/hapi/v17/definitions/route/route-options-response.d.ts b/types/hapi/v17/definitions/route/route-options-response.d.ts index cbf389e862..16c2249e29 100644 --- a/types/hapi/v17/definitions/route/route-options-response.d.ts +++ b/types/hapi/v17/definitions/route/route-options-response.d.ts @@ -9,6 +9,8 @@ export enum EmptyStatusCode { HTTP_204 = 204, } +export type RouteOptionsResponseSchema = boolean | ValidationOptions | ((value: object, options: object) => Function); + /** * Processing rules for the outgoing response. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse) @@ -69,7 +71,7 @@ export interface RouteOptionsResponse { * * * if the function returns a value and modify is true, the value is used as the new response. If the original response is an error, the return value is used to override the original error output.payload. If an error is thrown, the error is processed according to failAction. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema) */ - schema?: boolean | ValidationOptions | ((value: any, options: any) => Function); // TODO it must be better + schema?: RouteOptionsResponseSchema; /** * Default value: none. @@ -77,6 +79,6 @@ export interface RouteOptionsResponse { * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) */ - status?: Util.Dictionary; // TODO it must be better + status?: Map; } diff --git a/types/hapi/v17/definitions/route/route-options-validate.d.ts b/types/hapi/v17/definitions/route/route-options-validate.d.ts index 6fba5dfc67..7fa61d5bef 100644 --- a/types/hapi/v17/definitions/route/route-options-validate.d.ts +++ b/types/hapi/v17/definitions/route/route-options-validate.d.ts @@ -1,4 +1,4 @@ -import {Lifecycle} from "hapi"; +import {Lifecycle, RouteOptionsResponseSchema} from "hapi"; import {ValidationOptions} from "joi"; /** @@ -13,7 +13,7 @@ export interface RouteOptionsValidate { * An optional object with error fields copied into every validation error response. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields) */ - errorFields?: any; + errorFields?: object; /** * Default value: 'error' (return a Bad Request (400) error response). @@ -34,7 +34,7 @@ export interface RouteOptionsValidate { * Note that all header field names must be in lowercase to match the headers normalized by node. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders) */ - headers?: boolean | ValidationOptions | ((value: any, option: any) => Function); + headers?: RouteOptionsResponseSchema; /** * Default value: none. @@ -45,7 +45,7 @@ export interface RouteOptionsValidate { * If the validation rules for headers, params, query, and payload are defined at both the server routes level and at the route level, the individual route settings override the routes defaults (the rules are not merged). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) */ - options?: ValidationOptions | Object; // TODO need review + options?: ValidationOptions | object; /** * Default value: true (no validation). @@ -59,7 +59,7 @@ export interface RouteOptionsValidate { * Note that failing to match the validation rules to the route path parameters definition will cause all requests to fail. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams) */ - params?: boolean | ValidationOptions | ((value: any, option: any) => Function); // TODO need review + params?: RouteOptionsResponseSchema; /** * Default value: true (no validation). @@ -73,7 +73,7 @@ export interface RouteOptionsValidate { * Note that validating large payloads and modifying them will cause memory duplication of the payload (since the original is kept), as well as the significant performance cost of validating large amounts of data. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload) */ - payload?: boolean | ValidationOptions | ((value: any, option: any) => Function); // TODO need review + payload?: RouteOptionsResponseSchema; /** * Default value: true (no validation). @@ -87,6 +87,6 @@ export interface RouteOptionsValidate { * Note that changes to the query parameters will not be reflected in request.url. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery) */ - query?: boolean | ValidationOptions | ((value: any, option: any) => Function); // TODO need review + query?: RouteOptionsResponseSchema; } diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index 5f8523b322..daf0005ddd 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -15,7 +15,7 @@ import {Lifecycle} from "hapi"; * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder) */ -export type RouteCompressionEncoderSettings = any; +export type RouteCompressionEncoderSettings = object; /** * Each route can be customized to change the default behavior of the request lifecycle. @@ -27,7 +27,7 @@ export interface RouteOptions { * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) */ - app?: any; + app?: object; /** * Route authentication configuration. Value can be: @@ -43,7 +43,7 @@ export interface RouteOptions { * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind) */ - bind?: any; + bind?: object; /** * Default value: { privacy: 'default', statuses: [200], otherwise: 'no-cache' }. @@ -93,8 +93,9 @@ export interface RouteOptions { * Default value: none. * Route-level request extension points by setting the option to an object with a key for each of the desired extension points ('onRequest' is not allowed), and the value is the same as the server.ext(events) event argument. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) */ - ext?: any; //TODO need to review and rewrite this definition // I saw again and I keep not understanding. + ext?: object; /** * Default value: { relativeTo: '.' }. @@ -114,7 +115,7 @@ export interface RouteOptions { * Note: handlers using a fat arrow style function cannot be bound to any bind property. Instead, the bound context is available under h.context. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler) */ - handler?: Lifecycle.Method | Object; //TODO need to review + handler?: Lifecycle.Method | object; /** * Default value: none. diff --git a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts index 52a7b732a3..55aa77eba1 100644 --- a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts +++ b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts @@ -7,7 +7,7 @@ import {Lifecycle} from "hapi"; * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme) */ -export type ServerAuthSchemeOptions = any; +export type ServerAuthSchemeOptions = object; /** * the method implementing the scheme with signature function(server, options) where: @@ -28,7 +28,7 @@ export interface ServerAuthSchemeObject { /** * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object. */ - api?: any; + api?: object; /** * A lifecycle method function called for each incoming request configured with the authentication scheme. The diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts index 785cee3a9d..d49b12439d 100644 --- a/types/hapi/v17/definitions/server/server-auth.d.ts +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -77,7 +77,7 @@ export interface ServerAuth { * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) */ strategy(name: string, scheme: string): void; - strategy(name: string, scheme: string, options: any): void; + strategy(name: string, scheme: string, options: object): void; /** * Tests a request against an authentication strategy where: diff --git a/types/hapi/v17/definitions/server/server-ext.d.ts b/types/hapi/v17/definitions/server/server-ext.d.ts index 40d0969f09..ce73328b6c 100644 --- a/types/hapi/v17/definitions/server/server-ext.d.ts +++ b/types/hapi/v17/definitions/server/server-ext.d.ts @@ -91,7 +91,7 @@ export interface RequestExtPointFunction extends Lifecycle.Method { export interface ServerExtOptions { before: string | string[]; after: string | string[]; - bind: any; + bind: object; sandbox?: 'server' | 'plugin'; } diff --git a/types/hapi/v17/definitions/server/server-inject.d.ts b/types/hapi/v17/definitions/server/server-inject.d.ts index cb04ba3aab..21ba1a8afa 100644 --- a/types/hapi/v17/definitions/server/server-inject.d.ts +++ b/types/hapi/v17/definitions/server/server-inject.d.ts @@ -23,9 +23,9 @@ import * as Shot from "shot"; * For context [Shot module](https://github.com/hapijs/shot) */ export interface ServerInjectOptions extends Shot.RequestOptions { - credentials?: any; - artifacts?: any; - app?: any; + credentials?: object; + artifacts?: object; + app?: object; plugins?: PluginsStates; allowInternals?: boolean; } @@ -45,6 +45,6 @@ export interface ServerInjectOptions extends Shot.RequestOptions { * For context [Shot module](https://github.com/hapijs/shot) */ export interface ServerInjectResponse extends Shot.ResponseObject { - result: any; + result: object | undefined; request: Request; } diff --git a/types/hapi/v17/definitions/server/server-method.d.ts b/types/hapi/v17/definitions/server/server-method.d.ts index 9806ffc5cb..e24f36cf74 100644 --- a/types/hapi/v17/definitions/server/server-method.d.ts +++ b/types/hapi/v17/definitions/server/server-method.d.ts @@ -8,7 +8,8 @@ import * as catbox from "catbox"; * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ export interface ServerMethod { - (args: any[], flags: {ttl?: number}): any; +// (args: any[], flags: {ttl?: number}): any; + (...args: any[]): any; // TODO it needs review. Look the doc: the first param is a ...args and the second is "flags". Typescript supports ...args only in the last param } /** @@ -29,7 +30,7 @@ export interface ServerMethodCache extends catbox.PolicyOptions { * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ export interface ServerMethodOptions { - bind: any; + bind: object; cache: ServerMethodCache; generateKey: Function; } diff --git a/types/hapi/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts index 4273a01988..dd96c8ea3a 100644 --- a/types/hapi/v17/definitions/server/server-options.d.ts +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -26,7 +26,7 @@ export interface ServerOptions { * Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) */ - app?: any; + app?: object; /** * Default value: true. diff --git a/types/hapi/v17/definitions/server/server-realm.d.ts b/types/hapi/v17/definitions/server/server-realm.d.ts index 289ea48018..ba60524ebd 100644 --- a/types/hapi/v17/definitions/server/server-realm.d.ts +++ b/types/hapi/v17/definitions/server/server-realm.d.ts @@ -1,8 +1,8 @@ import {PluginsStates} from "../plugin/plugin"; /** - 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). + * 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: */ @@ -16,11 +16,11 @@ export interface ServerRealm { } }; /** the realm of the parent server object, or null for the root server. */ - parent: any | null; + parent: object | null; /** the active plugin name (empty string if at the server root). */ plugin: string; /** the plugin options object passed at registration. */ - pluginOptions: any; // OptionsPassedToPlugin; + pluginOptions: object; /** plugin-specific state to be shared only among activities sharing the same active state. plugins is an object where each key is a plugin name and the value is the plugin state. */ plugins: PluginsStates; /** settings overrides */ @@ -28,6 +28,6 @@ export interface ServerRealm { files: { relativeTo: string; }; - bind: any; + bind: object; }; } diff --git a/types/hapi/v17/definitions/server/server-register.d.ts b/types/hapi/v17/definitions/server/server-register.d.ts index 14746bc85a..a16db4547b 100644 --- a/types/hapi/v17/definitions/server/server-register.d.ts +++ b/types/hapi/v17/definitions/server/server-register.d.ts @@ -28,5 +28,5 @@ export interface ServerRegisterOptions { */ export interface ServerRegisterPluginObject extends ServerRegisterOptions { plugin: Plugin; - options?: any; + options?: object; } diff --git a/types/hapi/v17/definitions/server/server-route.d.ts b/types/hapi/v17/definitions/server/server-route.d.ts index 70e0bf1d34..efcc910f57 100644 --- a/types/hapi/v17/definitions/server/server-route.d.ts +++ b/types/hapi/v17/definitions/server/server-route.d.ts @@ -37,11 +37,11 @@ export interface ServerRoute { /** * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. */ - options?: Object | ((server: Server) => Function); + options?: object | ((server: Server) => Function); /** * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. */ - rules?: any; + rules?: object; } diff --git a/types/hapi/v17/definitions/server/server-state-options.d.ts b/types/hapi/v17/definitions/server/server-state-options.d.ts index 289507b849..e650309d95 100644 --- a/types/hapi/v17/definitions/server/server-state-options.d.ts +++ b/types/hapi/v17/definitions/server/server-state-options.d.ts @@ -43,13 +43,13 @@ export interface ServerStateCookieOptions { * * 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 + integrity?: object; // TODO make iron definitions and getting typing from iron. Needs review! 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 + iron?: object; // TODO make iron definitions and getting typing from iron. Needs review! /** 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. */ diff --git a/types/hapi/v17/definitions/server/server-state.d.ts b/types/hapi/v17/definitions/server/server-state.d.ts index 1331d32e4a..32107b8f07 100644 --- a/types/hapi/v17/definitions/server/server-state.d.ts +++ b/types/hapi/v17/definitions/server/server-state.d.ts @@ -23,7 +23,7 @@ export interface ServerState { * The server cookies manager. * Access: read only and statehood public interface. */ - readonly states: any; + readonly states: object; /** * The server cookies manager settings. The settings are based on the values configured in [server.options.state](https://github.com/hapijs/hapi/blob/master/API.md#server.options.state). @@ -34,7 +34,7 @@ export interface ServerState { * An object containing the configuration of each cookie added via [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()) where each key is the * cookie name and value is the configuration object. */ - readonly cookies: any; // TODO what the difference between this one and the settings above? This one should be an array? + readonly cookies: object; /** * An array containing the names of all configued cookies. diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 8f0e792a06..44ab2a5280 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -65,7 +65,7 @@ export class Server extends Podium { * Initialized with an empty object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) */ - app?: any; + app?: object; /** * Server Auth: properties and methods @@ -104,7 +104,7 @@ export class Server extends Podium { */ event(events: ServerEventsApplication): void; event(events: ServerEventsApplication[]): void; - + /** * Access: podium public interface. * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. @@ -177,7 +177,7 @@ export class Server extends Podium { * the server.plugins[name] object directly or via the server.expose() method. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) */ - plugins: any; + plugins: object; /** * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When @@ -233,7 +233,7 @@ export class Server extends Podium { * When setting a context inside a plugin, the context is applied only to methods set up by the plugin. Note that the context applies only to routes and extensions added after it has been set. Ignored if the method being bound is an arrow function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext) */ - bind(context: any): void; + bind(context: object): void; /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) @@ -348,7 +348,7 @@ export class Server extends Podium { * objects. Instead favor server.expose(key, value), which only copies a reference to value. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj) */ - expose(obj: Object): void; + expose(obj: object): void; /** * Registers an extension function in one of the request lifecycle extension points where: @@ -441,7 +441,7 @@ export class Server extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) */ - log(tags: string | string[], data?: string | Object | (() => Function), timestamp?: number): void; + log(tags: string | string[], data?: string | object | (() => Function), timestamp?: number): void; /** * Looks up a route configuration where: @@ -556,8 +556,8 @@ export class Server extends Podium { * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) */ - rules(processor: (rules: any, info: {method: string, path: string, vhost?: string}) => Function): void; - rules(processor: (rules: any, info: {method: string, path: string, vhost?: string}) => Function, options: {validate: any}): void; // TODO needs implementation + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => Function): void; + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => Function, options: {validate: object}): void; // TODO needs implementation /** * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). From 9fb4ab18b394a9aec15afee86d80588dbba834f1 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 19:44:37 -0300 Subject: [PATCH 55/79] Replace Dictionary by Map supported in es6 --- types/hapi/v17/definitions/request/request.d.ts | 8 ++++---- types/hapi/v17/definitions/response/response-object.d.ts | 2 +- .../hapi/v17/definitions/route/route-options-payload.d.ts | 2 +- types/hapi/v17/definitions/route/route-options.d.ts | 6 +++--- types/hapi/v17/definitions/server/server-auth.d.ts | 2 +- types/hapi/v17/definitions/server/server-inject.d.ts | 2 +- types/hapi/v17/definitions/server/server-options.d.ts | 2 +- types/hapi/v17/definitions/server/server-state.d.ts | 4 ++-- types/hapi/v17/definitions/server/server.d.ts | 6 +++--- types/hapi/v17/definitions/util/util.d.ts | 6 ------ 10 files changed, 17 insertions(+), 23 deletions(-) diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 2a92b8a142..992a117b7d 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -61,7 +61,7 @@ export interface Request extends Podium { * The raw request headers (references request.raw.req.headers). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) */ - readonly headers: Util.Dictionary; + readonly headers: Map; /** * Request information: @@ -105,7 +105,7 @@ export interface Request extends Podium { /** * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). */ - readonly params: Util.Dictionary; + readonly params: Map; /** * An array containing all the path params values in the order they appeared in the path. @@ -131,7 +131,7 @@ export interface Request extends Podium { /** * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses. */ - readonly pre: Util.Dictionary; + readonly pre: Map; /** * Access: read / write (see limitations below). @@ -142,7 +142,7 @@ export interface Request extends Podium { /** * Same as pre but represented as the response object created by the pre method. */ - readonly preResponses: Util.Dictionary; + readonly preResponses: Map; /** * 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). diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index 71415c0b33..40b827d31b 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -52,7 +52,7 @@ export interface ResponseObject extends Podium { * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) */ - readonly headers: Util.Dictionary; + readonly headers: Map; /** * Default value: {}. diff --git a/types/hapi/v17/definitions/route/route-options-payload.d.ts b/types/hapi/v17/definitions/route/route-options-payload.d.ts index c48d09aa0c..79efc0d144 100644 --- a/types/hapi/v17/definitions/route/route-options-payload.d.ts +++ b/types/hapi/v17/definitions/route/route-options-payload.d.ts @@ -38,7 +38,7 @@ export interface RouteOptionsPayload { * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) */ - compression?: Util.Dictionary; + compression?: Map; /** * Default value: 'application/json'. diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index daf0005ddd..8284f9b21a 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -27,7 +27,7 @@ export interface RouteOptions { * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp) */ - app?: object; + app?: any; /** * Route authentication configuration. Value can be: @@ -65,7 +65,7 @@ export interface RouteOptions { * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) */ - compression?: Util.Dictionary; + compression?: Map; /** * Default value: false (no CORS headers). @@ -180,7 +180,7 @@ export interface RouteOptions { * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) */ - plugins?: Util.Dictionary; + plugins?: Map; /** * Default value: none. diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts index d49b12439d..56e13edc8d 100644 --- a/types/hapi/v17/definitions/server/server-auth.d.ts +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -27,7 +27,7 @@ export interface ServerAuth { * returned from its implementation function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) */ - api: Util.Dictionary; + api: Map; /** * Contains the default authentication configuration is a default strategy was set via diff --git a/types/hapi/v17/definitions/server/server-inject.d.ts b/types/hapi/v17/definitions/server/server-inject.d.ts index 21ba1a8afa..e398e1915e 100644 --- a/types/hapi/v17/definitions/server/server-inject.d.ts +++ b/types/hapi/v17/definitions/server/server-inject.d.ts @@ -25,7 +25,7 @@ import * as Shot from "shot"; export interface ServerInjectOptions extends Shot.RequestOptions { credentials?: object; artifacts?: object; - app?: object; + app?: any; plugins?: PluginsStates; allowInternals?: boolean; } diff --git a/types/hapi/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts index dd96c8ea3a..4273a01988 100644 --- a/types/hapi/v17/definitions/server/server-options.d.ts +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -26,7 +26,7 @@ export interface ServerOptions { * Note the difference between server.settings.app which is used to store static configuration values and server.app which is meant for storing run-time state. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp) */ - app?: object; + app?: any; /** * Default value: true. diff --git a/types/hapi/v17/definitions/server/server-state.d.ts b/types/hapi/v17/definitions/server/server-state.d.ts index 32107b8f07..bfc9568c51 100644 --- a/types/hapi/v17/definitions/server/server-state.d.ts +++ b/types/hapi/v17/definitions/server/server-state.d.ts @@ -39,7 +39,7 @@ export interface ServerState { /** * An array containing the names of all configued cookies. */ - readonly names: Util.Dictionary; + readonly names: string[]; /** * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). @@ -67,6 +67,6 @@ export interface ServerState { * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) */ - parse(header: string): Util.Dictionary; + parse(header: string): Map; } diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 44ab2a5280..4b82f4a8b4 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -65,7 +65,7 @@ export class Server extends Podium { * Initialized with an empty object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp) */ - app?: object; + app?: any; /** * Server Auth: properties and methods @@ -104,7 +104,7 @@ export class Server extends Podium { */ event(events: ServerEventsApplication): void; event(events: ServerEventsApplication[]): void; - + /** * Access: podium public interface. * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters. @@ -162,7 +162,7 @@ export class Server extends Podium { * server method name is an object property. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods */ - readonly methods: Util.Dictionary; + readonly methods: Map; /** * Provides access to the server MIME database used for setting content-type information. The object must not be diff --git a/types/hapi/v17/definitions/util/util.d.ts b/types/hapi/v17/definitions/util/util.d.ts index f92b23bb4d..9e2264a257 100644 --- a/types/hapi/v17/definitions/util/util.d.ts +++ b/types/hapi/v17/definitions/util/util.d.ts @@ -1,11 +1,5 @@ export namespace Util { - - export interface Dictionary { - [key: string]: T; - } - export type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_LOWERCASE; export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; - } From 81e58330cca9951cfc9eb9781a6295957af385fb Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 19:52:20 -0300 Subject: [PATCH 56/79] Add h.redirect() without param to work with hapijs official tests. --- types/hapi/v17/definitions/response/response-toolkit.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/hapi/v17/definitions/response/response-toolkit.d.ts b/types/hapi/v17/definitions/response/response-toolkit.d.ts index 0ab64f10b0..1157002f99 100644 --- a/types/hapi/v17/definitions/response/response-toolkit.d.ts +++ b/types/hapi/v17/definitions/response/response-toolkit.d.ts @@ -87,6 +87,7 @@ export interface ResponseToolkit { * @return Returns a response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) */ + redirect(): ResponseObject; redirect(uri: string): ResponseObject; /** From b74e40249b1270f30a28147a376d2ee17c3a85c1 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 20:48:07 -0300 Subject: [PATCH 57/79] Add ResponseEvent types. --- .../definitions/response/response-events.d.ts | 24 +++++++++++++++++++ .../definitions/response/response-object.d.ts | 8 +++---- types/hapi/v17/index.d.ts | 1 + 3 files changed, 29 insertions(+), 4 deletions(-) create mode 100644 types/hapi/v17/definitions/response/response-events.d.ts diff --git a/types/hapi/v17/definitions/response/response-events.d.ts b/types/hapi/v17/definitions/response/response-events.d.ts new file mode 100644 index 0000000000..469009087c --- /dev/null +++ b/types/hapi/v17/definitions/response/response-events.d.ts @@ -0,0 +1,24 @@ +import * as Podium from "podium"; + +/** + * Access: read only and the public podium interface. + * The response.events object supports the following events: + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + * [See docs](https://hapijs.com/api/17.0.1#-responseevents) + */ +export interface ResponseEvents extends Podium { + + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + */ + on(criteria: 'peak', listener: Function): void; + once(criteria: 'peak', listener: Function): void; + + /** + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ + on(criteria: 'finish', listener: Function): void; + once(criteria: 'finish', listener: Function): void; + +} diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index 40b827d31b..1cb2c27862 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -1,9 +1,9 @@ import {PluginsStates} from "../plugin/plugin"; -import {Util} from "../util/util"; import {ResponseSettings} from "./response-settings"; import {ServerStateCookieOptions} from "../server/server-state-options"; import * as Podium from "podium"; import {Json, Lifecycle} from "hapi"; +import {ResponseEvents} from "./response-events"; /** * Object where: @@ -40,11 +40,11 @@ export interface ResponseObject extends Podium { /** * 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 (). + * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). * [See docs](https://hapijs.com/api/17.0.1#-responseevents) */ - readonly events: object; // TODO need to be implemented. I didn't understand yet. + readonly events: ResponseEvents; /** * Default value: {}. diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index f2b0f40c22..3ded9fe2bf 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -20,6 +20,7 @@ export * from './definitions/request/request-info' export * from './definitions/request/request-route' /** RESPONSE */ +export * from './definitions/response/response-events' export * from './definitions/response/response-object' export * from './definitions/response/response-settings' export * from './definitions/response/response-toolkit' From baeccd245e804f5fa82b9160aaaa368d98be0aae Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 20:49:42 -0300 Subject: [PATCH 58/79] Add request.route.auth.access() method --- .../definitions/request/request-route.d.ts | 21 ++++++++++++++++++- .../hapi/v17/definitions/request/request.d.ts | 19 ++--------------- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/types/hapi/v17/definitions/request/request-route.d.ts b/types/hapi/v17/definitions/request/request-route.d.ts index 531b60f796..2917c00606 100644 --- a/types/hapi/v17/definitions/request/request-route.d.ts +++ b/types/hapi/v17/definitions/request/request-route.d.ts @@ -1,4 +1,4 @@ -import {RouteOptions, ServerRealm, Util} from "hapi"; +import {RouteOptions, ServerRealm, Util, Request} from "hapi"; /** * The request route information object, where: @@ -11,16 +11,35 @@ import {RouteOptions, ServerRealm, Util} from "hapi"; * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) */ export interface RequestRoute { + /** the route HTTP method. */ method: Util.HTTP_METHODS_PARTIAL; + /** the route path. */ path: string; + /** the route vhost option if configured. */ vhost?: string | string[]; + /** the active realm associated with the route.*/ realm: ServerRealm; + /** the route options object with all defaults applied. */ settings: RouteOptions; + /** the route internal normalized string representing the normalized path. */ fingerprint: string; + + auth: { + /** + * Validates a request against the route's authentication access configuration, where: + * @param request - the request object. + * @return Return value: true if the request would have passed the route's access requirements. + * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. + * If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route requires any authentication. + * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) + */ + access(request: Request): boolean; + } + } diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 992a117b7d..7e7ec43e7c 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -160,14 +160,9 @@ export interface Request extends Podium { }; /** - * 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. + * The request route information object and method * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute) + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest) */ readonly route: RequestRoute; @@ -209,16 +204,6 @@ export interface Request extends Podium { log(tags: string, data?: string | object | (() => string | object)): void; log(tags: string[], data?: string | object | (() => string | object)): void; - /** - * Validates a request against the route's authentication access configuration, where: - * @param request - the request object. - * @return Return value: true if the request would have passed the route's access requirements. - * Note that the route's authentication mode and strategies are ignored. The only match is made between the request.auth.credentials scope and entity information and the route access configuration. - * If the route uses dynamic scopes, the scopes are constructed against the request.query, request.params, request.payload, and request.auth.credentials which may or may not match between the route and the request's route. If this method is called using a request that has not been authenticated (yet or not at all), it will return false if the route requires any authentication. - * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest) - */ - // TODO how to implement it? It is a function inside route.auth! We have another "route" properti in this file. (The v16 doesn't have this option) - /** * Changes the request method before the router begins processing the request where: * @param method - is the request HTTP method (e.g. 'GET'). From 32bfe6b2889d846398e0ddf1e155dcc2ffdb4156 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 20:51:40 -0300 Subject: [PATCH 59/79] Add "Function" support param in server.events.emit() --- types/hapi/v17/definitions/server/server-events.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/hapi/v17/definitions/server/server-events.d.ts b/types/hapi/v17/definitions/server/server-events.d.ts index 16e81f34ef..8d07ee0b5b 100644 --- a/types/hapi/v17/definitions/server/server-events.d.ts +++ b/types/hapi/v17/definitions/server/server-events.d.ts @@ -81,7 +81,7 @@ export interface ServerEvents extends Podium { * Note that events must be registered before they can be emitted or subscribed to by calling server.event(events). This is done to detect event name misspelling and invalid event activities. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsemitcriteria-data) */ - emit(criteria: string, data: any): void; + emit(criteria: string, data: any | Function): void; emit(criteria: {name: string, channel?: string, tags?: string | string[]}, data: any): void; /** From aff418b46dbb3407b39145358fefc7d4caed0b67 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Fri, 8 Dec 2017 21:07:53 -0300 Subject: [PATCH 60/79] Optimize imports. --- types/hapi/v17/definitions/plugin/plugin.d.ts | 3 +-- .../definitions/request/request-route.d.ts | 2 +- .../hapi/v17/definitions/request/request.d.ts | 9 +------ .../definitions/response/response-object.d.ts | 6 +---- .../response/response-toolkit.d.ts | 3 +-- .../route/route-options-payload.d.ts | 2 +- .../route/route-options-response.d.ts | 2 +- .../v17/definitions/route/route-options.d.ts | 25 ++++++++++--------- .../server/server-auth-scheme.d.ts | 5 +--- .../v17/definitions/server/server-auth.d.ts | 5 +--- .../v17/definitions/server/server-ext.d.ts | 2 +- .../v17/definitions/server/server-inject.d.ts | 2 +- .../definitions/server/server-options.d.ts | 3 +-- .../v17/definitions/server/server-realm.d.ts | 2 +- .../v17/definitions/server/server-route.d.ts | 2 +- .../server/server-state-options.d.ts | 2 +- .../v17/definitions/server/server-state.d.ts | 1 - .../hapi/v17/definitions/util/lifecycle.d.ts | 4 +-- 18 files changed, 30 insertions(+), 50 deletions(-) diff --git a/types/hapi/v17/definitions/plugin/plugin.d.ts b/types/hapi/v17/definitions/plugin/plugin.d.ts index cda5c37f4a..cd499c5645 100644 --- a/types/hapi/v17/definitions/plugin/plugin.d.ts +++ b/types/hapi/v17/definitions/plugin/plugin.d.ts @@ -1,5 +1,4 @@ -import {Server} from "../server/server"; -import {ServerRegisterOptions} from "hapi"; +import {Server, ServerRegisterOptions} from "hapi"; export interface PluginsStates { [pluginName: string]: any; diff --git a/types/hapi/v17/definitions/request/request-route.d.ts b/types/hapi/v17/definitions/request/request-route.d.ts index 2917c00606..fbafd033a6 100644 --- a/types/hapi/v17/definitions/request/request-route.d.ts +++ b/types/hapi/v17/definitions/request/request-route.d.ts @@ -1,4 +1,4 @@ -import {RouteOptions, ServerRealm, Util, Request} from "hapi"; +import {Request, RouteOptions, ServerRealm, Util} from "hapi"; /** * The request route information object, where: diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 7e7ec43e7c..e22d1ed391 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -1,15 +1,8 @@ import * as stream from "stream"; import * as url from "url"; import * as http from "http"; -import {Server} from "../server/server"; -import {ResponseObject} from "../response/response-object"; -import {Util} from "../util/util"; -import {PluginsStates} from "../plugin/plugin"; -import {RequestRoute} from "./request-route"; -import {RequestAuth} from "./request-auth"; -import {RequestInfo} from "./request-info"; import * as Podium from "podium"; -import {RequestEvents} from "hapi"; +import {PluginsStates, RequestAuth, RequestEvents, RequestInfo, RequestRoute, ResponseObject, Server, Util} from "hapi"; /** * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed. diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index 1cb2c27862..28afdbba0a 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -1,9 +1,5 @@ -import {PluginsStates} from "../plugin/plugin"; -import {ResponseSettings} from "./response-settings"; -import {ServerStateCookieOptions} from "../server/server-state-options"; import * as Podium from "podium"; -import {Json, Lifecycle} from "hapi"; -import {ResponseEvents} from "./response-events"; +import {Json, Lifecycle, PluginsStates, ResponseEvents, ResponseSettings, ServerStateCookieOptions} from "hapi"; /** * Object where: diff --git a/types/hapi/v17/definitions/response/response-toolkit.d.ts b/types/hapi/v17/definitions/response/response-toolkit.d.ts index 1157002f99..41fcf0d62a 100644 --- a/types/hapi/v17/definitions/response/response-toolkit.d.ts +++ b/types/hapi/v17/definitions/response/response-toolkit.d.ts @@ -1,5 +1,4 @@ -import {ServerRealm, ServerStateCookieOptions} from "hapi"; -import {ResponseObject} from "./response-object"; +import {ResponseObject, ServerRealm, ServerStateCookieOptions} from "hapi"; /** * See more about Lifecycle diff --git a/types/hapi/v17/definitions/route/route-options-payload.d.ts b/types/hapi/v17/definitions/route/route-options-payload.d.ts index 79efc0d144..5213f2c230 100644 --- a/types/hapi/v17/definitions/route/route-options-payload.d.ts +++ b/types/hapi/v17/definitions/route/route-options-payload.d.ts @@ -1,4 +1,4 @@ -import {Util, Lifecycle} from "hapi"; +import {Lifecycle} from "hapi"; /** * The value must be one of: diff --git a/types/hapi/v17/definitions/route/route-options-response.d.ts b/types/hapi/v17/definitions/route/route-options-response.d.ts index 16c2249e29..64318af3d9 100644 --- a/types/hapi/v17/definitions/route/route-options-response.d.ts +++ b/types/hapi/v17/definitions/route/route-options-response.d.ts @@ -1,4 +1,4 @@ -import {Lifecycle, Util} from "hapi"; +import {Lifecycle} from "hapi"; import {ValidationOptions} from "joi"; /** diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index 8284f9b21a..a1fc8814ec 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -1,15 +1,16 @@ -import {RouteOptionsAccess} from "./route-options-access"; -import {RouteOptionsCache} from "./route-options-cache"; -import {Util} 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 {RouteOptionsValidate} from "./route-options-validate"; -import {PluginSpecificConfiguration} from "../plugin/plugin"; -import {Json} from "../util/json"; -import {RouteOptionsPreArray} from "./route-options-pre"; -import {Lifecycle} from "hapi"; +import { + Json, + Lifecycle, + PluginSpecificConfiguration, + RouteOptionsAccess, + RouteOptionsCache, + RouteOptionsCors, + RouteOptionsPayload, + RouteOptionsPreArray, + RouteOptionsResponse, + RouteOptionsSecure, + RouteOptionsValidate +} from "hapi"; /** * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) diff --git a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts index 55aa77eba1..e8a4d2adbe 100644 --- a/types/hapi/v17/definitions/server/server-auth-scheme.d.ts +++ b/types/hapi/v17/definitions/server/server-auth-scheme.d.ts @@ -1,7 +1,4 @@ -import {Server} from "./server"; -import {ResponseToolkit} from "../response/response-toolkit"; -import {Request} from "../request/request"; -import {Lifecycle} from "hapi"; +import {Lifecycle, Request, ResponseToolkit, Server} from "hapi"; /** * The scheme options argument passed to server.auth.strategy() when instantiation a strategy. diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts index 56e13edc8d..c52a0a3cda 100644 --- a/types/hapi/v17/definitions/server/server-auth.d.ts +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -1,7 +1,4 @@ -import {ServerAuthScheme} from "./server-auth-scheme"; -import {Request} from "../request/request"; -import {RouteOptionsAccess} from "hapi"; -import {Util} from "../util/util"; +import {Request, RouteOptionsAccess, ServerAuthScheme} from "hapi"; /** * The authentication credentials object diff --git a/types/hapi/v17/definitions/server/server-ext.d.ts b/types/hapi/v17/definitions/server/server-ext.d.ts index ce73328b6c..02853a2888 100644 --- a/types/hapi/v17/definitions/server/server-ext.d.ts +++ b/types/hapi/v17/definitions/server/server-ext.d.ts @@ -1,4 +1,4 @@ -import {Server, Lifecycle} from "hapi"; +import {Lifecycle, Server} from "hapi"; /** * The extension point event name. The available extension points include the request extension points as well as the following server extension points: diff --git a/types/hapi/v17/definitions/server/server-inject.d.ts b/types/hapi/v17/definitions/server/server-inject.d.ts index e398e1915e..ddb3c3e7b7 100644 --- a/types/hapi/v17/definitions/server/server-inject.d.ts +++ b/types/hapi/v17/definitions/server/server-inject.d.ts @@ -1,4 +1,4 @@ -import {Request, PluginsStates} from "hapi"; +import {PluginsStates, Request} from "hapi"; import * as Shot from "shot"; /** diff --git a/types/hapi/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts index 4273a01988..407ebfd1c4 100644 --- a/types/hapi/v17/definitions/server/server-options.d.ts +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -1,9 +1,8 @@ -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"; +import {PluginSpecificConfiguration, RouteOptions, ServerOptionsCache} from "hapi"; /** * he server options control the behavior of the server object. Note that the options object is deeply cloned diff --git a/types/hapi/v17/definitions/server/server-realm.d.ts b/types/hapi/v17/definitions/server/server-realm.d.ts index ba60524ebd..cfab9b75b7 100644 --- a/types/hapi/v17/definitions/server/server-realm.d.ts +++ b/types/hapi/v17/definitions/server/server-realm.d.ts @@ -1,4 +1,4 @@ -import {PluginsStates} from "../plugin/plugin"; +import {PluginsStates} from "hapi"; /** * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm container specific to that registration. It allows each plugin to maintain its own settings without leaking and affecting other plugins. diff --git a/types/hapi/v17/definitions/server/server-route.d.ts b/types/hapi/v17/definitions/server/server-route.d.ts index efcc910f57..c2d972c631 100644 --- a/types/hapi/v17/definitions/server/server-route.d.ts +++ b/types/hapi/v17/definitions/server/server-route.d.ts @@ -1,4 +1,4 @@ -import {Util, Lifecycle, Server} from "hapi"; +import {Lifecycle, Server, Util} from "hapi"; /** * A route configuration object or an array of configuration objects where each object contains: diff --git a/types/hapi/v17/definitions/server/server-state-options.d.ts b/types/hapi/v17/definitions/server/server-state-options.d.ts index e650309d95..55f749792f 100644 --- a/types/hapi/v17/definitions/server/server-state-options.d.ts +++ b/types/hapi/v17/definitions/server/server-state-options.d.ts @@ -1,4 +1,4 @@ -import {Request} from "../request/request"; +import {Request} from "hapi"; /** * Optional cookie settings diff --git a/types/hapi/v17/definitions/server/server-state.d.ts b/types/hapi/v17/definitions/server/server-state.d.ts index bfc9568c51..e09937f32e 100644 --- a/types/hapi/v17/definitions/server/server-state.d.ts +++ b/types/hapi/v17/definitions/server/server-state.d.ts @@ -1,5 +1,4 @@ import {ServerStateCookieOptions} from "hapi"; -import {Util} from "hapi"; /** * A single object or an array of object where each contains: diff --git a/types/hapi/v17/definitions/util/lifecycle.d.ts b/types/hapi/v17/definitions/util/lifecycle.d.ts index 583fdf3c28..87dcf8ff1a 100644 --- a/types/hapi/v17/definitions/util/lifecycle.d.ts +++ b/types/hapi/v17/definitions/util/lifecycle.d.ts @@ -1,6 +1,6 @@ -import * as Boom from "../../../../boom/index"; +import * as Boom from "boom"; import * as stream from "stream"; -import {ResponseToolkit, Request} from "hapi"; +import {Request, ResponseToolkit} from "hapi"; export namespace Lifecycle { From b453000bc5ca0cc89e2e3c0a082fa3ae0557148a Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 12:00:10 -0300 Subject: [PATCH 61/79] Going back with Dictionary. It didn't work as expected :-/ --- types/hapi/v17/definitions/request/request.d.ts | 10 +++++----- .../hapi/v17/definitions/response/response-object.d.ts | 4 ++-- .../v17/definitions/route/route-options-payload.d.ts | 4 ++-- .../v17/definitions/route/route-options-response.d.ts | 4 ++-- types/hapi/v17/definitions/route/route-options.d.ts | 7 ++++--- types/hapi/v17/definitions/server/server-auth.d.ts | 4 ++-- types/hapi/v17/definitions/server/server-state.d.ts | 4 ++-- types/hapi/v17/definitions/server/server.d.ts | 2 +- types/hapi/v17/definitions/util/util.d.ts | 6 ++++++ 9 files changed, 26 insertions(+), 19 deletions(-) diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index e22d1ed391..a9a8c8b6d2 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -54,7 +54,7 @@ export interface Request extends Podium { * The raw request headers (references request.raw.req.headers). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders) */ - readonly headers: Map; + readonly headers: Util.Dictionary; /** * Request information: @@ -98,7 +98,7 @@ export interface Request extends Podium { /** * An object where each key is a path parameter name with matching value as described in [Path parameters](https://github.com/hapijs/hapi/blob/master/API.md#path-parameters). */ - readonly params: Map; + readonly params: Util.Dictionary; /** * An array containing all the path params values in the order they appeared in the path. @@ -124,7 +124,7 @@ export interface Request extends Podium { /** * An object where each key is the name assigned by a route pre-handler methods function. The values are the raw values provided to the continuation function as argument. For the wrapped response object, use responses. */ - readonly pre: Map; + readonly pre: Util.Dictionary; /** * Access: read / write (see limitations below). @@ -135,7 +135,7 @@ export interface Request extends Podium { /** * Same as pre but represented as the response object created by the pre method. */ - readonly preResponses: Map; + readonly preResponses: Util.Dictionary; /** * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query attribute as an unparsed string). @@ -168,7 +168,7 @@ export interface Request extends Podium { /** * An object containing parsed HTTP state information (cookies) where each key is the cookie name and value is the matching cookie content after processing using any registered cookie definition. */ - readonly state: Map; + readonly state: Util.Dictionary; /** * The parsed request URI. diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index 28afdbba0a..378fee420f 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -1,5 +1,5 @@ import * as Podium from "podium"; -import {Json, Lifecycle, PluginsStates, ResponseEvents, ResponseSettings, ServerStateCookieOptions} from "hapi"; +import {Json, Lifecycle, PluginsStates, ResponseEvents, ResponseSettings, ServerStateCookieOptions, Util} from "hapi"; /** * Object where: @@ -48,7 +48,7 @@ export interface ResponseObject extends Podium { * Note that this is an incomplete list of headers to be included with the response. Additional headers will be added once the response is prepared for transmission. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders) */ - readonly headers: Map; + readonly headers: Util.Dictionary; /** * Default value: {}. diff --git a/types/hapi/v17/definitions/route/route-options-payload.d.ts b/types/hapi/v17/definitions/route/route-options-payload.d.ts index 5213f2c230..a13db35c32 100644 --- a/types/hapi/v17/definitions/route/route-options-payload.d.ts +++ b/types/hapi/v17/definitions/route/route-options-payload.d.ts @@ -1,4 +1,4 @@ -import {Lifecycle} from "hapi"; +import {Lifecycle, Util} from "hapi"; /** * The value must be one of: @@ -38,7 +38,7 @@ export interface RouteOptionsPayload { * An object where each key is a content-encoding name and each value is an object with the desired decoder settings. Note that encoder settings are set in compression. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression) */ - compression?: Map; + compression?: Util.Dictionary; /** * Default value: 'application/json'. diff --git a/types/hapi/v17/definitions/route/route-options-response.d.ts b/types/hapi/v17/definitions/route/route-options-response.d.ts index 64318af3d9..a1c4d71a75 100644 --- a/types/hapi/v17/definitions/route/route-options-response.d.ts +++ b/types/hapi/v17/definitions/route/route-options-response.d.ts @@ -1,4 +1,4 @@ -import {Lifecycle} from "hapi"; +import {Lifecycle, Util} from "hapi"; import {ValidationOptions} from "joi"; /** @@ -79,6 +79,6 @@ export interface RouteOptionsResponse { * status is set to an object where each key is a 3 digit HTTP status code and the value has the same definition as schema. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus) */ - status?: Map; + status?: Util.Dictionary; } diff --git a/types/hapi/v17/definitions/route/route-options.d.ts b/types/hapi/v17/definitions/route/route-options.d.ts index a1fc8814ec..2bc2542f4a 100644 --- a/types/hapi/v17/definitions/route/route-options.d.ts +++ b/types/hapi/v17/definitions/route/route-options.d.ts @@ -9,7 +9,8 @@ import { RouteOptionsPreArray, RouteOptionsResponse, RouteOptionsSecure, - RouteOptionsValidate + RouteOptionsValidate, + Util } from "hapi"; /** @@ -66,7 +67,7 @@ export interface RouteOptions { * An object where each key is a content-encoding name and each value is an object with the desired encoder settings. Note that decoder settings are set in compression. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression) */ - compression?: Map; + compression?: Util.Dictionary; /** * Default value: false (no CORS headers). @@ -181,7 +182,7 @@ export interface RouteOptions { * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins) */ - plugins?: Map; + plugins?: Util.Dictionary; /** * Default value: none. diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts index c52a0a3cda..0d0bafc7e1 100644 --- a/types/hapi/v17/definitions/server/server-auth.d.ts +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -1,4 +1,4 @@ -import {Request, RouteOptionsAccess, ServerAuthScheme} from "hapi"; +import {Request, RouteOptionsAccess, ServerAuthScheme, Util} from "hapi"; /** * The authentication credentials object @@ -24,7 +24,7 @@ export interface ServerAuth { * returned from its implementation function. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi) */ - api: Map; + api: Util.Dictionary; /** * Contains the default authentication configuration is a default strategy was set via diff --git a/types/hapi/v17/definitions/server/server-state.d.ts b/types/hapi/v17/definitions/server/server-state.d.ts index e09937f32e..f233956a29 100644 --- a/types/hapi/v17/definitions/server/server-state.d.ts +++ b/types/hapi/v17/definitions/server/server-state.d.ts @@ -1,4 +1,4 @@ -import {ServerStateCookieOptions} from "hapi"; +import {ServerStateCookieOptions, Util} from "hapi"; /** * A single object or an array of object where each contains: @@ -66,6 +66,6 @@ export interface ServerState { * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie parsing (e.g. when server parsing is disabled). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader) */ - parse(header: string): Map; + parse(header: string): Util.Dictionary; } diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 4b82f4a8b4..2af9a5edf0 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -162,7 +162,7 @@ export class Server extends Podium { * server method name is an object property. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods */ - readonly methods: Map; + readonly methods: Util.Dictionary; /** * Provides access to the server MIME database used for setting content-type information. The object must not be diff --git a/types/hapi/v17/definitions/util/util.d.ts b/types/hapi/v17/definitions/util/util.d.ts index 9e2264a257..f92b23bb4d 100644 --- a/types/hapi/v17/definitions/util/util.d.ts +++ b/types/hapi/v17/definitions/util/util.d.ts @@ -1,5 +1,11 @@ export namespace Util { + + export interface Dictionary { + [key: string]: T; + } + export type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options'; export type HTTP_METHODS_PARTIAL = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | HTTP_METHODS_PARTIAL_LOWERCASE; export type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL; + } From 6fd4625f823dc6ad40559c1f84987f4f65bf143d Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 12:03:06 -0300 Subject: [PATCH 62/79] Add more tests files. --- types/hapi/v17/test/index.test.d.ts | 2 ++ types/hapi/v17/test/reply/state_cookie.ts | 1 - types/hapi/v17/test/request/get-log.ts | 30 +++++++++++++++++++++++ types/hapi/v17/test/request/query.ts | 27 ++++++++++++++++++++ 4 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 types/hapi/v17/test/request/get-log.ts create mode 100644 types/hapi/v17/test/request/query.ts diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index 35555aa057..fb3babbbec 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -19,6 +19,8 @@ export * from './reply/reply'; export * from './reply/state_cookie'; export * from './request/event-types'; +export * from './request/get-log'; +export * from './request/query'; export * from './response/error'; diff --git a/types/hapi/v17/test/reply/state_cookie.ts b/types/hapi/v17/test/reply/state_cookie.ts index 4ef420915e..9952ee0e77 100644 --- a/types/hapi/v17/test/reply/state_cookie.ts +++ b/types/hapi/v17/test/reply/state_cookie.ts @@ -1,7 +1,6 @@ // from https://hapijs.com/tutorials/cookies?lang=en_US import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute, ServerStateCookieOptions} from "hapi"; - const options: ServerOptions = { port: 8000, }; diff --git a/types/hapi/v17/test/request/get-log.ts b/types/hapi/v17/test/request/get-log.ts new file mode 100644 index 0000000000..89084cbb07 --- /dev/null +++ b/types/hapi/v17/test/request/get-log.ts @@ -0,0 +1,30 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data +import {Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const handler: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { + request.log(['test', 'error'], 'Test event'); + return 'path: ' + request.path; +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: handler +}; + +const server = new Server(options); +server.route(serverRoute); +server.start(); +console.log('Server started at: ' + server.info.uri); + +server.events.on('request', (request: Request, event: any, tags: any) => { + console.log(event); + console.log(tags); + if (tags.error) { + console.log(event); + } +}); diff --git a/types/hapi/v17/test/request/query.ts b/types/hapi/v17/test/request/query.ts new file mode 100644 index 0000000000..e176e078e9 --- /dev/null +++ b/types/hapi/v17/test/request/query.ts @@ -0,0 +1,27 @@ +// Added test in addition to docs, for request.query +import {Request, ResponseToolkit, Lifecycle, Server, ServerOptions, ServerRoute} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + +const handler: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { + const query = request.query as GetThingQuery; + // http://localhost:8000/?name=test + return `You asked for ${query.name}` +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: handler +}; + +interface GetThingQuery { + name: string; +} + +const server = new Server(options); +server.route(serverRoute); +server.start(); +console.log('Server started at: ' + server.info.uri); From 2cbd2d48e8cc91839437d77aa3ea55fe8260842d Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 16:41:54 -0300 Subject: [PATCH 63/79] Add more test files. --- types/hapi/v17/test/index.test.d.ts | 30 +++++++---- .../v17/test/{path => request}/catch-all.ts | 0 types/hapi/v17/test/request/get-log.ts | 1 - .../v17/test/{path => request}/parameters.ts | 0 .../v17/test/{reply => response}/continue.ts | 0 .../v17/test/{reply => response}/redirect.ts | 0 .../v17/test/{reply => response}/reply.ts | 4 +- .../test/{reply => response}/state_cookie.ts | 0 .../adding-routes.ts} | 5 +- types/hapi/v17/test/route/config.ts | 54 +++++++++++++++++++ types/hapi/v17/test/route/handler.ts | 9 ++++ .../a-simple-server.ts} | 0 types/hapi/v17/test/server/app.ts | 2 +- types/hapi/v17/test/server/info.ts | 16 +++--- types/hapi/v17/test/server/select.ts | 17 ++++++ .../v17/test/server/server-events-once.ts | 8 ++- types/hapi/v17/test/server/settings.ts | 12 +++++ types/hapi/v17/test/server/start.ts | 11 ++++ types/hapi/v17/test/server/stop.ts | 17 ++++++ types/hapi/v17/test/server/version.ts | 9 ++++ 20 files changed, 164 insertions(+), 31 deletions(-) rename types/hapi/v17/test/{path => request}/catch-all.ts (100%) rename types/hapi/v17/test/{path => request}/parameters.ts (100%) rename types/hapi/v17/test/{reply => response}/continue.ts (100%) rename types/hapi/v17/test/{reply => response}/redirect.ts (100%) rename types/hapi/v17/test/{reply => response}/reply.ts (92%) rename types/hapi/v17/test/{reply => response}/state_cookie.ts (100%) rename types/hapi/v17/test/{getting-started/02-adding-routes.ts => route/adding-routes.ts} (88%) create mode 100644 types/hapi/v17/test/route/config.ts create mode 100644 types/hapi/v17/test/route/handler.ts rename types/hapi/v17/test/{getting-started/01-creating-a-server.ts => server/a-simple-server.ts} (100%) create mode 100644 types/hapi/v17/test/server/select.ts create mode 100644 types/hapi/v17/test/server/settings.ts create mode 100644 types/hapi/v17/test/server/start.ts create mode 100644 types/hapi/v17/test/server/stop.ts create mode 100644 types/hapi/v17/test/server/version.ts diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index fb3babbbec..228ffdc02c 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -8,26 +8,36 @@ /// -/** Getting Started */ -export * from './getting-started/01-creating-a-server'; -export * from './getting-started/02-adding-routes'; -export * from './path/catch-all'; -export * from './path/parameters'; -export * from './reply/continue'; -export * from './reply/redirect'; -export * from './reply/reply'; -export * from './reply/state_cookie'; - +/** REQUEST */ +export * from './request/catch-all'; export * from './request/event-types'; export * from './request/get-log'; +export * from './request/parameters'; export * from './request/query'; +/** RESPONSE */ +export * from './response/continue'; export * from './response/error'; +export * from './response/redirect'; +export * from './response/reply'; +export * from './response/state_cookie'; +/** ROUTE */ +export * from './route/adding-routes'; +export * from './route/config'; +export * from './route/handler'; + +/** SERVER */ +export * from './server/a-simple-server'; export * from './server/app'; export * from './server/info'; +export * from './server/select'; export * from './server/server-events-once'; +export * from './server/settings'; +export * from './server/start'; +export * from './server/stop'; export * from './server/table'; +export * from './server/version'; diff --git a/types/hapi/v17/test/path/catch-all.ts b/types/hapi/v17/test/request/catch-all.ts similarity index 100% rename from types/hapi/v17/test/path/catch-all.ts rename to types/hapi/v17/test/request/catch-all.ts diff --git a/types/hapi/v17/test/request/get-log.ts b/types/hapi/v17/test/request/get-log.ts index 89084cbb07..047799c394 100644 --- a/types/hapi/v17/test/request/get-log.ts +++ b/types/hapi/v17/test/request/get-log.ts @@ -22,7 +22,6 @@ server.start(); console.log('Server started at: ' + server.info.uri); server.events.on('request', (request: Request, event: any, tags: any) => { - console.log(event); console.log(tags); if (tags.error) { console.log(event); diff --git a/types/hapi/v17/test/path/parameters.ts b/types/hapi/v17/test/request/parameters.ts similarity index 100% rename from types/hapi/v17/test/path/parameters.ts rename to types/hapi/v17/test/request/parameters.ts diff --git a/types/hapi/v17/test/reply/continue.ts b/types/hapi/v17/test/response/continue.ts similarity index 100% rename from types/hapi/v17/test/reply/continue.ts rename to types/hapi/v17/test/response/continue.ts diff --git a/types/hapi/v17/test/reply/redirect.ts b/types/hapi/v17/test/response/redirect.ts similarity index 100% rename from types/hapi/v17/test/reply/redirect.ts rename to types/hapi/v17/test/response/redirect.ts diff --git a/types/hapi/v17/test/reply/reply.ts b/types/hapi/v17/test/response/reply.ts similarity index 92% rename from types/hapi/v17/test/reply/reply.ts rename to types/hapi/v17/test/response/reply.ts index 185f80ed3d..a2d4c250ed 100644 --- a/types/hapi/v17/test/reply/reply.ts +++ b/types/hapi/v17/test/response/reply.ts @@ -17,7 +17,7 @@ const serverRoutes: ServerRoute[] = [ return response; } }, - // Chained notation + // chained notation { path: '/test2', method: 'GET', @@ -34,4 +34,4 @@ const server = new Server(options); server.route(serverRoutes); server.start(); -console.log('Server started at: ' + server.info.uri); \ No newline at end of file +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/reply/state_cookie.ts b/types/hapi/v17/test/response/state_cookie.ts similarity index 100% rename from types/hapi/v17/test/reply/state_cookie.ts rename to types/hapi/v17/test/response/state_cookie.ts diff --git a/types/hapi/v17/test/getting-started/02-adding-routes.ts b/types/hapi/v17/test/route/adding-routes.ts similarity index 88% rename from types/hapi/v17/test/getting-started/02-adding-routes.ts rename to types/hapi/v17/test/route/adding-routes.ts index 4f383c15dc..7d503502c2 100644 --- a/types/hapi/v17/test/getting-started/02-adding-routes.ts +++ b/types/hapi/v17/test/route/adding-routes.ts @@ -6,10 +6,9 @@ const options: ServerOptions = { }; const serverRoute: ServerRoute = { - path: '/test', + path: '/', method: 'GET', handler: function (request: Request, h: ResponseToolkit) { - console.log(request); return 'ok: ' + request.path; } }; @@ -19,7 +18,6 @@ const serverRoutes: ServerRoute[] = [ path: '/test1', method: 'GET', handler: function (request: Request, h: ResponseToolkit) { - console.log(request); return 'ok: ' + request.path; } }, @@ -27,7 +25,6 @@ const serverRoutes: ServerRoute[] = [ path: '/test2', method: 'GET', handler: function (request: Request, h: ResponseToolkit) { - console.log(request); return 'ok: ' + request.path; } }, diff --git a/types/hapi/v17/test/route/config.ts b/types/hapi/v17/test/route/config.ts new file mode 100644 index 0000000000..1ecabd0c56 --- /dev/null +++ b/types/hapi/v17/test/route/config.ts @@ -0,0 +1,54 @@ +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute, RouteOptions} from "hapi"; + +const options: ServerOptions = { + port: 8000, +}; + + +// different methods +var routeConfig: ServerRoute = { + path: '/signin', + method: 'PUT', + vhost: 'site.coms', +}; +var routeConfig: ServerRoute = { + path: '/signin', + method: '*' +}; +var routeConfig: ServerRoute = { + path: '/signin', + method: ['OPTIONS', '*'] +}; + +// different handlers +var routeConfig: ServerRoute = { + path: '/signin', + method: 'PUT', + handler: function (request: Request, h: ResponseToolkit) { + return 'ok'; + } +}; +var routeConfig: ServerRoute = { + path: '/signin', + method: 'PUT', + handler: function (request: Request, h: ResponseToolkit) { + return 'ok'; + } +}; + +const server = new Server(options); +server.route(routeConfig); + +// Handler in config +const user: RouteOptions = { + cache: { expiresIn: 5000 }, + handler: function (request: Request, h: ResponseToolkit) { + return { name: 'John' }; + } +}; + +server.route({method: 'GET', path: '/user', options: user }); +//server.route({ method: 'GET', path: '/public/{path*}', options: { cache: { privacy: 'public', expiresIn: 24 * 60 * 60 * 1000 } }, handler: { directory: { path: __dirname, listing: false, index: false } } }); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/route/handler.ts b/types/hapi/v17/test/route/handler.ts new file mode 100644 index 0000000000..fa20d7b677 --- /dev/null +++ b/types/hapi/v17/test/route/handler.ts @@ -0,0 +1,9 @@ +import {Lifecycle, Request, ResponseToolkit} from "hapi"; + +const handler: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { + return 'success'; +} + +const strictHandler: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { + return 123; +} diff --git a/types/hapi/v17/test/getting-started/01-creating-a-server.ts b/types/hapi/v17/test/server/a-simple-server.ts similarity index 100% rename from types/hapi/v17/test/getting-started/01-creating-a-server.ts rename to types/hapi/v17/test/server/a-simple-server.ts diff --git a/types/hapi/v17/test/server/app.ts b/types/hapi/v17/test/server/app.ts index ea376560b7..cfd0bd91a4 100644 --- a/types/hapi/v17/test/server/app.ts +++ b/types/hapi/v17/test/server/app.ts @@ -19,4 +19,4 @@ const serverRoute: ServerRoute = { server.route(serverRoute); server.start(); -console.log(`Server running at: ${server.info!.uri}`); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/info.ts b/types/hapi/v17/test/server/info.ts index 1fd15b240b..253a1b72aa 100644 --- a/types/hapi/v17/test/server/info.ts +++ b/types/hapi/v17/test/server/info.ts @@ -1,15 +1,15 @@ // From https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo -import {Server, ServerOptions} from "hapi"; -import assert = require('assert'); +import {Server} from "hapi"; +import * as assert from "assert"; -const options: ServerOptions = { +const server = new Server({ port: 8000, -}; -const server = new Server(options); +}); +server.start(); // check the correct port -if(server.info) assert(server.info.port === 8000); -assert(server.info !== null); +console.log(server.info); +if (server.info) assert(server.info.port === 8000); -server.start(); +assert(server.info !== null); console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/select.ts b/types/hapi/v17/test/server/select.ts new file mode 100644 index 0000000000..cdf2cfd1e7 --- /dev/null +++ b/types/hapi/v17/test/server/select.ts @@ -0,0 +1,17 @@ +// From https://hapijs.com/api/16.1.1#serverselectlabels +import {Server} from "hapi"; + +/* +const server = new Hapi.Server(); +server.connection({ port: 80, labels: ['a', 'b'] }); +server.connection({ port: 8080, labels: ['a', 'c'] }); +server.connection({ port: 8081, labels: ['b', 'c'] }); + +const a = server.select('a'); // 80, 8080 +const ac = a.select('c'); // 8080 +*/ +// TODO How do this with v17? + +const server = new Server({ + port: 8000, +}); diff --git a/types/hapi/v17/test/server/server-events-once.ts b/types/hapi/v17/test/server/server-events-once.ts index d36deb10bb..022cdb6f33 100644 --- a/types/hapi/v17/test/server/server-events-once.ts +++ b/types/hapi/v17/test/server/server-events-once.ts @@ -1,10 +1,6 @@ // from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; -const options: ServerOptions = { - port: 8000, -}; - const serverRoute: ServerRoute = { path: '/', method: 'GET', @@ -13,7 +9,9 @@ const serverRoute: ServerRoute = { } }; -const server = new Server(options); +const server = new Server({ + port: 8000, +}); server.route(serverRoute); server.event('test1'); server.event('test2'); diff --git a/types/hapi/v17/test/server/settings.ts b/types/hapi/v17/test/server/settings.ts new file mode 100644 index 0000000000..ebe7588b88 --- /dev/null +++ b/types/hapi/v17/test/server/settings.ts @@ -0,0 +1,12 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-serversettings +import {Server} from "hapi"; + +const server = new Server({ + port: 8000, + app: { + key: 'value' + } +}); +server.start(); + +console.log(server.settings.app); // { key: 'value' } diff --git a/types/hapi/v17/test/server/start.ts b/types/hapi/v17/test/server/start.ts new file mode 100644 index 0000000000..425c287842 --- /dev/null +++ b/types/hapi/v17/test/server/start.ts @@ -0,0 +1,11 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart +import {Server} from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/stop.ts b/types/hapi/v17/test/server/stop.ts new file mode 100644 index 0000000000..2e7f3f9b2b --- /dev/null +++ b/types/hapi/v17/test/server/stop.ts @@ -0,0 +1,17 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions +import {Server} from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.start(); +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); +server.events.on('stop', () => { + console.log('Server stoped.'); +}); +setTimeout(function() { + server.stop({ timeout: 10 * 1000 }); +}, 5 * 1000); diff --git a/types/hapi/v17/test/server/version.ts b/types/hapi/v17/test/server/version.ts new file mode 100644 index 0000000000..041a565f48 --- /dev/null +++ b/types/hapi/v17/test/server/version.ts @@ -0,0 +1,9 @@ +// From https://github.com/hapijs/hapi/blob/master/API.md#-serverversion +import {Server} from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.start(); +console.log(server.version); // 17.x.x From 6e56e7d01475358216be222d690cc350db99c771 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 17:34:00 -0300 Subject: [PATCH 64/79] Fix decorate() param. It must support the "toolkit" option. --- types/hapi/v17/definitions/server/server.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 2af9a5edf0..6674ceed2f 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -303,7 +303,7 @@ export class Server extends Podium { * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options) */ decorate(type: 'request', property: string, method: ((request: Request) => Function), options?: {apply: true; extend: false} ): void; - decorate(type: 'handler' | 'request' | 'reply' | 'server', property: string, method: Function, options?: {apply: boolean; extend: boolean} ): void; + decorate(type: 'handler' | 'request' | 'server' | 'toolkit', property: string, method: Function, options?: {apply: boolean; extend: boolean} ): void; /** * Used within a plugin to declare a required dependency on other plugins where: From 4d97af115e344c72a6e80d0c36636ec6f224680a Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 17:36:15 -0300 Subject: [PATCH 65/79] Fix mime property. It must be "any" like v16. --- types/hapi/v17/definitions/server/server.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 6674ceed2f..2cc215f627 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -2,7 +2,6 @@ import * as http from "http"; import * as catbox from "catbox"; import * as zlib from "zlib"; import * as Podium from "podium"; -import {MimosOptions} from "mimos"; import { PayloadCompressionDecoderSettings, Plugin, @@ -169,7 +168,7 @@ export class Server extends Podium { * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime) */ - mime: MimosOptions; + mime: any; /** * An object containing the values exposed by each registered plugin where each key is a plugin name and the values From a476fcedc1f5822bcc4b9d5582c0d7c87b7892a2 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 18:46:52 -0300 Subject: [PATCH 66/79] Many fix discovered with the tests. --- types/hapi/v17/definitions/plugin/plugin.d.ts | 2 +- .../v17/definitions/request/request-auth.d.ts | 2 +- .../response/response-toolkit.d.ts | 2 +- .../route/route-options-response.d.ts | 2 +- .../v17/definitions/server/server-auth.d.ts | 10 +--- .../v17/definitions/server/server-cache.d.ts | 42 +++++++++++++++ .../v17/definitions/server/server-inject.d.ts | 2 +- .../v17/definitions/server/server-route.d.ts | 2 +- types/hapi/v17/definitions/server/server.d.ts | 53 +++---------------- 9 files changed, 57 insertions(+), 60 deletions(-) create mode 100644 types/hapi/v17/definitions/server/server-cache.d.ts diff --git a/types/hapi/v17/definitions/plugin/plugin.d.ts b/types/hapi/v17/definitions/plugin/plugin.d.ts index cd499c5645..4340f804e1 100644 --- a/types/hapi/v17/definitions/plugin/plugin.d.ts +++ b/types/hapi/v17/definitions/plugin/plugin.d.ts @@ -22,7 +22,7 @@ export interface Plugin { * * server - the server object with a plugin-specific server.realm. * * options - any options passed to the plugin during registration via server.register(). */ - register: (server: Server, options: ServerRegisterOptions) => Function; + register: (server: Server, options: ServerRegisterOptions) => void; /** * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm diff --git a/types/hapi/v17/definitions/request/request-auth.d.ts b/types/hapi/v17/definitions/request/request-auth.d.ts index a11dd07467..72dd69a4b4 100644 --- a/types/hapi/v17/definitions/request/request-auth.d.ts +++ b/types/hapi/v17/definitions/request/request-auth.d.ts @@ -13,7 +13,7 @@ export interface RequestAuth { /** an artifact object received from the authentication strategy and used in authentication-related actions. */ artifacts: object; /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */ - credentials: object; + credentials: any; /** the authentication error is failed and mode set to 'try'. */ error: Error; /** true if the request has been successfully authenticated, otherwise false. */ diff --git a/types/hapi/v17/definitions/response/response-toolkit.d.ts b/types/hapi/v17/definitions/response/response-toolkit.d.ts index 41fcf0d62a..7c5b122c2f 100644 --- a/types/hapi/v17/definitions/response/response-toolkit.d.ts +++ b/types/hapi/v17/definitions/response/response-toolkit.d.ts @@ -33,7 +33,7 @@ export interface ResponseToolkit { * A response symbol. Provides access to the route or server context set via the route [bind](https://github.com/hapijs/hapi/blob/master/API.md#route.options.bind) * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()). */ - readonly context: Object; + readonly context: any; /** * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response. diff --git a/types/hapi/v17/definitions/route/route-options-response.d.ts b/types/hapi/v17/definitions/route/route-options-response.d.ts index a1c4d71a75..fa3c8f8560 100644 --- a/types/hapi/v17/definitions/route/route-options-response.d.ts +++ b/types/hapi/v17/definitions/route/route-options-response.d.ts @@ -9,7 +9,7 @@ export enum EmptyStatusCode { HTTP_204 = 204, } -export type RouteOptionsResponseSchema = boolean | ValidationOptions | ((value: object, options: object) => Function); +export type RouteOptionsResponseSchema = boolean | ValidationOptions | ((value: object, options: object) => any); /** * Processing rules for the outgoing response. diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts index 0d0bafc7e1..d8f1c257e6 100644 --- a/types/hapi/v17/definitions/server/server-auth.d.ts +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -1,13 +1,5 @@ import {Request, RouteOptionsAccess, ServerAuthScheme, Util} from "hapi"; -/** - * The authentication credentials object - * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) - */ -export interface ServerAuthenticatedCredentials { - -} - /** * An authentication configuration object using the same format as the route auth handler options. * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) @@ -86,7 +78,7 @@ export interface ServerAuth { * include verifying scope, entity, or other route properties. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request) */ - test(strategy: string, request: Request): ServerAuthenticatedCredentials; + test(strategy: string, request: Request): any; } diff --git a/types/hapi/v17/definitions/server/server-cache.d.ts b/types/hapi/v17/definitions/server/server-cache.d.ts new file mode 100644 index 0000000000..d21d3c2613 --- /dev/null +++ b/types/hapi/v17/definitions/server/server-cache.d.ts @@ -0,0 +1,42 @@ +import * as catbox from "catbox"; +import {ServerOptionsCache} from "hapi"; + +/** + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ +export interface ServerCache { + + /** + * Provisions a cache segment within the server cache facility where: + * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: + * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. + * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. + * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: + * - `id` - the `id` string or object provided to the `get()` method. + * - `flags` - an object used to pass back additional flags to the cache where: + * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. + * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. + * * staleTimeout - number of milliseconds to wait before checking if an item is stale. + * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. + * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. + * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. + * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. + * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). + * * cache - the cache name configured in server.cache. Defaults to the default cache. + * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. + * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. + * @return Catbox Policy. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) + */ + (options: ServerOptionsCache): catbox.Policy; + + /** + * Provisions a server cache as described in server.cache where: + * @param options - same as the server cache configuration options. + * @return Return value: none. + * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. + * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) + */ + provision(options: ServerOptionsCache): void; + +} diff --git a/types/hapi/v17/definitions/server/server-inject.d.ts b/types/hapi/v17/definitions/server/server-inject.d.ts index ddb3c3e7b7..d034bbf0a0 100644 --- a/types/hapi/v17/definitions/server/server-inject.d.ts +++ b/types/hapi/v17/definitions/server/server-inject.d.ts @@ -23,7 +23,7 @@ import * as Shot from "shot"; * For context [Shot module](https://github.com/hapijs/shot) */ export interface ServerInjectOptions extends Shot.RequestOptions { - credentials?: object; + credentials?: any; artifacts?: object; app?: any; plugins?: PluginsStates; diff --git a/types/hapi/v17/definitions/server/server-route.d.ts b/types/hapi/v17/definitions/server/server-route.d.ts index c2d972c631..b3c8e6fcee 100644 --- a/types/hapi/v17/definitions/server/server-route.d.ts +++ b/types/hapi/v17/definitions/server/server-route.d.ts @@ -37,7 +37,7 @@ export interface ServerRoute { /** * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. */ - options?: object | ((server: Server) => Function); + options?: object | ((server: Server) => object); /** * route custom rules object. The object is passed to each rules processor registered with server.rules(). Cannot be used if route.options.rules is defined. diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 2cc215f627..1f3654b1be 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -1,5 +1,4 @@ import * as http from "http"; -import * as catbox from "catbox"; import * as zlib from "zlib"; import * as Podium from "podium"; import { @@ -11,7 +10,7 @@ import { RequestRoute, ResponseToolkit, RouteCompressionEncoderSettings, - ServerAuth, + ServerAuth, ServerCache, ServerEvents, ServerEventsApplication, ServerExtEventsObject, @@ -27,7 +26,6 @@ import { ServerMethodConfigurationObject, ServerMethodOptions, ServerOptions, - ServerOptionsCache, ServerRealm, ServerRegisterOptions, ServerRegisterPluginObject, @@ -176,7 +174,7 @@ export class Server extends Podium { * the server.plugins[name] object directly or via the server.expose() method. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins) */ - plugins: object; + plugins: any; /** * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When @@ -237,42 +235,7 @@ export class Server extends Podium { /** * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) */ - cache: { - - /** - * Provisions a cache segment within the server cache facility where: - * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where: - * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. - * * expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records expire. Uses local time. Cannot be used together with expiresIn. - * * generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is async function(id, flags) where: - * - `id` - the `id` string or object provided to the `get()` method. - * - `flags` - an object used to pass back additional flags to the cache where: - * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy. - * * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. - * * staleTimeout - number of milliseconds to wait before checking if an item is stale. - * * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. - * * generateOnReadError - if false, an upstream cache read error will stop the cache.get() method from calling the generate function and will instead pass back the cache error. Defaults to true. - * * generateIgnoreWriteError - if false, an upstream cache write error when calling cache.get() will be passed back with the generated value when calling. Defaults to true. - * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. - * * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0 (no blocking of concurrent generateFunc calls beyond staleTimeout). - * * cache - the cache name configured in server.cache. Defaults to the default cache. - * * segment - string segment name, used to isolate cached items within the cache partition. When called within a plugin, defaults to '!name' where 'name' is the plugin name. When called within a server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin. - * * shared - if true, allows multiple cache provisions to share the same segment. Default to false. - * @return Catbox Policy. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions) - */ - (options: catbox.PolicyOptions): catbox.Policy; - - /** - * Provisions a server cache as described in server.cache where: - * @param options - same as the server cache configuration options. - * @return Return value: none. - * Note that if the server has been initialized or started, the cache will be automatically started to match the state of any other provisioned server cache. - * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions) - */ - provision(options: ServerOptionsCache): void; - - }; + cache: ServerCache; /** * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where: @@ -316,9 +279,9 @@ export class Server extends Podium { * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) */ dependency(dependencies: string): void; - dependency(dependencies: string, after: ((server: Server) => Function)): void; + dependency(dependencies: string, after: ((server: Server) => void)): void; dependency(dependencies: string[]): void; - dependency(dependencies: string[], after: ((server: Server) => Function)): void; + dependency(dependencies: string[], after: ((server: Server) => void)): void; /** * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: @@ -440,7 +403,7 @@ export class Server extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp) */ - log(tags: string | string[], data?: string | object | (() => Function), timestamp?: number): void; + log(tags: string | string[], data?: string | object | (() => any), timestamp?: number): void; /** * Looks up a route configuration where: @@ -555,8 +518,8 @@ export class Server extends Podium { * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) */ - rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => Function): void; - rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => Function, options: {validate: object}): void; // TODO needs implementation + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object): void; + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options: {validate: object}): void; // TODO needs implementation /** * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). From b65a79ab8bcb16f499ddc4861879792bacaf8e69 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 19:55:35 -0300 Subject: [PATCH 67/79] Many fix discovered with the tests cases. --- types/hapi/v17/definitions/server/server-method.d.ts | 6 +++--- types/hapi/v17/definitions/server/server-route.d.ts | 7 ++++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/types/hapi/v17/definitions/server/server-method.d.ts b/types/hapi/v17/definitions/server/server-method.d.ts index e24f36cf74..c7d6e01446 100644 --- a/types/hapi/v17/definitions/server/server-method.d.ts +++ b/types/hapi/v17/definitions/server/server-method.d.ts @@ -30,9 +30,9 @@ export interface ServerMethodCache extends catbox.PolicyOptions { * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ export interface ServerMethodOptions { - bind: object; - cache: ServerMethodCache; - generateKey: Function; + bind?: object; + cache?: ServerMethodCache; + generateKey?: Function; } /** diff --git a/types/hapi/v17/definitions/server/server-route.d.ts b/types/hapi/v17/definitions/server/server-route.d.ts index b3c8e6fcee..caaa348fe0 100644 --- a/types/hapi/v17/definitions/server/server-route.d.ts +++ b/types/hapi/v17/definitions/server/server-route.d.ts @@ -32,7 +32,7 @@ export interface ServerRoute { /** * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation. */ - handler?: Lifecycle.Method; + handler?: Lifecycle.Method | object; /** * additional route options. The options value can be an object or a function that returns an object using the signature function(server) where server is the server the route is being added to and this is bound to the current realm's bind option. @@ -44,4 +44,9 @@ export interface ServerRoute { */ rules?: object; + /** + * TODO: Missing documentation. Exist only in examples and test files. + */ + config?: any; + } From d91c350ad54b5751492eda6e295dbc4a10b647c4 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 20:25:18 -0300 Subject: [PATCH 68/79] Add more new test files, mainly Server test files. --- types/hapi/v17/test/index.test.d.ts | 39 +++++++++++++----- types/hapi/v17/test/request/catch-all.ts | 2 +- types/hapi/v17/test/request/event-types.ts | 11 +++-- types/hapi/v17/test/request/get-log.ts | 2 +- types/hapi/v17/test/request/parameters.ts | 2 +- types/hapi/v17/test/request/query.ts | 2 +- types/hapi/v17/test/response/continue.ts | 2 +- types/hapi/v17/test/response/error.ts | 2 +- types/hapi/v17/test/response/redirect.ts | 2 +- types/hapi/v17/test/response/reply.ts | 2 +- types/hapi/v17/test/route/config.ts | 2 +- types/hapi/v17/test/server/a-simple-server.ts | 11 ----- types/hapi/v17/test/server/select.ts | 17 -------- .../v17/test/server/{app.ts => server-app.ts} | 2 +- types/hapi/v17/test/server/server-auth-api.ts | 40 +++++++++++++++++++ .../v17/test/server/server-auth-default.ts | 35 ++++++++++++++++ .../hapi/v17/test/server/server-auth-test.ts | 40 +++++++++++++++++++ types/hapi/v17/test/server/server-bind.ts | 31 ++++++++++++++ .../v17/test/server/server-cache-provision.ts | 21 ++++++++++ types/hapi/v17/test/server/server-cache.ts | 23 +++++++++++ types/hapi/v17/test/server/server-decoder.ts | 8 ++++ .../v17/test/server/server-decorations.ts | 25 ++++++++++++ types/hapi/v17/test/server/server-encoder.ts | 8 ++++ .../v17/test/server/server-events-once.ts | 2 +- types/hapi/v17/test/server/server-events.ts | 11 +++++ types/hapi/v17/test/server/server-expose.ts | 22 ++++++++++ .../test/server/{info.ts => server-info.ts} | 2 +- types/hapi/v17/test/server/server-inject.ts | 20 ++++++++++ types/hapi/v17/test/server/server-listener.ts | 14 +++++++ types/hapi/v17/test/server/server-load.ts | 15 +++++++ types/hapi/v17/test/server/server-lookup.ts | 20 ++++++++++ types/hapi/v17/test/server/server-match.ts | 20 ++++++++++ types/hapi/v17/test/server/server-method.ts | 26 ++++++++++++ types/hapi/v17/test/server/server-methods.ts | 11 +++++ types/hapi/v17/test/server/server-mime.ts | 22 ++++++++++ types/hapi/v17/test/server/server-path.ts | 30 ++++++++++++++ types/hapi/v17/test/server/server-plugins.ts | 20 ++++++++++ .../{settings.ts => server-settings.ts} | 2 +- .../test/server/{start.ts => server-start.ts} | 2 +- .../server-state.ts} | 0 .../test/server/{stop.ts => server-stop.ts} | 2 +- .../test/server/{table.ts => server-table.ts} | 2 +- .../server/{version.ts => server-version.ts} | 2 +- 43 files changed, 516 insertions(+), 58 deletions(-) delete mode 100644 types/hapi/v17/test/server/a-simple-server.ts delete mode 100644 types/hapi/v17/test/server/select.ts rename types/hapi/v17/test/server/{app.ts => server-app.ts} (87%) create mode 100644 types/hapi/v17/test/server/server-auth-api.ts create mode 100644 types/hapi/v17/test/server/server-auth-default.ts create mode 100644 types/hapi/v17/test/server/server-auth-test.ts create mode 100644 types/hapi/v17/test/server/server-bind.ts create mode 100644 types/hapi/v17/test/server/server-cache-provision.ts create mode 100644 types/hapi/v17/test/server/server-cache.ts create mode 100644 types/hapi/v17/test/server/server-decoder.ts create mode 100644 types/hapi/v17/test/server/server-decorations.ts create mode 100644 types/hapi/v17/test/server/server-encoder.ts create mode 100644 types/hapi/v17/test/server/server-events.ts create mode 100644 types/hapi/v17/test/server/server-expose.ts rename types/hapi/v17/test/server/{info.ts => server-info.ts} (81%) create mode 100644 types/hapi/v17/test/server/server-inject.ts create mode 100644 types/hapi/v17/test/server/server-listener.ts create mode 100644 types/hapi/v17/test/server/server-load.ts create mode 100644 types/hapi/v17/test/server/server-lookup.ts create mode 100644 types/hapi/v17/test/server/server-match.ts create mode 100644 types/hapi/v17/test/server/server-method.ts create mode 100644 types/hapi/v17/test/server/server-methods.ts create mode 100644 types/hapi/v17/test/server/server-mime.ts create mode 100644 types/hapi/v17/test/server/server-path.ts create mode 100644 types/hapi/v17/test/server/server-plugins.ts rename types/hapi/v17/test/server/{settings.ts => server-settings.ts} (71%) rename types/hapi/v17/test/server/{start.ts => server-start.ts} (71%) rename types/hapi/v17/test/{response/state_cookie.ts => server/server-state.ts} (100%) rename types/hapi/v17/test/server/{stop.ts => server-stop.ts} (80%) rename types/hapi/v17/test/server/{table.ts => server-table.ts} (86%) rename types/hapi/v17/test/server/{version.ts => server-version.ts} (65%) diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index 228ffdc02c..ed5b66c2ba 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -20,7 +20,6 @@ export * from './response/continue'; export * from './response/error'; export * from './response/redirect'; export * from './response/reply'; -export * from './response/state_cookie'; /** ROUTE */ export * from './route/adding-routes'; @@ -28,16 +27,36 @@ export * from './route/config'; export * from './route/handler'; /** SERVER */ -export * from './server/a-simple-server'; -export * from './server/app'; -export * from './server/info'; -export * from './server/select'; +export * from './server/server-app'; +export * from './server/server-auth-api'; +export * from './server/server-auth-default'; +export * from './server/server-auth-test'; +export * from './server/server-bind'; +export * from './server/server-cache'; +export * from './server/server-cache-provision'; +export * from './server/server-decoder'; +export * from './server/server-decorations'; +export * from './server/server-encoder'; +export * from './server/server-events'; export * from './server/server-events-once'; -export * from './server/settings'; -export * from './server/start'; -export * from './server/stop'; -export * from './server/table'; -export * from './server/version'; +export * from './server/server-expose'; +export * from './server/server-info'; +export * from './server/server-inject'; +export * from './server/server-listener'; +export * from './server/server-load'; +export * from './server/server-lookup'; +export * from './server/server-match'; +export * from './server/server-method'; +export * from './server/server-methods'; +export * from './server/server-mime'; +export * from './server/server-path'; +export * from './server/server-plugins'; +export * from './server/server-settings'; +export * from './server/server-start'; +export * from './server/server-state'; +export * from './server/server-stop'; +export * from './server/server-table'; +export * from './server/server-version'; diff --git a/types/hapi/v17/test/request/catch-all.ts b/types/hapi/v17/test/request/catch-all.ts index a5292d4b7e..38a5638841 100644 --- a/types/hapi/v17/test/request/catch-all.ts +++ b/types/hapi/v17/test/request/catch-all.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route +// https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route import {Request, ResponseToolkit, Server, ServerOptions} from "hapi"; const options: ServerOptions = { diff --git a/types/hapi/v17/test/request/event-types.ts b/types/hapi/v17/test/request/event-types.ts index ae1c0ac081..411472d70f 100644 --- a/types/hapi/v17/test/request/event-types.ts +++ b/types/hapi/v17/test/request/event-types.ts @@ -1,7 +1,12 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents -// From https://github.com/hapijs/hapi/blob/master/API.md#-requestevents +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +// https://github.com/hapijs/hapi/blob/master/API.md#-requestevents import { - Request, RequestExtPointFunction, ResponseToolkit, RouteOptions, Server, ServerOptions, + Request, + RequestExtPointFunction, + ResponseToolkit, + RouteOptions, + Server, + ServerOptions, ServerRoute } from "hapi"; import * as Crypto from 'crypto'; diff --git a/types/hapi/v17/test/request/get-log.ts b/types/hapi/v17/test/request/get-log.ts index 047799c394..34e5ac56dc 100644 --- a/types/hapi/v17/test/request/get-log.ts +++ b/types/hapi/v17/test/request/get-log.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data +// https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data import {Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { diff --git a/types/hapi/v17/test/request/parameters.ts b/types/hapi/v17/test/request/parameters.ts index 11684555db..40f79746dc 100644 --- a/types/hapi/v17/test/request/parameters.ts +++ b/types/hapi/v17/test/request/parameters.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-requestparams +// https://github.com/hapijs/hapi/blob/master/API.md#-requestparams import {Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { diff --git a/types/hapi/v17/test/request/query.ts b/types/hapi/v17/test/request/query.ts index e176e078e9..332d8914ee 100644 --- a/types/hapi/v17/test/request/query.ts +++ b/types/hapi/v17/test/request/query.ts @@ -1,5 +1,5 @@ // Added test in addition to docs, for request.query -import {Request, ResponseToolkit, Lifecycle, Server, ServerOptions, ServerRoute} from "hapi"; +import {Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { port: 8000, diff --git a/types/hapi/v17/test/response/continue.ts b/types/hapi/v17/test/response/continue.ts index 5a0b37b5f9..56d1cd4ddd 100644 --- a/types/hapi/v17/test/response/continue.ts +++ b/types/hapi/v17/test/response/continue.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options +// https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { diff --git a/types/hapi/v17/test/response/error.ts b/types/hapi/v17/test/response/error.ts index c9c5e3e822..7103e8361f 100644 --- a/types/hapi/v17/test/response/error.ts +++ b/types/hapi/v17/test/response/error.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#errors +// https://github.com/hapijs/hapi/blob/master/API.md#errors import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; import * as Boom from "boom"; diff --git a/types/hapi/v17/test/response/redirect.ts b/types/hapi/v17/test/response/redirect.ts index 37af39707e..735a07d7cd 100644 --- a/types/hapi/v17/test/response/redirect.ts +++ b/types/hapi/v17/test/response/redirect.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi +// https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { diff --git a/types/hapi/v17/test/response/reply.ts b/types/hapi/v17/test/response/reply.ts index a2d4c250ed..4d6d7fc323 100644 --- a/types/hapi/v17/test/response/reply.ts +++ b/types/hapi/v17/test/response/reply.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue +// https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { diff --git a/types/hapi/v17/test/route/config.ts b/types/hapi/v17/test/route/config.ts index 1ecabd0c56..f4ace674e9 100644 --- a/types/hapi/v17/test/route/config.ts +++ b/types/hapi/v17/test/route/config.ts @@ -1,4 +1,4 @@ -import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute, RouteOptions} from "hapi"; +import {Request, ResponseToolkit, RouteOptions, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { port: 8000, diff --git a/types/hapi/v17/test/server/a-simple-server.ts b/types/hapi/v17/test/server/a-simple-server.ts deleted file mode 100644 index 995cac708c..0000000000 --- a/types/hapi/v17/test/server/a-simple-server.ts +++ /dev/null @@ -1,11 +0,0 @@ -// From https://hapijs.com/tutorials/getting-started#creating-a-server -import {Server, ServerOptions} from 'hapi'; - -const options: ServerOptions = { - port: 8000, -}; - -const server = new Server(options); -server.start(); - -console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/select.ts b/types/hapi/v17/test/server/select.ts deleted file mode 100644 index cdf2cfd1e7..0000000000 --- a/types/hapi/v17/test/server/select.ts +++ /dev/null @@ -1,17 +0,0 @@ -// From https://hapijs.com/api/16.1.1#serverselectlabels -import {Server} from "hapi"; - -/* -const server = new Hapi.Server(); -server.connection({ port: 80, labels: ['a', 'b'] }); -server.connection({ port: 8080, labels: ['a', 'c'] }); -server.connection({ port: 8081, labels: ['b', 'c'] }); - -const a = server.select('a'); // 80, 8080 -const ac = a.select('c'); // 8080 -*/ -// TODO How do this with v17? - -const server = new Server({ - port: 8000, -}); diff --git a/types/hapi/v17/test/server/app.ts b/types/hapi/v17/test/server/server-app.ts similarity index 87% rename from types/hapi/v17/test/server/app.ts rename to types/hapi/v17/test/server/server-app.ts index cfd0bd91a4..f4f5d51540 100644 --- a/types/hapi/v17/test/server/app.ts +++ b/types/hapi/v17/test/server/server-app.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-serverapp +// https://github.com/hapijs/hapi/blob/master/API.md#-serverapp import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { diff --git a/types/hapi/v17/test/server/server-auth-api.ts b/types/hapi/v17/test/server/server-auth-api.ts new file mode 100644 index 0000000000..b1b40bdd5e --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-api.ts @@ -0,0 +1,40 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi +import { + Request, + ResponseToolkit, + Server, + ServerAuthScheme, + ServerAuthSchemeObject, + ServerAuthSchemeOptions +} from "hapi"; +import * as Boom from "boom"; + +const scheme:ServerAuthScheme = function (server:Server, options:ServerAuthSchemeOptions): ServerAuthSchemeObject { + + return { + api: { + settings: { + x: 5 + } + }, + authenticate: function (request: Request, h: ResponseToolkit) { + + const authorization = request.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + + return h.authenticated({ credentials: { user: 'john' } }); + } + }; + +}; + +const server = new Server({ + port: 8000, +}); +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); +server.start(); + +console.log(server.auth.api.default.settings.x); // 5 diff --git a/types/hapi/v17/test/server/server-auth-default.ts b/types/hapi/v17/test/server/server-auth-default.ts new file mode 100644 index 0000000000..415b7ad243 --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-default.ts @@ -0,0 +1,35 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme +import {Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions} from "hapi"; +import * as Boom from "boom"; + +const server = new Server({ + port: 8000, +}); + +const scheme:ServerAuthScheme = function (server:Server, options:ServerAuthSchemeOptions) { + return { + authenticate: function (request:Request, h:ResponseToolkit) { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: 'john' } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); +server.auth.default('default'); + +server.route({ + method: 'GET', + path: '/', + handler: function (request:Request, h:ResponseToolkit) { + return request.auth.credentials.user; + } +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-auth-test.ts b/types/hapi/v17/test/server/server-auth-test.ts new file mode 100644 index 0000000000..0747d8abc2 --- /dev/null +++ b/types/hapi/v17/test/server/server-auth-test.ts @@ -0,0 +1,40 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme +import {Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions} from "hapi"; +import * as Boom from "boom"; + +const server = new Server({ + port: 8000, +}); + +const scheme:ServerAuthScheme = function (server:Server, options:ServerAuthSchemeOptions) { + return { + authenticate: function (request:Request, h:ResponseToolkit) { + const req = request.raw.req; + const authorization = req.headers.authorization; + if (!authorization) { + throw Boom.unauthorized(null, 'Custom'); + } + return h.authenticated({ credentials: { user: 'john' } }); + } + }; +}; + +server.auth.scheme('custom', scheme); +server.auth.strategy('default', 'custom'); + +server.route({ + method: 'GET', + path: '/', + handler: function (request:Request, h:ResponseToolkit) { + try { + const credentials = request.server.auth.test('default', request); + return { status: true, user: credentials.name }; + } + catch (err) { + return { status: false }; + } + } +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-bind.ts b/types/hapi/v17/test/server/server-bind.ts new file mode 100644 index 0000000000..9653bcee3a --- /dev/null +++ b/types/hapi/v17/test/server/server-bind.ts @@ -0,0 +1,31 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext +import {Plugin, Request, ResponseToolkit, Server, ServerRegisterOptions} from "hapi"; + +const server = new Server({ + port: 8000, +}); +const handler = function (request:Request, h:ResponseToolkit) { + return h.context.message; // Or h.context.message +}; + +const plugin:Plugin = { + name: 'example', + register: function (server:Server, options:ServerRegisterOptions) { + + const bind = { + message: 'hello' + }; + + server.bind(bind); + server.route({ method: 'GET', path: '/', handler }); + } +}; + + + +server.start(); +server.register(plugin); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-cache-provision.ts b/types/hapi/v17/test/server/server-cache-provision.ts new file mode 100644 index 0000000000..3eac02cc51 --- /dev/null +++ b/types/hapi/v17/test/server/server-cache-provision.ts @@ -0,0 +1,21 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions +import {Server} from "hapi"; +import * as catbox from "catbox"; + +const server = new Server({ + port: 8000, +}); +server.initialize(); +server.cache.provision({engine: require('catbox-memory'), name: 'countries' }); + +const cache:catbox.Policy = server.cache({segment: 'countries', cache: 'countries', expiresIn: 60 * 60 * 1000 }); +cache.set('norway', 'oslo', 10 * 1000, null); +const value = cache.get('norway', null); + +// TODO Not working. It needs review. + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-cache.ts b/types/hapi/v17/test/server/server-cache.ts new file mode 100644 index 0000000000..79049f23fd --- /dev/null +++ b/types/hapi/v17/test/server/server-cache.ts @@ -0,0 +1,23 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions +import {Server, ServerOptionsCache} from "hapi"; +import * as catbox from "catbox"; + +const server = new Server({ + port: 8000, +}); + +const catboxOptions:ServerOptionsCache = { + segment: 'countries', + expiresIn: 60 * 60 * 1000 +} +const cache:catbox.Policy = server.cache(catboxOptions); +cache.set('norway', 'oslo', 10 * 1000, null); + +const value = cache.get('norway', null); +console.log("Value: " + value); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-decoder.ts b/types/hapi/v17/test/server/server-decoder.ts new file mode 100644 index 0000000000..67e0a3abaa --- /dev/null +++ b/types/hapi/v17/test/server/server-decoder.ts @@ -0,0 +1,8 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder +import {Server} from "hapi"; +import * as Zlib from "zlib"; + +const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); +server.decoder('special', (options) => Zlib.createGunzip(options)); + +server.start(); diff --git a/types/hapi/v17/test/server/server-decorations.ts b/types/hapi/v17/test/server/server-decorations.ts new file mode 100644 index 0000000000..dd9c1ffcf3 --- /dev/null +++ b/types/hapi/v17/test/server/server-decorations.ts @@ -0,0 +1,25 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options +import {Server} from "hapi"; + +const server = new Server({ + port: 8000, +}); + +/* +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return h.success(); + } +}; +const success = function () { + return this.response({ status: 'ok' }); +}; + +server.start(); +server.decorate('toolkit', 'success', success); +*/ +// TODO how to implement it with TS? + +console.log(server.decorations.toolkit); // ['success'] diff --git a/types/hapi/v17/test/server/server-encoder.ts b/types/hapi/v17/test/server/server-encoder.ts new file mode 100644 index 0000000000..ccc00e93e9 --- /dev/null +++ b/types/hapi/v17/test/server/server-encoder.ts @@ -0,0 +1,8 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder +import {Server} from "hapi"; +import * as Zlib from "zlib"; + +const server = new Server({ port: 80, routes: { payload: { compression: { special: { chunkSize: 16 * 1024 } } } } }); +server.encoder('special', (options) => Zlib.createGzip(options)); + +server.start(); diff --git a/types/hapi/v17/test/server/server-events-once.ts b/types/hapi/v17/test/server/server-events-once.ts index 022cdb6f33..d81852f539 100644 --- a/types/hapi/v17/test/server/server-events-once.ts +++ b/types/hapi/v17/test/server/server-events-once.ts @@ -1,5 +1,5 @@ // from https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener -import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; +import {Request, ResponseToolkit, Server, ServerRoute} from "hapi"; const serverRoute: ServerRoute = { path: '/', diff --git a/types/hapi/v17/test/server/server-events.ts b/types/hapi/v17/test/server/server-events.ts new file mode 100644 index 0000000000..6c77d1826b --- /dev/null +++ b/types/hapi/v17/test/server/server-events.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +import {Server} from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.event('test'); +server.events.on('test', (update:any) => console.log(update)); +server.events.emit('test', 'hello'); + +server.start(); diff --git a/types/hapi/v17/test/server/server-expose.ts b/types/hapi/v17/test/server/server-expose.ts new file mode 100644 index 0000000000..1852a26aec --- /dev/null +++ b/types/hapi/v17/test/server/server-expose.ts @@ -0,0 +1,22 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +import {Plugin, Server, ServerRegisterOptions} from "hapi"; + +const plugin1:Plugin = { + name: 'example1', + register: function (server:Server, options:ServerRegisterOptions) { + server.expose('util', () => console.log('something')); + } +}; +const plugin2:Plugin = { + name: 'example2', + register: function (server:Server, options:ServerRegisterOptions) { + server.expose('util', () => console.log('something')); + } +}; + +const server = new Server({ + port: 8000, +}); +server.start(); +server.register(plugin1); +server.register(plugin2); diff --git a/types/hapi/v17/test/server/info.ts b/types/hapi/v17/test/server/server-info.ts similarity index 81% rename from types/hapi/v17/test/server/info.ts rename to types/hapi/v17/test/server/server-info.ts index 253a1b72aa..3543f5d30e 100644 --- a/types/hapi/v17/test/server/info.ts +++ b/types/hapi/v17/test/server/server-info.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo +// https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo import {Server} from "hapi"; import * as assert from "assert"; diff --git a/types/hapi/v17/test/server/server-inject.ts b/types/hapi/v17/test/server/server-inject.ts new file mode 100644 index 0000000000..03cb591e06 --- /dev/null +++ b/types/hapi/v17/test/server/server-inject.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions +import {Request, ResponseToolkit, Server, ServerRoute} from "hapi"; + +const server = new Server({ + port: 8000, +}); +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: function (request: Request, h: ResponseToolkit) { + return 'Success!'; + } +}; + +server.route(serverRoute); +server.start(); + +const res = server.inject('/'); +console.log(res.result); // 'Success!' // TODO It's not working + diff --git a/types/hapi/v17/test/server/server-listener.ts b/types/hapi/v17/test/server/server-listener.ts new file mode 100644 index 0000000000..7a99ed260d --- /dev/null +++ b/types/hapi/v17/test/server/server-listener.ts @@ -0,0 +1,14 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener +import {Server} from "hapi"; +import * as SocketIO from "socket.io" + +const server = new Server({ + port: 8000, +}); + +const io = SocketIO.listen(server.listener); +io.sockets.on('connection', (socket) => { + socket.emit('welcome'); +}); + +server.start(); diff --git a/types/hapi/v17/test/server/server-load.ts b/types/hapi/v17/test/server/server-load.ts new file mode 100644 index 0000000000..2b28bcda9d --- /dev/null +++ b/types/hapi/v17/test/server/server-load.ts @@ -0,0 +1,15 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverload +import {Server} from "hapi"; + +const server = new Server({ + port: 8000, + load: { sampleInterval: 1000 } +}); +server.start(); + +setTimeout(function() { + console.log(server.load.rss); + console.log(server.load.eventLoopDelay); + console.log(server.load.heapUsed); +}, 5 * 1000); + diff --git a/types/hapi/v17/test/server/server-lookup.ts b/types/hapi/v17/test/server/server-lookup.ts new file mode 100644 index 0000000000..c0531afb49 --- /dev/null +++ b/types/hapi/v17/test/server/server-lookup.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid +import {RequestRoute, Server} from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.route({ + path: '/', + method: 'GET', + config: { + id: 'root', + handler: () => 'ok' + } +}); + +const route:RequestRoute = server.lookup('root'); +console.log(route); + +server.start(); diff --git a/types/hapi/v17/test/server/server-match.ts b/types/hapi/v17/test/server/server-match.ts new file mode 100644 index 0000000000..4a3a7805af --- /dev/null +++ b/types/hapi/v17/test/server/server-match.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host +import {RequestRoute, Server} from "hapi"; + +const server = new Server({ + port: 8000, +}); + +server.route({ + path: '/', + method: 'GET', + config: { + id: 'root', + handler: () => 'ok' + } +}); + +const route:RequestRoute = server.match('get', '/'); +console.log(route.path); + +server.start(); diff --git a/types/hapi/v17/test/server/server-method.ts b/types/hapi/v17/test/server/server-method.ts new file mode 100644 index 0000000000..8214842760 --- /dev/null +++ b/types/hapi/v17/test/server/server-method.ts @@ -0,0 +1,26 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods +import {Server, ServerMethodConfigurationObject} from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +const add = function (a:any, b:any) { + return a + b; +}; + +const methodObject:ServerMethodConfigurationObject = { + name: 'sum', + method: add, + options: { + cache: { + expiresIn: 2000, + generateTimeout: 100 + } + } +} + +server.method(methodObject); + + diff --git a/types/hapi/v17/test/server/server-methods.ts b/types/hapi/v17/test/server/server-methods.ts new file mode 100644 index 0000000000..1d0831fd53 --- /dev/null +++ b/types/hapi/v17/test/server/server-methods.ts @@ -0,0 +1,11 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethods +import {Server} from "hapi"; + +const server = new Server({ + port: 8000, +}); +server.start(); + +server.method('add', (a, b) => (a + b)); +const result = server.methods.add(1, 2); // 3 +console.log(result); diff --git a/types/hapi/v17/test/server/server-mime.ts b/types/hapi/v17/test/server/server-mime.ts new file mode 100644 index 0000000000..76fcac5594 --- /dev/null +++ b/types/hapi/v17/test/server/server-mime.ts @@ -0,0 +1,22 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-servermime +import {Server, ServerOptions} from "hapi"; + +const options:ServerOptions = { + port: 8000, + mime: { + override: { + 'node/module': { + source: 'steve', + compressible: false, + extensions: ['node', 'module', 'npm'], + type: 'node/module' + } + } + } +}; + +const server = new Server(options); +console.log(server.mime.path('code.js').type) // 'application/javascript' +console.log(server.mime.path('file.npm').type) // 'node/module' + +server.start(); diff --git a/types/hapi/v17/test/server/server-path.ts b/types/hapi/v17/test/server/server-path.ts new file mode 100644 index 0000000000..4baa613245 --- /dev/null +++ b/types/hapi/v17/test/server/server-path.ts @@ -0,0 +1,30 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto +import {Plugin, Server, ServerRegisterOptions, ServerRoute} from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const serverRouteOption:ServerRoute = { + path: '/file', + method: 'GET', + handler: { + file: './test.html' + } +} + +const plugin:Plugin = { + name: 'example', + register: function (server:Server, options:ServerRegisterOptions) { + // Assuming the Inert plugin was registered previously + server.path(__dirname + '../static'); + server.route(serverRouteOption); + } +}; + +server.start(); +server.register(plugin); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); diff --git a/types/hapi/v17/test/server/server-plugins.ts b/types/hapi/v17/test/server/server-plugins.ts new file mode 100644 index 0000000000..620609b4cb --- /dev/null +++ b/types/hapi/v17/test/server/server-plugins.ts @@ -0,0 +1,20 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +import {Plugin, Server, ServerRegisterOptions} from "hapi"; + +const plugin:Plugin = { + name: 'example', + register: function (server:Server, options:ServerRegisterOptions) { + + server.expose('key', 'value'); + server.plugins.example.other = 'other'; + + console.log(server.plugins.example.key); // 'value' + console.log(server.plugins.example.other); // 'other' + } +}; + +const server = new Server({ + port: 8000, +}); +server.start(); +server.register(plugin); diff --git a/types/hapi/v17/test/server/settings.ts b/types/hapi/v17/test/server/server-settings.ts similarity index 71% rename from types/hapi/v17/test/server/settings.ts rename to types/hapi/v17/test/server/server-settings.ts index ebe7588b88..07bfec2b64 100644 --- a/types/hapi/v17/test/server/settings.ts +++ b/types/hapi/v17/test/server/server-settings.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-serversettings +// https://github.com/hapijs/hapi/blob/master/API.md#-serversettings import {Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/start.ts b/types/hapi/v17/test/server/server-start.ts similarity index 71% rename from types/hapi/v17/test/server/start.ts rename to types/hapi/v17/test/server/server-start.ts index 425c287842..ab95930a4d 100644 --- a/types/hapi/v17/test/server/start.ts +++ b/types/hapi/v17/test/server/server-start.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart import {Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/response/state_cookie.ts b/types/hapi/v17/test/server/server-state.ts similarity index 100% rename from types/hapi/v17/test/response/state_cookie.ts rename to types/hapi/v17/test/server/server-state.ts diff --git a/types/hapi/v17/test/server/stop.ts b/types/hapi/v17/test/server/server-stop.ts similarity index 80% rename from types/hapi/v17/test/server/stop.ts rename to types/hapi/v17/test/server/server-stop.ts index 2e7f3f9b2b..a143577410 100644 --- a/types/hapi/v17/test/server/stop.ts +++ b/types/hapi/v17/test/server/server-stop.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions import {Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/table.ts b/types/hapi/v17/test/server/server-table.ts similarity index 86% rename from types/hapi/v17/test/server/table.ts rename to types/hapi/v17/test/server/server-table.ts index 58c8e4c52d..78f2df90db 100644 --- a/types/hapi/v17/test/server/table.ts +++ b/types/hapi/v17/test/server/server-table.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost +// https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost import {Request, ResponseToolkit, Server, ServerOptions} from "hapi"; const options: ServerOptions = { diff --git a/types/hapi/v17/test/server/version.ts b/types/hapi/v17/test/server/server-version.ts similarity index 65% rename from types/hapi/v17/test/server/version.ts rename to types/hapi/v17/test/server/server-version.ts index 041a565f48..02f7ca1d20 100644 --- a/types/hapi/v17/test/server/version.ts +++ b/types/hapi/v17/test/server/server-version.ts @@ -1,4 +1,4 @@ -// From https://github.com/hapijs/hapi/blob/master/API.md#-serverversion +// https://github.com/hapijs/hapi/blob/master/API.md#-serverversion import {Server} from "hapi"; const server = new Server({ From 0e389ba4e7e9a47f43069539f8f9d150be687993 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 20:25:57 -0300 Subject: [PATCH 69/79] Add new type ServerCache in index. --- types/hapi/v17/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/hapi/v17/index.d.ts b/types/hapi/v17/index.d.ts index 3ded9fe2bf..9dcc6b841c 100644 --- a/types/hapi/v17/index.d.ts +++ b/types/hapi/v17/index.d.ts @@ -41,6 +41,7 @@ export * from './definitions/route/route-options-validate' export * from './definitions/server/server' export * from './definitions/server/server-auth' export * from './definitions/server/server-auth-scheme' +export * from './definitions/server/server-cache' export * from './definitions/server/server-events' export * from './definitions/server/server-ext' export * from './definitions/server/server-info' From 1b597e080af8a3e72aca5b5f4a327783e9358195 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 21:17:58 -0300 Subject: [PATCH 70/79] More fix based in test cases. --- types/hapi/v17/definitions/request/request.d.ts | 2 +- .../v17/definitions/response/response-events.d.ts | 9 ++------- types/hapi/v17/definitions/server/server-ext.d.ts | 10 +++------- types/hapi/v17/definitions/server/server.d.ts | 12 +++++------- 4 files changed, 11 insertions(+), 22 deletions(-) diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index a9a8c8b6d2..5fe1a63f5b 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -140,7 +140,7 @@ export interface Request extends Podium { /** * By default the object outputted from node's URL parse() method. Might also be set indirectly via request.setUrl in which case it may be a string (if url is set to an object with the query attribute as an unparsed string). */ - readonly query: object; + readonly query: any; /** * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended. diff --git a/types/hapi/v17/definitions/response/response-events.d.ts b/types/hapi/v17/definitions/response/response-events.d.ts index 469009087c..e5dcb43d30 100644 --- a/types/hapi/v17/definitions/response/response-events.d.ts +++ b/types/hapi/v17/definitions/response/response-events.d.ts @@ -11,14 +11,9 @@ export interface ResponseEvents extends Podium { /** * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). - */ - on(criteria: 'peak', listener: Function): void; - once(criteria: 'peak', listener: Function): void; - - /** * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). */ - on(criteria: 'finish', listener: Function): void; - once(criteria: 'finish', listener: Function): void; + on(criteria: 'peek' | 'finish', listener: Function): void; + once(criteria: 'peek' | 'finish', listener: Function): void; } diff --git a/types/hapi/v17/definitions/server/server-ext.d.ts b/types/hapi/v17/definitions/server/server-ext.d.ts index 02853a2888..809f4ddc61 100644 --- a/types/hapi/v17/definitions/server/server-ext.d.ts +++ b/types/hapi/v17/definitions/server/server-ext.d.ts @@ -9,7 +9,7 @@ import {Lifecycle, Server} from "hapi"; * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) */ -export type ServerExtType = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'; +export type ServerExtType = 'onRequest' | 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop'| 'onPreResponse'; /** * The extension point event name for Request @@ -41,7 +41,7 @@ export type ServerExtRequestType = 'onRequest'; */ export interface ServerExtEventsObject { type: ServerExtType; - method: ServerExtPointFunction | ServerExtPointFunction[]; + method: ServerExtPointFunction | ServerExtPointFunction[] | Function; options?: ServerExtOptions; } @@ -68,7 +68,7 @@ export interface ServerExtEventsObject { */ export interface ServerExtEventsRequestObject { type: ServerExtRequestType; - method: RequestExtPointFunction | RequestExtPointFunction[]; + method: Lifecycle.Method | Lifecycle.Method[]; options?: ServerExtOptions; } @@ -76,10 +76,6 @@ export interface ServerExtPointFunction { (server: Server): void; } -export interface RequestExtPointFunction extends Lifecycle.Method { - -} - /** * An object with the following: * * before - a string or array of strings of plugin names this method must execute before (on the same event). Otherwise, extension methods are executed in the order added. diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index 1f3654b1be..b7ac0e908f 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -2,22 +2,22 @@ import * as http from "http"; import * as zlib from "zlib"; import * as Podium from "podium"; import { + Lifecycle, PayloadCompressionDecoderSettings, Plugin, PluginsListRegistered, Request, - RequestExtPointFunction, RequestRoute, ResponseToolkit, RouteCompressionEncoderSettings, - ServerAuth, ServerCache, + ServerAuth, + ServerCache, ServerEvents, ServerEventsApplication, ServerExtEventsObject, ServerExtEventsRequestObject, ServerExtOptions, ServerExtPointFunction, - ServerExtRequestType, ServerExtType, ServerInfo, ServerInjectOptions, @@ -343,10 +343,8 @@ export class Server extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) */ - ext(event: ServerExtType, method: ServerExtPointFunction): void; - ext(event: ServerExtType, method: ServerExtPointFunction, options: ServerExtOptions): void; - ext(event: ServerExtRequestType, method: RequestExtPointFunction): void; - ext(event: ServerExtRequestType, method: RequestExtPointFunction, options: ServerExtOptions): void; + ext(event: ServerExtType, method: ServerExtPointFunction | Lifecycle.Method | Function): void; + ext(event: ServerExtType, method: ServerExtPointFunction | Lifecycle.Method | Function, options: ServerExtOptions): void; /** * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. From b1ca20cc48deaae2223556de1a2fcc4080cfb127 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sat, 9 Dec 2017 21:29:43 -0300 Subject: [PATCH 71/79] Add more tests. --- types/hapi/v17/test/index.test.d.ts | 4 +- types/hapi/v17/test/request/event-types.ts | 4 +- .../hapi/v17/test/response/response-events.ts | 31 ++++++++++++++ .../test/response/{reply.ts => response.ts} | 4 +- .../hapi/v17/test/route/route-options-pre.ts | 42 +++++++++++++++++++ 5 files changed, 80 insertions(+), 5 deletions(-) create mode 100644 types/hapi/v17/test/response/response-events.ts rename types/hapi/v17/test/response/{reply.ts => response.ts} (95%) create mode 100644 types/hapi/v17/test/route/route-options-pre.ts diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index ed5b66c2ba..a3e94ac7dd 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -19,12 +19,14 @@ export * from './request/query'; export * from './response/continue'; export * from './response/error'; export * from './response/redirect'; -export * from './response/reply'; +export * from './response/response'; +export * from './response/response-events'; /** ROUTE */ export * from './route/adding-routes'; export * from './route/config'; export * from './route/handler'; +export * from './route/route-options-pre'; /** SERVER */ export * from './server/server-app'; diff --git a/types/hapi/v17/test/request/event-types.ts b/types/hapi/v17/test/request/event-types.ts index 411472d70f..7e22841e64 100644 --- a/types/hapi/v17/test/request/event-types.ts +++ b/types/hapi/v17/test/request/event-types.ts @@ -1,8 +1,8 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents // https://github.com/hapijs/hapi/blob/master/API.md#-requestevents import { + Lifecycle, Request, - RequestExtPointFunction, ResponseToolkit, RouteOptions, Server, @@ -23,7 +23,7 @@ const serverRoute: ServerRoute = { } }; -const onRequest: RequestExtPointFunction = function (request: Request, h: ResponseToolkit) { +const onRequest: Lifecycle.Method = function (request: Request, h: ResponseToolkit) { /* * Server events diff --git a/types/hapi/v17/test/response/response-events.ts b/types/hapi/v17/test/response/response-events.ts new file mode 100644 index 0000000000..3b0f29879f --- /dev/null +++ b/types/hapi/v17/test/response/response-events.ts @@ -0,0 +1,31 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-responseevents +import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute, ResponseObject} from "hapi"; +import * as Crypto from "crypto"; + +const preResponse = function (request: Request, h: ResponseToolkit) { + + const response:ResponseObject = request.response; + // if (response.isBoom) { + // return null; + // } + + const hash = Crypto.createHash('sha1'); + response.events.on('peek', (chunk:any) => { + hash.update(chunk); + }); + + response.events.once('finish', () => { + console.log(hash.digest('hex')); + }); + + return h.continue; +}; + +const server = new Server({ + port: 8000, +}); + +server.ext('onPreResponse', preResponse); + +server.start(); +console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/response/reply.ts b/types/hapi/v17/test/response/response.ts similarity index 95% rename from types/hapi/v17/test/response/reply.ts rename to types/hapi/v17/test/response/response.ts index 4d6d7fc323..55af428a34 100644 --- a/types/hapi/v17/test/response/reply.ts +++ b/types/hapi/v17/test/response/response.ts @@ -6,7 +6,7 @@ const options: ServerOptions = { }; const serverRoutes: ServerRoute[] = [ - // verbose notation + // Detailed notation { path: '/test1', method: 'GET', @@ -17,7 +17,7 @@ const serverRoutes: ServerRoute[] = [ return response; } }, - // chained notation + // Chained notation { path: '/test2', method: 'GET', diff --git a/types/hapi/v17/test/route/route-options-pre.ts b/types/hapi/v17/test/route/route-options-pre.ts new file mode 100644 index 0000000000..63cbe09647 --- /dev/null +++ b/types/hapi/v17/test/route/route-options-pre.ts @@ -0,0 +1,42 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre +import {Server, Request, ResponseToolkit} from "hapi"; + +const server = new Server({ + port: 8000, +}); + +const pre1 = function(request: Request, h: ResponseToolkit) { + return 'Hello'; +}; + +const pre2 = function(request: Request, h: ResponseToolkit) { + return 'World'; +}; + +const pre3 = function(request: Request, h: ResponseToolkit) { + return request.pre.m1 + ' ' + request.pre.m2; +}; + +server.route({ + method: 'GET', + path: '/', + config: { + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + handler: function (request: Request, h: ResponseToolkit) { + return request.pre.m3 + '!\n'; + } + } +}); + +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); From 6a11db62bdd29720dbe008cbfc25b563764f4b0f Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 10 Dec 2017 17:08:15 -0300 Subject: [PATCH 72/79] Delete comments. --- types/hapi/v17/test/response/response-events.ts | 3 --- types/hapi/v17/test/route/config.ts | 1 - types/hapi/v17/test/server/server-decorations.ts | 16 +++------------- 3 files changed, 3 insertions(+), 17 deletions(-) diff --git a/types/hapi/v17/test/response/response-events.ts b/types/hapi/v17/test/response/response-events.ts index 3b0f29879f..8427352cba 100644 --- a/types/hapi/v17/test/response/response-events.ts +++ b/types/hapi/v17/test/response/response-events.ts @@ -5,9 +5,6 @@ import * as Crypto from "crypto"; const preResponse = function (request: Request, h: ResponseToolkit) { const response:ResponseObject = request.response; - // if (response.isBoom) { - // return null; - // } const hash = Crypto.createHash('sha1'); response.events.on('peek', (chunk:any) => { diff --git a/types/hapi/v17/test/route/config.ts b/types/hapi/v17/test/route/config.ts index f4ace674e9..94465cd736 100644 --- a/types/hapi/v17/test/route/config.ts +++ b/types/hapi/v17/test/route/config.ts @@ -48,7 +48,6 @@ const user: RouteOptions = { }; server.route({method: 'GET', path: '/user', options: user }); -//server.route({ method: 'GET', path: '/public/{path*}', options: { cache: { privacy: 'public', expiresIn: 24 * 60 * 60 * 1000 } }, handler: { directory: { path: __dirname, listing: false, index: false } } }); server.start(); console.log('Server started at: ' + server.info.uri); diff --git a/types/hapi/v17/test/server/server-decorations.ts b/types/hapi/v17/test/server/server-decorations.ts index dd9c1ffcf3..05e7714f2b 100644 --- a/types/hapi/v17/test/server/server-decorations.ts +++ b/types/hapi/v17/test/server/server-decorations.ts @@ -1,25 +1,15 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options -import {Server} from "hapi"; +import {ResponseToolkit, Server} from "hapi"; const server = new Server({ port: 8000, }); -/* -const serverRoute: ServerRoute = { - path: '/', - method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { - return h.success(); - } -}; -const success = function () { - return this.response({ status: 'ok' }); +const success = function (h: ResponseToolkit) { + return h.response({ status: 'ok' }); }; server.start(); server.decorate('toolkit', 'success', success); -*/ -// TODO how to implement it with TS? console.log(server.decorations.toolkit); // ['success'] From 3d6b18467eae8940f5834142d38f0a2d15817854 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 10 Dec 2017 17:08:40 -0300 Subject: [PATCH 73/79] Remove asserts. It's not necessary here. --- types/hapi/v17/test/server/server-info.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/types/hapi/v17/test/server/server-info.ts b/types/hapi/v17/test/server/server-info.ts index 3543f5d30e..6599fe5b5a 100644 --- a/types/hapi/v17/test/server/server-info.ts +++ b/types/hapi/v17/test/server/server-info.ts @@ -1,15 +1,10 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo import {Server} from "hapi"; -import * as assert from "assert"; const server = new Server({ port: 8000, }); server.start(); -// check the correct port console.log(server.info); -if (server.info) assert(server.info.port === 8000); - -assert(server.info !== null); console.log('Server started at: ' + server.info.uri); From 1a5f4f589451493176d9325b5a012cc9fd286d1a Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 10 Dec 2017 17:36:53 -0300 Subject: [PATCH 74/79] Replace all "function" with arrow function "() =>". --- types/hapi/v17/test/request/catch-all.ts | 4 ++-- types/hapi/v17/test/request/event-types.ts | 8 ++++---- types/hapi/v17/test/request/get-log.ts | 4 ++-- types/hapi/v17/test/request/parameters.ts | 6 +++--- types/hapi/v17/test/request/query.ts | 2 +- types/hapi/v17/test/response/continue.ts | 4 ++-- types/hapi/v17/test/response/error.ts | 6 +++--- types/hapi/v17/test/response/redirect.ts | 4 ++-- types/hapi/v17/test/response/response-events.ts | 4 ++-- types/hapi/v17/test/response/response.ts | 6 +++--- types/hapi/v17/test/route/adding-routes.ts | 6 +++--- types/hapi/v17/test/route/config.ts | 7 +++---- types/hapi/v17/test/route/handler.ts | 4 ++-- types/hapi/v17/test/route/route-options-pre.ts | 10 +++++----- types/hapi/v17/test/server/server-app.ts | 4 ++-- types/hapi/v17/test/server/server-auth-api.ts | 6 +++--- types/hapi/v17/test/server/server-auth-default.ts | 8 ++++---- types/hapi/v17/test/server/server-auth-test.ts | 8 ++++---- types/hapi/v17/test/server/server-bind.ts | 10 +++------- types/hapi/v17/test/server/server-cache-provision.ts | 2 +- types/hapi/v17/test/server/server-cache.ts | 2 +- types/hapi/v17/test/server/server-decorations.ts | 4 ++-- types/hapi/v17/test/server/server-encoder.ts | 2 +- types/hapi/v17/test/server/server-events-once.ts | 6 +++--- types/hapi/v17/test/server/server-events.ts | 2 +- types/hapi/v17/test/server/server-expose.ts | 6 +++--- types/hapi/v17/test/server/server-info.ts | 2 +- types/hapi/v17/test/server/server-inject.ts | 4 ++-- types/hapi/v17/test/server/server-listener.ts | 2 +- types/hapi/v17/test/server/server-load.ts | 4 ++-- types/hapi/v17/test/server/server-lookup.ts | 2 +- types/hapi/v17/test/server/server-match.ts | 2 +- types/hapi/v17/test/server/server-method.ts | 4 ++-- types/hapi/v17/test/server/server-methods.ts | 2 +- types/hapi/v17/test/server/server-mime.ts | 2 +- types/hapi/v17/test/server/server-path.ts | 4 ++-- types/hapi/v17/test/server/server-plugins.ts | 4 ++-- types/hapi/v17/test/server/server-settings.ts | 2 +- types/hapi/v17/test/server/server-start.ts | 2 +- types/hapi/v17/test/server/server-state.ts | 2 +- types/hapi/v17/test/server/server-stop.ts | 4 ++-- types/hapi/v17/test/server/server-table.ts | 4 ++-- types/hapi/v17/test/server/server-version.ts | 2 +- 43 files changed, 89 insertions(+), 94 deletions(-) diff --git a/types/hapi/v17/test/request/catch-all.ts b/types/hapi/v17/test/request/catch-all.ts index 38a5638841..1917cd8fff 100644 --- a/types/hapi/v17/test/request/catch-all.ts +++ b/types/hapi/v17/test/request/catch-all.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route +// https://github.com/hapijs/hapi/blob/master/API.md#catch-all-route import {Request, ResponseToolkit, Server, ServerOptions} from "hapi"; const options: ServerOptions = { @@ -6,7 +6,7 @@ const options: ServerOptions = { }; const server = new Server(options); -const handler = function (request: Request, h: ResponseToolkit) { +const handler = (request: Request, h: ResponseToolkit) => { return h.response('The page was not found').code(404); }; server.route({ method: '*', path: '/{p*}', handler }); diff --git a/types/hapi/v17/test/request/event-types.ts b/types/hapi/v17/test/request/event-types.ts index 7e22841e64..894e4dcf39 100644 --- a/types/hapi/v17/test/request/event-types.ts +++ b/types/hapi/v17/test/request/event-types.ts @@ -1,5 +1,5 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents -// https://github.com/hapijs/hapi/blob/master/API.md#-requestevents +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +// https://github.com/hapijs/hapi/blob/master/API.md#-requestevents import { Lifecycle, Request, @@ -18,12 +18,12 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'ok: ' + request.path; } }; -const onRequest: Lifecycle.Method = function (request: Request, h: ResponseToolkit) { +const onRequest: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { /* * Server events diff --git a/types/hapi/v17/test/request/get-log.ts b/types/hapi/v17/test/request/get-log.ts index 34e5ac56dc..007d396fe5 100644 --- a/types/hapi/v17/test/request/get-log.ts +++ b/types/hapi/v17/test/request/get-log.ts @@ -1,11 +1,11 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data +// https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data import {Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { port: 8000, }; -const handler: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { +const handler: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { request.log(['test', 'error'], 'Test event'); return 'path: ' + request.path; }; diff --git a/types/hapi/v17/test/request/parameters.ts b/types/hapi/v17/test/request/parameters.ts index 40f79746dc..43259ea4fb 100644 --- a/types/hapi/v17/test/request/parameters.ts +++ b/types/hapi/v17/test/request/parameters.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-requestparams +// https://github.com/hapijs/hapi/blob/master/API.md#-requestparams import {Lifecycle, Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { @@ -7,7 +7,7 @@ const options: ServerOptions = { // Example 1 // http://localhost:8000/album-name/song-optional -const getAlbum: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { +const getAlbum: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { console.log(request.params); return 'ok: ' + request.path; } @@ -19,7 +19,7 @@ const serverRoute1: ServerRoute = { // Example 2 // http://localhost:8000/person/rafael/fijalkowski -const getPerson: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { +const getPerson: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { const nameParts = request.params.name.split('/'); return { first: nameParts[0], last: nameParts[1] }; } diff --git a/types/hapi/v17/test/request/query.ts b/types/hapi/v17/test/request/query.ts index 332d8914ee..b5a950e2ad 100644 --- a/types/hapi/v17/test/request/query.ts +++ b/types/hapi/v17/test/request/query.ts @@ -5,7 +5,7 @@ const options: ServerOptions = { port: 8000, }; -const handler: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { +const handler: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { const query = request.query as GetThingQuery; // http://localhost:8000/?name=test return `You asked for ${query.name}` diff --git a/types/hapi/v17/test/response/continue.ts b/types/hapi/v17/test/response/continue.ts index 56d1cd4ddd..4839b4b6e2 100644 --- a/types/hapi/v17/test/response/continue.ts +++ b/types/hapi/v17/test/response/continue.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options +// https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { @@ -8,7 +8,7 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/test', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'ok: ' + request.path; } }; diff --git a/types/hapi/v17/test/response/error.ts b/types/hapi/v17/test/response/error.ts index 7103e8361f..6cc92acbdb 100644 --- a/types/hapi/v17/test/response/error.ts +++ b/types/hapi/v17/test/response/error.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#errors +// https://github.com/hapijs/hapi/blob/master/API.md#errors import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; import * as Boom from "boom"; @@ -10,14 +10,14 @@ const serverRoutes: ServerRoute[] = [ { path: '/badRequest', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { throw Boom.badRequest('Unsupported parameter'); } }, { path: '/internal', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { throw new Error('unexpect error'); } }, diff --git a/types/hapi/v17/test/response/redirect.ts b/types/hapi/v17/test/response/redirect.ts index 735a07d7cd..3cb6addba7 100644 --- a/types/hapi/v17/test/response/redirect.ts +++ b/types/hapi/v17/test/response/redirect.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi +// https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { @@ -8,7 +8,7 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return h.redirect('http://example.com'); } } diff --git a/types/hapi/v17/test/response/response-events.ts b/types/hapi/v17/test/response/response-events.ts index 8427352cba..06c6d6bfa8 100644 --- a/types/hapi/v17/test/response/response-events.ts +++ b/types/hapi/v17/test/response/response-events.ts @@ -1,8 +1,8 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-responseevents +// https://github.com/hapijs/hapi/blob/master/API.md#-responseevents import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute, ResponseObject} from "hapi"; import * as Crypto from "crypto"; -const preResponse = function (request: Request, h: ResponseToolkit) { +const preResponse = (request: Request, h: ResponseToolkit) => { const response:ResponseObject = request.response; diff --git a/types/hapi/v17/test/response/response.ts b/types/hapi/v17/test/response/response.ts index 55af428a34..66b11b352f 100644 --- a/types/hapi/v17/test/response/response.ts +++ b/types/hapi/v17/test/response/response.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue +// https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { @@ -10,7 +10,7 @@ const serverRoutes: ServerRoute[] = [ { path: '/test1', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { const response = h.response('success'); response.type('text/plain'); response.header('X-Custom', 'some-value'); @@ -21,7 +21,7 @@ const serverRoutes: ServerRoute[] = [ { path: '/test2', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return h.response('success') .type('text/plain') .header('X-Custom', 'some-value'); diff --git a/types/hapi/v17/test/route/adding-routes.ts b/types/hapi/v17/test/route/adding-routes.ts index 7d503502c2..8136c6508b 100644 --- a/types/hapi/v17/test/route/adding-routes.ts +++ b/types/hapi/v17/test/route/adding-routes.ts @@ -8,7 +8,7 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'ok: ' + request.path; } }; @@ -17,14 +17,14 @@ const serverRoutes: ServerRoute[] = [ { path: '/test1', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'ok: ' + request.path; } }, { path: '/test2', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'ok: ' + request.path; } }, diff --git a/types/hapi/v17/test/route/config.ts b/types/hapi/v17/test/route/config.ts index 94465cd736..1f36cd51b3 100644 --- a/types/hapi/v17/test/route/config.ts +++ b/types/hapi/v17/test/route/config.ts @@ -4,7 +4,6 @@ const options: ServerOptions = { port: 8000, }; - // different methods var routeConfig: ServerRoute = { path: '/signin', @@ -24,14 +23,14 @@ var routeConfig: ServerRoute = { var routeConfig: ServerRoute = { path: '/signin', method: 'PUT', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'ok'; } }; var routeConfig: ServerRoute = { path: '/signin', method: 'PUT', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'ok'; } }; @@ -42,7 +41,7 @@ server.route(routeConfig); // Handler in config const user: RouteOptions = { cache: { expiresIn: 5000 }, - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return { name: 'John' }; } }; diff --git a/types/hapi/v17/test/route/handler.ts b/types/hapi/v17/test/route/handler.ts index fa20d7b677..e3bea54939 100644 --- a/types/hapi/v17/test/route/handler.ts +++ b/types/hapi/v17/test/route/handler.ts @@ -1,9 +1,9 @@ import {Lifecycle, Request, ResponseToolkit} from "hapi"; -const handler: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { +const handler: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { return 'success'; } -const strictHandler: Lifecycle.Method = function(request: Request, h: ResponseToolkit) { +const strictHandler: Lifecycle.Method = (request: Request, h: ResponseToolkit) => { return 123; } diff --git a/types/hapi/v17/test/route/route-options-pre.ts b/types/hapi/v17/test/route/route-options-pre.ts index 63cbe09647..fedfab4c45 100644 --- a/types/hapi/v17/test/route/route-options-pre.ts +++ b/types/hapi/v17/test/route/route-options-pre.ts @@ -1,19 +1,19 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre +// https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre import {Server, Request, ResponseToolkit} from "hapi"; const server = new Server({ port: 8000, }); -const pre1 = function(request: Request, h: ResponseToolkit) { +const pre1 = (request: Request, h: ResponseToolkit) => { return 'Hello'; }; -const pre2 = function(request: Request, h: ResponseToolkit) { +const pre2 = (request: Request, h: ResponseToolkit) => { return 'World'; }; -const pre3 = function(request: Request, h: ResponseToolkit) { +const pre3 = (request: Request, h: ResponseToolkit) => { return request.pre.m1 + ' ' + request.pre.m2; }; @@ -29,7 +29,7 @@ server.route({ ], { method: pre3, assign: 'm3' }, ], - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return request.pre.m3 + '!\n'; } } diff --git a/types/hapi/v17/test/server/server-app.ts b/types/hapi/v17/test/server/server-app.ts index f4f5d51540..b70a83c301 100644 --- a/types/hapi/v17/test/server/server-app.ts +++ b/types/hapi/v17/test/server/server-app.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverapp +// https://github.com/hapijs/hapi/blob/master/API.md#-serverapp import {Request, ResponseToolkit, Server, ServerOptions, ServerRoute} from "hapi"; const options: ServerOptions = { @@ -11,7 +11,7 @@ server.app.key = 'value2'; const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'key: ' + request.server.app.key; } } diff --git a/types/hapi/v17/test/server/server-auth-api.ts b/types/hapi/v17/test/server/server-auth-api.ts index b1b40bdd5e..9f2bc5da3b 100644 --- a/types/hapi/v17/test/server/server-auth-api.ts +++ b/types/hapi/v17/test/server/server-auth-api.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi import { Request, ResponseToolkit, @@ -9,7 +9,7 @@ import { } from "hapi"; import * as Boom from "boom"; -const scheme:ServerAuthScheme = function (server:Server, options:ServerAuthSchemeOptions): ServerAuthSchemeObject { +const scheme:ServerAuthScheme = (server:Server, options:ServerAuthSchemeOptions): ServerAuthSchemeObject => { return { api: { @@ -17,7 +17,7 @@ const scheme:ServerAuthScheme = function (server:Server, options:ServerAuthSchem x: 5 } }, - authenticate: function (request: Request, h: ResponseToolkit) { + authenticate: (request: Request, h: ResponseToolkit) => { const authorization = request.headers.authorization; if (!authorization) { diff --git a/types/hapi/v17/test/server/server-auth-default.ts b/types/hapi/v17/test/server/server-auth-default.ts index 415b7ad243..3287da5ab8 100644 --- a/types/hapi/v17/test/server/server-auth-default.ts +++ b/types/hapi/v17/test/server/server-auth-default.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions // https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme import {Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions} from "hapi"; import * as Boom from "boom"; @@ -7,9 +7,9 @@ const server = new Server({ port: 8000, }); -const scheme:ServerAuthScheme = function (server:Server, options:ServerAuthSchemeOptions) { +const scheme:ServerAuthScheme = (server:Server, options:ServerAuthSchemeOptions) => { return { - authenticate: function (request:Request, h:ResponseToolkit) { + authenticate: (request:Request, h:ResponseToolkit) => { const req = request.raw.req; const authorization = req.headers.authorization; if (!authorization) { @@ -27,7 +27,7 @@ server.auth.default('default'); server.route({ method: 'GET', path: '/', - handler: function (request:Request, h:ResponseToolkit) { + handler: (request:Request, h:ResponseToolkit) => { return request.auth.credentials.user; } }); diff --git a/types/hapi/v17/test/server/server-auth-test.ts b/types/hapi/v17/test/server/server-auth-test.ts index 0747d8abc2..668fb27994 100644 --- a/types/hapi/v17/test/server/server-auth-test.ts +++ b/types/hapi/v17/test/server/server-auth-test.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request // https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme import {Request, ResponseToolkit, Server, ServerAuthScheme, ServerAuthSchemeOptions} from "hapi"; import * as Boom from "boom"; @@ -7,9 +7,9 @@ const server = new Server({ port: 8000, }); -const scheme:ServerAuthScheme = function (server:Server, options:ServerAuthSchemeOptions) { +const scheme:ServerAuthScheme = (server:Server, options:ServerAuthSchemeOptions) => { return { - authenticate: function (request:Request, h:ResponseToolkit) { + authenticate: (request:Request, h:ResponseToolkit) => { const req = request.raw.req; const authorization = req.headers.authorization; if (!authorization) { @@ -26,7 +26,7 @@ server.auth.strategy('default', 'custom'); server.route({ method: 'GET', path: '/', - handler: function (request:Request, h:ResponseToolkit) { + handler: (request:Request, h:ResponseToolkit) => { try { const credentials = request.server.auth.test('default', request); return { status: true, user: credentials.name }; diff --git a/types/hapi/v17/test/server/server-bind.ts b/types/hapi/v17/test/server/server-bind.ts index 9653bcee3a..ebd071fb63 100644 --- a/types/hapi/v17/test/server/server-bind.ts +++ b/types/hapi/v17/test/server/server-bind.ts @@ -1,28 +1,24 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext +// https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext import {Plugin, Request, ResponseToolkit, Server, ServerRegisterOptions} from "hapi"; const server = new Server({ port: 8000, }); -const handler = function (request:Request, h:ResponseToolkit) { +const handler = (request:Request, h:ResponseToolkit) => { return h.context.message; // Or h.context.message }; const plugin:Plugin = { name: 'example', - register: function (server:Server, options:ServerRegisterOptions) { - + register: (server:Server, options:ServerRegisterOptions) => { const bind = { message: 'hello' }; - server.bind(bind); server.route({ method: 'GET', path: '/', handler }); } }; - - server.start(); server.register(plugin); diff --git a/types/hapi/v17/test/server/server-cache-provision.ts b/types/hapi/v17/test/server/server-cache-provision.ts index 3eac02cc51..ce733403f3 100644 --- a/types/hapi/v17/test/server/server-cache-provision.ts +++ b/types/hapi/v17/test/server/server-cache-provision.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions import {Server} from "hapi"; import * as catbox from "catbox"; diff --git a/types/hapi/v17/test/server/server-cache.ts b/types/hapi/v17/test/server/server-cache.ts index 79049f23fd..df92a45038 100644 --- a/types/hapi/v17/test/server/server-cache.ts +++ b/types/hapi/v17/test/server/server-cache.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions import {Server, ServerOptionsCache} from "hapi"; import * as catbox from "catbox"; diff --git a/types/hapi/v17/test/server/server-decorations.ts b/types/hapi/v17/test/server/server-decorations.ts index 05e7714f2b..a5a5f3d69f 100644 --- a/types/hapi/v17/test/server/server-decorations.ts +++ b/types/hapi/v17/test/server/server-decorations.ts @@ -1,11 +1,11 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options +// https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options import {ResponseToolkit, Server} from "hapi"; const server = new Server({ port: 8000, }); -const success = function (h: ResponseToolkit) { +const success = (h: ResponseToolkit) => { return h.response({ status: 'ok' }); }; diff --git a/types/hapi/v17/test/server/server-encoder.ts b/types/hapi/v17/test/server/server-encoder.ts index ccc00e93e9..920ade785b 100644 --- a/types/hapi/v17/test/server/server-encoder.ts +++ b/types/hapi/v17/test/server/server-encoder.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder +// https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder import {Server} from "hapi"; import * as Zlib from "zlib"; diff --git a/types/hapi/v17/test/server/server-events-once.ts b/types/hapi/v17/test/server/server-events-once.ts index d81852f539..18f9fe2fd3 100644 --- a/types/hapi/v17/test/server/server-events-once.ts +++ b/types/hapi/v17/test/server/server-events-once.ts @@ -4,7 +4,7 @@ import {Request, ResponseToolkit, Server, ServerRoute} from "hapi"; const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'oks: ' + request.path; } }; @@ -15,8 +15,8 @@ const server = new Server({ server.route(serverRoute); server.event('test1'); server.event('test2'); -server.events.once('test1', function(update: any) {console.log(update);}); -server.events.once('test2', function(...args: any[]) {console.log(args);}); +server.events.once('test1', (update: any) => {console.log(update);}); +server.events.once('test2', (...args: any[]) => {console.log(args);}); server.events.emit('test1', 'hello-1'); server.events.emit('test2', 'hello-2'); // Ignored diff --git a/types/hapi/v17/test/server/server-events.ts b/types/hapi/v17/test/server/server-events.ts index 6c77d1826b..32deb7c8e6 100644 --- a/types/hapi/v17/test/server/server-events.ts +++ b/types/hapi/v17/test/server/server-events.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents +// https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents import {Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/server-expose.ts b/types/hapi/v17/test/server/server-expose.ts index 1852a26aec..c35e3c1d78 100644 --- a/types/hapi/v17/test/server/server-expose.ts +++ b/types/hapi/v17/test/server/server-expose.ts @@ -1,15 +1,15 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins import {Plugin, Server, ServerRegisterOptions} from "hapi"; const plugin1:Plugin = { name: 'example1', - register: function (server:Server, options:ServerRegisterOptions) { + register: (server:Server, options:ServerRegisterOptions) => { server.expose('util', () => console.log('something')); } }; const plugin2:Plugin = { name: 'example2', - register: function (server:Server, options:ServerRegisterOptions) { + register: (server:Server, options:ServerRegisterOptions) => { server.expose('util', () => console.log('something')); } }; diff --git a/types/hapi/v17/test/server/server-info.ts b/types/hapi/v17/test/server/server-info.ts index 6599fe5b5a..6f7ed24912 100644 --- a/types/hapi/v17/test/server/server-info.ts +++ b/types/hapi/v17/test/server/server-info.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo +// https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo import {Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/server-inject.ts b/types/hapi/v17/test/server/server-inject.ts index 03cb591e06..4d50f766e0 100644 --- a/types/hapi/v17/test/server/server-inject.ts +++ b/types/hapi/v17/test/server/server-inject.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions import {Request, ResponseToolkit, Server, ServerRoute} from "hapi"; const server = new Server({ @@ -7,7 +7,7 @@ const server = new Server({ const serverRoute: ServerRoute = { path: '/', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return 'Success!'; } }; diff --git a/types/hapi/v17/test/server/server-listener.ts b/types/hapi/v17/test/server/server-listener.ts index 7a99ed260d..b4cdcc47ed 100644 --- a/types/hapi/v17/test/server/server-listener.ts +++ b/types/hapi/v17/test/server/server-listener.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener import {Server} from "hapi"; import * as SocketIO from "socket.io" diff --git a/types/hapi/v17/test/server/server-load.ts b/types/hapi/v17/test/server/server-load.ts index 2b28bcda9d..e53f8e8546 100644 --- a/types/hapi/v17/test/server/server-load.ts +++ b/types/hapi/v17/test/server/server-load.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverload +// https://github.com/hapijs/hapi/blob/master/API.md#-serverload import {Server} from "hapi"; const server = new Server({ @@ -7,7 +7,7 @@ const server = new Server({ }); server.start(); -setTimeout(function() { +setTimeout(() => { console.log(server.load.rss); console.log(server.load.eventLoopDelay); console.log(server.load.heapUsed); diff --git a/types/hapi/v17/test/server/server-lookup.ts b/types/hapi/v17/test/server/server-lookup.ts index c0531afb49..45e8ef304c 100644 --- a/types/hapi/v17/test/server/server-lookup.ts +++ b/types/hapi/v17/test/server/server-lookup.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid +// https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid import {RequestRoute, Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/server-match.ts b/types/hapi/v17/test/server/server-match.ts index 4a3a7805af..8da8ba6220 100644 --- a/types/hapi/v17/test/server/server-match.ts +++ b/types/hapi/v17/test/server/server-match.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host +// https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host import {RequestRoute, Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/server-method.ts b/types/hapi/v17/test/server/server-method.ts index 8214842760..396cfa62d8 100644 --- a/types/hapi/v17/test/server/server-method.ts +++ b/types/hapi/v17/test/server/server-method.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods import {Server, ServerMethodConfigurationObject} from "hapi"; const server = new Server({ @@ -6,7 +6,7 @@ const server = new Server({ }); server.start(); -const add = function (a:any, b:any) { +const add = (a:any, b:any) => { return a + b; }; diff --git a/types/hapi/v17/test/server/server-methods.ts b/types/hapi/v17/test/server/server-methods.ts index 1d0831fd53..4ce4b8ceaf 100644 --- a/types/hapi/v17/test/server/server-methods.ts +++ b/types/hapi/v17/test/server/server-methods.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-servermethods +// https://github.com/hapijs/hapi/blob/master/API.md#-servermethods import {Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/server-mime.ts b/types/hapi/v17/test/server/server-mime.ts index 76fcac5594..ad8922d0b5 100644 --- a/types/hapi/v17/test/server/server-mime.ts +++ b/types/hapi/v17/test/server/server-mime.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-servermime +// https://github.com/hapijs/hapi/blob/master/API.md#-servermime import {Server, ServerOptions} from "hapi"; const options:ServerOptions = { diff --git a/types/hapi/v17/test/server/server-path.ts b/types/hapi/v17/test/server/server-path.ts index 4baa613245..7578a9ba2f 100644 --- a/types/hapi/v17/test/server/server-path.ts +++ b/types/hapi/v17/test/server/server-path.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto +// https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto import {Plugin, Server, ServerRegisterOptions, ServerRoute} from "hapi"; const server = new Server({ @@ -15,7 +15,7 @@ const serverRouteOption:ServerRoute = { const plugin:Plugin = { name: 'example', - register: function (server:Server, options:ServerRegisterOptions) { + register: (server:Server, options:ServerRegisterOptions) => { // Assuming the Inert plugin was registered previously server.path(__dirname + '../static'); server.route(serverRouteOption); diff --git a/types/hapi/v17/test/server/server-plugins.ts b/types/hapi/v17/test/server/server-plugins.ts index 620609b4cb..c38f240067 100644 --- a/types/hapi/v17/test/server/server-plugins.ts +++ b/types/hapi/v17/test/server/server-plugins.ts @@ -1,9 +1,9 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins +// https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins import {Plugin, Server, ServerRegisterOptions} from "hapi"; const plugin:Plugin = { name: 'example', - register: function (server:Server, options:ServerRegisterOptions) { + register: (server:Server, options:ServerRegisterOptions) => { server.expose('key', 'value'); server.plugins.example.other = 'other'; diff --git a/types/hapi/v17/test/server/server-settings.ts b/types/hapi/v17/test/server/server-settings.ts index 07bfec2b64..ec30cdc606 100644 --- a/types/hapi/v17/test/server/server-settings.ts +++ b/types/hapi/v17/test/server/server-settings.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serversettings +// https://github.com/hapijs/hapi/blob/master/API.md#-serversettings import {Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/server-start.ts b/types/hapi/v17/test/server/server-start.ts index ab95930a4d..228b9ca6a2 100644 --- a/types/hapi/v17/test/server/server-start.ts +++ b/types/hapi/v17/test/server/server-start.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart import {Server} from "hapi"; const server = new Server({ diff --git a/types/hapi/v17/test/server/server-state.ts b/types/hapi/v17/test/server/server-state.ts index 9952ee0e77..7a6c118c4d 100644 --- a/types/hapi/v17/test/server/server-state.ts +++ b/types/hapi/v17/test/server/server-state.ts @@ -8,7 +8,7 @@ const options: ServerOptions = { const serverRoute: ServerRoute = { path: '/say-hello', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return h.response('Hello').state('data', { firstVisit: false }); } } diff --git a/types/hapi/v17/test/server/server-stop.ts b/types/hapi/v17/test/server/server-stop.ts index a143577410..c07649ff65 100644 --- a/types/hapi/v17/test/server/server-stop.ts +++ b/types/hapi/v17/test/server/server-stop.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions +// https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions import {Server} from "hapi"; const server = new Server({ @@ -12,6 +12,6 @@ server.events.on('start', () => { server.events.on('stop', () => { console.log('Server stoped.'); }); -setTimeout(function() { +setTimeout(() => { server.stop({ timeout: 10 * 1000 }); }, 5 * 1000); diff --git a/types/hapi/v17/test/server/server-table.ts b/types/hapi/v17/test/server/server-table.ts index 78f2df90db..75d63ac724 100644 --- a/types/hapi/v17/test/server/server-table.ts +++ b/types/hapi/v17/test/server/server-table.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost +// https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost import {Request, ResponseToolkit, Server, ServerOptions} from "hapi"; const options: ServerOptions = { @@ -11,7 +11,7 @@ server.app.key = 'value2'; server.route({ path: '/', method: 'GET', - handler: function (request: Request, h: ResponseToolkit) { + handler: (request: Request, h: ResponseToolkit) => { return h.response("Hello World"); } }); diff --git a/types/hapi/v17/test/server/server-version.ts b/types/hapi/v17/test/server/server-version.ts index 02f7ca1d20..ecca8ba5ba 100644 --- a/types/hapi/v17/test/server/server-version.ts +++ b/types/hapi/v17/test/server/server-version.ts @@ -1,4 +1,4 @@ -// https://github.com/hapijs/hapi/blob/master/API.md#-serverversion +// https://github.com/hapijs/hapi/blob/master/API.md#-serverversion import {Server} from "hapi"; const server = new Server({ From 9f0b8755afd962705a549c3c3b056004d4c54f2a Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 10 Dec 2017 18:20:19 -0300 Subject: [PATCH 75/79] Add "server-options.ts" test file containing all possible options. --- types/hapi/v17/test/index.test.d.ts | 1 + types/hapi/v17/test/server/server-options.ts | 103 +++++++++++++++++++ 2 files changed, 104 insertions(+) create mode 100644 types/hapi/v17/test/server/server-options.ts diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index a3e94ac7dd..7b9041f929 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -51,6 +51,7 @@ export * from './server/server-match'; export * from './server/server-method'; export * from './server/server-methods'; export * from './server/server-mime'; +export * from './server/server-options'; export * from './server/server-path'; export * from './server/server-plugins'; export * from './server/server-settings'; diff --git a/types/hapi/v17/test/server/server-options.ts b/types/hapi/v17/test/server/server-options.ts new file mode 100644 index 0000000000..8057613781 --- /dev/null +++ b/types/hapi/v17/test/server/server-options.ts @@ -0,0 +1,103 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#-server-options +import {Server, ServerOptions, Plugin, Request, ServerRegisterOptions, ServerRoute, ResponseToolkit} from "hapi"; +import {MimosOptions, MimosOptionsValue} from "mimos"; + +const CatboxMemory = require('catbox-memory'); + +const mimeOptions: MimosOptions = { + override: { + 'node/module': { + source: 'iana', + compressible: true, + extensions: ['node', 'modsule', 'npm'], + type: 'node/module' + }, + 'application/javascript': { + source: 'iana', + charset: 'UTF-8', + compressible: true, + extensions: ['js', 'javascript'], + type: 'text/javascript' + }, + 'text/html': { + predicate: (mime:MimosOptionsValue) => { + if (1 == 1) { + //mime.foo = 'test'; + } + else { + //mime.foo = 'bar'; + } + return mime; + } + } + } +}; + +const plugin: Plugin = { + name: 'example', + register: (server:Server, options:ServerRegisterOptions) => { + server.expose('key', 'value'); + server.plugins.example.other = 'other'; + console.log(server.plugins.example.key); // 'value' + console.log(server.plugins.example.other); // 'other' + } +}; + +const serverRoute: ServerRoute = { + path: '/', + method: 'GET', + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + } +}; + +const options: ServerOptions = { + address: '0.0.0.0', + app: { + key1: 'value1', + key2: 'value2', + any_thing: 'any_value', + }, + autoListen: true, + cache: { + engine: CatboxMemory, + name: 'test', + shared: true, + partition: 'hapi-cache', + any_thing_1: 'any_thing_1', + any_thing_2: 'any_thing_2' + }, + compression: { + minBytes: 1024 + }, + debug: { + request: ['implementation'] + }, + host: 'localhost', + listener: null, + load: { sampleInterval: 0 }, + mime: mimeOptions, + plugins: plugin, + port: 8000, + router: { + isCaseSensitive: true, + stripTrailingSlash: false + }, + routes: serverRoute, + state: { + strictHeader: true, + ignoreErrors: false, + isSecure: true, + isHttpOnly: true, + isSameSite: 'Strict', + encoding: 'none' + }, + tls: null +}; + +const server = new Server(options); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +}); From cb280b5ccfa3fb9d43501cf47d59acb965361d40 Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 10 Dec 2017 18:49:38 -0300 Subject: [PATCH 76/79] Add type object to compression property. It is not only boolean. --- types/hapi/v17/definitions/server/server-options.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/hapi/v17/definitions/server/server-options.d.ts b/types/hapi/v17/definitions/server/server-options.d.ts index 407ebfd1c4..606dd701ba 100644 --- a/types/hapi/v17/definitions/server/server-options.d.ts +++ b/types/hapi/v17/definitions/server/server-options.d.ts @@ -55,7 +55,7 @@ export interface ServerOptions { * 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; + compression?: boolean | object; /** * Default value: '1024'. From 6a92487939470e96f6f3219963e66962a97ff6ac Mon Sep 17 00:00:00 2001 From: rafaelsouzaf Date: Sun, 10 Dec 2017 18:50:21 -0300 Subject: [PATCH 77/79] Add more options in "server-options.ts" test file. --- types/hapi/v17/test/server/server-options.ts | 22 +++++++++++++------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/types/hapi/v17/test/server/server-options.ts b/types/hapi/v17/test/server/server-options.ts index 8057613781..49d567eee8 100644 --- a/types/hapi/v17/test/server/server-options.ts +++ b/types/hapi/v17/test/server/server-options.ts @@ -1,5 +1,5 @@ // https://github.com/hapijs/hapi/blob/master/API.md#-server-options -import {Server, ServerOptions, Plugin, Request, ServerRegisterOptions, ServerRoute, ResponseToolkit} from "hapi"; +import {Server, ServerOptions, Plugin, ServerRegisterOptions, RouteOptions} from "hapi"; import {MimosOptions, MimosOptionsValue} from "mimos"; const CatboxMemory = require('catbox-memory'); @@ -43,12 +43,18 @@ const plugin: Plugin = { } }; -const serverRoute: ServerRoute = { - path: '/', - method: 'GET', - handler: (request: Request, h: ResponseToolkit) => { - return 'ok: ' + request.path; - } +const routeOptions: RouteOptions = { + compression: { + test: { + some: 'option' + } + }, + files: { + relativeTo: __dirname + }, + cors: { + origin: ['http://test.example.com', 'http://www.example.com', 'http://*.a.com'] + }, }; const options: ServerOptions = { @@ -83,7 +89,7 @@ const options: ServerOptions = { isCaseSensitive: true, stripTrailingSlash: false }, - routes: serverRoute, + routes: routeOptions, state: { strictHeader: true, ignoreErrors: false, From d780053e7fe2af628a64ef46ce112ac17cf5889c Mon Sep 17 00:00:00 2001 From: rsouza Date: Mon, 11 Dec 2017 15:06:56 -0300 Subject: [PATCH 78/79] Following best practices of Function Overloading: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html --- .../hapi/v17/definitions/request/request.d.ts | 7 +-- .../definitions/response/response-events.d.ts | 5 ++ .../definitions/response/response-object.d.ts | 12 ++--- .../response/response-toolkit.d.ts | 19 +++---- .../v17/definitions/server/server-auth.d.ts | 6 +-- .../v17/definitions/server/server-events.d.ts | 12 ++--- .../v17/definitions/server/server-state.d.ts | 6 +-- types/hapi/v17/definitions/server/server.d.ts | 54 +++++++------------ 8 files changed, 42 insertions(+), 79 deletions(-) diff --git a/types/hapi/v17/definitions/request/request.d.ts b/types/hapi/v17/definitions/request/request.d.ts index 5fe1a63f5b..a0605254a8 100644 --- a/types/hapi/v17/definitions/request/request.d.ts +++ b/types/hapi/v17/definitions/request/request.d.ts @@ -182,9 +182,7 @@ export interface Request extends Podium { * @return ResponseObject * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options) */ - generateResponse(source: object, options?: {variety?: string; prepare?: Function; marshal?: Function; close?: Function; }): ResponseObject; - generateResponse(source: string, options?: {variety?: string; prepare?: Function; marshal?: Function; close?: Function; }): ResponseObject; - generateResponse(source: null, options?: {variety?: string; prepare?: Function; marshal?: Function; close?: Function; }): ResponseObject; + generateResponse(source: string | object | null, options?: {variety?: string; prepare?: Function; marshal?: Function; close?: Function; }): ResponseObject; /** * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are: @@ -194,8 +192,7 @@ export interface Request extends Podium { * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data) */ - log(tags: string, data?: string | object | (() => string | object)): void; - log(tags: string[], data?: string | object | (() => string | object)): void; + log(tags: string | string[], data?: string | object | (() => string | object)): void; /** * Changes the request method before the router begins processing the request where: diff --git a/types/hapi/v17/definitions/response/response-events.d.ts b/types/hapi/v17/definitions/response/response-events.d.ts index e5dcb43d30..087b92cf37 100644 --- a/types/hapi/v17/definitions/response/response-events.d.ts +++ b/types/hapi/v17/definitions/response/response-events.d.ts @@ -14,6 +14,11 @@ export interface ResponseEvents extends Podium { * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). */ on(criteria: 'peek' | 'finish', listener: Function): void; + + /** + * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding). + * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function (). + */ once(criteria: 'peek' | 'finish', listener: Function): void; } diff --git a/types/hapi/v17/definitions/response/response-object.d.ts b/types/hapi/v17/definitions/response/response-object.d.ts index 378fee420f..b9887c4ae6 100644 --- a/types/hapi/v17/definitions/response/response-object.d.ts +++ b/types/hapi/v17/definitions/response/response-object.d.ts @@ -150,8 +150,7 @@ export interface ResponseObject extends Podium { * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options) */ - etag(tag: string): ResponseObject; - etag(tag: string, options: {weak: boolean, vary: boolean}): ResponseObject; + etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject; /** * Sets an HTTP header where: @@ -165,8 +164,7 @@ export interface ResponseObject extends Podium { * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options) */ - header(name: string, value: string): ResponseObject; - header(name: string, value: string, options: ResponseObjectHeaderOptions): ResponseObject; + header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject; /** * Sets the HTTP 'Location' header where: @@ -209,8 +207,7 @@ export interface ResponseObject extends Podium { * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options) */ - state(name: string, value: object): ResponseObject; - state(name: string, value: object, options: ServerStateCookieOptions): ResponseObject; + state(name: string, value: object, options?: ServerStateCookieOptions): ResponseObject; /** * Sets a string suffix when the response is process via JSON.stringify() where: @@ -244,8 +241,7 @@ export interface ResponseObject extends Podium { * @return Return value: the current response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options) */ - unstate(name: string): ResponseObject; - unstate(name: string, options: ServerStateCookieOptions): ResponseObject; + unstate(name: string, options?: ServerStateCookieOptions): ResponseObject; /** * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where: diff --git a/types/hapi/v17/definitions/response/response-toolkit.d.ts b/types/hapi/v17/definitions/response/response-toolkit.d.ts index 7c5b122c2f..7496b4cee2 100644 --- a/types/hapi/v17/definitions/response/response-toolkit.d.ts +++ b/types/hapi/v17/definitions/response/response-toolkit.d.ts @@ -77,8 +77,7 @@ export interface ResponseToolkit { * it should be used as the return value (but may be customize using the response methods). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions) */ - entity(): ResponseObject | undefined; - entity(options: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; + entity(options?: {etag?: string, modified?: string, vary?: boolean}): ResponseObject | undefined; /** * Redirects the client to the specified uri. Same as calling h.response().redirect(uri). @@ -86,8 +85,7 @@ export interface ResponseToolkit { * @return Returns a response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi) */ - redirect(): ResponseObject; - redirect(uri: string): ResponseObject; + redirect(uri?: string): ResponseObject; /** * Wraps the provided value and returns a response object which allows customizing the response @@ -96,9 +94,7 @@ export interface ResponseToolkit { * @return Returns a response object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue) */ - response(): ResponseObject; - response(value: string): ResponseObject; - response(value: object): ResponseObject; + response(value?: string | object): ResponseObject; /** * Sets a response cookie using the same arguments as response.state(). @@ -108,8 +104,7 @@ export interface ResponseToolkit { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options) */ - state(name: string, value: string): void; - state(name: string, value: string, options: ServerStateCookieOptions): void; + state(name: string, value: string, options?: ServerStateCookieOptions): void; /** * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where: @@ -124,8 +119,7 @@ export interface ResponseToolkit { * There is no difference between throwing the error or passing it with the h.unauthenticated() method is no credentials are passed, but it might still be helpful for code clarity. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data) */ - unauthenticated(error: Error): void; - unauthenticated(error: Error, data: {credentials: object, artifacts?: object}): void; + unauthenticated(error: Error, data?: {credentials: object, artifacts?: object}): void; /** * Clears a response cookie using the same arguments as @@ -134,7 +128,6 @@ export interface ResponseToolkit { * @return void. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options) */ - unstate(name: string): void; - unstate(name: string, options: ServerStateCookieOptions): void; + unstate(name: string, options?: ServerStateCookieOptions): void; } diff --git a/types/hapi/v17/definitions/server/server-auth.d.ts b/types/hapi/v17/definitions/server/server-auth.d.ts index d8f1c257e6..0b082c2872 100644 --- a/types/hapi/v17/definitions/server/server-auth.d.ts +++ b/types/hapi/v17/definitions/server/server-auth.d.ts @@ -43,8 +43,7 @@ export interface ServerAuth { * authentication configuration of a route, use server.auth.lookup(request.route). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions) */ - default(options: string): void; - default(options: ServerAuthConfig): void; + default(options: string | ServerAuthConfig): void; /** * Registers an authentication scheme where: @@ -65,8 +64,7 @@ export interface ServerAuth { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options) */ - strategy(name: string, scheme: string): void; - strategy(name: string, scheme: string, options: object): void; + strategy(name: string, scheme: string, options?: object): void; /** * Tests a request against an authentication strategy where: diff --git a/types/hapi/v17/definitions/server/server-events.d.ts b/types/hapi/v17/definitions/server/server-events.d.ts index 8d07ee0b5b..5eb7bdc283 100644 --- a/types/hapi/v17/definitions/server/server-events.d.ts +++ b/types/hapi/v17/definitions/server/server-events.d.ts @@ -100,9 +100,7 @@ export interface ServerEvents extends Podium { * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event) * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event) */ - on(criteria: string, listener: Function): void; - on(criteria: ServerEventsApplicationObject, listener: Function): void; - on(criteria: ServerEventCriteria, listener: Function): void; + on(criteria: string | ServerEventsApplicationObject | ServerEventCriteria, listener: Function): void; /** * Same as calling [server.events.on()](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) with the count option set to 1. @@ -114,9 +112,7 @@ export interface ServerEvents extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener) */ - once(criteria: string, listener: (...args: any[]) => void): void; // TODO I am not sure if the best way (here and the functions above/below) is use Function or (...args: any[]) => void) considering the JSDocs "The function signature depends on the event argument" - once(criteria: ServerEventsApplicationObject, listener: Function): void; - once(criteria: ServerEventCriteria, listener: Function): void; + once(criteria: string | ServerEventsApplicationObject | ServerEventCriteria, listener: Function): void; /** * Same as calling server.events.on() with the count option set to 1. @@ -127,9 +123,7 @@ export interface ServerEvents extends Podium { * @return Return value: a promise that resolves when the event is emitted. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria) */ - once(criteria: string): any; - once(criteria: ServerEventsApplicationObject): any; - once(criteria: ServerEventCriteria): any; + once(criteria: string | ServerEventsApplicationObject | ServerEventCriteria): any; /** * The follow method is only mentioned in Hapi API. The doc about that method can be found [here](https://github.com/hapijs/podium/blob/master/API.md#podiumremovelistenername-listener) diff --git a/types/hapi/v17/definitions/server/server-state.d.ts b/types/hapi/v17/definitions/server/server-state.d.ts index f233956a29..74842abd78 100644 --- a/types/hapi/v17/definitions/server/server-state.d.ts +++ b/types/hapi/v17/definitions/server/server-state.d.ts @@ -43,8 +43,7 @@ export interface ServerState { /** * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()). */ - add(name: string): void; - add(name: string, options: ServerStateCookieOptions): void; + add(name: string, options?: ServerStateCookieOptions): void; /** * Formats an HTTP 'Set-Cookie' header based on the server.options.state where: @@ -56,8 +55,7 @@ export interface ServerState { * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formating (e.g. when headers are set manually). * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies) */ - format(cookies: ServerStateFormat): string; - format(cookies: ServerStateFormat[]): string; + format(cookies: ServerStateFormat | ServerStateFormat[]): string; /** * Parses an HTTP 'Cookies' header based on the server.options.state where: diff --git a/types/hapi/v17/definitions/server/server.d.ts b/types/hapi/v17/definitions/server/server.d.ts index b7ac0e908f..01d5fcc062 100644 --- a/types/hapi/v17/definitions/server/server.d.ts +++ b/types/hapi/v17/definitions/server/server.d.ts @@ -99,8 +99,7 @@ export class Server extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents) */ - event(events: ServerEventsApplication): void; - event(events: ServerEventsApplication[]): void; + event(events: ServerEventsApplication | ServerEventsApplication[]): void; /** * Access: podium public interface. @@ -278,10 +277,7 @@ export class Server extends Podium { * The method does not provide version dependency which should be implemented using npm peer dependencies. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after) */ - dependency(dependencies: string): void; - dependency(dependencies: string, after: ((server: Server) => void)): void; - dependency(dependencies: string[]): void; - dependency(dependencies: string[], after: ((server: Server) => void)): void; + dependency(dependencies: string | string[], after?: ((server: Server) => void)): void; /** * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where: @@ -333,18 +329,15 @@ export class Server extends Podium { * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents) */ - ext(events: ServerExtEventsObject): void; - ext(events: ServerExtEventsObject[]): void; - ext(events: ServerExtEventsRequestObject): void; - ext(events: ServerExtEventsRequestObject[]): void; + ext(events: ServerExtEventsObject | ServerExtEventsObject[]): void; + ext(events: ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void; /** * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments. * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options) */ - ext(event: ServerExtType, method: ServerExtPointFunction | Lifecycle.Method | Function): void; - ext(event: ServerExtType, method: ServerExtPointFunction | Lifecycle.Method | Function, options: ServerExtOptions): void; + ext(event: ServerExtType, method: ServerExtPointFunction | Lifecycle.Method | Function, options?: ServerExtOptions): void; /** * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port. @@ -390,8 +383,7 @@ export class Server extends Podium { * * request - the request object. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions) */ - inject(options: string): ServerInjectResponse; - inject(options: ServerInjectOptions): ServerInjectResponse; + inject(options: string | ServerInjectOptions): ServerInjectResponse; /** * Logs server events that cannot be associated with a specific request. When called the server emits a 'log' event which can be used by other listeners or plugins to record the information or output to the console. The arguments are: @@ -419,8 +411,7 @@ export class Server extends Podium { * @return Return value: the route information if found, otherwise null. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host) */ - match(method: Util.HTTP_METHODS, path: string): RequestRoute | null; - match(method: Util.HTTP_METHODS, path: string, host: string): RequestRoute | null; + match(method: Util.HTTP_METHODS, path: string, host?: string): RequestRoute | null; /** * Registers a server method where: @@ -438,8 +429,7 @@ export class Server extends Podium { * When configured with caching enabled, server.methods[name].cache is assigned an object with the following properties and methods: - await drop(...args) - a function that can be used to clear the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options) */ - method(name: string, method: ServerMethod): void; - method(name: string, method: ServerMethod, options: ServerMethodOptions): void; + method(name: string, method: ServerMethod, options?: ServerMethodOptions): void; /** * Registers a server method function as described in server.method() using a configuration object where: @@ -450,8 +440,7 @@ export class Server extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods) */ - method(methods: ServerMethodConfigurationObject): void; - method(methods: ServerMethodConfigurationObject[]): void; + method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void; /** * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where: @@ -470,7 +459,7 @@ export class Server extends Podium { * * * plugin - a plugin object. * * * options - (optional) options passed to the plugin during registration. * * * once, routes - (optional) plugin-specific registration options as defined below. - * @paramoptions - (optional) registration options (different from the options passed to the registration function): + * @param options - (optional) registration options (different from the options passed to the registration function): * * once - if true, subsequent registrations of the same plugin are skipped without error. Cannot be used with plugin options. Defaults to false. If not set to true, an error will be thrown the second time a plugin is registered on the server. * * routes - modifiers applied to each route added by the plugin: * * * prefix - string added as prefix to any route path (must begin with '/'). If a plugin registers a child plugin the prefix is passed on to the child or is added in front of the child-specific prefix. @@ -478,10 +467,8 @@ export class Server extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options) */ - register(plugins: Plugin | ServerRegisterPluginObject): void; - register(plugins: Plugin | ServerRegisterPluginObject, options: ServerRegisterOptions): void; - register(plugins: Plugin[] | ServerRegisterPluginObject[]): void; - register(plugins: Plugin[] | ServerRegisterPluginObject[], options: ServerRegisterOptions): void; + register(plugins: Plugin | Plugin[], options?: ServerRegisterOptions): void; + register(plugins: ServerRegisterPluginObject | ServerRegisterPluginObject[], options?: ServerRegisterOptions): void; /** * Adds a route where: @@ -496,8 +483,7 @@ export class Server extends Podium { * Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute) */ - route(route: ServerRoute): void; - route(route: ServerRoute[]): void; + route(route: ServerRoute | ServerRoute[]): void; /** * Defines a route rules processor for converting route rules object into route configuration where: @@ -506,7 +492,7 @@ export class Server extends Podium { * * info - an object with the following properties: * * * method - the route method. * * * path - the route path. - * * *vhost - the route virtual host (if any defined). + * * * vhost - the route virtual host (if any defined). * * returns a route config object. * @param options - optional settings: * * validate - rules object validation: @@ -516,8 +502,7 @@ export class Server extends Podium { * @return void * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options) */ - rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object): void; - rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options: {validate: object}): void; // TODO needs implementation + rules(processor: (rules: object, info: {method: string, path: string, vhost?: string}) => object, options?: {validate: object}): void; // TODO needs implementation /** * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false). @@ -536,8 +521,7 @@ export class Server extends Podium { * State defaults can be modified via the server default state configuration option. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options) */ - state(name: string): void; - state(name: string, options: ServerStateCookieOptions): void; + state(name: string, options?: ServerStateCookieOptions): void; /** * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where: @@ -546,8 +530,7 @@ export class Server extends Podium { * @return Return value: none. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions) */ - stop(): void; - stop(options: {timeout: number}): void; + stop(options?: {timeout: number}): void; /** * Returns a copy of the routing table where: @@ -558,7 +541,6 @@ export class Server extends Podium { * * path - the route path. * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost) */ - table(): {settings: ServerRoute; method: Util.HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; // TODO I am not sure if the ServerRoute is the object expected here - table(host: string): {settings: ServerRoute; method: Util.HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; + table(host?: string): {settings: ServerRoute; method: Util.HTTP_METHODS_PARTIAL_LOWERCASE, path: string}[]; // TODO I am not sure if the ServerRoute is the object expected here } From a1c8fc8f932797b0e303450ed2355ae3fbb1c1bb Mon Sep 17 00:00:00 2001 From: rsouza Date: Mon, 11 Dec 2017 16:18:57 -0300 Subject: [PATCH 79/79] Add RouteOptions test file with complete available options. --- types/hapi/v17/test/index.test.d.ts | 1 + types/hapi/v17/test/route/route-options.ts | 167 +++++++++++++++++++++ 2 files changed, 168 insertions(+) create mode 100644 types/hapi/v17/test/route/route-options.ts diff --git a/types/hapi/v17/test/index.test.d.ts b/types/hapi/v17/test/index.test.d.ts index 7b9041f929..08711f00f6 100644 --- a/types/hapi/v17/test/index.test.d.ts +++ b/types/hapi/v17/test/index.test.d.ts @@ -26,6 +26,7 @@ export * from './response/response-events'; export * from './route/adding-routes'; export * from './route/config'; export * from './route/handler'; +export * from './route/route-options'; export * from './route/route-options-pre'; /** SERVER */ diff --git a/types/hapi/v17/test/route/route-options.ts b/types/hapi/v17/test/route/route-options.ts new file mode 100644 index 0000000000..5e2506684f --- /dev/null +++ b/types/hapi/v17/test/route/route-options.ts @@ -0,0 +1,167 @@ +// https://github.com/hapijs/hapi/blob/master/API.md#route-options +import { + EmptyStatusCode, + Request, + ResponseToolkit, + RouteOptions, + RouteOptionsAccess, + RouteOptionsAccessEntity, + RouteOptionsAccessMode, + RouteOptionsAccessPayload, + RouteOptionsCors, + RouteOptionsPayload, + RouteOptionsResponse, + RouteOptionsValidate, + Server +} from "hapi"; + +const routeOptionsAccess: RouteOptionsAccess = { + access: {}, + scope: false, + entity: RouteOptionsAccessEntity.User, + mode: RouteOptionsAccessMode.Optional, + payload: RouteOptionsAccessPayload.Optional, + strategies: ['', ''], + strategy: '' +}; + +const corsOption: RouteOptionsCors = { + origin: 'ignore', + maxAge: 5000, + headers: ['test', 'test', 'test'], + additionalHeaders: ['test', 'test', 'test'], + exposedHeaders: ['test', 'test', 'test'], + additionalExposedHeaders: ['test', 'test', 'test'], + credentials: false +}; + +const payloadOptions: RouteOptionsPayload = { + allow: 'string', + compression: { + test1: { + test: 2 + } + }, + defaultContentType: 'application/json', + failAction: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + maxBytes: 1048576, + multipart: { + output: 'annotated' + }, + output: 'stream', + override: '', + parse: 'gunzip', + timeout: 5000, + uploads: 'dir/' +}; + +const pre1 = (request: Request, h: ResponseToolkit) => { + return 'Hello'; +}; + +const pre2 = (request: Request, h: ResponseToolkit) => { + return 'World'; +}; + +const pre3 = (request: Request, h: ResponseToolkit) => { + return request.pre.m1 + ' ' + request.pre.m2; +}; + +const routeOptionsResponse:RouteOptionsResponse = { + emptyStatusCode: EmptyStatusCode.HTTP_200, + failAction: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + modify: false, + options: null, + ranges: true, + sample: 100, + schema: true, + status: { + '200': true, + '302': true, + '404': false, + } +}; + +const routeOptionsValidate: RouteOptionsValidate = { + errorFields: {}, + failAction: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + headers: false, + options: {}, + params: false, + payload: true, + query: true, +}; + +const routeOptions: RouteOptions = { + + app: {}, + auth: routeOptionsAccess, + bind: null, + cache: { + privacy: 'default', + statuses: [200], + otherwise: 'no-cache' + }, + compression: { + test1: { + test: 2 + } + }, + cors: corsOption, + description: 'description here', + ext: null, + files: { relativeTo: '.' }, + handler: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + id: 'test', + isInternal: false, + json: null, + jsonp: 'callback', + log: { collect: false }, + notes: ['test', 'test', 'test'], + payload: payloadOptions, + plugins: { + plugin1: {}, + plugin2: {}, + }, + pre: [ + [ + // m1 and m2 executed in parallel + { method: pre1, assign: 'm1' }, + { method: pre2, assign: 'm2' } + ], + { method: pre3, assign: 'm3' }, + ], + response: routeOptionsResponse, + security: false, + state: { + parse: true, + failAction: (request: Request, h: ResponseToolkit) => { + return 'ok: ' + request.path; + }, + }, + tags: ['test', 'test', 'test'], + timeout: { + server: 10000, + socket: false + }, + validate: routeOptionsValidate + +}; + +const server = new Server({ + port: 8000, + routes: routeOptions +}); +server.start(); + +server.events.on('start', () => { + console.log('Server started at: ' + server.info.uri); +});