UNPKG

234 kBTypeScriptView Raw
1// Type definitions for @hapi/hapi 20.0
2// Project: https://github.com/hapijs/hapi, https://hapijs.com
3// Definitions by: Rafael Souza Fijalkowski <https://github.com/rafaelsouzaf>
4// Justin Simms <https://github.com/jhsimms>
5// Simon Schick <https://github.com/SimonSchick>
6// Rodrigo Saboya <https://github.com/saboya>
7// Silas Rech <https://github.com/lenovouser>
8// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
9// TypeScript Version: 2.8
10
11/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
12 + +
13 + +
14 + +
15 + WARNING: BACKWARDS INCOMPATIBLE +
16 + +
17 + +
18 + +
19 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
20
21/// <reference types='node' />
22
23import { Boom } from '@hapi/boom';
24import * as http from 'http';
25import * as https from 'https';
26import * as Shot from '@hapi/shot';
27import * as stream from 'stream';
28import * as url from 'url';
29import * as zlib from 'zlib';
30
31import { MimosOptions } from '@hapi/mimos';
32import { SealOptions, SealOptionsSub } from '@hapi/iron';
33import { ValidationOptions, SchemaMap, ObjectSchema, Schema, Root } from 'joi';
34import Podium = require('@hapi/podium');
35import { PolicyOptionVariants, PolicyOptions, EnginePrototype, Policy, ClientApi, ClientOptions } from '@hapi/catbox';
36
37/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
38 + +
39 + +
40 + +
41 + Plugin +
42 + +
43 + +
44 + +
45 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
46
47/**
48 * one of
49 * a single plugin name string.
50 * an array of plugin name strings.
51 * an object where each key is a plugin name and each matching value is a
52 * {@link https://www.npmjs.com/package/semver version range string} which must match the registered
53 * plugin version.
54 */
55export type Dependencies = string | string[] | {
56 [key: string]: string;
57};
58
59/**
60 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
61 */
62// tslint:disable-next-line no-empty-interface
63export interface PluginsListRegistered {
64}
65
66/**
67 * An object of the currently registered plugins where each key is a registered plugin name and the value is an
68 * object containing:
69 * * version - the plugin version.
70 * * name - the plugin name.
71 * * options - (optional) options passed to the plugin during registration.
72 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
73 */
74export interface PluginRegistered {
75 /**
76 * the plugin version.
77 */
78 version: string;
79
80 /**
81 * the plugin name.
82 */
83 name: string;
84
85 /**
86 * options used to register the plugin.
87 */
88 options: object;
89}
90
91// tslint:disable-next-line no-empty-interface
92export interface PluginsStates {
93}
94
95// tslint:disable-next-line no-empty-interface
96export interface PluginSpecificConfiguration {
97}
98
99export interface PluginNameVersion {
100 /**
101 * (required) the plugin name string. The name is used as a unique key. Published plugins (e.g. published in the npm
102 * registry) should use the same name as the name field in their 'package.json' file. Names must be
103 * unique within each application.
104 */
105 name: string;
106
107 /**
108 * 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
109 * 'package.json' file.
110 */
111 version?: string | undefined;
112}
113
114export interface PluginPackage {
115 /**
116 * Alternatively, the name and version can be included via the pkg property containing the 'package.json' file for the module which already has the name and version included
117 */
118 pkg: any;
119}
120
121/**
122 * Plugins provide a way to organize application code by splitting the server logic into smaller components. Each
123 * plugin can manipulate the server through the standard server interface, but with the added ability to sandbox
124 * certain properties. For example, setting a file path in one plugin doesn't affect the file path set
125 * in another plugin.
126 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#plugins)
127 *
128 * The type T is the type of the plugin options.
129 */
130export interface PluginBase<T> {
131 /**
132 * (required) the registration function with the signature async function(server, options) where:
133 * * server - the server object with a plugin-specific server.realm.
134 * * options - any options passed to the plugin during registration via server.register().
135 */
136 register: (server: Server, options: T) => void | Promise<void>;
137
138 /** (optional) if true, allows the plugin to be registered multiple times with the same server. Defaults to false. */
139 multiple?: boolean | undefined;
140
141 /** (optional) a string or an array of strings indicating a plugin dependency. Same as setting dependencies via server.dependency(). */
142 dependencies?: Dependencies | undefined;
143
144 /**
145 * Allows defining semver requirements for node and hapi.
146 * @default Allows all.
147 */
148 requirements?: {
149 node?: string | undefined;
150 hapi?: string | undefined;
151 } | undefined;
152
153 /** 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. */
154 once?: boolean | undefined;
155}
156
157export type Plugin<T> = PluginBase<T> & (PluginNameVersion | PluginPackage);
158
159/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
160 + +
161 + +
162 + +
163 + Request +
164 + +
165 + +
166 + +
167 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
168
169/**
170 * User extensible types user credentials.
171 */
172// tslint:disable-next-line:no-empty-interface
173export interface UserCredentials {
174}
175
176/**
177 * User extensible types app credentials.
178 */
179// tslint:disable-next-line:no-empty-interface
180export interface AppCredentials {
181}
182
183/**
184 * User-extensible type for request.auth credentials.
185 */
186export interface AuthCredentials<
187 AuthUser extends object = UserCredentials,
188 AuthApp extends object = AppCredentials,
189> {
190 /**
191 * The application scopes to be granted.
192 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope)
193 */
194 scope?: string[] | undefined;
195 /**
196 * If set, will only work with routes that set `access.entity` to `user`.
197 */
198 user?: MergeType<UserCredentials, AuthUser> | undefined;
199
200 /**
201 * If set, will only work with routes that set `access.entity` to `app`.
202 */
203 app?: MergeType<AppCredentials, AuthApp> | undefined;
204}
205
206export interface AuthArtifacts {
207 [key: string]: unknown;
208}
209
210export type AuthMode = 'required' | 'optional' | 'try';
211
212/**
213 * Authentication information:
214 * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions.
215 * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication.
216 * * error - the authentication error is failed and mode set to 'try'.
217 * * isAuthenticated - true if the request has been successfully authenticated, otherwise false.
218 * * 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
219 * authorization, set to false.
220 * * mode - the route authentication mode.
221 * * strategy - the name of the strategy used.
222 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth)
223 */
224export interface RequestAuth<
225 AuthUser extends object = UserCredentials,
226 AuthApp extends object = AppCredentials,
227 CredentialsExtra extends object = Record<string, unknown>,
228 ArtifactsExtra = Record<string, unknown>
229> {
230 /** an artifact object received from the authentication strategy and used in authentication-related actions. */
231 artifacts: ArtifactsExtra;
232 /** the credential object received during the authentication process. The presence of an object does not mean successful authentication. */
233 credentials: MergeType<CredentialsExtra, AuthCredentials<AuthUser, AuthApp>>;
234 /** the authentication error is failed and mode set to 'try'. */
235 error: Error;
236 /** true if the request has been successfully authenticated, otherwise false. */
237 isAuthenticated: boolean;
238 /**
239 * 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,
240 * set to false.
241 */
242 isAuthorized: boolean;
243 /** the route authentication mode. */
244 mode: AuthMode;
245 /** the name of the strategy used. */
246 strategy: string;
247}
248
249/**
250 * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
251 * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
252 * 'disconnect' - emitted when a request errors or aborts unexpectedly.
253 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
254 */
255export type RequestEventType = 'peek' | 'finish' | 'disconnect';
256
257/**
258 * Access: read only and the public podium interface.
259 * The request.events supports the following events:
260 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
261 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
262 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
263 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
264 */
265export interface RequestEvents extends Podium {
266 /**
267 * Access: read only and the public podium interface.
268 * The request.events supports the following events:
269 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
270 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
271 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
272 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
273 */
274 on(criteria: 'peek', listener: PeekListener): this;
275
276 on(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): this;
277
278 /**
279 * Access: read only and the public podium interface.
280 * The request.events supports the following events:
281 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
282 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
283 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
284 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
285 */
286 once(criteria: 'peek', listener: PeekListener): this;
287 once(criteria: 'peek'): Promise<Parameters<PeekListener>>;
288
289 once(criteria: 'finish' | 'disconnect', listener: (data: undefined) => void): this;
290}
291
292/**
293 * Request information:
294 * * acceptEncoding - the request preferred encoding.
295 * * cors - if CORS is enabled for the route, contains the following:
296 * * 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
297 * 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.
298 * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080').
299 * * hostname - the hostname part of the 'Host' header (e.g. 'example.com').
300 * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').
301 * * received - request reception timestamp.
302 * * referrer - content of the HTTP 'Referrer' (or 'Referer') header.
303 * * remoteAddress - remote client IP address.
304 * * remotePort - remote client port.
305 * * responded - request response timestamp (0 is not responded yet).
306 * Note that the request.info object is not meant to be modified.
307 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo)
308 */
309export interface RequestInfo {
310 /** the request preferred encoding. */
311 acceptEncoding: string;
312 /** if CORS is enabled for the route, contains the following: */
313 cors: {
314 /**
315 * 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
316 * the 'onRequest' extension point as CORS is configured per-route and no routing decisions are made at that point in the request lifecycle.
317 */
318 isOriginMatch?: boolean | undefined;
319 };
320 /** content of the HTTP 'Host' header (e.g. 'example.com:8080'). */
321 host: string;
322 /** the hostname part of the 'Host' header (e.g. 'example.com'). */
323 hostname: string;
324 /** a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}') */
325 id: string;
326 /** request reception timestamp. */
327 received: number;
328 /** content of the HTTP 'Referrer' (or 'Referer') header. */
329 referrer: string;
330 /** remote client IP address. */
331 remoteAddress: string;
332 /** remote client port. */
333 remotePort: string;
334 /** request response timestamp (0 is not responded yet). */
335 responded: number;
336 /** request processing completion timestamp (0 is still processing). */
337 completed: number;
338}
339
340/**
341 * The request route information object, where:
342 * * method - the route HTTP method.
343 * * path - the route path.
344 * * vhost - the route vhost option if configured.
345 * * realm - the active realm associated with the route.
346 * * settings - the route options object with all defaults applied.
347 * * fingerprint - the route internal normalized string representing the normalized path.
348 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute)
349 */
350export interface RequestRoute {
351 /** the route HTTP method. */
352 method: Util.HTTP_METHODS_PARTIAL;
353
354 /** the route path. */
355 path: string;
356
357 /** the route vhost option if configured. */
358 vhost?: string | string[] | undefined;
359
360 /** the active realm associated with the route. */
361 realm: ServerRealm;
362
363 /** the route options object with all defaults applied. */
364 settings: RouteSettings;
365
366 /** the route internal normalized string representing the normalized path. */
367 fingerprint: string;
368
369 auth: {
370 /**
371 * Validates a request against the route's authentication access configuration, where:
372 * @param request - the request object.
373 * @return Return value: true if the request would have passed the route's access requirements.
374 * 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
375 * 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
376 * 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
377 * requires any authentication.
378 * [See docs](https://hapijs.com/api/17.0.1#-requestrouteauthaccessrequest)
379 */
380 access(request: Request): boolean;
381 };
382}
383
384/**
385 * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.
386 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestorig)
387 */
388export interface RequestOrig {
389 params: object;
390 query: object;
391 payload: object;
392}
393
394export interface RequestLog {
395 request: string;
396 timestamp: number;
397 tags: string[];
398 data: string | object;
399 channel: string;
400}
401export interface RequestQuery {
402 [key: string]: any;
403}
404export interface InternalRequestDefaults {
405 Payload: stream.Readable | Buffer | string | object;
406 Query: RequestQuery;
407 Params: Util.Dictionary<any>;
408 Pres: Util.Dictionary<any>;
409 Headers: Util.Dictionary<any>;
410 RequestApp: RequestApplicationState;
411
412 AuthUser: UserCredentials;
413 AuthApp: AppCredentials;
414 AuthApi: ServerAuthSchemeObjectApi;
415 AuthCredentialsExtra: Record<string, unknown>;
416 AuthArtifactsExtra: Record<string, unknown>;
417
418 Rules: RouteRules;
419 Bind: object | null;
420}
421
422/**
423 * Default request references. Used to give typing to requests,
424 * route handlers, lifecycle methods, auth credentials, etc.
425 * This can be overwritten to whatever is suitable and universal
426 * in your specific app, but whatever references you pass to
427 * server route generic, or lifecycle methods will take precedence
428 * over these.
429 */
430// tslint:disable-next-line no-empty-interface
431export interface ReqRefDefaults extends InternalRequestDefaults {}
432
433/**
434 * Route request overrides
435 */
436export type ReqRef = Partial<Record<keyof ReqRefDefaults, unknown>>;
437
438/**
439 * Utilities for merging request refs and other things
440 */
441export type MergeType<T extends object, U extends object> = Omit<T, keyof U> & U;
442export type MergeRefs<T extends ReqRef> = MergeType<ReqRefDefaults, T>;
443
444/**
445 * The request object is created internally for each incoming request. It is not the same object received from the node
446 * 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
447 * the request [lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle).
448 */
449export interface Request<Refs extends ReqRef = ReqRefDefaults> extends Podium {
450 /**
451 * 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].
452 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestapp)
453 */
454 app: MergeRefs<Refs>['RequestApp'];
455
456 /**
457 * Authentication information:
458 * * artifacts - an artifact object received from the authentication strategy and used in authentication-related actions.
459 * * credentials - the credential object received during the authentication process. The presence of an object does not mean successful authentication.
460 * * error - the authentication error is failed and mode set to 'try'.
461 * * isAuthenticated - true if the request has been successfully authenticated, otherwise false.
462 * * 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
463 * authorization, set to false.
464 * * mode - the route authentication mode.
465 * * strategy - the name of the strategy used.
466 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestauth)
467 */
468 readonly auth: RequestAuth<
469 MergeRefs<Refs>['AuthUser'],
470 MergeRefs<Refs>['AuthApp'],
471 MergeRefs<Refs>['AuthCredentialsExtra'],
472 MergeRefs<Refs>['AuthArtifactsExtra']
473 >;
474
475 /**
476 * Access: read only and the public podium interface.
477 * The request.events supports the following events:
478 * * 'peek' - emitted for each chunk of payload data read from the client connection. The event method signature is function(chunk, encoding).
479 * * 'finish' - emitted when the request payload finished reading. The event method signature is function ().
480 * * 'disconnect' - emitted when a request errors or aborts unexpectedly.
481 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestevents)
482 */
483 events: RequestEvents;
484
485 /**
486 * The raw request headers (references request.raw.req.headers).
487 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestheaders)
488 */
489 readonly headers: MergeRefs<Refs>['Headers'];
490
491 /**
492 * Request information:
493 * * acceptEncoding - the request preferred encoding.
494 * * cors - if CORS is enabled for the route, contains the following:
495 * * 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
496 * 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.
497 * * host - content of the HTTP 'Host' header (e.g. 'example.com:8080').
498 * * hostname - the hostname part of the 'Host' header (e.g. 'example.com').
499 * * id - a unique request identifier (using the format '{now}:{connection.info.id}:{5 digits counter}').
500 * * received - request reception timestamp.
501 * * referrer - content of the HTTP 'Referrer' (or 'Referer') header.
502 * * remoteAddress - remote client IP address.
503 * * remotePort - remote client port.
504 * * responded - request response timestamp (0 is not responded yet).
505 * Note that the request.info object is not meant to be modified.
506 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestinfo)
507 */
508 readonly info: RequestInfo;
509
510 /**
511 * An array containing the logged request events.
512 * Note that this array will be empty if route log.collect is set to false.
513 */
514 readonly logs: RequestLog[];
515
516 /**
517 * The request method in lower case (e.g. 'get', 'post').
518 */
519 readonly method: Util.HTTP_METHODS_PARTIAL_LOWERCASE;
520
521 /**
522 * The parsed content-type header. Only available when payload parsing enabled and no payload error occurred.
523 */
524 readonly mime: string;
525
526 /**
527 * An object containing the values of params, query, and payload before any validation modifications made. Only set when input validation is performed.
528 */
529 readonly orig: RequestOrig;
530
531 /**
532 * 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).
533 */
534 readonly params: MergeRefs<Refs>['Params'];
535
536 /**
537 * An array containing all the path params values in the order they appeared in the path.
538 */
539 readonly paramsArray: keyof MergeRefs<Refs>['Params'] | string[];
540
541 /**
542 * The request URI's pathname component.
543 */
544 readonly path: string;
545
546 /**
547 * The request payload based on the route payload.output and payload.parse settings.
548 * TODO check this typing and add references / links.
549 */
550 readonly payload: MergeRefs<Refs>['Payload'];
551
552 /**
553 * 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.
554 */
555 plugins: PluginsStates;
556
557 /**
558 * 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
559 * object, use responses.
560 */
561 readonly pre: MergeRefs<Refs>['Pres'];
562
563 /**
564 * Access: read / write (see limitations below).
565 * 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
566 * override with a different response.
567 * In case of an aborted request the status code will be set to `disconnectStatusCode`.
568 */
569 response: ResponseObject | Boom;
570
571 /**
572 * Same as pre but represented as the response object created by the pre method.
573 */
574 readonly preResponses: Util.Dictionary<any>;
575
576 /**
577 * By default the object outputted from node's URL parse() method.
578 */
579 readonly query: MergeRefs<Refs>['Query'];
580
581 /**
582 * An object containing the Node HTTP server objects. Direct interaction with these raw objects is not recommended.
583 * * req - the node request object.
584 * * res - the node response object.
585 */
586 readonly raw: {
587 req: http.IncomingMessage;
588 res: http.ServerResponse;
589 };
590
591 /**
592 * The request route information object and method
593 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestroute)
594 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestrouteauthaccessrequest)
595 */
596 readonly route: RequestRoute;
597
598 /**
599 * Access: read only and the public server interface.
600 * The server object.
601 */
602 server: Server;
603
604 /**
605 * 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.
606 */
607 readonly state: Util.Dictionary<any>;
608
609 /**
610 * The parsed request URI.
611 */
612 readonly url: url.URL;
613
614 /**
615 * Returns `true` when the request is active and processing should continue and `false` when the
616 * request terminated early or completed its lifecycle. Useful when request processing is a
617 * resource-intensive operation and should be terminated early if the request is no longer active
618 * (e.g. client disconnected or aborted early).
619 */
620 active(): boolean;
621
622 /**
623 * Returns a response which you can pass into the reply interface where:
624 * @param source - the value to set as the source of the reply interface, optional.
625 * @param options - options for the method, optional.
626 * @return ResponseObject
627 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestgenerateresponsesource-options)
628 */
629 /* tslint:disable-next-line:max-line-length */
630 generateResponse(source: string | object | null, options?: { variety?: string | undefined; prepare?: ((response: ResponseObject) => Promise<ResponseObject>) | undefined; marshal?: ((response: ResponseObject) => Promise<ResponseValue>) | undefined; close?: ((response: ResponseObject) => void | undefined); }): ResponseObject;
631
632 /**
633 * Logs request-specific events. When called, the server emits a 'request' event which can be used by other listeners or plugins. The arguments are:
634 * @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
635 * for describing and filtering events.
636 * @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
637 * 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
638 * set to true.
639 * @return void
640 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-requestlogtags-data)
641 */
642 log(tags: string | string[], data?: string | object | (() => string | object)): void;
643
644 /**
645 * Changes the request method before the router begins processing the request where:
646 * @param method - is the request HTTP method (e.g. 'GET').
647 * @return void
648 * Can only be called from an 'onRequest' extension method.
649 * [See docs](https://hapijs.com/api/17.0.1#-requestsetmethodmethod)
650 */
651 setMethod(method: Util.HTTP_METHODS_PARTIAL): void;
652
653 /**
654 * Changes the request URI before the router begins processing the request where:
655 * Can only be called from an 'onRequest' extension method.
656 * @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
657 * parse() method output.
658 * @param stripTrailingSlash - if true, strip the trailing slash from the path. Defaults to false.
659 * @return void
660 * [See docs](https://hapijs.com/api/17.0.1#-requestseturlurl-striptrailingslash)
661 */
662 setUrl(url: string | url.URL, stripTrailingSlash?: boolean): void;
663}
664
665/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
666 + +
667 + +
668 + +
669 + Response +
670 + +
671 + +
672 + +
673 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
674
675/**
676 * Access: read only and the public podium interface.
677 * The response.events object supports the following events:
678 * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
679 * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
680 * [See docs](https://hapijs.com/api/17.0.1#-responseevents)
681 */
682export interface ResponseEvents extends Podium {
683 /**
684 * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
685 * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
686 */
687 on(criteria: 'peek', listener: PeekListener): this;
688
689 on(criteria: 'finish', listener: (data: undefined) => void): this;
690
691 /**
692 * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
693 * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
694 */
695 once(criteria: 'peek', listener: PeekListener): this;
696 once(criteria: 'peek'): Promise<Parameters<PeekListener>>;
697
698 once(criteria: 'finish', listener: (data: undefined) => void): this;
699}
700
701/**
702 * Object where:
703 * * append - if true, the value is appended to any existing header value using separator. Defaults to false.
704 * * separator - string used as separator when appending to an existing value. Defaults to ','.
705 * * override - if false, the header value is not set if an existing value present. Defaults to true.
706 * * 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.
707 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options)
708 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object)
709 */
710export interface ResponseObjectHeaderOptions {
711 append?: boolean | undefined;
712 separator?: string | undefined;
713 override?: boolean | undefined;
714 duplicate?: boolean | undefined;
715}
716
717/**
718 * The response object contains the request response value along with various HTTP headers and flags. When a lifecycle
719 * method returns a value, the value is wrapped in a response object along with some default flags (e.g. 200 status
720 * code). In order to customize a response before it is returned, the h.response() method is provided.
721 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-object)
722 * 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)
723 */
724export interface ResponseObject extends Podium {
725 /**
726 * @default {}.
727 * 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].
728 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseapp)
729 */
730 app: ResponseApplicationState;
731
732 /**
733 * Access: read only and the public podium interface.
734 * The response.events object supports the following events:
735 * * 'peek' - emitted for each chunk of data written back to the client connection. The event method signature is function(chunk, encoding).
736 * * 'finish' - emitted when the response finished writing but before the client response connection is ended. The event method signature is function ().
737 * [See docs](https://hapijs.com/api/17.0.1#-responseevents)
738 */
739 readonly events: ResponseEvents;
740
741 /**
742 * @default {}.
743 * 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.
744 * 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.
745 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheaders)
746 */
747 readonly headers: Util.Dictionary<string | string[]>;
748
749 /**
750 * @default {}.
751 * 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.
752 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseplugins)
753 */
754 plugins: PluginsStates;
755
756 /**
757 * Object containing the response handling flags.
758 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings)
759 */
760 readonly settings: ResponseSettings;
761
762 /**
763 * The raw value returned by the lifecycle method.
764 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesource)
765 */
766 readonly source: Lifecycle.ReturnValue;
767
768 /**
769 * @default 200.
770 * The HTTP response status code.
771 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatuscode)
772 */
773 readonly statusCode: number;
774
775 /**
776 * A string indicating the type of source with available values:
777 * * 'plain' - a plain response such as string, number, null, or simple object.
778 * * 'buffer' - a Buffer.
779 * * 'stream' - a Stream.
780 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevariety)
781 */
782 readonly variety: 'plain' | 'buffer' | 'stream';
783
784 /**
785 * Sets the HTTP 'Content-Length' header (to avoid chunked transfer encoding) where:
786 * @param length - the header value. Must match the actual payload size.
787 * @return Return value: the current response object.
788 * [See docs](https://hapijs.com/api/17.0.1#-responsebyteslength)
789 */
790 bytes(length: number): ResponseObject;
791
792 /**
793 * Controls the 'Content-Type' HTTP header 'charset' property of the response.
794 * * When invoked without any parameter, will prevent hapi from applying its default charset normalization to 'utf-8'
795 * * When 'charset' parameter is provided, will set the 'Content-Type' HTTP header 'charset' property where:
796 * @param charset - the charset property value.
797 * @return Return value: the current response object.
798 * [See docs](https://hapijs.com/api/17.0.1#-responsecharsetcharset)
799 */
800 charset(charset?: string): ResponseObject;
801
802 /**
803 * Sets the HTTP status code where:
804 * @param statusCode - the HTTP status code (e.g. 200).
805 * @return Return value: the current response object.
806 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecodestatuscode)
807 */
808 code(statusCode: number): ResponseObject;
809
810 /**
811 * Sets the HTTP status message where:
812 * @param httpMessage - the HTTP status message (e.g. 'Ok' for status code 200).
813 * @return Return value: the current response object.
814 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsemessagehttpmessage)
815 */
816 message(httpMessage: string): ResponseObject;
817
818 /**
819 * Sets the HTTP status code to Created (201) and the HTTP 'Location' header where:
820 * @param uri - an absolute or relative URI used as the 'Location' header value.
821 * @return Return value: the current response object.
822 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsecreateduri)
823 */
824 created(uri: string): ResponseObject;
825
826 /**
827 * Sets the string encoding scheme used to serial data into the HTTP payload where:
828 * @param encoding the encoding property value (see node Buffer encoding [See docs](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings)).
829 * * 'ascii' - for 7-bit ASCII data only. This encoding is fast and will strip the high bit if set.
830 * * 'utf8' - Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8.
831 * * 'utf16le' - 2 or 4 bytes, little-endian encoded Unicode characters. Surrogate pairs (U+10000 to U+10FFFF) are supported.
832 * * 'ucs2' - Alias of 'utf16le'.
833 * * '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.
834 * * '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).
835 * * 'binary' - Alias for 'latin1'.
836 * * 'hex' - Encode each byte as two hexadecimal characters.
837 * @return Return value: the current response object.
838 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseencodingencoding)
839 */
840 encoding(encoding: 'ascii' | 'utf8' | 'utf16le' | 'ucs2' | 'base64' | 'latin1' | 'binary' | 'hex'): ResponseObject;
841
842 /**
843 * Sets the representation entity tag where:
844 * @param tag - the entity tag string without the double-quote.
845 * @param options - (optional) settings where:
846 * * 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.
847 * * 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
848 * a '-' character). Ignored when weak is true. Defaults to true.
849 * @return Return value: the current response object.
850 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseetagtag-options)
851 */
852 etag(tag: string, options?: {weak: boolean, vary: boolean}): ResponseObject;
853
854 /**
855 * Sets an HTTP header where:
856 * @param name - the header name.
857 * @param value - the header value.
858 * @param options - (optional) object where:
859 * * append - if true, the value is appended to any existing header value using separator. Defaults to false.
860 * * separator - string used as separator when appending to an existing value. Defaults to ','.
861 * * override - if false, the header value is not set if an existing value present. Defaults to true.
862 * * 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.
863 * @return Return value: the current response object.
864 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseheadername-value-options)
865 */
866 header(name: string, value: string, options?: ResponseObjectHeaderOptions): ResponseObject;
867
868 /**
869 * Sets the HTTP 'Location' header where:
870 * @param uri - an absolute or relative URI used as the 'Location' header value.
871 * @return Return value: the current response object.
872 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responselocationuri)
873 */
874 location(uri: string): ResponseObject;
875
876 /**
877 * Sets an HTTP redirection response (302) and decorates the response with additional methods, where:
878 * @param uri - an absolute or relative URI used to redirect the client to another resource.
879 * @return Return value: the current response object.
880 * Decorates the response object with the response.temporary(), response.permanent(), and response.rewritable() methods to easily change the default redirection code (302).
881 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseredirecturi)
882 */
883 redirect(uri: string): ResponseObject;
884
885 /**
886 * Sets the JSON.stringify() replacer argument where:
887 * @param method - the replacer function or array. Defaults to none.
888 * @return Return value: the current response object.
889 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsereplacermethod)
890 */
891 replacer(method: Json.StringifyReplacer): ResponseObject;
892
893 /**
894 * Sets the JSON.stringify() space argument where:
895 * @param count - the number of spaces to indent nested object keys. Defaults to no indentation.
896 * @return Return value: the current response object.
897 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsespacescount)
898 */
899 spaces(count: number): ResponseObject;
900
901 /**
902 * Sets an HTTP cookie where:
903 * @param name - the cookie name.
904 * @param value - the cookie value. If no options.encoding is defined, must be a string. See server.state() for supported encoding values.
905 * @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
906 * definition.
907 * @return Return value: the current response object.
908 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsestatename-value-options)
909 */
910 state(name: string, value: object | string, options?: ServerStateCookieOptions): ResponseObject;
911
912 /**
913 * Sets a string suffix when the response is process via JSON.stringify() where:
914 * @param suffix - the string suffix.
915 * @return Return value: the current response object.
916 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesuffixsuffix)
917 */
918 suffix(suffix: string): ResponseObject;
919
920 /**
921 * Overrides the default route cache expiration rule for this response instance where:
922 * @param msec - the time-to-live value in milliseconds.
923 * @return Return value: the current response object.
924 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsettlmsec)
925 */
926 ttl(msec: number): ResponseObject;
927
928 /**
929 * Sets the HTTP 'Content-Type' header where:
930 * @param mimeType - is the mime type.
931 * @return Return value: the current response object.
932 * Should only be used to override the built-in default for each response type.
933 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetypemimetype)
934 */
935 type(mimeType: string): ResponseObject;
936
937 /**
938 * Clears the HTTP cookie by setting an expired value where:
939 * @param name - the cookie name.
940 * @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
941 * definition.
942 * @return Return value: the current response object.
943 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responseunstatename-options)
944 */
945 unstate(name: string, options?: ServerStateCookieOptions): ResponseObject;
946
947 /**
948 * Adds the provided header to the list of inputs affected the response generation via the HTTP 'Vary' header where:
949 * @param header - the HTTP request header name.
950 * @return Return value: the current response object.
951 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsevaryheader)
952 */
953 vary(header: string): ResponseObject;
954
955 /**
956 * Marks the response object as a takeover response.
957 * @return Return value: the current response object.
958 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetakeover)
959 */
960 takeover(): ResponseObject;
961
962 /**
963 * Sets the status code to 302 or 307 (based on the response.rewritable() setting) where:
964 * @param isTemporary - if false, sets status to permanent. Defaults to true.
965 * @return Return value: the current response object.
966 * Only available after calling the response.redirect() method.
967 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsetemporaryistemporary)
968 */
969 temporary(isTemporary: boolean): ResponseObject;
970
971 /**
972 * Sets the status code to 301 or 308 (based on the response.rewritable() setting) where:
973 * @param isPermanent - if false, sets status to temporary. Defaults to true.
974 * @return Return value: the current response object.
975 * Only available after calling the response.redirect() method.
976 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsepermanentispermanent)
977 */
978 permanent(isPermanent: boolean): ResponseObject;
979
980 /**
981 * 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'
982 * to 'GET'). Exact code based on the response.temporary() or response.permanent() setting. Arguments:
983 * @param isRewritable - if false, sets to non-rewritable. Defaults to true.
984 * @return Return value: the current response object.
985 * Only available after calling the response.redirect() method.
986 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responserewritableisrewritable)
987 */
988 rewritable(isRewritable: boolean): ResponseObject;
989}
990
991/**
992 * Object containing the response handling flags.
993 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-responsesettings)
994 */
995export interface ResponseSettings {
996 /**
997 * Defaults value: true.
998 * If true and source is a Stream, copies the statusCode and headers properties of the stream object to the outbound response.
999 */
1000 readonly passThrough: boolean;
1001
1002 /**
1003 * @default null (use route defaults).
1004 * Override the route json options used when source value requires stringification.
1005 */
1006 readonly stringify: Json.StringifyArguments;
1007
1008 /**
1009 * @default null (use route defaults).
1010 * If set, overrides the route cache with an expiration value in milliseconds.
1011 */
1012 readonly ttl: number;
1013
1014 /**
1015 * @default false.
1016 * 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.
1017 */
1018 varyEtag: boolean;
1019}
1020
1021/**
1022 * See more about Lifecycle
1023 * https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle
1024 *
1025 */
1026
1027export type ResponseValue = string | object;
1028
1029export interface AuthenticationData<
1030
1031 AuthUser extends object = UserCredentials,
1032 AuthApp extends object = AppCredentials,
1033 CredentialsExtra extends object = Record<string, unknown>,
1034 ArtifactsExtra = AuthArtifacts
1035> {
1036 credentials: MergeType<CredentialsExtra, AuthCredentials<AuthUser, AuthApp>>;
1037 artifacts?: ArtifactsExtra | undefined;
1038}
1039
1040export interface Auth<
1041 AuthUser extends object = UserCredentials,
1042 AuthApp extends object = AppCredentials,
1043 CredentialsExtra extends object = Record<string, unknown>,
1044 ArtifactsExtra = AuthArtifacts
1045> {
1046 readonly isAuth: true;
1047 readonly error?: Error | null | undefined;
1048 readonly data?: AuthenticationData<AuthUser, AuthApp, CredentialsExtra, ArtifactsExtra> | undefined;
1049}
1050
1051/**
1052 * 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)
1053 * It is somewhat hard to define as it provides both utilities for manipulating responses as well as other information. Since the
1054 * toolkit is passed as a function argument, developers can name it whatever they want. For the purpose of this
1055 * document the h notation is used. It is named in the spirit of the RethinkDB r method, with h for hapi.
1056 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#response-toolkit)
1057 */
1058export interface ResponseToolkit<Refs extends ReqRef = ReqRefDefaults> {
1059 /**
1060 * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step
1061 * without further interaction with the node response stream. It is the developer's responsibility to write
1062 * and end the response directly via [request.raw.res](https://github.com/hapijs/hapi/blob/master/API.md#request.raw).
1063 */
1064 readonly abandon: symbol;
1065
1066 /**
1067 * A response symbol. When returned by a lifecycle method, the request lifecycle skips to the finalizing step after
1068 * calling request.raw.res.end()) to close the the node response stream.
1069 */
1070 readonly close: symbol;
1071
1072 /**
1073 * 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)
1074 * option or [server.bind()](https://github.com/hapijs/hapi/blob/master/API.md#server.bind()).
1075 */
1076 readonly context: any;
1077
1078 /**
1079 * A response symbol. When returned by a lifecycle method, the request lifecycle continues without changing the response.
1080 */
1081 readonly continue: symbol;
1082
1083 /**
1084 * The [server realm](https://github.com/hapijs/hapi/blob/master/API.md#server.realm) associated with the matching
1085 * route. Defaults to the root server realm in the onRequest step.
1086 */
1087 readonly realm: ServerRealm;
1088
1089 /**
1090 * Access: read only and public request interface.
1091 * The [request] object. This is a duplication of the request lifecycle method argument used by
1092 * [toolkit decorations](https://github.com/hapijs/hapi/blob/master/API.md#server.decorate()) to access the current request.
1093 */
1094 readonly request: Readonly<Request<Refs>>;
1095
1096 /**
1097 * Used by the [authentication] method to pass back valid credentials where:
1098 * @param data - an object with:
1099 * * credentials - (required) object representing the authenticated entity.
1100 * * artifacts - (optional) authentication artifacts object specific to the authentication scheme.
1101 * @return Return value: an internal authentication object.
1102 */
1103 authenticated <
1104 AuthUser extends object = MergeRefs<Refs>['AuthUser'],
1105 AuthApp extends object = MergeRefs<Refs>['AuthApp'],
1106 CredentialsExtra extends object = MergeRefs<Refs>['AuthCredentialsExtra'],
1107 ArtifactsExtra = MergeRefs<Refs>['AuthArtifactsExtra']
1108 >(
1109 data: (
1110 AuthenticationData<
1111 AuthUser,
1112 AuthApp,
1113 CredentialsExtra,
1114 ArtifactsExtra
1115 >
1116 )
1117 ): Auth<
1118 AuthUser,
1119 AuthApp,
1120 CredentialsExtra,
1121 ArtifactsExtra
1122 >;
1123
1124 /**
1125 * Sets the response 'ETag' and 'Last-Modified' headers and checks for any conditional request headers to decide if
1126 * the response is going to qualify for an HTTP 304 (Not Modified). If the entity values match the request
1127 * conditions, h.entity() returns a response object for the lifecycle method to return as its value which will
1128 * set a 304 response. Otherwise, it sets the provided entity headers and returns undefined.
1129 * The method arguments are:
1130 * @param options - a required configuration object with:
1131 * * etag - the ETag string. Required if modified is not present. Defaults to no header.
1132 * * modified - the Last-Modified header value. Required if etag is not present. Defaults to no header.
1133 * * vary - same as the response.etag() option. Defaults to true.
1134 * @return Return value: - a response object if the response is unmodified. - undefined if the response has changed.
1135 * If undefined is returned, the developer must return a valid lifecycle method value. If a response is returned,
1136 * it should be used as the return value (but may be customize using the response methods).
1137 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hentityoptions)
1138 */
1139 entity(options?: {etag?: string | undefined, modified?: string | undefined, vary?: boolean | undefined}): ResponseObject | undefined;
1140
1141 /**
1142 * Redirects the client to the specified uri. Same as calling h.response().redirect(uri).
1143 * @param url
1144 * @return Returns a response object.
1145 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hredirecturi)
1146 */
1147 redirect(uri?: string): ResponseObject;
1148
1149 /**
1150 * Wraps the provided value and returns a response object which allows customizing the response
1151 * (e.g. setting the HTTP status code, custom headers, etc.), where:
1152 * @param value - (optional) return value. Defaults to null.
1153 * @return Returns a response object.
1154 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hresponsevalue)
1155 */
1156 response(value?: ResponseValue): ResponseObject;
1157
1158 /**
1159 * Sets a response cookie using the same arguments as response.state().
1160 * @param name of the cookie
1161 * @param value of the cookie
1162 * @param (optional) ServerStateCookieOptions object.
1163 * @return Return value: none.
1164 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hstatename-value-options)
1165 */
1166 state(name: string, value: string | object, options?: ServerStateCookieOptions): void;
1167
1168 /**
1169 * Used by the [authentication] method to indicate authentication failed and pass back the credentials received where:
1170 * @param error - (required) the authentication error.
1171 * @param data - (optional) an object with:
1172 * * credentials - (required) object representing the authenticated entity.
1173 * * artifacts - (optional) authentication artifacts object specific to the authentication scheme.
1174 * @return void.
1175 * The method is used to pass both the authentication error and the credentials. For example, if a request included
1176 * expired credentials, it allows the method to pass back the user information (combined with a 'try'
1177 * authentication mode) for error customization.
1178 * 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.
1179 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunauthenticatederror-data)
1180 */
1181 unauthenticated <
1182 AuthUser extends object = MergeRefs<Refs>['AuthUser'],
1183 AuthApp extends object = MergeRefs<Refs>['AuthApp'],
1184 CredentialsExtra extends object = MergeRefs<Refs>['AuthCredentialsExtra'],
1185 ArtifactsExtra = MergeRefs<Refs>['AuthArtifactsExtra']
1186 >(
1187 error: Error,
1188 data?: (
1189 AuthenticationData<
1190 AuthUser,
1191 AuthApp,
1192 CredentialsExtra,
1193 ArtifactsExtra
1194 >
1195 )
1196 ): Auth<
1197 AuthUser,
1198 AuthApp,
1199 CredentialsExtra,
1200 ArtifactsExtra
1201 >;
1202
1203 /**
1204 * Clears a response cookie using the same arguments as
1205 * @param name of the cookie
1206 * @param options (optional) ServerStateCookieOptions object.
1207 * @return void.
1208 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-hunstatename-options)
1209 */
1210 unstate(name: string, options?: ServerStateCookieOptions): void;
1211}
1212
1213/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
1214 + +
1215 + +
1216 + +
1217 + Route +
1218 + +
1219 + +
1220 + +
1221 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
1222
1223/**
1224 * Overrides for `InternalRouteOptionType`. Extend this to have
1225 * typings for route.options.auth['strategy' || 'scope']
1226 *
1227 * @example
1228 *
1229 * interface RoutOptionTypes {
1230 * Strategy: 'jwt' | 'basic' | 'myCustom'
1231 * Scope: 'user' | 'admin' | 'manager-users'
1232 * }
1233 */
1234// tslint:disable-next-line no-empty-interface
1235export interface RouteOptionTypes {
1236}
1237
1238export interface InternalRouteOptionType {
1239 Strategy: string;
1240 Scope: RouteOptionsAccessScope;
1241}
1242
1243export type RouteOptionsAccessScope = false | string | string[];
1244
1245export type AccessEntity = 'any' | 'user' | 'app';
1246
1247export interface RouteOptionsAccessScopeObject {
1248 scope: RouteOptionsAccessScope;
1249}
1250
1251export interface RouteOptionsAccessEntityObject {
1252 entity: AccessEntity;
1253}
1254
1255export type RouteOptionsAccessObject =
1256 RouteOptionsAccessScopeObject
1257 | RouteOptionsAccessEntityObject
1258 | (RouteOptionsAccessScopeObject & RouteOptionsAccessEntityObject);
1259
1260/**
1261 * Route Authentication Options
1262 */
1263export interface RouteOptionsAccess {
1264 /**
1265 * @default none.
1266 * 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
1267 * must include at least one of scope or entity.
1268 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccess)
1269 */
1270 access?: RouteOptionsAccessObject | RouteOptionsAccessObject[] | undefined;
1271
1272 /**
1273 * @default false (no scope requirements).
1274 * 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
1275 * 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
1276 * 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
1277 * 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}'.
1278 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessscope)
1279 */
1280 scope?: MergeType<InternalRouteOptionType, RouteOptionTypes>['Scope'] | undefined;
1281
1282 /**
1283 * @default 'any'.
1284 * The required authenticated entity type. If set, must match the entity value of the request authenticated credentials. Available values:
1285 * * 'any' - the authentication can be on behalf of a user or application.
1286 * * '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.
1287 * * '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
1288 * strategy.
1289 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthaccessentity)
1290 */
1291 entity?: AccessEntity | undefined;
1292
1293 /**
1294 * @default 'required'.
1295 * The authentication mode. Available values:
1296 * * 'required' - authentication is required.
1297 * * 'optional' - authentication is optional - the request must include valid credentials or no credentials at all.
1298 * * 'try' - similar to 'optional', any request credentials are attempted authentication, but if the credentials are invalid, the request proceeds regardless of the authentication error.
1299 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthmode)
1300 */
1301 mode?: AuthMode | undefined;
1302
1303 /**
1304 * @default false, unless the scheme requires payload authentication.
1305 * 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'
1306 * when the scheme sets the authentication options.payload to true. Available values:
1307 * * false - no payload authentication.
1308 * * 'required' - payload authentication required.
1309 * * 'optional' - payload authentication performed only when the client includes payload authentication information (e.g. hash attribute in Hawk).
1310 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthpayload)
1311 */
1312 payload?: false | 'required' | 'optional' | undefined;
1313
1314 /**
1315 * @default the default strategy set via server.auth.default().
1316 * An array of string strategy names in the order they should be attempted. Cannot be used together with strategy.
1317 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategies)
1318 */
1319 strategies?: Array<MergeType<InternalRouteOptionType, RouteOptionTypes>['Strategy']> | undefined;
1320
1321 /**
1322 * @default the default strategy set via server.auth.default().
1323 * A string strategy names. Cannot be used together with strategies.
1324 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsauthstrategy)
1325 */
1326 strategy?: MergeType<InternalRouteOptionType, RouteOptionTypes>['Strategy'] | undefined;
1327}
1328
1329/**
1330 * Values are:
1331 * * * 'default' - no privacy flag.
1332 * * * 'public' - mark the response as suitable for public caching.
1333 * * * 'private' - mark the response as suitable only for private caching.
1334 * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
1335 * * 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.
1336 * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive.
1337 * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled.
1338 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache)
1339 */
1340export type RouteOptionsCache = {
1341 privacy?: 'default' | 'public' | 'private' | undefined;
1342 statuses?: number[] | undefined;
1343 otherwise?: string | undefined;
1344} & (
1345 {
1346 expiresIn?: number | undefined;
1347 expiresAt?: undefined;
1348 } | {
1349 expiresIn?: undefined;
1350 expiresAt?: string | undefined;
1351} | {
1352 expiresIn?: undefined;
1353 expiresAt?: undefined;
1354}
1355 );
1356
1357/**
1358 * @default false (no CORS headers).
1359 * 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
1360 * than the API server. To enable, set cors to true, or to an object with the following options:
1361 * * 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
1362 * 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 '*'.
1363 * Defaults to any origin ['*'].
1364 * * 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.
1365 * Defaults to 86400 (one day).
1366 * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'].
1367 * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place.
1368 * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization'].
1369 * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place.
1370 * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false.
1371 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors)
1372 */
1373export interface RouteOptionsCors {
1374 /**
1375 * 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 '*'
1376 * 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
1377 * origin ['*'].
1378 */
1379 origin?: string[] | '*' | 'ignore' | undefined;
1380 /**
1381 * 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.
1382 * Defaults to 86400 (one day).
1383 */
1384 maxAge?: number | undefined;
1385 /**
1386 * a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'].
1387 */
1388 headers?: string[] | undefined;
1389 /**
1390 * a strings array of additional headers to headers. Use this to keep the default headers in place.
1391 */
1392 additionalHeaders?: string[] | undefined;
1393 /**
1394 * a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization'].
1395 */
1396 exposedHeaders?: string[] | undefined;
1397 /**
1398 * a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place.
1399 */
1400 additionalExposedHeaders?: string[] | undefined;
1401 /**
1402 * if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false.
1403 */
1404 credentials?: boolean | undefined;
1405}
1406
1407/**
1408 * The value must be one of:
1409 * * '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
1410 * Buffer is returned.
1411 * * '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
1412 * 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
1413 * payloads are a synthetic interface created on top of the entire multipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the
1414 * multipart payload in the handler using a streaming parser (e.g. pez).
1415 * * '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
1416 * 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
1417 * which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup. For context [See
1418 * docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput)
1419 */
1420export type PayloadOutput = 'data' | 'stream' | 'file';
1421
1422/**
1423 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression)
1424 */
1425export type PayloadCompressionDecoderSettings = object;
1426
1427/**
1428 * Determines how the request payload is processed.
1429 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload)
1430 */
1431export interface RouteOptionsPayload {
1432 /**
1433 * @default allows parsing of the following mime types:
1434 * * application/json
1435 * * application/*+json
1436 * * application/octet-stream
1437 * * application/x-www-form-urlencoded
1438 * * multipart/form-data
1439 * * text/*
1440 * 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
1441 * above will not enable them to be parsed, and if parse is true, the request will result in an error response.
1442 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadallow)
1443 */
1444 allow?: string | string[] | undefined;
1445
1446 /**
1447 * @default none.
1448 * 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.
1449 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadcompression)
1450 */
1451 compression?: Util.Dictionary<PayloadCompressionDecoderSettings> | undefined;
1452
1453 /**
1454 * @default 'application/json'.
1455 * The default content type if the 'Content-Type' request header is missing.
1456 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaddefaultcontenttype)
1457 */
1458 defaultContentType?: string | undefined;
1459
1460 /**
1461 * @default 'error' (return a Bad Request (400) error response).
1462 * A failAction value which determines how to handle payload parsing errors.
1463 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadfailaction)
1464 */
1465 failAction?: Lifecycle.FailAction | undefined;
1466
1467 /**
1468 * @default 1048576 (1MB).
1469 * Limits the size of incoming payloads to the specified byte count. Allowing very large payloads may cause the server to run out of memory.
1470 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmaxbytes)
1471 */
1472 maxBytes?: number | undefined;
1473
1474 /**
1475 * @default none.
1476 * Overrides payload processing for multipart requests. Value can be one of:
1477 * * false - disable multipart processing.
1478 * an object with the following required options:
1479 * * output - same as the output option with an additional value option:
1480 * * * annotated - wraps each multipart part in an object with the following keys: // TODO type this?
1481 * * * * headers - the part headers.
1482 * * * * filename - the part file name.
1483 * * * * payload - the processed part payload.
1484 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadmultipart)
1485 */
1486 multipart?:
1487 | false
1488 | {
1489 output: PayloadOutput | 'annotated';
1490 }
1491 | undefined;
1492
1493 /**
1494 * @default 'data'.
1495 * The processed payload format. The value must be one of:
1496 * * '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
1497 * Buffer is returned.
1498 * * '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
1499 * 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
1500 * payloads are a synthetic interface created on top of the entire multipart content loaded into memory. To avoid loading large multipart payloads into memory, set parse to false and handle the
1501 * multipart payload in the handler using a streaming parser (e.g. pez).
1502 * * '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
1503 * 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
1504 * of which files are used (e.g. using the request.app object), and listening to the server 'response' event to perform cleanup.
1505 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoutput)
1506 */
1507 output?: PayloadOutput | undefined;
1508
1509 /**
1510 * @default none.
1511 * A mime type string overriding the 'Content-Type' header value received.
1512 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadoverride)
1513 */
1514 override?: string | undefined;
1515
1516 /**
1517 * @default true.
1518 * Determines if the incoming payload is processed or presented raw. Available values:
1519 * * 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
1520 * format is unknown, a Bad Request (400) error response is sent. Any known content encoding is decoded.
1521 * * false - the raw payload is returned unmodified.
1522 * * 'gunzip' - the raw payload is returned unmodified after any known content encoding is decoded.
1523 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadparse)
1524 */
1525 parse?: boolean | 'gunzip' | undefined;
1526
1527 /**
1528 * @default to 10000 (10 seconds).
1529 * 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)
1530 * error response. Set to false to disable.
1531 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloadtimeout)
1532 */
1533 timeout?: false | number | undefined;
1534
1535 /**
1536 * @default os.tmpdir().
1537 * The directory used for writing file uploads.
1538 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayloaduploads)
1539 */
1540 uploads?: string | undefined;
1541}
1542
1543/**
1544 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1545 */
1546export type RouteOptionsPreArray<Refs extends ReqRef = ReqRefDefaults> = Array<RouteOptionsPreAllOptions<Refs>>;
1547
1548/**
1549 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1550 */
1551export type RouteOptionsPreAllOptions<Refs extends ReqRef = ReqRefDefaults> = RouteOptionsPreObject<Refs> | Array<RouteOptionsPreObject<Refs>> | Lifecycle.Method<Refs>;
1552
1553/**
1554 * An object with:
1555 * * method - a lifecycle method.
1556 * * assign - key name used to assign the response of the method to in request.pre and request.preResponses.
1557 * * 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.
1558 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
1559 */
1560export interface RouteOptionsPreObject<Refs extends ReqRef = ReqRefDefaults> {
1561 /**
1562 * a lifecycle method.
1563 */
1564 method: Lifecycle.Method<Refs>;
1565 /**
1566 * key name used to assign the response of the method to in request.pre and request.preResponses.
1567 */
1568 assign?: keyof Refs['Pres'] | undefined;
1569 /**
1570 * 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.
1571 */
1572 failAction?: Lifecycle.FailAction | undefined;
1573}
1574
1575export type ValidationObject = SchemaMap;
1576
1577/**
1578 * * true - any query parameter value allowed (no validation performed). false - no parameter value allowed.
1579 * * a joi validation object.
1580 * * a validation function using the signature async function(value, options) where:
1581 * * * value - the request.* object containing the request parameters.
1582 * * * options - options.
1583 */
1584export type RouteOptionsResponseSchema =
1585 boolean
1586 | ValidationObject
1587 | Schema
1588 | ((value: object | Buffer | string, options: ValidationOptions) => Promise<any>);
1589
1590/**
1591 * Processing rules for the outgoing response.
1592 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse)
1593 */
1594export interface RouteOptionsResponse {
1595 /**
1596 * @default 204.
1597 * 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
1598 * response status code will remain 200 throughout the request lifecycle unless manually set).
1599 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseemptystatuscode)
1600 */
1601 emptyStatusCode?: 200 | 204 | undefined;
1602
1603 /**
1604 * @default 'error' (return an Internal Server Error (500) error response).
1605 * A failAction value which defines what to do when a response fails payload validation.
1606 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsefailaction)
1607 */
1608 failAction?: Lifecycle.FailAction | undefined;
1609
1610 /**
1611 * @default false.
1612 * If true, applies the validation rule changes to the response payload.
1613 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsemodify)
1614 */
1615 modify?: boolean | undefined;
1616
1617 /**
1618 * @default none.
1619 * [joi](https://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
1620 * 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.
1621 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseoptions)
1622 */
1623 options?: ValidationOptions | undefined; // TODO needs validation
1624
1625 /**
1626 * @default true.
1627 * If false, payload range support is disabled.
1628 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseranges)
1629 */
1630 ranges?: boolean | undefined;
1631
1632 /**
1633 * @default 100 (all responses).
1634 * The percent of response payloads validated (0 - 100). Set to 0 to disable all validation.
1635 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsesample)
1636 */
1637 sample?: number | undefined;
1638
1639 /**
1640 * @default true (no validation).
1641 * The default response payload validation rules (for all non-error responses) expressed as one of:
1642 * * true - any payload allowed (no validation).
1643 * * false - no payload allowed.
1644 * * a joi validation object. The options along with the request context ({ headers, params, query, payload, app, auth }) are passed to the validation function.
1645 * * a validation function using the signature async function(value, options) where:
1646 * * * value - the pending response payload.
1647 * * * options - The options along with the request context ({ headers, params, query, payload, app, auth }).
1648 * * * 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
1649 * output.payload. If an error is thrown, the error is processed according to failAction.
1650 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponseschema)
1651 */
1652 schema?: RouteOptionsResponseSchema | undefined;
1653
1654 /**
1655 * @default none.
1656 * Validation schemas for specific HTTP status codes. Responses (excluding errors) not matching the listed status codes are validated using the default schema.
1657 * 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.
1658 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponsestatus)
1659 */
1660 status?: Util.Dictionary<RouteOptionsResponseSchema> | undefined;
1661
1662 /**
1663 * The default HTTP status code used to set a response error when the request is closed or aborted before the
1664 * response is fully transmitted.
1665 * Value can be any integer greater or equal to 400.
1666 * The default value 499 is based on the non-standard nginx "CLIENT CLOSED REQUEST" error.
1667 * The value is only used for logging as the request has already ended.
1668 * @default 499
1669 */
1670 disconnectStatusCode?: number | undefined;
1671}
1672
1673/**
1674 * @see https://www.w3.org/TR/referrer-policy/
1675 */
1676export type ReferrerPolicy = '' | 'no-referrer' | 'no-referrer-when-downgrade' | 'unsafe-url' |
1677 'same-origin' | 'origin' | 'strict-origin' | 'origin-when-cross-origin' | 'strict-origin-when-cross-origin';
1678
1679/**
1680 * @default false (security headers disabled).
1681 * Sets common security headers. To enable, set security to true or to an object with the following options:
1682 * * hsts - controls the 'Strict-Transport-Security' header, where:
1683 * * * true - the header will be set to max-age=15768000. This is the default value.
1684 * * * a number - the maxAge parameter will be set to the provided value.
1685 * * * an object with the following fields:
1686 * * * * maxAge - the max-age portion of the header, as a number. Default is 15768000.
1687 * * * * includeSubDomains - a boolean specifying whether to add the includeSubDomains flag to the header.
1688 * * * * 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.
1689 * * xframe - controls the 'X-Frame-Options' header, where:
1690 * * * true - the header will be set to 'DENY'. This is the default value.
1691 * * * 'deny' - the headers will be set to 'DENY'.
1692 * * * 'sameorigin' - the headers will be set to 'SAMEORIGIN'.
1693 * * * an object for specifying the 'allow-from' rule, where:
1694 * * * * rule - one of:
1695 * * * * * 'deny'
1696 * * * * * 'sameorigin'
1697 * * * * * 'allow-from'
1698 * * * * 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
1699 * changed to 'sameorigin'.
1700 * * xss - boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'.
1701 * Note: this setting can create a security vulnerability in versions of Internet Explorer below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively
1702 * support old versions of IE, it may be wise to explicitly set this flag to false.
1703 * * 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'.
1704 * * noSniff - boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'.
1705 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity)
1706 */
1707export interface RouteOptionsSecureObject {
1708 /**
1709 * hsts - controls the 'Strict-Transport-Security' header
1710 */
1711 hsts?: boolean | number | {
1712 /**
1713 * the max-age portion of the header, as a number. Default is 15768000.
1714 */
1715 maxAge: number;
1716 /**
1717 * a boolean specifying whether to add the includeSubDomains flag to the header.
1718 */
1719 includeSubDomains: boolean;
1720 /**
1721 * 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.
1722 */
1723 preload: boolean;
1724 } | undefined;
1725 /**
1726 * controls the 'X-Frame-Options' header
1727 */
1728 xframe?: true | 'deny' | 'sameorigin' | {
1729 /**
1730 * an object for specifying the 'allow-from' rule,
1731 */
1732 rule: 'deny' | 'sameorigin' | 'allow-from';
1733 /**
1734 * 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
1735 * to 'sameorigin'.
1736 */
1737 source: string;
1738 } | undefined;
1739 /**
1740 * boolean that controls the 'X-XSS-PROTECTION' header for Internet Explorer. Defaults to true which sets the header to equal '1; mode=block'.
1741 * Note: this setting can create a security vulnerability in versions of Internet Explorer below 8, as well as unpatched versions of IE8. See here and here for more information. If you actively
1742 * support old versions of IE, it may be wise to explicitly set this flag to false.
1743 */
1744 xss?: boolean | undefined;
1745 /**
1746 * 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'.
1747 */
1748 noOpen?: boolean | undefined;
1749 /**
1750 * boolean controlling the 'X-Content-Type-Options' header. Defaults to true setting the header to its only and default option, 'nosniff'.
1751 */
1752 noSniff?: boolean | undefined;
1753
1754 /**
1755 * Controls the `Referrer-Policy` header, which has the following possible values.
1756 * @default false Header will not be send.
1757 */
1758 referrer?: false | ReferrerPolicy | undefined;
1759}
1760
1761export type RouteOptionsSecure = boolean | RouteOptionsSecureObject;
1762
1763/**
1764 * @default { headers: true, params: true, query: true, payload: true, failAction: 'error' }.
1765 * Request input validation rules for various request components.
1766 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate)
1767 */
1768export interface RouteOptionsValidate {
1769 /**
1770 * @default none.
1771 * An optional object with error fields copied into every validation error response.
1772 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateerrorfields)
1773 */
1774 errorFields?: object | undefined;
1775
1776 /**
1777 * @default 'error' (return a Bad Request (400) error response).
1778 * 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.
1779 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatefailaction)
1780 */
1781 failAction?: Lifecycle.FailAction | undefined;
1782
1783 /**
1784 * Validation rules for incoming request headers:
1785 * * 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
1786 * 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.
1787 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateheaders)
1788 * @default true
1789 */
1790 headers?: RouteOptionsResponseSchema | undefined;
1791
1792 /**
1793 * 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).
1794 * 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.
1795 * 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
1796 * Joi.ref('$query.key')).
1797 * 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
1798 * 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
1799 * individual route settings override the routes defaults (the rules are not merged).
1800 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams)
1801 * @default true
1802 */
1803 options?: ValidationOptions | object | undefined;
1804
1805 /**
1806 * Validation rules for incoming request path parameters, after matching the path against the route, extracting any parameters, and storing them in request.params, where:
1807 * * true - any path parameter value allowed (no validation performed).
1808 * * a joi validation object.
1809 * * a validation function using the signature async function(value, options) where:
1810 * * * value - the request.params object containing the request path parameters.
1811 * * * options - options.
1812 * 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
1813 * 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.
1814 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidateparams)
1815 * @default true
1816 */
1817 params?: RouteOptionsResponseSchema | undefined;
1818
1819 /**
1820 * Validation rules for incoming request payload (request body), where:
1821 * * 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
1822 * 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
1823 * as the significant performance cost of validating large amounts of data.
1824 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatepayload)
1825 * @default true
1826 */
1827 payload?: RouteOptionsResponseSchema | undefined;
1828
1829 /**
1830 * 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
1831 * request.query prior to validation. Where:
1832 * * 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.
1833 * If an error
1834 * is thrown, the error is handled according to failAction. Note that changes to the query parameters will not be reflected in request.url.
1835 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidatequery)
1836 * @default true
1837 */
1838 query?: RouteOptionsResponseSchema | undefined;
1839
1840 /**
1841 * Validation rules for incoming cookies.
1842 * The cookie header is parsed and decoded into the request.state prior to validation.
1843 * @default true
1844 */
1845 state?: RouteOptionsResponseSchema | undefined;
1846}
1847
1848/**
1849 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression)
1850 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder)
1851 */
1852export type RouteCompressionEncoderSettings = object;
1853
1854/**
1855 * Empty interface to allow for user-defined augmentations.
1856 */
1857
1858// tslint:disable-next-line no-empty-interface
1859export interface RouteOptionsApp {}
1860
1861export interface CommonRouteProperties<Refs extends ReqRef = ReqRefDefaults> {
1862 /**
1863 * Application-specific route configuration state. Should not be used by plugins which should use options.plugins[name] instead.
1864 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp)
1865 */
1866 app?: RouteOptionsApp | undefined;
1867
1868 /**
1869 * @default null.
1870 * An object passed back to the provided handler (via this) when called. Ignored if the method is an arrow function.
1871 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsbind)
1872 */
1873 bind?: MergeRefs<Refs>['Bind'] | undefined;
1874
1875 /**
1876 * @default { privacy: 'default', statuses: [200], otherwise: 'no-cache' }.
1877 * 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:
1878 * privacy - determines the privacy flag included in client-side caching using the 'Cache-Control' header. Values are:
1879 * * * 'default' - no privacy flag.
1880 * * * 'public' - mark the response as suitable for public caching.
1881 * * * 'private' - mark the response as suitable only for private caching.
1882 * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
1883 * * 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.
1884 * * statuses - an array of HTTP response status code numbers (e.g. 200) which are allowed to include a valid caching directive.
1885 * * otherwise - a string with the value of the 'Cache-Control' header when caching is disabled.
1886 * The default Cache-Control: no-cache header can be disabled by setting cache to false.
1887 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscache)
1888 */
1889 cache?: false | RouteOptionsCache | undefined;
1890
1891 /**
1892 * 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.
1893 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscompression)
1894 */
1895 compression?: Util.Dictionary<RouteCompressionEncoderSettings> | undefined;
1896
1897 /**
1898 * @default false (no CORS headers).
1899 * 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
1900 * domain than the API server. To enable, set cors to true, or to an object with the following options:
1901 * * 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
1902 * 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 '*'.
1903 * Defaults to any origin ['*'].
1904 * * 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
1905 * policy. Defaults to 86400 (one day).
1906 * * headers - a strings array of allowed headers ('Access-Control-Allow-Headers'). Defaults to ['Accept', 'Authorization', 'Content-Type', 'If-None-Match'].
1907 * * additionalHeaders - a strings array of additional headers to headers. Use this to keep the default headers in place.
1908 * * exposedHeaders - a strings array of exposed headers ('Access-Control-Expose-Headers'). Defaults to ['WWW-Authenticate', 'Server-Authorization'].
1909 * * additionalExposedHeaders - a strings array of additional headers to exposedHeaders. Use this to keep the default headers in place.
1910 * * credentials - if true, allows user credentials to be sent ('Access-Control-Allow-Credentials'). Defaults to false.
1911 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionscors)
1912 */
1913 cors?: boolean | RouteOptionsCors | undefined;
1914
1915 /**
1916 * @default none.
1917 * Route description used for generating documentation (string).
1918 * This setting is not available when setting server route defaults using server.options.routes.
1919 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsdescription)
1920 */
1921 description?: string | undefined;
1922
1923 /**
1924 * @default none.
1925 * 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
1926 * server.ext(events) event argument.
1927 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsext)
1928 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle)
1929 */
1930 ext?: {
1931 [key in RouteRequestExtType]?: RouteExtObject | RouteExtObject[];
1932 } | undefined;
1933
1934 /**
1935 * @default { relativeTo: '.' }.
1936 * Defines the behavior for accessing files:
1937 * * relativeTo - determines the folder relative paths are resolved against.
1938 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsfiles)
1939 */
1940 files?: {
1941 relativeTo: string;
1942 } | undefined;
1943
1944 /**
1945 * @default none.
1946 * The route handler function performs the main business logic of the route and sets the response. handler can be assigned:
1947 * * a lifecycle method.
1948 * * an object with a single property using the name of a handler type registered with the server.handler() method. The matching property value is passed as options to the registered handler
1949 * 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.
1950 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionshandler)
1951 */
1952 handler?: Lifecycle.Method<Refs> | object | undefined;
1953
1954 /**
1955 * @default none.
1956 * An optional unique identifier used to look up the route using server.lookup(). Cannot be assigned to routes added with an array of methods.
1957 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsid)
1958 */
1959 id?: string | undefined;
1960
1961 /**
1962 * @default false.
1963 * 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
1964 * not be accessible to the outside world.
1965 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsisinternal)
1966 */
1967 isInternal?: boolean | undefined;
1968
1969 /**
1970 * @default none.
1971 * 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:
1972 * * replacer - the replacer function or array. Defaults to no action.
1973 * * space - number of spaces to indent nested object keys. Defaults to no indentation.
1974 * * suffix - string suffix added after conversion to JSON string. Defaults to no suffix.
1975 * * escape - calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false.
1976 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson)
1977 */
1978 json?: Json.StringifyArguments | undefined;
1979
1980 /**
1981 * @default none.
1982 * Enables JSONP support by setting the value to the query parameter name containing the function name used to wrap the response payload.
1983 * 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
1984 * 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
1985 * explicitly set by response.type().
1986 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjsonp)
1987 */
1988 jsonp?: string | undefined;
1989
1990 /**
1991 * @default { collect: false }.
1992 * Request logging options:
1993 * collect - if true, request-level logs (both internal and application) are collected and accessible via request.logs.
1994 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionslog)
1995 */
1996 log?: {
1997 collect: boolean;
1998 } | undefined;
1999
2000 /**
2001 * @default none.
2002 * Route notes used for generating documentation (string or array of strings).
2003 * This setting is not available when setting server route defaults using server.options.routes.
2004 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsnotes)
2005 */
2006 notes?: string | string[] | undefined;
2007
2008 /**
2009 * Determines how the request payload is processed.
2010 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspayload)
2011 */
2012 payload?: RouteOptionsPayload | undefined;
2013
2014 /**
2015 * @default {}.
2016 * Plugin-specific configuration. plugins is an object where each key is a plugin name and the value is the plugin configuration.
2017 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsplugins)
2018 */
2019 plugins?: PluginSpecificConfiguration | undefined;
2020
2021 /**
2022 * @default none.
2023 * 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
2024 * across 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
2025 * 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
2026 * 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:
2027 * * an array containing the elements listed below, which are executed in parallel.
2028 * * an object with:
2029 * * * method - a lifecycle method.
2030 * * * assign - key name used to assign the response of the method to in request.pre and request.preResponses.
2031 * * * 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
2032 * assigned.
2033 * * a method function - same as including an object with a single method key.
2034 * 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
2035 * 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
2036 * lifecycle methods.
2037 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionspre)
2038 */
2039 pre?: RouteOptionsPreArray<Refs> | undefined;
2040
2041 /**
2042 * Processing rules for the outgoing response.
2043 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsresponse)
2044 */
2045 response?: RouteOptionsResponse | undefined;
2046
2047 /**
2048 * @default false (security headers disabled).
2049 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionssecurity)
2050 */
2051 security?: RouteOptionsSecure | undefined;
2052
2053 /**
2054 * @default { parse: true, failAction: 'error' }.
2055 * 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
2056 * 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
2057 * errors. Defaults to 'error' (return a Bad Request (400) error response).
2058 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsstate)
2059 */
2060 state?: {
2061 parse?: boolean | undefined;
2062 failAction?: Lifecycle.FailAction | undefined;
2063 } | undefined;
2064
2065 /**
2066 * @default none.
2067 * Route tags used for generating documentation (array of strings).
2068 * This setting is not available when setting server route defaults using server.options.routes.
2069 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstags)
2070 */
2071 tags?: string[] | undefined;
2072
2073 /**
2074 * @default { server: false }.
2075 * Timeouts for processing durations.
2076 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionstimeout)
2077 */
2078 timeout?: {
2079 /**
2080 * 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
2081 * response.
2082 */
2083 server?: boolean | number | undefined;
2084
2085 /**
2086 * @default none (use node default of 2 minutes).
2087 * By default, node sockets automatically timeout after 2 minutes. Use this option to override this behavior. Set to false to disable socket timeouts.
2088 */
2089 socket?: boolean | number | undefined;
2090 } | undefined;
2091
2092 /**
2093 * @default { headers: true, params: true, query: true, payload: true, failAction: 'error' }.
2094 * Request input validation rules for various request components.
2095 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsvalidate)
2096 */
2097 validate?: RouteOptionsValidate | undefined;
2098}
2099
2100export interface AccessScopes {
2101 forbidden?: string[] | undefined;
2102 required?: string[] | undefined;
2103 selection?: string[] | undefined;
2104}
2105
2106export interface AccessSetting {
2107 entity?: AccessEntity | undefined;
2108 scope: AccessScopes | false;
2109}
2110
2111export interface AuthSettings {
2112 strategies: string[];
2113 mode: AuthMode;
2114 access?: AccessSetting[] | undefined;
2115}
2116
2117export interface RouteSettings extends CommonRouteProperties {
2118 auth?: AuthSettings | undefined;
2119}
2120
2121/**
2122 * Each route can be customized to change the default behavior of the request lifecycle.
2123 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#route-options)
2124 */
2125export interface RouteOptions<Refs extends ReqRef = ReqRefDefaults> extends CommonRouteProperties<Refs> {
2126 /**
2127 * Route authentication configuration. Value can be:
2128 * false to disable authentication if a default strategy is set.
2129 * a string with the name of an authentication strategy registered with server.auth.strategy(). The strategy will be set to 'required' mode.
2130 * an authentication configuration object.
2131 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsapp)
2132 */
2133 auth?: false | string | RouteOptionsAccess | undefined;
2134}
2135
2136/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
2137 + +
2138 + +
2139 + +
2140 + Server +
2141 + +
2142 + +
2143 + +
2144 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
2145
2146/**
2147 * The scheme options argument passed to server.auth.strategy() when instantiation a strategy.
2148 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme)
2149 */
2150export type ServerAuthSchemeOptions = object;
2151
2152/**
2153 * the method implementing the scheme with signature function(server, options) where:
2154 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme)
2155 * @param server - a reference to the server object the scheme is added to.
2156 * @param options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy.
2157 */
2158export type ServerAuthScheme<
2159 // tslint:disable-next-line no-unnecessary-generics
2160 Options extends ServerAuthSchemeOptions = ServerAuthSchemeOptions,
2161 // tslint:disable-next-line no-unnecessary-generics
2162 Refs extends ReqRef = ReqRefDefaults
2163> = (server: Server, options?: Options) => ServerAuthSchemeObject<Refs>;
2164
2165// tslint:disable-next-line no-empty-interface
2166export interface ServerAuthSchemeObjectApi {}
2167
2168/**
2169 * The scheme method must return an object with the following
2170 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#authentication-scheme)
2171 */
2172
2173export interface ServerAuthSchemeObject<Refs extends ReqRef = ReqRefDefaults> {
2174 /**
2175 * optional object which is exposed via the [server.auth.api](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.api) object.
2176 */
2177 api?: MergeRefs<Refs>['AuthApi'] | undefined;
2178
2179 /**
2180 * A lifecycle method function called for each incoming request configured with the authentication scheme. The
2181 * method is provided with two special toolkit methods for returning an authenticated or an unauthenticated result:
2182 * * h.authenticated() - indicate request authenticated successfully.
2183 * * h.unauthenticated() - indicate request failed to authenticate.
2184 * @param request the request object.
2185 * @param h the ResponseToolkit
2186 * @return the Lifecycle.ReturnValue
2187 */
2188 authenticate(request: Request<Refs>, h: ResponseToolkit<Refs>): Lifecycle.ReturnValue<Refs>;
2189
2190 /**
2191 * A lifecycle method to authenticate the request payload.
2192 * When the scheme payload() method returns an error with a message, it means payload validation failed due to bad
2193 * payload. If the error has no message but includes a scheme name (e.g. Boom.unauthorized(null, 'Custom')),
2194 * authentication may still be successful if the route auth.payload configuration is set to 'optional'.
2195 * @param request the request object.
2196 * @param h the ResponseToolkit
2197 * @return the Lifecycle.ReturnValue
2198 */
2199 payload?(request: Request<Refs>, h: ResponseToolkit<Refs>): Lifecycle.ReturnValue<Refs>;
2200
2201 /**
2202 * A lifecycle method to decorate the response with authentication headers before the response headers or payload is written.
2203 * @param request the request object.
2204 * @param h the ResponseToolkit
2205 * @return the Lifecycle.ReturnValue
2206 */
2207 response?(request: Request<Refs>, h: ResponseToolkit<Refs>): Lifecycle.ReturnValue<Refs>;
2208
2209 /**
2210 * a method used to verify the authentication credentials provided
2211 * are still valid (e.g. not expired or revoked after the initial authentication).
2212 * the method throws an `Error` when the credentials passed are no longer valid (e.g. expired or
2213 * revoked). Note that the method does not have access to the original request, only to the
2214 * credentials and artifacts produced by the `authenticate()` method.
2215 */
2216 verify?(
2217 auth: RequestAuth<
2218 MergeRefs<Refs>['AuthUser'],
2219 MergeRefs<Refs>['AuthApp'],
2220 MergeRefs<Refs>['AuthCredentialsExtra'],
2221 MergeRefs<Refs>['AuthArtifactsExtra']
2222 >
2223 ): Promise<void>;
2224
2225 /**
2226 * An object with the following keys:
2227 * * payload
2228 */
2229 options?: {
2230 /**
2231 * if true, requires payload validation as part of the scheme and forbids routes from disabling payload auth validation. Defaults to false.
2232 */
2233 payload?: boolean | undefined;
2234 } | undefined;
2235}
2236
2237/**
2238 * An authentication configuration object using the same format as the route auth handler options.
2239 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions)
2240 */
2241
2242// tslint:disable-next-line no-empty-interface
2243export interface ServerAuthConfig extends RouteOptionsAccess {
2244}
2245
2246export interface ServerAuth {
2247 /**
2248 * An object where each key is an authentication strategy name and the value is the exposed strategy API.
2249 * Available only when the authentication scheme exposes an API by returning an api key in the object
2250 * returned from its implementation function.
2251 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthapi)
2252 */
2253 api: Util.Dictionary<ServerAuthSchemeObjectApi>;
2254
2255 /**
2256 * Contains the default authentication configuration is a default strategy was set via
2257 * [server.auth.default()](https://github.com/hapijs/hapi/blob/master/API.md#server.auth.default()).
2258 */
2259 readonly settings: {
2260 default: ServerAuthConfig;
2261 };
2262
2263 /**
2264 * Sets a default strategy which is applied to every route where:
2265 * @param options - one of:
2266 * * a string with the default strategy name
2267 * * an authentication configuration object using the same format as the route auth handler options.
2268 * @return void.
2269 * The default does not apply when a route config specifies auth as false, or has an authentication strategy
2270 * configured (contains the strategy or strategies authentication settings). Otherwise, the route authentication
2271 * config is applied to the defaults.
2272 * Note that if the route has authentication configured, the default only applies at the time of adding the route,
2273 * not at runtime. This means that calling server.auth.default() after adding a route with some authentication
2274 * config will have no impact on the routes added prior. However, the default will apply to routes added
2275 * before server.auth.default() is called if those routes lack any authentication config.
2276 * The default auth strategy configuration can be accessed via server.auth.settings.default. To obtain the active
2277 * authentication configuration of a route, use server.auth.lookup(request.route).
2278 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthdefaultoptions)
2279 */
2280 default(options: string | ServerAuthConfig): void;
2281
2282 /**
2283 * Registers an authentication scheme where:
2284 * @param name the scheme name.
2285 * @param scheme - the method implementing the scheme with signature function(server, options) where:
2286 * * server - a reference to the server object the scheme is added to.
2287 * * options - (optional) the scheme options argument passed to server.auth.strategy() when instantiation a strategy.
2288 * @return void.
2289 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthschemename-scheme)
2290 */
2291
2292 scheme <
2293 Refs extends ReqRef = ReqRefDefaults,
2294 Options extends object = {}
2295 // tslint:disable-next-line no-unnecessary-generics
2296 >(name: string, scheme: ServerAuthScheme<Options, Refs>): void;
2297
2298 /**
2299 * Registers an authentication strategy where:
2300 * @param name - the strategy name.
2301 * @param scheme - the scheme name (must be previously registered using server.auth.scheme()).
2302 * @param options - scheme options based on the scheme requirements.
2303 * @return Return value: none.
2304 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverauthstrategyname-scheme-options)
2305 */
2306 strategy(
2307 name: MergeType<InternalRouteOptionType, RouteOptionTypes>['Strategy'],
2308 scheme: string,
2309 options?: object
2310 ): void;
2311
2312 /**
2313 * Tests a request against an authentication strategy where:
2314 * @param strategy - the strategy name registered with server.auth.strategy().
2315 * @param request - the request object.
2316 * @return an object containing the authentication credentials and artifacts if authentication was successful, otherwise throws an error.
2317 * Note that the test() method does not take into account the route authentication configuration. It also does not
2318 * perform payload authentication. It is limited to the basic strategy authentication execution. It does not
2319 * include verifying scope, entity, or other route properties.
2320 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverauthteststrategy-request)
2321 */
2322 test(strategy: string, request: Request): Promise<AuthenticationData>;
2323
2324 /**
2325 * Verify a request's authentication credentials against an authentication strategy.
2326 * Returns nothing if verification was successful, otherwise throws an error.
2327 *
2328 * Note that the `verify()` method does not take into account the route authentication configuration
2329 * or any other information from the request other than the `request.auth` object. It also does not
2330 * perform payload authentication. It is limited to verifying that the previously valid credentials
2331 * are still valid (e.g. have not been revoked or expired). It does not include verifying scope,
2332 * entity, or other route properties.
2333 */
2334 // tslint:disable-next-line no-unnecessary-generics
2335 verify <Refs extends ReqRef = ReqRefDefaults>(request: Request<Refs>): Promise<void>;
2336}
2337
2338export type CachePolicyOptions<T> = PolicyOptionVariants<T> & {
2339 /**
2340 * @default '_default'
2341 */
2342 cache?: string | undefined;
2343 segment?: string | undefined;
2344};
2345
2346/**
2347 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions)
2348 */
2349export interface ServerCache {
2350 /**
2351 * Provisions a cache segment within the server cache facility where:
2352 * @param options - [catbox policy](https://github.com/hapijs/catbox#policy) configuration where:
2353 * * expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt.
2354 * * 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.
2355 * * 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:
2356 * - `id` - the `id` string or object provided to the `get()` method.
2357 * - `flags` - an object used to pass back additional flags to the cache where:
2358 * - `ttl` - the cache ttl value in milliseconds. Set to `0` to skip storing in the cache. Defaults to the cache global policy.
2359 * * 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.
2360 * * staleTimeout - number of milliseconds to wait before checking if an item is stale.
2361 * * 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
2362 * 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.
2363 * * 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.
2364 * * 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.
2365 * * dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true.
2366 * * 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
2367 * concurrent generateFunc calls beyond staleTimeout).
2368 * * cache - the cache name configured in server.cache. Defaults to the default cache.
2369 * * 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
2370 * server method, defaults to '#name' where 'name' is the server method name. Required when called outside of a plugin.
2371 * * shared - if true, allows multiple cache provisions to share the same segment. Default to false.
2372 * @return Catbox Policy.
2373 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions)
2374 */
2375 <T, O extends CachePolicyOptions<T> = CachePolicyOptions<T>>(options: O): Policy<T, O>;
2376
2377 /**
2378 * Provisions a server cache as described in server.cache where:
2379 * @param options - same as the server cache configuration options.
2380 * @return Return value: none.
2381 * 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.
2382 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servercacheprovisionoptions)
2383 */
2384 provision(options: ServerOptionsCache): Promise<void>;
2385}
2386
2387/**
2388 * an event name string.
2389 * an event options object.
2390 * a podium emitter object.
2391 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents)
2392 */
2393export type ServerEventsApplication = string | ServerEventsApplicationObject | Podium;
2394
2395/**
2396 * Object that it will be used in Event
2397 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventevents)
2398 */
2399export interface ServerEventsApplicationObject {
2400 /** the event name string (required). */
2401 name: string;
2402 /** a string or array of strings specifying the event channels available. Defaults to no channel restrictions (event updates can specify a channel or not). */
2403 channels?: string | string[] | undefined;
2404 /**
2405 * 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).
2406 */
2407 clone?: boolean | undefined;
2408 /**
2409 * 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
2410 * 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).
2411 */
2412 spread?: boolean | undefined;
2413 /**
2414 * 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
2415 * the arguments list at the end. A configuration override can be set by each listener. Defaults to false.
2416 */
2417 tags?: boolean | undefined;
2418 /**
2419 * 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
2420 * configuration is used. Defaults to false (a duplicate registration will throw an error).
2421 */
2422 shared?: boolean | undefined;
2423}
2424
2425/**
2426 * A criteria object with the following optional keys (unless noted otherwise):
2427 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener)
2428 *
2429 * The type parameter T is the type of the name of the event.
2430 */
2431export interface ServerEventCriteria<T> {
2432 /** (required) the event name string. */
2433 name: T;
2434 /**
2435 * 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
2436 * channels. If channels are specified, event updates without any channel designation will not be included in the subscription. Defaults to no channels filter.
2437 */
2438 channels?: string | string[] | undefined;
2439 /** 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). */
2440 clone?: boolean | undefined;
2441 /**
2442 * 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().
2443 * Defaults to no limit.
2444 */
2445 count?: number | undefined;
2446 /**
2447 * filter - the event tags (if present) to subscribe to which can be one of:
2448 * * a tag string.
2449 * * an array of tag strings.
2450 * * an object with the following:
2451 * * * tags - a tag string or array of tag strings.
2452 * * * all - if true, all tags must be present for the event update to match the subscription. Defaults to false (at least one matching tag).
2453 */
2454 filter?: string | string[] | { tags: string | string[] | undefined, all?: boolean | undefined } | undefined;
2455 /**
2456 * 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
2457 * when the emitted data structure is known and predictable. Defaults to the event registration option (which defaults to false).
2458 */
2459 spread?: boolean | undefined;
2460 /**
2461 * 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
2462 * to the arguments list at the end. Defaults to the event registration option (which defaults to false).
2463 */
2464 tags?: boolean | undefined;
2465}
2466
2467export interface LogEvent {
2468 /** the event timestamp. */
2469 timestamp: string;
2470 /** an array of tags identifying the event (e.g. ['error', 'http']) */
2471 tags: string[];
2472 /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */
2473 channel: 'internal' | 'app';
2474 /** the request identifier. */
2475 request: string;
2476 /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */
2477 data: object;
2478 /** the error object related to the event if applicable. Cannot appear together with data */
2479 error: object;
2480}
2481
2482export interface RequestEvent {
2483 /** the event timestamp. */
2484 timestamp: string;
2485 /** an array of tags identifying the event (e.g. ['error', 'http']) */
2486 tags: string[];
2487 /** set to 'internal' for internally generated events, otherwise 'app' for events generated by server.log() */
2488 channel: 'internal' | 'app' | 'error';
2489 /** event-specific information. Available when event data was provided and is not an error. Errors are passed via error. */
2490 data: object;
2491 /** the error object related to the event if applicable. Cannot appear together with data */
2492 error: object;
2493}
2494
2495export type LogEventHandler = (event: LogEvent, tags: { [key: string]: true }) => void;
2496export type RequestEventHandler = (request: Request, event: RequestEvent, tags: { [key: string]: true }) => void;
2497export type ResponseEventHandler = (request: Request) => void;
2498export type RouteEventHandler = (route: RequestRoute) => void;
2499export type StartEventHandler = () => void;
2500export type StopEventHandler = () => void;
2501
2502export interface PodiumEvent<K extends string, T> {
2503 emit(criteria: K, listener: (value: T) => void): void;
2504
2505 on(criteria: K, listener: (value: T) => void): void;
2506
2507 once(criteria: K, listener: (value: T) => void): void;
2508
2509 once(criteria: K): Promise<T>;
2510
2511 removeListener(criteria: K, listener: Podium.Listener): this;
2512
2513 removeAllListeners(criteria: K): this;
2514
2515 hasListeners(criteria: K): this;
2516}
2517
2518/**
2519 * Access: podium public interface.
2520 * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters.
2521 * Use the following methods to interact with server.events:
2522 * [server.event(events)](https://github.com/hapijs/hapi/blob/master/API.md#server.event()) - register application events.
2523 * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events.
2524 * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events.
2525 * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to
2526 * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name).
2527 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
2528 */
2529export interface ServerEvents extends Podium {
2530 /**
2531 * Subscribe to an event where:
2532 * @param criteria - the subscription criteria which must be one of:
2533 * * event name string which can be any of the built-in server events
2534 * * a custom application event registered with server.event().
2535 * * a criteria object
2536 * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options.
2537 * @return Return value: none.
2538 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncriteria-listener)
2539 * See ['log' event](https://github.com/hapijs/hapi/blob/master/API.md#-log-event)
2540 * See ['request' event](https://github.com/hapijs/hapi/blob/master/API.md#-request-event)
2541 * See ['response' event](https://github.com/hapijs/hapi/blob/master/API.md#-response-event)
2542 * See ['route' event](https://github.com/hapijs/hapi/blob/master/API.md#-route-event)
2543 * See ['start' event](https://github.com/hapijs/hapi/blob/master/API.md#-start-event)
2544 * See ['stop' event](https://github.com/hapijs/hapi/blob/master/API.md#-stop-event)
2545 */
2546 on(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): this;
2547
2548 on(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): this;
2549
2550 on(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): this;
2551
2552 on(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): this;
2553
2554 on(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): this;
2555
2556 on(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): this;
2557
2558 /**
2559 * 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.
2560 * @param criteria - the subscription criteria which must be one of:
2561 * * event name string which can be any of the built-in server events
2562 * * a custom application event registered with server.event().
2563 * * a criteria object
2564 * @param listener - the handler method set to receive event updates. The function signature depends on the event argument, and the spread and tags options.
2565 * @return Return value: none.
2566 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servereventsoncecriteria-listener)
2567 */
2568 once(criteria: 'log' | ServerEventCriteria<'log'>, listener: LogEventHandler): this;
2569
2570 once(criteria: 'request' | ServerEventCriteria<'request'>, listener: RequestEventHandler): this;
2571
2572 once(criteria: 'response' | ServerEventCriteria<'response'>, listener: ResponseEventHandler): this;
2573
2574 once(criteria: 'route' | ServerEventCriteria<'route'>, listener: RouteEventHandler): this;
2575
2576 once(criteria: 'start' | ServerEventCriteria<'start'>, listener: StartEventHandler): this;
2577
2578 once(criteria: 'stop' | ServerEventCriteria<'stop'>, listener: StopEventHandler): this;
2579
2580 /**
2581 * Same as calling server.events.on() with the count option set to 1.
2582 * @param criteria - the subscription criteria which must be one of:
2583 * * event name string which can be any of the built-in server events
2584 * * a custom application event registered with server.event().
2585 * * a criteria object
2586 * @return Return value: a promise that resolves when the event is emitted.
2587 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-servereventsoncecriteria)
2588 */
2589 once(criteria: string | ServerEventCriteria<string>): Promise<any>;
2590
2591 /**
2592 * 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)
2593 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
2594 */
2595 removeListener(name: string, listener: Podium.Listener): this;
2596
2597 /**
2598 * 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)
2599 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
2600 */
2601 removeAllListeners(name: string): this;
2602
2603 /**
2604 * 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)
2605 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
2606 */
2607 hasListeners(name: string): boolean;
2608}
2609
2610/**
2611 * The extension point event name. The available extension points include the request extension points as well as the following server extension points:
2612 * 'onPreStart' - called before the connection listeners are started.
2613 * 'onPostStart' - called after the connection listeners are started.
2614 * 'onPreStop' - called before the connection listeners are stopped.
2615 * 'onPostStop' - called after the connection listeners are stopped.
2616 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
2617 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle)
2618 */
2619export type ServerExtType = 'onPreStart' | 'onPostStart' | 'onPreStop' | 'onPostStop';
2620export type RouteRequestExtType = 'onPreAuth'
2621 | 'onCredentials'
2622 | 'onPostAuth'
2623 | 'onPreHandler'
2624 | 'onPostHandler'
2625 | 'onPreResponse'
2626 | 'onPostResponse';
2627
2628export type ServerRequestExtType =
2629 RouteRequestExtType
2630 | 'onRequest';
2631
2632/**
2633 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
2634 * Registers an extension function in one of the request lifecycle extension points where:
2635 * @param events - an object or array of objects with the following:
2636 * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
2637 * * * 'onPreStart' - called before the connection listeners are started.
2638 * * * 'onPostStart' - called after the connection listeners are started.
2639 * * * 'onPreStop' - called before the connection listeners are stopped.
2640 * * * 'onPostStop' - called after the connection listeners are stopped.
2641 * * 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:
2642 * * * server extension points: async function(server) where:
2643 * * * * server - the server object.
2644 * * * * this - the object provided via options.bind or the current active context set with server.bind().
2645 * * * request extension points: a lifecycle method.
2646 * * options - (optional) an object with the following:
2647 * * * 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.
2648 * * * 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.
2649 * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2650 * * * 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
2651 * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
2652 * @return void
2653 */
2654export interface ServerExtEventsObject {
2655 /**
2656 * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
2657 * * 'onPreStart' - called before the connection listeners are started.
2658 * * 'onPostStart' - called after the connection listeners are started.
2659 * * 'onPreStop' - called before the connection listeners are stopped.
2660 */
2661 type: ServerExtType;
2662 /**
2663 * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is:
2664 * * server extension points: async function(server) where:
2665 * * * server - the server object.
2666 * * * this - the object provided via options.bind or the current active context set with server.bind().
2667 * * request extension points: a lifecycle method.
2668 */
2669 method: ServerExtPointFunction | ServerExtPointFunction[];
2670 options?: ServerExtOptions | undefined;
2671}
2672
2673export interface RouteExtObject<Refs extends ReqRef = ReqRefDefaults> {
2674 method: Lifecycle.Method<Refs>;
2675 options?: ServerExtOptions | undefined;
2676}
2677
2678/**
2679 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
2680 * Registers an extension function in one of the request lifecycle extension points where:
2681 * @param events - an object or array of objects with the following:
2682 * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
2683 * * * 'onPreStart' - called before the connection listeners are started.
2684 * * * 'onPostStart' - called after the connection listeners are started.
2685 * * * 'onPreStop' - called before the connection listeners are stopped.
2686 * * * 'onPostStop' - called after the connection listeners are stopped.
2687 * * 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:
2688 * * * server extension points: async function(server) where:
2689 * * * * server - the server object.
2690 * * * * this - the object provided via options.bind or the current active context set with server.bind().
2691 * * * request extension points: a lifecycle method.
2692 * * options - (optional) an object with the following:
2693 * * * 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.
2694 * * * 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.
2695 * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2696 * * * 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
2697 * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
2698 * @return void
2699 */
2700export interface ServerExtEventsRequestObject {
2701 /**
2702 * (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
2703 * * 'onPreStart' - called before the connection listeners are started.
2704 * * 'onPostStart' - called after the connection listeners are started.
2705 * * 'onPreStop' - called before the connection listeners are stopped.
2706 * * 'onPostStop' - called after the connection listeners are stopped.
2707 */
2708 type: ServerRequestExtType;
2709 /**
2710 * (required) a function or an array of functions to be executed at a specified point during request processing. The required extension function signature is:
2711 * * server extension points: async function(server) where:
2712 * * * server - the server object.
2713 * * * this - the object provided via options.bind or the current active context set with server.bind().
2714 * * request extension points: a lifecycle method.
2715 */
2716 method: Lifecycle.Method | Lifecycle.Method[];
2717 /**
2718 * (optional) an object with the following:
2719 * * 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.
2720 * * 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.
2721 * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2722 * * 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,
2723 * or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
2724 */
2725 options?: ServerExtOptions | undefined;
2726}
2727
2728export type ServerExtPointFunction = (server: Server) => void;
2729
2730/**
2731 * An object with the following:
2732 * * 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.
2733 * * 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.
2734 * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2735 * * 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
2736 * when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to. For context [See
2737 * docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
2738 */
2739export interface ServerExtOptions {
2740 /**
2741 * 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.
2742 */
2743 before?: string | string[] | undefined;
2744 /**
2745 * 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.
2746 */
2747 after?: string | string[] | undefined;
2748 /**
2749 * a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
2750 */
2751 bind?: object | undefined;
2752 /**
2753 * 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
2754 * adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
2755 */
2756 sandbox?: 'server' | 'plugin' | undefined;
2757}
2758
2759/**
2760 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo)
2761 * An object containing information about the server where:
2762 */
2763export interface ServerInfo {
2764 /**
2765 * a unique server identifier (using the format '{hostname}:{pid}:{now base36}').
2766 */
2767 id: string;
2768
2769 /**
2770 * server creation timestamp.
2771 */
2772 created: number;
2773
2774 /**
2775 * server start timestamp (0 when stopped).
2776 */
2777 started: number;
2778
2779 /**
2780 * the connection [port](https://github.com/hapijs/hapi/blob/master/API.md#server.options.port) based on the following rules:
2781 * * before the server has been started: the configured port value.
2782 * * after the server has been started: the actual port assigned when no port is configured or was set to 0.
2783 */
2784 port: number | string;
2785
2786 /**
2787 * The [host](https://github.com/hapijs/hapi/blob/master/API.md#server.options.host) configuration value.
2788 */
2789 host: string;
2790
2791 /**
2792 * the active IP address the connection was bound to after starting. Set to undefined until the server has been
2793 * started or when using a non TCP port (e.g. UNIX domain socket).
2794 */
2795 address: undefined | string;
2796
2797 /**
2798 * the protocol used:
2799 * * 'http' - HTTP.
2800 * * 'https' - HTTPS.
2801 * * 'socket' - UNIX domain socket or Windows named pipe.
2802 */
2803 protocol: 'http' | 'https' | 'socket';
2804
2805 /**
2806 * a string representing the connection (e.g. 'http://example.com:8080' or 'socket:/unix/domain/socket/path'). Contains
2807 * the uri value if set, otherwise constructed from the available settings. If no port is configured or is set
2808 * to 0, the uri will not include a port component until the server is started.
2809 */
2810 uri: string;
2811}
2812
2813/**
2814 * An object with:
2815 * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'.
2816 * * 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.
2817 * * 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.
2818 * * 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
2819 * processing defaults to 'application/json' if no 'Content-Type' header provided.
2820 * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as if
2821 * they were received via an authentication scheme. Defaults to no credentials.
2822 * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly as
2823 * if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.
2824 * * app - (optional) sets the initial value of request.app, defaults to {}.
2825 * * plugins - (optional) sets the initial value of request.plugins, defaults to {}.
2826 * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false.
2827 * * remoteAddress - (optional) sets the remote address for the incoming connection.
2828 * * simulate - (optional) an object with options used to simulate client request stream conditions for testing:
2829 * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false.
2830 * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false.
2831 * * end - if false, does not end the stream. Defaults to true.
2832 * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked.
2833 * * 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
2834 * separately.
2835 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions)
2836 * For context [Shot module](https://github.com/hapijs/shot)
2837 */
2838export interface ServerInjectOptions extends Shot.RequestOptions {
2839 /**
2840 * Authentication bypass options.
2841 */
2842 auth?: {
2843 /**
2844 * The authentication strategy name matching the provided credentials.
2845 */
2846 strategy: string;
2847 /**
2848 * The credentials are used to bypass the default authentication strategies,
2849 * and are validated directly as if they were received via an authentication scheme.
2850 */
2851 credentials: AuthCredentials;
2852 /**
2853 * The artifacts are used to bypass the default authentication strategies,
2854 * and are validated directly as if they were received via an authentication scheme. Defaults to no artifacts.
2855 */
2856 artifacts?: AuthArtifacts | undefined;
2857 } | undefined;
2858 /**
2859 * sets the initial value of request.app, defaults to {}.
2860 */
2861 app?: RequestApplicationState | undefined;
2862 /**
2863 * sets the initial value of request.plugins, defaults to {}.
2864 */
2865 plugins?: PluginsStates | undefined;
2866 /**
2867 * allows access to routes with config.isInternal set to true. Defaults to false.
2868 */
2869 allowInternals?: boolean | undefined;
2870}
2871
2872/**
2873 * A response object with the following properties:
2874 * * statusCode - the HTTP status code.
2875 * * headers - an object containing the headers set.
2876 * * payload - the response payload string.
2877 * * rawPayload - the raw response payload buffer.
2878 * * raw - an object with the injection request and response objects:
2879 * * req - the simulated node request object.
2880 * * res - the simulated node response object.
2881 * * 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
2882 * the internal objects returned (instead of parsing the response string).
2883 * * request - the request object.
2884 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions)
2885 * For context [Shot module](https://github.com/hapijs/shot)
2886 */
2887export interface ServerInjectResponse<Result = object> extends Shot.ResponseObject {
2888 /**
2889 * 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
2890 * internal objects returned (instead of parsing the response string).
2891 */
2892 result: Result | undefined;
2893 /**
2894 * the request object.
2895 */
2896 request: Request;
2897}
2898
2899/**
2900 * The method function with a signature async function(...args, [flags]) where:
2901 * * ...args - the method function arguments (can be any number of arguments or none).
2902 * * flags - when caching is enabled, an object used to set optional method result flags:
2903 * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy.
2904 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options)
2905 */
2906export type ServerMethod = (...args: any[]) => any;
2907
2908/**
2909 * The same cache configuration used in server.cache().
2910 * The generateTimeout option is required.
2911 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options)
2912 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions)
2913 */
2914export interface ServerMethodCache extends PolicyOptions<any> {
2915 generateTimeout: number | false;
2916}
2917
2918/**
2919 * Configuration object:
2920 * * 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
2921 * arrow function.
2922 * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required.
2923 * * 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
2924 * 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
2925 * which takes the same arguments as the function and returns a unique string (or null if no key can be generated). For reference [See
2926 * docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options)
2927 */
2928export interface ServerMethodOptions {
2929 /**
2930 * 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
2931 * function.
2932 */
2933 bind?: object | undefined;
2934 /**
2935 * the same cache configuration used in server.cache(). The generateTimeout option is required.
2936 */
2937 cache?: ServerMethodCache | undefined;
2938 /**
2939 * 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
2940 * 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
2941 * takes the same arguments as the function and returns a unique string (or null if no key can be generated).
2942 */
2943 generateKey?(...args: any[]): string | null;
2944}
2945
2946/**
2947 * An object or an array of objects where each one contains:
2948 * * name - the method name.
2949 * * method - the method function.
2950 * * options - (optional) settings.
2951 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods)
2952 */
2953export interface ServerMethodConfigurationObject {
2954 /**
2955 * the method name.
2956 */
2957 name: string;
2958 /**
2959 * the method function.
2960 */
2961 method: ServerMethod;
2962 /**
2963 * (optional) settings.
2964 */
2965 options?: ServerMethodOptions | undefined;
2966}
2967
2968export type CacheProvider<T extends ClientOptions = ClientOptions> = EnginePrototype<any> | {
2969 constructor: EnginePrototype<any>;
2970 options?: T | undefined;
2971};
2972
2973/**
2974 * hapi uses catbox for its cache implementation which includes support for common storage solutions (e.g. Redis,
2975 * MongoDB, Memcached, Riak, among others). Caching is only utilized if methods and plugins explicitly store their state in the cache.
2976 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-cache)
2977 */
2978export interface ServerOptionsCache extends PolicyOptions<any> {
2979 /** catbox engine object. */
2980 engine?: ClientApi<any> | undefined;
2981
2982 /**
2983 * a class or a prototype function
2984 */
2985 provider?: CacheProvider | undefined;
2986
2987 /**
2988 * 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
2989 * the default cache. If every cache includes a name, a default memory cache is provisioned as well.
2990 */
2991 name?: string | undefined;
2992
2993 /** if true, allows multiple cache users to share the same segment (e.g. multiple methods using the same cache storage container). Default to false. */
2994 shared?: boolean | undefined;
2995
2996 /** (optional) string used to isolate cached data. Defaults to 'hapi-cache'. */
2997 partition?: string | undefined;
2998
2999 /** 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). */
3000 [s: string]: any;
3001}
3002
3003export interface ServerOptionsCompression {
3004 minBytes: number;
3005}
3006
3007/**
3008 * Empty interface to allow for custom augmentation.
3009 */
3010
3011// tslint:disable-next-line no-empty-interface
3012export interface ServerOptionsApp {
3013}
3014
3015export type SameSitePolicy = false | 'None' | 'Lax' | 'Strict';
3016
3017/**
3018 * The server options control the behavior of the server object. Note that the options object is deeply cloned
3019 * (with the exception of listener which is shallowly copied) and should not contain any values that are unsafe to perform deep copy on.
3020 * All options are optionals.
3021 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-server-options)
3022 */
3023export interface ServerOptions {
3024 /**
3025 * @default '0.0.0.0' (all available network interfaces).
3026 * 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
3027 * restrict the server to only those coming from the same host.
3028 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsaddress)
3029 */
3030 address?: string | undefined;
3031
3032 /**
3033 * @default {}.
3034 * 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
3035 * 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
3036 * state.
3037 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsapp)
3038 */
3039 app?: ServerOptionsApp | undefined;
3040
3041 /**
3042 * @default true.
3043 * Used to disable the automatic initialization of the listener. When false, indicates that the listener will be started manually outside the framework.
3044 * Cannot be set to true along with a port value.
3045 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsautolisten)
3046 */
3047 autoListen?: boolean | undefined;
3048
3049 /**
3050 * @default { engine: require('@hapi/catbox-memory' }.
3051 * 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
3052 * 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
3053 * 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
3054 * (array):
3055 * * a class or prototype function (usually obtained by calling require() on a catbox strategy such as require('@hapi/catbox-redis')). A new catbox client will be created internally using this
3056 * function.
3057 * * a configuration object with the following:
3058 * * * engine - a class, a prototype function, or a catbox engine object.
3059 * * * 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
3060 * the default cache. If every cache includes a name, a default memory cache is provisioned as well.
3061 * * * 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.
3062 * * * partition - (optional) string used to isolate cached data. Defaults to 'hapi-cache'.
3063 * * * 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).
3064 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionscache)
3065 */
3066 cache?: CacheProvider | ServerOptionsCache | ServerOptionsCache[] | undefined;
3067
3068 /**
3069 * @default { minBytes: 1024 }.
3070 * Defines server handling of content encoding requests. If false, response content encoding is disabled and no compression is performed by the server.
3071 */
3072 compression?: boolean | ServerOptionsCompression | undefined;
3073
3074 /**
3075 * @default { request: ['implementation'] }.
3076 * 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
3077 * disable all console logging, or to an object with:
3078 * * 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.
3079 * * 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
3080 * 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
3081 * 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
3082 * 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
3083 * false.
3084 */
3085 debug?: false | {
3086 log?: string[] | false | undefined;
3087 request?: string[] | false | undefined;
3088 } | undefined;
3089
3090 /**
3091 * @default the operating system hostname and if not available, to 'localhost'.
3092 * The public hostname or IP address. Used to set server.info.host and server.info.uri and as address is none provided.
3093 */
3094 host?: string | undefined;
3095
3096 /**
3097 * @default none.
3098 * An optional node HTTP (or HTTPS) http.Server object (or an object with a compatible interface).
3099 * If the listener needs to be manually started, set autoListen to false.
3100 * If the listener uses TLS, set tls to true.
3101 */
3102 listener?: http.Server | undefined;
3103
3104 /**
3105 * @default { sampleInterval: 0 }.
3106 * Server excessive load handling limits where:
3107 * * sampleInterval - the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling).
3108 * * maxHeapUsedBytes - maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).
3109 * * maxRssBytes - maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).
3110 * * 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).
3111 */
3112 load?: {
3113 /** the frequency of sampling in milliseconds. When set to 0, the other load options are ignored. Defaults to 0 (no sampling). */
3114 sampleInterval?: number | undefined;
3115
3116 /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */
3117 maxHeapUsedBytes?: number | undefined;
3118 /**
3119 * maximum process RSS size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit).
3120 */
3121 maxRssBytes?: number | undefined;
3122 /**
3123 * maximum event loop delay duration in milliseconds over which incoming requests are rejected with an HTTP Server Timeout (503) response.
3124 * Defaults to 0 (no limit).
3125 */
3126 maxEventLoopDelay?: number | undefined;
3127 } | undefined;
3128
3129 /**
3130 * @default none.
3131 * Options passed to the mimos module when generating the mime database used by the server (and accessed via server.mime):
3132 * * 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:
3133 * * key - the lower-cased mime-type string (e.g. 'application/javascript').
3134 * * value - an object following the specifications outlined here. Additional values include:
3135 * * * type - specify the type value of result objects, defaults to key.
3136 * * * predicate - method with signature function(mime) when this mime type is found in the database, this function will execute to allows customizations.
3137 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsmime)
3138 */
3139 mime?: MimosOptions | undefined;
3140
3141 /**
3142 * @default {}.
3143 * 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
3144 * difference between server.settings.plugins which is used to store static configuration values and server.plugins which is meant for storing run-time state.
3145 */
3146 plugins?: PluginSpecificConfiguration | undefined;
3147
3148 /**
3149 * @default 0 (an ephemeral port).
3150 * The TCP port the server will listen to. Defaults the next available port when the server is started (and assigned to server.info.port).
3151 * 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.
3152 */
3153 port?: number | string | undefined;
3154
3155 /**
3156 * @default { isCaseSensitive: true, stripTrailingSlash: false }.
3157 * Controls how incoming request URIs are matched against the routing table:
3158 * * isCaseSensitive - determines whether the paths '/example' and '/EXAMPLE' are considered different resources. Defaults to true.
3159 * * stripTrailingSlash - removes trailing slashes on incoming paths. Defaults to false.
3160 */
3161 router?: {
3162 isCaseSensitive?: boolean | undefined;
3163 stripTrailingSlash?: boolean | undefined;
3164 } | undefined;
3165
3166 /**
3167 * @default none.
3168 * A route options object used as the default configuration for every route.
3169 */
3170 routes?: RouteOptions | undefined;
3171
3172 /**
3173 * Default value:
3174 * {
3175 * strictHeader: true,
3176 * ignoreErrors: false,
3177 * isSecure: true,
3178 * isHttpOnly: true,
3179 * isSameSite: 'Strict',
3180 * encoding: 'none'
3181 * }
3182 * Sets the default configuration for every state (cookie) set explicitly via server.state() or implicitly (without definition) using the state configuration object.
3183 */
3184 // 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.
3185 // state?: ServerStateCookieOptions;
3186 state?: {
3187 strictHeader?: boolean | undefined,
3188 ignoreErrors?: boolean | undefined,
3189 isSecure?: boolean | undefined,
3190 isHttpOnly?: boolean | undefined,
3191 isSameSite?: SameSitePolicy | undefined,
3192 encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron' | undefined
3193 };
3194
3195 /**
3196 * @default none.
3197 * Used to create an HTTPS connection. The tls object is passed unchanged to the node HTTPS server as described in the node HTTPS documentation.
3198 */
3199 tls?: boolean | https.ServerOptions | undefined;
3200
3201 /**
3202 * @default constructed from runtime server information.
3203 * 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.
3204 */
3205 uri?: string | undefined;
3206
3207 /**
3208 * Query parameter configuration.
3209 */
3210 query?: {
3211 /**
3212 * the method must return an object where each key is a parameter and matching value is the parameter value.
3213 * If the method throws, the error is used as the response or returned when `request.setUrl` is called.
3214 */
3215 parser(raw: Util.Dictionary<string>): Util.Dictionary<any>;
3216 } | undefined;
3217}
3218
3219/**
3220 * 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
3221 * 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
3222 * 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
3223 * and extensions added at the same level (server root or plugin).
3224 *
3225 * https://github.com/hapijs/hapi/blob/master/API.md#server.realm
3226 */
3227export interface ServerRealm {
3228 /** 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: */
3229 modifiers: {
3230 /** routes preferences: */
3231 route: {
3232 /**
3233 * 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
3234 * the trailing slash.
3235 */
3236 prefix: string;
3237 /** the route virtual host settings used by any calls to server.route() from the server. */
3238 vhost: string;
3239 }
3240 };
3241 /** the realm of the parent server object, or null for the root server. */
3242 parent: ServerRealm | null;
3243 /** the active plugin name (empty string if at the server root). */
3244 plugin: string;
3245 /** the plugin options object passed at registration. */
3246 pluginOptions: object;
3247 /** 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. */
3248 plugins: PluginsStates;
3249 /** settings overrides */
3250 settings: {
3251 files: {
3252 relativeTo: string;
3253 };
3254 bind: object;
3255 };
3256}
3257
3258/**
3259 * Registration options (different from the options passed to the registration function):
3260 * * 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
3261 * second time a plugin is registered on the server.
3262 * * routes - modifiers applied to each route added by the plugin:
3263 * * * 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
3264 * prefix.
3265 * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
3266 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options)
3267 */
3268export interface ServerRegisterOptions {
3269 /**
3270 * 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
3271 * time a plugin is registered on the server.
3272 */
3273 once?: boolean | undefined;
3274 /**
3275 * modifiers applied to each route added by the plugin:
3276 */
3277 routes?: {
3278 /**
3279 * 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.
3280 */
3281 prefix: string;
3282 /**
3283 * virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
3284 */
3285 vhost?: string | string[] | undefined;
3286 } | undefined;
3287}
3288
3289/**
3290 * An object with the following:
3291 * * plugin - a plugin object.
3292 * * options - (optional) options passed to the plugin during registration.
3293 * * 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
3294 * second time a plugin is registered on the server.
3295 * * routes - modifiers applied to each route added by the plugin:
3296 * * * 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
3297 * prefix.
3298 * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
3299 * For reference [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options)
3300 *
3301 * The type parameter T is the type of the plugin configuration options.
3302 */
3303export interface ServerRegisterPluginObject<T> extends ServerRegisterOptions {
3304 /**
3305 * a plugin object.
3306 */
3307 plugin: Plugin<T>;
3308 /**
3309 * options passed to the plugin during registration.
3310 */
3311 options?: T | undefined;
3312}
3313
3314export type ServerRegisterPluginObjectArray<T, U, V, W, X, Y, Z> = Array<
3315 ServerRegisterPluginObject<T> |
3316 ServerRegisterPluginObject<U> |
3317 ServerRegisterPluginObject<V> |
3318 ServerRegisterPluginObject<W> |
3319 ServerRegisterPluginObject<X> |
3320 ServerRegisterPluginObject<Y> |
3321 ServerRegisterPluginObject<Z>
3322>;
3323
3324// tslint:disable-next-line no-empty-interface
3325export interface HandlerDecorations {}
3326
3327// tslint:disable-next-line no-empty-interface
3328export interface RouteRules {}
3329
3330export interface RulesInfo {
3331 method: string;
3332 path: string;
3333 vhost: string;
3334}
3335
3336export interface RulesOptions<Refs extends ReqRef = ReqRefDefaults> {
3337 validate: {
3338 schema?: ObjectSchema<MergeRefs<Refs>['Rules']> | Record<keyof MergeRefs<Refs>['Rules'], Schema>;
3339 options?: ValidationOptions;
3340 };
3341}
3342
3343export interface RulesProcessor<Refs extends ReqRef = ReqRefDefaults> {
3344 (rules: MergeRefs<Refs>['Rules'] | null, info: RulesInfo): Partial<RouteOptions<Refs>> | null;
3345}
3346
3347/**
3348 * A route configuration object or an array of configuration objects where each object contains:
3349 * * 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
3350 * path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.
3351 * * 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
3352 * 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
3353 * result as adding the same route with different methods manually.
3354 * * 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
3355 * header only (excluding the port). Defaults to all hosts.
3356 * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation.
3357 * * 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
3358 * added to and this is bound to the current realm's bind option.
3359 * * 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.
3360 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute)
3361 */
3362export interface ServerRoute<Refs extends ReqRef = ReqRefDefaults> {
3363 /**
3364 * (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
3365 * can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters. For context [See
3366 * 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)
3367 */
3368 path: string;
3369
3370 /**
3371 * (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
3372 * (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
3373 * result as adding the same route with different methods manually.
3374 */
3375 method: Util.HTTP_METHODS_PARTIAL | Util.HTTP_METHODS_PARTIAL[] | string | string[];
3376
3377 /**
3378 * (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
3379 * only (excluding the port). Defaults to all hosts.
3380 */
3381 vhost?: string | string[] | undefined;
3382
3383 /**
3384 * (required when handler is not set) the route handler function called to generate the response after successful authentication and validation.
3385 */
3386 handler?: Lifecycle.Method<Refs> | HandlerDecorations | undefined;
3387
3388 /**
3389 * 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
3390 * and this is bound to the current realm's bind option.
3391 */
3392 options?: RouteOptions<Refs> | ((server: Server) => RouteOptions<Refs>) | undefined;
3393
3394 /**
3395 * 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.
3396 */
3397 rules?: Refs['Rules'] | undefined;
3398}
3399
3400/**
3401 * Optional cookie settings
3402 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options)
3403 */
3404export interface ServerStateCookieOptions {
3405 /** time-to-live in milliseconds. Defaults to null (session time-life - cookies are deleted when the browser is closed). */
3406 ttl?: number | null | undefined;
3407 /** sets the 'Secure' flag. Defaults to true. */
3408 isSecure?: boolean | undefined;
3409 /** sets the 'HttpOnly' flag. Defaults to true. */
3410 isHttpOnly?: boolean | undefined;
3411 /**
3412 * sets the 'SameSite' flag. The value must be one of:
3413 * * false - no flag.
3414 * * 'Strict' - sets the value to 'Strict' (this is the default value).
3415 * * 'Lax' - sets the value to 'Lax'.
3416 */
3417 isSameSite?: SameSitePolicy | undefined;
3418 /** the path scope. Defaults to null (no path). */
3419 path?: string | null | undefined;
3420 /** the domain scope. Defaults to null (no domain). */
3421 domain?: string | null | undefined;
3422
3423 /**
3424 * if present and the cookie was not received from the client or explicitly set by the route handler, the
3425 * cookie is automatically added to the response with the provided value. The value can be
3426 * a function with signature async function(request) where:
3427 */
3428 autoValue?(request: Request): void;
3429
3430 /**
3431 * encoding performs on the provided value before serialization. Options are:
3432 * * 'none' - no encoding. When used, the cookie value must be a string. This is the default value.
3433 * * 'base64' - string value is encoded using Base64.
3434 * * 'base64json' - object value is JSON-stringified then encoded using Base64.
3435 * * 'form' - object value is encoded using the x-www-form-urlencoded method.
3436 * * 'iron' - Encrypts and sign the value using iron.
3437 */
3438 encoding?: 'none' | 'base64' | 'base64json' | 'form' | 'iron' | undefined;
3439 /**
3440 * an object used to calculate an HMAC for cookie integrity validation. This does not provide privacy, only a mean
3441 * to verify that the cookie value was generated by the server. Redundant when 'iron' encoding is used. Options are:
3442 * * integrity - algorithm options. Defaults to require('@hapi/iron').defaults.integrity.
3443 * * password - password used for HMAC key generation (must be at least 32 characters long).
3444 */
3445 sign?: {
3446 integrity?: SealOptionsSub | undefined;
3447 password: string;
3448 } | undefined;
3449 /** password used for 'iron' encoding (must be at least 32 characters long). */
3450 password?: string | undefined;
3451 /** options for 'iron' encoding. Defaults to require('@hapi/iron').defaults. */
3452 iron?: SealOptions | undefined;
3453 /** if true, errors are ignored and treated as missing cookies. */
3454 ignoreErrors?: boolean | undefined;
3455 /** if true, automatically instruct the client to remove invalid cookies. Defaults to false. */
3456 clearInvalid?: boolean | undefined;
3457 /** if false, allows any cookie value including values in violation of RFC 6265. Defaults to true. */
3458 strictHeader?: boolean | undefined;
3459 /** used by proxy plugins (e.g. h2o2). */
3460 passThrough?: any;
3461}
3462
3463/**
3464 * A single object or an array of object where each contains:
3465 * * name - the cookie name.
3466 * * value - the cookie value.
3467 * * options - cookie configuration to override the server settings.
3468 */
3469export interface ServerStateFormat {
3470 name: string;
3471 value: string;
3472 options: ServerStateCookieOptions;
3473}
3474
3475/**
3476 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options)
3477 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptionsstate)
3478 */
3479export interface ServerState {
3480 /**
3481 * The server cookies manager.
3482 * Access: read only and statehood public interface.
3483 */
3484 readonly states: object;
3485
3486 /**
3487 * 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).
3488 */
3489 readonly settings: ServerStateCookieOptions;
3490
3491 /**
3492 * 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
3493 * cookie name and value is the configuration object.
3494 */
3495 readonly cookies: {
3496 [key: string]: ServerStateCookieOptions;
3497 };
3498
3499 /**
3500 * An array containing the names of all configured cookies.
3501 */
3502 readonly names: string[];
3503
3504 /**
3505 * Same as calling [server.state()](https://github.com/hapijs/hapi/blob/master/API.md#server.state()).
3506 */
3507 add(name: string, options?: ServerStateCookieOptions): void;
3508
3509 /**
3510 * Formats an HTTP 'Set-Cookie' header based on the server.options.state where:
3511 * @param cookies - a single object or an array of object where each contains:
3512 * * name - the cookie name.
3513 * * value - the cookie value.
3514 * * options - cookie configuration to override the server settings.
3515 * @return Return value: a header string.
3516 * Note that this utility uses the server configuration but does not change the server state. It is provided for manual cookie formatting (e.g. when headers are set manually).
3517 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesformatcookies)
3518 */
3519 format(cookies: ServerStateFormat | ServerStateFormat[]): Promise<string>;
3520
3521 /**
3522 * Parses an HTTP 'Cookies' header based on the server.options.state where:
3523 * @param header - the HTTP header.
3524 * @return Return value: an object where each key is a cookie name and value is the parsed cookie.
3525 * 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).
3526 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-async-serverstatesparseheader)
3527 */
3528 parse(header: string): Promise<Util.Dictionary<string>>;
3529}
3530
3531/**
3532 * The method function can have a defaults object or function property. If the property is set to an object, that object is used as the default route config for routes using this handler.
3533 * If the property is set to a function, the function uses the signature function(method) and returns the route default configuration.
3534 */
3535export interface HandlerDecorationMethod {
3536 (route: RequestRoute, options: any): Lifecycle.Method;
3537 defaults?: RouteOptions | ((method: any) => RouteOptions) | undefined;
3538}
3539
3540/**
3541 * The general case for decorators added via server.decorate.
3542 */
3543export type DecorationMethod<T> = (this: T, ...args: any[]) => any;
3544
3545/**
3546 * An empty interface to allow typings of custom plugin properties.
3547 */
3548
3549// tslint:disable-next-line no-empty-interface
3550export interface PluginProperties {
3551}
3552
3553/**
3554 * An empty interface to allow typings of custom server.methods.
3555 */
3556// tslint:disable-next-line no-empty-interface
3557export interface ServerMethods extends Util.Dictionary<ServerMethod> {
3558}
3559
3560export type DecorateName = string | symbol;
3561
3562/**
3563 * The server object is the main application container. The server manages all incoming requests along with all
3564 * the facilities provided by the framework. Each server supports a single connection (e.g. listen to port 80).
3565 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#server)
3566 */
3567export class Server {
3568 /**
3569 * Creates a new server object
3570 * @param options server configuration object.
3571 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serveroptions)
3572 */
3573 constructor(options?: ServerOptions);
3574
3575 /**
3576 * Provides a safe place to store server-specific run-time application data without potential conflicts with
3577 * the framework internals. The data can be accessed whenever the server is accessible.
3578 * Initialized with an empty object.
3579 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverapp)
3580 */
3581 app: ServerApplicationState;
3582
3583 /**
3584 * Server Auth: properties and methods
3585 */
3586 readonly auth: ServerAuth;
3587
3588 /**
3589 * Links another server to the initialize/start/stop state of the current server by calling the
3590 * controlled server `initialize()`/`start()`/`stop()` methods whenever the current server methods
3591 * are called, where:
3592 */
3593 control(server: Server): void;
3594
3595 /**
3596 * Provides access to the decorations already applied to various framework interfaces. The object must not be
3597 * modified directly, but only through server.decorate.
3598 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecorations)
3599 */
3600 readonly decorations: {
3601 /**
3602 * decorations on the request object.
3603 */
3604 request: string[],
3605 /**
3606 * decorations on the response toolkit.
3607 */
3608 toolkit: string[],
3609 /**
3610 * decorations on the server object.
3611 */
3612 server: string[]
3613 };
3614
3615 /**
3616 * Register custom application events where:
3617 * @param events must be one of:
3618 * * an event name string.
3619 * * an event options object with the following optional keys (unless noted otherwise):
3620 * * * name - the event name string (required).
3621 * * * 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).
3622 * * * 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
3623 * passed as-is).
3624 * * * 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
3625 * 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
3626 * type).
3627 * * * 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
3628 * appended to the arguments list at the end. A configuration override can be set by each listener. Defaults to false.
3629 * * * 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
3630 * the first configuration is used. Defaults to false (a duplicate registration will throw an error).
3631 * * a podium emitter object.
3632 * * an array containing any of the above.
3633 * @return Return value: none.
3634 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
3635 */
3636 event(events: ServerEventsApplication | ServerEventsApplication[]): void;
3637
3638 /**
3639 * Access: podium public interface.
3640 * The server events emitter. Utilizes the podium with support for event criteria validation, channels, and filters.
3641 * Use the following methods to interact with server.events:
3642 * [server.events.emit(criteria, data)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.emit()) - emit server events.
3643 * [server.events.on(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.on()) - subscribe to all events.
3644 * [server.events.once(criteria, listener)](https://github.com/hapijs/hapi/blob/master/API.md#server.events.once()) - subscribe to
3645 * Other methods include: server.events.removeListener(name, listener), server.events.removeAllListeners(name), and server.events.hasListeners(name).
3646 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverevents)
3647 */
3648 events: ServerEvents;
3649
3650 /**
3651 * An object containing information about the server where:
3652 * * id - a unique server identifier (using the format '{hostname}:{pid}:{now base36}').
3653 * * created - server creation timestamp.
3654 * * started - server start timestamp (0 when stopped).
3655 * * port - the connection port based on the following rules:
3656 * * host - The host configuration value.
3657 * * 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).
3658 * * protocol - the protocol used:
3659 * * 'http' - HTTP.
3660 * * 'https' - HTTPS.
3661 * * 'socket' - UNIX domain socket or Windows named pipe.
3662 * * 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
3663 * settings. If no port is configured or is set to 0, the uri will not include a port component until the server is started.
3664 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverinfo)
3665 */
3666 readonly info: ServerInfo;
3667
3668 /**
3669 * Access: read only and listener public interface.
3670 * The node HTTP server object.
3671 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlistener)
3672 */
3673 listener: http.Server;
3674
3675 /**
3676 * An object containing the process load metrics (when load.sampleInterval is enabled):
3677 * * eventLoopDelay - event loop delay milliseconds.
3678 * * heapUsed - V8 heap usage.
3679 * * rss - RSS memory usage.
3680 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverload)
3681 */
3682 readonly load: {
3683 /**
3684 * event loop delay milliseconds.
3685 */
3686 eventLoopDelay: number;
3687
3688 /**
3689 * V8 heap usage.
3690 */
3691 heapUsed: number;
3692 /**
3693 * RSS memory usage.
3694 */
3695 rss: number;
3696 };
3697
3698 /**
3699 * Server methods are functions registered with the server and used throughout the application as a common utility.
3700 * Their advantage is in the ability to configure them to use the built-in cache and share across multiple request
3701 * handlers without having to create a common module.
3702 * sever.methods is an object which provides access to the methods registered via server.method() where each
3703 * server method name is an object property.
3704 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethods
3705 */
3706 readonly methods: ServerMethods;
3707
3708 /**
3709 * Provides access to the server MIME database used for setting content-type information. The object must not be
3710 * modified directly but only through the [mime](https://github.com/hapijs/hapi/blob/master/API.md#server.options.mime) server setting.
3711 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermime)
3712 */
3713 mime: any;
3714
3715 /**
3716 * An object containing the values exposed by each registered plugin where each key is a plugin name and the values
3717 * are the exposed properties by each plugin using server.expose(). Plugins may set the value of
3718 * the server.plugins[name] object directly or via the server.expose() method.
3719 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverplugins)
3720 */
3721 plugins: PluginProperties;
3722
3723 /**
3724 * The realm object contains sandboxed server settings specific to each plugin or authentication strategy. When
3725 * registering a plugin or an authentication scheme, a server object reference is provided with a new server.realm
3726 * container specific to that registration. It allows each plugin to maintain its own settings without leaking
3727 * and affecting other plugins.
3728 * For example, a plugin can set a default file path for local resources without breaking other plugins' configured
3729 * paths. When calling server.bind(), the active realm's settings.bind property is set which is then used by
3730 * routes and extensions added at the same level (server root or plugin).
3731 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrealm)
3732 */
3733 readonly realm: ServerRealm;
3734
3735 /**
3736 * An object of the currently registered plugins where each key is a registered plugin name and the value is
3737 * an object containing:
3738 * * version - the plugin version.
3739 * * name - the plugin name.
3740 * * options - (optional) options passed to the plugin during registration.
3741 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverregistrations)
3742 */
3743 readonly registrations: PluginsListRegistered;
3744
3745 /**
3746 * The server configuration object after defaults applied.
3747 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serversettings)
3748 */
3749 readonly settings: ServerOptions;
3750
3751 /**
3752 * The server cookies manager.
3753 * Access: read only and statehood public interface.
3754 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstates)
3755 */
3756 readonly states: ServerState;
3757
3758 /**
3759 * A string indicating the listener type where:
3760 * * 'socket' - UNIX domain socket or Windows named pipe.
3761 * * 'tcp' - an HTTP listener.
3762 */
3763 readonly type: 'socket' | 'tcp';
3764
3765 /**
3766 * The hapi module version number.
3767 */
3768 readonly version: string;
3769
3770 /**
3771 * Sets a global context used as the default bind object when adding a route or an extension where:
3772 * @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.
3773 * @return Return value: none.
3774 * 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.
3775 * Ignored if the method being bound is an arrow function.
3776 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverbindcontext)
3777 */
3778 bind(context: object): void;
3779
3780 /**
3781 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servercacheoptions)
3782 */
3783 cache: ServerCache;
3784
3785 /**
3786 * Registers a custom content decoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
3787 * @param encoding - the decoder name string.
3788 * @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
3789 * return value is an object compatible with the output of node's zlib.createGunzip().
3790 * @return Return value: none.
3791 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoderencoding-decoder)
3792 */
3793 decoder(encoding: string, decoder: ((options: PayloadCompressionDecoderSettings) => zlib.Gunzip)): void;
3794
3795 /**
3796 * Extends various framework interfaces with custom methods where:
3797 * @param type - the interface being decorated. Supported types:
3798 * 'handler' - adds a new handler type to be used in routes handlers.
3799 * 'request' - adds methods to the Request object.
3800 * 'server' - adds methods to the Server object.
3801 * 'toolkit' - adds methods to the response toolkit.
3802 * @param property - the object decoration key name.
3803 * @param method - the extension function or other value.
3804 * @param options - (optional) supports the following optional settings:
3805 * 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
3806 * 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
3807 * decoration method value. must return the new decoration function or value. cannot be used to extend handler decorations.
3808 * @return void;
3809 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdecoratetype-property-method-options)
3810 */
3811 decorate(type: 'handler', property: DecorateName, method: HandlerDecorationMethod, options?: {apply?: boolean | undefined, extend?: boolean | undefined}): void;
3812 decorate(type: 'request', property: DecorateName, method: (existing: ((...args: any[]) => any)) => (request: Request) => DecorationMethod<Request>, options: {apply: true, extend: true}): void;
3813 decorate(type: 'request', property: DecorateName, method: (request: Request) => DecorationMethod<Request>, options: {apply: true, extend?: boolean | undefined}): void;
3814 decorate(type: 'request', property: DecorateName, method: DecorationMethod<Request>, options?: {apply?: boolean | undefined, extend?: boolean | undefined}): void;
3815 decorate(type: 'toolkit', property: DecorateName, method: (existing: ((...args: any[]) => any)) => DecorationMethod<ResponseToolkit>, options: {apply?: boolean | undefined, extend: true}): void;
3816 decorate(type: 'toolkit', property: DecorateName, method: DecorationMethod<ResponseToolkit>, options?: {apply?: boolean | undefined, extend?: boolean | undefined}): void;
3817 decorate(type: 'server', property: DecorateName, method: (existing: ((...args: any[]) => any)) => DecorationMethod<Server>, options: {apply?: boolean | undefined, extend: true}): void;
3818 decorate(type: 'server', property: DecorateName, method: DecorationMethod<Server>, options?: {apply?: boolean | undefined, extend?: boolean | undefined}): void;
3819
3820 /**
3821 * Used within a plugin to declare a required dependency on other plugins where:
3822 * @param dependencies - plugins which must be registered in order for this plugin to operate. Plugins listed must be registered before the server is
3823 * initialized or started.
3824 * @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
3825 * initialized or started. The function signature is async function(server) where: server - the server the dependency() method was called on.
3826 * @return Return value: none.
3827 * The after method is identical to setting a server extension point on 'onPreStart'.
3828 * 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).
3829 * The method does not provide version dependency which should be implemented using npm peer dependencies.
3830 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverdependencydependencies-after)
3831 */
3832 dependency(dependencies: Dependencies, after?: ((server: Server) => Promise<void>)): void;
3833
3834 /**
3835 * Registers a custom content encoding compressor to extend the built-in support for 'gzip' and 'deflate' where:
3836 * @param encoding - the encoder name string.
3837 * @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
3838 * compatible with the output of node's zlib.createGzip().
3839 * @return Return value: none.
3840 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverencoderencoding-encoder)
3841 */
3842 encoder(encoding: string, encoder: ((options: RouteCompressionEncoderSettings) => zlib.Gzip)): void;
3843
3844 /**
3845 * Used within a plugin to expose a property via server.plugins[name] where:
3846 * @param key - the key assigned (server.plugins[name][key]).
3847 * @param value - the value assigned.
3848 * @return Return value: none.
3849 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposekey-value)
3850 */
3851 expose(key: string, value: any): void;
3852
3853 /**
3854 * Merges an object into to the existing content of server.plugins[name] where:
3855 * @param obj - the object merged into the exposed properties container.
3856 * @return Return value: none.
3857 * Note that all the properties of obj are deeply cloned into server.plugins[name], so avoid using this method
3858 * for exposing large objects that may be expensive to clone or singleton objects such as database client
3859 * objects. Instead favor server.expose(key, value), which only copies a reference to value.
3860 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverexposeobj)
3861 */
3862 expose(obj: object): void;
3863
3864 /**
3865 * Registers an extension function in one of the request lifecycle extension points where:
3866 * @param events - an object or array of objects with the following:
3867 * * type - (required) the extension point event name. The available extension points include the request extension points as well as the following server extension points:
3868 * * * 'onPreStart' - called before the connection listeners are started.
3869 * * * 'onPostStart' - called after the connection listeners are started.
3870 * * * 'onPreStop' - called before the connection listeners are stopped.
3871 * * * 'onPostStop' - called after the connection listeners are stopped.
3872 * * 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:
3873 * * * server extension points: async function(server) where:
3874 * * * * server - the server object.
3875 * * * * this - the object provided via options.bind or the current active context set with server.bind().
3876 * * * request extension points: a lifecycle method.
3877 * * options - (optional) an object with the following:
3878 * * * 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.
3879 * * * 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.
3880 * * * bind - a context object passed back to the provided method (via this) when called. Ignored if the method is an arrow function.
3881 * * * 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
3882 * extensions, or when adding server extensions. Defaults to 'server' which applies to any route added to the server the extension is added to.
3883 * @return void
3884 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevents)
3885 */
3886 ext(events: ServerExtEventsObject | ServerExtEventsObject[] | ServerExtEventsRequestObject | ServerExtEventsRequestObject[]): void;
3887
3888 /**
3889 * Registers a single extension event using the same properties as used in server.ext(events), but passed as arguments.
3890 * @return Return value: none.
3891 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverextevent-method-options)
3892 */
3893 ext(event: ServerExtType, method: ServerExtPointFunction, options?: ServerExtOptions): void;
3894 ext(event: ServerRequestExtType, method: Lifecycle.Method, options?: ServerExtOptions): void;
3895
3896 /**
3897 * Initializes the server (starts the caches, finalizes plugin registration) but does not start listening on the connection port.
3898 * @return Return value: none.
3899 * Note that if the method fails and throws an error, the server is considered to be in an undefined state and
3900 * should be shut down. In most cases it would be impossible to fully recover as the various plugins, caches, and
3901 * other event listeners will get confused by repeated attempts to start the server or make assumptions about the
3902 * healthy state of the environment. It is recommended to abort the process when the server fails to start properly.
3903 * If you must try to resume after an error, call server.stop() first to reset the server state.
3904 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinitialize)
3905 */
3906 initialize(): Promise<void>;
3907
3908 /**
3909 * 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
3910 * 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:
3911 * @param options - can be assigned a string with the requested URI, or an object with:
3912 * * method - (optional) the request HTTP method (e.g. 'POST'). Defaults to 'GET'.
3913 * * 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.
3914 * * 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.
3915 * * 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
3916 * processing defaults to 'application/json' if no 'Content-Type' header provided.
3917 * * credentials - (optional) an credentials object containing authentication information. The credentials are used to bypass the default authentication strategies, and are validated directly as
3918 * if they were received via an authentication scheme. Defaults to no credentials.
3919 * * artifacts - (optional) an artifacts object containing authentication artifact information. The artifacts are used to bypass the default authentication strategies, and are validated directly
3920 * as if they were received via an authentication scheme. Ignored if set without credentials. Defaults to no artifacts.
3921 * * app - (optional) sets the initial value of request.app, defaults to {}.
3922 * * plugins - (optional) sets the initial value of request.plugins, defaults to {}.
3923 * * allowInternals - (optional) allows access to routes with config.isInternal set to true. Defaults to false.
3924 * * remoteAddress - (optional) sets the remote address for the incoming connection.
3925 * * simulate - (optional) an object with options used to simulate client request stream conditions for testing:
3926 * * error - if true, emits an 'error' event after payload transmission (if any). Defaults to false.
3927 * * close - if true, emits a 'close' event after payload transmission (if any). Defaults to false.
3928 * * end - if false, does not end the stream. Defaults to true.
3929 * * split - indicates whether the request payload will be split into chunks. Defaults to undefined, meaning payload will not be chunked.
3930 * * 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
3931 * separately.
3932 * @return Return value: a response object with the following properties:
3933 * * statusCode - the HTTP status code.
3934 * * headers - an object containing the headers set.
3935 * * payload - the response payload string.
3936 * * rawPayload - the raw response payload buffer.
3937 * * raw - an object with the injection request and response objects:
3938 * * req - the simulated node request object.
3939 * * res - the simulated node response object.
3940 * * 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
3941 * of the internal objects returned (instead of parsing the response string).
3942 * * request - the request object.
3943 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverinjectoptions)
3944 */
3945 // tslint:disable-next-line no-unnecessary-generics
3946 inject <Result = object>(options: string | ServerInjectOptions): Promise<ServerInjectResponse<Result>>;
3947
3948 /**
3949 * 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
3950 * output to the console. The arguments are:
3951 * @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
3952 * mechanism for describing and filtering events. Any logs generated by the server internally include the 'hapi' tag along with event-specific information.
3953 * @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
3954 * value) the actual data emitted to the listeners. If no listeners match the event, the data function is not invoked.
3955 * @param timestamp - (optional) an timestamp expressed in milliseconds. Defaults to Date.now() (now).
3956 * @return Return value: none.
3957 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlogtags-data-timestamp)
3958 */
3959 log(tags: string | string[], data?: string | object | (() => any), timestamp?: number): void;
3960
3961 /**
3962 * Looks up a route configuration where:
3963 * @param id - the route identifier.
3964 * @return Return value: the route information if found, otherwise null.
3965 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverlookupid)
3966 */
3967 lookup(id: string): RequestRoute | null;
3968
3969 /**
3970 * Looks up a route configuration where:
3971 * @param method - the HTTP method (e.g. 'GET', 'POST').
3972 * @param path - the requested path (must begin with '/').
3973 * @param host - (optional) hostname (to match against routes with vhost).
3974 * @return Return value: the route information if found, otherwise null.
3975 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermatchmethod-path-host)
3976 */
3977 match(method: Util.HTTP_METHODS, path: string, host?: string): RequestRoute | null;
3978
3979 /**
3980 * Registers a server method where:
3981 * @param name - a unique method name used to invoke the method via server.methods[name].
3982 * @param method - the method function with a signature async function(...args, [flags]) where:
3983 * * ...args - the method function arguments (can be any number of arguments or none).
3984 * * flags - when caching is enabled, an object used to set optional method result flags:
3985 * * * ttl - 0 if result is valid but cannot be cached. Defaults to cache policy.
3986 * @param options - (optional) configuration object:
3987 * * 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
3988 * an arrow function.
3989 * * cache - the same cache configuration used in server.cache(). The generateTimeout option is required.
3990 * * 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
3991 * 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
3992 * 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).
3993 * @return Return value: none.
3994 * 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).
3995 * 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
3996 * the cache for a given key. - stats - an object with cache statistics, see catbox for stats documentation.
3997 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodname-method-options)
3998 */
3999 method(name: string, method: ServerMethod, options?: ServerMethodOptions): void;
4000
4001 /**
4002 * Registers a server method function as described in server.method() using a configuration object where:
4003 * @param methods - an object or an array of objects where each one contains:
4004 * * name - the method name.
4005 * * method - the method function.
4006 * * options - (optional) settings.
4007 * @return Return value: none.
4008 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servermethodmethods)
4009 */
4010 method(methods: ServerMethodConfigurationObject | ServerMethodConfigurationObject[]): void;
4011
4012 /**
4013 * Sets the path prefix used to locate static resources (files and view templates) when relative paths are used where:
4014 * @param relativeTo - the path prefix added to any relative file path starting with '.'.
4015 * @return Return value: none.
4016 * 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
4017 * path only applies to routes added after it has been set.
4018 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverpathrelativeto)
4019 */
4020 path(relativeTo: string): void;
4021
4022 /**
4023 * Registers a plugin where:
4024 * @param plugins - one or an array of:
4025 * * a plugin object.
4026 * * an object with the following:
4027 * * * plugin - a plugin object.
4028 * * * options - (optional) options passed to the plugin during registration.
4029 * * * once, routes - (optional) plugin-specific registration options as defined below.
4030 * @param options - (optional) registration options (different from the options passed to the registration function):
4031 * * 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
4032 * second time a plugin is registered on the server.
4033 * * routes - modifiers applied to each route added by the plugin:
4034 * * * 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
4035 * child-specific prefix.
4036 * * * vhost - virtual host string (or array of strings) applied to every route. The outer-most vhost overrides the any nested configuration.
4037 * @return Return value: none.
4038 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverregisterplugins-options)
4039 */
4040 /* tslint:disable-next-line:no-unnecessary-generics */
4041 register<T>(plugin: ServerRegisterPluginObject<T>, options?: ServerRegisterOptions): Promise<void>;
4042 /* tslint:disable-next-line:no-unnecessary-generics */
4043 register<T, U, V, W, X, Y, Z>(plugins: ServerRegisterPluginObjectArray<T, U, V, W, X, Y, Z>, options?: ServerRegisterOptions): Promise<void>;
4044 register(plugins: Array<ServerRegisterPluginObject<any>>, options?: ServerRegisterOptions): Promise<void>;
4045 /* tslint:disable-next-line:unified-signatures */
4046 register(plugins: Plugin<any> | Array<Plugin<any>>, options?: ServerRegisterOptions): Promise<void>;
4047
4048 /**
4049 * Adds a route where:
4050 * @param route - a route configuration object or an array of configuration objects where each object contains:
4051 * * 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.
4052 * The path can include named parameters enclosed in {} which will be matched against literal values in the request as described in Path parameters.
4053 * * 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
4054 * 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
4055 * the same result as adding the same route with different methods manually.
4056 * * 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
4057 * header only (excluding the port). Defaults to all hosts.
4058 * * handler - (required when handler is not set) the route handler function called to generate the response after successful authentication and validation.
4059 * * 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
4060 * added to and this is bound to the current realm's bind option.
4061 * * 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.
4062 * @return Return value: none.
4063 * 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.
4064 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrouteroute)
4065 */
4066
4067 // tslint:disable-next-line:no-unnecessary-generics
4068 route <Refs extends ReqRef = ReqRefDefaults>(route: ServerRoute<Refs> | Array<ServerRoute<Refs>>): void;
4069
4070 /**
4071 * Defines a route rules processor for converting route rules object into route configuration where:
4072 * @param processor - a function using the signature function(rules, info) where:
4073 * * rules -
4074 * * info - an object with the following properties:
4075 * * * method - the route method.
4076 * * * path - the route path.
4077 * * * vhost - the route virtual host (if any defined).
4078 * * returns a route config object.
4079 * @param options - optional settings:
4080 * * validate - rules object validation:
4081 * * * schema - joi schema.
4082 * * * options - optional joi validation options. Defaults to { allowUnknown: true }.
4083 * 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.
4084 * 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
4085 * by the root processor if they overlap. The route config overrides the rules config if the overlap.
4086 * @return void
4087 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverrulesprocessor-options)
4088 */
4089 rules <Refs extends ReqRef = ReqRefDefaults>(
4090 processor: RulesProcessor<Refs>,
4091 options?: RulesOptions<Refs>
4092 ): void;
4093
4094 /**
4095 * Starts the server by listening for incoming requests on the configured port (unless the connection was configured with autoListen set to false).
4096 * @return Return value: none.
4097 * 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
4098 * 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
4099 * 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
4100 * is started again, the second call to server.start() is ignored. No events will be emitted and no extension points invoked.
4101 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstart)
4102 */
4103 start(): Promise<void>;
4104
4105 /**
4106 * HTTP state management uses client cookies to persist a state across multiple requests.
4107 * @param name - the cookie name string.
4108 * @param options - are the optional cookie settings
4109 * @return Return value: none.
4110 * State defaults can be modified via the server default state configuration option.
4111 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-serverstatename-options)
4112 */
4113 state(name: string, options?: ServerStateCookieOptions): void;
4114
4115 /**
4116 * Stops the server's listener by refusing to accept any new connections or requests (existing connections will continue until closed or timeout), where:
4117 * @param options - (optional) object with:
4118 * * timeout - overrides the timeout in millisecond before forcefully terminating a connection. Defaults to 5000 (5 seconds).
4119 * @return Return value: none.
4120 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-await-serverstopoptions)
4121 */
4122 stop(options?: {timeout: number}): Promise<void>;
4123
4124 /**
4125 * Returns a copy of the routing table where:
4126 * @param host - (optional) host to filter routes matching a specific virtual host. Defaults to all virtual hosts.
4127 * @return Return value: an array of routes where each route contains:
4128 * * settings - the route config with defaults applied.
4129 * * method - the HTTP method in lower case.
4130 * * path - the route path.
4131 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-servertablehost)
4132 */
4133 table(host?: string): RequestRoute[];
4134
4135 /**
4136 * Registers a server validation module used to compile raw validation rules into validation schemas for all routes.
4137 * The validator is only used when validation rules are not pre-compiled schemas. When a validation rules is a function or schema object, the rule is used as-is and the validator is not used.
4138 */
4139 validator(joi: Root): void;
4140}
4141
4142/**
4143 * Factory function to create a new server object (introduced in v17).
4144 */
4145export function server(opts?: ServerOptions): Server;
4146
4147/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
4148 + +
4149 + +
4150 + +
4151 + Utils +
4152 + +
4153 + +
4154 + +
4155 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + */
4156
4157/**
4158 * User-extensible type for application specific state (`server.app`).
4159 */
4160
4161// tslint:disable-next-line no-empty-interface
4162export interface ServerApplicationState {
4163}
4164
4165/**
4166 * User-extensible type for application specific state on requests (`request.app`).
4167 */
4168
4169// tslint:disable-next-line no-empty-interface
4170export interface RequestApplicationState {
4171}
4172
4173/**
4174 * User-extensible type for application specific state on responses (`response.app`).
4175 */
4176
4177// tslint:disable-next-line no-empty-interface
4178export interface ResponseApplicationState {
4179}
4180
4181export type PeekListener = (chunk: string, encoding: string) => void;
4182
4183export namespace Json {
4184 /**
4185 * @see {@link https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter}
4186 */
4187 type StringifyReplacer = ((key: string, value: any) => any) | Array<(string | number)> | undefined;
4188
4189 /**
4190 * Any value greater than 10 is truncated.
4191 */
4192 type StringifySpace = number | string;
4193
4194 /**
4195 * For context [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-routeoptionsjson)
4196 */
4197 interface StringifyArguments {
4198 /** the replacer function or array. Defaults to no action. */
4199 replacer?: StringifyReplacer | undefined;
4200 /** number of spaces to indent nested object keys. Defaults to no indentation. */
4201 space?: StringifySpace | undefined;
4202 /* string suffix added after conversion to JSON string. Defaults to no suffix. */
4203 suffix?: string | undefined;
4204 /* calls Hoek.jsonEscape() after conversion to JSON string. Defaults to false. */
4205 escape?: boolean | undefined;
4206 }
4207}
4208
4209export namespace Lifecycle {
4210 /**
4211 * Lifecycle methods are the interface between the framework and the application. Many of the request lifecycle steps:
4212 * extensions, authentication, handlers, pre-handler methods, and failAction function values are lifecycle methods
4213 * provided by the developer and executed by the framework.
4214 * Each lifecycle method is a function with the signature await function(request, h, [err]) where:
4215 * * request - the request object.
4216 * * h - the response toolkit the handler must call to set a response and return control back to the framework.
4217 * * err - an error object available only when the method is used as a failAction value.
4218 */
4219 type Method<
4220 Refs extends ReqRef = ReqRefDefaults,
4221 R extends ReturnValue<any> = ReturnValue<Refs>
4222 > = (
4223 this: MergeRefs<Refs>['Bind'],
4224 request: Request<Refs>,
4225 h: ResponseToolkit<Refs>,
4226 err?: Error
4227 ) => R;
4228
4229 /**
4230 * Each lifecycle method must return a value or a promise that resolves into a value. If a lifecycle method returns
4231 * without a value or resolves to an undefined value, an Internal Server Error (500) error response is sent.
4232 * The return value must be one of:
4233 * - Plain value: null, string, number, boolean
4234 * - Buffer object
4235 * - Error object: plain Error OR a Boom object.
4236 * - Stream object
4237 * - any object or array
4238 * - a toolkit signal:
4239 * - a toolkit method response:
4240 * - a promise object that resolve to any of the above values
4241 * For more info please [See docs](https://github.com/hapijs/hapi/blob/master/API.md#lifecycle-methods)
4242 */
4243 type ReturnValue<Refs extends ReqRef = ReqRefDefaults> = ReturnValueTypes<Refs> | (Promise<ReturnValueTypes<Refs>>);
4244 type ReturnValueTypes<Refs extends ReqRef = ReqRefDefaults> =
4245 (null | string | number | boolean) |
4246 (Buffer) |
4247 (Error | Boom) |
4248 (stream.Stream) |
4249 (object | object[]) |
4250 symbol |
4251 Auth<
4252 MergeRefs<Refs>['AuthUser'],
4253 MergeRefs<Refs>['AuthApp'],
4254 MergeRefs<Refs>['AuthCredentialsExtra'],
4255 MergeRefs<Refs>['AuthArtifactsExtra']
4256 > |
4257 ResponseObject;
4258
4259 /**
4260 * 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
4261 * configured to perform another action. When supported the failAction option supports the following values:
4262 * * 'error' - return the error object as the response.
4263 * * 'log' - report the error but continue processing the request.
4264 * * 'ignore' - take no action and continue processing the request.
4265 * * a lifecycle method with the signature async function(request, h, err) where:
4266 * * * request - the request object.
4267 * * * h - the response toolkit.
4268 * * * err - the error object.
4269 * [See docs](https://github.com/hapijs/hapi/blob/master/API.md#-failaction-configuration)
4270 */
4271 type FailAction = 'error' | 'log' | 'ignore' | Method;
4272}
4273
4274export namespace Util {
4275 interface Dictionary<T> {
4276 [key: string]: T;
4277 }
4278
4279 type HTTP_METHODS_PARTIAL_LOWERCASE = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'options';
4280 type HTTP_METHODS_PARTIAL =
4281 'GET'
4282 | 'POST'
4283 | 'PUT'
4284 | 'PATCH'
4285 | 'DELETE'
4286 | 'OPTIONS'
4287 | HTTP_METHODS_PARTIAL_LOWERCASE;
4288 type HTTP_METHODS = 'HEAD' | 'head' | HTTP_METHODS_PARTIAL;
4289}
4290
\No newline at end of file