From ae60b8ca46d277d558d74afe2e03ab55f57d16b5 Mon Sep 17 00:00:00 2001 From: Alexander James Phillips Date: Sun, 7 May 2017 15:04:37 +0100 Subject: [PATCH] Move hapi dependencies to own modules catbox, h2o2, mime-db, mimos, podium, shot, vision Add tests where possible. Add note regarding apparent failure of some nested object literals to enforce typings --- types/boom/index.d.ts | 2 - types/boom/tsconfig.json | 4 +- types/{hapi => }/catbox/index.d.ts | 2 - types/catbox/tsconfig.json | 21 +++ types/h2o2/h2o2-tests.ts | 165 ++++++++++++++++++ types/h2o2/index.d.ts | 89 ++++++++++ types/h2o2/tsconfig.json | 22 +++ types/hapi/h2o2/h2o2-tests.ts | 64 ------- types/hapi/h2o2/index.d.ts | 75 -------- types/hapi/index.d.ts | 56 +++++- types/hapi/json/index.d.ts | 17 -- types/hapi/json/json-tests.ts | 8 - types/hapi/shot/index.d.ts | 109 ------------ .../tests/response/error-representation.ts | 4 +- types/hapi/tests/response/events.ts | 2 +- types/hapi/tsconfig.json | 15 +- types/inert/index.d.ts | 47 ++--- types/inert/inert-tests.ts | 129 ++++++++++---- types/inert/tsconfig.json | 2 +- types/{hapi => }/mime-db/index.d.ts | 2 - types/mime-db/tsconfig.json | 21 +++ types/{hapi => }/mimos/index.d.ts | 4 +- types/mimos/tsconfig.json | 21 +++ types/{hapi => }/podium/index.d.ts | 14 +- types/podium/podium-tests.ts | 33 ++++ types/podium/tsconfig.json | 22 +++ types/shot/index.d.ts | 113 ++++++++++++ types/shot/shot-tests.ts | 29 +++ types/shot/tsconfig.json | 22 +++ types/{hapi => }/vision/index.d.ts | 5 + types/vision/tsconfig.json | 22 +++ types/{hapi => }/vision/vision-tests.ts | 0 32 files changed, 768 insertions(+), 373 deletions(-) rename types/{hapi => }/catbox/index.d.ts (99%) create mode 100644 types/catbox/tsconfig.json create mode 100644 types/h2o2/h2o2-tests.ts create mode 100644 types/h2o2/index.d.ts create mode 100644 types/h2o2/tsconfig.json delete mode 100644 types/hapi/h2o2/h2o2-tests.ts delete mode 100644 types/hapi/h2o2/index.d.ts delete mode 100644 types/hapi/json/index.d.ts delete mode 100644 types/hapi/json/json-tests.ts delete mode 100644 types/hapi/shot/index.d.ts rename types/{hapi => }/mime-db/index.d.ts (93%) create mode 100644 types/mime-db/tsconfig.json rename types/{hapi => }/mimos/index.d.ts (91%) create mode 100644 types/mimos/tsconfig.json rename types/{hapi => }/podium/index.d.ts (97%) create mode 100644 types/podium/podium-tests.ts create mode 100644 types/podium/tsconfig.json create mode 100644 types/shot/index.d.ts create mode 100644 types/shot/shot-tests.ts create mode 100644 types/shot/tsconfig.json rename types/{hapi => }/vision/index.d.ts (98%) create mode 100644 types/vision/tsconfig.json rename types/{hapi => }/vision/vision-tests.ts (100%) diff --git a/types/boom/index.d.ts b/types/boom/index.d.ts index bb2f5e4bc0..4d9d0b3a5b 100644 --- a/types/boom/index.d.ts +++ b/types/boom/index.d.ts @@ -3,8 +3,6 @@ // Definitions by: Igor Rogatty , AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - export = Boom; declare namespace Boom { diff --git a/types/boom/tsconfig.json b/types/boom/tsconfig.json index d64d51130b..1ad2b9c1f3 100644 --- a/types/boom/tsconfig.json +++ b/types/boom/tsconfig.json @@ -6,12 +6,12 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], - "types": [], + "types": ["node"], "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/hapi/catbox/index.d.ts b/types/catbox/index.d.ts similarity index 99% rename from types/hapi/catbox/index.d.ts rename to types/catbox/index.d.ts index 013997cfaf..e832f58446 100644 --- a/types/hapi/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -1,5 +1,3 @@ -// TODO needs tests -// TODO move to own definition // Type definitions for catbox 7.1 // Project: https://github.com/hapijs/catbox // Definitions by: Jason Swearingen , AJP diff --git a/types/catbox/tsconfig.json b/types/catbox/tsconfig.json new file mode 100644 index 0000000000..3bc13b0278 --- /dev/null +++ b/types/catbox/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/types/h2o2/h2o2-tests.ts b/types/h2o2/h2o2-tests.ts new file mode 100644 index 0000000000..f8e88c5c9b --- /dev/null +++ b/types/h2o2/h2o2-tests.ts @@ -0,0 +1,165 @@ +import http = require("http"); +import * as Boom from 'boom'; +import * as Hapi from 'hapi'; +import * as Wreck from 'wreck'; +import h2o2 = require('h2o2'); + +// https://github.com/hapijs/h2o2#manual-loading + +const server = new Hapi.Server({}); + +server.register({ + register: h2o2 +}, function (err) { + + if (err) { + console.log('Failed to load h2o2'); + } + + server.start(function (err) { + + console.log('Server started at: ' + server.info!.uri); + }); +}); + +// https://github.com/hapijs/h2o2#replyproxyoptions + +const handler: Hapi.RouteHandler = function (request, reply) { + + return reply.proxy({ host: 'example.com', port: 80, protocol: 'http' }); +}; + +// https://github.com/hapijs/h2o2#using-the-host-port-protocol-options + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + host: '10.33.33.1', + port: '443', + protocol: 'https' + } + } +}); + +// https://github.com/hapijs/h2o2#using-the-uri-option + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + uri: 'https://some.upstream.service.com/that/has?what=you&want=todo' + } + } +}); + +// https://github.com/hapijs/h2o2#custom-uri-template-values + +server.route({ + method: 'GET', + path: '/foo', + handler: { + proxy: { + uri: '{protocol}://{host}:{port}/go/to/{path}' + } + } +}); + +server.route({ + method: 'GET', + path: '/foo/{bar}', + handler: { + proxy: { + uri: 'https://some.upstream.service.com/some/path/to/{bar}' + } + } +}); + +// https://github.com/hapijs/h2o2#using-the-mapuri-and-onresponse-options + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + mapUri: function (request, callback) { + + console.log('doing some aditional stuff before redirecting'); + callback(null, 'https://some.upstream.service.com/'); + }, + onResponse: function (err, res, request, reply, settings, ttl) { + + console.log('receiving the response from the upstream.'); + Wreck.read(res, { json: true }, function (err, payload) { + + console.log('some payload manipulation if you want to.') + reply(payload).headers = res.headers; + }); + } + } + } +}); + +/** + * test code added in additional to code in docs. Demonstrates that for the moment + * you need flat + * objects with typing along the way to benefit from typescript catching + * misspelt, or unsupported keys. + * This is because of an unknown reason. Expecting this to work because: + * "Object literals get special treatment and undergo excess + * property checking when assigning them to other variables, or passing them + * as arguments", see github.com/Microsoft/TypeScript + */ + +var proxyOptions: h2o2.ProxyHandlerOptions = { + host: '10.33.33.1', + port: '443', + protocol: 'https' // errors correctly if misspelt +} + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + host: '10.33.33.1', + port: '443', + BAD_protocol: 'https' // TODO change typings to fix this / submit bug report + } + } +}) + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + uri: 'https://some.upstream.service.com/that/has?what=you&want=todo' + } + } +}) + +server.route({ + method: 'GET', + path: '/', + handler: { + proxy: { + mapUri: function (request: Hapi.Request, callback: (err: null | Boom.BoomError, value: string) => void) { + + console.log('doing some aditional stuff before redirecting'); + callback(null, 'https://some.upstream.service.com/'); + }, + onResponse: function (err: null | Boom.BoomError, res: http.IncomingMessage, request: Hapi.Request, reply: Hapi.ReplyWithContinue, settings: h2o2.ProxyHandlerOptions, ttl: number) { + + console.log('receiving the response from the upstream.'); + Wreck.read(res, { json: true }, function (err: null | Boom.BoomError, payload: any) { + + console.log('some payload manipulation if you want to.') + reply(payload).headers = res.headers; + }); + } + } + } +}); diff --git a/types/h2o2/index.d.ts b/types/h2o2/index.d.ts new file mode 100644 index 0000000000..d15eb90cec --- /dev/null +++ b/types/h2o2/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for h2o2 5.4 +// Project: https://github.com/hapijs/catbox +// Definitions by: Jason Swearingen , AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import http = require("http"); +import * as hapi from 'hapi'; +import * as Boom from 'boom'; + +declare namespace H2o2 { + /** Proxy handler options */ + export interface ProxyHandlerOptions { + /** host - upstream service host to proxy requests to. It will have the same path as the client request. */ + host?: string; + /** port - upstream service port. */ + port?: number | string; + /** protocol - protocol to use when making the request to the proxied host: */ + protocol?: 'http' | 'https'; + /** uri - absolute URI used instead of host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri. */ + uri?: string; + /** passThrough - if set to true, it forwards the headers from the client to the upstream service, headers sent from the upstream service will also be forwarded to the client. Defaults to false. */ + passThrough?: boolean; + /** localStatePassThrough - if set tofalse, any locally defined state is removed from incoming requests before being sent to the upstream service. This value can be overridden on a per state basis via the server.state()``passThrough option. Defaults to false */ + localStatePassThrough?: boolean; + /** acceptEncoding - if set to false, does not pass-through the 'Accept-Encoding' HTTP header which is useful for the onResponse post-processing to avoid receiving an encoded response. Can only be used together with passThrough. Defaults to true (passing header). */ + acceptEncoding?: boolean; + /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. If set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true. */ + rejectUnauthorized?: boolean; + /** xforward - if set to true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto', 'X-Forwarded-Host' headers when making a request to the proxied upstream endpoint. Defaults to false. */ + xforward?: boolean; + /** redirects - the maximum number of HTTP redirections allowed to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false. */ + redirects?: number | false; + /** timeout - number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes). */ + timeout?: number; + /** mapUri - a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function (request, callback) where: + * @param request - is the incoming request object. + * @param callback - is function (err, uri, headers) where: + * @param err - internal error condition. TODO: check this is of type BoomError or just Error. + * @param uri - the absolute proxy URI. + * @param headers - optional object where each key is an HTTP request header and the value is the header content. + */ + mapUri?: (request: hapi.Request, callback: (err: null | Boom.BoomError, uri: string, headers?: { [key: string]: string }) => void) => void; + /** + * onResponse - a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function (err, res, request, reply, settings, ttl) where: + * @param err - internal or upstream error returned from attempting to contact the upstream proxy. TODO: check this is of type BoomError or just Error. + * @param res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). + * @param request - is the incoming request object. + * @param reply - the reply interface function. + * @param settings - the proxy handler configuration. + * @param ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'. + */ + onResponse?: (err: null | Boom.BoomError, + res: http.IncomingMessage, + req: hapi.Request, + reply: hapi.ReplyWithContinue, // TODO, check it has continue + settings: ProxyHandlerOptions, + ttl: number) => void; + /** ttl - if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided). */ + ttl?: 'upstream'; + /** agent - a node http(s) agent to be used for connections to upstream server. @see {@link https://nodejs.org/api/http.html#http_class_http_agent} */ + agent?: http.Agent; + /** maxSockets - sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity. */ + maxSockets?: false | number; + } +} + +declare module 'hapi' { + /** + * As one of the handlers for hapi, it is used through the route configuration object. + * [see docs](https://github.com/hapijs/h2o2#usage) + */ + interface RouteHandlerPlugins { + proxy?: H2o2.ProxyHandlerOptions; + } + + interface Base_Reply { + /** + * Proxies the request to an upstream endpoint + * @param options an object including the same keys and restrictions defined by the [route proxy handler options](https://github.com/hapijs/h2o2#options). + * [see docs](https://github.com/hapijs/h2o2#replyproxyoptions) + */ + proxy(options: H2o2.ProxyHandlerOptions): void; + } +} + +declare var H2o2: hapi.PluginFunction<{}>; + +export = H2o2; diff --git a/types/h2o2/tsconfig.json b/types/h2o2/tsconfig.json new file mode 100644 index 0000000000..1abbac7fb0 --- /dev/null +++ b/types/h2o2/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "h2o2-tests.ts" + ] +} \ No newline at end of file diff --git a/types/hapi/h2o2/h2o2-tests.ts b/types/hapi/h2o2/h2o2-tests.ts deleted file mode 100644 index 981f712593..0000000000 --- a/types/hapi/h2o2/h2o2-tests.ts +++ /dev/null @@ -1,64 +0,0 @@ -import http = require("http"); -import * as Boom from 'boom'; -import * as Hapi from 'hapi'; -import * as Wreck from 'wreck'; -import * as h2o2 from './index'; - -// const handler = function (request: Hapi.Request, reply: Hapi.IReply) { -// return reply.proxy({ host: 'example.com', port: 80, protocol: 'http' }); -// }; - -const server = new Hapi.Server({}); - -var proxyOptions: h2o2.ProxyHandlerOptions = { - host: '10.33.33.1', - port: '443', - protocol: 'https' -}; -var routeConfig: Hapi.RouteConfiguration = { - method: 'GET', - path: '/', - handler: { - proxy: proxyOptions - } -}; -server.route({ - method: 'GET', - path: '/', - handler: { - proxy: proxyOptions - } -}); - -server.route({ - method: 'GET', - path: '/', - handler: { - proxy: { - uri: 'https://some.upstream.service.com/that/has?what=you&want=todo' - } - } -}); - -server.route({ - method: 'GET', - path: '/', - handler: { - proxy: { - mapUri: function (request: Hapi.Request, callback: (err: null | Boom.BoomError, value: string) => void) { - - console.log('doing some aditional stuff before redirecting'); - callback(null, 'https://some.upstream.service.com/'); - }, - onResponse: function (err: null | Boom.BoomError, res: http.IncomingMessage, request: Hapi.Request, reply: Hapi.ReplyWithContinue, settings: h2o2.ProxyHandlerOptions, ttl: number) { - - console.log('receiving the response from the upstream.'); - Wreck.read(res, { json: true }, function (err: null | Boom.BoomError, payload: any) { - - console.log('some payload manipulation if you want to.') - reply(payload).headers = res.headers; - }); - } - } - } -}); diff --git a/types/hapi/h2o2/index.d.ts b/types/hapi/h2o2/index.d.ts deleted file mode 100644 index 9ff4bd1f70..0000000000 --- a/types/hapi/h2o2/index.d.ts +++ /dev/null @@ -1,75 +0,0 @@ -// TODO move to own definition -// Type definitions for h2o2 5.4 -// Project: https://github.com/hapijs/catbox -// Definitions by: Jason Swearingen , AJP -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 - -import http = require("http"); -import * as hapi from 'hapi'; -import * as Boom from 'boom'; - -/** Proxy handler options */ -export interface ProxyHandlerOptions { - /** host - upstream service host to proxy requests to. It will have the same path as the client request. */ - host?: string; - /** port - upstream service port. */ - port?: string; - /** protocol - protocol to use when making the request to the proxied host: */ - protocol?: 'http' | 'https'; - /** uri - absolute URI used instead of host, port, protocol, path, and query. Cannot be used with host, port, protocol, or mapUri. */ - uri?: string; - /** passThrough - if set to true, it forwards the headers from the client to the upstream service, headers sent from the upstream service will also be forwarded to the client. Defaults to false. */ - passThrough?: boolean; - /** localStatePassThrough - if set tofalse, any locally defined state is removed from incoming requests before being sent to the upstream service. This value can be overridden on a per state basis via the server.state()``passThrough option. Defaults to false */ - localStatePassThrough?: boolean; - /** acceptEncoding - if set to false, does not pass-through the 'Accept-Encoding' HTTP header which is useful for the onResponse post-processing to avoid receiving an encoded response. Can only be used together with passThrough. Defaults to true (passing header). */ - acceptEncoding?: boolean; - /** rejectUnauthorized - sets the rejectUnauthorized property on the https agent making the request. This value is only used when the proxied server uses TLS/SSL. If set it will override the node.js rejectUnauthorized property. If false then ssl errors will be ignored. When true the server certificate is verified and an 500 response will be sent when verification fails. This shouldn't be used alongside the agent setting as the agent will be used instead. Defaults to the https agent default value of true. */ - rejectUnauthorized?: boolean; - /** xforward - if set to true, sets the 'X-Forwarded-For', 'X-Forwarded-Port', 'X-Forwarded-Proto', 'X-Forwarded-Host' headers when making a request to the proxied upstream endpoint. Defaults to false. */ - xforward?: boolean; - /** redirects - the maximum number of HTTP redirections allowed to be followed automatically by the handler. Set to false or 0 to disable all redirections (the response will contain the redirection received from the upstream service). If redirections are enabled, no redirections (301, 302, 307, 308) will be passed along to the client, and reaching the maximum allowed redirections will return an error response. Defaults to false. */ - redirects?: number | false; - /** timeout - number of milliseconds before aborting the upstream request. Defaults to 180000 (3 minutes). */ - timeout?: number; - /** mapUri - a function used to map the request URI to the proxied URI. Cannot be used together with host, port, protocol, or uri. The function signature is function (request, callback) where: - * @param request - is the incoming request object. - * @param callback - is function (err, uri, headers) where: - * @param err - internal error condition. TODO: check this is of type BoomError or just Error. - * @param uri - the absolute proxy URI. - * @param headers - optional object where each key is an HTTP request header and the value is the header content. - */ - mapUri?: (request: hapi.Request, callback: (err: null | Boom.BoomError, uri: string, headers?: { [key: string]: string }) => void) => void; - /** - * onResponse - a custom function for processing the response from the upstream service before sending to the client. Useful for custom error handling of responses from the proxied endpoint or other payload manipulation. Function signature is function (err, res, request, reply, settings, ttl) where: - * @param err - internal or upstream error returned from attempting to contact the upstream proxy. TODO: check this is of type BoomError or just Error. - * @param res - the node response object received from the upstream service. res is a readable stream (use the wreck module read method to easily convert it to a Buffer or string). - * @param request - is the incoming request object. - * @param reply - the reply interface function. - * @param settings - the proxy handler configuration. - * @param ttl - the upstream TTL in milliseconds if proxy.ttl it set to 'upstream' and the upstream response included a valid 'Cache-Control' header with 'max-age'. - */ - onResponse?: (err: null | Boom.BoomError, - res: http.IncomingMessage, - req: hapi.Request, - reply: hapi.ReplyWithContinue, // TODO, check it has continue - settings: ProxyHandlerOptions, - ttl: number) => void; - /** ttl - if set to 'upstream', applies the upstream response caching policy to the response using the response.ttl() method (or passed as an argument to the onResponse method if provided). */ - ttl?: 'upstream'; - /** agent - a node http(s) agent to be used for connections to upstream server. @see {@link https://nodejs.org/api/http.html#http_class_http_agent} */ - agent?: http.Agent; - /** maxSockets - sets the maximum number of sockets available per outgoing proxy host connection. false means use the wreck module default value (Infinity). Does not affect non-proxy outgoing client connections. Defaults to Infinity. */ - maxSockets?: false | number; -} - -declare module 'hapi' { - interface RouteHandlerPlugins { - /** - * the Proxy Handler - * @see {@link https://github.com/hapijs/h2o2#replyproxyoptions} - */ - proxy?: ProxyHandlerOptions; - } -} diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 2f555f68d2..2ef76367dd 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -22,7 +22,6 @@ * Renaming of all interfaces to remove preceding I in preparation of dtslint */ - import Events = require("events"); import stream = require("stream"); import http = require("http"); @@ -37,11 +36,10 @@ import { Schema as JoiValidationObject, } from 'joi'; -import * as Catbox from './catbox'; -import {MimosOptions} from './mimos'; -import * as Podium from './podium'; -import * as Json from './json'; -import * as Shot from './shot'; +import * as Catbox from 'catbox'; +import {MimosOptions} from 'mimos'; +import * as Podium from 'podium'; +import * as Shot from 'shot'; export interface Dictionary { [key: string]: T; @@ -1018,8 +1016,9 @@ interface ApplicationEventOptionsObject { * The route configuration object * * [See docs](https://hapijs.com/api/16.1.1#route-configuration) + * + * TODO typings check that the following refers to RouteAdditionalConfigurationOptions "Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on." */ -// TODO check that the following refers to RouteAdditionalConfigurationOptions "Note that the options object is deeply cloned (with the exception of bind which is shallowly copied) and cannot contain any values that are unsafe to perform deep copy on." export interface RouteConfiguration { /** the absolute path used to match incoming requests (must begin with '/'). Incoming requests are compared to the configured paths based on the connection router configuration option. The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. */ path: string; @@ -2535,3 +2534,46 @@ export interface PluginRegistrationOptions { routes?: {prefix?: string, vhost?: string | string[]}; select?: string | string[]; } + +/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + JSON + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */ +// This was in a seperate file and perhaps should move to some of the lib typings? +// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/16065#issuecomment-299443673 +// +// json/json-tests.ts +// +// import * as JSON from './index'; +// +// var a: JSON.StringifyReplacer = function(key, value) { +// if (key === "do not include") { +// return undefined; +// } +// return value; +// }; +// + +export module Json { + /** + * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} + */ + export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; + + /** + * Any value greater than 10 is truncated. + */ + export type StringifySpace = number | string; + + export interface StringifyArguments { + /** the replacer function or array. Defaults to no action. */ + replacer?: StringifyReplacer; + /** number of spaces to indent nested object keys. Defaults to no indentation. */ + space?: StringifySpace; + } +} diff --git a/types/hapi/json/index.d.ts b/types/hapi/json/index.d.ts deleted file mode 100644 index 6febf05c6a..0000000000 --- a/types/hapi/json/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ - -/** - * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter} - */ -export type StringifyReplacer = ((key: string, value: any) => any) | (string | number)[] | undefined; - -/** - * Any value greater than 10 is truncated. - */ -export type StringifySpace = number | string; - -export interface StringifyArguments { - /** the replacer function or array. Defaults to no action. */ - replacer?: StringifyReplacer; - /** number of spaces to indent nested object keys. Defaults to no indentation. */ - space?: StringifySpace; -} diff --git a/types/hapi/json/json-tests.ts b/types/hapi/json/json-tests.ts deleted file mode 100644 index cbe9529b83..0000000000 --- a/types/hapi/json/json-tests.ts +++ /dev/null @@ -1,8 +0,0 @@ -import * as JSON from './index'; - -var a: JSON.StringifyReplacer = function(key, value) { - if (key === "do not include") { - return undefined; - } - return value; -}; diff --git a/types/hapi/shot/index.d.ts b/types/hapi/shot/index.d.ts deleted file mode 100644 index 8bace851f1..0000000000 --- a/types/hapi/shot/index.d.ts +++ /dev/null @@ -1,109 +0,0 @@ -// TODO needs tests -// TODO move to own definition -// Type definitions for shot 3.4 -// Project: https://github.com/hapijs/shot -// Definitions by: AJP -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 - -import * as Http from 'http'; -import * as Stream from 'stream'; - -export interface Shot { - /** - * Injects a fake request into an HTTP server. - * @param dispatchFunc listener function. The same as you would pass to Http.createServer when making a node HTTP server. @see IListener - * @param options request options object @see RequestOptions - * @param callback the callback function @see Callback - * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} - */ - inject(dispatchFunc: Listener, options: RequestOptions, callback: (res: ResponseObject) => void): void; - - /** - * Checks if given object obj is a Shot Request object. - * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotisinjectionobj} - */ - isInjection(obj: any): boolean; -} - -/** - * listener function. The same as you would pass to Http.createServer when making a node HTTP server. Has the signature function (req, res) where: - * * req - a simulated request object. Inherits from Stream.Readable. - * * res - a simulated response object. Inherits from node's Http.ServerResponse. - * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} - */ -export interface Listener { - (req: SimulatedRequestObject, res: SimulatedResponseObject): void; -} - -/** - * a simulated request object. Inherits from Stream.Readable. - * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} - */ -interface SimulatedRequestObject extends Stream.Readable {} - -/** - * a simulated response object. Inherits from node's Http.ServerResponse. - * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} - */ -interface SimulatedResponseObject extends Http.ServerResponse {} - -/** - * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} - */ -export interface RequestOptions { - /** a string specifying the request URL. */ - url: string; - /** a string specifying the HTTP request method, defaulting to 'GET'. */ - method?: string; - /** a string specifying the HTTP HOST header value to be used if no header is provided, and the url does not include an authority component. Defaults to 'localhost'. */ - authority?: string; - /** an optional object containing request headers. */ - headers?: Headers; - /** an optional string specifying the client remote address. Defaults to '127.0.0.1'. */ - remoteAddress?: string; - /** an optional request payload. Can be a string, Buffer, Stream or object. */ - payload?: string | Buffer | Stream.Stream | {[key: string]: any}; - /** an object containing flags to simulate various conditions: */ - simulate?: { - /** indicates whether the request will fire an end event. Defaults to undefined, meaning an end event will fire. */ - end?: boolean; - /** indicates whether the request payload will be split into chunks. Defaults to `undefined`, meaning payload will not be chunked. */ - split?: boolean; - /** whether the request will emit an error event. Defaults to undefined, meaning no error event will be emitted. If set to true, the emitted error will have a message of 'Simulated'. */ - error?: boolean; - /** whether the request will emit a close event. Defaults to undefined, meaning no close event will be emitted. */ - close?: boolean; - } - /** Optional flag to validate this options object. Defaults to true. */ - validate?: boolean; -} - -interface Headers { - [header: string]: string; -} - -/** - * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} - */ -export interface ResponseObject { - /** an object containing the raw request and response objects where: */ - raw: { - /** the simulated request object. */ - req: SimulatedRequestObject; - /** the simulated response object. */ - res: SimulatedResponseObject; - }; - /** an object containing the response headers. */ - headers: Headers; - /** the HTTP status code. */ - statusCode: number; - /** the HTTP status message. */ - statusMessage: string; - /** the payload as a UTF-8 encoded string. */ - payload: string; - /** the raw payload as a Buffer. */ - rawPayload: Buffer; - /** an object containing the response trailers. */ - trailers: {[index: string]: any}; -} diff --git a/types/hapi/tests/response/error-representation.ts b/types/hapi/tests/response/error-representation.ts index 8b9b1099f9..f0fb62eb30 100644 --- a/types/hapi/tests/response/error-representation.ts +++ b/types/hapi/tests/response/error-representation.ts @@ -2,7 +2,7 @@ // From https://hapijs.com/api/16.1.1#error-transformation import * as Hapi from 'hapi'; -import Vision from '../../vision'; +import Vision from 'vision'; const server = new Hapi.Server(); server.register(Vision, {}, (err) => { server.views({ @@ -15,7 +15,7 @@ server.connection({ port: 80 }); const preResponse: Hapi.ServerExtRequestHandler = function (request, reply) { - const response = request.response; + const response = request.response!; if (!response.isBoom) { return reply.continue(); } diff --git a/types/hapi/tests/response/events.ts b/types/hapi/tests/response/events.ts index 6f927ce5f7..2d1658087b 100644 --- a/types/hapi/tests/response/events.ts +++ b/types/hapi/tests/response/events.ts @@ -8,7 +8,7 @@ server.connection({ port: 80 }); const preResponse: Hapi.ServerExtRequestHandler = function (request, reply) { - const response = request.response; + const response = request.response!; if (response.isBoom) { return reply(); } diff --git a/types/hapi/tsconfig.json b/types/hapi/tsconfig.json index d6604cb6b5..9996053227 100644 --- a/types/hapi/tsconfig.json +++ b/types/hapi/tsconfig.json @@ -11,7 +11,7 @@ "typeRoots": [ "../" ], - "types": [], + "types": ["node"], "noEmit": true, "forceConsistentCasingInFileNames": true }, @@ -87,17 +87,6 @@ "tests/server/state.ts", "tests/server/stop.ts", "tests/server/table.ts", - "tests/server/version.ts", - "catbox/index.d.ts", - "h2o2/index.d.ts", - "h2o2/h2o2-tests.ts", - "json/index.d.ts", - "json/json-tests.ts", - "mime-db/index.d.ts", - "mimos/index.d.ts", - "podium/index.d.ts", - "shot/index.d.ts", - "vision/index.d.ts", - "vision/vision-tests.ts" + "tests/server/version.ts" ] } \ No newline at end of file diff --git a/types/inert/index.d.ts b/types/inert/index.d.ts index 5e27881a3f..a54841eac7 100644 --- a/types/inert/index.d.ts +++ b/types/inert/index.d.ts @@ -5,8 +5,8 @@ import * as hapi from 'hapi'; -declare module 'hapi' { - interface FileHandlerOptions { +declare namespace inert { + export interface ReplyFileHandlerOptions { /** confine - serve file relative to this directory and returns 403 Forbidden if the path resolves outside the confine directory. Defaults to true which uses the relativeTo route option as the confine. Set to false to disable this security feature. */ confine?: boolean; /** filename - an optional filename to specify if sending a 'Content-Disposition' header, defaults to the basename of path */ @@ -35,18 +35,18 @@ declare module 'hapi' { end?: number; } - interface FileHandlerObject extends FileHandlerOptions { + export interface FileHandlerRouteObject extends ReplyFileHandlerOptions { /** path - a path string or function as described above (required). */ - path: string | RequestHandler; + path: string | hapi.RequestHandler; } - interface DirectoryHandlerObject { + export interface DirectoryHandlerRouteObject { /** path - (required) the directory root path (relative paths are resolved based on the route files configuration). Value can be: * * a single path string used as the prefix for any resources requested by appending the request path parameter to the provided string. * * an array of path strings. Each path will be attempted in order until a match is found (by following the same process as the single path string). * * a function with the signature function(request) which returns the path string or an array of path strings. If the function returns an error, the error is passed back to the client in the response. */ - path: string | string[] | RequestHandler; + path: string | string[] | hapi.RequestHandler; /** index - optional boolean|string|string[], determines if an index file will be served if found in the folder when requesting a directory. The given string or strings specify the name(s) of the index file to look for. If true, looks for 'index.html'. Any falsy value disables index file lookup. Defaults to true. */ index?: boolean | string | string[]; /** listing - optional boolean, determines if directory listing is generated when a directory is requested without an index document. Defaults to false. */ @@ -68,6 +68,19 @@ declare module 'hapi' { defaultExtension?: string; } + /** + * inert accepts the following registration options + * @see {@link https://github.com/hapijs/inert#registration-options} + */ + interface OptionalRegistrationOptions { + /** + * sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000. + */ + etagsCacheMaxSize?: number; + } +} + +declare module 'hapi' { interface RouteHandlerPlugins { /** * The file handler @@ -78,14 +91,14 @@ declare module 'hapi' { * * an object with one or more of the following options @see IFileHandler * @see {@link https://github.com/hapijs/inert#the-file-handler} */ - file?: string | RequestHandler | FileHandlerObject; + file?: string | RequestHandler | inert.FileHandlerRouteObject; /** * The directory handler * * Generates a directory endpoint for serving static content from a directory. Routes using the directory handler must include a path parameter at the end of the path string (e.g. /path/to/somewhere/{param} where the parameter name does not matter). The path parameter can use any of the parameter options (e.g. {param} for one level files only, {param?} for one level files or the directory root, {param*} for any level, or {param*3} for a specific level). If additional path parameters are present, they are ignored for the purpose of selecting the file system resource. The directory handler is an object with the following options: * @see {@link https://github.com/hapijs/inert#the-directory-handler} */ - directory?: DirectoryHandlerObject; + directory?: inert.DirectoryHandlerRouteObject; } interface Base_Reply { @@ -93,22 +106,10 @@ declare module 'hapi' { * Transmits a file from the file system. The 'Content-Type' header defaults to the matching mime type based on filename extension. * @see {@link https://github.com/hapijs/inert#replyfilepath-options} */ - file: (path: string, options?: FileHandlerOptions) => Response; + file: (path: string, options?: inert.ReplyFileHandlerOptions) => Response; } - } -/** - * inert accepts the following registration options - * @see {@link https://github.com/hapijs/inert#registration-options} - */ -interface OptionalRegistrationOptions { - /** - * sets the maximum number of file etag hash values stored in the etags cache. Defaults to 10000. - */ - etagsCacheMaxSize?: number; -} +declare var inert: hapi.PluginFunction; -declare var inertPlugin: hapi.PluginFunction; - -export default inertPlugin; +export = inert; diff --git a/types/inert/inert-tests.ts b/types/inert/inert-tests.ts index 177808817c..9062e13f6b 100644 --- a/types/inert/inert-tests.ts +++ b/types/inert/inert-tests.ts @@ -1,54 +1,67 @@ -import * as HapiES6 from 'hapi'; -import InertES6 from 'inert'; +// Copied from: https://github.com/hapijs/inert#examples -const server = new HapiES6.Server({}); -server.register(InertES6, {}, (err) => {}); +import Path = require('path'); +import Hapi = require('hapi'); +import Inert = require('inert'); + +const server = new Hapi.Server({ + connections: { + routes: { + files: { + relativeTo: Path.join(__dirname, 'public') + } + } + } +}); +server.connection({ port: 3000 }); + +server.register(Inert, () => {}); // added in addition to code from docs +const options: Inert.OptionalRegistrationOptions = {etagsCacheMaxSize: 400}; server.register({ - register: InertES6, - options: {etagsCacheMaxSize: 400}, + register: Inert, + options, }, (err) => {}); // added in addition to code from docs server.register({ - register: InertES6, + register: Inert, once: true, }, (err) => {}); server.route({ - path: '', method: 'GET', + path: '/{param*}', handler: { - file: { - path: '', - confine: true, - }, directory: { - path: '', - listing: true - }, - }, - config: { files: { relativeTo: __dirname } } -}) - -var fileHandler: HapiES6.FileHandlerObject = { - path: '', - confine: true, -} - -var directoryHandler: HapiES6.DirectoryHandlerObject = { - path: function(){ - if(Math.random() > 0.5) { - return ''; + path: '.', + redirectToSlash: true, + index: true } - else if(Math.random() > 0) { - return ['']; - } - return new Error(''); - }, - listing: true, -} + } +}); + +server.start((err) => { + + if (err) { + throw err; + } + + console.log('Server running at:', server.info!.uri); +}); + +// https://github.com/hapijs/inert#serving-a-single-file + +server.route({ + method: 'GET', + path: '/{path*}', + handler: { + file: 'page.html' + } +}); + +// https://github.com/hapijs/inert#customized-file-response server.route({ method: 'GET', @@ -64,9 +77,9 @@ server.route({ } }); -server.ext('onPostHandler', function (request: HapiES6.Request, reply: HapiES6.ReplyWithContinue) { +const handler: Hapi.ServerExtRequestHandler = function (request, reply) { - const response = request.response; + const response = request.response!; if (response.isBoom && response.output!.statusCode === 404) { @@ -74,4 +87,44 @@ server.ext('onPostHandler', function (request: HapiES6.Request, reply: HapiES6.R } return reply.continue(); -}); +} + +server.ext('onPostHandler', handler); + +// additional code added in addition to doc example code + +var file: Inert.FileHandlerRouteObject = { + path: '', + confine: true, +}; +var directory: Inert.DirectoryHandlerRouteObject = { + path: '', + listing: true +}; + +file = { + path: '', + confine: true, +}; + +server.route({ + path: '', + method: 'GET', + handler: { + file, + directory: { + path: function(){ + if(Math.random() > 0.5) { + return ''; + } + else if(Math.random() > 0) { + return ['']; + } + return new Error(''); + }, + BAD_listing: true, // TODO change typings to make this error + }, + }, + config: { files: { relativeTo: __dirname } } +}) + diff --git a/types/inert/tsconfig.json b/types/inert/tsconfig.json index 5b805cfc2d..7c74dcc2e7 100644 --- a/types/inert/tsconfig.json +++ b/types/inert/tsconfig.json @@ -11,7 +11,7 @@ "typeRoots": [ "../" ], - "types": [], + "types": ["node"], "noEmit": true, "forceConsistentCasingInFileNames": true }, diff --git a/types/hapi/mime-db/index.d.ts b/types/mime-db/index.d.ts similarity index 93% rename from types/hapi/mime-db/index.d.ts rename to types/mime-db/index.d.ts index 536a4c9e27..cf46a0c593 100644 --- a/types/hapi/mime-db/index.d.ts +++ b/types/mime-db/index.d.ts @@ -1,5 +1,3 @@ -// TODO needs tests -// TODO move to own definition // Type definitions for mime-db 1.27 // Project: https://github.com/jshttp/mime-db // Definitions by: AJP diff --git a/types/mime-db/tsconfig.json b/types/mime-db/tsconfig.json new file mode 100644 index 0000000000..3bc13b0278 --- /dev/null +++ b/types/mime-db/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/types/hapi/mimos/index.d.ts b/types/mimos/index.d.ts similarity index 91% rename from types/hapi/mimos/index.d.ts rename to types/mimos/index.d.ts index 386c3db589..9d000b0ce9 100644 --- a/types/hapi/mimos/index.d.ts +++ b/types/mimos/index.d.ts @@ -1,12 +1,10 @@ -// TODO needs tests -// TODO move to own definition // Type definitions for mimos 3.0 // Project: https://github.com/hapijs/mimos // Definitions by: AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 -import {DataStructure as MimeDbDataStructure} from '../mime-db'; +import {DataStructure as MimeDbDataStructure} from 'mime-db'; /** * diff --git a/types/mimos/tsconfig.json b/types/mimos/tsconfig.json new file mode 100644 index 0000000000..3bc13b0278 --- /dev/null +++ b/types/mimos/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts" + ] +} \ No newline at end of file diff --git a/types/hapi/podium/index.d.ts b/types/podium/index.d.ts similarity index 97% rename from types/hapi/podium/index.d.ts rename to types/podium/index.d.ts index 30df7b2ed9..0d62740479 100644 --- a/types/hapi/podium/index.d.ts +++ b/types/podium/index.d.ts @@ -1,17 +1,17 @@ -// TODO needs tests -// TODO move to own definition // Type definitions for podium 1.0 // Project: https://github.com/hapijs/podium // Definitions by: AJP // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 + /** * Podium * Node (semi) compatible event emitter with extra features. * podium is an event emitter with support for tags, filters, channels, event update cloning, arguments spreading, and other features useful when building large scale applications. While node's native EventEmitter is strictly focused on maximum performance, it lacks many features that do not belong in the core implementation. podium is not restricted by node's performance requirement as it is designed for application layer needs where it's overhead is largely insignificant as implementing these features will have similar cost on top of the native emitter. * @see {@link https://github.com/hapijs/podium} */ +// declare class Podium { export class Podium { /** * Creates a new podium emitter @@ -160,7 +160,7 @@ export interface CriteriaObject { /** * @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener} */ -interface CriteriaFilterOptionsObject { +export interface CriteriaFilterOptionsObject { /** a tag string or array of tag strings. */ tags?: string | string[]; /** if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag). */ @@ -176,7 +176,13 @@ export type Criteria = string | CriteriaObject; * @see {@link https://github.com/hapijs/podium/blob/master/API.md#podiumoncriteria-listener} */ export interface Listener { - (data: any, tags?: Tags, callback?: () => void): void; +(data: any, tags?: Tags, callback?: () => void): void; } export type Tags = {[tag: string]: boolean}; + +// export = Podium; + +// declare namespace Podium { +// type Tags = {[tag: string]: boolean}; +// } diff --git a/types/podium/podium-tests.ts b/types/podium/podium-tests.ts new file mode 100644 index 0000000000..f5cee6bbec --- /dev/null +++ b/types/podium/podium-tests.ts @@ -0,0 +1,33 @@ +/* +import Podium = require('podium'); +const podiumObject = new Podium(); // new emitter + +const podiumObject2 = new Podium('event1');// creates new event and calls registerEvent() + +podiumObject.registerEvent('event1'); + +//with optional parameters +podiumObject.registerEvent({ + name: 'event1', + shared: true +}); + +podiumObject.registerEvent('event1'); + +podiumObject.on('event1',function(update){ // Way 1 + console.log('inside autonomous listener without name! data:', update); +}); + +const listener1 = function() { // normal function object + console.log('listener1 called'); +} +podiumObject.on('event1',listener1); // Way 2 + +// podium.addListener(criteria, listener) Same as podium.on(). + +podiumObject.addListener('event1',listener1); + +// podium.once(criteria, listener) Same as calling podium.on() with the count option set to 1. Whenever we call emit(), listener1 will get fired but also get removed, so that it won't get fired on call to emit(). + +podiumObject.once('event1',listener1); +*/ diff --git a/types/podium/tsconfig.json b/types/podium/tsconfig.json new file mode 100644 index 0000000000..267d05537f --- /dev/null +++ b/types/podium/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "podium-tests.ts" + ] +} \ No newline at end of file diff --git a/types/shot/index.d.ts b/types/shot/index.d.ts new file mode 100644 index 0000000000..4fdaff2688 --- /dev/null +++ b/types/shot/index.d.ts @@ -0,0 +1,113 @@ +// Type definitions for shot 3.4 +// Project: https://github.com/hapijs/shot +// Definitions by: AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import stream = require("stream"); +import http = require("http"); + +interface ShotAPI { + /** + * Injects a fake request into an HTTP server. + * @param dispatchFunc listener function. The same as you would pass to Http.createServer when making a node HTTP server. @see IListener + * @param options request options object @see RequestOptions + * @param callback the callback function @see Callback + * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} + */ + inject(dispatchFunc: Shot.Listener, options: Shot.RequestOptions, callback: (res: Shot.ResponseObject) => void): void; + + /** + * Checks if given object obj is a Shot Request object. + * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotisinjectionobj} + */ + isInjection(obj: any): boolean; +} + +declare namespace Shot { + /** + * listener function. The same as you would pass to Http.createServer when making a node HTTP server. Has the signature function (req, res) where: + * * req - a simulated request object. Inherits from Stream.Readable. + * * res - a simulated response object. Inherits from node's Http.ServerResponse. + * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} + */ + export interface Listener { + (req: SimulatedRequestObject, res: SimulatedResponseObject): void; + } + + /** + * a simulated request object. Inherits from Stream.Readable. + * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} + */ + interface SimulatedRequestObject extends stream.Readable {} + + /** + * a simulated response object. Inherits from node's Http.ServerResponse. + * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} + */ + interface SimulatedResponseObject extends http.ServerResponse {} + + /** + * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} + */ + export interface RequestOptions { + /** a string specifying the request URL. */ + url: string; + /** a string specifying the HTTP request method, defaulting to 'GET'. */ + method?: string; + /** a string specifying the HTTP HOST header value to be used if no header is provided, and the url does not include an authority component. Defaults to 'localhost'. */ + authority?: string; + /** an optional object containing request headers. */ + headers?: Headers; + /** an optional string specifying the client remote address. Defaults to '127.0.0.1'. */ + remoteAddress?: string; + /** an optional request payload. Can be a string, Buffer, Stream or object. */ + payload?: string | Buffer | stream.Stream | {[key: string]: any}; + /** an object containing flags to simulate various conditions: */ + simulate?: { + /** indicates whether the request will fire an end event. Defaults to undefined, meaning an end event will fire. */ + end?: boolean; + /** indicates whether the request payload will be split into chunks. Defaults to `undefined`, meaning payload will not be chunked. */ + split?: boolean; + /** whether the request will emit an error event. Defaults to undefined, meaning no error event will be emitted. If set to true, the emitted error will have a message of 'Simulated'. */ + error?: boolean; + /** whether the request will emit a close event. Defaults to undefined, meaning no close event will be emitted. */ + close?: boolean; + } + /** Optional flag to validate this options object. Defaults to true. */ + validate?: boolean; + } + + interface Headers { + [header: string]: string; + } + + /** + * @see {@link https://github.com/hapijs/shot/blob/master/API.md#shotinjectdispatchfunc-options-callback} + */ + export interface ResponseObject { + /** an object containing the raw request and response objects where: */ + raw: { + /** the simulated request object. */ + req: SimulatedRequestObject; + /** the simulated response object. */ + res: SimulatedResponseObject; + }; + /** an object containing the response headers. */ + headers: Headers; + /** the HTTP status code. */ + statusCode: number; + /** the HTTP status message. */ + statusMessage: string; + /** the payload as a UTF-8 encoded string. */ + payload: string; + /** the raw payload as a Buffer. */ + rawPayload: Buffer; + /** an object containing the response trailers. */ + trailers: {[index: string]: any}; + } +} + +declare var Shot: ShotAPI; + +export = Shot; diff --git a/types/shot/shot-tests.ts b/types/shot/shot-tests.ts new file mode 100644 index 0000000000..1c6749915b --- /dev/null +++ b/types/shot/shot-tests.ts @@ -0,0 +1,29 @@ +// From: https://github.com/hapijs/shot#example + +// Load modules + +import Http = require('http'); +import Shot = require('shot'); + +// Declare internals + +const internals: any = {}; + +internals.main = function () { + + const dispatch = function (req: Http.IncomingMessage, res: Http.ServerResponse) { + + const reply = 'Hello World'; + res.writeHead(200, { 'Content-Type': 'text/plain', 'Content-Length': reply.length }); + res.end(reply); + }; + + const server = Http.createServer(dispatch); + + Shot.inject(dispatch, { method: 'get', url: '/' }, (res) => { + + console.log(res.payload); + }); +}; + +internals.main(); diff --git a/types/shot/tsconfig.json b/types/shot/tsconfig.json new file mode 100644 index 0000000000..12dbee6598 --- /dev/null +++ b/types/shot/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": ["node"], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shot-tests.ts" + ] +} \ No newline at end of file diff --git a/types/hapi/vision/index.d.ts b/types/vision/index.d.ts similarity index 98% rename from types/hapi/vision/index.d.ts rename to types/vision/index.d.ts index cee02fc56c..2b0164cc0f 100644 --- a/types/hapi/vision/index.d.ts +++ b/types/vision/index.d.ts @@ -1,3 +1,8 @@ +// Type definitions for vision 4.1 +// Project: https://github.com/hapijs/vision +// Definitions by: Jason Swearingen , AJP +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import * as Hapi from 'hapi'; diff --git a/types/vision/tsconfig.json b/types/vision/tsconfig.json new file mode 100644 index 0000000000..428d9c2764 --- /dev/null +++ b/types/vision/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": ["node"], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vision-tests.ts" + ] +} \ No newline at end of file diff --git a/types/hapi/vision/vision-tests.ts b/types/vision/vision-tests.ts similarity index 100% rename from types/hapi/vision/vision-tests.ts rename to types/vision/vision-tests.ts