Socket
Socket
Sign inDemoInstall

@react-native/codegen

Package Overview
Dependencies
Maintainers
10
Versions
408
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@react-native/codegen - npm Package Compare versions

Comparing version 0.72.5 to 0.73.0-nightly-20230603-fd9e295be

19

lib/CodegenSchema.d.ts

@@ -53,2 +53,6 @@ /**

export interface MixedTypeAnnotation {
readonly type: 'MixedTypeAnnotation';
}
export interface FunctionTypeAnnotation<P, R> {

@@ -78,2 +82,3 @@ readonly type: 'FunctionTypeAnnotation';

readonly commands: readonly NamedShape<CommandTypeAnnotation>[];
readonly deprecatedViewConfigName?: string | undefined;
}

@@ -113,3 +118,7 @@

| StringEnumTypeAnnotation
| ObjectTypeAnnotation<EventTypeAnnotation>;
| ObjectTypeAnnotation<EventTypeAnnotation>
| {
readonly type: 'ArrayTypeAnnotation';
readonly elementType: EventTypeAnnotation
};

@@ -174,3 +183,4 @@ export type PropTypeAnnotation =

};
};
}
| MixedTypeAnnotation;

@@ -270,3 +280,3 @@ export interface ReservedPropTypeAnnotation {

readonly name: string;
readonly value: string;
readonly value: string | number;
}[];

@@ -293,2 +303,3 @@

readonly type: 'GenericObjectTypeAnnotation';
readonly dictionaryValueType?: Nullable<NativeModuleTypeAnnotation> | undefined;
}

@@ -352,4 +363,4 @@

export type NativeModuleReturnOnlyTypeAnnotation =
| NativeModuleFunctionTypeAnnotation
| NativeModulePromiseTypeAnnotation
| VoidTypeAnnotation;

@@ -122,3 +122,3 @@ /**

{
name: 'onDire tChange',
name: 'onDirectChange',
paperTopLevelNameDeprecated: 'paperDirectChange',

@@ -1189,2 +1189,95 @@ optional: true,

{
name: 'onArrayEventType',
optional: true,
bubblingType: 'bubble',
typeAnnotation: {
type: 'EventTypeAnnotation',
argument: {
type: 'ObjectTypeAnnotation',
properties: [
{
name: 'bool_array_event_prop',
optional: false,
typeAnnotation: {
type: 'ArrayTypeAnnotation',
elementType: {
type: 'BooleanTypeAnnotation',
},
},
},
{
name: 'string_enum_event_prop',
optional: false,
typeAnnotation: {
type: 'ArrayTypeAnnotation',
elementType: {
type: 'StringEnumTypeAnnotation',
options: ['YES', 'NO'],
},
},
},
{
name: 'array_array_event_prop',
optional: false,
typeAnnotation: {
type: 'ArrayTypeAnnotation',
elementType: {
type: 'ArrayTypeAnnotation',
elementType: {
type: 'StringTypeAnnotation',
},
},
},
},
{
name: 'array_object_event_prop',
optional: false,
typeAnnotation: {
type: 'ArrayTypeAnnotation',
elementType: {
type: 'ObjectTypeAnnotation',
properties: [
{
name: 'lat',
optional: false,
typeAnnotation: {
type: 'DoubleTypeAnnotation',
},
},
{
name: 'lon',
optional: false,
typeAnnotation: {
type: 'DoubleTypeAnnotation',
},
},
{
name: 'names',
optional: false,
typeAnnotation: {
type: 'ArrayTypeAnnotation',
elementType: {
type: 'StringTypeAnnotation',
},
},
},
],
},
},
},
{
name: 'array_mixed_event_prop',
optional: false,
typeAnnotation: {
type: 'ArrayTypeAnnotation',
elementType: {
type: 'MixedTypeAnnotation',
},
},
},
],
},
},
},
{
name: 'onEventDirect',

@@ -1238,2 +1331,22 @@ optional: true,

},
{
name: 'onEventWithMixedPropAttribute',
optional: true,
bubblingType: 'direct',
typeAnnotation: {
type: 'EventTypeAnnotation',
argument: {
type: 'ObjectTypeAnnotation',
properties: [
{
name: 'value',
optional: false,
typeAnnotation: {
type: 'MixedTypeAnnotation',
},
},
],
},
},
},
],

@@ -1240,0 +1353,0 @@ props: [

@@ -31,2 +31,4 @@ /**

return 'Float';
case 'MixedTypeAnnotation':
return 'folly::dynamic';
default:

@@ -37,2 +39,34 @@ type;

}
function getCppArrayTypeForAnnotation(typeElement, structParts) {
switch (typeElement.type) {
case 'BooleanTypeAnnotation':
case 'StringTypeAnnotation':
case 'DoubleTypeAnnotation':
case 'FloatTypeAnnotation':
case 'Int32TypeAnnotation':
case 'MixedTypeAnnotation':
return `std::vector<${getCppTypeForAnnotation(typeElement.type)}>`;
case 'StringEnumTypeAnnotation':
case 'ObjectTypeAnnotation':
if (!structParts) {
throw new Error(
`Trying to generate the event emitter for an Array of ${typeElement.type} without informations to generate the generic type`,
);
}
return `std::vector<${generateEventStructName(structParts)}>`;
case 'ArrayTypeAnnotation':
return `std::vector<${getCppArrayTypeForAnnotation(
typeElement.elementType,
structParts,
)}>`;
default:
throw new Error(
`Can't determine array type with typeElement: ${JSON.stringify(
typeElement,
null,
2,
)}`,
);
}
}
function getImports(properties) {

@@ -72,2 +106,5 @@ const imports = new Set();

}
if (typeAnnotation.type === 'MixedTypeAnnotation') {
imports.add('#include <folly/dynamic.h>');
}
if (typeAnnotation.type === 'ObjectTypeAnnotation') {

@@ -82,4 +119,3 @@ const objectImports = getImports(typeAnnotation.properties);

function generateEventStructName(parts = []) {
const additional = parts.map(toSafeCppString).join('');
return `${additional}`;
return parts.map(toSafeCppString).join('');
}

@@ -181,2 +217,3 @@ function generateStructName(componentName, parts = []) {

convertDefaultTypeToString,
getCppArrayTypeForAnnotation,
getCppTypeForAnnotation,

@@ -183,0 +220,0 @@ getEnumMaskName,

@@ -13,5 +13,7 @@ /**

const _require = require('./CppHelpers.js'),
const _require = require('./CppHelpers'),
generateEventStructName = _require.generateEventStructName;
const FileTemplate = ({events, libraryName}) => `
const _require2 = require('../Utils'),
indent = _require2.indent;
const FileTemplate = ({events, libraryName, extraIncludes}) => `
/**

@@ -27,8 +29,7 @@ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).

#include <react/renderer/components/${libraryName}/EventEmitters.h>
${[...extraIncludes].join('\n')}
namespace facebook {
namespace react {
${events}
} // namespace react

@@ -44,7 +45,7 @@ } // namespace facebook

}) => {
const capture = implementation.includes('event')
? 'event=std::move(event)'
const capture = implementation.includes('$event')
? '$event=std::move($event)'
: '';
return `
void ${className}EventEmitter::${eventName}(${structName} event) const {
void ${className}EventEmitter::${eventName}(${structName} $event) const {
dispatchEvent("${dispatchEventName}", [${capture}](jsi::Runtime &runtime) {

@@ -54,3 +55,3 @@ ${implementation}

}
`.trim();
`;
};

@@ -63,17 +64,196 @@ const BasicComponentTemplate = ({className, eventName, dispatchEventName}) =>

`.trim();
function generateSetter(variableName, propertyName, propertyParts) {
const trailingPeriod = propertyParts.length === 0 ? '' : '.';
const eventChain = `event.${propertyParts.join(
'.',
)}${trailingPeriod}${propertyName});`;
return `${variableName}.setProperty(runtime, "${propertyName}", ${eventChain}`;
function generateSetter(
variableName,
propertyName,
propertyParts,
usingEvent,
valueMapper = value => value,
) {
const eventChain = usingEvent
? `$event.${[...propertyParts, propertyName].join('.')}`
: [propertyParts, propertyName].join('.');
return `${variableName}.setProperty(runtime, "${propertyName}", ${valueMapper(
eventChain,
)});`;
}
function generateEnumSetter(variableName, propertyName, propertyParts) {
const trailingPeriod = propertyParts.length === 0 ? '' : '.';
const eventChain = `event.${propertyParts.join(
'.',
)}${trailingPeriod}${propertyName})`;
return `${variableName}.setProperty(runtime, "${propertyName}", toString(${eventChain});`;
function generateObjectSetter(
variableName,
propertyName,
propertyParts,
typeAnnotation,
extraIncludes,
usingEvent,
) {
return `
{
auto ${propertyName} = jsi::Object(runtime);
${indent(
generateSetters(
propertyName,
typeAnnotation.properties,
propertyParts.concat([propertyName]),
extraIncludes,
usingEvent,
),
2,
)}
${variableName}.setProperty(runtime, "${propertyName}", ${propertyName});
}
function generateSetters(parentPropertyName, properties, propertyParts) {
`.trim();
}
function setValueAtIndex(
propertyName,
indexVariable,
loopLocalVariable,
mappingFunction = value => value,
) {
return `${propertyName}.setValueAtIndex(runtime, ${indexVariable}++, ${mappingFunction(
loopLocalVariable,
)});`;
}
function generateArraySetter(
variableName,
propertyName,
propertyParts,
elementType,
extraIncludes,
usingEvent,
) {
const eventChain = usingEvent
? `$event.${[...propertyParts, propertyName].join('.')}`
: [propertyParts, propertyName].join('.');
const indexVar = `${propertyName}Index`;
const innerLoopVar = `${propertyName}Value`;
return `
auto ${propertyName} = jsi::Array(runtime, ${eventChain}.size());
size_t ${indexVar} = 0;
for (auto ${innerLoopVar} : ${eventChain}) {
${handleArrayElementType(
elementType,
propertyName,
indexVar,
innerLoopVar,
propertyParts,
extraIncludes,
usingEvent,
)}
}
${variableName}.setProperty(runtime, "${propertyName}", ${propertyName});
`;
}
function handleArrayElementType(
elementType,
propertyName,
indexVariable,
loopLocalVariable,
propertyParts,
extraIncludes,
usingEvent,
) {
switch (elementType.type) {
case 'BooleanTypeAnnotation':
return setValueAtIndex(
propertyName,
indexVariable,
loopLocalVariable,
val => `(bool)${val}`,
);
case 'StringTypeAnnotation':
case 'Int32TypeAnnotation':
case 'DoubleTypeAnnotation':
case 'FloatTypeAnnotation':
return setValueAtIndex(propertyName, indexVariable, loopLocalVariable);
case 'MixedTypeAnnotation':
return setValueAtIndex(
propertyName,
indexVariable,
loopLocalVariable,
val => `jsi::valueFromDynamic(runtime, ${val})`,
);
case 'StringEnumTypeAnnotation':
return setValueAtIndex(
propertyName,
indexVariable,
loopLocalVariable,
val => `toString(${val})`,
);
case 'ObjectTypeAnnotation':
return convertObjectTypeArray(
propertyName,
indexVariable,
loopLocalVariable,
propertyParts,
elementType,
extraIncludes,
);
case 'ArrayTypeAnnotation':
return convertArrayTypeArray(
propertyName,
indexVariable,
loopLocalVariable,
propertyParts,
elementType,
extraIncludes,
usingEvent,
);
default:
throw new Error(
`Received invalid elementType for array ${elementType.type}`,
);
}
}
function convertObjectTypeArray(
propertyName,
indexVariable,
loopLocalVariable,
propertyParts,
objectTypeAnnotation,
extraIncludes,
) {
return `auto ${propertyName}Object = jsi::Object(runtime);
${generateSetters(
`${propertyName}Object`,
objectTypeAnnotation.properties,
[].concat([loopLocalVariable]),
extraIncludes,
false,
)}
${setValueAtIndex(propertyName, indexVariable, `${propertyName}Object`)}`;
}
function convertArrayTypeArray(
propertyName,
indexVariable,
loopLocalVariable,
propertyParts,
eventTypeAnnotation,
extraIncludes,
usingEvent,
) {
if (eventTypeAnnotation.type !== 'ArrayTypeAnnotation') {
throw new Error(
`Inconsistent eventTypeAnnotation received. Expected type = 'ArrayTypeAnnotation'; received = ${eventTypeAnnotation.type}`,
);
}
return `auto ${propertyName}Array = jsi::Array(runtime, ${loopLocalVariable}.size());
size_t ${indexVariable}Internal = 0;
for (auto ${loopLocalVariable}Internal : ${loopLocalVariable}) {
${handleArrayElementType(
eventTypeAnnotation.elementType,
`${propertyName}Array`,
`${indexVariable}Internal`,
`${loopLocalVariable}Internal`,
propertyParts,
extraIncludes,
usingEvent,
)}
}
${setValueAtIndex(propertyName, indexVariable, `${propertyName}Array`)}`;
}
function generateSetters(
parentPropertyName,
properties,
propertyParts,
extraIncludes,
usingEvent = true,
) {
const propSetters = properties

@@ -84,8 +264,6 @@ .map(eventProperty => {

case 'BooleanTypeAnnotation':
return generateSetter(
parentPropertyName,
eventProperty.name,
propertyParts,
);
case 'StringTypeAnnotation':
case 'Int32TypeAnnotation':
case 'DoubleTypeAnnotation':
case 'FloatTypeAnnotation':
return generateSetter(

@@ -95,4 +273,6 @@ parentPropertyName,

propertyParts,
usingEvent,
);
case 'Int32TypeAnnotation':
case 'MixedTypeAnnotation':
extraIncludes.add('#include <jsi/JSIDynamic.h>');
return generateSetter(

@@ -102,4 +282,6 @@ parentPropertyName,

propertyParts,
usingEvent,
prop => `jsi::valueFromDynamic(runtime, ${prop})`,
);
case 'DoubleTypeAnnotation':
case 'StringEnumTypeAnnotation':
return generateSetter(

@@ -109,32 +291,28 @@ parentPropertyName,

propertyParts,
usingEvent,
prop => `toString(${prop})`,
);
case 'FloatTypeAnnotation':
return generateSetter(
case 'ObjectTypeAnnotation':
return generateObjectSetter(
parentPropertyName,
eventProperty.name,
propertyParts,
typeAnnotation,
extraIncludes,
usingEvent,
);
case 'StringEnumTypeAnnotation':
return generateEnumSetter(
case 'ArrayTypeAnnotation':
return generateArraySetter(
parentPropertyName,
eventProperty.name,
propertyParts,
typeAnnotation.elementType,
extraIncludes,
usingEvent,
);
case 'ObjectTypeAnnotation':
const propertyName = eventProperty.name;
return `
{
auto ${propertyName} = jsi::Object(runtime);
${generateSetters(
propertyName,
typeAnnotation.properties,
propertyParts.concat([propertyName]),
)}
${parentPropertyName}.setProperty(runtime, "${propertyName}", ${propertyName});
}
`.trim();
default:
typeAnnotation.type;
throw new Error('Received invalid event property type');
throw new Error(
`Received invalid event property type ${typeAnnotation.type}`,
);
}

@@ -145,3 +323,3 @@ })

}
function generateEvent(componentName, event) {
function generateEvent(componentName, event, extraIncludes) {
// This is a gross hack necessary because native code is sending

@@ -158,5 +336,10 @@ // events named things like topChange to JS which is then converted back to

const implementation = `
auto payload = jsi::Object(runtime);
${generateSetters('payload', event.typeAnnotation.argument.properties, [])}
return payload;
auto $payload = jsi::Object(runtime);
${generateSetters(
'$payload',
event.typeAnnotation.argument.properties,
[],
extraIncludes,
)}
return $payload;
`.trim();

@@ -197,3 +380,3 @@ if (!event.name.startsWith('on')) {

.reduce((acc, components) => Object.assign(acc, components), {});
const fileName = 'EventEmitters.cpp';
const extraIncludes = new Set();
const componentEmitters = Object.keys(moduleComponents)

@@ -203,11 +386,11 @@ .map(componentName => {

return component.events
.map(event => {
return generateEvent(componentName, event);
})
.map(event => generateEvent(componentName, event, extraIncludes))
.join('\n');
})
.join('\n');
const fileName = 'EventEmitters.cpp';
const replacedTemplate = FileTemplate({
libraryName,
events: componentEmitters,
extraIncludes,
});

@@ -214,0 +397,0 @@ return new Map([[fileName, replacedTemplate]]);

@@ -15,2 +15,4 @@ /**

const _require = require('./CppHelpers'),
getImports = _require.getImports,
getCppArrayTypeForAnnotation = _require.getCppArrayTypeForAnnotation,
getCppTypeForAnnotation = _require.getCppTypeForAnnotation,

@@ -21,3 +23,3 @@ generateEventStructName = _require.generateEventStructName;

toSafeCppString = _require2.toSafeCppString;
const FileTemplate = ({componentEmitters}) => `
const FileTemplate = ({componentEmitters, extraIncludes}) => `
/**

@@ -34,9 +36,7 @@ * This code was generated by [react-native-codegen](https://www.npmjs.com/package/react-native-codegen).

#include <react/renderer/components/view/ViewEventEmitter.h>
#include <jsi/jsi.h>
${[...extraIncludes].join('\n')}
namespace facebook {
namespace react {
${componentEmitters}
} // namespace react

@@ -47,3 +47,3 @@ } // namespace facebook

`
class JSI_EXPORT ${className}EventEmitter : public ViewEventEmitter {
class ${className}EventEmitter : public ViewEventEmitter {
public:

@@ -53,3 +53,2 @@ using ViewEventEmitter::ViewEventEmitter;

${structs}
${events}

@@ -83,7 +82,18 @@ };

case 'FloatTypeAnnotation':
case 'MixedTypeAnnotation':
return getCppTypeForAnnotation(type);
case 'StringEnumTypeAnnotation':
return generateEventStructName(nameParts.concat([eventProperty.name]));
case 'ObjectTypeAnnotation':
return generateEventStructName(nameParts.concat([eventProperty.name]));
return generateEventStructName([...nameParts, eventProperty.name]);
case 'ArrayTypeAnnotation':
const eventTypeAnnotation = eventProperty.typeAnnotation;
if (eventTypeAnnotation.type !== 'ArrayTypeAnnotation') {
throw new Error(
"Inconsistent Codegen state: type was ArrayTypeAnnotation at the beginning of the body and now it isn't",
);
}
return getCppArrayTypeForAnnotation(eventTypeAnnotation.elementType, [
...nameParts,
eventProperty.name,
]);
default:

@@ -114,2 +124,28 @@ type;

}
function handleGenerateStructForArray(
structs,
name,
componentName,
elementType,
nameParts,
) {
if (elementType.type === 'ObjectTypeAnnotation') {
generateStruct(
structs,
componentName,
nameParts.concat([name]),
nullthrows(elementType.properties),
);
} else if (elementType.type === 'StringEnumTypeAnnotation') {
generateEnum(structs, elementType.options, nameParts.concat([name]));
} else if (elementType.type === 'ArrayTypeAnnotation') {
handleGenerateStructForArray(
structs,
name,
componentName,
elementType.elementType,
nameParts,
);
}
}
function generateStruct(structs, componentName, nameParts, properties) {

@@ -132,11 +168,17 @@ const structNameParts = nameParts;

case 'BooleanTypeAnnotation':
return;
case 'StringTypeAnnotation':
return;
case 'Int32TypeAnnotation':
return;
case 'DoubleTypeAnnotation':
return;
case 'FloatTypeAnnotation':
case 'MixedTypeAnnotation':
return;
case 'ArrayTypeAnnotation':
handleGenerateStructForArray(
structs,
name,
componentName,
typeAnnotation.elementType,
nameParts,
);
return;
case 'ObjectTypeAnnotation':

@@ -200,3 +242,3 @@ generateStruct(

if (module.type !== 'Component') {
return;
return null;
}

@@ -212,20 +254,27 @@ const components = module.components;

.reduce((acc, components) => Object.assign(acc, components), {});
const moduleComponentsWithEvents = Object.keys(moduleComponents);
const extraIncludes = new Set();
const componentEmitters = Object.keys(moduleComponents)
.map(componentName => {
const component = moduleComponents[componentName];
component.events.forEach(event => {
if (event.typeAnnotation.argument) {
const argIncludes = getImports(
event.typeAnnotation.argument.properties,
);
// $FlowFixMe[method-unbinding]
argIncludes.forEach(extraIncludes.add, extraIncludes);
}
});
const replacedTemplate = ComponentTemplate({
className: componentName,
structs: indent(generateStructs(componentName, component), 2),
events: generateEvents(componentName, component),
});
return replacedTemplate;
})
.join('\n');
const fileName = 'EventEmitters.h';
const componentEmitters =
moduleComponentsWithEvents.length > 0
? Object.keys(moduleComponents)
.map(componentName => {
const component = moduleComponents[componentName];
const replacedTemplate = ComponentTemplate({
className: componentName,
structs: indent(generateStructs(componentName, component), 2),
events: generateEvents(componentName, component),
});
return replacedTemplate;
})
.join('\n')
: '';
const replacedTemplate = FileTemplate({
componentEmitters,
extraIncludes,
});

@@ -232,0 +281,0 @@ return new Map([[fileName, replacedTemplate]]);

@@ -49,3 +49,3 @@ /**

${structs}
class JSI_EXPORT ${className} final${extendClasses} {
class ${className} final${extendClasses} {
public:

@@ -350,3 +350,2 @@ ${className}() = default;

imports.add('#include <react/renderer/core/PropsParserContext.h>');
imports.add('#include <jsi/jsi.h>');
extendsProps.forEach(extendProps => {

@@ -353,0 +352,0 @@ switch (extendProps.type) {

@@ -92,3 +92,2 @@ /**

const arrayTypeAnnotation = typeAnnotation;
// TODO: Flow assumes elementType can be any. Fix this.
const elementType = arrayTypeAnnotation.elementType;

@@ -95,0 +94,0 @@ const pojoElementType = (() => {

@@ -36,4 +36,8 @@ /**

#ifndef RCT_DYNAMIC_FRAMEWORKS
${lookupFuncs}
#endif
#ifdef __cplusplus

@@ -40,0 +44,0 @@ }

@@ -34,3 +34,5 @@ /**

static std::unordered_map<std::string, Class (*)(void)> sFabricComponentsClassMap = {
#ifndef RCT_DYNAMIC_FRAMEWORKS
${lookupMap}
#endif
};

@@ -37,0 +39,0 @@

@@ -94,4 +94,4 @@ /**

const isVoid = returnTypeAnnotation.type === 'VoidTypeAnnotation';
const methodCallArgs = ['rt', ...args].join(', ');
const methodCall = `static_cast<${hasteModuleName}CxxSpecJSI *>(&turboModule)->${methodName}(${methodCallArgs})`;
const methodCallArgs = [' rt', ...args].join(',\n ');
const methodCall = `static_cast<${hasteModuleName}CxxSpecJSI *>(&turboModule)->${methodName}(\n${methodCallArgs}\n )`;
return `static jsi::Value __hostFunction_${hasteModuleName}CxxSpecJSI_${methodName}(jsi::Runtime &rt, TurboModule &turboModule, const jsi::Value* args, size_t count) {${

@@ -172,3 +172,3 @@ isVoid

if (optional) {
condition = `count < ${index} || ${condition}`;
condition = `count <= ${index} || ${condition}`;
}

@@ -175,0 +175,0 @@ return `${condition} ? std::nullopt : std::make_optional(${expression})`;

@@ -108,3 +108,3 @@ /**

public abstract class ${className} extends ReactContextBaseJavaModule implements ReactModuleWithSpec, TurboModule {
public abstract class ${className} extends ReactContextBaseJavaModule implements TurboModule {
public static final String NAME = "${jsName}";

@@ -492,3 +492,2 @@

'com.facebook.react.bridge.ReactMethod',
'com.facebook.react.bridge.ReactModuleWithSpec',
'com.facebook.react.turbomodule.core.interfaces.TurboModule',

@@ -495,0 +494,0 @@ 'com.facebook.proguard.annotations.DoNotStrip',

@@ -283,2 +283,40 @@ /**

}
function throwIfConfigNotfound(foundConfigs) {
if (foundConfigs.length === 0) {
throw new Error('Could not find component config for native component');
}
}
function throwIfMoreThanOneConfig(foundConfigs) {
if (foundConfigs.length > 1) {
throw new Error('Only one component is supported per file');
}
}
function throwIfEventHasNoName(typeAnnotation, parser) {
const name =
parser.language() === 'Flow' ? typeAnnotation.id : typeAnnotation.typeName;
if (!name) {
throw new Error("typeAnnotation of event doesn't have a name");
}
}
function throwIfBubblingTypeIsNull(bubblingType, eventName) {
if (!bubblingType) {
throw new Error(
`Unable to determine event bubbling type for "${eventName}"`,
);
}
return bubblingType;
}
function throwIfArgumentPropsAreNull(argumentProps, eventName) {
if (!argumentProps) {
throw new Error(`Unable to determine event arguments for "${eventName}"`);
}
return argumentProps;
}
function throwIfTypeAliasIsNotInterface(typeAlias, parser) {
if (typeAlias.type !== parser.interfaceDeclaration) {
throw new Error(
`The type argument for codegenNativeCommands must be an interface, received ${typeAlias.type}`,
);
}
}
module.exports = {

@@ -302,2 +340,8 @@ throwIfModuleInterfaceIsMisnamed,

throwIfMoreThanOneCodegenNativecommands,
throwIfConfigNotfound,
throwIfMoreThanOneConfig,
throwIfEventHasNoName,
throwIfBubblingTypeIsNull,
throwIfArgumentPropsAreNull,
throwIfTypeAliasIsNotInterface,
};

@@ -87,2 +87,53 @@ /**

}>,
boolean_array_required: $ReadOnlyArray<boolean>,
boolean_array_optional_key?: boolean[],
boolean_array_optional_value: ?$ReadOnlyArray<boolean>,
boolean_array_optional_both?: ?boolean[],
string_array_required: $ReadOnlyArray<string>,
string_array_optional_key?: string[],
string_array_optional_value: ?$ReadOnlyArray<string>,
string_array_optional_both?: ?string[],
double_array_required: $ReadOnlyArray<Double>,
double_array_optional_key?: Double[],
double_array_optional_value: ?$ReadOnlyArray<Double>,
double_array_optional_both?: ?Double[],
float_array_required: $ReadOnlyArray<Float>,
float_array_optional_key?: Float[],
float_array_optional_value: ?$ReadOnlyArray<Float>,
float_array_optional_both?: ?Float[],
int32_array_required: $ReadOnlyArray<Int32>,
int32_array_optional_key?: Int32[],
int32_array_optional_value: ?$ReadOnlyArray<Int32>,
int32_array_optional_both?: ?Int32[],
enum_array_required: $ReadOnlyArray<('small' | 'large')>,
enum_array_optional_key?: ('small' | 'large')[],
enum_array_optional_value: ?$ReadOnlyArray<('small' | 'large')>,
enum_array_optional_both?: ?('small' | 'large')[],
object_array_required: $ReadOnlyArray<{
boolean_required: boolean,
}>,
object_array_optional_key?: {
string_optional_key?: string,
}[],
object_array_optional_value: ?$ReadOnlyArray<{
float_optional_value: ?Float,
}>,
object_array_optional_both?: ?{
int32_optional_both?: ?Int32,
}[],
int32_array_array_required: $ReadOnlyArray<$ReadOnlyArray<Int32>>,
int32_array_array_optional_key?: Int32[][],
int32_array_array_optional_value: ?$ReadOnlyArray<$ReadOnlyArray<Int32>>,
int32_array_array_optional_both?: ?Int32[][],
`;

@@ -89,0 +140,0 @@ const ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS = `

@@ -30,2 +30,3 @@ /**

types,
parser,
buildSchema,

@@ -57,3 +58,3 @@ ) {

)
.map(prop => buildSchema(prop, types))
.map(prop => buildSchema(prop, types, parser))
.filter(Boolean),

@@ -77,3 +78,3 @@ };

)
.map(prop => buildSchema(prop, types))
.map(prop => buildSchema(prop, types, parser))
.filter(Boolean),

@@ -214,2 +215,3 @@ },

types,
parser,
buildSchema,

@@ -229,2 +231,3 @@ ) {

types,
parser,
buildSchema,

@@ -244,3 +247,3 @@ ),

)
.map(prop => buildSchema(prop, types))
.map(prop => buildSchema(prop, types, parser))
.filter(Boolean),

@@ -458,5 +461,2 @@ };

}
// $FlowFixMe[unclear-type] there's no flowtype for ASTs
module.exports = {

@@ -463,0 +463,0 @@ getProperties,

@@ -13,2 +13,13 @@ /**

const _require = require('../../error-utils'),
throwIfEventHasNoName = _require.throwIfEventHasNoName,
throwIfBubblingTypeIsNull = _require.throwIfBubblingTypeIsNull,
throwIfArgumentPropsAreNull = _require.throwIfArgumentPropsAreNull;
const _require2 = require('../../parsers-commons'),
getEventArgument = _require2.getEventArgument;
const _require3 = require('../../parsers-primitives'),
emitBoolProp = _require3.emitBoolProp,
emitDoubleProp = _require3.emitDoubleProp,
emitFloatProp = _require3.emitFloatProp,
emitStringProp = _require3.emitStringProp;
function getPropertyType(

@@ -20,24 +31,10 @@ /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's

typeAnnotation,
parser,
) {
const type =
typeAnnotation.type === 'GenericTypeAnnotation'
? typeAnnotation.id.name
: typeAnnotation.type;
const type = extractTypeFromTypeAnnotation(typeAnnotation);
switch (type) {
case 'BooleanTypeAnnotation':
return {
name,
optional,
typeAnnotation: {
type: 'BooleanTypeAnnotation',
},
};
return emitBoolProp(name, optional);
case 'StringTypeAnnotation':
return {
name,
optional,
typeAnnotation: {
type: 'StringTypeAnnotation',
},
};
return emitStringProp(name, optional);
case 'Int32':

@@ -52,17 +49,5 @@ return {

case 'Double':
return {
name,
optional,
typeAnnotation: {
type: 'DoubleTypeAnnotation',
},
};
return emitDoubleProp(name, optional);
case 'Float':
return {
name,
optional,
typeAnnotation: {
type: 'FloatTypeAnnotation',
},
};
return emitFloatProp(name, optional);
case '$ReadOnly':

@@ -73,2 +58,3 @@ return getPropertyType(

typeAnnotation.typeParameters.params[0],
parser,
);

@@ -81,3 +67,5 @@ case 'ObjectTypeAnnotation':

type: 'ObjectTypeAnnotation',
properties: typeAnnotation.properties.map(buildPropertiesForEvent),
properties: typeAnnotation.properties.map(member =>
buildPropertiesForEvent(member, parser),
),
},

@@ -94,8 +82,101 @@ };

};
case 'UnsafeMixed':
return {
name,
optional,
typeAnnotation: {
type: 'MixedTypeAnnotation',
},
};
case 'ArrayTypeAnnotation':
case '$ReadOnlyArray':
return {
name,
optional,
typeAnnotation: extractArrayElementType(typeAnnotation, name, parser),
};
default:
type;
throw new Error(`Unable to determine event type for "${name}": ${type}`);
}
}
function extractArrayElementType(typeAnnotation, name, parser) {
const type = extractTypeFromTypeAnnotation(typeAnnotation);
switch (type) {
case 'BooleanTypeAnnotation':
return {
type: 'BooleanTypeAnnotation',
};
case 'StringTypeAnnotation':
return {
type: 'StringTypeAnnotation',
};
case 'Int32':
return {
type: 'Int32TypeAnnotation',
};
case 'Float':
return {
type: 'FloatTypeAnnotation',
};
case 'NumberTypeAnnotation':
case 'Double':
return {
type: 'DoubleTypeAnnotation',
};
case 'UnionTypeAnnotation':
return {
type: 'StringEnumTypeAnnotation',
options: typeAnnotation.types.map(option => option.value),
};
case 'UnsafeMixed':
return {
type: 'MixedTypeAnnotation',
};
case 'ObjectTypeAnnotation':
return {
type: 'ObjectTypeAnnotation',
properties: typeAnnotation.properties.map(member =>
buildPropertiesForEvent(member, parser),
),
};
case 'ArrayTypeAnnotation':
return {
type: 'ArrayTypeAnnotation',
elementType: extractArrayElementType(
typeAnnotation.elementType,
name,
parser,
),
};
case '$ReadOnlyArray':
const genericParams = typeAnnotation.typeParameters.params;
if (genericParams.length !== 1) {
throw new Error(
`Events only supports arrays with 1 Generic type. Found ${
genericParams.length
} types:\n${prettify(genericParams)}`,
);
}
return {
type: 'ArrayTypeAnnotation',
elementType: extractArrayElementType(genericParams[0], name, parser),
};
default:
throw new Error(
`Unrecognized ${type} for Array ${name} in events.\n${prettify(
typeAnnotation,
)}`,
);
}
}
function prettify(jsonObject) {
return JSON.stringify(jsonObject, null, 2);
}
function extractTypeFromTypeAnnotation(typeAnnotation) {
return typeAnnotation.type === 'GenericTypeAnnotation'
? typeAnnotation.id.name
: typeAnnotation.type;
}
function findEventArgumentsAndType(
parser,
typeAnnotation,

@@ -106,5 +187,3 @@ types,

) {
if (!typeAnnotation.id) {
throw new Error("typeAnnotation of event doesn't have a name");
}
throwIfEventHasNoName(typeAnnotation, parser);
const name = typeAnnotation.id.name;

@@ -125,3 +204,3 @@ if (name === '$ReadOnly') {

typeAnnotation.typeParameters.params[0].type ===
'NullLiteralTypeAnnotation'
parser.nullLiteralTypeAnnotation
) {

@@ -135,2 +214,3 @@ return {

return findEventArgumentsAndType(
parser,
typeAnnotation.typeParameters.params[0],

@@ -143,2 +223,3 @@ types,

return findEventArgumentsAndType(
parser,
types[name].right,

@@ -157,9 +238,10 @@ types,

}
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
function buildPropertiesForEvent(property) {
function buildPropertiesForEvent(
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
property,
parser,
) {
const name = property.key.name;
const optional =
property.value.type === 'NullableTypeAnnotation' || property.optional;
const optional = parser.isOptionalProperty(property);
let typeAnnotation =

@@ -169,14 +251,5 @@ property.value.type === 'NullableTypeAnnotation'

: property.value;
return getPropertyType(name, optional, typeAnnotation);
return getPropertyType(name, optional, typeAnnotation, parser);
}
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
function getEventArgument(argumentProps, name) {
return {
type: 'ObjectTypeAnnotation',
properties: argumentProps.map(buildPropertiesForEvent),
};
}
function buildEventSchema(types, property) {
function buildEventSchema(types, property, parser) {
const name = property.key.name;

@@ -197,2 +270,3 @@ const optional =

const _findEventArgumentsAn = findEventArgumentsAndType(
parser,
typeAnnotation,

@@ -205,31 +279,36 @@ types,

_findEventArgumentsAn.paperTopLevelNameDeprecated;
if (bubblingType && argumentProps) {
if (paperTopLevelNameDeprecated != null) {
return {
name,
optional,
bubblingType,
paperTopLevelNameDeprecated,
typeAnnotation: {
type: 'EventTypeAnnotation',
argument: getEventArgument(argumentProps, name),
},
};
}
const nonNullableArgumentProps = throwIfArgumentPropsAreNull(
argumentProps,
name,
);
const nonNullableBubblingType = throwIfBubblingTypeIsNull(bubblingType, name);
if (paperTopLevelNameDeprecated != null) {
return {
name,
optional,
bubblingType,
bubblingType: nonNullableBubblingType,
paperTopLevelNameDeprecated,
typeAnnotation: {
type: 'EventTypeAnnotation',
argument: getEventArgument(argumentProps, name),
argument: getEventArgument(
nonNullableArgumentProps,
buildPropertiesForEvent,
parser,
),
},
};
}
if (argumentProps === null) {
throw new Error(`Unable to determine event arguments for "${name}"`);
}
if (bubblingType === null) {
throw new Error(`Unable to determine event arguments for "${name}"`);
}
return {
name,
optional,
bubblingType: nonNullableBubblingType,
typeAnnotation: {
type: 'EventTypeAnnotation',
argument: getEventArgument(
nonNullableArgumentProps,
buildPropertiesForEvent,
parser,
),
},
};
}

@@ -239,6 +318,6 @@

function getEvents(eventTypeAST, types) {
function getEvents(eventTypeAST, types, parser) {
return eventTypeAST
.filter(property => property.type === 'ObjectTypeProperty')
.map(property => buildEventSchema(types, property))
.map(property => buildEventSchema(types, property, parser))
.filter(Boolean);

@@ -245,0 +324,0 @@ }

@@ -17,99 +17,29 @@ /**

getEvents = _require2.getEvents;
const _require3 = require('./extends'),
getExtendsProps = _require3.getExtendsProps,
removeKnownExtends = _require3.removeKnownExtends;
const _require4 = require('./props'),
getProps = _require4.getProps;
const _require5 = require('./componentsUtils.js'),
getProperties = _require5.getProperties;
const _require6 = require('../../error-utils'),
throwIfMoreThanOneCodegenNativecommands =
_require6.throwIfMoreThanOneCodegenNativecommands;
const _require7 = require('../../parsers-commons'),
createComponentConfig = _require7.createComponentConfig,
findNativeComponentType = _require7.findNativeComponentType,
getCommandOptions = _require7.getCommandOptions,
getOptions = _require7.getOptions;
// $FlowFixMe[signature-verification-failure] there's no flowtype for AST
function findComponentConfig(ast, parser) {
const foundConfigs = [];
const defaultExports = ast.body.filter(
node => node.type === 'ExportDefaultDeclaration',
);
defaultExports.forEach(statement => {
findNativeComponentType(statement, foundConfigs, parser);
});
if (foundConfigs.length === 0) {
throw new Error('Could not find component config for native component');
}
if (foundConfigs.length > 1) {
throw new Error('Only one component is supported per file');
}
const foundConfig = foundConfigs[0];
const namedExports = ast.body.filter(
node => node.type === 'ExportNamedDeclaration',
);
const commandsTypeNames = namedExports
.map(statement => {
let callExpression;
let calleeName;
try {
callExpression = statement.declaration.declarations[0].init;
calleeName = callExpression.callee.name;
} catch (e) {
return;
}
if (calleeName !== 'codegenNativeCommands') {
return;
}
// const statement.declaration.declarations[0].init
if (callExpression.arguments.length !== 1) {
throw new Error(
'codegenNativeCommands must be passed options including the supported commands',
);
}
const typeArgumentParam = callExpression.typeArguments.params[0];
if (typeArgumentParam.type !== 'GenericTypeAnnotation') {
throw new Error(
"codegenNativeCommands doesn't support inline definitions. Specify a file local type alias",
);
}
return {
commandTypeName: typeArgumentParam.id.name,
commandOptionsExpression: callExpression.arguments[0],
};
})
.filter(Boolean);
throwIfMoreThanOneCodegenNativecommands(commandsTypeNames);
return createComponentConfig(foundConfig, commandsTypeNames);
}
function getCommandProperties(
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
commandTypeName,
types,
commandOptions,
) {
const _require3 = require('./componentsUtils.js'),
getProperties = _require3.getProperties;
const _require4 = require('../../error-utils'),
throwIfTypeAliasIsNotInterface = _require4.throwIfTypeAliasIsNotInterface;
const _require5 = require('../../parsers-commons'),
propertyNames = _require5.propertyNames,
getCommandOptions = _require5.getCommandOptions,
getOptions = _require5.getOptions,
findComponentConfig = _require5.findComponentConfig;
function getCommandProperties(ast, parser) {
const _findComponentConfig = findComponentConfig(ast, parser),
commandTypeName = _findComponentConfig.commandTypeName,
commandOptionsExpression = _findComponentConfig.commandOptionsExpression;
if (commandTypeName == null) {
return [];
}
const types = parser.getTypes(ast);
const typeAlias = types[commandTypeName];
if (typeAlias.type !== 'InterfaceDeclaration') {
throwIfTypeAliasIsNotInterface(typeAlias, parser);
const properties = parser.bodyProperties(typeAlias);
if (!properties) {
throw new Error(
`The type argument for codegenNativeCommands must be an interface, received ${typeAlias.type}`,
);
}
let properties;
try {
properties = typeAlias.body.properties;
} catch (e) {
throw new Error(
`Failed to find type definition for "${commandTypeName}", please check that you have a valid codegen flow file`,
);
}
const flowPropertyNames = properties
.map(property => property && property.key && property.key.name)
.filter(Boolean);
const flowPropertyNames = propertyNames(properties);
const commandOptions = getCommandOptions(commandOptionsExpression);
if (commandOptions == null || commandOptions.supportedCommands == null) {

@@ -137,21 +67,14 @@ throw new Error(

function buildComponentSchema(ast, parser) {
const _findComponentConfig = findComponentConfig(ast, parser),
componentName = _findComponentConfig.componentName,
propsTypeName = _findComponentConfig.propsTypeName,
commandTypeName = _findComponentConfig.commandTypeName,
commandOptionsExpression = _findComponentConfig.commandOptionsExpression,
optionsExpression = _findComponentConfig.optionsExpression;
const _findComponentConfig2 = findComponentConfig(ast, parser),
componentName = _findComponentConfig2.componentName,
propsTypeName = _findComponentConfig2.propsTypeName,
optionsExpression = _findComponentConfig2.optionsExpression;
const types = parser.getTypes(ast);
const propProperties = getProperties(propsTypeName, types);
const commandOptions = getCommandOptions(commandOptionsExpression);
const commandProperties = getCommandProperties(
commandTypeName,
types,
commandOptions,
);
const extendsProps = getExtendsProps(propProperties, types);
const commandProperties = getCommandProperties(ast, parser);
const _parser$getProps = parser.getProps(propProperties, types),
extendsProps = _parser$getProps.extendsProps,
props = _parser$getProps.props;
const options = getOptions(optionsExpression);
const nonExtendsProps = removeKnownExtends(propProperties, types);
const props = getProps(nonExtendsProps, types);
const events = getEvents(propProperties, types);
const events = getEvents(propProperties, types, parser);
const commands = getCommands(commandProperties, types);

@@ -158,0 +81,0 @@ return {

@@ -81,29 +81,22 @@ /**

}
const _require = require('../utils'),
resolveTypeAnnotation = _require.resolveTypeAnnotation;
const _require2 = require('../../parsers-commons'),
unwrapNullable = _require2.unwrapNullable,
wrapNullable = _require2.wrapNullable,
const _require = require('../../parsers-commons'),
unwrapNullable = _require.unwrapNullable,
wrapNullable = _require.wrapNullable,
assertGenericTypeAnnotationHasExactlyOneTypeParameter =
_require2.assertGenericTypeAnnotationHasExactlyOneTypeParameter,
parseObjectProperty = _require2.parseObjectProperty;
const _require3 = require('../../parsers-primitives'),
emitArrayType = _require3.emitArrayType,
emitBoolean = _require3.emitBoolean,
emitFunction = _require3.emitFunction,
emitNumber = _require3.emitNumber,
emitGenericObject = _require3.emitGenericObject,
emitPromise = _require3.emitPromise,
emitRootTag = _require3.emitRootTag,
emitVoid = _require3.emitVoid,
emitString = _require3.emitString,
emitMixed = _require3.emitMixed,
emitUnion = _require3.emitUnion,
emitCommonTypes = _require3.emitCommonTypes,
typeAliasResolution = _require3.typeAliasResolution,
typeEnumResolution = _require3.typeEnumResolution;
const _require4 = require('../../errors'),
_require.assertGenericTypeAnnotationHasExactlyOneTypeParameter,
parseObjectProperty = _require.parseObjectProperty;
const _require2 = require('../../parsers-primitives'),
emitArrayType = _require2.emitArrayType,
emitFunction = _require2.emitFunction,
emitDictionary = _require2.emitDictionary,
emitPromise = _require2.emitPromise,
emitRootTag = _require2.emitRootTag,
emitUnion = _require2.emitUnion,
emitCommonTypes = _require2.emitCommonTypes,
typeAliasResolution = _require2.typeAliasResolution,
typeEnumResolution = _require2.typeEnumResolution;
const _require3 = require('../../errors'),
UnsupportedTypeAnnotationParserError =
_require4.UnsupportedTypeAnnotationParserError,
UnsupportedGenericParserError = _require4.UnsupportedGenericParserError;
_require3.UnsupportedTypeAnnotationParserError,
UnsupportedGenericParserError = _require3.UnsupportedGenericParserError;
function translateTypeAnnotation(

@@ -122,5 +115,7 @@ hasteModuleName,

) {
const _resolveTypeAnnotatio = resolveTypeAnnotation(
const resolveTypeAnnotationFN = parser.getResolveTypeAnnotationFN();
const _resolveTypeAnnotatio = resolveTypeAnnotationFN(
flowTypeAnnotation,
types,
parser,
),

@@ -220,3 +215,3 @@ nullable = _resolveTypeAnnotatio.nullable,

const propertyType = indexers[0].value;
translateTypeAnnotation(
const valueType = translateTypeAnnotation(
hasteModuleName,

@@ -232,3 +227,3 @@ propertyType,

// no need to do further checking
return emitGenericObject(nullable);
return emitDictionary(nullable, valueType);
}

@@ -265,14 +260,2 @@ }

}
case 'BooleanTypeAnnotation': {
return emitBoolean(nullable);
}
case 'NumberTypeAnnotation': {
return emitNumber(nullable);
}
case 'VoidTypeAnnotation': {
return emitVoid(nullable);
}
case 'StringTypeAnnotation': {
return emitString(nullable);
}
case 'FunctionTypeAnnotation': {

@@ -302,9 +285,2 @@ return emitFunction(

}
case 'MixedTypeAnnotation': {
if (cxxOnly) {
return emitMixed(nullable);
} else {
return emitGenericObject(nullable);
}
}
case 'EnumStringBody':

@@ -322,7 +298,21 @@ case 'EnumNumberBody': {

default: {
throw new UnsupportedTypeAnnotationParserError(
const commonType = emitCommonTypes(
hasteModuleName,
types,
typeAnnotation,
parser.language(),
aliasMap,
enumMap,
tryParse,
cxxOnly,
nullable,
parser,
);
if (!commonType) {
throw new UnsupportedTypeAnnotationParserError(
hasteModuleName,
typeAnnotation,
parser.language(),
);
}
return commonType;
}

@@ -329,0 +319,0 @@ }

@@ -8,4 +8,11 @@ /**

import type {Parser} from '../parser';
import type { Parser } from '../parser';
import type { SchemaType } from '../../CodegenSchema';
import type { ParserType } from '../errors';
export declare class FlowParser implements Parser{}
export declare class FlowParser implements Parser {
language(): ParserType;
parseFile(filename: string): SchemaType;
parseString(contents: string, filename?: string): SchemaType;
parseModuleFixture(filename: string): SchemaType;
}

@@ -41,19 +41,23 @@ /**

}
const _require = require('./modules'),
flowTranslateTypeAnnotation = _require.flowTranslateTypeAnnotation;
const invariant = require('invariant');
const _require = require('./components/componentsUtils'),
getSchemaInfo = _require.getSchemaInfo,
getTypeAnnotation = _require.getTypeAnnotation,
flattenProperties = _require.flattenProperties;
const _require2 = require('./modules'),
flowTranslateTypeAnnotation = _require2.flowTranslateTypeAnnotation;
// $FlowFixMe[untyped-import] there's no flowtype flow-parser
const flowParser = require('flow-parser');
const _require2 = require('../parsers-commons'),
buildSchema = _require2.buildSchema;
const _require3 = require('../parsers-primitives'),
Visitor = _require3.Visitor;
const _require4 = require('./components'),
buildComponentSchema = _require4.buildComponentSchema;
const _require5 = require('../schema.js'),
wrapComponentSchema = _require5.wrapComponentSchema;
const _require6 = require('../parsers-commons.js'),
buildModuleSchema = _require6.buildModuleSchema;
const _require7 = require('./utils'),
resolveTypeAnnotation = _require7.resolveTypeAnnotation;
const _require3 = require('../parsers-commons'),
buildSchema = _require3.buildSchema,
buildPropSchema = _require3.buildPropSchema;
const _require4 = require('../parsers-primitives'),
Visitor = _require4.Visitor;
const _require5 = require('./components'),
buildComponentSchema = _require5.buildComponentSchema;
const _require6 = require('../schema.js'),
wrapComponentSchema = _require6.wrapComponentSchema;
const _require7 = require('../parsers-commons.js'),
buildModuleSchema = _require7.buildModuleSchema;
const fs = require('fs');

@@ -70,2 +74,15 @@ const _require8 = require('../errors'),

);
_defineProperty(this, 'typeAlias', 'TypeAlias');
_defineProperty(this, 'enumDeclaration', 'EnumDeclaration');
_defineProperty(this, 'interfaceDeclaration', 'InterfaceDeclaration');
_defineProperty(
this,
'nullLiteralTypeAnnotation',
'NullLiteralTypeAnnotation',
);
_defineProperty(
this,
'undefinedLiteralTypeAnnotation',
'VoidLiteralTypeAnnotation',
);
}

@@ -90,3 +107,9 @@ isProperty(property) {

nameForGenericTypeAnnotation(typeAnnotation) {
return typeAnnotation.id.name;
var _typeAnnotation$id;
return typeAnnotation === null || typeAnnotation === void 0
? void 0
: (_typeAnnotation$id = typeAnnotation.id) === null ||
_typeAnnotation$id === void 0
? void 0
: _typeAnnotation$id.name;
}

@@ -122,3 +145,2 @@ checkIfInvalidModule(typeArguments) {

this,
resolveTypeAnnotation,
flowTranslateTypeAnnotation,

@@ -215,2 +237,5 @@ );

}
isGenericTypeAnnotation(type) {
return type === 'GenericTypeAnnotation';
}
extractAnnotatedElement(typeAnnotation, types) {

@@ -308,2 +333,128 @@ return types[typeAnnotation.typeParameters.params[0].id.name];

}
bodyProperties(typeAlias) {
return typeAlias.body.properties;
}
convertKeywordToTypeAnnotation(keyword) {
return keyword;
}
argumentForProp(prop) {
return prop.argument;
}
nameForArgument(prop) {
return prop.argument.id.name;
}
isOptionalProperty(property) {
return (
property.value.type === 'NullableTypeAnnotation' || property.optional
);
}
getGetSchemaInfoFN() {
return getSchemaInfo;
}
getGetTypeAnnotationFN() {
return getTypeAnnotation;
}
getResolvedTypeAnnotation(typeAnnotation, types, parser) {
invariant(
typeAnnotation != null,
'resolveTypeAnnotation(): typeAnnotation cannot be null',
);
let node = typeAnnotation;
let nullable = false;
let typeResolutionStatus = {
successful: false,
};
for (;;) {
if (node.type === 'NullableTypeAnnotation') {
nullable = true;
node = node.typeAnnotation;
continue;
}
if (node.type !== 'GenericTypeAnnotation') {
break;
}
const resolvedTypeAnnotation = types[node.id.name];
if (resolvedTypeAnnotation == null) {
break;
}
switch (resolvedTypeAnnotation.type) {
case parser.typeAlias: {
typeResolutionStatus = {
successful: true,
type: 'alias',
name: node.id.name,
};
node = resolvedTypeAnnotation.right;
break;
}
case parser.enumDeclaration: {
typeResolutionStatus = {
successful: true,
type: 'enum',
name: node.id.name,
};
node = resolvedTypeAnnotation.body;
break;
}
default: {
throw new TypeError(
`A non GenericTypeAnnotation must be a type declaration ('${parser.typeAlias}') or enum ('${parser.enumDeclaration}'). Instead, got the unsupported ${resolvedTypeAnnotation.type}.`,
);
}
}
}
return {
nullable: nullable,
typeAnnotation: node,
typeResolutionStatus,
};
}
getResolveTypeAnnotationFN() {
return (typeAnnotation, types, parser) =>
this.getResolvedTypeAnnotation(typeAnnotation, types, parser);
}
extendsForProp(prop, types, parser) {
const argument = this.argumentForProp(prop);
if (!argument) {
console.log('null', prop);
}
const name = parser.nameForArgument(prop);
if (types[name] != null) {
// This type is locally defined in the file
return null;
}
switch (name) {
case 'ViewProps':
return {
type: 'ReactNativeBuiltInType',
knownTypeName: 'ReactNativeCoreViewProps',
};
default: {
throw new Error(`Unable to handle prop spread: ${name}`);
}
}
}
removeKnownExtends(typeDefinition, types) {
return typeDefinition.filter(
prop =>
prop.type !== 'ObjectTypeSpreadProperty' ||
this.extendsForProp(prop, types, this) === null,
);
}
getExtendsProps(typeDefinition, types) {
return typeDefinition
.filter(prop => prop.type === 'ObjectTypeSpreadProperty')
.map(prop => this.extendsForProp(prop, types, this))
.filter(Boolean);
}
getProps(typeDefinition, types) {
const nonExtendsProps = this.removeKnownExtends(typeDefinition, types);
const props = flattenProperties(nonExtendsProps, types)
.map(property => buildPropSchema(property, types, this))
.filter(Boolean);
return {
props,
extendsProps: this.getExtendsProps(typeDefinition, types),
};
}
}

@@ -310,0 +461,0 @@ module.exports = {

@@ -13,64 +13,2 @@ /**

// $FlowFixMe[unclear-type] there's no flowtype for ASTs
const invariant = require('invariant');
function resolveTypeAnnotation(
// TODO(T71778680): This is an Flow TypeAnnotation. Flow-type this
typeAnnotation,
types,
) {
invariant(
typeAnnotation != null,
'resolveTypeAnnotation(): typeAnnotation cannot be null',
);
let node = typeAnnotation;
let nullable = false;
let typeResolutionStatus = {
successful: false,
};
for (;;) {
if (node.type === 'NullableTypeAnnotation') {
nullable = true;
node = node.typeAnnotation;
continue;
}
if (node.type !== 'GenericTypeAnnotation') {
break;
}
const resolvedTypeAnnotation = types[node.id.name];
if (resolvedTypeAnnotation == null) {
break;
}
switch (resolvedTypeAnnotation.type) {
case 'TypeAlias': {
typeResolutionStatus = {
successful: true,
type: 'alias',
name: node.id.name,
};
node = resolvedTypeAnnotation.right;
break;
}
case 'EnumDeclaration': {
typeResolutionStatus = {
successful: true,
type: 'enum',
name: node.id.name,
};
node = resolvedTypeAnnotation.body;
break;
}
default: {
throw new TypeError(
`A non GenericTypeAnnotation must be a type declaration ('TypeAlias') or enum ('EnumDeclaration'). Instead, got the unsupported ${resolvedTypeAnnotation.type}.`,
);
}
}
}
return {
nullable: nullable,
typeAnnotation: node,
typeResolutionStatus,
};
}
function getValueFromTypes(value, types) {

@@ -84,3 +22,2 @@ if (value.type === 'GenericTypeAnnotation' && types[value.id.name]) {

getValueFromTypes,
resolveTypeAnnotation,
};

@@ -41,7 +41,13 @@ /**

}
import invariant from 'invariant';
const _require = require('./typescript/components/componentsUtils'),
flattenProperties = _require.flattenProperties;
const _require2 = require('./parsers-commons'),
buildPropSchema = _require2.buildPropSchema;
// $FlowFixMe[untyped-import] there's no flowtype flow-parser
const flowParser = require('flow-parser');
const _require = require('./errors'),
const _require3 = require('./errors'),
UnsupportedObjectPropertyTypeAnnotationParserError =
_require.UnsupportedObjectPropertyTypeAnnotationParserError;
_require3.UnsupportedObjectPropertyTypeAnnotationParserError;
const schemaMock = {

@@ -69,2 +75,15 @@ modules: {

);
_defineProperty(this, 'typeAlias', 'TypeAlias');
_defineProperty(this, 'enumDeclaration', 'EnumDeclaration');
_defineProperty(this, 'interfaceDeclaration', 'InterfaceDeclaration');
_defineProperty(
this,
'nullLiteralTypeAnnotation',
'NullLiteralTypeAnnotation',
);
_defineProperty(
this,
'undefinedLiteralTypeAnnotation',
'VoidLiteralTypeAnnotation',
);
}

@@ -163,2 +182,5 @@ isProperty(property) {

}
isGenericTypeAnnotation(type) {
return true;
}
extractAnnotatedElement(typeAnnotation, types) {

@@ -214,2 +236,143 @@ return types[typeAnnotation.typeParameters.params[0].id.name];

}
bodyProperties(typeAlias) {
return typeAlias.body.properties;
}
convertKeywordToTypeAnnotation(keyword) {
return keyword;
}
argumentForProp(prop) {
return prop.expression;
}
nameForArgument(prop) {
return prop.expression.name;
}
isOptionalProperty(property) {
return property.optional || false;
}
getGetTypeAnnotationFN() {
return () => {
return {};
};
}
getGetSchemaInfoFN() {
return () => {
return {
name: 'MockedSchema',
optional: false,
typeAnnotation: 'BooleanTypeAnnotation',
defaultValue: false,
withNullDefault: false,
};
};
}
getResolveTypeAnnotationFN() {
return () => {
return {
nullable: false,
typeAnnotation: null,
typeResolutionStatus: {
successful: false,
},
};
};
}
getResolvedTypeAnnotation(typeAnnotation, types) {
invariant(
typeAnnotation != null,
'resolveTypeAnnotation(): typeAnnotation cannot be null',
);
let node = typeAnnotation;
let nullable = false;
let typeResolutionStatus = {
successful: false,
};
for (;;) {
if (node.type === 'NullableTypeAnnotation') {
nullable = true;
node = node.typeAnnotation;
continue;
}
if (node.type !== 'GenericTypeAnnotation') {
break;
}
const resolvedTypeAnnotation = types[node.id.name];
if (resolvedTypeAnnotation == null) {
break;
}
switch (resolvedTypeAnnotation.type) {
case 'TypeAlias': {
typeResolutionStatus = {
successful: true,
type: 'alias',
name: node.id.name,
};
node = resolvedTypeAnnotation.right;
break;
}
case 'EnumDeclaration': {
typeResolutionStatus = {
successful: true,
type: 'enum',
name: node.id.name,
};
node = resolvedTypeAnnotation.body;
break;
}
default: {
throw new TypeError(
`A non GenericTypeAnnotation must be a type declaration ('TypeAlias') or enum ('EnumDeclaration'). Instead, got the unsupported ${resolvedTypeAnnotation.type}.`,
);
}
}
}
return {
nullable: nullable,
typeAnnotation: node,
typeResolutionStatus,
};
}
getExtendsProps(typeDefinition, types) {
return typeDefinition
.filter(prop => prop.type === 'ObjectTypeSpreadProperty')
.map(prop => this.extendsForProp(prop, types, this))
.filter(Boolean);
}
extendsForProp(prop, types, parser) {
const argument = this.argumentForProp(prop);
if (!argument) {
console.log('null', prop);
}
const name = parser.nameForArgument(prop);
if (types[name] != null) {
// This type is locally defined in the file
return null;
}
switch (name) {
case 'ViewProps':
return {
type: 'ReactNativeBuiltInType',
knownTypeName: 'ReactNativeCoreViewProps',
};
default: {
throw new Error(`Unable to handle prop spread: ${name}`);
}
}
}
removeKnownExtends(typeDefinition, types) {
return typeDefinition.filter(
prop =>
prop.type !== 'ObjectTypeSpreadProperty' ||
this.extendsForProp(prop, types, this) === null,
);
}
getProps(typeDefinition, types) {
const nonExtendsProps = this.removeKnownExtends(typeDefinition, types);
const props = flattenProperties(nonExtendsProps, types)
.map(property => buildPropSchema(property, types, this))
.filter(Boolean);
return {
props,
extendsProps: this.getExtendsProps(typeDefinition, types),
};
}
}

@@ -172,3 +172,7 @@ /**

_require2.throwIfMoreThanOneModuleInterfaceParserError,
throwIfModuleInterfaceIsMisnamed = _require2.throwIfModuleInterfaceIsMisnamed;
throwIfModuleInterfaceIsMisnamed = _require2.throwIfModuleInterfaceIsMisnamed,
throwIfMoreThanOneCodegenNativecommands =
_require2.throwIfMoreThanOneCodegenNativecommands,
throwIfConfigNotfound = _require2.throwIfConfigNotfound,
throwIfMoreThanOneConfig = _require2.throwIfMoreThanOneConfig;
const _require3 = require('./errors'),

@@ -399,3 +403,2 @@ MissingTypeParameterGenericParserError =

cxxOnly,
resolveTypeAnnotation,
translateTypeAnnotation,

@@ -414,3 +417,4 @@ parser,

}
var _resolveTypeAnnotatio = resolveTypeAnnotation(value, types);
const resolveTypeAnnotationFN = parser.getResolveTypeAnnotationFN();
var _resolveTypeAnnotatio = resolveTypeAnnotationFN(value, types, parser);
nullable = _resolveTypeAnnotatio.nullable;

@@ -452,3 +456,2 @@ value = _resolveTypeAnnotatio.typeAnnotation;

parser,
resolveTypeAnnotation,
translateTypeAnnotation,

@@ -475,3 +478,2 @@ ) {

parser,
resolveTypeAnnotation,
translateTypeAnnotation,

@@ -511,3 +513,2 @@ ),

parser,
resolveTypeAnnotation,
translateTypeAnnotation,

@@ -534,3 +535,2 @@ ) {

parser,
resolveTypeAnnotation,
translateTypeAnnotation,

@@ -610,3 +610,2 @@ );

parser,
resolveTypeAnnotation,
translateTypeAnnotation,

@@ -669,3 +668,2 @@ ) => {

cxxOnly,
resolveTypeAnnotation,
translateTypeAnnotation,

@@ -799,2 +797,117 @@ parser,

}
function getCommandTypeNameAndOptionsExpression(namedExport, parser) {
let callExpression;
let calleeName;
try {
callExpression = namedExport.declaration.declarations[0].init;
calleeName = callExpression.callee.name;
} catch (e) {
return;
}
if (calleeName !== 'codegenNativeCommands') {
return;
}
if (callExpression.arguments.length !== 1) {
throw new Error(
'codegenNativeCommands must be passed options including the supported commands',
);
}
const typeArgumentParam =
parser.getTypeArgumentParamsFromDeclaration(callExpression)[0];
if (!parser.isGenericTypeAnnotation(typeArgumentParam.type)) {
throw new Error(
"codegenNativeCommands doesn't support inline definitions. Specify a file local type alias",
);
}
return {
commandTypeName: parser.nameForGenericTypeAnnotation(typeArgumentParam),
commandOptionsExpression: callExpression.arguments[0],
};
}
function propertyNames(properties) {
return properties
.map(property => property && property.key && property.key.name)
.filter(Boolean);
}
function extendsForProp(prop, types, parser) {
const argument = parser.argumentForProp(prop);
if (!argument) {
console.log('null', prop);
}
const name = parser.nameForArgument(prop);
if (types[name] != null) {
// This type is locally defined in the file
return null;
}
switch (name) {
case 'ViewProps':
return {
type: 'ReactNativeBuiltInType',
knownTypeName: 'ReactNativeCoreViewProps',
};
default: {
throw new Error(`Unable to handle prop spread: ${name}`);
}
}
}
function buildPropSchema(property, types, parser) {
const getSchemaInfoFN = parser.getGetSchemaInfoFN();
const info = getSchemaInfoFN(property, types);
if (info == null) {
return null;
}
const name = info.name,
optional = info.optional,
typeAnnotation = info.typeAnnotation,
defaultValue = info.defaultValue,
withNullDefault = info.withNullDefault;
const getTypeAnnotationFN = parser.getGetTypeAnnotationFN();
return {
name,
optional,
typeAnnotation: getTypeAnnotationFN(
name,
typeAnnotation,
defaultValue,
withNullDefault,
types,
parser,
buildPropSchema,
),
};
}
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
function getEventArgument(argumentProps, buildPropertiesForEvent, parser) {
return {
type: 'ObjectTypeAnnotation',
properties: argumentProps.map(member =>
buildPropertiesForEvent(member, parser),
),
};
}
/* $FlowFixMe[signature-verification-failure] there's no flowtype for AST.
* TODO(T108222691): Use flow-types for @babel/parser */
function findComponentConfig(ast, parser) {
const foundConfigs = [];
const defaultExports = ast.body.filter(
node => node.type === 'ExportDefaultDeclaration',
);
defaultExports.forEach(statement => {
findNativeComponentType(statement, foundConfigs, parser);
});
throwIfConfigNotfound(foundConfigs);
throwIfMoreThanOneConfig(foundConfigs);
const foundConfig = foundConfigs[0];
const namedExports = ast.body.filter(
node => node.type === 'ExportNamedDeclaration',
);
const commandsTypeNames = namedExports
.map(statement => getCommandTypeNameAndOptionsExpression(statement, parser))
.filter(Boolean);
throwIfMoreThanOneCodegenNativecommands(commandsTypeNames);
return createComponentConfig(foundConfig, commandsTypeNames);
}
module.exports = {

@@ -815,4 +928,10 @@ wrapModuleSchema,

findNativeComponentType,
propertyNames,
getCommandOptions,
getOptions,
getCommandTypeNameAndOptionsExpression,
extendsForProp,
buildPropSchema,
getEventArgument,
findComponentConfig,
};

