@opentf/afw 0.37.0 → 0.38.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/jsx-runtime.d.ts +22 -1
- package/package.json +5 -1
- package/runtime/dom.js +23 -4
- package/runtime/error-boundary.d.ts +1 -1
- package/runtime/error-boundary.js +11 -1
- package/runtime/head.js +10 -1
- package/runtime/index.d.ts +4 -0
- package/runtime/index.js +5 -0
- package/runtime/lazy.d.ts +8 -0
- package/runtime/lazy.js +135 -0
- package/runtime/pending-scope.d.ts +6 -0
- package/runtime/pending-scope.js +39 -0
- package/runtime/pending.d.ts +31 -0
- package/runtime/pending.js +276 -0
- package/runtime/resource.d.ts +6 -0
- package/runtime/resource.js +65 -5
- package/runtime/route-data.js +33 -1
- package/runtime/route-errors.d.ts +3 -0
- package/runtime/route-errors.js +16 -0
- package/runtime/route-match.js +79 -12
- package/runtime/router.d.ts +35 -3
- package/runtime/router.js +397 -48
- package/runtime/scroll.js +130 -0
- package/runtime/transition-hooks.js +10 -0
- package/runtime/transition.d.ts +43 -0
- package/runtime/transition.js +187 -0
- package/server/api.js +3 -3
- package/server/builtins.js +29 -1
- package/server/index.d.ts +12 -1
- package/server/index.js +1 -1
- package/server/loader.js +73 -7
- package/server/middleware.js +9 -5
- package/server/render.js +53 -9
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// Scroll restoration for client navigation (SPA mode).
|
|
2
|
+
//
|
|
3
|
+
// The browser's own restoration runs when the URL changes — before an async page
|
|
4
|
+
// (loader data, `loading.jsx`, resources) has rendered, so it lands on a short page
|
|
5
|
+
// or a skeleton. The router takes over instead (`history.scrollRestoration =
|
|
6
|
+
// "manual"`):
|
|
7
|
+
//
|
|
8
|
+
// - Each history entry carries a key in `history.state` (`afwKey`).
|
|
9
|
+
// - Leaving an entry saves its scroll position under that key (kept in
|
|
10
|
+
// sessionStorage, so a reload restores it too).
|
|
11
|
+
// - Back/forward and reload restore the saved position once the page has
|
|
12
|
+
// rendered, and keep retrying while the page is still too short to reach it —
|
|
13
|
+
// until it fits, the user scrolls, or 2 s pass.
|
|
14
|
+
|
|
15
|
+
const STORE = "afw:scroll";
|
|
16
|
+
const LIMIT = 100; // entries kept; the oldest go first
|
|
17
|
+
const GIVE_UP_MS = 2000;
|
|
18
|
+
|
|
19
|
+
let positions = null;
|
|
20
|
+
let currentKey = null;
|
|
21
|
+
let stopPending = null;
|
|
22
|
+
|
|
23
|
+
function store() {
|
|
24
|
+
if (positions) return positions;
|
|
25
|
+
positions = {};
|
|
26
|
+
try {
|
|
27
|
+
const saved = JSON.parse(sessionStorage.getItem(STORE) || "{}");
|
|
28
|
+
if (saved && typeof saved === "object") positions = saved;
|
|
29
|
+
} catch {
|
|
30
|
+
// Storage blocked (private mode, sandboxed iframe): positions last for this page only.
|
|
31
|
+
}
|
|
32
|
+
return positions;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function persist() {
|
|
36
|
+
const keys = Object.keys(positions);
|
|
37
|
+
for (const key of keys.slice(0, Math.max(0, keys.length - LIMIT))) delete positions[key];
|
|
38
|
+
try {
|
|
39
|
+
sessionStorage.setItem(STORE, JSON.stringify(positions));
|
|
40
|
+
} catch {
|
|
41
|
+
// See `store`.
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const newKey = () => Math.random().toString(36).slice(2, 10);
|
|
46
|
+
|
|
47
|
+
/** Take over scroll restoration from the browser, and save the position on unload. */
|
|
48
|
+
let managing = false;
|
|
49
|
+
export function manageScroll() {
|
|
50
|
+
if ("scrollRestoration" in history) history.scrollRestoration = "manual";
|
|
51
|
+
if (managing) return;
|
|
52
|
+
managing = true;
|
|
53
|
+
window.addEventListener("pagehide", rememberScroll);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Save the current entry's scroll position (call before the view changes). */
|
|
57
|
+
export function rememberScroll() {
|
|
58
|
+
if (!currentKey) return;
|
|
59
|
+
store()[currentKey] = [window.scrollX, window.scrollY];
|
|
60
|
+
persist();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Record the history entry a navigation lands on and make it current: a new entry
|
|
65
|
+
* (`push`), the current one replaced (`replace`), or — for back/forward and the
|
|
66
|
+
* first load — the entry already there, given a key if it has none.
|
|
67
|
+
*/
|
|
68
|
+
export function enterEntry(path, mode) {
|
|
69
|
+
cancelRestore();
|
|
70
|
+
if (mode === "pop") {
|
|
71
|
+
let key = history.state?.afwKey;
|
|
72
|
+
if (!key) {
|
|
73
|
+
key = newKey();
|
|
74
|
+
history.replaceState({ ...(history.state ?? {}), afwKey: key }, "");
|
|
75
|
+
}
|
|
76
|
+
currentKey = key;
|
|
77
|
+
return key;
|
|
78
|
+
}
|
|
79
|
+
const key = newKey();
|
|
80
|
+
if (mode === "replace") history.replaceState({ afwKey: key }, "", path);
|
|
81
|
+
else history.pushState({ afwKey: key }, "", path);
|
|
82
|
+
currentKey = key;
|
|
83
|
+
return key;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Restore the scroll position saved for `key`. Returns false when none was saved.
|
|
88
|
+
* While the page is too short to reach it, it retries as the page grows.
|
|
89
|
+
*/
|
|
90
|
+
export function restoreScroll(key) {
|
|
91
|
+
const saved = key ? store()[key] : null;
|
|
92
|
+
if (!saved) return false;
|
|
93
|
+
const [x, y] = saved;
|
|
94
|
+
window.scrollTo(x, y);
|
|
95
|
+
if (reached(y) || typeof ResizeObserver !== "function") return true;
|
|
96
|
+
const observer = new ResizeObserver(() => {
|
|
97
|
+
window.scrollTo(x, y);
|
|
98
|
+
if (reached(y)) cancelRestore();
|
|
99
|
+
});
|
|
100
|
+
observer.observe(document.body);
|
|
101
|
+
const timer = setTimeout(cancelRestore, GIVE_UP_MS);
|
|
102
|
+
const events = ["wheel", "touchstart", "keydown", "pointerdown"];
|
|
103
|
+
stopPending = () => {
|
|
104
|
+
observer.disconnect();
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
for (const type of events) window.removeEventListener(type, cancelRestore, true);
|
|
107
|
+
};
|
|
108
|
+
for (const type of events) window.addEventListener(type, cancelRestore, { capture: true, passive: true });
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const reached = (y) => Math.abs(window.scrollY - y) < 2;
|
|
113
|
+
|
|
114
|
+
function cancelRestore() {
|
|
115
|
+
const stop = stopPending;
|
|
116
|
+
stopPending = null;
|
|
117
|
+
stop?.();
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Test hook: forget saved positions and the current entry. */
|
|
121
|
+
export function __resetScroll() {
|
|
122
|
+
cancelRestore();
|
|
123
|
+
positions = {};
|
|
124
|
+
currentKey = null;
|
|
125
|
+
try {
|
|
126
|
+
sessionStorage.removeItem(STORE);
|
|
127
|
+
} catch {
|
|
128
|
+
// ignore
|
|
129
|
+
}
|
|
130
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// The seam between the DOM regions (dom.js) and enter/exit transitions
|
|
2
|
+
// (transition.js). Both slots stay null until a compiled element declares a
|
|
3
|
+
// transition (`setTransition`), so an app without transitions never loads
|
|
4
|
+
// transition.js and its regions add and remove nodes exactly as before.
|
|
5
|
+
//
|
|
6
|
+
// - `enter(node, initial)`: called for each root node a region has just inserted.
|
|
7
|
+
// `initial` is true on the region's first render.
|
|
8
|
+
// - `leave(node)`: called for each root node a region is removing. Returns true
|
|
9
|
+
// when it takes over the removal (the node animates out, then removes itself).
|
|
10
|
+
export const transitionHooks = { enter: null, leave: null };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/** What a transition function returns for one run. */
|
|
2
|
+
export type TransitionResult =
|
|
3
|
+
/** Keyframes describing *entering* (hidden → shown), played with the Web Animations API. Leaving plays them in reverse. */
|
|
4
|
+
| { keyframes: Keyframe[]; duration?: number; delay?: number; easing?: string }
|
|
5
|
+
/** A running animation (a Web Animation, a Motion animation): the element leaves when `finished` settles. */
|
|
6
|
+
| { finished: PromiseLike<unknown> }
|
|
7
|
+
/** Any thenable, such as a GSAP tween. */
|
|
8
|
+
| PromiseLike<unknown>
|
|
9
|
+
| null
|
|
10
|
+
| undefined;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* An enter/exit transition for the `transition`, `in` and `out` props. Called with the
|
|
14
|
+
* element each time it enters or leaves. Set `initial` to also play when the
|
|
15
|
+
* surrounding conditional or list first renders.
|
|
16
|
+
*/
|
|
17
|
+
export interface Transition {
|
|
18
|
+
(element: Element, context: { direction: "in" | "out" }): TransitionResult;
|
|
19
|
+
initial?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface TransitionOptions {
|
|
23
|
+
/** Milliseconds. Default 200. */
|
|
24
|
+
duration?: number;
|
|
25
|
+
/** Milliseconds before the animation starts. Default 0. */
|
|
26
|
+
delay?: number;
|
|
27
|
+
/** Any CSS easing. Default `"ease-out"` (leaving plays it in reverse). */
|
|
28
|
+
easing?: string;
|
|
29
|
+
/** Also play when the surrounding conditional or list first renders. Default false. */
|
|
30
|
+
initial?: boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Fade opacity in and out. */
|
|
34
|
+
export function fade(options?: TransitionOptions): Transition;
|
|
35
|
+
/** Scale up from `start` (default 0.95) while fading from `opacity` (default 0). */
|
|
36
|
+
export function scale(options?: TransitionOptions & { start?: number; opacity?: number }): Transition;
|
|
37
|
+
/** Move in from an offset in pixels (default `{ x: 0, y: 8 }`) while fading from `opacity` (default 0). */
|
|
38
|
+
export function fly(options?: TransitionOptions & { x?: number; y?: number; opacity?: number }): Transition;
|
|
39
|
+
/** Grow from zero height (or width with `axis: "x"`), including padding, margin and border. */
|
|
40
|
+
export function slide(options?: TransitionOptions & { axis?: "x" | "y" }): Transition;
|
|
41
|
+
|
|
42
|
+
/** Compiler-emitted: attach a transition prop to an element. */
|
|
43
|
+
export function setTransition(element: Element, kind: "both" | "in" | "out", spec: Transition | null | undefined): void;
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Enter and exit transitions for elements that conditionals and lists add and
|
|
2
|
+
// remove (`transition`, `in` and `out` props). The compiler emits one
|
|
3
|
+
// `setTransition(el, kind, spec)` call per prop; the regions in dom.js call the
|
|
4
|
+
// hooks installed here when they insert or remove a root node.
|
|
5
|
+
//
|
|
6
|
+
// A transition is a function `(el, { direction }) => result`, where `result` is:
|
|
7
|
+
// - a config `{ keyframes, duration, delay, easing }`, played with the Web
|
|
8
|
+
// Animations API. The keyframes describe *entering* (hidden → shown); leaving
|
|
9
|
+
// plays them in reverse.
|
|
10
|
+
// - an object with a `finished` promise (a Web Animation, a Motion animation),
|
|
11
|
+
// or any thenable (a GSAP tween): the node leaves when it settles.
|
|
12
|
+
// - null / undefined: no animation.
|
|
13
|
+
|
|
14
|
+
import { reportError } from "../core/errors.js";
|
|
15
|
+
import { transitionHooks } from "./transition-hooks.js";
|
|
16
|
+
|
|
17
|
+
/** el → { enter, leave, running, leaving } */
|
|
18
|
+
const records = new WeakMap();
|
|
19
|
+
|
|
20
|
+
const DEFAULTS = { duration: 200, delay: 0, easing: "ease-out" };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Attach a transition to an element. `kind` is `"both"` (`transition`), `"in"` or
|
|
24
|
+
* `"out"`. A nullish `spec` leaves that direction without an animation.
|
|
25
|
+
* Compiler-emitted; not part of the authoring API.
|
|
26
|
+
*/
|
|
27
|
+
export function setTransition(el, kind, spec) {
|
|
28
|
+
if (!transitionHooks.enter) {
|
|
29
|
+
transitionHooks.enter = enterNode;
|
|
30
|
+
transitionHooks.leave = leaveNode;
|
|
31
|
+
}
|
|
32
|
+
if (spec != null && typeof spec !== "function") {
|
|
33
|
+
reportError(new TypeError(`a \`${kind === "both" ? "transition" : kind}\` prop expects a transition function such as fade(), got ${typeof spec}`), { phase: "transition" });
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
let record = records.get(el);
|
|
37
|
+
if (!record) records.set(el, (record = { enter: null, leave: null, running: null, leaving: null }));
|
|
38
|
+
if (kind !== "out") record.enter = spec ?? null;
|
|
39
|
+
if (kind !== "in") record.leave = spec ?? null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const reducedMotion = () =>
|
|
43
|
+
typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
|
|
44
|
+
|
|
45
|
+
/** Run `spec` on `el`; returns the running animation (or thenable), or null. */
|
|
46
|
+
function play(el, spec, direction) {
|
|
47
|
+
if (reducedMotion()) return null;
|
|
48
|
+
let result;
|
|
49
|
+
try {
|
|
50
|
+
result = spec(el, { direction });
|
|
51
|
+
} catch (error) {
|
|
52
|
+
reportError(error, { phase: "transition" });
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
if (result == null) return null;
|
|
56
|
+
if (Array.isArray(result.keyframes)) return animate(el, result, direction);
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Play a `{ keyframes, duration, delay, easing }` config. Entering fills backwards
|
|
62
|
+
* (hidden through a delay, then the element's own styles); leaving plays in
|
|
63
|
+
* reverse and fills forwards, so the node stays hidden until it is removed.
|
|
64
|
+
*/
|
|
65
|
+
function animate(el, config, direction) {
|
|
66
|
+
if (typeof el.animate !== "function") return null; // no Web Animations (test DOMs)
|
|
67
|
+
const out = direction === "out";
|
|
68
|
+
return el.animate(config.keyframes, {
|
|
69
|
+
duration: config.duration ?? DEFAULTS.duration,
|
|
70
|
+
delay: config.delay ?? DEFAULTS.delay,
|
|
71
|
+
easing: config.easing ?? DEFAULTS.easing,
|
|
72
|
+
direction: out ? "reverse" : "normal",
|
|
73
|
+
fill: out ? "forwards" : "backwards",
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Resolves when `running` (an Animation, thenable or anything else) settles. */
|
|
78
|
+
function settled(running) {
|
|
79
|
+
const done = running && typeof running === "object" && "finished" in running ? running.finished : running;
|
|
80
|
+
return Promise.resolve(done).then(() => {}, () => {});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function enterNode(el, initial) {
|
|
84
|
+
const record = records.get(el);
|
|
85
|
+
if (!record) return;
|
|
86
|
+
// Re-inserted while leaving (a region that re-shows the same node): stop the exit.
|
|
87
|
+
if (record.leaving) {
|
|
88
|
+
const leaving = record.leaving;
|
|
89
|
+
record.leaving = null;
|
|
90
|
+
el.inert = false;
|
|
91
|
+
if (typeof leaving.cancel === "function") leaving.cancel();
|
|
92
|
+
}
|
|
93
|
+
const spec = record.enter;
|
|
94
|
+
if (!spec || (initial && !spec.initial)) return;
|
|
95
|
+
const running = play(el, spec, "in");
|
|
96
|
+
record.running = running;
|
|
97
|
+
if (running) settled(running).then(() => { if (record.running === running) record.running = null; });
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function leaveNode(el) {
|
|
101
|
+
const record = records.get(el);
|
|
102
|
+
if (!record || !record.leave) return false;
|
|
103
|
+
let running;
|
|
104
|
+
// Leaving mid-enter with the same transition: reverse the enter from where it is.
|
|
105
|
+
if (record.running && record.leave === record.enter && typeof record.running.reverse === "function") {
|
|
106
|
+
running = record.running;
|
|
107
|
+
running.reverse();
|
|
108
|
+
} else {
|
|
109
|
+
if (record.running && typeof record.running.cancel === "function") record.running.cancel();
|
|
110
|
+
running = play(el, record.leave, "out");
|
|
111
|
+
}
|
|
112
|
+
record.running = null;
|
|
113
|
+
if (!running) return false;
|
|
114
|
+
record.leaving = running;
|
|
115
|
+
el.inert = true;
|
|
116
|
+
settled(running).then(() => {
|
|
117
|
+
if (record.leaving !== running) return; // re-entered meanwhile
|
|
118
|
+
record.leaving = null;
|
|
119
|
+
el.inert = false;
|
|
120
|
+
el.remove();
|
|
121
|
+
});
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// --- Built-in transitions ----------------------------------------------------
|
|
126
|
+
|
|
127
|
+
/** Mark a transition function as playing on the region's first render too. */
|
|
128
|
+
function withOptions(fn, options) {
|
|
129
|
+
if (options.initial) fn.initial = true;
|
|
130
|
+
return fn;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const timing = (o) => ({ duration: o.duration, delay: o.delay, easing: o.easing });
|
|
134
|
+
|
|
135
|
+
/** Fade opacity in and out. */
|
|
136
|
+
export function fade(options = {}) {
|
|
137
|
+
return withOptions(() => ({ keyframes: [{ opacity: 0 }, { opacity: 1 }], ...timing(options) }), options);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Scale up from `start` (default 0.95) while fading in. */
|
|
141
|
+
export function scale(options = {}) {
|
|
142
|
+
const start = options.start ?? 0.95;
|
|
143
|
+
const opacity = options.opacity ?? 0;
|
|
144
|
+
return withOptions(() => ({
|
|
145
|
+
keyframes: [{ transform: `scale(${start})`, opacity }, { transform: "scale(1)", opacity: 1 }],
|
|
146
|
+
...timing(options),
|
|
147
|
+
}), options);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Move in from an offset (`x`, `y` in pixels; default `y: 8`) while fading in. */
|
|
151
|
+
export function fly(options = {}) {
|
|
152
|
+
const x = options.x ?? 0;
|
|
153
|
+
const y = options.y ?? 8;
|
|
154
|
+
const opacity = options.opacity ?? 0;
|
|
155
|
+
return withOptions(() => ({
|
|
156
|
+
keyframes: [{ transform: `translate(${x}px, ${y}px)`, opacity }, { transform: "none", opacity: 1 }],
|
|
157
|
+
...timing(options),
|
|
158
|
+
}), options);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Grow from zero height (or width, with `axis: "x"`), including padding, margin and
|
|
163
|
+
* border, the way an accordion panel opens. The element clips its content while it
|
|
164
|
+
* animates.
|
|
165
|
+
*/
|
|
166
|
+
export function slide(options = {}) {
|
|
167
|
+
const x = options.axis === "x";
|
|
168
|
+
const size = x ? "width" : "height";
|
|
169
|
+
const sides = x ? ["Left", "Right"] : ["Top", "Bottom"];
|
|
170
|
+
return withOptions((el, { direction }) => {
|
|
171
|
+
if (typeof el.animate !== "function") return null;
|
|
172
|
+
const style = getComputedStyle(el);
|
|
173
|
+
const shown = { [size]: style[size] };
|
|
174
|
+
const hidden = { [size]: "0px" };
|
|
175
|
+
for (const side of sides) {
|
|
176
|
+
for (const prop of [`padding${side}`, `margin${side}`, `border${side}Width`]) {
|
|
177
|
+
shown[prop] = style[prop];
|
|
178
|
+
hidden[prop] = "0px";
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
const previous = el.style.overflow;
|
|
182
|
+
el.style.overflow = "hidden";
|
|
183
|
+
const animation = animate(el, { keyframes: [hidden, shown], ...timing(options) }, direction);
|
|
184
|
+
settled(animation).then(() => { if (direction === "in") el.style.overflow = previous; });
|
|
185
|
+
return animation;
|
|
186
|
+
}, options);
|
|
187
|
+
}
|
package/server/api.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
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 { compareRoutes, compileRoute,
|
|
17
|
+
import { compareRoutes, compileRoute, decodeParams, normalizePath as normalize, scopeMatcher, stripAppDir } from "../runtime/route-match.js";
|
|
18
18
|
import { middlewareScopeFromPath, outermostFirst } from "./middleware.js";
|
|
19
19
|
|
|
20
20
|
// Scope derivation lives in middleware.js now that middleware governs the whole
|
|
@@ -57,7 +57,7 @@ function allowedMethods(mod) {
|
|
|
57
57
|
* `init.locals` — a pre-existing `locals` bag from pipeline middleware
|
|
58
58
|
* (middleware.js), shared by reference so its writes reach the handlers.
|
|
59
59
|
*/
|
|
60
|
-
export function createApiHandler(routeModules = {}, middlewareModules = {}, { appDir } = {}) {
|
|
60
|
+
export function createApiHandler(routeModules = {}, middlewareModules = {}, { appDir, groupScopes = {} } = {}) {
|
|
61
61
|
const routes = [];
|
|
62
62
|
for (const file in routeModules) {
|
|
63
63
|
const route = apiRouteFromPath(file, appDir);
|
|
@@ -73,7 +73,7 @@ export function createApiHandler(routeModules = {}, middlewareModules = {}, { ap
|
|
|
73
73
|
const fn = mod.default ?? mod.middleware;
|
|
74
74
|
if (typeof fn === "function") {
|
|
75
75
|
const scope = middlewareScopeFromPath(file, appDir);
|
|
76
|
-
middleware.push({ scope, matcher:
|
|
76
|
+
middleware.push({ scope, matcher: scopeMatcher(scope, groupScopes[scope]), fn });
|
|
77
77
|
}
|
|
78
78
|
}
|
|
79
79
|
// Outermost runs first, so `/api/_middleware` wraps `/api/users/_middleware`.
|
package/server/builtins.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
//! hand-written Custom Elements, not compiled). Registered on import so the SSG
|
|
3
3
|
//! bundle can render `<Link>`, `<ContextProvider>`, `<Portal>`, `<ErrorBoundary>`.
|
|
4
4
|
|
|
5
|
-
import { attr, defineSSG } from "./ssg-runtime.js";
|
|
5
|
+
import { attr, defineSSG, ssgText } from "./ssg-runtime.js";
|
|
6
6
|
import { localizePath } from "../runtime/router.js";
|
|
7
7
|
|
|
8
8
|
// Passthrough: their effect is structural/client-side; SSG renders children inline.
|
|
@@ -35,6 +35,34 @@ ContextProvider.hostAttrs = (props) =>
|
|
|
35
35
|
props && props.context && props.context.id ? ` data-afw-ctx="${props.context.id}"` : "";
|
|
36
36
|
export const Portal = passthrough("afw-internal-portal");
|
|
37
37
|
export const ErrorBoundary = passthrough("afw-internal-error-boundary");
|
|
38
|
+
// Pending: resources don't fetch on the server, so the boundary is still waiting — render
|
|
39
|
+
// the fallback through a declarative shadow root (the client's PendingElement reuses it),
|
|
40
|
+
// with the children in the light DOM, hidden until the client's resources settle.
|
|
41
|
+
export const Pending = register("afw-internal-pending", (props, children) => {
|
|
42
|
+
const fallback = props && props.fallback != null
|
|
43
|
+
? `<span slot="fallback" style="display:contents">${ssgText(props.fallback)}</span>`
|
|
44
|
+
: "";
|
|
45
|
+
return '<template shadowrootmode="open"><style>:host{display:contents}</style><slot name="fallback"></slot></template>' +
|
|
46
|
+
fallback + slot("afw-internal-pending", children);
|
|
47
|
+
});
|
|
48
|
+
/**
|
|
49
|
+
* Server half of `lazyComponent` (runtime/lazy.js). A lazy component renders in the
|
|
50
|
+
* browser only, so the server sends its placeholder: a declarative shadow root that
|
|
51
|
+
* displays nothing, with the children in the light DOM (hidden), marked so hydration
|
|
52
|
+
* adopts them. The props travel in the hydration payload like any island's.
|
|
53
|
+
*/
|
|
54
|
+
export function lazyComponent(loader, tag) {
|
|
55
|
+
const lazy = () => loader();
|
|
56
|
+
Object.defineProperty(lazy, "tag", { value: tag });
|
|
57
|
+
if (!registered.has(tag)) {
|
|
58
|
+
registered.add(tag);
|
|
59
|
+
register(tag, (_props, children) =>
|
|
60
|
+
'<template shadowrootmode="open"><style>:host{display:contents}</style></template>' + slot(tag, children));
|
|
61
|
+
}
|
|
62
|
+
return lazy;
|
|
63
|
+
}
|
|
64
|
+
const registered = new Set();
|
|
65
|
+
|
|
38
66
|
// RawHtml: emit the trusted HTML string inline (MDX highlighted code blocks).
|
|
39
67
|
export const RawHtml = register("afw-internal-raw-html", (props) => (props && props.html != null ? String(props.html) : ""));
|
|
40
68
|
// CodeFence: same inline HTML as RawHtml; the copy button wires up on the client
|
package/server/index.d.ts
CHANGED
|
@@ -24,6 +24,9 @@ export const Link: ServerComponent;
|
|
|
24
24
|
export const ContextProvider: ServerComponent;
|
|
25
25
|
export const Portal: ServerComponent;
|
|
26
26
|
export const ErrorBoundary: ServerComponent;
|
|
27
|
+
export const Pending: ServerComponent;
|
|
28
|
+
/** Compiler-emitted: a lazy component's loader with its placeholder tag (renders the empty placeholder on the server). */
|
|
29
|
+
export function lazyComponent<L extends () => Promise<unknown>>(loader: L, tag: string): L & { readonly tag: string };
|
|
27
30
|
export const RawHtml: ServerComponent;
|
|
28
31
|
export const CodeFence: ServerComponent;
|
|
29
32
|
export function shouldInterceptNav(): boolean;
|
|
@@ -140,9 +143,17 @@ export interface LoaderRegistry {
|
|
|
140
143
|
|
|
141
144
|
export function createLoaderRegistry(
|
|
142
145
|
loaderModules?: Record<string, { default?: Loader; loader?: Loader }>,
|
|
143
|
-
|
|
146
|
+
/** `pageRoutes`: every page route, so a page beneath a `layout.loader.*` matches without a loader of its own. */
|
|
147
|
+
options?: { appDir?: string; i18n?: { locales?: string[]; defaultLocale?: string }; pageRoutes?: string[] },
|
|
144
148
|
): LoaderRegistry;
|
|
149
|
+
/** The route a `loader.*` (its page) or `layout.loader.*` (its layout's folder) belongs to. */
|
|
145
150
|
export function loaderRouteFromPath(filePath: string, appDir?: string): string;
|
|
151
|
+
/** Is this a `layout.loader.{js,ts}` file? */
|
|
152
|
+
export function isLayoutLoaderFile(filePath: string): boolean;
|
|
153
|
+
/** Does the layout at `folder` wrap the page at `route`? */
|
|
154
|
+
export function layoutWraps(folder: string, route: string): boolean;
|
|
155
|
+
/** Page routes with loader data: their own `loader.*`, or beneath a `layout.loader.*`. */
|
|
156
|
+
export function loaderPageRoutes(routes: { pages?: string[]; pageLoaders?: string[]; layoutLoaders?: string[] }): string[];
|
|
146
157
|
/** Throw "this page does not exist" from inside a loader (404 semantics). */
|
|
147
158
|
export function notFound(message?: string): never;
|
|
148
159
|
export function isNotFound(e: unknown): boolean;
|
package/server/index.js
CHANGED
|
@@ -12,7 +12,7 @@ export { resource } from "../runtime/resource.js";
|
|
|
12
12
|
export { invalidate } from "../runtime/invalidate.js";
|
|
13
13
|
export { ServerFunctionError, serverFunction } from "../runtime/server-function.js";
|
|
14
14
|
export { copyText, copyWithFeedback } from "../runtime/clipboard.js";
|
|
15
|
-
export { Link, ContextProvider, Portal, ErrorBoundary, RawHtml, CodeFence } from "./builtins.js";
|
|
15
|
+
export { Link, ContextProvider, Portal, ErrorBoundary, Pending, RawHtml, CodeFence, lazyComponent } from "./builtins.js";
|
|
16
16
|
export * from "./head.js";
|
|
17
17
|
export * from "./render.js";
|
|
18
18
|
// Share registration and request-scoped route state without loading Custom Elements.
|
package/server/loader.js
CHANGED
|
@@ -13,6 +13,12 @@
|
|
|
13
13
|
// `request`), the SSR server (per request), the dev server, and the
|
|
14
14
|
// `<path>/__data.json` HTTP endpoint SPA navigation fetches from (`handle`).
|
|
15
15
|
//
|
|
16
|
+
// A `layout.loader.{js,ts}` beside a `layout.*` loads data for every page beneath
|
|
17
|
+
// that layout. A page's loaders — each layout loader from the root down, then the
|
|
18
|
+
// page's own — run in parallel, and their results merge into one object (layout
|
|
19
|
+
// data first, the page's on top), so one `router.data` and one `__data.json`
|
|
20
|
+
// request serve the whole chain.
|
|
21
|
+
//
|
|
16
22
|
// Matching duplicates the `[param]` / `[...rest]` compile/decode approach of the
|
|
17
23
|
// API handler (api.js) — like api.js itself mirrors the page router — so params
|
|
18
24
|
// behave identically across pages, endpoints, and loaders.
|
|
@@ -23,10 +29,43 @@ import { compareRoutes, compileRoute, decodeParams, normalizePath as normalize,
|
|
|
23
29
|
/** The page route a `.../app/<...>/loader.{js,ts}` file feeds (folder = URL):
|
|
24
30
|
* `app/todos/loader.js` → `/todos`, `app/loader.js` → `/`. */
|
|
25
31
|
export function loaderRouteFromPath(filePath, appDir) {
|
|
26
|
-
const r = stripAppDir(filePath, appDir).replace(/\/loader\.(js|ts)$/, "");
|
|
32
|
+
const r = stripAppDir(filePath, appDir).replace(/\/(?:layout\.)?loader\.(js|ts)$/, "");
|
|
27
33
|
return r === "" ? "/" : r;
|
|
28
34
|
}
|
|
29
35
|
|
|
36
|
+
/** Is this a `layout.loader.{js,ts}` file? */
|
|
37
|
+
export const isLayoutLoaderFile = (filePath) => /(?:^|\/)layout\.loader\.(js|ts)$/.test(filePath);
|
|
38
|
+
|
|
39
|
+
/** Does the layout at `folder` (a route like "/dashboard") wrap the page at `route`? */
|
|
40
|
+
export const layoutWraps = (folder, route) =>
|
|
41
|
+
folder === "/" || route === folder || route.startsWith(`${folder}/`);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The page routes that have loader data: those with their own `loader.*`, and every
|
|
45
|
+
* page beneath a `layout.loader.*`. The client router fetches `__data.json` for these.
|
|
46
|
+
*/
|
|
47
|
+
export function loaderPageRoutes({ pages = [], pageLoaders = [], layoutLoaders = [] }) {
|
|
48
|
+
const out = new Set(pageLoaders);
|
|
49
|
+
for (const page of pages) if (layoutLoaders.some((folder) => layoutWraps(folder, page))) out.add(page);
|
|
50
|
+
return [...out].sort();
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Merge a page's loader results: layout data outermost first, the page's own on top.
|
|
55
|
+
* A single result passes through unchanged (any JSON value); a chain must be objects.
|
|
56
|
+
*/
|
|
57
|
+
function mergeLoaderData(results) {
|
|
58
|
+
const defined = results.filter((r) => r.value !== undefined);
|
|
59
|
+
if (defined.length <= 1) return defined[0]?.value;
|
|
60
|
+
for (const { value, route, layout } of defined) {
|
|
61
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
62
|
+
const kind = layout ? `layout loader ${route}` : `loader ${route}`;
|
|
63
|
+
throw new TypeError(`${kind} returned ${Array.isArray(value) ? "an array" : String(value === null ? null : typeof value)}; loaders that share a page must return objects so their data can merge`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return Object.assign({}, ...defined.map((r) => r.value));
|
|
67
|
+
}
|
|
68
|
+
|
|
30
69
|
/**
|
|
31
70
|
* Signal "this page does not exist for these params" from inside a loader — the
|
|
32
71
|
* SSR server responds 404 (rendering the 404 page), the data endpoint returns a
|
|
@@ -74,15 +113,26 @@ export function serializeRouteData(value) {
|
|
|
74
113
|
* loadSerialized: (m: object, ctx?: object) => Promise<{ data: unknown, json: string }>,
|
|
75
114
|
* handle: (request: Request, extras?: { locals?: object }) => Promise<Response | null> }}
|
|
76
115
|
*/
|
|
77
|
-
export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {}) {
|
|
78
|
-
const
|
|
116
|
+
export function createLoaderRegistry(loaderModules = {}, { appDir, i18n, pageRoutes = [] } = {}) {
|
|
117
|
+
const pageFns = new Map(); // page route → its loader
|
|
118
|
+
const layouts = []; // { route: layout folder, fn }
|
|
79
119
|
for (const file in loaderModules) {
|
|
80
120
|
const ns = loaderModules[file];
|
|
81
121
|
const fn = ns.default ?? ns.loader;
|
|
82
122
|
if (typeof fn !== "function") continue; // a loader file without a loader export is inert
|
|
83
123
|
const route = loaderRouteFromPath(file, appDir);
|
|
84
|
-
|
|
124
|
+
if (isLayoutLoaderFile(file)) layouts.push({ route, fn });
|
|
125
|
+
else pageFns.set(route, fn);
|
|
85
126
|
}
|
|
127
|
+
// Outermost layout first: the order their data merges in.
|
|
128
|
+
layouts.sort((a, b) => a.route.split("/").length - b.route.split("/").length || (a.route < b.route ? -1 : 1));
|
|
129
|
+
const pages = loaderPageRoutes({ pages: pageRoutes, pageLoaders: [...pageFns.keys()], layoutLoaders: layouts.map((l) => l.route) });
|
|
130
|
+
const entries = pages.map((route) => ({
|
|
131
|
+
route,
|
|
132
|
+
pattern: compileRoute(route),
|
|
133
|
+
fn: pageFns.get(route) ?? null,
|
|
134
|
+
layouts: layouts.filter((l) => layoutWraps(l.route, route)),
|
|
135
|
+
}));
|
|
86
136
|
// Most specific first, segment by segment — the same ranking as pages and API routes.
|
|
87
137
|
entries.sort((a, b) => compareRoutes(a.route, b.route));
|
|
88
138
|
|
|
@@ -104,7 +154,7 @@ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {})
|
|
|
104
154
|
for (const e of entries) {
|
|
105
155
|
const m = path.match(e.pattern);
|
|
106
156
|
if (!m) continue;
|
|
107
|
-
return { route: e.route, params: decodeParams(e.route, m.groups), locale, fn: e.fn };
|
|
157
|
+
return { route: e.route, params: decodeParams(e.route, m.groups), locale, fn: e.fn, layouts: e.layouts };
|
|
108
158
|
}
|
|
109
159
|
return null;
|
|
110
160
|
}
|
|
@@ -113,7 +163,21 @@ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {})
|
|
|
113
163
|
* `undefined` at SSG prerender; `locals` is the per-request bag pipeline
|
|
114
164
|
* middleware stamped (middleware.js) — empty at prerender, where none runs. */
|
|
115
165
|
async function load(m, { request, query = {}, locals = {} } = {}) {
|
|
116
|
-
|
|
166
|
+
const context = { params: m.params, query, request, locale: m.locale, locals };
|
|
167
|
+
const chain = m.layouts ?? [];
|
|
168
|
+
if (!chain.length) return m.fn ? m.fn(context) : undefined;
|
|
169
|
+
// Every loader at once; a failing layout loader is tagged with its folder, so the
|
|
170
|
+
// error view above that layout can replace it (`afwLayoutRoute`).
|
|
171
|
+
const runs = chain.map(async (layout) => {
|
|
172
|
+
try {
|
|
173
|
+
return { value: await layout.fn(context), route: layout.route, layout: true };
|
|
174
|
+
} catch (error) {
|
|
175
|
+
if (error && typeof error === "object" && !(error instanceof Response)) error.afwLayoutRoute ??= layout.route;
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
if (m.fn) runs.push(Promise.resolve(m.fn(context)).then((value) => ({ value, route: m.route, layout: false })));
|
|
180
|
+
return mergeLoaderData(await Promise.all(runs));
|
|
117
181
|
}
|
|
118
182
|
|
|
119
183
|
/** {@link load}, plus the serialized form — escaping lives in one place. */
|
|
@@ -163,7 +227,9 @@ export function createLoaderRegistry(loaderModules = {}, { appDir, i18n } = {})
|
|
|
163
227
|
return e;
|
|
164
228
|
}
|
|
165
229
|
console.error(`✗ loader ${pagePath}:`, e?.stack ?? e);
|
|
166
|
-
|
|
230
|
+
// `layout`: which layout's loader failed, so the client shows the error view above it.
|
|
231
|
+
const body = e?.afwLayoutRoute ? { error: "Internal Server Error", layout: e.afwLayoutRoute } : { error: "Internal Server Error" };
|
|
232
|
+
return Response.json(body, { status: 500 });
|
|
167
233
|
}
|
|
168
234
|
}
|
|
169
235
|
|
package/server/middleware.js
CHANGED
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
// middleware), mirroring the loader registry (loader.js `match`).
|
|
20
20
|
|
|
21
21
|
import { DATA_FILE } from "../runtime/route-data.js";
|
|
22
|
-
import { compareRoutes,
|
|
22
|
+
import { compareRoutes, normalizePath as normalize, scopeMatcher, stripAppDir } from "../runtime/route-match.js";
|
|
23
23
|
|
|
24
24
|
/** The folder route a `_middleware.{js,ts}` file governs: `app/api/_middleware.js`
|
|
25
25
|
* → `/api` (applies to `/api` and everything nested under it); `app/_middleware.js`
|
|
@@ -44,22 +44,26 @@ export function outermostFirst(a, b) {
|
|
|
44
44
|
*
|
|
45
45
|
* @param {Record<string, object>} middlewareModules the middleware is each
|
|
46
46
|
* module's default (or named `middleware`) export.
|
|
47
|
-
* @param {{ appDir?: string, i18n?: { locales?: string[], defaultLocale?: string }
|
|
47
|
+
* @param {{ appDir?: string, i18n?: { locales?: string[], defaultLocale?: string },
|
|
48
|
+
* groupScopes?: Record<string, { scopes?: string[], paths?: string[] }> }} [options]
|
|
48
49
|
* `appDir` pins exact scope derivation; `i18n` lets scope matching strip a
|
|
49
|
-
* leading non-default locale prefix (mirroring the loader registry)
|
|
50
|
+
* leading non-default locale prefix (mirroring the loader registry);
|
|
51
|
+
* `groupScopes` gives each middleware folder inside a route group what it covers.
|
|
50
52
|
* @returns {{ size: number, scopes: string[],
|
|
51
53
|
* run: (request: Request,
|
|
52
54
|
* terminal: (req: Request, context: object) => Response | Promise<Response>,
|
|
53
55
|
* extras?: { env?: unknown, ctx?: unknown }) => Promise<Response> }}
|
|
54
56
|
*/
|
|
55
|
-
export function createMiddleware(middlewareModules = {}, { appDir, i18n } = {}) {
|
|
57
|
+
export function createMiddleware(middlewareModules = {}, { appDir, i18n, groupScopes = {} } = {}) {
|
|
56
58
|
const entries = [];
|
|
57
59
|
for (const file in middlewareModules) {
|
|
58
60
|
const mod = middlewareModules[file];
|
|
59
61
|
const fn = mod.default ?? mod.middleware;
|
|
60
62
|
if (typeof fn === "function") {
|
|
61
63
|
const scope = middlewareScopeFromPath(file, appDir);
|
|
62
|
-
|
|
64
|
+
// A folder inside a route group covers what the group holds (`groupScopes`, from
|
|
65
|
+
// the build), not a URL prefix: see `scopeMatcher`.
|
|
66
|
+
entries.push({ scope, matcher: scopeMatcher(scope, groupScopes[scope]), fn });
|
|
63
67
|
}
|
|
64
68
|
}
|
|
65
69
|
entries.sort(outermostFirst);
|