codeplay-common 3.2.8 → 3.2.9

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.
@@ -1,960 +1,960 @@
1
- /*
2
- Can be run like
3
- node finalrelease
4
- node finalrelease 1
5
- node finalrelease "1,2,7"
6
- */
7
-
8
- import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
9
- import { join, resolve } from 'path';
10
- import { execSync } from 'child_process';
11
- import { createInterface } from 'readline';
12
-
13
- import { fileURLToPath } from 'url';
14
- import { dirname } from 'path';
15
-
16
- /* const path = require('path');
17
- const fs = require('fs'); */
18
-
19
- import fs from 'fs';
20
- import path from 'path';
21
-
22
- // Define a mapping between store IDs and store names
23
- /* const storeNames = {
24
- "1": "PlayStore",
25
- "2": "SamsungStore",
26
- "7": "AmazonStore"
27
- }; */
28
-
29
-
30
- const isOnlyOneAPK = true; // 🔥 change to false for normal behavior
31
-
32
- const storeNames = {
33
- "1": "PlayStore",
34
- "2": "SamsungStore",
35
- "7": "AmazonStore",
36
-
37
- "3": "MiStore",
38
- "4": "HuaweiStore",
39
- "5": "OppoStore",
40
- //"6": "iOSStore",
41
- "8": "VivoStore"
42
- };
43
-
44
-
45
- //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
46
-
47
-
48
-
49
-
50
-
51
-
52
-
53
- let isAdmobFound = false;
54
-
55
- const amazonMinSdkVersion=24;
56
-
57
- const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
58
-
59
-
60
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
61
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
62
-
63
- const _appUniqueId = config.android?.APP_UNIQUE_ID;
64
- const _appName=config.appName;
65
- const _appPackageId=config.appId;
66
-
67
-
68
-
69
- const __filename = fileURLToPath(import.meta.url);
70
- const __dirname = dirname(__filename);
71
-
72
- function fileExists(filePath) {
73
- return existsSync(filePath);
74
- }
75
-
76
-
77
- const ffmpegPluginXmlPath = path.join(__dirname, 'node_modules', 'codeplay-fmpg', 'plugin.xml');
78
- const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
79
-
80
-
81
-
82
- function isFfmpegUsed() {
83
- try {
84
- const xmlContent = fs.readFileSync(ffmpegPluginXmlPath, 'utf8');
85
- // Simple check: if plugin.xml exists and contains <plugin> tag (or any FFmpeg-specific tag)
86
- return /<plugin\b/.test(xmlContent);
87
- } catch (err) {
88
- console.log('⚠️ FFmpeg plugin not found:', err.message);
89
- return false;
90
- }
91
- }
92
-
93
- const _isffmpegUsed = isFfmpegUsed();
94
-
95
- function getAdMobConfig() {
96
- if (!fileExists(capacitorConfigPath)) {
97
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
98
- }
99
-
100
- const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
101
- const admobConfig = config.plugins?.AdMob;
102
-
103
- //_appPackageId=config.appId;
104
-
105
- if (!admobConfig) {
106
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
107
- }
108
-
109
- // Default to true if ADMOB_ENABLED is not specified
110
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
111
-
112
- if (!isEnabled) {
113
- return { ADMOB_ENABLED: false }; // Skip further validation
114
- }
115
-
116
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
117
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
118
- }
119
-
120
- return {
121
- ADMOB_ENABLED: true,
122
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
123
- APP_ID_IOS: admobConfig.APP_ID_IOS,
124
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
125
- };
126
- }
127
-
128
-
129
-
130
- const _capacitorConfig = getAdMobConfig();
131
-
132
- const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
133
-
134
- // Proceed only if ADMOB_ENABLED is true
135
- //if (_capacitorConfig.ADMOB_ENABLED)
136
-
137
-
138
- const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration.json');
139
- let admobConfig;
140
-
141
- if (_isADMOB_ENABLED)
142
- {
143
- try
144
- {
145
- admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
146
- }
147
- catch (err)
148
- {
149
- console.error("❌ Failed to read admob-ad-configuration.json", err);
150
- process.exit(1);
151
- }
152
- }
153
-
154
-
155
-
156
-
157
-
158
- function updateIOSVersion(versionCode, versionName) {
159
-
160
- const pbxprojPath = join("ios", "App", "App.xcodeproj", "project.pbxproj");
161
-
162
- // 🔥 Single check only
163
- if (!existsSync(pbxprojPath)) {
164
- console.warn("⚠️ iOS project not found, skipping version update");
165
- return;
166
- }
167
-
168
-
169
- let content = readFileSync(pbxprojPath, 'utf8');
170
-
171
- // Update MARKETING_VERSION
172
- content = content.replace(
173
- /MARKETING_VERSION = .*?;/g,
174
- `MARKETING_VERSION = ${versionName};`
175
- );
176
-
177
- // Update CURRENT_PROJECT_VERSION
178
- /* content = content.replace(
179
- /CURRENT_PROJECT_VERSION = .*?;/g,
180
- `CURRENT_PROJECT_VERSION = ${versionCode};`
181
- ); */
182
-
183
- writeFileSync(pbxprojPath, content, 'utf8');
184
-
185
- console.log(`🍏 iOS updated via Xcode settings → version: ${versionName}, build: ${versionCode}`);
186
- }
187
-
188
-
189
-
190
-
191
-
192
-
193
-
194
-
195
-
196
-
197
-
198
-
199
-
200
-
201
-
202
-
203
-
204
-
205
-
206
-
207
-
208
- const checkCommonFileStoreId=()=>{
209
- const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
210
- let viteConfigPath;
211
- for (const configFile of possibleConfigFiles) {
212
- const fullPath = resolve( configFile);
213
- if (existsSync(fullPath)) {
214
- viteConfigPath = fullPath;
215
- break;
216
- }
217
- }
218
-
219
- if (!viteConfigPath) {
220
- console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
221
- process.exit(1);
222
- }
223
-
224
- try {
225
- // Read vite config file
226
- const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
227
-
228
- // Extract @common alias path
229
- const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
230
- const match = viteConfigContent.match(aliasPattern);
231
-
232
- if (!match) {
233
- console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
234
- process.exit(1);
235
- }
236
-
237
- const commonFilePath = match[1];
238
- const resolvedCommonPath = resolve(__dirname, commonFilePath);
239
-
240
- // Read the common file content
241
- if (!existsSync(resolvedCommonPath)) {
242
- console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
243
- process.exit(1);
244
- }
245
-
246
- const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
247
-
248
- // Check for the _storeid export line
249
- const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
250
- if (!storeIdPattern.test(commonFileContent)) {
251
- console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
252
- process.exit(1);
253
- }
254
-
255
- console.log(commonFilePath,'Success - No problem found');
256
- } catch (error) {
257
- console.error('❌ Error:', error);
258
- process.exit(1);
259
- }
260
-
261
- }
262
-
263
- const checkIsTestingInAdmob=()=>{
264
-
265
- if (admobConfig.config && admobConfig.config.isTesting === true) {
266
- console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration.json" file.`);
267
- process.exit(1); // Exit with an error code to halt the process
268
- } else {
269
- console.log('✅ No problem found. "isTesting" is either already false or not defined.');
270
- }
271
- }
272
-
273
- const checkIsAdsDisableByReturnStatement=()=>{
274
-
275
-
276
- const adsFolder = join('src', 'js', 'Ads');
277
- const filePattern = /^admob-emi-(\d+\.)+\d+\.js$/;
278
-
279
- // Step 1: Find the admob file
280
- const files = readdirSync(adsFolder);
281
- const admobFile = files.find(f => filePattern.test(f));
282
-
283
- if (!admobFile) {
284
- console.log('❌ No Admob file found.');
285
- process.exit(1);
286
- }
287
-
288
- const filePath = join(adsFolder, admobFile);
289
- const content = readFileSync(filePath, 'utf-8');
290
-
291
- // Step 2: Extract the adsOnDeviceReady function body
292
- const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
293
- const match = content.match(functionRegex);
294
-
295
- if (!match) {
296
- console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
297
- process.exit(1);
298
- }
299
-
300
- const body = match[1];
301
- const lines = body.split('\n').map(line => line.trim());
302
-
303
- // Step 3: Skip blank lines and comments, get the first real code line
304
- let firstCodeLine = '';
305
- for (const line of lines) {
306
- if (line === '' || line.startsWith('//')) continue;
307
- firstCodeLine = line;
308
- break;
309
- }
310
-
311
- // Step 4: Block if it's any of the unwanted returns
312
- const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
313
-
314
- if (badReturnPattern.test(firstCodeLine)) {
315
- console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
316
- process.exit(2);
317
- } else {
318
- console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
319
- }
320
- }
321
-
322
-
323
-
324
- const addPermission_AD_ID=async()=>{
325
-
326
- const admobPluginXmlPath = join('node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
327
-
328
-
329
- //let isAdmobFound = false;
330
- try {
331
- await promises.access(admobPluginXmlPath, constants.F_OK);
332
- isAdmobFound = true;
333
- } catch (err) {
334
- isAdmobFound = false;
335
- }
336
-
337
-
338
-
339
- if (isAdmobFound) {
340
- if (existsSync(androidManifestPath)) {
341
- let manifestContent = readFileSync(androidManifestPath, 'utf8');
342
- let modified = false;
343
-
344
- // --- Step 1: Ensure AD_ID permission exists ---
345
- const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
346
- if (!manifestContent.includes(adIdPermission)) {
347
- console.log("📄 AD_ID permission not found. Adding to AndroidManifest.xml.");
348
- manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
349
- console.log("✅ AD_ID permission added successfully.");
350
- modified = true;
351
- } else {
352
- console.log("ℹ️ AD_ID permission already exists in AndroidManifest.xml.");
353
- }
354
-
355
- // --- Step 2: Ensure OPTIMIZE_AD_LOADING meta-data exists ---
356
- const optimizeAdMeta = `<meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" />`;
357
-
358
- if (!manifestContent.includes(optimizeAdMeta)) {
359
- console.log("📄 OPTIMIZE_AD_LOADING meta-data not found. Adding to AndroidManifest.xml.");
360
-
361
- const appTagPattern = /<application[^>]*>/;
362
- if (appTagPattern.test(manifestContent)) {
363
- manifestContent = manifestContent.replace(appTagPattern, match => `${match}\n ${optimizeAdMeta}`);
364
- console.log("✅ OPTIMIZE_AD_LOADING meta-data added successfully.");
365
- modified = true;
366
- } else {
367
- console.error("❌ <application> tag not found in AndroidManifest.xml.");
368
- }
369
- } else {
370
- console.log("ℹ️ OPTIMIZE_AD_LOADING meta-data already exists in AndroidManifest.xml.");
371
- }
372
-
373
- // --- Step 3: Write only if modified ---
374
- if (modified) {
375
- writeFileSync(androidManifestPath, manifestContent, 'utf8');
376
- console.log("💾 AndroidManifest.xml updated successfully.");
377
- } else {
378
- console.log("✅ No changes needed. AndroidManifest.xml is up to date.");
379
- }
380
-
381
- } else {
382
- console.error("❌ AndroidManifest.xml not found at the specified path.");
383
- }
384
- } else {
385
- console.log("\x1b[33m%s\x1b[0m", "⚠️ No AdMob found, so AD_ID permission and meta-data were not added");
386
- }
387
-
388
-
389
-
390
-
391
-
392
-
393
- }
394
-
395
-
396
-
397
-
398
-
399
-
400
-
401
-
402
-
403
-
404
-
405
- checkCommonFileStoreId();
406
-
407
-
408
-
409
- if (_isADMOB_ENABLED)
410
- {
411
- checkIsTestingInAdmob();
412
- checkIsAdsDisableByReturnStatement()
413
-
414
- await addPermission_AD_ID()
415
- }
416
-
417
-
418
-
419
- let originalReleaseType, originalSigningType;
420
-
421
- function readCapacitorConfig() {
422
- return JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
423
- }
424
-
425
- function writeCapacitorConfig(config) {
426
- fs.writeFileSync(capacitorConfigPath, JSON.stringify(config, null, 2), 'utf8');
427
- }
428
-
429
- /* function updateCapacitorConfig(releaseType, signingType) {
430
- const config = readCapacitorConfig();
431
-
432
- // Save original values once
433
- if (originalReleaseType === undefined) originalReleaseType = config.android?.buildOptions?.releaseType || '';
434
- if (originalSigningType === undefined) originalSigningType = config.android?.buildOptions?.signingType || '';
435
-
436
- // Update values
437
- config.android = config.android || {};
438
- config.android.buildOptions = config.android.buildOptions || {};
439
- config.android.buildOptions.releaseType = releaseType;
440
- config.android.buildOptions.signingType = signingType;
441
-
442
- writeCapacitorConfig(config);
443
- console.log(`ℹ️ capacitor.config.json updated: releaseType=${releaseType}, signingType=${signingType}`);
444
- } */
445
-
446
- /* function restoreCapacitorConfig() {
447
- const config = readCapacitorConfig();
448
- if (originalReleaseType !== undefined) config.android.buildOptions.releaseType = originalReleaseType;
449
- if (originalSigningType !== undefined) config.android.buildOptions.signingType = originalSigningType;
450
- writeCapacitorConfig(config);
451
- console.log(`✅ capacitor.config.json restored to original values.`);
452
- }
453
-
454
- process.on('SIGINT', () => {
455
- console.log('\n⚠️ Detected Ctrl+C, restoring capacitor.config.json...');
456
- restoreCapacitorConfig();
457
- process.exit(0);
458
- });
459
-
460
- process.on('exit', () => {
461
- restoreCapacitorConfig();
462
- }); */
463
-
464
-
465
-
466
- const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
467
- console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
468
-
469
-
470
-
471
-
472
-
473
-
474
- // Get the store ID from the command line arguments
475
- /* const storeIdArg = ["2","3"]//process.argv[2]; // Get the store ID from the command line
476
- const storeIds = storeIdArg ? storeIdArg : Object.keys(storeNames);//["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
477
-
478
- debugger; */
479
-
480
- let storeIdArg = process.argv[2]; // command-line argument
481
- let storeIds;
482
-
483
- if (storeIdArg) {
484
- try {
485
- // Try parsing as JSON array first
486
- const parsed = JSON.parse(storeIdArg);
487
- if (Array.isArray(parsed)) {
488
- storeIds = parsed.map(String); // ensure strings
489
- } else {
490
- storeIds = [parsed.toString()];
491
- }
492
- } catch (e) {
493
- // Not JSON, assume comma-separated string
494
- storeIds = storeIdArg.split(",").map(s => s.trim());
495
- }
496
- } else {
497
- // No argument, use all store IDs
498
- storeIds = Object.keys(storeNames);
499
- }
500
-
501
-
502
- // 🔥 If only one APK mode, override APK storeIds
503
- /* if (isOnlyOneAPK) {
504
- console.log("⚡ isOnlyOneAPK enabled → Only MiStore (3) will be used for APK build");
505
- storeIds = ["3"]; // Only MiStore
506
- } */
507
-
508
- // Store the original minSdkVersion globally
509
- let originalMinSdkVersion;
510
-
511
- // Remove any existing AAB files before starting the build process
512
- const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
513
- if (existsSync(aabDirectory)) {
514
- const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
515
- files.forEach(file => {
516
- const filePath = join(aabDirectory, file);
517
- unlinkSync(filePath);
518
- console.log(`ℹ️ Deleted existing AAB file: ${file}`);
519
- });
520
- }
521
-
522
- const aabOutputDir = join("AAB");
523
- if (!existsSync(aabOutputDir)) {
524
- mkdirSync(aabOutputDir);
525
- console.log(`Created directory: ${aabOutputDir}`);
526
- }
527
-
528
- if (existsSync(aabOutputDir)) {
529
- const files = readdirSync(aabOutputDir).filter(
530
- file => file.endsWith('.aab') || file.endsWith('.apk')
531
- );
532
-
533
- files.forEach(file => {
534
- const filePath = join(aabOutputDir, file);
535
- unlinkSync(filePath);
536
- console.log(`Deleted existing build file: ${file}`);
537
- });
538
- }
539
-
540
-
541
- // Extract version code and version name from build.gradle
542
- const gradleFilePath = join("android", "app", "build.gradle");
543
- const gradleContent = readFileSync(gradleFilePath, 'utf8');
544
-
545
- const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
546
- const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
547
-
548
- const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
549
- const versionName = versionNameMatch ? versionNameMatch[1] : '';
550
-
551
- // Display the current versionCode and versionName
552
- console.log(`Current versionCode: ${versionCode}`);
553
- console.log(`Current versionName: ${versionName}`);
554
-
555
- // Create an interface for user input
556
- const rl = createInterface({
557
- input: process.stdin,
558
- output: process.stdout
559
- });
560
-
561
- // Ask for new versionCode
562
- rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
563
- const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
564
-
565
- // Ask for new versionName
566
- rl.question('Enter new versionName (press enter to keep current): ', (newVersionName) => {
567
- const finalVersionName = newVersionName || versionName; // Use existing if no input
568
-
569
- // Log the final version details
570
- console.log(`📦 Final versionCode: ${finalVersionCode}`);
571
- console.log(`📝 Final versionName: ${finalVersionName}`);
572
-
573
-
574
- updateIOSVersion(finalVersionCode, finalVersionName);
575
-
576
- // Update build.gradle with the new version details
577
- let updatedGradleContent = gradleContent
578
- .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
579
- .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
580
-
581
- // Check if resConfigs "en" already exists
582
- const resConfigsLine = ' resConfigs "en"';
583
- if (!updatedGradleContent.includes(resConfigsLine)) {
584
- // Add resConfigs "en" below versionName
585
- updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
586
- } else {
587
- console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
588
- }
589
-
590
-
591
-
592
- // List of package IDs for which minify should be false
593
-
594
-
595
- // Determine desired minify value
596
- const desiredMinify = !_isffmpegUsed;
597
-
598
- // Check if minifyEnabled is already present
599
- if (/minifyEnabled\s+(true|false)/.test(updatedGradleContent)) {
600
- // Replace existing value with desired
601
- updatedGradleContent = updatedGradleContent.replace(/minifyEnabled\s+(true|false)/, `minifyEnabled ${desiredMinify}`);
602
- console.log(`Replaced minifyEnabled with ${desiredMinify}.`);
603
- } else if (/buildTypes\s*{[\s\S]*?release\s*{/.test(updatedGradleContent)) {
604
- // Insert minifyEnabled if not present
605
- updatedGradleContent = updatedGradleContent.replace(
606
- /(buildTypes\s*{[\s\S]*?release\s*{)/,
607
- `$1\n minifyEnabled ${desiredMinify}`
608
- );
609
- console.log(`✅ Inserted minifyEnabled ${desiredMinify} into release block.`);
610
- } else {
611
- console.log('⚠️ Warning: buildTypes > release block not found. minifyEnabled was not added.');
612
- }
613
-
614
-
615
-
616
-
617
-
618
-
619
- // Write the updated gradle content back to build.gradle
620
- writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
621
- console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en" and "minifyEnabled true"`);
622
-
623
- storeIds.forEach((id) => {
624
- console.log(`ℹ️ Building for Store ID ${id}`);
625
-
626
- // Set the environment variable for store ID
627
- process.env.VITE_STORE_ID = id;
628
-
629
- // Conditionally set the new file name
630
- let newFileName;
631
- let storeName = storeNames[id];
632
-
633
-
634
- if (
635
- isOnlyOneAPK &&
636
- ["OppoStore", "VivoStore"].includes(storeName)
637
- ) {
638
- console.log(`⏭ Skipping ${storeName} because isOnlyOneAPK is enabled`);
639
- return; // skip this iteration only
640
- }
641
-
642
-
643
- managePackages(storeName);
644
-
645
- // 🔥 Only change filename logic — nothing else touched
646
- if (isOnlyOneAPK && ["MiStore","OppoStore","VivoStore"].includes(storeName)) {
647
-
648
- newFileName =
649
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-VI_MI_OPPO-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
650
-
651
- }
652
- else if (storeName === "SamsungStore") {
653
-
654
- newFileName =
655
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
656
-
657
- }
658
- else {
659
-
660
- newFileName =
661
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName}.aab`;
662
-
663
- }
664
-
665
- //storeName="amazon"
666
- const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
667
-
668
- // Modify minSdkVersion in variables.gradle for SamsungStore
669
- const variablesGradleFilePath = join("android", "variables.gradle");
670
- let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
671
-
672
- // Extract the current minSdkVersion
673
- const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
674
- const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
675
-
676
- // Store the original minSdkVersion (only on the first iteration)
677
- if (!originalMinSdkVersion) {
678
- originalMinSdkVersion = currentMinSdkVersion;
679
- }
680
- try {
681
- // Modify the minSdkVersion based on the store
682
-
683
-
684
- if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
685
- {
686
- if (storeName === "SamsungStore" || storeName === "PlayStore" ||
687
- //_appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker"
688
-
689
- //ffmpegUsedPackages.includes(_appPackageId)
690
- _isffmpegUsed
691
- ) {
692
- if (currentMinSdkVersion !== 24) {
693
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
694
- console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
695
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
696
- }
697
- } else {
698
- // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
699
- //if (currentMinSdkVersion !== originalMinSdkVersion) {
700
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
701
- console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
702
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
703
- //}
704
- }
705
- }
706
-
707
-
708
- // Run the Node.js script to modify plugin.xml
709
- if (isAdmobFound) {
710
- execSync('node buildCodeplay/modify-plugin-xml.js', { stdio: 'inherit' });
711
- } else {
712
- console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
713
- }
714
-
715
- // Run the Vite build
716
- execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
717
-
718
-
719
-
720
-
721
-
722
-
723
- // Copy the built files to the appropriate folder
724
- const src = join("www", "*");
725
- const dest = join("android", "app", "src", "main", "assets", "public");
726
-
727
- // Use 'xcopy' command for Windows
728
- execSync(`xcopy ${src} ${dest} /E /I /Y`, { stdio: 'inherit' });
729
-
730
- // Build Android AAB file
731
- //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
732
-
733
-
734
- // Build Android AAB or APK file based on store
735
- console.log(`🏗️ Building release for ${storeName}...`);
736
-
737
- /* let buildType = "AAB";
738
- if (["VivoStore", "OppoStore", "MiStore"].includes(storeName)) {
739
- buildType = "APK";
740
- } */
741
-
742
-
743
- // Determine build type and signing type per store
744
- let buildType = ["VivoStore","OppoStore","MiStore"].includes(storeName) ? "APK" : "AAB";
745
- let signingType = buildType === "APK" ? "apksigner" : "jarsigner";
746
-
747
- // Update capacitor.config.json for this store - This is not needed
748
- //updateCapacitorConfig(buildType, signingType);
749
-
750
-
751
-
752
- /* execSync('npx cap sync android', { stdio: 'inherit' });
753
- execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' }); */
754
-
755
-
756
- execSync('npx cap sync android', { stdio: 'inherit' });
757
-
758
- if (buildType === "APK") {
759
- console.log("📦 Using custom Node signing script for APK build...");
760
- execSync('node buildCodeplay/apk-store-builder.js', { stdio: 'inherit' });
761
- } else {
762
- execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' });
763
- }
764
-
765
-
766
-
767
- // Determine output paths
768
- let oldFilePath;
769
- let newExt = buildType === "APK" ? "apk" : "aab";
770
-
771
- if (buildType === "APK") {
772
- //oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release-signed.apk");
773
- oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release.apk");
774
- } else {
775
- oldFilePath = join("android", "app", "build", "outputs", "bundle", "release", "app-release-signed.aab");
776
- }
777
-
778
- const checkFullPath = join("AAB", newFileName.replace(/\.aab$/, `.${newExt}`));
779
-
780
- // Rename the output file
781
- if (existsSync(oldFilePath)) {
782
- renameSync(oldFilePath, checkFullPath);
783
- console.log(`✅ Renamed output ${newExt.toUpperCase()} file to: ${path.basename(checkFullPath)}`);
784
- } else {
785
- console.error(`❌ ${newExt.toUpperCase()} file not found after build.`);
786
- }
787
-
788
- } catch (error) {
789
- console.error(`❌ Error during build for Store ID ${id}:`, error);
790
- process.exit(1);
791
- }
792
- });
793
-
794
- rl.close(); // Close the readline interface after all operations
795
- });
796
- });
797
-
798
-
799
-
800
-
801
-
802
- function managePackages(store) {
803
- console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
804
-
805
- let install = "";
806
- let uninstall = "";
807
-
808
-
809
-
810
- let manifestContent = readFileSync(androidManifestPath, 'utf-8');
811
-
812
- const permissionsToRemove = [
813
- 'com.android.vending.BILLING',
814
- 'com.samsung.android.iap.permission.BILLING'
815
- ];
816
-
817
-
818
- permissionsToRemove.forEach(permission => {
819
- const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
820
- if (permissionRegex.test(manifestContent)) {
821
- manifestContent = manifestContent.replace(permissionRegex, '');
822
- console.log(`✅ Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
823
- }
824
- });
825
-
826
- // Write the updated content back to the file
827
- writeFileSync(androidManifestPath, manifestContent, 'utf-8');
828
-
829
-
830
-
831
- if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
832
- install = '@revenuecat/purchases-capacitor';
833
- uninstall = 'cordova-plugin-samsungiap';
834
-
835
- // Update AndroidManifest.xml for PlayStore
836
- if(playstore)
837
- updateAndroidManifest(store,
838
- '<uses-permission android:name="com.android.vending.BILLING" />');
839
-
840
- } else if (samsung && store === "SamsungStore") {
841
- install = 'cordova-plugin-samsungiap';
842
- uninstall = '@revenuecat/purchases-capacitor';
843
-
844
- // Update AndroidManifest.xml for SamsungStore
845
- updateAndroidManifest(store,
846
- '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
847
-
848
- } else {
849
- console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
850
- try {
851
- execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
852
- execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
853
- console.log(`✅ Both plugins uninstalled successfully.`);
854
- } catch (err) {
855
- console.error("❌ Error uninstalling plugins:", err);
856
- }
857
- return;
858
- }
859
-
860
- console.log(`⚠️ Installing ${install} and uninstalling ${uninstall} for ${store}...`);
861
- try {
862
- if (install) {
863
- execSync(`npm install ${install}`, { stdio: 'inherit' });
864
- }
865
- if (uninstall) {
866
- execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
867
- }
868
- console.log(`✅ ${install} installed and ${uninstall} uninstalled successfully.`);
869
- } catch (err) {
870
- console.error(`❌ Error managing packages for ${store}:`, err);
871
- }
872
- }
873
-
874
-
875
-
876
- function updateAndroidManifest(store, addPermission) {
877
- try {
878
- if (!existsSync(androidManifestPath)) {
879
- console.error("❌ AndroidManifest.xml file not found!");
880
- return;
881
- }
882
-
883
- // Read the content of the AndroidManifest.xml
884
- let manifestContent = readFileSync(androidManifestPath, 'utf-8');
885
-
886
- // Normalize line endings to `\n` for consistent processing
887
- manifestContent = manifestContent.replace(/\r\n/g, '\n');
888
-
889
- // Check if the permission is already present
890
- if (manifestContent.includes(addPermission.trim())) {
891
- console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
892
- return; // Skip if the permission is already present
893
- }
894
-
895
- // Insert the permission before the closing </manifest> tag
896
- const closingTag = '</manifest>';
897
- const formattedPermission = ` ${addPermission.trim()}\n`;
898
- if (manifestContent.includes(closingTag)) {
899
- manifestContent = manifestContent.replace(
900
- closingTag,
901
- `${formattedPermission}${closingTag}`
902
- );
903
- console.log(`✅ Added ${addPermission} before </manifest> tag.`);
904
- } else {
905
- console.warn(`⚠️ </manifest> tag not found. Adding ${addPermission} at the end of the file.`);
906
- manifestContent += `\n${formattedPermission}`;
907
- }
908
-
909
- // Normalize line endings back to `\r\n` and write the updated content
910
- manifestContent = manifestContent.replace(/\n/g, '\r\n');
911
- writeFileSync(androidManifestPath, manifestContent, 'utf-8');
912
- console.log(`✅ AndroidManifest.xml updated successfully for ${store}`);
913
- } catch (err) {
914
- console.error(`❌ Error updating AndroidManifest.xml for ${store}:`, err);
915
- }
916
- }
917
-
918
-
919
-
920
- /* restoreCapacitorConfig();
921
- console.log("🏁 All builds completed, capacitor.config.json restored."); */
922
-
923
-
924
- /* function updateAndroidManifest1(store, addPermission) {
925
- try {
926
- if (!fs.existsSync(androidManifestPath)) {
927
- console.error("AndroidManifest.xml file not found!");
928
- return;
929
- }
930
-
931
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
932
-
933
-
934
-
935
- // Add the required permission if not already present
936
- if (!manifestContent.includes(addPermission)) {
937
- const manifestLines = manifestContent.split('\n');
938
- const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
939
- if (insertIndex > -1) {
940
- manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
941
- manifestContent = manifestLines.join('\n');
942
- console.log(`Added ${addPermission} to AndroidManifest.xml`);
943
- }
944
- }
945
-
946
- // Write the updated content back to the file
947
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
948
- console.log(`AndroidManifest.xml updated successfully for ${store}`);
949
- } catch (err) {
950
- console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
951
- }
952
- } */
953
-
954
-
955
-
956
-
957
-
958
-
959
-
960
-
1
+ /*
2
+ Can be run like
3
+ node finalrelease
4
+ node finalrelease 1
5
+ node finalrelease "1,2,7"
6
+ */
7
+
8
+ import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
9
+ import { join, resolve } from 'path';
10
+ import { execSync } from 'child_process';
11
+ import { createInterface } from 'readline';
12
+
13
+ import { fileURLToPath } from 'url';
14
+ import { dirname } from 'path';
15
+
16
+ /* const path = require('path');
17
+ const fs = require('fs'); */
18
+
19
+ import fs from 'fs';
20
+ import path from 'path';
21
+
22
+ // Define a mapping between store IDs and store names
23
+ /* const storeNames = {
24
+ "1": "PlayStore",
25
+ "2": "SamsungStore",
26
+ "7": "AmazonStore"
27
+ }; */
28
+
29
+
30
+ const isOnlyOneAPK = true; // 🔥 change to false for normal behavior
31
+
32
+ const storeNames = {
33
+ "1": "PlayStore",
34
+ "2": "SamsungStore",
35
+ "7": "AmazonStore",
36
+
37
+ "3": "MiStore",
38
+ "4": "HuaweiStore",
39
+ "5": "OppoStore",
40
+ //"6": "iOSStore",
41
+ "8": "VivoStore"
42
+ };
43
+
44
+
45
+ //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+ let isAdmobFound = false;
54
+
55
+ const amazonMinSdkVersion=24;
56
+
57
+ const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
58
+
59
+
60
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
61
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
62
+
63
+ const _appUniqueId = config.android?.APP_UNIQUE_ID;
64
+ const _appName=config.appName;
65
+ const _appPackageId=config.appId;
66
+
67
+
68
+
69
+ const __filename = fileURLToPath(import.meta.url);
70
+ const __dirname = dirname(__filename);
71
+
72
+ function fileExists(filePath) {
73
+ return existsSync(filePath);
74
+ }
75
+
76
+
77
+ const ffmpegPluginXmlPath = path.join(__dirname, 'node_modules', 'codeplay-fmpg', 'plugin.xml');
78
+ const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
79
+
80
+
81
+
82
+ function isFfmpegUsed() {
83
+ try {
84
+ const xmlContent = fs.readFileSync(ffmpegPluginXmlPath, 'utf8');
85
+ // Simple check: if plugin.xml exists and contains <plugin> tag (or any FFmpeg-specific tag)
86
+ return /<plugin\b/.test(xmlContent);
87
+ } catch (err) {
88
+ console.log('⚠️ FFmpeg plugin not found:', err.message);
89
+ return false;
90
+ }
91
+ }
92
+
93
+ const _isffmpegUsed = isFfmpegUsed();
94
+
95
+ function getAdMobConfig() {
96
+ if (!fileExists(capacitorConfigPath)) {
97
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
98
+ }
99
+
100
+ const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
101
+ const admobConfig = config.plugins?.AdMob;
102
+
103
+ //_appPackageId=config.appId;
104
+
105
+ if (!admobConfig) {
106
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
107
+ }
108
+
109
+ // Default to true if ADMOB_ENABLED is not specified
110
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
111
+
112
+ if (!isEnabled) {
113
+ return { ADMOB_ENABLED: false }; // Skip further validation
114
+ }
115
+
116
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
117
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
118
+ }
119
+
120
+ return {
121
+ ADMOB_ENABLED: true,
122
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
123
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
124
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
125
+ };
126
+ }
127
+
128
+
129
+
130
+ const _capacitorConfig = getAdMobConfig();
131
+
132
+ const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
133
+
134
+ // Proceed only if ADMOB_ENABLED is true
135
+ //if (_capacitorConfig.ADMOB_ENABLED)
136
+
137
+
138
+ const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration.json');
139
+ let admobConfig;
140
+
141
+ if (_isADMOB_ENABLED)
142
+ {
143
+ try
144
+ {
145
+ admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
146
+ }
147
+ catch (err)
148
+ {
149
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
150
+ process.exit(1);
151
+ }
152
+ }
153
+
154
+
155
+
156
+
157
+
158
+ function updateIOSVersion(versionCode, versionName) {
159
+
160
+ const pbxprojPath = join("ios", "App", "App.xcodeproj", "project.pbxproj");
161
+
162
+ // 🔥 Single check only
163
+ if (!existsSync(pbxprojPath)) {
164
+ console.warn("⚠️ iOS project not found, skipping version update");
165
+ return;
166
+ }
167
+
168
+
169
+ let content = readFileSync(pbxprojPath, 'utf8');
170
+
171
+ // Update MARKETING_VERSION
172
+ content = content.replace(
173
+ /MARKETING_VERSION = .*?;/g,
174
+ `MARKETING_VERSION = ${versionName};`
175
+ );
176
+
177
+ // Update CURRENT_PROJECT_VERSION
178
+ /* content = content.replace(
179
+ /CURRENT_PROJECT_VERSION = .*?;/g,
180
+ `CURRENT_PROJECT_VERSION = ${versionCode};`
181
+ ); */
182
+
183
+ writeFileSync(pbxprojPath, content, 'utf8');
184
+
185
+ console.log(`🍏 iOS updated via Xcode settings → version: ${versionName}, build: ${versionCode}`);
186
+ }
187
+
188
+
189
+
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+
198
+
199
+
200
+
201
+
202
+
203
+
204
+
205
+
206
+
207
+
208
+ const checkCommonFileStoreId=()=>{
209
+ const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
210
+ let viteConfigPath;
211
+ for (const configFile of possibleConfigFiles) {
212
+ const fullPath = resolve( configFile);
213
+ if (existsSync(fullPath)) {
214
+ viteConfigPath = fullPath;
215
+ break;
216
+ }
217
+ }
218
+
219
+ if (!viteConfigPath) {
220
+ console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
221
+ process.exit(1);
222
+ }
223
+
224
+ try {
225
+ // Read vite config file
226
+ const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
227
+
228
+ // Extract @common alias path
229
+ const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
230
+ const match = viteConfigContent.match(aliasPattern);
231
+
232
+ if (!match) {
233
+ console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
234
+ process.exit(1);
235
+ }
236
+
237
+ const commonFilePath = match[1];
238
+ const resolvedCommonPath = resolve(__dirname, commonFilePath);
239
+
240
+ // Read the common file content
241
+ if (!existsSync(resolvedCommonPath)) {
242
+ console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
243
+ process.exit(1);
244
+ }
245
+
246
+ const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
247
+
248
+ // Check for the _storeid export line
249
+ const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
250
+ if (!storeIdPattern.test(commonFileContent)) {
251
+ console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
252
+ process.exit(1);
253
+ }
254
+
255
+ console.log(commonFilePath,'Success - No problem found');
256
+ } catch (error) {
257
+ console.error('❌ Error:', error);
258
+ process.exit(1);
259
+ }
260
+
261
+ }
262
+
263
+ const checkIsTestingInAdmob=()=>{
264
+
265
+ if (admobConfig.config && admobConfig.config.isTesting === true) {
266
+ console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration.json" file.`);
267
+ process.exit(1); // Exit with an error code to halt the process
268
+ } else {
269
+ console.log('✅ No problem found. "isTesting" is either already false or not defined.');
270
+ }
271
+ }
272
+
273
+ const checkIsAdsDisableByReturnStatement=()=>{
274
+
275
+
276
+ const adsFolder = join('src', 'js', 'Ads');
277
+ const filePattern = /^admob-emi-(\d+\.)+\d+\.js$/;
278
+
279
+ // Step 1: Find the admob file
280
+ const files = readdirSync(adsFolder);
281
+ const admobFile = files.find(f => filePattern.test(f));
282
+
283
+ if (!admobFile) {
284
+ console.log('❌ No Admob file found.');
285
+ process.exit(1);
286
+ }
287
+
288
+ const filePath = join(adsFolder, admobFile);
289
+ const content = readFileSync(filePath, 'utf-8');
290
+
291
+ // Step 2: Extract the adsOnDeviceReady function body
292
+ const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
293
+ const match = content.match(functionRegex);
294
+
295
+ if (!match) {
296
+ console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
297
+ process.exit(1);
298
+ }
299
+
300
+ const body = match[1];
301
+ const lines = body.split('\n').map(line => line.trim());
302
+
303
+ // Step 3: Skip blank lines and comments, get the first real code line
304
+ let firstCodeLine = '';
305
+ for (const line of lines) {
306
+ if (line === '' || line.startsWith('//')) continue;
307
+ firstCodeLine = line;
308
+ break;
309
+ }
310
+
311
+ // Step 4: Block if it's any of the unwanted returns
312
+ const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
313
+
314
+ if (badReturnPattern.test(firstCodeLine)) {
315
+ console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
316
+ process.exit(2);
317
+ } else {
318
+ console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
319
+ }
320
+ }
321
+
322
+
323
+
324
+ const addPermission_AD_ID=async()=>{
325
+
326
+ const admobPluginXmlPath = join('node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
327
+
328
+
329
+ //let isAdmobFound = false;
330
+ try {
331
+ await promises.access(admobPluginXmlPath, constants.F_OK);
332
+ isAdmobFound = true;
333
+ } catch (err) {
334
+ isAdmobFound = false;
335
+ }
336
+
337
+
338
+
339
+ if (isAdmobFound) {
340
+ if (existsSync(androidManifestPath)) {
341
+ let manifestContent = readFileSync(androidManifestPath, 'utf8');
342
+ let modified = false;
343
+
344
+ // --- Step 1: Ensure AD_ID permission exists ---
345
+ const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
346
+ if (!manifestContent.includes(adIdPermission)) {
347
+ console.log("📄 AD_ID permission not found. Adding to AndroidManifest.xml.");
348
+ manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
349
+ console.log("✅ AD_ID permission added successfully.");
350
+ modified = true;
351
+ } else {
352
+ console.log("ℹ️ AD_ID permission already exists in AndroidManifest.xml.");
353
+ }
354
+
355
+ // --- Step 2: Ensure OPTIMIZE_AD_LOADING meta-data exists ---
356
+ const optimizeAdMeta = `<meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" />`;
357
+
358
+ if (!manifestContent.includes(optimizeAdMeta)) {
359
+ console.log("📄 OPTIMIZE_AD_LOADING meta-data not found. Adding to AndroidManifest.xml.");
360
+
361
+ const appTagPattern = /<application[^>]*>/;
362
+ if (appTagPattern.test(manifestContent)) {
363
+ manifestContent = manifestContent.replace(appTagPattern, match => `${match}\n ${optimizeAdMeta}`);
364
+ console.log("✅ OPTIMIZE_AD_LOADING meta-data added successfully.");
365
+ modified = true;
366
+ } else {
367
+ console.error("❌ <application> tag not found in AndroidManifest.xml.");
368
+ }
369
+ } else {
370
+ console.log("ℹ️ OPTIMIZE_AD_LOADING meta-data already exists in AndroidManifest.xml.");
371
+ }
372
+
373
+ // --- Step 3: Write only if modified ---
374
+ if (modified) {
375
+ writeFileSync(androidManifestPath, manifestContent, 'utf8');
376
+ console.log("💾 AndroidManifest.xml updated successfully.");
377
+ } else {
378
+ console.log("✅ No changes needed. AndroidManifest.xml is up to date.");
379
+ }
380
+
381
+ } else {
382
+ console.error("❌ AndroidManifest.xml not found at the specified path.");
383
+ }
384
+ } else {
385
+ console.log("\x1b[33m%s\x1b[0m", "⚠️ No AdMob found, so AD_ID permission and meta-data were not added");
386
+ }
387
+
388
+
389
+
390
+
391
+
392
+
393
+ }
394
+
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+
403
+
404
+
405
+ checkCommonFileStoreId();
406
+
407
+
408
+
409
+ if (_isADMOB_ENABLED)
410
+ {
411
+ checkIsTestingInAdmob();
412
+ checkIsAdsDisableByReturnStatement()
413
+
414
+ await addPermission_AD_ID()
415
+ }
416
+
417
+
418
+
419
+ let originalReleaseType, originalSigningType;
420
+
421
+ function readCapacitorConfig() {
422
+ return JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
423
+ }
424
+
425
+ function writeCapacitorConfig(config) {
426
+ fs.writeFileSync(capacitorConfigPath, JSON.stringify(config, null, 2), 'utf8');
427
+ }
428
+
429
+ /* function updateCapacitorConfig(releaseType, signingType) {
430
+ const config = readCapacitorConfig();
431
+
432
+ // Save original values once
433
+ if (originalReleaseType === undefined) originalReleaseType = config.android?.buildOptions?.releaseType || '';
434
+ if (originalSigningType === undefined) originalSigningType = config.android?.buildOptions?.signingType || '';
435
+
436
+ // Update values
437
+ config.android = config.android || {};
438
+ config.android.buildOptions = config.android.buildOptions || {};
439
+ config.android.buildOptions.releaseType = releaseType;
440
+ config.android.buildOptions.signingType = signingType;
441
+
442
+ writeCapacitorConfig(config);
443
+ console.log(`ℹ️ capacitor.config.json updated: releaseType=${releaseType}, signingType=${signingType}`);
444
+ } */
445
+
446
+ /* function restoreCapacitorConfig() {
447
+ const config = readCapacitorConfig();
448
+ if (originalReleaseType !== undefined) config.android.buildOptions.releaseType = originalReleaseType;
449
+ if (originalSigningType !== undefined) config.android.buildOptions.signingType = originalSigningType;
450
+ writeCapacitorConfig(config);
451
+ console.log(`✅ capacitor.config.json restored to original values.`);
452
+ }
453
+
454
+ process.on('SIGINT', () => {
455
+ console.log('\n⚠️ Detected Ctrl+C, restoring capacitor.config.json...');
456
+ restoreCapacitorConfig();
457
+ process.exit(0);
458
+ });
459
+
460
+ process.on('exit', () => {
461
+ restoreCapacitorConfig();
462
+ }); */
463
+
464
+
465
+
466
+ const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
467
+ console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
468
+
469
+
470
+
471
+
472
+
473
+
474
+ // Get the store ID from the command line arguments
475
+ /* const storeIdArg = ["2","3"]//process.argv[2]; // Get the store ID from the command line
476
+ const storeIds = storeIdArg ? storeIdArg : Object.keys(storeNames);//["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
477
+
478
+ debugger; */
479
+
480
+ let storeIdArg = process.argv[2]; // command-line argument
481
+ let storeIds;
482
+
483
+ if (storeIdArg) {
484
+ try {
485
+ // Try parsing as JSON array first
486
+ const parsed = JSON.parse(storeIdArg);
487
+ if (Array.isArray(parsed)) {
488
+ storeIds = parsed.map(String); // ensure strings
489
+ } else {
490
+ storeIds = [parsed.toString()];
491
+ }
492
+ } catch (e) {
493
+ // Not JSON, assume comma-separated string
494
+ storeIds = storeIdArg.split(",").map(s => s.trim());
495
+ }
496
+ } else {
497
+ // No argument, use all store IDs
498
+ storeIds = Object.keys(storeNames);
499
+ }
500
+
501
+
502
+ // 🔥 If only one APK mode, override APK storeIds
503
+ /* if (isOnlyOneAPK) {
504
+ console.log("⚡ isOnlyOneAPK enabled → Only MiStore (3) will be used for APK build");
505
+ storeIds = ["3"]; // Only MiStore
506
+ } */
507
+
508
+ // Store the original minSdkVersion globally
509
+ let originalMinSdkVersion;
510
+
511
+ // Remove any existing AAB files before starting the build process
512
+ const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
513
+ if (existsSync(aabDirectory)) {
514
+ const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
515
+ files.forEach(file => {
516
+ const filePath = join(aabDirectory, file);
517
+ unlinkSync(filePath);
518
+ console.log(`ℹ️ Deleted existing AAB file: ${file}`);
519
+ });
520
+ }
521
+
522
+ const aabOutputDir = join("AAB");
523
+ if (!existsSync(aabOutputDir)) {
524
+ mkdirSync(aabOutputDir);
525
+ console.log(`Created directory: ${aabOutputDir}`);
526
+ }
527
+
528
+ if (existsSync(aabOutputDir)) {
529
+ const files = readdirSync(aabOutputDir).filter(
530
+ file => file.endsWith('.aab') || file.endsWith('.apk')
531
+ );
532
+
533
+ files.forEach(file => {
534
+ const filePath = join(aabOutputDir, file);
535
+ unlinkSync(filePath);
536
+ console.log(`Deleted existing build file: ${file}`);
537
+ });
538
+ }
539
+
540
+
541
+ // Extract version code and version name from build.gradle
542
+ const gradleFilePath = join("android", "app", "build.gradle");
543
+ const gradleContent = readFileSync(gradleFilePath, 'utf8');
544
+
545
+ const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
546
+ const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
547
+
548
+ const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
549
+ const versionName = versionNameMatch ? versionNameMatch[1] : '';
550
+
551
+ // Display the current versionCode and versionName
552
+ console.log(`Current versionCode: ${versionCode}`);
553
+ console.log(`Current versionName: ${versionName}`);
554
+
555
+ // Create an interface for user input
556
+ const rl = createInterface({
557
+ input: process.stdin,
558
+ output: process.stdout
559
+ });
560
+
561
+ // Ask for new versionCode
562
+ rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
563
+ const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
564
+
565
+ // Ask for new versionName
566
+ rl.question('Enter new versionName (press enter to keep current): ', (newVersionName) => {
567
+ const finalVersionName = newVersionName || versionName; // Use existing if no input
568
+
569
+ // Log the final version details
570
+ console.log(`📦 Final versionCode: ${finalVersionCode}`);
571
+ console.log(`📝 Final versionName: ${finalVersionName}`);
572
+
573
+
574
+ updateIOSVersion(finalVersionCode, finalVersionName);
575
+
576
+ // Update build.gradle with the new version details
577
+ let updatedGradleContent = gradleContent
578
+ .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
579
+ .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
580
+
581
+ // Check if resConfigs "en" already exists
582
+ const resConfigsLine = ' resConfigs "en"';
583
+ if (!updatedGradleContent.includes(resConfigsLine)) {
584
+ // Add resConfigs "en" below versionName
585
+ updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
586
+ } else {
587
+ console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
588
+ }
589
+
590
+
591
+
592
+ // List of package IDs for which minify should be false
593
+
594
+
595
+ // Determine desired minify value
596
+ const desiredMinify = !_isffmpegUsed;
597
+
598
+ // Check if minifyEnabled is already present
599
+ if (/minifyEnabled\s+(true|false)/.test(updatedGradleContent)) {
600
+ // Replace existing value with desired
601
+ updatedGradleContent = updatedGradleContent.replace(/minifyEnabled\s+(true|false)/, `minifyEnabled ${desiredMinify}`);
602
+ console.log(`Replaced minifyEnabled with ${desiredMinify}.`);
603
+ } else if (/buildTypes\s*{[\s\S]*?release\s*{/.test(updatedGradleContent)) {
604
+ // Insert minifyEnabled if not present
605
+ updatedGradleContent = updatedGradleContent.replace(
606
+ /(buildTypes\s*{[\s\S]*?release\s*{)/,
607
+ `$1\n minifyEnabled ${desiredMinify}`
608
+ );
609
+ console.log(`✅ Inserted minifyEnabled ${desiredMinify} into release block.`);
610
+ } else {
611
+ console.log('⚠️ Warning: buildTypes > release block not found. minifyEnabled was not added.');
612
+ }
613
+
614
+
615
+
616
+
617
+
618
+
619
+ // Write the updated gradle content back to build.gradle
620
+ writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
621
+ console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en" and "minifyEnabled true"`);
622
+
623
+ storeIds.forEach((id) => {
624
+ console.log(`ℹ️ Building for Store ID ${id}`);
625
+
626
+ // Set the environment variable for store ID
627
+ process.env.VITE_STORE_ID = id;
628
+
629
+ // Conditionally set the new file name
630
+ let newFileName;
631
+ let storeName = storeNames[id];
632
+
633
+
634
+ if (
635
+ isOnlyOneAPK &&
636
+ ["OppoStore", "VivoStore"].includes(storeName)
637
+ ) {
638
+ console.log(`⏭ Skipping ${storeName} because isOnlyOneAPK is enabled`);
639
+ return; // skip this iteration only
640
+ }
641
+
642
+
643
+ managePackages(storeName);
644
+
645
+ // 🔥 Only change filename logic — nothing else touched
646
+ if (isOnlyOneAPK && ["MiStore","OppoStore","VivoStore"].includes(storeName)) {
647
+
648
+ newFileName =
649
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-VI_MI_OPPO-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
650
+
651
+ }
652
+ else if (storeName === "SamsungStore") {
653
+
654
+ newFileName =
655
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
656
+
657
+ }
658
+ else {
659
+
660
+ newFileName =
661
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName}.aab`;
662
+
663
+ }
664
+
665
+ //storeName="amazon"
666
+ const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
667
+
668
+ // Modify minSdkVersion in variables.gradle for SamsungStore
669
+ const variablesGradleFilePath = join("android", "variables.gradle");
670
+ let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
671
+
672
+ // Extract the current minSdkVersion
673
+ const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
674
+ const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
675
+
676
+ // Store the original minSdkVersion (only on the first iteration)
677
+ if (!originalMinSdkVersion) {
678
+ originalMinSdkVersion = currentMinSdkVersion;
679
+ }
680
+ try {
681
+ // Modify the minSdkVersion based on the store
682
+
683
+
684
+ if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
685
+ {
686
+ if (storeName === "SamsungStore" || storeName === "PlayStore" ||
687
+ //_appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker"
688
+
689
+ //ffmpegUsedPackages.includes(_appPackageId)
690
+ _isffmpegUsed
691
+ ) {
692
+ if (currentMinSdkVersion !== 24) {
693
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
694
+ console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
695
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
696
+ }
697
+ } else {
698
+ // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
699
+ //if (currentMinSdkVersion !== originalMinSdkVersion) {
700
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
701
+ console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
702
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
703
+ //}
704
+ }
705
+ }
706
+
707
+
708
+ // Run the Node.js script to modify plugin.xml
709
+ if (isAdmobFound) {
710
+ execSync('node buildCodeplay/modify-plugin-xml.js', { stdio: 'inherit' });
711
+ } else {
712
+ console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
713
+ }
714
+
715
+ // Run the Vite build
716
+ execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
717
+
718
+
719
+
720
+
721
+
722
+
723
+ // Copy the built files to the appropriate folder
724
+ const src = join("www", "*");
725
+ const dest = join("android", "app", "src", "main", "assets", "public");
726
+
727
+ // Use 'xcopy' command for Windows
728
+ execSync(`xcopy ${src} ${dest} /E /I /Y`, { stdio: 'inherit' });
729
+
730
+ // Build Android AAB file
731
+ //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
732
+
733
+
734
+ // Build Android AAB or APK file based on store
735
+ console.log(`🏗️ Building release for ${storeName}...`);
736
+
737
+ /* let buildType = "AAB";
738
+ if (["VivoStore", "OppoStore", "MiStore"].includes(storeName)) {
739
+ buildType = "APK";
740
+ } */
741
+
742
+
743
+ // Determine build type and signing type per store
744
+ let buildType = ["VivoStore","OppoStore","MiStore"].includes(storeName) ? "APK" : "AAB";
745
+ let signingType = buildType === "APK" ? "apksigner" : "jarsigner";
746
+
747
+ // Update capacitor.config.json for this store - This is not needed
748
+ //updateCapacitorConfig(buildType, signingType);
749
+
750
+
751
+
752
+ /* execSync('npx cap sync android', { stdio: 'inherit' });
753
+ execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' }); */
754
+
755
+
756
+ execSync('npx cap sync android', { stdio: 'inherit' });
757
+
758
+ if (buildType === "APK") {
759
+ console.log("📦 Using custom Node signing script for APK build...");
760
+ execSync('node buildCodeplay/apk-store-builder.js', { stdio: 'inherit' });
761
+ } else {
762
+ execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' });
763
+ }
764
+
765
+
766
+
767
+ // Determine output paths
768
+ let oldFilePath;
769
+ let newExt = buildType === "APK" ? "apk" : "aab";
770
+
771
+ if (buildType === "APK") {
772
+ //oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release-signed.apk");
773
+ oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release.apk");
774
+ } else {
775
+ oldFilePath = join("android", "app", "build", "outputs", "bundle", "release", "app-release-signed.aab");
776
+ }
777
+
778
+ const checkFullPath = join("AAB", newFileName.replace(/\.aab$/, `.${newExt}`));
779
+
780
+ // Rename the output file
781
+ if (existsSync(oldFilePath)) {
782
+ renameSync(oldFilePath, checkFullPath);
783
+ console.log(`✅ Renamed output ${newExt.toUpperCase()} file to: ${path.basename(checkFullPath)}`);
784
+ } else {
785
+ console.error(`❌ ${newExt.toUpperCase()} file not found after build.`);
786
+ }
787
+
788
+ } catch (error) {
789
+ console.error(`❌ Error during build for Store ID ${id}:`, error);
790
+ process.exit(1);
791
+ }
792
+ });
793
+
794
+ rl.close(); // Close the readline interface after all operations
795
+ });
796
+ });
797
+
798
+
799
+
800
+
801
+
802
+ function managePackages(store) {
803
+ console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
804
+
805
+ let install = "";
806
+ let uninstall = "";
807
+
808
+
809
+
810
+ let manifestContent = readFileSync(androidManifestPath, 'utf-8');
811
+
812
+ const permissionsToRemove = [
813
+ 'com.android.vending.BILLING',
814
+ 'com.samsung.android.iap.permission.BILLING'
815
+ ];
816
+
817
+
818
+ permissionsToRemove.forEach(permission => {
819
+ const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
820
+ if (permissionRegex.test(manifestContent)) {
821
+ manifestContent = manifestContent.replace(permissionRegex, '');
822
+ console.log(`✅ Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
823
+ }
824
+ });
825
+
826
+ // Write the updated content back to the file
827
+ writeFileSync(androidManifestPath, manifestContent, 'utf-8');
828
+
829
+
830
+
831
+ if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
832
+ install = '@revenuecat/purchases-capacitor';
833
+ uninstall = 'cordova-plugin-samsungiap';
834
+
835
+ // Update AndroidManifest.xml for PlayStore
836
+ if(playstore)
837
+ updateAndroidManifest(store,
838
+ '<uses-permission android:name="com.android.vending.BILLING" />');
839
+
840
+ } else if (samsung && store === "SamsungStore") {
841
+ install = 'cordova-plugin-samsungiap';
842
+ uninstall = '@revenuecat/purchases-capacitor';
843
+
844
+ // Update AndroidManifest.xml for SamsungStore
845
+ updateAndroidManifest(store,
846
+ '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
847
+
848
+ } else {
849
+ console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
850
+ try {
851
+ execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
852
+ execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
853
+ console.log(`✅ Both plugins uninstalled successfully.`);
854
+ } catch (err) {
855
+ console.error("❌ Error uninstalling plugins:", err);
856
+ }
857
+ return;
858
+ }
859
+
860
+ console.log(`⚠️ Installing ${install} and uninstalling ${uninstall} for ${store}...`);
861
+ try {
862
+ if (install) {
863
+ execSync(`npm install ${install}`, { stdio: 'inherit' });
864
+ }
865
+ if (uninstall) {
866
+ execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
867
+ }
868
+ console.log(`✅ ${install} installed and ${uninstall} uninstalled successfully.`);
869
+ } catch (err) {
870
+ console.error(`❌ Error managing packages for ${store}:`, err);
871
+ }
872
+ }
873
+
874
+
875
+
876
+ function updateAndroidManifest(store, addPermission) {
877
+ try {
878
+ if (!existsSync(androidManifestPath)) {
879
+ console.error("❌ AndroidManifest.xml file not found!");
880
+ return;
881
+ }
882
+
883
+ // Read the content of the AndroidManifest.xml
884
+ let manifestContent = readFileSync(androidManifestPath, 'utf-8');
885
+
886
+ // Normalize line endings to `\n` for consistent processing
887
+ manifestContent = manifestContent.replace(/\r\n/g, '\n');
888
+
889
+ // Check if the permission is already present
890
+ if (manifestContent.includes(addPermission.trim())) {
891
+ console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
892
+ return; // Skip if the permission is already present
893
+ }
894
+
895
+ // Insert the permission before the closing </manifest> tag
896
+ const closingTag = '</manifest>';
897
+ const formattedPermission = ` ${addPermission.trim()}\n`;
898
+ if (manifestContent.includes(closingTag)) {
899
+ manifestContent = manifestContent.replace(
900
+ closingTag,
901
+ `${formattedPermission}${closingTag}`
902
+ );
903
+ console.log(`✅ Added ${addPermission} before </manifest> tag.`);
904
+ } else {
905
+ console.warn(`⚠️ </manifest> tag not found. Adding ${addPermission} at the end of the file.`);
906
+ manifestContent += `\n${formattedPermission}`;
907
+ }
908
+
909
+ // Normalize line endings back to `\r\n` and write the updated content
910
+ manifestContent = manifestContent.replace(/\n/g, '\r\n');
911
+ writeFileSync(androidManifestPath, manifestContent, 'utf-8');
912
+ console.log(`✅ AndroidManifest.xml updated successfully for ${store}`);
913
+ } catch (err) {
914
+ console.error(`❌ Error updating AndroidManifest.xml for ${store}:`, err);
915
+ }
916
+ }
917
+
918
+
919
+
920
+ /* restoreCapacitorConfig();
921
+ console.log("🏁 All builds completed, capacitor.config.json restored."); */
922
+
923
+
924
+ /* function updateAndroidManifest1(store, addPermission) {
925
+ try {
926
+ if (!fs.existsSync(androidManifestPath)) {
927
+ console.error("AndroidManifest.xml file not found!");
928
+ return;
929
+ }
930
+
931
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
932
+
933
+
934
+
935
+ // Add the required permission if not already present
936
+ if (!manifestContent.includes(addPermission)) {
937
+ const manifestLines = manifestContent.split('\n');
938
+ const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
939
+ if (insertIndex > -1) {
940
+ manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
941
+ manifestContent = manifestLines.join('\n');
942
+ console.log(`Added ${addPermission} to AndroidManifest.xml`);
943
+ }
944
+ }
945
+
946
+ // Write the updated content back to the file
947
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
948
+ console.log(`AndroidManifest.xml updated successfully for ${store}`);
949
+ } catch (err) {
950
+ console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
951
+ }
952
+ } */
953
+
954
+
955
+
956
+
957
+
958
+
959
+
960
+