@tinyhttp/app 2.3.1 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/app.d.ts CHANGED
@@ -1,11 +1,11 @@
1
- import { Server } from 'node:http';
2
- import { Handler, Middleware, NextFunction, UseMethodParams, Router } from '@tinyhttp/router';
3
- import { TemplateEngineOptions } from './index.js';
4
- import { ErrorHandler } from './onError.js';
5
- import { Request } from './request.js';
6
- import { Response } from './response.js';
7
- import { AppConstructor, AppRenderOptions, AppSettings, TemplateEngine } from './types.js';
8
-
1
+ import { type Server } from 'node:http';
2
+ import type { Handler, Middleware, NextFunction, UseMethodParams } from '@tinyhttp/router';
3
+ import { Router } from '@tinyhttp/router';
4
+ import type { TemplateEngineOptions } from './index.js';
5
+ import type { ErrorHandler } from './onError.js';
6
+ import type { Request } from './request.js';
7
+ import type { Response } from './response.js';
8
+ import type { AppConstructor, AppInterface, AppRenderOptions, AppSettings, TemplateEngine } from './types.js';
9
9
  /**
10
10
  * `App` class - the starting point of tinyhttp app.
11
11
  *
@@ -28,7 +28,7 @@ import { AppConstructor, AppRenderOptions, AppSettings, TemplateEngine } from '.
28
28
  * const app = App<any, CoolReq, Response>()
29
29
  * ```
30
30
  */
