edgedb / edgedb-js

The official TypeScript/JS client library and query builder for EdgeDB
https://edgedb.com
Apache License 2.0
512 stars 66 forks source link

Uncaught ReferenceError: Buffer is not defined in Partykit (Cloudflare Worker) #1003

Closed danieldunderfelt closed 5 months ago

danieldunderfelt commented 5 months ago

Describe the bug

I am trying to use EdgeDB in Partykit, which runs on Cloudflare Workers. When starting the Partykit dev server locally, it throws the error: Uncaught ReferenceError: Buffer is not defined

I am not sure how far the local dev server goes to simulate a Cloudflare Worker environment, but CF Workers do support Buffer: https://developers.cloudflare.com/workers/runtime-apis/nodejs

It has to be imported, it can't be used as a global.

The error happens immediately when the dev server is started.

Reproduction

Any use of the edgedb-js client.

Expected behavior

I do not expect an error.

Versions (please complete the following information):

Additional context

I am running the Partykit dev server with Bun, but I also tried with Node and it had the same result.

danieldunderfelt commented 5 months ago

Quick fix:

Put import { Buffer } from 'node:buffer' on line 52 of node_modules/edgedb/dist/primitives/buffer.js, before if (Buffer === "function"). Then it works. Use patch-package to make it stick.

scotttrinh commented 5 months ago

Appreciate the note about the workaround, hopefully that'll hold over anyone who might be running into this until we can get out a proper fix.

For a fix, we should either use a browser compatible API that also works with Node and doesn't sacrifice performance (might be hard...) or use our existing "adapter" pattern to chose either a Node-like or Browser-like adapter like we do for crypto.

danieldunderfelt commented 5 months ago

The workaround doesn't seem to work when using @edgedb/generate 🤦‍♂️

This works better: instead of importing Buffer, check Buffer from globalThis:

if (typeof globalThis.Buffer === "function")

Thanks for this @scotttrinh!

scotttrinh commented 5 months ago

@danieldunderfelt

Thanks for the investigation there! That's definitely an easy fix, so good to know that works for the Cloudflare context. Will update.