@capacitor/cli 4.0.1-alpha.0 → 4.0.2-nightly-76f28e70.0

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.
@@ -0,0 +1,653 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.migrateCommand = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const utils_fs_1 = require("@ionic/utils-fs");
6
+ const path_1 = require("path");
7
+ const rimraf_1 = tslib_1.__importDefault(require("rimraf"));
8
+ const common_1 = require("../common");
9
+ const errors_1 = require("../errors");
10
+ const log_1 = require("../log");
11
+ const fs_1 = require("../util/fs");
12
+ const subprocess_1 = require("../util/subprocess");
13
+ const template_1 = require("../util/template");
14
+ const xml_1 = require("../util/xml");
15
+ // eslint-disable-next-line prefer-const
16
+ let allDependencies = {};
17
+ const libs = [
18
+ '@capacitor/core',
19
+ '@capacitor/cli',
20
+ '@capacitor/ios',
21
+ '@capacitor/android',
22
+ ];
23
+ const plugins = [
24
+ '@capacitor/action-sheet',
25
+ '@capacitor/app',
26
+ '@capacitor/app-launcher',
27
+ '@capacitor/browser',
28
+ '@capacitor/camera',
29
+ '@capacitor/clipboard',
30
+ '@capacitor/device',
31
+ '@capacitor/dialog',
32
+ '@capacitor/filesystem',
33
+ '@capacitor/geolocation',
34
+ '@capacitor/google-maps',
35
+ '@capacitor/haptics',
36
+ '@capacitor/keyboard',
37
+ '@capacitor/local-notifications',
38
+ '@capacitor/motion',
39
+ '@capacitor/network',
40
+ '@capacitor/preferences',
41
+ '@capacitor/push-notifications',
42
+ '@capacitor/screen-reader',
43
+ '@capacitor/share',
44
+ '@capacitor/splash-screen',
45
+ '@capacitor/status-bar',
46
+ '@capacitor/text-zoom',
47
+ '@capacitor/toast',
48
+ ];
49
+ const coreVersion = '^4.0.0';
50
+ const pluginVersion = '^4.0.0';
51
+ async function migrateCommand(config) {
52
+ if (config === null) {
53
+ errors_1.fatal('Config data missing');
54
+ }
55
+ const variablesAndClasspaths = await getAndroidVarriablesAndClasspaths(config);
56
+ if (!variablesAndClasspaths) {
57
+ errors_1.fatal('Variable and Classpath info could not be read.');
58
+ }
59
+ //*
60
+ allDependencies = {
61
+ ...config.app.package.dependencies,
62
+ ...config.app.package.devDependencies,
63
+ };
64
+ const monorepoWarning = 'Please note this tool is not intended for use in a mono-repo enviroment, please check out the Ionic vscode extension for this functionality.';
65
+ log_1.logger.info(monorepoWarning);
66
+ const { migrateconfirm } = await log_1.logPrompt(`Capacitor 4 sets a deployment target of iOS 13 and Android 12 (SDK 32). \n`, {
67
+ type: 'text',
68
+ name: 'migrateconfirm',
69
+ message: `Are you sure you want to migrate? (Y/n)`,
70
+ initial: 'y',
71
+ });
72
+ if (typeof migrateconfirm === 'string' &&
73
+ migrateconfirm.toLowerCase() === 'y') {
74
+ try {
75
+ const { npmInstallConfirm } = await log_1.logPrompt(`Would you like the migrator to run npm install to install the latest versions of capacitor packages? (Those using other package managers should answer N)`, {
76
+ type: 'text',
77
+ name: 'npmInstallConfirm',
78
+ message: `Run Npm Install? (Y/n)`,
79
+ initial: 'y',
80
+ });
81
+ const runNpmInstall = typeof npmInstallConfirm === 'string' &&
82
+ npmInstallConfirm.toLowerCase() === 'y';
83
+ await common_1.runTask(`Installing Latest NPM Modules.`, () => {
84
+ return installLatestNPMLibs(runNpmInstall, config);
85
+ });
86
+ await common_1.runTask(`Migrating @capacitor/storage to @capacitor/preferences.`, () => {
87
+ return migrateStoragePluginToPreferences(runNpmInstall);
88
+ });
89
+ if (allDependencies['@capacitor/ios'] &&
90
+ utils_fs_1.existsSync(config.ios.platformDirAbs)) {
91
+ // Set deployment target to 13.0
92
+ await common_1.runTask(`Migrating deployment target to 13.0.`, () => {
93
+ return updateFile(config, path_1.join(config.ios.nativeXcodeProjDirAbs, 'project.pbxproj'), 'IPHONEOS_DEPLOYMENT_TARGET = ', ';', '13.0');
94
+ });
95
+ // Update Podfile to 13.0
96
+ await common_1.runTask(`Migrating Podfile to 13.0.`, () => {
97
+ return updateFile(config, path_1.join(config.ios.nativeProjectDirAbs, 'Podfile'), `platform :ios, '`, `'`, '13.0');
98
+ });
99
+ await common_1.runTask(`Migrating Podfile to use post_install script.`, () => {
100
+ return podfileAssertDeploymentTarget(path_1.join(config.ios.nativeProjectDirAbs, 'Podfile'));
101
+ });
102
+ // Remove touchesBegan
103
+ await common_1.runTask(`Migrating AppDelegate.swift by removing touchesBegan.`, () => {
104
+ return updateFile(config, path_1.join(config.ios.nativeTargetDirAbs, 'AppDelegate.swift'), `override func touchesBegan`, `}`, undefined, true);
105
+ });
106
+ // Remove NSAppTransportSecurity
107
+ await common_1.runTask(`Migrating Info.plist by removing NSAppTransportSecurity key.`, () => {
108
+ return removeKey(path_1.join(config.ios.nativeTargetDirAbs, 'Info.plist'), 'NSAppTransportSecurity');
109
+ });
110
+ // Remove USE_PUSH
111
+ await common_1.runTask(`Migrating by removing USE_PUSH.`, () => {
112
+ return replacePush(path_1.join(config.ios.nativeXcodeProjDirAbs, 'project.pbxproj'));
113
+ });
114
+ // Remove from App Delegate
115
+ await common_1.runTask(`Migrating App Delegate.`, () => {
116
+ return replaceIfUsePush(config);
117
+ });
118
+ }
119
+ if (allDependencies['@capacitor/android'] &&
120
+ utils_fs_1.existsSync(config.android.platformDirAbs)) {
121
+ // AndroidManifest.xml add attribute: <activity android:exported="true"
122
+ await common_1.runTask(`Migrating AndroidManifest.xml by adding android:exported attribute to Activity.`, () => {
123
+ return updateAndroidManifest(path_1.join(config.android.srcMainDirAbs, 'AndroidManifest.xml'));
124
+ });
125
+ // Update build.gradle
126
+ const { leaveJCenterPrompt } = await log_1.logPrompt(`Some projects still require JCenter to function. If your project does, please answer yes below.`, {
127
+ type: 'text',
128
+ name: 'leaveJCenterPrompt',
129
+ message: `Keep JCenter if present? (y/N)`,
130
+ initial: 'n',
131
+ });
132
+ await common_1.runTask(`Migrating build.gradle file.`, () => {
133
+ return updateBuildGradle(path_1.join(config.android.platformDirAbs, 'build.gradle'), typeof leaveJCenterPrompt === 'string' &&
134
+ leaveJCenterPrompt.toLowerCase() === 'y', variablesAndClasspaths);
135
+ });
136
+ // Update app.gradle
137
+ await common_1.runTask(`Migrating app/build.gradle file.`, () => {
138
+ return updateAppBuildGradle(path_1.join(config.android.appDirAbs, 'build.gradle'));
139
+ });
140
+ // Update gradle-wrapper.properties
141
+ await common_1.runTask(`Migrating gradle-wrapper.properties by updating gradle version from 7.0 to 7.4.2.`, () => {
142
+ return updateGradleWrapper(path_1.join(config.android.platformDirAbs, 'gradle', 'wrapper', 'gradle-wrapper.properties'));
143
+ });
144
+ // Variables gradle
145
+ await common_1.runTask(`Migrating variables.gradle file.`, () => {
146
+ return (async () => {
147
+ const variablesPath = path_1.join(config.android.platformDirAbs, 'variables.gradle');
148
+ let txt = readFile(variablesPath);
149
+ if (!txt) {
150
+ return;
151
+ }
152
+ txt = txt.replace(/= {2}'/g, `= '`);
153
+ utils_fs_1.writeFileSync(variablesPath, txt, { encoding: 'utf-8' });
154
+ for (const variable of Object.keys(variablesAndClasspaths.variables)) {
155
+ if (!(await updateFile(config, variablesPath, `${variable} = '`, `'`, variablesAndClasspaths.variables[variable].toString(), true))) {
156
+ const didWork = await updateFile(config, variablesPath, `${variable} = `, `\n`, variablesAndClasspaths.variables[variable].toString(), true);
157
+ if (!didWork) {
158
+ let file = readFile(variablesPath);
159
+ if (file) {
160
+ file = file.replace('}', ` ${variable} = '${variablesAndClasspaths.variables[variable].toString()}'\n}`);
161
+ utils_fs_1.writeFileSync(variablesPath, file);
162
+ }
163
+ }
164
+ }
165
+ }
166
+ })();
167
+ });
168
+ // remove init
169
+ await common_1.runTask('Migrating MainActivity', () => {
170
+ return migrateMainActivity(config);
171
+ });
172
+ rimraf_1.default.sync(path_1.join(config.android.appDirAbs, 'build'));
173
+ // add new splashscreen
174
+ await common_1.runTask('Migrate to Android 12 Splashscreen and apply DayNight theme.', () => {
175
+ return addNewSplashScreen(config);
176
+ });
177
+ }
178
+ // Run Cap Sync
179
+ await common_1.runTask(`Running cap sync.`, () => {
180
+ return subprocess_1.getCommandOutput('npx', ['cap', 'sync']);
181
+ });
182
+ // Write all breaking changes
183
+ await common_1.runTask(`Writing breaking changes.`, () => {
184
+ return writeBreakingChanges();
185
+ });
186
+ log_1.logSuccess(`Migration to Capacitor ${coreVersion} is complete. Run and test your app!`);
187
+ }
188
+ catch (err) {
189
+ errors_1.fatal(`Failed to migrate: ${err}`);
190
+ }
191
+ }
192
+ else {
193
+ errors_1.fatal(`User canceled migration.`);
194
+ }
195
+ //*/
196
+ }
197
+ exports.migrateCommand = migrateCommand;
198
+ async function installLatestNPMLibs(runInstall, config) {
199
+ const pkgJsonPath = path_1.join(config.app.rootDir, 'package.json');
200
+ const pkgJsonFile = readFile(pkgJsonPath);
201
+ if (!pkgJsonFile) {
202
+ return;
203
+ }
204
+ const pkgJson = JSON.parse(pkgJsonFile);
205
+ for (const devDepKey of Object.keys(pkgJson['devDependencies'] || {})) {
206
+ if (libs.includes(devDepKey)) {
207
+ pkgJson['devDependencies'][devDepKey] = coreVersion;
208
+ }
209
+ else if (plugins.includes(devDepKey)) {
210
+ pkgJson['devDependencies'][devDepKey] = pluginVersion;
211
+ }
212
+ }
213
+ for (const depKey of Object.keys(pkgJson['dependencies'])) {
214
+ if (libs.includes(depKey)) {
215
+ pkgJson['dependencies'][depKey] = coreVersion;
216
+ }
217
+ else if (plugins.includes(depKey)) {
218
+ pkgJson['dependencies'][depKey] = pluginVersion;
219
+ }
220
+ }
221
+ utils_fs_1.writeFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2), {
222
+ encoding: 'utf-8',
223
+ });
224
+ if (runInstall) {
225
+ rimraf_1.default.sync(path_1.join(config.app.rootDir, 'package-lock.json'));
226
+ rimraf_1.default.sync(path_1.join(config.app.rootDir, 'node_modules/@capacitor/!(cli)'));
227
+ await subprocess_1.getCommandOutput('npm', ['i']);
228
+ }
229
+ else {
230
+ log_1.logger.info(`Please run an install command with your package manager of choice. (ex: yarn install)`);
231
+ }
232
+ }
233
+ async function migrateStoragePluginToPreferences(runInstall) {
234
+ if (allDependencies['@capacitor/storage']) {
235
+ log_1.logger.info('NOTE: @capacitor/storage was renamed to @capacitor/preferences, please be sure to replace occurances in your code.');
236
+ if (runInstall) {
237
+ await subprocess_1.getCommandOutput('npm', ['uninstall', '@capacitor/storage']);
238
+ await subprocess_1.getCommandOutput('npm', [
239
+ 'i',
240
+ `@capacitor/preferences@${pluginVersion}`,
241
+ ]);
242
+ }
243
+ else {
244
+ log_1.logger.info(`Please manually uninstall @capacitor/storage and replace it with @capacitor/preferences@${pluginVersion}`);
245
+ }
246
+ }
247
+ }
248
+ async function writeBreakingChanges() {
249
+ const breaking = [
250
+ '@capacitor/storage',
251
+ '@capacitor/camera',
252
+ '@capacitor/push-notifications',
253
+ '@capacitor/local-notifications',
254
+ ];
255
+ const broken = [];
256
+ for (const lib of breaking) {
257
+ if (allDependencies[lib]) {
258
+ broken.push(lib);
259
+ }
260
+ }
261
+ if (broken.length > 0) {
262
+ log_1.logger.info(`IMPORTANT: Review https://capacitorjs.com/docs/updating/4-0#plugins for breaking changes in these plugins that you use: ${broken.join(', ')}.`);
263
+ }
264
+ if (allDependencies['@capacitor/android']) {
265
+ log_1.logger.info('Warning: The Android Gradle plugin was updated and it requires Java 11 to run. You may need to select this in Android Studio.');
266
+ }
267
+ }
268
+ async function updateAndroidManifest(filename) {
269
+ const txt = readFile(filename);
270
+ if (!txt) {
271
+ return;
272
+ }
273
+ const hasAndroidExportedAlreadySet = new RegExp(/<activity([^>]*(android:exported=")[^>]*)>/g).test(txt);
274
+ let isAndroidExportedSetToFalse = false;
275
+ if (hasAndroidExportedAlreadySet) {
276
+ isAndroidExportedSetToFalse = new RegExp(/<activity([^>]*(android:exported="false")[^>]*)>/g).test(txt);
277
+ }
278
+ // AndroidManifest.xml add attribute: <activity android:exported="true"
279
+ if (hasAndroidExportedAlreadySet && !isAndroidExportedSetToFalse) {
280
+ return; // Probably already updated manually
281
+ }
282
+ let replaced = txt;
283
+ if (!hasAndroidExportedAlreadySet) {
284
+ replaced = setAllStringIn(txt, '<activity', ' ', `\n android:exported="true"\n`);
285
+ }
286
+ else {
287
+ log_1.logger.info(`Found 'android:exported="false"' in your AndroidManifest.xml, if this is not intentional please update it manually to "true".`);
288
+ }
289
+ if (txt == replaced) {
290
+ log_1.logger.error(`Unable to update Android Manifest. Missing <activity> tag`);
291
+ return;
292
+ }
293
+ utils_fs_1.writeFileSync(filename, replaced, 'utf-8');
294
+ }
295
+ async function updateBuildGradle(filename, leaveJCenter, variablesAndClasspaths) {
296
+ // In build.gradle add dependencies:
297
+ // classpath 'com.android.tools.build:gradle:7.2.1'
298
+ // classpath 'com.google.gms:google-services:4.3.13'
299
+ const txt = readFile(filename);
300
+ if (!txt) {
301
+ return;
302
+ }
303
+ const neededDeps = {
304
+ 'com.android.tools.build:gradle': variablesAndClasspaths['com.android.tools.build:gradle'],
305
+ 'com.google.gms:google-services': variablesAndClasspaths['com.google.gms:google-services'],
306
+ };
307
+ let replaced = txt;
308
+ for (const dep of Object.keys(neededDeps)) {
309
+ if (replaced.includes(`classpath '${dep}`)) {
310
+ replaced = setAllStringIn(replaced, `classpath '${dep}:`, `'`, neededDeps[dep]);
311
+ log_1.logger.info(`Set ${dep} = ${neededDeps[dep]}.`);
312
+ }
313
+ }
314
+ // Replace jcenter()
315
+ const lines = replaced.split('\n');
316
+ let inRepositories = false;
317
+ let hasMavenCentral = false;
318
+ let final = '';
319
+ for (const line of lines) {
320
+ if (line.includes('repositories {')) {
321
+ inRepositories = true;
322
+ hasMavenCentral = false;
323
+ }
324
+ else if (line.trim() == '}') {
325
+ // Make sure we have mavenCentral()
326
+ if (inRepositories && !hasMavenCentral) {
327
+ final += ' mavenCentral()\n';
328
+ log_1.logger.info(`Added mavenCentral().`);
329
+ }
330
+ inRepositories = false;
331
+ }
332
+ if (inRepositories && line.trim() === 'mavenCentral()') {
333
+ hasMavenCentral = true;
334
+ }
335
+ if (inRepositories && line.trim() === 'jcenter()' && !leaveJCenter) {
336
+ // skip jCentral()
337
+ log_1.logger.info(`Removed jcenter().`);
338
+ }
339
+ else {
340
+ final += line + '\n';
341
+ }
342
+ }
343
+ if (txt !== final) {
344
+ utils_fs_1.writeFileSync(filename, final, 'utf-8');
345
+ return;
346
+ }
347
+ }
348
+ async function getAndroidVarriablesAndClasspaths(config) {
349
+ const tempAndroidTemplateFolder = path_1.join(config.cli.assetsDirAbs, 'tempAndroidTemplate');
350
+ await template_1.extractTemplate(config.cli.assets.android.platformTemplateArchiveAbs, tempAndroidTemplateFolder);
351
+ const variablesGradleFile = readFile(path_1.join(tempAndroidTemplateFolder, 'variables.gradle'));
352
+ const buildGradleFile = readFile(path_1.join(tempAndroidTemplateFolder, 'build.gradle'));
353
+ if (!variablesGradleFile || !buildGradleFile) {
354
+ return;
355
+ }
356
+ fs_1.deleteFolderRecursive(tempAndroidTemplateFolder);
357
+ const firstIndxOfCATBGV = buildGradleFile.indexOf(`classpath 'com.android.tools.build:gradle:`) + 42;
358
+ const firstIndxOfCGGGS = buildGradleFile.indexOf(`com.google.gms:google-services:`) + 31;
359
+ const comAndroidToolsBuildGradleVersion = '' +
360
+ buildGradleFile.substring(firstIndxOfCATBGV, buildGradleFile.indexOf("'", firstIndxOfCATBGV));
361
+ const comGoogleGmsGoogleServices = '' +
362
+ buildGradleFile.substring(firstIndxOfCGGGS, buildGradleFile.indexOf("'", firstIndxOfCGGGS));
363
+ const variablesGradleAsJSON = JSON.parse(variablesGradleFile
364
+ .replace('ext ', '')
365
+ .replace(/=/g, ':')
366
+ .replace(/\n/g, ',')
367
+ .replace(/,([^:]+):/g, function (_k, p1) {
368
+ return `,"${p1}":`;
369
+ })
370
+ .replace('{,', '{')
371
+ .replace(',}', '}')
372
+ .replace(/\s/g, '')
373
+ .replace(/'/g, '"'));
374
+ return {
375
+ 'variables': variablesGradleAsJSON,
376
+ 'com.android.tools.build:gradle': comAndroidToolsBuildGradleVersion,
377
+ 'com.google.gms:google-services': comGoogleGmsGoogleServices,
378
+ };
379
+ }
380
+ function readFile(filename) {
381
+ try {
382
+ if (!utils_fs_1.existsSync(filename)) {
383
+ log_1.logger.error(`Unable to find ${filename}. Try updating it manually`);
384
+ return;
385
+ }
386
+ return utils_fs_1.readFileSync(filename, 'utf-8');
387
+ }
388
+ catch (err) {
389
+ log_1.logger.error(`Unable to read ${filename}. Verify it is not already open. ${err}`);
390
+ }
391
+ }
392
+ async function updateAppBuildGradle(filename) {
393
+ const txt = readFile(filename);
394
+ if (!txt) {
395
+ return;
396
+ }
397
+ let replaced = txt;
398
+ if (!txt.includes('androidx.coordinatorlayout:coordinatorlayout:')) {
399
+ replaced = replaced.replace('dependencies {', 'dependencies {\n implementation "androidx.coordinatorlayout:coordinatorlayout:$androidxCoordinatorLayoutVersion"');
400
+ }
401
+ if (!txt.includes('androidx.core:core-splashscreen:')) {
402
+ replaced = replaced.replace('dependencies {', 'dependencies {\n implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion"');
403
+ }
404
+ // const lines = txt.split('\n');
405
+ if (replaced !== txt) {
406
+ utils_fs_1.writeFileSync(filename, replaced, 'utf-8');
407
+ }
408
+ }
409
+ async function updateGradleWrapper(filename) {
410
+ const txt = readFile(filename);
411
+ if (!txt) {
412
+ return;
413
+ }
414
+ const replaced = setAllStringIn(txt, 'distributionUrl=', '\n',
415
+ // eslint-disable-next-line no-useless-escape
416
+ `https\\://services.gradle.org/distributions/gradle-7.4.2-all.zip`);
417
+ utils_fs_1.writeFileSync(filename, replaced, 'utf-8');
418
+ }
419
+ async function updateFile(config, filename, textStart, textEnd, replacement, skipIfNotFound) {
420
+ if (config === null) {
421
+ return false;
422
+ }
423
+ const path = filename;
424
+ let txt = readFile(path);
425
+ if (!txt) {
426
+ return false;
427
+ }
428
+ if (txt.includes(textStart)) {
429
+ if (replacement) {
430
+ txt = setAllStringIn(txt, textStart, textEnd, replacement);
431
+ utils_fs_1.writeFileSync(path, txt, { encoding: 'utf-8' });
432
+ }
433
+ else {
434
+ // Replacing in code so we need to count the number of brackets to find the end of the function in swift
435
+ const lines = txt.split('\n');
436
+ let replaced = '';
437
+ let keep = true;
438
+ let brackets = 0;
439
+ for (const line of lines) {
440
+ if (line.includes(textStart)) {
441
+ keep = false;
442
+ }
443
+ if (!keep) {
444
+ brackets += (line.match(/{/g) || []).length;
445
+ brackets -= (line.match(/}/g) || []).length;
446
+ if (brackets == 0) {
447
+ keep = true;
448
+ }
449
+ }
450
+ else {
451
+ replaced += line + '\n';
452
+ }
453
+ }
454
+ utils_fs_1.writeFileSync(path, replaced, { encoding: 'utf-8' });
455
+ }
456
+ return true;
457
+ }
458
+ else if (!skipIfNotFound) {
459
+ log_1.logger.error(`Unable to find "${textStart}" in ${filename}. Try updating it manually`);
460
+ }
461
+ return false;
462
+ }
463
+ function setAllStringIn(data, start, end, replacement) {
464
+ let position = 0;
465
+ let result = data;
466
+ let replaced = true;
467
+ while (replaced) {
468
+ const foundIdx = result.indexOf(start, position);
469
+ if (foundIdx == -1) {
470
+ replaced = false;
471
+ }
472
+ else {
473
+ const idx = foundIdx + start.length;
474
+ position = idx + replacement.length;
475
+ result =
476
+ result.substring(0, idx) +
477
+ replacement +
478
+ result.substring(result.indexOf(end, idx));
479
+ }
480
+ }
481
+ return result;
482
+ }
483
+ async function replaceIfUsePush(config) {
484
+ const startLine = '#if USE_PUSH';
485
+ const endLine = '#endif';
486
+ const filename = path_1.join(config.ios.nativeTargetDirAbs, 'AppDelegate.swift');
487
+ const txt = readFile(filename);
488
+ if (!txt) {
489
+ return;
490
+ }
491
+ const lines = txt.split('\n');
492
+ let startLineIndex = null;
493
+ let endLineIndex = null;
494
+ for (const [key, item] of lines.entries()) {
495
+ if (item.includes(startLine)) {
496
+ startLineIndex = key;
497
+ break;
498
+ }
499
+ }
500
+ if (startLineIndex !== null) {
501
+ for (const [key, item] of lines.entries()) {
502
+ if (item.includes(endLine) && key > startLineIndex) {
503
+ endLineIndex = key;
504
+ break;
505
+ }
506
+ }
507
+ if (endLineIndex !== null) {
508
+ lines[endLineIndex] = '';
509
+ lines[startLineIndex] = '';
510
+ utils_fs_1.writeFileSync(filename, lines.join('\n'), 'utf-8');
511
+ }
512
+ }
513
+ }
514
+ async function replacePush(filename) {
515
+ const txt = readFile(filename);
516
+ if (!txt) {
517
+ return;
518
+ }
519
+ let replaced = txt;
520
+ replaced = replaced.replace('DEBUG USE_PUSH', 'DEBUG');
521
+ replaced = replaced.replace('USE_PUSH', '""');
522
+ if (replaced != txt) {
523
+ utils_fs_1.writeFileSync(filename, replaced, 'utf-8');
524
+ }
525
+ }
526
+ async function removeKey(filename, key) {
527
+ const txt = readFile(filename);
528
+ if (!txt) {
529
+ return;
530
+ }
531
+ let lines = txt.split('\n');
532
+ let removed = false;
533
+ let removing = false;
534
+ lines = lines.filter(line => {
535
+ if (removing && line.includes('</dict>')) {
536
+ removing = false;
537
+ return false;
538
+ }
539
+ if (line.includes(`<key>${key}</key`)) {
540
+ removing = true;
541
+ removed = true;
542
+ }
543
+ return !removing;
544
+ });
545
+ if (removed) {
546
+ utils_fs_1.writeFileSync(filename, lines.join('\n'), 'utf-8');
547
+ }
548
+ }
549
+ async function podfileAssertDeploymentTarget(filename) {
550
+ const txt = readFile(filename);
551
+ if (!txt) {
552
+ return;
553
+ }
554
+ let replaced = txt;
555
+ if (!replaced.includes(`require_relative '../../node_modules/@capacitor/ios/scripts/pods_helpers`)) {
556
+ replaced =
557
+ `require_relative '../../node_modules/@capacitor/ios/scripts/pods_helpers'\n\n` +
558
+ txt;
559
+ }
560
+ if (replaced.includes('post_install do |installer|')) {
561
+ if (!replaced.includes(`assertDeploymentTarget(installer)`)) {
562
+ replaced = replaced.replace('post_install do |installer|', `post_install do |installer|\n assertDeploymentTarget(installer)\n`);
563
+ }
564
+ }
565
+ else {
566
+ replaced =
567
+ replaced +
568
+ `\n\npost_install do |installer|\n assertDeploymentTarget(installer)\nend\n`;
569
+ }
570
+ utils_fs_1.writeFileSync(filename, replaced, 'utf-8');
571
+ }
572
+ async function migrateMainActivity(config) {
573
+ const xmlData = await xml_1.readXML(path_1.join(config.android.srcMainDirAbs, 'AndroidManifest.xml'));
574
+ const manifestNode = xmlData.manifest;
575
+ const applicationChildNodes = manifestNode.application;
576
+ let mainActivityClassPath = '';
577
+ applicationChildNodes.find(applicationChildNode => {
578
+ const activityChildNodes = applicationChildNode.activity;
579
+ if (!Array.isArray(activityChildNodes)) {
580
+ return false;
581
+ }
582
+ const mainActivityNode = activityChildNodes.find(activityChildNode => {
583
+ const intentFilterChildNodes = activityChildNode['intent-filter'];
584
+ if (!Array.isArray(intentFilterChildNodes)) {
585
+ return false;
586
+ }
587
+ return intentFilterChildNodes.find(intentFilterChildNode => {
588
+ const actionChildNodes = intentFilterChildNode.action;
589
+ if (!Array.isArray(actionChildNodes)) {
590
+ return false;
591
+ }
592
+ const mainActionChildNode = actionChildNodes.find(actionChildNode => {
593
+ const androidName = actionChildNode.$['android:name'];
594
+ return androidName === 'android.intent.action.MAIN';
595
+ });
596
+ if (!mainActionChildNode) {
597
+ return false;
598
+ }
599
+ const categoryChildNodes = intentFilterChildNode.category;
600
+ if (!Array.isArray(categoryChildNodes)) {
601
+ return false;
602
+ }
603
+ return categoryChildNodes.find(categoryChildNode => {
604
+ const androidName = categoryChildNode.$['android:name'];
605
+ return androidName === 'android.intent.category.LAUNCHER';
606
+ });
607
+ });
608
+ });
609
+ if (mainActivityNode) {
610
+ mainActivityClassPath = mainActivityNode.$['android:name'];
611
+ }
612
+ return mainActivityNode;
613
+ });
614
+ const mainActivityClassName = mainActivityClassPath.split('.').pop();
615
+ const mainActivityPathArray = mainActivityClassPath.split('.');
616
+ mainActivityPathArray.pop();
617
+ const mainActivityClassFileName = `${mainActivityClassName}.java`;
618
+ const mainActivityClassFilePath = path_1.join(path_1.join(config.android.srcMainDirAbs, 'java'), ...mainActivityPathArray, mainActivityClassFileName);
619
+ let data = readFile(mainActivityClassFilePath);
620
+ if (data) {
621
+ const bindex = data.indexOf('this.init(savedInstanceState');
622
+ if (bindex !== -1) {
623
+ const eindex = data.indexOf('}});', bindex) + 4;
624
+ data = data.replace(data.substring(bindex, eindex), '');
625
+ data = data.replace('// Initializes the Bridge', '');
626
+ }
627
+ const rindex = data.indexOf('registerPlugin');
628
+ if (rindex !== -1) {
629
+ if (data.indexOf('super.onCreate(savedInstanceState);') < rindex) {
630
+ data = data.replace('super.onCreate(savedInstanceState);\n ', '');
631
+ const eindex = data.lastIndexOf('.class);') + 8;
632
+ data = data.replace(data.substring(bindex, eindex), `${data.substring(bindex, eindex)}\n super.onCreate(savedInstanceState);`);
633
+ }
634
+ }
635
+ if (bindex == -1 && rindex == -1) {
636
+ return;
637
+ }
638
+ utils_fs_1.writeFileSync(mainActivityClassFilePath, data);
639
+ }
640
+ }
641
+ async function addNewSplashScreen(config) {
642
+ const stylePath = path_1.join(config.android.srcMainDirAbs, 'res', 'values', 'styles.xml');
643
+ let stylesXml = readFile(stylePath);
644
+ if (!stylesXml)
645
+ return;
646
+ stylesXml = stylesXml.replace(`parent="AppTheme.NoActionBar"`, `parent="Theme.SplashScreen"`);
647
+ // revert wrong replaces
648
+ stylesXml = stylesXml.replace(`name="Theme.SplashScreen"`, `name="AppTheme.NoActionBar"`);
649
+ stylesXml = stylesXml.replace(`name="Theme.SplashScreenLaunch"`, `name="AppTheme.NoActionBarLaunch"`);
650
+ // Apply DayNight theme
651
+ stylesXml = stylesXml.replace(`parent="Theme.AppCompat.NoActionBar"`, `parent="Theme.AppCompat.DayNight.NoActionBar"`);
652
+ utils_fs_1.writeFileSync(stylePath, stylesXml);
653
+ }
package/dist/tasks/run.js CHANGED
@@ -56,7 +56,7 @@ async function runCommand(config, selectedPlatformName, options) {
56
56
  }
57
57
  try {
58
58
  if (options.sync) {
59
- await sync_1.sync(config, platformName, false);
59
+ await sync_1.sync(config, platformName, false, true);
60
60
  }
61
61
  await run(config, platformName, options);
62
62
  }