UNPKG

40.7 kBTypeScriptView Raw
1// Type definitions for Express 4.17
2// Project: http://expressjs.com
3// Definitions by: Boris Yankov <https://github.com/borisyankov>
4// Satana Charuwichitratana <https://github.com/micksatana>
5// Sami Jaber <https://github.com/samijaber>
6// Jose Luis Leon <https://github.com/JoseLion>
7// David Stephens <https://github.com/dwrss>
8// Shin Ando <https://github.com/andoshin11>
9// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
10// TypeScript Version: 2.3
11
12// This extracts the core definitions from express to prevent a circular dependency between express and serve-static
13/// <reference types="node" />
14
15declare global {
16 namespace Express {
17 // These open interfaces may be extended in an application-specific manner via declaration merging.
18 // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/method-override/index.d.ts)
19 interface Request {}
20 interface Response {}
21 interface Application {}
22 }
23}
24
25import * as http from 'http';
26import { EventEmitter } from 'events';
27import { Options as RangeParserOptions, Result as RangeParserResult, Ranges as RangeParserRanges } from 'range-parser';
28import { ParsedQs } from 'qs';
29
30export {};
31
32export type Query = ParsedQs;
33
34export interface NextFunction {
35 (err?: any): void;
36 /**
37 * "Break-out" of a router by calling {next('router')};
38 * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.router}
39 */
40 (deferToNext: 'router'): void;
41 /**
42 * "Break-out" of a route by calling {next('route')};
43 * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.application}
44 */
45 (deferToNext: 'route'): void;
46}
47
48export interface Dictionary<T> {
49 [key: string]: T;
50}
51
52export interface ParamsDictionary {
53 [key: string]: string;
54}
55export type ParamsArray = string[];
56export type Params = ParamsDictionary | ParamsArray;
57
58export interface RequestHandler<
59 P = ParamsDictionary,
60 ResBody = any,
61 ReqBody = any,
62 ReqQuery = ParsedQs,
63 Locals extends Record<string, any> = Record<string, any>
64> {
65 // tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2)
66 (
67 req: Request<P, ResBody, ReqBody, ReqQuery, Locals>,
68 res: Response<ResBody, Locals>,
69 next: NextFunction,
70 ): void;
71}
72
73export type ErrorRequestHandler<
74 P = ParamsDictionary,
75 ResBody = any,
76 ReqBody = any,
77 ReqQuery = ParsedQs,
78 Locals extends Record<string, any> = Record<string, any>
79> = (
80 err: any,
81 req: Request<P, ResBody, ReqBody, ReqQuery, Locals>,
82 res: Response<ResBody, Locals>,
83 next: NextFunction,
84) => void;
85
86export type PathParams = string | RegExp | Array<string | RegExp>;
87
88export type RequestHandlerParams<
89 P = ParamsDictionary,
90 ResBody = any,
91 ReqBody = any,
92 ReqQuery = ParsedQs,
93 Locals extends Record<string, any> = Record<string, any>
94> =
95 | RequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>
96 | ErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>
97 | Array<RequestHandler<P> | ErrorRequestHandler<P>>;
98
99type RemoveTail<S extends string, Tail extends string> = S extends `${infer P}${Tail}` ? P : S;
100type GetRouteParameter<S extends string> = RemoveTail<
101 RemoveTail<RemoveTail<S, `/${string}`>, `-${string}`>,
102 `.${string}`
103>;
104
105// prettier-ignore
106export type RouteParameters<Route extends string> = string extends Route
107 ? ParamsDictionary
108 : Route extends `${string}(${string}`
109 ? ParamsDictionary //TODO: handling for regex parameters
110 : Route extends `${string}:${infer Rest}`
111 ? (
112 GetRouteParameter<Rest> extends never
113 ? ParamsDictionary
114 : GetRouteParameter<Rest> extends `${infer ParamName}?`
115 ? { [P in ParamName]?: string }
116 : { [P in GetRouteParameter<Rest>]: string }
117 ) &
118 (Rest extends `${GetRouteParameter<Rest>}${infer Next}`
119 ? RouteParameters<Next> : unknown)
120 : {};
121
122export interface IRouterMatcher<
123 T,
124 Method extends 'all' | 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head' = any
125> {
126 <
127 Route extends string,
128 P = RouteParameters<Route>,
129 ResBody = any,
130 ReqBody = any,
131 ReqQuery = ParsedQs,
132 Locals extends Record<string, any> = Record<string, any>
133 >(
134 // tslint:disable-next-line no-unnecessary-generics (it's used as the default type parameter for P)
135 path: Route,
136 // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
137 ...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>>
138 ): T;
139 <
140 Path extends string,
141 P = RouteParameters<Path>,
142 ResBody = any,
143 ReqBody = any,
144 ReqQuery = ParsedQs,
145 Locals extends Record<string, any> = Record<string, any>
146 >(
147 // tslint:disable-next-line no-unnecessary-generics (it's used as the default type parameter for P)
148 path: Path,
149 // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
150 ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, Locals>>
151 ): T;
152 <
153 P = ParamsDictionary,
154 ResBody = any,
155 ReqBody = any,
156 ReqQuery = ParsedQs,
157 Locals extends Record<string, any> = Record<string, any>
158 >(
159 path: PathParams,
160 // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
161 ...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>>
162 ): T;
163 <
164 P = ParamsDictionary,
165 ResBody = any,
166 ReqBody = any,
167 ReqQuery = ParsedQs,
168 Locals extends Record<string, any> = Record<string, any>
169 >(
170 path: PathParams,
171 // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
172 ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, Locals>>
173 ): T;
174 (path: PathParams, subApplication: Application): T;
175}
176
177export interface IRouterHandler<T, Route extends string = string> {
178 (...handlers: Array<RequestHandler<RouteParameters<Route>>>): T;
179 (...handlers: Array<RequestHandlerParams<RouteParameters<Route>>>): T;
180 <
181 P = RouteParameters<Route>,
182 ResBody = any,
183 ReqBody = any,
184 ReqQuery = ParsedQs,
185 Locals extends Record<string, any> = Record<string, any>
186 >(
187 // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
188 ...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>>
189 ): T;
190 <
191 P = RouteParameters<Route>,
192 ResBody = any,
193 ReqBody = any,
194 ReqQuery = ParsedQs,
195 Locals extends Record<string, any> = Record<string, any>
196 >(
197 // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
198 ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, Locals>>
199 ): T;
200 <
201 P = ParamsDictionary,
202 ResBody = any,
203 ReqBody = any,
204 ReqQuery = ParsedQs,
205 Locals extends Record<string, any> = Record<string, any>
206 >(
207 // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
208 ...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery, Locals>>
209 ): T;
210 <
211 P = ParamsDictionary,
212 ResBody = any,
213 ReqBody = any,
214 ReqQuery = ParsedQs,
215 Locals extends Record<string, any> = Record<string, any>
216 >(
217 // tslint:disable-next-line no-unnecessary-generics (This generic is meant to be passed explicitly.)
218 ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, Locals>>
219 ): T;
220}
221
222export interface IRouter extends RequestHandler {
223 /**
224 * Map the given param placeholder `name`(s) to the given callback(s).
225 *
226 * Parameter mapping is used to provide pre-conditions to routes
227 * which use normalized placeholders. For example a _:user_id_ parameter
228 * could automatically load a user's information from the database without
229 * any additional code,
230 *
231 * The callback uses the samesignature as middleware, the only differencing
232 * being that the value of the placeholder is passed, in this case the _id_
233 * of the user. Once the `next()` function is invoked, just like middleware
234 * it will continue on to execute the route, or subsequent parameter functions.
235 *
236 * app.param('user_id', function(req, res, next, id){
237 * User.find(id, function(err, user){
238 * if (err) {
239 * next(err);
240 * } else if (user) {
241 * req.user = user;
242 * next();
243 * } else {
244 * next(new Error('failed to load user'));
245 * }
246 * });
247 * });
248 */
249 param(name: string, handler: RequestParamHandler): this;
250
251 /**
252 * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param()
253 *
254 * @deprecated since version 4.11
255 */
256 param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
257
258 /**
259 * Special-cased "all" method, applying the given route `path`,
260 * middleware, and callback to _every_ HTTP method.
261 */
262 all: IRouterMatcher<this, 'all'>;
263 get: IRouterMatcher<this, 'get'>;
264 post: IRouterMatcher<this, 'post'>;
265 put: IRouterMatcher<this, 'put'>;
266 delete: IRouterMatcher<this, 'delete'>;
267 patch: IRouterMatcher<this, 'patch'>;
268 options: IRouterMatcher<this, 'options'>;
269 head: IRouterMatcher<this, 'head'>;
270
271 checkout: IRouterMatcher<this>;
272 connect: IRouterMatcher<this>;
273 copy: IRouterMatcher<this>;
274 lock: IRouterMatcher<this>;
275 merge: IRouterMatcher<this>;
276 mkactivity: IRouterMatcher<this>;
277 mkcol: IRouterMatcher<this>;
278 move: IRouterMatcher<this>;
279 'm-search': IRouterMatcher<this>;
280 notify: IRouterMatcher<this>;
281 propfind: IRouterMatcher<this>;
282 proppatch: IRouterMatcher<this>;
283 purge: IRouterMatcher<this>;
284 report: IRouterMatcher<this>;
285 search: IRouterMatcher<this>;
286 subscribe: IRouterMatcher<this>;
287 trace: IRouterMatcher<this>;
288 unlock: IRouterMatcher<this>;
289 unsubscribe: IRouterMatcher<this>;
290
291 use: IRouterHandler<this> & IRouterMatcher<this>;
292
293 route<T extends string>(prefix: T): IRoute<T>;
294 route(prefix: PathParams): IRoute;
295 /**
296 * Stack of configured routes
297 */
298 stack: any[];
299}
300
301export interface IRoute<Route extends string = string> {
302 path: string;
303 stack: any;
304 all: IRouterHandler<this, Route>;
305 get: IRouterHandler<this, Route>;
306 post: IRouterHandler<this, Route>;
307 put: IRouterHandler<this, Route>;
308 delete: IRouterHandler<this, Route>;
309 patch: IRouterHandler<this, Route>;
310 options: IRouterHandler<this, Route>;
311 head: IRouterHandler<this, Route>;
312
313 checkout: IRouterHandler<this, Route>;
314 copy: IRouterHandler<this, Route>;
315 lock: IRouterHandler<this, Route>;
316 merge: IRouterHandler<this, Route>;
317 mkactivity: IRouterHandler<this, Route>;
318 mkcol: IRouterHandler<this, Route>;
319 move: IRouterHandler<this, Route>;
320 'm-search': IRouterHandler<this, Route>;
321 notify: IRouterHandler<this, Route>;
322 purge: IRouterHandler<this, Route>;
323 report: IRouterHandler<this, Route>;
324 search: IRouterHandler<this, Route>;
325 subscribe: IRouterHandler<this, Route>;
326 trace: IRouterHandler<this, Route>;
327 unlock: IRouterHandler<this, Route>;
328 unsubscribe: IRouterHandler<this, Route>;
329}
330
331export interface Router extends IRouter {}
332
333export interface CookieOptions {
334 maxAge?: number | undefined;
335 signed?: boolean | undefined;
336 expires?: Date | undefined;
337 httpOnly?: boolean | undefined;
338 path?: string | undefined;
339 domain?: string | undefined;
340 secure?: boolean | undefined;
341 encode?: ((val: string) => string) | undefined;
342 sameSite?: boolean | 'lax' | 'strict' | 'none' | undefined;
343}
344
345export interface ByteRange {
346 start: number;
347 end: number;
348}
349
350export interface RequestRanges extends RangeParserRanges {}
351
352export type Errback = (err: Error) => void;
353
354/**
355 * @param P For most requests, this should be `ParamsDictionary`, but if you're
356 * using this in a route handler for a route that uses a `RegExp` or a wildcard
357 * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in
358 * which case you should use `ParamsArray` instead.
359 *
360 * @see https://expressjs.com/en/api.html#req.params
361 *
362 * @example
363 * app.get('/user/:id', (req, res) => res.send(req.params.id)); // implicitly `ParamsDictionary`
364 * app.get<ParamsArray>(/user\/(.*)/, (req, res) => res.send(req.params[0]));
365 * app.get<ParamsArray>('/user/*', (req, res) => res.send(req.params[0]));
366 */
367export interface Request<
368 P = ParamsDictionary,
369 ResBody = any,
370 ReqBody = any,
371 ReqQuery = ParsedQs,
372 Locals extends Record<string, any> = Record<string, any>
373> extends http.IncomingMessage,
374 Express.Request {
375 /**
376 * Return request header.
377 *
378 * The `Referrer` header field is special-cased,
379 * both `Referrer` and `Referer` are interchangeable.
380 *
381 * Examples:
382 *
383 * req.get('Content-Type');
384 * // => "text/plain"
385 *
386 * req.get('content-type');
387 * // => "text/plain"
388 *
389 * req.get('Something');
390 * // => undefined
391 *
392 * Aliased as `req.header()`.
393 */
394 get(name: 'set-cookie'): string[] | undefined;
395 get(name: string): string | undefined;
396
397 header(name: 'set-cookie'): string[] | undefined;
398 header(name: string): string | undefined;
399
400 /**
401 * Check if the given `type(s)` is acceptable, returning
402 * the best match when true, otherwise `undefined`, in which
403 * case you should respond with 406 "Not Acceptable".
404 *
405 * The `type` value may be a single mime type string
406 * such as "application/json", the extension name
407 * such as "json", a comma-delimted list such as "json, html, text/plain",
408 * or an array `["json", "html", "text/plain"]`. When a list
409 * or array is given the _best_ match, if any is returned.
410 *
411 * Examples:
412 *
413 * // Accept: text/html
414 * req.accepts('html');
415 * // => "html"
416 *
417 * // Accept: text/*, application/json
418 * req.accepts('html');
419 * // => "html"
420 * req.accepts('text/html');
421 * // => "text/html"
422 * req.accepts('json, text');
423 * // => "json"
424 * req.accepts('application/json');
425 * // => "application/json"
426 *
427 * // Accept: text/*, application/json
428 * req.accepts('image/png');
429 * req.accepts('png');
430 * // => undefined
431 *
432 * // Accept: text/*;q=.5, application/json
433 * req.accepts(['html', 'json']);
434 * req.accepts('html, json');
435 * // => "json"
436 */
437 accepts(): string[];
438 accepts(type: string): string | false;
439 accepts(type: string[]): string | false;
440 accepts(...type: string[]): string | false;
441
442 /**
443 * Returns the first accepted charset of the specified character sets,
444 * based on the request's Accept-Charset HTTP header field.
445 * If none of the specified charsets is accepted, returns false.
446 *
447 * For more information, or if you have issues or concerns, see accepts.
448 */
449 acceptsCharsets(): string[];
450 acceptsCharsets(charset: string): string | false;
451 acceptsCharsets(charset: string[]): string | false;
452 acceptsCharsets(...charset: string[]): string | false;
453
454 /**
455 * Returns the first accepted encoding of the specified encodings,
456 * based on the request's Accept-Encoding HTTP header field.
457 * If none of the specified encodings is accepted, returns false.
458 *
459 * For more information, or if you have issues or concerns, see accepts.
460 */
461 acceptsEncodings(): string[];
462 acceptsEncodings(encoding: string): string | false;
463 acceptsEncodings(encoding: string[]): string | false;
464 acceptsEncodings(...encoding: string[]): string | false;
465
466 /**
467 * Returns the first accepted language of the specified languages,
468 * based on the request's Accept-Language HTTP header field.
469 * If none of the specified languages is accepted, returns false.
470 *
471 * For more information, or if you have issues or concerns, see accepts.
472 */
473 acceptsLanguages(): string[];
474 acceptsLanguages(lang: string): string | false;
475 acceptsLanguages(lang: string[]): string | false;
476 acceptsLanguages(...lang: string[]): string | false;
477
478 /**
479 * Parse Range header field, capping to the given `size`.
480 *
481 * Unspecified ranges such as "0-" require knowledge of your resource length. In
482 * the case of a byte range this is of course the total number of bytes.
483 * If the Range header field is not given `undefined` is returned.
484 * If the Range header field is given, return value is a result of range-parser.
485 * See more ./types/range-parser/index.d.ts
486 *
487 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
488 * should respond with 4 users when available, not 3.
489 *
490 */
491 range(size: number, options?: RangeParserOptions): RangeParserRanges | RangeParserResult | undefined;
492
493 /**
494 * Return an array of Accepted media types
495 * ordered from highest quality to lowest.
496 */
497 accepted: MediaType[];
498
499 /**
500 * @deprecated since 4.11 Use either req.params, req.body or req.query, as applicable.
501 *
502 * Return the value of param `name` when present or `defaultValue`.
503 *
504 * - Checks route placeholders, ex: _/user/:id_
505 * - Checks body params, ex: id=12, {"id":12}
506 * - Checks query string params, ex: ?id=12
507 *
508 * To utilize request bodies, `req.body`
509 * should be an object. This can be done by using
510 * the `connect.bodyParser()` middleware.
511 */
512 param(name: string, defaultValue?: any): string;
513
514 /**
515 * Check if the incoming request contains the "Content-Type"
516 * header field, and it contains the give mime `type`.
517 *
518 * Examples:
519 *
520 * // With Content-Type: text/html; charset=utf-8
521 * req.is('html');
522 * req.is('text/html');
523 * req.is('text/*');
524 * // => true
525 *
526 * // When Content-Type is application/json
527 * req.is('json');
528 * req.is('application/json');
529 * req.is('application/*');
530 * // => true
531 *
532 * req.is('html');
533 * // => false
534 */
535 is(type: string | string[]): string | false | null;
536
537 /**
538 * Return the protocol string "http" or "https"
539 * when requested with TLS. When the "trust proxy"
540 * setting is enabled the "X-Forwarded-Proto" header
541 * field will be trusted. If you're running behind
542 * a reverse proxy that supplies https for you this
543 * may be enabled.
544 */
545 protocol: string;
546
547 /**
548 * Short-hand for:
549 *
550 * req.protocol == 'https'
551 */
552 secure: boolean;
553
554 /**
555 * Return the remote address, or when
556 * "trust proxy" is `true` return
557 * the upstream addr.
558 */
559 ip: string;
560
561 /**
562 * When "trust proxy" is `true`, parse
563 * the "X-Forwarded-For" ip address list.
564 *
565 * For example if the value were "client, proxy1, proxy2"
566 * you would receive the array `["client", "proxy1", "proxy2"]`
567 * where "proxy2" is the furthest down-stream.
568 */
569 ips: string[];
570
571 /**
572 * Return subdomains as an array.
573 *
574 * Subdomains are the dot-separated parts of the host before the main domain of
575 * the app. By default, the domain of the app is assumed to be the last two
576 * parts of the host. This can be changed by setting "subdomain offset".
577 *
578 * For example, if the domain is "tobi.ferrets.example.com":
579 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
580 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
581 */
582 subdomains: string[];
583
584 /**
585 * Short-hand for `url.parse(req.url).pathname`.
586 */
587 path: string;
588
589 /**
590 * Parse the "Host" header field hostname.
591 */
592 hostname: string;
593
594 /**
595 * @deprecated Use hostname instead.
596 */
597 host: string;
598
599 /**
600 * Check if the request is fresh, aka
601 * Last-Modified and/or the ETag
602 * still match.
603 */
604 fresh: boolean;
605
606 /**
607 * Check if the request is stale, aka
608 * "Last-Modified" and / or the "ETag" for the
609 * resource has changed.
610 */
611 stale: boolean;
612
613 /**
614 * Check if the request was an _XMLHttpRequest_.
615 */
616 xhr: boolean;
617
618 //body: { username: string; password: string; remember: boolean; title: string; };
619 body: ReqBody;
620
621 //cookies: { string; remember: boolean; };
622 cookies: any;
623
624 method: string;
625
626 params: P;
627
628 query: ReqQuery;
629
630 route: any;
631
632 signedCookies: any;
633
634 originalUrl: string;
635
636 url: string;
637
638 baseUrl: string;
639
640 app: Application;
641
642 /**
643 * After middleware.init executed, Request will contain res and next properties
644 * See: express/lib/middleware/init.js
645 */
646 res?: Response<ResBody, Locals> | undefined;
647 next?: NextFunction | undefined;
648}
649
650export interface MediaType {
651 value: string;
652 quality: number;
653 type: string;
654 subtype: string;
655}
656
657export type Send<ResBody = any, T = Response<ResBody>> = (body?: ResBody) => T;
658
659export interface Response<
660 ResBody = any,
661 Locals extends Record<string, any> = Record<string, any>,
662 StatusCode extends number = number
663> extends http.ServerResponse,
664 Express.Response {
665 /**
666 * Set status `code`.
667 */
668 status(code: StatusCode): this;
669
670 /**
671 * Set the response HTTP status code to `statusCode` and send its string representation as the response body.
672 * @link http://expressjs.com/4x/api.html#res.sendStatus
673 *
674 * Examples:
675 *
676 * res.sendStatus(200); // equivalent to res.status(200).send('OK')
677 * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
678 * res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
679 * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
680 */
681 sendStatus(code: StatusCode): this;
682
683 /**
684 * Set Link header field with the given `links`.
685 *
686 * Examples:
687 *
688 * res.links({
689 * next: 'http://api.example.com/users?page=2',
690 * last: 'http://api.example.com/users?page=5'
691 * });
692 */
693 links(links: any): this;
694
695 /**
696 * Send a response.
697 *
698 * Examples:
699 *
700 * res.send(new Buffer('wahoo'));
701 * res.send({ some: 'json' });
702 * res.send('<p>some html</p>');
703 * res.status(404).send('Sorry, cant find that');
704 */
705 send: Send<ResBody, this>;
706
707 /**
708 * Send JSON response.
709 *
710 * Examples:
711 *
712 * res.json(null);
713 * res.json({ user: 'tj' });
714 * res.status(500).json('oh noes!');
715 * res.status(404).json('I dont have that');
716 */
717 json: Send<ResBody, this>;
718
719 /**
720 * Send JSON response with JSONP callback support.
721 *
722 * Examples:
723 *
724 * res.jsonp(null);
725 * res.jsonp({ user: 'tj' });
726 * res.status(500).jsonp('oh noes!');
727 * res.status(404).jsonp('I dont have that');
728 */
729 jsonp: Send<ResBody, this>;
730
731 /**
732 * Transfer the file at the given `path`.
733 *
734 * Automatically sets the _Content-Type_ response header field.
735 * The callback `fn(err)` is invoked when the transfer is complete
736 * or when an error occurs. Be sure to check `res.headersSent`
737 * if you wish to attempt responding, as the header and some data
738 * may have already been transferred.
739 *
740 * Options:
741 *
742 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
743 * - `root` root directory for relative filenames
744 * - `headers` object of headers to serve with file
745 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
746 *
747 * Other options are passed along to `send`.
748 *
749 * Examples:
750 *
751 * The following example illustrates how `res.sendFile()` may
752 * be used as an alternative for the `static()` middleware for
753 * dynamic situations. The code backing `res.sendFile()` is actually
754 * the same code, so HTTP cache support etc is identical.
755 *
756 * app.get('/user/:uid/photos/:file', function(req, res){
757 * var uid = req.params.uid
758 * , file = req.params.file;
759 *
760 * req.user.mayViewFilesFrom(uid, function(yes){
761 * if (yes) {
762 * res.sendFile('/uploads/' + uid + '/' + file);
763 * } else {
764 * res.send(403, 'Sorry! you cant see that.');
765 * }
766 * });
767 * });
768 *
769 * @api public
770 */
771 sendFile(path: string, fn?: Errback): void;
772 sendFile(path: string, options: any, fn?: Errback): void;
773
774 /**
775 * @deprecated Use sendFile instead.
776 */
777 sendfile(path: string): void;
778 /**
779 * @deprecated Use sendFile instead.
780 */
781 sendfile(path: string, options: any): void;
782 /**
783 * @deprecated Use sendFile instead.
784 */
785 sendfile(path: string, fn: Errback): void;
786 /**
787 * @deprecated Use sendFile instead.
788 */
789 sendfile(path: string, options: any, fn: Errback): void;
790
791 /**
792 * Transfer the file at the given `path` as an attachment.
793 *
794 * Optionally providing an alternate attachment `filename`,
795 * and optional callback `fn(err)`. The callback is invoked
796 * when the data transfer is complete, or when an error has
797 * ocurred. Be sure to check `res.headersSent` if you plan to respond.
798 *
799 * The optional options argument passes through to the underlying
800 * res.sendFile() call, and takes the exact same parameters.
801 *
802 * This method uses `res.sendfile()`.
803 */
804 download(path: string, fn?: Errback): void;
805 download(path: string, filename: string, fn?: Errback): void;
806 download(path: string, filename: string, options: any, fn?: Errback): void;
807
808 /**
809 * Set _Content-Type_ response header with `type` through `mime.lookup()`
810 * when it does not contain "/", or set the Content-Type to `type` otherwise.
811 *
812 * Examples:
813 *
814 * res.type('.html');
815 * res.type('html');
816 * res.type('json');
817 * res.type('application/json');
818 * res.type('png');
819 */
820 contentType(type: string): this;
821
822 /**
823 * Set _Content-Type_ response header with `type` through `mime.lookup()`
824 * when it does not contain "/", or set the Content-Type to `type` otherwise.
825 *
826 * Examples:
827 *
828 * res.type('.html');
829 * res.type('html');
830 * res.type('json');
831 * res.type('application/json');
832 * res.type('png');
833 */
834 type(type: string): this;
835
836 /**
837 * Respond to the Acceptable formats using an `obj`
838 * of mime-type callbacks.
839 *
840 * This method uses `req.accepted`, an array of
841 * acceptable types ordered by their quality values.
842 * When "Accept" is not present the _first_ callback
843 * is invoked, otherwise the first match is used. When
844 * no match is performed the server responds with
845 * 406 "Not Acceptable".
846 *
847 * Content-Type is set for you, however if you choose
848 * you may alter this within the callback using `res.type()`
849 * or `res.set('Content-Type', ...)`.
850 *
851 * res.format({
852 * 'text/plain': function(){
853 * res.send('hey');
854 * },
855 *
856 * 'text/html': function(){
857 * res.send('<p>hey</p>');
858 * },
859 *
860 * 'appliation/json': function(){
861 * res.send({ message: 'hey' });
862 * }
863 * });
864 *
865 * In addition to canonicalized MIME types you may
866 * also use extnames mapped to these types:
867 *
868 * res.format({
869 * text: function(){
870 * res.send('hey');
871 * },
872 *
873 * html: function(){
874 * res.send('<p>hey</p>');
875 * },
876 *
877 * json: function(){
878 * res.send({ message: 'hey' });
879 * }
880 * });
881 *
882 * By default Express passes an `Error`
883 * with a `.status` of 406 to `next(err)`
884 * if a match is not made. If you provide
885 * a `.default` callback it will be invoked
886 * instead.
887 */
888 format(obj: any): this;
889
890 /**
891 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
892 */
893 attachment(filename?: string): this;
894
895 /**
896 * Set header `field` to `val`, or pass
897 * an object of header fields.
898 *
899 * Examples:
900 *
901 * res.set('Foo', ['bar', 'baz']);
902 * res.set('Accept', 'application/json');
903 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
904 *
905 * Aliased as `res.header()`.
906 */
907 set(field: any): this;
908 set(field: string, value?: string | string[]): this;
909
910 header(field: any): this;
911 header(field: string, value?: string | string[]): this;
912
913 // Property indicating if HTTP headers has been sent for the response.
914 headersSent: boolean;
915
916 /** Get value for header `field`. */
917 get(field: string): string;
918
919 /** Clear cookie `name`. */
920 clearCookie(name: string, options?: CookieOptions): this;
921
922 /**
923 * Set cookie `name` to `val`, with the given `options`.
924 *
925 * Options:
926 *
927 * - `maxAge` max-age in milliseconds, converted to `expires`
928 * - `signed` sign the cookie
929 * - `path` defaults to "/"
930 *
931 * Examples:
932 *
933 * // "Remember Me" for 15 minutes
934 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
935 *
936 * // save as above
937 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
938 */
939 cookie(name: string, val: string, options: CookieOptions): this;
940 cookie(name: string, val: any, options: CookieOptions): this;
941 cookie(name: string, val: any): this;
942
943 /**
944 * Set the location header to `url`.
945 *
946 * The given `url` can also be the name of a mapped url, for
947 * example by default express supports "back" which redirects
948 * to the _Referrer_ or _Referer_ headers or "/".
949 *
950 * Examples:
951 *
952 * res.location('/foo/bar').;
953 * res.location('http://example.com');
954 * res.location('../login'); // /blog/post/1 -> /blog/login
955 *
956 * Mounting:
957 *
958 * When an application is mounted and `res.location()`
959 * is given a path that does _not_ lead with "/" it becomes
960 * relative to the mount-point. For example if the application
961 * is mounted at "/blog", the following would become "/blog/login".
962 *
963 * res.location('login');
964 *
965 * While the leading slash would result in a location of "/login":
966 *
967 * res.location('/login');
968 */
969 location(url: string): this;
970
971 /**
972 * Redirect to the given `url` with optional response `status`
973 * defaulting to 302.
974 *
975 * The resulting `url` is determined by `res.location()`, so
976 * it will play nicely with mounted apps, relative paths,
977 * `"back"` etc.
978 *
979 * Examples:
980 *
981 * res.redirect('/foo/bar');
982 * res.redirect('http://example.com');
983 * res.redirect(301, 'http://example.com');
984 * res.redirect('http://example.com', 301);
985 * res.redirect('../login'); // /blog/post/1 -> /blog/login
986 */
987 redirect(url: string): void;
988 redirect(status: number, url: string): void;
989 redirect(url: string, status: number): void;
990
991 /**
992 * Render `view` with the given `options` and optional callback `fn`.
993 * When a callback function is given a response will _not_ be made
994 * automatically, otherwise a response of _200_ and _text/html_ is given.
995 *
996 * Options:
997 *
998 * - `cache` boolean hinting to the engine it should cache
999 * - `filename` filename of the view being rendered
1000 */
1001 render(view: string, options?: object, callback?: (err: Error, html: string) => void): void;
1002 render(view: string, callback?: (err: Error, html: string) => void): void;
1003
1004 locals: Locals;
1005
1006 charset: string;
1007
1008 /**
1009 * Adds the field to the Vary response header, if it is not there already.
1010 * Examples:
1011 *
1012 * res.vary('User-Agent').render('docs');
1013 *
1014 */
1015 vary(field: string): this;
1016
1017 app: Application;
1018
1019 /**
1020 * Appends the specified value to the HTTP response header field.
1021 * If the header is not already set, it creates the header with the specified value.
1022 * The value parameter can be a string or an array.
1023 *
1024 * Note: calling res.set() after res.append() will reset the previously-set header value.
1025 *
1026 * @since 4.11.0
1027 */
1028 append(field: string, value?: string[] | string): this;
1029
1030 /**
1031 * After middleware.init executed, Response will contain req property
1032 * See: express/lib/middleware/init.js
1033 */
1034 req: Request;
1035}
1036
1037export interface Handler extends RequestHandler {}
1038
1039export type RequestParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => any;
1040
1041export type ApplicationRequestHandler<T> = IRouterHandler<T> &
1042 IRouterMatcher<T> &
1043 ((...handlers: RequestHandlerParams[]) => T);
1044
1045export interface Application<
1046 Locals extends Record<string, any> = Record<string, any>
1047> extends EventEmitter, IRouter, Express.Application {
1048 /**
1049 * Express instance itself is a request handler, which could be invoked without
1050 * third argument.
1051 */
1052 (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any;
1053
1054 /**
1055 * Initialize the server.
1056 *
1057 * - setup default configuration
1058 * - setup default middleware
1059 * - setup route reflection methods
1060 */
1061 init(): void;
1062
1063 /**
1064 * Initialize application configuration.
1065 */
1066 defaultConfiguration(): void;
1067
1068 /**
1069 * Register the given template engine callback `fn`
1070 * as `ext`.
1071 *
1072 * By default will `require()` the engine based on the
1073 * file extension. For example if you try to render
1074 * a "foo.jade" file Express will invoke the following internally:
1075 *
1076 * app.engine('jade', require('jade').__express);
1077 *
1078 * For engines that do not provide `.__express` out of the box,
1079 * or if you wish to "map" a different extension to the template engine
1080 * you may use this method. For example mapping the EJS template engine to
1081 * ".html" files:
1082 *
1083 * app.engine('html', require('ejs').renderFile);
1084 *
1085 * In this case EJS provides a `.renderFile()` method with
1086 * the same signature that Express expects: `(path, options, callback)`,
1087 * though note that it aliases this method as `ejs.__express` internally
1088 * so if you're using ".ejs" extensions you dont need to do anything.
1089 *
1090 * Some template engines do not follow this convention, the
1091 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)
1092 * library was created to map all of node's popular template
1093 * engines to follow this convention, thus allowing them to
1094 * work seamlessly within Express.
1095 */
1096 engine(
1097 ext: string,
1098 fn: (path: string, options: object, callback: (e: any, rendered?: string) => void) => void,
1099 ): this;
1100
1101 /**
1102 * Assign `setting` to `val`, or return `setting`'s value.
1103 *
1104 * app.set('foo', 'bar');
1105 * app.get('foo');
1106 * // => "bar"
1107 * app.set('foo', ['bar', 'baz']);
1108 * app.get('foo');
1109 * // => ["bar", "baz"]
1110 *
1111 * Mounted servers inherit their parent server's settings.
1112 */
1113 set(setting: string, val: any): this;
1114 get: ((name: string) => any) & IRouterMatcher<this>;
1115
1116 param(name: string | string[], handler: RequestParamHandler): this;
1117
1118 /**
1119 * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param()
1120 *
1121 * @deprecated since version 4.11
1122 */
1123 param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
1124
1125 /**
1126 * Return the app's absolute pathname
1127 * based on the parent(s) that have
1128 * mounted it.
1129 *
1130 * For example if the application was
1131 * mounted as "/admin", which itself
1132 * was mounted as "/blog" then the
1133 * return value would be "/blog/admin".
1134 */
1135 path(): string;
1136
1137 /**
1138 * Check if `setting` is enabled (truthy).
1139 *
1140 * app.enabled('foo')
1141 * // => false
1142 *
1143 * app.enable('foo')
1144 * app.enabled('foo')
1145 * // => true
1146 */
1147 enabled(setting: string): boolean;
1148
1149 /**
1150 * Check if `setting` is disabled.
1151 *
1152 * app.disabled('foo')
1153 * // => true
1154 *
1155 * app.enable('foo')
1156 * app.disabled('foo')
1157 * // => false
1158 */
1159 disabled(setting: string): boolean;
1160
1161 /** Enable `setting`. */
1162 enable(setting: string): this;
1163
1164 /** Disable `setting`. */
1165 disable(setting: string): this;
1166
1167 /**
1168 * Render the given view `name` name with `options`
1169 * and a callback accepting an error and the
1170 * rendered template string.
1171 *
1172 * Example:
1173 *
1174 * app.render('email', { name: 'Tobi' }, function(err, html){
1175 * // ...
1176 * })
1177 */
1178 render(name: string, options?: object, callback?: (err: Error, html: string) => void): void;
1179 render(name: string, callback: (err: Error, html: string) => void): void;
1180
1181 /**
1182 * Listen for connections.
1183 *
1184 * A node `http.Server` is returned, with this
1185 * application (which is a `Function`) as its
1186 * callback. If you wish to create both an HTTP
1187 * and HTTPS server you may do so with the "http"
1188 * and "https" modules as shown here:
1189 *
1190 * var http = require('http')
1191 * , https = require('https')
1192 * , express = require('express')
1193 * , app = express();
1194 *
1195 * http.createServer(app).listen(80);
1196 * https.createServer({ ... }, app).listen(443);
1197 */
1198 listen(port: number, hostname: string, backlog: number, callback?: () => void): http.Server;
1199 listen(port: number, hostname: string, callback?: () => void): http.Server;
1200 listen(port: number, callback?: () => void): http.Server;
1201 listen(callback?: () => void): http.Server;
1202 listen(path: string, callback?: () => void): http.Server;
1203 listen(handle: any, listeningListener?: () => void): http.Server;
1204
1205 router: string;
1206
1207 settings: any;
1208
1209 resource: any;
1210
1211 map: any;
1212
1213 locals: Locals;
1214
1215 /**
1216 * The app.routes object houses all of the routes defined mapped by the
1217 * associated HTTP verb. This object may be used for introspection
1218 * capabilities, for example Express uses this internally not only for
1219 * routing but to provide default OPTIONS behaviour unless app.options()
1220 * is used. Your application or framework may also remove routes by
1221 * simply by removing them from this object.
1222 */
1223 routes: any;
1224
1225 /**
1226 * Used to get all registered routes in Express Application
1227 */
1228 _router: any;
1229
1230 use: ApplicationRequestHandler<this>;
1231
1232 /**
1233 * The mount event is fired on a sub-app, when it is mounted on a parent app.
1234 * The parent app is passed to the callback function.
1235 *
1236 * NOTE:
1237 * Sub-apps will:
1238 * - Not inherit the value of settings that have a default value. You must set the value in the sub-app.
1239 * - Inherit the value of settings with no default value.
1240 */
1241 on: (event: string, callback: (parent: Application) => void) => this;
1242
1243 /**
1244 * The app.mountpath property contains one or more path patterns on which a sub-app was mounted.
1245 */
1246 mountpath: string | string[];
1247}
1248
1249export interface Express extends Application {
1250 request: Request;
1251 response: Response;
1252}