Skip to content

Commit b745f10

Browse files
lxsmnsycclaude
andcommitted
feat(web): send files anywhere in rich server function arguments
With enableRichArguments(), a call whose arguments hold files or blobs used to fail before sending, unless the file was the only argument or the last one. Ports solidjs/solid-start#2359 to the core transport. - The rich-args encoder finds each file with a seroval plugin made for the call, wherever the codec meets it: arguments, arrays, objects, maps, sets and FormData entries. - A call with files sends multipart form data. The codec output goes in the `args` field and each file goes as it is in a `file<index>` part. - The new BodyFormat.SerializedFormData ("10") marks the request. - The server decodes `args` with a plugin made for that request, which turns each index back into its part. Other bodies decode without it. - A missing `args` field, a bad index or a missing part is refused with 400. bodySizeLimit bounds the whole body. - Default JSON mode is unchanged. Upload code ships only in the rich-args entry. - The version skew spec moves its unknown tag from "10" to "11". Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 9f64ca9 commit b745f10

10 files changed

Lines changed: 499 additions & 18 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@solidjs/web": patch
3+
---
4+
5+
With `enableRichArguments()`, a server function can take files and blobs anywhere in its arguments. Calls like `upload(file, { tags })`, `upload({ file })` and `upload(formData, 1)` used to fail before sending. They now send multipart form data, with each file as its own part instead of encoded inside the arguments.

‎documentation/solid-2.0/10-server-functions.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ One architectural fact worth stating, because the two directive levels land on o
4444

4545
The package resolves to a client entry in the browser and a server entry elsewhere.
4646

