codeplay-common 4.2.0 → 4.2.2

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