Skip to content

Commit

Permalink
Stop using node:perf_hooks (#1704)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jym77 authored Oct 22, 2024
1 parent ec86fd9 commit de88d1f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 21 deletions.
7 changes: 7 additions & 0 deletions .changeset/strong-cougars-push.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@siteimprove/alfa-performance": patch
---

**Changed:** `Performance.now()` does not try to use `node:perf_hooks` anymore.

This created problem when trying to bundle `Performance` for browsers, where `node:` imports are not available.
39 changes: 18 additions & 21 deletions packages/alfa-performance/src/now.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,22 @@
/// <reference lib="dom" />

import type { Thunk } from "@siteimprove/alfa-thunk";

import perfHooks from "node:perf_hooks";

export let now: Thunk<number>;

/**
* The continuations are needed to correctly handle the "this" bindings.
* Eta-contracting breaks in node 19.0.0 and above. This may be linked to the
* upgrade to V8 10.7.
/*
* Performance measurement comes from different places in NodeJS and browser
* environments. The former uses node:perf_hooks, while the latter uses the
* global performance object. Trying to use the wrong one leads to at best
* undefined value, at worst compile errors at build time.
*
* Date.now actually works without the eta-expansion, keeping it for
* consistency.
* It seems to not be that easy to polyfill between the two. While it is easy
* to test whether performance is defined, trying to import perf_hooks is enough
* to crash bundlers like Webpack.
*
* Therefore, we just ignore node:perf_hooks and defaults to the widely available
* Date.now() if the performance object is not available.
*/
if (typeof performance !== "undefined") {
now = () => performance.now();
} else {
try {
now = () => perfHooks.performance.now();
} catch {
now = () => Date.now();
}
}

import type { Thunk } from "@siteimprove/alfa-thunk";

export const now: Thunk<number> =
typeof performance !== "undefined"
? () => performance.now()
: () => Date.now();

0 comments on commit de88d1f

Please sign in to comment.