UNPKG

41 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
330export interface CookieOptions {
331 maxAge?: number | undefined;
332 signed?: boolean | undefined;
333 expires?: Date | undefined;
334 httpOnly?: boolean | undefined;
335 path?: string | undefined;
336 domain?: string | undefined;
337 secure?: boolean | undefined;
338 encode?: ((val: string) => string) | undefined;
339 sameSite?: boolean | "lax" | "strict" | "none" | undefined;
340}
341
342export interface ByteRange {
343 start: number;
344 end: number;
345}
346
347export interface RequestRanges extends RangeParserRanges {}
348
349export type Errback = (err: Error) => void;
350
351/**
352 * @param P For most requests, this should be `ParamsDictionary`, but if you're
353 * using this in a route handler for a route that uses a `RegExp` or a wildcard
354 * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in
355 * which case you should use `ParamsArray` instead.
356 *
357 * @see https://expressjs.com/en/api.html#req.params
358 *
359 * @example
360 * app.get('/user/:id', (req, res) => res.send(req.params.id)); // implicitly `ParamsDictionary`
361 * app.get<ParamsArray>(/user\/(.*)/, (req, res) => res.send(req.params[0]));
362 * app.get<ParamsArray>('/user/*', (req, res) => res.send(req.params[0]));
363 */
364export interface Request<
365 P = ParamsDictionary,
366 ResBody = any,
367 ReqBody = any,
368 ReqQuery = ParsedQs,
369 LocalsObj extends Record<string, any> = Record<string, any>,
370> extends http.IncomingMessage, Express.Request {
371 /**
372 * Return request header.
373 *
374 * The `Referrer` header field is special-cased,
375 * both `Referrer` and `Referer` are interchangeable.
376 *
377 * Examples:
378 *
379 * req.get('Content-Type');
380 * // => "text/plain"
381 *
382 * req.get('content-type');
383 * // => "text/plain"
384 *
385 * req.get('Something');
386 * // => undefined
387 *
388 * Aliased as `req.header()`.
389 */
390 get(name: "set-cookie"): string[] | undefined;
391 get(name: string): string | undefined;
392
393 header(name: "set-cookie"): string[] | undefined;
394 header(name: string): string | undefined;
395
396 /**
397 * Check if the given `type(s)` is acceptable, returning
398 * the best match when true, otherwise `undefined`, in which
399 * case you should respond with 406 "Not Acceptable".
400 *
401 * The `type` value may be a single mime type string
402 * such as "application/json", the extension name
403 * such as "json", a comma-delimted list such as "json, html, text/plain",
404 * or an array `["json", "html", "text/plain"]`. When a list
405 * or array is given the _best_ match, if any is returned.
406 *
407 * Examples:
408 *
409 * // Accept: text/html
410 * req.accepts('html');
411 * // => "html"
412 *
413 * // Accept: text/*, application/json
414 * req.accepts('html');
415 * // => "html"
416 * req.accepts('text/html');
417 * // => "text/html"
418 * req.accepts('json, text');
419 * // => "json"
420 * req.accepts('application/json');
421 * // => "application/json"
422 *
423 * // Accept: text/*, application/json
424 * req.accepts('image/png');
425 * req.accepts('png');
426 * // => undefined
427 *
428 * // Accept: text/*;q=.5, application/json
429 * req.accepts(['html', 'json']);
430 * req.accepts('html, json');
431 * // => "json"
432 */
433 accepts(): string[];
434 accepts(type: string): string | false;
435 accepts(type: string[]): string | false;
436 accepts(...type: string[]): string | false;
437
438 /**
439 * Returns the first accepted charset of the specified character sets,
440 * based on the request's Accept-Charset HTTP header field.
441 * If none of the specified charsets is accepted, returns false.
442 *
443 * For more information, or if you have issues or concerns, see accepts.
444 */
445 acceptsCharsets(): string[];
446 acceptsCharsets(charset: string): string | false;
447 acceptsCharsets(charset: string[]): string | false;
448 acceptsCharsets(...charset: string[]): string | false;
449
450 /**
451 * Returns the first accepted encoding of the specified encodings,
452 * based on the request's Accept-Encoding HTTP header field.
453 * If none of the specified encodings is accepted, returns false.
454 *
455 * For more information, or if you have issues or concerns, see accepts.
456 */
457 acceptsEncodings(): string[];
458 acceptsEncodings(encoding: string): string | false;
459 acceptsEncodings(encoding: string[]): string | false;
460 acceptsEncodings(...encoding: string[]): string | false;
461
462 /**
463 * Returns the first accepted language of the specified languages,
464 * based on the request's Accept-Language HTTP header field.
465 * If none of the specified languages is accepted, returns false.
466 *
467 * For more information, or if you have issues or concerns, see accepts.
468 */
469 acceptsLanguages(): string[];
470 acceptsLanguages(lang: string): string | false;
471 acceptsLanguages(lang: string[]): string | false;
472 acceptsLanguages(...lang: string[]): string | false;
473
474 /**
475 * Parse Range header field, capping to the given `size`.
476 *
477 * Unspecified ranges such as "0-" require knowledge of your resource length. In
478 * the case of a byte range this is of course the total number of bytes.
479 * If the Range header field is not given `undefined` is returned.
480 * If the Range header field is given, return value is a result of range-parser.
481 * See more ./types/range-parser/index.d.ts
482 *
483 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
484 * should respond with 4 users when available, not 3.
485 */
486 range(size: number, options?: RangeParserOptions): RangeParserRanges | RangeParserResult | undefined;
487
488 /**
489 * Return an array of Accepted media types
490 * ordered from highest quality to lowest.
491 */
492 accepted: MediaType[];
493
494 /**
495 * @deprecated since 4.11 Use either req.params, req.body or req.query, as applicable.
496 *
497 * Return the value of param `name` when present or `defaultValue`.
498 *
499 * - Checks route placeholders, ex: _/user/:id_
500 * - Checks body params, ex: id=12, {"id":12}
501 * - Checks query string params, ex: ?id=12
502 *
503 * To utilize request bodies, `req.body`
504 * should be an object. This can be done by using
505 * the `connect.bodyParser()` middleware.
506 */
507 param(name: string, defaultValue?: any): string;
508
509 /**
510 * Check if the incoming request contains the "Content-Type"
511 * header field, and it contains the give mime `type`.
512 *
513 * Examples:
514 *
515 * // With Content-Type: text/html; charset=utf-8
516 * req.is('html');
517 * req.is('text/html');
518 * req.is('text/*');
519 * // => true
520 *
521 * // When Content-Type is application/json
522 * req.is('json');
523 * req.is('application/json');
524 * req.is('application/*');
525 * // => true
526 *
527 * req.is('html');
528 * // => false
529 */
530 is(type: string | string[]): string | false | null;
531
532 /**
533 * Return the protocol string "http" or "https"
534 * when requested with TLS. When the "trust proxy"
535 * setting is enabled the "X-Forwarded-Proto" header
536 * field will be trusted. If you're running behind
537 * a reverse proxy that supplies https for you this
538 * may be enabled.
539 */
540 protocol: string;
541
542 /**
543 * Short-hand for:
544 *
545 * req.protocol == 'https'
546 */
547 secure: boolean;
548
549 /**
550 * Return the remote address, or when
551 * "trust proxy" is `true` return
552 * the upstream addr.
553 *
554 * Value may be undefined if the `req.socket` is destroyed
555 * (for example, if the client disconnected).
556 */
557 ip: string | undefined;
558
559 /**
560 * When "trust proxy" is `true`, parse
561 * the "X-Forwarded-For" ip address list.
562 *
563 * For example if the value were "client, proxy1, proxy2"
564 * you would receive the array `["client", "proxy1", "proxy2"]`
565 * where "proxy2" is the furthest down-stream.
566 */
567 ips: string[];
568
569 /**
570 * Return subdomains as an array.
571 *
572 * Subdomains are the dot-separated parts of the host before the main domain of
573 * the app. By default, the domain of the app is assumed to be the last two
574 * parts of the host. This can be changed by setting "subdomain offset".
575 *
576 * For example, if the domain is "tobi.ferrets.example.com":
577 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
578 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
579 */
580 subdomains: string[];
581
582 /**
583 * Short-hand for `url.parse(req.url).pathname`.
584 */
585 path: string;
586
587 /**
588 * Parse the "Host" header field hostname.
589 */
590 hostname: string;
591
592 /**
593 * @deprecated Use hostname instead.
594 */
595 host: string;
596
597 /**
598 * Check if the request is fresh, aka
599 * Last-Modified and/or the ETag
600 * still match.
601 */
602 fresh: boolean;
603
604 /**
605 * Check if the request is stale, aka
606 * "Last-Modified" and / or the "ETag" for the
607 * resource has changed.
608 */
609 stale: boolean;
610
611 /**
612 * Check if the request was an _XMLHttpRequest_.
613 */
614 xhr: boolean;
615
616 // body: { username: string; password: string; remember: boolean; title: string; };
617 body: ReqBody;
618
619 // cookies: { string; remember: boolean; };
620 cookies: any;
621
622 method: string;
623
624 params: P;
625
626 query: ReqQuery;
627
628 route: any;
629
630 signedCookies: any;
631
632 originalUrl: string;
633
634 url: string;
635
636 baseUrl: string;
637
638 app: Application;
639
640 /**
641 * After middleware.init executed, Request will contain res and next properties
642 * See: express/lib/middleware/init.js
643 */
644 res?: Response<ResBody, LocalsObj> | undefined;
645 next?: NextFunction | undefined;
646}
647
648export interface MediaType {
649 value: string;
650 quality: number;
651 type: string;
652 subtype: string;
653}
654
655export type Send<ResBody = any, T = Response<ResBody>> = (body?: ResBody) => T;
656
657export interface SendFileOptions extends SendOptions {
658 /** Object containing HTTP headers to serve with the file. */
659 headers?: Record<string, unknown>;
660}
661
662export interface DownloadOptions extends SendOptions {
663 /** Object containing HTTP headers to serve with the file. The header `Content-Disposition` will be overridden by the filename argument. */
664 headers?: Record<string, unknown>;
665}
666
667export interface Response<
668 ResBody = any,
669 LocalsObj extends Record<string, any> = Record<string, any>,
670 StatusCode extends number = number,
671> extends http.ServerResponse, Express.Response {
672 /**
673 * Set status `code`.
674 */
675 status(code: StatusCode): this;
676
677 /**
678 * Set the response HTTP status code to `statusCode` and send its string representation as the response body.
679 * @link http://expressjs.com/4x/api.html#res.sendStatus
680 *
681 * Examples:
682 *
683 * res.sendStatus(200); // equivalent to res.status(200).send('OK')
684 * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
685 * res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
686 * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
687 */
688 sendStatus(code: StatusCode): this;
689
690 /**
691 * Set Link header field with the given `links`.
692 *
693 * Examples:
694 *
695 * res.links({
696 * next: 'http://api.example.com/users?page=2',
697 * last: 'http://api.example.com/users?page=5'
698 * });
699 */
700 links(links: any): this;
701
702 /**
703 * Send a response.
704 *
705 * Examples:
706 *
707 * res.send(new Buffer('wahoo'));
708 * res.send({ some: 'json' });
709 * res.send('<p>some html</p>');
710 * res.status(404).send('Sorry, cant find that');
711 */
712 send: Send<ResBody, this>;
713
714 /**
715 * Send JSON response.
716 *
717 * Examples:
718 *
719 * res.json(null);
720 * res.json({ user: 'tj' });
721 * res.status(500).json('oh noes!');
722 * res.status(404).json('I dont have that');
723 */
724 json: Send<ResBody, this>;
725
726 /**
727 * Send JSON response with JSONP callback support.
728 *
729 * Examples:
730 *
731 * res.jsonp(null);
732 * res.jsonp({ user: 'tj' });
733 * res.status(500).jsonp('oh noes!');
734 * res.status(404).jsonp('I dont have that');
735 */
736 jsonp: Send<ResBody, this>;
737
738 /**
739 * Transfer the file at the given `path`.
740 *
741 * Automatically sets the _Content-Type_ response header field.
742 * The callback `fn(err)` is invoked when the transfer is complete
743 * or when an error occurs. Be sure to check `res.headersSent`
744 * if you wish to attempt responding, as the header and some data
745 * may have already been transferred.
746 *
747 * Options:
748 *
749 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
750 * - `root` root directory for relative filenames
751 * - `headers` object of headers to serve with file
752 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
753 *
754 * Other options are passed along to `send`.
755 *
756 * Examples:
757 *
758 * The following example illustrates how `res.sendFile()` may
759 * be used as an alternative for the `static()` middleware for
760 * dynamic situations. The code backing `res.sendFile()` is actually
761 * the same code, so HTTP cache support etc is identical.
762 *
763 * app.get('/user/:uid/photos/:file', function(req, res){
764 * var uid = req.params.uid
765 * , file = req.params.file;
766 *
767 * req.user.mayViewFilesFrom(uid, function(yes){
768 * if (yes) {
769 * res.sendFile('/uploads/' + uid + '/' + file);
770 * } else {
771 * res.send(403, 'Sorry! you cant see that.');
772 * }
773 * });
774 * });
775 *
776 * @api public
777 */
778 sendFile(path: string, fn?: Errback): void;
779 sendFile(path: string, options: SendFileOptions, fn?: Errback): void;
780
781 /**
782 * @deprecated Use sendFile instead.
783 */
784 sendfile(path: string): void;
785 /**
786 * @deprecated Use sendFile instead.
787 */
788 sendfile(path: string, options: SendFileOptions): void;
789 /**
790 * @deprecated Use sendFile instead.
791 */
792 sendfile(path: string, fn: Errback): void;
793 /**
794 * @deprecated Use sendFile instead.
795 */
796 sendfile(path: string, options: SendFileOptions, fn: Errback): void;
797
798 /**
799 * Transfer the file at the given `path` as an attachment.
800 *
801 * Optionally providing an alternate attachment `filename`,
802 * and optional callback `fn(err)`. The callback is invoked
803 * when the data transfer is complete, or when an error has
804 * ocurred. Be sure to check `res.headersSent` if you plan to respond.
805 *
806 * The optional options argument passes through to the underlying
807 * res.sendFile() call, and takes the exact same parameters.
808 *
809 * This method uses `res.sendfile()`.
810 */
811 download(path: string, fn?: Errback): void;
812 download(path: string, filename: string, fn?: Errback): void;
813 download(path: string, filename: string, options: DownloadOptions, fn?: Errback): void;
814
815 /**
816 * Set _Content-Type_ response header with `type` through `mime.lookup()`
817 * when it does not contain "/", or set the Content-Type to `type` otherwise.
818 *
819 * Examples:
820 *
821 * res.type('.html');
822 * res.type('html');
823 * res.type('json');
824 * res.type('application/json');
825 * res.type('png');
826 */
827 contentType(type: string): this;
828
829 /**
830 * Set _Content-Type_ response header with `type` through `mime.lookup()`
831 * when it does not contain "/", or set the Content-Type to `type` otherwise.
832 *
833 * Examples:
834 *
835 * res.type('.html');
836 * res.type('html');
837 * res.type('json');
838 * res.type('application/json');
839 * res.type('png');
840 */
841 type(type: string): this;
842
843 /**
844 * Respond to the Acceptable formats using an `obj`
845 * of mime-type callbacks.
846 *
847 * This method uses `req.accepted`, an array of
848 * acceptable types ordered by their quality values.
849 * When "Accept" is not present the _first_ callback
850 * is invoked, otherwise the first match is used. When
851 * no match is performed the server responds with
852 * 406 "Not Acceptable".
853 *
854 * Content-Type is set for you, however if you choose
855 * you may alter this within the callback using `res.type()`
856 * or `res.set('Content-Type', ...)`.
857 *
858 * res.format({
859 * 'text/plain': function(){
860 * res.send('hey');
861 * },
862 *
863 * 'text/html': function(){
864 * res.send('<p>hey</p>');
865 * },
866 *
867 * 'appliation/json': function(){
868 * res.send({ message: 'hey' });
869 * }
870 * });
871 *
872 * In addition to canonicalized MIME types you may
873 * also use extnames mapped to these types:
874 *
875 * res.format({
876 * text: function(){
877 * res.send('hey');
878 * },
879 *
880 * html: function(){
881 * res.send('<p>hey</p>');
882 * },
883 *
884 * json: function(){
885 * res.send({ message: 'hey' });
886 * }
887 * });
888 *
889 * By default Express passes an `Error`
890 * with a `.status` of 406 to `next(err)`
891 * if a match is not made. If you provide
892 * a `.default` callback it will be invoked
893 * instead.
894 */
895 format(obj: any): this;
896
897 /**
898 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
899 */
900 attachment(filename?: string): this;
901
902 /**
903 * Set header `field` to `val`, or pass
904 * an object of header fields.
905 *
906 * Examples:
907 *
908 * res.set('Foo', ['bar', 'baz']);
909 * res.set('Accept', 'application/json');
910 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
911 *
912 * Aliased as `res.header()`.
913 */
914 set(field: any): this;
915 set(field: string, value?: string | string[]): this;
916
917 header(field: any): this;
918 header(field: string, value?: string | string[]): this;
919
920 // Property indicating if HTTP headers has been sent for the response.
921 headersSent: boolean;
922
923 /** Get value for header `field`. */
924 get(field: string): string | undefined;
925
926 /** Clear cookie `name`. */
927 clearCookie(name: string, options?: CookieOptions): this;
928
929 /**
930 * Set cookie `name` to `val`, with the given `options`.
931 *
932 * Options:
933 *
934 * - `maxAge` max-age in milliseconds, converted to `expires`
935 * - `signed` sign the cookie
936 * - `path` defaults to "/"
937 *
938 * Examples:
939 *
940 * // "Remember Me" for 15 minutes
941 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
942 *
943 * // save as above
944 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
945 */
946 cookie(name: string, val: string, options: CookieOptions): this;
947 cookie(name: string, val: any, options: CookieOptions): this;
948 cookie(name: string, val: any): this;
949
950 /**
951 * Set the location header to `url`.
952 *
953 * The given `url` can also be the name of a mapped url, for
954 * example by default express supports "back" which redirects
955 * to the _Referrer_ or _Referer_ headers or "/".
956 *
957 * Examples:
958 *
959 * res.location('/foo/bar').;
960 * res.location('http://example.com');
961 * res.location('../login'); // /blog/post/1 -> /blog/login
962 *
963 * Mounting:
964 *
965 * When an application is mounted and `res.location()`
966 * is given a path that does _not_ lead with "/" it becomes
967 * relative to the mount-point. For example if the application
968 * is mounted at "/blog", the following would become "/blog/login".
969 *
970 * res.location('login');
971 *
972 * While the leading slash would result in a location of "/login":
973 *
974 * res.location('/login');
975 */
976 location(url: string): this;
977
978 /**
979 * Redirect to the given `url` with optional response `status`
980 * defaulting to 302.
981 *
982 * The resulting `url` is determined by `res.location()`, so
983 * it will play nicely with mounted apps, relative paths,
984 * `"back"` etc.
985 *
986 * Examples:
987 *
988 * res.redirect('back');
989 * res.redirect('/foo/bar');
990 * res.redirect('http://example.com');
991 * res.redirect(301, 'http://example.com');
992 * res.redirect('http://example.com', 301);
993 * res.redirect('../login'); // /blog/post/1 -> /blog/login
994 */
995 redirect(url: string): void;
996 redirect(status: number, url: string): void;
997 /** @deprecated use res.redirect(status, url) instead */
998 redirect(url: string, status: number): void;
999
1000 /**
1001 * Render `view` with the given `options` and optional callback `fn`.
1002 * When a callback function is given a response will _not_ be made
1003 * automatically, otherwise a response of _200_ and _text/html_ is given.
1004 *
1005 * Options:
1006 *
1007 * - `cache` boolean hinting to the engine it should cache
1008 * - `filename` filename of the view being rendered
1009 */
1010 render(view: string, options?: object, callback?: (err: Error, html: string) => void): void;
1011 render(view: string, callback?: (err: Error, html: string) => void): void;
1012
1013 locals: LocalsObj & Locals;
1014
1015 charset: string;
1016
1017 /**
1018 * Adds the field to the Vary response header, if it is not there already.
1019 * Examples:
1020 *
1021 * res.vary('User-Agent').render('docs');
1022 */
1023 vary(field: string): this;
1024
1025 app: Application;
1026
1027 /**
1028 * Appends the specified value to the HTTP response header field.
1029 * If the header is not already set, it creates the header with the specified value.
1030 * The value parameter can be a string or an array.
1031 *
1032 * Note: calling res.set() after res.append() will reset the previously-set header value.
1033 *
1034 * @since 4.11.0
1035 */
1036 append(field: string, value?: string[] | string): this;
1037
1038 /**
1039 * After middleware.init executed, Response will contain req property
1040 * See: express/lib/middleware/init.js
1041 */
1042 req: Request;
1043}
1044
1045export interface Handler extends RequestHandler {}
1046
1047export type RequestParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => any;
1048
1049export type ApplicationRequestHandler<T> =
1050 & IRouterHandler<T>
1051 & IRouterMatcher<T>
1052 & ((...handlers: RequestHandlerParams[]) => T);
1053
1054export interface Application<
1055 LocalsObj extends Record<string, any> = Record<string, any>,
1056> extends EventEmitter, IRouter, Express.Application {
1057 /**
1058 * Express instance itself is a request handler, which could be invoked without
1059 * third argument.
1060 */
1061 (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any;
1062
1063 /**
1064 * Initialize the server.
1065 *
1066 * - setup default configuration
1067 * - setup default middleware
1068 * - setup route reflection methods
1069 */
1070 init(): void;
1071
1072 /**
1073 * Initialize application configuration.
1074 */
1075 defaultConfiguration(): void;
1076
1077 /**
1078 * Register the given template engine callback `fn`
1079 * as `ext`.
1080 *
1081 * By default will `require()` the engine based on the
1082 * file extension. For example if you try to render
1083 * a "foo.jade" file Express will invoke the following internally:
1084 *
1085 * app.engine('jade', require('jade').__express);
1086 *
1087 * For engines that do not provide `.__express` out of the box,
1088 * or if you wish to "map" a different extension to the template engine
1089 * you may use this method. For example mapping the EJS template engine to
1090 * ".html" files:
1091 *
1092 * app.engine('html', require('ejs').renderFile);
1093 *
1094 * In this case EJS provides a `.renderFile()` method with
1095 * the same signature that Express expects: `(path, options, callback)`,
1096 * though note that it aliases this method as `ejs.__express` internally
1097 * so if you're using ".ejs" extensions you dont need to do anything.
1098 *
1099 * Some template engines do not follow this convention, the
1100 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)
1101 * library was created to map all of node's popular template
1102 * engines to follow this convention, thus allowing them to
1103 * work seamlessly within Express.
1104 */
1105 engine(
1106 ext: string,
1107 fn: (path: string, options: object, callback: (e: any, rendered?: string) => void) => void,
1108 ): this;
1109
1110 /**
1111 * Assign `setting` to `val`, or return `setting`'s value.
1112 *
1113 * app.set('foo', 'bar');
1114 * app.get('foo');
1115 * // => "bar"
1116 * app.set('foo', ['bar', 'baz']);
1117 * app.get('foo');
1118 * // => ["bar", "baz"]
1119 *
1120 * Mounted servers inherit their parent server's settings.
1121 */
1122 set(setting: string, val: any): this;
1123 get: ((name: string) => any) & IRouterMatcher<this>;
1124
1125 param(name: string | string[], handler: RequestParamHandler): this;
1126
1127 /**
1128 * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param()
1129 *
1130 * @deprecated since version 4.11
1131 */
1132 param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
1133
1134 /**
1135 * Return the app's absolute pathname
1136 * based on the parent(s) that have
1137 * mounted it.
1138 *
1139 * For example if the application was
1140 * mounted as "/admin", which itself
1141 * was mounted as "/blog" then the
1142 * return value would be "/blog/admin".
1143 */
1144 path(): string;
1145
1146 /**
1147 * Check if `setting` is enabled (truthy).
1148 *
1149 * app.enabled('foo')
1150 * // => false
1151 *
1152 * app.enable('foo')
1153 * app.enabled('foo')
1154 * // => true
1155 */
1156 enabled(setting: string): boolean;
1157
1158 /**
1159 * Check if `setting` is disabled.
1160 *
1161 * app.disabled('foo')
1162 * // => true
1163 *
1164 * app.enable('foo')
1165 * app.disabled('foo')
1166 * // => false
1167 */
1168 disabled(setting: string): boolean;
1169
1170 /** Enable `setting`. */
1171 enable(setting: string): this;
1172
1173 /** Disable `setting`. */
1174 disable(setting: string): this;
1175
1176 /**
1177 * Render the given view `name` name with `options`
1178 * and a callback accepting an error and the
1179 * rendered template string.
1180 *
1181 * Example:
1182 *
1183 * app.render('email', { name: 'Tobi' }, function(err, html){
1184 * // ...
1185 * })
1186 */
1187 render(name: string, options?: object, callback?: (err: Error, html: string) => void): void;
1188 render(name: string, callback: (err: Error, html: string) => void): void;
1189
1190 /**
1191 * Listen for connections.
1192 *
1193 * A node `http.Server` is returned, with this
1194 * application (which is a `Function`) as its
1195 * callback. If you wish to create both an HTTP
1196 * and HTTPS server you may do so with the "http"
1197 * and "https" modules as shown here:
1198 *
1199 * var http = require('http')
1200 * , https = require('https')
1201 * , express = require('express')
1202 * , app = express();
1203 *
1204 * http.createServer(app).listen(80);
1205 * https.createServer({ ... }, app).listen(443);
1206 */
1207 listen(port: number, hostname: string, backlog: number, callback?: () => void): http.Server;
1208 listen(port: number, hostname: string, callback?: () => void): http.Server;
1209 listen(port: number, callback?: () => void): http.Server;
1210 listen(callback?: () => void): http.Server;
1211 listen(path: string, callback?: () => void): http.Server;
1212 listen(handle: any, listeningListener?: () => void): http.Server;
1213
1214 router: string;
1215
1216 settings: any;
1217
1218 resource: any;
1219
1220 map: any;
1221
1222 locals: LocalsObj & Locals;
1223
1224 /**
1225 * The app.routes object houses all of the routes defined mapped by the
1226 * associated HTTP verb. This object may be used for introspection
1227 * capabilities, for example Express uses this internally not only for
1228 * routing but to provide default OPTIONS behaviour unless app.options()
1229 * is used. Your application or framework may also remove routes by
1230 * simply by removing them from this object.
1231 */
1232 routes: any;
1233
1234 /**
1235 * Used to get all registered routes in Express Application
1236 */
1237 _router: any;
1238
1239 use: ApplicationRequestHandler<this>;
1240
1241 /**
1242 * The mount event is fired on a sub-app, when it is mounted on a parent app.
1243 * The parent app is passed to the callback function.
1244 *
1245 * NOTE:
1246 * Sub-apps will:
1247 * - Not inherit the value of settings that have a default value. You must set the value in the sub-app.
1248 * - Inherit the value of settings with no default value.
1249 */
1250 on: (event: string, callback: (parent: Application) => void) => this;
1251
1252 /**
1253 * The app.mountpath property contains one or more path patterns on which a sub-app was mounted.
1254 */
1255 mountpath: string | string[];
1256}
1257
1258export interface Express extends Application {
1259 request: Request;
1260 response: Response;
1261}
1262
\No newline at end of file