@opentf/afw 0.33.0 → 0.34.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/index.d.ts +1 -0
- package/jsx-runtime.d.ts +3 -1
- package/macros.d.ts +24 -0
- package/package.json +2 -1
- package/runtime/hmr.js +16 -2
- package/runtime/route-match.js +99 -0
- package/runtime/router.js +19 -19
- package/server/adapters/node.js +31 -6
- package/server/api.d.ts +3 -1
- package/server/api.js +14 -58
- package/server/index.d.ts +4 -0
- package/server/loader.js +5 -42
- package/server/middleware.js +16 -14
package/index.d.ts
CHANGED
package/jsx-runtime.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
/// <reference path="./macros.d.ts" />
|
|
1
2
|
/** Type-only JSX entry for the AFW compiler (`jsx: "preserve"`). */
|
|
2
3
|
export namespace JSX {
|
|
3
4
|
type Element = Node;
|
|
@@ -15,7 +16,8 @@ export namespace JSX {
|
|
|
15
16
|
class?: string | Record<string, unknown> | unknown[];
|
|
16
17
|
className?: string;
|
|
17
18
|
style?: string | Record<string, string | number | undefined>;
|
|
18
|
-
ref
|
|
19
|
+
/** A signal holding the element, or a `$ref()` variable (typed as the element itself). */
|
|
20
|
+
ref?: { value: E | null | undefined } | E;
|
|
19
21
|
tabindex?: number;
|
|
20
22
|
autofocus?: boolean;
|
|
21
23
|
readonly?: boolean;
|
package/macros.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Types for AFW's compiler macros. The compiler rewrites these calls, so they are
|
|
2
|
+
// globals with no runtime import; this file only teaches TypeScript and editors
|
|
3
|
+
// their shapes. It is referenced from the package's types and its JSX types, so a
|
|
4
|
+
// project typed against `@opentf/afw` sees them without extra setup.
|
|
5
|
+
|
|
6
|
+
import type { Context } from "./core/context.js";
|
|
7
|
+
|
|
8
|
+
declare global {
|
|
9
|
+
/** Reactive state: read and write the variable directly (`count++`). */
|
|
10
|
+
function $state<T>(initial: T): T;
|
|
11
|
+
function $state<T = undefined>(): T | undefined;
|
|
12
|
+
/** A cached value, recomputed when the state it reads changes. */
|
|
13
|
+
function $derived<T>(value: T): T;
|
|
14
|
+
/** A side effect that re-runs when the state it reads changes; may return a cleanup. */
|
|
15
|
+
function $effect(fn: () => void | (() => void)): void;
|
|
16
|
+
/** A handle to a DOM node or component element, bound with `ref={…}`. */
|
|
17
|
+
function $ref<T = any>(): T;
|
|
18
|
+
/** The value of the nearest `<ContextProvider>` for `context`. */
|
|
19
|
+
function $context<T>(context: Context<T>): T;
|
|
20
|
+
/** Publish methods on this component's element for a parent holding its `$ref`. */
|
|
21
|
+
function $expose(api: Record<string, unknown>): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentf/afw",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.0",
|
|
4
4
|
"description": "The AFW runtime: signals and zero-VDOM DOM bindings, with routing and server rendering.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"scripts": {
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"index.js",
|
|
37
37
|
"index.d.ts",
|
|
38
38
|
"jsx-runtime.d.ts",
|
|
39
|
+
"macros.d.ts",
|
|
39
40
|
"core",
|
|
40
41
|
"runtime",
|
|
41
42
|
"components",
|
package/runtime/hmr.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
// Imported only by development compiler output.
|
|
1
|
+
// Imported only by development compiler output. It runs under esdev's and Vite's
|
|
2
|
+
// `import.meta.hot`: it uses `data`, `accept` and `invalidate`, which both provide,
|
|
3
|
+
// and `keep` where esdev has it (see `keep` below). The Custom Elements registry
|
|
2
4
|
// caches lifecycle callbacks at define time, so stable callbacks dispatch to the
|
|
3
5
|
// current implementation rather than redefining an existing tag.
|
|
4
6
|
import { scope } from "../core/signals.js";
|
|
@@ -19,6 +21,18 @@ export function hotRouteState(key, create) {
|
|
|
19
21
|
return routeSlots.get(key);
|
|
20
22
|
}
|
|
21
23
|
|
|
24
|
+
/**
|
|
25
|
+
* A value made once and returned on every replacement of the module. esdev provides
|
|
26
|
+
* `hot.keep`; Vite's `import.meta.hot` has no `keep`, but its `data` object survives
|
|
27
|
+
* replacement the same way, so the value is kept there.
|
|
28
|
+
*/
|
|
29
|
+
function keep(hot, key, make) {
|
|
30
|
+
if (typeof hot.keep === "function") return hot.keep(key, make);
|
|
31
|
+
const slot = `afwKeep:${key}`;
|
|
32
|
+
if (!(slot in hot.data)) hot.data[slot] = make();
|
|
33
|
+
return hot.data[slot];
|
|
34
|
+
}
|
|
35
|
+
|
|
22
36
|
/**
|
|
23
37
|
* `exports` is the source of the page's exports other than its view and the route data the
|
|
24
38
|
* router re-reads (see the compiler's `hot_exports_shape`). Importers hold the old values,
|
|
@@ -33,7 +47,7 @@ export function registerHotRoute(hot, factory, shape = "", exports = "", data =
|
|
|
33
47
|
}
|
|
34
48
|
hot.data.afwExports = exports;
|
|
35
49
|
hot.data.afwRouteBoundary = true;
|
|
36
|
-
const record =
|
|
50
|
+
const record = keep(hot, "afw-route", () => {
|
|
37
51
|
const entry = { factory, shape };
|
|
38
52
|
// `previous` is the view node this build replaces during a refresh. Its state
|
|
39
53
|
// slots carry over when the declarations still match; otherwise state is fresh.
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// Route-pattern matching shared by the page router, API routes, route loaders and
|
|
2
|
+
// middleware scopes, so `[param]` / `[...rest]` folders behave identically in each.
|
|
3
|
+
//
|
|
4
|
+
// Precedence is by specificity, segment by segment: a static segment beats a
|
|
5
|
+
// `[param]`, which beats a `[...rest]`. So `/blog/new` wins over `/blog/[slug]` and
|
|
6
|
+
// `/api/[id]` wins over `/api/[...rest]`, whatever order the files were discovered in
|
|
7
|
+
// and whatever the params are called.
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Strip the app-directory prefix from a route/middleware file path. When the caller
|
|
11
|
+
* knows the app dir, the exact prefix is removed — unambiguous even for an
|
|
12
|
+
* `app/app/...` folder. Without it, fall back to the last complete `/app` path
|
|
13
|
+
* segment; the lookahead keeps folders that merely *start* with "app"
|
|
14
|
+
* (`/appointments`, `/apps`) intact.
|
|
15
|
+
*/
|
|
16
|
+
export function stripAppDir(filePath, appDir) {
|
|
17
|
+
if (appDir) {
|
|
18
|
+
const base = appDir.replace(/\/+$/, "");
|
|
19
|
+
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
20
|
+
}
|
|
21
|
+
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Drop a trailing slash, except for the root "/". */
|
|
25
|
+
export const normalizePath = (p) => (p || "/").replace(/(.)\/+$/, "$1");
|
|
26
|
+
|
|
27
|
+
const PARAM_SPLIT = /(\[\.\.\.[^\]]+\]|\[[^\]]+\])/;
|
|
28
|
+
|
|
29
|
+
/** Regex source for a route with `[param]` / `[...rest]` segments. Named groups
|
|
30
|
+
* become params; literal parts are regex-escaped (`v1.0` must not match `v1X0`). */
|
|
31
|
+
function patternSource(route) {
|
|
32
|
+
return route
|
|
33
|
+
.split(PARAM_SPLIT)
|
|
34
|
+
.map((part) => {
|
|
35
|
+
if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
|
|
36
|
+
if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
|
|
37
|
+
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
38
|
+
})
|
|
39
|
+
.join("");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** A full-path matcher for `route`; the optional trailing slash is tolerated. */
|
|
43
|
+
export function compileRoute(route) {
|
|
44
|
+
return new RegExp(`^${patternSource(route)}/?$`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* A scope matcher for a middleware folder route: the folder itself and anything
|
|
49
|
+
* nested under it. `/users/[id]` covers `/users/7` and `/users/7/edit`; `/` covers
|
|
50
|
+
* every path.
|
|
51
|
+
*/
|
|
52
|
+
export function compileScope(scope) {
|
|
53
|
+
if (scope === "/") return /^\//;
|
|
54
|
+
return new RegExp(`^${patternSource(scope)}(?:/.*)?$`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Segment kinds, most specific first.
|
|
58
|
+
const segmentKind = (seg) => (seg.startsWith("[...") ? 2 : seg.startsWith("[") ? 1 : 0);
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Sort comparator: more specific routes first. Compares segment kinds left to
|
|
62
|
+
* right (static < `[param]` < `[...rest]`); with equal kinds the route with more
|
|
63
|
+
* segments is more specific; the final tie-break is lexical, for a deterministic order.
|
|
64
|
+
*/
|
|
65
|
+
export function compareRoutes(a, b) {
|
|
66
|
+
const sa = a.split("/").filter(Boolean);
|
|
67
|
+
const sb = b.split("/").filter(Boolean);
|
|
68
|
+
for (let i = 0; i < Math.min(sa.length, sb.length); i++) {
|
|
69
|
+
const d = segmentKind(sa[i]) - segmentKind(sb[i]);
|
|
70
|
+
if (d !== 0) return d;
|
|
71
|
+
}
|
|
72
|
+
if (sa.length !== sb.length) return sb.length - sa.length;
|
|
73
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Percent-decode a match's named groups into params: catch-all segments are split
|
|
78
|
+
* first (so an encoded `%2F` never adds a segment) and arrive as an array. Returns
|
|
79
|
+
* `null` on malformed percent-encoding when `strict`, else keeps the raw text.
|
|
80
|
+
*/
|
|
81
|
+
export function decodeParams(route, groups, { strict = false } = {}) {
|
|
82
|
+
const params = { ...(groups || {}) };
|
|
83
|
+
for (const k in params) {
|
|
84
|
+
const decode = (s) => {
|
|
85
|
+
try {
|
|
86
|
+
return decodeURIComponent(s);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
if (strict) throw e;
|
|
89
|
+
return s;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
try {
|
|
93
|
+
params[k] = route.includes(`[...${k}]`) ? params[k].split("/").map(decode) : decode(params[k]);
|
|
94
|
+
} catch {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return params;
|
|
99
|
+
}
|
package/runtime/router.js
CHANGED
|
@@ -22,6 +22,7 @@ import { prepareRouteHead, updateRouteHead } from "./head.js";
|
|
|
22
22
|
import { beginHydration, cursor, endHydration, renderedForPath } from "./hydrate.js";
|
|
23
23
|
import { buildScopedView, runCleanup, runMount } from "./mount.js";
|
|
24
24
|
import { fetchRouteData, readInlineRouteData } from "./route-data.js";
|
|
25
|
+
import { compareRoutes, compileRoute, decodeParams } from "./route-match.js";
|
|
25
26
|
|
|
26
27
|
const isBrowser = typeof window !== "undefined";
|
|
27
28
|
|
|
@@ -386,32 +387,31 @@ export function setRouteState({ pathname = "/", search = "", params = {}, locale
|
|
|
386
387
|
*/
|
|
387
388
|
export function matchRoute(pathname) {
|
|
388
389
|
pathname = resolveLocale(pathname).path;
|
|
389
|
-
for (const route
|
|
390
|
-
|
|
391
|
-
// (a `v1.0` folder must not match `v1X0`).
|
|
392
|
-
const pattern = route
|
|
393
|
-
.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\])/)
|
|
394
|
-
.map((part) => {
|
|
395
|
-
if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
|
|
396
|
-
if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
|
|
397
|
-
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
398
|
-
})
|
|
399
|
-
.join("");
|
|
400
|
-
const m = pathname.match(new RegExp(`^${pattern}/?$`));
|
|
390
|
+
for (const { route, pattern } of rankedPages()) {
|
|
391
|
+
const m = pathname.match(pattern);
|
|
401
392
|
if (m) {
|
|
402
|
-
const params =
|
|
403
|
-
|
|
404
|
-
try {
|
|
405
|
-
params[k] = route.includes(`[...${k}]`)
|
|
406
|
-
? params[k].split("/").map(decodeURIComponent) : decodeURIComponent(params[k]);
|
|
407
|
-
} catch { return null; }
|
|
408
|
-
}
|
|
393
|
+
const params = decodeParams(route, m.groups, { strict: true });
|
|
394
|
+
if (!params) return null;
|
|
409
395
|
return { entry: routes.pages[route], params, route };
|
|
410
396
|
}
|
|
411
397
|
}
|
|
412
398
|
return null;
|
|
413
399
|
}
|
|
414
400
|
|
|
401
|
+
// Compiled page patterns, most specific first (route-match.js `compareRoutes`), so a
|
|
402
|
+
// static `/blog/new` beats `/blog/[slug]` whatever order the files were discovered in.
|
|
403
|
+
// Rebuilt when the set of routes changes (registration, HMR, tests swapping the table).
|
|
404
|
+
let ranked = { key: null, list: [] };
|
|
405
|
+
function rankedPages() {
|
|
406
|
+
const names = Object.keys(routes.pages);
|
|
407
|
+
const key = names.join("\0");
|
|
408
|
+
if (ranked.key !== key) {
|
|
409
|
+
const list = names.sort(compareRoutes).map((route) => ({ route, pattern: compileRoute(route) }));
|
|
410
|
+
ranked = { key, list };
|
|
411
|
+
}
|
|
412
|
+
return ranked.list;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
415
|
// Monotonic navigation sequence: a navigation that awaited its loader-data fetch
|
|
416
416
|
// commits only if no newer navigation started meanwhile (stale data must never
|
|
417
417
|
// win over a later click).
|
package/server/adapters/node.js
CHANGED
|
@@ -45,11 +45,30 @@ export async function sendWebResponse(res, webRes) {
|
|
|
45
45
|
const cookies = webRes.headers.getSetCookie?.() ?? [];
|
|
46
46
|
if (cookies.length > 0) headers["set-cookie"] = cookies;
|
|
47
47
|
res.writeHead(webRes.status, headers);
|
|
48
|
-
if (webRes.body) {
|
|
49
|
-
const buf = Buffer.from(await webRes.arrayBuffer());
|
|
50
|
-
res.end(buf);
|
|
51
|
-
} else {
|
|
48
|
+
if (!webRes.body) {
|
|
52
49
|
res.end();
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
// Stream the body chunk by chunk, so server-sent events and large downloads reach
|
|
53
|
+
// the client as they are produced instead of after the whole body is buffered.
|
|
54
|
+
// Honour backpressure (`write()` returning false waits for "drain") and stop
|
|
55
|
+
// reading when the client goes away.
|
|
56
|
+
const reader = webRes.body.getReader();
|
|
57
|
+
let closed = false;
|
|
58
|
+
const onClose = () => {
|
|
59
|
+
closed = true;
|
|
60
|
+
reader.cancel().catch(() => {});
|
|
61
|
+
};
|
|
62
|
+
res.on?.("close", onClose);
|
|
63
|
+
try {
|
|
64
|
+
while (!closed) {
|
|
65
|
+
const { done, value } = await reader.read();
|
|
66
|
+
if (done) break;
|
|
67
|
+
if (!res.write(value)) await new Promise((resolve) => res.once("drain", resolve));
|
|
68
|
+
}
|
|
69
|
+
} finally {
|
|
70
|
+
res.off?.("close", onClose);
|
|
71
|
+
if (!closed) res.end();
|
|
53
72
|
}
|
|
54
73
|
}
|
|
55
74
|
|
|
@@ -66,9 +85,15 @@ export function toNodeListener(handler, { fallback } = {}) {
|
|
|
66
85
|
if (!webRes) webRes = fallback ? await fallback(request) : new Response("Not Found", { status: 404 });
|
|
67
86
|
await sendWebResponse(res, webRes);
|
|
68
87
|
} catch (e) {
|
|
69
|
-
if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" });
|
|
70
|
-
res.end(JSON.stringify({ error: "Internal Server Error" }));
|
|
71
88
|
console.error("✗ API (node adapter):", e?.stack ?? e);
|
|
89
|
+
if (res.headersSent) {
|
|
90
|
+
// Mid-stream failure: the status is already out, so appending an error body
|
|
91
|
+
// would corrupt the response. Abort the connection instead.
|
|
92
|
+
res.destroy?.(e);
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
res.writeHead(500, { "content-type": "application/json" });
|
|
96
|
+
res.end(JSON.stringify({ error: "Internal Server Error" }));
|
|
72
97
|
}
|
|
73
98
|
};
|
|
74
99
|
}
|
package/server/api.d.ts
CHANGED
|
@@ -20,7 +20,9 @@ export type RouteParams = Record<string, string | string[]>;
|
|
|
20
20
|
export interface ApiContext {
|
|
21
21
|
/** Dynamic route params resolved from the matched path. */
|
|
22
22
|
params: RouteParams;
|
|
23
|
-
/** Parsed query-string parameters
|
|
23
|
+
/** Parsed query-string parameters, one string per name: a repeated name keeps its
|
|
24
|
+
* last value (`?tag=a&tag=b` → `{ tag: "b" }`). Read every value with
|
|
25
|
+
* `url.searchParams.getAll("tag")`. */
|
|
24
26
|
query: Record<string, string>;
|
|
25
27
|
/** The parsed request URL. */
|
|
26
28
|
url: URL;
|
package/server/api.js
CHANGED
|
@@ -14,7 +14,8 @@
|
|
|
14
14
|
// approach of the page router (runtime/router.js `matchRoute`) so behavior is
|
|
15
15
|
// identical across pages and API and across every deployment target.
|
|
16
16
|
|
|
17
|
-
import {
|
|
17
|
+
import { compareRoutes, compileRoute, compileScope, decodeParams, normalizePath as normalize, stripAppDir } from "../runtime/route-match.js";
|
|
18
|
+
import { middlewareScopeFromPath, outermostFirst } from "./middleware.js";
|
|
18
19
|
|
|
19
20
|
// Scope derivation lives in middleware.js now that middleware governs the whole
|
|
20
21
|
// pipeline, not just API routes; re-exported here for backward compatibility.
|
|
@@ -22,21 +23,6 @@ export { middlewareScopeFromPath };
|
|
|
22
23
|
|
|
23
24
|
const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"];
|
|
24
25
|
|
|
25
|
-
/**
|
|
26
|
-
* Strip the app-directory prefix from a route/middleware file path. When the
|
|
27
|
-
* caller knows the app dir (the CLI always does), the exact prefix is removed —
|
|
28
|
-
* unambiguous even for an `app/app/...` folder. Without it, fall back to the last
|
|
29
|
-
* complete `/app` path segment; the lookahead keeps folders that merely *start*
|
|
30
|
-
* with "app" (`/appointments`, `/apps`) intact.
|
|
31
|
-
*/
|
|
32
|
-
function stripAppDir(filePath, appDir) {
|
|
33
|
-
if (appDir) {
|
|
34
|
-
const base = appDir.replace(/\/+$/, "");
|
|
35
|
-
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
36
|
-
}
|
|
37
|
-
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
38
|
-
}
|
|
39
|
-
|
|
40
26
|
/**
|
|
41
27
|
* Derive the API route path from a `.../app/<...>/route.{js,ts}` file path — the
|
|
42
28
|
* folder is the URL, mirroring `routeFromPath` in the page router.
|
|
@@ -49,32 +35,6 @@ export function apiRouteFromPath(filePath, appDir) {
|
|
|
49
35
|
return r === "" ? "/" : r;
|
|
50
36
|
}
|
|
51
37
|
|
|
52
|
-
/** Compile a route path with `[param]` / `[...rest]` segments to a matcher regex.
|
|
53
|
-
* Named groups become route params; literal parts are regex-escaped (a `v1.0`
|
|
54
|
-
* folder must not match `v1X0`); the optional trailing slash is tolerated. */
|
|
55
|
-
function compilePattern(route) {
|
|
56
|
-
const src = route
|
|
57
|
-
.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\])/)
|
|
58
|
-
.map((part) => {
|
|
59
|
-
if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
|
|
60
|
-
if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
|
|
61
|
-
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
62
|
-
})
|
|
63
|
-
.join("");
|
|
64
|
-
return new RegExp(`^${src}/?$`);
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
// Percent-decode a matched param segment; malformed input stays raw rather than throwing.
|
|
68
|
-
const decodeParam = (s) => {
|
|
69
|
-
try {
|
|
70
|
-
return decodeURIComponent(s);
|
|
71
|
-
} catch {
|
|
72
|
-
return s;
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
|
|
76
|
-
const normalize = (p) => (p || "/").replace(/(.)\/+$/, "$1");
|
|
77
|
-
|
|
78
38
|
/** The `Allow` header value for a handler module: the methods it exports, plus the
|
|
79
39
|
* auto-provided HEAD (when GET exists) and OPTIONS. */
|
|
80
40
|
function allowedMethods(mod) {
|
|
@@ -101,20 +61,23 @@ export function createApiHandler(routeModules = {}, middlewareModules = {}, { ap
|
|
|
101
61
|
const routes = [];
|
|
102
62
|
for (const file in routeModules) {
|
|
103
63
|
const route = apiRouteFromPath(file, appDir);
|
|
104
|
-
routes.push({ route, pattern:
|
|
64
|
+
routes.push({ route, pattern: compileRoute(route), module: routeModules[file] });
|
|
105
65
|
}
|
|
106
|
-
//
|
|
107
|
-
//
|
|
108
|
-
routes.sort((a, b) => a.
|
|
66
|
+
// Most specific first, segment by segment (static, then `[param]`, then
|
|
67
|
+
// `[...rest]`), so the winner never depends on discovery order or param names.
|
|
68
|
+
routes.sort((a, b) => compareRoutes(a.route, b.route));
|
|
109
69
|
|
|
110
70
|
const middleware = [];
|
|
111
71
|
for (const file in middlewareModules) {
|
|
112
72
|
const mod = middlewareModules[file];
|
|
113
73
|
const fn = mod.default ?? mod.middleware;
|
|
114
|
-
if (typeof fn === "function")
|
|
74
|
+
if (typeof fn === "function") {
|
|
75
|
+
const scope = middlewareScopeFromPath(file, appDir);
|
|
76
|
+
middleware.push({ scope, matcher: compileScope(scope), fn });
|
|
77
|
+
}
|
|
115
78
|
}
|
|
116
|
-
// Outermost
|
|
117
|
-
middleware.sort(
|
|
79
|
+
// Outermost runs first, so `/api/_middleware` wraps `/api/users/_middleware`.
|
|
80
|
+
middleware.sort(outermostFirst);
|
|
118
81
|
|
|
119
82
|
return async function handle(request, env, ctx, init) {
|
|
120
83
|
const url = new URL(request.url);
|
|
@@ -126,14 +89,9 @@ export function createApiHandler(routeModules = {}, middlewareModules = {}, { ap
|
|
|
126
89
|
const m = pathname.match(r.pattern);
|
|
127
90
|
if (!m) continue;
|
|
128
91
|
matched = r;
|
|
129
|
-
params = { ...(m.groups || {}) };
|
|
130
92
|
// Params reach handlers percent-decoded (`/users/John%20Doe` → "John Doe");
|
|
131
93
|
// catch-all segments are split first so an encoded `%2F` never adds a segment.
|
|
132
|
-
|
|
133
|
-
params[k] = r.route.includes(`[...${k}]`)
|
|
134
|
-
? params[k].split("/").map(decodeParam)
|
|
135
|
-
: decodeParam(params[k]);
|
|
136
|
-
}
|
|
94
|
+
params = decodeParams(r.route, m.groups);
|
|
137
95
|
break;
|
|
138
96
|
}
|
|
139
97
|
if (!matched) return null; // no API route — fall through to SSR / 404
|
|
@@ -171,9 +129,7 @@ export function createApiHandler(routeModules = {}, middlewareModules = {}, { ap
|
|
|
171
129
|
|
|
172
130
|
// Compose the applicable middleware chain around dispatch (outermost first).
|
|
173
131
|
// The root scope ("/", from an `app/_middleware.*`) governs every route.
|
|
174
|
-
const chain = middleware.filter(
|
|
175
|
-
(mw) => mw.scope === "/" || pathname === mw.scope || pathname.startsWith(mw.scope + "/"),
|
|
176
|
-
);
|
|
132
|
+
const chain = middleware.filter((mw) => mw.matcher.test(pathname));
|
|
177
133
|
let next = dispatch;
|
|
178
134
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
179
135
|
const { fn } = chain[i];
|
package/server/index.d.ts
CHANGED
|
@@ -33,6 +33,8 @@ export function registerRoutes(modules: Record<string, unknown>): void;
|
|
|
33
33
|
export const router: {
|
|
34
34
|
readonly pathname: string;
|
|
35
35
|
readonly searchParams: URLSearchParams;
|
|
36
|
+
/** One string per name; a repeated name keeps its last value. Use
|
|
37
|
+
* `searchParams.getAll(name)` for every value. */
|
|
36
38
|
readonly query: Record<string, string>;
|
|
37
39
|
readonly params: RouteParams;
|
|
38
40
|
readonly locale: string | null;
|
|
@@ -104,6 +106,8 @@ import type { RouteParams } from "./api.js";
|
|
|
104
106
|
* Request under serve/dev and undefined at SSG prerender; `locals` is reserved. */
|
|
105
107
|
export interface LoaderContext {
|
|
106
108
|
params: RouteParams;
|
|
109
|
+
/** One string per name; a repeated name keeps its last value. For every value, read
|
|
110
|
+
* `new URL(request.url).searchParams.getAll(name)` (request servers only). */
|
|
107
111
|
query: Record<string, string>;
|
|
108
112
|
request?: Request;
|
|
109
113
|
locale: string | null;
|
package/server/loader.js
CHANGED
|
@@ -18,15 +18,7 @@
|
|
|
18
18
|
// behave identically across pages, endpoints, and loaders.
|
|
19
19
|
|
|
20
20
|
import { DATA_FILE } from "../runtime/route-data.js";
|
|
21
|
-
|
|
22
|
-
/** See `stripAppDir` in api.js — exact-prefix strip with a `/app` segment fallback. */
|
|
23
|
-
function stripAppDir(filePath, appDir) {
|
|
24
|
-
if (appDir) {
|
|
25
|
-
const base = appDir.replace(/\/+$/, "");
|
|
26
|
-
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
27
|
-
}
|
|
28
|
-
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
29
|
-
}
|
|
21
|
+
import { compareRoutes, compileRoute, decodeParams, normalizePath as normalize, stripAppDir } from "../runtime/route-match.js";
|
|
30
22
|
|
|
31
23
|
/** The page route a `.../app/<...>/loader.{js,ts}` file feeds (folder = URL):
|
|
32
24
|
* `app/todos/loader.js` → `/todos`, `app/loader.js` → `/`. */
|
|
@@ -35,29 +27,6 @@ export function loaderRouteFromPath(filePath, appDir) {
|
|
|
35
27
|
return r === "" ? "/" : r;
|
|
36
28
|
}
|
|
37
29
|
|
|
38
|
-
/** Compile a route with `[param]` / `[...rest]` segments to a matcher regex (see api.js). */
|
|
39
|
-
function compilePattern(route) {
|
|
40
|
-
const src = route
|
|
41
|
-
.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\])/)
|
|
42
|
-
.map((part) => {
|
|
43
|
-
if (part.startsWith("[...")) return `(?<${part.slice(4, -1)}>.+)`;
|
|
44
|
-
if (part.startsWith("[")) return `(?<${part.slice(1, -1)}>[^/]+)`;
|
|
45
|
-
return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
46
|
-
})
|
|
47
|
-
.join("");
|
|
48
|
-
return new RegExp(`^${src}/?$`);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const decodeParam = (s) => {
|
|
52
|
-
try {
|
|
53
|
-
return decodeURIComponent(s);
|
|
54
|
-
} catch {
|
|
55
|
-
return s;
|
|
56
|
-
}
|
|
57
|
-
};
|
|
58
|
-
|
|
59
|
-
const normalize = (p) => (p || "/").replace(/(.)\/+$/, "$1");
|
|
60
|
-
|
|
61
30
|
/**
|
|
62
31
|
* Signal "this page does not exist for these params" from inside a loader — the
|
|
63
32
|
* SSR server responds 404 (rendering the 404 page), the data endpoint returns a
|
|
@@ -112,10 +81,10 @@ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {})
|
|
|
112
81
|
const fn = ns.default ?? ns.loader;
|
|
113
82
|
if (typeof fn !== "function") continue; // a loader file without a loader export is inert
|
|
114
83
|
const route = loaderRouteFromPath(file, appDir);
|
|
115
|
-
entries.push({ route, pattern:
|
|
84
|
+
entries.push({ route, pattern: compileRoute(route), fn });
|
|
116
85
|
}
|
|
117
|
-
//
|
|
118
|
-
entries.sort((a, b) => a.
|
|
86
|
+
// Most specific first, segment by segment — the same ranking as pages and API routes.
|
|
87
|
+
entries.sort((a, b) => compareRoutes(a.route, b.route));
|
|
119
88
|
|
|
120
89
|
const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
|
|
121
90
|
const defaultLocale = i18nOn ? (i18n.defaultLocale ?? i18n.locales[0]) : null;
|
|
@@ -135,13 +104,7 @@ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {})
|
|
|
135
104
|
for (const e of entries) {
|
|
136
105
|
const m = path.match(e.pattern);
|
|
137
106
|
if (!m) continue;
|
|
138
|
-
|
|
139
|
-
for (const k in params) {
|
|
140
|
-
params[k] = e.route.includes(`[...${k}]`)
|
|
141
|
-
? params[k].split("/").map(decodeParam)
|
|
142
|
-
: decodeParam(params[k]);
|
|
143
|
-
}
|
|
144
|
-
return { route: e.route, params, locale, fn: e.fn };
|
|
107
|
+
return { route: e.route, params: decodeParams(e.route, m.groups), locale, fn: e.fn };
|
|
145
108
|
}
|
|
146
109
|
return null;
|
|
147
110
|
}
|
package/server/middleware.js
CHANGED
|
@@ -19,15 +19,7 @@
|
|
|
19
19
|
// middleware), mirroring the loader registry (loader.js `match`).
|
|
20
20
|
|
|
21
21
|
import { DATA_FILE } from "../runtime/route-data.js";
|
|
22
|
-
|
|
23
|
-
/** See `stripAppDir` in api.js — exact-prefix strip with a `/app` segment fallback. */
|
|
24
|
-
function stripAppDir(filePath, appDir) {
|
|
25
|
-
if (appDir) {
|
|
26
|
-
const base = appDir.replace(/\/+$/, "");
|
|
27
|
-
if (filePath.startsWith(base + "/")) return filePath.slice(base.length);
|
|
28
|
-
}
|
|
29
|
-
return filePath.replace(/^.*\/app(?=\/)/, "");
|
|
30
|
-
}
|
|
22
|
+
import { compareRoutes, compileScope, normalizePath as normalize, stripAppDir } from "../runtime/route-match.js";
|
|
31
23
|
|
|
32
24
|
/** The folder route a `_middleware.{js,ts}` file governs: `app/api/_middleware.js`
|
|
33
25
|
* → `/api` (applies to `/api` and everything nested under it); `app/_middleware.js`
|
|
@@ -37,7 +29,15 @@ export function middlewareScopeFromPath(filePath, appDir) {
|
|
|
37
29
|
return r === "" ? "/" : r;
|
|
38
30
|
}
|
|
39
31
|
|
|
40
|
-
|
|
32
|
+
/**
|
|
33
|
+
* Sort comparator for middleware scopes: outermost (fewest segments) first, so
|
|
34
|
+
* `app/_middleware` wraps `app/api/_middleware`; at equal depth a dynamic folder
|
|
35
|
+
* wraps a static one. Ties fall back to a lexical order, independent of discovery.
|
|
36
|
+
*/
|
|
37
|
+
export function outermostFirst(a, b) {
|
|
38
|
+
const depth = (s) => s.split("/").filter(Boolean).length;
|
|
39
|
+
return depth(a.scope) - depth(b.scope) || compareRoutes(b.scope, a.scope);
|
|
40
|
+
}
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
43
|
* Build the middleware runner from a discovered `{ absFilePath: namespace }` map.
|
|
@@ -57,10 +57,12 @@ export function createMiddleware(middlewareModules = {}, { appDir, i18n } = {})
|
|
|
57
57
|
for (const file in middlewareModules) {
|
|
58
58
|
const mod = middlewareModules[file];
|
|
59
59
|
const fn = mod.default ?? mod.middleware;
|
|
60
|
-
if (typeof fn === "function")
|
|
60
|
+
if (typeof fn === "function") {
|
|
61
|
+
const scope = middlewareScopeFromPath(file, appDir);
|
|
62
|
+
entries.push({ scope, matcher: compileScope(scope), fn });
|
|
63
|
+
}
|
|
61
64
|
}
|
|
62
|
-
|
|
63
|
-
entries.sort((a, b) => a.scope.length - b.scope.length);
|
|
65
|
+
entries.sort(outermostFirst);
|
|
64
66
|
|
|
65
67
|
const i18nOn = !!(i18n && Array.isArray(i18n.locales) && i18n.locales.length);
|
|
66
68
|
const defaultLocale = i18nOn ? (i18n.defaultLocale ?? i18n.locales[0]) : null;
|
|
@@ -95,7 +97,7 @@ export function createMiddleware(middlewareModules = {}, { appDir, i18n } = {})
|
|
|
95
97
|
const url = new URL(request.url);
|
|
96
98
|
const context = { url, locals: {}, env, ctx };
|
|
97
99
|
const path = scopePath(url.pathname);
|
|
98
|
-
const chain = entries.filter((e) => e.
|
|
100
|
+
const chain = entries.filter((e) => e.matcher.test(path));
|
|
99
101
|
let next = (req) => terminal(req, context);
|
|
100
102
|
for (let i = chain.length - 1; i >= 0; i--) {
|
|
101
103
|
const { fn } = chain[i];
|