@opentf/afw 0.34.0 → 0.36.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.
@@ -4,6 +4,8 @@ export interface LinkProps {
4
4
  children?: unknown;
5
5
  class?: JSX.IntrinsicElements["a"]["class"];
6
6
  reload?: boolean | "";
7
+ /** Warm the route ahead of a click: `"intent"` (default: hover, focus, touch), `"viewport"`, or `false`. */
8
+ prefetch?: "intent" | "viewport" | "none" | boolean;
7
9
  ariaLabel?: string;
8
10
  ariaCurrent?: string;
9
11
  "aria-label"?: string;
@@ -9,7 +9,13 @@
9
9
  // `class` is a declared prop, so it lands on the rendered <a> (the link), not on
10
10
  // the <afw-link> host — no duplicated styling.
11
11
 
12
- import { localizePath, navigate, shouldInterceptNav } from "../runtime/router.js";
12
+ import { onMount } from "../runtime/lifecycle.js";
13
+ import { localizePath, navigate, prefetch, shouldInterceptNav } from "../runtime/router.js";
14
+
15
+ // `prefetch`: "intent" (default) warms the route on hover, focus or touch; "viewport"
16
+ // when the link scrolls into view; `false` / "none" never.
17
+ const prefetchMode = (value) =>
18
+ value === false || value === "false" || value === "none" ? "none" : value === "viewport" ? "viewport" : "intent";
13
19
 
14
20
  export default function Link(props) {
15
21
  const href = props.href;
@@ -25,6 +31,23 @@ export default function Link(props) {
25
31
  const forceReload = reload != null && reload !== false;
26
32
  const ariaLabel = props["aria-label"] || props.ariaLabel;
27
33
  const ariaCurrent = props["aria-current"] || props.ariaCurrent;
34
+ const mode = prefetchMode(props.prefetch);
35
+ const canPrefetch = () => mode !== "none" && !forceReload && shouldInterceptNav();
36
+ const warm = () => {
37
+ if (canPrefetch()) prefetch(target);
38
+ };
39
+ let anchor = $ref();
40
+ onMount(() => {
41
+ if (mode !== "viewport" || typeof IntersectionObserver === "undefined" || !anchor) return;
42
+ const observer = new IntersectionObserver((entries) => {
43
+ if (entries.some((entry) => entry.isIntersecting)) {
44
+ observer.disconnect();
45
+ warm();
46
+ }
47
+ });
48
+ observer.observe(anchor);
49
+ return () => observer.disconnect();
50
+ });
28
51
 
29
52
  const onclick = (e) => {
30
53
  // Let the browser handle modified clicks (new tab, etc.) and non-primary buttons.
@@ -47,6 +70,10 @@ export default function Link(props) {
47
70
  aria-label={ariaLabel}
48
71
  aria-current={ariaCurrent}
49
72
  onclick={onclick}
73
+ onpointerenter={mode === "intent" ? warm : undefined}
74
+ onfocus={mode === "intent" ? warm : undefined}
75
+ ontouchstart={mode === "intent" ? warm : undefined}
76
+ ref={anchor}
50
77
  >
51
78
  {props.children}
52
79
  </a>
@@ -0,0 +1,30 @@
1
+ // The wire encoding of server function arguments and results, shared by the browser
2
+ // stub and the server registry: @opentf/serialize's `{ v, $refs }` envelope, which
3
+ // round-trips Date, Map, Set, BigInt, URL, RegExp, Error, typed arrays, undefined,
4
+ // NaN/±Infinity/-0, Temporal and shared or cyclic references, while plain data stays
5
+ // readable JSON. Functions, symbols and class instances are refused.
6
+
7
+ import { SerializeError, parse, stringify } from "@opentf/serialize";
8
+
9
+ export { SerializeError };
10
+
11
+ export const CONTENT_TYPE = "application/json";
12
+
13
+ /** Deepest nesting accepted from a request (`[[1]]` is depth 2). */
14
+ export const MAX_DEPTH = 64;
15
+
16
+ /** Encode a value for the wire. */
17
+ export function encode(value) {
18
+ return stringify(value);
19
+ }
20
+
21
+ /**
22
+ * Decode a wire value. An empty text is `undefined` (a call without arguments).
23
+ * `maxLength` / `maxDepth` bound untrusted input; failures throw a `SerializeError`
24
+ * with a `code` (`INPUT_TOO_LARGE`, `INVALID_JSON`, `INVALID_ENVELOPE`, …). A
25
+ * `__proto__` key stays an own property, never a prototype.
26
+ */
27
+ export function decode(text, { maxLength = Infinity, maxDepth = Infinity } = {}) {
28
+ if (text === "") return undefined;
29
+ return parse(text, { maxLength, maxDepth });
30
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opentf/afw",
3
- "version": "0.34.0",
3
+ "version": "0.36.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": {
@@ -65,5 +65,8 @@
65
65
  "publishConfig": {
66
66
  "access": "public"
67
67
  },
68
- "types": "./index.d.ts"
68
+ "types": "./index.d.ts",
69
+ "dependencies": {
70
+ "@opentf/serialize": "^0.1.0"
71
+ }
69
72
  }
package/runtime/hmr.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // caches lifecycle callbacks at define time, so stable callbacks dispatch to the
5
5
  // current implementation rather than redefining an existing tag.
6
6
  import { scope } from "../core/signals.js";
7
+ import { collectHotState, takeHotState, withHotCarry } from "./hot-carry.js";
7
8
  import { refreshHotRoute } from "./router.js";
8
9
 
9
10
  const components = new Map();
@@ -93,6 +94,12 @@ export function registerHotRoute(hot, factory, shape = "", exports = "", data =
93
94
  }
94
95
 
95
96
  export function hotState(host, key, create) {
97
+ // A new element built by a refresh picks up the state of the one it replaces.
98
+ if (!host.__afwHotCarried) {
99
+ host.__afwHotCarried = true;
100
+ const carried = takeHotState(host);
101
+ if (carried) host._hotState = carried;
102
+ }
96
103
  const slots = host._hotState ??= new Map();
97
104
  if (!slots.has(key)) slots.set(key, create());
98
105
  return slots.get(key);
@@ -114,13 +121,17 @@ function refresh(record, hosts) {
114
121
  const focusId = host.contains(focused) ? focused.id : null;
115
122
  const selection = focusId && typeof focused.selectionStart === "number"
116
123
  ? [focused.selectionStart, focused.selectionEnd] : null;
124
+ // Components this one renders get new elements; carry their state across. Its
125
+ // slotted children are moved, not rebuilt, so they keep theirs anyway.
126
+ const slotted = host._hotChildren || [];
127
+ const carried = collectHotState([...host.children], slotted);
117
128
  cleanup(host);
118
129
  host._mounted = false;
119
130
  host._hotRefreshing = true;
120
131
  // Slotted children belong to the parent. Keep the original capture and move
121
132
  // those nodes into the new view in the same task (no genuine disconnect).
122
- host.replaceChildren(...(host._hotChildren || []));
123
- try { record.connected?.call(host); }
133
+ host.replaceChildren(...slotted);
134
+ try { withHotCarry(carried, () => record.connected?.call(host)); }
124
135
  finally { host._hotRefreshing = false; }
125
136
  if (focusId) {
126
137
  const target = document.getElementById(focusId);
@@ -0,0 +1,52 @@
1
+ // Development refresh: component state carried across a rebuilt view.
2
+ //
3
+ // A page, layout or component refresh rebuilds its view, so the components it renders
4
+ // get new elements, and a new element starts with empty `$state`. Before the rebuild,
5
+ // the state of the elements about to be replaced is collected per tag, in document
6
+ // order; while the new view connects, each new element of that tag takes the next
7
+ // one (`hotState` in hmr.js). Matching by tag and position is how a component keeps
8
+ // its count when only the text around it was edited.
9
+ //
10
+ // Only refresh code calls `beginHotCarry`, so outside a refresh this is inert.
11
+
12
+ let carry = null;
13
+
14
+ const isHost = (el) => el?._hotState instanceof Map;
15
+
16
+ /**
17
+ * Collect the state of every component element under `roots` (document order),
18
+ * skipping the subtrees in `keep`: nodes the rebuild moves rather than recreates
19
+ * (a layout's page, a component's slotted children).
20
+ */
21
+ export function collectHotState(roots, keep = []) {
22
+ const queues = new Map();
23
+ const kept = (el) => keep.some((node) => node === el || node.contains?.(el));
24
+ const add = (el) => {
25
+ if (!isHost(el) || kept(el)) return;
26
+ if (!queues.has(el.localName)) queues.set(el.localName, []);
27
+ queues.get(el.localName).push(el._hotState);
28
+ };
29
+ for (const root of roots) {
30
+ if (root?.nodeType !== 1) continue;
31
+ add(root);
32
+ for (const el of root.querySelectorAll("*")) add(el);
33
+ }
34
+ return queues;
35
+ }
36
+
37
+ /** Run `build` with `queues` available to the elements it connects. */
38
+ export function withHotCarry(queues, build) {
39
+ const outer = carry;
40
+ carry = queues.size ? queues : null;
41
+ try {
42
+ return build();
43
+ } finally {
44
+ carry = outer;
45
+ }
46
+ }
47
+
48
+ /** The carried state for a newly connected `host`, or undefined. */
49
+ export function takeHotState(host) {
50
+ const queue = carry?.get(host.localName);
51
+ return queue?.length ? queue.shift() : undefined;
52
+ }
@@ -6,6 +6,8 @@ export * from "./lifecycle.js";
6
6
  export * from "./router.js";
7
7
  export * from "./route-data.js";
8
8
  export * from "./resource.js";
9
+ export { invalidate } from "./invalidate.js";
10
+ export { ServerFunctionError, serverFunction } from "./server-function.js";
9
11
  export * from "./context.js";
10
12
  export * from "./error-boundary.js";
11
13
  export * from "./portal.js";
package/runtime/index.js CHANGED
@@ -16,6 +16,8 @@ export * from "./lifecycle.js";
16
16
  export * from "./router.js";
17
17
  export * from "./route-data.js";
18
18
  export * from "./resource.js";
19
+ export { invalidate } from "./invalidate.js";
20
+ export { ServerFunctionError, serverFunction } from "./server-function.js";
19
21
  export * from "./context.js";
20
22
  export * from "./error-boundary.js";
21
23
  export * from "./portal.js";
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Refetch the live resources that called any of `fns` (server functions imported from a
3
+ * `.server` module). With no arguments: every live resource, and the current page's
4
+ * loader data. Browser only; resolves at once on the server.
5
+ */
6
+ export function invalidate(...fns: Array<(...args: any[]) => unknown>): Promise<void>;
@@ -0,0 +1,89 @@
1
+ // `invalidate()` — refetch the data server functions produced (docs/SERVER_FUNCTIONS.md
2
+ // §3.8). After an action changes data, the views that show it refetch:
3
+ //
4
+ // const todos = resource(() => listTodos({ done: false }));
5
+ // await addTodo({ title });
6
+ // invalidate(listTodos); // every live resource that called listTodos refetches
7
+ // invalidate(); // every live resource, and the current page's loader data
8
+ //
9
+ // A resource records the server functions its fetcher calls while it starts (the
10
+ // synchronous part, which is where `() => listTodos(args)` calls them). A fetcher
11
+ // that calls one after an `await` names it with `resource(fn, { invalidatedBy: [...] })`.
12
+ //
13
+ // Browser only: on the server nothing is live, and `invalidate()` resolves at once.
14
+
15
+ const byEndpoint = new Map(); // endpoint → Set of live resource entries
16
+ const live = new Set(); // every live resource entry
17
+ let tracking = null; // endpoints called while a fetcher starts
18
+ let refreshRoute = null; // the router's loader-data reload, once an app is mounted
19
+
20
+ /** Record a server function call by the fetcher that is starting (the browser stub). */
21
+ export function trackServerCall(endpoint) {
22
+ tracking?.add(endpoint);
23
+ }
24
+
25
+ /** Run `start` and return its result with the server function endpoints it called. */
26
+ export function withTracking(start) {
27
+ const previous = tracking;
28
+ const endpoints = new Set();
29
+ tracking = endpoints;
30
+ try {
31
+ return { result: start(), endpoints };
32
+ } finally {
33
+ tracking = previous;
34
+ }
35
+ }
36
+
37
+ /** The endpoint of a browser stub (or an endpoint string), else null. */
38
+ export function endpointOf(fn) {
39
+ if (typeof fn === "string") return fn;
40
+ return typeof fn === "function" && typeof fn.endpoint === "string" ? fn.endpoint : null;
41
+ }
42
+
43
+ /** A live resource `entry` (`{ refetch }`) now depends on `endpoints`. */
44
+ export function registerResource(entry, endpoints) {
45
+ unregisterResource(entry);
46
+ entry.endpoints = endpoints;
47
+ live.add(entry);
48
+ for (const endpoint of endpoints) {
49
+ let set = byEndpoint.get(endpoint);
50
+ if (!set) byEndpoint.set(endpoint, (set = new Set()));
51
+ set.add(entry);
52
+ }
53
+ }
54
+
55
+ /** A resource stopped (paused or disposed). */
56
+ export function unregisterResource(entry) {
57
+ live.delete(entry);
58
+ for (const endpoint of entry.endpoints ?? []) {
59
+ const set = byEndpoint.get(endpoint);
60
+ set?.delete(entry);
61
+ if (set?.size === 0) byEndpoint.delete(endpoint);
62
+ }
63
+ entry.endpoints = undefined;
64
+ }
65
+
66
+ /** The router's hook for reloading the current page's loader data (`mountApp`). */
67
+ export function setRouteDataRefresher(fn) {
68
+ refreshRoute = fn;
69
+ }
70
+
71
+ /**
72
+ * Refetch the live resources that called any of `fns` (server functions, as imported
73
+ * from a `.server` module). With no arguments: every live resource, and the current
74
+ * page's loader data. Resolves when the refetches settle.
75
+ */
76
+ export async function invalidate(...fns) {
77
+ if (typeof document === "undefined") return;
78
+ if (fns.length === 0) {
79
+ await Promise.all([...[...live].map((entry) => entry.refetch()), refreshRoute?.()]);
80
+ return;
81
+ }
82
+ const targets = new Set();
83
+ for (const fn of fns) {
84
+ const endpoint = endpointOf(fn);
85
+ if (!endpoint) throw new TypeError("invalidate() takes server functions imported from a .server module");
86
+ for (const entry of byEndpoint.get(endpoint) ?? []) targets.add(entry);
87
+ }
88
+ await Promise.all([...targets].map((entry) => entry.refetch()));
89
+ }
@@ -4,6 +4,12 @@ export interface Resource<T> {
4
4
  readonly error: unknown;
5
5
  refetch(): Promise<T | undefined> | undefined;
6
6
  }
7
- export function resource<T>(fetcher: (value: true, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: { initial?: T }): Resource<T>;
8
- export function resource<S, T>(source: () => S, fetcher: (value: NonNullable<Exclude<S, false>>, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: { initial?: T }): Resource<T>;
7
+ export interface ResourceOptions<T> {
8
+ /** Seeds `data` before the first resolution. */
9
+ initial?: T;
10
+ /** Server functions whose `invalidate()` refetches this resource, beyond those its fetcher calls as it starts. */
11
+ invalidatedBy?: Array<(...args: any[]) => unknown>;
12
+ }
13
+ export function resource<T>(fetcher: (value: true, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
14
+ export function resource<S, T>(source: () => S, fetcher: (value: NonNullable<Exclude<S, false>>, context: { signal: AbortSignal | undefined }) => T | Promise<T>, options?: ResourceOptions<T>): Resource<T>;
9
15
  export function __setResourceServer(value: boolean | null): void;
@@ -22,6 +22,7 @@
22
22
  // hydration adoption aligned.
23
23
 
24
24
  import { batch, effect, signal, untracked } from "../core/signals.js";
25
+ import { endpointOf, registerResource, unregisterResource, withTracking } from "./invalidate.js";
25
26
 
26
27
  // Test override: the DOM suites run in esdev's `--dom` realm (a `document`
27
28
  // always exists), so server behavior is opted into explicitly.
@@ -44,8 +45,10 @@ const isServer = () => serverOverride ?? typeof document === "undefined";
44
45
  * @param {Function} source reactive source read inside the tracking effect; its
45
46
  * value is passed to the fetcher.
46
47
  * @param {Function} fetcher `(sourceValue, { signal }) => data | Promise<data>`.
47
- * @param {{ initial?: unknown }} [options] `initial` seeds `data` before the
48
- * first resolution.
48
+ * @param {{ initial?: unknown, invalidatedBy?: Function[] }} [options] `initial`
49
+ * seeds `data` before the first resolution. `invalidatedBy` names server
50
+ * functions whose `invalidate()` refetches this resource, beyond those its
51
+ * fetcher calls as it starts (which are recorded automatically).
49
52
  * @returns {{ data: unknown, loading: boolean, error: unknown,
50
53
  * refetch: () => Promise<unknown> | undefined }} reactive getters —
51
54
  * read them inside bindings/effects to subscribe.
@@ -62,6 +65,9 @@ export function resource(source, fetcher, options = {}) {
62
65
  const loading = signal(true); // a fetch is intended; the server leaves it true
63
66
  let token = 0;
64
67
  let controller = null;
68
+ // This resource in the `invalidate()` registry (runtime/invalidate.js).
69
+ const entry = { refetch: () => refetch() };
70
+ const named = (options.invalidatedBy ?? []).map(endpointOf).filter(Boolean);
65
71
 
66
72
  function run(value) {
67
73
  controller?.abort();
@@ -75,7 +81,11 @@ export function resource(source, fetcher, options = {}) {
75
81
  });
76
82
  // The async IIFE starts the fetcher *synchronously* (no wasted microtask)
77
83
  // while converting a synchronous throw into a rejection.
78
- return (async () => fetcher(value, { signal: c?.signal }))()
84
+ // Started under tracking: the server functions the fetcher calls register it.
85
+ const { result, endpoints } = withTracking(() => (async () => fetcher(value, { signal: c?.signal }))());
86
+ for (const endpoint of named) endpoints.add(endpoint);
87
+ registerResource(entry, endpoints);
88
+ return result
79
89
  .then(
80
90
  (v) => {
81
91
  if (t !== token) return; // superseded — a newer run owns the signals
@@ -107,6 +117,7 @@ export function resource(source, fetcher, options = {}) {
107
117
  controller = null;
108
118
  loading.value = false;
109
119
  });
120
+ unregisterResource(entry);
110
121
  return;
111
122
  }
112
123
  untracked(() => run(value));
@@ -115,10 +126,17 @@ export function resource(source, fetcher, options = {}) {
115
126
  return () => {
116
127
  token++;
117
128
  controller?.abort();
129
+ unregisterResource(entry);
118
130
  };
119
131
  });
120
132
  }
121
133
 
134
+ function refetch() {
135
+ const value = untracked(src);
136
+ if (value == null || value === false) return undefined;
137
+ return run(value);
138
+ }
139
+
122
140
  return {
123
141
  get data() {
124
142
  return data.value;
@@ -130,10 +148,6 @@ export function resource(source, fetcher, options = {}) {
130
148
  return error.value;
131
149
  },
132
150
  /** Re-run the fetcher with the current source value (no-op while paused). */
133
- refetch() {
134
- const value = untracked(src);
135
- if (value == null || value === false) return undefined;
136
- return run(value);
137
- },
151
+ refetch,
138
152
  };
139
153
  }
@@ -13,3 +13,12 @@ export function readInlineRouteData(): any;
13
13
  export function __resetInlineRouteData(): void;
14
14
  /** The reserved per-route data filename/URL suffix (`/todos` → `/todos/__data.json`). */
15
15
  export const DATA_FILE: "__data.json";
16
+ /** The header the data endpoint sets when a loader redirected. */
17
+ export const REDIRECT_HEADER: "x-afw-redirect";
18
+ /** Returned by `fetchRouteData` in place of data when the route redirects. */
19
+ export class RouteRedirect {
20
+ constructor(location: string, options?: { reload?: boolean });
21
+ redirect: string;
22
+ /** A full page load is needed (the server redirected the data request itself). */
23
+ reload: boolean;
24
+ }
@@ -25,13 +25,36 @@ export function dataUrlFor(pathname, search = "") {
25
25
  return (path === "/" ? `/${DATA_FILE}` : `${path}/${DATA_FILE}`) + (search || "");
26
26
  }
27
27
 
28
+ /** The header the data endpoint sets when a loader redirected (`throw redirect`). */
29
+ export const REDIRECT_HEADER = "x-afw-redirect";
30
+
31
+ /**
32
+ * What `fetchRouteData` returns instead of data when the route redirects:
33
+ * `{ redirect: "/login", reload: false }`. `reload` asks for a full page load, for a
34
+ * redirect the browser hid (middleware redirecting the data request itself).
35
+ */
36
+ export class RouteRedirect {
37
+ constructor(location, { reload = false } = {}) {
38
+ this.redirect = location;
39
+ this.reload = reload;
40
+ }
41
+ }
42
+
28
43
  /**
29
44
  * Fetch a route's loader data. 200 → the parsed JSON; 404 → `undefined` (no
30
- * loader / `notFound()`); anything else throws (the router reports it and
31
- * commits the navigation with no data).
45
+ * loader / `notFound()`); a redirect → a {@link RouteRedirect}; anything else throws
46
+ * (the router reports it and commits the navigation with no data).
32
47
  */
33
48
  export async function fetchRouteData(pathname, search = "") {
34
- const res = await fetch(dataUrlFor(pathname, search));
49
+ // "manual": a redirect is not data. Following it would fetch an HTML page.
50
+ const res = await fetch(dataUrlFor(pathname, search), { redirect: "manual" });
51
+ const location = res.headers.get(REDIRECT_HEADER);
52
+ if (location) return new RouteRedirect(location); // the loader redirected
53
+ // Middleware redirected the data request (an auth guard): the target is hidden
54
+ // from fetch, so load the page itself and let the server redirect it.
55
+ if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
56
+ return new RouteRedirect(pathname + search, { reload: true });
57
+ }
35
58
  if (res.status === 404) return undefined;
36
59
  if (!res.ok) throw new Error(`route data request for ${pathname} failed (${res.status})`);
37
60
  return res.json();
@@ -105,6 +105,10 @@ export function matchRoute(pathname: any): {
105
105
  * updates window.history.
106
106
  */
107
107
  export function navigate(path: any, replace?: boolean, isPop?: boolean, hydrate?: boolean): Promise<void>;
108
+ /** Warm a route: load its page and layout chunks and its loader data, reused by the navigation. */
109
+ export function prefetch(path: string): void;
110
+ /** Reload the current page's loader data into `router.data`. */
111
+ export function refreshRouteData(): Promise<void>;
108
112
  export function refreshHotRoute(factory: any): Promise<void>;
109
113
  /**
110
114
  * Bootstrap the application: register routes, wire history, and render the page
package/runtime/router.js CHANGED
@@ -20,8 +20,10 @@ 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
- import { fetchRouteData, readInlineRouteData } from "./route-data.js";
25
+ import { RouteRedirect, fetchRouteData, readInlineRouteData } from "./route-data.js";
26
+ import { setRouteDataRefresher } from "./invalidate.js";
25
27
  import { compareRoutes, compileRoute, decodeParams } from "./route-match.js";
26
28
 
27
29
  const isBrowser = typeof window !== "undefined";
@@ -417,6 +419,84 @@ function rankedPages() {
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
+ /** Go where a loader (or the server) redirected a navigation. */
475
+ function followRedirect(target) {
476
+ if (target.reload) {
477
+ window.location.assign(target.redirect);
478
+ return;
479
+ }
480
+ return navigate(target.redirect, true);
481
+ }
482
+
483
+ export async function refreshRouteData() {
484
+ prefetched.clear();
485
+ if (!isBrowser || !rootEl) return;
486
+ const pathname = state.pathname.value;
487
+ const match = matchRoute(pathname);
488
+ if (!match?.route || !routes.loaderRoutes.has(match.route)) return;
489
+ const seq = navSeq;
490
+ try {
491
+ const data = await fetchRouteData(pathname, window.location.search);
492
+ if (seq !== navSeq) return; // a navigation since owns the data
493
+ if (data instanceof RouteRedirect) return followRedirect(data);
494
+ state.data.value = data;
495
+ } catch (e) {
496
+ reportError(e, { phase: "data", path: pathname });
497
+ }
498
+ }
499
+
420
500
  // --- Stale-chunk recovery ---------------------------------------------------
421
501
  // Pages/layouts are code-split, so a route is loaded by a lazy `() => import(...)`
422
502
  // at navigation time. Asset filenames are content-hashed (`layout-DmM9YRKj.js`),
@@ -553,11 +633,13 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
553
633
  data = readInlineRouteData();
554
634
  } else {
555
635
  try {
556
- data = await fetchRouteData(url.pathname, url.search);
636
+ const warmed = takePrefetched(url.pathname + url.search);
637
+ data = warmed ? await warmed.catch(() => fetchRouteData(url.pathname, url.search)) : await fetchRouteData(url.pathname, url.search);
557
638
  } catch (e) {
558
639
  reportError(e, { phase: "data", path: url.pathname });
559
640
  }
560
641
  if (seq !== navSeq) return; // a newer navigation superseded this one
642
+ if (data instanceof RouteRedirect) return followRedirect(data);
561
643
  }
562
644
  }
563
645
 
@@ -710,10 +792,15 @@ export async function refreshHotRoute(factory, data = null) {
710
792
  const layouts = layoutModules.map((module, i) => (index === layoutModules.length - i ? fresh(module) : namespace(module)));
711
793
  // An edited page may have new headings: publish them before the view rebuilds.
712
794
  setRouteToc(page);
713
- node = buildScopedView(() => factory(props, previous));
714
795
  const old = viewNodes(previous);
715
796
  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]);
797
+ // Components the rebuilt view renders get new elements, which connect on insert;
798
+ // carry their state across. A layout's page is moved, not rebuilt.
799
+ const carried = collectHotState(old, inner ? viewNodes(inner) : []);
800
+ withHotCarry(carried, () => {
801
+ node = buildScopedView(() => factory(props, previous));
802
+ old[0].parentNode.insertBefore(node, old[0]);
803
+ });
717
804
  for (const n of old) n.remove();
718
805
  runCleanup(previous);
719
806
  currentNodes = currentNodes.map((current, i) => (i === index ? node : current));
@@ -767,6 +854,8 @@ export function mountApp({ pages, target, guard: g, i18n, nav, loaders } = {}) {
767
854
  if (pages) registerRoutes(pages);
768
855
  if (loaders) registerLoaderRoutes(loaders);
769
856
  guard = g || null;
857
+ setRouteDataRefresher(refreshRouteData);
858
+ prefetched.clear(); // a fresh app starts with nothing warmed
770
859
  // In MPA mode the browser owns navigation (full loads push real history entries),
771
860
  // so there is no client-side history to react to — only wire popstate for SPA.
772
861
  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
+ }
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. */
@@ -61,6 +62,8 @@ export function setRouteState(state?: {
61
62
  }): void;
62
63
  /** No-op on the server: there is no mounted app to navigate. */
63
64
  export function navigate(path: string, replace?: boolean): Promise<void>;
65
+ /** No-op on the server. */
66
+ export function prefetch(path: string): void;
64
67
  /** Always `false` during server rendering. */
65
68
  export function isHydrating(): boolean;
66
69
  export { emit } from "../runtime/events.js";
@@ -157,3 +160,51 @@ export function attr(name: string, value: unknown): string;
157
160
  export function ssgText(v: unknown): string;
158
161
  export function ssgList<T>(arr: T[], fn: (item: T, index: number) => string): string;
159
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
@@ -155,6 +155,13 @@ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {})
155
155
  return new Response(method === "HEAD" ? null : json || "null", { status: 200, headers });
156
156
  } catch (e) {
157
157
  if (isNotFound(e)) return new Response("null", { status: 404, headers });
158
+ if (e instanceof Response) {
159
+ // A redirect is answered as data the router follows: fetch() would follow a
160
+ // real 3xx to an HTML page. Any other thrown Response (401, 403…) passes through.
161
+ const location = e.status >= 300 && e.status < 400 ? e.headers.get("location") : null;
162
+ if (location) return new Response("null", { status: 200, headers: { ...headers, "x-afw-redirect": location } });
163
+ return e;
164
+ }
158
165
  console.error(`✗ loader ${pagePath}:`, e?.stack ?? e);
159
166
  return Response.json({ error: "Internal Server Error" }, { status: 500 });
160
167
  }
@@ -0,0 +1,138 @@
1
+ // Server functions (docs/SERVER_FUNCTIONS.md): `query()` and `action()` exports of
2
+ // `*.server.{js,ts}` modules, callable from the browser through a generated stub and
3
+ // directly from other server code.
4
+ //
5
+ // export const listTodos = query(async (args, { locals }) => db.list(locals.user));
6
+ // export const addTodo = action(schema, async (input, context) => db.insert(input));
7
+ //
8
+ // The build gives each function an endpoint under its folder (`/todos/__fn/<id>`), so
9
+ // that folder's `_middleware` guards it like a page. `createServerFunctions` turns the
10
+ // build's `{ endpoint: fn }` map into a handler for those requests.
11
+
12
+ import { CONTENT_TYPE, MAX_DEPTH, SerializeError, decode, encode } from "../core/fn-codec.js";
13
+ import { isNotFound } from "./loader.js";
14
+
15
+ const MARK = Symbol.for("afw.serverFunction");
16
+
17
+ /** Thrown to the caller when the input does not match the function's schema. */
18
+ export class ValidationError extends Error {
19
+ constructor(issues) {
20
+ super("Invalid input");
21
+ this.name = "ValidationError";
22
+ this.issues = issues;
23
+ }
24
+ }
25
+
26
+ const isSchema = (value) => typeof value?.["~standard"]?.validate === "function";
27
+
28
+ /** Validate `input` with a Standard Schema (https://standardschema.dev) schema. */
29
+ async function validate(schema, input) {
30
+ if (!schema) return input;
31
+ const result = await schema["~standard"].validate(input);
32
+ if (result.issues) throw new ValidationError(result.issues.map((i) => ({ message: i.message, path: i.path?.map((p) => (typeof p === "object" ? p.key : p)) })));
33
+ return result.value;
34
+ }
35
+
36
+ function define(kind, args) {
37
+ const [schema, handler] = args.length >= 2 ? args : [undefined, args[0]];
38
+ if (schema !== undefined && !isSchema(schema)) {
39
+ throw new TypeError(`${kind}(schema, fn): the schema must implement Standard Schema (zod, valibot, arktype…)`);
40
+ }
41
+ if (typeof handler !== "function") throw new TypeError(`${kind}(): the last argument must be a function`);
42
+ // Called directly from server code (a loader, an API route, another function): run it
43
+ // with the given context, input validated the same way as over HTTP.
44
+ const fn = async (input, context = {}) => handler(await validate(schema, input), context);
45
+ Object.defineProperty(fn, MARK, { value: { kind, schema, handler } });
46
+ return fn;
47
+ }
48
+
49
+ /** A read: idempotent, callable with GET or POST. `query(fn)` or `query(schema, fn)`. */
50
+ export function query(...args) {
51
+ return define("query", args);
52
+ }
53
+
54
+ /** A write: POST only. `action(fn)` or `action(schema, fn)`. */
55
+ export function action(...args) {
56
+ return define("action", args);
57
+ }
58
+
59
+ /** The kind of a server function export (`"query"` | `"action"`), or null. */
60
+ export function serverFunctionKind(value) {
61
+ return (typeof value === "function" && value[MARK]?.kind) || null;
62
+ }
63
+
64
+ const json = (status, body, headers = {}) =>
65
+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store", ...headers } });
66
+
67
+ // A cross-site request carrying the user's cookies must not reach an endpoint. Browsers
68
+ // send `Origin` on POST and `Sec-Fetch-Site` on every request; a client that sends
69
+ // neither is not a browser, so it cannot be forging a user's request.
70
+ function crossSite(request, url) {
71
+ const origin = request.headers.get("origin");
72
+ if (origin) return origin !== url.origin;
73
+ const site = request.headers.get("sec-fetch-site");
74
+ return site != null && site !== "same-origin" && site !== "none";
75
+ }
76
+
77
+ /**
78
+ * The handler for server function requests.
79
+ *
80
+ * @param {Record<string, Function>} endpoints `{ "/todos/__fn/<id>": listTodos }`, built
81
+ * by the toolchain from the app's `*.server` modules.
82
+ * @param {{ maxBodyBytes?: number, maxDepth?: number }} [options] limits on the decoded
83
+ * input: body size (default 1 MiB) and nesting depth (default 64)
84
+ * @returns {{ size: number, handle: (request: Request, context?: object) => Promise<Response | null> }}
85
+ * `handle` answers a request for one of the endpoints, or returns null. `context` is
86
+ * what middleware built (`locals`, `env`, `ctx`).
87
+ */
88
+ export function createServerFunctions(endpoints = {}, { maxBodyBytes = 1024 * 1024, maxDepth = MAX_DEPTH } = {}) {
89
+ const limits = { maxLength: maxBodyBytes, maxDepth };
90
+ const table = new Map();
91
+ for (const [path, fn] of Object.entries(endpoints)) {
92
+ const kind = serverFunctionKind(fn);
93
+ if (!kind) throw new TypeError(`${path}: not a query() or action()`);
94
+ table.set(path, { kind, fn });
95
+ }
96
+
97
+ async function handle(request, context = {}) {
98
+ const url = new URL(request.url);
99
+ const entry = table.get(url.pathname);
100
+ if (!entry) return null;
101
+ const method = request.method.toUpperCase();
102
+ const allowed = entry.kind === "query" ? "GET, POST" : "POST";
103
+ if (!allowed.split(", ").includes(method)) return json(405, { error: { message: "Method not allowed" } }, { allow: allowed });
104
+ if (crossSite(request, url)) return json(403, { error: { message: "Cross-site request refused" } });
105
+
106
+ let input;
107
+ try {
108
+ if (method === "GET") {
109
+ input = decode(url.searchParams.get("a") ?? "", limits);
110
+ } else {
111
+ const type = request.headers.get("content-type") ?? "";
112
+ // Forms and plain-text posts can be sent cross-site without a preflight; JSON cannot.
113
+ if (!type.startsWith(CONTENT_TYPE)) return json(415, { error: { message: `Expected ${CONTENT_TYPE}` } });
114
+ input = decode(await request.text(), limits);
115
+ }
116
+ } catch (error) {
117
+ if (error instanceof SerializeError && error.code === "INPUT_TOO_LARGE") {
118
+ return json(413, { error: { message: "Request body too large" } });
119
+ }
120
+ return json(400, { error: { message: "Malformed request body" } });
121
+ }
122
+
123
+ const ctx = { request, url, locals: context.locals ?? {}, env: context.env, ctx: context.ctx };
124
+ try {
125
+ const result = await entry.fn(input, ctx);
126
+ // A result the codec refuses (a class instance, a function) is a server bug: 500.
127
+ return new Response(encode(result), { status: 200, headers: { "content-type": CONTENT_TYPE, "cache-control": "no-store" } });
128
+ } catch (error) {
129
+ if (error instanceof Response) return error; // a redirect or custom status from the function
130
+ if (error instanceof ValidationError) return json(400, { error: { message: error.message, issues: error.issues } });
131
+ if (isNotFound(error)) return json(404, { error: { message: "Not found" } });
132
+ console.error(`✗ server function ${url.pathname}:`, error?.stack ?? error);
133
+ return json(500, { error: { message: "Internal Server Error" } });
134
+ }
135
+ }
136
+
137
+ return { size: table.size, handle };
138
+ }