Skip to content

Reset Error.prepareStackTrace finally - #16187

Merged
JLHwung merged 3 commits into
babel:mainfrom
liuxingbaoyu:fix-reset-prepareStackTrace
Nov 14, 2026
Merged

JLHwung merged 3 commits into
babel:mainfrom
liuxingbaoyu:fix-reset-prepareStackTrace

Conversation

@liuxingbaoyu

Copy link
Copy Markdown
Member
Q                       A
Fixed Issues? Fixes #16099
Patch: Bug Fix?
Major: Breaking Change?
Minor: New Feature?
Tests Added + Pass? √
Documentation PR Link
Any Dependency Changes?
License MIT

@liuxingbaoyu liuxingbaoyu added PR: Bug Fix 🐛 A type of pull request used for our changelog categories pkg: core labels Dec 21, 2023
@babel-bot

babel-bot commented Dec 21, 2023 •

Copy link
Copy Markdown
Collaborator

Build successful! You can test your changes in the REPL here: https://babeljs.io/repl/build/63279

@liuxingbaoyu
liuxingbaoyu marked this pull request as draft December 21, 2023 13:32
@liuxingbaoyu
liuxingbaoyu force-pushed the fix-reset-prepareStackTrace branch from c4a52d2 to 4d041b2 Compare December 21, 2023 13:34
@liuxingbaoyu
liuxingbaoyu marked this pull request as ready for review December 21, 2023 13:35
@liuxingbaoyu
liuxingbaoyu force-pushed the fix-reset-prepareStackTrace branch from 4d041b2 to 6a42b03 Compare December 21, 2023 13:58
@liuxingbaoyu liuxingbaoyu changed the title Reset Error.prepareStackTrace on finally Reset Error.prepareStackTrace finally Dec 21, 2023
@liuxingbaoyu
liuxingbaoyu force-pushed the fix-reset-prepareStackTrace branch from f3a5753 to 58d0bc7 Compare January 8, 2024 13:55
@liuxingbaoyu
liuxingbaoyu force-pushed the fix-reset-prepareStackTrace branch from 58d0bc7 to 38e063f Compare February 17, 2024 23:24
@liuxingbaoyu
liuxingbaoyu force-pushed the fix-reset-prepareStackTrace branch from 38e063f to 950fb08 Compare February 26, 2024 09:17
@JLHwung
JLHwung requested a review from nicolo-ribaudo June 4, 2025 18:32
@JLHwung

JLHwung commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

@liuxingbaoyu Could you rebase this PR?

@liuxingbaoyu
liuxingbaoyu force-pushed the fix-reset-prepareStackTrace branch from 950fb08 to 7c360c2 Compare November 11, 2026 16:37
@liuxingbaoyu

Copy link
Copy Markdown
Member Author

@JLHwung Done! Sorry for the delay, because I rewrote this fix.

@liuxingbaoyu
liuxingbaoyu force-pushed the fix-reset-prepareStackTrace branch from 7c360c2 to e1770e9 Compare November 11, 2026 16:43
@pkg-pr-new

pkg-pr-new Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

