From de88d1fbb69f2ee6b3d58a5e7bbf5f74ef132a13 Mon Sep 17 00:00:00 2001 From: Jean-Yves Moyen Date: Tue, 22 Oct 2024 11:47:08 +0200 Subject: [PATCH] Stop using node:perf_hooks (#1704) --- .changeset/strong-cougars-push.md | 7 +++++ packages/alfa-performance/src/now.ts | 39 +++++++++++++--------------- 2 files changed, 25 insertions(+), 21 deletions(-) create mode 100644 .changeset/strong-cougars-push.md diff --git a/.changeset/strong-cougars-push.md b/.changeset/strong-cougars-push.md new file mode 100644 index 0000000000..2c7a015f94 --- /dev/null +++ b/.changeset/strong-cougars-push.md @@ -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. diff --git a/packages/alfa-performance/src/now.ts b/packages/alfa-performance/src/now.ts index 6bf2d4d5cc..205945092b 100644 --- a/packages/alfa-performance/src/now.ts +++ b/packages/alfa-performance/src/now.ts @@ -1,25 +1,22 @@ /// -import type { Thunk } from "@siteimprove/alfa-thunk"; - -import perfHooks from "node:perf_hooks"; - -export let now: Thunk; - -/** - * 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 = + typeof performance !== "undefined" + ? () => performance.now() + : () => Date.now();