Commit Graph

24 Commits

Author SHA1 Message Date
Umar Mohammad 191ddc1ec7 Fix React Native Commands Export Validation in Coverage Mode (#53381)
Summary:
Changelog: [GENERAL] [FIXED] - Fixed babel plugin validation error when coverage instrumentation is enabled

Pull Request resolved: https://github.com/facebook/react-native/pull/53381

### Problem

[Workplace post](https://fb.workplace.com/groups/235694244595999/permalink/1278937163605030/)

React Native tests were failing **only when coverage collection was enabled** with the error:

`'Commands' is a reserved export and may only be used to export the result of codegenNativeCommands.`

### Root Cause

The React Native Babel plugin's `codegenNativeCommands` validation logic only handled direct `CallExpression` AST nodes. When coverage instrumentation was enabled, it transformed:

**Normal code:**

`export const Commands = codegenNativeCommands<NativeCommands>({...})`

**With coverage:**

`export const Commands = (cov_xxx().s[0]++, codegenNativeCommands<NativeCommands>({...}))`

The plugin failed to recognize the valid `codegenNativeCommands` call wrapped in a `SequenceExpression` by coverage instrumentation.

### **Solution**

Added `isCodegenNativeCommandsDeclaration` function to handle:

1.  **Coverage instrumentation**: `SequenceExpression` nodes containing the function call
2.  **Flow type casts**: `TypeCastExpression` and `AsExpression`
3.  **TypeScript assertions**: `TSAsExpression`
4.  **Direct calls**: Original `CallExpression` (backward compatibility)

Reviewed By: andrewdacenko

Differential Revision: D80572666

fbshipit-source-id: 465f4312a0229d8a92e495c685f46b607ce326e4
2025-08-21 11:33:52 -07:00
Sam Zhou af1bcb6d44 Mass replace $FlowIgnore with $FlowFixMe in react-native (#53076)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/53076

Changelog: [Internal]

Reviewed By: marcoww6

Differential Revision: D79672242

fbshipit-source-id: 560f057d8658ed602cf7241e584bade70d8f3a99
2025-08-05 15:44:41 -07:00
Tim Yung 404f3ebde2 RN: Flowify packages/react-native-codegen (#51781)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/51781

Adds `flow` to the remaining files that are lacking it in the `packages/react-native-codegen` directory.

This also adds any necessary type annotations (using comment syntax).

Changelog:
[Internal]

Reviewed By: huntie

Differential Revision: D75884727

fbshipit-source-id: 69e880b2dc63c3d6430f841652506e57436544a8
2025-06-04 12:03:52 -07:00
Tim Yung c9ea05552f RN: Fix lint/sort-imports Errors (#47109)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/47109

Fixes the `lint/sort-imports` errors that are now surfaced after fixing the lint configuration.

For a couple files, I added lint suppressions instead because the unsorted import ordering is important due to interleaved calls with side effects.

Changelog:
[Internal]

Reviewed By: GijsWeterings

Differential Revision: D64569485

fbshipit-source-id: 26415d792e2b9efe08c05d1436f723faae549882
2024-10-18 04:07:02 -07:00
Vitali Zaidman 8fba154b66 Fix source mapping for codegenNativeCommands (#46452)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/46452

`babel-plugin-codegen` transforms `codegenNativeComponent`s by expending it with a whole set of many commands (~40 lines) that don't have a good equivalent on the source file.

Currently these lines are pointing to random parts of the due to a bug that causes the source maps to be incorrect and confusing.

Instead, I point all these generated lines of code to the default export as the only line that can represent them.

This way, if an error is thrown from that generated code it would point to that export.

If the users are confused by how it works, there's a comment in the function that is used in the default export in these that explains it:
```
// If this function runs then that means the view configs were not
// generated at build time using `GenerateViewConfigJs.js`. Thus
// we need to `requireNativeComponent` to get the view configs from view managers.
// `requireNativeComponent` is not available in Bridgeless mode.
// e.g. This function runs at runtime if `codegenNativeComponent` was not called
// from a file suffixed with NativeComponent.js.
function codegenNativeComponent<Props>(
  componentName: string,
  options?: Options,
): NativeComponentType<Props> {
```

The transformation is from all the types and exports after the imports:
[`MyNativeViewNativeComponent` for example](https://github.com/facebook/react-native/blob/773a02ad5d3cc38e0f5837b42ba9a5e05a206bf9/packages/rn-tester/NativeComponentExample/js/MyNativeViewNativeComponent.js#L4)
Which is roughly (ignoring all typing):
```
// types and exports
export const Commands: NativeCommands = codegenNativeCommands<NativeCommands>({
  supportedCommands: [
    'callNativeMethodToChangeBackgroundColor',
    'callNativeMethodToAddOverlays',
    'callNativeMethodToRemoveOverlays',
    'fireLagacyStyleEvent',
  ],
});

export default (codegenNativeComponent<NativeProps>(
  'RNTMyNativeView',
): MyNativeViewType);

```
to roughly:
```
  var React = require('react');
  var nativeComponentName = 'RNTMyNativeView';
  var __INTERNAL_VIEW_CONFIG = {
    uiViewClassName: 'RNTMyNativeView',
    bubblingEventTypes: {
      topIntArrayChanged: { /* */ },
      topAlternativeLegacyName: { /* */ },
    },
    validAttributes: {
      opacity: true,
      values: true,
      ...require('ViewConfigIgnore').ConditionallyIgnoredEventHandlers({
        onIntArrayChanged: true,
        onLegacyStyleEvent: true
      })
    }
  };
  var _default = require('NativeComponentRegistry').get(nativeComponentName, () => __INTERNAL_VIEW_CONFIG);
  var Commands = {
    callNativeMethodToChangeBackgroundColor(ref, color) {
      require('RendererProxy').dispatchCommand(ref, "callNativeMethodToChangeBackgroundColor", [color]);
    },
    callNativeMethodToAddOverlays(ref, overlayColors) {
     require('RendererProxy').dispatchCommand(ref, "callNativeMethodToAddOverlays", [overlayColors]);
    },
    callNativeMethodToRemoveOverlays(ref) {
      require('RendererProxy').dispatchCommand(ref, "callNativeMethodToRemoveOverlays", []);
    },
    fireLagacyStyleEvent(ref) {
     require('RendererProxy').dispatchCommand(ref, "fireLagacyStyleEvent", []);
    }
  };
  exports.default = _default;
  exports.__INTERNAL_VIEW_CONFIG = __INTERNAL_VIEW_CONFIG;
  exports.Commands = Commands;
```

Changelog: [Fix] Fixed source maps in Native Components JS files that use codegenNativeComponent

Reviewed By: robhogan, huntie

Differential Revision: D62443699

fbshipit-source-id: 522b4382736a8fed93a1bc687a78d6885fe7c9d5
2024-09-16 05:22:38 -07:00
George Zahariev 9c135eb928 Update scripts to support AsExpressions
Summary:
Update various scripts to support AsExpressions, found by looking for scripts currently handling `TypeCastExpression`

Changelog: [Internal]

Reviewed By: SamChou19815

Differential Revision: D50822952

fbshipit-source-id: c88c04a507d94ddbc6458a68fd36509463e91953
2023-11-02 14:09:03 -07:00
Gijs Weterings d4ad19c969 Revert D49370200: Migrate codegen to shared build setup, remove package build pre-step from RNTester
Differential Revision:
D49370200

Original commit changeset: 992913155169

Original Phabricator Diff: D49370200

fbshipit-source-id: e8232c97c22065fb54ac940ee2351b2155eb51e0
2023-10-23 12:00:54 -07:00
Alex Hunt 4db31a3110 Migrate codegen to shared build setup, remove package build pre-step from RNTester (#39540)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/39540

This simplifies the use of Codegen when creating dev builds of `rn-tester` in the monorepo. It now runs from source for this internal scenario, and this package is now built using the shared monorepo build setup.

Changes:
- Migrate `packages/react-native-codegen` to the shared `yarn build` setup.
    - Update package to use `"exports"` field and wrap entry point modules with `babel-register` (NOTE: This is only required for each entry point internally used in the monorepo).
- Fixup small Flow syntax quirks that fail under `hermes-parser`.
- Remove `BuildCodegenCLITask` task from Android build.
- Remove Codegen `build.sh` call from iOS build, use `require.resolve` for `combine-js-to-schema-cli.js` entry point.

Externally significant FYIs:
- `react-native/codegen` is converted to use the `"exports"` field — it should export all `.js` files, as before.
- `codegenPath` is now ignored and marked as deprecated on `ReactExtensions.kt`.

NOTE: TypeScript auto-generation is not yet enabled on this package, since it uses CommonJS `module.exports` syntax (unsupported by `flow-api-translator`).

Changelog: [Internal]

Reviewed By: cipolleschi

Differential Revision: D49370200

fbshipit-source-id: 992913155169912ea1a3cb24cb26efbd3f783058
2023-10-23 08:32:33 -07:00
Dmitry Rykun 02957718d7 SVC Codegen: Handle TSAsExpression when looking for the codegen declaration (#40860)
Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/40860

This diff adds support for the `AS` expression in TS sources. The following codegen declaration should work now:
```
export default codegenNativeComponent<NativeProps>(
  'MyComponentView',
) as HostComponent<NativeProps>;
```
Changelog: [General][Added] - Handle TSAsExpression when looking for the codegen declaration

Reviewed By: shwanton

Differential Revision: D50225241

fbshipit-source-id: 247a3d341d742b548e82318d0fa21dff9884d2bd
2023-10-12 11:24:16 -07:00
MaeIg 462815001b Extract parseString and parseModuleFixture functions in typescript and flow parsers (#35928)
Summary:
This PR aims to extract parseString and parseModuleFixture functions into the typescript and flow parsers. This task was proposed in https://github.com/facebook/react-native/issues/35158 and helps https://github.com/facebook/react-native/issues/34872.

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry.

Pick one each for the category and type tags:

[ANDROID|GENERAL|IOS|INTERNAL] [BREAKING|ADDED|CHANGED|DEPRECATED|REMOVED|FIXED|SECURITY] - Message

For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->
[Internal] [Changed] - Extract parseString and parseModuleFixture functions in typescript and flow parsers

Pull Request resolved: https://github.com/facebook/react-native/pull/35928

Test Plan:
yarn test:
<img width="386" alt="image" src="https://user-images.githubusercontent.com/40902940/213889984-f0cadaff-4472-42d6-b55b-4901023aad1e.png">

yarn flow:
<img width="166" alt="image" src="https://user-images.githubusercontent.com/40902940/213889974-21ac2483-2731-4cb1-a2b5-195d98619649.png">

yarn lint:
<img width="514" alt="image" src="https://user-images.githubusercontent.com/40902940/213889980-090af354-346f-4a9c-90bc-7006899f0819.png">

Reviewed By: jacdebug

Differential Revision: D42673866

Pulled By: cipolleschi

fbshipit-source-id: f1b5f8a7b3944e7e8223b25c0fb9bf4e8b512aa7
2023-01-25 12:38:52 -08:00
shivenmian b7a85b59b5 chore: renamed react-native-codegen to @react-native/codegen (#34804)
Summary:
Renamed react-native-codegen package to react-native/codegen and updated references, without changing the folder name; part of RFC480 (https://github.com/facebook/react-native/issues/34692). Follow-up from https://github.com/facebook/react-native/pull/34578

## Changelog

[General] [Changed] - Renamed react-native-codegen package to react-native/codegen and updated references

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests
-->

Pull Request resolved: https://github.com/facebook/react-native/pull/34804

Reviewed By: cortinico

Differential Revision: D39883584

Pulled By: hoxyq

fbshipit-source-id: 0ef384b75c6edd248b31e37b8f05f64b4d39ca6f
2022-11-28 08:28:51 -08:00
Tim Yung 908571de2f RN: Fix Existing Lint Warnings
Summary:
Fixes all existing lint warnings in React Native.

Changelog:
[Internal]

Reviewed By: christophpurrer

Differential Revision: D39831224

fbshipit-source-id: 6ad3fc3fc7dbb9c24cdb4ff4a99639bad27c1901
2022-09-27 09:22:58 -07:00
Ramanpreet Nara df0b6900ec Enable SVC codegen in TypeScript Spec files
Summary:
## Context
babel-plugin-codegen:
1. Looks at HostComponent spec files (i.e: *NativeComponent.js files).
2. It runs the Static ViewConfig codegen (i.e: GenerateViewConfigJs.js)
3. It replaces codegenNativeComponent with NativeComponentRegistry.get.

**Before**

[react-native-svg/src/fabric/CircleNativeComponent.ts](https://github.com/react-native-svg/react-native-svg/pull/1847/files#diff-676990c4b50b85e2530021bed11f83744fb646c8ffcc769fd5d982eac1b97e98R9-R55)
```
interface SvgNodeCommonProps {
  name?: string;
  opacity?: WithDefault<Float, 1.0>;
  matrix?: ReadonlyArray<Float>;
  // transform?: ____TransformStyle_Internal, // CATransform3D, custom handling
  mask?: string;
  markerStart?: string;
  markerMid?: string;
  markerEnd?: string;
  clipPath?: string;
  clipRule?: WithDefault<Int32, 0>;
  responsible?: boolean;
  display?: string;
}

type ColorStruct = Readonly<{
  type?: WithDefault<Int32, -1>;
  value?: ColorValue;
  brushRef?: string;
}>;

interface SvgRenderableCommonProps {
  fill?: ColorStruct;
  fillOpacity?: WithDefault<Float, 1.0>;
  fillRule?: WithDefault<Int32, 1>;
  stroke?: ColorStruct;
  strokeOpacity?: WithDefault<Float, 1.0>;
  strokeWidth?: WithDefault<string, '1'>;
  strokeLinecap?: WithDefault<Int32, 0>;
  strokeLinejoin?: WithDefault<Int32, 0>;
  strokeDasharray?: ReadonlyArray<string>;
  strokeDashoffset?: Float;
  strokeMiterlimit?: Float;
  vectorEffect?: WithDefault<Int32, 0>;
  propList?: ReadonlyArray<string>;
}

interface NativeProps
  extends ViewProps,
    SvgNodeCommonProps,
    SvgRenderableCommonProps {
  cx?: string;
  cy?: string;
  r?: string;
}

export default codegenNativeComponent<NativeProps>('RNSVGCircle');
```

**After**
```
var __INTERNAL_VIEW_CONFIG = {
  uiViewClassName: "RNSVGCircle",
  validAttributes: {
    name: true,
    opacity: true,
    matrix: true,
    mask: true,
    markerStart: true,
    markerMid: true,
    markerEnd: true,
    clipPath: true,
    clipRule: true,
    responsible: true,
    display: true,
    fill: true,
    fillOpacity: true,
    fillRule: true,
    stroke: true,
    strokeOpacity: true,
    strokeWidth: true,
    strokeLinecap: true,
    strokeLinejoin: true,
    strokeDasharray: true,
    strokeDashoffset: true,
    strokeMiterlimit: true,
    vectorEffect: true,
    propList: true,
    cx: true,
    cy: true,
    r: true,
  },
};
exports.__INTERNAL_VIEW_CONFIG = __INTERNAL_VIEW_CONFIG;
var _default = NativeComponentRegistry.get(nativeComponentName, function () {
  return __INTERNAL_VIEW_CONFIG;
});
exports.default = _default;

```

## Changes
This babel plugin only worked with Flow HostComponent spec files. After this change, it'll start to work with TypeScript files as well.

## Motivation
Once published, this update will allow us to make react-native-svg static ViewConfigs-compatible.

For usage, see this GitHub commit: [feat: try to add babel plugin](https://github.com/react-native-svg/react-native-svg/pull/1847/commits/80fe687747fba6c7d7b072562278496b5fec15d1)

Changelog: [General][Added] Make babel-plugin-codegen work for TypeScript Spec files

Reviewed By: cipolleschi

Differential Revision: D39136171

fbshipit-source-id: d89d35b591577e7626ce46a9c8e73b4d7ac7f227
2022-08-30 15:15:31 -07:00
Janic Duplessis ae756647c9 Fix babel-plugin-codegen crash when export init is null (#33387)
Summary:
It is possible that `init` is null when using the following code.

```js
export var a;
```

The typescript compiler actually generates something like this for enums so a lot of third party libraries triggered this issue.

For example in expo-apple-authentication/build/AppleAuthentication.types.js

```js
export var AppleAuthenticationScope;
(function (AppleAuthenticationScope) {
    AppleAuthenticationScope[AppleAuthenticationScope["FULL_NAME"] = 0] = "FULL_NAME";
    AppleAuthenticationScope[AppleAuthenticationScope["EMAIL"] = 1] = "EMAIL";
})(AppleAuthenticationScope || (AppleAuthenticationScope = {}));
```

This simply adds a null check.

## Changelog

[General] [Fixed] - Fix babel-plugin-codegen crash when export init is null

Pull Request resolved: https://github.com/facebook/react-native/pull/33387

Test Plan: Tested that this fixed the crash in an app.

Reviewed By: javache

Differential Revision: D34687271

Pulled By: philIip

fbshipit-source-id: 7a7e0fe1bb6a7a21a5b442af26b221a263d4173d
2022-03-11 23:24:22 -08:00
Andres Suarez 8bd3edec88 Update copyright headers from Facebook to Meta
Reviewed By: aaronabramov

Differential Revision: D33367752

fbshipit-source-id: 4ce94d184485e5ee0a62cf67ad2d3ba16e285c8f
2021-12-30 15:11:21 -08:00
Sota Ogo 09b69036c0 Fallback to use lib when src doesn't exist.
Summary:
Changelog: [Internal] babel-plugin-codegen.js to fallback to use lib instead of src.

The bubel plugin uses react-native-codegen/src but it's not compatible when react-native-codegen is installed as a separate dependency (which is the case for OSS).

Reviewed By: cortinico

Differential Revision: D32908846

fbshipit-source-id: 1d3e3a3485e94e2f051e220d76dd2dbcdd8070a8
2021-12-07 12:34:50 -08:00
Tim Yung 77ecc7ede1 JS: Format with Prettier v2.4.1 [3/n]
Summary:
Changelog:
[General][Internal]

Reviewed By: zertosh

Differential Revision: D31883447

fbshipit-source-id: cbbf85e4bf935096d242336f41bf0cc5d6f92359
2021-11-02 22:14:16 -07:00
Moti Zilberman 8db946ade8 Pass configFile: false to Babel parser
Summary:
Changelog: [Internal]

Disables implicit `babel.config.js` lookup in a `parse()` call that does not need any user-specified config.

Reviewed By: javache

Differential Revision: D30396331

fbshipit-source-id: 9b07c361eae53cdffc6a76ba30f1146a7af65a10
2021-08-19 07:03:41 -07:00
Micha Reiser 58a0f9b4e2 Upgrade babel from 7.12.3 -> 7.14.1
Summary:
Changelog:

[General] [Changed] Upgrade Babel from 7.12.3 to 7.14.1

Reviewed By: motiz88

Differential Revision: D27851184

fbshipit-source-id: 59326332d1d188f163cdb034556eea7808824360
2021-05-13 02:48:09 -07:00
Ramanpreet Nara e67fc7cada Stop inlining the TurboModule schema in NativeModule specs
Summary:
See title.

Changelog: [Internal]

Reviewed By: fkgozali

Differential Revision: D25915169

fbshipit-source-id: 9a5ab08b11fb0d5e9eb47b4a4c579dcff1e60e92
2021-01-14 19:14:23 -08:00
Danny van Velzen fc1ddb6128 Fix typo of TurobModule to TurboModule (#30723)
Summary:
Fix typo in a code comment of babel codegen: TurobModule -> TurboModule
This was discovered in the PR [https://github.com/facebook/react-native/issues/6832](https://github.com/microsoft/react-native-windows/pull/6832) when [microsoft/react-native-windows](https://github.com/microsoft/react-native-windows) ingested latest react-native bits..

## Changelog

<!-- Help reviewers and the release process by writing your own changelog entry. For an example, see:
https://github.com/facebook/react-native/wiki/Changelog
-->

[Internal] [Fixed] - Fix a typo in a code comment.

Pull Request resolved: https://github.com/facebook/react-native/pull/30723

Test Plan: None, change is in a comment and most of the scripts like lint-ci don't work on windows.

Reviewed By: shergin

Differential Revision: D25884872

Pulled By: sammy-SC

fbshipit-source-id: 49dfc25d220aa9bc4f7de61c664837b193ae25e5
2021-01-13 08:22:40 -08:00
Evan Gilbert f52e3b3e8b Workaround for react-native-web failing to build
Summary:
There is partially compiled TurboModule code in [NativeAnimatedModule](https://fburl.com/diffusion/g91a70ng) that fails to build with:
`"File neither contains a module declaration, nor a component declaration. For module declarations, please make sure your file has an InterfaceDeclaration extending TurboModule. For component declarations, please make sure your file has a default export calling the codegenNativeComponent<Props>(...) macro"`

This diff removes react-native-web from the TurboModules logic while we work on a cleaner solution, tracked in T80868008

msdkland[metro]
Changelog: [Internal]

Reviewed By: cpojer, RSNara

Differential Revision: D25325163

fbshipit-source-id: 346abf52660073f976b0f978cbfbfc8402f4b3ee
2020-12-08 17:45:28 -08:00
Ramanpreet Nara b6a72bac69 Extend babel-plugin-codegen to generate TurboModule JS codegen
Summary:
## New Functionality
- Detect if the JS file represents a NativeModule spec.
  - **Note:** A JS file is a NativeModule spec if it contains a flow `interface` that extends `TurboModule`. This logic is copied over from the OSS Codegen, here: https://github.com/facebook/react-native/blob/7ccb67a49c087e7ee536c2ffb71717e68a79324b/packages/react-native-codegen/src/parsers/flow/index.js#L60-L75
- For all NativeModule specs, generate the spec's schema using the OSS Codegen for Modules, and conditionally inline it into every `TurboModuleRegistry.get(Enforcing)?` call in the spec, like so:

**Before:**
```
/**
 * flow
 */

import type {TurboModule} from 'RCTExport';
export interface Spec extends TurboModule {
  //...
}

export default TurboModuleRegistry.get<Spec>('FooModule');
```

**After:**
```
/**
 * flow
 */

import type {TurboModule} from 'RCTExport';
export interface Spec extends TurboModule {
  //...
}

export default TurboModuleRegistry.get<Spec>('FooModule', __getModuleShape());

function __getModuleShape() {
  if (!(global.RN$EnableTurboModuleJSCodegen === true)) {
    return undefined;
  }

  return {...};
}
```

Changelog: [General][Added] Extend react-native/babel-plugin-codegen to generate TurboModule JS codegen

Reviewed By: TheSavior

Differential Revision: D22803845

fbshipit-source-id: 18c157a1dbfcc575012184de31c38908acd53c36
2020-11-08 14:24:05 -08:00
Ramanpreet Nara 4cbc39a431 Rename babel-plugin-inline-view-configs to @react-native/babel-plugin-codegen
Summary:
This babel plugin will also take care of the JS TurboModule Codegen. Therefore, we should rename this into something more generic.

Changelog:
[General][Changed] Rename babel-plugin-inline-view-configs to react-native/babel-plugin-codegen

Reviewed By: rickhanlonii, cpojer

Differential Revision: D22803209

fbshipit-source-id: 416c97fea6fa0820d25bbc91033a0cbbbbbff825
2020-07-31 13:00:50 -07:00