ulid / javascript

Universally Unique Lexicographically Sortable Identifier
MIT License
3.04k stars 107 forks source link

Look for crypto library using `self` keyword instead of `window` #97

Open jrsun opened 2 years ago

jrsun commented 2 years ago

The name of the global namespace varies in different execution environments. The self keyword allows accessing crypto in both the browser and WorkerGlobalScope (web workers/service workers), whereas window only works for the browser. This change allows the library to work in more environments than previously.

References

Window.self WorkerGlobalScope.self Web APIs available in Workers

DavidJFelix commented 2 years ago

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.