ovr 4.5.1 → 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.
Files changed (41) hide show
  1. package/dist/app/context.d.ts +58 -56
  2. package/dist/app/context.d.ts.map +1 -1
  3. package/dist/app/context.js +97 -134
  4. package/dist/app/helper/index.d.ts +2 -6
  5. package/dist/app/helper/index.d.ts.map +1 -1
  6. package/dist/app/helper/index.js +5 -19
  7. package/dist/app/index.d.ts +31 -45
  8. package/dist/app/index.d.ts.map +1 -1
  9. package/dist/app/index.js +68 -94
  10. package/dist/app/memo/index.d.ts +1 -1
  11. package/dist/app/memo/index.d.ts.map +1 -1
  12. package/dist/app/memo/index.js +2 -2
  13. package/dist/index.d.ts +1 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +0 -1
  16. package/dist/jsx/chunk/index.d.ts +9 -0
  17. package/dist/jsx/chunk/index.d.ts.map +1 -1
  18. package/dist/jsx/chunk/index.js +11 -0
  19. package/dist/jsx/index.d.ts +5 -4
  20. package/dist/jsx/index.d.ts.map +1 -1
  21. package/dist/jsx/index.js +43 -45
  22. package/dist/jsx/merge-async-generators.d.ts.map +1 -1
  23. package/dist/jsx/merge-async-generators.js +9 -3
  24. package/dist/trie/index.d.ts +5 -0
  25. package/dist/trie/index.d.ts.map +1 -1
  26. package/dist/trie/index.js +8 -2
  27. package/package.json +2 -2
  28. package/src/app/context.ts +100 -164
  29. package/src/app/helper/index.ts +6 -24
  30. package/src/app/index.ts +111 -123
  31. package/src/app/memo/index.ts +2 -2
  32. package/src/index.ts +1 -2
  33. package/src/jsx/chunk/index.ts +12 -0
  34. package/src/jsx/index.ts +61 -74
  35. package/src/jsx/merge-async-generators.ts +8 -5
  36. package/src/trie/index.ts +9 -2
  37. package/src/util/hash.ts +1 -1
  38. package/dist/app/mw/csrf.d.ts +0 -23
  39. package/dist/app/mw/csrf.d.ts.map +0 -1
  40. package/dist/app/mw/csrf.js +0 -30
  41. package/src/app/mw/csrf.ts +0 -32
