Skip to content

Commit bc58563

Browse files
committed
ref: safer typed logic
1 parent 829b2cf commit bc58563

File tree

2 files changed

+26
-19
lines changed

2 files changed

+26
-19
lines changed

packages/core/src/utils/cloudflareWaitUntil.ts

Lines changed: 20 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -5,26 +5,30 @@ export type MinimalCloudflareContext = {
55
waitUntil(promise: Promise<any>): void;
66
};
77

8-
export const CloudflareContextKey = '__cloudflare-context__';
8+
/**
9+
* Gets the Cloudflare context from the global object.
10+
*/
11+
function _getCloudflareContext(): MinimalCloudflareContext | undefined {
12+
const cfContextSymbol = Symbol.for('__cloudflare-context__');
13+
const globalWithCfContext = GLOBAL_OBJ as typeof GLOBAL_OBJ & {
14+
[cfContextSymbol]?: {
15+
ctx: MinimalCloudflareContext;
16+
};
17+
};
18+
19+
return globalWithCfContext[cfContextSymbol]?.ctx;
20+
}
921

1022
/**
1123
* Function that delays closing of a Cloudflare lambda until the provided promise is resolved.
1224
*/
1325
export function cloudflareWaitUntil(task: Promise<unknown>): void {
14-
try {
15-
const cfContextSymbol = Symbol.for(CloudflareContextKey);
16-
const globalWithCfContext = GLOBAL_OBJ as typeof GLOBAL_OBJ & {
17-
[cfContextSymbol]: {
18-
ctx: MinimalCloudflareContext;
19-
};
20-
};
21-
22-
const context = globalWithCfContext[cfContextSymbol].ctx;
26+
_getCloudflareContext()?.waitUntil(task);
27+
}
2328

24-
if (typeof context.waitUntil === 'function') {
25-
context.waitUntil(task);
26-
}
27-
} catch {
28-
// Ignore errors
29-
}
29+
/**
30+
* Checks if the Cloudflare waitUntil function is available globally.
31+
*/
32+
export function isCloudflareWaitUntilAvailable(): boolean {
33+
return typeof _getCloudflareContext()?.waitUntil === 'function';
3034
}

packages/core/src/utils/flushIfServerless.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import { flush } from '../exports';
2-
import { type MinimalCloudflareContext, CloudflareContextKey, cloudflareWaitUntil } from './cloudflareWaitUntil';
2+
import {
3+
type MinimalCloudflareContext,
4+
cloudflareWaitUntil,
5+
isCloudflareWaitUntilAvailable,
6+
} from './cloudflareWaitUntil';
37
import { debug } from './debug-logger';
48
import { vercelWaitUntil } from './vercelWaitUntil';
59
import { GLOBAL_OBJ } from './worldwide';
@@ -54,8 +58,7 @@ export async function flushIfServerless(
5458
return;
5559
}
5660

57-
// @ts-expect-error This is not typed
58-
if (GLOBAL_OBJ[Symbol.for(CloudflareContextKey)]) {
61+
if (isCloudflareWaitUntilAvailable()) {
5962
// If the cloudflareWaitUntil function is available, use it to flush the events, if not then fallback to the regular flush
6063
cloudflareWaitUntil(flushWithTimeout(timeout));
6164
return;

0 commit comments

Comments
 (0)