ovr 3.0.0 → 4.0.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.
Files changed (62) hide show
  1. package/dist/app/context.d.ts +1 -0
  2. package/dist/app/context.d.ts.map +1 -0
  3. package/dist/app/context.js +46 -27
  4. package/dist/app/{page.d.ts → get.d.ts} +5 -6
  5. package/dist/app/get.d.ts.map +1 -0
  6. package/dist/app/{page.js → get.js} +4 -6
  7. package/dist/app/index.d.ts +5 -4
  8. package/dist/app/index.d.ts.map +1 -0
  9. package/dist/app/index.js +7 -7
  10. package/dist/app/memo/index.d.ts +1 -0
  11. package/dist/app/memo/index.d.ts.map +1 -0
  12. package/dist/app/mw/csrf.d.ts +1 -0
  13. package/dist/app/mw/csrf.d.ts.map +1 -0
  14. package/dist/app/{action.d.ts → post.d.ts} +8 -9
  15. package/dist/app/post.d.ts.map +1 -0
  16. package/dist/app/{action.js → post.js} +1 -1
  17. package/dist/index.d.ts +3 -2
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +2 -2
  20. package/dist/jsx/chunk/index.d.ts +14 -11
  21. package/dist/jsx/chunk/index.d.ts.map +1 -0
  22. package/dist/jsx/chunk/index.js +26 -28
  23. package/dist/jsx/index.d.ts +13 -9
  24. package/dist/jsx/index.d.ts.map +1 -0
  25. package/dist/jsx/index.js +57 -36
  26. package/dist/jsx/{elements.d.ts → intrinsic-elements.d.ts} +2 -1
  27. package/dist/jsx/intrinsic-elements.d.ts.map +1 -0
  28. package/dist/jsx/{merge-async-iterables.d.ts → merge-async-generators.d.ts} +2 -4
  29. package/dist/jsx/merge-async-generators.d.ts.map +1 -0
  30. package/dist/jsx/{merge-async-iterables.js → merge-async-generators.js} +7 -9
  31. package/dist/jsx-dev-runtime.d.ts +1 -0
  32. package/dist/jsx-dev-runtime.d.ts.map +1 -0
  33. package/dist/jsx-runtime.d.ts +1 -0
  34. package/dist/jsx-runtime.d.ts.map +1 -0
  35. package/dist/trie/index.d.ts +1 -0
  36. package/dist/trie/index.d.ts.map +1 -0
  37. package/dist/trie/insert-params.d.ts +1 -0
  38. package/dist/trie/insert-params.d.ts.map +1 -0
  39. package/dist/types/index.d.ts +1 -0
  40. package/dist/types/index.d.ts.map +1 -0
  41. package/dist/util/hash.d.ts +10 -0
  42. package/dist/util/hash.d.ts.map +1 -0
  43. package/dist/util/hash.js +9 -2
  44. package/package.json +4 -2
  45. package/src/app/context.ts +350 -0
  46. package/src/app/get.ts +54 -0
  47. package/src/app/index.ts +302 -0
  48. package/src/app/memo/index.ts +40 -0
  49. package/src/app/mw/csrf.ts +28 -0
  50. package/src/app/post.ts +79 -0
  51. package/src/index.ts +9 -0
  52. package/src/jsx/chunk/index.ts +68 -0
  53. package/src/jsx/index.ts +247 -0
  54. package/src/jsx/intrinsic-elements.ts +812 -0
  55. package/src/jsx/merge-async-generators.ts +42 -0
  56. package/src/jsx-dev-runtime.ts +1 -0
  57. package/src/jsx-runtime.ts +1 -0
  58. package/src/trie/index.ts +335 -0
  59. package/src/trie/insert-params.ts +31 -0
  60. package/src/types/index.ts +23 -0
  61. package/src/util/hash.ts +17 -0
  62. /package/dist/jsx/{elements.js → intrinsic-elements.js} +0 -0
