codeplay-common 3.1.2 → 3.1.4

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