From c651538cc536d83302eb88057629e39237c361f6 Mon Sep 17 00:00:00 2001 From: Vitali Zaidman Date: Thu, 22 Aug 2024 07:36:46 -0700 Subject: [PATCH] re-implemented babel traverse bug workaround Summary: **Problem:** `traverse(ast` was polluting `traverse.cache.path` with values missing the `hub` property needed by Babel transformation. **Former solution:** the solution implemented formally, was saving `traverse.cache.path`, clearing the cache, and then re-assigning `traverse.cache.path` to be the one before the traversal. Unfortunately, with the latest version of `babel/traverse` the assignment `traverse.cache.path = previousCache` no longer works. This is because `path` inside the esmodule `traverse.cache` is a `let export` ([see source code](https://github.com/babel/babel/blob/main/packages/babel-traverse/src/cache.ts#L6C1-L21C1)) which is resoved to: ``` let pathsCache = exports.path = new WeakMap(); function clearPath() { exports.path = pathsCache = new WeakMap(); } function getCachedPaths(hub, parent) { // ... pathsCache.get( //... // ... } ``` this means that re-writing `exports.path` breaks the module since `exports.path` won't be identical to `pathsCache` anymore and because it is used inside the module, the module breaks. **Proposed solution:** A one time shallow copy ("`shallowCopiedAST`") of the `ast` for the traverse ensures that the original `ast` is not polluted. The copy is then deleted when `forEachMapping` which calls `traverse` is ends and `shallowCopiedAST` goes out of scope, referenced only by `traverse.cache.path` which is a `WeakMap`. Differential Revision: D61336390 --- packages/metro-source-map/src/generateFunctionMap.js | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/metro-source-map/src/generateFunctionMap.js b/packages/metro-source-map/src/generateFunctionMap.js index 3e6e980bb7..7c7578a4e6 100644 --- a/packages/metro-source-map/src/generateFunctionMap.js +++ b/packages/metro-source-map/src/generateFunctionMap.js @@ -224,17 +224,15 @@ function forEachMapping( // values missing the `hub` property needed by Babel transformation, so we // save, clear, and restore the cache around our traversal. // See: https://github.com/facebook/metro/pull/854#issuecomment-1336499395 - const previousCache = traverse.cache.path; - traverse.cache.clearPath(); - traverse(ast, { + // @nocommit TODO: comment to the comment above ^ in the OS PR and update the comment above + const shallowCopiedAST = {...ast}; + traverse(shallowCopiedAST, { // Our visitor doesn't care about scope noScope: true, - Function: visitor, Program: visitor, Class: visitor, }); - traverse.cache.path = previousCache; } const ANONYMOUS_NAME = '';