-
Notifications
You must be signed in to change notification settings - Fork 112
/
Copy pathgenerateComposite.ts
345 lines (319 loc) · 11.7 KB
/
generateComposite.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import {
findNativeDependencies,
gitCli,
kax,
log,
nativeDepenciesVersionResolution,
NativeDependencies,
PackagePath,
readPackageJson,
shell,
yarn,
} from 'ern-core';
import { cleanupCompositeDir } from './cleanupCompositeDir';
import fs from 'fs-extra';
import path from 'path';
import semver from 'semver';
import _ from 'lodash';
import { CompositeGeneratorConfig } from './types';
import { v4 as uuid } from 'uuid';
import { addRNDepToPjson } from './addRNDepToPjson';
import { getNodeModuleVersion } from './getNodeModuleVersion';
import { addRNStartScriptToPjson } from './addRNStartScriptToPjson';
import { createIndexJs } from './createIndexJs';
import { createBaseCompositeImports } from './createBaseCompositeImports';
import { patchCompositeBabelRcRoots } from './patchCompositeBabelRcRoots';
import { patchMetro51AssetsBug } from './patchMetro51AssetsBug';
import { patchMetroAssetsBug } from './patchMetroAssetsBug';
import { patchMetroBabelEnv } from './patchMetroBabelEnv';
import { createBabelRc } from './createBabelRc';
import { applyYarnResolutions } from './applyYarnResolutions';
import { createMetroConfig } from './createMetroConfig';
import { createRNCliConfig } from './createRNCliConfig';
import { installPackages } from './installPackages';
import { installPackagesWithoutYarnLock } from './installPackagesWithoutYarnLock';
import { installExtraPackages } from './installExtraPackages';
import { createWatchmanConfig } from './createWatchmanConfig';
import Table from 'cli-table';
import os from 'os';
export async function generateComposite(config: CompositeGeneratorConfig) {
log.debug(`generateComposite config : ${JSON.stringify(config, null, 2)}`);
// Set env var ERN_BUGSNAG_CODE_BUNDLE_ID as a unique code bundle id for bugsnag
process.env.ERN_BUGSNAG_CODE_BUNDLE_ID =
process.env.ERN_BUGSNAG_CODE_BUNDLE_ID ?? uuid();
if (
config.miniApps.length === 0 &&
(config.jsApiImplDependencies || []).length === 0
) {
throw new Error(
`At least one MiniApp or JS API implementation is needed to generate a composite`,
);
}
return config.baseComposite
? generateCompositeFromBase(
config.miniApps,
config.outDir,
config.baseComposite,
{
extraJsDependencies: config.extraJsDependencies,
jsApiImplDependencies: config.jsApiImplDependencies,
},
)
: generateFullComposite(config.miniApps, config.outDir, {
extraJsDependencies: config.extraJsDependencies,
jsApiImplDependencies: config.jsApiImplDependencies,
metroExtraNodeModules: config.metroExtraNodeModules,
pathToYarnLock: config.pathToYarnLock,
resolutions: config.resolutions,
});
}
async function generateCompositeFromBase(
miniApps: PackagePath[],
outDir: string,
baseComposite: PackagePath,
{
extraJsDependencies = [],
jsApiImplDependencies,
}: {
extraJsDependencies?: PackagePath[];
jsApiImplDependencies?: PackagePath[];
} = {},
) {
if (baseComposite.isRegistryPath) {
throw new Error(
`baseComposite can only be a file or git path (${baseComposite})`,
);
}
if ((await fs.pathExists(outDir)) && (await fs.readdir(outDir)).length > 0) {
throw new Error(
`${outDir} directory exists and is not empty.
Composite output directory should either not exist (it will be created) or should be empty.`,
);
} else {
shell.mkdir('-p', outDir);
}
if (baseComposite.isGitPath) {
await gitCli().clone(baseComposite.basePath, outDir);
if (baseComposite.version) {
await gitCli(outDir).checkout(baseComposite.version);
}
} else {
shell.cp('-Rf', path.join(baseComposite.basePath, '{.*,*}'), outDir);
}
const jsPackages = jsApiImplDependencies
? [...miniApps, ...jsApiImplDependencies]
: miniApps;
shell.pushd(outDir);
try {
await installPackagesWithoutYarnLock({ cwd: outDir, jsPackages });
await createBaseCompositeImports({ cwd: outDir });
if (extraJsDependencies) {
await installExtraPackages({ cwd: outDir, extraJsDependencies });
}
} finally {
shell.popd();
}
}
async function generateFullComposite(
miniApps: PackagePath[],
outDir: string,
{
extraJsDependencies = [],
jsApiImplDependencies = [],
pathToYarnLock,
resolutions,
metroExtraNodeModules,
}: {
extraJsDependencies?: PackagePath[];
jsApiImplDependencies?: PackagePath[];
pathToYarnLock?: string;
resolutions?: { [pkg: string]: string };
metroExtraNodeModules?: { [pkg: string]: string };
} = {},
) {
if (await fs.pathExists(outDir)) {
await kax
.task('Cleaning up existing composite directory')
.run(cleanupCompositeDir(outDir));
} else {
shell.mkdir('-p', outDir);
}
shell.pushd(outDir);
const remoteMiniapps = miniApps.filter((p) => !p.isFilePath);
const localMiniApps = miniApps.filter((p) => p.isFilePath);
const localMiniAppsPaths = localMiniApps.map((m) => m.basePath);
// Explicitly add react as an extra node module in metro config
// Because it's not a native module, it will not be auto added
// later on as done for native modules
const extraNodeModules: { [pkg: string]: string } = {
react: path.join(outDir, 'node_modules/react'),
};
try {
if (remoteMiniapps.length > 0) {
// Only install remote miniapps coming from git/npm
await installPackages({
cwd: outDir,
jsApiImplDependencies,
miniApps: remoteMiniapps,
pathToYarnLock,
});
} else {
await yarn.init();
// We need to install react-native in top level composite as it won't
// transitively come with install of a miniapp in composite (we didn't
// `yarn add` any miniapps as they are all local).
// To know the version to install, we will just have a peak to one of
// the miniapps, given that react native version is aligned across all.
const pJson = await readPackageJson(localMiniAppsPaths[0]);
const miniAppRnVersion = pJson.dependencies['react-native'];
extraJsDependencies.push(
PackagePath.fromString(`react-native@${miniAppRnVersion}`),
);
// We also need to keep react in the composite project root as
// keeping it outside the root will lead to isses with versions of
// react native <= 0.60.0 but also cause some side effect with
// more recent react native version (one we identified has to do
// with react hooks causing a red screen if react is not part of
// the project root)
const miniAppReactVersion = pJson.dependencies.react;
extraJsDependencies.push(
PackagePath.fromString(`react@${miniAppReactVersion}`),
);
// Also add latest version of the bridge
extraJsDependencies.push(
PackagePath.fromString('react-native-electrode-bridge'),
);
extraJsDependencies = [...extraJsDependencies, ...jsApiImplDependencies];
}
await addRNStartScriptToPjson({ cwd: outDir });
await createIndexJs({
cwd: outDir,
jsApiImplDependencies,
miniApps,
});
await createWatchmanConfig({ cwd: outDir });
await kax.task('Adding extra packages to the composite').run(
installExtraPackages({
cwd: outDir,
extraJsDependencies: [
PackagePath.fromString('ern-bundle-store-metro-asset-plugin'),
PackagePath.fromString('babel-plugin-module-resolver'),
PackagePath.fromString('react-native-svg-transformer'),
...extraJsDependencies,
],
}),
);
if (resolutions) {
// This function should be be called prior to applying
// any file patches in node_modules, as it will run
// `yarn install`, thus potentially clearing any previously
// applied patches
await applyYarnResolutions({ cwd: outDir, resolutions });
}
let blacklistRe: RegExp[] = [];
if (localMiniApps.length > 0) {
// If we have some local miniapps we need to do a few extra things.
// Basically, we need to identify all native modules used by the local
// miniapps, and build proper blacklistRe / extraNodeModules metro
// config values.
// What we want here, is for extraNodeModules to contain a local path
// to each native module, and blacklist all other existing paths to
// the native module to avoid duplication conflicts.
const localMiniAppsNodeModulePaths = localMiniAppsPaths.map((p) =>
path.join(p, 'node_modules'),
);
const allNativeDeps: NativeDependencies = await findNativeDependencies([
path.join(outDir, 'node_modules'),
...localMiniAppsNodeModulePaths,
]);
// Exclude api/api impls as they are not native modules
allNativeDeps.apis = [];
allNativeDeps.nativeApisImpl = [];
const dedupedNativeModules =
nativeDepenciesVersionResolution.resolveNativeDependenciesVersionsEx(
allNativeDeps,
);
if (dedupedNativeModules.pluginsWithMismatchingVersions.length > 0) {
let errorMsg = `Mismatching native module versions detected.
Native module(s) versions should be aligned across miniapps.
You should resolve the following version mismatches prior to retrying.${os.EOL}`;
for (const pkgName of dedupedNativeModules.pluginsWithMismatchingVersions) {
const mismatchingPkgs = allNativeDeps.all.filter(
(x) => x.name === pkgName,
);
const table = new Table({
head: ['path', 'version'],
});
mismatchingPkgs.forEach((pkg) =>
table.push([pkg.fullPath, pkg.version]),
);
errorMsg += `${table.toString()}${os.EOL}`;
}
throw new Error(errorMsg);
}
const allNativeModules = [
...allNativeDeps.thirdPartyInManifest,
...allNativeDeps.thirdPartyNotInManifest,
];
dedupedNativeModules.resolved.forEach((m) => {
extraNodeModules[m.name!] = m.basePath;
});
blacklistRe = _.difference(
allNativeModules.map((d) => d.basePath),
dedupedNativeModules.resolved.map((d) => d.basePath),
)
.concat(
...localMiniAppsPaths.map((p) => path.join(p, 'node_modules/react')),
)
.map(
(l) =>
new RegExp(
os.platform() === 'win32'
? `${l}\\.*`.replace(/\\/g, '\\\\')
: `${l}\/.*`,
),
);
}
if (metroExtraNodeModules) {
Object.keys(metroExtraNodeModules).map((value) => {
const moduleValue = metroExtraNodeModules[value];
extraNodeModules[value] = path.isAbsolute(moduleValue)
? moduleValue
: path.join(outDir, 'node_modules', moduleValue);
});
}
await patchCompositeBabelRcRoots({
cwd: outDir,
extraPaths: localMiniAppsPaths,
});
await createBabelRc({ cwd: outDir, extraPaths: localMiniAppsPaths });
const rnVersion = await getNodeModuleVersion({
cwd: outDir,
name: 'react-native',
});
await createMetroConfig({
blacklistRe,
cwd: outDir,
extraNodeModules,
reactNativeVersion: rnVersion,
watchFolders: localMiniAppsPaths,
});
if (semver.gte(rnVersion, '0.57.0')) {
await createRNCliConfig({ cwd: outDir });
}
await addRNDepToPjson(outDir, rnVersion);
if (semver.lt(rnVersion, '0.60.0')) {
await patchMetro51AssetsBug({ cwd: outDir });
}
if (localMiniApps.length > 0) {
// We only need to apply this patch if there is at least one local
// MiniApp, as the bug it fixes only happens when dealing with
// a monorepo like configuration. Such a configuration is only created
// when at least one local MiniApp is present in the composite
await patchMetroAssetsBug({ cwd: outDir });
}
await patchMetroBabelEnv({ cwd: outDir });
} finally {
shell.popd();
}
}