@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/components/Link.d.ts +2 -0
- package/components/Link.jsx +28 -1
- package/core/fn-codec.js +30 -0
- package/index.d.ts +1 -0
- package/jsx-runtime.d.ts +3 -1
- package/macros.d.ts +24 -0
- package/package.json +6 -2
- package/runtime/hmr.js +29 -4
- package/runtime/hot-carry.js +52 -0
- package/runtime/index.d.ts +2 -0
- package/runtime/index.js +2 -0
- package/runtime/invalidate.d.ts +6 -0
- package/runtime/invalidate.js +89 -0
- package/runtime/resource.d.ts +8 -2
- package/runtime/resource.js +22 -8
- package/runtime/route-match.js +99 -0
- package/runtime/router.d.ts +4 -0
- package/runtime/router.js +99 -22
- package/runtime/server-function.d.ts +14 -0
- package/runtime/server-function.js +53 -0
- 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 +55 -0
- package/server/index.js +4 -1
- package/server/loader.js +5 -42
- package/server/middleware.js +16 -14
- package/server/server-functions.js +138 -0
package/components/Link.d.ts
CHANGED
|
@@ -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;
|
package/components/Link.jsx
CHANGED
|
@@ -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 {
|
|
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>
|
package/core/fn-codec.js
ADDED
|
@@ -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/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.35.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",
|
|
@@ -64,5 +65,8 @@
|
|
|
64
65
|
"publishConfig": {
|
|
65
66
|
"access": "public"
|
|
66
67
|
},
|
|
67
|
-
"types": "./index.d.ts"
|
|
68
|
+
"types": "./index.d.ts",
|
|
69
|
+
"dependencies": {
|
|
70
|
+
"@opentf/serialize": "^0.1.0"
|
|
71
|
+
}
|
|
68
72
|
}
|
package/runtime/hmr.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
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";
|
|
7
|
+
import { collectHotState, takeHotState, withHotCarry } from "./hot-carry.js";
|
|
5
8
|
import { refreshHotRoute } from "./router.js";
|
|
6
9
|
|
|
7
10
|
const components = new Map();
|
|
@@ -19,6 +22,18 @@ export function hotRouteState(key, create) {
|
|
|
19
22
|
return routeSlots.get(key);
|
|
20
23
|
}
|
|
21
24
|
|
|
25
|
+
/**
|
|
26
|
+
* A value made once and returned on every replacement of the module. esdev provides
|
|
27
|
+
* `hot.keep`; Vite's `import.meta.hot` has no `keep`, but its `data` object survives
|
|
28
|
+
* replacement the same way, so the value is kept there.
|
|
29
|
+
*/
|
|
30
|
+
function keep(hot, key, make) {
|
|
31
|
+
if (typeof hot.keep === "function") return hot.keep(key, make);
|
|
32
|
+
const slot = `afwKeep:${key}`;
|
|
33
|
+
if (!(slot in hot.data)) hot.data[slot] = make();
|
|
34
|
+
return hot.data[slot];
|
|
35
|
+
}
|
|
36
|
+
|
|
22
37
|
/**
|
|
23
38
|
* `exports` is the source of the page's exports other than its view and the route data the
|
|
24
39
|
* router re-reads (see the compiler's `hot_exports_shape`). Importers hold the old values,
|
|
@@ -33,7 +48,7 @@ export function registerHotRoute(hot, factory, shape = "", exports = "", data =
|
|
|
33
48
|
}
|
|
34
49
|
hot.data.afwExports = exports;
|
|
35
50
|
hot.data.afwRouteBoundary = true;
|
|
36
|
-
const record =
|
|
51
|
+
const record = keep(hot, "afw-route", () => {
|
|
37
52
|
const entry = { factory, shape };
|
|
38
53
|
// `previous` is the view node this build replaces during a refresh. Its state
|
|
39
54
|
// slots carry over when the declarations still match; otherwise state is fresh.
|
|
@@ -79,6 +94,12 @@ export function registerHotRoute(hot, factory, shape = "", exports = "", data =
|
|
|
79
94
|
}
|
|
80
95
|
|
|
81
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
|
+
}
|
|
82
103
|
const slots = host._hotState ??= new Map();
|
|
83
104
|
if (!slots.has(key)) slots.set(key, create());
|
|
84
105
|
return slots.get(key);
|
|
@@ -100,13 +121,17 @@ function refresh(record, hosts) {
|
|
|
100
121
|
const focusId = host.contains(focused) ? focused.id : null;
|
|
101
122
|
const selection = focusId && typeof focused.selectionStart === "number"
|
|
102
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);
|
|
103
128
|
cleanup(host);
|
|
104
129
|
host._mounted = false;
|
|
105
130
|
host._hotRefreshing = true;
|
|
106
131
|
// Slotted children belong to the parent. Keep the original capture and move
|
|
107
132
|
// those nodes into the new view in the same task (no genuine disconnect).
|
|
108
|
-
host.replaceChildren(...
|
|
109
|
-
try { record.connected?.call(host); }
|
|
133
|
+
host.replaceChildren(...slotted);
|
|
134
|
+
try { withHotCarry(carried, () => record.connected?.call(host)); }
|
|
110
135
|
finally { host._hotRefreshing = false; }
|
|
111
136
|
if (focusId) {
|
|
112
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
|
+
}
|
package/runtime/index.d.ts
CHANGED
|
@@ -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
|
+
}
|
package/runtime/resource.d.ts
CHANGED
|
@@ -4,6 +4,12 @@ export interface Resource<T> {
|
|
|
4
4
|
readonly error: unknown;
|
|
5
5
|
refetch(): Promise<T | undefined> | undefined;
|
|
6
6
|
}
|
|
7
|
-
export
|
|
8
|
-
|
|
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;
|
package/runtime/resource.js
CHANGED
|
@@ -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`
|
|
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
|
-
|
|
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
|
}
|
|
@@ -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.d.ts
CHANGED
|
@@ -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
|