fondu 0.7.0 → 0.8.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/dist/paths.d.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  /**
2
- * `routes/` file → URL pattern (Hono syntax). Shared by the runtime (`createApp`) and the type generator.
2
+ * `routes/` file → its URL patterns (Hono syntax). Shared by the runtime (`createApp`) and the type generator.
3
3
  *
4
4
  * - `index.ts` is its directory: `routes/users/index.ts` → `/users`
5
5
  * - `[id]` → `:id`, `[...path]` → `:path{.+}` (one or more segments)
6
+ * - `[[lang]]`, an optional segment: two patterns, without it and with it (`/about`, `/:lang/about`), as Hono takes
7
+ * an optional param only at the end of a path. One per route.
6
8
  * - `(group)` directories group files without a URL segment
7
9
  * - `_middleware.ts` applies to its directory
8
10
  */
9
- export declare function routePattern(file: string): string;
11
+ export declare function routePatterns(file: string): string[];
10
12
  /** a path inside `routes/` that is a route file: every `.ts` file but `_middleware.ts`, tests and declarations */
11
13
  export declare function isRouteFile(file: string): boolean;
12
14
  /** a path inside `pages/` that is a page: a .tsx, .jsx or .mdx file whose name doesn't start with `_` (`_layout.tsx`) */
package/dist/paths.js CHANGED
@@ -1,18 +1,32 @@
1
1
  /**
2
- * `routes/` file → URL pattern (Hono syntax). Shared by the runtime (`createApp`) and the type generator.
2
+ * `routes/` file → its URL patterns (Hono syntax). Shared by the runtime (`createApp`) and the type generator.
3
3
  *
4
4
  * - `index.ts` is its directory: `routes/users/index.ts` → `/users`
5
5
  * - `[id]` → `:id`, `[...path]` → `:path{.+}` (one or more segments)
6
+ * - `[[lang]]`, an optional segment: two patterns, without it and with it (`/about`, `/:lang/about`), as Hono takes
7
+ * an optional param only at the end of a path. One per route.
6
8
  * - `(group)` directories group files without a URL segment
7
9
  * - `_middleware.ts` applies to its directory
8
10
  */
