@opentf/afw 0.39.0 → 0.40.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/core/fn-codec.js +9 -0
- package/jsx-runtime.d.ts +46 -2
- package/macros.d.ts +13 -0
- package/package.json +1 -1
- package/runtime/dom.d.ts +2 -0
- package/runtime/dom.js +57 -8
- package/runtime/error-boundary.js +11 -1
- package/runtime/hmr.js +70 -10
- package/runtime/hydrate.d.ts +4 -0
- package/runtime/hydrate.js +44 -0
- package/runtime/index.d.ts +1 -0
- package/runtime/index.js +1 -0
- package/runtime/invalidate.d.ts +7 -4
- package/runtime/invalidate.js +150 -38
- package/runtime/mutate.d.ts +16 -0
- package/runtime/mutate.js +79 -0
- package/runtime/portal.js +3 -1
- package/runtime/query-cache.js +265 -0
- package/runtime/resource.d.ts +24 -0
- package/runtime/resource.js +203 -44
- package/runtime/revalidate.js +39 -0
- package/runtime/route-data.d.ts +9 -3
- package/runtime/route-data.js +28 -7
- package/runtime/route-match.js +11 -4
- package/runtime/router.js +17 -4
- package/runtime/server-function.js +78 -8
- package/server/index.d.ts +17 -2
- package/server/server-functions.js +101 -4
- package/server/ssg-runtime.js +32 -0
package/runtime/resource.js
CHANGED
|
@@ -16,16 +16,22 @@
|
|
|
16
16
|
// (passed to the fetcher as `{ signal }`), so an out-of-order resolution can never
|
|
17
17
|
// overwrite newer data — even for fetchers that ignore the signal.
|
|
18
18
|
//
|
|
19
|
+
// Caching: a server function fetcher (`resource(() => ({ id }), getTodo)`) or a `key`
|
|
20
|
+
// option puts the result in the query cache (query-cache.js). Every user of the key
|
|
21
|
+
// shares one request and shows the same data; a remount shows the cached data at once
|
|
22
|
+
// and revalidates it (or skips the request while it is younger than `staleTime`).
|
|
23
|
+
//
|
|
19
24
|
// Server (SSG/SSR): no effect is created and nothing is fetched — `loading` stays
|
|
20
|
-
// `true
|
|
21
|
-
// the client's first paint renders
|
|
22
|
-
// hydration adoption aligned.
|
|
25
|
+
// `true` (or `false` for a source that starts paused), so the prerendered HTML shows
|
|
26
|
+
// the branch the client's first paint renders, keeping hydration adoption aligned.
|
|
23
27
|
|
|
24
28
|
import { getCurrentInstance } from "../core/context.js";
|
|
25
29
|
import { reportError } from "../core/errors.js";
|
|
26
30
|
import { batch, effect, signal, untracked } from "../core/signals.js";
|
|
27
31
|
import { endpointOf, registerResource, unregisterResource, withTracking } from "./invalidate.js";
|
|
28
32
|
import { buildingPending, closestPending } from "./pending-scope.js";
|
|
33
|
+
import { DEFAULT_GC_TIME, callKey, customKey, fetchShared, isFresh, peek, subscribe, viewOf } from "./query-cache.js";
|
|
34
|
+
import { revalidateEvents, watch } from "./revalidate.js";
|
|
29
35
|
|
|
30
36
|
// Test override: the DOM suites run in esdev's `--dom` realm (a `document`
|
|
31
37
|
// always exists), so server behavior is opted into explicitly.
|
|
@@ -38,6 +44,8 @@ export function __setResourceServer(v) {
|
|
|
38
44
|
|
|
39
45
|
const isServer = () => serverOverride ?? typeof document === "undefined";
|
|
40
46
|
|
|
47
|
+
const paused = (value) => value == null || value === false;
|
|
48
|
+
|
|
41
49
|
/**
|
|
42
50
|
* Create a resource. Two call shapes:
|
|
43
51
|
*
|
|
@@ -45,17 +53,31 @@ const isServer = () => serverOverride ?? typeof document === "undefined";
|
|
|
45
53
|
* resource(source, fetcher, options?) — re-fetch when the reactive `source`
|
|
46
54
|
* changes; `null`/`false` pauses
|
|
47
55
|
*
|
|
56
|
+
* A server function as the fetcher (`resource(() => ({ id }), getTodo)`, or
|
|
57
|
+
* `resource(listTodos)` for one without input) is cached by its endpoint and input; a
|
|
58
|
+
* `key` option caches any other fetcher. A cached resource shows the entry's data at
|
|
59
|
+
* once, shares requests with every other user of the key, and follows their updates.
|
|
60
|
+
*
|
|
48
61
|
* @param {Function} source reactive source read inside the tracking effect; its
|
|
49
62
|
* value is passed to the fetcher.
|
|
50
63
|
* @param {Function} fetcher `(sourceValue, { signal }) => data | Promise<data>`.
|
|
51
|
-
* @param {{ initial?: unknown, invalidatedBy?: Function[], errors?: "inline"
|
|
64
|
+
* @param {{ initial?: unknown, invalidatedBy?: Function[], errors?: "inline",
|
|
65
|
+
* key?: unknown, staleTime?: number, gcTime?: number, timeout?: number,
|
|
66
|
+
* revalidateOn?: "focus" | "online" | Array<"focus" | "online"> }} [options]
|
|
52
67
|
* `initial` seeds `data` before the first resolution. `invalidatedBy` names
|
|
53
68
|
* server functions whose `invalidate()` refetches this resource, beyond those
|
|
54
69
|
* its fetcher calls as it starts (which are recorded automatically).
|
|
55
70
|
* `errors: "inline"` keeps failures on `error` only, even under `<Pending>`.
|
|
71
|
+
* `key` (a value, or a function of the source value) caches the fetcher's result.
|
|
72
|
+
* `staleTime` (ms, default 0): how long cached data answers without a request.
|
|
73
|
+
* `gcTime` (ms, default 5 minutes): how long an unused cache entry is kept.
|
|
74
|
+
* `timeout` (ms): abort a run that takes longer, with a TimeoutError.
|
|
75
|
+
* `revalidateOn` ("focus" | "online" | both): refetch when the tab becomes
|
|
76
|
+
* visible again or the browser reconnects, once the data is older than staleTime.
|
|
56
77
|
* @returns {{ data: unknown, loading: boolean, error: unknown,
|
|
57
78
|
* refetch: () => Promise<unknown> | undefined }} reactive getters —
|
|
58
|
-
* read them inside bindings/effects to subscribe.
|
|
79
|
+
* read them inside bindings/effects to subscribe. `refetch()` resolves with the
|
|
80
|
+
* new data and rejects when the fetch fails.
|
|
59
81
|
*/
|
|
60
82
|
export function resource(source, fetcher, options = {}) {
|
|
61
83
|
if (typeof fetcher !== "function") {
|
|
@@ -66,55 +88,156 @@ export function resource(source, fetcher, options = {}) {
|
|
|
66
88
|
const src = typeof source === "function" ? source : () => true;
|
|
67
89
|
const data = signal(options.initial);
|
|
68
90
|
const error = signal(undefined);
|
|
69
|
-
|
|
91
|
+
// A fetch is intended. The server settles it as the browser's first paint will: still
|
|
92
|
+
// loading, unless the source starts paused (hydration adopts the same branch).
|
|
93
|
+
const loading = signal(isServer() ? !startsPaused(src) : true);
|
|
70
94
|
// Has a run succeeded at least once? A `<Pending>` shows its fallback while a
|
|
71
95
|
// resource it waits on is loading and has never loaded, so retrying a failed first
|
|
72
96
|
// load shows the fallback again.
|
|
73
97
|
const settled = signal(false);
|
|
74
98
|
let token = 0;
|
|
75
99
|
let controller = null;
|
|
76
|
-
// This resource in the `invalidate()` registry (runtime/invalidate.js).
|
|
77
|
-
|
|
100
|
+
// This resource in the `invalidate()` registry (runtime/invalidate.js). `fromCache`:
|
|
101
|
+
// a call its fetcher made changed in the cache (`setQueryData`, an optimistic overlay,
|
|
102
|
+
// an action's refresh), so it re-runs against the cache. A resource that shows the
|
|
103
|
+
// entry itself heard the write already.
|
|
104
|
+
const entry = {
|
|
105
|
+
refetch: () => reload(),
|
|
106
|
+
fromCache: (key) => {
|
|
107
|
+
if (key === followed || disposed) return;
|
|
108
|
+
const value = untracked(src);
|
|
109
|
+
if (!paused(value)) run(value, { fromCache: true });
|
|
110
|
+
},
|
|
111
|
+
};
|
|
78
112
|
const named = (options.invalidatedBy ?? []).map(endpointOf).filter(Boolean);
|
|
79
113
|
|
|
80
|
-
|
|
114
|
+
// --- The query cache (query-cache.js) ---------------------------------------
|
|
115
|
+
const staleTime = Math.max(0, Number(options.staleTime) || 0);
|
|
116
|
+
const timeout = Number(options.timeout) > 0 ? Number(options.timeout) : 0;
|
|
117
|
+
let loadedAt = 0; // when the shown data was fetched, for `revalidateOn`
|
|
118
|
+
const gcTime = options.gcTime ?? DEFAULT_GC_TIME;
|
|
119
|
+
const stub = typeof fetcher.endpoint === "string" ? fetcher.endpoint : null;
|
|
120
|
+
const custom = "key" in options;
|
|
121
|
+
// `resource(listTodos)`: a server function without a source takes no input.
|
|
122
|
+
const input = (value) => (stub && !source ? undefined : value);
|
|
123
|
+
const keyOf = (value) => {
|
|
124
|
+
if (custom) return customKey(typeof options.key === "function" ? options.key(value) : options.key);
|
|
125
|
+
return stub ? callKey(stub, input(value)) : null;
|
|
126
|
+
};
|
|
127
|
+
let followed = null; // the key this resource shows
|
|
128
|
+
let unfollow = null;
|
|
129
|
+
function follow(key) {
|
|
130
|
+
if (key === followed) return;
|
|
131
|
+
unfollow?.();
|
|
132
|
+
followed = key;
|
|
133
|
+
unfollow = key ? subscribe(key, onWrite, { gcTime }) : null;
|
|
134
|
+
}
|
|
135
|
+
// Another user of the key stored new data.
|
|
136
|
+
function onWrite(value) {
|
|
137
|
+
batch(() => {
|
|
138
|
+
data.value = value;
|
|
139
|
+
error.value = undefined;
|
|
140
|
+
settled.value = true;
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
// A cached resource's dependencies for `invalidate()`: its own call, or what the
|
|
144
|
+
// fetcher behind its custom key called.
|
|
145
|
+
function register(key, endpoints = new Set(), keys = new Set()) {
|
|
146
|
+
if (key && stub && !custom) {
|
|
147
|
+
endpoints.add(stub);
|
|
148
|
+
keys.add(key);
|
|
149
|
+
}
|
|
150
|
+
const deps = key && custom ? peek(key)?.deps : null;
|
|
151
|
+
if (deps) {
|
|
152
|
+
for (const endpoint of deps.endpoints) endpoints.add(endpoint);
|
|
153
|
+
for (const k of deps.keys) keys.add(k);
|
|
154
|
+
}
|
|
155
|
+
registerResource(entry, endpoints, keys, named);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// One run of the fetcher. Resolves with its outcome, never rejects:
|
|
159
|
+
// `{ ok: true, value }`, `{ ok: false, error }`, or `{ superseded: true }`.
|
|
160
|
+
function run(value, { force = false, fromCache = false } = {}) {
|
|
81
161
|
controller?.abort();
|
|
82
162
|
// Captured per-run: by the time a superseded run's promise settles, the
|
|
83
163
|
// module-level `controller` already belongs to a newer run.
|
|
84
164
|
const c = (controller = typeof AbortController !== "undefined" ? new AbortController() : null);
|
|
165
|
+
// `timeout` ms: the run aborts with a TimeoutError (the resource's error).
|
|
166
|
+
const runSignal = timeout && c ? AbortSignal.any([c.signal, AbortSignal.timeout(timeout)]) : c?.signal;
|
|
85
167
|
const t = ++token;
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
168
|
+
// `refetch()` and `invalidate()` always ask the server. A re-run from the cache runs
|
|
169
|
+
// the fetcher again, its server function calls answering from cached data.
|
|
170
|
+
const age = force || fromCache ? 0 : staleTime;
|
|
171
|
+
const inner = fromCache ? Infinity : age;
|
|
172
|
+
let key = null;
|
|
173
|
+
let keyError = null;
|
|
174
|
+
try {
|
|
175
|
+
key = keyOf(value);
|
|
176
|
+
} catch (e) {
|
|
177
|
+
keyError = e; // a key or input the codec refuses
|
|
178
|
+
}
|
|
179
|
+
follow(key);
|
|
180
|
+
const cached = key ? peek(key) : undefined;
|
|
181
|
+
if (cached?.hasData) {
|
|
182
|
+
// Show the cached data at once; a stale entry revalidates behind it.
|
|
183
|
+
const shown = viewOf(cached);
|
|
184
|
+
batch(() => {
|
|
185
|
+
data.value = shown;
|
|
186
|
+
error.value = undefined;
|
|
187
|
+
settled.value = true;
|
|
188
|
+
if (isFresh(cached, age)) loading.value = false;
|
|
189
|
+
});
|
|
190
|
+
if (isFresh(cached, age)) {
|
|
191
|
+
loadedAt = cached.updatedAt;
|
|
192
|
+
register(key);
|
|
193
|
+
return Promise.resolve({ ok: true, value: shown });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// A re-run from the cache settles within microtasks: no loading state to show.
|
|
197
|
+
if (!fromCache) {
|
|
198
|
+
batch(() => {
|
|
199
|
+
loading.value = true;
|
|
200
|
+
error.value = undefined;
|
|
201
|
+
});
|
|
202
|
+
}
|
|
90
203
|
// The async IIFE starts the fetcher *synchronously* (no wasted microtask)
|
|
91
204
|
// while converting a synchronous throw into a rejection.
|
|
205
|
+
const start = (s) => (async () => fetcher(input(value), { signal: s }))();
|
|
92
206
|
// Started under tracking: the server functions the fetcher calls register it.
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
}
|
|
117
|
-
|
|
207
|
+
let tracked = null;
|
|
208
|
+
const { result, endpoints, keys } = withTracking(() => {
|
|
209
|
+
if (keyError) return Promise.reject(keyError);
|
|
210
|
+
if (!custom) return start(runSignal);
|
|
211
|
+
return fetchShared(key, start, { signal: runSignal, staleTime: age, deps: () => tracked });
|
|
212
|
+
}, { staleTime: inner });
|
|
213
|
+
tracked = { endpoints, keys };
|
|
214
|
+
register(key, endpoints, keys);
|
|
215
|
+
return result.then(
|
|
216
|
+
(v) => {
|
|
217
|
+
if (t !== token) return { superseded: true };
|
|
218
|
+
loadedAt = Date.now();
|
|
219
|
+
batch(() => {
|
|
220
|
+
data.value = v;
|
|
221
|
+
error.value = undefined;
|
|
222
|
+
loading.value = false;
|
|
223
|
+
settled.value = true;
|
|
224
|
+
});
|
|
225
|
+
// A custom key joined a request someone else started: register what it called.
|
|
226
|
+
if (custom && endpoints.size === 0) register(key, endpoints, keys);
|
|
227
|
+
return { ok: true, value: v };
|
|
228
|
+
},
|
|
229
|
+
(e) => {
|
|
230
|
+
if (t !== token) return { superseded: true };
|
|
231
|
+
// Keep the last good `data` (stale-while-error); only `error` flips.
|
|
232
|
+
const first = !settled.value;
|
|
233
|
+
batch(() => {
|
|
234
|
+
error.value = e;
|
|
235
|
+
loading.value = false;
|
|
236
|
+
});
|
|
237
|
+
failed(e, first);
|
|
238
|
+
return { ok: false, error: e };
|
|
239
|
+
},
|
|
240
|
+
);
|
|
118
241
|
}
|
|
119
242
|
|
|
120
243
|
// --- `<Pending>` boundaries (pending.js) ------------------------------------
|
|
@@ -125,7 +248,7 @@ export function resource(source, fetcher, options = {}) {
|
|
|
125
248
|
const handle = {
|
|
126
249
|
loading: () => loading.value,
|
|
127
250
|
settled: () => settled.value,
|
|
128
|
-
refetch: () => (disposed ? undefined :
|
|
251
|
+
refetch: () => (disposed ? undefined : reload()),
|
|
129
252
|
};
|
|
130
253
|
function track(boundary) {
|
|
131
254
|
if (!boundary || boundaries.has(boundary)) return;
|
|
@@ -148,14 +271,19 @@ export function resource(source, fetcher, options = {}) {
|
|
|
148
271
|
const host = getCurrentInstance();
|
|
149
272
|
if (host) track(closestPending(host));
|
|
150
273
|
// Runs its cleanup only when the owning scope is disposed (no tracked reads).
|
|
274
|
+
// `revalidateOn`: refetch on focus / reconnect once the data is older than staleTime.
|
|
275
|
+
const unwatch = watch(revalidateEvents(options.revalidateOn), () => {
|
|
276
|
+
if (!disposed && Date.now() - loadedAt >= staleTime) reload();
|
|
277
|
+
});
|
|
151
278
|
const disposeTracking = effect(() => () => {
|
|
152
279
|
disposed = true;
|
|
280
|
+
unwatch();
|
|
153
281
|
for (const boundary of boundaries) boundary.__untrack(handle);
|
|
154
282
|
boundaries.clear();
|
|
155
283
|
});
|
|
156
284
|
const disposeFetching = effect(() => {
|
|
157
285
|
const value = src(); // the effect's ONLY tracked read
|
|
158
|
-
if (value
|
|
286
|
+
if (paused(value)) {
|
|
159
287
|
// Paused: cancel anything in flight and settle as "not loading".
|
|
160
288
|
untracked(() => {
|
|
161
289
|
token++;
|
|
@@ -164,6 +292,7 @@ export function resource(source, fetcher, options = {}) {
|
|
|
164
292
|
loading.value = false;
|
|
165
293
|
});
|
|
166
294
|
unregisterResource(entry);
|
|
295
|
+
follow(null);
|
|
167
296
|
return;
|
|
168
297
|
}
|
|
169
298
|
untracked(() => run(value));
|
|
@@ -173,6 +302,7 @@ export function resource(source, fetcher, options = {}) {
|
|
|
173
302
|
token++;
|
|
174
303
|
controller?.abort();
|
|
175
304
|
unregisterResource(entry);
|
|
305
|
+
follow(null);
|
|
176
306
|
};
|
|
177
307
|
});
|
|
178
308
|
// A component body runs outside any scope; its host tears down `_cleanups` on
|
|
@@ -181,10 +311,27 @@ export function resource(source, fetcher, options = {}) {
|
|
|
181
311
|
if (host && Array.isArray(host._cleanups)) host._cleanups.push(disposeTracking, disposeFetching);
|
|
182
312
|
}
|
|
183
313
|
|
|
184
|
-
|
|
314
|
+
// Re-run with the current source value, bypassing `staleTime`. Paused: undefined.
|
|
315
|
+
function rerun() {
|
|
185
316
|
const value = untracked(src);
|
|
186
|
-
|
|
187
|
-
|
|
317
|
+
return paused(value) ? undefined : run(value, { force: true });
|
|
318
|
+
}
|
|
319
|
+
// For `invalidate()`, `<Pending>` and error-boundary retries: never rejects, since
|
|
320
|
+
// the failure already shows on `error` (or goes to a boundary).
|
|
321
|
+
function reload() {
|
|
322
|
+
return rerun()?.then(() => undefined);
|
|
323
|
+
}
|
|
324
|
+
// Public: resolves with the new data (undefined if a newer run superseded it) and
|
|
325
|
+
// rejects when the fetch fails. The failure also shows on `error`, so a caller that
|
|
326
|
+
// ignores the promise (`onclick={() => r.refetch()}`) is not an unhandled rejection;
|
|
327
|
+
// one that awaits it still sees the rejection.
|
|
328
|
+
function refetch() {
|
|
329
|
+
const result = rerun()?.then((outcome) => {
|
|
330
|
+
if (outcome.ok === false) throw outcome.error;
|
|
331
|
+
return outcome.value;
|
|
332
|
+
});
|
|
333
|
+
result?.catch(() => {});
|
|
334
|
+
return result;
|
|
188
335
|
}
|
|
189
336
|
|
|
190
337
|
// A read while a boundary's children are being built makes that boundary wait on
|
|
@@ -207,7 +354,19 @@ export function resource(source, fetcher, options = {}) {
|
|
|
207
354
|
reading();
|
|
208
355
|
return error.value;
|
|
209
356
|
},
|
|
210
|
-
/**
|
|
357
|
+
/**
|
|
358
|
+
* Re-run the fetcher with the current source value (no-op while paused). Resolves
|
|
359
|
+
* with the new data; rejects when the fetch fails.
|
|
360
|
+
*/
|
|
211
361
|
refetch,
|
|
212
362
|
};
|
|
213
363
|
}
|
|
364
|
+
|
|
365
|
+
/** Is the source paused on the server? A source that throws there counts as running. */
|
|
366
|
+
function startsPaused(src) {
|
|
367
|
+
try {
|
|
368
|
+
return paused(untracked(src));
|
|
369
|
+
} catch {
|
|
370
|
+
return false;
|
|
371
|
+
}
|
|
372
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Revalidation triggers for `resource(…, { revalidateOn })` (docs/DATA.md §3): when the
|
|
2
|
+
// tab becomes visible again ("focus") or the browser comes back online ("online"), a
|
|
3
|
+
// resource whose data is older than its `staleTime` refetches. One listener per event
|
|
4
|
+
// serves every resource; nothing is installed until a resource asks.
|
|
5
|
+
|
|
6
|
+
const watchers = { focus: new Set(), online: new Set() };
|
|
7
|
+
let installed = false;
|
|
8
|
+
|
|
9
|
+
function fire(event) {
|
|
10
|
+
for (const fn of [...watchers[event]]) fn();
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function install() {
|
|
14
|
+
if (installed || typeof document === "undefined") return;
|
|
15
|
+
installed = true;
|
|
16
|
+
document.addEventListener("visibilitychange", () => {
|
|
17
|
+
if (document.visibilityState === "visible") fire("focus");
|
|
18
|
+
});
|
|
19
|
+
globalThis.addEventListener?.("online", () => fire("online"));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Normalize `revalidateOn` to a list of events, refusing unknown ones. */
|
|
23
|
+
export function revalidateEvents(value) {
|
|
24
|
+
const events = value == null ? [] : Array.isArray(value) ? value : [value];
|
|
25
|
+
for (const event of events) {
|
|
26
|
+
if (!(event in watchers)) throw new TypeError(`revalidateOn: expected "focus" or "online", got ${JSON.stringify(event)}`);
|
|
27
|
+
}
|
|
28
|
+
return events;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Call `fn` on each of `events`; returns the unwatch function. */
|
|
32
|
+
export function watch(events, fn) {
|
|
33
|
+
if (events.length === 0) return () => {};
|
|
34
|
+
install();
|
|
35
|
+
for (const event of events) watchers[event].add(fn);
|
|
36
|
+
return () => {
|
|
37
|
+
for (const event of events) watchers[event].delete(fn);
|
|
38
|
+
};
|
|
39
|
+
}
|
package/runtime/route-data.d.ts
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
* `"/todos"` → `/todos/__data.json`, preserving the query string. */
|
|
3
3
|
export function dataUrlFor(pathname: any, search?: string): string;
|
|
4
4
|
/**
|
|
5
|
-
* Fetch a route's loader data. 200 → the parsed JSON; 404 → `
|
|
6
|
-
*
|
|
7
|
-
* commits the navigation with no data).
|
|
5
|
+
* Fetch a route's loader data. 200 → the parsed JSON; 404 → a `RouteNotFound`
|
|
6
|
+
* (`notFound()`, or a path with no page); a redirect → a `RouteRedirect`; anything
|
|
7
|
+
* else throws (the router reports it and commits the navigation with no data).
|
|
8
8
|
*/
|
|
9
9
|
export function fetchRouteData(pathname: any, search?: string): Promise<any>;
|
|
10
10
|
/** The loader data inlined by the server for the current document, or `undefined`. */
|
|
@@ -22,3 +22,9 @@ export class RouteRedirect {
|
|
|
22
22
|
/** A full page load is needed (the server redirected the data request itself). */
|
|
23
23
|
reload: boolean;
|
|
24
24
|
}
|
|
25
|
+
/** Returned by `fetchRouteData` when the route has no data: the loader called `notFound()`. */
|
|
26
|
+
export class RouteNotFound {}
|
|
27
|
+
/** The inline-data payload marking a server-rendered 404 page (a loader's `notFound()`). */
|
|
28
|
+
export const NOT_FOUND_PAYLOAD: string;
|
|
29
|
+
/** Does the inline data mark a server-rendered 404 page? */
|
|
30
|
+
export function isNotFoundPayload(data: unknown): boolean;
|
package/runtime/route-data.js
CHANGED
|
@@ -8,9 +8,10 @@
|
|
|
8
8
|
// servers answer dynamically);
|
|
9
9
|
// • dev/CSR first load — the same fetch, since there is no server markup.
|
|
10
10
|
//
|
|
11
|
-
// The endpoint returns the raw loader JSON (no envelope)
|
|
12
|
-
//
|
|
13
|
-
// `
|
|
11
|
+
// The endpoint returns the raw loader JSON (no envelope). A loader that returns
|
|
12
|
+
// nothing answers 200 `null` (and a prerendered page's file holds `null`), so a 404
|
|
13
|
+
// means the loader called `notFound()` or the path has no page: the router shows
|
|
14
|
+
// the 404 page, as a full page load of that URL does.
|
|
14
15
|
|
|
15
16
|
/** The reserved per-route data filename/URL suffix (`/todos` → `/todos/__data.json`). */
|
|
16
17
|
export const DATA_FILE = "__data.json";
|
|
@@ -41,9 +42,15 @@ export class RouteRedirect {
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
/**
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
|
|
45
|
+
* What `fetchRouteData` returns when the endpoint answers 404: the loader called
|
|
46
|
+
* `notFound()`, or (on a static host) the path was never prerendered.
|
|
47
|
+
*/
|
|
48
|
+
export class RouteNotFound {}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Fetch a route's loader data. 200 → the parsed JSON; 404 → a {@link RouteNotFound};
|
|
52
|
+
* a redirect → a {@link RouteRedirect}; anything else throws (the router reports it
|
|
53
|
+
* and commits the navigation with no data).
|
|
47
54
|
*/
|
|
48
55
|
export async function fetchRouteData(pathname, search = "") {
|
|
49
56
|
// "manual": a redirect is not data. Following it would fetch an HTML page.
|
|
@@ -55,7 +62,7 @@ export async function fetchRouteData(pathname, search = "") {
|
|
|
55
62
|
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400)) {
|
|
56
63
|
return new RouteRedirect(pathname + search, { reload: true });
|
|
57
64
|
}
|
|
58
|
-
if (res.status === 404) return
|
|
65
|
+
if (res.status === 404) return new RouteNotFound();
|
|
59
66
|
if (!res.ok) {
|
|
60
67
|
const error = Object.assign(new Error(`route data request for ${pathname} failed (${res.status})`), { status: res.status });
|
|
61
68
|
// The endpoint names the layout whose loader failed (see the server's loader registry).
|
|
@@ -89,6 +96,20 @@ export function routeErrorPayload(error) {
|
|
|
89
96
|
return JSON.stringify(marker).replace(/</g, "\\u003c");
|
|
90
97
|
}
|
|
91
98
|
|
|
99
|
+
const NOT_FOUND = "__afwNotFound";
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The inline-data payload marking a page the server answered with the 404 page (a
|
|
103
|
+
* loader called `notFound()`): the URL matches a route, but the markup is the 404
|
|
104
|
+
* page's, so first paint must adopt that instead of the route's layouts.
|
|
105
|
+
*/
|
|
106
|
+
export const NOT_FOUND_PAYLOAD = JSON.stringify({ [NOT_FOUND]: true });
|
|
107
|
+
|
|
108
|
+
/** Does the inline data mark a server-rendered 404 page? */
|
|
109
|
+
export function isNotFoundPayload(data) {
|
|
110
|
+
return !!data && typeof data === "object" && data[NOT_FOUND] === true;
|
|
111
|
+
}
|
|
112
|
+
|
|
92
113
|
/** The error a {@link routeErrorPayload} carries, as an `Error` with `status`, or null. */
|
|
93
114
|
export function routeErrorFrom(data) {
|
|
94
115
|
const marker = data && typeof data === "object" ? data[ROUTE_ERROR] : null;
|
package/runtime/route-match.js
CHANGED
|
@@ -125,17 +125,24 @@ const segmentKind = (seg) => {
|
|
|
125
125
|
/**
|
|
126
126
|
* Sort comparator: more specific routes first, by URL (groups dropped). Compares
|
|
127
127
|
* segment kinds left to right (static < `[param]` < `[[param]]` < `[...rest]` <
|
|
128
|
-
* `[[...rest]]`)
|
|
129
|
-
*
|
|
128
|
+
* `[[...rest]]`). With equal kinds, the route with more segments is more specific —
|
|
129
|
+
* unless every extra segment is optional: then both match the shorter URL, and the
|
|
130
|
+
* route that names it exactly wins (`/shop` before `/shop/[[...filters]]`). The final
|
|
131
|
+
* tie-break is lexical, for a deterministic order.
|
|
130
132
|
*/
|
|
131
133
|
export function compareRoutes(a, b) {
|
|
132
134
|
const sa = urlOf(a).split("/").filter(Boolean);
|
|
133
135
|
const sb = urlOf(b).split("/").filter(Boolean);
|
|
134
|
-
|
|
136
|
+
const shared = Math.min(sa.length, sb.length);
|
|
137
|
+
for (let i = 0; i < shared; i++) {
|
|
135
138
|
const d = segmentKind(sa[i]) - segmentKind(sb[i]);
|
|
136
139
|
if (d !== 0) return d;
|
|
137
140
|
}
|
|
138
|
-
if (sa.length !== sb.length)
|
|
141
|
+
if (sa.length !== sb.length) {
|
|
142
|
+
const extra = (sa.length > sb.length ? sa : sb).slice(shared);
|
|
143
|
+
const longerFirst = sb.length - sa.length;
|
|
144
|
+
return extra.every((seg) => OPTIONAL.test(seg)) ? -longerFirst : longerFirst;
|
|
145
|
+
}
|
|
139
146
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
140
147
|
}
|
|
141
148
|
|
package/runtime/router.js
CHANGED
|
@@ -23,7 +23,7 @@ import { prepareRouteHead, updateRouteHead } from "./head.js";
|
|
|
23
23
|
import { beginHydration, cursor, endHydration, renderedForPath, runBuild } from "./hydrate.js";
|
|
24
24
|
import { collectHotState, withHotCarry } from "./hot-carry.js";
|
|
25
25
|
import { buildScopedView, runCleanup, runMount } from "./mount.js";
|
|
26
|
-
import { RouteRedirect, fetchRouteData, readInlineRouteData, routeErrorFrom } from "./route-data.js";
|
|
26
|
+
import { RouteNotFound, RouteRedirect, fetchRouteData, isNotFoundPayload, readInlineRouteData, routeErrorFrom } from "./route-data.js";
|
|
27
27
|
import { enterPending, exitPending } from "./pending-scope.js";
|
|
28
28
|
import { setRouteErrorHandler } from "./route-errors.js";
|
|
29
29
|
import { enterEntry, manageScroll, rememberScroll, restoreScroll } from "./scroll.js";
|
|
@@ -864,6 +864,8 @@ export async function refreshRouteData() {
|
|
|
864
864
|
const data = await fetchRouteData(pathname, window.location.search);
|
|
865
865
|
if (seq !== navSeq) return; // a navigation since owns the data
|
|
866
866
|
if (data instanceof RouteRedirect) return followRedirect(data);
|
|
867
|
+
// The data is gone (`notFound()` now): navigate again, which shows the 404 page.
|
|
868
|
+
if (data instanceof RouteNotFound) return navigate(pathname + window.location.search, true);
|
|
867
869
|
state.data.value = data;
|
|
868
870
|
} catch (e) {
|
|
869
871
|
reportError(e, { phase: "data", path: pathname });
|
|
@@ -995,9 +997,8 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
|
|
|
995
997
|
if (redirected) return;
|
|
996
998
|
}
|
|
997
999
|
|
|
998
|
-
const
|
|
999
|
-
|
|
1000
|
-
(routes.notFound ? { entry: routes.notFound, params: {}, route: null } : null);
|
|
1000
|
+
const notFoundMatch = () => (routes.notFound ? { entry: routes.notFound, params: {}, route: null } : null);
|
|
1001
|
+
let match = matchRoute(url.pathname) || notFoundMatch();
|
|
1001
1002
|
|
|
1002
1003
|
// Loader data (docs/DATA.md): resolved before any state write / history push /
|
|
1003
1004
|
// DOM swap, mirroring the guard's "settle before commit" flow. First paint over
|
|
@@ -1021,6 +1022,12 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
|
|
|
1021
1022
|
// The server rendered this page's `error.jsx` (its loader failed).
|
|
1022
1023
|
dataError = routeErrorFrom(data);
|
|
1023
1024
|
if (dataError) data = undefined;
|
|
1025
|
+
// The server answered with the 404 page (the loader called `notFound()`): adopt
|
|
1026
|
+
// that markup, inside the root layout, not this route's layout chain.
|
|
1027
|
+
if (isNotFoundPayload(data)) {
|
|
1028
|
+
data = undefined;
|
|
1029
|
+
match = notFoundMatch();
|
|
1030
|
+
}
|
|
1024
1031
|
} else {
|
|
1025
1032
|
try {
|
|
1026
1033
|
const warmed = takePrefetched(url.pathname + url.search);
|
|
@@ -1031,6 +1038,12 @@ export async function navigate(path, replace = false, isPop = false, hydrate = f
|
|
|
1031
1038
|
}
|
|
1032
1039
|
if (seq !== navSeq) return; // a newer navigation superseded this one
|
|
1033
1040
|
if (data instanceof RouteRedirect) return followRedirect(data);
|
|
1041
|
+
// The loader called `notFound()`: show the 404 page, as the server does for a
|
|
1042
|
+
// full page load of this URL, instead of the page with no data.
|
|
1043
|
+
if (data instanceof RouteNotFound) {
|
|
1044
|
+
data = undefined;
|
|
1045
|
+
match = notFoundMatch();
|
|
1046
|
+
}
|
|
1034
1047
|
}
|
|
1035
1048
|
}
|
|
1036
1049
|
|