31
- export declare class App<Req extends Request = Request, Res extends Response = Response> extends Router<App, Req, Res> {
31
+ export declare class App<Req extends Request = Request, Res extends Response = Response> extends Router<App, Req, Res> implements AppInterface<Req, Res> {
32
32
  #private;
33
33
  middleware: Middleware<Req, Res>[];
34
34
  locals: Record<string, unknown>;
@@ -36,71 +36,20 @@ export declare class App<Req extends Request = Request, Res extends Response = R
36
36
  onError: ErrorHandler;
37
37
  settings: AppSettings;
38
38
  engines: Record<string, TemplateEngine>;
39
- applyExtensions: (req: Request, res: Response, next: NextFunction) => void;
39
+ applyExtensions?: Handler;
40
40
  attach: (req: Req, res: Res, next?: NextFunction) => void;
41
41
  cache: Record<string, unknown>;
42
42
  constructor(options?: AppConstructor<Req, Res>);
43
- /**
44
- * Set app setting
45
- * @param setting setting name
46
- * @param value setting value
47
- */
48
43
  set<K extends keyof AppSettings>(setting: K, value: AppSettings[K]): this;
49
- /**
50
- * Enable app setting
51
- * @param setting Setting name
52
- */
53
44
  enable<K extends keyof AppSettings>(setting: K): this;
54
- /**
55
- * Check if setting is enabled
56
- * @param setting Setting name
57
- * @returns
58
- */
59
45
  enabled<K extends keyof AppSettings>(setting: K): boolean;
60
- /**
61
- * Disable app setting
62
- * @param setting Setting name
63
- */
64
46
  disable<K extends keyof AppSettings>(setting: K): this;
65
- /**
66
- * Return the app's absolute pathname
67
- * based on the parent(s) that have
68
- * mounted it.
69
- *
70
- * For example if the application was
71
- * mounted as `"/admin"`, which itself
72
- * was mounted as `"/blog"` then the
73
- * return value would be `"/blog/admin"`.
74
- *
75
- */
76
- path(): string;
77
- /**
78
- * Register a template engine with extension
79
- */
47
+ path(): any;
80
48
  engine<RenderOptions extends TemplateEngineOptions = TemplateEngineOptions>(ext: string, fn: TemplateEngine<RenderOptions>): this;
81
- /**
82
- * Render a template
83
- * @param name What to render
84
- * @param data data that is passed to a template
85
- * @param options Template engine options
86
- * @param cb Callback that consumes error and html
87
- */
88
49
  render<RenderOptions extends TemplateEngineOptions = TemplateEngineOptions>(name: string, data?: Record<string, unknown>, options?: AppRenderOptions<RenderOptions>, cb?: (err: unknown, html?: unknown) => void): void;
89
- use(...args: UseMethodParams<Req, Res, App>): this;
90
- route(path: string): App;
91
- /**
92
- * Extends Req / Res objects, pushes 404 and 500 handlers, dispatches middleware
93
- * @param req Req object
94
- * @param res Res object
95
- * @param next 'Next' function
96
- */
50
+ use(...args: UseMethodParams<Req, Res, AppInterface<any, any>>): this;
51
+ route(path: string): AppInterface<any, any>;
97
52
  handler<RenderOptions extends TemplateEngineOptions = TemplateEngineOptions>(req: Req, res: Res, next?: NextFunction): void;
98
- /**
99
- * Creates HTTP server and dispatches middleware
100
- * @param port server listening port
101
- * @param cb callback to be invoked after server starts listening
102
- * @param host server listening host
103
- */
104
- listen(port?: number, cb?: () => void, host?: string): Server;
53
+ listen(port?: number, cb?: () => void, host?: string): Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
105
54
  }
106
55
  //# sourceMappingURL=app.d.ts.map
package/dist/app.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAgB,MAAM,WAAW,CAAA;AAErD,OAAO,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAA;AAC1F,OAAO,EAAE,MAAM,EAAkB,MAAM,kBAAkB,CAAA;AAGzD,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAGhD,OAAO,KAAK,EAAE,OAAO,EAAa,MAAM,cAAc,CAAA;AACtD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAC7C,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAuB/F;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,GAAG,CAAC,GAAG,SAAS,OAAO,GAAG,OAAO,EAAE,GAAG,SAAS,QAAQ,GAAG,QAAQ,CAAE,SAAQ,MAAM,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC;;IAC5G,UAAU,EAAE,UAAU,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,CAAK;IACvC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAK;IACpC,cAAc,EAAE,OAAO,CAAA;IACvB,OAAO,EAAE,YAAY,CAAA;IACrB,QAAQ,EAAE,WAAW,CAAA;IACrB,OAAO,EAAE,MAAM,CAAC,MAAM,EA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,EAAE,OAAO,CAAM,EAClC,OAAO,GAAE,gBAAgB,CAAC,aAAa,CAAyC,EAChF,EAAE,GAAE,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAe;IA+CvD,GAAG,CAAC,GAAG,IAAI,EAAE,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,GAAG,IAAI;IAmErE,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,YAAY,CAAC,GAAG,EAAE,GAAG,CAAC;IAsB3C,OAAO,CAAC,aAAa,SAAS,qBAAqB,GAAG,qBAAqB,EACzE,GAAG,EAAE,GAAG,EACR,GAAG,EAAE,GAAG,EACR,IAAI,CAAC,EAAE,YAAY;IAoHrB,MAAM,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,IAAI,EAAE,IAAI,CAAC,EAAE,MAAM;CAGrD"}
package/dist/app.js ADDED
@@ -0,0 +1,326 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var _App_instances, _App_find;
7
+ import { createServer } from 'node:http';
8
+ import { getPathname } from '@tinyhttp/req';
9
+ import { Router, pushMiddleware } from '@tinyhttp/router';
10
+ import { parse as rg } from 'regexparam';
11
+ import { extendMiddleware } from './extend.js';
12
+ import { onErrorHandler } from './onError.js';
13
+ import { getURLParams } from './request.js';
14
+ import { View } from './view.js';
15
+ /**
16
+ * Add leading slash if not present (e.g. path -> /path, /path -> /path)
17
+ * @param x
18
+ */
19
+ const lead = (x) => (x.charCodeAt(0) === 47 ? x : `/${x}`);
20
+ const trail = (x) => (x.charCodeAt(x.length - 1) === 47 ? x.substring(0, x.length - 1) : x);
21
+ const mount = (fn) => (fn instanceof App ? fn.attach : fn);
22
+ const applyHandler = (h) => async (req, res, next) => {
23
+ try {
24
+ if (h[Symbol.toStringTag] === 'AsyncFunction') {
25
+ await h(req, res, next);
26
+ }
27
+ else
28
+ h(req, res, next);
29
+ }
30
+ catch (e) {
31
+ next(e);
32
+ }
33
+ };
34
+ /**
35
+ * `App` class - the starting point of tinyhttp app.
36
+ *
37
+ * With the `App` you can:
38
+ * * use routing methods and `.use(...)`
39
+ * * set no match (404) and error (500) handlers
40
+ * * configure template engines
41
+ * * store data in locals
42
+ * * listen the http server on a specified port
43
+ *
44
+ * In case you use TypeScript, you can pass custom types to this class because it is also a generic class.
45
+ *
46
+ * Example:
47
+ *
48
+ * ```ts
49
+ * interface CoolReq extends Request {
50
+ * genericsAreDope: boolean
51
+ * }
52
+ *
53
+ * const app = App<any, CoolReq, Response>()
54
+ * ```
55
+ */
56
+ export class App extends Router {
57
+ constructor(options = {}) {
58
+ super();
59
+ _App_instances.add(this);
60
+ this.middleware = [];
61
+ this.locals = {};
62
+ this.engines = {};
63
+ this.onError = (options === null || options === void 0 ? void 0 : options.onError) || onErrorHandler;
64
+ // @ts-expect-error typescript is not smart enough to understand "this" ts(2345)
65
+ this.noMatchHandler = (options === null || options === void 0 ? void 0 : options.noMatchHandler) || this.onError.bind(this, { code: 404 });
66
+ this.settings = {
67
+ view: View,
68
+ xPoweredBy: true,
69
+ views: `${process.cwd()}/views`,
70
+ 'view cache': process.env.NODE_ENV === 'production',
71
+ 'trust proxy': 0,
72
+ ...options.settings
73
+ };
74
+ if (options.applyExtensions)
75
+ this.applyExtensions = options === null || options === void 0 ? void 0 : options.applyExtensions;
76
+ const boundHandler = this.handler.bind(this);
77
+ this.attach = (req, res, next) => setImmediate(boundHandler, req, res, next);
78
+ this.cache = {};
79
+ }
80
+ set(setting, value) {
81
+ this.settings[setting] = value;
82
+ return this;
83
+ }
84
+ enable(setting) {
85
+ this.settings[setting] = true;
86
+ return this;
87
+ }
88
+ enabled(setting) {
89
+ return Boolean(this.settings[setting]);
90
+ }
91
+ disable(setting) {
92
+ this.settings[setting] = false;
93
+ return this;
94
+ }
95
+ path() {
96
+ return this.parent ? this.parent.path() + this.mountpath : '';
97
+ }
98
+ engine(ext, fn) {
99
+ this.engines[ext[0] === '.' ? ext : `.${ext}`] = fn;
100
+ return this;
101
+ }
102
+ render(name, data = {}, options = {}, cb = () => { }) {
103
+ let view;
104
+ const { _locals, ...opts } = options;
105
+ let locals = this.locals;
106
+ if (_locals)
107
+ locals = { ...locals, ..._locals };
108
+ locals = { ...locals, ...data };
109
+ if (opts.cache == null)
110
+ opts.cache = this.enabled('view cache');
111
+ if (opts.cache) {
112
+ view = this.cache[name];
113
+ }
114
+ if (!view) {
115
+ const View = this.settings.view;
116
+ view = new View(name, {
117
+ defaultEngine: this.settings['view engine'],
118
+ root: this.settings.views,
119
+ engines: this.engines
120
+ });
121
+ if (!view.path) {
122
+ const dirs = Array.isArray(view.root) && view.root.length > 1
123
+ ? `directories "${view.root.slice(0, -1).join('", "')}" or "${view.root[view.root.length - 1]}"`
124
+ : `directory "${view.root}"`;
125
+ const err = new Error(`Failed to lookup view "${name}" in views ${dirs}`);
126
+ return cb(err);
127
+ }
128
+ if (opts.cache) {
129
+ this.cache[name] = view;
130
+ }
131
+ }
132
+ try {
133
+ view.render(opts, locals, cb);
134
+ }
135
+ catch (err) {
136
+ cb(err);
137
+ }
138
+ }
139
+ use(...args) {
140
+ var _a;
141
+ const base = args[0];
142
+ const fns = args.slice(1).flat();
143
+ let pathArray = [];
144
+ if (typeof base === 'function' || base instanceof App) {
145
+ fns.unshift(base);
146
+ }
147
+ else {
148
+ // if base is not an array of paths, then convert it to an array.
149
+ let basePaths = [];
150
+ if (Array.isArray(base))
151
+ basePaths = base;
152
+ else if (typeof base === 'string')
153
+ basePaths = [base];
154
+ basePaths = basePaths.filter((element) => {
155
+ if (typeof element === 'string') {
156
+ pathArray.push(element);
157
+ return false;
158
+ }
159
+ return true;
160
+ });
161
+ fns.unshift(...basePaths);
162
+ }
163
+ pathArray = pathArray.length ? pathArray.map((path) => lead(path)) : ['/'];
164
+ const mountpath = pathArray.join(', ');
165
+ let regex;
166
+ for (const fn of fns) {
167
+ if (fn instanceof App) {
168
+ for (const path of pathArray) {
169
+ regex = rg(path, true);
170
+ fn.mountpath = mountpath;
171
+ this.apps[path] = fn;
172
+ // @ts-expect-error typescript is not smart enough to understand "this" ts(2345)
173
+ fn.parent = this;
174
+ }
175
+ }
176
+ }
177
+ for (const path of pathArray) {
178
+ const handlerPaths = [];
179
+ const handlerFunctions = [];
180
+ const handlerPathBase = path === '/' ? '' : lead(path);
181
+ for (const fn of fns) {
182
+ if (fn instanceof App && ((_a = fn.middleware) === null || _a === void 0 ? void 0 : _a.length)) {
183
+ for (const mw of fn.middleware) {
184
+ handlerPaths.push(handlerPathBase + lead(mw.path));
185
+ handlerFunctions.push(fn);
186
+ }
187
+ }
188
+ else {
189
+ handlerPaths.push('');
190
+ handlerFunctions.push(fn);
191
+ }
192
+ }
193
+ pushMiddleware(this.middleware)({
194
+ path,
195
+ regex,
196
+ type: 'mw',
197
+ handler: mount(handlerFunctions[0]),
198
+ handlers: handlerFunctions.slice(1).map(mount),
199
+ fullPaths: handlerPaths
200
+ });
201
+ }
202
+ return this;
203
+ }
204
+ route(path) {
205
+ const app = new App({ settings: this.settings });
206
+ this.use(path, app);
207
+ return app;
208
+ }
209
+ handler(req, res, next) {
210
+ /* Set X-Powered-By header */
211
+ const { xPoweredBy } = this.settings;
212
+ if (xPoweredBy)
213
+ res.setHeader('X-Powered-By', typeof xPoweredBy === 'string' ? xPoweredBy : 'tinyhttp');
214
+ // @ts-expect-error typescript is not smart enough to understand "this" ts(2345)
215
+ const exts = this.applyExtensions || extendMiddleware(this);
216
+ let mw = [
217
+ {
218
+ handler: exts,
219
+ type: 'mw',
220
+ path: '/'
221
+ }
222
+ ];
223
+ req.baseUrl = '';
224
+ const handle = (mw, pathname) => async (req, res, next) => {
225
+ var _a;
226
+ const { path, handler, regex } = mw;
227
+ let params;
228
+ try {
229
+ params = regex ? getURLParams(regex, pathname) : {};
230
+ }
231
+ catch (e) {
232
+ console.error(e);
233
+ if (e instanceof URIError)
234
+ return res.sendStatus(400);
235
+ throw e;
236
+ }
237
+ // Warning: users should not use :wild as a pattern
238
+ let prefix = path;
239
+ if (regex) {
240
+ for (const key of regex.keys) {
241
+ if (key === 'wild') {
242
+ prefix = prefix.replace('*', params.wild);
243
+ }
244
+ else {
245
+ prefix = prefix.replace(`:${key}`, params[key]);
246
+ }
247
+ }
248
+ }
249
+ req.params = { ...req.params, ...params };
250
+ if (mw.type === 'mw') {
251
+ req.url = lead(req.originalUrl.substring(prefix.length));
252
+ req.baseUrl = trail(req.originalUrl.substring(0, prefix.length));
253
+ }
254
+ if (!req.path)
255
+ req.path = pathname;
256
+ if ((_a = this.settings) === null || _a === void 0 ? void 0 : _a.enableReqRoute)
257
+ req.route = mw;
258
+ await applyHandler(handler)(req, res, next);
259
+ };
260
+ let idx = 0;
261
+ const loop = () => {
262
+ req.originalUrl = req.baseUrl + req.url;
263
+ const pathname = getPathname(req.url);
264
+ const matched = __classPrivateFieldGet(this, _App_instances, "m", _App_find).call(this, pathname).filter((x) => (req.method === 'HEAD' || (x.method ? x.method === req.method : true)) && !mw.includes(x));
265
+ if (matched.length && matched[0] !== null) {
266
+ if (idx !== 0) {
267
+ idx = mw.length;
268
+ req.params = {};
269
+ }
270
+ mw = [
271
+ ...mw,
272
+ ...matched,
273
+ {
274
+ type: 'mw',
275
+ handler: (req, res, next) => {
276
+ if (req.method === 'HEAD') {
277
+ res.statusCode = 204;
278
+ return res.end('');
279
+ }
280
+ next();
281
+ },
282
+ path: '/'
283
+ }
284
+ ];
285
+ }
286
+ else if (this.parent == null) {
287
+ mw.push({
288
+ handler: this.noMatchHandler,
289
+ type: 'route',
290
+ path: '/'
291
+ });
292
+ }
293
+ void handle(mw[idx++], pathname)(req, res, next);
294
+ };
295
+ const parentNext = next;
296
+ next = (err) => {
297
+ if (err != null) {
298
+ // @ts-expect-error The 'this' context of type 'this' is not assignable to method's 'this' of type 'App<Request, Response<unknown>>' ts(2345)
299
+ return this.onError(err, req, res);
300
+ }
301
+ if (res.writableEnded)
302
+ return;
303
+ if (idx >= mw.length) {
304
+ if (parentNext != null)
305
+ parentNext();
306
+ return;
307
+ }
308
+ loop();
309
+ };
310
+ loop();
311
+ }
312
+ listen(port, cb, host) {
313
+ return createServer().on('request', this.attach).listen(port, host, cb);
314
+ }
315
+ }
316
+ _App_instances = new WeakSet(), _App_find = function _App_find(url) {
317
+ return this.middleware.filter((m) => {
318
+ m.regex = m.regex || rg(m.path, m.type === 'mw');
319
+ let fullPathRegex;
320
+ m.fullPath && typeof m.fullPath === 'string'
321
+ ? (fullPathRegex = rg(m.fullPath, m.type === 'mw'))
322
+ : (fullPathRegex = null);
323
+ return m.regex.pattern.test(url) && (m.type === 'mw' && fullPathRegex ? fullPathRegex.pattern.test(url) : true);
324
+ });
325
+ };
326
+ //# sourceMappingURL=app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.js","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAe,YAAY,EAAE,MAAM,WAAW,CAAA;AACrD,OAAO,EAAE,WAAW,EAAE,MAAM,eAAe,CAAA;AAE3C,OAAO,EAAE,MAAM,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAA;AACzD,OAAO,EAAE,KAAK,IAAI,EAAE,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AAG9C,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAA;AAC7C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAI3C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAEhC;;;GAGG;AAC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AAC,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC,IAAK,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,CAAA;QAEjD,IAAI,aAAyD,CAAA;QAE7D,CAAC,CAAC,QAAQ,IAAI,OAAO,CAAC,CAAC,QAAQ,KAAK,QAAQ;YAC1C,CAAC,CAAC,CAAC,aAAa,GAAG,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;YACnD,CAAC,CAAC,CAAC,aAAa,GAAG,IAAI,CAAC,CAAA;QAE1B,OAAO,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,IAAI,aAAa,CAAC,CAAC,CAAC,aAAa,CAAC,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAA;IACjH,CAAC,CAAC,CAAA;AACJ,CAAC"}
package/dist/extend.d.ts CHANGED
@@ -1,11 +1,8 @@
1
- import { NextFunction } from '@tinyhttp/router';
2
- import { App } from './app.js';
3
- import { Request } from './request.js';
4
- import { Response } from './response.js';
5
- import { TemplateEngineOptions } from './types.js';
6
-
1
+ import type { App } from './app.js';
2
+ import type { Handler } from './index.js';
3
+ import type { TemplateEngineOptions } from './types.js';
7
4
  /**
8
5
  * Extends Request and Response objects with custom properties and methods
9
6
  */
10
- export declare const extendMiddleware: <EngineOptions extends TemplateEngineOptions = TemplateEngineOptions>(app: App) => (req: Request, res: Response<EngineOptions>, next: NextFunction) => void;
7
+ export declare const extendMiddleware: <EngineOptions extends TemplateEngineOptions = TemplateEngineOptions>(app: App) => Handler;
11
8
  //# sourceMappingURL=extend.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"extend.d.ts","sourceRoot":"","sources":["../src/extend.ts"],"names":[],"mappings":"AAgCA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AACpD,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,EAAE,KAAK,OAAO,EAAiB,MAAM,cAAc,CAAA;AAE1D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAE7C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAEvD;;GAEG;AACH,eAAO,MAAM,gBAAgB,GAC1B,aAAa,SAAS,qBAAqB,+BAA+B,GAAG,WACxE,OAAO,OAAO,QAAQ,CAAC,aAAa,CAAC,QAAQ,YAAY,KAAG,IA4DjE,CAAA"}
1
+ {"version":3,"file":"extend.d.ts","sourceRoot":"","sources":["../src/extend.ts"],"names":[],"mappings":"AAiCA,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AACnC,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAA;AAKzC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAEvD;;GAEG;AACH,eAAO,MAAM,gBAAgB,GAAI,aAAa,SAAS,qBAAqB,+BAA+B,GAAG,KA8DtG,OAAO,CAAA"}
package/dist/extend.js ADDED
@@ -0,0 +1,63 @@
1
+ import { compile } from '@tinyhttp/proxy-addr';
2
+ import { checkIfXMLHttpRequest, getAccepts, getAcceptsCharsets, getAcceptsEncodings, getAcceptsLanguages, getFreshOrStale, getQueryParams, getRangeFromHeader, getRequestHeader } from '@tinyhttp/req';
3
+ import { append, attachment, clearCookie, download, formatResponse, getResponseHeader, json, redirect, send, sendFile, sendStatus, setContentType, setCookie, setHeader, setLinksHeader, setLocationHeader, setVaryHeader, status } from '@tinyhttp/res';
4
+ import { getSubdomains } from './request.js';
5
+ import { getHost, getIP, getIPs, getProtocol } from './request.js';
6
+ import { renderTemplate } from './response.js';
7
+ /**
8
+ * Extends Request and Response objects with custom properties and methods
9
+ */
10
+ export const extendMiddleware = (app) => ((req, res, next) => {
11
+ const { settings } = app;
12
+ res.get = getResponseHeader(res);
13
+ req.get = getRequestHeader(req);
14
+ if (settings === null || settings === void 0 ? void 0 : settings.bindAppToReqRes) {
15
+ req.app = app;
16
+ res.app = app;
17
+ }
18
+ if (settings === null || settings === void 0 ? void 0 : settings.networkExtensions) {
19
+ let trust = settings === null || settings === void 0 ? void 0 : settings['trust proxy'];
20
+ if (typeof trust !== 'function') {
21
+ trust = compile(trust);
22
+ settings['trust proxy'] = trust;
23
+ }
24
+ req.protocol = getProtocol(req, trust);
25
+ req.secure = req.protocol === 'https';
26
+ const host = getHost(req, trust);
27
+ req.hostname = host === null || host === void 0 ? void 0 : host.hostname;
28
+ req.port = host === null || host === void 0 ? void 0 : host.port;
29
+ req.subdomains = getSubdomains(req, trust, settings.subdomainOffset);
30
+ req.ip = getIP(req, trust);
31
+ req.ips = getIPs(req, trust);
32
+ }
33
+ req.query = getQueryParams(req.url);
34
+ req.range = getRangeFromHeader(req);
35
+ req.accepts = getAccepts(req);
36
+ req.acceptsCharsets = getAcceptsCharsets(req);
37
+ req.acceptsEncodings = getAcceptsEncodings(req);
38
+ req.acceptsLanguages = getAcceptsLanguages(req);
39
+ req.xhr = checkIfXMLHttpRequest(req);
40
+ res.header = res.set = setHeader(res);
41
+ res.send = send(req, res);
42
+ res.json = json(res);
43
+ res.status = status(res);
44
+ res.sendStatus = sendStatus(req, res);
45
+ res.sendFile = sendFile(req, res);
46
+ res.type = setContentType(res);
47
+ res.location = setLocationHeader(req, res);
48
+ res.links = setLinksHeader(res);
49
+ res.vary = setVaryHeader(res);
50
+ res.cookie = setCookie(req, res);
51
+ res.clearCookie = clearCookie(req, res);
52
+ res.render = renderTemplate(req, res, app);
53
+ res.format = formatResponse(req, res, next);
54
+ res.redirect = redirect(req, res, next);
55
+ res.attachment = attachment(res);
56
+ res.download = download(req, res);
57
+ res.append = append(res);
58
+ res.locals = res.locals || Object.create(null);
59
+ Object.defineProperty(req, 'fresh', { get: getFreshOrStale.bind(null, req, res), configurable: true });
60
+ req.stale = !req.fresh;
61
+ next();
62
+ });
63
+ //# sourceMappingURL=extend.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"extend.js","sourceRoot":"","sources":["../src/extend.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAA;AAC9C,OAAO,EACL,qBAAqB,EACrB,UAAU,EACV,kBAAkB,EAClB,mBAAmB,EACnB,mBAAmB,EACnB,eAAe,EACf,cAAc,EACd,kBAAkB,EAClB,gBAAgB,EACjB,MAAM,eAAe,CAAA;AACtB,OAAO,EACL,MAAM,EACN,UAAU,EACV,WAAW,EACX,QAAQ,EACR,cAAc,EACd,iBAAiB,EACjB,IAAI,EACJ,QAAQ,EACR,IAAI,EACJ,QAAQ,EACR,UAAU,EACV,cAAc,EACd,SAAS,EACT,SAAS,EACT,cAAc,EACd,iBAAiB,EACjB,aAAa,EACb,MAAM,EACP,MAAM,eAAe,CAAA;AAItB,OAAO,EAAgB,aAAa,EAAE,MAAM,cAAc,CAAA;AAC1D,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,cAAc,CAAA;AAElE,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAG9C;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAsE,GAAQ,EAAE,EAAE,CAChH,CAAC,CAAC,GAAY,EAAE,GAA4B,EAAE,IAAkB,EAAE,EAAE;IAClE,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAA;IAExB,GAAG,CAAC,GAAG,GAAG,iBAAiB,CAAC,GAAG,CAAC,CAAA;IAChC,GAAG,CAAC,GAAG,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAA;IAE/B,IAAI,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,eAAe,EAAE,CAAC;QAC9B,GAAG,CAAC,GAAG,GAAG,GAAG,CAAA;QACb,GAAG,CAA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AQ,GAAG,QAAQ,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,CAAC,CAAA;IACvC,GAAG,CAAC,UAAU,GAAG,UAAU,CAAW,GAAG,CAAC,CAAA;IAC1C,GAAG,CAAC,QAAQ,GAAG,QAAQ,CAAoB,GAAG,EAAE,GAAG,CAAC,CAAA;IACpD,GAAG,CAAC,MAAM,GAAG,MAAM,CAAW,GAAG,CAAC,CAAA;IAClC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;IAE9C,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,eAAe,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,CAAC,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAA;IACtG,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,CAAC,KAAK,CAAA;IAEtB,IAAI,EAAE,CAAA;AACR,CAAC,CAAY,CAAA"}
package/dist/index.d.ts CHANGED
@@ -1,6 +1,3 @@
1
- import { Middleware, NextFunction, AsyncHandler as RAsyncHandler, Handler as RHandler, SyncHandler as RSyncHandler } from '@tinyhttp/router';
2
- import { Request } from './request.js';
3
- import { Response } from './response.js';
4
1
  export { App } from './app.js';
5
2
  export * from './request.js';
6
3
  export * from './response.js';
@@ -8,6 +5,9 @@ export { extendMiddleware } from './extend.js';
8
5
  export { onErrorHandler, type ErrorHandler } from './onError.js';
9
6
  export { View } from './view.js';
10
7
  export type { AppSettings, TemplateEngineOptions, TemplateEngine, AppConstructor } from './types.js';
8
+ import type { Middleware, NextFunction, AsyncHandler as RAsyncHandler, Handler as RHandler, SyncHandler as RSyncHandler } from '@tinyhttp/router';
9
+ import type { Request } from './request.js';
10
+ import type { Response } from './response.js';
11
11
  export type Handler = RHandler<Request, Response>;
12
12
  export type AsyncHandler = RAsyncHandler<Request, Response>;
13
13
  export type SyncHandler = RSyncHandler<Request, Response>;