package/src/app/index.ts CHANGED
@@ -7,11 +7,12 @@ import type {
7
7
  import { Context } from "./context.js";
8
8
  import { Get } from "./helper/get.js";
9
9
  import { Post } from "./helper/post.js";
10
- import { AsyncLocalStorage } from "node:async_hooks";
10
+
11
+ export type Next = () => Promise<void>;
11
12
 
12
13
  export type Middleware<P extends Params = Params> = (
13
14
  context: Context<P>,
14
- next: () => Promise<void>,
15
+ next: Next,
15
16
  ) => any;
16
17
 
17
18
  export type TrailingSlash = "always" | "never" | "ignore";
@@ -28,30 +29,22 @@ type Method =
28
29
  | "PATCH"
29
30
  | (string & {});
30
31
 
31
- type UnmatchedContext<P extends Params = Params> = Omit<Context<P>, "route"> &
32
- // route might be defined
33
- Partial<Pick<Context<P>, "route">>;
34
-
35
- export type ErrorHandler<P extends Params = Params> =
36
- | ((context: UnmatchedContext<P>, error: unknown) => any)
37
- | null;
38
-
39
- export type NotFoundHandler<P extends Params = Params> = (
40
- context: UnmatchedContext<P>,
41
- ) => any;
42
-
43
- export class App {
44
- // allows for users to put other properties on the app
45
- [key: string | symbol | number]: any;
46
-
47
- /** Built tries per HTTP method. */
48
- #trieMap = new Map<Method, Trie<Middleware[]>>();
49
-
50
- /** Added routes per HTTP method. */
51
- #routesMap = new Map<Method, Route<Middleware[]>[]>();
52
-
53
- /** Global middleware. */
54
- #use: Middleware[] = [];
32
+ /** `App` configuration options */
33
+ type AppOptions = {
34
+ /**
35
+ * Basic
36
+ * [cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF)
37
+ * protection that checks the request's `method`, and its
38
+ * [`Sec-Fetch-Site`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site)
39
+ * and [`Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin)
40
+ * headers.
41
+ *
42
+ * More robust protection requires a stateful server or a database to store
43
+ * [CSRF tokens](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF#csrf_tokens).
44
+ *
45
+ * @default true
46
+ */
47
+ csrf?: boolean;
55
48
 
56
49
  /**
57
50
  * - `"never"` - Not found requests with a trailing slash will be redirected to the same path without a trailing slash
@@ -62,45 +55,32 @@ export class App {
62
55
  *
63
56
  * @default "never"
64
57
  */
65
- trailingSlash: TrailingSlash = "never";
58
+ trailingSlash?: TrailingSlash;
59
+ };
66
60
 
67
- /**
68
- * Base HTML to inject the `head` and `page` elements into.
69
- *
70
- * @default
71
- *
72
- * ```html
73
- * <!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>
74
- * ```
75
- */
76
- base =
77
- '<!doctype html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body></body></html>';
61
+ export class App {
62
+ constructor(options?: AppOptions) {
63
+ const resolved: Required<AppOptions> = {
64
+ csrf: true,
65
+ trailingSlash: "never",
66
+ };
67
+ Object.assign(resolved, options);
78
68
 
79
- /**
80
- * Assign a handler to run when an `Error` is thrown.
81
- *
82
- * If not set, `Error` will be thrown. This might be desired
83
- * if your server already includes error handling. Set in `config.start`
84
- * to handle errors globally.
85
- *
86
- * @default null
87
- */
88
- error: ErrorHandler = null;
69
+ if (resolved.csrf === true) this.#use.push(App.#csrf);
89
70
 
90
- /**
91
- * Middleware to run when no `body` or `status` has been set on the `context`.
92
- * Set to a new function to override the default.
93
- *
94
- * @default
95
- *
96
- * ```ts
97
- * (c) => c.html("Not found", 404)
98
- * ```
99
- */
100
- notFound: NotFoundHandler = (c) => c.html("Not found", 404);
71
+ if (resolved.trailingSlash !== "ignore") {
72
+ this.#use.push(App.#trailingSlash(resolved.trailingSlash));
73
+ }
74
+ }
101
75
 
102
- /** Stores context per request. */
103
- static storage = new AsyncLocalStorage<Context>();
76
+ /** Built tries per HTTP method. */
77
+ #trieMap = new Map<Method, Trie<Middleware[]>>();
78
+
79
+ /** Added routes per HTTP method. */
80
+ #routesMap = new Map<Method, Route<Middleware[]>[]>();
81
+
82
+ /** Global middleware. */
83
+ #use: Middleware[] = [];
104
84
 
105
85
  /**
106
86
  * @param helpers `Helper` to add to `App`
@@ -231,70 +211,78 @@ export class App {
231
211
  }
232
212
 
233
213
  /**
234
- * @param req [`Request` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
235
- * @returns [`Response` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response)
214
+ * Request a resource from the application.
215
+ *
216
+ * [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch)
217
+ *
218
+ * @param resource [Resource](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch#resource) to fetch
219
+ * @param options [Options](https://developer.mozilla.org/en-US/docs/Web/API/Window/fetch#options) to apply to the request
220
+ * @returns Promise that resolves to the [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) to the request
236
221
  */
237
- fetch = (req: Request): Promise<Response> => {
238
- const c = new Context(
239
- req,
240
- new URL(req.url),
241
- this.trailingSlash,
242
- this.base,
243
- this.error,
244
- this.notFound,
245
- );
246
-
247
- return App.storage.run(c, async () => {
248
- try {
249
- // check to see if the method is already built
250
- let trie = this.#trieMap.get(req.method);
251
-
252
- if (!trie) {
253
- // check if there are any routes with the method
254
- const routes = this.#routesMap.get(req.method);
255
-
256
- if (routes) {
257
- // build trie
258
- trie = new Trie<Middleware[]>();
259
- for (const route of routes) trie.add(route);
260
- this.#trieMap.set(req.method, trie);
261
- }
262
- }
263
-
264
- if (trie) {
265
- const match = trie.find(c.url.pathname);
266
-
267
- if (match) {
268
- Object.assign(c, match);
269
-
270
- const middleware = [...this.#use, ...match.route.store];
271
-
272
- // compose
273
- let i = -1;
274
- const dispatch = async (current: number): Promise<void> => {
275
- if (current <= i) throw new Error("next() called multiple times");
276
- i = current;
277
-
278
- if (middleware[current]) {
279
- const result: unknown = await middleware[current](c, () =>
280
- dispatch(current + 1),
281
- );
282
-
283
- if (result instanceof Response) c.res(result.body, result);
284
- else if (result instanceof ReadableStream) c.body = result;
285
- else if (result != null) c.page(result);
286
- }
287
- };
288
-
289
- await dispatch(0);
290
- }
291
- }
292
- } catch (error) {
293
- if (c.error) c.error(c, error);
294
- else throw error;
222
+ fetch = async (
223
+ resource: RequestInfo | URL,
224
+ options?: RequestInit,
225
+ ): Promise<Response> => {
226
+ const c = new Context(new Request(resource, options));
227
+
228
+ // see if the method is already built
229
+ let trie = this.#trieMap.get(c.req.method);
230
+
231
+ if (!trie) {
232
+ // check if there are any routes with the method
233
+ const routes = this.#routesMap.get(c.req.method);
234
+
235
+ if (routes) {
236
+ // build trie
237
+ trie = new Trie<Middleware[]>();
238
+ for (const route of routes) trie.add(route);
239
+ this.#trieMap.set(c.req.method, trie);
295
240
  }
241
+ }
296
242
 
297
- return c.build();
298
- });
243
+ if (trie) {
244
+ const match = trie.find(c.url.pathname);
245
+
246
+ if (match) {
247
+ Object.assign(c, match);
248
+ return c.build(this.#use.concat(match.route.store));
249
+ }
250
+ }
251
+
252
+ // no match, just run global middleware
253
+ return c.build(this.#use);
299
254
  };
255
+
256
+ /** Basic CSRF middleware. */
257
+ static async #csrf(c: Context, next: Next) {
258
+ if (
259
+ c.req.method === "GET" ||
260
+ c.req.method === "HEAD" ||
261
+ c.req.headers.get("sec-fetch-site") === "same-origin" ||
262
+ c.req.headers.get("origin") === c.url.origin
263
+ ) {
264
+ return next();
265
+ }
266
+
267
+ c.text("Forbidden", 403);
268
+ }
269
+
270
+ /** @returns Trailing slash middleware */
271
+ static #trailingSlash(mode: TrailingSlash) {
272
+ return async (c: Context, next: Next) => {
273
+ await next();
274
+
275
+ if (c.status && c.status !== 404) return;
276
+
277
+ const last = c.url.pathname.at(-1);
278
+
279
+ if (mode === "always" && last !== "/") {
280
+ c.url.pathname += "/";
281
+ c.redirect(c.url, 308);
282
+ } else if (mode === "never" && c.url.pathname !== "/" && last === "/") {
283
+ c.url.pathname = c.url.pathname.slice(0, -1);
284
+ c.redirect(c.url, 308);
285
+ }
286
+ };
287
+ }
300
288
  }
@@ -12,7 +12,7 @@ export class Memo {
12
12
  * @param fn Function to memoize.
13
13
  * @returns The memoized function.
14
14
  */
15
- use = <A extends any[], R>(fn: (...args: A) => R) => {
15
+ use<A extends any[], R>(fn: (...args: A) => R) {
16
16
  if (this.#memoized.has(fn)) return this.#memoized.get(fn) as typeof fn;
17
17
 
18
18
  // closure will GC automatically
@@ -36,5 +36,5 @@ export class Memo {
36
36
  this.#memoized.set(fn, memo);
37
37
 
38
38
  return memo;
39
- };
39
+ }
40
40
  }
package/src/index.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  export { jsx, toGenerator, toStream, toString, type JSX } from "./jsx/index.js";
2
2
  export { Chunk } from "./jsx/chunk/index.js";
3
3
  export { Trie, Route } from "./trie/index.js";
4
- export { App, type Middleware } from "./app/index.js";
4
+ export { App, type Middleware, type Next } from "./app/index.js";
5
5
  export { Context } from "./app/context.js";
6
6
  export { Get } from "./app/helper/get.js";
7
7
  export { Post } from "./app/helper/post.js";
8
- export { csrf } from "./app/mw/csrf.js";
@@ -30,6 +30,18 @@ export class Chunk {
30
30
  this.value += chunks.join("");
31
31
  }
32
32
 
33
+ /**
34
+ * Wraps `new Chunk("html", true)`.
35
+ *
36
+ * Use to create a new `Chunk` and bypass escaping.
37
+ *
38
+ * @param html Safe string of HTML
39
+ * @returns New _safe_ `Chunk`
40
+ */
41
+ static safe(html: unknown) {
42
+ return new Chunk(html, true);
43
+ }
44
+
33
45
  /**
34
46
  * Escapes strings of HTML.
35
47
  *
package/src/jsx/index.ts CHANGED
@@ -2,7 +2,6 @@ import type { MaybeFunction, MaybePromise } from "../types/index.js";
2
2
  import { Chunk } from "./chunk/index.js";
3
3
  import type { IntrinsicElements as IE } from "./intrinsic-elements.js";
4
4
  import { merge } from "./merge-async-generators.js";
5
- import { setImmediate } from "node:timers/promises";
6
5
 
7
6
  /** ovr JSX namespace */
8
7
  export namespace JSX {
@@ -26,7 +25,7 @@ export namespace JSX {
26
25
  >;
27
26
  }
28
27
 
29
- /** Unknown component props. */
28
+ /** Unknown component props */
30
29
  export type Props = Record<string, JSX.Element>;
31
30
 
32
31
  /**
@@ -52,11 +51,12 @@ const voidElements = new Set([
52
51
 
53
52
  /**
54
53
  * The main function of the JSX transform cycle, each time JSX is encountered
55
- * it is passed into this function to be resolved.
54
+ * it is passed into this function to be resolved. This function doesn't need to be
55
+ * called recursively, JSX will be transformed into these `jsx()` function calls.
56
56
  *
57
57
  * @param tag string or function component
58
58
  * @param props object containing all the properties and attributes passed to the element or component
59
- * @returns an async generator that yields `Chunk`s of HTML
59
+ * @returns `AsyncGenerator` that yields `Chunk`s of HTML
60
60
  */
61
61
  export async function* jsx<P extends Props = Props>(
62
62
  tag: ((props: P) => JSX.Element) | string,
@@ -65,17 +65,18 @@ export async function* jsx<P extends Props = Props>(
65
65
  if (typeof tag === "function") {
66
66
  // component or fragment
67
67
  yield* toGenerator(tag(props));
68
-
69
68
  return;
70
69
  }
71
70
 
72
71
  // intrinsic element
73
- const { children, ...rest } = props;
74
-
72
+ // faster to concatenate attributes than to yield them as separate chunks
75
73
  let attributes = "";
76
74
 
77
- for (const key in rest) {
78
- const value = rest[key];
75
+ for (const key in props) {
76
+ // more memory efficient to skip children instead of destructuring and using ...rest
77
+ if (key === "children") continue;
78
+
79
+ const value = props[key];
79
80
 
80
81
  if (value === true) {
81
82
  // just put the key without the value
@@ -88,13 +89,15 @@ export async function* jsx<P extends Props = Props>(
88
89
  // otherwise, don't include the attribute
89
90
  }
90
91
 
91
- yield new Chunk(`<${tag}${attributes}>`, true);
92
+ if (tag === "html") yield Chunk.safe("<!doctype html>");
93
+
94
+ yield Chunk.safe(`<${tag}${attributes}>`);
92
95
 
93
96
  if (voidElements.has(tag)) return;
94
97
 
95
- yield* toGenerator(children);
98
+ yield* toGenerator(props.children);
96
99
 
97
- yield new Chunk(`</${tag}>`, true);
100
+ yield Chunk.safe(`</${tag}>`);
98
101
  }
99
102
 
100
103
  /**
@@ -109,7 +112,7 @@ export async function* Fragment(props: { children?: JSX.Element } = {}) {
109
112
 
110
113
  /**
111
114
  * @param element
112
- * @yields `Chunk`s of HTML as the `Element` resolves.
115
+ * @yields `Chunk`s of HTML as the `Element` resolves
113
116
  */
114
117
  export async function* toGenerator(
115
118
  element: JSX.Element,
@@ -127,69 +130,38 @@ export async function* toGenerator(
127
130
  if (element instanceof Chunk) {
128
131
  // already escaped or safe
129
132
  yield element;
130
-
131
133
  return;
132
134
  }
133
135
 
134
136
  if (typeof element === "object") {
135
137
  if (Symbol.asyncIterator in element) {
136
- // async iterable - lazily resolve
138
+ // any async iterable - lazily resolve
137
139
  for await (const children of element) yield* toGenerator(children);
138
-
139
140
  return;
140
141
  }
141
142
 
142
143
  if (Symbol.iterator in element) {
143
144
  // sync iterable
144
- const iterator = element[Symbol.iterator]();
145
-
146
- if (
147
- typeof iterator.next === "function" &&
148
- typeof iterator.throw === "function" &&
149
- typeof iterator.return === "function"
150
- ) {
151
- // sync generator
152
- // process lazily - avoids loading all in memory
153
- const yieldIterations = 150;
154
- let yieldCounter = yieldIterations;
155
-
156
- while (true) {
157
- const result = iterator.next();
158
-
159
- if (result.done) break;
160
- yield* toGenerator(result.value);
161
-
162
- if (--yieldCounter === 0) {
163
- // yields back to the event loop to send chunks
164
- // or check if the request has been cancelled
165
- await setImmediate();
166
- yieldCounter = yieldIterations;
167
- }
168
- }
169
-
145
+ if ("next" in element) {
146
+ // sync generator - lazily resolve, avoids loading all in memory
147
+ for (const children of element) yield* toGenerator(children);
170
148
  return;
171
149
  }
172
150
 
173
151
  // other iterable - array, set, etc.
174
152
  // process children in parallel
175
- const generators: AsyncGenerator<Chunk, void, unknown>[] = [];
176
-
177
- while (true) {
178
- const result = iterator.next();
179
- if (result.done) break;
180
- generators.push(toGenerator(result.value));
181
- }
182
-
183
- const queue: (Chunk | null)[] = new Array(generators.length);
184
- const complete = new Set<number>();
153
+ const generators = Array.from(element, toGenerator);
154
+ const n = generators.length;
155
+ const queue = new Array<Chunk | null>(n);
156
+ const complete = new Uint8Array(n);
185
157
  let current = 0;
186
158
 
187
159
  for await (const m of merge(generators)) {
188
160
  if (m.result.done) {
189
- complete.add(m.index);
161
+ complete[m.index] = 1;
190
162
 
191
163
  if (m.index === current) {
192
- while (++current < generators.length) {
164
+ while (++current < n) {
193
165
  if (queue[current]) {
194
166
  // yield whatever is in the next queue even if it hasn't completed yet
195
167
  yield queue[current]!;
@@ -197,7 +169,7 @@ export async function* toGenerator(
197
169
  }
198
170
 
199
171
  // if it hasn't completed, stop iterating to the next
200
- if (!complete.has(current)) break;
172
+ if (!complete[current]) break;
201
173
  }
202
174
  }
203
175
  } else if (m.index === current) {
@@ -210,8 +182,7 @@ export async function* toGenerator(
210
182
  }
211
183
 
212
184
  // clear the queue
213
- yield* queue.filter(Boolean) as Chunk[];
214
-
185
+ yield* queue.filter((chunk) => chunk !== null);
215
186
  return;
216
187
  }
217
188
  }
@@ -247,25 +218,41 @@ const encoder = new TextEncoder();
247
218
  export const toStream = (element: JSX.Element) => {
248
219
  const gen = toGenerator(element);
249
220
 
250
- return new ReadableStream<Uint8Array>({
251
- async pull(c) {
252
- const result = await gen.next();
221
+ return new ReadableStream<Uint8Array>(
222
+ {
223
+ // enables zero-copy transfer from underlying source when queue is empty
224
+ // https://developer.mozilla.org/en-US/docs/Web/API/Streams_API/Using_readable_byte_streams#overview
225
+ type: "bytes",
226
+ // `pull` ensures backpressure and cancelled requests stop the generator
227
+ async pull(c) {
228
+ const result = await gen.next();
229
+
230
+ if (result.done) {
231
+ c.close();
232
+ gen.return();
233
+ return;
234
+ }
253
235
 
254
- if (result.done) {
255
- c.close();
236
+ c.enqueue(
237
+ // need to encode for Node (ex: during prerendering) or it will error
238
+ // doesn't seem to be needed for browsers
239
+ // faster than piping through a `TextEncoderStream`
240
+ encoder.encode(result.value.value),
241
+ );
242
+ },
243
+ cancel() {
256
244
  gen.return();
257
- return;
258
- }
259
-
260
- c.enqueue(
261
- // need to encode for Node JS (ex: during prerendering)
262
- // faster than piping through a `TextEncoderStream`
263
- encoder.encode(result.value.value),
264
- );
245
+ },
265
246
  },
266
-
267
- cancel() {
268
- gen.return();
247
+ {
248
+ // `highWaterMark` defaults to 1
249
+ // https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/ReadableStream#highwatermark
250
+ // setting this ensures at least a small buffer is maintained if the
251
+ // underlying server does not have its own high water mark set
252
+ // https://blog.cloudflare.com/unpacking-cloudflare-workers-cpu-performance-benchmarks/#inefficient-streams-adapters
253
+ // in Node, the default is 16kb, so this stacks another 2kb in front
254
+ // https://nodejs.org/api/http.html#outgoingmessagewritablehighwatermark
255
+ highWaterMark: 2048,
269
256
  },
270
- });
257
+ );
271
258
  };
@@ -16,9 +16,9 @@ export async function* merge<T>(generators: AsyncGenerator<T, void>[]) {
16
16
  const iterators = generators.map((gen) => gen[Symbol.asyncIterator]());
17
17
  const promises = new Map<number, ReturnType<typeof next<T, void>>>();
18
18
 
19
- iterators.forEach((iterator, index) =>
20
- promises.set(index, next(iterator, index)),
21
- );
19
+ for (let i = 0; i < iterators.length; i++) {
20
+ promises.set(i, next(iterators[i]!, i));
21
+ }
22
22
 
23
23
  let current: Awaited<ReturnType<typeof next>>;
24
24
 
@@ -37,8 +37,11 @@ export async function* merge<T>(generators: AsyncGenerator<T, void>[]) {
37
37
  }
38
38
  } finally {
39
39
  for (const iterator of iterators) {
40
- // catch - could have already returned
41
- iterator.return().catch(() => {});
40
+ try {
41
+ iterator.return();
42
+ } catch {
43
+ // could have already returned
44
+ }
42
45
  }
43
46
  }
44
47
  }
package/src/trie/index.ts CHANGED
@@ -7,6 +7,10 @@ export class Route<Store> {
7
7
  /** Store returned when route is found */
8
8
  store: Store;
9
9
 
10
+ /**
11
+ * @param pattern route pattern
12
+ * @param store value to store in the patterns final node
13
+ */
10
14
  constructor(pattern: string, store: Store) {
11
15
  if (pattern[0] !== "/") {
12
16
  throw new Error(
@@ -50,6 +54,9 @@ export class Trie<Store> {
50
54
  /** Matched wildcard route */
51
55
  wildcardRoute: Route<Store> | null = null;
52
56
 
57
+ static #paramMatch = /:.+?(?=\/|$)/g;
58
+ static #paramSplit = /:.+?(?=\/|$)/;
59
+
53
60
  /**
54
61
  * @param segment pattern segment
55
62
  * @param staticChildren static children nodes to add to staticMap
@@ -142,8 +149,8 @@ export class Trie<Store> {
142
149
  const endsWithWildcard = pattern.endsWith("*");
143
150
  if (endsWithWildcard) pattern = pattern.slice(0, -1);
144
151
 
145
- const paramSegments = pattern.match(/:.+?(?=\/|$)/g) ?? []; // match the params
146
- const staticSegments = pattern.split(/:.+?(?=\/|$)/); // split on the params
152
+ const paramSegments = pattern.match(Trie.#paramMatch) ?? [];
153
+ const staticSegments = pattern.split(Trie.#paramSplit);
147
154
 
148
155
  // if the last segment is a param without a trailing slash
149
156
  // then there will be an empty string, remove
package/src/util/hash.ts CHANGED
@@ -9,8 +9,8 @@
9
9
  */
10
10
  export const hash = (s: string) => {
11
11
  let hash = 5381;
12
-
13
12
  let i = s.length;
13
+
14
14
  while (i) hash = (hash * 33) ^ s.charCodeAt(--i);
15
15
 
16
16
  return (hash >>> 0).toString(36);
@@ -1,23 +0,0 @@
1
- import type { Middleware } from "../index.js";
2
- /**
3
- * Basic
4
- * [cross-site request forgery (CSRF)](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF)
5
- * protection that checks the request's `method` and `Origin` header.
6
- * For more robust protection you'll need a stateful server or a database to store
7
- * [CSRF tokens](https://developer.mozilla.org/en-US/docs/Web/Security/Attacks/CSRF#csrf_tokens).
8
- *
9
- * @param options
10
- * @returns CSRF middleware
11
- *
12
- * @example
13
- *
14
- * ```ts
15
- * import { csrf } from "ovr";
16
- *
17
- * app.use(csrf({ origin: "https://example.com" }));
18
- * ```
19
- */
20
- export declare const csrf: (options: {
21
- origin: string | string[];
22
- }) => Middleware;
23
- //# sourceMappingURL=csrf.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"csrf.d.ts","sourceRoot":"","sources":["../../../src/app/mw/csrf.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAE9C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,IAAI,GAAI,SAAS;IAAE,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;CAAE,KAAG,UAW7D,CAAC"}