From 4c1024853245e34d50d68c8bfffae305e8ab5a0e Mon Sep 17 00:00:00 2001 From: Alex Hunt Date: Fri, 1 Nov 2024 05:15:17 -0700 Subject: [PATCH] Skip plugin for non-Flow JS code (#1556) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: This is a mitigation for https://github.com/facebook/hermes/issues/1549. Updates `babel-plugin-syntax-hermes-parser` to abort when the file contents do not include `flow`. **Context: React Native** Originally changed in https://github.com/facebook/react-native/pull/46696, as our internal Flow support had diverged from `babel/plugin-syntax-flow` (https://github.com/facebook/react-native/issues/46601). We effectively have three flavours of JavaScript in support: - Flow@latest for the `react-native` package, shipped as source — uses `hermes-parser`. - TypeScript for product code (community template, Expo) — uses `babel/plugin-syntax-typescript`. - Plain JavaScript/JSX in product code, *which may be extended with additional user Babel plugins and needs lenient parsing* — uses base `babel/parser` (**this change**). I'd love to simplify this 😅. Differential Revision: D65272155 --- .../__tests__/babel-plugin-syntax-hermes-parser-test.js | 2 +- .../js/babel-plugin-syntax-hermes-parser/src/index.js | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/__tests__/babel-plugin-syntax-hermes-parser-test.js b/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/__tests__/babel-plugin-syntax-hermes-parser-test.js index a03108c2b20..3bcf530c55c 100644 --- a/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/__tests__/babel-plugin-syntax-hermes-parser-test.js +++ b/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/__tests__/babel-plugin-syntax-hermes-parser-test.js @@ -16,7 +16,7 @@ import {transformSync} from '@babel/core'; import hermesParserPlugin from '../src'; import * as HermesParser from 'hermes-parser'; -const MODULE_PREAMBLE = '"use strict";\n\n'; +const MODULE_PREAMBLE = '// @flow\n\n"use strict";\n\n'; describe('babel-plugin-syntax-hermes-parser', () => { test('test basic parsing', () => { diff --git a/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/src/index.js b/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/src/index.js index a04237fb031..9bc6818fe74 100644 --- a/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/src/index.js +++ b/tools/hermes-parser/js/babel-plugin-syntax-hermes-parser/src/index.js @@ -42,6 +42,7 @@ export default function BabelPluginSyntaxHermesParser( ) { return; } + const opts: ParserOptions = {}; for (const [key, value] of Object.entries(curParserOpts)) { if (HermesParser.ParserOptionsKeys.has(key)) { @@ -49,6 +50,11 @@ export default function BabelPluginSyntaxHermesParser( opts[key] = value; } } + + if (opts.flow !== 'all' && !/@flow/.test(code)) { + return; + } + return HermesParser.parse(code, {...opts, babel: true}); },