@react-native-windows/codegen 0.0.0-canary.13 → 0.0.0-canary.130

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +1125 -16
  2. package/README.md +1 -1
  3. package/bin.js +0 -0
  4. package/lib-commonjs/Cli.d.ts +7 -0
  5. package/lib-commonjs/Cli.js +103 -0
  6. package/lib-commonjs/Cli.js.map +1 -0
  7. package/lib-commonjs/generators/AliasGen.d.ts +12 -0
  8. package/lib-commonjs/generators/AliasGen.js +115 -0
  9. package/lib-commonjs/generators/AliasGen.js.map +1 -0
  10. package/lib-commonjs/generators/AliasManaging.d.ts +15 -0
  11. package/lib-commonjs/generators/AliasManaging.js +49 -0
  12. package/lib-commonjs/generators/AliasManaging.js.map +1 -0
  13. package/lib-commonjs/generators/GenerateComponentWindows.d.ts +13 -0
  14. package/lib-commonjs/generators/GenerateComponentWindows.js +469 -0
  15. package/lib-commonjs/generators/GenerateComponentWindows.js.map +1 -0
  16. package/lib-commonjs/generators/GenerateNM2.d.ts +15 -0
  17. package/lib-commonjs/generators/GenerateNM2.js +145 -0
  18. package/lib-commonjs/generators/GenerateNM2.js.map +1 -0
  19. package/lib-commonjs/generators/GenerateTypeScript.d.ts +11 -0
  20. package/lib-commonjs/generators/GenerateTypeScript.js +166 -0
  21. package/lib-commonjs/generators/GenerateTypeScript.js.map +1 -0
  22. package/lib-commonjs/generators/ObjectTypes.d.ts +13 -0
  23. package/lib-commonjs/generators/ObjectTypes.js +81 -0
  24. package/lib-commonjs/generators/ObjectTypes.js.map +1 -0
  25. package/lib-commonjs/generators/ParamTypes.d.ts +13 -0
  26. package/lib-commonjs/generators/ParamTypes.js +183 -0
  27. package/lib-commonjs/generators/ParamTypes.js.map +1 -0
  28. package/lib-commonjs/generators/PropObjectTypes.d.ts +18 -0
  29. package/lib-commonjs/generators/PropObjectTypes.js +208 -0
  30. package/lib-commonjs/generators/PropObjectTypes.js.map +1 -0
  31. package/lib-commonjs/generators/ReturnTypes.d.ts +10 -0
  32. package/lib-commonjs/generators/ReturnTypes.js +29 -0
  33. package/lib-commonjs/generators/ReturnTypes.js.map +1 -0
  34. package/lib-commonjs/generators/ValidateConstants.d.ts +8 -0
  35. package/lib-commonjs/generators/ValidateConstants.js +38 -0
  36. package/lib-commonjs/generators/ValidateConstants.js.map +1 -0
  37. package/lib-commonjs/generators/ValidateMethods.d.ts +14 -0
  38. package/lib-commonjs/generators/ValidateMethods.js +112 -0
  39. package/lib-commonjs/generators/ValidateMethods.js.map +1 -0
  40. package/lib-commonjs/index.d.ts +39 -0
  41. package/lib-commonjs/index.js +227 -0
  42. package/lib-commonjs/index.js.map +1 -0
  43. package/package.json +39 -21
  44. package/src/Cli.ts +69 -232
  45. package/src/generators/AliasGen.ts +195 -0
  46. package/src/generators/AliasManaging.ts +75 -0
  47. package/src/generators/GenerateComponentWindows.ts +616 -0
  48. package/src/generators/GenerateNM2.ts +128 -131
  49. package/src/generators/GenerateTypeScript.ts +250 -0
  50. package/src/generators/ObjectTypes.ts +95 -37
  51. package/src/generators/ParamTypes.ts +309 -53
  52. package/src/generators/PropObjectTypes.ts +223 -0
  53. package/src/generators/ReturnTypes.ts +38 -40
  54. package/src/generators/ValidateConstants.ts +50 -0
  55. package/src/generators/ValidateMethods.ts +270 -0
  56. package/src/index.ts +415 -0
  57. package/.eslintrc.js +0 -4
  58. package/.vscode/launch.json +0 -23
  59. package/CHANGELOG.json +0 -726
  60. package/jest.config.js +0 -1
  61. package/tsconfig.json +0 -5
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ * @format
5
+ */
6
+ 'use strict';
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.createNM2Generator = void 0;
9
+ const AliasManaging_1 = require("./AliasManaging");
10
+ const AliasGen_1 = require("./AliasGen");
11
+ const ValidateConstants_1 = require("./ValidateConstants");
12
+ const ValidateMethods_1 = require("./ValidateMethods");
13
+ const headerTemplate = `/*
14
+ * This file is auto-generated from a NativeModule spec file in js.
15
+ *
16
+ * This is a C++ Spec class that should be used with MakeTurboModuleProvider to register native modules
17
+ * in a way that also verifies at compile time that the native module matches the interface required
18
+ * by the TurboModule JS spec.
19
+ */
20
+ #pragma once
21
+ // clang-format off`;
22
+ const specTemplate = `::_MODULE_CUSTOM_TYPES_REFLECTION_::
23
+ struct ::_MODULE_NAME_::Spec : winrt::Microsoft::ReactNative::TurboModuleSpec {
24
+ ::_MODULE_MEMBERS_TUPLES_::
25
+
26
+ template <class TModule>
27
+ static constexpr void ValidateModule() noexcept {
28
+ ::_MODULE_MEMBERS_CHECKS_::
29
+
30
+ ::_MODULE_MEMBERS_ERRORS_::
31
+ }`;
32
+ const typeOnlyTemplate = `
33
+ ${headerTemplate}
34
+
35
+ #include <string>
36
+ #include <optional>
37
+ #include <functional>
38
+ #include <vector>
39
+
40
+ namespace ::_NAMESPACE_:: {
41
+ ::_MODULE_CUSTOM_TYPES_::
42
+ } // namespace ::_NAMESPACE_::
43
+ `;
44
+ const moduleOnlyTemplate = `
45
+ ${headerTemplate}
46
+
47
+ ::_TYPE_DEFINITION_INCLUDE_::
48
+ #include <NativeModules.h>
49
+ #include <tuple>
50
+
51
+ namespace ::_NAMESPACE_:: {
52
+ ${specTemplate}
53
+ };
54
+
55
+ } // namespace ::_NAMESPACE_::
56
+ `;
57
+ const allInOneTemplate = `
58
+ ${headerTemplate}
59
+
60
+ #include <NativeModules.h>
61
+ #include <tuple>
62
+
63
+ namespace ::_NAMESPACE_:: {
64
+ ::_MODULE_CUSTOM_TYPES_::
65
+ ${specTemplate}
66
+ };
67
+
68
+ } // namespace ::_NAMESPACE_::
69
+ `;
70
+ function createNM2Generator({ methodOnly, namespace, cppStringType, separateDataTypes, }) {
71
+ return (_libraryName, schema, _moduleSpecName) => {
72
+ const files = new Map();
73
+ for (const moduleName of Object.keys(schema.modules)) {
74
+ const nativeModule = schema.modules[moduleName];
75
+ // from 0.65 facebook's react-native-codegen
76
+ // the module name has the Native prefix comparing to 0.63
77
+ // when reading files we provided
78
+ const preferredModuleName = moduleName.startsWith('Native')
79
+ ? moduleName.substr(6)
80
+ : moduleName;
81
+ (0, AliasManaging_1.setPreferredModuleName)(preferredModuleName);
82
+ if (nativeModule.type === 'NativeModule') {
83
+ console.log(`Generating Native${preferredModuleName}Spec.g.h`);
84
+ // copy all explicit to a map
85
+ const aliases = (0, AliasGen_1.createAliasMap)(nativeModule.aliasMap);
86
+ // prepare methods
87
+ const methods = (0, ValidateMethods_1.generateValidateMethods)(nativeModule, aliases, {
88
+ cppStringType,
89
+ });
90
+ let tuples = `
91
+ static constexpr auto methods = std::tuple{
92
+ ${methods.traversedPropertyTuples}${methods.traversedEventEmitterTuples ? '\n' : ''}${methods.traversedEventEmitterTuples}
93
+ };`;
94
+ let checks = `
95
+ constexpr auto methodCheckResults = CheckMethods<TModule, ::_MODULE_NAME_::Spec>();`;
96
+ let errors = methods.traversedProperties +
97
+ (methods.traversedEventEmitters ? '\n' : '') +
98
+ methods.traversedEventEmitters;
99
+ // prepare constants
100
+ const constants = (0, ValidateConstants_1.generateValidateConstants)(nativeModule, aliases);
101
+ if (constants !== undefined && !methodOnly) {
102
+ tuples = `
103
+ static constexpr auto constants = std::tuple{
104
+ ${constants[0]}
105
+ };${tuples}`;
106
+ checks = `
107
+ constexpr auto constantCheckResults = CheckConstants<TModule, ::_MODULE_NAME_::Spec>();${checks}`;
108
+ errors = `${constants[1]}
109
+
110
+ ${errors}`;
111
+ }
112
+ // generate code for structs
113
+ const [customTypes, customReflection] = (0, AliasGen_1.generateAliases)(aliases, {
114
+ cppStringType,
115
+ });
116
+ const customTypesExist = customTypes !== '';
117
+ const replaceContent = function (template) {
118
+ return template
119
+ .replace(/::_MODULE_CUSTOM_TYPES_::/g, customTypes)
120
+ .replace(/::_MODULE_CUSTOM_TYPES_REFLECTION_::/g, customReflection)
121
+ .replace(/::_MODULE_MEMBERS_TUPLES_::/g, tuples.substring(1))
122
+ .replace(/::_MODULE_MEMBERS_CHECKS_::/g, checks.substring(1))
123
+ .replace(/::_MODULE_MEMBERS_ERRORS_::/g, errors)
124
+ .replace(/::_MODULE_NAME_::/g, preferredModuleName)
125
+ .replace(/::_TYPE_DEFINITION_INCLUDE_::/g, customTypesExist
126
+ ? `// #include "Native${preferredModuleName}DataTypes.g.h" before this file to use the generated type definition`
127
+ : '')
128
+ .replace(/::_NAMESPACE_::/g, namespace);
129
+ };
130
+ if (separateDataTypes) {
131
+ if (customTypesExist) {
132
+ files.set(`Native${preferredModuleName}DataTypes.g.h`, replaceContent(typeOnlyTemplate));
133
+ }
134
+ files.set(`Native${preferredModuleName}Spec.g.h`, replaceContent(moduleOnlyTemplate));
135
+ }
136
+ else {
137
+ files.set(`Native${preferredModuleName}Spec.g.h`, replaceContent(allInOneTemplate));
138
+ }
139
+ }
140
+ }
141
+ return files;
142
+ };
143
+ }
144
+ exports.createNM2Generator = createNM2Generator;
145
+ //# sourceMappingURL=GenerateNM2.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GenerateNM2.js","sourceRoot":"","sources":["../../src/generators/GenerateNM2.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,YAAY,CAAC;;;AAGb,mDAAiE;AACjE,yCAA2D;AAC3D,2DAA8D;AAC9D,uDAA0D;AAO1D,MAAM,cAAc,GAAG;;;;;;;;oBAQH,CAAC;AAErB,MAAM,YAAY,GAAG;;;;;;;;;IASjB,CAAC;AAEL,MAAM,gBAAgB,GAAG;EACvB,cAAc;;;;;;;;;;CAUf,CAAC;AAEF,MAAM,kBAAkB,GAAG;EACzB,cAAc;;;;;;;EAOd,YAAY;;;;CAIb,CAAC;AAEF,MAAM,gBAAgB,GAAG;EACvB,cAAc;;;;;;;EAOd,YAAY;;;;CAIb,CAAC;AAEF,SAAgB,kBAAkB,CAAC,EACjC,UAAU,EACV,SAAS,EACT,aAAa,EACb,iBAAiB,GAM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AAC,CACjC,CAAC;qBACH;oBACD,KAAK,CAAC,GAAG,CACP,SAAS,mBAAmB,UAAU,EACtC,cAAc,CAAC,kBAAkB,CAAC,CACnC,CAAC;iBACH;qBAAM;oBACL,KAAK,CAAC,GAAG,CACP,SAAS,mBAAmB,UAAU,EACtC,cAAc,CAAC,gBAAgB,CAAC,CACjC,CAAC;iBACH;aACF;SACF;QAED,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;AACJ,CAAC;AA/GD,gDA+GC","sourcesContent":["/**\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n * @format\n */\n\n'use strict';\n\nimport type {SchemaType} from '@react-native/codegen/lib/CodegenSchema';\nimport {AliasMap, setPreferredModuleName} from './AliasManaging';\nimport {createAliasMap, generateAliases} from './AliasGen';\nimport {generateValidateConstants} from './ValidateConstants';\nimport {generateValidateMethods} from './ValidateMethods';\nimport type {CppStringTypes} from './ObjectTypes';\n\nexport type {CppStringTypes} from './ObjectTypes';\n\ntype FilesOutput = Map<string, string>;\n\nconst headerTemplate = `/*\n * This file is auto-generated from a NativeModule spec file in js.\n *\n * This is a C++ Spec class that should be used with MakeTurboModuleProvider to register native modules\n * in a way that also verifies at compile time that the native module matches the interface required\n * by the TurboModule JS spec.\n */\n#pragma once\n// clang-format off`;\n\nconst specTemplate = `::_MODULE_CUSTOM_TYPES_REFLECTION_::\nstruct ::_MODULE_NAME_::Spec : winrt::Microsoft::ReactNative::TurboModuleSpec {\n::_MODULE_MEMBERS_TUPLES_::\n\n template <class TModule>\n static constexpr void ValidateModule() noexcept {\n::_MODULE_MEMBERS_CHECKS_::\n\n::_MODULE_MEMBERS_ERRORS_::\n }`;\n\nconst typeOnlyTemplate = `\n${headerTemplate}\n\n#include <string>\n#include <optional>\n#include <functional>\n#include <vector>\n\nnamespace ::_NAMESPACE_:: {\n::_MODULE_CUSTOM_TYPES_::\n} // namespace ::_NAMESPACE_::\n`;\n\nconst moduleOnlyTemplate = `\n${headerTemplate}\n\n::_TYPE_DEFINITION_INCLUDE_::\n#include <NativeModules.h>\n#include <tuple>\n\nnamespace ::_NAMESPACE_:: {\n${specTemplate}\n};\n\n} // namespace ::_NAMESPACE_::\n`;\n\nconst allInOneTemplate = `\n${headerTemplate}\n\n#include <NativeModules.h>\n#include <tuple>\n\nnamespace ::_NAMESPACE_:: {\n::_MODULE_CUSTOM_TYPES_::\n${specTemplate}\n};\n\n} // namespace ::_NAMESPACE_::\n`;\n\nexport function createNM2Generator({\n methodOnly,\n namespace,\n cppStringType,\n separateDataTypes,\n}: {\n methodOnly: boolean;\n namespace: string;\n cppStringType: CppStringTypes;\n separateDataTypes: boolean;\n}) {\n return (\n _libraryName: string,\n schema: SchemaType,\n _moduleSpecName: string,\n ): FilesOutput => {\n const files = new Map<string, string>();\n\n for (const moduleName of Object.keys(schema.modules)) {\n const nativeModule = schema.modules[moduleName];\n // from 0.65 facebook's react-native-codegen\n // the module name has the Native prefix comparing to 0.63\n // when reading files we provided\n const preferredModuleName = moduleName.startsWith('Native')\n ? moduleName.substr(6)\n : moduleName;\n setPreferredModuleName(preferredModuleName);\n\n if (nativeModule.type === 'NativeModule') {\n console.log(`Generating Native${preferredModuleName}Spec.g.h`);\n\n // copy all explicit to a map\n const aliases: AliasMap = createAliasMap(nativeModule.aliasMap);\n\n // prepare methods\n const methods = generateValidateMethods(nativeModule, aliases, {\n cppStringType,\n });\n let tuples = `\n static constexpr auto methods = std::tuple{\n${methods.traversedPropertyTuples}${\n methods.traversedEventEmitterTuples ? '\\n' : ''\n }${methods.traversedEventEmitterTuples}\n };`;\n let checks = `\n constexpr auto methodCheckResults = CheckMethods<TModule, ::_MODULE_NAME_::Spec>();`;\n let errors =\n methods.traversedProperties +\n (methods.traversedEventEmitters ? '\\n' : '') +\n methods.traversedEventEmitters;\n\n // prepare constants\n const constants = generateValidateConstants(nativeModule, aliases);\n if (constants !== undefined && !methodOnly) {\n tuples = `\n static constexpr auto constants = std::tuple{\n${constants[0]}\n };${tuples}`;\n checks = `\n constexpr auto constantCheckResults = CheckConstants<TModule, ::_MODULE_NAME_::Spec>();${checks}`;\n errors = `${constants[1]}\n\n${errors}`;\n }\n\n // generate code for structs\n const [customTypes, customReflection] = generateAliases(aliases, {\n cppStringType,\n });\n\n const customTypesExist = customTypes !== '';\n\n const replaceContent = function (template: string): string {\n return template\n .replace(/::_MODULE_CUSTOM_TYPES_::/g, customTypes)\n .replace(/::_MODULE_CUSTOM_TYPES_REFLECTION_::/g, customReflection)\n .replace(/::_MODULE_MEMBERS_TUPLES_::/g, tuples.substring(1))\n .replace(/::_MODULE_MEMBERS_CHECKS_::/g, checks.substring(1))\n .replace(/::_MODULE_MEMBERS_ERRORS_::/g, errors)\n .replace(/::_MODULE_NAME_::/g, preferredModuleName)\n .replace(\n /::_TYPE_DEFINITION_INCLUDE_::/g,\n customTypesExist\n ? `// #include \"Native${preferredModuleName}DataTypes.g.h\" before this file to use the generated type definition`\n : '',\n )\n .replace(/::_NAMESPACE_::/g, namespace);\n };\n\n if (separateDataTypes) {\n if (customTypesExist) {\n files.set(\n `Native${preferredModuleName}DataTypes.g.h`,\n replaceContent(typeOnlyTemplate),\n );\n }\n files.set(\n `Native${preferredModuleName}Spec.g.h`,\n replaceContent(moduleOnlyTemplate),\n );\n } else {\n files.set(\n `Native${preferredModuleName}Spec.g.h`,\n replaceContent(allInOneTemplate),\n );\n }\n }\n }\n\n return files;\n };\n}\n"]}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ * @format
5
+ */
6
+ import type { NativeModuleSchema, SchemaType } from '@react-native/codegen/lib/CodegenSchema';
7
+ export declare function setOptionalTurboModule(schema: NativeModuleSchema, optional: boolean): void;
8
+ export declare function getOptionalTurboModule(schema: NativeModuleSchema): boolean;
9
+ type FilesOutput = Map<string, string>;
10
+ export declare function generateTypeScript(_libraryName: string, schema: SchemaType, _moduleSpecName: string): FilesOutput;
11
+ export {};
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ * @format
5
+ */
6
+ 'use strict';
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.generateTypeScript = exports.getOptionalTurboModule = exports.setOptionalTurboModule = void 0;
9
+ function setOptionalTurboModule(schema, optional) {
10
+ const cs = schema;
11
+ cs.optionalTurboModule = optional;
12
+ }
13
+ exports.setOptionalTurboModule = setOptionalTurboModule;
14
+ function getOptionalTurboModule(schema) {
15
+ var _a;
16
+ return (_a = schema.optionalTurboModule) !== null && _a !== void 0 ? _a : false;
17
+ }
18
+ exports.getOptionalTurboModule = getOptionalTurboModule;
19
+ const moduleTemplate = `
20
+ /*
21
+ * This file is auto-generated from a NativeModule spec file in js.
22
+ *
23
+ * This is a TypeScript turbo module definition file.
24
+ */
25
+
26
+ import {TurboModule, TurboModuleRegistry} from 'react-native';
27
+ 'use strict';
28
+ ::_MODULE_ALIASED_STRUCTS_::
29
+ export interface Spec extends TurboModule {
30
+ ::_MODULE_MEMBERS_::
31
+ }
32
+
33
+ export default TurboModuleRegistry.::_MODULE_GETTER_::<Spec>('::_MODULE_NAME_::');
34
+ `;
35
+ function optionalSign(obj) {
36
+ return obj.optional ? '?' : '';
37
+ }
38
+ function translateType(type) {
39
+ // avoid: Property 'type' does not exist on type 'never'
40
+ const returnType = type.type;
41
+ switch (type.type) {
42
+ case 'StringTypeAnnotation':
43
+ return 'string';
44
+ case 'NumberTypeAnnotation':
45
+ case 'FloatTypeAnnotation':
46
+ case 'DoubleTypeAnnotation':
47
+ case 'Int32TypeAnnotation':
48
+ return 'number';
49
+ case 'BooleanTypeAnnotation':
50
+ return 'boolean';
51
+ case 'ArrayTypeAnnotation':
52
+ if (type.elementType.type !== 'AnyTypeAnnotation') {
53
+ return `${translateType(type.elementType)}[]`;
54
+ }
55
+ else {
56
+ return `Array`;
57
+ }
58
+ case 'GenericObjectTypeAnnotation':
59
+ return 'object';
60
+ case 'ObjectTypeAnnotation':
61
+ return `{${type.properties
62
+ .map((prop) => {
63
+ return `${prop.name}${optionalSign(prop)}: ${translateType(prop.typeAnnotation)}`;
64
+ })
65
+ .join(', ')}}`;
66
+ case 'ReservedTypeAnnotation': {
67
+ // avoid: Property 'name' does not exist on type 'never'
68
+ const name = type.name;
69
+ // (#6597)
70
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
71
+ if (name !== 'RootTag')
72
+ throw new Error(`Unknown reserved function: ${name} in translateReturnType`);
73
+ return 'number';
74
+ }
75
+ case 'TypeAliasTypeAnnotation':
76
+ return type.name;
77
+ case 'NullableTypeAnnotation':
78
+ return `(${translateType(type.typeAnnotation)} | null | undefined)`;
79
+ case 'VoidTypeAnnotation':
80
+ return `void`;
81
+ case 'PromiseTypeAnnotation':
82
+ return `Promise`;
83
+ case `FunctionTypeAnnotation`:
84
+ return `((${type.params
85
+ .map((param) => {
86
+ return `${param.name}${optionalSign(param)}: ${translateType(param.typeAnnotation)}`;
87
+ })
88
+ .join(', ')}) => ${translateType(type.returnTypeAnnotation)})`;
89
+ default:
90
+ throw new Error(`Unhandled type in translateReturnType: ${returnType}`);
91
+ }
92
+ }
93
+ function translateAlias(name, type) {
94
+ return `
95
+ export interface ${name} {
96
+ ${type.properties
97
+ .map((prop) => {
98
+ return ` ${prop.name}${optionalSign(prop)}: ${translateType(prop.typeAnnotation)};`;
99
+ })
100
+ .join('\n')}
101
+ }
102
+ `;
103
+ }
104
+ function tryGetConstantType(nativeModule) {
105
+ const candidates = nativeModule.spec.methods.filter(prop => prop.name === 'getConstants');
106
+ if (candidates.length === 0) {
107
+ return undefined;
108
+ }
109
+ const getConstant = candidates[0];
110
+ const funcType = getConstant.typeAnnotation.type === 'NullableTypeAnnotation'
111
+ ? getConstant.typeAnnotation.typeAnnotation
112
+ : getConstant.typeAnnotation;
113
+ if (funcType.params.length > 0 ||
114
+ funcType.returnTypeAnnotation.type !== 'ObjectTypeAnnotation') {
115
+ return undefined;
116
+ }
117
+ const constantType = funcType.returnTypeAnnotation;
118
+ if (constantType.properties.length === 0) {
119
+ return undefined;
120
+ }
121
+ return constantType;
122
+ }
123
+ function translateMethod(func) {
124
+ const funcType = func.typeAnnotation.type === 'NullableTypeAnnotation'
125
+ ? func.typeAnnotation.typeAnnotation
126
+ : func.typeAnnotation;
127
+ return `
128
+ ${func.name}(${funcType.params
129
+ .map((param) => {
130
+ return `${param.name}${optionalSign(param)}: ${translateType(param.typeAnnotation)}`;
131
+ })
132
+ .join(', ')})${optionalSign(func)}: ${translateType(funcType.returnTypeAnnotation)}${funcType.returnTypeAnnotation.type === 'ObjectTypeAnnotation' ? '' : ';'}`;
133
+ }
134
+ function generateTypeScript(_libraryName, schema, _moduleSpecName) {
135
+ const files = new Map();
136
+ for (const moduleName of Object.keys(schema.modules)) {
137
+ const nativeModule = schema.modules[moduleName];
138
+ // from 0.65 facebook's react-native-codegen
139
+ // the module name has the Native prefix comparing to 0.63
140
+ // when reading files we provided
141
+ const nativePrefix = 'Native';
142
+ const preferredModuleName = moduleName.startsWith(nativePrefix)
143
+ ? moduleName.substr(nativePrefix.length)
144
+ : moduleName;
145
+ if (nativeModule.type === 'NativeModule') {
146
+ console.log(`Generating ${preferredModuleName}Spec.g.ts`);
147
+ const aliasCode = Object.keys(nativeModule.aliasMap)
148
+ .map(name => translateAlias(name, nativeModule.aliasMap[name]))
149
+ .join('');
150
+ const constantType = tryGetConstantType(nativeModule);
151
+ const constantCode = constantType === undefined
152
+ ? ''
153
+ : ` getConstants(): ${translateType(constantType)}`;
154
+ const methods = nativeModule.spec.methods.filter(prop => prop.name !== 'getConstants');
155
+ const membersCode = methods.map(translateMethod).join('');
156
+ files.set(`${preferredModuleName}Spec.g.ts`, moduleTemplate
157
+ .replace(/::_MODULE_ALIASED_STRUCTS_::/g, aliasCode)
158
+ .replace(/::_MODULE_MEMBERS_::/g, constantCode + membersCode)
159
+ .replace(/::_MODULE_NAME_::/g, preferredModuleName)
160
+ .replace(/::_MODULE_GETTER_::/g, getOptionalTurboModule(nativeModule) ? 'get' : 'getEnforcing'));
161
+ }
162
+ }
163
+ return files;
164
+ }
165
+ exports.generateTypeScript = generateTypeScript;
166
+ //# sourceMappingURL=GenerateTypeScript.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"GenerateTypeScript.js","sourceRoot":"","sources":["../../src/generators/GenerateTypeScript.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,YAAY,CAAC;;;AAmBb,SAAgB,sBAAsB,CACpC,MAA0B,EAC1B,QAAiB;IAEjB,MAAM,EAAE,GAA8B,MAAM,CAAC;IAC7C,EAAE,CAAC,mBAAmB,GAAG,QAAQ,CAAC;AACpC,CAAC;AAND,wDAMC;AAED,SAAgB,sBAAsB,CAAC,MAA0B;;IAC/D,OAAO,MAA4B,MAAO,CAAC,mBAAmB,mCAAI,KAAK,CAAC;AAC1E,CAAC;AAFD,wDAEC;AAOD,MAAM,cAAc,GAAG;;;;;;;;;;;;;;;CAetB,CAAC;AAEF,SAAS,YAAY,CAAI,GAAkB;IACzC,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;AACjC,CAAC;AAED,SAAS,aAAa,CACpB,IAM2B;IAE3B,wDAAwD;IACxD,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC;IAC7B,QAAQ,IAAI,CAAC,IAAI,EAAE;QACjB,KAAK,sBAAsB;YACzB,OAAO,QAAQ,CAAC;QAClB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,qBAAqB,CAAC;QAC3B,KAAK,sBAAsB,CAAC;QAC5B,KAAK,qBAAqB;YACxB,OAAO,QAAQ,CAAC;QAClB,KAAK,uBAAuB;YAC1B,OAAO,SAAS,CAAC;QACnB,KAAK,qBAAqB;YACxB,IAAI,IAAI,CAAC,WAAW,CAAC,IAAI,KAAK,mBAAmB,EAAE;gBACjD,OAAO,GAAG,aAAa,CAAC,IAAI,CAAC,WAAW,CA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SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,QAAQ,CAAC;iBACjD,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,cAAc,CAAC,IAAI,EAAE,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;iBAC9D,IAAI,CAAC,EAAE,CAAC,CAAC;YAEZ,MAAM,YAAY,GAAG,kBAAkB,CAAC,YAAY,CAAC,CAAC;YACtD,MAAM,YAAY,GAChB,YAAY,KAAK,SAAS;gBACxB,CAAC,CAAC,EAAE;gBACJ,CAAC,CAAC,qBAAqB,aAAa,CAAC,YAAY,CAAC,EAAE,CAAC;YAEzD,MAAM,OAAO,GAAG,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,CAC9C,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,cAAc,CACrC,CAAC;YACF,MAAM,WAAW,GAAG,OAAO,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;YAE1D,KAAK,CAAC,GAAG,CACP,GAAG,mBAAmB,WAAW,EACjC,cAAc;iBACX,OAAO,CAAC,+BAA+B,EAAE,SAAS,CAAC;iBACnD,OAAO,CAAC,uBAAuB,EAAE,YAAY,GAAG,WAAW,CAAC;iBAC5D,OAAO,CAAC,oBAAoB,EAAE,mBAAmB,CAAC;iBAClD,OAAO,CACN,sBAAsB,EACtB,sBAAsB,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,cAAc,CAC9D,CACJ,CAAC;SACH;KACF;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAlDD,gDAkDC","sourcesContent":["/**\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n * @format\n */\n\n'use strict';\n\nimport type {\n NamedShape,\n NativeModuleBaseTypeAnnotation,\n NativeModuleFunctionTypeAnnotation,\n NativeModuleObjectTypeAnnotation,\n NativeModuleParamTypeAnnotation,\n NativeModuleReturnTypeAnnotation,\n NativeModuleSchema,\n UnsafeAnyTypeAnnotation,\n Nullable,\n SchemaType,\n} from '@react-native/codegen/lib/CodegenSchema';\n\ninterface CodegenNativeModuleSchema extends NativeModuleSchema {\n optionalTurboModule?: boolean;\n}\n\nexport function setOptionalTurboModule(\n schema: NativeModuleSchema,\n optional: boolean,\n): void {\n const cs = <CodegenNativeModuleSchema>schema;\n cs.optionalTurboModule = optional;\n}\n\nexport function getOptionalTurboModule(schema: NativeModuleSchema): boolean {\n return (<CodegenNativeModuleSchema>schema).optionalTurboModule ?? false;\n}\n\ntype ObjectProp = NamedShape<Nullable<NativeModuleBaseTypeAnnotation>>;\ntype FunctionParam = NamedShape<Nullable<NativeModuleParamTypeAnnotation>>;\ntype FunctionDecl = NamedShape<Nullable<NativeModuleFunctionTypeAnnotation>>;\ntype FilesOutput = Map<string, string>;\n\nconst moduleTemplate = `\n/*\n * This file is auto-generated from a NativeModule spec file in js.\n *\n * This is a TypeScript turbo module definition file.\n */\n\nimport {TurboModule, TurboModuleRegistry} from 'react-native';\n'use strict';\n::_MODULE_ALIASED_STRUCTS_::\nexport interface Spec extends TurboModule {\n::_MODULE_MEMBERS_::\n}\n\nexport default TurboModuleRegistry.::_MODULE_GETTER_::<Spec>('::_MODULE_NAME_::');\n`;\n\nfunction optionalSign<T>(obj: NamedShape<T>): string {\n return obj.optional ? '?' : '';\n}\n\nfunction translateType(\n type:\n | Nullable<\n | NativeModuleBaseTypeAnnotation\n | NativeModuleParamTypeAnnotation\n | NativeModuleReturnTypeAnnotation\n >\n | UnsafeAnyTypeAnnotation,\n): string {\n // avoid: Property 'type' does not exist on type 'never'\n const returnType = type.type;\n switch (type.type) {\n case 'StringTypeAnnotation':\n return 'string';\n case 'NumberTypeAnnotation':\n case 'FloatTypeAnnotation':\n case 'DoubleTypeAnnotation':\n case 'Int32TypeAnnotation':\n return 'number';\n case 'BooleanTypeAnnotation':\n return 'boolean';\n case 'ArrayTypeAnnotation':\n if (type.elementType.type !== 'AnyTypeAnnotation') {\n return `${translateType(type.elementType)}[]`;\n } else {\n return `Array`;\n }\n case 'GenericObjectTypeAnnotation':\n return 'object';\n case 'ObjectTypeAnnotation':\n return `{${type.properties\n .map((prop: ObjectProp) => {\n return `${prop.name}${optionalSign(prop)}: ${translateType(\n prop.typeAnnotation,\n )}`;\n })\n .join(', ')}}`;\n case 'ReservedTypeAnnotation': {\n // avoid: Property 'name' does not exist on type 'never'\n const name = type.name;\n // (#6597)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (name !== 'RootTag')\n throw new Error(\n `Unknown reserved function: ${name} in translateReturnType`,\n );\n return 'number';\n }\n case 'TypeAliasTypeAnnotation':\n return type.name;\n case 'NullableTypeAnnotation':\n return `(${translateType(type.typeAnnotation)} | null | undefined)`;\n case 'VoidTypeAnnotation':\n return `void`;\n case 'PromiseTypeAnnotation':\n return `Promise`;\n case `FunctionTypeAnnotation`:\n return `((${type.params\n .map((param: FunctionParam) => {\n return `${param.name}${optionalSign(param)}: ${translateType(\n param.typeAnnotation,\n )}`;\n })\n .join(', ')}) => ${translateType(type.returnTypeAnnotation)})`;\n default:\n throw new Error(`Unhandled type in translateReturnType: ${returnType}`);\n }\n}\n\nfunction translateAlias(\n name: string,\n type: NativeModuleObjectTypeAnnotation,\n): string {\n return `\nexport interface ${name} {\n${type.properties\n .map((prop: ObjectProp) => {\n return ` ${prop.name}${optionalSign(prop)}: ${translateType(\n prop.typeAnnotation,\n )};`;\n })\n .join('\\n')}\n}\n`;\n}\n\nfunction tryGetConstantType(\n nativeModule: NativeModuleSchema,\n): NativeModuleObjectTypeAnnotation | undefined {\n const candidates = nativeModule.spec.methods.filter(\n prop => prop.name === 'getConstants',\n );\n if (candidates.length === 0) {\n return undefined;\n }\n\n const getConstant = candidates[0];\n const funcType =\n getConstant.typeAnnotation.type === 'NullableTypeAnnotation'\n ? getConstant.typeAnnotation.typeAnnotation\n : getConstant.typeAnnotation;\n if (\n funcType.params.length > 0 ||\n funcType.returnTypeAnnotation.type !== 'ObjectTypeAnnotation'\n ) {\n return undefined;\n }\n\n const constantType = funcType.returnTypeAnnotation;\n if (constantType.properties.length === 0) {\n return undefined;\n }\n\n return constantType;\n}\n\nfunction translateMethod(func: FunctionDecl): string {\n const funcType =\n func.typeAnnotation.type === 'NullableTypeAnnotation'\n ? func.typeAnnotation.typeAnnotation\n : func.typeAnnotation;\n\n return `\n ${func.name}(${funcType.params\n .map((param: FunctionParam) => {\n return `${param.name}${optionalSign(param)}: ${translateType(\n param.typeAnnotation,\n )}`;\n })\n .join(', ')})${optionalSign(func)}: ${translateType(\n funcType.returnTypeAnnotation,\n )}${\n funcType.returnTypeAnnotation.type === 'ObjectTypeAnnotation' ? '' : ';'\n }`;\n}\n\nexport function generateTypeScript(\n _libraryName: string,\n schema: SchemaType,\n _moduleSpecName: string,\n): FilesOutput {\n const files = new Map<string, string>();\n\n for (const moduleName of Object.keys(schema.modules)) {\n const nativeModule = schema.modules[moduleName];\n // from 0.65 facebook's react-native-codegen\n // the module name has the Native prefix comparing to 0.63\n // when reading files we provided\n const nativePrefix = 'Native';\n const preferredModuleName = moduleName.startsWith(nativePrefix)\n ? moduleName.substr(nativePrefix.length)\n : moduleName;\n\n if (nativeModule.type === 'NativeModule') {\n console.log(`Generating ${preferredModuleName}Spec.g.ts`);\n\n const aliasCode = Object.keys(nativeModule.aliasMap)\n .map(name => translateAlias(name, nativeModule.aliasMap[name]))\n .join('');\n\n const constantType = tryGetConstantType(nativeModule);\n const constantCode =\n constantType === undefined\n ? ''\n : ` getConstants(): ${translateType(constantType)}`;\n\n const methods = nativeModule.spec.methods.filter(\n prop => prop.name !== 'getConstants',\n );\n const membersCode = methods.map(translateMethod).join('');\n\n files.set(\n `${preferredModuleName}Spec.g.ts`,\n moduleTemplate\n .replace(/::_MODULE_ALIASED_STRUCTS_::/g, aliasCode)\n .replace(/::_MODULE_MEMBERS_::/g, constantCode + membersCode)\n .replace(/::_MODULE_NAME_::/g, preferredModuleName)\n .replace(\n /::_MODULE_GETTER_::/g,\n getOptionalTurboModule(nativeModule) ? 'get' : 'getEnforcing',\n ),\n );\n }\n }\n\n return files;\n}\n"]}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ * @format
5
+ */
6
+ import type { NativeModuleBaseTypeAnnotation, NativeModuleStringTypeAnnotation, NativeModuleFunctionTypeAnnotation, NativeModuleStringLiteralTypeAnnotation, StringLiteralUnionTypeAnnotation, UnsafeAnyTypeAnnotation, Nullable } from '@react-native/codegen/lib/CodegenSchema';
7
+ import { AliasMap } from './AliasManaging';
8
+ export type CppStringTypes = 'std::string' | 'std::wstring';
9
+ export interface CppCodegenOptions {
10
+ cppStringType: CppStringTypes;
11
+ }
12
+ export declare function translateFieldOrReturnType(type: Nullable<NativeModuleBaseTypeAnnotation | NativeModuleStringTypeAnnotation | NativeModuleFunctionTypeAnnotation | NativeModuleStringLiteralTypeAnnotation | StringLiteralUnionTypeAnnotation> | UnsafeAnyTypeAnnotation, aliases: AliasMap, baseAliasName: string, callerName: 'translateField' | 'translateReturnType', options: CppCodegenOptions): string;
13
+ export declare function translateField(type: Nullable<NativeModuleBaseTypeAnnotation>, aliases: AliasMap, baseAliasName: string, options: CppCodegenOptions): string;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ * @format
5
+ */
6
+ 'use strict';
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.translateField = exports.translateFieldOrReturnType = void 0;
9
+ const AliasManaging_1 = require("./AliasManaging");
10
+ function translateUnionReturnType(type, options) {
11
+ const memberType = type.memberType;
12
+ switch (type.memberType) {
13
+ case 'StringTypeAnnotation':
14
+ return options.cppStringType;
15
+ case 'NumberTypeAnnotation':
16
+ return 'double';
17
+ case 'ObjectTypeAnnotation':
18
+ return '::React::JSValue';
19
+ default:
20
+ throw new Error(`Unknown enum/union member type in translateReturnType: ${memberType}`);
21
+ }
22
+ }
23
+ // eslint-disable-next-line complexity
24
+ function translateFieldOrReturnType(type, aliases, baseAliasName, callerName, options) {
25
+ // avoid: Property 'type' does not exist on type 'never'
26
+ const returnType = type.type;
27
+ switch (type.type) {
28
+ case 'StringTypeAnnotation':
29
+ case 'StringLiteralTypeAnnotation':
30
+ case 'StringLiteralUnionTypeAnnotation':
31
+ return options.cppStringType;
32
+ case 'NumberTypeAnnotation':
33
+ case 'FloatTypeAnnotation':
34
+ case 'DoubleTypeAnnotation':
35
+ return 'double';
36
+ case 'Int32TypeAnnotation':
37
+ return 'int';
38
+ case 'BooleanTypeAnnotation':
39
+ return 'bool';
40
+ case 'ArrayTypeAnnotation':
41
+ if (type.elementType.type !== 'AnyTypeAnnotation') {
42
+ return `std::vector<${translateFieldOrReturnType(type.elementType, aliases, `${baseAliasName}_element`, callerName, options)}>`;
43
+ }
44
+ else {
45
+ return `::React::JSValueArray`;
46
+ }
47
+ case 'GenericObjectTypeAnnotation':
48
+ return '::React::JSValue';
49
+ case 'ObjectTypeAnnotation':
50
+ return (0, AliasManaging_1.getAnonymousAliasCppName)(aliases, baseAliasName, type);
51
+ case 'ReservedTypeAnnotation': {
52
+ // avoid: Property 'name' does not exist on type 'never'
53
+ const name = type.name;
54
+ // (#6597)
55
+ // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
56
+ if (name !== 'RootTag')
57
+ throw new Error(`Unknown reserved function: ${name} in ${callerName}`);
58
+ return 'double';
59
+ }
60
+ case 'TypeAliasTypeAnnotation':
61
+ return (0, AliasManaging_1.getAliasCppName)(type.name);
62
+ case 'NullableTypeAnnotation':
63
+ return `std::optional<${translateFieldOrReturnType(type.typeAnnotation, aliases, baseAliasName, callerName, options)}>`;
64
+ case 'FunctionTypeAnnotation':
65
+ case 'MixedTypeAnnotation':
66
+ return '';
67
+ case 'EnumDeclaration':
68
+ case 'UnionTypeAnnotation':
69
+ return translateUnionReturnType(type, options);
70
+ case 'AnyTypeAnnotation':
71
+ return '::React::JSValue?';
72
+ default:
73
+ throw new Error(`Unhandled type in ${callerName}: ${returnType}`);
74
+ }
75
+ }
76
+ exports.translateFieldOrReturnType = translateFieldOrReturnType;
77
+ function translateField(type, aliases, baseAliasName, options) {
78
+ return translateFieldOrReturnType(type, aliases, baseAliasName, 'translateField', options);
79
+ }
80
+ exports.translateField = translateField;
81
+ //# sourceMappingURL=ObjectTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ObjectTypes.js","sourceRoot":"","sources":["../../src/generators/ObjectTypes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,YAAY,CAAC;;;AAab,mDAIyB;AAQzB,SAAS,wBAAwB,CAC/B,IAAmE,EACnE,OAA0B;IAE1B,MAAM,UAAU,GAAG,IAAI,CAAC,UAAU,CAAC;IACnC,QAAQ,IAAI,CAAC,UAAU,EAAE;QACvB,KAAK,sBAAsB;YACzB,OAAO,OAAO,CAAC,aAAa,CAAC;QAC/B,KAAK,sBAAsB;YACzB,OAAO,QAAQ,CAAC;QAClB,KAAK,sBAAsB;YACzB,OAAO,kBAAkB,CAAC;QAC5B;YACE,MAAM,IAAI,KAAK,CACb,0DAA0D,UAAU,EAAE,CACvE,CAAC;KACL;AACH,CAAC;AAED,sCAAsC;AACtC,SAAgB,0BAA0B,CACxC,IAQ2B,EAC3B,OAAiB,EACjB,aAAqB,EACrB,UAAoD,EACpD,OAA0B;IAE1B,wDAAwD;IACxD,MAAM,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC;IAC7B,QAAQ,IAAI,CAAC,IAAI,EAAE;QACjB,KAAK,sBAAsB,CAAC;QAC5B,KAAK,6BAA6B,CAAC;QACnC,KAAK,kCAAkC;YACrC,OAAO,OAAO,CAAC,aAAa,CAAC;QAC/B,KAAK,sBAAsB,CAAC;QAC5B,KAAK,qBAAqB,CAAC;QAC3B,KAAK,sBAAsB;YACzB,OAAO,QAAQ,CAAC;QAClB,KAAK,qBAAqB;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,CAAC,CAAC;KACrE;AACH,CAAC;AA5ED,gEA4EC;AAED,SAAgB,cAAc,CAC5B,IAA8C,EAC9C,OAAiB,EACjB,aAAqB,EACrB,OAA0B;IAE1B,OAAO,0BAA0B,CAC/B,IAAI,EACJ,OAAO,EACP,aAAa,EACb,gBAAgB,EAChB,OAAO,CACR,CAAC;AACJ,CAAC;AAbD,wCAaC","sourcesContent":["/**\n * Copyright (c) Microsoft Corporation.\n * Licensed under the MIT License.\n * @format\n */\n\n'use strict';\n\nimport type {\n NativeModuleEnumDeclaration,\n NativeModuleBaseTypeAnnotation,\n NativeModuleUnionTypeAnnotation,\n NativeModuleStringTypeAnnotation,\n NativeModuleFunctionTypeAnnotation,\n NativeModuleStringLiteralTypeAnnotation,\n StringLiteralUnionTypeAnnotation,\n UnsafeAnyTypeAnnotation,\n Nullable,\n} from '@react-native/codegen/lib/CodegenSchema';\nimport {\n AliasMap,\n getAliasCppName,\n getAnonymousAliasCppName,\n} from './AliasManaging';\n\nexport type CppStringTypes = 'std::string' | 'std::wstring';\n\nexport interface CppCodegenOptions {\n cppStringType: CppStringTypes;\n}\n\nfunction translateUnionReturnType(\n type: NativeModuleEnumDeclaration | NativeModuleUnionTypeAnnotation,\n options: CppCodegenOptions,\n): string {\n const memberType = type.memberType;\n switch (type.memberType) {\n case 'StringTypeAnnotation':\n return options.cppStringType;\n case 'NumberTypeAnnotation':\n return 'double';\n case 'ObjectTypeAnnotation':\n return '::React::JSValue';\n default:\n throw new Error(\n `Unknown enum/union member type in translateReturnType: ${memberType}`,\n );\n }\n}\n\n// eslint-disable-next-line complexity\nexport function translateFieldOrReturnType(\n type:\n | Nullable<\n | NativeModuleBaseTypeAnnotation\n | NativeModuleStringTypeAnnotation\n | NativeModuleFunctionTypeAnnotation\n | NativeModuleStringLiteralTypeAnnotation\n | StringLiteralUnionTypeAnnotation\n >\n | UnsafeAnyTypeAnnotation,\n aliases: AliasMap,\n baseAliasName: string,\n callerName: 'translateField' | 'translateReturnType',\n options: CppCodegenOptions,\n): string {\n // avoid: Property 'type' does not exist on type 'never'\n const returnType = type.type;\n switch (type.type) {\n case 'StringTypeAnnotation':\n case 'StringLiteralTypeAnnotation':\n case 'StringLiteralUnionTypeAnnotation':\n return options.cppStringType;\n case 'NumberTypeAnnotation':\n case 'FloatTypeAnnotation':\n case 'DoubleTypeAnnotation':\n return 'double';\n case 'Int32TypeAnnotation':\n return 'int';\n case 'BooleanTypeAnnotation':\n return 'bool';\n case 'ArrayTypeAnnotation':\n if (type.elementType.type !== 'AnyTypeAnnotation') {\n return `std::vector<${translateFieldOrReturnType(\n type.elementType,\n aliases,\n `${baseAliasName}_element`,\n callerName,\n options,\n )}>`;\n } else {\n return `::React::JSValueArray`;\n }\n case 'GenericObjectTypeAnnotation':\n return '::React::JSValue';\n case 'ObjectTypeAnnotation':\n return getAnonymousAliasCppName(aliases, baseAliasName, type);\n case 'ReservedTypeAnnotation': {\n // avoid: Property 'name' does not exist on type 'never'\n const name = type.name;\n // (#6597)\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (name !== 'RootTag')\n throw new Error(`Unknown reserved function: ${name} in ${callerName}`);\n return 'double';\n }\n case 'TypeAliasTypeAnnotation':\n return getAliasCppName(type.name);\n case 'NullableTypeAnnotation':\n return `std::optional<${translateFieldOrReturnType(\n type.typeAnnotation,\n aliases,\n baseAliasName,\n callerName,\n options,\n )}>`;\n case 'FunctionTypeAnnotation':\n case 'MixedTypeAnnotation':\n return '';\n case 'EnumDeclaration':\n case 'UnionTypeAnnotation':\n return translateUnionReturnType(type, options);\n case 'AnyTypeAnnotation':\n return '::React::JSValue?';\n default:\n throw new Error(`Unhandled type in ${callerName}: ${returnType}`);\n }\n}\n\nexport function translateField(\n type: Nullable<NativeModuleBaseTypeAnnotation>,\n aliases: AliasMap,\n baseAliasName: string,\n options: CppCodegenOptions,\n): string {\n return translateFieldOrReturnType(\n type,\n aliases,\n baseAliasName,\n 'translateField',\n options,\n );\n}\n"]}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ * @format
5
+ */
6
+ import type { NamedShape, NativeModuleEventEmitterTypeAnnotation, NativeModuleParamTypeAnnotation, Nullable } from '@react-native/codegen/lib/CodegenSchema';
7
+ import { AliasMap } from './AliasManaging';
8
+ import type { CppCodegenOptions } from './ObjectTypes';
9
+ type NativeModuleParamShape = NamedShape<Nullable<NativeModuleParamTypeAnnotation>>;
10
+ export declare function translateSpecArgs(params: ReadonlyArray<NativeModuleParamShape>, aliases: AliasMap, baseAliasName: string, options: CppCodegenOptions): string[];
11
+ export declare function translateEventEmitterArgs(params: NativeModuleEventEmitterTypeAnnotation, aliases: AliasMap, baseAliasName: string, options: CppCodegenOptions): string;
12
+ export declare function translateArgs(params: ReadonlyArray<NativeModuleParamShape>, aliases: AliasMap, baseAliasName: string, options: CppCodegenOptions): string[];
13
+ export {};