UNPKG

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