commit: c9e933f

};
function resetPrepareStackTrace() {
if (--stackTraceRewriterRefCount > 0) return;
Error.prepareStackTrace = originalPrepareStackTrace;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we reset only if Error.prepareStackTrace is stackTraceRewriter? So we will not mess up with other libraries that might also overwrite Error.prepareStackTrace. Ditto for stackTraceLimit.

} catch (err) {
// Format the stack while the rewriter is still installed.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
(err as Error).stack;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we guard this with the non-null and typeof object check? Otherwise if a plugin throw null here, the error will be very confusing.

"restores stack settings after an asynchronous $mode call (fails: $fails)",
async function ({ mode, fails }) {
const { prepareStackTrace, stackTraceLimit } = Error;
const { promise: paused, resolve: resume } = Promise.withResolvers();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment is from Claude:

Promise.withResolvers requires Node ^22.18, when backporting to 7.x we may have to revise the test here.

}
Error.stackTraceLimit = originalMaxStackTraceLimit;
if (Error.prepareStackTrace !== stackTraceRewriter) {
stackTraceRewriterRefCount = -1;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When resetPrepareStackTrace is called, if Error.prepareStackTrace is a function defined in a Babel plugin, then the stackTraceRewriterRefCount will be -1, and it seems now any future resetPrepareStackTrace and setupPrepareStackTrace will exit early right? If so how do we reset Error.prepareStackTrace to the original one?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems we can't safely remove it unless we ignore the user's changes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we don't keep the hook installed during the call, but rather do it in the catch of withStackTraceRewriting:

  • Install the rewriter, chained to current hook (We don't care if it is modified or not)
  • Read err.stack
  • Put the previous hook back

This happens in one sync step, so no other codes can see Babel's hook. Does it work around this issue?

The following diff is my local experiment with the help of Claude, could you check if it solves this issue?

diff --git a/packages/babel-core/src/errors/rewrite-stack-trace.ts b/packages/babel-core/src/errors/rewrite-stack-trace.ts
index 0817a369f5..dd9d29c25c 100644
--- a/packages/babel-core/src/errors/rewrite-stack-trace.ts
+++ b/packages/babel-core/src/errors/rewrite-stack-trace.ts
@@ -104,31 +104,29 @@ export function beginHiddenCallStack<A extends unknown[], R>(
   );
 }
 
-// Keep the lifecycle inside the generator so all gensync entry points release
-// the hook on completion, before invoking a callback or settling a promise.
-// The STOP_HIDING boundary stays outside gensync to hide its internal frames.
+// Only Error.stackTraceLimit has to stay raised for the whole call, so that
+// errors capture enough frames. Error.prepareStackTrace is swapped in just for
+// the synchronous `.stack` read at the API boundary: V8 formats stacks lazily
+// on first access, so no other code can ever observe Babel's formatter.
 export function withStackTraceRewriting<A extends unknown[], R>(
   fn: (...args: A) => Handler<R>,
 ): (...args: A) => Handler<R> {
   if (!SUPPORTED) return fn;
 
   return function* rewriteStackTrace(...args: A): Handler<R> {
-    setupPrepareStackTrace();
+    raiseStackTraceLimit();
     try {
       return yield* fn(...args);
     } catch (err) {
-      // Format the stack while the rewriter is still installed.
       if (
         err !== null &&
-        (typeof err === "object" || typeof err === "function") &&
-        "stack" in err
+        (typeof err === "object" || typeof err === "function")
       ) {
-        // eslint-disable-next-line @typescript-eslint/no-unused-expressions
-        err.stack;
+        formatStack(err as Error);
       }
       throw err;
     } finally {
-      resetPrepareStackTrace();
+      restoreStackTraceLimit();
     }
   };
 }
@@ -147,11 +145,52 @@ export function endHiddenCallStack<A extends unknown[], R>(
   );
 }
 
-let originalPrepareStackTrace: (err: Error, trace: CallSite[]) => string;
-let originalMaxStackTraceLimit: number;
-let stackTraceRewriterRefCount = 0;
+let activeCalls = 0;
+let originalStackTraceLimit: number;
+let raisedStackTraceLimit: number;
 
-function stackTraceRewriter(err: Error, trace: CallSite[]) {
+function raiseStackTraceLimit() {
+  if (activeCalls++ > 0) return;
+  originalStackTraceLimit = Error.stackTraceLimit;
+  // We add some extra frames to Error.stackTraceLimit, so that we can
+  // always show some useful frames even after deleting ours.
+  // However, we only do it if the user did not explicitly set it to 0.
+  const MIN_STACK_TRACE_LIMIT = 50;
+  Error.stackTraceLimit &&= Math.max(
+    Error.stackTraceLimit,
+    MIN_STACK_TRACE_LIMIT,
+  );
+  raisedStackTraceLimit = Error.stackTraceLimit;
+}
+
+function restoreStackTraceLimit() {
+  if (--activeCalls > 0) return;
+  // Leave it alone if someone else changed it in the meantime.
+  if (Error.stackTraceLimit === raisedStackTraceLimit) {
+    Error.stackTraceLimit = originalStackTraceLimit;
+  }
+}
+
+function formatStack(err: Error) {
+  const prepareStackTrace = Error.prepareStackTrace;
+  Error.prepareStackTrace = function stackTraceRewriter(err, trace) {
+    return (prepareStackTrace || defaultPrepareStackTrace)(
+      err,
+      rewriteTrace(err, trace),
+    );
+  };
+  try {
+    // Formats the stack if nothing has read it yet; no-op otherwise.
+    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
+    err.stack;
+  } catch {
+    // e.g. a throwing `stack` getter: not our business
+  } finally {
+    Error.prepareStackTrace = prepareStackTrace;
+  }
+}
+
+function rewriteTrace(err: Error, trace: CallSite[]) {
   let newTrace = [];
 
   const isExpected = expectedErrors.has(err);
@@ -170,50 +209,13 @@ function stackTraceRewriter(err: Error, trace: CallSite[]) {
         }
       } else if (status === "unknown") {
         // Unexpected internal error, show the full stack trace
-        newTrace = trace;
-        break;
+        return trace;
       }
     } else if (status !== "hiding") {
       newTrace.push(trace[i]);
     }
   }