@@ -0,0 +1,350 @@
1
+ import { Chunk } from "../jsx/chunk/index.js";
2
+ import { type JSX, toGenerator } from "../jsx/index.js";
3
+ import type { Route } from "../trie/index.js";
4
+ import { hash } from "../util/hash.js";
5
+ import {
6
+ App,
7
+ type ErrorHandler,
8
+ type Middleware,
9
+ type NotFoundHandler,
10
+ type Params,
11
+ type TrailingSlash,
12
+ } from "./index.js";
13
+ import { Memo } from "./memo/index.js";
14
+
15
+ type Layout = (props: { children: JSX.Element }) => JSX.Element;
16
+
17
+ class TagNotFound extends Error {
18
+ constructor(tag: string) {
19
+ super(`No closing ${tag} tag found`);
20
+ this.name = "TagNotFound";
21
+ }
22
+ }
23
+
24
+ export class Context<P extends Params = Params> {
25
+ /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request) */
26
+ req: Request;
27
+
28
+ /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URL) */
29
+ url: URL;
30
+
31
+ /**
32
+ * Route pattern parameters
33
+ *
34
+ * Given the route pattern `/posts/:slug` is added, a request made to
35
+ * `/posts/my-post` creates a `params` object `{ slug: "my-post" }`.
36
+ *
37
+ * @example { slug: "my-post" }
38
+ */
39
+ params!: P; // set after match
40
+
41
+ /** The matched `Route` instance. */
42
+ route!: Route<Middleware<P>[]>; // set after match
43
+
44
+ /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#body) */
45
+ body: BodyInit | null = null;
46
+
47
+ /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) */
48
+ status?: number;
49
+
50
+ /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Headers) */
51
+ headers = new Headers();
52
+
53
+ #layouts: Layout[] = [];
54
+
55
+ #headElements: JSX.Element[] = [];
56
+
57
+ #trailingSlash: TrailingSlash;
58
+
59
+ /** Passed from `app.base` */
60
+ base: string;
61
+
62
+ /** Passed from `app.error` */
63
+ error: ErrorHandler<P>;
64
+
65
+ /** Passed from `app.notFound` */
66
+ notFound: NotFoundHandler<P>;
67
+
68
+ #memo = new Memo();
69
+
70
+ memo = this.#memo.use;
71
+
72
+ constructor(
73
+ req: Request,
74
+ url: URL,
75
+ trailingSlash: TrailingSlash,
76
+ base: string,
77
+ error: ErrorHandler<P>,
78
+ notFound: NotFoundHandler<P>,
79
+ ) {
80
+ this.req = req;
81
+ this.url = url;
82
+ this.#trailingSlash = trailingSlash;
83
+ this.base = base;
84
+ this.error = error;
85
+ this.notFound = notFound;
86
+ }
87
+
88
+ /**
89
+ * Mirrors `new Response()` constructor, set values with one function.
90
+ *
91
+ * @param body Response BodyInit
92
+ * @param init Enhanced ResponseInit
93
+ */
94
+ res(
95
+ body: BodyInit | null,
96
+ init?: {
97
+ /**
98
+ * [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
99
+ *
100
+ * @default 200
101
+ */
102
+ status?: number;
103
+
104
+ /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Headers) */
105
+ headers?: HeadersInit;
106
+ },
107
+ ) {
108
+ this.body = body;
109
+ this.status = init?.status ?? 200;
110
+
111
+ if (init?.headers) {
112
+ for (const [name, value] of new Headers(init.headers)) {
113
+ this.headers.set(name, value);
114
+ }
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Creates an HTML response.
120
+ *
121
+ * @param body HTML body
122
+ * @param status [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
123
+ */
124
+ html(body: BodyInit | null, status?: number) {
125
+ this.res(body, {
126
+ status,
127
+ headers: { "content-type": "text/html; charset=utf-8" },
128
+ });
129
+ }
130
+
131
+ /**
132
+ * Creates a JSON response.
133
+ *
134
+ * @param data passed into JSON.stringify to create the body
135
+ * @param status [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
136
+ */
137
+ json(data: any, status?: number) {
138
+ this.res(JSON.stringify(data), {
139
+ status,
140
+ headers: { "content-type": "application/json" },
141
+ });
142
+ }
143
+
144
+ /**
145
+ * Creates a plain text response.
146
+ *
147
+ * @param body response body
148
+ * @param status [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
149
+ */
150
+ text(body: BodyInit, status?: number) {
151
+ this.res(body, {
152
+ status,
153
+ headers: { "content-type": "text/plain; charset=utf-8" },
154
+ });
155
+ }
156
+
157
+ /**
158
+ * Creates a redirect response.
159
+ *
160
+ * @param location redirect `Location` header
161
+ * @param status HTTP status code
162
+ *
163
+ * - [301 Moved Permanently](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/301)
164
+ * - [302 Found](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302) (default)
165
+ * - [303 See Other](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/303)
166
+ * - [307 Temporary Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/307)
167
+ * - [308 Permanent Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308)
168
+ */
169
+ redirect(location: string | URL, status: 301 | 302 | 303 | 307 | 308 = 302) {
170
+ this.headers.set("location", location.toString());
171
+ this.status = status;
172
+ }
173
+
174
+ /**
175
+ * @param Element `JSX.Element` to add to the head
176
+ */
177
+ head(...Element: JSX.Element[]) {
178
+ this.#headElements.push(...Element);
179
+ }
180
+
181
+ /**
182
+ * @param Layout `Layout`(s) for the `Page` to be passed into before being injected into the `<body>`
183
+ */
184
+ layout(...Layout: Layout[]) {
185
+ this.#layouts.push(...Layout);
186
+ }
187
+
188
+ /**
189
+ * Creates an HTML response based on the `head` elements, `Layout`(s), and `Page` provided.
190
+ *
191
+ * @param Page `JSX.Element` to inject into the `<body>`
192
+ * @param status [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
193
+ */
194
+ page(Page: JSX.Element, status?: number) {
195
+ for (let i = this.#layouts.length - 1; i >= 0; i--) {
196
+ Page = this.#layouts[i]!({ children: Page });
197
+ }
198
+
199
+ let gen: AsyncGenerator<Chunk, void>;
200
+
201
+ if (this.base) {
202
+ // inject into base
203
+ const headClose = "</head>";
204
+ const bodyClose = "</body>";
205
+
206
+ const elements: JSX.Element[] = this.base.split(headClose);
207
+ if (!elements[1]) throw new TagNotFound(headClose);
208
+
209
+ elements.splice(1, 0, this.#headElements, headClose);
210
+
211
+ const bodyParts = (elements[3] as string).split(bodyClose);
212
+ if (!bodyParts[1]) throw new TagNotFound(bodyClose);
213
+
214
+ const userAgent = this.req.headers.get("user-agent");
215
+ if (userAgent?.includes("Safari") && !userAgent.includes("Chrome")) {
216
+ // https://bugs.webkit.org/show_bug.cgi?id=252413
217
+ // https://github.com/sveltejs/kit/issues/10315
218
+ // https://github.com/remix-run/remix/issues/5804
219
+ bodyParts[0] += `<div aria-hidden=true style=position:absolute;width:0;height:0;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border-width:0>${"\u200b".repeat(200)}</div>`;
220
+ }
221
+
222
+ elements[3] = bodyParts[0];
223
+ elements.push(Page, bodyClose + bodyParts[1]);
224
+
225
+ gen = toGenerator(
226
+ elements.map((el) => {
227
+ if (typeof el === "string") return new Chunk(el, true);
228
+ return el;
229
+ }),
230
+ );
231
+ } else {
232
+ // HTML partial - just use the layouts + page
233
+ gen = toGenerator(Page);
234
+ }
235
+
236
+ this.html(
237
+ new ReadableStream<string>({
238
+ pull: async (c) => {
239
+ if (this.req.signal.aborted) {
240
+ c.close();
241
+ gen.return();
242
+ return;
243
+ }
244
+
245
+ const result = await gen.next();
246
+ if (result.done) c.close();
247
+ else c.enqueue(result.value.value);
248
+ },
249
+
250
+ cancel() {
251
+ gen.return();
252
+ },
253
+ }).pipeThrough(new TextEncoderStream()),
254
+ status,
255
+ );
256
+ }
257
+
258
+ /**
259
+ * Generates an etag from a hash of the string provided.
260
+ * If the etag matches, sets the response to not modified.
261
+ *
262
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag)
263
+ *
264
+ * @param s string to hash
265
+ * @returns `true` if the etag matches, `false` otherwise
266
+ */
267
+ etag(s: string) {
268
+ const etag = `"${hash(s)}"`;
269
+
270
+ this.headers.set("etag", etag);
271
+
272
+ if (this.req.headers.get("if-none-match") === etag) {
273
+ this.body = null;
274
+ this.status = 304;
275
+
276
+ return true;
277
+ }
278
+
279
+ return false;
280
+ }
281
+
282
+ /**
283
+ * @returns the constructed `Response`
284
+ */
285
+ build() {
286
+ if (this.req.signal.aborted) {
287
+ // user cancelled the request
288
+ this.body = null;
289
+ this.status = 408;
290
+ }
291
+
292
+ if (
293
+ (!this.status || this.status === 404) &&
294
+ this.#trailingSlash !== "ignore"
295
+ ) {
296
+ const last = this.url.pathname.at(-1);
297
+
298
+ if (this.#trailingSlash === "always" && last !== "/") {
299
+ this.url.pathname += "/";
300
+ this.redirect(this.url, 308);
301
+ } else if (
302
+ this.#trailingSlash === "never" &&
303
+ this.url.pathname !== "/" &&
304
+ last === "/"
305
+ ) {
306
+ this.url.pathname = this.url.pathname.slice(0, -1);
307
+ this.redirect(this.url, 308);
308
+ }
309
+ }
310
+
311
+ if (!this.body && !this.status) this.notFound(this);
312
+
313
+ return new Response(this.body, this);
314
+ }
315
+
316
+ /**
317
+ * Call within the scope of a handler to get the current context.
318
+ *
319
+ * @returns Request context
320
+ *
321
+ * @example
322
+ *
323
+ * ```ts
324
+ * import { Context } from "ovr";
325
+ *
326
+ * const app = new Router();
327
+ *
328
+ * const fn = () => {
329
+ * const c = Context.get();
330
+ * // ...
331
+ * }
332
+ *
333
+ * app.get("/", () => {
334
+ * fn(); // OK
335
+ * });
336
+ *
337
+ * fn() // ReferenceError - outside AsyncLocalStorage scope
338
+ * ```
339
+ */
340
+ static get() {
341
+ const c = App.storage.getStore();
342
+
343
+ if (!c)
344
+ throw new ReferenceError(
345
+ "Context can only be obtained within a handler.",
346
+ );
347
+
348
+ return c;
349
+ }
350
+ }
package/src/app/get.ts ADDED
@@ -0,0 +1,54 @@
1
+ import { type JSX, jsx } from "../jsx/index.js";
2
+ import { insertParams } from "../trie/insert-params.js";
3
+ import type { ExtractParams } from "../types/index.js";
4
+ import type { Middleware, Params } from "./index.js";
5
+
6
+ type AnchorProps<P extends Params> = JSX.IntrinsicElements["a"] &
7
+ (keyof P extends never ? { params?: never } : { params: P });
8
+
9
+ export class Get<Pattern extends string = string> {
10
+ /** Route pattern */
11
+ pattern: Pattern;
12
+
13
+ /** GET middleware */
14
+ middleware: Middleware<any>[];
15
+
16
+ /** `<a>` component with preset `href` attribute. */
17
+ Anchor: (props: AnchorProps<ExtractParams<Pattern>>) => JSX.Element;
18
+
19
+ #parts: string[];
20
+
21
+ /**
22
+ * @param pattern Route pattern
23
+ * @param middleware GET middleware
24
+ *
25
+ * @example
26
+ *
27
+ * ```tsx
28
+ * import { Get } from "ovr";
29
+ *
30
+ * const page = new Get("/", () => {
31
+ * return <p>Hello world</p>
32
+ * });
33
+ *
34
+ * const Nav = () => {
35
+ * return <page.Anchor>Home</page.Anchor>
36
+ * }
37
+ *
38
+ * app.add(page); register
39
+ * ```
40
+ */
41
+ constructor(
42
+ pattern: Pattern,
43
+ ...middleware: Middleware<ExtractParams<Pattern>>[]
44
+ ) {
45
+ this.pattern = pattern;
46
+ this.middleware = middleware;
47
+ this.#parts = pattern.split("/");
48
+ this.Anchor = (props) => {
49
+ const { params = {}, ...rest } = props;
50
+
51
+ return jsx("a", { href: insertParams(this.#parts, params), ...rest });
52
+ };
53
+ }
54
+ }
@@ -0,0 +1,302 @@
1
+ import { Route, Trie } from "../trie/index.js";
2
+ import type {
3
+ DeepArray,
4
+ ExtractMultiParams,
5
+ ExtractParams,
6
+ } from "../types/index.js";
7
+ import { Context } from "./context.js";
8
+ import { Get } from "./get.js";
9
+ import { Post } from "./post.js";
10
+ import { AsyncLocalStorage } from "node:async_hooks";
11
+
12
+ export type Params = Record<string, string>;
13
+
14
+ export type Middleware<P extends Params = Params> = (
15
+ context: Context<P>,
16
+ next: () => Promise<void>,
17
+ ) => any;
18
+
19
+ export type TrailingSlash = "always" | "never" | "ignore";
20
+
21
+ type Method =
22
+ | "GET"
23
+ | "HEAD"
24
+ | "POST"
25
+ | "PUT"
26
+ | "DELETE"
27
+ | "CONNECT"
28
+ | "OPTIONS"
29
+ | "TRACE"
30
+ | "PATCH"
31
+ | (string & {});
32
+
33
+ type UnmatchedContext<P extends Params = Params> = Omit<Context<P>, "route"> &
34
+ // route might be defined
35
+ Partial<Pick<Context<P>, "route">>;
36
+
37
+ export type ErrorHandler<P extends Params = Params> =
38
+ | ((context: UnmatchedContext<P>, error: unknown) => any)
39
+ | null;
40
+
41
+ export type NotFoundHandler<P extends Params = Params> = (
42
+ context: UnmatchedContext<P>,
43
+ ) => any;
44
+
45
+ export class App {
46
+ // allows for users to put other properties on the app
47
+ [key: string | symbol | number]: any;
48
+
49
+ /** Built tries per HTTP method. */
50
+ #trieMap = new Map<Method, Trie<Middleware[]>>();
51
+
52
+ /** Added routes per HTTP method. */
53
+ #routesMap = new Map<Method, Route<Middleware[]>[]>();
54
+
55
+ /** Global middleware. */
56
+ #use: Middleware[] = [];
57
+
58
+ /**
59
+ * - `"never"` - Not found requests with a trailing slash will be redirected to the same path without a trailing slash
60
+ * - `"always"` - Not found requests without a trailing slash will be redirected to the same path with a trailing slash
61
+ * - `"ignore"` - no redirects (not recommended, bad for SEO)
62
+ *
63
+ * [Trailing Slash for Frameworks by Bjorn Lu](https://bjornlu.com/blog/trailing-slash-for-frameworks)
64
+ *
65
+ * @default "never"
66
+ */
67
+ trailingSlash: TrailingSlash = "never";
68
+
69
+ /**
70
+ * Base HTML to inject the `head` and `page` elements into.
71
+ *
72
+ * @default
73
+ *
74
+ * ```html
75
+ * <!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>
76
+ * ```
77
+ */
78
+ base =
79
+ '<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>';
80
+
81
+ /**
82
+ * Assign a handler to run when an `Error` is thrown.
83
+ *
84
+ * If not set, `Error` will be thrown. This might be desired
85
+ * if your server already includes error handling. Set in `config.start`
86
+ * to handle errors globally.
87
+ *
88
+ * @default null
89
+ */
90
+ error: ErrorHandler = null;
91
+
92
+ /**
93
+ * Middleware to run when no `body` or `status` has been set on the `context`.
94
+ * Set to a new function to override the default.
95
+ *
96
+ * @default
97
+ *
98
+ * ```ts
99
+ * (c) => c.html("Not found", 404)
100
+ * ```
101
+ */
102
+ notFound: NotFoundHandler = (c) => c.html("Not found", 404);
103
+
104
+ /** Stores context per request. */
105
+ static storage = new AsyncLocalStorage<Context>();
106
+
107
+ /**
108
+ * @param routes `Get` or `Post` to add to `App`
109
+ * @returns `App` instance
110
+ */
111
+ add(...routes: DeepArray<Get | Post | Record<string, Get | Post>>[]) {
112
+ for (const route of routes) {
113
+ if (route instanceof Array) {
114
+ this.add(...route);
115
+ } else if (route instanceof Get) {
116
+ this.get(route.pattern, ...route.middleware);
117
+ } else if (route instanceof Post) {
118
+ this.post(route.pattern, ...route.middleware);
119
+ } else {
120
+ this.add(...Object.values(route));
121
+ }
122
+ }
123
+
124
+ return this;
125
+ }
126
+
127
+ /**
128
+ * Add global middleware.
129
+ *
130
+ * @param middleware
131
+ * @returns `App` instance
132
+ */
133
+ use(...middleware: Middleware[]) {
134
+ this.#use.push(...middleware);
135
+ return this;
136
+ }
137
+
138
+ /**
139
+ * @param method HTTP method
140
+ * @param pattern Route pattern
141
+ * @param middleware
142
+ * @returns `App` instance
143
+ */
144
+ on<Pattern extends string>(
145
+ method: Method | Method[],
146
+ pattern: Pattern,
147
+ ...middleware: Middleware<ExtractParams<Pattern>>[]
148
+ ): this;
149
+ /**
150
+ * @param method HTTP method
151
+ * @param patterns Array of route patterns
152
+ * @param middleware
153
+ * @returns `App` instance
154
+ */
155
+ on<Patterns extends string[]>(
156
+ method: Method | Method[],
157
+ patterns: [...Patterns],
158
+ ...middleware: Middleware<ExtractMultiParams<Patterns>>[]
159
+ ): this;
160
+ on<PatternOrPatterns extends string | string[]>(
161
+ method: Method | Method[],
162
+ pattern: PatternOrPatterns,
163
+ ...middleware: Middleware[]
164
+ ) {
165
+ if (!Array.isArray(method)) method = [method];
166
+
167
+ let patterns: string[];
168
+ if (!Array.isArray(pattern)) patterns = [pattern];
169
+ else patterns = pattern;
170
+
171
+ for (const p of patterns) {
172
+ const route = new Route(p, middleware);
173
+
174
+ for (const m of method) {
175
+ const routes = this.#routesMap.get(m);
176
+
177
+ if (routes) routes.push(route);
178
+ else this.#routesMap.set(m, [route]);
179
+ }
180
+ }
181
+
182
+ return this;
183
+ }
184
+
185
+ /**
186
+ * @param pattern Route pattern
187
+ * @param middleware
188
+ * @returns `App` instance
189
+ */
190
+ get<Pattern extends string>(
191
+ pattern: Pattern,
192
+ ...middleware: Middleware<ExtractParams<Pattern>>[]
193
+ ): this;
194
+ /**
195
+ * @param patterns Array of route patterns
196
+ * @param middleware
197
+ * @returns `App` instance
198
+ */
199
+ get<Patterns extends string[]>(
200
+ patterns: [...Patterns],
201
+ ...middleware: Middleware<ExtractMultiParams<Patterns>>[]
202
+ ): this;
203
+ get<PatternOrPatterns extends string | string[]>(
204
+ patternOrPatterns: PatternOrPatterns,
205
+ ...middleware: Middleware[]
206
+ ) {
207
+ return this.on("GET", patternOrPatterns as string, ...middleware);
208
+ }
209
+
210
+ /**
211
+ * @param pattern Route pattern
212
+ * @param middleware
213
+ * @returns the router instance
214
+ */
215
+ post<Pattern extends string>(
216
+ pattern: Pattern,
217
+ ...middleware: Middleware<ExtractParams<Pattern>>[]
218
+ ): this;
219
+ /**
220
+ * @param patterns Array of route patterns
221
+ * @param middleware
222
+ * @returns the router instance
223
+ */
224
+ post<Patterns extends string[]>(
225
+ patterns: [...Patterns],
226
+ ...middleware: Middleware<ExtractMultiParams<Patterns>>[]
227
+ ): this;
228
+ post<PatternOrPatterns extends string | string[]>(
229
+ patternOrPatterns: PatternOrPatterns,
230
+ ...middleware: Middleware[]
231
+ ): this {
232
+ return this.on("POST", patternOrPatterns as string, ...middleware);
233
+ }
234
+
235
+ /**
236
+ * @param req [`Request` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
237
+ * @returns [`Response` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response)
238
+ */
239
+ fetch = (req: Request): Promise<Response> => {
240
+ const c = new Context(
241
+ req,
242
+ new URL(req.url),
243
+ this.trailingSlash,
244
+ this.base,
245
+ this.error,
246
+ this.notFound,
247
+ );
248
+
249
+ return App.storage.run(c, async () => {
250
+ try {
251
+ // check to see if the method is already built
252
+ let trie = this.#trieMap.get(req.method);
253
+
254
+ if (!trie) {
255
+ // check if there are any routes with the method
256
+ const routes = this.#routesMap.get(req.method);
257
+
258
+ if (routes) {
259
+ // build trie
260
+ trie = new Trie<Middleware[]>();
261
+ for (const route of routes) trie.add(route);
262
+ this.#trieMap.set(req.method, trie);
263
+ }
264
+ }
265
+
266
+ if (trie) {
267
+ const match = trie.find(c.url.pathname);
268
+
269
+ if (match) {
270
+ Object.assign(c, match);
271
+
272
+ const middleware = [...this.#use, ...match.route.store];
273
+
274
+ // compose
275
+ let i = -1;
276
+ const dispatch = async (current: number): Promise<void> => {
277
+ if (current <= i) throw new Error("next() called multiple times");
278
+ i = current;
279
+
280
+ if (middleware[current]) {
281
+ const result: unknown = await middleware[current](c, () =>
282
+ dispatch(current + 1),
283
+ );
284
+
285
+ if (result instanceof Response) c.res(result.body, result);
286
+ else if (result instanceof ReadableStream) c.body = result;
287
+ else if (result != null) c.page(result);
288
+ }
289
+ };
290
+
291
+ await dispatch(0);
292
+ }
293
+ }
294
+ } catch (error) {
295
+ if (c.error) c.error(c, error);
296
+ else throw error;
297
+ }
298
+
299
+ return c.build();
300
+ });
301
+ };
302
+ }