@zubra/router 5.17.0 → 5.19.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zubra/router",
3
- "version": "5.17.0",
3
+ "version": "5.19.0",
4
4
  "description": "Serve Zubra components that say 'use route <path>' as pages, with a server-only load, for apps with no host framework.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -22,8 +22,8 @@
22
22
  "urlpattern-polyfill": "10.1.0"
23
23
  },
24
24
  "peerDependencies": {
25
- "@zubra/compiler": "^5.17.0",
26
- "@zubra/server": "^5.17.0"
25
+ "@zubra/compiler": "^5.19.0",
26
+ "@zubra/server": "^5.19.0"
27
27
  },
28
28
  "devDependencies": {
29
29
  "@zubra/compiler": "file:../compiler",
package/src/answers.js CHANGED
@@ -5,11 +5,17 @@ export const ANSWER = Symbol.for('@zubra/router.answer');
5
5
  /** `return notFound()`: the path has nothing behind it (no such farm). The response is a 404. */
6
6
  export const notFound = () => ({ [ANSWER]: 'notFound' });
7
7
 
8
- /** `return redirect('/cart')`: send the browser elsewhere (303 unless `status` says otherwise). */
9
- export const redirect = (location, status = 303) => {
8
+ /**
9
+ * `return redirect('/cart')`: send the browser elsewhere (303 unless `status` says otherwise).
10
+ * Only on this site: another site needs `redirect(url, { external: true })` (or
11
+ * `redirect(url, 302, { external: true })`), so a `next` taken from the query string can't send
12
+ * a visitor off it.
13
+ */
14
+ export const redirect = (location, status = 303, { external = false } = {}) => {
15
+ if (status && typeof status === 'object') ({ status = 303, external = false } = status);
10
16
  if (typeof location !== 'string' || !location) throw new TypeError("@zubra/router: redirect() needs where to go: redirect('/cart')");
11
17
  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 };
18
+ return { [ANSWER]: 'redirect', location, status, external: Boolean(external) };
13
19
  };
14
20
 
15
21
  /**
package/src/index.js CHANGED
@@ -29,7 +29,7 @@ import { dirname, join, relative, resolve, sep } from 'node:path';
29
29
  import { pathToFileURL } from 'node:url';
30
30
  import { findCompiler } from '@zubra/server';
31
31
  import { ANSWER } from './answers.js';
32
- import { APP, buildTable, fromRoot, matcher, RouteError } from './table.js';
32
+ import { APP, buildTable, fromRoot, layoutMatcher, matcher, RouteError } from './table.js';
33
33
 
34
34
  export { notFound, redirect, show } from './answers.js';
35
35
 
@@ -114,14 +114,17 @@ export async function createRouter({
114
114
  for (const [name, path] of halves) {
115
115
  const response = compile({ emit: 'server', path, files: read(path) });
116
116
  if (!response.ok) throw new Error(response.error);
117
- const module = join(cacheDir, `${name.split('/').join('__')}.route.mjs`);
117
+ // One file name per component name, with no two names sharing one (`a/b` and `a__b` did).
118
+ const module = join(cacheDir, `${name.replace(/_/g, '_u').replace(/\//g, '_s')}.route.mjs`);
118
119
  const writing = `${module}.${process.pid}.${randomUUID()}.tmp`;
119
120
  writeFileSync(writing, rewriteImports(response.output, (specifier) => pathToFileURL(resolve(dirname(path), specifier)).href));
120
121
  renameSync(writing, module);
121
122
  loads.set(name, (await import(`${pathToFileURL(module).href}?t=${Date.now()}`)).load);
122
123
  }
123
124
 
124
- const match = matcher(pages, await urlPattern());
125
+ const URLPatternClass = await urlPattern();
126
+ const match = matcher(pages, URLPatternClass);
127
+ const layoutsOver = layoutMatcher(layouts, URLPatternClass);
125
128
 
126
129
  /** A Response for a GET or HEAD to a route, or null. `extra` (`{ req }`, `{ c }`) goes to `context`. */
127
130
  async function respond(request, extra = {}, { unknown = false } = {}) {
@@ -129,7 +132,11 @@ export async function createRouter({
129
132
  const url = new URL(request.url);
130
133
  const found = unknown ? null : match(url.pathname);
131
134
  if (!found && !unknown) return null;
132
- const { page = null, params = {} } = found ?? {};
135
+ const { page = null, params: pageParams = {} } = found ?? {};
136
+ // The layouts over this path, matched against the path itself (`layoutMatcher`), and their
137
+ // parameters, so a layout's `load` reads its own (`params.org`) whatever the page calls it.
138
+ const over = page ? layoutsOver(url.pathname) : [];
139
+ const params = Object.assign({}, ...over.map((each) => each.params), pageParams);
133
140
  const route = { path: url.pathname, pattern: page?.pattern ?? null, params };
134
141
  const headers = new Headers();
135
142
  const fail = (error) => {
@@ -177,7 +184,9 @@ export async function createRouter({
177
184
  let given;
178
185
  const loadArguments = async () => {
179
186
  if (!given) {
180
- const result = actions ? actions.result(extra.req ?? request, (name, value) => headers.append(name, value)) : null;
187
+ // A HEAD (a prefetch, a link checker) doesn't use up an action's one-use answer: the
188
+ // GET that follows still shows it.
189
+ const result = actions && request.method !== 'HEAD' ? actions.result(extra.req ?? request, (name, value) => headers.append(name, value)) : null;
181
190
  given = { params, url, request, route, context: (context ? await context({ request, ...extra }) : null) ?? {}, result };
182
191
  }
183
192
  return given;
@@ -201,7 +210,13 @@ export async function createRouter({
201
210
  // ones outside returned reaches the ones inside as props they declare. A `show()` puts
202
211
  // another component in the place of the one that answered, and the walk starts again with
203
212
  // it (the loads that already ran aren't run twice).
204
- let chain = page.layouts;
213
+ //
214
+ // Every layout over the path runs its `load`, a `root` layout's outer ones and `app.zb`'s
215
+ // included, so an outer check guards a root section too; only those from the innermost
216
+ // `root` one are rendered.
217
+ const around = over.map(({ layout }) => layout.name);
218
+ let rendered = new Set(fromRoot(over.map(({ layout }) => layout)).map((layout) => layout.name));
219
+ let chain = around;
205
220
  let leaf = { name: page.name };
206
221
  let status = 200;
207
222
  let parts;
@@ -209,7 +224,7 @@ export async function createRouter({
209
224
  try {
210
225
  walk: for (let walks = 0; ; walks++) {
211
226
  // 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()`);
227
+ if (walks > around.length + 2) throw new RouteError(`${route.pattern}: show() kept being answered with another show()`);
213
228
  parts = [];
214
229
  title = undefined;
215
230
  const data = {};
@@ -222,12 +237,15 @@ export async function createRouter({
222
237
  case 'notFound':
223
238
  return errorPage(404);
224
239
  case 'redirect':
225
- headers.set('location', answer.location);
240
+ headers.set('location', checkedLocation(answer, url));
226
241
  return new Response(null, { status: answer.status, headers });
227
242
  case 'show':
228
243
  // In place of a layout: inside the layouts over it, as if it weren't there (so a
229
244
  // `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);
245
+ if (!last) {
246
+ chain = around.slice(0, around.indexOf(name));
247
+ rendered = new Set(fromRoot(chain.map((each) => ({ name: each, root: isRoot.get(each) }))).map((each) => each.name));
248
+ }
231
249
  leaf = { name: answer.name, props: { ...answer.props } };
232
250
  status = answer.status;
233
251
  continue walk;
@@ -240,7 +258,7 @@ export async function createRouter({
240
258
  for (const [key, value] of Object.entries(params)) if (declared.has(key)) props[key] = value;
241
259
  // Props the component declares; anything else the loads return doesn't reach it.
242
260
  for (const [key, value] of Object.entries(data)) if (declared.has(key)) props[key] = value;
243
- parts.push({ name, props, last });
261
+ if (last || rendered.has(name)) parts.push({ name, props, last });
244
262
  }
245
263
  break;
246
264
  }
@@ -261,6 +279,9 @@ export async function createRouter({
261
279
  return fail(error);
262
280
  }
263
281
  headers.set('content-type', 'text/html; charset=utf-8');
282
+ // A page whose loads read the request (the session, an action's answer) is that visitor's:
283
+ // no shared cache keeps it for the next one. The app can say otherwise in its own handler.
284
+ if (given) headers.set('cache-control', 'private, no-store');
264
285
  return new Response(request.method === 'HEAD' ? null : html, { status, headers });
265
286
  }
266
287
 
@@ -334,9 +355,46 @@ function rewriteImports(code, to) {
334
355
  return code.replace(/(\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.{1,2}\/[^'"]+)\2/g, (_, keyword, quote, specifier) => `${keyword}${quote}${to(specifier)}${quote}`);
335
356
  }
336
357
 
337
- /** A Node GET or HEAD request as a fetch Request. */
358
+ /**
359
+ * Where a `redirect()` sends the browser: on this site unless it says `{ external: true }`.
360
+ * A path starting `//` or `/\` is another site to a browser, so it's written with one slash;
361
+ * an absolute URL elsewhere (a `next` from the query string) is refused, and so is any scheme
362
+ * that isn't http(s). `redirect(next)` after a sign-in can't send anyone off the site.
363
+ */
364
+ function checkedLocation({ location, external }, url) {
365
+ if (/^[/\\]/.test(location)) return '/' + location.replace(/^[/\\]+/, '');
366
+ let target;
367
+ try {
368
+ target = new URL(location, url);
369
+ } catch {
370
+ throw new RouteError(`redirect() to ${JSON.stringify(location)}: not a URL`);
371
+ }
372
+ if (!['http:', 'https:'].includes(target.protocol)) throw new RouteError(`redirect() to a ${target.protocol} URL is refused`);
373
+ if (target.origin !== url.origin && !external) throw new RouteError(`redirect() to ${target.origin}, another site: say redirect(to, { external: true }) if that's meant`);
374
+ return target.origin === url.origin ? target.pathname + target.search + target.hash : target.href;
375
+ }
376
+
377
+ // A Host header is a host and an optional port. Anything else (a path, a query, an empty one)
378
+ // would move the URL's path away from the request's: `Host: site/admin` with `GET /public` would
379
+ // read as `/admin/public`, past a proxy that allowed `/public`. That's refused (the callers answer
380
+ // 400); a request without one (HTTP/1.0) is for localhost.
381
+ const HOST = /^(?:[\w.-]+|\[[\da-fA-F:.]+\])(?::\d{1,5})?$/;
382
+ const hostOf = (req) => {
383
+ const { host } = req.headers;
384
+ if (host === undefined) return 'localhost';
385
+ if (!HOST.test(host)) throw new TypeError(`not a host: ${JSON.stringify(host)}`);
386
+ return host;
387
+ };
388
+
389
+ /**
390
+ * A Node GET or HEAD request as a fetch Request. The path routed is `req.url`'s, and nothing
391
+ * else: a target that isn't a path (`http://evil/staff`, `//evil/staff`) would make the URL's
392
+ * path differ from `req.url`, past any guard the app keeps on it. That throws, as a bad Host
393
+ * does, and `handle()` answers 400.
394
+ */
338
395
  function toRequest(req) {
339
- const host = req.headers.host ?? 'localhost';
396
+ const host = hostOf(req);
397
+ if (typeof req.url !== 'string' || !req.url.startsWith('/') || req.url.startsWith('//')) throw new RouteError('a request target that is not a path');
340
398
  const protocol = req.socket?.encrypted ? 'https' : 'http';
341
399
  const headers = new Headers();
342
400
  for (const [name, value] of Object.entries(req.headers)) {
package/src/table.js CHANGED
@@ -150,10 +150,18 @@ function compareSpecificity(a, b) {
150
150
  return right.length - left.length || (a < b ? -1 : a > b ? 1 : 0);
151
151
  }
152
152
 
153
+ /**
154
+ * A pathname the router answers: one leading slash. The URLPattern polyfill (Node 22 has no
155
+ * global one) reads a leading `//host` as an authority, so `//evil/staff` would match `/staff`
156
+ * and pass any guard the app or a proxy keeps on the raw path.
157
+ */
158
+ const routable = (pathname) => typeof pathname === 'string' && pathname.startsWith('/') && !pathname.startsWith('//');
159
+
153
160
  /** A matcher over the pages: `match(pathname)` → `{ page, params }` or null. */
154
161
  export function matcher(pages, URLPatternClass) {
155
162
  const compiled = pages.map((page) => ({ page, pattern: new URLPatternClass({ pathname: page.pattern }) }));
156
163
  return (pathname) => {
164
+ if (!routable(pathname)) return null;
157
165
  for (const { page, pattern } of compiled) {
158
166
  const found = pattern.exec({ pathname });
159
167
  if (found) {
@@ -165,3 +173,30 @@ export function matcher(pages, URLPatternClass) {
165
173
  return null;
166
174
  };
167
175
  }
176
+
177
+ /**
178
+ * The layouts over a requested path, outermost first: every layout whose prefix matches the
179
+ * start of the path itself. Matched against the path, not compared with the page's pattern
180
+ * text, so a page written `/org/:id(\\d+)/x`, `/org/:orgId/x` or `/docs/:path*` is still inside
181
+ * the layouts of `/org/:org` and `/docs/private` whenever the path is under them: a layout's
182
+ * check guards every page under its prefix, however that page's pattern is spelled.
183
+ * `match(pathname)` → `[{ layout, params }]`.
184
+ */
185
+ export function layoutMatcher(layouts, URLPatternClass) {
186
+ const compiled = layouts.map((layout) => ({
187
+ layout,
188
+ pattern: new URLPatternClass({ pathname: layout.pattern === '/' ? '/*' : `${layout.pattern}{/*}?` }),
189
+ }));
190
+ return (pathname) => {
191
+ if (!routable(pathname)) return [];
192
+ const found = [];
193
+ for (const { layout, pattern } of compiled) {
194
+ const matched = pattern.exec({ pathname });
195
+ if (!matched) continue;
196
+ const params = {};
197
+ for (const [key, value] of Object.entries(matched.pathname.groups)) if (value !== undefined && !/^\d+$/.test(key)) params[key] = value;
198
+ found.push({ layout, params });
199
+ }
200
+ return found.sort((a, b) => segmentsOf(a.layout.pattern).length - segmentsOf(b.layout.pattern).length);
201
+ };
202
+ }