Skip to content

Commit 6ec7b5f

Browse files
fix(router): server-function status, abort and input encoding fixes (#2775)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 6569bbc commit 6ec7b5f

7 files changed

Lines changed: 232 additions & 94 deletions

File tree

‎packages/router/server/src/server-fn/dispatch.spec.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,19 @@ describe('dispatchServerFn', () => {
120120
expect(result.body).toBe('listed');
121121
});
122122

123+
it('dispatches an h3 event that only carries a fetch Request', async () => {
124+
serverFn({ id: 'host' }, async () => inject(REQUEST).headers['host']);
125+
126+
const result = await dispatchServerFn(
127+
'host',
128+
undefined,
129+
{ req: new Request('http://example.com/_analog/fn/host') } as never,
130+
{ method: 'GET' },
131+
);
132+
133+
expect(result).toEqual({ status: 200, body: 'example.com' });
134+
});
135+
123136
it('404s an unknown function', async () => {
124137
const result = await dispatchServerFn('nope', undefined, eventFor(), {
125138
method: 'GET',

‎packages/router/server/src/server-fn/dispatch.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import type { H3Event } from 'h3';
88

99
import { detectLocale, getBaseUrl } from '../provide-server-context';
1010
import { serverFnRegistry } from './registry';
11-
import { assertNodeContext } from './node-context';
11+
import { assertNodeContext, nodeContext } from './node-context';
1212
import { SERVER_FN_INTERCEPTORS, runInterceptors } from './interceptors';
1313
import {
1414
SERVER_FN_ALLOWED_ORIGINS,
@@ -74,11 +74,14 @@ export interface DispatchServerFnOptions {
7474
export async function dispatchServerFn(
7575
id: string,
7676
rawInput: unknown,
77-
event: Pick<H3Event, 'node'>,
77+
event: Pick<H3Event, 'node'> & { req?: unknown },
7878
options: DispatchServerFnOptions = {},
7979
): Promise<DispatchResult> {
8080
const { parent, providers = [], method, allowedOrigins = [] } = options;
81-
const node = assertNodeContext(event);
81+
const node =
82+
event.node?.req || !(event.req instanceof Request)
83+
? assertNodeContext(event)
84+
: nodeContext(event.req, new URL(event.req.url));
8285
const headers = (node.req.headers ?? {}) as HeaderBag;
8386

8487
// Same-origin guard runs first — before we even confirm the function exists —
Lines changed: 86 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Injector, inject } from '@angular/core';
2-
import { RESPONSE } from '@analogjs/router/tokens';
2+
import { REQUEST, RESPONSE, type ServerRequest } from '@analogjs/router/tokens';
33
import { beforeEach, describe, expect, it, vi } from 'vitest';
44

55
// Keep h3 real except `readBody`, whose parse-failure path is what the
@@ -22,32 +22,19 @@ import { handleServerFnRequest } from './event-handler';
2222
import { serverFnRegistry } from './registry';
2323
import { serverFn } from './server-fn';
2424

25-
type FakeRes = {
26-
statusCode: number;
27-
headers: Record<string, string | string[]>;
28-
setHeader(key: string, value: string | string[]): void;
29-
};
30-
3125
function fakeEvent(options: {
3226
id: string;
3327
method?: string;
3428
body?: unknown;
3529
bodyThrows?: boolean;
3630
headers?: Record<string, string>;
3731
}) {
38-
const res: FakeRes = {
39-
statusCode: 200,
40-
headers: {},
41-
setHeader(key, value) {
42-
this.headers[key] = value;
43-
},
44-
};
4532
return {
4633
method: options.method ?? 'GET',
4734
context: { params: { id: options.id } },
4835
node: {
4936
req: { headers: options.headers ?? {} },
50-
res,
37+
res: {},
5138
},
5239
// `readBody(event)` reads `event._requestBody` under h3's unenv shim in
5340
// tests; model it (and the throwing case) directly.
@@ -63,19 +50,16 @@ describe('handleServerFnRequest', () => {
6350

6451
const jsonHeaders = { 'content-type': 'application/json' };
6552

66-
it('dispatches a GET and writes the status and body', async () => {
53+
it('dispatches a GET and returns the status and body as a Response', async () => {
6754
serverFn({ id: 'read' }, async () => ({ ok: true }));
6855

69-
const event = fakeEvent({ id: 'read', method: 'GET' });
70-
const body = await handleServerFnRequest(
71-
event,
56+
const response = await handleServerFnRequest(
57+
fakeEvent({ id: 'read', method: 'GET' }),
7258
Injector.create({ providers: [] }),
7359
);
7460

75-
expect(body).toEqual({ ok: true });
76-
expect(
77-
(event as never as { node: { res: FakeRes } }).node.res.statusCode,
78-
).toBe(200);
61+
expect(response.status).toBe(200);
62+
expect(await response.json()).toEqual({ ok: true });
7963
});
8064

8165
it('accepts a promised injector, awaiting it before dispatch', async () => {
@@ -84,44 +68,76 @@ describe('handleServerFnRequest', () => {
8468
const event = fakeEvent({ id: 'read2', method: 'GET' });
8569
const injector = Promise.resolve(Injector.create({ providers: [] }));
8670

87-
await expect(handleServerFnRequest(event, injector)).resolves.toBe('ok');
71+
const response = await handleServerFnRequest(event, injector);
72+
expect(await response.json()).toBe('ok');
8873
});
8974

90-
it('propagates response headers onto the h3 response', async () => {
75+
it('carries a returned Response status and headers on the Node path', async () => {
9176
serverFn({ id: 'redir' }, async () => {
9277
return new Response(null, {
93-
status: 302,
78+
status: 303,
9479
headers: { Location: '/next' },
9580
});
9681
});
9782

98-
const event = fakeEvent({ id: 'redir', method: 'GET' });
99-
const res = (event as never as { node: { res: FakeRes } }).node.res;
83+
const response = await handleServerFnRequest(
84+
fakeEvent({ id: 'redir', method: 'GET' }),
85+
Injector.create({ providers: [] }),
86+
);
87+
88+
expect(response.status).toBe(303);
89+
expect(response.headers.get('location')).toBe('/next');
90+
});
91+
92+
it('answers invalid input with 422 on the Node path', async () => {
93+
serverFn(
94+
{
95+
id: 'validated',
96+
method: 'POST',
97+
input: {
98+
'~standard': {
99+
version: 1,
100+
vendor: 'spec',
101+
validate: () => ({ issues: [{ message: 'invalid' }] }),
102+
},
103+
},
104+
},
105+
async () => 'never',
106+
);
100107

101-
await handleServerFnRequest(event, Injector.create({ providers: [] }));
108+
const response = await handleServerFnRequest(
109+
fakeEvent({
110+
id: 'validated',
111+
method: 'POST',
112+
body: {},
113+
headers: jsonHeaders,
114+
}),
115+
Injector.create({ providers: [] }),
116+
);
102117

103-
expect(res.statusCode).toBe(302);
104-
expect(res.headers['location']).toBe('/next');
118+
expect(response.status).toBe(422);
119+
expect(await response.json()).toEqual({
120+
errors: [{ message: 'invalid' }],
121+
});
105122
});
106123

107124
it('returns 400 with the JSON error contract when the body is malformed', async () => {
108125
serverFn({ id: 'write', method: 'POST' }, async () => 'never');
109126

110-
const event = fakeEvent({
111-
id: 'write',
112-
method: 'POST',
113-
bodyThrows: true,
114-
headers: jsonHeaders,
115-
});
116-
const res = (event as never as { node: { res: FakeRes } }).node.res;
117-
118-
const body = await handleServerFnRequest(
119-
event,
127+
const response = await handleServerFnRequest(
128+
fakeEvent({
129+
id: 'write',
130+
method: 'POST',
131+
bodyThrows: true,
132+
headers: jsonHeaders,
133+
}),
120134
Injector.create({ providers: [] }),
121135
);
122136

123-
expect(res.statusCode).toBe(400);
124-
expect(body).toEqual({ message: 'Malformed request body' });
137+
expect(response.status).toBe(400);
138+
expect(await response.json()).toEqual({
139+
message: 'Malformed request body',
140+
});
125141
});
126142

127143
it('serves events without a Node request from their fetch Request', async () => {
@@ -130,7 +146,7 @@ describe('handleServerFnRequest', () => {
130146
return (input as { text: string }).text.toUpperCase();
131147
});
132148

133-
const response = (await handleServerFnRequest(
149+
const response = await handleServerFnRequest(
134150
{
135151
method: 'POST',
136152
context: { params: { id: 'shout' } },
@@ -141,10 +157,35 @@ describe('handleServerFnRequest', () => {
141157
}),
142158
} as never,
143159
Injector.create({ providers: [] }),
144-
)) as Response;
160+
);
145161

146162
expect(response.status).toBe(200);
147163
expect(response.headers.get('x-shout')).toBe('yes');
148164
expect(await response.json()).toBe('HI');
149165
});
166+
167+
it('exposes the fetch Request and its abort signal on REQUEST', async () => {
168+
serverFn({ id: 'aborted' }, async () => {
169+
const req = inject(REQUEST) as ServerRequest & { request: Request };
170+
return { aborted: req.signal.aborted, url: req.request.url };
171+
});
172+
const controller = new AbortController();
173+
controller.abort();
174+
175+
const response = await handleServerFnRequest(
176+
{
177+
method: 'GET',
178+
context: { params: { id: 'aborted' } },
179+
req: new Request('http://localhost/_analog/fn/aborted', {
180+
signal: controller.signal,
181+
}),
182+
} as never,
183+
Injector.create({ providers: [] }),
184+
);
185+
186+
expect(await response.json()).toEqual({
187+
aborted: true,
188+
url: 'http://localhost/_analog/fn/aborted',
189+
});
190+
});
150191
});

‎packages/router/server/src/server-fn/event-handler.ts‎

Lines changed: 25 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,8 @@ import {
77
type H3Event,
88
} from 'h3';
99

10-
import { dispatchServerFn } from './dispatch';
11-
import {
12-
assertNodeContext,
13-
nodeContext,
14-
withResponseHeaders,
15-
} from './node-context';
10+
import { dispatchServerFn, type DispatchResult } from './dispatch';
11+
import { nodeContext, withResponseHeaders } from './node-context';
1612
import type { AnalogRequestContext } from '../request-handler';
1713

1814
/**
@@ -42,7 +38,7 @@ export function createServerFnEventHandler(
4238
export async function handleServerFnRequest(
4339
event: H3Event,
4440
appInjector: Injector | Promise<Injector>,
45-
): Promise<unknown> {
41+
): Promise<Response> {
4642
const id = getRouterParam(event, 'id') ?? '';
4743
if (!event.node?.req) {
4844
return handleServerFnFetch(
@@ -51,7 +47,6 @@ export async function handleServerFnRequest(
5147
await appInjector,
5248
);
5349
}
54-
const node = assertNodeContext(event);
5550

5651
// h3 parses the body before dispatch gets a say, and its parse error is an
5752
// HTML/500-shaped response rather than the JSON contract callers expect.
@@ -60,23 +55,16 @@ export async function handleServerFnRequest(
6055
try {
6156
input = await readBody(event);
6257
} catch {
63-
node.res.statusCode = 400;
64-
return { message: 'Malformed request body' };
58+
return malformedBodyResponse();
6559
}
6660
}
6761

68-
const { status, body, headers } = await dispatchServerFn(id, input, event, {
69-
parent: await appInjector,
70-
method: event.method,
71-
});
72-
73-
node.res.statusCode = status;
74-
if (headers) {
75-
for (const [key, value] of Object.entries(headers)) {
76-
node.res.setHeader(key, value);
77-
}
78-
}
79-
return body;
62+
return serverFnResponse(
63+
await dispatchServerFn(id, input, event, {
64+
parent: await appInjector,
65+
method: event.method,
66+
}),
67+
);
8068
}
8169

8270
/** h3 v2 on fetch-native hosts (workerd, Bun, Deno) has a `Request` only. */
@@ -102,18 +90,20 @@ export async function callServerFn(
10290
try {
10391
input = text ? JSON.parse(text) : undefined;
10492
} catch {
105-
return Response.json(
106-
{ message: 'Malformed request body' },
107-
{ status: 400 },
108-
);
93+
return malformedBodyResponse();
10994
}
11095
}
111-
const { status, body, headers } = await dispatchServerFn(
112-
id,
113-
input,
114-
{ node: context },
115-
{ parent, method: request.method },
96+
return serverFnResponse(
97+
await dispatchServerFn(
98+
id,
99+
input,
100+
{ node: context },
101+
{ parent, method: request.method },
102+
),
116103
);
104+
}
105+
106+
function serverFnResponse({ status, body, headers }: DispatchResult): Response {
117107
const responseHeaders = new Headers();
118108
for (const [key, value] of Object.entries(headers ?? {})) {
119109
for (const item of [value].flat()) {
@@ -126,6 +116,10 @@ export async function callServerFn(
126116
return Response.json(body ?? null, { status, headers: responseHeaders });
127117
}
128118

119+
function malformedBodyResponse(): Response {
120+
return Response.json({ message: 'Malformed request body' }, { status: 400 });
121+
}
122+
129123
function isNullBodyStatus(status: number): boolean {
130124
return status === 204 || status === 205 || status === 304;
131125
}

‎packages/router/server/src/server-fn/node-context.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,9 @@ export function assertNodeContext(
3232

3333
/**
3434
* A Node request/response pair for a bare `Request`, carrying what Analog
35-
* reads: method, URL, headers and protocol. The same approach as h3's web
36-
* adapter; it needs `node:http` (Node, Bun, Deno).
35+
* reads: method, URL, headers and protocol, plus the `Request` and its abort
36+
* `signal`. The same approach as h3's web adapter; it needs `node:http` (Node,
37+
* Bun, Deno).
3738
*/
3839
export function nodeContext(request: Request, url: URL): AnalogRequestContext {
3940
const socket = new Socket();
@@ -45,6 +46,10 @@ export function nodeContext(request: Request, url: URL): AnalogRequestContext {
4546
req.method = request.method;
4647
req.url = path;
4748
Object.assign(req, { originalUrl: path });
49+
Object.defineProperties(req, {
50+
signal: { value: request.signal },
51+
request: { value: request },
52+
});
4853
req.headers = { host: url.host, ...Object.fromEntries(request.headers) };
4954
return { req, res: new ServerResponse(req) };
5055
}

0 commit comments

Comments
 (0)