ovr 4.6.0 → 5.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.
@@ -1,41 +1,33 @@
1
1
  import { Chunk } from "../jsx/chunk/index.js";
2
2
  import { type JSX, toStream } from "../jsx/index.js";
3
- import type { Params, Route } from "../trie/index.js";
3
+ import { type Params, Route } from "../trie/index.js";
4
4
  import { hash } from "../util/hash.js";
5
- import {
6
- App,
7
- type ErrorHandler,
8
- type Middleware,
9
- type NotFoundHandler,
10
- type TrailingSlash,
11
- } from "./index.js";
5
+ import { type Middleware } from "./index.js";
12
6
  import { Memo } from "./memo/index.js";
13
7
 
14
8
  type Layout = (props: { children: JSX.Element }) => JSX.Element;
15
9
 
16
10
  class TagNotFound extends Error {
17
11
  override name = "TagNotFound";
12
+
18
13
  constructor(tag: string) {
19
14
  super(`No closing ${tag} tag found`);
20
15
  }
21
16
  }
22
17
 
23
- class ResponseFinalized extends Error {
24
- override name = "ResponseFinalized";
25
- constructor(property: string) {
26
- super(
27
- `Cannot set \`${property}\` after the \`Response\` has been finalized. ` +
28
- `This can occur if \`${property}\` is set within a component since ` +
29
- "components are evaluated during streaming.",
30
- );
31
- }
32
- }
33
-
34
18
  export class Context<P extends Params = Params> {
35
- /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request) */
19
+ /**
20
+ * Incoming `Request` to the server.
21
+ *
22
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
23
+ */
36
24
  req: Request;
37
25
 
38
- /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URL) */
26
+ /**
27
+ * Parsed `URL` created from `req.url`.
28
+ *
29
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URL)
30
+ */
39
31
  url: URL;
40
32
 
41
33
  /**
@@ -46,92 +38,75 @@ export class Context<P extends Params = Params> {
46
38
  *
47
39
  * @example { slug: "my-post" }
48
40
  */
49
- params!: P; // set after match
41
+ params: P = {} as P; // set after match
50
42
 
51
- /** The matched `Route` instance. */
52
- route!: Route<Middleware<P>[]>; // set after match
43
+ /** Matched `Route` instance. */
44
+ route: Route<Middleware<P>[]> | null = null;
53
45
 
54
- #body: BodyInit | null = null;
46
+ /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#body) */
47
+ body: BodyInit | null = null;
55
48
 
56
- #status?: number;
49
+ /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) */
50
+ status?: number;
57
51
 
58
52
  /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Headers) */
59
53
  headers = new Headers();
60
54
 
61
- #layouts: Layout[] = [];
62
-
63
- #headElements: JSX.Element[] = [];
55
+ /** `layouts` for the `Page` to be passed into before being injected into the `<body>` */
56
+ layouts: Layout[] = [];
64
57
 
65
- #trailingSlash: TrailingSlash;
58
+ /** `JSX.Element`(s) to add to the head */
59
+ head: JSX.Element[] = [];
66
60
 
67
- #base: string;
68
-
69
- /** Passed from `app.error` */
70
- error: ErrorHandler<P>;
61
+ /**
62
+ * Middleware to run when no `body` or `status` has been set on the `context`.
63
+ * Set to a new function to override the default.
64
+ *
65
+ * @default
66
+ *
67
+ * ```ts
68
+ * (c) => {
69
+ * c.text("Not found", 404);
70
+ * c.headers.set("cache-control", "no-cache");
71
+ * }
72
+ * ```
73
+ */
74
+ notFound: Middleware<P> = (c) => {
75
+ c.text("Not found", 404);
76
+ c.headers.set("cache-control", "no-cache");
77
+ };
71
78
 
72
- /** Passed from `app.notFound` */
73
- notFound: NotFoundHandler<P>;
79
+ /**
80
+ * Base HTML to inject the `head` and `page` elements into.
81
+ *
82
+ * If left empty, components will be returned as partials.
83
+ *
84
+ * @default ""
85
+ */
86
+ base = "";
74
87
 
75
88
  /** `Memo` unique to the current `Request` context */
76
- #memo = new Memo();
77
-
78
- memo = this.#memo.use;
79
-
80
- /** Check if the `Response` has been built already */
81
- #finalized = false;
89
+ memo = new Memo();
82
90
 
83
91
  static readonly #contentType = "content-type";
84
92
  static readonly #headClose = "</head>";
85
93
  static readonly #bodyClose = "</body>";
86
94
 
