-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathaction.ts
More file actions
535 lines (510 loc) · 21.8 KB
/
Copy pathaction.ts
File metadata and controls
535 lines (510 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
import { $TRACK, action as createSolidAction, createMemo, onCleanup, getOwner } from "solid-js";
import { isResponseEnvelope, isServer, REVALIDATE_HEADER, type JSX } from "@solidjs/web";
import {
createServerReference,
decodeRedirectHeaderValue,
decodeResponsePayload,
parseServerFunctionUrl,
REDIRECT_HEADER,
subscribeFlightData
} from "@solidjs/web/server-functions";
// The explicit /server specifier is safe here: the only call site is
// server-guarded, so client builds tree-shake the codec away.
import { decodeFlashCookie } from "@solidjs/web/server-functions/server";
import { provideFlashDecoder, provideFlightConsumer, useRouter } from "../routing.js";
import { setRouterFormHandler } from "./events.js";
import type {
RouterContext,
Submission,
Navigator,
NarrowResponse
} from "../types.js";
import { mockBase, setFunctionName } from "../utils.js";
import { cacheKeyOp, deliverFlightData, hashKey, revalidate, query } from "./query.js";
export type Action<T extends Array<any>, U, V = T> = (T extends [FormData | URLSearchParams] | []
? JSX.SerializableAttributeValue
: unknown) &
((...vars: T) => Promise<NarrowResponse<U>>) & {
url: string;
with<A extends any[], B extends any[]>(
this: (this: any, ...args: [...A, ...B]) => Promise<NarrowResponse<U>>,
...args: A
): Action<B, U, V>;
onSubmit(hook: (...args: V extends Array<any> ? V : T) => void): Action<T, U, V>;
onSettled(hook: (submission: Submission<V extends Array<any> ? V : T, NarrowResponse<U>>) => void): Action<
T,
U,
V
>;
};
type ActionFactory = {
<T extends Array<any>, U = void>(fn: (...args: T) => Promise<U>, name?: string): Action<T, U>;
<T extends Array<any>, U = void>(fn: (...args: T) => Promise<U>, options?: { name?: string }): Action<T, U>;
};
type InternalAction<T extends Array<any>, U, V = T> = {
(this: { r: RouterContext; f?: HTMLFormElement }, ...args: T): Promise<NarrowResponse<U>>;
url: string;
with<A extends any[], B extends any[]>(
this: InternalAction<[...A, ...B], U, V>,
...args: A
): InternalAction<B, U, V>;
onSubmit(hook: (...args: V extends Array<any> ? V : T) => void): InternalAction<T, U, V>;
onSettled(
hook: (submission: Submission<V extends Array<any> ? V : T, NarrowResponse<U>>) => void
): InternalAction<T, U, V>;
base: string;
[submitHooksSymbol]: Map<symbol, (...args: any[]) => void>;
[settledHooksSymbol]: Map<symbol, (submission: Submission<any, any>) => void>;
[invokeSymbol]: (
this: { r: RouterContext; f?: HTMLFormElement },
args: any[],
current: InternalAction<any, any, any>
) => Promise<any>;
};
const submitHooksSymbol = Symbol("routerActionSubmitHooks");
const settledHooksSymbol = Symbol("routerActionSettledHooks");
const invokeSymbol = Symbol("routerActionInvoke");
// Forms submitted through delegation are marked `aria-busy` while their
// action is in flight — the form half of the attribute vocabulary links get
// (`data-active`/`data-pending`). Style with `form[aria-busy] button { ... }`.
// A counter (not a boolean) keeps the attribute through overlapping
// submissions from the same form.
const busyForms = /* #__PURE__ */ new WeakMap<HTMLFormElement, number>();
function setFormBusy(form: HTMLFormElement, delta: number) {
const count = (busyForms.get(form) || 0) + delta;
busyForms.set(form, count);
count > 0 ? form.setAttribute("aria-busy", "true") : form.removeAttribute("aria-busy");
}
export const actions = /* #__PURE__ */ new Map<string, Action<any, any>>();
/**
* The document-delegation submit handler for router actions. Lives here —
* not in events.ts — so the router's event wiring holds no static reference
* to the action module; `installRouterIntegrations` slots it in when the
* first action is created on the client.
*/
export function handleFormAction(evt: SubmitEvent, router: RouterContext, actionBase: string) {
if (evt.defaultPrevented) return;
let actionRef =
evt.submitter && evt.submitter.hasAttribute("formaction")
? evt.submitter.getAttribute("formaction")
: (evt.target as HTMLElement).getAttribute("action");
if (!actionRef) return;
const serverAction = !actionRef.startsWith("https://action/");
if (serverAction) {
// normalize server actions
const url = new URL(actionRef, mockBase);
actionRef = router.parsePath(url.pathname + url.search);
if (!actionRef.startsWith(actionBase)) return;
}
if ((evt.target as HTMLFormElement).method.toUpperCase() !== "POST")
throw new Error("Only POST forms are supported for Actions");
// A registry miss on a server-action url is a direct bind whose module
// never loaded client-side (server components): the url is self-describing
// (the id in the path, bound `?args` in the query), so a generic invocation
// is synthesized from it — delegation alone is sufficient, the no-JS path
// stays a no-JS fallback.
// Client-only actions (`https://action/`) are their module's JS by
// definition, so a miss there falls through to native submission.
const handler = actions.get(actionRef) || (serverAction && createServerFormAction(actionRef));
if (handler) {
evt.preventDefault();
const data = new FormData(evt.target as HTMLFormElement, evt.submitter);
handler.call(
{ r: router, f: evt.target },
(evt.target as HTMLFormElement).enctype === "multipart/form-data"
? data
: new URLSearchParams(data as any)
);
}
}
/**
* Synthesizes a router action for a server-rendered action url. The url
* carries everything an invocation needs — the function id in the path
* (`<endpoint>/<id>`) and any bound `.with()` arguments (plain JSON in
* `?args`, which the server prepends for natural-encoding bodies exactly as
* it does for no-JS posts) — so the FormData is posted through the
* server-function transport, which addresses its own scripted calls at the
* url's data sibling (`<endpoint>/data/<id>`, solidjs/solid#3094) with the
* bound query intact: submissions, `aria-busy`, redirects, revalidation,
* and single-flight all flow through the normal action machinery.
* Registered under the rendered url, so repeat submits reuse it (and a
* later real registration overrides it).
*/
function createServerFormAction(
url: string
): Action<[FormData | URLSearchParams], unknown> | undefined {
const id = parseServerFunctionUrl(url);
if (!id) return undefined;
// typecheck resolves the server half of the dual module; this path only
// runs in the browser, where the client transport's signature applies
const stub = (
createServerReference as unknown as (
id: string,
name?: string,
base?: string
) => (...args: unknown[]) => Promise<unknown>
)(id, undefined, url);
const caller = Object.assign(
(form: FormData | URLSearchParams) => stub(form) as Promise<unknown>,
{ url }
);
return actionImpl(caller);
}
/**
* Entry point for delegation's lazy fallback (data/events.ts): when no form
* handler was ever installed — no action module in the client graph at all —
* the router intercepts posts to server-action urls synchronously and loads
* this module to run them. The FormData was captured at submit time; only
* the enctype conversion and the generic invocation happen here.
*/
export function submitServerForm(
router: RouterContext,
url: string,
form: HTMLFormElement,
data: FormData
) {
const handler = actions.get(url) || createServerFormAction(url);
// not an address (`<endpoint>/<id>`) — not the server function convention;
// nothing can run it, resubmit natively (submit() bypasses the delegated
// handler)
if (!handler) return form.submit();
handler.call(
{ r: router, f: form },
form.enctype === "multipart/form-data" ? data : new URLSearchParams(data as any)
);
}
// Wires the action layer into the router's slots exactly once, triggered by
// the first action creation. Not an import side effect — with
// `sideEffects: false`, module evaluation only happens when action() is
// actually used, which is precisely when the wiring is wanted: no action in
// the graph means no form interception, no single-flight subscription (the
// server is never asked to collect), and no flash cookies to decode. On the
// server, actions are created at module scope, so the flash decoder is
// always installed before useSubmission can read the submissions signal.
let integrationsInstalled = false;
function installRouterIntegrations() {
if (integrationsInstalled) return;
integrationsInstalled = true;
if (isServer) {
// Server-only: initSubmissions only decodes during SSR, so client builds
// tree-shake the codec (which now lives behind the runtime's server entry).
provideFlashDecoder(decodeFlashCookie);
} else {
setRouterFormHandler(handleFormAction);
provideFlightConsumer(setupFlightDataConsumer);
}
}
export function useSubmissions<T extends Array<any>, U, V>(
fn: Action<T, U, V>,
filter?: (input: V) => boolean
): Submission<V, NarrowResponse<U>>[] {
const router = useRouter();
const subs = createMemo(() =>
router.submissions[0]().filter(s => s.url === (fn as any).base && (!filter || filter(s.input)))
);
return new Proxy<Submission<any, any>[]>([] as any, {
get(_, property) {
if (property === $TRACK) return subs();
return subs()[property as any];
},
has(_, property) {
return property in subs();
}
});
}
export function useAction<T extends Array<any>, U, V>(action: Action<T, U, V>) {
const r = useRouter();
return (...args: Parameters<Action<T, U, V>>) => action.apply({ r }, args);
}
function actionImpl<T extends Array<any>, U = void>(
fn: (...args: T) => Promise<U>,
options: string | { name?: string } = {}
): Action<T, U> {
async function invoke(
this: { r: RouterContext; f?: HTMLFormElement },
variables: T,
current: InternalAction<T, U>
): Promise<NarrowResponse<U>> {
const router = this.r;
const form = this.f;
const submitHooks = current[submitHooksSymbol];
const settledHooks = current[settledHooksSymbol];
// Single-flight opt-in is no longer per call: the router's registered
// flight-data consumer (see setupFlightDataConsumer) makes the transport
// send the request header itself, so the mutation is just called.
const runMutation = () => fn(...variables);
const run = createSolidAction(
async function* (context: { call: () => Promise<U>; optimistic?: () => void }) {
context.optimistic?.();
try {
const value = await context.call();
yield;
return { error: false, value };
} catch (error) {
yield;
return { error: true, value: error };
}
}
);
form && setFormBusy(form, 1);
let settled;
let response;
// The transport consumer is awaited before a single-flight mutation
// resolves, so a counter delta over the call tells whether this action's
// metadata was already applied. Overlapping mutations can cross-attribute
// a run (skipping one default revalidation another pass just covered) —
// a far smaller window than predicting from the function's identity,
// which misses every response the server returned without flight data.
const flightApplicationsBefore = flightApplications;
try {
settled = await settleActionResult(
run({
call: runMutation,
optimistic: submitHooks.size
? () => {
for (const hook of submitHooks.values()) hook(...variables);
}
: undefined
})
);
response = await handleResponse(
settled.value,
settled.error,
router.navigatorFactory(),
flightApplications !== flightApplicationsBefore
);
} finally {
form && setFormBusy(form, -1);
}
let submission!: Submission<T, NarrowResponse<U>>;
submission = {
input: variables,
url,
result: response && response.data,
error: response && response.error,
clear() {
router.submissions[1](entries => entries.filter(entry => entry !== submission));
},
retry() {
submission.clear();
return current[invokeSymbol].call({ r: router, f: form }, variables, current);
}
};
// Book-keeping is intentional: only outcomes worth showing or retrying
// (a result or an error) enter the submissions list, so the typical void
// mutation leaves nothing behind. Settled hooks still see every
// completion — void, metadata-only, and redirects included — one
// `onSettled` per invocation (#580).
response && router.submissions[1](entries => [...entries, submission]);
for (const hook of settledHooks.values()) hook(submission);
if (response) {
if (response.error && !form) throw response.error;
return response.data as NarrowResponse<U>;
}
return undefined as NarrowResponse<U>;
}
const o = typeof options === "string" ? { name: options } : options;
const name = o.name || (!isServer ? String(hashString(fn.toString())) : undefined);
const url: string = (fn as any).url || (name && `https://action/${name}`) || "";
const wrapped = toAction<T, U, T>(invoke as InternalAction<T, U, T>[typeof invokeSymbol], url) as Action<T, U>;
if (name) setFunctionName(wrapped, name);
return wrapped;
}
export const action = actionImpl as ActionFactory;
function toAction<T extends Array<any>, U, V = T>(
invoke: InternalAction<T, U, V>[typeof invokeSymbol],
url: string,
boundArgs: unknown[] = [],
base = url,
submitHooks = new Map<symbol, (...args: any[]) => void>(),
settledHooks = new Map<symbol, (submission: Submission<any, any>) => void>()
): Action<T, U, V> {
const fn = function (this: { r: RouterContext; f?: HTMLFormElement }, ...args: T) {
return invoke.call(this, [...boundArgs, ...args], fn);
} as InternalAction<T, U, V>;
fn.toString = () => {
if (!url) throw new Error("Client Actions need explicit names if server rendered");
return url;
};
fn.with = function <A extends any[], B extends any[]>(
this: InternalAction<[...A, ...B], U, V>,
...args: A
) {
const uri = new URL(url, mockBase);
uri.searchParams.set("args", hashKey(args));
const next = toAction<B, U, V>(
invoke,
(uri.origin === "https://action" ? uri.origin : "") + uri.pathname + uri.search,
[...boundArgs, ...args],
base,
submitHooks,
settledHooks
) as unknown as InternalAction<B, U, V>;
return next;
};
fn.onSubmit = function (hook: (...args: V extends Array<any> ? V : T) => void) {
const id = Symbol("actionOnSubmitHook");
submitHooks.set(id, hook as (...args: any[]) => void);
getOwner() && onCleanup(() => submitHooks.delete(id));
return this;
};
fn.onSettled = function (
hook: (submission: Submission<V extends Array<any> ? V : T, NarrowResponse<U>>) => void
) {
const id = Symbol("actionOnSettledHook");
settledHooks.set(id, hook as (submission: Submission<any, any>) => void);
getOwner() && onCleanup(() => settledHooks.delete(id));
return this;
};
fn.url = url;
fn.base = base;
fn[submitHooksSymbol] = submitHooks;
fn[settledHooksSymbol] = settledHooks;
fn[invokeSymbol] = invoke;
installRouterIntegrations();
if (!isServer) {
actions.set(url, fn as unknown as Action<T, U, V>);
// Only remove the registration if it still belongs to this instance —
// a re-created action (e.g. a new `.with()` binding after revalidation)
// may have registered itself under the same URL since.
getOwner() &&
onCleanup(() => actions.get(url) === (fn as unknown) && actions.delete(url));
}
return fn as unknown as Action<T, U, V>;
}
const hashString = (s: string) =>
s.split("").reduce((a, b) => ((a << 5) - a + b.charCodeAt(0)) | 0, 0);
async function settleActionResult<T>(result: T | Promise<T> | AsyncIterable<T>) {
const value = result as any;
if (value && typeof value.then === "function") {
return (result as Promise<T>).then(value => value);
}
if (value && typeof value.next === "function") {
const iterator = value as AsyncIterator<T>;
let next = await iterator.next();
while (!next.done) {
next = await iterator.next();
}
return next.value;
}
return result as T;
}
// Invocation count of the flight-data consumer. An action compares it across
// its mutation call to learn whether the transport already applied this
// response's metadata (and so the default revalidation pass must not run
// again and wipe the freshly seeded cache).
let flightApplications = 0;
// The statuses fetch follows (Fetch §2.2.3) — the set the server masks into
// the redirect carrier for scripted calls, and the set a locally-produced
// redirect() envelope wears for real.
const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
/**
* Registers the router as the single-flight consumer of the server function
* transport. Subscribing is the opt-in: while registered, the transport
* sends the `X-Single-Flight` request header on mutations and delivers the
* folded payload here — fresh route data is seeded into the `query` cache
* and the envelope metadata (redirect `Location`, `X-Revalidate` keys) is
* applied, all before the action sees its plain return value. Called by the
* Router component on the client unless `singleFlight={false}`, which now
* simply means "never subscribe" — no consumer, no request header, no
* collection work on the server. Returns the unsubscribe function.
*/
export function setupFlightDataConsumer(router: RouterContext) {
return subscribeFlightData<Record<string, any>>((data, { response }) => {
flightApplications++;
return applyResponseMetadata(response, router.navigatorFactory(), data);
});
}
/**
* Applies a server function response's integration metadata: `X-Revalidate`
* keys invalidate, the redirect carrier navigates (soft when same-origin,
* hard otherwise), flight data seeds the query cache, and matching entries
* revalidate. Shared by the flight-data consumer and the action response
* path (which still sees metadata-bearing responses when no flight data was
* collected).
*/
function applyResponseMetadata(
metadata: Response | undefined,
navigate: Navigator,
flightData?: Record<string, any>
) {
let keys: string[] | undefined;
if (metadata) {
if (metadata.headers.has(REVALIDATE_HEADER))
keys = metadata.headers.get(REVALIDATE_HEADER)!.split(",");
// The carrier delivers the target RESOLVED to an absolute url
// (solidjs/solid#3102), so the soft/hard split is a real origin
// comparison — never a guess from how the author spelled the target,
// which sent `redirect("/")` and `redirect(new URL("/", url).href)`
// down different navigation paths (solidjs/solid#3107). A redirect
// produced locally (a client-side action's `redirect()`) never crossed
// the wire, so no carrier was attached: it is the real 3xx with its
// Location, resolved against the page it runs in. A `Location` on any
// other status is the author's data (a 201's created-at) and never
// navigates. Same-origin targets navigate softly under the router;
// anything else leaves the app, so the document goes with it.
// `replace` matches what HTTP gives a form post: the target takes the
// submission's place in history rather than stacking on it.
const carried = decodeRedirectHeaderValue(metadata.headers.get(REDIRECT_HEADER));
const local =
!carried && REDIRECT_STATUSES.has(metadata.status) && metadata.headers.get("Location");
const target = carried
? new URL(carried.url)
: local
? new URL(local, window.location.href)
: undefined;
if (target) {
if (target.origin === window.location.origin) {
navigate(target.pathname + target.search + target.hash, { replace: true });
} else {
window.location.href = target.href;
}
}
}
// invalidate
cacheKeyOp(keys, entry => (entry[0] = 0));
// set cache — and fan the payload out to other keyed stores (live query
// channels adopt delivered values instead of reconnecting)
flightData && Object.keys(flightData).forEach(k => query.set(k, flightData[k]));
flightData && deliverFlightData(flightData);
// trigger revalidation inside the same transition as the navigation, so
// the redirect commits atomically with fresh data: surviving consumers
// (shared layouts) the flight payload didn't seed refetch and hold the
// commit rather than painting stale and updating after. Seeded entries
// are fresh again by now, so the sweep re-reads them from cache.
revalidate(keys, false);
}
async function handleResponse(
response: unknown,
error: boolean | undefined,
navigate: Navigator,
metadataHandled: boolean
) {
let data: any;
let flightData: Record<string, any> | undefined;
let metadata: Response | undefined;
if (isResponseEnvelope(response)) {
// client-only respond(): the value rides in memory beside the metadata
data = response.value;
metadata = response.response;
} else if (response instanceof Response) {
metadata = response;
// responses the transport hands over whole (redirects, revalidation)
// carry a codec-encoded body the router decodes itself. With the
// flight-data consumer registered single-flight payloads never reach
// this path, but a manually opted-in call (no consumer) still can —
// the runtime splits its own envelope shape.
if (response.body) {
const payload = await decodeResponsePayload(response);
data = payload.value;
flightData = payload.flightData as Record<string, any> | undefined;
}
} else if (error) return { error: response };
else data = response;
// The transport consumer applies metadata before returning a server
// function's unwrapped value. Do not treat that value as a second plain
// action response and invalidate the freshly seeded query cache again.
if (!metadataHandled || metadata || flightData)
applyResponseMetadata(metadata, navigate, flightData);
return data != null ? { data } : undefined;
}