codeplay-common 4.11.12 → 4.11.14

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +114 -101
  2. package/LICENSE +21 -21
  3. package/README.md +274 -229
  4. package/RELEASE_NOTES.md +110 -97
  5. package/files/buildCodeplay/add-splash-screen.js +256 -255
  6. package/files/buildCodeplay/apk-store-builder.js +97 -97
  7. package/files/buildCodeplay/codeplayBeforeBuild.js +45 -43
  8. package/files/buildCodeplay/ensure-current-build.cjs +42 -42
  9. package/files/buildCodeplay/fix-onesignal-plugin.js +96 -96
  10. package/files/buildCodeplay/ios-emi-admob-modification.js +49 -49
  11. package/files/buildCodeplay/manifestModification.js +38 -38
  12. package/files/buildCodeplay/newly added.txt +89 -89
  13. package/files/buildCodeplay/release-sync.config.json +4 -4
  14. package/files/buildCodeplay/remove-force-kotlin-disable.js +43 -43
  15. package/files/buildCodeplay/setSplashAnimation.js +227 -225
  16. package/files/buildCodeplay/splash-setup.cjs +88 -0
  17. package/files/buildCodeplay/splashxml/codeplay_splashScreen.xml +1 -1
  18. package/files/buildCodeplay/sync-admob-nextgen.js +219 -219
  19. package/files/buildCodeplay/versions.json +27 -27
  20. package/files/finalrelease +1263 -1263
  21. package/files/generate-ai-promo-video.js +23 -23
  22. package/files/ionic.config.json +6 -6
  23. package/files/scripts-common/generate-baseline-profile.js +46 -46
  24. package/files/scripts-common/run-codeplay-sync-after.js +21 -21
  25. package/files/scripts-common/screenshot/background-decorations.js +120 -120
  26. package/files/scripts-common/screenshot/frame-samples.js +117 -117
  27. package/files/scripts-common/setup-baseline-profile.js +291 -291
  28. package/files/take-screen-video.js +644 -644
  29. package/package.json +3 -2
  30. package/runtime/splash-ready.mjs +52 -0
  31. package/scripts/ensure-current-build.test.cjs +76 -76
  32. package/scripts/splash-setup.test.cjs +142 -0
  33. package/scripts/sync-files.js +114 -113
  34. package/scripts/uninstall.js +2 -2
