javascript icon indicating copy to clipboard operation
javascript copied to clipboard

Error in worker

Open budarin opened this issue 4 years ago • 2 comments

in order to detect the browser, you need to take into account that the code can be executed in the worker and there is no window, but there is self

root = typeof window !== "undefined" ? window : null;

should be rewritten as

root = self instanceof Window || self instanceof ServiceWorkerGlobalScope || self instanceof Worker ? self : null;

budarin avatar Jan 07 '22 07:01 budarin

Hey, if anyone else finds this issue like I did and is using cloudflare workers, here's what worked for me:

import {monotonicFactory} from 'ulid'
// or import {factory} from 'ulid'

const prng = () => {
  const buffer = new Uint8Array(1)
  crypto.getRandomValues(buffer)
  return buffer[0] / 0xff
}
export const ulid = monotonicFactory(prng) // or factory(prng)

This will bypass the code that checks for browser crypto and allow you to set your own. The PRNG function is the same as used internally with a different global reference.

I think this package may be abandoned, I'm working on potentially forking it.

DavidJFelix avatar Jun 01 '22 13:06 DavidJFelix

Friendly reminder that we now have worker support over on ulidx, which is maintained unlike this library.

perry-mitchell avatar Jul 23 '23 13:07 perry-mitchell