theturtle32 / WebSocket-Node

A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

websocket fails to determine global this in SvelteKit SSR

ixxie opened this issue · comments

I've been trying to isolate an issue which occurs when I try to use @supabase/supabase-js in SvelteKit; it appears supabase-js uses websocket, which uses es5-ext to try and robustly identify a globalThis across browsers in this block of code:

try {
    _globalThis = require('es5-ext/global');
} catch (error) {
} finally {
    if (!_globalThis && typeof window !== 'undefined') { _globalThis = window; }
    if (!_globalThis) { throw new Error('Could not determine global this'); }
}

Unfortunately, this fails in SvelteKit:

5:49:56 PM [vite] Error when evaluating SSR module /node_modules/websocket/lib/browser.js?v=f34fcf64:
Error: Could not determine global this
    at /node_modules/websocket/lib/browser.js?v=f34fcf64:7:28
    at instantiateModule (/home/ixxie/repos/minex/node_modules/vite/dist/node/chunks/dep-66eb515d.js:69030:166)

To reproduce this, run the following in an empty folder:

npm init svelte@next
npm install
npm install websocket
sed -i "s/<script>/<script>\n\timport { w3cwebsocket } from 'websocket';\n\tconsole.log(w3cwebsocket);\n/" ./src/routes/index.svelte
npm run dev

It seems es5-ext is a dead project; at least it hasn't had any Github activity in the last year. I noticed the seems to be globalThis support in all major browsers since spring of 2019 (except Edge, which got support in January 2020); perhaps this could resolve the issue?

@ixxie thanks for bringing this up and pointing out the new globalThis support. I've updated the code to check for and use globalThis first if it's available.

As for es5-ext, it still gets 10,643,967 weekly downloads according to npm, so I wouldn't exactly call it dead. It's one of those types of projects that, once it's done, working, and stable, probably doesn't really require much ongoing change or maintenance. This situation, however, may be an exception to that. Let me know if websocket-node v1.0.34 resolves your issue.

@theturtle32 thanks for the rapid response! This resolves the issue successfully, although now I am running into challenges relating to ESM interoperability (but this is a different scope - I will raise a different issue if appropriate).