11import "#nitro/virtual/polyfills" ;
22import type * as CF from "@cloudflare/workers-types" ;
3- import type { ExportedHandler } from "@cloudflare/workers-types" ;
4- import type { ServerRequest } from "srvx" ;
3+ import type { ServerRequest , ServerRuntimeContext } from "srvx" ;
54
65import { runCronTasks } from "#nitro/runtime/task" ;
76import { useNitroApp , useNitroHooks } from "nitro/app" ;
@@ -22,6 +21,9 @@ export function createHandler<Env>(hooks: {
2221
2322 return {
2423 async fetch ( request , env , context ) {
24+ ( globalThis as any ) . __env__ = env ;
25+ augmentReq ( request as any , { env : env as any , context } ) ;
26+
2527 const ctxExt = { } ;
2628 const url = new URL ( request . url ) ;
2729
@@ -33,14 +35,7 @@ export function createHandler<Env>(hooks: {
3335 }
3436 }
3537
36- return fetchHandler (
37- request ,
38- env ,
39- context ,
40- url ,
41- nitroApp ,
42- ctxExt
43- ) as Promise < any /* CF response! */ > ;
38+ return ( await nitroApp . fetch ( request ) ) as any ;
4439 } ,
4540
4641 scheduled ( controller , env , context ) {
@@ -71,8 +66,8 @@ export function createHandler<Env>(hooks: {
7166 ( globalThis as any ) . __env__ = env ;
7267 context . waitUntil (
7368 nitroHooks . callHook ( "cloudflare:email" , {
74- message,
75- event : message , // backward compat
69+ message : message as any ,
70+ event : message as any , // backward compat
7671 env,
7772 context,
7873 } ) || Promise . resolve ( )
@@ -115,22 +110,12 @@ export function createHandler<Env>(hooks: {
115110 } satisfies ExportedHandler < Env > ;
116111}
117112
118- export async function fetchHandler (
113+ export function augmentReq (
119114 cfReq : Request | CF . Request ,
120- env : unknown ,
121- context : CF . ExecutionContext | DurableObjectState ,
122- url : URL = new URL ( cfReq . url ) ,
123- nitroApp = useNitroApp ( ) ,
124- ctxExt : any
115+ ctx : NonNullable < ServerRuntimeContext [ "cloudflare" ] >
125116) {
126- // Expose latest env to the global context
127- ( globalThis as any ) . __env__ = env ;
128-
129- // srvx compatibility
130117 const req = cfReq as ServerRequest ;
131118 req . runtime ??= { name : "cloudflare" } ;
132- req . runtime . cloudflare ??= { context, env } as any ;
133- req . waitUntil = context . waitUntil . bind ( context ) ;
134-
135- return nitroApp . fetch ( req ) as unknown as Promise < Response > ;
119+ req . runtime . cloudflare = { ...req . runtime . cloudflare , ...ctx } ;
120+ req . waitUntil = ctx . context ?. waitUntil . bind ( ctx . context ) ;
136121}
0 commit comments