// Server component routes (experimental — rides the experimental server
// components surface in @solidjs/web; the arg shape may change).
//
// `serverRouteComponent(source)` turns a function of route arguments that
// resolves to a component into a route `component`. It replaces the client
// wrapper a server-component route used to need:
//
// // before: a client component exists only to make the call
// const getStory = query(storyView, "story");
// component: props => {
// const View = dynamicComponent(() => getStory(props.params.id));
// return {props.children};
// }
// // after
// component: serverRouteComponent(query(storyView, "story"))
//
// The source is the app's: `query(fn, key)` for a request/response server
// component, `liveQuery(fn, key)` for one that streams successive versions,
// or any function of the args. The router does not choose the cache
// strategy and does not own the key — `revalidate("story")` is the app's,
// as it is for any query. What the router adds is the URL → call
// translation: it derives the call's arguments from the match, mounts the
// resolved component with the outlet as `children`, and calls the same
// source under preload intent (link hover, `preloadRoute`, the single-flight
// collector), so the query or live channel is warm before the navigation
// renders against it.
//
// Arguments are derived, not read from a live location: the call's
// `(function, arguments)` address keys the frame store and the query cache,
// so the args must name precisely what the route depends on. They are the
// params this route's pattern (with its ancestors') declares — never a
// child's, so a layout does not refetch when a leaf param changes — and, only
// when the route declares a `search` schema, its validated output.
//
// The router fills exactly one client position: `children`, with the outlet.
// A server component that takes other client positions — handlers, refs,
// named slots — has a client half, and that half is a client component; the
// helper does not pretend otherwise. Write the wrapper for that route.
import { dynamicComponent, getServerFunctionMetadata, isServer } from "@solidjs/web";
import type { JSX } from "@solidjs/web";
import { createComponent, DEV, untrack } from "solid-js";
import { getIntent } from "./routing.js";
import type { Component } from "solid-js";
import { SERVER_ROUTE, type BrandedRouteComponent } from "./serverRouteShared.js";
import type {
Params,
RouteSectionProps,
ServerRouteArgs,
ServerRouteFunction,
ServerRouteParams,
TypedRouteConfig
} from "./types.js";
/**
* Use a server component as a route (experimental). `source` is a function
* of the router-derived {@link ServerRouteArgs} — this route's `params`, and
* `search` when the route declares a schema — resolving to a server
* component: typically a `"use server"` function wrapped in `query()` or
* `liveQuery()`, whose key the app names and revalidates. The router mounts
* the result with the outlet as `children` and calls the same source under
* preload intent, so link hover and single-flight collection warm it.
*
* `children` is the only client position the router fills, so the server
* component may declare no other. One that takes client handlers, refs, or
* slots has a client half — write an ordinary route component for it.
*
* ```ts
* defineRoute({ path: "/stories/:id", component: serverRouteComponent(query(storyView, "story")) });
* ```
*/
export function serverRouteComponent
(
// A source that ignores its args (an app shell) is `(...args: never[])`
// once `query()` has typed it; that is the same call, so accept it too.
source: ServerRouteFunction
| ((...args: never[]) => ReturnType>)
): Component>> {
const call = handOffPreloads(source as ServerRouteFunction);
// The value is a component only so it fits the `component` field; the
// router core never calls it — it mounts through the brand, with THIS
// level's params and the declared search output. A direct mount (a
// `lazy()` wrapper around the helper, a hand-written ``) would
// have only the merged params to call with: the same view under a second
// address, missing the cache and owning its own frame. Refuse it.
const route: BrandedRouteComponent = () => {
throw new Error(
"serverRouteComponent(): mount it as a route's `component`" +
(DEV
? " — the router derives the call from the match. It was rendered directly (through " +
"lazy(), as the root, or outside a route). For an app shell, make it a " +
"pathless layout route with children."
: "")
);
};
function render(args: () => ServerRouteArgs, routeProps: RouteSectionProps) {
// The source may answer a component, a promise of one, or (a live query)
// successive components; `dynamicComponent`'s memo lands each the same
// way. Never a tag, so the element runtime `dynamic` retains stays out.
const View = dynamicComponent(() => call(args()) as Promise>);
return createComponent(View, {
get children() {
return routeProps.children;
}
}) as JSX.Element;
}
route[SERVER_ROUTE] = { call, render };
return route as Component>>;
}
// How long a preload's call stays claimable by the render it warmed — the
// same window `query()` gives a preloaded entry.
const PRELOAD_TIMEOUT = 5000;
// A bare `GET(fn)` source has no cache of its own, so a link preload and the
// render it warms would each send the request (#677). Hand the preload's
// call to the next render with the same args, once: the render mounts the
// result the preload already started, and a later render calls fresh, as a
// bare GET always does. Concurrent preloads of the same args share one call.
// `query()`/`liveQuery()` sources and plain functions keep their own path.
function handOffPreloads(source: ServerRouteFunction): ServerRouteFunction {
if (isServer || getServerFunctionMetadata(source)?.method !== "GET") return source;
const preloads = new Map]>();
return args => {
const now = Date.now();
for (const [k, [time]] of preloads) now - time >= PRELOAD_TIMEOUT && preloads.delete(k);
const key = JSON.stringify(args);
const entry = preloads.get(key);
if (untrack(getIntent) === "preload") {
if (entry) return entry[1];
const result = source(args);
preloads.set(key, [now, result]);
// A failed preload is not handed on: the render retries.
const drop = () => preloads.get(key)?.[1] === result && preloads.delete(key);
result && typeof (result as any).then === "function" && (result as any).then(undefined, drop);
return result;
}
if (entry) {
preloads.delete(key);
return entry[1];
}
return source(args);
};
}