ovr 6.1.0 → 6.2.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.
Files changed (43) hide show
  1. package/dist/LICENSE.md +2 -0
  2. package/dist/app/index.d.ts.map +1 -1
  3. package/dist/app/index.js +13 -9
  4. package/dist/context/index.d.ts +33 -9
  5. package/dist/context/index.d.ts.map +1 -1
  6. package/dist/context/index.js +61 -17
  7. package/dist/cookie/index.d.ts +1 -1
  8. package/dist/cookie/index.d.ts.map +1 -1
  9. package/dist/cookie/index.js +2 -2
  10. package/dist/index.d.ts +4 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +3 -2
  13. package/dist/middleware/index.d.ts +12 -3
  14. package/dist/middleware/index.d.ts.map +1 -1
  15. package/dist/multipart/index.d.ts +5 -0
  16. package/dist/multipart/index.d.ts.map +1 -1
  17. package/dist/multipart/index.js +20 -22
  18. package/dist/render/index.d.ts +1 -0
  19. package/dist/render/index.d.ts.map +1 -1
  20. package/dist/render/index.js +6 -4
  21. package/dist/route/index.d.ts +143 -42
  22. package/dist/route/index.d.ts.map +1 -1
  23. package/dist/route/index.js +94 -42
  24. package/dist/schema/index.d.ts +1286 -0
  25. package/dist/schema/index.d.ts.map +1 -0
  26. package/dist/schema/index.js +1321 -0
  27. package/dist/trie/index.d.ts.map +1 -1
  28. package/dist/trie/index.js +8 -2
  29. package/dist/util/index.d.ts +113 -19
  30. package/dist/util/index.d.ts.map +1 -1
  31. package/dist/util/index.js +111 -35
  32. package/package.json +4 -1
  33. package/src/app/index.ts +13 -12
  34. package/src/context/index.ts +104 -25
  35. package/src/cookie/index.ts +3 -3
  36. package/src/index.ts +4 -3
  37. package/src/middleware/index.ts +19 -8
  38. package/src/multipart/index.ts +23 -24
  39. package/src/render/index.ts +7 -4
  40. package/src/route/index.ts +336 -95
  41. package/src/schema/index.ts +2798 -0
  42. package/src/trie/index.ts +12 -2
  43. package/src/util/index.ts +142 -36
@@ -1,11 +1,12 @@
1
1
  import type { App } from "../app/index.js";
2
2
  import { Cookie } from "../cookie/index.js";
3
- import { type Middleware } from "../middleware/index.js";
3
+ import type { Middleware } from "../middleware/index.js";
4
4
  import { Multipart } from "../multipart/index.js";
5
5
  import { Render } from "../render/index.js";
6
6
  import { Route } from "../route/index.js";
7
- import { type Trie } from "../trie/index.js";
8
- import { Hash, Header, Method, Mime } from "../util/index.js";
7
+ import { Form as FormSchema } from "../schema/index.js";
8
+ import type { Trie } from "../trie/index.js";
9
+ import { Checksum, Header, Method, Mime, type Util } from "../util/index.js";
9
10
 
10
11
  /** Properties to build the final `Response` with once middleware has run. */
