diff --git a/src/utils.ts b/src/utils.ts index a11b1b3..61528c0 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,6 +1,32 @@ import { emptyFunction, tTable } from './constants'; import type { Fn, Statistics } from './types'; +/** + * The JavaScript runtime environment. + */ +enum JSRuntime { + bun = 'bun', + deno = 'deno', + node = 'node', + browser = 'browser', +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access +const isBun = !!(globalThis as any).Bun || !!globalThis.process.versions.bun; +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access +const isDeno = !!(globalThis as any).Deno; +const isNode = globalThis.process.release.name === 'node'; +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access +const isBrowser = !!(globalThis as any).navigator; + +const runtime: JSRuntime | 'unknown' = (() => { + if (isBun) return JSRuntime.bun; + if (isDeno) return JSRuntime.deno; + if (isNode) return JSRuntime.node; + if (isBrowser) return JSRuntime.browser; + return 'unknown'; +})(); + /** * Converts nanoseconds to milliseconds. * @@ -17,7 +43,14 @@ export const nToMs = (ns: number) => ns / 1e6; */ export const mToNs = (ms: number) => ms * 1e6; -const hrtimeBigint = process.hrtime.bigint.bind(process.hrtime); +let hrtimeBigint: () => bigint; +if (runtime === JSRuntime.browser) { + hrtimeBigint = () => { + throw new Error('hrtime.bigint() is not supported in this JS environment'); + }; +} else { + hrtimeBigint = process.hrtime.bigint.bind(process.hrtime); +} export const hrtimeNow = () => nToMs(Number(hrtimeBigint())); const performanceNow = performance.now.bind(performance);