Skip to content

Commit e543ec9

Browse files
committed
fix(web): keep uploads out of the core client's request path
The codec request path no longer sets `Content-Type: text/plain` or picks a body-format tag per body. Fetch gives a string body `text/plain` and a `FormData` body its multipart boundary, so uploads keep the `Serialized` tag and the handler tells them apart by the multipart content type. That drops `BodyFormat.SerializedFormData` and the `instanceof FormData` branch, so apps that don't use rich arguments pay nothing for uploads (−21 B minified on the server-function scenarios against the PR's base). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_018LY7F9czoRqdMEvk2QwPr1
1 parent b745f10 commit e543ec9

7 files changed

Lines changed: 33 additions & 41 deletions

File tree

‎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. 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.)
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 (still `X-Server-Function-Format: 0`; the `multipart/form-data` content type marks the upload). 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/client.ts‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -763,19 +763,18 @@ async function initializeResponse(base, id, options, args, meta) {
763763
}
764764
// Everything else needs the codec, which is opt-in (enableRichArguments).
765765
// 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;
766+
// uploads.js). No content type is set here: fetch gives a string body
767+
// `text/plain` and a form its multipart boundary, which is how the handler
768+
// tells the two apart.
769769
return createRequest(
770770
base,
771771
id,
772772
{
773773
...options,
774-
body,
774+
body: await serializeArguments(args),
775775
headers: {
776776
...options.headers,
777-
...(!upload && { "Content-Type": "text/plain" }),
778-
[BODY_FORMAT_HEADER]: upload ? BodyFormat.SerializedFormData : BodyFormat.Serialized
777+
[BODY_FORMAT_HEADER]: BodyFormat.Serialized
779778
}
780779
},
781780
meta

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

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1944,9 +1944,7 @@ async function parseArguments(request, url, scripted, codec, buffered) {
19441944
// the body and never put arguments in the url.
19451945
const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
19461946
const args = url.searchParams.get("args");
1947-
const codecBody =
1948-
bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.SerializedFormData;
1949-
if (args && (!scripted || request.method === "GET" || !codecBody)) {
1947+
if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
19501948
// framed codec output (from the client runtime) or plain JSON (from
19511949
// integrations building urls by hand). Anything that is not an argument
19521950
// array is a malformed request, which dispatch answers as one: the query
@@ -2008,23 +2006,25 @@ async function parseArguments(request, url, scripted, codec, buffered) {
20082006
if (bodyFormat === BodyFormat.Serialized) {
20092007
let argumentCodec = argumentCodecFor(codec);
20102008
if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
2011-
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");
2009+
if ((request.headers.get("content-type") || "").startsWith("multipart/form-data")) {
2010+
// A codec argument list with its files as form parts (see uploads.js).
2011+
// The tag stays `Serialized` so the client runtime pays nothing for
2012+
// uploads; the multipart content type is what marks one. The upload
2013+
// plugin is made for this request only, so a file index means
2014+
// something here and nowhere else.
2015+
const form = await body.formData();
2016+
const encoded = form.get(UPLOAD_ARGS_PART);
2017+
if (typeof encoded !== "string") {
2018+
throw new TypeError("Malformed server function upload");
2019+
}
2020+
const uploadCodec = withArgumentPlugins(argumentCodec, [createUploadDeserializer(form)]);
2021+
decoded = await decodeArguments(
2022+
wire => deserializeStream(new Response(encoded), uploadCodec, wire),
2023+
encoded
2024+
);
2025+
} else {
2026+
decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
20202027
}
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-
);
20282028
} else {
20292029
decoded = await extractBody(body, codec);
20302030
}
@@ -2033,7 +2033,7 @@ async function parseArguments(request, url, scripted, codec, buffered) {
20332033
// must not be the uncapped alternative (#3119). Either way the payload
20342034
// is spread into the call, so anything but an array is malformed — a
20352035
// 400, not a range error out of the function.
2036-
if (codecBody || bodyFormat === BodyFormat.Json) {
2036+
if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
20372037
if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
20382038
if (!Array.isArray(decoded)) {
20392039
throw new TypeError("Server function arguments must encode an array");

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

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -972,13 +972,7 @@ 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",
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"
975+
Void: "9"
982976
};
983977

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

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
// - the codec output in the `UPLOAD_ARGS_PART` field;
66
// - each file in its own `UPLOAD_FILE_PART<index>` part, as it is, without
77
// base64.
8-
// The codec output holds only each file's index. `BodyFormat.SerializedFormData`
9-
// marks the request.
8+
// The codec output holds only each file's index. The request keeps the
9+
// `Serialized` tag; its multipart content type is what marks an upload.
1010
//
1111
// A seroval plugin made for the call finds the files wherever the codec
1212
// meets one: arguments, arrays, objects, maps, sets, and `FormData` entries.

‎packages/web/test/server/server-functions-format-version-skew.spec.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ import * as devServer from "../../server-functions/dist/server.dev.js";
4040
const RequestContext = Symbol.for("solid.RequestContext");
4141
const BODY_FORMAT_HEADER = "X-Server-Function-Format";
4242
/** The next tag the runtime ships — this build has no case for it. */
43-
const FUTURE_FORMAT = "11";
43+
const FUTURE_FORMAT = "10";
4444

4545
beforeAll(() => {
4646
(globalThis as any)[RequestContext] = new AsyncLocalStorage();

‎packages/web/test/server/server-functions-uploads.spec.tsx‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import { enableRichArguments } from "../../server-functions/dist/rich-args.js";
2121
const RequestContext = Symbol.for("solid.RequestContext");
2222
const BODY_FORMAT_HEADER = "X-Server-Function-Format";
2323
const SERIALIZED_FORMAT = "0";
24-
const UPLOAD_FORMAT = "10";
2524

2625
beforeAll(() => {
2726
(globalThis as any)[RequestContext] = new AsyncLocalStorage();
@@ -54,7 +53,7 @@ function connectTransport() {
5453
}
5554

5655
/** A request to the same address as `captured`, with `form` as its body. */
57-
function resend(captured: Request, form: FormData | string, format = UPLOAD_FORMAT) {
56+
function resend(captured: Request, form: FormData | string, format = SERIALIZED_FORMAT) {
5857
const headers: Record<string, string> = {
5958
[BODY_FORMAT_HEADER]: format,
6059
"Sec-Fetch-Site": "same-origin"
@@ -84,7 +83,7 @@ describe("files in codec arguments", () => {
8483
});
8584
expect(result).toEqual({ file: "a.txt", type: "text/plain", text: "hello", tags: ["x"] });
8685
const [request] = transport.requests;
87-
expect(request.headers.get(BODY_FORMAT_HEADER)).toBe(UPLOAD_FORMAT);
86+
expect(request.headers.get(BODY_FORMAT_HEADER)).toBe(SERIALIZED_FORMAT);
8887
expect(request.headers.get("content-type")).toMatch(/^multipart\/form-data/);
8988
const form = await request.formData();
9089
expect(typeof form.get("args")).toBe("string");
@@ -208,7 +207,7 @@ describe("files in codec arguments", () => {
208207
slice: (...args: any[]) => real.slice(...args)
209208
};
210209
expect(await call({ blob: foreign })).toEqual({ type: "text/x-far", text: "far" });
211-
expect(transport.requests[0].headers.get(BODY_FORMAT_HEADER)).toBe(UPLOAD_FORMAT);
210+
expect(transport.requests[0].headers.get(BODY_FORMAT_HEADER)).toBe(SERIALIZED_FORMAT);
212211
} finally {
213212
transport.restore();
214213
}

0 commit comments

Comments
 (0)