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

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 +1135 -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 +468 -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 +165 -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 +412 -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
package/src/index.ts ADDED
@@ -0,0 +1,412 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ * Licensed under the MIT License.
4
+ *
5
+ * @format
6
+ */
7
+
8
+ import path from 'path';
9
+ import fs from '@react-native-windows/fs';
10
+ import globby from 'globby';
11
+ import type {CppStringTypes} from './generators/GenerateNM2';
12
+ import {createNM2Generator} from './generators/GenerateNM2';
13
+ import {createComponentGenerator} from './generators/GenerateComponentWindows';
14
+ import {
15
+ generateTypeScript,
16
+ setOptionalTurboModule,
17
+ } from './generators/GenerateTypeScript';
18
+ import type {SchemaType} from '@react-native/codegen/lib/CodegenSchema';
19
+ import type {Parser} from '@react-native/codegen/lib/parsers/parser';
20
+
21
+ export type {CppStringTypes} from './generators/GenerateNM2';
22
+
23
+ // Load @react-native/codegen from react-native
24
+ const rnPath = path.dirname(require.resolve('react-native/package.json'));
25
+ const rncodegenPath = path.dirname(
26
+ require.resolve('@react-native/codegen/package.json', {paths: [rnPath]}),
27
+ );
28
+
29
+ function getParser(isTypeScript: boolean): Parser {
30
+ if (isTypeScript) {
31
+ const fp = require(path.resolve(
32
+ rncodegenPath,
33
+ 'lib/parsers/typescript/parser',
34
+ ));
35
+ return new fp.TypeScriptParser();
36
+ } else {
37
+ const fp = require(path.resolve(rncodegenPath, 'lib/parsers/flow/parser'));
38
+ return new fp.FlowParser();
39
+ }
40
+ }
41
+
42
+ const schemaValidator = require(path.resolve(
43
+ rncodegenPath,
44
+ 'lib/SchemaValidator',
45
+ ));
46
+
47
+ export interface SharedOptions {
48
+ libraryName: string;
49
+ methodOnly: boolean;
50
+ modulesCxx: boolean;
51
+ modulesTypeScriptTypes: boolean;
52
+ modulesWindows: boolean;
53
+ componentsWindows: boolean;
54
+ internalComponents: boolean;
55
+ namespace: string;
56
+ outputDirectory: string;
57
+ cppStringType: CppStringTypes;
58
+ separateDataTypes: boolean;
59
+ }
60
+
61
+ interface Options extends SharedOptions {
62
+ moduleSpecName: string;
63
+ schema: SchemaType;
64
+ }
65
+
66
+ interface Config {
67
+ generators: any[] /*Generators[]*/;
68
+ test?: boolean;
69
+ }
70
+
71
+ function normalizeFileMap(
72
+ map: Map<string, string>,
73
+ outputDir: string,
74
+ outMap: Map<string, string>,
75
+ ): void {
76
+ for (const [fileName, contents] of map) {
77
+ const location = path.join(outputDir, fileName);
78
+ outMap.set(path.normalize(location), contents);
79
+ }
80
+ }
81
+
82
+ function checkFilesForChanges(
83
+ map: Map<string, string>,
84
+ outputDir: string,
85
+ ): boolean {
86
+ let hasChanges = false;
87
+
88
+ outputDir = path.resolve(outputDir);
89
+ const globbyDir = outputDir.replace(/\\/g, '/');
90
+ const allExistingFiles = globby
91
+ .sync([`${globbyDir}/**`, `${globbyDir}/**/.*`], {absolute: true})
92
+ .map(_ => path.normalize(_));
93
+ const allGeneratedFiles = [...map.keys()].map(_ => path.normalize(_)).sort();
94
+
95
+ if (
96
+ allExistingFiles.length !== allGeneratedFiles.length ||
97
+ !allGeneratedFiles.every(filepath =>
98
+ allExistingFiles.includes(
99
+ path.normalize(path.resolve(process.cwd(), filepath)),
100
+ ),
101
+ )
102
+ )
103
+ return true;
104
+
105
+ for (const [fileName, contents] of map) {
106
+ if (!fs.existsSync(fileName)) {
107
+ hasChanges = true;
108
+ continue;
109
+ }
110
+
111
+ const currentContents = fs.readFileSync(fileName, 'utf8');
112
+ // The current file may be saved using crlf, in which case the new lines may differ from the new output
113
+ if (currentContents.replaceAll('\r\n', '\n') !== contents) {
114
+ console.log(`- ${fileName} has changed`);
115
+ hasChanges = true;
116
+ continue;
117
+ }
118
+ }
119
+
120
+ return hasChanges;
121
+ }
122
+
123
+ function writeMapToFiles(map: Map<string, string>, outputDir: string) {
124
+ let success = true;
125
+
126
+ outputDir = path.resolve(outputDir);
127
+ const globbyDir = outputDir.replace(/\\/g, '/');
128
+
129
+ // This ensures that we delete any generated files from modules that have been deleted
130
+ const allExistingFiles = globby.sync(
131
+ [`${globbyDir}/**`, `${globbyDir}/**/.*`],
132
+ {absolute: true},
133
+ );
134
+
135
+ const allGeneratedFiles = [...map.keys()].map(_ => path.normalize(_)).sort();
136
+ allExistingFiles.forEach(existingFile => {
137
+ if (!allGeneratedFiles.includes(path.normalize(existingFile))) {
138
+ console.log('Deleting ', existingFile);
139
+ fs.unlinkSync(existingFile);
140
+ }
141
+ });
142
+
143
+ for (const [fileName, contents] of map) {
144
+ try {
145
+ fs.mkdirSync(path.dirname(fileName), {recursive: true});
146
+
147
+ if (fs.existsSync(fileName)) {
148
+ const currentContents = fs.readFileSync(fileName, 'utf8');
149
+ // Don't update the files if there are no changes as this breaks incremental builds
150
+ // The current file may be saved using crlf, in which case the new lines may differ from the new output
151
+ if (currentContents.replaceAll('\r\n', '\n') === contents) {
152
+ continue;
153
+ }
154
+ }
155
+
156
+ console.log('Writing ', fileName);
157
+ fs.writeFileSync(fileName, contents);
158
+ } catch (error) {
159
+ success = false;
160
+ console.error(`Failed to write ${fileName} to ${fileName}`, error);
161
+ }
162
+ }
163
+
164
+ return success;
165
+ }
166
+
167
+ export function parseFile(filename: string): SchemaType {
168
+ try {
169
+ const isTypeScript =
170
+ path.extname(filename) === '.ts' || path.extname(filename) === '.tsx';
171
+ const contents = fs.readFileSync(filename, 'utf8');
172
+ const schema = getParser(isTypeScript).parseString(contents, filename);
173
+ // there will be at most one turbo module per file
174
+ const moduleName = Object.keys(schema.modules)[0];
175
+ if (moduleName) {
176
+ const spec = schema.modules[moduleName];
177
+ if (spec.type === 'NativeModule') {
178
+ if (contents) {
179
+ // This is a temporary implementation until such information is added to the schema in facebook/react-native
180
+ if (contents.includes('TurboModuleRegistry.get<')) {
181
+ setOptionalTurboModule(spec, true);
182
+ } else if (contents.includes('TurboModuleRegistry.getEnforcing<')) {
183
+ setOptionalTurboModule(spec, false);
184
+ }
185
+ }
186
+ }
187
+ }
188
+ return schema;
189
+ } catch (e) {
190
+ if (e instanceof Error) {
191
+ e.message = `(${filename}): ${e.message}`;
192
+ }
193
+ throw e;
194
+ }
195
+ }
196
+
197
+ export function combineSchemas(files: string[]): SchemaType {
198
+ return files.reduce(
199
+ (merged, filename) => {
200
+ const contents = fs.readFileSync(filename, 'utf8');
201
+ if (
202
+ contents &&
203
+ (/export\s+default\s+\(?codegenNativeComponent</.test(contents) ||
204
+ contents.includes('extends TurboModule'))
205
+ ) {
206
+ const schema = parseFile(filename);
207
+ merged.modules = {...merged.modules, ...schema.modules};
208
+ }
209
+ return merged;
210
+ },
211
+ {modules: {}},
212
+ );
213
+ }
214
+
215
+ export function generate(
216
+ {
217
+ libraryName,
218
+ methodOnly,
219
+ modulesCxx,
220
+ modulesTypeScriptTypes,
221
+ modulesWindows,
222
+ internalComponents,
223
+ componentsWindows,
224
+ namespace,
225
+ outputDirectory,
226
+ cppStringType,
227
+ separateDataTypes,
228
+ moduleSpecName,
229
+ schema,
230
+ }: Options,
231
+ {/*generators,*/ test}: Config,
232
+ ): boolean {
233
+ schemaValidator.validate(schema);
234
+
235
+ const componentOutputdir = path.join(
236
+ outputDirectory,
237
+ 'react/components',
238
+ libraryName,
239
+ );
240
+
241
+ const generatedFiles = new Map<string, string>();
242
+
243
+ generatedFiles.set(
244
+ path.join(outputDirectory, '.clang-format'),
245
+ 'DisableFormat: true\nSortIncludes: false',
246
+ );
247
+
248
+ const generateNM2 = createNM2Generator({
249
+ methodOnly,
250
+ namespace,
251
+ cppStringType,
252
+ separateDataTypes,
253
+ });
254
+
255
+ const generateJsiModuleH = require(path.resolve(
256
+ rncodegenPath,
257
+ 'lib/generators/modules/GenerateModuleH',
258
+ )).generate;
259
+ const generatorPropsH = require(path.resolve(
260
+ rncodegenPath,
261
+ 'lib/generators/components/GeneratePropsH',
262
+ )).generate;
263
+ const generatorPropsCPP = require(path.resolve(
264
+ rncodegenPath,
265
+ 'lib/generators/components/GeneratePropsCpp',
266
+ )).generate;
267
+ const generatorShadowNodeH = require(path.resolve(
268
+ rncodegenPath,
269
+ 'lib/generators/components/GenerateShadowNodeH',
270
+ )).generate;
271
+ const generatorShadowNodeCPP = require(path.resolve(
272
+ rncodegenPath,
273
+ 'lib/generators/components/GenerateShadowNodeCpp',
274
+ )).generate;
275
+ const generatorComponentDescriptorH = require(path.resolve(
276
+ rncodegenPath,
277
+ 'lib/generators/components/GenerateComponentDescriptorH',
278
+ )).generate;
279
+ const generatorEventEmitterH = require(path.resolve(
280
+ rncodegenPath,
281
+ 'lib/generators/components/GenerateEventEmitterH',
282
+ )).generate;
283
+ const generatorEventEmitterCPP = require(path.resolve(
284
+ rncodegenPath,
285
+ 'lib/generators/components/GenerateEventEmitterCpp',
286
+ )).generate;
287
+ const generatorStateCPP = require(path.resolve(
288
+ rncodegenPath,
289
+ 'lib/generators/components/GenerateStateCpp',
290
+ )).generate;
291
+ const generatorStateH = require(path.resolve(
292
+ rncodegenPath,
293
+ 'lib/generators/components/GenerateStateH',
294
+ )).generate;
295
+
296
+ const moduleGenerators = [];
297
+
298
+ if (modulesWindows) {
299
+ moduleGenerators.push(generateNM2);
300
+ }
301
+
302
+ if (modulesCxx) {
303
+ moduleGenerators.push(generateJsiModuleH);
304
+ }
305
+
306
+ if (modulesTypeScriptTypes) {
307
+ moduleGenerators.push(generateTypeScript);
308
+ }
309
+
310
+ moduleGenerators.forEach(generator => {
311
+ const generated: Map<string, string> = generator(
312
+ libraryName,
313
+ schema,
314
+ moduleSpecName,
315
+ );
316
+ normalizeFileMap(generated, outputDirectory, generatedFiles);
317
+ });
318
+
319
+ if (
320
+ Object.keys(schema.modules).some(
321
+ moduleName => schema.modules[moduleName].type === 'Component',
322
+ )
323
+ ) {
324
+ const componentGenerators = [];
325
+
326
+ if (internalComponents) {
327
+ componentGenerators.push(
328
+ generatorComponentDescriptorH,
329
+ generatorEventEmitterCPP,
330
+ generatorEventEmitterH,
331
+ generatorPropsCPP,
332
+ generatorPropsH,
333
+ generatorShadowNodeCPP,
334
+ generatorShadowNodeH,
335
+ generatorStateCPP,
336
+ generatorStateH,
337
+ );
338
+ }
339
+
340
+ if (componentsWindows) {
341
+ const generateComponentWindows = createComponentGenerator({
342
+ namespace,
343
+ cppStringType,
344
+ });
345
+
346
+ componentGenerators.push(generateComponentWindows);
347
+ }
348
+
349
+ componentGenerators.forEach(generator => {
350
+ const generated: Map<string, string> = generator(
351
+ libraryName,
352
+ schema,
353
+ moduleSpecName,
354
+ );
355
+ normalizeFileMap(generated, componentOutputdir, generatedFiles);
356
+ });
357
+ }
358
+
359
+ if (test === true) {
360
+ return checkFilesForChanges(generatedFiles, outputDirectory);
361
+ }
362
+
363
+ return writeMapToFiles(generatedFiles, outputDirectory);
364
+ }
365
+
366
+ export interface CodeGenOptions extends SharedOptions {
367
+ file?: string;
368
+ files?: string[];
369
+ test: boolean;
370
+ }
371
+
372
+ export function runCodeGen(options: CodeGenOptions): boolean {
373
+ if (!options.file && !options.files)
374
+ throw new Error('Must specify file or files option');
375
+
376
+ const schema = options.file
377
+ ? parseFile(options.file)
378
+ : combineSchemas(globby.sync(options.files!));
379
+
380
+ const libraryName = options.libraryName;
381
+ const moduleSpecName = 'moduleSpecName';
382
+ const {
383
+ methodOnly,
384
+ modulesCxx,
385
+ modulesTypeScriptTypes,
386
+ modulesWindows,
387
+ componentsWindows,
388
+ internalComponents,
389
+ namespace,
390
+ outputDirectory,
391
+ cppStringType,
392
+ separateDataTypes,
393
+ } = options;
394
+ return generate(
395
+ {
396
+ libraryName,
397
+ methodOnly,
398
+ modulesCxx,
399
+ modulesTypeScriptTypes,
400
+ modulesWindows,
401
+ componentsWindows,
402
+ internalComponents,
403
+ namespace,
404
+ outputDirectory,
405
+ cppStringType,
406
+ separateDataTypes,
407
+ moduleSpecName,
408
+ schema,
409
+ },
410
+ {generators: [], test: options.test},
411
+ );
412
+ }
package/.eslintrc.js DELETED
@@ -1,4 +0,0 @@
1
- module.exports = {
2
- extends: ['@rnw-scripts'],
3
- parserOptions: {tsconfigRootDir : __dirname},
4
- };
@@ -1,23 +0,0 @@
1
- {
2
- // Use IntelliSense to learn about possible attributes.
3
- // Hover to view descriptions of existing attributes.
4
- // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5
- "version": "0.2.0",
6
- "configurations": [
7
- {
8
- "name": "vscode-jest-tests",
9
- "type": "node",
10
- "request": "launch",
11
- "runtimeArgs": [
12
- "--inspect-brk",
13
- "../../node_modules/jest/bin/jest.js",
14
- "--runInBand",
15
- "--config",
16
- "../@rnw-scripts/jest-debug-config/jest.debug.config.js",
17
- ],
18
- "console": "integratedTerminal",
19
- "internalConsoleOptions": "neverOpen",
20
- "port": 9229,
21
- },
22
- ]
23
- }