@zubra/router 0.0.0-stage → 5.18.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.
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026, Mikey Nichols
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,93 @@
1
- # Temporary Holding Version
1
+ # @zubra/router
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Serve Zubra components as pages, for apps with no host framework. A component says where it lives with `'use route <path>'`; an exported `load` runs on the server before it renders, and what it returns becomes its props.
4
+
5
+ ```html
6
+ <script>
7
+ 'use route /farms/:id'
8
+ import { farms } from '../db.js'
9
+ export async function load({ params }) {
10
+ const farm = await farms.get(params.id)
11
+ return { name: farm.name }
12
+ }
13
+ </script>
14
+ <farm-page name="">
15
+ <h1>{name}</h1>
16
+ </farm-page>
17
+ ```
18
+
19
+ ```js
20
+ import { createServer } from 'node:http';
21
+ import { createZubra } from '@zubra/server';
22
+ import { createRouter } from '@zubra/router';
23
+
24
+ const zubra = createZubra({ components: 'components' });
25
+ const router = await createRouter({ zubra, components: 'components' });
26
+
27
+ createServer(async (req, res) => {
28
+ if (zubra.handle(req, res)) return; // the components' browser modules
29
+ if (await router.handle(req, res)) return; // a GET or HEAD to a route
30
+ // …the app's own routes and files…
31
+ await router.notFound(req, res); // the 404 page
32
+ }).listen(3000);
33
+ ```
34
+
35
+ `router.listener` is a route or the 404 page, for `createServer` on its own, and `router.fetch(request)` answers fetch-style servers (a `Response`, or `null` when the path isn't a route; `router.notFoundResponse(request)` is the 404).
36
+
37
+ ## Routes
38
+
39
+ - `'use route /farms/:id'` names a path in [URLPattern](https://developer.mozilla.org/docs/Web/API/URL_Pattern_API) syntax: `:id`, `:path*`, `:tab?`.
40
+ - In a `routes/` folder inside the components folder, a bare `'use route'` takes its path from its place: `routes/index.zb` is `/`, `routes/farms/[id].zb` is `/farms/:id`, `routes/docs/[...path].zb` is `/docs/:path*`. A written path there must agree with the folder.
41
+ - A path with text in a segment is tried before one with a parameter there, and a parameter before a wildcard.
42
+ - Two routes with one path, and a parameter that neither `load` nor a prop reads, are errors: the compiler reports a written path's, `createRouter` a folder's and the duplicates.
43
+ - With `@zubra/router` not installed, `@zubra/server` refuses to render a `'use route'` component and says what to install.
44
+
45
+ ## Layouts
46
+
47
+ A layout is a component with a `<zb-slot></zb-slot>` where the page goes.
48
+
49
+ - **`app.zb`** in the components folder is the shell: the layout around every page. It needs no directive (it can say `'use layout /'` to export a `load`).
50
+ - **`'use layout /farm'`** wraps `/farm` and every page below it (whole segments: not `/farmers`), inside the shell. In `routes/`, a `layout.zb` with a bare `'use layout'` takes its folder as its prefix (`routes/farm/layout.zb`). Layouts nest to any depth, outermost first.
51
+ - **`'use layout /farm root'`** starts over: pages under `/farm` are inside it and not inside `app.zb` or any layout above it. For a section with its own frame, like a dashboard beside a public site.
52
+ - A layout or page that declares a `route` prop is given `{ path, pattern, params }`, to mark where you are: `aria-current={route.path === '/farm/stock' ? 'page' : null}`.
53
+ - A layout can export its own `load`; the loads run outermost first (see below).
54
+
55
+ The router writes the document around them: `<!doctype html>`, `<html lang>`, a `<head>` with the charset, the viewport and the components' CSS, and the scripts. `createRouter({ lang: 'en-GB', head: '<link rel="stylesheet" href="/site.css">' })` sets the language and adds to the head; `head` can be a function of `{ url, request, route }`.
56
+
57
+ A layout with no default slot, two layouts for one prefix, and a `layout.zb` whose written prefix disagrees with its folder are errors at `createRouter`.
58
+
59
+ ## `load`
60
+
61
+ `load({ params, url, request, route, context, result })` runs on the server only. The compiler takes it, and whatever only it imports, out of the browser module; it isn't an action, so nothing can post to it.
62
+
63
+ - **`context`** is what `createRouter({ context })` returns for the request: the signed-in person, a database handle. Give it the function `createActions({ context })` has, so actions and pages see the same thing. It is made once per request.
64
+ - **`result`** is an action's answer after a post without JavaScript, once (`{ action, value }`, or `null`). Pass `createRouter({ actions })` the app's `createActions()`; the router sends the header that clears it.
65
+
66
+ What it returns:
67
+
68
+ - **Props.** The props the page declares are taken from the result; anything else stays on the server (the compiler warns about a key a page returns that isn't one of its props). A parameter the page declares as a prop is passed too.
69
+ - **`title`**: the document's `<title>`. The innermost one wins, so a page's over its layout's.
70
+ - **`notFound()`**: a 404.
71
+ - **`redirect('/cart')`**: 303 to there (`redirect(to, 301)` for another status).
72
+ - **`show('sign-in', { next: '/door' })`**: another component at the same URL, in this one's place, with those props (`{ status: 403 }` as a third argument sets the response's). For a sign-in form or a "this page is for farmers" notice.
73
+
74
+ ```html
75
+ <script>
76
+ 'use route /door'
77
+ import { show } from '@zubra/router'
78
+ export async function load({ context }) {
79
+ if (!context.staff) return show('sign-in', { next: '/door' })
80
+ return { who: context.staff.name }
81
+ }
82
+ </script>
83
+ ```
84
+
85
+ A layout's `load` works the same way, and for its whole section: what it returns reaches every layout and page inside it that declares the prop, and when it answers with `notFound()`, `redirect()` or `show()`, the loads inside it don't run. A `show()` from a layout takes the layout's place, inside the layouts over it; from a `root` layout, that is the app's shell.
86
+
87
+ ## Errors
88
+
89
+ An unknown path (`router.notFound(req, res)` at the end of the app's handlers, or `router.listener`), `notFound()`, and a `load` that throws render inside `app.zb`, with status 404 or 500. `error.zb`, if the app has one, goes in the shell's slot with a `status` prop; otherwise a heading does. A shell that declares an `error` prop is given `{ status }`. The message never reaches the browser; `onError(error, request)` is told. With no shell, or when the shell can't render, the response is plain text.
90
+
91
+ ## What it doesn't do
92
+
93
+ Client-side navigation: links load pages. Posts: those are `@zubra/actions`, or the app's own handler. Static files, sessions and caching are the app's server's. `docs/router.md` in the repository has the whole reference.
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@zubra/router",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "5.18.0",
4
+ "description": "Serve Zubra components that say 'use route <path>' as pages, with a server-only load, for apps with no host framework.",
5
+ "type": "module",
6
+ "main": "./src/index.js",
7
+ "types": "./src/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./src/index.d.ts",
11
+ "default": "./src/index.js"
12
+ },
13
+ "./table": {
14
+ "types": "./src/table.d.ts",
15
+ "default": "./src/table.js"
16
+ }
17
+ },
18
+ "scripts": {
19
+ "test": "node --test \"test/*.test.js\""
20
+ },
21
+ "dependencies": {
22
+ "urlpattern-polyfill": "10.1.0"
23
+ },
24
+ "peerDependencies": {
25
+ "@zubra/compiler": "^5.18.0",
26
+ "@zubra/server": "^5.18.0"
27
+ },
28
+ "devDependencies": {
29
+ "@zubra/compiler": "file:../compiler",
30
+ "@zubra/runtime": "file:../runtime",
31
+ "@zubra/server": "file:../server",
32
+ "playwright": "1.63.0"
33
+ },
34
+ "files": [
35
+ "src",
36
+ "README.md"
37
+ ],
38
+ "engines": {
39
+ "node": ">=20"
40
+ },
41
+ "license": "ISC",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "git+https://github.com/journey-to-code-org/zubra.git",
45
+ "directory": "router"
46
+ }
47
+ }
package/src/answers.js ADDED
@@ -0,0 +1,23 @@
1
+ // What a `load` can return besides props. Marked with a registered symbol, so an answer made by
2
+ // one copy of this module is recognised by another.
3
+ export const ANSWER = Symbol.for('@zubra/router.answer');
4
+
5
+ /** `return notFound()`: the path has nothing behind it (no such farm). The response is a 404. */
6
+ export const notFound = () => ({ [ANSWER]: 'notFound' });
7
+
8
+ /** `return redirect('/cart')`: send the browser elsewhere (303 unless `status` says otherwise). */
9
+ export const redirect = (location, status = 303) => {
10
+ if (typeof location !== 'string' || !location) throw new TypeError("@zubra/router: redirect() needs where to go: redirect('/cart')");
11
+ if (![301, 302, 303, 307, 308].includes(status)) throw new TypeError(`@zubra/router: redirect()'s status is 301, 302, 303, 307 or 308, not ${status}`);
12
+ return { [ANSWER]: 'redirect', location, status };
13
+ };
14
+
15
+ /**
16
+ * `return show('sign-in', { next: '/door' })`: render another component here, at the same URL,
17
+ * in place of the one whose `load` this is (a sign-in form, a "this page is for farmers"
18
+ * notice). `status` is the response's (200 unless given: 401, 403).
19
+ */
20
+ export const show = (name, props = {}, { status = 200 } = {}) => {
21
+ if (typeof name !== 'string' || !name) throw new TypeError("@zubra/router: show() needs a component's name: show('sign-in', { next })");
22
+ return { [ANSWER]: 'show', name, props, status };
23
+ };
package/src/index.d.ts ADDED
@@ -0,0 +1,97 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Zubra } from '@zubra/server';
3
+
4
+ export { RouteError } from './table.js';
5
+
6
+ /** An answer from `load` that isn't props. */
7
+ export interface LoadAnswer { readonly __answer: 'notFound' | 'redirect' | 'show' }
8
+ /** `return notFound()`: nothing is behind this path. The response is a 404. */
9
+ export function notFound(): LoadAnswer;
10
+ /** `return redirect('/cart')`: send the browser elsewhere (303 unless `status` says otherwise). */
11
+ export function redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): LoadAnswer;
12
+ /**
13
+ * `return show('sign-in', { next })`: render another component at the same URL, in place of
14
+ * the one whose `load` this is. From a layout, it takes the layout's place, inside the layouts
15
+ * over it.
16
+ */
17
+ export function show(name: string, props?: Record<string, unknown>, options?: { status?: number }): LoadAnswer;
18
+
19
+ /** What a route's `load` is given. */
20
+ export interface LoadArguments {
21
+ /** The route's parameters (`{ id: 'hilltop' }` for `/farms/:id` at `/farms/hilltop`). */
22
+ params: Record<string, string>;
23
+ url: URL;
24
+ request: Request;
25
+ /** The page the request matched. */
26
+ route: MatchedRoute;
27
+ /** What `createRouter({ context })` returned for this request (`{}` without one). */
28
+ context: Record<string, any>;
29
+ /** After a post without JavaScript, the action's answer, once (needs `createRouter({ actions })`). */
30
+ result: { action: string; value: unknown } | null;
31
+ }
32
+
33
+ /** What a layout or page that declares a `route` prop is given. */
34
+ export interface MatchedRoute {
35
+ /** The request's path: `/farms/hilltop`. */
36
+ path: string;
37
+ /** The page's pattern: `/farms/:id`. */
38
+ pattern: string;
39
+ params: Record<string, string>;
40
+ }
41
+
42
+ export interface RouterOptions {
43
+ /** The app's `createZubra()`: it renders the pages. */
44
+ zubra: Zubra;
45
+ /** The folder of components, the same one `zubra` reads (default `components`). */
46
+ components?: string;
47
+ /** Where the routes' server halves are written (default `node_modules/.cache/zubra-router`). */
48
+ cacheDir?: string;
49
+ /** Called when a `load` or a render throws; the browser gets the 500 page, never the message. */
50
+ onError?(error: unknown, request: Request): void;
51
+ /** The document's language (default `en`). */
52
+ lang?: string;
53
+ /**
54
+ * HTML for every page's `<head>` (fonts, a stylesheet), or a function returning it. Written
55
+ * as given: the app's own markup, never a visitor's text.
56
+ */
57
+ head?: string | ((page: { url: URL; request: Request; route: MatchedRoute }) => string | Promise<string>);
58
+ /**
59
+ * What each `load` gets as `context` (the signed-in person, a database handle), made once per
60
+ * request. The same function `createActions({ context })` takes.
61
+ */
62
+ context?: (from: { request: Request; req?: IncomingMessage; c?: unknown }) => object | Promise<object>;
63
+ /** The app's `createActions()`, so a `load` gets an action's answer as `result`. */
64
+ actions?: { result(request: Request | IncomingMessage, setHeader?: (name: string, value: string) => void): unknown };
65
+ }
66
+
67
+ export interface Route {
68
+ /** The component, by its path in the folder without the extension. */
69
+ name: string;
70
+ /** A URLPattern pathname: `/farms/:id`. */
71
+ pattern: string;
72
+ params: string[];
73
+ load: boolean;
74
+ /** The layouts around it, outermost first, by name. */
75
+ layouts: string[];
76
+ }
77
+
78
+ export interface Router {
79
+ /** Node's http: answers a GET or HEAD to a route and resolves true, or resolves false. */
80
+ handle(req: IncomingMessage, res: ServerResponse): Promise<boolean>;
81
+ /** The 404 page, for the end of the app's handlers: inside `app.zb` for a GET or HEAD. */
82
+ notFound(req: IncomingMessage, res: ServerResponse): Promise<void>;
83
+ /** Fetch-style servers: the 404 page as a Response. */
84
+ notFoundResponse(request: Request, extra?: { req?: IncomingMessage; c?: unknown }): Promise<Response>;
85
+ /** For `http.createServer(router.listener)`: a route, or the 404 page. */
86
+ listener(req: IncomingMessage, res: ServerResponse): Promise<void>;
87
+ /** Fetch-style servers: the page's Response, or null when the request isn't a route's. */
88
+ fetch(request: Request, extra?: { req?: IncomingMessage; c?: unknown }): Promise<Response | null>;
89
+ /** The pages, most specific first. */
90
+ routes(): Route[];
91
+ /** The layouts, outermost first (`app.zb` is `/`). */
92
+ layouts(): { name: string; pattern: string; root: boolean }[];
93
+ /** Which page a path goes to, or null. */
94
+ match(pathname: string): { name: string; pattern: string; params: Record<string, string> } | null;
95
+ }
96
+
97
+ export function createRouter(options: RouterOptions): Promise<Router>;
package/src/index.js ADDED
@@ -0,0 +1,367 @@
1
+ // @zubra/router: serve components that say 'use route <path>' as pages.
2
+ //
3
+ // import { createZubra } from '@zubra/server';
4
+ // import { createRouter } from '@zubra/router';
5
+ // const zubra = createZubra({ components: 'components' });
6
+ // const router = await createRouter({ zubra, components: 'components' });
7
+ //
8
+ // router.handle(req, res) // Node's http: true if it answered (a GET or HEAD to a route)
9
+ // router.fetch(request) // fetch-style servers: a Response, or null if not ours
10
+ // router.listener // (req, res) for http.createServer: a route, or 404
11
+ //
12
+ // It is one more handler in the app's own server, like `zubra.handle` and `actions.handle`:
13
+ // the app keeps its order, its static files and its other routes (plan/app-design.md).
14
+ //
15
+ // A route's `load({ params, url, request })` runs on the server before the page renders; what
16
+ // it returns becomes the page's props. A parameter the page declares as a prop is passed too.
17
+ //
18
+ // Layouts wrap the page, outermost first: `app.zb`, then each 'use layout <prefix>' the path is
19
+ // under, the page in the innermost one's default slot. A layout has its own `load`, and one
20
+ // that declares a `route` prop is given `{ path, pattern, params }` (to mark where you are).
21
+ //
22
+ // `load` is given `{ params, url, request, route, context, result }`: `context` is the app's
23
+ // (`createRouter({ context })`, the same function `createActions` takes), `result` an action's
24
+ // answer after a post without JavaScript (`createRouter({ actions })`). Besides props it can
25
+ // return a `title`, `notFound()`, `redirect(to)` or `show(component, props)`.
26
+ import { randomUUID } from 'node:crypto';
27
+ import { existsSync, mkdirSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
28
+ import { dirname, join, relative, resolve, sep } from 'node:path';
29
+ import { pathToFileURL } from 'node:url';
30
+ import { findCompiler } from '@zubra/server';
31
+ import { ANSWER } from './answers.js';
32
+ import { APP, buildTable, fromRoot, matcher, RouteError } from './table.js';
33
+
34
+ export { notFound, redirect, show } from './answers.js';
35
+
36
+ export { RouteError };
37
+
38
+ const SOURCE = /\.zb(?:\.[jt]sx)?$/;
39
+
40
+ /** The component shown in the shell's slot for a 404 or a 500, when the app has one. */
41
+ const ERROR = 'error';
42
+
43
+ let compiler;
44
+ async function compilerModule() {
45
+ if (!compiler) {
46
+ findCompiler();
47
+ compiler = await import('@zubra/compiler');
48
+ }
49
+ return compiler;
50
+ }
51
+
52
+ async function urlPattern() {
53
+ if (globalThis.URLPattern) return globalThis.URLPattern;
54
+ return (await import('urlpattern-polyfill/urlpattern')).URLPattern;
55
+ }
56
+
57
+ /**
58
+ * `zubra`: the app's `createZubra()`, which renders the pages. `components`: the same folder
59
+ * (default `components`). `cacheDir`: where the routes' server halves are written (bare imports
60
+ * resolve from there, so keep it inside the project). `onError(error, request)`: called when a
61
+ * `load` throws; the browser gets a plain 500, never the message. `lang`: the document's
62
+ * language (default `en`). `head`: HTML for every page's `<head>` (fonts, a stylesheet), or a
63
+ * function of `{ url, request, route }` returning it; written as given, so it is the app's own
64
+ * markup, never a visitor's text. `context({ request, req })`: what each `load` gets as
65
+ * `context` (the signed-in person, a database handle), made once per request; give it the
66
+ * function `createActions` has. `actions`: the app's `createActions()`, so `load` gets an
67
+ * action's answer as `result`.
68
+ */
69
+ export async function createRouter({
70
+ zubra,
71
+ components = 'components',
72
+ cacheDir = join(process.cwd(), 'node_modules', '.cache', 'zubra-router'),
73
+ onError = (error) => console.error(error),
74
+ lang = 'en',
75
+ head = '',
76
+ context,
77
+ actions,
78
+ } = {}) {
79
+ if (!zubra?.page) throw new RouteError('createRouter({ zubra }) needs the app\'s createZubra() to render pages');
80
+ const root = resolve(components);
81
+ if (!existsSync(root)) throw new RouteError(`no components folder at ${root}`);
82
+ const { request: compile, sources: read } = await compilerModule();
83
+ mkdirSync(cacheDir, { recursive: true });
84
+
85
+ // Every component that is a route or a layout: what its interface says, and its server half.
86
+ const entries = [];
87
+ const halves = new Map();
88
+ for (const path of sourcesUnder(root)) {
89
+ const described = compile({ emit: 'interface', path, files: read(path) });
90
+ if (!described.ok) throw new Error(described.error);
91
+ const info = JSON.parse(described.output);
92
+ const name = relative(root, path).split(sep).join('/').replace(SOURCE, '');
93
+ if (!info.route && name !== APP) continue;
94
+ const file = relative(process.cwd(), path);
95
+ entries.push({ name, file, props: info.props.map((prop) => prop.name), slots: info.slots, route: info.route });
96
+ if (info.route?.load) halves.set(name, path);
97
+ }
98
+ const { pages, layouts } = buildTable(entries);
99
+ // The props a component declares: only those are taken from what the loads return.
100
+ const declaredBy = new Map(entries.map((entry) => [entry.name, new Set(entry.props)]));
101
+ const propsOf = (name) => {
102
+ if (!declaredBy.has(name)) declaredBy.set(name, new Set(zubra.describe(name).props.map((prop) => prop.name)));
103
+ return declaredBy.get(name);
104
+ };
105
+ const isRoot = new Map(layouts.map((layout) => [layout.name, layout.root]));
106
+ // Errors render inside the shell, with `error.zb` in its slot when the app has one.
107
+ const hasShell = layouts.some((layout) => layout.name === APP);
108
+ const hasErrorPage = zubra.names.includes(ERROR);
109
+
110
+ // The server halves of those with a `load`, written to the cache and imported. Their relative
111
+ // imports point back at the source; each is written beside its place and renamed in, so a
112
+ // second process starting at the same moment never imports half a file.
113
+ const loads = new Map();
114
+ for (const [name, path] of halves) {
115
+ const response = compile({ emit: 'server', path, files: read(path) });
116
+ if (!response.ok) throw new Error(response.error);
117
+ const module = join(cacheDir, `${name.split('/').join('__')}.route.mjs`);
118
+ const writing = `${module}.${process.pid}.${randomUUID()}.tmp`;
119
+ writeFileSync(writing, rewriteImports(response.output, (specifier) => pathToFileURL(resolve(dirname(path), specifier)).href));
120
+ renameSync(writing, module);
121
+ loads.set(name, (await import(`${pathToFileURL(module).href}?t=${Date.now()}`)).load);
122
+ }
123
+
124
+ const match = matcher(pages, await urlPattern());
125
+
126
+ /** A Response for a GET or HEAD to a route, or null. `extra` (`{ req }`, `{ c }`) goes to `context`. */
127
+ async function respond(request, extra = {}, { unknown = false } = {}) {
128
+ if (request.method !== 'GET' && request.method !== 'HEAD') return null;
129
+ const url = new URL(request.url);
130
+ const found = unknown ? null : match(url.pathname);
131
+ if (!found && !unknown) return null;
132
+ const { page = null, params = {} } = found ?? {};
133
+ const route = { path: url.pathname, pattern: page?.pattern ?? null, params };
134
+ const headers = new Headers();
135
+ const fail = (error) => {
136
+ onError(error, request);
137
+ return errorPage(500);
138
+ };
139
+ const document = async (body, title) => {
140
+ const extraHead = typeof head === 'function' ? await head({ url, request, route }) : head;
141
+ const titled = title == null ? '' : `<title>${escapeText(title)}</title>`;
142
+ return `<!doctype html>\n<html lang="${escapeAttribute(lang)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">${titled}${extraHead ?? ''}</head><body>${body}</body></html>`;
143
+ };
144
+
145
+ // A 404 or a 500, inside the app's shell where there is one: `error.zb` in the shell's slot
146
+ // (or a heading), and `{ status }` as the shell's `error` prop if it declares one. Never
147
+ // the error's message. Plain text when there is no shell, or the shell itself can't render.
148
+ const errorPage = async (status) => {
149
+ const plain = () => text(status, status === 404 ? 'Not found' : 'Internal error', headers);
150
+ if (!hasShell || threw.has(APP)) return plain();
151
+ try {
152
+ const answer = loads.has(APP) ? await run(APP) : {};
153
+ if (answer[ANSWER]) return plain();
154
+ const error = { status };
155
+ const give = (name, data) => {
156
+ const declared = propsOf(name);
157
+ const props = {};
158
+ if (declared.has('route')) props.route = route;
159
+ for (const [key, value] of Object.entries(data)) if (declared.has(key)) props[key] = value;
160
+ if (declared.has('error')) props.error = error;
161
+ return props;
162
+ };
163
+ const rendering = zubra.page();
164
+ const words = status === 404 ? 'Page not found' : 'Something went wrong';
165
+ const inside = hasErrorPage ? rendering.render(ERROR, give(ERROR, { status })) : `<h1>${words}</h1>`;
166
+ const html = rendering.finish(await document(rendering.render(APP, give(APP, answer), { default: inside }), words));
167
+ headers.set('content-type', 'text/html; charset=utf-8');
168
+ return new Response(request.method === 'HEAD' ? null : html, { status, headers });
169
+ } catch (failure) {
170
+ onError(failure, request);
171
+ return plain();
172
+ }
173
+ };
174
+
175
+ // What every `load` of this request is given. The app's context is made once, and so is the
176
+ // read of an action's answer (reading it clears its cookie), and only if a `load` runs.
177
+ let given;
178
+ const loadArguments = async () => {
179
+ if (!given) {
180
+ const result = actions ? actions.result(extra.req ?? request, (name, value) => headers.append(name, value)) : null;
181
+ given = { params, url, request, route, context: (context ? await context({ request, ...extra }) : null) ?? {}, result };
182
+ }
183
+ return given;
184
+ };
185
+ const loaded = new Map();
186
+ const threw = new Set();
187
+ const run = async (name) => {
188
+ if (!loaded.has(name)) {
189
+ try {
190
+ loaded.set(name, (await loads.get(name)(await loadArguments())) ?? {});
191
+ } catch (error) {
192
+ threw.add(name);
193
+ throw error;
194
+ }
195
+ }
196
+ return loaded.get(name);
197
+ };
198
+ if (!page) return errorPage(404);
199
+
200
+ // The layouts, outermost first, then the page. Each `load` runs in that order, and what the
201
+ // ones outside returned reaches the ones inside as props they declare. A `show()` puts
202
+ // another component in the place of the one that answered, and the walk starts again with
203
+ // it (the loads that already ran aren't run twice).
204
+ let chain = page.layouts;
205
+ let leaf = { name: page.name };
206
+ let status = 200;
207
+ let parts;
208
+ let title;
209
+ try {
210
+ walk: for (let walks = 0; ; walks++) {
211
+ // Each show() from a layout leaves fewer layouts, so this can't go round for long.
212
+ if (walks > page.around.length + 2) throw new RouteError(`${route.pattern}: show() kept being answered with another show()`);
213
+ parts = [];
214
+ title = undefined;
215
+ const data = {};
216
+ const names = [...chain, leaf.name];
217
+ for (let index = 0; index < names.length; index++) {
218
+ const name = names[index];
219
+ const last = index === names.length - 1;
220
+ const answer = last && leaf.props ? leaf.props : loads.has(name) ? await run(name) : {};
221
+ switch (answer[ANSWER]) {
222
+ case 'notFound':
223
+ return errorPage(404);
224
+ case 'redirect':
225
+ headers.set('location', answer.location);
226
+ return new Response(null, { status: answer.status, headers });
227
+ case 'show':
228
+ // In place of a layout: inside the layouts over it, as if it weren't there (so a
229
+ // `root` layout that turns someone away shows its notice in the app's shell).
230
+ if (!last) chain = fromRoot(page.around.slice(0, page.around.indexOf(name)).map((each) => ({ name: each, root: isRoot.get(each) }))).map((each) => each.name);
231
+ leaf = { name: answer.name, props: { ...answer.props } };
232
+ status = answer.status;
233
+ continue walk;
234
+ }
235
+ Object.assign(data, answer);
236
+ if (answer.title != null) title = String(answer.title);
237
+ const declared = propsOf(name);
238
+ const props = {};
239
+ if (declared.has('route')) props.route = route;
240
+ for (const [key, value] of Object.entries(params)) if (declared.has(key)) props[key] = value;
241
+ // Props the component declares; anything else the loads return doesn't reach it.
242
+ for (const [key, value] of Object.entries(data)) if (declared.has(key)) props[key] = value;
243
+ parts.push({ name, props, last });
244
+ }
245
+ break;
246
+ }
247
+ } catch (error) {
248
+ return fail(error);
249
+ }
250
+
251
+ let html;
252
+ try {
253
+ const rendering = zubra.page();
254
+ // Inside out: the page, then each layout with what's inside it in its default slot.
255
+ let body = '';
256
+ for (const { name, props, last } of parts.reverse()) {
257
+ body = last ? rendering.render(name, props) : rendering.render(name, props, { default: body });
258
+ }
259
+ html = rendering.finish(await document(body, title));
260
+ } catch (error) {
261
+ return fail(error);
262
+ }
263
+ headers.set('content-type', 'text/html; charset=utf-8');
264
+ return new Response(request.method === 'HEAD' ? null : html, { status, headers });
265
+ }
266
+
267
+ /** Node's http: answers a route and returns true, or returns false. */
268
+ async function handle(req, res) {
269
+ if (req.method !== 'GET' && req.method !== 'HEAD') return false;
270
+ let request;
271
+ try { request = toRequest(req); } catch { res.writeHead(400, { 'content-type': 'text/plain' }).end('Bad request'); return true; }
272
+ const response = await respond(request, { req });
273
+ if (!response) return false;
274
+ await send(response, res);
275
+ return true;
276
+ }
277
+
278
+ /**
279
+ * The 404 page, for the end of the app's handlers: inside `app.zb` (with `error.zb` in its
280
+ * slot, if there is one) for a GET or HEAD, plain text otherwise.
281
+ */
282
+ async function notFound(req, res) {
283
+ let response = null;
284
+ try { response = await respond(toRequest(req), { req }, { unknown: true }); } catch {}
285
+ if (response) await send(response, res);
286
+ else res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }).end('Not found');
287
+ }
288
+
289
+ /** For `http.createServer(router.listener)`: a route, or the 404 page. */
290
+ async function listener(req, res) {
291
+ if (!(await handle(req, res))) await notFound(req, res);
292
+ }
293
+
294
+ return {
295
+ handle,
296
+ listener,
297
+ notFound,
298
+ fetch: (request, extra) => respond(request, extra),
299
+ /** Fetch-style servers: the 404 page as a Response (see `notFound`). */
300
+ notFoundResponse: async (request, extra) => (await respond(request, extra, { unknown: true })) ?? text(404, 'Not found'),
301
+ /** The pages, most specific first: `[{ name, pattern, params, load }]`. */
302
+ routes: () => pages.map(({ name, pattern, params, load, layouts }) => ({ name, pattern, params, load, layouts })),
303
+ /** The layouts, outermost first: `[{ name, pattern, root }]` (`app.zb` is `/`). */
304
+ layouts: () => layouts.map(({ name, pattern, root }) => ({ name, pattern, root })),
305
+ /** Which page a path goes to: `{ name, pattern, params }`, or null. */
306
+ match: (pathname) => {
307
+ const found = match(pathname);
308
+ return found && { name: found.page.name, pattern: found.page.pattern, params: found.params };
309
+ },
310
+ };
311
+ }
312
+
313
+ const escapeAttribute = (value) => String(value).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;');
314
+
315
+ const escapeText = (value) => String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;');
316
+
317
+ function text(status, body, headers = new Headers()) {
318
+ headers.set('content-type', 'text/plain; charset=utf-8');
319
+ return new Response(body, { status, headers });
320
+ }
321
+
322
+ function sourcesUnder(dir, out = []) {
323
+ for (const entry of readdirSync(dir).sort()) {
324
+ const path = join(dir, entry);
325
+ if (statSync(path).isDirectory()) {
326
+ if (entry !== 'node_modules' && !entry.startsWith('.')) sourcesUnder(path, out);
327
+ } else if (SOURCE.test(entry)) out.push(path);
328
+ }
329
+ return out;
330
+ }
331
+
332
+ /** Rewrite each relative import (`'./x'`, `'../x'`) with `to(specifier)`. */
333
+ function rewriteImports(code, to) {
334
+ return code.replace(/(\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.{1,2}\/[^'"]+)\2/g, (_, keyword, quote, specifier) => `${keyword}${quote}${to(specifier)}${quote}`);
335
+ }
336
+
337
+ // A Host header is a host and an optional port. Anything else (a path, a query, an empty one)
338
+ // would move the URL's path away from the request's: `Host: site/admin` with `GET /public` would
339
+ // read as `/admin/public`, past a proxy that allowed `/public`. That's refused (the callers answer
340
+ // 400); a request without one (HTTP/1.0) is for localhost.
341
+ const HOST = /^(?:[\w.-]+|\[[\da-fA-F:.]+\])(?::\d{1,5})?$/;
342
+ const hostOf = (req) => {
343
+ const { host } = req.headers;
344
+ if (host === undefined) return 'localhost';
345
+ if (!HOST.test(host)) throw new TypeError(`not a host: ${JSON.stringify(host)}`);
346
+ return host;
347
+ };
348
+
349
+ /** A Node GET or HEAD request as a fetch Request. */
350
+ function toRequest(req) {
351
+ const host = hostOf(req);
352
+ const protocol = req.socket?.encrypted ? 'https' : 'http';
353
+ const headers = new Headers();
354
+ for (const [name, value] of Object.entries(req.headers)) {
355
+ if (Array.isArray(value)) value.forEach((each) => headers.append(name, each));
356
+ else if (value !== undefined) headers.set(name, value);
357
+ }
358
+ return new Request(`${protocol}://${host}${req.url}`, { method: req.method, headers });
359
+ }
360
+
361
+ async function send(response, res) {
362
+ res.statusCode = response.status;
363
+ for (const [name, value] of response.headers) if (name !== 'set-cookie') res.setHeader(name, value);
364
+ const cookies = response.headers.getSetCookie();
365
+ if (cookies.length) res.setHeader('set-cookie', cookies);
366
+ res.end(response.body ? Buffer.from(await response.arrayBuffer()) : undefined);
367
+ }
package/src/table.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ export const ROUTES: 'routes';
2
+ export const APP: 'app';
3
+
4
+ export class RouteError extends Error {}
5
+
6
+ /** The path a component's place in `routes/` gives it (`routes/farms/[id]` → `/farms/:id`), or null. */
7
+ export function folderPattern(name: string, kind?: 'page' | 'layout'): string | null;
8
+ /** A pathname pattern's named parameters, in order. */
9
+ export function patternParams(pattern: string): string[];
10
+
11
+ export interface TableEntry {
12
+ name: string;
13
+ file?: string;
14
+ props?: string[];
15
+ slots?: string[];
16
+ route: null | { kind: 'page' | 'layout'; pattern: string | null; params?: string[]; root?: boolean; load?: boolean; reads?: string[] | null };
17
+ }
18
+
19
+ export interface TablePage { name: string; file: string; pattern: string; params: string[]; load: boolean; root: boolean; layouts?: string[]; around?: string[] }
20
+
21
+ export function buildTable(entries: TableEntry[]): { pages: TablePage[]; layouts: TablePage[] };
22
+ /** The layouts around a page's pattern, outermost first, from the innermost `root` one. */
23
+ export function layoutsFor<L extends { pattern: string; root: boolean }>(pattern: string, layouts: L[]): L[];
24
+ /** Every layout over a pattern, `root` ones or not. */
25
+ export function layoutsAround<L extends { pattern: string; root: boolean }>(pattern: string, layouts: L[]): L[];
26
+ /** A list of layouts from its innermost `root` one. */
27
+ export function fromRoot<L extends { root: boolean }>(around: L[]): L[];
28
+ export function matcher(pages: TablePage[], URLPattern: unknown): (pathname: string) => { page: TablePage; params: Record<string, string> } | null;
package/src/table.js ADDED
@@ -0,0 +1,167 @@
1
+ // The route table: which component answers which path. Pure (no files, no compiler), so the
2
+ // rules are tested on their own and an edge entry can build the same table later.
3
+ //
4
+ // A page says where it lives with 'use route /farms/:id', or, in a `routes/` folder, with a
5
+ // bare 'use route' and its place in the folder (`routes/farms/[id].zb` is `/farms/:id`).
6
+ // Both make the same table. Matching is URLPattern's pathname syntax.
7
+ //
8
+ // A layout wraps the pages under its prefix, the page in its default <zb-slot>: `app.zb` wraps
9
+ // every page, 'use layout /farm' (or `routes/farm/layout.zb` with a bare 'use layout') wraps
10
+ // /farm and everything below it, and they nest. 'use layout /farm root' starts over there:
11
+ // its pages aren't inside `app.zb` or any layout above it.
12
+
13
+ /** The component that is the app's shell, the outermost layout, when there is one. */
14
+ export const APP = 'app';
15
+
16
+ /** The folder `routes/` pages live in, relative to the components folder. */
17
+ export const ROUTES = 'routes';
18
+
19
+ /**
20
+ * The path a component's place in `routes/` gives it, or null outside the folder:
21
+ * `routes/index` → `/`, `routes/farms/[id]` → `/farms/:id`, `routes/docs/[...path]` → `/docs/:path*`.
22
+ */
23
+ export function folderPattern(name, kind = 'page') {
24
+ const parts = name.split('/');
25
+ if (parts[0] !== ROUTES || parts.length < 2) return null;
26
+ const segments = parts.slice(1);
27
+ // A layout's prefix is its folder (`routes/farm/layout` → `/farm`); any other name isn't one.
28
+ if (kind === 'layout') {
29
+ if (segments.at(-1) !== 'layout') return null;
30
+ segments.pop();
31
+ } else if (segments.at(-1) === 'index') segments.pop();
32
+ const pattern = segments.map((segment) => {
33
+ const rest = /^\[\.\.\.([A-Za-z_$][\w$]*)\]$/.exec(segment);
34
+ if (rest) return `:${rest[1]}*`;
35
+ const param = /^\[([A-Za-z_$][\w$]*)\]$/.exec(segment);
36
+ if (param) return `:${param[1]}`;
37
+ if (/[[\]:*?(){}]/.test(segment)) throw new RouteError(`${name}: a folder or file name in ${ROUTES}/ is plain text or one [param] (\`[id]\`, \`[...path]\`), not \`${segment}\``);
38
+ return segment;
39
+ });
40
+ return `/${pattern.join('/')}`;
41
+ }
42
+
43
+ /** The named parameters of a pathname pattern, in order (`:id`, `:path*`). */
44
+ export function patternParams(pattern) {
45
+ return [...pattern.replace(/\\./g, '').matchAll(/:([A-Za-z_$][\w$]*)/g)].map((match) => match[1]);
46
+ }
47
+
48
+ export class RouteError extends Error {
49
+ constructor(message) {
50
+ super(`@zubra/router: ${message}`);
51
+ this.name = 'RouteError';
52
+ }
53
+ }
54
+
55
+ /**
56
+ * The table from what each component's interface says.
57
+ *
58
+ * `entries`: `[{ name, file, props: ['id', …], route: { kind, pattern, params, root, load, reads } }]`
59
+ * for every component that is a route or a layout (`file` is for messages).
60
+ * Returns `{ pages: [{ name, pattern, params, load }], layouts: [...] }`, pages ordered so the
61
+ * most specific pattern is tried first.
62
+ */
63
+ export function buildTable(entries) {
64
+ const pages = [];
65
+ const layouts = [];
66
+ for (const entry of entries) {
67
+ const { name, file = name, props = [], slots } = entry;
68
+ // `app.zb` is the shell whether or not it says so; it can say 'use layout /' to have a `load`.
69
+ const route = entry.route ?? (name === APP ? { kind: 'layout', pattern: '/' } : null);
70
+ if (!route) continue;
71
+ if (name === APP && (route.kind !== 'layout' || (route.pattern ?? '/') !== '/')) {
72
+ throw new RouteError(`${file} is the app's shell, the layout around every page: it can say 'use layout /' (to export \`load\`), not 'use ${[route.kind === 'layout' ? 'layout' : 'route', route.pattern].filter(Boolean).join(' ')}'`);
73
+ }
74
+ const layout = route.kind === 'layout';
75
+ const word = layout ? 'layout' : 'route';
76
+ const fromFolder = folderPattern(name, route.kind);
77
+ let pattern = route.pattern ?? (name === APP ? '/' : null);
78
+ if (layout && slots && !slots.includes('default')) {
79
+ throw new RouteError(`${file} is a layout with nowhere for its page: put \`<zb-slot></zb-slot>\` where the page goes`);
80
+ }
81
+ if (pattern == null) {
82
+ if (fromFolder == null) {
83
+ throw new RouteError(layout
84
+ ? `${file} says 'use layout' with no prefix, and isn't a layout.zb in a ${ROUTES}/ folder: name its prefix ('use layout /farm'), or make it ${ROUTES}/farm/layout.zb`
85
+ : `${file} says 'use route' with no path, and isn't in a ${ROUTES}/ folder: name its path ('use route /farms/:id'), or move it to ${ROUTES}/`);
86
+ }
87
+ pattern = fromFolder;
88
+ // The compiler checked a written path's parameters; a folder's are checked here.
89
+ for (const param of patternParams(pattern)) {
90
+ const read = props.includes(param) || (route.load && (route.reads == null || route.reads.includes(param)));
91
+ if (!read) throw new RouteError(`${file} is ${pattern}, whose parameter \`${param}\` neither \`load\` nor a prop reads`);
92
+ }
93
+ } else if (fromFolder != null && fromFolder !== pattern) {
94
+ throw new RouteError(`${file} says 'use ${word} ${pattern}', but its place in ${ROUTES}/ makes it ${fromFolder}: drop the path from the directive, or move the file`);
95
+ }
96
+ (layout ? layouts : pages).push({ name, file, pattern, params: patternParams(pattern), load: Boolean(route.load), root: Boolean(route.root) });
97
+ }
98
+ for (const list of [pages, layouts]) {
99
+ const seen = new Map();
100
+ for (const entry of list) {
101
+ const other = seen.get(entry.pattern);
102
+ if (other) throw new RouteError(`${other.file} and ${entry.file} are both ${list === pages ? 'routes' : 'layouts'} for ${entry.pattern}`);
103
+ seen.set(entry.pattern, entry);
104
+ }
105
+ }
106
+ pages.sort((a, b) => compareSpecificity(a.pattern, b.pattern));
107
+ layouts.sort((a, b) => segmentsOf(a.pattern).length - segmentsOf(b.pattern).length);
108
+ for (const page of pages) {
109
+ // `around`: every layout over the page's path; `layouts`: those it is rendered inside.
110
+ page.around = layoutsAround(page.pattern, layouts).map((layout) => layout.name);
111
+ page.layouts = layoutsFor(page.pattern, layouts).map((layout) => layout.name);
112
+ }
113
+ return { pages, layouts };
114
+ }
115
+
116
+ const segmentsOf = (pattern) => pattern.split('/').filter(Boolean);
117
+
118
+ /**
119
+ * The layouts around a page, outermost first: every layout whose prefix is the start of the
120
+ * page's path, segment for segment (`/farm` is around `/farm` and `/farm/stock`, not
121
+ * `/farmers`), from the innermost `root` one inwards.
122
+ */
123
+ export function layoutsFor(pattern, layouts) {
124
+ return fromRoot(layoutsAround(pattern, layouts));
125
+ }
126
+
127
+ /** Every layout whose prefix is the start of the path, outermost first, `root` ones or not. */
128
+ export function layoutsAround(pattern, layouts) {
129
+ const path = segmentsOf(pattern);
130
+ return layouts
131
+ .filter((layout) => segmentsOf(layout.pattern).every((segment, index) => path[index] === segment))
132
+ .sort((a, b) => segmentsOf(a.pattern).length - segmentsOf(b.pattern).length);
133
+ }
134
+
135
+ /** A list of layouts, outermost first, from its innermost `root` one. */
136
+ export function fromRoot(around) {
137
+ const from = around.findLastIndex((layout) => layout.root);
138
+ return from > 0 ? around.slice(from) : around;
139
+ }
140
+
141
+ // Static segments before parameters before wildcards, segment by segment; then longer first.
142
+ const rank = (segment) => (segment.includes('*') ? 2 : segment.includes(':') ? 1 : 0);
143
+ function compareSpecificity(a, b) {
144
+ const left = a.split('/');
145
+ const right = b.split('/');
146
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
147
+ const difference = rank(left[i]) - rank(right[i]);
148
+ if (difference) return difference;
149
+ }
150
+ return right.length - left.length || (a < b ? -1 : a > b ? 1 : 0);
151
+ }
152
+
153
+ /** A matcher over the pages: `match(pathname)` → `{ page, params }` or null. */
154
+ export function matcher(pages, URLPatternClass) {
155
+ const compiled = pages.map((page) => ({ page, pattern: new URLPatternClass({ pathname: page.pattern }) }));
156
+ return (pathname) => {
157
+ for (const { page, pattern } of compiled) {
158
+ const found = pattern.exec({ pathname });
159
+ if (found) {
160
+ const params = {};
161
+ for (const [key, value] of Object.entries(found.pathname.groups)) if (value !== undefined) params[key] = value;
162
+ return { page, params };
163
+ }
164
+ }
165
+ return null;
166
+ };
167
+ }