Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/forty-tools-cheat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'svelte-check': patch
'svelte2tsx': patch
---

fix: use Promise<Response> for async kit handler return types
5 changes: 5 additions & 0 deletions packages/svelte-check/test-success/src/routes/$types.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
export type PageData = {};
export type RequestEvent = {
url: URL;
request: Request;
params: Record<string, string>;
};
8 changes: 8 additions & 0 deletions packages/svelte-check/test-success/src/routes/+server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export async function GET({ url }) {
return new Response(url.pathname);
}

export async function POST({ request }) {
const body = await request.text();
return new Response(body, { status: 201 });
}
14 changes: 13 additions & 1 deletion packages/svelte2tsx/src/helpers/sveltekit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -485,11 +485,23 @@ function addTypeToFunction(
const paramInsertion = surround(!returnType ? `: Parameters<${type}>[0]` : `: ${type}`);
insert(paramPos, paramInsertion);
if (!fn.node.type && fn.node.body) {
const isAsync =
fn.node.modifiers?.some((m) => m.kind === ts.SyntaxKind.AsyncKeyword) ?? false;
let effectiveReturnType = returnType;
if (isAsync && returnType) {
// Async functions must return Promise<T>, not T | Promise<T>
const promisePart = returnType
.split(' | ')
.find((t) => t.startsWith('Promise<'));
if (promisePart) {
effectiveReturnType = promisePart;
}
}
const returnPos = ts.isArrowFunction(fn.node)
? fn.node.equalsGreaterThanToken.getStart()
: fn.node.body.getStart();
const returnInsertion = surround(
!returnType ? `: ReturnType<${type}> ` : `: ${returnType} `
!effectiveReturnType ? `: ReturnType<${type}> ` : `: ${effectiveReturnType} `
);
insert(returnPos, returnInsertion);
}
Expand Down
10 changes: 9 additions & 1 deletion packages/svelte2tsx/test/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,15 @@ describe('Internal Helpers - upsertKitFile', () => {
upsert(
'+server.ts',
`export async function GET(e) {}`,
`export async function GET(e: import('./$types.js').RequestEvent) : Response | Promise<Response> {}`
`export async function GET(e: import('./$types.js').RequestEvent) : Promise<Response> {}`
);
});

it('upserts GET non-async function', () => {
upsert(
'+server.ts',
`export function GET(e) { return new Response(); }`,
`export function GET(e: import('./$types.js').RequestEvent) : Response | Promise<Response> { return new Response(); }`
);
});

Expand Down