@opentf/afw 0.33.0 → 0.35.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/runtime/router.js CHANGED
@@ -20,8 +20,11 @@ import { getRenderContext } from "../core/render-context.js";
20
20
  import { resolveMetadataModules } from "../core/metadata.js";
21
21
  import { prepareRouteHead, updateRouteHead } from "./head.js";
22
22
  import { beginHydration, cursor, endHydration, renderedForPath } from "./hydrate.js";
23
+ import { collectHotState, withHotCarry } from "./hot-carry.js";
23
24
  import { buildScopedView, runCleanup, runMount } from "./mount.js";
24
25
  import { fetchRouteData, readInlineRouteData } from "./route-data.js";
26
+ import { setRouteDataRefresher } from "./invalidate.js";
27
+ import { compareRoutes, compileRoute, decodeParams } from "./route-match.js";
25
28
 
26
29
  const isBrowser = typeof window !== "undefined";
27
30
 
@@ -386,37 +389,103 @@ export function setRouteState({ pathname = "/", search = "", params = {}, locale
386
389
  */
387
390
  export function matchRoute(pathname) {
388
391
  pathname = resolveLocale(pathname).path;
389
- for (const route in routes.pages) {
390
- // `[param]` / `[...rest]` become named groups; literal parts are regex-escaped
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}/?$`));
392
+ for (const { route, pattern } of rankedPages()) {
393
+ const m = pathname.match(pattern);
401
394
  if (m) {
402
- const params = { ...(m.groups || {}) };
403
- for (const k in params) {
404
- try {
405
- params[k] = route.includes(`[...${k}]`)
406
- ? params[k].split("/").map(decodeURIComponent) : decodeURIComponent(params[k]);
407
- } catch { return null; }
408
- }
395
+ const params = decodeParams(route, m.groups, { strict: true });
396
+ if (!params) return null;
409
397
  return { entry: routes.pages[route], params, route };
410
398
  }
411
399
  }
412
400
  return null;
413
401
  }
414
402
 
403
+ // Compiled page patterns, most specific first (route-match.js `compareRoutes`), so a
404
+ // static `/blog/new` beats `/blog/[slug]` whatever order the files were discovered in.
405
+ // Rebuilt when the set of routes changes (registration, HMR, tests swapping the table).
406
+ let ranked = { key: null, list: [] };
407
+ function rankedPages() {
408
+ const names = Object.keys(routes.pages);
409
+ const key = names.join("\0");
410
+ if (ranked.key !== key) {
411
+ const list = names.sort(compareRoutes).map((route) => ({ route, pattern: compileRoute(route) }));
412
+ ranked = { key, list };
413
+ }
414
+ return ranked.list;
415
+ }
416
+
415
417
  // Monotonic navigation sequence: a navigation that awaited its loader-data fetch
416
418
  // commits only if no newer navigation started meanwhile (stale data must never
417
419
  // win over a later click).
418
420
  let navSeq = 0;
419
421
 
422
+ // Prefetched loader data (`prefetch`): `pathname + search` → { data: Promise, at }. A
423
+ // navigation takes an entry once, while fresh; `invalidate()` clears them all.
424
+ const prefetched = new Map();
425
+ const PREFETCH_TTL_MS = 30_000;
426
+ // Route entries whose chunk prefetch started; a failed one may be retried.
427
+ const warmedEntries = new WeakSet();
428
+
429
+ function takePrefetched(key) {
430
+ const hit = prefetched.get(key);
431
+ prefetched.delete(key);
432
+ return hit && Date.now() - hit.at < PREFETCH_TTL_MS ? hit.data : null;
433
+ }
434
+
435
+ /**
436
+ * Warm a route before it is visited: start loading its page and layout chunks and, when
437
+ * it has a loader, its data, which the navigation then reuses (once, within 30 s).
438
+ * `<Link>` calls this on hover, focus or touch. A no-op on the server, before
439
+ * `mountApp`, for another origin, for an unknown route, and when the browser asks to
440
+ * save data.
441
+ */
442
+ export function prefetch(path) {
443
+ if (!isBrowser || !rootEl || !path) return;
444
+ if (typeof navigator !== "undefined" && navigator.connection?.saveData) return;
445
+ let url;
446
+ try {
447
+ url = new URL(path, window.location.origin);
448
+ } catch {
449
+ return;
450
+ }
451
+ if (url.origin !== window.location.origin) return;
452
+ const match = matchRoute(url.pathname);
453
+ if (!match) return;
454
+ for (const entry of [match.entry, ...layoutChain(match.route)]) {
455
+ if (typeof entry !== "function" || warmedEntries.has(entry)) continue; // eager, or already started
456
+ warmedEntries.add(entry);
457
+ // A failure is the navigation's to report; it may be retried.
458
+ Promise.resolve().then(() => resolveModule(entry)).catch(() => warmedEntries.delete(entry));
459
+ }
460
+ if (match.route && routes.loaderRoutes.has(match.route)) {
461
+ const key = url.pathname + url.search;
462
+ const hit = prefetched.get(key);
463
+ if (hit && Date.now() - hit.at < PREFETCH_TTL_MS) return;
464
+ const data = fetchRouteData(url.pathname, url.search);
465
+ data.catch(() => prefetched.delete(key));
466
+ prefetched.set(key, { data, at: Date.now() });
467
+ }
468
+ }
469
+
470
+ /**
471
+ * Reload the current page's loader data into `router.data` (`invalidate()`), and drop
472
+ * prefetched data, which may be stale too.
473
+ */
474
+ export async function refreshRouteData() {
475
+ prefetched.clear();
476
+ if (!isBrowser || !rootEl) return;
477
+ const pathname = state.pathname.value;
478
+ const match = matchRoute(pathname);
479
+ if (!match?.route || !routes.loaderRoutes.has(match.route)) return;
480
+ const seq = navSeq;
481
+ try {
482
+ const data = await fetchRouteData(pathname, window.location.search);
483
+ if (seq === navSeq) state.data.value = data; // a navigation since owns the data
484
+ } catch (e) {
485
+ reportError(e, { phase: "data", path: pathname });
486
+ }
487
+ }
488
+
420
489
  // --- Stale-chunk recovery ---------------------------------------------------
421
490
  // Pages/layouts are code-split, so a route is loaded by a lazy `() => import(...)`
422
491
  // at navigation time. Asset filenames are content-hashed (`layout-DmM9YRKj.js`),
@@ -553,7 +622,8 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
553
622
  data = readInlineRouteData();
554
623
  } else {
555
624
  try {
556
- data = await fetchRouteData(url.pathname, url.search);
625
+ const warmed = takePrefetched(url.pathname + url.search);
626
+ data = warmed ? await warmed.catch(() => fetchRouteData(url.pathname, url.search)) : await fetchRouteData(url.pathname, url.search);
557
627
  } catch (e) {
558
628
  reportError(e, { phase: "data", path: url.pathname });
559
629
  }
@@ -710,10 +780,15 @@ export async function refreshHotRoute(factory, data = null) {
710
780
  const layouts = layoutModules.map((module, i) => (index === layoutModules.length - i ? fresh(module) : namespace(module)));
711
781
  // An edited page may have new headings: publish them before the view rebuilds.
712
782
  setRouteToc(page);
713
- node = buildScopedView(() => factory(props, previous));
714
783
  const old = viewNodes(previous);
715
784
  if (old.length === 0) throw new Error("the refreshed view has no nodes in the document to replace");
716
- old[0].parentNode.insertBefore(node, old[0]);
785
+ // Components the rebuilt view renders get new elements, which connect on insert;
786
+ // carry their state across. A layout's page is moved, not rebuilt.
787
+ const carried = collectHotState(old, inner ? viewNodes(inner) : []);
788
+ withHotCarry(carried, () => {
789
+ node = buildScopedView(() => factory(props, previous));
790
+ old[0].parentNode.insertBefore(node, old[0]);
791
+ });
717
792
  for (const n of old) n.remove();
718
793
  runCleanup(previous);
719
794
  currentNodes = currentNodes.map((current, i) => (i === index ? node : current));
@@ -767,6 +842,8 @@ export function mountApp({ pages, target, guard: g, i18n, nav, loaders } = {}) {
767
842
  if (pages) registerRoutes(pages);
768
843
  if (loaders) registerLoaderRoutes(loaders);
769
844
  guard = g || null;
845
+ setRouteDataRefresher(refreshRouteData);
846
+ prefetched.clear(); // a fresh app starts with nothing warmed
770
847
  // In MPA mode the browser owns navigation (full loads push real history entries),
771
848
  // so there is no client-side history to react to — only wire popstate for SPA.
772
849
  if (isBrowser && navMode === "spa") {
@@ -0,0 +1,14 @@
1
+ /** A failed server function call. */
2
+ export class ServerFunctionError extends Error {
3
+ /** The HTTP status: 400 invalid input, 401/403 refused, 404 not found, 500 failed. */
4
+ status: number;
5
+ /** The schema's issues when the input was invalid. */
6
+ issues?: Array<{ message: string; path?: PropertyKey[] }>;
7
+ /** The server answered with a redirect (e.g. an auth guard). */
8
+ redirected: boolean;
9
+ }
10
+ /** The browser stub for a server function (generated by the build). */
11
+ export function serverFunction<Input = unknown, Output = unknown>(
12
+ endpoint: string,
13
+ kind: "query" | "action",
14
+ ): (input: Input, options?: { signal?: AbortSignal }) => Promise<Output>;
@@ -0,0 +1,53 @@
1
+ // The browser side of server functions (docs/SERVER_FUNCTIONS.md). The build replaces a
2
+ // `*.server` module with stubs made here: `serverFunction("/todos/__fn/<id>", "query")`
3
+ // is an async function with the server function's signature that calls its endpoint.
4
+
5
+ import { CONTENT_TYPE, decode, encode } from "../core/fn-codec.js";
6
+ import { trackServerCall } from "./invalidate.js";
7
+
8
+ // Queries go by GET while the encoded arguments fit comfortably in a URL.
9
+ const MAX_GET_ARGS = 2000;
10
+
11
+ /** A failed server function call: `status`, and `issues` when the input was invalid. */
12
+ export class ServerFunctionError extends Error {
13
+ constructor(message, { status, issues, redirected = false } = {}) {
14
+ super(message);
15
+ this.name = "ServerFunctionError";
16
+ this.status = status;
17
+ this.issues = issues;
18
+ this.redirected = redirected;
19
+ }
20
+ }
21
+
22
+ /**
23
+ * A stub for the server function at `endpoint`. `kind` is `"query"` (GET, or POST for
24
+ * large arguments) or `"action"` (POST). The stub takes the input and an optional
25
+ * `{ signal }` to abort the call.
26
+ */
27
+ export function serverFunction(endpoint, kind) {
28
+ async function call(input, { signal } = {}) {
29
+ trackServerCall(endpoint); // a resource starting this call depends on it (invalidate)
30
+ const args = encode(input);
31
+ const init = { signal, credentials: "same-origin", redirect: "manual", headers: { accept: CONTENT_TYPE } };
32
+ const response = kind === "query" && args.length <= MAX_GET_ARGS
33
+ ? await fetch(`${endpoint}?a=${encodeURIComponent(args)}`, init)
34
+ : await fetch(endpoint, { ...init, method: "POST", headers: { ...init.headers, "content-type": CONTENT_TYPE }, body: args });
35
+ // A redirect (an auth guard sending to a login page, say) is not data: the caller decides.
36
+ if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) {
37
+ throw new ServerFunctionError("The server redirected the call", { status: response.status || 302, redirected: true });
38
+ }
39
+ if (response.ok) return decode(await response.text());
40
+ let body = null;
41
+ try {
42
+ body = await response.json();
43
+ } catch {
44
+ // a response without the JSON error body (a proxy, a middleware Response)
45
+ }
46
+ throw new ServerFunctionError(body?.error?.message ?? `Server function failed (${response.status})`, {
47
+ status: response.status, issues: body?.error?.issues,
48
+ });
49
+ }
50
+ // `invalidate(listTodos)` finds the resources that called this endpoint.
51
+ Object.defineProperty(call, "endpoint", { value: endpoint });
52
+ return call;
53
+ }
@@ -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 { middlewareScopeFromPath } from "./middleware.js";
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: compilePattern(route), module: routeModules[file], dynamic: route.includes("[") });
64
+ routes.push({ route, pattern: compileRoute(route), module: routeModules[file] });
105
65
  }
106
- // Static routes before dynamic, longer (more specific) before shorter, so the
107
- // most specific match wins deterministically regardless of discovery order.
108
- routes.sort((a, b) => a.dynamic - b.dynamic || b.route.length - a.route.length);
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") middleware.push({ scope: middlewareScopeFromPath(file, appDir), fn });
74
+ if (typeof fn === "function") {
75
+ const scope = middlewareScopeFromPath(file, appDir);
76
+ middleware.push({ scope, matcher: compileScope(scope), fn });
77
+ }
115
78
  }
116
- // Outermost (shortest scope) runs first, so `/api/_middleware` wraps `/api/users/_middleware`.
117
- middleware.sort((a, b) => a.scope.length - b.scope.length);
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
- for (const k in params) {
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
@@ -10,6 +10,7 @@ export * from "../core/errors.js";
10
10
  export * from "../core/context.js";
11
11
  export * from "../runtime/lifecycle.js";
12
12
  export { resource } from "../runtime/resource.js";
13
+ export { invalidate } from "../runtime/invalidate.js";
13
14
  export { copyText, copyWithFeedback } from "../runtime/clipboard.js";
14
15
 
15
16
  /** DOM-free built-in renderers used by the server compiler. */
@@ -33,6 +34,8 @@ export function registerRoutes(modules: Record<string, unknown>): void;
33
34
  export const router: {
34
35
  readonly pathname: string;
35
36
  readonly searchParams: URLSearchParams;
37
+ /** One string per name; a repeated name keeps its last value. Use
38
+ * `searchParams.getAll(name)` for every value. */
36
39
  readonly query: Record<string, string>;
37
40
  readonly params: RouteParams;
38
41
  readonly locale: string | null;
@@ -59,6 +62,8 @@ export function setRouteState(state?: {
59
62
  }): void;
60
63
  /** No-op on the server: there is no mounted app to navigate. */
61
64
  export function navigate(path: string, replace?: boolean): Promise<void>;
65
+ /** No-op on the server. */
66
+ export function prefetch(path: string): void;
62
67
  /** Always `false` during server rendering. */
63
68
  export function isHydrating(): boolean;
64
69
  export { emit } from "../runtime/events.js";
@@ -104,6 +109,8 @@ import type { RouteParams } from "./api.js";
104
109
  * Request under serve/dev and undefined at SSG prerender; `locals` is reserved. */
105
110
  export interface LoaderContext {
106
111
  params: RouteParams;
112
+ /** One string per name; a repeated name keeps its last value. For every value, read
113
+ * `new URL(request.url).searchParams.getAll(name)` (request servers only). */
107
114
  query: Record<string, string>;
108
115
  request?: Request;
109
116
  locale: string | null;
@@ -153,3 +160,51 @@ export function attr(name: string, value: unknown): string;
153
160
  export function ssgText(v: unknown): string;
154
161
  export function ssgList<T>(arr: T[], fn: (item: T, index: number) => string): string;
155
162
  export function ssgComponent(tag: string, props?: Record<string, unknown>, children?: unknown): string;
163
+
164
+ // ── Server functions (server-functions.js, docs/SERVER_FUNCTIONS.md) ───────────
165
+ /** A Standard Schema (https://standardschema.dev): zod, valibot, arktype… */
166
+ export interface StandardSchemaV1<Input = unknown, Output = Input> {
167
+ readonly "~standard": {
168
+ readonly version: 1;
169
+ readonly vendor: string;
170
+ readonly validate: (value: unknown) =>
171
+ | { value: Output; issues?: undefined }
172
+ | { issues: ReadonlyArray<{ message: string; path?: ReadonlyArray<PropertyKey | { key: PropertyKey }> }> }
173
+ | Promise<{ value: Output; issues?: undefined } | { issues: ReadonlyArray<{ message: string; path?: ReadonlyArray<PropertyKey | { key: PropertyKey }> }> }>;
174
+ readonly types?: { readonly input: Input; readonly output: Output };
175
+ };
176
+ }
177
+ type SchemaInput<S> = S extends StandardSchemaV1<infer I, any> ? I : never;
178
+ type SchemaOutput<S> = S extends StandardSchemaV1<any, infer O> ? O : never;
179
+
180
+ /** What a server function receives besides its input. */
181
+ export interface ServerFunctionContext {
182
+ request?: Request;
183
+ url?: URL;
184
+ /** What middleware stored, e.g. the authenticated user. */
185
+ locals: Record<string, unknown>;
186
+ env?: unknown;
187
+ ctx?: unknown;
188
+ }
189
+
190
+ /** A server function: called with its input (and, from server code, a context). */
191
+ export type ServerFunction<Input, Output> = (input: Input, context?: Partial<ServerFunctionContext>) => Promise<Awaited<Output>>;
192
+
193
+ /** A read: idempotent, callable with GET or POST. */
194
+ export function query<Output, Input = void>(fn: (input: Input, context: ServerFunctionContext) => Output): ServerFunction<Input, Output>;
195
+ export function query<S extends StandardSchemaV1, Output>(schema: S, fn: (input: SchemaOutput<S>, context: ServerFunctionContext) => Output): ServerFunction<SchemaInput<S>, Output>;
196
+ /** A write: POST only. */
197
+ export function action<Output, Input = void>(fn: (input: Input, context: ServerFunctionContext) => Output): ServerFunction<Input, Output>;
198
+ export function action<S extends StandardSchemaV1, Output>(schema: S, fn: (input: SchemaOutput<S>, context: ServerFunctionContext) => Output): ServerFunction<SchemaInput<S>, Output>;
199
+ /** `"query"`, `"action"`, or null for anything else. */
200
+ export function serverFunctionKind(value: unknown): "query" | "action" | null;
201
+ /** The input did not match the function's schema. */
202
+ export class ValidationError extends Error {
203
+ issues: Array<{ message: string; path?: PropertyKey[] }>;
204
+ }
205
+ /** The handler for server function requests, from the build's `{ endpoint: fn }` map. */
206
+ export function createServerFunctions(
207
+ endpoints: Record<string, ServerFunction<any, any>>,
208
+ /** Limits on decoded input: body size (default 1 MiB) and nesting depth (default 64). */
209
+ options?: { maxBodyBytes?: number; maxDepth?: number },
210
+ ): { size: number; handle(request: Request, context?: { locals?: Record<string, unknown>; env?: unknown; ctx?: unknown }): Promise<Response | null> };
package/server/index.js CHANGED
@@ -9,6 +9,8 @@ export * from "../core/errors.js";
9
9
  export * from "../core/context.js";
10
10
  export * from "../runtime/lifecycle.js";
11
11
  export { resource } from "../runtime/resource.js";
12
+ export { invalidate } from "../runtime/invalidate.js";
13
+ export { ServerFunctionError, serverFunction } from "../runtime/server-function.js";
12
14
  export { copyText, copyWithFeedback } from "../runtime/clipboard.js";
13
15
  export { Link, ContextProvider, Portal, ErrorBoundary, RawHtml, CodeFence } from "./builtins.js";
14
16
  export * from "./head.js";
@@ -20,7 +22,7 @@ export * from "./render.js";
20
22
  export {
21
23
  registerRoutes, router, matchRoute, configureI18n, i18nLocales,
22
24
  resolveLocale, localizePath, shouldInterceptNav,
23
- setLocale, setRouteState, setRouteToc, navigate,
25
+ setLocale, setRouteState, setRouteToc, navigate, prefetch,
24
26
  } from "../runtime/router.js";
25
27
  export { isHydrating } from "../runtime/hydrate.js";
26
28
  export { emit } from "../runtime/events.js";
@@ -28,4 +30,5 @@ export * from "./api.js";
28
30
  export { createMiddleware } from "./middleware.js";
29
31
  export * from "./cookies.js";
30
32
  export * from "./loader.js";
33
+ export { ValidationError, action, createServerFunctions, query, serverFunctionKind } from "./server-functions.js";
31
34
  import "./builtins.js";
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: compilePattern(route), fn, dynamic: route.includes("[") });
84
+ entries.push({ route, pattern: compileRoute(route), fn });
116
85
  }
117
- // Static before dynamic, longer before shorter — most specific wins (see api.js).
118
- entries.sort((a, b) => a.dynamic - b.dynamic || b.route.length - a.route.length);
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
- const params = { ...(m.groups || {}) };
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
  }