ovr 3.0.0 → 3.0.1
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/action.d.ts +1 -0
- package/dist/app/action.d.ts.map +1 -0
- package/dist/app/context.d.ts +1 -0
- package/dist/app/context.d.ts.map +1 -0
- package/dist/app/index.d.ts +1 -0
- package/dist/app/index.d.ts.map +1 -0
- package/dist/app/index.js +1 -1
- package/dist/app/memo/index.d.ts +1 -0
- package/dist/app/memo/index.d.ts.map +1 -0
- package/dist/app/mw/csrf.d.ts +1 -0
- package/dist/app/mw/csrf.d.ts.map +1 -0
- package/dist/app/page.d.ts +1 -0
- package/dist/app/page.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/jsx/chunk/index.d.ts +14 -11
- package/dist/jsx/chunk/index.d.ts.map +1 -0
- package/dist/jsx/chunk/index.js +29 -28
- package/dist/jsx/index.d.ts +13 -9
- package/dist/jsx/index.d.ts.map +1 -0
- package/dist/jsx/index.js +48 -36
- package/dist/jsx/{elements.d.ts → intrinsic-elements.d.ts} +2 -1
- package/dist/jsx/intrinsic-elements.d.ts.map +1 -0
- package/dist/jsx/{merge-async-iterables.d.ts → merge-async-generators.d.ts} +1 -0
- package/dist/jsx/merge-async-generators.d.ts.map +1 -0
- package/dist/jsx-dev-runtime.d.ts +1 -0
- package/dist/jsx-dev-runtime.d.ts.map +1 -0
- package/dist/jsx-runtime.d.ts +1 -0
- package/dist/jsx-runtime.d.ts.map +1 -0
- package/dist/trie/index.d.ts +1 -0
- package/dist/trie/index.d.ts.map +1 -0
- package/dist/trie/insert-params.d.ts +1 -0
- package/dist/trie/insert-params.d.ts.map +1 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/util/hash.d.ts +10 -0
- package/dist/util/hash.d.ts.map +1 -0
- package/dist/util/hash.js +9 -2
- package/package.json +4 -2
- package/src/app/action.ts +81 -0
- package/src/app/context.ts +329 -0
- package/src/app/index.ts +302 -0
- package/src/app/memo/index.ts +40 -0
- package/src/app/mw/csrf.ts +28 -0
- package/src/app/page.ts +56 -0
- package/src/index.ts +9 -0
- package/src/jsx/chunk/index.ts +70 -0
- package/src/jsx/index.ts +235 -0
- package/src/jsx/intrinsic-elements.ts +812 -0
- package/src/jsx/merge-async-generators.ts +42 -0
- package/src/jsx-dev-runtime.ts +1 -0
- package/src/jsx-runtime.ts +1 -0
- package/src/trie/index.ts +335 -0
- package/src/trie/insert-params.ts +31 -0
- package/src/types/index.ts +23 -0
- package/src/util/hash.ts +17 -0
- /package/dist/jsx/{elements.js → intrinsic-elements.js} +0 -0
- /package/dist/jsx/{merge-async-iterables.js → merge-async-generators.js} +0 -0
|
@@ -0,0 +1,81 @@
|
|
|
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 { hash } from "../util/hash.js";
|
|
5
|
+
import type { Middleware, Params } from "./index.js";
|
|
6
|
+
|
|
7
|
+
type FormProps<P extends Params> = JSX.IntrinsicElements["form"] &
|
|
8
|
+
(keyof P extends never ? { params?: never } : { params: P });
|
|
9
|
+
|
|
10
|
+
export class Action<Pattern extends string = string> {
|
|
11
|
+
/** Route pattern */
|
|
12
|
+
pattern: Pattern;
|
|
13
|
+
|
|
14
|
+
/** POST middleware */
|
|
15
|
+
middleware: Middleware<any>[];
|
|
16
|
+
|
|
17
|
+
/** `<form>` component with preset `method` and `action` attributes. */
|
|
18
|
+
Form: (props: FormProps<ExtractParams<Pattern>>) => JSX.Element;
|
|
19
|
+
|
|
20
|
+
#parts: string[] = [];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param middleware POST middleware
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
*
|
|
27
|
+
* ```tsx
|
|
28
|
+
* // action.tsx
|
|
29
|
+
* import { Action } from "ovr";
|
|
30
|
+
*
|
|
31
|
+
* export const action = new Action((c) => {
|
|
32
|
+
* console.log("posted");
|
|
33
|
+
* c.redirect("/", 303);
|
|
34
|
+
* });
|
|
35
|
+
*
|
|
36
|
+
* export const page = new Page("/", () => (
|
|
37
|
+
* <action.Form>
|
|
38
|
+
* <input />
|
|
39
|
+
* <button>Submit</button>
|
|
40
|
+
* </action.Form>
|
|
41
|
+
* ));
|
|
42
|
+
*
|
|
43
|
+
* // app.tsx
|
|
44
|
+
* app.add(page, action); registers the action
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
constructor(...middleware: Middleware<{}>[]);
|
|
48
|
+
/**
|
|
49
|
+
* @param pattern Route pattern
|
|
50
|
+
* @param middleware POST middleware
|
|
51
|
+
*/
|
|
52
|
+
constructor(
|
|
53
|
+
pattern: Pattern,
|
|
54
|
+
...middleware: Middleware<ExtractParams<Pattern>>[]
|
|
55
|
+
);
|
|
56
|
+
constructor(
|
|
57
|
+
patternOrMiddleware: Pattern | Middleware<ExtractParams<Pattern>>,
|
|
58
|
+
...middleware: Middleware<ExtractParams<Pattern>>[]
|
|
59
|
+
) {
|
|
60
|
+
this.middleware = middleware;
|
|
61
|
+
|
|
62
|
+
if (typeof patternOrMiddleware === "string") {
|
|
63
|
+
this.pattern = patternOrMiddleware;
|
|
64
|
+
} else {
|
|
65
|
+
this.middleware.unshift(patternOrMiddleware);
|
|
66
|
+
this.pattern = `/_action/${hash(this.middleware.join())}` as Pattern;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
this.#parts = this.pattern.split("/");
|
|
70
|
+
|
|
71
|
+
this.Form = (props) => {
|
|
72
|
+
const { params = {}, ...rest } = props;
|
|
73
|
+
|
|
74
|
+
return jsx("form", {
|
|
75
|
+
action: insertParams(this.#parts, params),
|
|
76
|
+
method: "post",
|
|
77
|
+
...rest,
|
|
78
|
+
});
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,329 @@
|
|
|
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
|
+
const headClose = "</head>";
|
|
199
|
+
const bodyClose = "</body>";
|
|
200
|
+
|
|
201
|
+
const elements: JSX.Element[] = this.base.split(headClose);
|
|
202
|
+
if (!elements[1]) throw new TagNotFound(headClose);
|
|
203
|
+
|
|
204
|
+
elements.splice(1, 0, this.#headElements, headClose);
|
|
205
|
+
|
|
206
|
+
const bodyParts = (elements[3] as string).split(bodyClose);
|
|
207
|
+
if (!bodyParts[1]) throw new TagNotFound(bodyClose);
|
|
208
|
+
|
|
209
|
+
const userAgent = this.req.headers.get("user-agent");
|
|
210
|
+
if (userAgent?.includes("Safari") && !userAgent.includes("Chrome")) {
|
|
211
|
+
// https://bugs.webkit.org/show_bug.cgi?id=252413
|
|
212
|
+
// https://github.com/sveltejs/kit/issues/10315
|
|
213
|
+
// https://github.com/remix-run/remix/issues/5804
|
|
214
|
+
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>`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
elements[3] = bodyParts[0];
|
|
218
|
+
elements.push(Page, bodyClose + bodyParts[1]);
|
|
219
|
+
|
|
220
|
+
const gen = toGenerator(
|
|
221
|
+
elements.map((el) => {
|
|
222
|
+
if (typeof el === "string") return new Chunk(el, true);
|
|
223
|
+
return el;
|
|
224
|
+
}),
|
|
225
|
+
);
|
|
226
|
+
|
|
227
|
+
this.html(
|
|
228
|
+
new ReadableStream<string>({
|
|
229
|
+
async pull(c) {
|
|
230
|
+
const { value, done } = await gen.next();
|
|
231
|
+
if (done) c.close();
|
|
232
|
+
else c.enqueue(value?.value);
|
|
233
|
+
},
|
|
234
|
+
|
|
235
|
+
cancel() {
|
|
236
|
+
gen.return();
|
|
237
|
+
},
|
|
238
|
+
}).pipeThrough(new TextEncoderStream()),
|
|
239
|
+
status,
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Generates an etag from a hash of the string provided.
|
|
245
|
+
* If the etag matches, sets the response to not modified.
|
|
246
|
+
*
|
|
247
|
+
* [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag)
|
|
248
|
+
*
|
|
249
|
+
* @param s string to hash
|
|
250
|
+
* @returns `true` if the etag matches, `false` otherwise
|
|
251
|
+
*/
|
|
252
|
+
etag(s: string) {
|
|
253
|
+
const etag = `"${hash(s)}"`;
|
|
254
|
+
|
|
255
|
+
this.headers.set("etag", etag);
|
|
256
|
+
|
|
257
|
+
if (this.req.headers.get("if-none-match") === etag) {
|
|
258
|
+
this.body = null;
|
|
259
|
+
this.status = 304;
|
|
260
|
+
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* @returns the constructed `Response`
|
|
269
|
+
*/
|
|
270
|
+
build() {
|
|
271
|
+
if (
|
|
272
|
+
(!this.status || this.status === 404) &&
|
|
273
|
+
this.#trailingSlash !== "ignore"
|
|
274
|
+
) {
|
|
275
|
+
const last = this.url.pathname.at(-1);
|
|
276
|
+
|
|
277
|
+
if (this.#trailingSlash === "always" && last !== "/") {
|
|
278
|
+
this.url.pathname += "/";
|
|
279
|
+
this.redirect(this.url, 308);
|
|
280
|
+
} else if (
|
|
281
|
+
this.#trailingSlash === "never" &&
|
|
282
|
+
this.url.pathname !== "/" &&
|
|
283
|
+
last === "/"
|
|
284
|
+
) {
|
|
285
|
+
this.url.pathname = this.url.pathname.slice(0, -1);
|
|
286
|
+
this.redirect(this.url, 308);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (!this.body && !this.status) this.notFound(this);
|
|
291
|
+
|
|
292
|
+
return new Response(this.body, this);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Call within the scope of a handler to get the current context.
|
|
297
|
+
*
|
|
298
|
+
* @returns Request context
|
|
299
|
+
*
|
|
300
|
+
* @example
|
|
301
|
+
*
|
|
302
|
+
* ```ts
|
|
303
|
+
* import { Context } from "ovr";
|
|
304
|
+
*
|
|
305
|
+
* const app = new Router();
|
|
306
|
+
*
|
|
307
|
+
* const fn = () => {
|
|
308
|
+
* const c = Context.get();
|
|
309
|
+
* // ...
|
|
310
|
+
* }
|
|
311
|
+
*
|
|
312
|
+
* app.get("/", () => {
|
|
313
|
+
* fn(); // OK
|
|
314
|
+
* });
|
|
315
|
+
*
|
|
316
|
+
* fn() // ReferenceError - outside AsyncLocalStorage scope
|
|
317
|
+
* ```
|
|
318
|
+
*/
|
|
319
|
+
static get() {
|
|
320
|
+
const c = App.storage.getStore();
|
|
321
|
+
|
|
322
|
+
if (!c)
|
|
323
|
+
throw new ReferenceError(
|
|
324
|
+
"Context can only be obtained within a handler.",
|
|
325
|
+
);
|
|
326
|
+
|
|
327
|
+
return c;
|
|
328
|
+
}
|
|
329
|
+
}
|
package/src/app/index.ts
ADDED
|
@@ -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 { Action } from "./action.js";
|
|
8
|
+
import { Context } from "./context.js";
|
|
9
|
+
import { Page } from "./page.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 `Page`s or `Action`s to add to the `App`
|
|
109
|
+
* @returns `App` instance
|
|
110
|
+
*/
|
|
111
|
+
add(...routes: DeepArray<Page | Action | Record<string, Page | Action>>[]) {
|
|
112
|
+
for (const route of routes) {
|
|
113
|
+
if (route instanceof Array) {
|
|
114
|
+
this.add(...route);
|
|
115
|
+
} else if (route instanceof Page) {
|
|
116
|
+
this.get(route.pattern, ...route.middleware);
|
|
117
|
+
} else if (route instanceof Action) {
|
|
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) 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
|
+
}
|