@@ -129,2 +129,11 @@ /**

}
function emitDoubleProp(name, optional) {
return {
name,
optional,
typeAnnotation: {
type: 'DoubleTypeAnnotation',
},
};
}
function emitVoid(nullable) {

@@ -175,2 +184,11 @@ return wrapNullable(nullable, {

}
function emitStringProp(name, optional) {
return {
name,
optional,
typeAnnotation: {
type: 'StringTypeAnnotation',
},
};
}
function typeAliasResolution(

@@ -320,2 +338,8 @@ typeResolution,

}
function emitDictionary(nullable, valueType) {
return wrapNullable(nullable, {
type: 'GenericObjectTypeAnnotation',
dictionaryValueType: valueType,
});
}
function emitObject(nullable, properties) {

@@ -332,2 +356,11 @@ return wrapNullable(nullable, {

}
function emitFloatProp(name, optional) {
return {
name,
optional,
typeAnnotation: {
type: 'FloatTypeAnnotation',
},
};
}
function emitUnion(nullable, hasteModuleName, typeAnnotation, parser) {

@@ -469,2 +502,3 @@ const unionTypes = parser.remapUnionTypeAnnotationMemberNames(

function emitPartial(
nullable,
hasteModuleName,

@@ -477,3 +511,2 @@ typeAnnotation,

cxxOnly,
nullable,
parser,

@@ -511,45 +544,59 @@ ) {

) {
const typeMap = {
Stringish: emitStringish,
Int32: emitInt32,
Double: emitDouble,
Float: emitFloat,
UnsafeObject: emitGenericObject,
Object: emitGenericObject,
$Partial: emitPartial,
Partial: emitPartial,
BooleanTypeAnnotation: emitBoolean,
NumberTypeAnnotation: emitNumber,
VoidTypeAnnotation: emitVoid,
StringTypeAnnotation: emitString,
MixedTypeAnnotation: cxxOnly ? emitMixed : emitGenericObject,
};
const typeAnnotationName = parser.convertKeywordToTypeAnnotation(
typeAnnotation.type,
);
const simpleEmitter = typeMap[typeAnnotationName];
if (simpleEmitter) {
return simpleEmitter(nullable);
}
const genericTypeAnnotationName =
parser.nameForGenericTypeAnnotation(typeAnnotation);
switch (genericTypeAnnotationName) {
case 'Stringish': {
return emitStringish(nullable);
}
case 'Int32': {
return emitInt32(nullable);
}
case 'Double': {
return emitDouble(nullable);
}
case 'Float': {
return emitFloat(nullable);
}
case 'UnsafeObject':
case 'Object': {
return emitGenericObject(nullable);
}
case '$Partial':
case 'Partial': {
return emitPartial(
hasteModuleName,
typeAnnotation,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
nullable,
parser,
);
}
default: {
return null;
}
const emitter = typeMap[genericTypeAnnotationName];
if (!emitter) {
return null;
}
return emitter(
nullable,
hasteModuleName,
typeAnnotation,
types,
aliasMap,
enumMap,
tryParse,
cxxOnly,
parser,
);
}
function emitBoolProp(name, optional) {
return {
name,
optional,
typeAnnotation: {
type: 'BooleanTypeAnnotation',
},
};
}
module.exports = {
emitArrayType,
emitBoolean,
emitBoolProp,
emitDouble,
emitDoubleProp,
emitFloat,
emitFloatProp,
emitFunction,

@@ -559,2 +606,3 @@ emitInt32,

emitGenericObject,
emitDictionary,
emitObject,

@@ -566,2 +614,3 @@ emitPromise,

emitStringish,
emitStringProp,
emitMixed,

@@ -568,0 +617,0 @@ emitUnion,

@@ -87,2 +87,53 @@ /**

}> | null | undefined;
boolean_array_required: boolean[];
boolean_array_optional_key?: boolean[];
boolean_array_optional_value: boolean[] | null | undefined;
boolean_array_optional_both?: boolean[] | null | undefined;
string_array_required: string[];
string_array_optional_key?: (string[]);
string_array_optional_value: (string[]) | null | undefined;
string_array_optional_both?: (string[] | null | undefined);
double_array_required: Double[];
double_array_optional_key?: Double[];
double_array_optional_value: Double[] | null | undefined;
double_array_optional_both?: Double[] | null | undefined;
float_array_required: Float[];
float_array_optional_key?: Float[];
float_array_optional_value: Float[] | null | undefined;
float_array_optional_both?: Float[] | null | undefined;
int32_array_required: Int32[];
int32_array_optional_key?: Int32[];
int32_array_optional_value: Int32[] | null | undefined;
int32_array_optional_both?: Int32[] | null | undefined;
enum_array_required: ('small' | 'large')[];
enum_array_optional_key?: ('small' | 'large')[];
enum_array_optional_value: ('small' | 'large')[] | null | undefined;
enum_array_optional_both?: ('small' | 'large')[] | null | undefined;
object_array_required: {
boolean_required: boolean;
}[];
object_array_optional_key?: {
string_optional_key?: string;
}[];
object_array_optional_value: {
float_optional_value: Float | null | undefined;
}[] | null | undefined;
object_array_optional_both?: {
int32_optional_both?: Int32 | null | undefined;
}[] | null | undefined;
int32_array_array_required: Int32[][];
int32_array_array_optional_key?: Int32[][];
int32_array_array_optional_value: Int32[][] | null | undefined;
int32_array_array_optional_both?: Int32[][] | null | undefined;
`;

@@ -89,0 +140,0 @@ const ONE_OF_EACH_PROP_EVENT_DEFAULT_AND_OPTIONS = `

@@ -112,2 +112,3 @@ /**

types,
parser,
buildSchema,

@@ -128,2 +129,3 @@ ) {

types,
parser,
buildSchema,

@@ -143,2 +145,3 @@ ),

types,
parser,
buildSchema,

@@ -162,2 +165,3 @@ ),

types,
parser,
buildSchema,

@@ -169,6 +173,6 @@ ),

}
function buildObjectType(rawProperties, types, buildSchema) {
function buildObjectType(rawProperties, types, parser, buildSchema) {
const flattenedProperties = flattenProperties(rawProperties, types);
const properties = flattenedProperties
.map(prop => buildSchema(prop, types))
.map(prop => buildSchema(prop, types, parser))
.filter(Boolean);

@@ -187,2 +191,3 @@ return {

types,
parser,
buildSchema,

@@ -192,5 +197,10 @@ ) {

case 'TSTypeLiteral':
return buildObjectType(typeAnnotation.members, types, buildSchema);
return buildObjectType(
typeAnnotation.members,
types,
parser,
buildSchema,
);
case 'TSInterfaceDeclaration':
return buildObjectType([typeAnnotation], types, buildSchema);
return buildObjectType([typeAnnotation], types, parser, buildSchema);
case 'TSIntersectionType':

@@ -200,2 +210,3 @@ return buildObjectType(

types,
parser,
buildSchema,

@@ -276,2 +287,3 @@ );

types,
parser,
buildSchema,

@@ -298,2 +310,3 @@ ) {

types,
parser,
buildSchema,

@@ -328,2 +341,3 @@ );

types,
parser,
buildSchema,

@@ -362,3 +376,12 @@ );

}
function getTypeAnnotation(name, annotation, defaultValue, types, buildSchema) {
function getTypeAnnotation(
name,
annotation,
defaultValue,
withNullDefault,
// Just to make `getTypeAnnotation` signature match with the one from Flow
types,
parser,
buildSchema,
) {
// unpack WithDefault, (T) or T|U

@@ -372,2 +395,3 @@ const topLevelType = parseTopLevelType(annotation, types);

types,
parser,
buildSchema,

@@ -390,2 +414,3 @@ );

types,
parser,
buildSchema,

@@ -436,7 +461,6 @@ );

defaultValue: topLevelType.defaultValue,
withNullDefault: false, // Just to make `getTypeAnnotation` signature match with the one from Flow
};
}
// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser
function verifyPropNotAlreadyDefined(props, needleProp) {

@@ -443,0 +467,0 @@ const propName = needleProp.key.name;

@@ -17,2 +17,13 @@ /**

parseTopLevelType = _require2.parseTopLevelType;
const _require3 = require('../../error-utils'),
throwIfEventHasNoName = _require3.throwIfEventHasNoName,
throwIfBubblingTypeIsNull = _require3.throwIfBubblingTypeIsNull,
throwIfArgumentPropsAreNull = _require3.throwIfArgumentPropsAreNull;
const _require4 = require('../../parsers-commons'),
getEventArgument = _require4.getEventArgument;
const _require5 = require('../../parsers-primitives'),
emitBoolProp = _require5.emitBoolProp,
emitDoubleProp = _require5.emitDoubleProp,
emitFloatProp = _require5.emitFloatProp,
emitStringProp = _require5.emitStringProp;
function getPropertyType(

@@ -26,2 +37,3 @@ /* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's

annotation,
parser,
) {

@@ -37,17 +49,5 @@ const topLevelType = parseTopLevelType(annotation);

case 'TSBooleanKeyword':
return {
name,
optional,
typeAnnotation: {
type: 'BooleanTypeAnnotation',
},
};
return emitBoolProp(name, optional);
case 'TSStringKeyword':
return {
name,
optional,
typeAnnotation: {
type: 'StringTypeAnnotation',
},
};
return emitStringProp(name, optional);
case 'Int32':

@@ -62,2 +62,6 @@ return {

case 'Double':
return emitDoubleProp(name, optional);
case 'Float':
return emitFloatProp(name, optional);
case 'TSTypeLiteral':
return {

@@ -67,6 +71,9 @@ name,

typeAnnotation: {
type: 'DoubleTypeAnnotation',
type: 'ObjectTypeAnnotation',
properties: typeAnnotation.members.map(member =>
buildPropertiesForEvent(member, parser),
),
},
};
case 'Float':
case 'TSUnionType':
return {

@@ -76,6 +83,7 @@ name,

typeAnnotation: {
type: 'FloatTypeAnnotation',
type: 'StringEnumTypeAnnotation',
options: typeAnnotation.types.map(option => option.literal.value),
},
};
case 'TSTypeLiteral':
case 'UnsafeMixed':
return {

@@ -85,14 +93,10 @@ name,

typeAnnotation: {
type: 'ObjectTypeAnnotation',
properties: typeAnnotation.members.map(buildPropertiesForEvent),
type: 'MixedTypeAnnotation',
},
};
case 'TSUnionType':
case 'TSArrayType':
return {
name,
optional,
typeAnnotation: {
type: 'StringEnumTypeAnnotation',
options: typeAnnotation.types.map(option => option.literal.value),
},
typeAnnotation: extractArrayElementType(typeAnnotation, name, parser),
};

@@ -104,3 +108,70 @@ default:

}
function extractArrayElementType(typeAnnotation, name, parser) {
const type = extractTypeFromTypeAnnotation(typeAnnotation);
switch (type) {
case 'TSParenthesizedType':
return extractArrayElementType(
typeAnnotation.typeAnnotation,
name,
parser,
);
case 'TSBooleanKeyword':
return {
type: 'BooleanTypeAnnotation',
};
case 'TSStringKeyword':
return {
type: 'StringTypeAnnotation',
};
case 'Float':
return {
type: 'FloatTypeAnnotation',
};
case 'Int32':
return {
type: 'Int32TypeAnnotation',
};
case 'TSNumberKeyword':
case 'Double':
return {
type: 'DoubleTypeAnnotation',
};
case 'TSUnionType':
return {
type: 'StringEnumTypeAnnotation',
options: typeAnnotation.types.map(option => option.literal.value),
};
case 'TSTypeLiteral':
return {
type: 'ObjectTypeAnnotation',
properties: typeAnnotation.members.map(member =>
buildPropertiesForEvent(member, parser),
),
};
case 'TSArrayType':
return {
type: 'ArrayTypeAnnotation',
elementType: extractArrayElementType(
typeAnnotation.elementType,
name,
parser,
),
};
default:
throw new Error(
`Unrecognized ${type} for Array ${name} in events.\n${JSON.stringify(
typeAnnotation,
null,
2,
)}`,
);
}
}
function extractTypeFromTypeAnnotation(typeAnnotation) {
return typeAnnotation.type === 'TSTypeReference'
? typeAnnotation.typeName.name
: typeAnnotation.type;
}
function findEventArgumentsAndType(
parser,
typeAnnotation,

@@ -125,8 +196,7 @@ types,

}
if (!typeAnnotation.typeName) {
throw new Error("typeAnnotation of event doesn't have a name");
}
throwIfEventHasNoName(typeAnnotation, parser);
const name = typeAnnotation.typeName.name;
if (name === 'Readonly') {
return findEventArgumentsAndType(
parser,
typeAnnotation.typeParameters.params[0],

@@ -144,4 +214,4 @@ types,

switch (typeAnnotation.typeParameters.params[0].type) {
case 'TSNullKeyword':
case 'TSUndefinedKeyword':
case parser.nullLiteralTypeAnnotation:
case parser.undefinedLiteralTypeAnnotation:
return {

@@ -154,2 +224,3 @@ argumentProps: [],

return findEventArgumentsAndType(
parser,
typeAnnotation.typeParameters.params[0],

@@ -167,2 +238,3 @@ types,

return findEventArgumentsAndType(
parser,
elementType,

@@ -181,24 +253,17 @@ types,

}
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
function buildPropertiesForEvent(property) {
function buildPropertiesForEvent(
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
property,
parser,
) {
const name = property.key.name;
const optional = property.optional || false;
const optional = parser.isOptionalProperty(property);
let typeAnnotation = property.typeAnnotation.typeAnnotation;
return getPropertyType(name, optional, typeAnnotation);
return getPropertyType(name, optional, typeAnnotation, parser);
}
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
function getEventArgument(argumentProps, name) {
return {
type: 'ObjectTypeAnnotation',
properties: argumentProps.map(buildPropertiesForEvent),
};
}
// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser
function buildEventSchema(types, property) {
function buildEventSchema(types, property, parser) {
// unpack WithDefault, (T) or T|U

@@ -213,2 +278,3 @@ const topLevelType = parseTopLevelType(

const _findEventArgumentsAn = findEventArgumentsAndType(
parser,
typeAnnotation,

@@ -221,32 +287,41 @@ types,

_findEventArgumentsAn.paperTopLevelNameDeprecated;
if (!argumentProps) {
throw new Error(`Unable to determine event arguments for "${name}"`);
} else if (!bubblingType) {
throw new Error(`Unable to determine event bubbling type for "${name}"`);
} else {
if (paperTopLevelNameDeprecated != null) {
return {
name,
optional,
bubblingType,
paperTopLevelNameDeprecated,
typeAnnotation: {
type: 'EventTypeAnnotation',
argument: getEventArgument(argumentProps, name),
},
};
}
const nonNullableArgumentProps = throwIfArgumentPropsAreNull(
argumentProps,
name,
);
const nonNullableBubblingType = throwIfBubblingTypeIsNull(bubblingType, name);
if (paperTopLevelNameDeprecated != null) {
return {
name,
optional,
bubblingType,
bubblingType: nonNullableBubblingType,
paperTopLevelNameDeprecated,
typeAnnotation: {
type: 'EventTypeAnnotation',
argument: getEventArgument(argumentProps, name),
argument: getEventArgument(
nonNullableArgumentProps,
buildPropertiesForEvent,
parser,
),
},
};
}
return {
name,
optional,
bubblingType: nonNullableBubblingType,
typeAnnotation: {
type: 'EventTypeAnnotation',
argument: getEventArgument(
nonNullableArgumentProps,
buildPropertiesForEvent,
parser,
),
},
};
}
function getEvents(eventTypeAST, types) {
return eventTypeAST.map(property => buildEventSchema(types, property));
function getEvents(eventTypeAST, types, parser) {
return eventTypeAST
.map(property => buildEventSchema(types, property, parser))
.filter(Boolean);
}

@@ -253,0 +328,0 @@ module.exports = {

@@ -15,24 +15,2 @@ /**

parseTopLevelType = _require.parseTopLevelType;
const _require2 = require('./componentsUtils.js'),
flattenProperties = _require2.flattenProperties;
function extendsForProp(prop, types) {
if (!prop.expression) {
console.log('null', prop);
}
const name = prop.expression.name;
if (types[name] != null) {
// This type is locally defined in the file
return null;
}
switch (name) {
case 'ViewProps':
return {
type: 'ReactNativeBuiltInType',
knownTypeName: 'ReactNativeCoreViewProps',
};
default: {
throw new Error(`Unable to handle prop spread: ${name}`);
}
}
}
function isEvent(typeAnnotation) {

@@ -45,31 +23,8 @@ if (typeAnnotation.type !== 'TSTypeReference') {

}
function isProp(name, typeAnnotation) {
if (typeAnnotation.type !== 'TSTypeReference') {
return true;
}
const isStyle =
name === 'style' &&
typeAnnotation.type === 'GenericTypeAnnotation' &&
typeAnnotation.typeName.name === 'ViewStyleProp';
return !isStyle;
}
// $FlowFixMe[unclear-type] TODO(T108222691): Use flow-types for @babel/parser
function categorizeProps(typeDefinition, types, extendsProps, props, events) {
const remaining = [];
function categorizeProps(typeDefinition, types, events) {
// find events
for (const prop of typeDefinition) {
// find extends
if (prop.type === 'TSExpressionWithTypeArguments') {
const extend = extendsForProp(prop, types);
if (extend) {
extendsProps.push(extend);
continue;
}
}
remaining.push(prop);
}
// find events and props
for (const prop of flattenProperties(remaining, types)) {
if (prop.type === 'TSPropertySignature') {

@@ -82,4 +37,2 @@ const topLevelType = parseTopLevelType(

events.push(prop);
} else if (isProp(prop.key.name, prop)) {
props.push(prop);
}

@@ -86,0 +39,0 @@ }

@@ -19,96 +19,29 @@ /**

categorizeProps = _require3.categorizeProps;
const _require4 = require('./props'),
getProps = _require4.getProps;
const _require5 = require('./componentsUtils.js'),
getProperties = _require5.getProperties;
const _require6 = require('../../error-utils'),
throwIfMoreThanOneCodegenNativecommands =
_require6.throwIfMoreThanOneCodegenNativecommands;
const _require7 = require('../../parsers-commons'),
createComponentConfig = _require7.createComponentConfig,
findNativeComponentType = _require7.findNativeComponentType,
getCommandOptions = _require7.getCommandOptions,
getOptions = _require7.getOptions;
// $FlowFixMe[signature-verification-failure] TODO(T108222691): Use flow-types for @babel/parser
function findComponentConfig(ast, parser) {
const foundConfigs = [];
const defaultExports = ast.body.filter(
node => node.type === 'ExportDefaultDeclaration',
);
defaultExports.forEach(statement =>
findNativeComponentType(statement, foundConfigs, parser),
);
if (foundConfigs.length === 0) {
throw new Error('Could not find component config for native component');
}
if (foundConfigs.length > 1) {
throw new Error('Only one component is supported per file');
}
const foundConfig = foundConfigs[0];
const namedExports = ast.body.filter(
node => node.type === 'ExportNamedDeclaration',
);
const commandsTypeNames = namedExports
.map(statement => {
let callExpression;
let calleeName;
try {
callExpression = statement.declaration.declarations[0].init;
calleeName = callExpression.callee.name;
} catch (e) {
return;
}
if (calleeName !== 'codegenNativeCommands') {
return;
}
// const statement.declaration.declarations[0].init
if (callExpression.arguments.length !== 1) {
throw new Error(
'codegenNativeCommands must be passed options including the supported commands',
);
}
const typeArgumentParam = callExpression.typeParameters.params[0];
if (typeArgumentParam.type !== 'TSTypeReference') {
throw new Error(
"codegenNativeCommands doesn't support inline definitions. Specify a file local type alias",
);
}
return {
commandTypeName: typeArgumentParam.typeName.name,
commandOptionsExpression: callExpression.arguments[0],
};
})
.filter(Boolean);
throwIfMoreThanOneCodegenNativecommands(commandsTypeNames);
return createComponentConfig(foundConfig, commandsTypeNames);
}
function getCommandProperties(
/* $FlowFixMe[missing-local-annot] The type annotation(s) required by Flow's
* LTI update could not be added via codemod */
commandTypeName,
types,
commandOptions,
) {
const _require4 = require('./componentsUtils.js'),
getProperties = _require4.getProperties;
const _require5 = require('../../error-utils'),
throwIfTypeAliasIsNotInterface = _require5.throwIfTypeAliasIsNotInterface;
const _require6 = require('../../parsers-commons'),
propertyNames = _require6.propertyNames,
getCommandOptions = _require6.getCommandOptions,
getOptions = _require6.getOptions,
findComponentConfig = _require6.findComponentConfig;
function getCommandProperties(ast, parser) {
const _findComponentConfig = findComponentConfig(ast, parser),
commandTypeName = _findComponentConfig.commandTypeName,
commandOptionsExpression = _findComponentConfig.commandOptionsExpression;
if (commandTypeName == null) {
return [];
}
const types = parser.getTypes(ast);
const typeAlias = types[commandTypeName];
if (typeAlias.type !== 'TSInterfaceDeclaration') {
throwIfTypeAliasIsNotInterface(typeAlias, parser);
const properties = parser.bodyProperties(typeAlias);
if (!properties) {
throw new Error(
`The type argument for codegenNativeCommands must be an interface, received ${typeAlias.type}`,
);
}
let properties;
try {
properties = typeAlias.body.body;
} catch (e) {
throw new Error(
`Failed to find type definition for "${commandTypeName}", please check that you have a valid codegen typescript file`,
);
}
const typeScriptPropertyNames = properties
.map(property => property && property.key && property.key.name)
.filter(Boolean);
const typeScriptPropertyNames = propertyNames(properties);
const commandOptions = getCommandOptions(commandOptionsExpression);
if (commandOptions == null || commandOptions.supportedCommands == null) {

@@ -139,29 +72,16 @@ throw new Error(

function buildComponentSchema(ast, parser) {
const _findComponentConfig = findComponentConfig(ast, parser),
componentName = _findComponentConfig.componentName,
propsTypeName = _findComponentConfig.propsTypeName,
commandTypeName = _findComponentConfig.commandTypeName,
commandOptionsExpression = _findComponentConfig.commandOptionsExpression,
optionsExpression = _findComponentConfig.optionsExpression;
const _findComponentConfig2 = findComponentConfig(ast, parser),
componentName = _findComponentConfig2.componentName,
propsTypeName = _findComponentConfig2.propsTypeName,
optionsExpression = _findComponentConfig2.optionsExpression;
const types = parser.getTypes(ast);
const propProperties = getProperties(propsTypeName, types);
const commandOptions = getCommandOptions(commandOptionsExpression);
const commandProperties = getCommandProperties(
commandTypeName,
types,
commandOptions,
);
const commandProperties = getCommandProperties(ast, parser);
const options = getOptions(optionsExpression);
const extendsProps = [];
const componentPropAsts = [];
const componentEventAsts = [];
categorizeProps(
propProperties,
types,
extendsProps,
componentPropAsts,
componentEventAsts,
);
const props = getProps(componentPropAsts, types);
const events = getEvents(componentEventAsts, types);
categorizeProps(propProperties, types, componentEventAsts);
const _parser$getProps = parser.getProps(propProperties, types),
props = _parser$getProps.props,
extendsProps = _parser$getProps.extendsProps;
const events = getEvents(componentEventAsts, types, parser);
const commands = getCommands(commandProperties, types);

@@ -168,0 +88,0 @@ return {

@@ -17,26 +17,19 @@ /**

flattenProperties = _require2.flattenProperties;
const _require3 = require('../utils'),
resolveTypeAnnotation = _require3.resolveTypeAnnotation;
const _require4 = require('../../parsers-commons'),
parseObjectProperty = _require4.parseObjectProperty;
const _require5 = require('../../parsers-primitives'),
emitArrayType = _require5.emitArrayType,
emitBoolean = _require5.emitBoolean,
emitFunction = _require5.emitFunction,
emitNumber = _require5.emitNumber,
emitGenericObject = _require5.emitGenericObject,
emitPromise = _require5.emitPromise,
emitRootTag = _require5.emitRootTag,
emitVoid = _require5.emitVoid,
emitString = _require5.emitString,
emitMixed = _require5.emitMixed,
emitUnion = _require5.emitUnion,
emitCommonTypes = _require5.emitCommonTypes,
typeAliasResolution = _require5.typeAliasResolution,
typeEnumResolution = _require5.typeEnumResolution,
translateArrayTypeAnnotation = _require5.translateArrayTypeAnnotation;
const _require6 = require('../../errors'),
UnsupportedGenericParserError = _require6.UnsupportedGenericParserError,
const _require3 = require('../../parsers-commons'),
parseObjectProperty = _require3.parseObjectProperty;
const _require4 = require('../../parsers-primitives'),
emitArrayType = _require4.emitArrayType,
emitFunction = _require4.emitFunction,
emitDictionary = _require4.emitDictionary,
emitPromise = _require4.emitPromise,
emitRootTag = _require4.emitRootTag,
emitUnion = _require4.emitUnion,
emitCommonTypes = _require4.emitCommonTypes,
typeAliasResolution = _require4.typeAliasResolution,
typeEnumResolution = _require4.typeEnumResolution,
translateArrayTypeAnnotation = _require4.translateArrayTypeAnnotation;
const _require5 = require('../../errors'),
UnsupportedGenericParserError = _require5.UnsupportedGenericParserError,
UnsupportedTypeAnnotationParserError =
_require6.UnsupportedTypeAnnotationParserError;
_require5.UnsupportedTypeAnnotationParserError;
function translateObjectTypeAnnotation(

@@ -177,9 +170,12 @@ hasteModuleName,

) {
const _resolveTypeAnnotatio = resolveTypeAnnotation(
const _parser$getResolvedTy = parser.getResolvedTypeAnnotation(
typeScriptTypeAnnotation,
types,
parser,
),
nullable = _resolveTypeAnnotatio.nullable,
typeAnnotation = _resolveTypeAnnotatio.typeAnnotation,
typeResolutionStatus = _resolveTypeAnnotatio.typeResolutionStatus;
nullable = _parser$getResolvedTy.nullable,
typeAnnotation = _parser$getResolvedTy.typeAnnotation,
typeResolutionStatus = _parser$getResolvedTy.typeResolutionStatus;
const resolveTypeaAnnotationFn = parser.getResolveTypeAnnotationFN();
resolveTypeaAnnotationFn(typeScriptTypeAnnotation, types, parser);
switch (typeAnnotation.type) {

@@ -308,3 +304,3 @@ case 'TSArrayType': {

const propertyType = indexSignatures[0].typeAnnotation;
translateTypeAnnotation(
const valueType = translateTypeAnnotation(
hasteModuleName,

@@ -320,3 +316,3 @@ propertyType,

// no need to do further checking
return emitGenericObject(nullable);
return emitDictionary(nullable, valueType);
}

@@ -348,14 +344,2 @@ }

}
case 'TSBooleanKeyword': {
return emitBoolean(nullable);
}
case 'TSNumberKeyword': {
return emitNumber(nullable);
}
case 'TSVoidKeyword': {
return emitVoid(nullable);
}
case 'TSStringKeyword': {
return emitString(nullable);
}
case 'TSFunctionType': {

@@ -378,15 +362,22 @@ return emitFunction(

}
case 'TSUnknownKeyword': {
if (cxxOnly) {
return emitMixed(nullable);
}
// Fallthrough
}
default: {
throw new UnsupportedTypeAnnotationParserError(
const commonType = emitCommonTypes(
hasteModuleName,
types,
typeAnnotation,
parser.language(),
aliasMap,
enumMap,
tryParse,
cxxOnly,
nullable,
parser,
);
if (!commonType) {
throw new UnsupportedTypeAnnotationParserError(
hasteModuleName,
typeAnnotation,
parser.language(),
);
}
return commonType;
}

@@ -393,0 +384,0 @@ }

@@ -8,4 +8,11 @@ /**

import type {Parser} from '../parser';
import type { Parser } from '../parser';
import type { SchemaType } from '../../CodegenSchema';
import type { ParserType } from '../errors';
export declare class TypeScriptParser implements Parser{}
export declare class TypeScriptParser implements Parser {
language(): ParserType;
parseFile(filename: string): SchemaType;
parseString(contents: string, filename?: string): SchemaType;
parseModuleFixture(filename: string): SchemaType;
}

@@ -41,2 +41,3 @@ /**

}
const invariant = require('invariant');
const _require = require('./modules'),

@@ -57,9 +58,15 @@ typeScriptTranslateTypeAnnotation =

const _require6 = require('../parsers-commons.js'),
buildModuleSchema = _require6.buildModuleSchema;
const _require7 = require('./utils'),
resolveTypeAnnotation = _require7.resolveTypeAnnotation;
buildModuleSchema = _require6.buildModuleSchema,
extendsForProp = _require6.extendsForProp,
buildPropSchema = _require6.buildPropSchema;
const _require7 = require('./parseTopLevelType'),
parseTopLevelType = _require7.parseTopLevelType;
const _require8 = require('./components/componentsUtils'),
getSchemaInfo = _require8.getSchemaInfo,
getTypeAnnotation = _require8.getTypeAnnotation,
flattenProperties = _require8.flattenProperties;
const fs = require('fs');
const _require8 = require('../errors'),
const _require9 = require('../errors'),
UnsupportedObjectPropertyTypeAnnotationParserError =
_require8.UnsupportedObjectPropertyTypeAnnotationParserError;
_require9.UnsupportedObjectPropertyTypeAnnotationParserError;
class TypeScriptParser {

@@ -72,2 +79,11 @@ constructor() {

);
_defineProperty(this, 'typeAlias', 'TSTypeAliasDeclaration');
_defineProperty(this, 'enumDeclaration', 'TSEnumDeclaration');
_defineProperty(this, 'interfaceDeclaration', 'TSInterfaceDeclaration');
_defineProperty(this, 'nullLiteralTypeAnnotation', 'TSNullKeyword');
_defineProperty(
this,
'undefinedLiteralTypeAnnotation',
'TSUndefinedKeyword',
);
}

@@ -92,3 +108,9 @@ isProperty(property) {

nameForGenericTypeAnnotation(typeAnnotation) {
return typeAnnotation.typeName.name;
var _typeAnnotation$typeN;
return typeAnnotation === null || typeAnnotation === void 0
? void 0
: (_typeAnnotation$typeN = typeAnnotation.typeName) === null ||
_typeAnnotation$typeN === void 0
? void 0
: _typeAnnotation$typeN.name;
}

@@ -126,3 +148,2 @@ checkIfInvalidModule(typeArguments) {

this,
resolveTypeAnnotation,
typeScriptTranslateTypeAnnotation,

@@ -232,2 +253,5 @@ );

}
isGenericTypeAnnotation(type) {
return type === 'TSTypeReference';
}
extractAnnotatedElement(typeAnnotation, types) {

@@ -315,2 +339,164 @@ return types[typeAnnotation.typeParameters.params[0].typeName.name];

}
bodyProperties(typeAlias) {
return typeAlias.body.body;
}
convertKeywordToTypeAnnotation(keyword) {
switch (keyword) {
case 'TSBooleanKeyword':
return 'BooleanTypeAnnotation';
case 'TSNumberKeyword':
return 'NumberTypeAnnotation';
case 'TSVoidKeyword':
return 'VoidTypeAnnotation';
case 'TSStringKeyword':
return 'StringTypeAnnotation';
case 'TSUnknownKeyword':
return 'MixedTypeAnnotation';
}
return keyword;
}
argumentForProp(prop) {
return prop.expression;
}
nameForArgument(prop) {
return prop.expression.name;
}
isOptionalProperty(property) {
return property.optional || false;
}
getGetSchemaInfoFN() {
return getSchemaInfo;
}
getGetTypeAnnotationFN() {
return getTypeAnnotation;
}
getResolvedTypeAnnotation(
// TODO(T108222691): Use flow-types for @babel/parser
typeAnnotation,
types,
parser,
) {
invariant(
typeAnnotation != null,
'resolveTypeAnnotation(): typeAnnotation cannot be null',
);
let node =
typeAnnotation.type === 'TSTypeAnnotation'
? typeAnnotation.typeAnnotation
: typeAnnotation;
let nullable = false;
let typeResolutionStatus = {
successful: false,
};
for (;;) {
const topLevelType = parseTopLevelType(node);
nullable = nullable || topLevelType.optional;
node = topLevelType.type;
if (node.type !== 'TSTypeReference') {
break;
}
const resolvedTypeAnnotation = types[node.typeName.name];
if (resolvedTypeAnnotation == null) {
break;
}
switch (resolvedTypeAnnotation.type) {
case parser.typeAlias: {
typeResolutionStatus = {
successful: true,
type: 'alias',
name: node.typeName.name,
};
node = resolvedTypeAnnotation.typeAnnotation;
break;
}
case parser.interfaceDeclaration: {
typeResolutionStatus = {
successful: true,
type: 'alias',
name: node.typeName.name,
};
node = resolvedTypeAnnotation;
break;
}
case parser.enumDeclaration: {
typeResolutionStatus = {
successful: true,
type: 'enum',
name: node.typeName.name,
};
node = resolvedTypeAnnotation;
break;
}
default: {
throw new TypeError(
`A non GenericTypeAnnotation must be a type declaration ('${parser.typeAlias}'), an interface ('${parser.interfaceDeclaration}'), or enum ('${parser.enumDeclaration}'). Instead, got the unsupported ${resolvedTypeAnnotation.type}.`,
);
}
}
}
return {
nullable: nullable,
typeAnnotation: node,
typeResolutionStatus,
};
}
getResolveTypeAnnotationFN() {
return (typeAnnotation, types, parser) => {
return this.getResolvedTypeAnnotation(typeAnnotation, types, parser);
};
}
isEvent(typeAnnotation) {
if (typeAnnotation.type !== 'TSTypeReference') {
return false;
}
const eventNames = new Set(['BubblingEventHandler', 'DirectEventHandler']);
return eventNames.has(typeAnnotation.typeName.name);
}
isProp(name, typeAnnotation) {
if (typeAnnotation.type !== 'TSTypeReference') {
return true;
}
const isStyle =
name === 'style' &&
typeAnnotation.type === 'GenericTypeAnnotation' &&
typeAnnotation.typeName.name === 'ViewStyleProp';
return !isStyle;
}
getProps(typeDefinition, types) {
const extendsProps = [];
const componentPropAsts = [];
const remaining = [];
for (const prop of typeDefinition) {
// find extends
if (prop.type === 'TSExpressionWithTypeArguments') {
const extend = extendsForProp(prop, types, this);
if (extend) {
extendsProps.push(extend);
continue;
}
}
remaining.push(prop);
}
// find events and props
for (const prop of flattenProperties(remaining, types)) {
const topLevelType = parseTopLevelType(
prop.typeAnnotation.typeAnnotation,
types,
);
if (
prop.type === 'TSPropertySignature' &&
!this.isEvent(topLevelType.type) &&
this.isProp(prop.key.name, prop)
) {
componentPropAsts.push(prop);
}
}
return {
props: componentPropAsts
.map(property => buildPropSchema(property, types, this))
.filter(Boolean),
extendsProps,
};
}
}

@@ -317,0 +503,0 @@ module.exports = {

{
"name": "@react-native/codegen",
"version": "0.72.5",
"description": "⚛️ Code generation tools for React Native",
"homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-codegen",
"version": "0.73.0-nightly-20230603-fd9e295be",
"description": "Code generation tools for React Native",
"license": "MIT",
"repository": {
"type": "git",
"url": "git@github.com:facebook/react-native.git",
"url": "https://github.com/facebook/react-native.git",
"directory": "packages/react-native-codegen"
},
"homepage": "https://github.com/facebook/react-native/tree/HEAD/packages/react-native-codegen#readme",
"keywords": [
"code",
"generation",
"codegen",
"tools",
"react-native"
],
"bugs": "https://github.com/facebook/react-native/issues",
"engines": {
"node": ">=16"
},
"scripts": {

@@ -16,3 +28,2 @@ "build": "yarn clean && node scripts/build.js --verbose",

},
"license": "MIT",
"files": [

@@ -19,0 +30,0 @@ "lib"

@@ -18,5 +18,5 @@ # @react-native/codegen

To run the tests in this package, run the following commands from the react Native root folder:
To run the tests in this package, run the following commands from the React Native root folder:
1. `yarn` to install the dependencies. You just need to run this once
2. `yarn jest react-native-codegen`.
2. `yarn jest packages/react-native-codegen`.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc