ovr 1.3.0 → 2.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.
@@ -0,0 +1,41 @@
1
+ import { type JSX } from "../jsx/index.js";
2
+ import type { ExtractParams } from "../types/index.js";
3
+ import type { Middleware, Params } from "./index.js";
4
+ type AnchorProps<P extends Params> = Omit<JSX.IntrinsicElements["a"], "href"> & (keyof P extends never ? {
5
+ params?: never;
6
+ } : {
7
+ params: P;
8
+ });
9
+ export declare class Page<Pattern extends string = string> {
10
+ #private;
11
+ /** Route pattern */
12
+ pattern: Pattern;
13
+ /** GET middleware */
14
+ middleware: Middleware<any>[];
15
+ /** `<a>` component with preset `href` attribute. */
16
+ Anchor: (props: AnchorProps<ExtractParams<Pattern>>) => AsyncGenerator<string, void, unknown>;
17
+ /**
18
+ * @param pattern Route pattern
19
+ * @param middleware GET middleware
20
+ *
21
+ * @example
22
+ *
23
+ * ```tsx
24
+ * // page.tsx
25
+ * import { Page } from "ovr";
26
+ *
27
+ * export const page = new Page("/", () => {
28
+ * return <p>Hello world</p>
29
+ * });
30
+ *
31
+ * const Nav = () => {
32
+ * return <page.Anchor>Home</page.Anchor>
33
+ * }
34
+ *
35
+ * // app.tsx
36
+ * app.add(page); registers the page
37
+ * ```
38
+ */
39
+ constructor(pattern: Pattern, ...middleware: Middleware<ExtractParams<Pattern>>[]);
40
+ }
41
+ export {};
@@ -0,0 +1,42 @@
1
+ import { jsx } from "../jsx/index.js";
2
+ import { insertParams } from "../trie/insert-params.js";
3
+ export class Page {
4
+ /** Route pattern */
5
+ pattern;
6
+ /** GET middleware */
7
+ middleware;
8
+ /** `<a>` component with preset `href` attribute. */
9
+ Anchor;
10
+ #parts;
11
+ /**
12
+ * @param pattern Route pattern
13
+ * @param middleware GET middleware
14
+ *
15
+ * @example
16
+ *
17
+ * ```tsx
18
+ * // page.tsx
19
+ * import { Page } from "ovr";
20
+ *
21
+ * export const page = new Page("/", () => {
22
+ * return <p>Hello world</p>
23
+ * });
24
+ *
25
+ * const Nav = () => {
26
+ * return <page.Anchor>Home</page.Anchor>
27
+ * }
28
+ *
29
+ * // app.tsx
30
+ * app.add(page); registers the page
31
+ * ```
32
+ */
33
+ constructor(pattern, ...middleware) {
34
+ this.pattern = pattern;
35
+ this.middleware = middleware;
36
+ this.#parts = pattern.split("/");
37
+ this.Anchor = (props) => {
38
+ const { params = {}, ...rest } = props;
39
+ return jsx("a", { href: insertParams(this.#parts, params), ...rest });
40
+ };
41
+ }
42
+ }
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Escapes strings of HTML.
3
3
  *
4
- * @param v value to escape
5
- * @param attr set to `true` if the value is an attribute, otherwise it's a string of HTML content
6
- * @returns escaped string of HTML
4
+ * @param value Converted to a string, then escaped.
5
+ * @param attr Set to `true` if the value is an attribute, otherwise it's a string of HTML content
6
+ * @returns Escaped string of HTML
7
7
  */
8
- export declare const escape: (v: unknown, attr?: boolean) => string;
8
+ export declare const escape: (value: unknown, attr?: boolean) => string;
@@ -1,15 +1,15 @@
1
- // Copied and adapted from https://github.com/sveltejs/svelte/blob/main/packages/svelte/src/escaping.js
2
1
  const attrRegex = /[&"<]/g;
3
2
  const contentRegex = /[&<]/g;
4
3
  /**
5
4
  * Escapes strings of HTML.
6
5
  *
7
- * @param v value to escape
8
- * @param attr set to `true` if the value is an attribute, otherwise it's a string of HTML content
9
- * @returns escaped string of HTML
6
+ * @param value Converted to a string, then escaped.
7
+ * @param attr Set to `true` if the value is an attribute, otherwise it's a string of HTML content
8
+ * @returns Escaped string of HTML
10
9
  */
11
- export const escape = (v, attr) => {
12
- const s = String(v ?? "");
10
+ export const escape = (value, attr) => {
11
+ // copied and adapted from https://github.com/sveltejs/svelte/blob/main/packages/svelte/src/escaping.js
12
+ const s = String(value ?? "");
13
13
  const regex = attr ? attrRegex : contentRegex;
14
14
  // search starts at beginning of the string
15
15
  regex.lastIndex = 0;
@@ -0,0 +1 @@
1
+ export declare const hash: (s: string) => string;
@@ -0,0 +1,9 @@
1
+ // Fast hashing algorithm http://www.cse.yorku.ca/~oz/hash.html
2
+ // Adapted from SvelteKit https://github.com/sveltejs/kit/blob/25d459104814b0c2dc6b4cf73b680378a29d8200/packages/kit/src/runtime/hash.js
3
+ export const hash = (s) => {
4
+ let hash = 5381;
5
+ let i = s.length;
6
+ while (i)
7
+ hash = (hash * 33) ^ s.charCodeAt(--i);
8
+ return (hash >>> 0).toString(36);
9
+ };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
- export { Suspense } from "./components/suspense.js";
2
- export { escape } from "./escape/index.js";
3
- export { jsx, jsx as jsxs, jsx as jsxDEV, Fragment, toGenerator, toString, type FC, type JSX, } from "./jsx/index.js";
4
- export { Context } from "./router/context.js";
5
- export { Router, type Middleware, type Params } from "./router/index.js";
1
+ export { jsx, toGenerator, toString, type JSX } from "./jsx/index.js";
6
2
  export { Trie, Route } from "./trie/index.js";
3
+ export { App, type Middleware, type Params } from "./app/index.js";
4
+ export { Context } from "./app/context.js";
5
+ export { Page } from "./app/page.js";
6
+ export { Action } from "./app/action.js";
7
+ export { escape } from "./escape/index.js";
8
+ export type * from "./types/index.js";
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
- export { Suspense } from "./components/suspense.js";
2
- export { escape } from "./escape/index.js";
3
- export { jsx, jsx as jsxs, jsx as jsxDEV, Fragment, toGenerator, toString, } from "./jsx/index.js";
4
- export { Context } from "./router/context.js";
5
- export { Router } from "./router/index.js";
1
+ export { jsx, toGenerator, toString } from "./jsx/index.js";
6
2
  export { Trie, Route } from "./trie/index.js";
3
+ export { App } from "./app/index.js";
4
+ export { Context } from "./app/context.js";
5
+ export { Page } from "./app/page.js";
6
+ export { Action } from "./app/action.js";
7
+ export { escape } from "./escape/index.js";
@@ -277,7 +277,7 @@ type LabelAttributes = Attributes<{
277
277
  type LiAttributes = Attributes<{
278
278
  value: string;
279
279
  }>;
280
- type LinkAttributes = Attributes<{
280
+ type AnchorAttributes = Attributes<{
281
281
  as: "audio" | "document" | "embed" | "fetch" | "font" | "image" | "object" | "script" | "style" | "track" | "video" | "worker";
282
282
  blocking: SharedAttributes["blocking"];
283
283
  crossorigin: SharedAttributes["crossorigin"];
@@ -503,7 +503,7 @@ export type Elements = Record<string, Attributes> & {
503
503
  label: LabelAttributes;
504
504
  legend: Attributes;
505
505
  li: LiAttributes;
506
- link: LinkAttributes;
506
+ link: AnchorAttributes;
507
507
  main: Attributes;
508
508
  map: MapAttributes;
509
509
  mark: Attributes;
@@ -1,6 +1,5 @@
1
+ import type { MaybeFunction, MaybePromise } from "../types/index.js";
1
2
  import type { Elements } from "./elements.js";
2
- type MaybePromise<T> = T | Promise<T>;
3
- type MaybeFunction<T> = T | (() => T);
4
3
  export declare namespace JSX {
5
4
  interface IntrinsicElements extends Elements {
6
5
  }
@@ -34,12 +33,12 @@ export declare function toGenerator(element: JSX.Element): AsyncGenerator<string
34
33
  /**
35
34
  * Converts a `JSX.Element` into a fully concatenated string of HTML.
36
35
  *
37
- * > [!WARNING]
38
- * >
39
- * > This negates streaming benefits and buffers the result into a string.
36
+ * ### WARNING
37
+ *
38
+ * This negates streaming benefits and buffers the result into a string.
39
+ * Use `toGenerator` whenever possible.
40
40
  *
41
41
  * @param element
42
- * @returns A promise that resolves to the concatenated string.
42
+ * @returns A promise that resolves to the concatenated HTML.
43
43
  */
44
44
  export declare const toString: (element: JSX.Element) => Promise<string>;
45
- export {};
package/dist/jsx/index.js CHANGED
@@ -84,8 +84,10 @@ export async function* toGenerator(element) {
84
84
  }
85
85
  else if (Symbol.iterator in element) {
86
86
  const generators = [];
87
- for (const children of element)
87
+ for (const children of element) {
88
+ // this is where to escape string children if added in the future
88
89
  generators.push(toGenerator(children));
90
+ }
89
91
  const queue = new Array(generators.length).fill("");
90
92
  const complete = new Set();
91
93
  let current = 0;
@@ -125,12 +127,13 @@ export async function* toGenerator(element) {
125
127
  /**
126
128
  * Converts a `JSX.Element` into a fully concatenated string of HTML.
127
129
  *
128
- * > [!WARNING]
129
- * >
130
- * > This negates streaming benefits and buffers the result into a string.
130
+ * ### WARNING
131
+ *
132
+ * This negates streaming benefits and buffers the result into a string.
133
+ * Use `toGenerator` whenever possible.
131
134
  *
132
135
  * @param element
133
- * @returns A promise that resolves to the concatenated string.
136
+ * @returns A promise that resolves to the concatenated HTML.
134
137
  */
135
138
  export const toString = async (element) => {
136
139
  let buffer = "";
@@ -1 +1 @@
1
- export { jsx, jsx as jsxs, jsx as jsxDEV, Fragment, toGenerator, toString, type FC, type JSX, } from "./jsx/index.js";
1
+ export { jsx as jsxDEV, Fragment, type JSX } from "./jsx/index.js";
@@ -1 +1 @@
1
- export { jsx, jsx as jsxs, jsx as jsxDEV, Fragment, toGenerator, toString, } from "./jsx/index.js";
1
+ export { jsx as jsxDEV, Fragment } from "./jsx/index.js";
@@ -1 +1 @@
1
- export { jsx, jsx as jsxs, jsx as jsxDEV, Fragment, toGenerator, toString, type FC, type JSX, } from "./jsx/index.js";
1
+ export { jsx, jsx as jsxs, Fragment, type JSX } from "./jsx/index.js";
@@ -1 +1 @@
1
- export { jsx, jsx as jsxs, jsx as jsxDEV, Fragment, toGenerator, toString, } from "./jsx/index.js";
1
+ export { jsx, jsx as jsxs, Fragment } from "./jsx/index.js";
@@ -0,0 +1,11 @@
1
+ export declare class Memo {
2
+ #private;
3
+ /**
4
+ * Calls to the returned function with the same arguments will
5
+ * return a cached result.
6
+ *
7
+ * @param fn Function to memoize.
8
+ * @returns The memoized function.
9
+ */
10
+ use: <A extends any[], R>(fn: (...args: A) => R) => (...args: A) => R;
11
+ }
@@ -0,0 +1,34 @@
1
+ export class Memo {
2
+ /** Already memoized functions. */
3
+ #memoized = new WeakMap();
4
+ /** Symbol to store the result of each memoized function. */
5
+ static #RESULT = Symbol();
6
+ /**
7
+ * Calls to the returned function with the same arguments will
8
+ * return a cached result.
9
+ *
10
+ * @param fn Function to memoize.
11
+ * @returns The memoized function.
12
+ */
13
+ use = (fn) => {
14
+ if (this.#memoized.has(fn))
15
+ return this.#memoized.get(fn);
16
+ // closure will GC automatically
17
+ const trie = new Map();
18
+ const memo = (...args) => {
19
+ let node = trie;
20
+ for (const arg of args) {
21
+ // get/create a node for each arg
22
+ if (!node.has(arg))
23
+ node.set(arg, new Map());
24
+ node = node.get(arg);
25
+ }
26
+ // set the final result if not there
27
+ if (!node.has(Memo.#RESULT))
28
+ node.set(Memo.#RESULT, fn(...args));
29
+ return node.get(Memo.#RESULT);
30
+ };
31
+ this.#memoized.set(fn, memo);
32
+ return memo;
33
+ };
34
+ }
@@ -1,3 +1,4 @@
1
+ export type Params = Record<string, string>;
1
2
  export declare class Route<Store> {
2
3
  /** Route pattern */
3
4
  pattern: string;
@@ -69,7 +70,7 @@ export declare class Trie<Store> {
69
70
  */
70
71
  find(pathname: string): {
71
72
  route: Route<Store>;
72
- params: Record<string, string>;
73
+ params: Params;
73
74
  } | null;
74
75
  }
75
76
  export {};
@@ -0,0 +1,7 @@
1
+ import type { Params } from "./index.js";
2
+ /**
3
+ * @param parts Pattern parts
4
+ * @param params Parameters to insert
5
+ * @returns Resolved pathname with params
6
+ */
7
+ export declare const insertParams: (parts: string[], params: Params) => string;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @param parts Pattern parts
3
+ * @param params Parameters to insert
4
+ * @returns Resolved pathname with params
5
+ */
6
+ export const insertParams = (parts, params) => parts
7
+ .map((part) => {
8
+ if (part.startsWith(":")) {
9
+ const param = part.slice(1);
10
+ if (!(param in params))
11
+ throw new Error(`Parameter "${param}" did not match pattern..`);
12
+ return params[param];
13
+ }
14
+ const wild = "*";
15
+ if (part === wild) {
16
+ if (!(wild in params))
17
+ throw new Error("No wildcard parameter found.");
18
+ return params[wild];
19
+ }
20
+ return part;
21
+ })
22
+ .join("/");
@@ -0,0 +1,14 @@
1
+ export type MaybePromise<T> = T | Promise<T>;
2
+ export type MaybeFunction<T> = T | (() => T);
3
+ export type DeepArray<T> = T | DeepArray<T>[];
4
+ export type ExtractParams<Pattern extends string = string> = Pattern extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
5
+ [k in Param | keyof ExtractParams<Rest>]: string;
6
+ } : Pattern extends `${infer _Start}:${infer Param}` ? {
7
+ [k in Param]: string;
8
+ } : Pattern extends `${infer _Rest}*` ? {
9
+ "*": string;
10
+ } : {};
11
+ export type ExtractMultiParams<Patterns extends string[]> = Patterns extends [
12
+ infer First extends string,
13
+ ...infer Rest extends string[]
14
+ ] ? Rest["length"] extends 0 ? ExtractParams<First> : ExtractParams<First> | ExtractMultiParams<Rest> : never;
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ovr",
3
- "description": "Asynchronous streaming server framework",
4
- "version": "1.3.0",
3
+ "description": "Progressive HTML Rendering",
4
+ "version": "2.0.0",
5
5
  "license": "MIT",
6
6
  "repository": {
7
7
  "type": "git",
@@ -16,6 +16,9 @@
16
16
  "types": "./dist/index.d.ts",
17
17
  "main": "./dist/index.js",
18
18
  "exports": {
19
+ "./package.json": {
20
+ "default": "./package.json"
21
+ },
19
22
  ".": {
20
23
  "types": "./dist/index.d.ts",
21
24
  "default": "./dist/index.js"
@@ -1,2 +0,0 @@
1
- /** Head tags to inject for included components. */
2
- export declare const head = "<style>l-f,l-c{display:contents}l-f:has(+*>l-c:not(:empty)){display:none}l-a{display:flex;flex-direction:column-reverse}</style>";
@@ -1,3 +0,0 @@
1
- import * as suspense from "./suspense.js";
2
- /** Head tags to inject for included components. */
3
- export const head = `<style>${suspense.style}</style>`;
@@ -1,33 +0,0 @@
1
- import type { JSX } from "../jsx/index.js";
2
- export declare const style = "l-f,l-c{display:contents}l-f:has(+*>l-c:not(:empty)){display:none}l-a{display:flex;flex-direction:column-reverse}";
3
- /**
4
- * Wrap an async component with `Suspense` to provide a loading `fallback`
5
- * to display before it resolves. The `Suspense` component works without
6
- * client-side JavaScript using CSS to hide the `fallback` once the `children`
7
- * are streamed in and to reverse the order of the `children` and `after` elements.
8
- *
9
- * `fallback`, `after`, and `children` are resolved in parallel but streamed sequentially.
10
- *
11
- * @param props
12
- *
13
- * @example
14
- *
15
- * ```tsx
16
- * <Suspense fallback={<p>Loading...</p>} after={<footer>After</footer>}>
17
- * <AsyncComponent />
18
- * </Suspense>
19
- * ```
20
- */
21
- export declare function Suspense(props: {
22
- /** Fallback to display while `children` are loading. */
23
- fallback?: JSX.Element;
24
- /**
25
- * Element(s) to display _visually after_ the `children`, but stream/resolve before.
26
- *
27
- * Ensure `after` does take less time to resolve than `children`, otherwise
28
- * `children` will be blocked until `after` resolves.
29
- */
30
- after?: JSX.Element;
31
- /** Asynchronous element(s) to provide a fallback for. */
32
- children?: JSX.Element;
33
- }): JSX.Element;
@@ -1,31 +0,0 @@
1
- export const style = /* css */ `l-f,l-c{display:contents}l-f:has(+*>l-c:not(:empty)){display:none}l-a{display:flex;flex-direction:column-reverse}`;
2
- /**
3
- * Wrap an async component with `Suspense` to provide a loading `fallback`
4
- * to display before it resolves. The `Suspense` component works without
5
- * client-side JavaScript using CSS to hide the `fallback` once the `children`
6
- * are streamed in and to reverse the order of the `children` and `after` elements.
7
- *
8
- * `fallback`, `after`, and `children` are resolved in parallel but streamed sequentially.
9
- *
10
- * @param props
11
- *
12
- * @example
13
- *
14
- * ```tsx
15
- * <Suspense fallback={<p>Loading...</p>} after={<footer>After</footer>}>
16
- * <AsyncComponent />
17
- * </Suspense>
18
- * ```
19
- */
20
- export function Suspense(props) {
21
- const wrap = props.after != null ? "a" : "w";
22
- return [
23
- "<l-f>",
24
- props.fallback,
25
- "</l-f><l-" + wrap + "><div>",
26
- props.after,
27
- "</div><l-c>",
28
- props.children,
29
- "</l-c></l-" + wrap + ">",
30
- ];
31
- }
@@ -1,99 +0,0 @@
1
- import { Context } from "./context.js";
2
- export type Params = Record<string, string>;
3
- export type UnmatchedContext<State, P extends Params> = Omit<Context<State, P>, "route"> & Partial<Pick<Context<State, P>, "route">>;
4
- export type Start<State> = (context: Omit<UnmatchedContext<any, Params>, "state" | "route" | "params">) => State;
5
- export type Middleware<State = null, P extends Params = Params> = (context: Context<State, P>, next: () => Promise<void>) => any;
6
- export type TrailingSlash = "always" | "never" | "ignore";
7
- type Method = "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "CONNECT" | "OPTIONS" | "TRACE" | "PATCH" | (string & {});
8
- type ExtractParams<Pattern extends string = string> = Pattern extends `${infer _Start}:${infer Param}/${infer Rest}` ? {
9
- [k in Param | keyof ExtractParams<Rest>]: string;
10
- } : Pattern extends `${infer _Start}:${infer Param}` ? {
11
- [k in Param]: string;
12
- } : Pattern extends `${infer _Rest}*` ? {
13
- "*": string;
14
- } : {};
15
- type ExtractMultiParams<Patterns extends string[]> = Patterns extends [
16
- infer First extends string,
17
- ...infer Rest extends string[]
18
- ] ? Rest["length"] extends 0 ? ExtractParams<First> : ExtractParams<First> | ExtractMultiParams<Rest> : never;
19
- export declare class Router<State = null> {
20
- #private;
21
- [key: string]: any;
22
- constructor(config?: {
23
- /**
24
- * - `"never"` - Not found requests with a trailing slash will be redirected to the same path without a trailing slash
25
- * - `"always"` - Not found requests without a trailing slash will be redirected to the same path with a trailing slash
26
- * - `"ignore"` - no redirects (not recommended, bad for SEO)
27
- *
28
- * [Trailing Slash for Frameworks by Bjorn Lu](https://bjornlu.com/blog/trailing-slash-for-frameworks)
29
- *
30
- * @default "never"
31
- */
32
- trailingSlash?: TrailingSlash;
33
- /**
34
- * Runs before middleware, return a value to set the initial state.
35
- *
36
- * @param context request context
37
- * @returns any state to access in middleware
38
- * @default null
39
- */
40
- start?: Start<State>;
41
- });
42
- /**
43
- * Add global middleware.
44
- *
45
- * @param middleware
46
- * @returns the router instance
47
- */
48
- use(...middleware: Middleware<State, Params>[]): this;
49
- /**
50
- * @param method HTTP method
51
- * @param pattern route pattern
52
- * @param middleware
53
- * @returns the router instance
54
- */
55
- on<Pattern extends string>(method: Method | Method[], pattern: Pattern, ...middleware: Middleware<State, ExtractParams<Pattern>>[]): this;
56
- /**
57
- * @param method HTTP method
58
- * @param patterns array of route patterns
59
- * @param middleware
60
- * @returns the router instance
61
- */
62
- on<Patterns extends string[]>(method: Method | Method[], patterns: [...Patterns], ...middleware: Middleware<State, ExtractMultiParams<Patterns>>[]): this;
63
- /**
64
- * @param pattern route pattern
65
- * @param middleware
66
- * @returns the router instance
67
- */
68
- get<Pattern extends string>(pattern: Pattern, ...middleware: Middleware<State, ExtractParams<Pattern>>[]): this;
69
- /**
70
- * @param patterns array of route patterns
71
- * @param middleware
72
- * @returns the router instance
73
- */
74
- get<Patterns extends string[]>(patterns: [...Patterns], ...middleware: Middleware<State, ExtractMultiParams<Patterns>>[]): this;
75
- /**
76
- * @param pattern route pattern
77
- * @param middleware
78
- * @returns the router instance
79
- */
80
- post<Pattern extends string>(pattern: Pattern, ...middleware: Middleware<State, ExtractParams<Pattern>>[]): this;
81
- /**
82
- * @param patterns array of route patterns
83
- * @param middleware
84
- * @returns the router instance
85
- */
86
- post<Patterns extends string[]>(patterns: [...Patterns], ...middleware: Middleware<State, ExtractMultiParams<Patterns>>[]): this;
87
- /**
88
- * @param basePattern pattern to mount the router to, each route will begin with this base
89
- * @param router sub-router to mount
90
- * @returns the base router instance
91
- */
92
- mount(basePattern: string, router: Router<State>): this;
93
- /**
94
- * @param req [`Request` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Request)
95
- * @returns [`Response` Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response)
96
- */
97
- fetch(req: Request): Promise<Response>;
98
- }
99
- export {};