-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
withDevLauncher.ts
306 lines (272 loc) · 11 KB
/
withDevLauncher.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
import {
ConfigPlugin,
createRunOncePlugin,
ExportedConfigWithProps,
WarningAggregator,
withDangerousMod,
withMainActivity,
} from '@expo/config-plugins';
import { ExpoConfig } from '@expo/config-types';
import fs from 'fs';
import path from 'path';
import semver from 'semver';
import { InstallationPage } from './constants';
import { resolveExpoUpdatesVersion } from './resolveExpoUpdatesVersion';
import { addLines, replaceLine } from './utils';
import { withDevLauncherAppDelegate } from './withDevLauncherAppDelegate';
const pkg = require('expo-dev-launcher/package.json');
const DEV_LAUNCHER_ANDROID_IMPORT = 'expo.modules.devlauncher.DevLauncherController';
const DEV_LAUNCHER_UPDATES_ANDROID_IMPORT = 'expo.modules.updates.UpdatesDevLauncherController';
const DEV_LAUNCHER_ON_NEW_INTENT = [
'',
' @Override',
' public void onNewIntent(Intent intent) {',
' super.onNewIntent(intent);',
' }',
'',
].join('\n');
const DEV_LAUNCHER_HANDLE_INTENT = [
' if (DevLauncherController.tryToHandleIntent(this, intent)) {',
' return;',
' }',
].join('\n');
const DEV_LAUNCHER_WRAPPED_ACTIVITY_DELEGATE = (activityDelegateDeclaration: string) =>
`DevLauncherController.wrapReactActivityDelegate(this, () -> ${activityDelegateDeclaration})`;
const DEV_LAUNCHER_ANDROID_INIT = 'DevLauncherController.initialize(this, getReactNativeHost());';
const DEV_LAUNCHER_UPDATES_ANDROID_INIT = `if (BuildConfig.DEBUG) {
DevLauncherController.getInstance().setUpdatesInterface(UpdatesDevLauncherController.initialize(this));
}`;
const DEV_LAUNCHER_UPDATES_DEVELOPER_SUPPORT =
'return DevLauncherController.getInstance().getUseDeveloperSupport();';
const DEV_LAUNCHER_JS_REGISTER_ERROR_HANDLERS = `import 'expo-dev-client'`;
const DEV_LAUNCHER_JS_REGISTER_ERROR_HANDLERS_VIA_LAUNCHER = `import 'expo-dev-launcher'`;
async function readFileAsync(path: string): Promise<string> {
return fs.promises.readFile(path, 'utf8');
}
async function saveFileAsync(path: string, content: string): Promise<void> {
return fs.promises.writeFile(path, content, 'utf8');
}
function findClosingBracketMatchIndex(str: string, pos: number) {
if (str[pos] !== '(') {
throw new Error("No '(' at index " + pos);
}
let depth = 1;
for (let i = pos + 1; i < str.length; i++) {
switch (str[i]) {
case '(':
depth++;
break;
case ')':
if (--depth === 0) {
return i;
}
break;
}
}
return -1; // No matching closing parenthesis
}
const replaceBetween = (origin: string, startIndex: number, endIndex: number, insertion: string) =>
`${origin.substring(0, startIndex)}${insertion}${origin.substring(endIndex)}`;
function addJavaImports(javaSource: string, javaImports: string[]): string {
const lines = javaSource.split('\n');
const lineIndexWithPackageDeclaration = lines.findIndex((line) => line.match(/^package .*;$/));
for (const javaImport of javaImports) {
if (!javaSource.includes(javaImport)) {
const importStatement = `import ${javaImport};`;
lines.splice(lineIndexWithPackageDeclaration + 1, 0, importStatement);
}
}
return lines.join('\n');
}
async function editMainApplication(
config: ExportedConfigWithProps,
action: (mainApplication: string) => string
): Promise<void> {
const mainApplicationPath = path.join(
config.modRequest.platformProjectRoot,
'app',
'src',
'main',
'java',
...config.android!.package!.split('.'),
'MainApplication.java'
);
try {
const mainApplication = action(await readFileAsync(mainApplicationPath));
return await saveFileAsync(mainApplicationPath, mainApplication);
} catch (e) {
WarningAggregator.addWarningAndroid(
'expo-dev-launcher',
`Couldn't modify MainApplication.java - ${e}.
See the expo-dev-client installation instructions to modify your MainApplication.java manually: ${InstallationPage}`
);
}
}
async function editPodfile(config: ExportedConfigWithProps, action: (podfile: string) => string) {
const podfilePath = path.join(config.modRequest.platformProjectRoot, 'Podfile');
try {
const podfile = action(await readFileAsync(podfilePath));
return await saveFileAsync(podfilePath, podfile);
} catch (e) {
WarningAggregator.addWarningIOS(
'expo-dev-launcher',
`Couldn't modify AppDelegate.m - ${e}.
See the expo-dev-client installation instructions to modify your AppDelegate.m manually: ${InstallationPage}`
);
}
}
async function editIndex(config: ExportedConfigWithProps, action: (index: string) => string) {
const indexPath = path.join(config.modRequest.projectRoot, 'index.js');
try {
const index = action(await readFileAsync(indexPath));
return await saveFileAsync(indexPath, index);
} catch (e) {
WarningAggregator.addWarningIOS(
'expo-dev-launcher',
`Couldn't modify index.js - ${e}.
See the expo-dev-client installation instructions to modify your index.js manually: ${InstallationPage}`
);
}
}
const withDevLauncherApplication: ConfigPlugin = (config) => {
return withDangerousMod(config, [
'android',
async (config) => {
await editMainApplication(config, (mainApplication) => {
mainApplication = addJavaImports(mainApplication, [DEV_LAUNCHER_ANDROID_IMPORT]);
mainApplication = addLines(mainApplication, 'initializeFlipper\\(this', 0, [
` ${DEV_LAUNCHER_ANDROID_INIT}`,
]);
let expoUpdatesVersion;
try {
expoUpdatesVersion = resolveExpoUpdatesVersion(config.modRequest.projectRoot);
} catch (e) {
WarningAggregator.addWarningAndroid(
'expo-dev-launcher',
`Failed to check compatibility with expo-updates - ${e}`
);
}
if (expoUpdatesVersion && semver.gt(expoUpdatesVersion, '0.6.0')) {
mainApplication = addJavaImports(mainApplication, [DEV_LAUNCHER_UPDATES_ANDROID_IMPORT]);
mainApplication = addLines(mainApplication, 'initializeFlipper\\(this', 0, [
` ${DEV_LAUNCHER_UPDATES_ANDROID_INIT}`,
]);
mainApplication = replaceLine(
mainApplication,
'return BuildConfig.DEBUG;',
` ${DEV_LAUNCHER_UPDATES_DEVELOPER_SUPPORT}`
);
}
return mainApplication;
});
return config;
},
]);
};
export function modifyJavaMainActivity(content: string): string {
content = addJavaImports(content, [DEV_LAUNCHER_ANDROID_IMPORT, 'android.content.Intent']);
if (!content.includes('onNewIntent')) {
const lines = content.split('\n');
const onCreateIndex = lines.findIndex((line) => line.includes('public class MainActivity'));
lines.splice(onCreateIndex + 1, 0, DEV_LAUNCHER_ON_NEW_INTENT);
content = lines.join('\n');
}
if (!content.includes(DEV_LAUNCHER_HANDLE_INTENT)) {
content = addLines(content, /super\.onNewIntent\(intent\)/, 0, [DEV_LAUNCHER_HANDLE_INTENT]);
}
if (!content.includes('DevLauncherController.wrapReactActivityDelegate')) {
const activityDelegateMatches = Array.from(
content.matchAll(/new ReactActivityDelegate(Wrapper)/g)
);
if (activityDelegateMatches.length !== 1) {
WarningAggregator.addWarningAndroid(
'expo-dev-launcher',
`Failed to wrap 'ReactActivityDelegate'
See the expo-dev-client installation instructions to modify your MainActivity.java manually: ${InstallationPage}`
);
return content;
}
const activityDelegateMatch = activityDelegateMatches[0];
const matchIndex = activityDelegateMatch.index!;
const openingBracketIndex = matchIndex + activityDelegateMatch[0].length; // next character after `new ReactActivityDelegateWrapper`
const closingBracketIndex = findClosingBracketMatchIndex(content, openingBracketIndex);
const reactActivityDelegateDeclaration = content.substring(matchIndex, closingBracketIndex + 1);
content = replaceBetween(
content,
matchIndex,
closingBracketIndex + 1,
DEV_LAUNCHER_WRAPPED_ACTIVITY_DELEGATE(reactActivityDelegateDeclaration)
);
}
return content;
}
const withDevLauncherActivity: ConfigPlugin = (config) => {
return withMainActivity(config, (config) => {
if (config.modResults.language === 'java') {
config.modResults.contents = modifyJavaMainActivity(config.modResults.contents);
} else {
WarningAggregator.addWarningAndroid(
'expo-dev-launcher',
`Cannot automatically configure MainActivity if it's not java.
See the expo-dev-client installation instructions to modify your MainActivity manually: ${InstallationPage}`
);
}
return config;
});
};
const withDevLauncherPodfile: ConfigPlugin = (config) => {
return withDangerousMod(config, [
'ios',
async (config) => {
await editPodfile(config, (podfile) => {
// replace all iOS versions below 12
podfile = podfile.replace(/platform :ios, '((\d\.0)|(1[0-1].0))'/, "platform :ios, '12.0'");
// Match both variations of Ruby config:
// unknown: pod 'expo-dev-launcher', path: '../node_modules/expo-dev-launcher', :configurations => :debug
// Rubocop: pod 'expo-dev-launcher', path: '../node_modules/expo-dev-launcher', configurations: :debug
if (
!podfile.match(
/pod ['"]expo-dev-launcher['"],\s?path: ['"][^'"]*node_modules\/expo-dev-launcher['"],\s?:?configurations:?\s(?:=>\s)?:debug/
)
) {
const packagePath = path.dirname(require.resolve('expo-dev-launcher/package.json'));
const relativePath = path.relative(config.modRequest.platformProjectRoot, packagePath);
podfile = addLines(podfile, 'use_react_native', 0, [
` pod 'expo-dev-launcher', path: '${relativePath}', :configurations => :debug`,
]);
}
return podfile;
});
return config;
},
]);
};
const withErrorHandling: ConfigPlugin = (config) => {
const injectErrorHandlers = async (config: ExportedConfigWithProps) => {
await editIndex(config, (index) => {
if (
!index.includes(DEV_LAUNCHER_JS_REGISTER_ERROR_HANDLERS) &&
!index.includes(DEV_LAUNCHER_JS_REGISTER_ERROR_HANDLERS_VIA_LAUNCHER)
) {
index = DEV_LAUNCHER_JS_REGISTER_ERROR_HANDLERS + ';\n\n' + index;
}
return index;
});
return config;
};
// We need to run the same task twice to ensure it will work on both platforms,
// because if someone runs `expo run:ios`, it will trigger only dangerous mode for that specific platform.
// Note: after the first execution, the second one won't change anything.
config = withDangerousMod(config, ['android', injectErrorHandlers]);
config = withDangerousMod(config, ['ios', injectErrorHandlers]);
return config;
};
const withDevLauncher = (config: ExpoConfig) => {
config = withDevLauncherActivity(config);
config = withDevLauncherApplication(config);
config = withDevLauncherPodfile(config);
config = withDevLauncherAppDelegate(config);
config = withErrorHandling(config);
return config;
};
export default createRunOncePlugin(withDevLauncher, pkg.name, pkg.version);