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 perfor