@@ -25,7 +25,8 @@ async function flushWithTimeout(timeout: number): Promise<void> {
2525 * The function is async, but in environments that support a `waitUntil` mechanism, it will run synchronously.
2626 *
2727 * This function is aware of the following serverless platforms:
28- * - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events.
28+ * - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events (keeps the `this` context of `ctx`).
29+ * If a `cloudflareWaitUntil` function is provided, it will use that to flush events (looses the `this` context of `ctx`).
2930 * - Vercel: It detects the Vercel environment and uses Vercel's `waitUntil` function.
3031 * - Other Serverless (AWS Lambda, Google Cloud, etc.): It detects the environment via environment variables
3132 * and uses a regular `await flush()`.
@@ -34,15 +35,19 @@ async function flushWithTimeout(timeout: number): Promise<void> {
3435 * @hidden
3536 */
3637export async function flushIfServerless (
37- params : {
38- timeout ?: number ;
39- cloudflareCtx ?: MinimalCloudflareContext ;
40- } = { } ,
38+ params : // eslint-disable-next-line @typescript-eslint/no-explicit-any
39+ | { timeout ?: number ; cloudflareWaitUntil ?: ( task : Promise < any > ) => void }
40+ | { timeout ?: number ; cloudflareCtx ?: MinimalCloudflareContext } ,
4141) : Promise < void > {
42- const { timeout = 2000 , cloudflareCtx } = params ;
42+ const { timeout = 2000 } = params ;
4343
44- if ( cloudflareCtx && typeof cloudflareCtx . waitUntil === 'function' ) {
45- cloudflareCtx . waitUntil ( flushWithTimeout ( timeout ) ) ;
44+ if ( 'cloudflareWaitUntil' in params && typeof params ?. cloudflareWaitUntil === 'function' ) {
45+ params . cloudflareWaitUntil ( flushWithTimeout ( timeout ) ) ;
46+ return ;
47+ }
48+
49+ if ( 'cloudflareCtx' in params && typeof params . cloudflareCtx ?. waitUntil === 'function' ) {
50+ params . cloudflareCtx . waitUntil ( flushWithTimeout ( timeout ) ) ;
4651 return ;
4752 }
4853
0 commit comments