87
- constructor(
88
- req: Request,
89
- url: URL,
90
- trailingSlash: TrailingSlash,
91
- base: string,
92
- error: ErrorHandler<P>,
93
- notFound: NotFoundHandler<P>,
94
- ) {
95
+ /**
96
+ * Creates a new `Context` with the current `Request`.
97
+ *
98
+ * @param req Request
99
+ */
100
+ constructor(req: Request) {
95
101
  this.req = req;
96
- this.url = url;
97
- this.#trailingSlash = trailingSlash;
98
- this.#base = base;
99
- this.error = error;
100
- this.notFound = notFound;
101
- }
102
-
103
- /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status) */
104
- get status() {
105
- return this.#status;
106
- }
107
- set status(status) {
108
- if (this.#finalized) throw new ResponseFinalized("status");
109
- this.#status = status;
110
- }
111
-
112
- /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#body) */
113
- get body() {
114
- return this.#body;
115
- }
116
- set body(body) {
117
- if (this.#finalized) throw new ResponseFinalized("body");
118
- this.#body = body;
119
- }
120
-
121
- /** Passed from `app.base` */
122
- get base() {
123
- return this.#base;
124
- }
125
- set base(base) {
126
- if (this.#finalized) throw new ResponseFinalized("base");
127
- this.#base = base;
102
+ this.url = new URL(req.url);
128
103
  }
129
104
 
130
105
  /**
131
106
  * Mirrors `new Response()` constructor, set values with one function.
132
107
  *
133
108
  * @param body Response BodyInit
134
- * @param init Enhanced ResponseInit
109
+ * @param init ResponseInit
135
110
  */
136
111
  res(
137
112
  body: BodyInit | null,
@@ -209,24 +184,7 @@ export class Context<P extends Params = Params> {
209
184
  * - [308 Permanent Redirect](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/308)
210
185
  */
211
186
  redirect(location: string | URL, status: 301 | 302 | 303 | 307 | 308 = 302) {
212
- this.headers.set("location", location.toString());
213
- this.status = status;
214
- }
215
-
216
- /**
217
- * @param Element `JSX.Element` to add to the head
218
- */
219
- head(...Element: JSX.Element[]) {
220
- if (this.#finalized) throw new ResponseFinalized("head");
221
- this.#headElements.push(...Element);
222
- }
223
-
224
- /**
225
- * @param Layout `Layout`(s) for the `Page` to be passed into before being injected into the `<body>`
226
- */
227
- layout(...Layout: Layout[]) {
228
- if (this.#finalized) throw new ResponseFinalized("layout");
229
- this.#layouts.push(...Layout);
187
+ this.res(null, { status, headers: { location: location.toString() } });
230
188
  }
231
189
 
232
190
  /**
@@ -236,18 +194,17 @@ export class Context<P extends Params = Params> {
236
194
  * @param status [HTTP response status code](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)
237
195
  */
238
196
  page(Page: JSX.Element, status?: number) {
239
- for (let i = this.#layouts.length - 1; i >= 0; i--) {
240
- Page = this.#layouts[i]!({ children: Page });
197
+ for (let i = this.layouts.length - 1; i >= 0; i--) {
198
+ // add layouts around the page in reverse order (1st is the root layout)
199
+ Page = this.layouts[i]!({ children: Page });
241
200
  }
242
201
 
243
- let stream: ReadableStream<Uint8Array>;
244
-
245
202
  if (this.base) {
246
203
  // inject into base
247
204
  const elements: JSX.Element[] = this.base.split(Context.#headClose);
248
205
  if (!elements[1]) throw new TagNotFound(Context.#headClose);
249
206
 
250
- elements.splice(1, 0, this.#headElements, Context.#headClose);
207
+ elements.splice(1, 0, this.head, Context.#headClose);
251
208
 
252
209
  const bodyParts = (elements[3] as string).split(Context.#bodyClose);
253
210
  if (!bodyParts[1]) throw new TagNotFound(Context.#bodyClose);
@@ -263,15 +220,17 @@ export class Context<P extends Params = Params> {
263
220
  elements[3] = bodyParts[0];
264
221
  elements.push(Page, Context.#bodyClose + bodyParts[1]);
265
222
 
266
- stream = toStream(
267
- elements.map((el) => (typeof el === "string" ? Chunk.safe(el) : el)),
223
+ return this.html(
224
+ toStream(
225
+ elements.map((el) => (typeof el === "string" ? Chunk.safe(el) : el)),
226
+ ),
227
+ status,
268
228
  );
269
- } else {
270
- // HTML partial - just use the layouts + page
271
- stream = toStream(Page);
272
229
  }
273
230
 
274
- this.html(stream, status);
231
+ // HTML partial - just use the layouts + page
232
+ // head elements are ignored if no base is set
233
+ return this.html(toStream(Page), status);
275
234
  }
276
235
 
277
236
  /**
@@ -299,67 +258,46 @@ export class Context<P extends Params = Params> {
299
258
  }
300
259
 
301
260
  /**
302
- * @returns the constructed `Response`
261
+ * Modifies the context based on the the return value of middleware.
262
+ *
263
+ * @param value value returned from middleware
303
264
  */
304
- build() {
305
- if (
306
- (!this.status || this.status === 404) &&
307
- this.#trailingSlash !== "ignore"
308
- ) {
309
- const last = this.url.pathname.at(-1);
310
-
311
- if (this.#trailingSlash === "always" && last !== "/") {
312
- this.url.pathname += "/";
313
- this.redirect(this.url, 308);
314
- } else if (
315
- this.#trailingSlash === "never" &&
316
- this.url.pathname !== "/" &&
317
- last === "/"
318
- ) {
319
- this.url.pathname = this.url.pathname.slice(0, -1);
320
- this.redirect(this.url, 308);
321
- }
265
+ #resolveReturn(value: unknown) {
266
+ if (value instanceof Response) {
267
+ this.res(value.body, value);
268
+ } else if (value instanceof ReadableStream) {
269
+ this.body = value;
270
+ } else if (value != null) {
271
+ // nullish are not used so `void` will not render empty page
272
+ this.page(value);
322
273
  }
274
+ }
323
275
 
324
- if (!this.body && !this.status) this.notFound(this);
325
-
326
- this.#finalized = true;
276
+ /**
277
+ * Dispatches the stack of `middleware` provided.
278
+ *
279
+ * @param middleware stack to run
280
+ * @param i current middleware index (default `0`)
281
+ */
282
+ async #run(middleware: Middleware<P>[], i = 0) {
283
+ if (!middleware[i]) return;
327
284
 
328
- return new Response(this.body, this);
285
+ this.#resolveReturn(
286
+ await middleware[i](this, () => this.#run(middleware, i + 1)),
287
+ );
329
288
  }
330
289
 
331
290
  /**
332
- * Call within the scope of a handler to get the current context.
333
- *
334
- * @returns Request context
335
- *
336
- * @example
291
+ * Composes a stack of `middleware` into a `Response`.
337
292
  *
338
- * ```ts
339
- * import { Context } from "ovr";
340
- *
341
- * const app = new Router();
342
- *
343
- * const fn = () => {
344
- * const c = Context.get();
345
- * // ...
346
- * }
347
- *
348
- * app.get("/", () => {
349
- * fn(); // OK
350
- * });
351
- *
352
- * fn() // ReferenceError - outside AsyncLocalStorage scope
353
- * ```
293
+ * @param middleware stack to compose
294
+ * @returns constructed `Response`
354
295
  */
355
- static get() {
356
- const c = App.storage.getStore();
296
+ async build(middleware: Middleware<P>[]) {
297
+ await this.#run(middleware);
357
298
 
358
- if (!c)
359
- throw new ReferenceError(
360
- "Context can only be obtained within a handler.",
361
- );
299
+ if (!this.body && !this.status) this.notFound(this, Promise.resolve);
362
300
 
363
- return c;
301
+ return new Response(this.body, this);
364
302
  }
365
303
  }
@@ -1,21 +1,15 @@
1
1
  import { type JSX, jsx } from "../../jsx/index.js";
2
2
  import type { Params } from "../../trie/index.js";
3
3
  import type { ExtractParams, InsertParams } from "../../types/index.js";
4
- import { Context } from "../context.js";
5
4
  import type { Middleware } from "../index.js";
6
5
 
7
6
  export type UrlOptions<P extends Params> = {
8
7
  /**
9
- * If `true` the current request's `url.search` is forwarded, this option
10
- * can only be used in the context of a request.
11
- *
12
- * Otherwise the value is passed into `URLSearchParams` constructor to
13
- * create new params.
8
+ * Passed into `URLSearchParams` constructor to create new params.
14
9
  *
15
10
  * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
16
11
  */
17
12
  search?:
18
- | boolean
19
13
  | string
20
14
  // Iterable is more accurate than the built in string[][] + URLSearchParams
21
15
  // https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/2070
@@ -104,25 +98,15 @@ export class Helper<Pattern extends string> {
104
98
  // @ts-expect-error - do not have to pass in {} if no params
105
99
  options?.params,
106
100
  );
101
+ let search = "";
102
+ let hash = "";
107
103
 
108
- let search: string;
109
104
  if (options?.search) {
110
- if (options.search === true) {
111
- // forward current request's search
112
- search = Context.get().url.search;
113
- } else {
114
- // use the value as the init
115
- search =
116
- "?" +
117
- new URLSearchParams(
118
- options.search as ConstructorParameters<typeof URLSearchParams>[0],
119
- );
120
- }
121
- } else {
122
- search = "";
105
+ // use the value as the init
106
+ // @ts-expect-error - see above
107
+ search = "?" + new URLSearchParams(options.search);
123
108
  }
124
109
 
125
- let hash: string;
126
110
  if (options?.hash) {
127
111
  // adding # prefix if not present matches the URL setter:
128
112
  // https://developer.mozilla.org/en-US/docs/Web/API/URL/hash
@@ -131,8 +115,6 @@ export class Helper<Pattern extends string> {
131
115
  } else {
132
116
  hash = "#" + options.hash;
133
117
  }
134
- } else {
135
- hash = "";
136
118
  }
137
119
 
138
120
  return pathname + search + hash;