47-
**Client:** `configureServerFunctionsClient({ endpoint?, codec?, fetch?, prepareRequest?, serializeArgs?, responseHandler? })` — call once in the client entry, only when deviating from the defaults (endpoint defaults to `/_server`; `codec` takes seroval plugin options and must match the server’s; `fetch` replaces the function the transport sends with — always called as `(address, init)` — for concerns the runtime has no opinion about: retries, telemetry, a test double, or pointing calls at a route of the app’s own, which the handler serves through the same `Request` it serves everything else with; `prepareRequest` is the transport middleware hook below; `responseHandler` is the integration seam server components install — see [RFC 11](11-server-components.md)). Compiled client output produces callables that POST to the call’s **data address** — `<endpoint>/data/<id>`, the id in a path segment — with no per-call header of their own (a read is exactly its url to caches and `<link rel="preload">`). The data address is the scripted transport’s own path, where answers are the codec’s; the bare `<endpoint>/<id>` address (a reference’s `.url`, what renders into form actions) answers plain HTTP. Two paths because the two caller kinds get differently shaped answers and shared caches key on the URL: with one shape per path, a cached answer can only ever be replayed to the caller kind it was made for. (A third caller kind, `live`'s loop, gets a third path — `<endpoint>/live/<id>`, answered as an event stream; same rule.) **Argument encoding (updated since first draft):** arguments with a natural HTTP encoding (a lone string, FormData, File, Blob, ...) go as-is; everything else is sent as **plain JSON by default** — no serializer in the client bundle — and values JSON can’t carry faithfully (Dates, Maps, Sets, typed arrays, cycles, a top-level `undefined` — except in a bound call whose trailing argument is a body-like object (FormData, URLSearchParams, File, Blob, ...), where the leading arguments ride `?args=` and `undefined` is sent as `null` as in the action url; a trailing string is not a body in this sense, so `fn(1, undefined, "str")` goes through the codec) **throw with a directed message** unless you opt in once via `enableRichArguments()` from `@solidjs/web/server-functions/rich-args`, which installs the codec’s write half (~5 KB gz) as `serializeArgs` — importing the entry is the opt-in at the module-graph level, so the serializer ships only when the app asks for it. _Results_ are unaffected — they always travel through the codec, whose decode half the client carries regardless. Async returns (promises, streams) settle over the open connection via length-prefixed chunk framing; a `live` source's response — requested at the live address — is the same stream framed as server-sent events (see `live(fn)` under the extension surface). (A `@solidjs/web/serialization` subpath exists; most of it is integration-facing plumbing — the bridge exposing the runtime’s serializer machinery for the runtime’s own entries and for integrations building transports — exempt from the 2.0 stability guarantee and subject to change. The one application-facing part is plugin _authoring_: `createPlugin` and `OpaqueReference` are re-exported there from the runtime’s own seroval instance, and custom plugins for the `codec` option must be built from that import — a plugin built against your own `seroval` dependency edge would not fail the build, it would emit nodes the other end of the wire can’t interpret (the version-pinning lesson of solid-start #1474). Application and router code authors plugins there and feeds them to `codec`; everything else on the subpath it should leave alone.)
47+
**Client:** `configureServerFunctionsClient({ endpoint?, codec?, fetch?, prepareRequest?, serializeArgs?, responseHandler? })` — call once in the client entry, only when deviating from the defaults (endpoint defaults to `/_server`; `codec` takes seroval plugin options and must match the server’s; `fetch` replaces the function the transport sends with — always called as `(address, init)` — for concerns the runtime has no opinion about: retries, telemetry, a test double, or pointing calls at a route of the app’s own, which the handler serves through the same `Request` it serves everything else with; `prepareRequest` is the transport middleware hook below; `responseHandler` is the integration seam server components install — see [RFC 11](11-server-components.md)). Compiled client output produces callables that POST to the call’s **data address** — `<endpoint>/data/<id>`, the id in a path segment — with no per-call header of their own (a read is exactly its url to caches and `<link rel="preload">`). The data address is the scripted transport’s own path, where answers are the codec’s; the bare `<endpoint>/<id>` address (a reference’s `.url`, what renders into form actions) answers plain HTTP. Two paths because the two caller kinds get differently shaped answers and shared caches key on the URL: with one shape per path, a cached answer can only ever be replayed to the caller kind it was made for. (A third caller kind, `live`'s loop, gets a third path — `<endpoint>/live/<id>`, answered as an event stream; same rule.) **Argument encoding (updated since first draft):** arguments with a natural HTTP encoding (a lone string, FormData, File, Blob, ...) go as-is; everything else is sent as **plain JSON by default** — no serializer in the client bundle — and values JSON can’t carry faithfully (Dates, Maps, Sets, typed arrays, cycles, a top-level `undefined` — except in a bound call whose trailing argument is a body-like object (FormData, URLSearchParams, File, Blob, ...), where the leading arguments ride `?args=` and `undefined` is sent as `null` as in the action url; a trailing string is not a body in this sense, so `fn(1, undefined, "str")` goes through the codec) **throw with a directed message** unless you opt in once via `enableRichArguments()` from `@solidjs/web/server-functions/rich-args`, which installs the codec’s write half (~5 KB gz) as `serializeArgs` — importing the entry is the opt-in at the module-graph level, so the serializer ships only when the app asks for it. With the codec on, files and blobs can sit anywhere in the arguments: next to other arguments, or inside arrays, objects, maps, sets and `FormData` entries. Such a call sends multipart form data, with the codec output in an `args` field and each file as it is in its own `file<index>` part (`X-Server-Function-Format: 10`). A file used twice is sent once and arrives as one value, a `Blob` arrives as a `File` named `blob`, and `bodySizeLimit` bounds the whole body. _Results_ are unaffected — they always travel through the codec, whose decode half the client carries regardless. Async returns (promises, streams) settle over the open connection via length-prefixed chunk framing; a `live` source's response — requested at the live address — is the same stream framed as server-sent events (see `live(fn)` under the extension surface). (A `@solidjs/web/serialization` subpath exists; most of it is integration-facing plumbing — the bridge exposing the runtime’s serializer machinery for the runtime’s own entries and for integrations building transports — exempt from the 2.0 stability guarantee and subject to change. The one application-facing part is plugin _authoring_: `createPlugin` and `OpaqueReference` are re-exported there from the runtime’s own seroval instance, and custom plugins for the `codec` option must be built from that import — a plugin built against your own `seroval` dependency edge would not fail the build, it would emit nodes the other end of the wire can’t interpret (the version-pinning lesson of solid-start #1474). Application and router code authors plugins there and feeds them to `codec`; everything else on the subpath it should leave alone.)
4848

4949
**Server:** `configureServerFunctionsServer({ endpoint?, codec?, provideEvent?, wrapInvocation?, collectFlightData?, transformResult?, transformDirectResult? })` plus the web-standard HTTP handler:
5050

‎packages/web/server-functions/src/argument-codec.ts‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -118,12 +118,24 @@ function encodeRefusal(name) {
118118

119119
let encodeRefusals;
120120

121-
/** The configured codec options with encode-side refusals ahead of every plugin. */
122-
export function argumentEncodeCodec(codec) {
121+
/**
122+
* The configured codec options with encode-side refusals ahead of every
123+
* plugin. `extra` holds plugins for one call (the upload serializer), which
124+
* go first.
125+
*/
126+
export function argumentEncodeCodec(codec, extra = []) {
123127
if (!encodeRefusals) encodeRefusals = [encodeRefusal("Response"), encodeRefusal("Request")];
124-
const refusals = encodeRefusals;
128+
const refusals = extra.length ? [...extra, ...encodeRefusals] : encodeRefusals;
125129
return {
126130
...codec,
127131
plugins: codec && codec.plugins ? [...refusals, ...codec.plugins] : refusals
128132
};
129133
}
134+
135+
/**
136+
* Decode options from `argumentDecodeCodec` with plugins for one request
137+
* (the upload deserializer) ahead of the resolved list.
138+
*/
139+
export function withArgumentPlugins(argumentCodec, extra) {
140+
return { ...argumentCodec, [RESOLVED_PLUGINS]: [...extra, ...argumentCodec[RESOLVED_PLUGINS]] };
141+
}

‎packages/web/server-functions/src/client.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -307,9 +307,11 @@ export interface ServerFunctionsClientConfig {
307307
* Encoder for argument lists JSON can't carry faithfully. JSON-safe args
308308
* always go as plain JSON (no codec in the bundle); anything else throws
309309
* unless this is set. Installed by `enableRichArguments()` from the
310-
* rich-args entry — set directly only for custom wire encodings.
310+
* rich-args entry — set directly only for custom wire encodings. A
311+
* `FormData` answer is sent as an upload: the codec output in its `args`
312+
* field and each file in a `file<index>` part.
311313
*/
312-
serializeArgs?(args: unknown[]): string | Promise<string>;
314+
serializeArgs?(args: unknown[]): string | FormData | Promise<string | FormData>;
313315
}
314316

315317
/** Wire-state transitions a live call's iterable can report. */
@@ -434,7 +436,7 @@ function serializeArguments(args) {
434436
"Server function arguments are sent as JSON by default and these " +
435437
"arguments are not JSON-serializable. Call enableRichArguments() " +
436438
'(from "@solidjs/web/server-functions/rich-args") once at startup ' +
437-
"to send Dates, Maps, Sets, typed arrays, etc. through the codec — " +
439+
"to send Dates, Maps, Sets, typed arrays, files, etc. through the codec — " +
438440
"or pass a single Blob/FormData/File argument, which has a native " +
439441
"HTTP encoding."
440442
);
@@ -760,16 +762,20 @@ async function initializeResponse(base, id, options, args, meta) {
760762
}
761763
}
762764
// Everything else needs the codec, which is opt-in (enableRichArguments).
765+
// The encoder answers `FormData` when the arguments hold files (see
766+
// uploads.js). The browser sets that body's multipart content type.
767+
const body = await serializeArguments(args);
768+
const upload = body instanceof FormData;
763769
return createRequest(
764770
base,
765771
id,
766772
{
767773
...options,
768-
body: await serializeArguments(args),
774+
body,
769775
headers: {
770776
...options.headers,
771-
"Content-Type": "text/plain",
772-
[BODY_FORMAT_HEADER]: BodyFormat.Serialized
777+
...(!upload && { "Content-Type": "text/plain" }),
778+
[BODY_FORMAT_HEADER]: upload ? BodyFormat.SerializedFormData : BodyFormat.Serialized
773779
}
774780
},
775781
meta

‎packages/web/server-functions/src/rich-args.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
// results as plain JSON and only rich results wake the decode half.
1212
import { getServerFunctionsCodec, serializeString } from "./shared.js";
1313
import { configureServerFunctionsClient } from "./client.js";
14-
import { argumentEncodeCodec } from "./argument-codec.js"; /**
14+
import { argumentEncodeCodec } from "./argument-codec.js";
15+
import { createUploadBody, createUploadSerializer } from "./uploads.js"; /**
1516
* Opt-in codec encoding for server-function ARGUMENTS. By default the client
1617
* sends argument lists as plain JSON (no serializer in the bundle) and
1718
* throws on values JSON can't carry faithfully. Call once at startup to
@@ -20,12 +21,20 @@ import { argumentEncodeCodec } from "./argument-codec.js"; /**
2021
* the decode half responses already need). The handler accepts both
2122
* encodings unconditionally. `Response` and `Request` values are refused
2223
* (the call rejects before anything is sent): the handler never decodes
23-
* them from arguments.
24+
* them from arguments. Files and blobs can sit anywhere in the arguments:
25+
* the call then sends multipart form data with each file as its own part.
2426
*/
2527
export function enableRichArguments(): void;
2628

2729
export function enableRichArguments() {
2830
configureServerFunctionsClient({
29-
serializeArgs: args => serializeString(args, argumentEncodeCodec(getServerFunctionsCodec()))
31+
serializeArgs: async args => {
32+
const files = [];
33+
const serialized = await serializeString(
34+
args,
35+
argumentEncodeCodec(getServerFunctionsCodec(), [createUploadSerializer(files)])
36+
);
37+
return files.length ? await createUploadBody(serialized, files) : serialized;
38+
}
3039
});
3140
}

‎packages/web/server-functions/src/server.ts‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,10 @@ import {
3131
argumentDecodeCodec,
3232
namesRefusedType,
3333
refusedArgument,
34-
refusedArgumentError
34+
refusedArgumentError,
35+
withArgumentPlugins
3536
} from "./argument-codec.js";
37+
import { UPLOAD_ARGS_PART, createUploadDeserializer } from "./uploads.js";
3638
import {
3739
BODY_FORMAT_HEADER,
3840
BodyFormat,
@@ -1942,7 +1944,9 @@ async function parseArguments(request, url, scripted, codec, buffered) {
19421944
// the body and never put arguments in the url.
19431945
const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
19441946
const args = url.searchParams.get("args");
1945-
if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
1947+
const codecBody =
1948+
bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.SerializedFormData;
1949+
if (args && (!scripted || request.method === "GET" || !codecBody)) {
19461950
// framed codec output (from the client runtime) or plain JSON (from
19471951
// integrations building urls by hand). Anything that is not an argument
19481952
// array is a malformed request, which dispatch answers as one: the query
@@ -2005,6 +2009,22 @@ async function parseArguments(request, url, scripted, codec, buffered) {
20052009
let argumentCodec = argumentCodecFor(codec);
20062010
if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
20072011
decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
2012+
} else if (bodyFormat === BodyFormat.SerializedFormData) {
2013+
// A codec argument list with its files as form parts (see uploads.js).
2014+
// The upload plugin is made for this request only, so a file index
2015+
// means something here and nowhere else.
2016+
const form = await body.formData();
2017+
const encoded = form.get(UPLOAD_ARGS_PART);
2018+
if (typeof encoded !== "string") {
2019+
throw new TypeError("Malformed server function upload");
2020+
}
2021+
let argumentCodec = argumentCodecFor(codec);
2022+
if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
2023+
const uploadCodec = withArgumentPlugins(argumentCodec, [createUploadDeserializer(form)]);
2024+
decoded = await decodeArguments(
2025+
wire => deserializeStream(new Response(encoded), uploadCodec, wire),
2026+
encoded
2027+
);
20082028
} else {
20092029
decoded = await extractBody(body, codec);
20102030
}
@@ -2013,7 +2033,7 @@ async function parseArguments(request, url, scripted, codec, buffered) {
20132033
// must not be the uncapped alternative (#3119). Either way the payload
20142034
// is spread into the call, so anything but an array is malformed — a
20152035
// 400, not a range error out of the function.
2016-
if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
2036+
if (codecBody || bodyFormat === BodyFormat.Json) {
20172037
if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
20182038
if (!Array.isArray(decoded)) {
20192039
throw new TypeError("Server function arguments must encode an array");

‎packages/web/server-functions/src/shared.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -972,7 +972,13 @@ export const BodyFormat = {
972972
* on it from a refusal answered by something else. Decoding falls through
973973
* to `undefined`, which is what a peer predating the tag reads too.
974974
*/
975-
Void: "9"
975+
Void: "9",
976+
/**
977+
* Multipart form data for a codec argument list that holds files: the codec
978+
* output in one field and each file in its own part (see uploads.js).
979+
* Request leg only.
980+
*/
981+
SerializedFormData: "10"
976982
};
977983

978984
// Nesting deeper than this is not JSON-safe. The guard itself walks an

0 commit comments

Comments
 (0)