9
- export function routePattern(file) {
11
+ export function routePatterns(file) {
10
12
  const segments = file
11
13
  .replace(/\.ts$/, '')
12
14
  .split('/')
13
- .filter((s) => s !== '' && s !== 'index' && !/^\(.+\)$/.test(s))
14
- .map((s) => s.replace(/^\[\.\.\.(\w+)\]$/, ':$1{.+}').replace(/^\[(\w+)\]$/, ':$1'));
15
- return '/' + segments.join('/');
15
+ .filter((s) => s !== '' && s !== 'index' && !/^\(.+\)$/.test(s));
16
+ const optional = segments.filter((s) => /^\[\[(?:\.\.\.)?\w+\]\]$/.test(s));
17
+ if (optional.some((s) => s.startsWith('[[...')))
18
+ throw new Error(`fondu: routes/${file}: an optional catch-all isn't a route; index.ts and [...path].ts are`);
19
+ if (optional.length > 1)
20
+ throw new Error(`fondu: routes/${file} has ${optional.length} optional segments; one at most`);
21
+ const pattern = (withOptional) => '/' +
22
+ segments
23
+ .filter((s) => withOptional || !optional.includes(s))
24
+ .map((s) => s
25
+ .replace(/^\[\[(\w+)\]\]$/, ':$1')
26
+ .replace(/^\[\.\.\.(\w+)\]$/, ':$1{.+}')
27
+ .replace(/^\[(\w+)\]$/, ':$1'))
28
+ .join('/');
29
+ return optional.length ? [pattern(false), pattern(true)] : [pattern(true)];
16
30
  }
17
31
  /** a path inside `routes/` that is a route file: every `.ts` file but `_middleware.ts`, tests and declarations */
18
32
  export function isRouteFile(file) {
@@ -5,11 +5,11 @@ import { HTTPException } from 'hono/http-exception';
5
5
  import { NONCE, secureHeaders } from 'hono/secure-headers';
6
6
  import { appendTrailingSlash, trimTrailingSlash } from 'hono/trailing-slash';
7
7
  import { prerender, version } from 'virtual:fondu/assets';
8
- import { isRouteFile, middlewareFor, routePattern } from '../paths.js';
9
8
  import { settings } from './document.js';
10
9
  import { errorResponse } from './errors.js';
11
10
  import { prerenderRoutes } from './prerender.js';
12
11
  import { protocol } from './protocol.js';
12
+ import { routeTable } from './routes.js';
13
13
  import { ValidationError, validationErrorResponse } from './validate.js';
14
14
  /** the default Content Security Policy: scripts of this site or with the request's nonce (the document's) */
15
15
  const CSP = {
@@ -76,32 +76,19 @@ export function createApp(options = {}) {
76
76
  return error.getResponse();
77
77
  return errorResponse(c, error instanceof HTTPException ? error.status : 500, error);
78
78
  });
79
- const modules = import.meta.glob(['/app/routes/**/*.ts', '!/app/routes/**/*.d.ts', '!/app/routes/**/*.{test,spec}.ts'], // test files aren't the app's
80
- { eager: true });
81
- const files = Object.keys(modules).map((k) => k.slice(ROOT.length));
82
- // a _middleware.ts may only set what applies to its directory (`prerender`), without a default export
83
- const rootMiddleware = modules[ROOT + '_middleware.ts']?.default;
79
+ const modules = Object.fromEntries(Object.entries(import.meta.glob(['/app/routes/**/*.ts', '!/app/routes/**/*.d.ts', '!/app/routes/**/*.{test,spec}.ts'], // test files aren't the app's
80
+ { eager: true })).map(([path, mod]) => [path.slice(ROOT.length), mod]));
81
+ // a _middleware.ts may only set what applies to its directory (`prerender`, `params`), without a default export
82
+ const rootMiddleware = modules['_middleware.ts']?.default;
84
83
  if (rootMiddleware)
85
84
  app.use(...chain(rootMiddleware));
86
- const middlewareFiles = files.filter((f) => f.endsWith('/_middleware.ts'));
87
- const routes = files
88
- .filter(isRouteFile)
89
- // static before dynamic before catch-all, segment by segment
90
- .map((file) => ({
91
- file,
92
- pattern: withSlash(routePattern(file), append),
93
- mod: modules[ROOT + file],
94
- }))
95
- .sort((a, b) => rank(a.pattern).localeCompare(rank(b.pattern)));
96
- for (const { file, pattern, mod } of routes) {
97
- const mws = middlewareFor(file, middlewareFiles).flatMap((f) => chain(modules[ROOT + f].default ?? []));
85
+ for (const { file, pattern, path, middleware } of routeTable(modules, append)) {
86
+ const mod = modules[file];
87
+ const mws = middleware.flatMap((f) => chain(modules[f].default ?? []));
98
88
  prerendered.push({
99
89
  file,
100
- pattern,
101
- settings: [
102
- file,
103
- ...middlewareFor(file, [...middlewareFiles, '_middleware.ts']).reverse(),
104
- ].map((f) => modules[ROOT + f]?.prerender),
90
+ pattern: path,
91
+ settings: [file, ...[...middleware].reverse(), '_middleware.ts'].map((f) => modules[f]?.prerender),
105
92
  get: Boolean(mod.loader ?? mod.GET),
106
93
  others: [
107
94
  ...(mod.action || mod.actions || mod.POST ? ['POST'] : []),
@@ -147,9 +134,3 @@ export function createApp(options = {}) {
147
134
  }
148
135
  return app;
149
136
  }
150
- const withSlash = (pattern, append) => append && pattern !== '/' && !pattern.endsWith('}') ? pattern + '/' : pattern;
151
- /** sort key: static segments first, then `:param`, then catch-alls */
152
- const rank = (pattern) => pattern
153
- .split('/')
154
- .map((s) => (s.includes('{') ? '2' : s.startsWith(':') ? '1' : '0') + s)
155
- .join('/');
@@ -0,0 +1,38 @@
1
+ import type { Handler, MiddlewareHandler } from 'hono';
2
+ import type { Prerender } from './prerender.js';
3
+ export type Handlers = Handler | MiddlewareHandler | ReadonlyArray<Handler | MiddlewareHandler>;
4
+ /** `export const params` (a route or a `_middleware.ts`): the values a param of its routes takes */
5
+ export type Params = Record<string, readonly string[]>;
6
+ export interface RouteModule {
7
+ /** `fondu({ prerender: true })`: written as static files at build time (also in a `_middleware.ts`) */
8
+ prerender?: Prerender;
9
+ /** the values its params take, `{ lang: ['de', 'fr'] }`, any other not its URL (also in a `_middleware.ts`) */
10
+ params?: Params;
11
+ /** a `_middleware.ts`: the middleware */
12
+ default?: Handlers;
13
+ loader?: Handlers;
14
+ action?: Handlers;
15
+ actions?: Record<string, Handlers>;
16
+ GET?: Handlers;
17
+ POST?: Handlers;
18
+ PUT?: Handlers;
19
+ PATCH?: Handlers;
20
+ DELETE?: Handlers;
21
+ OPTIONS?: Handlers;
22
+ }
23
+ export interface Route {
24
+ file: string;
25
+ /** what Hono matches: `/:lang{(?:de|fr)}/about` */
26
+ pattern: string;
27
+ /** the URL pattern of fondu.gen.d.ts and `href()`: `/:lang/about` */
28
+ path: string;
29
+ /** its directories' `_middleware.ts` files, outermost first (the root's applies to every request: not listed) */
30
+ middleware: string[];
31
+ }
32
+ /**
33
+ * The routes of `app/routes/` (`modules`: file inside routes/ → its module), in the order Hono gets them: segment
34
+ * by segment, static before a param with listed values, before any param, before a catch-all. Throws, at startup,
35
+ * on what would answer the wrong way: two files for the same URLs (one would never answer, or answer without the
36
+ * other's middleware), `params` that no route takes or that aren't single segments.
37
+ */
38
+ export declare function routeTable(modules: Record<string, RouteModule>, append: boolean): Route[];
@@ -0,0 +1,80 @@
1
+ import { isRouteFile, middlewareFor, routePatterns } from '../paths.js';
2
+ /** a value of `params`: a URL segment of unreserved characters, matched as it is (Hono decodes the path first) */
3
+ const SEGMENT = /^[\w.~-]+$/;
4
+ /**
5
+ * The routes of `app/routes/` (`modules`: file inside routes/ → its module), in the order Hono gets them: segment
6
+ * by segment, static before a param with listed values, before any param, before a catch-all. Throws, at startup,
7
+ * on what would answer the wrong way: two files for the same URLs (one would never answer, or answer without the
8
+ * other's middleware), `params` that no route takes or that aren't single segments.
9
+ */
10
+ export function routeTable(modules, append) {
11
+ const files = Object.keys(modules);
12
+ const middlewareFiles = files.filter((f) => f.endsWith('/_middleware.ts'));
13
+ const used = new Set(); // `${file}:${name}`: a `params` entry that applies to a route
14
+ const routes = [];
15
+ for (const file of files.filter(isRouteFile)) {
16
+ // the values of each param: the root's _middleware.ts, its directories', its own; the nearest counts
17
+ const values = new Map();
18
+ for (const from of [...middlewareFor(file, [...middlewareFiles, '_middleware.ts']), file])
19
+ for (const [name, list] of Object.entries(paramsOf(from, modules[from])))
20
+ values.set(name, { list, from });
21
+ const paths = routePatterns(file)
22
+ .map((path) => {
23
+ let empty = false;
24
+ const pattern = path.replace(/:(\w+)(\{[^}]*\})?/g, (param, name, regex) => {
25
+ const listed = values.get(name);
26
+ if (!listed)
27
+ return param;
28
+ used.add(`${listed.from}:${name}`);
29
+ if (regex)
30
+ throw new Error(`fondu: routes/${listed.from}: params.${name} lists the values of one segment, and routes/${file} has [...${name}]`);
31
+ if (listed.list.length === 0)
32
+ empty = true;
33
+ return `:${name}{(?:${listed.list.map((v) => v.replaceAll('.', '\\.')).join('|')})}`;
34
+ });
35
+ return empty ? null : { path: withSlash(path, append), pattern: withSlash(pattern, append) };
36
+ })
37
+ .filter((p) => p !== null);
38
+ if (!paths.length)
39
+ throw new Error(`fondu: routes/${file} has no URL: a param of it lists no values (params)`);
40
+ const middleware = middlewareFor(file, middlewareFiles);
41
+ for (const { path, pattern } of paths)
42
+ routes.push({ file, path, pattern, middleware });
43
+ }
44
+ for (const from of files)
45
+ for (const name of Object.keys(paramsOf(from, modules[from])))
46
+ if (!used.has(`${from}:${name}`))
47
+ throw new Error(`fondu: routes/${from} exports params.${name}, but no route it applies to has [${name}] or [[${name}]]`);
48
+ // the same URLs: the same pattern but for the names of its params
49
+ const byKey = new Map();
50
+ for (const route of routes) {
51
+ const key = route.pattern.replace(/(?<=\/):\w+/g, ':');
52
+ const other = byKey.get(key);
53
+ if (other && other.file !== route.file)
54
+ throw new Error(`fondu: routes/${other.file} (${other.path}) and routes/${route.file} (${route.path}) answer the same URLs. ` +
55
+ (other.path === route.path
56
+ ? 'One file per URL'
57
+ : 'Move one, or list the values of a param: `export const params = { name: [...] }`'));
58
+ byKey.set(key, route);
59
+ }
60
+ return routes.sort((a, b) => rank(a.pattern).localeCompare(rank(b.pattern)));
61
+ }
62
+ function paramsOf(file, mod) {
63
+ const params = mod?.params;
64
+ if (params === undefined)
65
+ return {};
66
+ if (typeof params !== 'object' || params === null || Array.isArray(params))
67
+ throw new Error(`fondu: routes/${file}: params is an object, \`{ name: ['value', …] }\``);
68
+ for (const [name, list] of Object.entries(params))
69
+ if (!Array.isArray(list) ||
70
+ list.some((v) => typeof v !== 'string' || !SEGMENT.test(v) || v === '.' || v === '..'))
71
+ throw new Error(`fondu: routes/${file}: params.${name} lists URL segments, of letters, digits and - . _ ~ (${JSON.stringify(list)})`);
72
+ return params;
73
+ }
74
+ // a catch-all takes the rest of the path: never a trailing slash
75
+ const withSlash = (pattern, append) => append && pattern !== '/' && !pattern.endsWith('{.+}') ? pattern + '/' : pattern;
76
+ /** sort key: static segments, then params with listed values, then params, then catch-alls */
77
+ const rank = (pattern) => pattern
78
+ .split('/')
79
+ .map((s) => (s.endsWith('{.+}') ? '3' : s.includes('{') ? '1' : s.startsWith(':') ? '2' : '0') + s)
80
+ .join('/');
@@ -1,6 +1,6 @@
1
1
  import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join, relative, sep } from 'node:path';
3
- import { isPageFile, isRouteFile, routePattern } from '../paths.js';
3
+ import { isPageFile, isRouteFile, routePatterns } from '../paths.js';
4
4
  const OUT = 'app/fondu.gen.d.ts';
5
5
  function walk(dir, out = [], base = dir) {
6
6
  if (!existsSync(dir))
@@ -29,13 +29,22 @@ declare module 'fondu' {
29
29
  ${pages.map((f) => line(f.replace(/\.(?:[jt]sx|mdx)$/, ''), `./pages/${f.replace(/\.[jt]sx$/, '')}`)).join('\n')}
30
30
  }
31
31
  routes: {
32
- ${routes.map((f) => line(routePattern(f), `./routes/${f.replace(/\.ts$/, '')}`)).join('\n')}
32
+ ${routes.flatMap((f) => patternsOf(f).map((p) => line(p, `./routes/${f.replace(/\.ts$/, '')}`))).join('\n')}
33
33
  }
34
34
  }
35
35
  }
36
36
  export {}
37
37
  `;
38
38
  }
39
+ /** a route file's URL patterns; none for one createApp() refuses (it says why) */
40
+ function patternsOf(file) {
41
+ try {
42
+ return routePatterns(file);
43
+ }
44
+ catch {
45
+ return [];
46
+ }
47
+ }
39
48
  export function writeTypes(root) {
40
49
  const file = join(root, OUT);
41
50
  const content = generateTypes(root);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fondu",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "A small meta-framework for full-stack React apps, built on Hono, Vite and Inertia. It runs on Bun, Cloudflare Workers and Node.",
5
5
  "keywords": [
6
6
  "bun",