-
-  return (originalPrepareStackTrace || defaultPrepareStackTrace)(err, newTrace);
-}
-
-function setupPrepareStackTrace() {
-  if (stackTraceRewriterRefCount < 0 || stackTraceRewriterRefCount++ > 0) {
-    return;
-  }
-  originalPrepareStackTrace = Error.prepareStackTrace;
-  originalMaxStackTraceLimit = Error.stackTraceLimit;
-
-  // We add some extra frames to Error.stackTraceLimit, so that we can
-  // always show some useful frames even after deleting ours.
-  // STACK_TRACE_LIMIT_DELTA should be around the maximum expected number
-  // of internal frames, and not too big because capturing the stack trace
-  // is slow (this is why Error.stackTraceLimit does not default to Infinity!).
-  // Increase it if needed.
-  // However, we only do it if the user did not explicitly set it to 0.
-  const MIN_STACK_TRACE_LIMIT = 50;
-  Error.stackTraceLimit &&= Math.max(
-    Error.stackTraceLimit,
-    MIN_STACK_TRACE_LIMIT,
-  );
-
-  Error.prepareStackTrace = stackTraceRewriter;
-}
-
-function resetPrepareStackTrace() {
-  if (stackTraceRewriterRefCount < 0 || --stackTraceRewriterRefCount > 0) {
-    return;
-  }
-  Error.stackTraceLimit = originalMaxStackTraceLimit;
-  if (Error.prepareStackTrace !== stackTraceRewriter) {
-    stackTraceRewriterRefCount = -1;
-    return;
-  }
-  Error.prepareStackTrace = originalPrepareStackTrace;
+  return newTrace;
 }
 
 function defaultPrepareStackTrace(err: Error, trace: CallSite[]) {
diff --git a/packages/babel-core/test/errors-stacks.js b/packages/babel-core/test/errors-stacks.js
index b29c7884ec..822c420c92 100644
--- a/packages/babel-core/test/errors-stacks.js
+++ b/packages/babel-core/test/errors-stacks.js
@@ -335,7 +335,7 @@ describe("@babel/core errors", function () {
               async pre() {
                 started();
                 await paused;
-                expect(Error.prepareStackTrace).not.toBeNull();
+                expect(Error.prepareStackTrace).toBeNull();
                 expect(Error.stackTraceLimit).toBeGreaterThanOrEqual(50);
                 if (fails) throw new Error("asynchronous plugin failure");
               },
@@ -356,7 +356,7 @@ describe("@babel/core errors", function () {
                 });
               });
         await entered;
-        expect(Error.prepareStackTrace).not.toBeNull();
+        expect(Error.prepareStackTrace).toBeNull();
         resume();
         const outcome = await pending.then(
           result => ({ result }),
@@ -395,7 +395,7 @@ describe("@babel/core errors", function () {
           () => ({
             pre() {
               const rewriter = Error.prepareStackTrace;
-              expect(rewriter).not.toBeNull();
+              expect(rewriter).toBeNull();
               babel.parseSync("bar;", { configFile: false, babelrc: false });
               expect(Error.prepareStackTrace).toBe(rewriter);
               expect(Error.stackTraceLimit).toBeGreaterThanOrEqual(50);
@@ -442,7 +442,7 @@ describe("@babel/core errors", function () {
       releases[0]();
       await pending[0];
       expect(Error.prepareStackTrace).toBe(rewriter);
-      expect(Error.prepareStackTrace).not.toBeNull();
+      expect(Error.prepareStackTrace).toBeNull();
       expect(Error.stackTraceLimit).toBeGreaterThanOrEqual(50);
       releases[1]();
       await pending[1];
@@ -485,6 +485,43 @@ describe("@babel/core errors", function () {
     }
   });
 
+  it("keeps hooks installed by other code during a call, and keeps hiding frames", function () {
+    const { prepareStackTrace, stackTraceLimit } = Error;
+    const foreign = (err, trace) => `${err}\n    at ${trace.join("\n    at ")}`;
+    try {
+      Error.prepareStackTrace = null;
+      Error.stackTraceLimit = 10;
+      babel.transformSync("foo;", {
+        configFile: false,
+        babelrc: false,
+        plugins: [
+          () => ({
+            pre() {
+              Error.prepareStackTrace = foreign;
+              Error.stackTraceLimit = 33;
+            },
+          }),
+        ],
+      });
+      expect(Error.prepareStackTrace).toBe(foreign);
+      expect(Error.stackTraceLimit).toBe(33);
+      Error.stackTraceLimit = 10;
+      // Frames are still hidden, and formatted by the current hook.
+      try {
+        babel.parseSync("foo;", { root: fixture("invalid-json") });
+      } catch (e) {
+        // Only the virtual config frame and the public entry point remain.
+        const frames = e.stack.split("\n").slice(1, 3);
+        expect(frames[0]).toMatch(/invalid-json\/babel\.config\.json$/);
+        expect(frames[1]).toMatch(/^\s+at Module\.parseSync /);
+      }
+      expect(Error.prepareStackTrace).toBe(foreign);
+    } finally {
+      Error.prepareStackTrace = prepareStackTrace;
+      Error.stackTraceLimit = stackTraceLimit;
+    }
+  });
+
   it("should not throw in `node --frozen-intrinsics`", function () {
     expect(
       spawnSync(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! This looks good.
If err.stack has already been read, it won’t take effect, but I think that’s fine.

Apply JLHwung's suggestion to install the formatter only while reading an
error stack, while keeping the stack trace limit raised during the call.

Source: babel#16187 (comment)

Assisted-by: GPT-6

@JLHwung JLHwung left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, I have no other comments.

@JLHwung
JLHwung added this pull request to the merge queue Nov 14, 2026
Merged via the queue into babel:main with commit 6284480 Nov 14, 2026
46 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pkg: core PR: Bug Fix 🐛 A type of pull request used for our changelog categories

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Our custom Error.prepareStackTrace leaks to the user

3 participants