codeplay-common 1.0.21 → 1.0.22

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,493 +1,493 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const child_process = require('child_process');
4
- const readline = require('readline');
5
-
6
- // Define a mapping between store IDs and store names
7
- const storeNames = {
8
- "1": "PlayStore",
9
- "2": "SamsungStore",
10
- "7": "AmazonStore"
11
- };
12
-
13
- const androidManifestPath = path.join("android", "app", "src", "main", "AndroidManifest.xml");
14
-
15
-
16
-
17
- const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
18
- let admobConfig;
19
- try {
20
- admobConfig = JSON.parse(fs.readFileSync(admobConfigPath, 'utf8'));
21
- } catch (err) {
22
- console.error("Failed to read admob-ad-configuration.json", err);
23
- process.exit(1);
24
- }
25
-
26
-
27
-
28
-
29
- const checkCommonFileStoreId=()=>{
30
- const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
31
- let viteConfigPath;
32
- for (const configFile of possibleConfigFiles) {
33
- const fullPath = path.resolve( configFile);
34
- if (fs.existsSync(fullPath)) {
35
- viteConfigPath = fullPath;
36
- break;
37
- }
38
- }
39
-
40
- if (!viteConfigPath) {
41
- console.error('Error: No vite.config.mjs or vite.config.js file found.');
42
- process.exit(1);
43
- }
44
-
45
- try {
46
- // Read vite config file
47
- const viteConfigContent = fs.readFileSync(viteConfigPath, 'utf-8');
48
-
49
- // Extract @common alias path
50
- const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
51
- const match = viteConfigContent.match(aliasPattern);
52
-
53
- if (!match) {
54
- console.error(`Error: @common alias not found in ${viteConfigPath}`);
55
- process.exit(1);
56
- }
57
-
58
- const commonFilePath = match[1];
59
- const resolvedCommonPath = path.resolve(__dirname, commonFilePath);
60
-
61
- // Read the common file content
62
- if (!fs.existsSync(resolvedCommonPath)) {
63
- console.error(`Error: Resolved common file does not exist: ${resolvedCommonPath}`);
64
- process.exit(1);
65
- }
66
-
67
- const commonFileContent = fs.readFileSync(resolvedCommonPath, 'utf-8');
68
-
69
- // Check for the _storeid export line
70
- const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
71
- if (!storeIdPattern.test(commonFileContent)) {
72
- console.error(`Error: _storeid value is wrong in ${commonFilePath}`);
73
- process.exit(1);
74
- }
75
-
76
- console.log(commonFilePath,'Success - No problem found');
77
- } catch (error) {
78
- console.error('Error:', error);
79
- process.exit(1);
80
- }
81
-
82
- }
83
-
84
- const checkIsTestingInAdmob=()=>{
85
-
86
- if (admobConfig.config && admobConfig.config.isTesting === true) {
87
- console.error(`Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration.json" file.`);
88
- process.exit(1); // Exit with an error code to halt the process
89
- } else {
90
- console.log('No problem found. "isTesting" is either already false or not defined.');
91
- }
92
- }
93
-
94
- const addPermission_AD_ID=()=>{
95
-
96
- const admobPluginXmlPath = path.join('node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
97
-
98
-
99
- fs.access(admobPluginXmlPath, fs.constants.F_OK, (err) => {
100
- if (err) {
101
- isAdmobFound = false;
102
- } else {
103
- isAdmobFound = true;
104
- }
105
- });
106
-
107
-
108
- if (isAdmobFound) {
109
- // Check if AndroidManifest.xml exists
110
- if (fs.existsSync(androidManifestPath)) {
111
- // Read the content of AndroidManifest.xml
112
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf8');
113
-
114
- // Check if the ad_id permission already exists
115
- const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
116
- if (!manifestContent.includes(adIdPermission)) {
117
- console.log("ad_id permission not found. Adding to AndroidManifest.xml.");
118
-
119
- // Add the ad_id permission before the closing </manifest> tag
120
- manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
121
-
122
- // Write the updated manifest content back to AndroidManifest.xml
123
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf8');
124
- console.log("ad_id permission added successfully.");
125
- } else {
126
- console.log("ad_id permission already exists in AndroidManifest.xml.");
127
- }
128
- } else {
129
- console.error("AndroidManifest.xml not found at the specified path.");
130
- }
131
- } else {
132
- console.log("\x1b[33m%s\x1b[0m", "No admob found, so permission.AD_ID is not added");
133
- }
134
- }
135
-
136
-
137
- checkCommonFileStoreId();
138
- checkIsTestingInAdmob();
139
-
140
-
141
- let isAdmobFound = true;
142
- addPermission_AD_ID()
143
-
144
-
145
-
146
- const { playstore, samsung, amazon } = admobConfig.IAP;
147
- console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
148
-
149
-
150
-
151
-
152
-
153
-
154
- // Get the store ID from the command line arguments
155
- const storeIdArg = process.argv[2]; // Get the store ID from the command line
156
- const storeIds = storeIdArg ? [storeIdArg] : ["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
157
-
158
- // Store the original minSdkVersion globally
159
- let originalMinSdkVersion;
160
-
161
- // Remove any existing AAB files before starting the build process
162
- const aabDirectory = path.join("android", "app", "build", "outputs", "bundle", "release");
163
- if (fs.existsSync(aabDirectory)) {
164
- const files = fs.readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
165
- files.forEach(file => {
166
- const filePath = path.join(aabDirectory, file);
167
- fs.unlinkSync(filePath);
168
- console.log(`Deleted existing AAB file: ${file}`);
169
- });
170
- }
171
-
172
- const aabOutputDir = path.join("AAB");
173
- if (!fs.existsSync(aabOutputDir)) {
174
- fs.mkdirSync(aabOutputDir);
175
- console.log(`Created directory: ${aabOutputDir}`);
176
- }
177
-
178
- if (fs.existsSync(aabOutputDir)) {
179
- const files = fs.readdirSync(aabOutputDir).filter(file => file.endsWith('.aab'));
180
- files.forEach(file => {
181
- const filePath = path.join(aabOutputDir, file);
182
- fs.unlinkSync(filePath);
183
- console.log(`Deleted existing AAB file: ${file}`);
184
- });
185
- }
186
-
187
-
188
- // Extract version code and version name from build.gradle
189
- const gradleFilePath = path.join("android", "app", "build.gradle");
190
- const gradleContent = fs.readFileSync(gradleFilePath, 'utf8');
191
-
192
- const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
193
- const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
194
-
195
- const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
196
- const versionName = versionNameMatch ? versionNameMatch[1] : '';
197
-
198
- // Display the current versionCode and versionName
199
- console.log(`Current versionCode: ${versionCode}`);
200
- console.log(`Current versionName: ${versionName}`);
201
-
202
- // Create an interface for user input
203
- const rl = readline.createInterface({
204
- input: process.stdin,
205
- output: process.stdout
206
- });
207
-
208
- // Ask for new versionCode
209
- rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
210
- const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
211
-
212
- // Ask for new versionName
213
- rl.question('Enter new versionName (press enter to keep current): ', (newVersionName) => {
214
- const finalVersionName = newVersionName || versionName; // Use existing if no input
215
-
216
- // Log the final version details
217
- console.log(`Final versionCode: ${finalVersionCode}`);
218
- console.log(`Final versionName: ${finalVersionName}`);
219
-
220
- // Update build.gradle with the new version details
221
- let updatedGradleContent = gradleContent
222
- .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
223
- .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
224
-
225
- // Check if resConfigs "en" already exists
226
- const resConfigsLine = ' resConfigs "en"';
227
- if (!updatedGradleContent.includes(resConfigsLine)) {
228
- // Add resConfigs "en" below versionName
229
- updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
230
- } else {
231
- console.log('resConfigs "en" already exists in build.gradle.');
232
- }
233
-
234
- // Write the updated gradle content back to build.gradle
235
- fs.writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
236
- console.log(`Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, and resConfigs "en"`);
237
-
238
- storeIds.forEach((id) => {
239
- console.log(`Building for Store ID ${id}`);
240
-
241
- // Set the environment variable for store ID
242
- process.env.VITE_STORE_ID = id;
243
-
244
- // Conditionally set the new file name
245
- let newFileName;
246
- const storeName = storeNames[id];
247
-
248
- managePackages(storeName);
249
-
250
- if (storeName === "SamsungStore") {
251
- // For SamsungStore, rename to versionCode value only
252
- newFileName = `${finalVersionCode}.aab`;
253
- } else {
254
- // For other stores, use the standard naming format
255
- newFileName = `app-release-signed-${storeName}-b${finalVersionCode}-v${finalVersionName}.aab`;
256
- }
257
-
258
- const checkFullPath = path.join("AAB", newFileName); // Update to point to the new AAB directory
259
-
260
- // Modify minSdkVersion in variables.gradle for SamsungStore
261
- const variablesGradleFilePath = path.join("android", "variables.gradle");
262
- let variablesGradleContent = fs.readFileSync(variablesGradleFilePath, 'utf8');
263
-
264
- // Extract the current minSdkVersion
265
- const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
266
- const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
267
-
268
- // Store the original minSdkVersion (only on the first iteration)
269
- if (!originalMinSdkVersion) {
270
- originalMinSdkVersion = currentMinSdkVersion;
271
- }
272
- try {
273
- // Modify the minSdkVersion based on the store
274
- if (storeName === "SamsungStore" || storeName === "PlayStore") {
275
- if (currentMinSdkVersion !== 24) {
276
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
277
- console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
278
- fs.writeFileSync(variablesGradleFilePath, variablesGradleContent);
279
- }
280
- } else {
281
- // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
282
- if (currentMinSdkVersion !== originalMinSdkVersion) {
283
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${originalMinSdkVersion}`);
284
- console.log(`minSdkVersion reverted to ${originalMinSdkVersion} for ${storeName}`);
285
- fs.writeFileSync(variablesGradleFilePath, variablesGradleContent);
286
- }
287
- }
288
-
289
- // Run the Node.js script to modify plugin.xml
290
- if (isAdmobFound) {
291
- child_process.execSync('node modify-plugin-xml.js', { stdio: 'inherit' });
292
- } else {
293
- console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
294
- }
295
-
296
- // Run the Vite build
297
- child_process.execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
298
-
299
-
300
-
301
- // Copy the built files to the appropriate folder
302
- const src = path.join("www", "*");
303
- const dest = path.join("android", "app", "src", "main", "assets", "public");
304
-
305
- // Use 'xcopy' command for Windows
306
- child_process.execSync(`xcopy ${src} ${dest} /E /I /Y`, { stdio: 'inherit' });
307
-
308
- // Build Android AAB file
309
- //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
310
-
311
-
312
- // Build Android AAB file with Capacitor
313
- child_process.execSync('npx cap sync android', { stdio: 'inherit' });
314
- child_process.execSync('npx cap build android --androidreleasetype=AAB', { stdio: 'inherit' });
315
-
316
-
317
- // Rename the output AAB file
318
- const oldFilePath = path.join(aabDirectory, "app-release-signed.aab");
319
- if (fs.existsSync(oldFilePath)) {
320
- fs.renameSync(oldFilePath, checkFullPath);
321
- console.log(`Renamed output AAB file to: ${newFileName}`);
322
- } else {
323
- console.error("AAB file not found after build.");
324
- }
325
-
326
- } catch (error) {
327
- console.error(`Error during build for Store ID ${id}:`, error);
328
- }
329
- });
330
-
331
- rl.close(); // Close the readline interface after all operations
332
- });
333
- });
334
-
335
-
336
-
337
-
338
-
339
- function managePackages(store) {
340
- console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
341
-
342
- let install = "";
343
- let uninstall = "";
344
-
345
-
346
-
347
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
348
-
349
- const permissionsToRemove = [
350
- 'com.android.vending.BILLING',
351
- 'com.samsung.android.iap.permission.BILLING'
352
- ];
353
-
354
-
355
- permissionsToRemove.forEach(permission => {
356
- const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
357
- if (permissionRegex.test(manifestContent)) {
358
- manifestContent = manifestContent.replace(permissionRegex, '');
359
- console.log(`Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
360
- }
361
- });
362
-
363
- // Write the updated content back to the file
364
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
365
-
366
-
367
-
368
- if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
369
- install = '@revenuecat/purchases-capacitor';
370
- uninstall = 'cordova-plugin-samsungiap';
371
-
372
- // Update AndroidManifest.xml for PlayStore
373
- if(playstore)
374
- updateAndroidManifest(store,
375
- '<uses-permission android:name="com.android.vending.BILLING" />');
376
-
377
- } else if (samsung && store === "SamsungStore") {
378
- install = 'cordova-plugin-samsungiap';
379
- uninstall = '@revenuecat/purchases-capacitor';
380
-
381
- // Update AndroidManifest.xml for SamsungStore
382
- updateAndroidManifest(store,
383
- '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
384
-
385
- } else {
386
- console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
387
- try {
388
- child_process.execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
389
- child_process.execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
390
- console.log(`Both plugins uninstalled successfully.`);
391
- } catch (err) {
392
- console.error("Error uninstalling plugins:", err);
393
- }
394
- return;
395
- }
396
-
397
- console.log(`Installing ${install} and uninstalling ${uninstall} for ${store}...`);
398
- try {
399
- if (install) {
400
- child_process.execSync(`npm install ${install}`, { stdio: 'inherit' });
401
- }
402
- if (uninstall) {
403
- child_process.execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
404
- }
405
- console.log(`${install} installed and ${uninstall} uninstalled successfully.`);
406
- } catch (err) {
407
- console.error(`Error managing packages for ${store}:`, err);
408
- }
409
- }
410
-
411
-
412
-
413
- function updateAndroidManifest(store, addPermission) {
414
- try {
415
- if (!fs.existsSync(androidManifestPath)) {
416
- console.error("AndroidManifest.xml file not found!");
417
- return;
418
- }
419
-
420
- // Read the content of the AndroidManifest.xml
421
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
422
-
423
- // Normalize line endings to `\n` for consistent processing
424
- manifestContent = manifestContent.replace(/\r\n/g, '\n');
425
-
426
- // Check if the permission is already present
427
- if (manifestContent.includes(addPermission.trim())) {
428
- console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
429
- return; // Skip if the permission is already present
430
- }
431
-
432
- // Insert the permission before the closing </manifest> tag
433
- const closingTag = '</manifest>';
434
- const formattedPermission = ` ${addPermission.trim()}\n`;
435
- if (manifestContent.includes(closingTag)) {
436
- manifestContent = manifestContent.replace(
437
- closingTag,
438
- `${formattedPermission}${closingTag}`
439
- );
440
- console.log(`Added ${addPermission} before </manifest> tag.`);
441
- } else {
442
- console.warn(`</manifest> tag not found. Adding ${addPermission} at the end of the file.`);
443
- manifestContent += `\n${formattedPermission}`;
444
- }
445
-
446
- // Normalize line endings back to `\r\n` and write the updated content
447
- manifestContent = manifestContent.replace(/\n/g, '\r\n');
448
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
449
- console.log(`AndroidManifest.xml updated successfully for ${store}`);
450
- } catch (err) {
451
- console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
452
- }
453
- }
454
-
455
-
456
-
457
- /* function updateAndroidManifest1(store, addPermission) {
458
- try {
459
- if (!fs.existsSync(androidManifestPath)) {
460
- console.error("AndroidManifest.xml file not found!");
461
- return;
462
- }
463
-
464
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
465
-
466
-
467
-
468
- // Add the required permission if not already present
469
- if (!manifestContent.includes(addPermission)) {
470
- const manifestLines = manifestContent.split('\n');
471
- const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
472
- if (insertIndex > -1) {
473
- manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
474
- manifestContent = manifestLines.join('\n');
475
- console.log(`Added ${addPermission} to AndroidManifest.xml`);
476
- }
477
- }
478
-
479
- // Write the updated content back to the file
480
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
481
- console.log(`AndroidManifest.xml updated successfully for ${store}`);
482
- } catch (err) {
483
- console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
484
- }
485
- } */
486
-
487
-
488
-
489
-
490
-
491
-
492
-
493
-
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const child_process = require('child_process');
4
+ const readline = require('readline');
5
+
6
+ // Define a mapping between store IDs and store names
7
+ const storeNames = {
8
+ "1": "PlayStore",
9
+ "2": "SamsungStore",
10
+ "7": "AmazonStore"
11
+ };
12
+
13
+ const androidManifestPath = path.join("android", "app", "src", "main", "AndroidManifest.xml");
14
+
15
+
16
+
17
+ const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
18
+ let admobConfig;
19
+ try {
20
+ admobConfig = JSON.parse(fs.readFileSync(admobConfigPath, 'utf8'));
21
+ } catch (err) {
22
+ console.error("Failed to read admob-ad-configuration.json", err);
23
+ process.exit(1);
24
+ }
25
+
26
+
27
+
28
+
29
+ const checkCommonFileStoreId=()=>{
30
+ const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
31
+ let viteConfigPath;
32
+ for (const configFile of possibleConfigFiles) {
33
+ const fullPath = path.resolve( configFile);
34
+ if (fs.existsSync(fullPath)) {
35
+ viteConfigPath = fullPath;
36
+ break;
37
+ }
38
+ }
39
+
40
+ if (!viteConfigPath) {
41
+ console.error('Error: No vite.config.mjs or vite.config.js file found.');
42
+ process.exit(1);
43
+ }
44
+
45
+ try {
46
+ // Read vite config file
47
+ const viteConfigContent = fs.readFileSync(viteConfigPath, 'utf-8');
48
+
49
+ // Extract @common alias path
50
+ const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
51
+ const match = viteConfigContent.match(aliasPattern);
52
+
53
+ if (!match) {
54
+ console.error(`Error: @common alias not found in ${viteConfigPath}`);
55
+ process.exit(1);
56
+ }
57
+
58
+ const commonFilePath = match[1];
59
+ const resolvedCommonPath = path.resolve(__dirname, commonFilePath);
60
+
61
+ // Read the common file content
62
+ if (!fs.existsSync(resolvedCommonPath)) {
63
+ console.error(`Error: Resolved common file does not exist: ${resolvedCommonPath}`);
64
+ process.exit(1);
65
+ }
66
+
67
+ const commonFileContent = fs.readFileSync(resolvedCommonPath, 'utf-8');
68
+
69
+ // Check for the _storeid export line
70
+ const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
71
+ if (!storeIdPattern.test(commonFileContent)) {
72
+ console.error(`Error: _storeid value is wrong in ${commonFilePath}`);
73
+ process.exit(1);
74
+ }
75
+
76
+ console.log(commonFilePath,'Success - No problem found');
77
+ } catch (error) {
78
+ console.error('Error:', error);
79
+ process.exit(1);
80
+ }
81
+
82
+ }
83
+
84
+ const checkIsTestingInAdmob=()=>{
85
+
86
+ if (admobConfig.config && admobConfig.config.isTesting === true) {
87
+ console.error(`Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration.json" file.`);
88
+ process.exit(1); // Exit with an error code to halt the process
89
+ } else {
90
+ console.log('No problem found. "isTesting" is either already false or not defined.');
91
+ }
92
+ }
93
+
94
+ const addPermission_AD_ID=()=>{
95
+
96
+ const admobPluginXmlPath = path.join('node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
97
+
98
+
99
+ fs.access(admobPluginXmlPath, fs.constants.F_OK, (err) => {
100
+ if (err) {
101
+ isAdmobFound = false;
102
+ } else {
103
+ isAdmobFound = true;
104
+ }
105
+ });
106
+
107
+
108
+ if (isAdmobFound) {
109
+ // Check if AndroidManifest.xml exists
110
+ if (fs.existsSync(androidManifestPath)) {
111
+ // Read the content of AndroidManifest.xml
112
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf8');
113
+
114
+ // Check if the ad_id permission already exists
115
+ const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
116
+ if (!manifestContent.includes(adIdPermission)) {
117
+ console.log("ad_id permission not found. Adding to AndroidManifest.xml.");
118
+
119
+ // Add the ad_id permission before the closing </manifest> tag
120
+ manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
121
+
122
+ // Write the updated manifest content back to AndroidManifest.xml
123
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf8');
124
+ console.log("ad_id permission added successfully.");
125
+ } else {
126
+ console.log("ad_id permission already exists in AndroidManifest.xml.");
127
+ }
128
+ } else {
129
+ console.error("AndroidManifest.xml not found at the specified path.");
130
+ }
131
+ } else {
132
+ console.log("\x1b[33m%s\x1b[0m", "No admob found, so permission.AD_ID is not added");
133
+ }
134
+ }
135
+
136
+
137
+ checkCommonFileStoreId();
138
+ checkIsTestingInAdmob();
139
+
140
+
141
+ let isAdmobFound = true;
142
+ addPermission_AD_ID()
143
+
144
+
145
+
146
+ const { playstore, samsung, amazon } = admobConfig.IAP;
147
+ console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
148
+
149
+
150
+
151
+
152
+
153
+
154
+ // Get the store ID from the command line arguments
155
+ const storeIdArg = process.argv[2]; // Get the store ID from the command line
156
+ const storeIds = storeIdArg ? [storeIdArg] : ["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
157
+
158
+ // Store the original minSdkVersion globally
159
+ let originalMinSdkVersion;
160
+
161
+ // Remove any existing AAB files before starting the build process
162
+ const aabDirectory = path.join("android", "app", "build", "outputs", "bundle", "release");
163
+ if (fs.existsSync(aabDirectory)) {
164
+ const files = fs.readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
165
+ files.forEach(file => {
166
+ const filePath = path.join(aabDirectory, file);
167
+ fs.unlinkSync(filePath);
168
+ console.log(`Deleted existing AAB file: ${file}`);
169
+ });
170
+ }
171
+
172
+ const aabOutputDir = path.join("AAB");
173
+ if (!fs.existsSync(aabOutputDir)) {
174
+ fs.mkdirSync(aabOutputDir);
175
+ console.log(`Created directory: ${aabOutputDir}`);
176
+ }
177
+
178
+ if (fs.existsSync(aabOutputDir)) {
179
+ const files = fs.readdirSync(aabOutputDir).filter(file => file.endsWith('.aab'));
180
+ files.forEach(file => {
181
+ const filePath = path.join(aabOutputDir, file);
182
+ fs.unlinkSync(filePath);
183
+ console.log(`Deleted existing AAB file: ${file}`);
184
+ });
185
+ }
186
+
187
+
188
+ // Extract version code and version name from build.gradle
189
+ const gradleFilePath = path.join("android", "app", "build.gradle");
190
+ const gradleContent = fs.readFileSync(gradleFilePath, 'utf8');
191
+
192
+ const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
193
+ const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
194
+
195
+ const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
196
+ const versionName = versionNameMatch ? versionNameMatch[1] : '';
197
+
198
+ // Display the current versionCode and versionName
199
+ console.log(`Current versionCode: ${versionCode}`);
200
+ console.log(`Current versionName: ${versionName}`);
201
+
202
+ // Create an interface for user input
203
+ const rl = readline.createInterface({
204
+ input: process.stdin,
205
+ output: process.stdout
206
+ });
207
+
208
+ // Ask for new versionCode
209
+ rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
210
+ const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
211
+
212
+ // Ask for new versionName
213
+ rl.question('Enter new versionName (press enter to keep current): ', (newVersionName) => {
214
+ const finalVersionName = newVersionName || versionName; // Use existing if no input
215
+
216
+ // Log the final version details
217
+ console.log(`Final versionCode: ${finalVersionCode}`);
218
+ console.log(`Final versionName: ${finalVersionName}`);
219
+
220
+ // Update build.gradle with the new version details
221
+ let updatedGradleContent = gradleContent
222
+ .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
223
+ .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
224
+
225
+ // Check if resConfigs "en" already exists
226
+ const resConfigsLine = ' resConfigs "en"';
227
+ if (!updatedGradleContent.includes(resConfigsLine)) {
228
+ // Add resConfigs "en" below versionName
229
+ updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
230
+ } else {
231
+ console.log('resConfigs "en" already exists in build.gradle.');
232
+ }
233
+
234
+ // Write the updated gradle content back to build.gradle
235
+ fs.writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
236
+ console.log(`Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, and resConfigs "en"`);
237
+
238
+ storeIds.forEach((id) => {
239
+ console.log(`Building for Store ID ${id}`);
240
+
241
+ // Set the environment variable for store ID
242
+ process.env.VITE_STORE_ID = id;
243
+
244
+ // Conditionally set the new file name
245
+ let newFileName;
246
+ const storeName = storeNames[id];
247
+
248
+ managePackages(storeName);
249
+
250
+ if (storeName === "SamsungStore") {
251
+ // For SamsungStore, rename to versionCode value only
252
+ newFileName = `${finalVersionCode}.aab`;
253
+ } else {
254
+ // For other stores, use the standard naming format
255
+ newFileName = `app-release-signed-${storeName}-b${finalVersionCode}-v${finalVersionName}.aab`;
256
+ }
257
+
258
+ const checkFullPath = path.join("AAB", newFileName); // Update to point to the new AAB directory
259
+
260
+ // Modify minSdkVersion in variables.gradle for SamsungStore
261
+ const variablesGradleFilePath = path.join("android", "variables.gradle");
262
+ let variablesGradleContent = fs.readFileSync(variablesGradleFilePath, 'utf8');
263
+
264
+ // Extract the current minSdkVersion
265
+ const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
266
+ const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
267
+
268
+ // Store the original minSdkVersion (only on the first iteration)
269
+ if (!originalMinSdkVersion) {
270
+ originalMinSdkVersion = currentMinSdkVersion;
271
+ }
272
+ try {
273
+ // Modify the minSdkVersion based on the store
274
+ if (storeName === "SamsungStore" || storeName === "PlayStore") {
275
+ if (currentMinSdkVersion !== 24) {
276
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
277
+ console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
278
+ fs.writeFileSync(variablesGradleFilePath, variablesGradleContent);
279
+ }
280
+ } else {
281
+ // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
282
+ if (currentMinSdkVersion !== originalMinSdkVersion) {
283
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${originalMinSdkVersion}`);
284
+ console.log(`minSdkVersion reverted to ${originalMinSdkVersion} for ${storeName}`);
285
+ fs.writeFileSync(variablesGradleFilePath, variablesGradleContent);
286
+ }
287
+ }
288
+
289
+ // Run the Node.js script to modify plugin.xml
290
+ if (isAdmobFound) {
291
+ child_process.execSync('node modify-plugin-xml.js', { stdio: 'inherit' });
292
+ } else {
293
+ console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
294
+ }
295
+
296
+ // Run the Vite build
297
+ child_process.execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
298
+
299
+
300
+
301
+ // Copy the built files to the appropriate folder
302
+ const src = path.join("www", "*");
303
+ const dest = path.join("android", "app", "src", "main", "assets", "public");
304
+
305
+ // Use 'xcopy' command for Windows
306
+ child_process.execSync(`xcopy ${src} ${dest} /E /I /Y`, { stdio: 'inherit' });
307
+
308
+ // Build Android AAB file
309
+ //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
310
+
311
+
312
+ // Build Android AAB file with Capacitor
313
+ child_process.execSync('npx cap sync android', { stdio: 'inherit' });
314
+ child_process.execSync('npx cap build android --androidreleasetype=AAB', { stdio: 'inherit' });
315
+
316
+
317
+ // Rename the output AAB file
318
+ const oldFilePath = path.join(aabDirectory, "app-release-signed.aab");
319
+ if (fs.existsSync(oldFilePath)) {
320
+ fs.renameSync(oldFilePath, checkFullPath);
321
+ console.log(`Renamed output AAB file to: ${newFileName}`);
322
+ } else {
323
+ console.error("AAB file not found after build.");
324
+ }
325
+
326
+ } catch (error) {
327
+ console.error(`Error during build for Store ID ${id}:`, error);
328
+ }
329
+ });
330
+
331
+ rl.close(); // Close the readline interface after all operations
332
+ });
333
+ });
334
+
335
+
336
+
337
+
338
+
339
+ function managePackages(store) {
340
+ console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
341
+
342
+ let install = "";
343
+ let uninstall = "";
344
+
345
+
346
+
347
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
348
+
349
+ const permissionsToRemove = [
350
+ 'com.android.vending.BILLING',
351
+ 'com.samsung.android.iap.permission.BILLING'
352
+ ];
353
+
354
+
355
+ permissionsToRemove.forEach(permission => {
356
+ const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
357
+ if (permissionRegex.test(manifestContent)) {
358
+ manifestContent = manifestContent.replace(permissionRegex, '');
359
+ console.log(`Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
360
+ }
361
+ });
362
+
363
+ // Write the updated content back to the file
364
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
365
+
366
+
367
+
368
+ if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
369
+ install = '@revenuecat/purchases-capacitor';
370
+ uninstall = 'cordova-plugin-samsungiap';
371
+
372
+ // Update AndroidManifest.xml for PlayStore
373
+ if(playstore)
374
+ updateAndroidManifest(store,
375
+ '<uses-permission android:name="com.android.vending.BILLING" />');
376
+
377
+ } else if (samsung && store === "SamsungStore") {
378
+ install = 'cordova-plugin-samsungiap';
379
+ uninstall = '@revenuecat/purchases-capacitor';
380
+
381
+ // Update AndroidManifest.xml for SamsungStore
382
+ updateAndroidManifest(store,
383
+ '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
384
+
385
+ } else {
386
+ console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
387
+ try {
388
+ child_process.execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
389
+ child_process.execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
390
+ console.log(`Both plugins uninstalled successfully.`);
391
+ } catch (err) {
392
+ console.error("Error uninstalling plugins:", err);
393
+ }
394
+ return;
395
+ }
396
+
397
+ console.log(`Installing ${install} and uninstalling ${uninstall} for ${store}...`);
398
+ try {
399
+ if (install) {
400
+ child_process.execSync(`npm install ${install}`, { stdio: 'inherit' });
401
+ }
402
+ if (uninstall) {
403
+ child_process.execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
404
+ }
405
+ console.log(`${install} installed and ${uninstall} uninstalled successfully.`);
406
+ } catch (err) {
407
+ console.error(`Error managing packages for ${store}:`, err);
408
+ }
409
+ }
410
+
411
+
412
+
413
+ function updateAndroidManifest(store, addPermission) {
414
+ try {
415
+ if (!fs.existsSync(androidManifestPath)) {
416
+ console.error("AndroidManifest.xml file not found!");
417
+ return;
418
+ }
419
+
420
+ // Read the content of the AndroidManifest.xml
421
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
422
+
423
+ // Normalize line endings to `\n` for consistent processing
424
+ manifestContent = manifestContent.replace(/\r\n/g, '\n');
425
+
426
+ // Check if the permission is already present
427
+ if (manifestContent.includes(addPermission.trim())) {
428
+ console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
429
+ return; // Skip if the permission is already present
430
+ }
431
+
432
+ // Insert the permission before the closing </manifest> tag
433
+ const closingTag = '</manifest>';
434
+ const formattedPermission = ` ${addPermission.trim()}\n`;
435
+ if (manifestContent.includes(closingTag)) {
436
+ manifestContent = manifestContent.replace(
437
+ closingTag,
438
+ `${formattedPermission}${closingTag}`
439
+ );
440
+ console.log(`Added ${addPermission} before </manifest> tag.`);
441
+ } else {
442
+ console.warn(`</manifest> tag not found. Adding ${addPermission} at the end of the file.`);
443
+ manifestContent += `\n${formattedPermission}`;
444
+ }
445
+
446
+ // Normalize line endings back to `\r\n` and write the updated content
447
+ manifestContent = manifestContent.replace(/\n/g, '\r\n');
448
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
449
+ console.log(`AndroidManifest.xml updated successfully for ${store}`);
450
+ } catch (err) {
451
+ console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
452
+ }
453
+ }
454
+
455
+
456
+
457
+ /* function updateAndroidManifest1(store, addPermission) {
458
+ try {
459
+ if (!fs.existsSync(androidManifestPath)) {
460
+ console.error("AndroidManifest.xml file not found!");
461
+ return;
462
+ }
463
+
464
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
465
+
466
+
467
+
468
+ // Add the required permission if not already present
469
+ if (!manifestContent.includes(addPermission)) {
470
+ const manifestLines = manifestContent.split('\n');
471
+ const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
472
+ if (insertIndex > -1) {
473
+ manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
474
+ manifestContent = manifestLines.join('\n');
475
+ console.log(`Added ${addPermission} to AndroidManifest.xml`);
476
+ }
477
+ }
478
+
479
+ // Write the updated content back to the file
480
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
481
+ console.log(`AndroidManifest.xml updated successfully for ${store}`);
482
+ } catch (err) {
483
+ console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
484
+ }
485
+ } */
486
+
487
+
488
+
489
+
490
+
491
+
492
+
493
+