Skip to content

Commit 40d5344

Browse files
author
Muhammad Ali
committed
fix(util): detect Cloudflare Workers in shouldUseGlobalFetchAndWebSocket
1 parent 2a06721 commit 40d5344

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { afterEach, describe, expect, test, vi } from 'vitest';
2+
import { shouldUseGlobalFetchAndWebSocket } from '../src/index.js';
3+
4+
describe('shouldUseGlobalFetchAndWebSocket', () => {
5+
afterEach(() => {
6+
vi.unstubAllGlobals();
7+
});
8+
9+
test('GIVEN browser env with fetch and WebSocket THEN returns true', () => {
10+
vi.stubGlobal('process', undefined);
11+
vi.stubGlobal('fetch', () => void 0);
12+
vi.stubGlobal('WebSocket', class {});
13+
expect(shouldUseGlobalFetchAndWebSocket()).toBe(true);
14+
});
15+
16+
test('GIVEN browser env without fetch or WebSocket THEN returns false', () => {
17+
vi.stubGlobal('process', undefined);
18+
// @ts-expect-error Testing missing globals
19+
delete globalThis.fetch;
20+
// @ts-expect-error Testing missing globals
21+
delete globalThis.WebSocket;
22+
expect(shouldUseGlobalFetchAndWebSocket()).toBe(false);
23+
});
24+
25+
test('GIVEN Cloudflare Workers with nodejs_compat THEN returns true', () => {
26+
vi.stubGlobal('process', { versions: { node: '22.19.0' } });
27+
vi.stubGlobal('WebSocketPair', class {});
28+
expect(shouldUseGlobalFetchAndWebSocket()).toBe(true);
29+
});
30+
31+
test('GIVEN Node.js THEN returns false', () => {
32+
vi.stubGlobal('process', { versions: { node: '22.19.0' } });
33+
expect(shouldUseGlobalFetchAndWebSocket()).toBe(false);
34+
});
35+
36+
test('GIVEN Deno THEN returns true', () => {
37+
vi.stubGlobal('process', { versions: { deno: '1.0.0' } });
38+
expect(shouldUseGlobalFetchAndWebSocket()).toBe(true);
39+
});
40+
41+
test('GIVEN Bun THEN returns true', () => {
42+
vi.stubGlobal('process', { versions: { bun: '1.0.0' } });
43+
expect(shouldUseGlobalFetchAndWebSocket()).toBe(true);
44+
});
45+
});

packages/util/src/functions/runtime.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,14 @@ export function shouldUseGlobalFetchAndWebSocket() {
66
return 'fetch' in globalThis && 'WebSocket' in globalThis;
77
}
88

9+
// Cloudflare Workers with nodejs_compat polyfills process (including
10+
// process.versions.node), but natively supports the Web WebSocket API.
11+
// WebSocketPair is a Workers-only global; no other runtime exposes it.
12+
// @ts-expect-error WebSocketPair is not in the globalThis type
13+
if (typeof globalThis.WebSocketPair !== 'undefined') {
14+
return true;
15+
}
16+
917
if ('versions' in globalThis.process) {
1018
return 'deno' in globalThis.process.versions || 'bun' in globalThis.process.versions;
1119
}

0 commit comments

Comments
 (0)