UNPKG

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