Files
react-native/packages/eslint-plugin-codegen/react-native-modules.js
T
Ramanpreet Nara 758b63313c Use custom require hook to strip Flow types from NativeModule spec parser
Summary:
## Context
We currently run ESLint using `flow-node`. This is a very recent change that was introduced in these two diffs:
- Switch VSCode ESLint plugin using flow-node: D24454702.
- Switch all ESLint scripts to use flow-node: D24379783 (https://github.com/facebook/react-native/commit/ad5802cf916c1cbe3e142385a29810a0d7205c6c).

## Problem
Because `react-native/eslint-plugin-codegen` (written in vanilla JavaScript) requires two files from `react-native-codegen` (written with Flow typings), we force all requires executed while initializing ESLint to compile out Flow types. Issues:
- In the grand scheme of things, this is such a tiny and isolated problem. It shouldn't be the reason why we switch over to using flow node. That's a larger decision that should be discussed outside of this diff.
- On VSCode cold start, in D24454702, I measured that using flow-node adds approximately 320ms to JavaScript file lint time. So, this is just slow.

## Solution
- Switch ESLint back to using regular node:
   - Revert the changes to VSCode's ESLint plugin: D24454702
   - Revert the changes to the internal ESLint scripts: D24379783 (https://github.com/facebook/react-native/commit/ad5802cf916c1cbe3e142385a29810a0d7205c6c).
- Inside the ESLint plugin, register a temporary require hook to remove Flow types from the NativeModule spec parser, before we require it. We de-register this hook after the requires finish.

## Implementation Notes:
- The `with-babel-register/` is a fork of `babel/register`, except I simplified the implementation based on the assumption that we're using it literally to only compile `react-native-codegen`.
- `with-babel-register/` uses a disk cache, so we only call transformSync when a the input file (1) hasn't been transformed before, or (2) the cache entry was created before the file was last modified.
- I ported over the source-map logic, so that when the NativeModule spec parser throws non-parsing errors, we get the correct stack trace. **Note:** I'm not sure if the source maps will work if there's a babel/register earlier during initialization. However, I don't think this will pose an actual problem, since we don't use a babel/register hook earlier. So, I think we should punt on this investigation.

## Alternative: Why aren't we using babel/register?
Every time you call babel/register, it replaces the last registered hook. We don't want the ESLint plugin to be changing any existing require hooks that people have set up. Abandoned diff with babel/register: D24519349.

Changelog: [Internal]

Reviewed By: cpojer

Differential Revision: D24551549

fbshipit-source-id: bbd7c5be44f74c0e9adbb20fe86e09802410b123
2020-10-27 00:41:47 -07:00

253 lines
6.6 KiB
JavaScript

/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react_native
* @format
*/
'use strict';
const path = require('path');
const withBabelRegister = require('./with-babel-register');
const ERRORS = {
misnamedHasteModule(hasteModuleName) {
return `Module ${hasteModuleName}: All files using TurboModuleRegistry must start with Native.`;
},
untypedModuleRequire(hasteModuleName, requireMethodName) {
return `Module ${hasteModuleName}: Please type parameterize the Module require: TurboModuleRegistry.${requireMethodName}<Spec>().`;
},
incorrectlyTypedModuleRequire(hasteModuleName, requireMethodName) {
return `Module ${hasteModuleName}: Type parameter of Module require must be 'Spec': TurboModuleRegistry.${requireMethodName}<Spec>().`;
},
multipleModuleRequires(hasteModuleName, numCalls) {
return `Module ${hasteModuleName}: Module spec must contain exactly one call into TurboModuleRegistry, detected ${numCalls}.`;
},
calledModuleRequireWithWrongType(hasteModuleName, requireMethodName, type) {
const a = /[aeiouy]/.test(type.toLowerCase()) ? 'an' : 'a';
return `Module ${hasteModuleName}: TurboModuleRegistry.${requireMethodName}<Spec>() must be called with a string literal, detected ${a} '${type}'.`;
},
calledModuleRequireWithWrongLiteral(
hasteModuleName,
requireMethodName,
literal,
) {
return `Module ${hasteModuleName}: TurboModuleRegistry.${requireMethodName}<Spec>() must be called with a string literal, detected ${literal}`;
},
};
let RNModuleParser;
let RNParserUtils;
function requireModuleParser() {
if (RNModuleParser == null || RNParserUtils == null) {
const config = {
only: [/react-native-codegen\/src\//],
plugins: [require('@babel/plugin-transform-flow-strip-types').default],
};
withBabelRegister(config, () => {
RNModuleParser = require('react-native-codegen/src/parsers/flow/modules');
RNParserUtils = require('react-native-codegen/src/parsers/flow/utils');
});
}
return {
buildModuleSchema: RNModuleParser.buildModuleSchema,
createParserErrorCapturer: RNParserUtils.createParserErrorCapturer,
};
}
const VALID_SPEC_NAMES = /^Native\S+$/;
function isModuleRequire(node) {
if (node.type !== 'CallExpression') {
return false;
}
const callExpression = node;
if (callExpression.callee.type !== 'MemberExpression') {
return false;
}
const memberExpression = callExpression.callee;
if (
!(
memberExpression.object.type === 'Identifier' &&
memberExpression.object.name === 'TurboModuleRegistry'
)
) {
return false;
}
if (
!(
memberExpression.property.type === 'Identifier' &&
(memberExpression.property.name === 'get' ||
memberExpression.property.name === 'getEnforcing')
)
) {
return false;
}
return true;
}
function isGeneratedFile(context) {
return (
context
.getSourceCode()
.getText()
.indexOf('@' + 'generated SignedSource<<') !== -1
);
}
/**
* A lint rule to guide best practices in writing type safe React NativeModules.
*/
function rule(context) {
const filename = context.getFilename();
const hasteModuleName = path.basename(filename).replace(/\.js$/, '');
if (isGeneratedFile(context)) {
return {};
}
let moduleRequires = [];
return {
'Program:exit': function(node) {
if (moduleRequires.length === 0) {
return;
}
if (moduleRequires.length > 1) {
moduleRequires.forEach(callExpressionNode => {
context.report({
node: callExpressionNode,
message: ERRORS.multipleModuleRequires(
hasteModuleName,
moduleRequires.length,
),
});
});
return;
}
// Report invalid file names
if (!VALID_SPEC_NAMES.test(hasteModuleName)) {
context.report({
node,
message: ERRORS.misnamedHasteModule(hasteModuleName),
});
}
const {
buildModuleSchema,
createParserErrorCapturer,
} = requireModuleParser();
const flowParser = require('flow-parser');
const [parsingErrors, guard] = createParserErrorCapturer();
const sourceCode = context.getSourceCode().getText();
const ast = flowParser.parse(sourceCode);
guard(() => buildModuleSchema(hasteModuleName, [], ast, guard));
parsingErrors.forEach(error => {
context.report({
loc: error.node.loc,
message: error.message,
});
});
},
CallExpression(node) {
if (!isModuleRequire(node)) {
return;
}
moduleRequires.push(node);
/**
* Validate that NativeModule requires are typed
*/
const {typeArguments} = node;
if (typeArguments == null) {
const methodName = node.callee.property.name;
context.report({
node,
message: ERRORS.untypedModuleRequire(hasteModuleName, methodName),
});
return;
}
if (typeArguments.type !== 'TypeParameterInstantiation') {
return;
}
const [param] = typeArguments.params;
/**
* Validate that NativeModule requires are correctly typed
*/
if (
typeArguments.params.length !== 1 ||
param.type !== 'GenericTypeAnnotation' ||
param.id.name !== 'Spec'
) {
const methodName = node.callee.property.name;
context.report({
node,
message: ERRORS.incorrectlyTypedModuleRequire(
hasteModuleName,
methodName,
),
});
return;
}
/**
* Validate the TurboModuleRegistry.get<Spec>(...) argument
*/
if (node.arguments.length === 1) {
const methodName = node.callee.property.name;
if (node.arguments[0].type !== 'Literal') {
context.report({
node: node.arguments[0],
message: ERRORS.calledModuleRequireWithWrongType(
hasteModuleName,
methodName,
node.arguments[0].type,
),
});
return;
}
if (typeof node.arguments[0].value !== 'string') {
context.report({
node: node.arguments[0],
message: ERRORS.calledModuleRequireWithWrongLiteral(
hasteModuleName,
methodName,
node.arguments[0].value,
),
});
return;
}
}
return true;
},
};
}
rule.errors = ERRORS;
module.exports = rule;