@@ -1,1263 +1,1263 @@
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, execFileSync } from 'child_process';
11
- import { createInterface } from 'readline';
12
-
13
- import { fileURLToPath } from 'url';
14
- import { dirname } from 'path';
15
- import { syncAndroidR8Rules } from './buildCodeplay/fix-optimize-builld/restore-android-r8-rules.cjs';
16
-
17
- /* const path = require('path');
18
- const fs = require('fs'); */
19
-
20
- import fs from 'fs';
21
- import path from 'path';
22
-
23
- const __filename = fileURLToPath(import.meta.url);
24
- const __dirname = process.cwd();
25
-
26
- function stripJavaScriptComments(content) {
27
- let result = '';
28
- let state = 'code';
29
-
30
- for (let index = 0; index < content.length; index++) {
31
- const character = content[index];
32
- const nextCharacter = content[index + 1];
33
-
34
- if (state === 'lineComment') {
35
- if (character === '\n') {
36
- result += character;
37
- state = 'code';
38
- } else {
39
- result += ' ';
40
- }
41
- continue;
42
- }
43
-
44
- if (state === 'blockComment') {
45
- if (character === '*' && nextCharacter === '/') {
46
- result += ' ';
47
- index++;
48
- state = 'code';
49
- } else {
50
- result += character === '\n' ? '\n' : ' ';
51
- }
52
- continue;
53
- }
54
-
55
- if (state !== 'code') {
56
- result += character;
57
-
58
- if (character === '\\') {
59
- if (nextCharacter !== undefined) {
60
- result += nextCharacter;
61
- index++;
62
- }
63
- } else if (
64
- (state === 'singleQuote' && character === "'") ||
65
- (state === 'doubleQuote' && character === '"') ||
66
- (state === 'templateLiteral' && character === '`')
67
- ) {
68
- state = 'code';
69
- }
70
- continue;
71
- }
72
-
73
- if (character === '/' && nextCharacter === '/') {
74
- result += ' ';
75
- index++;
76
- state = 'lineComment';
77
- } else if (character === '/' && nextCharacter === '*') {
78
- result += ' ';
79
- index++;
80
- state = 'blockComment';
81
- } else {
82
- result += character;
83
-
84
- if (character === "'") state = 'singleQuote';
85
- else if (character === '"') state = 'doubleQuote';
86
- else if (character === '`') state = 'templateLiteral';
87
- }
88
- }
89
-
90
- return result;
91
- }
92
-
93
- function checkProductionAdmobAlias() {
94
- const capacitorConfig = JSON.parse(readFileSync(resolve(__dirname, 'capacitor.config.json'), 'utf8'));
95
- if (capacitorConfig.plugins?.AdMob?.ADMOB_ENABLED === false) {
96
- console.log('ℹ️ AdMob is disabled; production @admob alias validation skipped.');
97
- return;
98
- }
99
-
100
- const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
101
- const viteConfigPath = possibleConfigFiles
102
- .map(configFile => resolve(__dirname, configFile))
103
- .find(filePath => existsSync(filePath));
104
-
105
- if (!viteConfigPath) {
106
- console.error('❌ FINAL RELEASE BLOCKED: No vite.config.mjs or vite.config.js file found.');
107
- process.exit(1);
108
- }
109
-
110
- const viteConfigContent = stripJavaScriptComments(readFileSync(viteConfigPath, 'utf8'));
111
- const aliasPattern = /(['"])@admob\1\s*:\s*path\.resolve\(\s*__dirname\s*,\s*(['"])([^'"\r\n]+)\2\s*\)/g;
112
- const activeAliases = [...viteConfigContent.matchAll(aliasPattern)].map(match => match[3]);
113
- const productionAliasPattern = /^\.\/src\/js\/Ads\/(?:admob-nextgen-\d+(?:\.\d+)+\/admob-emi-nextgen|admob-emi-nextgen-\d+(?:\.\d+)+)\.js$/;
114
-
115
- if (activeAliases.length === 0) {
116
- console.error('❌ FINAL RELEASE BLOCKED: The production @admob alias is commented out or missing in the Vite config.');
117
- console.error(" Enable: '@admob': path.resolve(__dirname, './src/js/Ads/admob-nextgen-x.x/admob-emi-nextgen.js')");
118
- process.exit(1);
119
- }
120
-
121
- if (activeAliases.length > 1) {
122
- console.error('❌ FINAL RELEASE BLOCKED: Multiple active @admob aliases were found in the Vite config.');
123
- console.error(' Keep exactly one active production @admob alias.');
124
- process.exit(1);
125
- }
126
-
127
- const activeAlias = activeAliases[0];
128
- if (!productionAliasPattern.test(activeAlias)) {
129
- console.error(`❌ FINAL RELEASE BLOCKED: @admob currently points to '${activeAlias}'.`);
130
- console.error(" It must point to './src/js/Ads/admob-nextgen-x.x/admob-emi-nextgen.js', not a test AdMob file.");
131
- process.exit(1);
132
- }
133
-
134
- const productionAdmobPath = resolve(__dirname, activeAlias);
135
- if (!existsSync(productionAdmobPath)) {
136
- console.error(`❌ FINAL RELEASE BLOCKED: The production @admob file does not exist: ${productionAdmobPath}`);
137
- process.exit(1);
138
- }
139
-
140
- console.log(`✅ Production @admob alias verified: ${activeAlias}`);
141
- }
142
-
143
- // Validate the production alias first when AdMob is enabled.
144
- checkProductionAdmobAlias();
145
-
146
- // Define a mapping between store IDs and store names
147
- /* const storeNames = {
148
- "1": "PlayStore",
149
- "2": "SamsungStore",
150
- "7": "AmazonStore"
151
- }; */
152
-
153
-
154
- const isOnlyOneAPK = false; // 🔥 change to false for normal behavior
155
-
156
- const storeNames = {
157
- "1": "PlayStore",
158
- "2": "SamsungStore",
159
- "7": "AmazonStore",
160
-
161
- "3": "MiStore",
162
- "4": "HuaweiStore",
163
- "5": "OppoStore",
164
- //"6": "iOSStore",
165
- "8": "VivoStore"
166
- };
167
-
168
-
169
- //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
170
-
171
-
172
-
173
-
174
-
175
-
176
-
177
- let isAdmobFound = false;
178
-
179
- const amazonMinSdkVersion=24;
180
-
181
- const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
182
-
183
-
184
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
185
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
186
-
187
- const _appUniqueId = config.android?.APP_UNIQUE_ID;
188
- const _appName=config.appName;
189
- const _appPackageId=config.appId;
190
-
191
- const appReleaseSyncConfigPath = join(process.cwd(), 'buildCodeplay', 'release-sync.config.json');
192
- const releaseSyncConfigPath = appReleaseSyncConfigPath;
193
- let releaseSyncConfig = {};
194
- if (existsSync(releaseSyncConfigPath)) {
195
- try {
196
- releaseSyncConfig = JSON.parse(readFileSync(releaseSyncConfigPath, 'utf8'));
197
- } catch (error) {
198
- console.warn(`⚠️ Could not read ${releaseSyncConfigPath}: ${error.message}`);
199
- }
200
- }
201
- const RELEASE_SYNC_URL = process.env.CODEPLAY_RELEASE_SYNC_URL || releaseSyncConfig.url || 'https://htmlcodeplay.com/codeplay/api/v1/release/sync';
202
- const RELEASE_SYNC_TOKEN = process.env.CODEPLAY_RELEASE_SYNC_TOKEN || releaseSyncConfig.token || '';
203
- const RELEASE_PLATFORM_IDS = { PlayStore: 1, SamsungStore: 13, AmazonStore: 17, MiStore: 15, HuaweiStore: 12, OppoStore: 14, VivoStore: 16 };
204
-
205
- function syncReleaseToCodeplay(storeName, finalVersionName, finalVersionCode, releasedDate) {
206
- if (!RELEASE_SYNC_TOKEN) {
207
- console.warn(`⚠️ Codeplay release sync skipped: add a token to ${releaseSyncConfigPath}.`);
208
- return;
209
- }
210
- const payload = JSON.stringify({
211
- app_name: _appName,
212
- package_id: _appPackageId,
213
- version_name: String(finalVersionName),
214
- version_code: String(finalVersionCode),
215
- released_date: releasedDate,
216
- language_id: 0,
217
- language_name: 'Capacitor+ Framework 7',
218
- notes: 'Automated release update',
219
- status: 1,
220
- folder_name: path.basename(process.cwd()),
221
- app_unique_id: String(_appUniqueId || ''),
222
- platform_id: RELEASE_PLATFORM_IDS[storeName],
223
- });
224
- try {
225
- const response = execFileSync('curl.exe', ['-sS', '--fail-with-body', '-X', 'POST', RELEASE_SYNC_URL,
226
- '-H', 'Content-Type: application/json', '-H', `X-Release-Token: ${RELEASE_SYNC_TOKEN}`, '--data-binary', payload],
227
- { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
228
- console.log(`✅ Codeplay sync (${storeName}): ${response.trim()}`);
229
- } catch (error) {
230
- console.warn(`⚠️ Codeplay sync failed for ${storeName}; continuing release builds: ${error.message}`);
231
- }
232
- }
233
-
234
- const FLOWCHART_API_APP_ID = 228;
235
- const FLOWCHART_SHARED_PATH = join('public', 'src', 'shared.js');
236
- const FLOWCHART_PLAY_API_BASE = 'https://htmlcodeplay.com/appfiles/128FlowChart';
237
- const FLOWCHART_OTHER_STORE_API_BASE = 'https://htmlcodeplay.com/appfiles/128FlowChart/otherapi';
238
- const FLOWCHART_OTHER_STORE_API_HASH = 'd1a3774529b74206ae2117f9c25f258e485a1f7348620e769db19c2796aa1fdf';
239
- const flowchartSharedOriginal = existsSync(FLOWCHART_SHARED_PATH)
240
- ? readFileSync(FLOWCHART_SHARED_PATH, 'utf8')
241
- : null;
242
-
243
- function applyFlowchartStoreApi(storeId) {
244
- if (String(_appUniqueId) !== String(FLOWCHART_API_APP_ID) || !flowchartSharedOriginal) return false;
245
- const apiBase = String(storeId) === '1' ? FLOWCHART_PLAY_API_BASE : FLOWCHART_OTHER_STORE_API_BASE;
246
- const accessHash = String(storeId) === '1' ? '' : FLOWCHART_OTHER_STORE_API_HASH;
247
- const apiBaseMarker = /const FLOWCHART_API_BASE = "[^"]*";/;
248
- const accessHashMarker = /const FLOWCHART_API_ACCESS_HASH = "[^"]*";/;
249
-
250
- if (!apiBaseMarker.test(flowchartSharedOriginal) || !accessHashMarker.test(flowchartSharedOriginal)) {
251
- throw new Error(`Flowchart API configuration markers were not found in ${FLOWCHART_SHARED_PATH}.`);
252
- }
253
-
254
- const updated = flowchartSharedOriginal
255
- .replace(apiBaseMarker, `const FLOWCHART_API_BASE = "${apiBase}";`)
256
- .replace(accessHashMarker, `const FLOWCHART_API_ACCESS_HASH = "${accessHash}";`);
257
- writeFileSync(FLOWCHART_SHARED_PATH, updated, 'utf8');
258
- console.log(`✅ App 228 API endpoint configured for Store ID ${storeId}.`);
259
- return true;
260
- }
261
-
262
- function restoreFlowchartStoreApi() {
263
- if (String(_appUniqueId) === String(FLOWCHART_API_APP_ID) && flowchartSharedOriginal) {
264
- writeFileSync(FLOWCHART_SHARED_PATH, flowchartSharedOriginal, 'utf8');
265
- }
266
- }
267
-
268
-
269
-
270
- function fileExists(filePath) {
271
- return existsSync(filePath);
272
- }
273
-
274
-
275
- const ffmpegPluginXmlPath = path.join(__dirname, 'node_modules', 'codeplay-fmpg', 'plugin.xml');
276
- const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
277
-
278
-
279
-
280
- function isFfmpegUsed() {
281
- try {
282
- const xmlContent = fs.readFileSync(ffmpegPluginXmlPath, 'utf8');
283
- // Simple check: if plugin.xml exists and contains <plugin> tag (or any FFmpeg-specific tag)
284
- return /<plugin\b/.test(xmlContent);
285
- } catch (err) {
286
- console.log('⚠️ FFmpeg plugin not found:', err.message);
287
- return false;
288
- }
289
- }
290
-
291
- const _isffmpegUsed = isFfmpegUsed();
292
-
293
- function getAdMobConfig() {
294
- if (!fileExists(capacitorConfigPath)) {
295
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
296
- }
297
-
298
- const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
299
- const admobConfig = config.plugins?.AdMob;
300
-
301
- //_appPackageId=config.appId;
302
-
303
- if (!admobConfig) {
304
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
305
- }
306
-
307
- // Default to true if ADMOB_ENABLED is not specified
308
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
309
-
310
- if (!isEnabled) {
311
- return { ADMOB_ENABLED: false }; // Skip further validation
312
- }
313
-
314
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
315
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
316
- }
317
-
318
- return {
319
- ADMOB_ENABLED: true,
320
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
321
- APP_ID_IOS: admobConfig.APP_ID_IOS,
322
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
323
- };
324
- }
325
-
326
-
327
-
328
- const _capacitorConfig = getAdMobConfig();
329
-
330
- const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
331
- isAdmobFound = _isADMOB_ENABLED;
332
-
333
- // Proceed only if ADMOB_ENABLED is true
334
- //if (_capacitorConfig.ADMOB_ENABLED)
335
-
336
-
337
- const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration-nextgen.json');
338
- let admobConfig;
339
-
340
- if (_isADMOB_ENABLED)
341
- {
342
- try
343
- {
344
- admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
345
- }
346
- catch (err)
347
- {
348
- console.error("❌ Failed to read admob-ad-configuration.json", err);
349
- process.exit(1);
350
- }
351
- }
352
-
353
-
354
-
355
-
356
-
357
- function updateIOSVersion(versionCode, versionName) {
358
-
359
- const pbxprojPath = join("ios", "App", "App.xcodeproj", "project.pbxproj");
360
-
361
- // 🔥 Single check only
362
- if (!existsSync(pbxprojPath)) {
363
- console.warn("⚠️ iOS project not found, skipping version update");
364
- return;
365
- }
366
-
367
-
368
- let content = readFileSync(pbxprojPath, 'utf8');
369
-
370
- // Update MARKETING_VERSION
371
- content = content.replace(
372
- /MARKETING_VERSION = .*?;/g,
373
- `MARKETING_VERSION = ${versionName};`
374
- );
375
-
376
- // Update CURRENT_PROJECT_VERSION
377
- /* content = content.replace(
378
- /CURRENT_PROJECT_VERSION = .*?;/g,
379
- `CURRENT_PROJECT_VERSION = ${versionCode};`
380
- ); */
381
-
382
- writeFileSync(pbxprojPath, content, 'utf8');
383
-
384
- console.log(`🍏 iOS updated via Xcode settings → version: ${versionName}, build: ${versionCode}`);
385
- }
386
-
387
-
388
-
389
-
390
-
391
-
392
-
393
-
394
-
395
-
396
-
397
-
398
-
399
-
400
-
401
-
402
-
403
-
404
-
405
-
406
-
407
- const checkCommonFileStoreId=()=>{
408
- const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
409
- let viteConfigPath;
410
- for (const configFile of possibleConfigFiles) {
411
- const fullPath = resolve( configFile);
412
- if (existsSync(fullPath)) {
413
- viteConfigPath = fullPath;
414
- break;
415
- }
416
- }
417
-
418
- if (!viteConfigPath) {
419
- console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
420
- process.exit(1);
421
- }
422
-
423
- try {
424
- // Read vite config file
425
- const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
426
-
427
- // Extract @common alias path
428
- const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
429
- const match = viteConfigContent.match(aliasPattern);
430
-
431
- if (!match) {
432
- console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
433
- process.exit(1);
434
- }
435
-
436
- const commonFilePath = match[1];
437
- const resolvedCommonPath = resolve(__dirname, commonFilePath);
438
-
439
- // Read the common file content
440
- if (!existsSync(resolvedCommonPath)) {
441
- console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
442
- process.exit(1);
443
- }
444
-
445
- const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
446
-
447
- // Check for the _storeid export line
448
- const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
449
- if (!storeIdPattern.test(commonFileContent)) {
450
- console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
451
- process.exit(1);
452
- }
453
-
454
- console.log(commonFilePath,'Success - No problem found');
455
- } catch (error) {
456
- console.error('❌ Error:', error);
457
- process.exit(1);
458
- }
459
-
460
- }
461
-
462
- const checkIsTestingInAdmob=()=>{
463
-
464
- if (admobConfig.config && admobConfig.config.isTesting === true) {
465
- console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration-nextgen.json" file.`);
466
- process.exit(1); // Exit with an error code to halt the process
467
- } else {
468
- console.log('✅ No problem found. "isTesting" is either already false or not defined.');
469
- }
470
- }
471
-
472
- const checkIsAdsDisableByReturnStatement=()=>{
473
-
474
-
475
- // Inspect the controller selected by the validated production alias.
476
- const viteFile = ['vite.config.mjs', 'vite.config.js']
477
- .map(file => resolve(__dirname, file)).find(file => existsSync(file));
478
- const config = stripJavaScriptComments(readFileSync(viteFile, 'utf8'));
479
- const alias = config.match(/(['"])@admob\1\s*:\s*path\.resolve\(\s*__dirname\s*,\s*(['"])([^'"\r\n]+)\2\s*\)/);
480
- const filePath = resolve(__dirname, alias[3]);
481
- const admobFile = alias[3];
482
- const content = readFileSync(filePath, 'utf-8');
483
-
484
- // Step 2: Extract the adsOnDeviceReady function body
485
- const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
486
- const match = content.match(functionRegex);
487
-
488
- if (!match) {
489
- console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
490
- process.exit(1);
491
- }
492
-
493
- const body = match[1];
494
- const lines = body.split('\n').map(line => line.trim());
495
-
496
- // Step 3: Skip blank lines and comments, get the first real code line
497
- let firstCodeLine = '';
498
- for (const line of lines) {
499
- if (line === '' || line.startsWith('//')) continue;
500
- firstCodeLine = line;
501
- break;
502
- }
503
-
504
- // Step 4: Block if it's any of the unwanted returns
505
- const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
506
-
507
- if (badReturnPattern.test(firstCodeLine)) {
508
- console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
509
- process.exit(2);
510
- } else {
511
- console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
512
- }
513
- }
514
-
515
-
516
-
517
- const addPermission_AD_ID=async()=>{
518
-
519
- if (isAdmobFound) {
520
- if (existsSync(androidManifestPath)) {
521
- let manifestContent = readFileSync(androidManifestPath, 'utf8');
522
- let modified = false;
523
-
524
- // --- Step 1: Ensure AD_ID permission exists ---
525
- const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
526
- if (!manifestContent.includes(adIdPermission)) {
527
- console.log("📄 AD_ID permission not found. Adding to AndroidManifest.xml.");
528
- manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
529
- console.log("✅ AD_ID permission added successfully.");
530
- modified = true;
531
- } else {
532
- console.log("ℹ️ AD_ID permission already exists in AndroidManifest.xml.");
533
- }
534
-
535
- // --- Step 2: Ensure OPTIMIZE_AD_LOADING meta-data exists ---
536
- const optimizeAdMeta = `<meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" />`;
537
-
538
- if (!manifestContent.includes(optimizeAdMeta)) {
539
- console.log("📄 OPTIMIZE_AD_LOADING meta-data not found. Adding to AndroidManifest.xml.");
540
-
541
- const appTagPattern = /<application[^>]*>/;
542
- if (appTagPattern.test(manifestContent)) {
543
- manifestContent = manifestContent.replace(appTagPattern, match => `${match}\n ${optimizeAdMeta}`);
544
- console.log("✅ OPTIMIZE_AD_LOADING meta-data added successfully.");
545
- modified = true;
546
- } else {
547
- console.error("❌ <application> tag not found in AndroidManifest.xml.");
548
- }
549
- } else {
550
- console.log("ℹ️ OPTIMIZE_AD_LOADING meta-data already exists in AndroidManifest.xml.");
551
- }
552
-
553
- // --- Step 3: Write only if modified ---
554
- if (modified) {
555
- writeFileSync(androidManifestPath, manifestContent, 'utf8');
556
- console.log("💾 AndroidManifest.xml updated successfully.");
557
- } else {
558
- console.log("✅ No changes needed. AndroidManifest.xml is up to date.");
559
- }
560
-
561
- } else {
562
- console.error("❌ AndroidManifest.xml not found at the specified path.");
563
- }
564
- } else {
565
- console.log("\x1b[33m%s\x1b[0m", "⚠️ No AdMob found, so AD_ID permission and meta-data were not added");
566
- }
567
-
568
-
569
-
570
-
571
-
572
-
573
- }
574
-
575
-
576
-
577
-
578
-
579
-
580
-
581
-
582
-
583
-
584
-
585
- checkCommonFileStoreId();
586
-
587
-
588
-
589
- if (_isADMOB_ENABLED)
590
- {
591
- checkIsTestingInAdmob();
592
- checkIsAdsDisableByReturnStatement()
593
-
594
- await addPermission_AD_ID()
595
- }
596
-
597
-
598
-
599
- let originalReleaseType, originalSigningType;
600
-
601
- function readCapacitorConfig() {
602
- return JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
603
- }
604
-
605
- function writeCapacitorConfig(config) {
606
- fs.writeFileSync(capacitorConfigPath, JSON.stringify(config, null, 2), 'utf8');
607
- }
608
-
609
- /* function updateCapacitorConfig(releaseType, signingType) {
610
- const config = readCapacitorConfig();
611
-
612
- // Save original values once
613
- if (originalReleaseType === undefined) originalReleaseType = config.android?.buildOptions?.releaseType || '';
614
- if (originalSigningType === undefined) originalSigningType = config.android?.buildOptions?.signingType || '';
615
-
616
- // Update values
617
- config.android = config.android || {};
618
- config.android.buildOptions = config.android.buildOptions || {};
619
- config.android.buildOptions.releaseType = releaseType;
620
- config.android.buildOptions.signingType = signingType;
621
-
622
- writeCapacitorConfig(config);
623
- console.log(`ℹ️ capacitor.config.json updated: releaseType=${releaseType}, signingType=${signingType}`);
624
- } */
625
-
626
- /* function restoreCapacitorConfig() {
627
- const config = readCapacitorConfig();
628
- if (originalReleaseType !== undefined) config.android.buildOptions.releaseType = originalReleaseType;
629
- if (originalSigningType !== undefined) config.android.buildOptions.signingType = originalSigningType;
630
- writeCapacitorConfig(config);
631
- console.log(`✅ capacitor.config.json restored to original values.`);
632
- }
633
-
634
- process.on('SIGINT', () => {
635
- console.log('\n⚠️ Detected Ctrl+C, restoring capacitor.config.json...');
636
- restoreCapacitorConfig();
637
- process.exit(0);
638
- });
639
-
640
- process.on('exit', () => {
641
- restoreCapacitorConfig();
642
- }); */
643
-
644
-
645
-
646
- const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
647
- console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
648
-
649
-
650
-
651
-
652
-
653
-
654
- // Get the store ID from the command line arguments
655
- /* const storeIdArg = ["2","3"]//process.argv[2]; // Get the store ID from the command line
656
- const storeIds = storeIdArg ? storeIdArg : Object.keys(storeNames);//["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
657
-
658
- debugger; */
659
-
660
- let storeIdArg = process.argv[2]; // command-line argument
661
- let storeIds;
662
-
663
- if (storeIdArg) {
664
- try {
665
- // Try parsing as JSON array first
666
- const parsed = JSON.parse(storeIdArg);
667
- if (Array.isArray(parsed)) {
668
- storeIds = parsed.map(String); // ensure strings
669
- } else {
670
- storeIds = [parsed.toString()];
671
- }
672
- } catch (e) {
673
- // Not JSON, assume comma-separated string
674
- storeIds = storeIdArg.split(",").map(s => s.trim());
675
- }
676
- } else {
677
- // No argument, use all store IDs
678
- storeIds = Object.keys(storeNames);
679
- }
680
-
681
-
682
- // 🔥 If only one APK mode, override APK storeIds
683
- /* if (isOnlyOneAPK) {
684
- console.log("⚡ isOnlyOneAPK enabled → Only MiStore (3) will be used for APK build");
685
- storeIds = ["3"]; // Only MiStore
686
- } */
687
-
688
- // Store the original minSdkVersion globally
689
- let originalMinSdkVersion;
690
-
691
- // Remove any existing AAB files before starting the build process
692
- const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
693
- if (existsSync(aabDirectory)) {
694
- const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
695
- files.forEach(file => {
696
- const filePath = join(aabDirectory, file);
697
- unlinkSync(filePath);
698
- console.log(`ℹ️ Deleted existing AAB file: ${file}`);
699
- });
700
- }
701
-
702
- const aabOutputDir = join("AAB");
703
- if (!existsSync(aabOutputDir)) {
704
- mkdirSync(aabOutputDir);
705
- console.log(`Created directory: ${aabOutputDir}`);
706
- }
707
-
708
- if (existsSync(aabOutputDir)) {
709
- const files = readdirSync(aabOutputDir).filter(
710
- file => file.endsWith('.aab') || file.endsWith('.apk')
711
- );
712
-
713
- files.forEach(file => {
714
- const filePath = join(aabOutputDir, file);
715
- unlinkSync(filePath);
716
- console.log(`Deleted existing build file: ${file}`);
717
- });
718
- }
719
-
720
-
721
- // Extract version code and version name from build.gradle
722
- const gradleFilePath = join("android", "app", "build.gradle");
723
- const gradleContent = readFileSync(gradleFilePath, 'utf8');
724
-
725
- // Return the character range of a Gradle block, allowing nested blocks inside it.
726
- function findGradleBlock(content, headerPattern) {
727
- const headerMatch = content.match(headerPattern);
728
- if (!headerMatch) return null;
729
- const openingBrace = content.indexOf('{', headerMatch.index + headerMatch[0].length);
730
- if (openingBrace === -1) return null;
731
- let depth = 0;
732
- let quote = null;
733
- for (let index = openingBrace; index < content.length; index += 1) {
734
- const character = content[index];
735
- const previous = content[index - 1];
736
- if (quote) {
737
- if (character === quote && previous !== '\\') quote = null;
738
- continue;
739
- }
740
- if (character === '\"' || character === "'") quote = character;
741
- else if (character === '{') depth += 1;
742
- else if (character === '}' && --depth === 0) return { start: openingBrace + 1, end: index };
743
- }
744
- return null;
745
- }
746
-
747
- function ensureReleaseCodeOptimization() {
748
- syncAndroidR8Rules(process.cwd(), { installGradleHook: true });
749
- const currentContent = readFileSync(gradleFilePath, 'utf8');
750
- const releaseBlock = findGradleBlock(currentContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
751
- if (!releaseBlock) throw new Error('Release build configuration was not found.');
752
-
753
- const releaseContent = currentContent.slice(releaseBlock.start, releaseBlock.end);
754
- let optimizedContent = releaseContent.replace(
755
- /getDefaultProguardFile\(\s*(['"])proguard-android\.txt\1\s*\)/g,
756
- "getDefaultProguardFile('proguard-android-optimize.txt')"
757
- );
758
- if (!/getDefaultProguardFile\(\s*(['"])proguard-android-optimize\.txt\1\s*\)/.test(optimizedContent)) {
759
- throw new Error('Release build must use the optimisation-enabled default ProGuard rules.');
760
- }
761
- const newline = currentContent.includes('\r\n') ? '\r\n' : '\n';
762
- // Preserve commented settings and explicit false values as app-specific opt-outs.
763
- const comments = optimizedContent.match(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g) || [];
764
- if (!comments.some(comment => /\bshrinkResources\b/.test(comment))) {
765
- const activeContent = optimizedContent.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, '');
766
- const shrinkResources = /^[ \t]*minifyEnabled\s*(?:=\s*)?true\b/m.test(activeContent);
767
- const shrinkPattern = /^([ \t]*shrinkResources\s*(?:=\s*)?)(true|false)\b/m;
768
- if (shrinkPattern.test(optimizedContent)) {
769
- if (!shrinkResources) optimizedContent = optimizedContent.replace(shrinkPattern, '$1false');
770
- } else {
771
- optimizedContent = `${newline} shrinkResources ${shrinkResources}${optimizedContent}`;
772
- }
773
- }
774
- if (optimizedContent !== releaseContent) {
775
- writeFileSync(gradleFilePath, currentContent.slice(0, releaseBlock.start)
776
- + optimizedContent + currentContent.slice(releaseBlock.end), 'utf8');
777
- }
778
-
779
- const propertiesPath = join(__dirname, 'android', 'gradle.properties');
780
- const properties = readFileSync(propertiesPath, 'utf8');
781
- const propertyPattern = /^[ \t]*[#!]?[ \t]*android\.r8\.optimizedResourceShrinking(?:[ \t]*[=:]|[ \t]+|[ \t]*$)/m;
782
- const property = 'android.r8.optimizedResourceShrinking=true';
783
- const nextProperties = propertyPattern.test(properties)
784
- ? properties
785
- : `${properties.trimEnd()}${newline}${property}${newline}`;
786
- if (nextProperties !== properties) writeFileSync(propertiesPath, nextProperties, 'utf8');
787
- }
788
-
789
- function signReleaseBundleWithSha256() {
790
- const buildOptions = readCapacitorConfig().android?.buildOptions;
791
- if (!buildOptions?.keystorePath || !buildOptions.keystorePassword
792
- || !buildOptions.keystoreAlias || !buildOptions.keystoreAliasPassword) {
793
- throw new Error('Android AAB signing requires the existing keystore path, alias and passwords.');
794
- }
795
-
796
- const keystorePath = resolve(__dirname, 'android', buildOptions.keystorePath);
797
- const bundleDirectory = join(__dirname, 'android', 'app', 'build', 'outputs', 'bundle', 'release');
798
- const unsignedBundle = join(bundleDirectory, 'app-release.aab');
799
- const signedBundle = join(bundleDirectory, 'app-release-signed.aab');
800
- if (!existsSync(keystorePath) || !existsSync(unsignedBundle)) {
801
- throw new Error('The configured upload keystore or release AAB was not found.');
802
- }
803
-
804
- const jarsigner = process.env.JAVA_HOME
805
- ? join(process.env.JAVA_HOME, 'bin', process.platform === 'win32' ? 'jarsigner.exe' : 'jarsigner')
806
- : 'jarsigner';
807
- try {
808
- // Keep passwords out of command arguments and error output.
809
- execFileSync(jarsigner, [
810
- '-sigalg', 'SHA256withRSA', '-digestalg', 'SHA-256',
811
- '-keystore', keystorePath,
812
- '-storepass:env', 'CODEPLAY_AAB_STORE_PASSWORD',
813
- '-keypass:env', 'CODEPLAY_AAB_KEY_PASSWORD',
814
- '-signedjar', signedBundle, unsignedBundle, buildOptions.keystoreAlias,
815
- ], {
816
- stdio: 'pipe',
817
- env: {
818
- ...process.env,
819
- CODEPLAY_AAB_STORE_PASSWORD: buildOptions.keystorePassword,
820
- CODEPLAY_AAB_KEY_PASSWORD: buildOptions.keystoreAliasPassword,
821
- },
822
- });
823
- const verification = execFileSync(jarsigner, [
824
- '-J-Duser.language=en', '-J-Duser.country=US', '-verify', signedBundle,
825
- ], { encoding: 'utf8', stdio: 'pipe' });
826
- if (!verification.includes('jar verified.') || verification.includes('treated as unsigned')) {
827
- throw new Error('Signature verification failed.');
828
- }
829
- } catch {
830
- throw new Error('SHA-256 AAB signing or verification failed. Check the configured upload key and JDK; release stopped.');
831
- }
832
- console.log('✅ Release AAB signed with SHA-256 using the existing upload key and signature verified.');
833
- }
834
-
835
- const amazonWindowExtensionsDependency = 'implementation "androidx.window.extensions.core:core:1.0.0"';
836
- const amazonWindowExtensionsDependencyPattern = /^[ \t]*implementation\s+["']androidx\.window\.extensions\.core:core:[^"']+["'][ \t]*(?:\r?\n)?/gm;
837
-
838
- function setAmazonWindowExtensionsDependency(enabled, { cleanup = false } = {}) {
839
- const currentGradleContent = readFileSync(gradleFilePath, 'utf8');
840
- let nextGradleContent = currentGradleContent.replace(amazonWindowExtensionsDependencyPattern, '');
841
-
842
- if (enabled) {
843
- const dependenciesBlock = findGradleBlock(nextGradleContent, /^\s*dependencies\s*/m);
844
- if (!dependenciesBlock) {
845
- throw new Error(`The dependencies block was not found in ${gradleFilePath}.`);
846
- }
847
-
848
- const newline = nextGradleContent.includes('\r\n') ? '\r\n' : '\n';
849
- const contentBeforeClosingBrace = nextGradleContent.slice(0, dependenciesBlock.end);
850
- const linePrefix = contentBeforeClosingBrace.endsWith('\n') ? '' : newline;
851
- nextGradleContent = contentBeforeClosingBrace
852
- + linePrefix
853
- + ` ${amazonWindowExtensionsDependency}${newline}`
854
- + nextGradleContent.slice(dependenciesBlock.end);
855
- }
856
-
857
- if (nextGradleContent !== currentGradleContent) {
858
- writeFileSync(gradleFilePath, nextGradleContent, 'utf8');
859
- }
860
-
861
- console.log(enabled
862
- ? '✅ Added Amazon Fire WebView compatibility dependency for Store ID 7.'
863
- : cleanup
864
- ? 'ℹ️ Removed temporary Amazon Fire WebView compatibility dependency after build cleanup.'
865
- : 'ℹ️ Amazon Fire WebView compatibility dependency is not included for this build.');
866
- }
867
-
868
- const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
869
- const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
870
-
871
- const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
872
- const versionName = versionNameMatch ? versionNameMatch[1] : '';
873
-
874
- // Display the current versionCode and versionName
875
- console.log(`Current versionCode: ${versionCode}`);
876
- console.log(`Current versionName: ${versionName}`);
877
-
878
- // Create an interface for user input
879
- async function checkBaselineProfileBeforeRelease() {
880
- const profilePaths = [
881
- join(__dirname, 'baselineProfiles', 'baseline-prof.txt'),
882
- join(__dirname, 'android', 'app', 'src', 'main', 'generated', 'baselineProfiles', 'baseline-prof.txt'),
883
- join(__dirname, 'android', 'app', 'src', 'main', 'baseline-prof.txt'),
884
- join(__dirname, 'android', 'app', 'src', 'main', 'baselineProfiles', 'baseline-prof.txt'),
885
- ];
886
- const hasProfile = () => profilePaths.some(profilePath =>
887
- existsSync(profilePath) && readFileSync(profilePath, 'utf8').trim().length > 0);
888
- if (hasProfile()) return;
889
-
890
- console.log('⚠️ baseline-prof.txt is missing or empty.');
891
- console.log('Generation command: npm run baseline-profile:generate');
892
- console.log('Generation requires an ADB-connected Android device or a configured emulator.');
893
- const answer = await new Promise(resolveAnswer => {
894
- rl.question('Generate AAB/APK without a Baseline Profile? [Enter/Y = continue, n = generate profile first]: ', resolveAnswer);
895
- });
896
- if (answer.trim().toLowerCase() !== 'n') return;
897
-
898
- rl.pause();
899
- try {
900
- execSync('npm run baseline-profile:generate', { cwd: __dirname, stdio: 'inherit' });
901
- if (!hasProfile()) {
902
- throw new Error('Baseline Profile generation did not produce a non-empty baseline-prof.txt; release stopped.');
903
- }
904
- // Reuse setup to back up and synchronise the generated profile before packaging.
905
- execFileSync(process.execPath, [join(__dirname, 'scripts-common', 'setup-baseline-profile.js')], {
906
- cwd: __dirname,
907
- stdio: 'inherit',
908
- });
909
- } finally {
910
- rl.resume();
911
- }
912
- }
913
-
914
- const rl = createInterface({
915
- input: process.stdin,
916
- output: process.stdout
917
- });
918
-
919
- // Ask for new versionCode
920
- rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
921
- const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
922
-
923
- // Ask for new versionName
924
- rl.question('Enter new versionName (press enter to keep current): ', async (newVersionName) => {
925
- const finalVersionName = newVersionName || versionName; // Use existing if no input
926
-
927
- // Log the final version details
928
- console.log(`📦 Final versionCode: ${finalVersionCode}`);
929
- console.log(`📝 Final versionName: ${finalVersionName}`);
930
-
931
-
932
- updateIOSVersion(finalVersionCode, finalVersionName);
933
-
934
- // Update build.gradle with the new version details
935
- let updatedGradleContent = gradleContent
936
- .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
937
- .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
938
-
939
- // Check if resConfigs "en" already exists
940
- const resConfigsLine = ' resConfigs "en"';
941
- if (!updatedGradleContent.includes(resConfigsLine)) {
942
- // Add resConfigs "en" below versionName
943
- updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
944
- } else {
945
- console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
946
- }
947
-
948
-
949
-
950
- // List of package IDs for which minify should be false
951
-
952
-
953
- // Determine desired minify value
954
- const desiredMinify = !_isffmpegUsed;
955
-
956
- // Limit minification changes to release; debug may have its own test settings.
957
- const minificationBlock = findGradleBlock(updatedGradleContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
958
- if (!minificationBlock) {
959
- throw new Error('Release build configuration was not found.');
960
- }
961
- let minificationContent = updatedGradleContent.slice(minificationBlock.start, minificationBlock.end);
962
- if (!/\bminifyEnabled\b/.test(minificationContent)) {
963
- // Insert minifyEnabled if not present
964
- minificationContent = `\n minifyEnabled ${desiredMinify}${minificationContent}`;
965
- console.log(`✅ Inserted minifyEnabled ${desiredMinify} into release block.`);
966
- }
967
- updatedGradleContent = updatedGradleContent.slice(0, minificationBlock.start)
968
- + minificationContent + updatedGradleContent.slice(minificationBlock.end);
969
-
970
- // Add native debug symbols for release AABs, but leave any existing setting untouched.
971
- const releaseBlock = findGradleBlock(updatedGradleContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
972
- if (releaseBlock) {
973
- const releaseContent = updatedGradleContent.slice(releaseBlock.start, releaseBlock.end);
974
- if (/\bdebugSymbolLevel\b/.test(releaseContent)) {
975
- console.log('ℹ️ debugSymbolLevel already exists in buildTypes.release; leaving it unchanged.');
976
- } else {
977
- const ndkBlock = `\n ndk {\n debugSymbolLevel 'FULL'\n }`;
978
- updatedGradleContent = updatedGradleContent.slice(0, releaseBlock.end)
979
- + ndkBlock
980
- + updatedGradleContent.slice(releaseBlock.end);
981
- console.log("✅ Added debugSymbolLevel 'FULL' to buildTypes.release.");
982
- }
983
- } else {
984
- console.log('⚠️ Warning: buildTypes.release block not found. debugSymbolLevel was not added.');
985
- }
986
-
987
-
988
-
989
-
990
-
991
-
992
- // Write the updated gradle content back to build.gradle
993
- writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
994
- console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en"; existing minification settings preserved.`);
995
-
996
- let baselineProfileChecked = false;
997
- for (const id of storeIds) {
998
- console.log(`ℹ️ Building for Store ID ${id}`);
999
-
1000
- // Set the environment variable for store ID
1001
- process.env.VITE_STORE_ID = id;
1002
-
1003
- // Conditionally set the new file name
1004
- let newFileName;
1005
- let storeName = storeNames[id];
1006
- // Amazon previously received version code 10000 for this package.
1007
- const storeVersionCode = _appPackageId === 'computer.shortcut.keys.app' && String(id) === '7'
1008
- ? String(10000 + Number(finalVersionCode))
1009
- : finalVersionCode;
1010
-
1011
-
1012
- if (
1013
- isOnlyOneAPK &&
1014
- ["OppoStore", "VivoStore"].includes(storeName)
1015
- ) {
1016
- console.log(`⏭ Skipping ${storeName} because isOnlyOneAPK is enabled`);
1017
- continue; // skip this iteration only
1018
- }
1019
-
1020
-
1021
- // build:storeid runs the shared before-build package/permission preparation.
1022
-
1023
- // 🔥 Only change filename logic — nothing else touched
1024
- if (isOnlyOneAPK && ["MiStore","OppoStore","VivoStore"].includes(storeName)) {
1025
-
1026
- newFileName =
1027
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-VI_MI_OPPO-b${storeVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
1028
-
1029
- }
1030
- else if (storeName === "SamsungStore") {
1031
-
1032
- newFileName =
1033
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${storeVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
1034
-
1035
- }
1036
- else {
1037
-
1038
- newFileName =
1039
- `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${storeVersionCode}-v${finalVersionName}.aab`;
1040
-
1041
- }
1042
-
1043
- //storeName="amazon"
1044
- const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
1045
-
1046
- // Modify minSdkVersion in variables.gradle for SamsungStore
1047
- const variablesGradleFilePath = join("android", "variables.gradle");
1048
- let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
1049
-
1050
- // Extract the current minSdkVersion
1051
- const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
1052
- const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
1053
-
1054
- // Store the original minSdkVersion (only on the first iteration)
1055
- if (!originalMinSdkVersion) {
1056
- originalMinSdkVersion = currentMinSdkVersion;
1057
- }
1058
- try {
1059
- applyFlowchartStoreApi(id);
1060
- const shouldIncludeAmazonWindowExtensions = String(id) === '7' && amazon === true;
1061
- setAmazonWindowExtensionsDependency(shouldIncludeAmazonWindowExtensions);
1062
- // Modify the minSdkVersion based on the store
1063
-
1064
-
1065
- if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
1066
- {
1067
- if (storeName === "SamsungStore" || storeName === "PlayStore" ||
1068
- //_appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker"
1069
-
1070
- //ffmpegUsedPackages.includes(_appPackageId)
1071
- _isffmpegUsed
1072
- ) {
1073
- if (currentMinSdkVersion !== 24) {
1074
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
1075
- console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
1076
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
1077
- }
1078
- } else {
1079
- // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
1080
- //if (currentMinSdkVersion !== originalMinSdkVersion) {
1081
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
1082
- console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
1083
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
1084
- //}
1085
- }
1086
- }
1087
-
1088
-
1089
- // Run the Node.js script to modify plugin.xml
1090
- if (isAdmobFound) {
1091
- const modifyPluginXmlPath = join('buildCodeplay', 'modify-plugin-xml.js');
1092
- if (existsSync(modifyPluginXmlPath)) {
1093
- execSync(`node ${modifyPluginXmlPath}`, { stdio: 'inherit' });
1094
- } else {
1095
- console.log("\x1b[33m%s\x1b[0m", "⚠️ modify-plugin-xml.js not found. Skipping old AdMob plugin.xml modification.");
1096
- }
1097
- } else {
1098
- console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
1099
- }
1100
-
1101
- // Run the Vite build
1102
- execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
1103
-
1104
-
1105
-
1106
-
1107
-
1108
-
1109
- // Copy the built files to the appropriate folder
1110
- const src = join("www");
1111
- const dest = join("android", "app", "src", "main", "assets", "public");
1112
-
1113
- // Copy the web build with Node so releases work on every platform.
1114
- fs.cpSync(src, dest, { recursive: true, force: true });
1115
-
1116
- // Build Android AAB file
1117
- //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
1118
-
1119
-
1120
- // Build Android AAB or APK file based on store
1121
- console.log(`🏗️ Building release for ${storeName}...`);
1122
-
1123
- /* let buildType = "AAB";
1124
- if (["VivoStore", "OppoStore", "MiStore"].includes(storeName)) {
1125
- buildType = "APK";
1126
- } */
1127
-
1128
-
1129
- // Determine build type and signing type per store
1130
- let buildType = ["VivoStore","OppoStore","MiStore"].includes(storeName) ? "APK" : "AAB";
1131
- let signingType = buildType === "APK" ? "apksigner" : "jarsigner";
1132
-
1133
- // Update capacitor.config.json for this store - This is not needed
1134
- //updateCapacitorConfig(buildType, signingType);
1135
-
1136
-
1137
-
1138
- /* execSync('npx cap sync android', { stdio: 'inherit' });
1139
- execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' }); */
1140
-
1141
-
1142
- execSync('npx cap sync android', { stdio: 'inherit' });
1143
-
1144
- if (!baselineProfileChecked) {
1145
- await checkBaselineProfileBeforeRelease();
1146
- baselineProfileChecked = true;
1147
- }
1148
- ensureReleaseCodeOptimization();
1149
-
1150
- const releaseBuildEnv = { ...process.env };
1151
- if (_appPackageId === 'resume.generator.cv') {
1152
- releaseBuildEnv.GRADLE_OPTS = [
1153
- process.env.GRADLE_OPTS,
1154
- '-Dorg.gradle.jvmargs="-Xmx4g -XX:MaxMetaspaceSize=1g"',
1155
- '-Dorg.gradle.workers.max=2',
1156
- ].filter(Boolean).join(' ');
1157
- }
1158
-
1159
- const hasStoreVersionOverride = String(storeVersionCode) !== String(finalVersionCode);
1160
- try {
1161
- if (hasStoreVersionOverride) {
1162
- const storeGradleContent = readFileSync(gradleFilePath, 'utf8');
1163
- writeFileSync(gradleFilePath, storeGradleContent.replace(/versionCode\s+\d+/, `versionCode ${storeVersionCode}`), 'utf8');
1164
- console.log(`📦 ${storeName} versionCode: ${storeVersionCode} (base: ${finalVersionCode})`);
1165
- }
1166
- if (buildType === "APK") {
1167
- console.log("📦 Using custom Node signing script for APK build...");
1168
- execFileSync(process.execPath, [join(process.cwd(), 'buildCodeplay', 'apk-store-builder.js')], { stdio: 'inherit', env: releaseBuildEnv });
1169
- } else {
1170
- execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit', env: releaseBuildEnv });
1171
- signReleaseBundleWithSha256();
1172
- }
1173
- } finally {
1174
- if (hasStoreVersionOverride) {
1175
- const storeGradleContent = readFileSync(gradleFilePath, 'utf8');
1176
- writeFileSync(gradleFilePath, storeGradleContent.replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`), 'utf8');
1177
- }
1178
- }
1179
-
1180
-
1181
-
1182
- // Determine output paths
1183
- let oldFilePath;
1184
- let newExt = buildType === "APK" ? "apk" : "aab";
1185
-
1186
- if (buildType === "APK") {
1187
- //oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release-signed.apk");
1188
- oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release.apk");
1189
- } else {
1190
- oldFilePath = join("android", "app", "build", "outputs", "bundle", "release", "app-release-signed.aab");
1191
- }
1192
-
1193
- const checkFullPath = join("AAB", newFileName.replace(/\.aab$/, `.${newExt}`));
1194
-
1195
- // Rename the output file
1196
- if (existsSync(oldFilePath)) {
1197
- renameSync(oldFilePath, checkFullPath);
1198
- console.log(`✅ Renamed output ${newExt.toUpperCase()} file to: ${path.basename(checkFullPath)}`);
1199
- syncReleaseToCodeplay(storeName, finalVersionName, storeVersionCode, new Date().toISOString().slice(0, 10));
1200
- } else {
1201
- console.error(`❌ ${newExt.toUpperCase()} file not found after build.`);
1202
- }
1203
-
1204
- } catch (error) {
1205
- console.error(`❌ Error during build for Store ID ${id}:`, error);
1206
- restoreFlowchartStoreApi();
1207
- setAmazonWindowExtensionsDependency(false, {
1208
- cleanup: String(id) === '7' && amazon === true,
1209
- });
1210
- process.exit(1);
1211
- } finally {
1212
- restoreFlowchartStoreApi();
1213
- setAmazonWindowExtensionsDependency(false, {
1214
- cleanup: String(id) === '7' && amazon === true,
1215
- });
1216
- }
1217
- }
1218
-
1219
- rl.close(); // Close the readline interface after all operations
1220
- });
1221
- });
1222
-
1223
-
1224
-
1225
-
1226
-
1227
- /* function updateAndroidManifest1(store, addPermission) {
1228
- try {
1229
- if (!fs.existsSync(androidManifestPath)) {
1230
- console.error("AndroidManifest.xml file not found!");
1231
- return;
1232
- }
1233
-
1234
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
1235
-
1236
-
1237
-
1238
- // Add the required permission if not already present
1239
- if (!manifestContent.includes(addPermission)) {
1240
- const manifestLines = manifestContent.split('\n');
1241
- const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
1242
- if (insertIndex > -1) {
1243
- manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
1244
- manifestContent = manifestLines.join('\n');
1245
- console.log(`Added ${addPermission} to AndroidManifest.xml`);
1246
- }
1247
- }
1248
-
1249
- // Write the updated content back to the file
1250
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
1251
- console.log(`AndroidManifest.xml updated successfully for ${store}`);
1252
- } catch (err) {
1253
- console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
1254
- }
1255
- } */
1256
-
1257
-
1258
-
1259
-
1260
-
1261
-
1262
-
1263
-
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, execFileSync } from 'child_process';
11
+ import { createInterface } from 'readline';
12
+
13
+ import { fileURLToPath } from 'url';
14
+ import { dirname } from 'path';
15
+ import { syncAndroidR8Rules } from './buildCodeplay/fix-optimize-builld/restore-android-r8-rules.cjs';
16
+
17
+ /* const path = require('path');
18
+ const fs = require('fs'); */
19
+
20
+ import fs from 'fs';
21
+ import path from 'path';
22
+
23
+ const __filename = fileURLToPath(import.meta.url);
24
+ const __dirname = process.cwd();
25
+
26
+ function stripJavaScriptComments(content) {
27
+ let result = '';
28
+ let state = 'code';
29
+
30
+ for (let index = 0; index < content.length; index++) {
31
+ const character = content[index];
32
+ const nextCharacter = content[index + 1];
33
+
34
+ if (state === 'lineComment') {
35
+ if (character === '\n') {
36
+ result += character;
37
+ state = 'code';
38
+ } else {
39
+ result += ' ';
40
+ }
41
+ continue;
42
+ }
43
+
44
+ if (state === 'blockComment') {
45
+ if (character === '*' && nextCharacter === '/') {
46
+ result += ' ';
47
+ index++;
48
+ state = 'code';
49
+ } else {
50
+ result += character === '\n' ? '\n' : ' ';
51
+ }
52
+ continue;
53
+ }
54
+
55
+ if (state !== 'code') {
56
+ result += character;
57
+
58
+ if (character === '\\') {
59
+ if (nextCharacter !== undefined) {
60
+ result += nextCharacter;
61
+ index++;
62
+ }
63
+ } else if (
64
+ (state === 'singleQuote' && character === "'") ||
65
+ (state === 'doubleQuote' && character === '"') ||
66
+ (state === 'templateLiteral' && character === '`')
67
+ ) {
68
+ state = 'code';
69
+ }
70
+ continue;
71
+ }
72
+
73
+ if (character === '/' && nextCharacter === '/') {
74
+ result += ' ';
75
+ index++;
76
+ state = 'lineComment';
77
+ } else if (character === '/' && nextCharacter === '*') {
78
+ result += ' ';
79
+ index++;
80
+ state = 'blockComment';
81
+ } else {
82
+ result += character;
83
+
84
+ if (character === "'") state = 'singleQuote';
85
+ else if (character === '"') state = 'doubleQuote';
86
+ else if (character === '`') state = 'templateLiteral';
87
+ }
88
+ }
89
+
90
+ return result;
91
+ }
92
+
93
+ function checkProductionAdmobAlias() {
94
+ const capacitorConfig = JSON.parse(readFileSync(resolve(__dirname, 'capacitor.config.json'), 'utf8'));
95
+ if (capacitorConfig.plugins?.AdMob?.ADMOB_ENABLED === false) {
96
+ console.log('ℹ️ AdMob is disabled; production @admob alias validation skipped.');
97
+ return;
98
+ }
99
+
100
+ const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
101
+ const viteConfigPath = possibleConfigFiles
102
+ .map(configFile => resolve(__dirname, configFile))
103
+ .find(filePath => existsSync(filePath));
104
+
105
+ if (!viteConfigPath) {
106
+ console.error('❌ FINAL RELEASE BLOCKED: No vite.config.mjs or vite.config.js file found.');
107
+ process.exit(1);
108
+ }
109
+
110
+ const viteConfigContent = stripJavaScriptComments(readFileSync(viteConfigPath, 'utf8'));
111
+ const aliasPattern = /(['"])@admob\1\s*:\s*path\.resolve\(\s*__dirname\s*,\s*(['"])([^'"\r\n]+)\2\s*\)/g;
112
+ const activeAliases = [...viteConfigContent.matchAll(aliasPattern)].map(match => match[3]);
113
+ const productionAliasPattern = /^\.\/src\/js\/Ads\/(?:admob-nextgen-\d+(?:\.\d+)+\/admob-emi-nextgen|admob-emi-nextgen-\d+(?:\.\d+)+)\.js$/;
114
+
115
+ if (activeAliases.length === 0) {
116
+ console.error('❌ FINAL RELEASE BLOCKED: The production @admob alias is commented out or missing in the Vite config.');
117
+ console.error(" Enable: '@admob': path.resolve(__dirname, './src/js/Ads/admob-nextgen-x.x/admob-emi-nextgen.js')");
118
+ process.exit(1);
119
+ }
120
+
121
+ if (activeAliases.length > 1) {
122
+ console.error('❌ FINAL RELEASE BLOCKED: Multiple active @admob aliases were found in the Vite config.');
123
+ console.error(' Keep exactly one active production @admob alias.');
124
+ process.exit(1);
125
+ }
126
+
127
+ const activeAlias = activeAliases[0];
128
+ if (!productionAliasPattern.test(activeAlias)) {
129
+ console.error(`❌ FINAL RELEASE BLOCKED: @admob currently points to '${activeAlias}'.`);
130
+ console.error(" It must point to './src/js/Ads/admob-nextgen-x.x/admob-emi-nextgen.js', not a test AdMob file.");
131
+ process.exit(1);
132
+ }
133
+
134
+ const productionAdmobPath = resolve(__dirname, activeAlias);
135
+ if (!existsSync(productionAdmobPath)) {
136
+ console.error(`❌ FINAL RELEASE BLOCKED: The production @admob file does not exist: ${productionAdmobPath}`);
137
+ process.exit(1);
138
+ }
139
+
140
+ console.log(`✅ Production @admob alias verified: ${activeAlias}`);
141
+ }
142
+
143
+ // Validate the production alias first when AdMob is enabled.
144
+ checkProductionAdmobAlias();
145
+
146
+ // Define a mapping between store IDs and store names
147
+ /* const storeNames = {
148
+ "1": "PlayStore",
149
+ "2": "SamsungStore",
150
+ "7": "AmazonStore"
151
+ }; */
152
+
153
+
154
+ const isOnlyOneAPK = false; // 🔥 change to false for normal behavior
155
+
156
+ const storeNames = {
157
+ "1": "PlayStore",
158
+ "2": "SamsungStore",
159
+ "7": "AmazonStore",
160
+
161
+ "3": "MiStore",
162
+ "4": "HuaweiStore",
163
+ "5": "OppoStore",
164
+ //"6": "iOSStore",
165
+ "8": "VivoStore"
166
+ };
167
+
168
+
169
+ //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
170
+
171
+
172
+
173
+
174
+
175
+
176
+
177
+ let isAdmobFound = false;
178
+
179
+ const amazonMinSdkVersion=24;
180
+
181
+ const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
182
+
183
+
184
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
185
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
186
+
187
+ const _appUniqueId = config.android?.APP_UNIQUE_ID;
188
+ const _appName=config.appName;
189
+ const _appPackageId=config.appId;
190
+
191
+ const appReleaseSyncConfigPath = join(process.cwd(), 'buildCodeplay', 'release-sync.config.json');
192
+ const releaseSyncConfigPath = appReleaseSyncConfigPath;
193
+ let releaseSyncConfig = {};
194
+ if (existsSync(releaseSyncConfigPath)) {
195
+ try {
196
+ releaseSyncConfig = JSON.parse(readFileSync(releaseSyncConfigPath, 'utf8'));
197
+ } catch (error) {
198
+ console.warn(`⚠️ Could not read ${releaseSyncConfigPath}: ${error.message}`);
199
+ }
200
+ }
201
+ const RELEASE_SYNC_URL = process.env.CODEPLAY_RELEASE_SYNC_URL || releaseSyncConfig.url || 'https://htmlcodeplay.com/codeplay/api/v1/release/sync';
202
+ const RELEASE_SYNC_TOKEN = process.env.CODEPLAY_RELEASE_SYNC_TOKEN || releaseSyncConfig.token || '';
203
+ const RELEASE_PLATFORM_IDS = { PlayStore: 1, SamsungStore: 13, AmazonStore: 17, MiStore: 15, HuaweiStore: 12, OppoStore: 14, VivoStore: 16 };
204
+
205
+ function syncReleaseToCodeplay(storeName, finalVersionName, finalVersionCode, releasedDate) {
206
+ if (!RELEASE_SYNC_TOKEN) {
207
+ console.warn(`⚠️ Codeplay release sync skipped: add a token to ${releaseSyncConfigPath}.`);
208
+ return;
209
+ }
210
+ const payload = JSON.stringify({
211
+ app_name: _appName,
212
+ package_id: _appPackageId,
213
+ version_name: String(finalVersionName),
214
+ version_code: String(finalVersionCode),
215
+ released_date: releasedDate,
216
+ language_id: 0,
217
+ language_name: 'Capacitor+ Framework 7',
218
+ notes: 'Automated release update',
219
+ status: 1,
220
+ folder_name: path.basename(process.cwd()),
221
+ app_unique_id: String(_appUniqueId || ''),
222
+ platform_id: RELEASE_PLATFORM_IDS[storeName],
223
+ });
224
+ try {
225
+ const response = execFileSync('curl.exe', ['-sS', '--fail-with-body', '-X', 'POST', RELEASE_SYNC_URL,
226
+ '-H', 'Content-Type: application/json', '-H', `X-Release-Token: ${RELEASE_SYNC_TOKEN}`, '--data-binary', payload],
227
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
228
+ console.log(`✅ Codeplay sync (${storeName}): ${response.trim()}`);
229
+ } catch (error) {
230
+ console.warn(`⚠️ Codeplay sync failed for ${storeName}; continuing release builds: ${error.message}`);
231
+ }
232
+ }
233
+
234
+ const FLOWCHART_API_APP_ID = 228;
235
+ const FLOWCHART_SHARED_PATH = join('public', 'src', 'shared.js');
236
+ const FLOWCHART_PLAY_API_BASE = 'https://htmlcodeplay.com/appfiles/128FlowChart';
237
+ const FLOWCHART_OTHER_STORE_API_BASE = 'https://htmlcodeplay.com/appfiles/128FlowChart/otherapi';
238
+ const FLOWCHART_OTHER_STORE_API_HASH = 'd1a3774529b74206ae2117f9c25f258e485a1f7348620e769db19c2796aa1fdf';
239
+ const flowchartSharedOriginal = existsSync(FLOWCHART_SHARED_PATH)
240
+ ? readFileSync(FLOWCHART_SHARED_PATH, 'utf8')
241
+ : null;
242
+
243
+ function applyFlowchartStoreApi(storeId) {
244
+ if (String(_appUniqueId) !== String(FLOWCHART_API_APP_ID) || !flowchartSharedOriginal) return false;
245
+ const apiBase = String(storeId) === '1' ? FLOWCHART_PLAY_API_BASE : FLOWCHART_OTHER_STORE_API_BASE;
246
+ const accessHash = String(storeId) === '1' ? '' : FLOWCHART_OTHER_STORE_API_HASH;
247
+ const apiBaseMarker = /const FLOWCHART_API_BASE = "[^"]*";/;
248
+ const accessHashMarker = /const FLOWCHART_API_ACCESS_HASH = "[^"]*";/;
249
+
250
+ if (!apiBaseMarker.test(flowchartSharedOriginal) || !accessHashMarker.test(flowchartSharedOriginal)) {
251
+ throw new Error(`Flowchart API configuration markers were not found in ${FLOWCHART_SHARED_PATH}.`);
252
+ }
253
+
254
+ const updated = flowchartSharedOriginal
255
+ .replace(apiBaseMarker, `const FLOWCHART_API_BASE = "${apiBase}";`)
256
+ .replace(accessHashMarker, `const FLOWCHART_API_ACCESS_HASH = "${accessHash}";`);
257
+ writeFileSync(FLOWCHART_SHARED_PATH, updated, 'utf8');
258
+ console.log(`✅ App 228 API endpoint configured for Store ID ${storeId}.`);
259
+ return true;
260
+ }
261
+
262
+ function restoreFlowchartStoreApi() {
263
+ if (String(_appUniqueId) === String(FLOWCHART_API_APP_ID) && flowchartSharedOriginal) {
264
+ writeFileSync(FLOWCHART_SHARED_PATH, flowchartSharedOriginal, 'utf8');
265
+ }
266
+ }
267
+
268
+
269
+
270
+ function fileExists(filePath) {
271
+ return existsSync(filePath);
272
+ }
273
+
274
+
275
+ const ffmpegPluginXmlPath = path.join(__dirname, 'node_modules', 'codeplay-fmpg', 'plugin.xml');
276
+ const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
277
+
278
+
279
+
280
+ function isFfmpegUsed() {
281
+ try {
282
+ const xmlContent = fs.readFileSync(ffmpegPluginXmlPath, 'utf8');
283
+ // Simple check: if plugin.xml exists and contains <plugin> tag (or any FFmpeg-specific tag)
284
+ return /<plugin\b/.test(xmlContent);
285
+ } catch (err) {
286
+ console.log('⚠️ FFmpeg plugin not found:', err.message);
287
+ return false;
288
+ }
289
+ }
290
+
291
+ const _isffmpegUsed = isFfmpegUsed();
292
+
293
+ function getAdMobConfig() {
294
+ if (!fileExists(capacitorConfigPath)) {
295
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
296
+ }
297
+
298
+ const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
299
+ const admobConfig = config.plugins?.AdMob;
300
+
301
+ //_appPackageId=config.appId;
302
+
303
+ if (!admobConfig) {
304
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
305
+ }
306
+
307
+ // Default to true if ADMOB_ENABLED is not specified
308
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
309
+
310
+ if (!isEnabled) {
311
+ return { ADMOB_ENABLED: false }; // Skip further validation
312
+ }
313
+
314
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
315
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
316
+ }
317
+
318
+ return {
319
+ ADMOB_ENABLED: true,
320
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
321
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
322
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
323
+ };
324
+ }
325
+
326
+
327
+
328
+ const _capacitorConfig = getAdMobConfig();
329
+
330
+ const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
331
+ isAdmobFound = _isADMOB_ENABLED;
332
+
333
+ // Proceed only if ADMOB_ENABLED is true
334
+ //if (_capacitorConfig.ADMOB_ENABLED)
335
+
336
+
337
+ const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration-nextgen.json');
338
+ let admobConfig;
339
+
340
+ if (_isADMOB_ENABLED)
341
+ {
342
+ try
343
+ {
344
+ admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
345
+ }
346
+ catch (err)
347
+ {
348
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
349
+ process.exit(1);
350
+ }
351
+ }
352
+
353
+
354
+
355
+
356
+
357
+ function updateIOSVersion(versionCode, versionName) {
358
+
359
+ const pbxprojPath = join("ios", "App", "App.xcodeproj", "project.pbxproj");
360
+
361
+ // 🔥 Single check only
362
+ if (!existsSync(pbxprojPath)) {
363
+ console.warn("⚠️ iOS project not found, skipping version update");
364
+ return;
365
+ }
366
+
367
+
368
+ let content = readFileSync(pbxprojPath, 'utf8');
369
+
370
+ // Update MARKETING_VERSION
371
+ content = content.replace(
372
+ /MARKETING_VERSION = .*?;/g,
373
+ `MARKETING_VERSION = ${versionName};`
374
+ );
375
+
376
+ // Update CURRENT_PROJECT_VERSION
377
+ /* content = content.replace(
378
+ /CURRENT_PROJECT_VERSION = .*?;/g,
379
+ `CURRENT_PROJECT_VERSION = ${versionCode};`
380
+ ); */
381
+
382
+ writeFileSync(pbxprojPath, content, 'utf8');
383
+
384
+ console.log(`🍏 iOS updated via Xcode settings → version: ${versionName}, build: ${versionCode}`);
385
+ }
386
+
387
+
388
+
389
+
390
+
391
+
392
+
393
+
394
+
395
+
396
+
397
+
398
+
399
+
400
+
401
+
402
+
403
+
404
+
405
+
406
+
407
+ const checkCommonFileStoreId=()=>{
408
+ const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
409
+ let viteConfigPath;
410
+ for (const configFile of possibleConfigFiles) {
411
+ const fullPath = resolve( configFile);
412
+ if (existsSync(fullPath)) {
413
+ viteConfigPath = fullPath;
414
+ break;
415
+ }
416
+ }
417
+
418
+ if (!viteConfigPath) {
419
+ console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
420
+ process.exit(1);
421
+ }
422
+
423
+ try {
424
+ // Read vite config file
425
+ const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
426
+
427
+ // Extract @common alias path
428
+ const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
429
+ const match = viteConfigContent.match(aliasPattern);
430
+
431
+ if (!match) {
432
+ console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
433
+ process.exit(1);
434
+ }
435
+
436
+ const commonFilePath = match[1];
437
+ const resolvedCommonPath = resolve(__dirname, commonFilePath);
438
+
439
+ // Read the common file content
440
+ if (!existsSync(resolvedCommonPath)) {
441
+ console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
442
+ process.exit(1);
443
+ }
444
+
445
+ const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
446
+
447
+ // Check for the _storeid export line
448
+ const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
449
+ if (!storeIdPattern.test(commonFileContent)) {
450
+ console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
451
+ process.exit(1);
452
+ }
453
+
454
+ console.log(commonFilePath,'Success - No problem found');
455
+ } catch (error) {
456
+ console.error('❌ Error:', error);
457
+ process.exit(1);
458
+ }
459
+
460
+ }
461
+
462
+ const checkIsTestingInAdmob=()=>{
463
+
464
+ if (admobConfig.config && admobConfig.config.isTesting === true) {
465
+ console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration-nextgen.json" file.`);
466
+ process.exit(1); // Exit with an error code to halt the process
467
+ } else {
468
+ console.log('✅ No problem found. "isTesting" is either already false or not defined.');
469
+ }
470
+ }
471
+
472
+ const checkIsAdsDisableByReturnStatement=()=>{
473
+
474
+
475
+ // Inspect the controller selected by the validated production alias.
476
+ const viteFile = ['vite.config.mjs', 'vite.config.js']
477
+ .map(file => resolve(__dirname, file)).find(file => existsSync(file));
478
+ const config = stripJavaScriptComments(readFileSync(viteFile, 'utf8'));
479
+ const alias = config.match(/(['"])@admob\1\s*:\s*path\.resolve\(\s*__dirname\s*,\s*(['"])([^'"\r\n]+)\2\s*\)/);
480
+ const filePath = resolve(__dirname, alias[3]);
481
+ const admobFile = alias[3];
482
+ const content = readFileSync(filePath, 'utf-8');
483
+
484
+ // Step 2: Extract the adsOnDeviceReady function body
485
+ const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
486
+ const match = content.match(functionRegex);
487
+
488
+ if (!match) {
489
+ console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
490
+ process.exit(1);
491
+ }
492
+
493
+ const body = match[1];
494
+ const lines = body.split('\n').map(line => line.trim());
495
+
496
+ // Step 3: Skip blank lines and comments, get the first real code line
497
+ let firstCodeLine = '';
498
+ for (const line of lines) {
499
+ if (line === '' || line.startsWith('//')) continue;
500
+ firstCodeLine = line;
501
+ break;
502
+ }
503
+
504
+ // Step 4: Block if it's any of the unwanted returns
505
+ const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
506
+
507
+ if (badReturnPattern.test(firstCodeLine)) {
508
+ console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
509
+ process.exit(2);
510
+ } else {
511
+ console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
512
+ }
513
+ }
514
+
515
+
516
+
517
+ const addPermission_AD_ID=async()=>{
518
+
519
+ if (isAdmobFound) {
520
+ if (existsSync(androidManifestPath)) {
521
+ let manifestContent = readFileSync(androidManifestPath, 'utf8');
522
+ let modified = false;
523
+
524
+ // --- Step 1: Ensure AD_ID permission exists ---
525
+ const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
526
+ if (!manifestContent.includes(adIdPermission)) {
527
+ console.log("📄 AD_ID permission not found. Adding to AndroidManifest.xml.");
528
+ manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
529
+ console.log("✅ AD_ID permission added successfully.");
530
+ modified = true;
531
+ } else {
532
+ console.log("ℹ️ AD_ID permission already exists in AndroidManifest.xml.");
533
+ }
534
+
535
+ // --- Step 2: Ensure OPTIMIZE_AD_LOADING meta-data exists ---
536
+ const optimizeAdMeta = `<meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" />`;
537
+
538
+ if (!manifestContent.includes(optimizeAdMeta)) {
539
+ console.log("📄 OPTIMIZE_AD_LOADING meta-data not found. Adding to AndroidManifest.xml.");
540
+
541
+ const appTagPattern = /<application[^>]*>/;
542
+ if (appTagPattern.test(manifestContent)) {
543
+ manifestContent = manifestContent.replace(appTagPattern, match => `${match}\n ${optimizeAdMeta}`);
544
+ console.log("✅ OPTIMIZE_AD_LOADING meta-data added successfully.");
545
+ modified = true;
546
+ } else {
547
+ console.error("❌ <application> tag not found in AndroidManifest.xml.");
548
+ }
549
+ } else {
550
+ console.log("ℹ️ OPTIMIZE_AD_LOADING meta-data already exists in AndroidManifest.xml.");
551
+ }
552
+
553
+ // --- Step 3: Write only if modified ---
554
+ if (modified) {
555
+ writeFileSync(androidManifestPath, manifestContent, 'utf8');
556
+ console.log("💾 AndroidManifest.xml updated successfully.");
557
+ } else {
558
+ console.log("✅ No changes needed. AndroidManifest.xml is up to date.");
559
+ }
560
+
561
+ } else {
562
+ console.error("❌ AndroidManifest.xml not found at the specified path.");
563
+ }
564
+ } else {
565
+ console.log("\x1b[33m%s\x1b[0m", "⚠️ No AdMob found, so AD_ID permission and meta-data were not added");
566
+ }
567
+
568
+
569
+
570
+
571
+
572
+
573
+ }
574
+
575
+
576
+
577
+
578
+
579
+
580
+
581
+
582
+
583
+
584
+
585
+ checkCommonFileStoreId();
586
+
587
+
588
+
589
+ if (_isADMOB_ENABLED)
590
+ {
591
+ checkIsTestingInAdmob();
592
+ checkIsAdsDisableByReturnStatement()
593
+
594
+ await addPermission_AD_ID()
595
+ }
596
+
597
+
598
+
599
+ let originalReleaseType, originalSigningType;
600
+
601
+ function readCapacitorConfig() {
602
+ return JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
603
+ }
604
+
605
+ function writeCapacitorConfig(config) {
606
+ fs.writeFileSync(capacitorConfigPath, JSON.stringify(config, null, 2), 'utf8');
607
+ }
608
+
609
+ /* function updateCapacitorConfig(releaseType, signingType) {
610
+ const config = readCapacitorConfig();
611
+
612
+ // Save original values once
613
+ if (originalReleaseType === undefined) originalReleaseType = config.android?.buildOptions?.releaseType || '';
614
+ if (originalSigningType === undefined) originalSigningType = config.android?.buildOptions?.signingType || '';
615
+
616
+ // Update values
617
+ config.android = config.android || {};
618
+ config.android.buildOptions = config.android.buildOptions || {};
619
+ config.android.buildOptions.releaseType = releaseType;
620
+ config.android.buildOptions.signingType = signingType;
621
+
622
+ writeCapacitorConfig(config);
623
+ console.log(`ℹ️ capacitor.config.json updated: releaseType=${releaseType}, signingType=${signingType}`);
624
+ } */
625
+
626
+ /* function restoreCapacitorConfig() {
627
+ const config = readCapacitorConfig();
628
+ if (originalReleaseType !== undefined) config.android.buildOptions.releaseType = originalReleaseType;
629
+ if (originalSigningType !== undefined) config.android.buildOptions.signingType = originalSigningType;
630
+ writeCapacitorConfig(config);
631
+ console.log(`✅ capacitor.config.json restored to original values.`);
632
+ }
633
+
634
+ process.on('SIGINT', () => {
635
+ console.log('\n⚠️ Detected Ctrl+C, restoring capacitor.config.json...');
636
+ restoreCapacitorConfig();
637
+ process.exit(0);
638
+ });
639
+
640
+ process.on('exit', () => {
641
+ restoreCapacitorConfig();
642
+ }); */
643
+
644
+
645
+
646
+ const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
647
+ console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
648
+
649
+
650
+
651
+
652
+
653
+
654
+ // Get the store ID from the command line arguments
655
+ /* const storeIdArg = ["2","3"]//process.argv[2]; // Get the store ID from the command line
656
+ const storeIds = storeIdArg ? storeIdArg : Object.keys(storeNames);//["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
657
+
658
+ debugger; */
659
+
660
+ let storeIdArg = process.argv[2]; // command-line argument
661
+ let storeIds;
662
+
663
+ if (storeIdArg) {
664
+ try {
665
+ // Try parsing as JSON array first
666
+ const parsed = JSON.parse(storeIdArg);
667
+ if (Array.isArray(parsed)) {
668
+ storeIds = parsed.map(String); // ensure strings
669
+ } else {
670
+ storeIds = [parsed.toString()];
671
+ }
672
+ } catch (e) {
673
+ // Not JSON, assume comma-separated string
674
+ storeIds = storeIdArg.split(",").map(s => s.trim());
675
+ }
676
+ } else {
677
+ // No argument, use all store IDs
678
+ storeIds = Object.keys(storeNames);
679
+ }
680
+
681
+
682
+ // 🔥 If only one APK mode, override APK storeIds
683
+ /* if (isOnlyOneAPK) {
684
+ console.log("⚡ isOnlyOneAPK enabled → Only MiStore (3) will be used for APK build");
685
+ storeIds = ["3"]; // Only MiStore
686
+ } */
687
+
688
+ // Store the original minSdkVersion globally
689
+ let originalMinSdkVersion;
690
+
691
+ // Remove any existing AAB files before starting the build process
692
+ const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
693
+ if (existsSync(aabDirectory)) {
694
+ const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
695
+ files.forEach(file => {
696
+ const filePath = join(aabDirectory, file);
697
+ unlinkSync(filePath);
698
+ console.log(`ℹ️ Deleted existing AAB file: ${file}`);
699
+ });
700
+ }
701
+
702
+ const aabOutputDir = join("AAB");
703
+ if (!existsSync(aabOutputDir)) {
704
+ mkdirSync(aabOutputDir);
705
+ console.log(`Created directory: ${aabOutputDir}`);
706
+ }
707
+
708
+ if (existsSync(aabOutputDir)) {
709
+ const files = readdirSync(aabOutputDir).filter(
710
+ file => file.endsWith('.aab') || file.endsWith('.apk')
711
+ );
712
+
713
+ files.forEach(file => {
714
+ const filePath = join(aabOutputDir, file);
715
+ unlinkSync(filePath);
716
+ console.log(`Deleted existing build file: ${file}`);
717
+ });
718
+ }
719
+
720
+
721
+ // Extract version code and version name from build.gradle
722
+ const gradleFilePath = join("android", "app", "build.gradle");
723
+ const gradleContent = readFileSync(gradleFilePath, 'utf8');
724
+
725
+ // Return the character range of a Gradle block, allowing nested blocks inside it.
726
+ function findGradleBlock(content, headerPattern) {
727
+ const headerMatch = content.match(headerPattern);
728
+ if (!headerMatch) return null;
729
+ const openingBrace = content.indexOf('{', headerMatch.index + headerMatch[0].length);
730
+ if (openingBrace === -1) return null;
731
+ let depth = 0;
732
+ let quote = null;
733
+ for (let index = openingBrace; index < content.length; index += 1) {
734
+ const character = content[index];
735
+ const previous = content[index - 1];
736
+ if (quote) {
737
+ if (character === quote && previous !== '\\') quote = null;
738
+ continue;
739
+ }
740
+ if (character === '\"' || character === "'") quote = character;
741
+ else if (character === '{') depth += 1;
742
+ else if (character === '}' && --depth === 0) return { start: openingBrace + 1, end: index };
743
+ }
744
+ return null;
745
+ }
746
+
747
+ function ensureReleaseCodeOptimization() {
748
+ syncAndroidR8Rules(process.cwd(), { installGradleHook: true });
749
+ const currentContent = readFileSync(gradleFilePath, 'utf8');
750
+ const releaseBlock = findGradleBlock(currentContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
751
+ if (!releaseBlock) throw new Error('Release build configuration was not found.');
752
+
753
+ const releaseContent = currentContent.slice(releaseBlock.start, releaseBlock.end);
754
+ let optimizedContent = releaseContent.replace(
755
+ /getDefaultProguardFile\(\s*(['"])proguard-android\.txt\1\s*\)/g,
756
+ "getDefaultProguardFile('proguard-android-optimize.txt')"
757
+ );
758
+ if (!/getDefaultProguardFile\(\s*(['"])proguard-android-optimize\.txt\1\s*\)/.test(optimizedContent)) {
759
+ throw new Error('Release build must use the optimisation-enabled default ProGuard rules.');
760
+ }
761
+ const newline = currentContent.includes('\r\n') ? '\r\n' : '\n';
762
+ // Preserve commented settings and explicit false values as app-specific opt-outs.
763
+ const comments = optimizedContent.match(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g) || [];
764
+ if (!comments.some(comment => /\bshrinkResources\b/.test(comment))) {
765
+ const activeContent = optimizedContent.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\//g, '');
766
+ const shrinkResources = /^[ \t]*minifyEnabled\s*(?:=\s*)?true\b/m.test(activeContent);
767
+ const shrinkPattern = /^([ \t]*shrinkResources\s*(?:=\s*)?)(true|false)\b/m;
768
+ if (shrinkPattern.test(optimizedContent)) {
769
+ if (!shrinkResources) optimizedContent = optimizedContent.replace(shrinkPattern, '$1false');
770
+ } else {
771
+ optimizedContent = `${newline} shrinkResources ${shrinkResources}${optimizedContent}`;
772
+ }
773
+ }
774
+ if (optimizedContent !== releaseContent) {
775
+ writeFileSync(gradleFilePath, currentContent.slice(0, releaseBlock.start)
776
+ + optimizedContent + currentContent.slice(releaseBlock.end), 'utf8');
777
+ }
778
+
779
+ const propertiesPath = join(__dirname, 'android', 'gradle.properties');
780
+ const properties = readFileSync(propertiesPath, 'utf8');
781
+ const propertyPattern = /^[ \t]*[#!]?[ \t]*android\.r8\.optimizedResourceShrinking(?:[ \t]*[=:]|[ \t]+|[ \t]*$)/m;
782
+ const property = 'android.r8.optimizedResourceShrinking=true';
783
+ const nextProperties = propertyPattern.test(properties)
784
+ ? properties
785
+ : `${properties.trimEnd()}${newline}${property}${newline}`;
786
+ if (nextProperties !== properties) writeFileSync(propertiesPath, nextProperties, 'utf8');
787
+ }
788
+
789
+ function signReleaseBundleWithSha256() {
790
+ const buildOptions = readCapacitorConfig().android?.buildOptions;
791
+ if (!buildOptions?.keystorePath || !buildOptions.keystorePassword
792
+ || !buildOptions.keystoreAlias || !buildOptions.keystoreAliasPassword) {
793
+ throw new Error('Android AAB signing requires the existing keystore path, alias and passwords.');
794
+ }
795
+
796
+ const keystorePath = resolve(__dirname, 'android', buildOptions.keystorePath);
797
+ const bundleDirectory = join(__dirname, 'android', 'app', 'build', 'outputs', 'bundle', 'release');
798
+ const unsignedBundle = join(bundleDirectory, 'app-release.aab');
799
+ const signedBundle = join(bundleDirectory, 'app-release-signed.aab');
800
+ if (!existsSync(keystorePath) || !existsSync(unsignedBundle)) {
801
+ throw new Error('The configured upload keystore or release AAB was not found.');
802
+ }
803
+
804
+ const jarsigner = process.env.JAVA_HOME
805
+ ? join(process.env.JAVA_HOME, 'bin', process.platform === 'win32' ? 'jarsigner.exe' : 'jarsigner')
806
+ : 'jarsigner';
807
+ try {
808
+ // Keep passwords out of command arguments and error output.
809
+ execFileSync(jarsigner, [
810
+ '-sigalg', 'SHA256withRSA', '-digestalg', 'SHA-256',
811
+ '-keystore', keystorePath,
812
+ '-storepass:env', 'CODEPLAY_AAB_STORE_PASSWORD',
813
+ '-keypass:env', 'CODEPLAY_AAB_KEY_PASSWORD',
814
+ '-signedjar', signedBundle, unsignedBundle, buildOptions.keystoreAlias,
815
+ ], {
816
+ stdio: 'pipe',
817
+ env: {
818
+ ...process.env,
819
+ CODEPLAY_AAB_STORE_PASSWORD: buildOptions.keystorePassword,
820
+ CODEPLAY_AAB_KEY_PASSWORD: buildOptions.keystoreAliasPassword,
821
+ },
822
+ });
823
+ const verification = execFileSync(jarsigner, [
824
+ '-J-Duser.language=en', '-J-Duser.country=US', '-verify', signedBundle,
825
+ ], { encoding: 'utf8', stdio: 'pipe' });
826
+ if (!verification.includes('jar verified.') || verification.includes('treated as unsigned')) {
827
+ throw new Error('Signature verification failed.');
828
+ }
829
+ } catch {
830
+ throw new Error('SHA-256 AAB signing or verification failed. Check the configured upload key and JDK; release stopped.');
831
+ }
832
+ console.log('✅ Release AAB signed with SHA-256 using the existing upload key and signature verified.');
833
+ }
834
+
835
+ const amazonWindowExtensionsDependency = 'implementation "androidx.window.extensions.core:core:1.0.0"';
836
+ const amazonWindowExtensionsDependencyPattern = /^[ \t]*implementation\s+["']androidx\.window\.extensions\.core:core:[^"']+["'][ \t]*(?:\r?\n)?/gm;
837
+
838
+ function setAmazonWindowExtensionsDependency(enabled, { cleanup = false } = {}) {
839
+ const currentGradleContent = readFileSync(gradleFilePath, 'utf8');
840
+ let nextGradleContent = currentGradleContent.replace(amazonWindowExtensionsDependencyPattern, '');
841
+
842
+ if (enabled) {
843
+ const dependenciesBlock = findGradleBlock(nextGradleContent, /^\s*dependencies\s*/m);
844
+ if (!dependenciesBlock) {
845
+ throw new Error(`The dependencies block was not found in ${gradleFilePath}.`);
846
+ }
847
+
848
+ const newline = nextGradleContent.includes('\r\n') ? '\r\n' : '\n';
849
+ const contentBeforeClosingBrace = nextGradleContent.slice(0, dependenciesBlock.end);
850
+ const linePrefix = contentBeforeClosingBrace.endsWith('\n') ? '' : newline;
851
+ nextGradleContent = contentBeforeClosingBrace
852
+ + linePrefix
853
+ + ` ${amazonWindowExtensionsDependency}${newline}`
854
+ + nextGradleContent.slice(dependenciesBlock.end);
855
+ }
856
+
857
+ if (nextGradleContent !== currentGradleContent) {
858
+ writeFileSync(gradleFilePath, nextGradleContent, 'utf8');
859
+ }
860
+
861
+ console.log(enabled
862
+ ? '✅ Added Amazon Fire WebView compatibility dependency for Store ID 7.'
863
+ : cleanup
864
+ ? 'ℹ️ Removed temporary Amazon Fire WebView compatibility dependency after build cleanup.'
865
+ : 'ℹ️ Amazon Fire WebView compatibility dependency is not included for this build.');
866
+ }
867
+
868
+ const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
869
+ const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
870
+
871
+ const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
872
+ const versionName = versionNameMatch ? versionNameMatch[1] : '';
873
+
874
+ // Display the current versionCode and versionName
875
+ console.log(`Current versionCode: ${versionCode}`);
876
+ console.log(`Current versionName: ${versionName}`);
877
+
878
+ // Create an interface for user input
879
+ async function checkBaselineProfileBeforeRelease() {
880
+ const profilePaths = [
881
+ join(__dirname, 'baselineProfiles', 'baseline-prof.txt'),
882
+ join(__dirname, 'android', 'app', 'src', 'main', 'generated', 'baselineProfiles', 'baseline-prof.txt'),
883
+ join(__dirname, 'android', 'app', 'src', 'main', 'baseline-prof.txt'),
884
+ join(__dirname, 'android', 'app', 'src', 'main', 'baselineProfiles', 'baseline-prof.txt'),
885
+ ];
886
+ const hasProfile = () => profilePaths.some(profilePath =>
887
+ existsSync(profilePath) && readFileSync(profilePath, 'utf8').trim().length > 0);
888
+ if (hasProfile()) return;
889
+
890
+ console.log('⚠️ baseline-prof.txt is missing or empty.');
891
+ console.log('Generation command: npm run baseline-profile:generate');
892
+ console.log('Generation requires an ADB-connected Android device or a configured emulator.');
893
+ const answer = await new Promise(resolveAnswer => {
894
+ rl.question('Generate AAB/APK without a Baseline Profile? [Enter/Y = continue, n = generate profile first]: ', resolveAnswer);
895
+ });
896
+ if (answer.trim().toLowerCase() !== 'n') return;
897
+
898
+ rl.pause();
899
+ try {
900
+ execSync('npm run baseline-profile:generate', { cwd: __dirname, stdio: 'inherit' });
901
+ if (!hasProfile()) {
902
+ throw new Error('Baseline Profile generation did not produce a non-empty baseline-prof.txt; release stopped.');
903
+ }
904
+ // Reuse setup to back up and synchronise the generated profile before packaging.
905
+ execFileSync(process.execPath, [join(__dirname, 'scripts-common', 'setup-baseline-profile.js')], {
906
+ cwd: __dirname,
907
+ stdio: 'inherit',
908
+ });
909
+ } finally {
910
+ rl.resume();
911
+ }
912
+ }
913
+
914
+ const rl = createInterface({
915
+ input: process.stdin,
916
+ output: process.stdout
917
+ });
918
+
919
+ // Ask for new versionCode
920
+ rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
921
+ const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
922
+
923
+ // Ask for new versionName
924
+ rl.question('Enter new versionName (press enter to keep current): ', async (newVersionName) => {
925
+ const finalVersionName = newVersionName || versionName; // Use existing if no input
926
+
927
+ // Log the final version details
928
+ console.log(`📦 Final versionCode: ${finalVersionCode}`);
929
+ console.log(`📝 Final versionName: ${finalVersionName}`);
930
+
931
+
932
+ updateIOSVersion(finalVersionCode, finalVersionName);
933
+
934
+ // Update build.gradle with the new version details
935
+ let updatedGradleContent = gradleContent
936
+ .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
937
+ .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
938
+
939
+ // Check if resConfigs "en" already exists
940
+ const resConfigsLine = ' resConfigs "en"';
941
+ if (!updatedGradleContent.includes(resConfigsLine)) {
942
+ // Add resConfigs "en" below versionName
943
+ updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
944
+ } else {
945
+ console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
946
+ }
947
+
948
+
949
+
950
+ // List of package IDs for which minify should be false
951
+
952
+
953
+ // Determine desired minify value
954
+ const desiredMinify = !_isffmpegUsed;
955
+
956
+ // Limit minification changes to release; debug may have its own test settings.
957
+ const minificationBlock = findGradleBlock(updatedGradleContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
958
+ if (!minificationBlock) {
959
+ throw new Error('Release build configuration was not found.');
960
+ }
961
+ let minificationContent = updatedGradleContent.slice(minificationBlock.start, minificationBlock.end);
962
+ if (!/\bminifyEnabled\b/.test(minificationContent)) {
963
+ // Insert minifyEnabled if not present
964
+ minificationContent = `\n minifyEnabled ${desiredMinify}${minificationContent}`;
965
+ console.log(`✅ Inserted minifyEnabled ${desiredMinify} into release block.`);
966
+ }
967
+ updatedGradleContent = updatedGradleContent.slice(0, minificationBlock.start)
968
+ + minificationContent + updatedGradleContent.slice(minificationBlock.end);
969
+
970
+ // Add native debug symbols for release AABs, but leave any existing setting untouched.
971
+ const releaseBlock = findGradleBlock(updatedGradleContent, /buildTypes\s*\{[\s\S]*?\brelease\s*/);
972
+ if (releaseBlock) {
973
+ const releaseContent = updatedGradleContent.slice(releaseBlock.start, releaseBlock.end);
974
+ if (/\bdebugSymbolLevel\b/.test(releaseContent)) {
975
+ console.log('ℹ️ debugSymbolLevel already exists in buildTypes.release; leaving it unchanged.');
976
+ } else {
977
+ const ndkBlock = `\n ndk {\n debugSymbolLevel 'FULL'\n }`;
978
+ updatedGradleContent = updatedGradleContent.slice(0, releaseBlock.end)
979
+ + ndkBlock
980
+ + updatedGradleContent.slice(releaseBlock.end);
981
+ console.log("✅ Added debugSymbolLevel 'FULL' to buildTypes.release.");
982
+ }
983
+ } else {
984
+ console.log('⚠️ Warning: buildTypes.release block not found. debugSymbolLevel was not added.');
985
+ }
986
+
987
+
988
+
989
+
990
+
991
+
992
+ // Write the updated gradle content back to build.gradle
993
+ writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
994
+ console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en"; existing minification settings preserved.`);
995
+
996
+ let baselineProfileChecked = false;
997
+ for (const id of storeIds) {
998
+ console.log(`ℹ️ Building for Store ID ${id}`);
999
+
1000
+ // Set the environment variable for store ID
1001
+ process.env.VITE_STORE_ID = id;
1002
+
1003
+ // Conditionally set the new file name
1004
+ let newFileName;
1005
+ let storeName = storeNames[id];
1006
+ // Amazon previously received version code 10000 for this package.
1007
+ const storeVersionCode = _appPackageId === 'computer.shortcut.keys.app' && String(id) === '7'
1008
+ ? String(10000 + Number(finalVersionCode))
1009
+ : finalVersionCode;
1010
+
1011
+
1012
+ if (
1013
+ isOnlyOneAPK &&
1014
+ ["OppoStore", "VivoStore"].includes(storeName)
1015
+ ) {
1016
+ console.log(`⏭ Skipping ${storeName} because isOnlyOneAPK is enabled`);
1017
+ continue; // skip this iteration only
1018
+ }
1019
+
1020
+
1021
+ // build:storeid runs the shared before-build package/permission preparation.
1022
+
1023
+ // 🔥 Only change filename logic — nothing else touched
1024
+ if (isOnlyOneAPK && ["MiStore","OppoStore","VivoStore"].includes(storeName)) {
1025
+
1026
+ newFileName =
1027
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-VI_MI_OPPO-b${storeVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
1028
+
1029
+ }
1030
+ else if (storeName === "SamsungStore") {
1031
+
1032
+ newFileName =
1033
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${storeVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`;
1034
+
1035
+ }
1036
+ else {
1037
+
1038
+ newFileName =
1039
+ `${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${storeVersionCode}-v${finalVersionName}.aab`;
1040
+
1041
+ }
1042
+
1043
+ //storeName="amazon"
1044
+ const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
1045
+
1046
+ // Modify minSdkVersion in variables.gradle for SamsungStore
1047
+ const variablesGradleFilePath = join("android", "variables.gradle");
1048
+ let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
1049
+
1050
+ // Extract the current minSdkVersion
1051
+ const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
1052
+ const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
1053
+
1054
+ // Store the original minSdkVersion (only on the first iteration)
1055
+ if (!originalMinSdkVersion) {
1056
+ originalMinSdkVersion = currentMinSdkVersion;
1057
+ }
1058
+ try {
1059
+ applyFlowchartStoreApi(id);
1060
+ const shouldIncludeAmazonWindowExtensions = String(id) === '7' && amazon === true;
1061
+ setAmazonWindowExtensionsDependency(shouldIncludeAmazonWindowExtensions);
1062
+ // Modify the minSdkVersion based on the store
1063
+
1064
+
1065
+ if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
1066
+ {
1067
+ if (storeName === "SamsungStore" || storeName === "PlayStore" ||
1068
+ //_appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker"
1069
+
1070
+ //ffmpegUsedPackages.includes(_appPackageId)
1071
+ _isffmpegUsed
1072
+ ) {
1073
+ if (currentMinSdkVersion !== 24) {
1074
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
1075
+ console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
1076
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
1077
+ }
1078
+ } else {
1079
+ // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
1080
+ //if (currentMinSdkVersion !== originalMinSdkVersion) {
1081
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
1082
+ console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
1083
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
1084
+ //}
1085
+ }
1086
+ }
1087
+
1088
+
1089
+ // Run the Node.js script to modify plugin.xml
1090
+ if (isAdmobFound) {
1091
+ const modifyPluginXmlPath = join('buildCodeplay', 'modify-plugin-xml.js');
1092
+ if (existsSync(modifyPluginXmlPath)) {
1093
+ execSync(`node ${modifyPluginXmlPath}`, { stdio: 'inherit' });
1094
+ } else {
1095
+ console.log("\x1b[33m%s\x1b[0m", "⚠️ modify-plugin-xml.js not found. Skipping old AdMob plugin.xml modification.");
1096
+ }
1097
+ } else {
1098
+ console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
1099
+ }
1100
+
1101
+ // Run the Vite build
1102
+ execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
1103
+
1104
+
1105
+
1106
+
1107
+
1108
+
1109
+ // Copy the built files to the appropriate folder
1110
+ const src = join("www");
1111
+ const dest = join("android", "app", "src", "main", "assets", "public");
1112
+
1113
+ // Copy the web build with Node so releases work on every platform.
1114
+ fs.cpSync(src, dest, { recursive: true, force: true });
1115
+
1116
+ // Build Android AAB file
1117
+ //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
1118
+
1119
+
1120
+ // Build Android AAB or APK file based on store
1121
+ console.log(`🏗️ Building release for ${storeName}...`);
1122
+
1123
+ /* let buildType = "AAB";
1124
+ if (["VivoStore", "OppoStore", "MiStore"].includes(storeName)) {
1125
+ buildType = "APK";
1126
+ } */
1127
+
1128
+
1129
+ // Determine build type and signing type per store
1130
+ let buildType = ["VivoStore","OppoStore","MiStore"].includes(storeName) ? "APK" : "AAB";
1131
+ let signingType = buildType === "APK" ? "apksigner" : "jarsigner";
1132
+
1133
+ // Update capacitor.config.json for this store - This is not needed
1134
+ //updateCapacitorConfig(buildType, signingType);
1135
+
1136
+
1137
+
1138
+ /* execSync('npx cap sync android', { stdio: 'inherit' });
1139
+ execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' }); */
1140
+
1141
+
1142
+ execSync('npx cap sync android', { stdio: 'inherit' });
1143
+
1144
+ if (!baselineProfileChecked) {
1145
+ await checkBaselineProfileBeforeRelease();
1146
+ baselineProfileChecked = true;
1147
+ }
1148
+ ensureReleaseCodeOptimization();
1149
+
1150
+ const releaseBuildEnv = { ...process.env };
1151
+ if (_appPackageId === 'resume.generator.cv') {
1152
+ releaseBuildEnv.GRADLE_OPTS = [
1153
+ process.env.GRADLE_OPTS,
1154
+ '-Dorg.gradle.jvmargs="-Xmx4g -XX:MaxMetaspaceSize=1g"',
1155
+ '-Dorg.gradle.workers.max=2',
1156
+ ].filter(Boolean).join(' ');
1157
+ }
1158
+
1159
+ const hasStoreVersionOverride = String(storeVersionCode) !== String(finalVersionCode);
1160
+ try {
1161
+ if (hasStoreVersionOverride) {
1162
+ const storeGradleContent = readFileSync(gradleFilePath, 'utf8');
1163
+ writeFileSync(gradleFilePath, storeGradleContent.replace(/versionCode\s+\d+/, `versionCode ${storeVersionCode}`), 'utf8');
1164
+ console.log(`📦 ${storeName} versionCode: ${storeVersionCode} (base: ${finalVersionCode})`);
1165
+ }
1166
+ if (buildType === "APK") {
1167
+ console.log("📦 Using custom Node signing script for APK build...");
1168
+ execFileSync(process.execPath, [join(process.cwd(), 'buildCodeplay', 'apk-store-builder.js')], { stdio: 'inherit', env: releaseBuildEnv });
1169
+ } else {
1170
+ execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit', env: releaseBuildEnv });
1171
+ signReleaseBundleWithSha256();
1172
+ }
1173
+ } finally {
1174
+ if (hasStoreVersionOverride) {
1175
+ const storeGradleContent = readFileSync(gradleFilePath, 'utf8');
1176
+ writeFileSync(gradleFilePath, storeGradleContent.replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`), 'utf8');
1177
+ }
1178
+ }
1179
+
1180
+
1181
+
1182
+ // Determine output paths
1183
+ let oldFilePath;
1184
+ let newExt = buildType === "APK" ? "apk" : "aab";
1185
+
1186
+ if (buildType === "APK") {
1187
+ //oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release-signed.apk");
1188
+ oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release.apk");
1189
+ } else {
1190
+ oldFilePath = join("android", "app", "build", "outputs", "bundle", "release", "app-release-signed.aab");
1191
+ }
1192
+
1193
+ const checkFullPath = join("AAB", newFileName.replace(/\.aab$/, `.${newExt}`));
1194
+
1195
+ // Rename the output file
1196
+ if (existsSync(oldFilePath)) {
1197
+ renameSync(oldFilePath, checkFullPath);
1198
+ console.log(`✅ Renamed output ${newExt.toUpperCase()} file to: ${path.basename(checkFullPath)}`);
1199
+ syncReleaseToCodeplay(storeName, finalVersionName, storeVersionCode, new Date().toISOString().slice(0, 10));
1200
+ } else {
1201
+ console.error(`❌ ${newExt.toUpperCase()} file not found after build.`);
1202
+ }
1203
+
1204
+ } catch (error) {
1205
+ console.error(`❌ Error during build for Store ID ${id}:`, error);
1206
+ restoreFlowchartStoreApi();
1207
+ setAmazonWindowExtensionsDependency(false, {
1208
+ cleanup: String(id) === '7' && amazon === true,
1209
+ });
1210
+ process.exit(1);
1211
+ } finally {
1212
+ restoreFlowchartStoreApi();
1213
+ setAmazonWindowExtensionsDependency(false, {
1214
+ cleanup: String(id) === '7' && amazon === true,
1215
+ });
1216
+ }
1217
+ }
1218
+
1219
+ rl.close(); // Close the readline interface after all operations
1220
+ });
1221
+ });
1222
+
1223
+
1224
+
1225
+
1226
+
1227
+ /* function updateAndroidManifest1(store, addPermission) {
1228
+ try {
1229
+ if (!fs.existsSync(androidManifestPath)) {
1230
+ console.error("AndroidManifest.xml file not found!");
1231
+ return;
1232
+ }
1233
+
1234
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
1235
+
1236
+
1237
+
1238
+ // Add the required permission if not already present
1239
+ if (!manifestContent.includes(addPermission)) {
1240
+ const manifestLines = manifestContent.split('\n');
1241
+ const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
1242
+ if (insertIndex > -1) {
1243
+ manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
1244
+ manifestContent = manifestLines.join('\n');
1245
+ console.log(`Added ${addPermission} to AndroidManifest.xml`);
1246
+ }
1247
+ }
1248
+
1249
+ // Write the updated content back to the file
1250
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
1251
+ console.log(`AndroidManifest.xml updated successfully for ${store}`);
1252
+ } catch (err) {
1253
+ console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
1254
+ }
1255
+ } */
1256
+
1257
+
1258
+
1259
+
1260
+
1261
+
1262
+
1263
+