11
12
  class PreparedResponse {
@@ -32,16 +33,38 @@ class PreparedResponse {
32
33
  }
33
34
 
34
35
  export namespace Context {
35
- // gives users access to Middleware.Context.Cookie.Options
36
- export type Cookie = InstanceType<typeof Cookie>;
36
+ /**
37
+ * Context.data return type.
38
+ *
39
+ * Routes without a schema return `null`.
40
+ *
41
+ * @template S Form shape
42
+ */
43
+ export type Result<S extends FormSchema.Shape> = [FormSchema.Shape] extends [
44
+ S,
45
+ ]
46
+ ? null
47
+ : Util.Prettify<
48
+ FormSchema.Parse.Result<
49
+ S,
50
+ {
51
+ /** URL with invalid field values encoded into a search parameter. */
52
+ readonly url: URL;
53
+ }
54
+ >
55
+ >;
37
56
  }
38
57
 
39
58
  /**
40
59
  * Request context.
41
60
  *
42
61
  * @template Params Parameters created from a route match
62
+ * @template Shape Parsed form data shape
43
63
  */
44
- export class Context<Params extends Trie.Params = Trie.Params> {
64
+ export class Context<
65
+ Params extends Trie.Params = Trie.Params,
66
+ Shape extends FormSchema.Shape = FormSchema.Shape,
67
+ > {
45
68
  /**
46
69
  * Incoming `Request` to the server.
47
70
  *
@@ -71,6 +94,9 @@ export class Context<Params extends Trie.Params = Trie.Params> {
71
94
  /** Forwarded app options */
72
95
  readonly #options: App.Options;
73
96
 
97
+ /** Cached result from `data()` to avoid re-reading request bodies. */
98
+ #parsed?: Promise<Context.Result<Shape>>;
99
+
74
100
  /**
75
101
  * Creates a new `Context` with the current `Request`.
76
102
  *
@@ -91,7 +117,7 @@ export class Context<Params extends Trie.Params = Trie.Params> {
91
117
  html(body: BodyInit | null, status?: number) {
92
118
  this.res.body = body;
93
119
  this.res.status = status;
94
- this.res.headers.set(Header.type, Header.utf8(Mime.html));
120
+ this.res.headers.set(Header.name.type, Header.utf8(Mime.type.html));
95
121
  }
96
122
 
97
123
  /**
@@ -103,7 +129,7 @@ export class Context<Params extends Trie.Params = Trie.Params> {
103
129
  json<D>(data: D extends bigint ? never : D, status?: number) {
104
130
  this.res.body = JSON.stringify(data);
105
131
  this.res.status = status;
106
- this.res.headers.set(Header.type, Mime.json);
132
+ this.res.headers.set(Header.name.type, Mime.type.json);
107
133
  }
108
134
 
109
135
  /**
@@ -115,7 +141,7 @@ export class Context<Params extends Trie.Params = Trie.Params> {
115
141
  text(body: BodyInit | null, status?: number) {
116
142
  this.res.body = body;
117
143
  this.res.status = status;
118
- this.res.headers.set(Header.type, Header.utf8(Mime.text));
144
+ this.res.headers.set(Header.name.type, Header.utf8(Mime.type.text));
119
145
  }
120
146
 
121
147
  /**
@@ -130,27 +156,33 @@ export class Context<Params extends Trie.Params = Trie.Params> {
130
156
  * - [307 Temporary Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/307)
131
157
  * - [308 Permanent Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308)
132
158
  */
133
- redirect(location: string | URL, status: 301 | 302 | 303 | 307 | 308 = 302) {
159
+ redirect(
160
+ location: string | URL | Route,
161
+ status: 301 | 302 | 303 | 307 | 308 = 302,
162
+ ) {
134
163
  this.res.body = null;
135
164
  this.res.status = status;
136
- this.res.headers.set("location", String(location));
165
+ this.res.headers.set(
166
+ Header.name.loc,
167
+ location instanceof Route ? location.pathname() : String(location),
168
+ );
137
169
  }
138
170
 
139
171
  /**
140
- * Generates an etag from a hash of the string provided.
172
+ * Generates an etag from a checksum of the string provided.
141
173
  * If the etag matches, sets the response to not modified.
142
174
  *
143
175
  * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag)
144
176
  *
145
- * @param string string to hash
177
+ * @param string string to check
146
178
  * @returns `true` if the etag matches, `false` otherwise
147
179
  */
148
180
  etag(string: string) {
149
- const etag = `"${Hash.djb2(string)}"`;
181
+ const etag = `"${Checksum.djb2(string)}"`;
150
182
 
151
- this.res.headers.set(Header.etag, etag);
183
+ this.res.headers.set(Header.name.etag, etag);
152
184
 
153
- if (this.req.headers.get(Header.ifNoneMatch) === etag) {
185
+ if (this.req.headers.get(Header.name.none) === etag) {
154
186
  this.res.body = null;
155
187
  this.res.status = 304;
156
188
 
@@ -161,10 +193,12 @@ export class Context<Params extends Trie.Params = Trie.Params> {
161
193
  }
162
194
 
163
195
  /**
164
- * Parse multipart requests.
196
+ * Parse a multipart request.
165
197
  *
166
- * @yields Multipart request `Part`(s)
198
+ * _Prefer_ `Context.data()` _when possible to parse
199
+ * with a type-safe schema._
167
200
  *
201
+ * @yields Multipart request `Part`(s)
168
202
  * @example
169
203
  *
170
204
  * ```ts
@@ -180,10 +214,55 @@ export class Context<Params extends Trie.Params = Trie.Params> {
180
214
  * ```
181
215
  */
182
216
  form(options?: Multipart.Options) {
183
- return new Multipart(
184
- this.req,
185
- Object.assign({}, this.#options.form, options),
186
- );
217
+ return new Multipart(this.req, { ...this.#options.form, ...options });
218
+ }
219
+
220
+ /**
221
+ * Parse route form data from search params or multipart requests.
222
+ *
223
+ * @param options Multipart options for POST requests
224
+ * @returns Parsed form data with possible invalid redirect URL state
225
+ */
226
+ async data(options?: Multipart.Options): Promise<Context.Result<Shape>> {
227
+ return (this.#parsed ??= (async () => {
228
+ const post = this.req.method === Method.post;
229
+ const form = this.route as Route.Post | undefined;
230
+
231
+ if (!form?.parse) return null as Context.Result<Shape>;
232
+
233
+ const result = await form.parse(
234
+ post
235
+ ? this.form({ parts: form.parts, ...options })
236
+ : this.url.searchParams,
237
+ );
238
+
239
+ if (result.issues) {
240
+ // create encoded URL state with invalid fields
241
+ let url = new URL(this.url);
242
+
243
+ if (post) {
244
+ const returnParam = url.searchParams.get(FormSchema.params[0]);
245
+
246
+ if (returnParam) {
247
+ try {
248
+ const returnUrl = new URL(returnParam, url);
249
+
250
+ if (returnUrl.origin === url.origin) url = returnUrl;
251
+ } catch {
252
+ // invalid redirect target
253
+ }
254
+ }
255
+ }
256
+
257
+ for (const param of FormSchema.params) url.searchParams.delete(param);
258
+
259
+ if (result.search) url.searchParams.set(...result.search[0]);
260
+
261
+ return Object.assign(result, { url }) as Context.Result<Shape>;
262
+ }
263
+
264
+ return result as Context.Result<Shape>;
265
+ })());
187
266
  }
188
267
 
189
268
  /**
@@ -193,7 +272,7 @@ export class Context<Params extends Trie.Params = Trie.Params> {
193
272
  * @param i current middleware index (default `0`)
194
273
  * @returns return value of `middleware[i]`
195
274
  */
196
- async #run(middleware: Middleware<Params>[], i = 0) {
275
+ async #run(middleware: Middleware<Params, Shape>[], i = 0) {
197
276
  const mw = middleware[i];
198
277
 
199
278
  if (!mw) return; // end of stack
@@ -215,7 +294,7 @@ export class Context<Params extends Trie.Params = Trie.Params> {
215
294
  }
216
295
  } else if (r !== undefined) {
217
296
  // something to stream
218
- const [mime] = Header.shift(this.res.headers.get(Header.type));
297
+ const [mime] = Header.shift(this.res.headers.get(Header.name.type));
219
298
 
220
299
  this.res.body = Render.stream(r, {
221
300
  // other defined types are safe
@@ -224,7 +303,7 @@ export class Context<Params extends Trie.Params = Trie.Params> {
224
303
 
225
304
  if (!mime) {
226
305
  // default to HTML
227
- this.res.headers.set(Header.type, Header.utf8(Mime.html));
306
+ this.res.headers.set(Header.name.type, Header.utf8(Mime.type.html));
228
307
  }
229
308
 
230
309
  // do not overwrite/remove status - that way user can set it before returning
@@ -92,7 +92,7 @@ export namespace Cookie {
92
92
 
93
93
  type InsecureOptions = BaseOptions & {
94
94
  /** Limits the scope of the cookie to a secure context (HTTPS). */
95
- readonly secure?: false;
95
+ readonly secure?: boolean;
96
96
 
97
97
  /**
98
98
  * Controls whether the cookie is sent with cross-site requests.
@@ -147,7 +147,7 @@ export class Cookie {
147
147
  */
148
148
  get(name: string) {
149
149
  return (this.#parsed ??= Header.params(
150
- this.#c.req.headers.get(Header.cookie),
150
+ this.#c.req.headers.get(Header.name.cookie),
151
151
  ))[name];
152
152
  }
153
153
 
@@ -184,6 +184,6 @@ export class Cookie {
184
184
  if (options.expires)
185
185
  cookie.push(`Expires=${options.expires.toUTCString()}`);
186
186
 
187
- this.#c.res.headers.append(Header.setCookie, cookie.join("; "));
187
+ this.#c.res.headers.append(Header.name.set, cookie.join("; "));
188
188
  }
189
189
  }
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { App } from "./app/index.js";
2
- export { Route } from "./route/index.js";
3
- export { Multipart } from "./multipart/index.js";
4
2
  export { JSX } from "./jsx/index.js";
5
- export { Render } from "./render/index.js";
6
3
  export type { Middleware } from "./middleware/index.js";
4
+ export { Multipart } from "./multipart/index.js";
5
+ export { Render } from "./render/index.js";
6
+ export { Route } from "./route/index.js";
7
+ export { Field, Form, Schema } from "./schema/index.js";
@@ -1,15 +1,25 @@
1
- import type { Context } from "../context/index.js";
1
+ import type { Context as ContextType } from "../context/index.js";
2
+ import type { Cookie as CookieType } from "../cookie/index.js";
3
+ import type { Form } from "../schema/index.js";
2
4
  import type { Trie } from "../trie/index.js";
3
5
 
4
6
  export namespace Middleware {
7
+ export namespace Context {
8
+ export namespace Cookie {
9
+ export type Options = CookieType.Options;
10
+ }
11
+ }
12
+
5
13
  /**
6
14
  * Middleware context.
7
15
  *
8
16
  * @template Params Parameters created from a route match
17
+ * @template Shape Parsed form data shape
9
18
  */
10
- export type Context<Params extends Trie.Params = Trie.Params> = InstanceType<
11
- typeof Context<Params>
12
- >;
19
+ export type Context<
20
+ Params extends Trie.Params = Trie.Params,
21
+ Shape extends Form.Shape = Form.Shape,
22
+ > = ContextType<Params, Shape>;
13
23
 
14
24
  /** Dispatches the next middleware in the stack */
15
25
  export type Next = () => Promise<void>;
@@ -19,11 +29,12 @@ export namespace Middleware {
19
29
  * App middleware.
20
30
  *
21
31
  * @template Params Parameters created from a route match
32
+ * @template Shape Parsed form data shape
22
33
  * @param context Request context
23
34
  * @param next Dispatches the next middleware in the stack
24
35
  * @returns `Response` or element(s) to stream as HTML
25
36
  */
26
- export type Middleware<Params extends Trie.Params = Trie.Params> = (
27
- context: Middleware.Context<Params>,
28
- next: Middleware.Next,
29
- ) => any;
37
+ export type Middleware<
38
+ Params extends Trie.Params = Trie.Params,
39
+ Shape extends Form.Shape = Form.Shape,
40
+ > = (context: ContextType<Params, Shape>, next: Middleware.Next) => any;
@@ -1,4 +1,4 @@
1
- import { Codec, Header, Mime } from "../util/index.js";
1
+ import { Codec, Header, Mime, Size } from "../util/index.js";
2
2
 
3
3
  /** Sequence of bytes to find within the stream */
4
4
  class Needle extends Uint8Array {
@@ -92,12 +92,26 @@ class Part extends Request {
92
92
  duplex: "half",
93
93
  });
94
94
 
95
- [this.type] = Header.shift(this.headers.get(Header.type));
95
+ [this.type] = Header.shift(this.headers.get(Header.name.type));
96
96
 
97
97
  ({ name: this.name = null, filename: this.filename = null } = Header.params(
98
- this.headers.get(Header.disposition),
98
+ this.headers.get(Header.name.disp),
99
99
  ));
100
100
  }
101
+
102
+ /**
103
+ *
104
+ * @returns Buffered FormDataEntryValue
105
+ */
106
+ async value(): Promise<FormDataEntryValue> {
107
+ if (this.filename || this.type === Mime.type.stream) {
108
+ const blob = await this.blob();
109
+
110
+ return new File([blob], this.filename ?? "blob", { type: blob.type });
111
+ }
112
+
113
+ return this.text();
114
+ }
101
115
  }
102
116
 
103
117
  export namespace Multipart {
@@ -160,16 +174,13 @@ export namespace Multipart {
160
174
 
161
175
  /** Multipart request */
162
176
  export class Multipart extends Request {
163
- static readonly #kb = 1024;
164
- static readonly #mb = 1024 ** 2;
165
-
166
177
  /** New line needle to share across requests and parts */
167
178
  static readonly #newLine = new Needle("\r\n\r\n");
168
179
 
169
180
  /** Parser options */
170
181
  readonly #options: Required<Multipart.Options> = {
171
- memory: 4 * Multipart.#mb,
172
- payload: 16 * Multipart.#mb,
182
+ memory: 4 * Size.mb,
183
+ payload: 16 * Size.mb,
173
184
  parts: Infinity,
174
185
  };
175
186
 
@@ -215,7 +226,7 @@ export class Multipart extends Request {
215
226
  constructor(req: Request, options?: Multipart.Options) {
216
227
  super(req);
217
228
 
218
- const [mime, params] = Header.shift(this.headers.get(Header.type));
229
+ const [mime, params] = Header.shift(this.headers.get(Header.name.type));
219
230
 
220
231
  if (!Mime.multipart(mime)) throw new TypeError("Unsupported Media Type");
221
232
 
@@ -233,7 +244,7 @@ export class Multipart extends Request {
233
244
  new ArrayBuffer(
234
245
  // slightly larger than common chunk size/high water mark 64kb for leftover boundary
235
246
  // prevents having to resize memory for most requests
236
- 65 * Multipart.#kb,
247
+ 65 * Size.kb,
237
248
  // cap max chunk size + leftover
238
249
  { maxByteLength: this.#options.memory },
239
250
  ),
@@ -426,6 +437,7 @@ export class Multipart extends Request {
426
437
  // cannot cancel, chunks would be in the next header
427
438
  if (part.body && !part.bodyUsed) {
428
439
  const partReader = part.body.getReader();
440
+
429
441
  try {
430
442
  while (!(await partReader.read()).done);
431
443
  } finally {
@@ -463,20 +475,7 @@ export class Multipart extends Request {
463
475
  const data = new FormData();
464
476
 
465
477
  for await (const part of this) {
466
- if (part.name) {
467
- let value: string | File;
468
-
469
- if (part.filename || part.type === Mime.stream) {
470
- const blob = await part.blob();
471
- value = new File([blob], part.filename ?? "blob", {
472
- type: blob.type,
473
- });
474
- } else {
475
- value = await part.text();
476
- }
477
-
478
- data.append(part.name, value);
479
- }
478
+ if (part.name) data.append(part.name, await part.value());
480
479
  }
481
480
 
482
481
  return data;
@@ -1,5 +1,5 @@
1
1
  import type { JSX } from "../jsx/index.js";
2
- import { Codec } from "../util/index.js";
2
+ import { Codec, Size } from "../util/index.js";
3
3
 
4
4
  type Next = { i: number; result: IteratorResult<Chunk, void> };
5
5
 
@@ -83,9 +83,11 @@ export class Render {
83
83
  if (element instanceof Promise) element = await element;
84
84
 
85
85
  // resolve based on type
86
- // should not render
87
- if (element == null || typeof element === "boolean" || element === "")
86
+
87
+ if (element == null || typeof element === "boolean" || element === "") {
88
+ // should not render
88
89
  return;
90
+ }
89
91
 
90
92
  if (element instanceof Chunk) {
91
93
  // already escaped or safe
@@ -201,7 +203,7 @@ export class Render {
201
203
  // https://blog.cloudflare.com/unpacking-cloudflare-workers-cpu-performance-benchmarks/#inefficient-streams-adapters
202
204
  // in Node, the default is 16kb, so this stacks another 2kb in front
203
205
  // https://nodejs.org/api/http.html#outgoingmessagewritablehighwatermark
204
- highWaterMark: 2048,
206
+ highWaterMark: 2 * Size.kb,
205
207
  },
206
208
  );
207
209
  }
@@ -212,6 +214,7 @@ export class Render {
212
214
  * ### WARNING
213
215
  *
214
216
  * This negates streaming benefits and buffers the result into a string.
217
+ *
215
218
  * @param element Element to render
216
219
  * @param options Render options
217
220
  * @returns Concatenated HTML