codeplay-common 3.1.2 → 3.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2030 +1,2031 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const plist = require('plist');
4
-
5
-
6
-
7
- const { execSync } = require("child_process");
8
-
9
-
10
-
11
-
12
- const { readFileSync } = require("fs");
13
-
14
- const ENABLE_AUTO_UPDATE = true;
15
- const USE_LIVE_SERVER_VERSION = true;
16
-
17
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
18
- const updateLogFile = path.join(process.cwd(), "", "plugin-update-log.txt");
19
-
20
- // Expected plugin list with minimum versions
21
- /* const requiredPlugins = [
22
-
23
- { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '2.0', required: true, baseDir: 'js',mandatoryUpdate: true},
24
-
25
-
26
- { pattern: /common-(\d+\.\d+)(?:-beta-(\d+))?\.js$/, minVersion: '6.0', required: true, baseDir: 'js',mandatoryUpdate: true },
27
-
28
- { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
29
- { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: true },
30
- { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js',mandatoryUpdate: false },
31
- { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true, baseDir: 'js',mandatoryUpdate: false },
32
- { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.3', required: true, baseDir: 'js',mandatoryUpdate: false },
33
- { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.1', required: true, baseDir: 'js',mandatoryUpdate: true },
34
- { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.7', required: true, baseDir: 'js',mandatoryUpdate: true },
35
-
36
- // New added plugins
37
- { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: false },
38
- { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
39
- { pattern: /common-(\d+\.\d+)\.less$/, minVersion: '1.6', required: true, baseDir: 'assets/css',mandatoryUpdate: false },
40
-
41
-
42
- // New folders
43
- { pattern: /IAP-(\d+\.\d+)$/, minVersion: '2.8', isFolder: true , required: true, baseDir: 'js/Ads',mandatoryUpdate: true },
44
- { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.9', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
45
- { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
46
- { pattern: /theme-(\d+\.\d+)$/, minVersion: '3.3', isFolder: true , required: true, baseDir: 'theme',mandatoryUpdate: true },
47
-
48
-
49
- { pattern: /certificatejs-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true , required: true, baseDir: 'certificate',mandatoryUpdate: true }
50
-
51
- ]; */
52
-
53
-
54
- function requireOrInstall(packageName) {
55
- try {
56
- return require(packageName);
57
- } catch (err) {
58
-
59
- console.log(`šŸ“¦ "${packageName}" not found. Installing automatically...`);
60
-
61
- try {
62
- execSync(`npm install ${packageName}`, { stdio: "inherit" });
63
- console.log(`āœ… "${packageName}" installed successfully.`);
64
- } catch (installErr) {
65
- console.error(`āŒ Failed to install "${packageName}".`);
66
- process.exit(1);
67
- }
68
-
69
- // Try loading again
70
- return require(packageName);
71
- }
72
- }
73
-
74
- const AdmZip = requireOrInstall("adm-zip");
75
-
76
-
77
-
78
- const pkg = require(path.join(process.cwd(), 'node_modules', 'codeplay-common', 'package.json'));
79
-
80
- const pluginName = pkg.name;
81
- const pluginVersion = pkg.version;
82
-
83
- let updateLogs = [];
84
-
85
- function writeUpdateLine(message) {
86
- updateLogs.push(message);
87
- }
88
-
89
- const MAX_LOG_BLOCKS = 50;
90
-
91
- function saveUpdateLogs() {
92
-
93
- if (updateLogs.length === 0) return;
94
-
95
- const logDir = path.dirname(updateLogFile);
96
-
97
- if (!fs.existsSync(logDir)) {
98
- fs.mkdirSync(logDir, { recursive: true });
99
- }
100
-
101
- const now = new Date();
102
-
103
- const formattedTime = now.toLocaleString('en-GB', {
104
- day: '2-digit',
105
- month: '2-digit',
106
- year: 'numeric',
107
- hour: '2-digit',
108
- minute: '2-digit',
109
- hour12: true
110
- }).replace(',', '').replace(/\//g, '-');
111
-
112
- let newBlock = `${pluginName}: ${pluginVersion}\n[${formattedTime}]\n`;
113
-
114
- updateLogs.forEach(line => {
115
- newBlock += `${line}\n`;
116
- });
117
-
118
- newBlock += "\n";
119
-
120
- let existingLog = "";
121
-
122
- if (fs.existsSync(updateLogFile)) {
123
- existingLog = fs.readFileSync(updateLogFile, "utf8");
124
- }
125
-
126
- let combinedLog = newBlock + existingLog;
127
-
128
- // Split blocks by plugin header
129
- const blocks = combinedLog.split(/\n(?=codeplay-common:)/);
130
-
131
- // Keep only latest 50
132
- const trimmed = blocks.slice(0, MAX_LOG_BLOCKS).join("\n");
133
-
134
- fs.writeFileSync(updateLogFile, trimmed);
135
-
136
- }
137
-
138
-
139
-
140
-
141
-
142
- const versionsFile = path.join(__dirname, "versions.json");
143
-
144
- function loadRequiredPlugins() {
145
-
146
- if (!fs.existsSync(versionsFile)) {
147
- console.error("āŒ versions.json not found");
148
- process.exit(1);
149
- }
150
-
151
- const json = JSON.parse(fs.readFileSync(versionsFile, "utf8"));
152
-
153
- return json.plugins.map(p => ({
154
- ...p,
155
- pattern: new RegExp(p.pattern)
156
- }));
157
-
158
- }
159
-
160
- let requiredPlugins = loadRequiredPlugins();
161
-
162
-
163
-
164
-
165
-
166
-
167
- async function downloadAndExtractZip(url, destFolder) {
168
-
169
- const zipPath = destFolder + ".zip";
170
-
171
- await downloadFile(url, zipPath);
172
-
173
- const zip = new AdmZip(zipPath);
174
- zip.extractAllTo(destFolder, true);
175
-
176
- fs.unlinkSync(zipPath);
177
-
178
- }
179
-
180
-
181
-
182
-
183
-
184
-
185
-
186
- //Check codeplay-common latest version installed or not Start
187
- //const { execSync } = require('child_process');
188
-
189
-
190
- function getInstalledVersion(packageName) {
191
- try {
192
- const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
193
- if (fs.existsSync(packageJsonPath)) {
194
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
195
- return packageJson.version;
196
- }
197
- } catch (error) {
198
- return null;
199
- }
200
- return null;
201
- }
202
-
203
- function getLatestVersion(packageName) {
204
- try {
205
- return execSync(`npm view ${packageName} version`).toString().trim();
206
- } catch (error) {
207
- console.error(`Failed to fetch latest version for ${packageName}`);
208
- return null;
209
- }
210
- }
211
-
212
- function checkPackageVersion() {
213
- const packageName = 'codeplay-common';
214
- const installedVersion = getInstalledVersion(packageName);
215
- const latestVersion = getLatestVersion(packageName);
216
-
217
- if (!installedVersion) {
218
- console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
219
- process.exit(1);
220
- }
221
-
222
- if (installedVersion !== latestVersion) {
223
- console.error(`\x1b[31m${packageName} is outdated (installed: ${installedVersion}, latest: ${latestVersion}). Please update it.\x1b[0m\n\x1b[33mUse 'npm uninstall codeplay-common ; npm i codeplay-common'\x1b[0m`);
224
- process.exit(1);
225
- }
226
-
227
- console.log(`${packageName} is up to date (version ${installedVersion}).`);
228
- }
229
-
230
- // Run package version check before executing the main script
231
- try {
232
- checkPackageVersion();
233
- } catch (error) {
234
- console.error(error.message);
235
- process.exit(1);
236
- }
237
-
238
- //Check codeplay-common latest version installed or not END
239
-
240
-
241
-
242
- function compareWithBeta(installedVersion, minVersion, isBeta) {
243
- const baseCompare = compareVersions(installedVersion, minVersion);
244
-
245
- if (!isBeta) {
246
- // Stable version → normal compare
247
- return baseCompare;
248
- }
249
-
250
- // Beta version logic
251
- if (baseCompare > 0) return 1; // 5.3-beta > 5.2
252
- if (baseCompare < 0) return -1; // 5.1-beta < 5.2
253
-
254
- // Same version but beta → LOWER than stable
255
- return -1; // 5.2-beta < 5.2
256
- }
257
-
258
-
259
-
260
-
261
- const checkAppUniqueId=()=>{
262
-
263
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
264
-
265
- const appUniqueId = config.android?.APP_UNIQUE_ID;
266
- const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
267
- const orientation = config.android?.ORIENTATION;
268
-
269
-
270
- let logErrorMessage="";
271
-
272
- // 1ļøāƒ£ Check if it’s missing
273
- if (RESIZEABLE_ACTIVITY === undefined) {
274
- logErrorMessage+='āŒ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
275
- }
276
-
277
- // 2ļøāƒ£ Check if it’s not boolean (true/false only)
278
- else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
279
- logErrorMessage+='āŒ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
280
- }
281
-
282
-
283
-
284
- if (!orientation) {
285
- logErrorMessage+='āŒ Missing android.ORIENTATION option in capacitor.config.json.\n';
286
- }
287
-
288
- else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
289
- {
290
- logErrorMessage+='āŒ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
291
- }
292
-
293
-
294
- if (!appUniqueId) {
295
- logErrorMessage+='āŒ APP_UNIQUE_ID is missing in capacitor.config.json.';
296
- }
297
-
298
- else if (!Number.isInteger(appUniqueId)) {
299
- logErrorMessage+='āŒ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
300
- }
301
-
302
-
303
-
304
- if(logErrorMessage!="")
305
- {
306
- console.error(logErrorMessage);
307
- process.exit(1)
308
- }
309
-
310
-
311
- console.log(`āœ… APP_UNIQUE_ID is valid: ${appUniqueId}`);
312
-
313
- }
314
-
315
- checkAppUniqueId();
316
-
317
-
318
-
319
-
320
-
321
-
322
-
323
- //@Codemirror check and install/uninstall the packages START
324
- //const fs = require("fs");
325
- //const path = require("path");
326
- //const { execSync } = require("child_process");
327
-
328
- const baseDir = path.join(__dirname, "..", "src", "js");
329
-
330
- // Step 1: Find highest versioned folder like `editor-1.6`
331
- const editorDirs = fs.readdirSync(baseDir)
332
- .filter(name => /^editor-\d+\.\d+$/.test(name))
333
- .sort((a, b) => {
334
- const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
335
- const [aMajor, aMinor] = getVersion(a);
336
- const [bMajor, bMinor] = getVersion(b);
337
- return bMajor - aMajor || bMinor - aMinor;
338
- });
339
-
340
- if (editorDirs.length === 0) {
341
-
342
- console.log("@Codemirror used editor(s) are not found")
343
- //console.error("āŒ No editor-x.x folders found in src/js.");
344
- //process.exit(1);
345
- }
346
- else
347
- {
348
-
349
- const latestEditorDir = editorDirs.sort((a, b) => {
350
- const versionA = parseFloat(a.split('-')[1]);
351
- const versionB = parseFloat(b.split('-')[1]);
352
- return versionB - versionA;
353
- })[0];
354
-
355
- //const latestEditorDir = editorDirs[editorDirs.length - 1];
356
- const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
357
-
358
- if (!fs.existsSync(runJsPath)) {
359
- console.error(`āŒ run.js not found in ${latestEditorDir}`);
360
- process.exit(1);
361
- }
362
-
363
- // Step 2: Execute the run.js file
364
- console.log(`šŸš€ Executing ${runJsPath}...`);
365
- execSync(`node "${runJsPath}"`, { stdio: "inherit" });
366
- }
367
-
368
- //@Codemirror check and install/uninstall the packages END
369
-
370
-
371
-
372
-
373
-
374
-
375
-
376
-
377
-
378
-
379
-
380
-
381
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
382
-
383
- const os = require('os');
384
-
385
- const saveToGalleryAndSaveFileCheck_iOS = () => {
386
-
387
- // List of paths to scan
388
- const SCAN_PATHS = [
389
- path.resolve(__dirname, '../src/certificate'),
390
- path.resolve(__dirname, '../src/pages'),
391
- path.resolve(__dirname, '../src/js'),
392
- path.resolve(__dirname, '../src/app.f7')
393
- ];
394
-
395
- // Directory to exclude
396
- const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
397
-
398
- const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
399
-
400
-
401
- // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
402
- const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
403
-
404
- // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
405
- const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
406
-
407
-
408
-
409
-
410
-
411
- const ALLOWED_EXTENSIONS = ['.js', '.f7'];
412
- const isMac = os.platform() === 'darwin';
413
-
414
- let iosImportFound = false;
415
- let androidImportFound = false;
416
-
417
- // Files to skip completely (full or partial match)
418
- const SKIP_FILES = [
419
- 'pdf-3.11.174.min.js',
420
- 'pdf.worker-3.11.174.min.js'
421
- ,'index.browser.js'
422
- ];
423
-
424
-
425
- function scanDirectory(dir) {
426
-
427
- /*
428
- //######################### DO NOT DELETE THIS - START [Appid base validation] #####################################
429
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
430
- const appUniqueId = config.android?.APP_UNIQUE_ID;
431
- if (appUniqueId == "206") return;
432
- //######################### DO NOT DELETE THIS - END [Appid base validation] #####################################
433
- */
434
-
435
- const stat = fs.statSync(dir);
436
-
437
- if (stat.isFile()) {
438
-
439
- // šŸ”„ Skip files in SKIP_FILES array
440
- const baseName = path.basename(dir);
441
- if (SKIP_FILES.includes(baseName)) {
442
- // Just skip silently
443
- return;
444
- }
445
-
446
- // Only scan allowed file extensions
447
- if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
448
- process.stdout.write(`\ršŸ” Scanning: ${dir} `);
449
-
450
- const content = fs.readFileSync(dir, 'utf8');
451
-
452
- if (IOS_FILE_REGEX.test(content)) {
453
- iosImportFound = true;
454
- if (!isMac) {
455
- console.error(`\nāŒ ERROR: iOS-specific import detected in: ${dir}`);
456
- console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
457
- process.exit(1);
458
- }
459
- }
460
- else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
461
- androidImportFound = true;
462
- }
463
- }
464
- }
465
- else if (stat.isDirectory()) {
466
- if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
467
-
468
- const entries = fs.readdirSync(dir, { withFileTypes: true });
469
- for (let entry of entries) {
470
- scanDirectory(path.join(dir, entry.name));
471
- }
472
- }
473
- }
474
-
475
-
476
- // Run scan on all specified paths
477
- for (let scanPath of SCAN_PATHS) {
478
- if (fs.existsSync(scanPath)) {
479
- scanDirectory(scanPath);
480
- }
481
- }
482
-
483
-
484
-
485
- /* // Check src folder
486
- if (!fs.existsSync(ROOT_DIR)) {
487
- console.warn(`āš ļø Warning: 'src' directory not found at: ${ROOT_DIR}`);
488
- return;
489
- } */
490
-
491
- //scanDirectory(ROOT_DIR);
492
-
493
- // iOS Checks
494
- if (isMac && !iosImportFound) {
495
- console.warn(`āš ļø WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
496
- process.exit(1);
497
- } else if (isMac && iosImportFound) {
498
- console.log('āœ… iOS version detected for macOS build.');
499
- } else if (!iosImportFound) {
500
- console.log('āœ… No iOS-specific imports detected for non-macOS.');
501
- }
502
-
503
- // Android Checks
504
- if (androidImportFound) {
505
- console.log("šŸ“± Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
506
-
507
- if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
508
- console.error("āŒ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
509
- return;
510
- }
511
-
512
- let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
513
-
514
- if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
515
- console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
516
-
517
- manifestContent = manifestContent.replace(
518
- /<application([^>]*)>/,
519
- (match, attrs) => {
520
- if (attrs.includes('android:requestLegacyExternalStorage')) return match;
521
- return `<application${attrs} android:requestLegacyExternalStorage="true">`;
522
- }
523
- );
524
-
525
- fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
526
- console.log("āœ… android:requestLegacyExternalStorage=\"true\" added successfully.");
527
- } else {
528
- console.log("ā„¹ļø android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
529
- }
530
- } else {
531
- console.log("āœ… No Android saveToGalleryAndSaveAnyFile imports detected.");
532
- }
533
- };
534
-
535
- saveToGalleryAndSaveFileCheck_iOS();
536
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
537
-
538
-
539
-
540
-
541
-
542
-
543
-
544
-
545
-
546
-
547
-
548
-
549
-
550
- /*
551
- // Clean up AppleDouble files (._*) created by macOS START
552
- if (process.platform === 'darwin') {
553
- try {
554
- console.log('🧹 Cleaning up AppleDouble files (._*)...');
555
- execSync(`find . -name '._*' -delete`);
556
- console.log('āœ… AppleDouble files removed.');
557
- } catch (err) {
558
- console.warn('āš ļø Failed to remove AppleDouble files:', err.message);
559
- }
560
- } else {
561
- console.log('ā„¹ļø Skipping AppleDouble cleanup — not a macOS machine.');
562
- }
563
-
564
- // Clean up AppleDouble files (._*) created by macOS END
565
- */
566
-
567
-
568
-
569
-
570
-
571
-
572
- //In routes.js file check static import START
573
-
574
- const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
575
- const routesContent = fs.readFileSync(routesPath, 'utf-8');
576
-
577
- let inBlockComment = false;
578
- const lines = routesContent.split('\n');
579
-
580
- const allowedImport = `import HomePage from '../pages/home.f7';`;
581
- const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
582
- const badImports = [];
583
-
584
- lines.forEach((line, index) => {
585
- const trimmed = line.trim();
586
-
587
- // Handle block comment start and end
588
- if (trimmed.startsWith('/*')) inBlockComment = true;
589
- if (inBlockComment && trimmed.endsWith('*/')) {
590
- inBlockComment = false;
591
- return;
592
- }
593
-
594
- // Skip if inside block comment or line comment
595
- if (inBlockComment || trimmed.startsWith('//')) return;
596
-
597
- // Match static .f7 import
598
- if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
599
- badImports.push({ line: trimmed, number: index + 1 });
600
- }
601
- });
602
-
603
- if (badImports.length > 0) {
604
- console.error('\nāŒ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
605
- console.error(`āš ļø Only this static import is allowed:\n ${allowedImport}\n`);
606
- console.error(`šŸ”§ Please convert other imports to async dynamic imports like this:\n`);
607
- console.error(`
608
-
609
- import HomePage from '../pages/home.f7';
610
-
611
- const routes = [
612
- {
613
- path: '/',
614
- component:HomePage,
615
- },
616
- {
617
- path: '/ProfilePage/',
618
- async async({ resolve }) {
619
- const page = await import('../pages/profile.f7');
620
- resolve({ component: page.default });
621
- },
622
- }]
623
- `);
624
-
625
- badImports.forEach(({ line, number }) => {
626
- console.error(`${number}: ${line}`);
627
- });
628
-
629
- process.exit(1);
630
- } else {
631
- console.log('āœ… routes.js passed the .f7 import check.');
632
- }
633
-
634
- //In routes.js file check static import END
635
-
636
-
637
-
638
-
639
-
640
-
641
-
642
-
643
-
644
-
645
-
646
-
647
-
648
- // Check and change the "BridgeWebViewClient.java" file START
649
- /*
650
- For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
651
- */
652
-
653
-
654
- const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
655
-
656
- // Read the file
657
- if (!fs.existsSync(bridgeWebViewClientFilePath)) {
658
- console.error('āŒ Error: BridgeWebViewClient.java not found.');
659
- process.exit(1);
660
- }
661
-
662
- let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
663
-
664
- // Define old and new code
665
- const oldCodeStart = `@Override
666
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
667
- super.onRenderProcessGone(view, detail);
668
- boolean result = false;
669
-
670
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
671
- if (webViewListeners != null) {
672
- for (WebViewListener listener : bridge.getWebViewListeners()) {
673
- result = listener.onRenderProcessGone(view, detail) || result;
674
- }
675
- }
676
-
677
- return result;
678
- }`;
679
-
680
- const newCode = `@Override
681
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
682
- super.onRenderProcessGone(view, detail);
683
-
684
- boolean result = false;
685
-
686
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
687
- if (webViewListeners != null) {
688
- for (WebViewListener listener : bridge.getWebViewListeners()) {
689
- result = listener.onRenderProcessGone(view, detail) || result;
690
- }
691
- }
692
-
693
- if (!result) {
694
- // If no one handled it, handle it ourselves!
695
-
696
- /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
697
- if (detail.didCrash()) {
698
- //Log.e("CapacitorWebView", "WebView crashed internally!");
699
- } else {
700
- //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
701
- }
702
- }*/
703
-
704
- view.post(() -> {
705
- Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
706
- });
707
-
708
- view.reload(); // Safely reload WebView
709
-
710
- return true; // We handled it
711
- }
712
-
713
- return result;
714
- }`;
715
-
716
- // Step 1: Update method if needed
717
- let updated = false;
718
-
719
- if (fileContent.includes(oldCodeStart)) {
720
- console.log('āœ… Found old onRenderProcessGone method. Replacing it...');
721
- fileContent = fileContent.replace(oldCodeStart, newCode);
722
- updated = true;
723
- } else if (fileContent.includes(newCode)) {
724
- console.log('ā„¹ļø Method already updated. No changes needed in "BridgeWebViewClient.java".');
725
- } else {
726
- console.error('āŒ Error: Neither old nor new code found. Unexpected content.');
727
- process.exit(1);
728
- }
729
-
730
- // Step 2: Check and add import if missing
731
- const importToast = 'import android.widget.Toast;';
732
- if (!fileContent.includes(importToast)) {
733
- console.log('āœ… Adding missing import for Toast...');
734
- const importRegex = /import\s+[^;]+;/g;
735
- const matches = [...fileContent.matchAll(importRegex)];
736
-
737
- if (matches.length > 0) {
738
- const lastImport = matches[matches.length - 1];
739
- const insertPosition = lastImport.index + lastImport[0].length;
740
- fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
741
- updated = true;
742
- } else {
743
- console.error('āŒ Error: No import section found in file.');
744
- process.exit(1);
745
- }
746
- } else {
747
- console.log('ā„¹ļø Import for Toast already exists. No changes needed.');
748
- }
749
-
750
- // Step 3: Save if updated
751
- if (updated) {
752
- fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
753
- console.log('āœ… File updated successfully.');
754
- } else {
755
- console.log('ā„¹ļø No changes needed.');
756
- }
757
-
758
-
759
-
760
-
761
- // Check and change the "BridgeWebViewClient.java" file END
762
-
763
-
764
-
765
-
766
-
767
-
768
-
769
-
770
- /*
771
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
772
-
773
- // Build the path dynamically like you requested
774
- const gradlePath = path.join(
775
- process.cwd(),
776
- 'android',
777
- 'build.gradle'
778
- );
779
-
780
- // Read the existing build.gradle
781
- let gradleContent = fs.readFileSync(gradlePath, 'utf8');
782
-
783
- // Add `ext.kotlin_version` if it's not already there
784
- if (!gradleContent.includes('ext.kotlin_version')) {
785
- gradleContent = gradleContent.replace(
786
- /buildscript\s*{/,
787
- `buildscript {\n ext.kotlin_version = '2.1.0'`
788
- );
789
- }
790
-
791
- // Add Kotlin classpath if it's not already there
792
- if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
793
- gradleContent = gradleContent.replace(
794
- /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
795
- `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
796
- );
797
- }
798
-
799
- // Write back the modified content
800
- fs.writeFileSync(gradlePath, gradleContent, 'utf8');
801
-
802
- console.log('āœ… Kotlin version updated in build.gradle.');
803
-
804
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
805
- */
806
-
807
-
808
-
809
-
810
-
811
-
812
-
813
-
814
- let _admobConfig;
815
-
816
-
817
-
818
- const androidPlatformPath = path.join(process.cwd(), 'android');
819
- const iosPlatformPath = path.join(process.cwd(), 'ios');
820
- const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
821
- const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
822
- const resourcesPath = path.join(process.cwd(), 'resources', 'res');
823
- const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
824
- const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
825
-
826
- function fileExists(filePath) {
827
- return fs.existsSync(filePath);
828
- }
829
-
830
- function copyFolderSync(source, target) {
831
- if (!fs.existsSync(target)) {
832
- fs.mkdirSync(target, { recursive: true });
833
- }
834
-
835
- fs.readdirSync(source).forEach(file => {
836
- const sourceFile = path.join(source, file);
837
- const targetFile = path.join(target, file);
838
-
839
- if (fs.lstatSync(sourceFile).isDirectory()) {
840
- copyFolderSync(sourceFile, targetFile);
841
- } else {
842
- fs.copyFileSync(sourceFile, targetFile);
843
- }
844
- });
845
- }
846
-
847
- function checkAndCopyResources() {
848
- if (fileExists(resourcesPath)) {
849
- copyFolderSync(resourcesPath, androidResPath);
850
- console.log('āœ… Successfully copied resources/res to android/app/src/main/res.');
851
- } else {
852
- console.log('resources/res folder not found.');
853
-
854
- if (fileExists(localNotificationsPluginPath)) {
855
- throw new Error('āŒ resources/res is required for @capacitor/local-notifications. Stopping execution.');
856
- }
857
- }
858
- }
859
-
860
-
861
-
862
-
863
-
864
-
865
-
866
-
867
- function getAdMobConfig() {
868
- if (!fileExists(configPath)) {
869
- throw new Error('āŒ capacitor.config.json not found. Ensure this is a Capacitor project.');
870
- }
871
-
872
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
873
- const admobConfig = config.plugins?.AdMob;
874
-
875
- if (!admobConfig) {
876
- throw new Error('āŒ AdMob configuration is missing in capacitor.config.json.');
877
- }
878
-
879
- // Default to true if ADMOB_ENABLED is not specified
880
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
881
-
882
- if (!isEnabled) {
883
- return { ADMOB_ENABLED: false }; // Skip further validation
884
- }
885
-
886
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
887
- throw new Error(' āŒ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
888
- }
889
-
890
- return {
891
- ADMOB_ENABLED: true,
892
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
893
- APP_ID_IOS: admobConfig.APP_ID_IOS,
894
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
895
- };
896
- }
897
-
898
- function validateAndroidBuildOptions() {
899
-
900
-
901
- if (!fileExists(configPath)) {
902
- console.log('āŒ capacitor.config.json not found. Ensure this is a Capacitor project.');
903
- process.exit(1);
904
- }
905
-
906
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
907
-
908
- const targetAppId=config.appId
909
-
910
- const buildOptions = config.android?.buildOptions;
911
-
912
- if (!buildOptions) {
913
- console.log('āŒ Missing android.buildOptions in capacitor.config.json.');
914
- process.exit(1);
915
- }
916
-
917
- const requiredProps = [
918
- 'keystorePath',
919
- 'keystorePassword',
920
- 'keystoreAlias',
921
- 'keystoreAliasPassword',
922
- 'releaseType',
923
- 'signingType'
924
- ];
925
-
926
- const missing = requiredProps.filter(prop => !buildOptions[prop]);
927
-
928
- if (missing.length > 0) {
929
- console.log('āŒ Missing properties android.buildOptions in capacitor.config.json.');
930
- process.exit(1);
931
- }
932
-
933
-
934
- const keystorePath=buildOptions.keystorePath
935
- const keyFileName = path.basename(keystorePath);
936
-
937
-
938
-
939
- const keystoreMap = {
940
- "gameskey.jks": [
941
- "com.cube.blaster",
942
- ],
943
- "htmleditorkeystoke.jks": [
944
- "com.HTML.AngularJS.Codeplay",
945
- "com.html.codeplay.pro",
946
- "com.bootstrap.code.play",
947
- "com.kids.learning.master",
948
- "com.Simple.Barcode.Scanner"
949
- ]
950
- };
951
-
952
- // find which keystore is required for the given targetAppId
953
- let requiredKey = "newappskey.jks"; // default
954
- for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
955
- if (appIds.includes(targetAppId)) {
956
- requiredKey = keyFile;
957
- break;
958
- }
959
- }
960
-
961
- // validate
962
- if (keyFileName !== requiredKey) {
963
- console.log(`āŒ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
964
- process.exit(1);
965
- }
966
-
967
-
968
-
969
-
970
-
971
- // optionally return them
972
- //return buildOptions;
973
- }
974
-
975
- function updatePluginXml(admobConfig) {
976
- if (!fileExists(pluginPath)) {
977
- console.error(' āŒ plugin.xml not found. Ensure the plugin is installed.');
978
- return;
979
- }
980
-
981
- let pluginContent = fs.readFileSync(pluginPath, 'utf8');
982
-
983
- pluginContent = pluginContent
984
- .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
985
- .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
986
-
987
- fs.writeFileSync(pluginPath, pluginContent, 'utf8');
988
- console.log('āœ… AdMob IDs successfully updated in plugin.xml');
989
- }
990
-
991
- function updateInfoPlist(admobConfig) {
992
- if (!fileExists(infoPlistPath)) {
993
- console.error(' āŒ Info.plist not found. Ensure you have built the iOS project.');
994
- return;
995
- }
996
-
997
- const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
998
- const plistData = plist.parse(plistContent);
999
-
1000
- plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
1001
- plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
1002
- plistData.GADDelayAppMeasurementInit = true;
1003
-
1004
- const updatedPlistContent = plist.build(plistData);
1005
- fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
1006
- console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
1007
- }
1008
-
1009
-
1010
- try {
1011
- if (!fileExists(configPath)) {
1012
- throw new Error(' āŒ capacitor.config.json not found. Skipping setup.');
1013
- }
1014
-
1015
- if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
1016
- throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
1017
- }
1018
-
1019
- checkAndCopyResources();
1020
-
1021
-
1022
-
1023
- _admobConfig = getAdMobConfig();
1024
-
1025
-
1026
-
1027
-
1028
-
1029
- // Proceed only if ADMOB_ENABLED is true
1030
- if (_admobConfig.ADMOB_ENABLED) {
1031
- if (fileExists(androidPlatformPath)) {
1032
- updatePluginXml(_admobConfig);
1033
- }
1034
-
1035
- if (fileExists(iosPlatformPath)) {
1036
- updateInfoPlist(_admobConfig);
1037
- }
1038
- }
1039
-
1040
-
1041
- } catch (error) {
1042
- console.error(error.message);
1043
- process.exit(1); // Stop execution if there's a critical error
1044
- }
1045
-
1046
-
1047
-
1048
- validateAndroidBuildOptions();
1049
-
1050
-
1051
-
1052
-
1053
-
1054
-
1055
- // Check all the codeplays plugins version START
1056
-
1057
-
1058
- const readline = require('readline');
1059
-
1060
-
1061
- //const srcDir = path.join(__dirname, 'src');
1062
- const srcDir = path.join(process.cwd(), 'src');
1063
- let outdatedPlugins = [];
1064
-
1065
- function parseVersion(ver) {
1066
- return ver.split('.').map(n => parseInt(n, 10));
1067
- }
1068
-
1069
- function compareVersions(v1, v2) {
1070
- const [a1, b1] = parseVersion(v1);
1071
- const [a2, b2] = parseVersion(v2);
1072
- if (a1 !== a2) return a1 - a2;
1073
- return b1 - b2;
1074
- }
1075
-
1076
- function walkSync(dir, filelist = []) {
1077
- fs.readdirSync(dir).forEach(file => {
1078
- const fullPath = path.join(dir, file);
1079
- const stat = fs.statSync(fullPath);
1080
- if (stat.isDirectory()) {
1081
- walkSync(fullPath, filelist);
1082
- } else {
1083
- filelist.push(fullPath);
1084
- }
1085
- });
1086
- return filelist;
1087
- }
1088
-
1089
-
1090
-
1091
- function getSearchRoot(plugin) {
1092
- return path.join(srcDir, plugin.baseDir || 'js');
1093
- }
1094
-
1095
-
1096
-
1097
-
1098
-
1099
-
1100
-
1101
-
1102
-
1103
-
1104
-
1105
-
1106
-
1107
-
1108
-
1109
-
1110
-
1111
-
1112
-
1113
-
1114
- /*############################################## AUTO DOWNLOAD FROM SERVER START #####################################*/
1115
-
1116
- // ============================================================
1117
- // šŸ”„ AUTO PLUGIN UPDATE SYSTEM (MANDATORY UPDATES)
1118
- // ============================================================
1119
-
1120
- const https = require("https");
1121
-
1122
- /**
1123
- * Check if file exists on server using HEAD request
1124
- */
1125
- function urlExists(url) {
1126
- return new Promise(resolve => {
1127
- const req = https.request(url, { method: "HEAD" }, res => {
1128
- resolve(res.statusCode === 200);
1129
- });
1130
-
1131
- req.on("error", () => resolve(false));
1132
- req.end();
1133
- });
1134
- }
1135
-
1136
- /**
1137
- * Download file from server
1138
- */
1139
- function downloadFile(url, dest) {
1140
- return new Promise((resolve, reject) => {
1141
- const file = fs.createWriteStream(dest);
1142
-
1143
- https.get(url, response => {
1144
- if (response.statusCode !== 200) {
1145
- reject("Download failed");
1146
- return;
1147
- }
1148
-
1149
- response.pipe(file);
1150
-
1151
- file.on("finish", () => {
1152
- file.close(resolve);
1153
- });
1154
- }).on("error", err => {
1155
- fs.unlink(dest, () => {});
1156
- reject(err);
1157
- });
1158
- });
1159
- }
1160
-
1161
- /**
1162
- * Update imports across src folder
1163
- * Replaces old filename → new filename
1164
- */
1165
- /**
1166
- * Update imports across project
1167
- * Replaces old filename → new filename
1168
- */
1169
-
1170
- const VITE_ALIAS_ONLY = [
1171
- "common",
1172
- "admob-emi",
1173
- "localization",
1174
- "theme",
1175
- "certificatejs",
1176
- "ffmpeg"
1177
- ];
1178
-
1179
- function updateImports(oldName, newName) {
1180
-
1181
- const projectRoot = process.cwd();
1182
-
1183
- const filesToScan = [
1184
- path.join(projectRoot, "vite.config.js"),
1185
- path.join(projectRoot, "vite.config.mjs")
1186
- ];
1187
-
1188
- const srcDir = path.join(projectRoot, "src");
1189
-
1190
- // scan vite config
1191
- filesToScan.forEach(file => {
1192
-
1193
- if (!fs.existsSync(file)) return;
1194
-
1195
- let content = fs.readFileSync(file, "utf8");
1196
-
1197
- if (content.includes(oldName)) {
1198
-
1199
- content = content.split(oldName).join(newName);
1200
-
1201
- fs.writeFileSync(file, content);
1202
-
1203
- console.log(`āœļø Updated alias in ${path.basename(file)}`);
1204
- }
1205
-
1206
- });
1207
-
1208
- // scan src files
1209
- function walk(dir) {
1210
-
1211
- fs.readdirSync(dir).forEach(file => {
1212
-
1213
- if (["node_modules","android","ios","dist",".git"].includes(file))
1214
- return;
1215
-
1216
- const full = path.join(dir, file);
1217
- const stat = fs.statSync(full);
1218
-
1219
- if (stat.isDirectory()) {
1220
- walk(full);
1221
- }
1222
-
1223
- else if (
1224
- (full.endsWith(".js") ||
1225
- full.endsWith(".f7") ||
1226
- full.endsWith(".mjs")) &&
1227
- !full.endsWith(".min.js")
1228
- ) {
1229
-
1230
- let content = fs.readFileSync(full, "utf8");
1231
-
1232
- if (content.includes(oldName)) {
1233
-
1234
- content = content.split(oldName).join(newName);
1235
-
1236
- fs.writeFileSync(full, content);
1237
-
1238
- console.log(`āœļø Updated import in ${path.relative(projectRoot, full)}`);
1239
- }
1240
-
1241
- }
1242
-
1243
- });
1244
-
1245
- }
1246
-
1247
- if (fs.existsSync(srcDir)) {
1248
- walk(srcDir);
1249
- }
1250
-
1251
- }
1252
-
1253
-
1254
- /**
1255
- * Auto-update a plugin file
1256
- * Returns TRUE if success
1257
- * Returns FALSE if fallback to manual needed
1258
- */
1259
-
1260
-
1261
- let _serverVersions = null;
1262
- async function fetchVersions() {
1263
-
1264
- if (_serverVersions) return _serverVersions;
1265
-
1266
- return new Promise((resolve) => {
1267
-
1268
- https.get(
1269
- "https://htmlcodeplay.com/code-play-plugin/versions.json",
1270
- { timeout: 5000 },
1271
- res => {
1272
-
1273
- let data = "";
1274
-
1275
- res.on("data", chunk => data += chunk);
1276
-
1277
- res.on("end", () => {
1278
-
1279
- try {
1280
-
1281
- _serverVersions = JSON.parse(data);
1282
-
1283
- resolve(_serverVersions);
1284
-
1285
- } catch {
1286
-
1287
- resolve(null);
1288
-
1289
- }
1290
-
1291
- });
1292
-
1293
- }
1294
-
1295
- ).on("error", () => resolve(null));
1296
-
1297
- });
1298
-
1299
- }
1300
-
1301
-
1302
-
1303
- async function autoUpdatePlugin(pluginDef, pluginInfo) {
1304
-
1305
- const versions = await fetchVersions();
1306
-
1307
- if (!versions) {
1308
- console.log("āš ļø versions.json not reachable");
1309
- return false;
1310
- }
1311
-
1312
- const oldFullPath = path.join(srcDir, pluginInfo.name);
1313
- const oldFileName = path.basename(oldFullPath);
1314
-
1315
- //const oldFileName = path.basename(oldFullPath);
1316
- const oldVersionFile = oldFileName;
1317
-
1318
-
1319
- const ext = path.extname(oldFileName); // .js or .less
1320
- //const baseName = oldFileName.replace(/-\d+\.\d+.*$/, "");
1321
- const baseName = oldFileName.replace(/-\d+\.\d+.*$/, '').replace(/\.(js|less)$/, '');
1322
-
1323
- // version lookup key
1324
- let pluginKey = baseName;
1325
-
1326
-
1327
- // Only common plugin has js and less variants
1328
- if (baseName === "common") {
1329
- if (ext === ".js") pluginKey = "common-js";
1330
- if (ext === ".less") pluginKey = "common-less";
1331
- }
1332
-
1333
- const latestVersion = versions[pluginKey];
1334
-
1335
- if (!latestVersion) {
1336
- console.log(`āŒ No version entry for ${baseName}`);
1337
- return false;
1338
- }
1339
-
1340
- // ===============================
1341
- // FOLDER PLUGIN UPDATE
1342
- // ===============================
1343
- if (pluginDef.isFolder) {
1344
-
1345
- const zipName = `${baseName}-${latestVersion}.zip`;
1346
- const url = `https://htmlcodeplay.com/code-play-plugin/${zipName}`;
1347
-
1348
- const destRoot = path.join(srcDir, pluginDef.destDir || pluginDef.baseDir || '');
1349
- const oldPath = path.join(destRoot, pluginInfo.name);
1350
- const newPath = path.join(destRoot, `${baseName}-${latestVersion}`);
1351
-
1352
- if (!(await urlExists(url))) return false;
1353
-
1354
- fs.rmSync(oldPath, { recursive: true, force: true });
1355
-
1356
- await downloadAndExtractZip(url, newPath);
1357
-
1358
- // šŸ”„ FIX: update imports
1359
- updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1360
-
1361
- console.log(`āœ… Folder updated → ${baseName}-${latestVersion}`);
1362
-
1363
- return true;
1364
- }
1365
- // ===============================
1366
- // FILE PLUGIN UPDATE
1367
- // ===============================
1368
-
1369
- const pluginDir = path.dirname(oldFullPath);
1370
-
1371
- // Only this plugin has ios variant
1372
- const IOS_VARIANT_PLUGINS = [
1373
- "saveToGalleryAndSaveAnyFile"
1374
- ];
1375
-
1376
- /* let variants = [
1377
- `${baseName}-${latestVersion}.js`
1378
- ]; */
1379
-
1380
- //const ext = path.extname(oldFileName);
1381
- const variants = [`${baseName.replace(ext,'')}-${latestVersion}${ext}`];
1382
-
1383
-
1384
- if (IOS_VARIANT_PLUGINS.includes(baseName)) {
1385
- variants.push(`${baseName}-${latestVersion}-ios.js`);
1386
- }
1387
-
1388
- let downloaded = [];
1389
-
1390
- // Download files
1391
- for (const fileName of variants) {
1392
-
1393
- const url = `https://htmlcodeplay.com/code-play-plugin/${fileName}`;
1394
-
1395
- console.log(`šŸ” Checking latest: ${fileName}`);
1396
-
1397
- if (await urlExists(url)) {
1398
-
1399
- const destPath = path.join(pluginDir, fileName);
1400
-
1401
- await downloadFile(url, destPath);
1402
-
1403
- downloaded.push(fileName);
1404
-
1405
- console.log(`⬇ Downloaded → ${fileName}`);
1406
-
1407
- //writeUpdateLine(`Downloaded: ${fileName}`);
1408
-
1409
- }
1410
- }
1411
-
1412
- if (downloaded.length === 0) {
1413
- console.log(`āŒ No files downloaded for ${baseName}`);
1414
- return false;
1415
- }
1416
-
1417
- // Remove ONLY versioned files (safe)
1418
- //const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\.js$`);
1419
- const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\${ext}$`);
1420
-
1421
- const existingFiles = fs.readdirSync(pluginDir);
1422
-
1423
- existingFiles.forEach(file => {
1424
-
1425
- if (
1426
- versionPattern.test(file) &&
1427
- !downloaded.includes(file)
1428
- ) {
1429
-
1430
- const oldPath = path.join(pluginDir, file);
1431
-
1432
- fs.unlinkSync(oldPath);
1433
-
1434
- console.log(`šŸ—‘ Removed old file → ${file}`);
1435
- //writeUpdateLine(`Removed old file: ${file}`);
1436
- }
1437
-
1438
- });
1439
-
1440
- //const newFileName = `${baseName}-${latestVersion}.js`;
1441
- const newFileName = `${baseName}-${latestVersion}${ext}`;
1442
-
1443
- writeUpdateLine(`${oldVersionFile} -> ${newFileName}`);
1444
-
1445
- updateImports(oldFileName, newFileName);
1446
- //updateImports(baseName, `${baseName}-${latestVersion}.js`);
1447
- //updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1448
-
1449
- //console.log(`āœ… Updated → ${newFileName}`);
1450
- //console.log(`āœ… Updated → ${baseName}-${latestVersion}`);
1451
-
1452
- return true;
1453
- }
1454
-
1455
-
1456
-
1457
-
1458
- /*############################################## AUTO DOWNLOAD FROM SERVER END #####################################*/
1459
-
1460
-
1461
-
1462
-
1463
-
1464
-
1465
-
1466
-
1467
-
1468
-
1469
-
1470
-
1471
-
1472
-
1473
-
1474
-
1475
-
1476
-
1477
- async function loadPluginVersions() {
1478
-
1479
- if (!USE_LIVE_SERVER_VERSION) {
1480
- console.log("ā„¹ļø Using local plugin versions (offline mode).");
1481
- return;
1482
- }
1483
-
1484
- console.log("🌐 Fetching plugin versions from server...");
1485
-
1486
- const versions = await fetchVersions();
1487
-
1488
- if (!versions || typeof versions !== "object") {
1489
- console.log("āš ļø Server unavailable or invalid versions.json. Falling back to local versions.");
1490
- return;
1491
- }
1492
-
1493
- requiredPlugins.forEach(plugin => {
1494
-
1495
- if (!plugin.name) return;
1496
-
1497
- if (versions[plugin.name]) {
1498
- plugin.minVersion = versions[plugin.name];
1499
- }
1500
-
1501
- });
1502
-
1503
- console.log("āœ… Plugin versions loaded from server.");
1504
-
1505
- }
1506
-
1507
-
1508
-
1509
- let hasMandatoryUpdate = false;
1510
- function checkPlugins() {
1511
- return new Promise(async (resolve, reject) => {
1512
- const files = walkSync(srcDir);
1513
- const outdatedPlugins = [];
1514
- let hasMandatoryUpdate = false;
1515
-
1516
- for (const plugin of requiredPlugins) {
1517
- const searchRoot = getSearchRoot(plugin);
1518
-
1519
- // ---------- Folder plugins ----------
1520
- if (plugin.isFolder) {
1521
- if (!fs.existsSync(searchRoot)) continue;
1522
-
1523
- const subDirs = fs.readdirSync(searchRoot)
1524
- .map(name => path.join(searchRoot, name))
1525
- .filter(p => fs.statSync(p).isDirectory());
1526
-
1527
- for (const dir of subDirs) {
1528
- const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
1529
- const match = plugin.pattern.exec(relativePath);
1530
-
1531
- if (match) {
1532
- const currentVersion = match[1];
1533
-
1534
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
1535
- outdatedPlugins.push({
1536
- name: relativePath,
1537
- currentVersion,
1538
- requiredVersion: plugin.minVersion,
1539
- mandatoryUpdate: plugin.mandatoryUpdate === true
1540
- });
1541
-
1542
- if (plugin.mandatoryUpdate) {
1543
- hasMandatoryUpdate = true;
1544
- }
1545
- }
1546
- }
1547
- }
1548
- continue;
1549
- }
1550
-
1551
- // ---------- File plugins ----------
1552
- const matchedFile = files.find(file =>
1553
- file.startsWith(searchRoot) && plugin.pattern.test(file)
1554
- );
1555
-
1556
- if (matchedFile) {
1557
- const match = plugin.pattern.exec(matchedFile);
1558
- if (match) {
1559
- const currentVersion = match[1];
1560
- const isBeta = !!match[2];
1561
-
1562
- const cmp = plugin.pattern.source.includes('beta')
1563
- ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1564
- : compareVersions(currentVersion, plugin.minVersion);
1565
-
1566
- if (cmp < 0) {
1567
- outdatedPlugins.push({
1568
- name: path.relative(srcDir, matchedFile),
1569
- currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1570
- requiredVersion: plugin.minVersion,
1571
- mandatoryUpdate: plugin.mandatoryUpdate === true
1572
- });
1573
-
1574
- if (plugin.mandatoryUpdate) {
1575
- hasMandatoryUpdate = true;
1576
- }
1577
- }
1578
- }
1579
- }
1580
- }
1581
-
1582
- // ---------- Result handling ----------
1583
- if (outdatedPlugins.length > 0) {
1584
- console.log('\nā— The following plugins are outdated:\n');
1585
-
1586
- outdatedPlugins.forEach( p => {
1587
- const tag = p.mandatoryUpdate ? 'šŸ”„ MANDATORY' : '';
1588
- console.log(
1589
- ` āš ļø - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion}) ${tag}`
1590
- );
1591
- });
1592
-
1593
- // 🚨 Mandatory update → stop build
1594
- /* if (hasMandatoryUpdate) {
1595
- console.log('\n🚫 One or more plugins require a mandatory update.');
1596
- console.log('āŒ Build cancelled. Please update mandatory plugins and try again.');
1597
- process.exit(1);
1598
- } */
1599
-
1600
-
1601
-
1602
-
1603
-
1604
- if (hasMandatoryUpdate) {
1605
-
1606
- //--------------------------------------------------
1607
- // 🚫 AUTO UPDATE DISABLED
1608
- //--------------------------------------------------
1609
- if (!ENABLE_AUTO_UPDATE) {
1610
- console.log("\n🚫 Auto-update disabled.");
1611
- console.log("āŒ Manual update required.");
1612
- process.exit(1);
1613
- }
1614
-
1615
- //--------------------------------------------------
1616
- // šŸ”„ AUTO UPDATE ENABLED
1617
- //--------------------------------------------------
1618
- console.log("\nšŸ”„ Mandatory plugins outdated. Trying auto-update...\n");
1619
-
1620
-
1621
-
1622
- let autoFailed = false;
1623
-
1624
- for (const p of outdatedPlugins.filter(x => x.mandatoryUpdate)) {
1625
-
1626
- const pluginDef = requiredPlugins.find(def =>
1627
- def.pattern.test(p.name)
1628
- );
1629
-
1630
- if (!pluginDef) continue;
1631
-
1632
- const success = await autoUpdatePlugin(
1633
- pluginDef,
1634
- p
1635
- );
1636
-
1637
- if (!success) {
1638
- autoFailed = true;
1639
-
1640
- const pluginDef = requiredPlugins.find(def =>
1641
- def.pattern.test(p.name)
1642
- );
1643
-
1644
- console.log(`āŒ Manual update required for ${p.name}`);
1645
-
1646
- if (pluginDef) {
1647
- console.log(`šŸ‘‰ Required minimum version: ${pluginDef.minVersion}`);
1648
- }
1649
- }
1650
- }
1651
-
1652
- // 🚨 Fallback to manual if any failed
1653
- if (autoFailed) {
1654
- console.log('\n🚫 One or more plugins require manual update.');
1655
- console.log('āŒ Build cancelled. Please update mandatory plugins.');
1656
- process.exit(1);
1657
- }
1658
-
1659
- console.log('\nšŸŽ‰ All mandatory plugins auto-updated! Rechecking plugins...\n');
1660
-
1661
- // Re-run plugin check so outdated list becomes empty
1662
- await checkPlugins();
1663
- return;
1664
- }
1665
-
1666
-
1667
-
1668
-
1669
-
1670
-
1671
- // Optional updates → ask user
1672
- const rl = readline.createInterface({
1673
- input: process.stdin,
1674
- output: process.stdout
1675
- });
1676
-
1677
- rl.question(
1678
- '\nAre you sure you want to continue without updating these plugins? (y/n): ',
1679
- answer => {
1680
- rl.close();
1681
-
1682
- if (answer.toLowerCase() !== 'y') {
1683
- console.log('\nāŒ Build cancelled due to outdated plugins.');
1684
- process.exit(1);
1685
- } else {
1686
- console.log('\nāœ… Continuing build...');
1687
- resolve();
1688
- }
1689
- }
1690
- );
1691
- } else {
1692
- console.log('āœ… All plugin versions are up to date.');
1693
- saveUpdateLogs();
1694
- resolve();
1695
- }
1696
- });
1697
- }
1698
-
1699
-
1700
-
1701
-
1702
-
1703
-
1704
-
1705
-
1706
- // Check all the codeplays plugins version START
1707
-
1708
-
1709
-
1710
-
1711
- // ====================================================================
1712
- // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
1713
- // ====================================================================
1714
-
1715
-
1716
-
1717
- const checkAndupdateDropInViteConfig = () => {
1718
-
1719
- const possibleFiles = [
1720
- "vite.config.js",
1721
- "vite.config.mjs"
1722
- ];
1723
-
1724
- // Detect existing config file
1725
- const viteConfigPath = possibleFiles
1726
- .map(file => path.join(process.cwd(), file))
1727
- .find(filePath => fs.existsSync(filePath));
1728
-
1729
- if (!viteConfigPath) {
1730
- console.warn("āš ļø No vite config found. Skipping.");
1731
- return;
1732
- }
1733
-
1734
- //console.log("šŸ“„ Using:", viteConfigPath.split("/").pop());
1735
-
1736
- let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1737
-
1738
- // Skip if already exists
1739
- if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1740
- console.log("ā„¹ļø vite.config.(m)js already Updated. Skipping...");
1741
- return;
1742
- }
1743
-
1744
- console.log("šŸ”§ Adding esbuild.drop ...");
1745
-
1746
- // If esbuild block exists
1747
- if (/esbuild\s*:\s*{/.test(viteContent)) {
1748
- viteContent = viteContent.replace(
1749
- /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1750
- (full, inner, indent) => {
1751
-
1752
- let lines = inner
1753
- .split("\n")
1754
- .map(l => l.trim())
1755
- .filter(Boolean);
1756
-
1757
- // Fix last comma
1758
- if (lines.length > 0) {
1759
- lines[lines.length - 1] =
1760
- lines[lines.length - 1].replace(/,+$/, "") + ",";
1761
- }
1762
-
1763
- // Re-indent
1764
- lines = lines.map(l => indent + " " + l);
1765
-
1766
- // Add drop
1767
- lines.push(`${indent} drop: ['console','debugger'],`);
1768
-
1769
- return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1770
- }
1771
- );
1772
- }
1773
-
1774
- // If esbuild missing
1775
- else {
1776
- viteContent = viteContent.replace(
1777
- /export default defineConfig\s*\(\s*{/,
1778
- m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1779
- );
1780
- }
1781
-
1782
- fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1783
- console.log("āœ… vite.config.(m)js Updated successfully.");
1784
- };
1785
-
1786
-
1787
-
1788
-
1789
-
1790
-
1791
-
1792
-
1793
-
1794
-
1795
- const compareVersion = (v1, v2) => {
1796
- const a = v1.split(".").map(Number);
1797
- const b = v2.split(".").map(Number);
1798
-
1799
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
1800
- const num1 = a[i] || 0;
1801
- const num2 = b[i] || 0;
1802
- if (num1 > num2) return 1;
1803
- if (num1 < num2) return -1;
1804
- }
1805
- return 0;
1806
- };
1807
-
1808
-
1809
-
1810
-
1811
- const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1812
-
1813
- const checkAdmobConfigurationProperty=()=>{
1814
-
1815
-
1816
- if (!_admobConfig.ADMOB_ENABLED)
1817
- {
1818
- console.log("ā„¹ļø Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1819
- return;
1820
- }
1821
-
1822
-
1823
- const REQUIRED_CONFIG_KEYS = [
1824
- "isKidsApp",
1825
- "isTesting",
1826
- "isConsoleLogEnabled",
1827
- "bannerEnabled",
1828
- "interstitialEnabled",
1829
- "appOpenEnabled",
1830
- "rewardVideoEnabled",
1831
- "rewardInterstitialEnabled",
1832
- "collapsibleEnabled",
1833
- "isLandScape",
1834
- "isOverlappingEnable",
1835
- "bannerTypeAndroid",
1836
- "bannerTypeiOS",
1837
- "bannerTopSpaceColor",
1838
- "interstitialLoadScreenTextColor",
1839
- "interstitialLoadScreenBackgroundColor",
1840
- "beforeBannerSpace",
1841
- "whenShow",
1842
- "minimumClick",
1843
- "interstitialTimeOut",
1844
- "interstitialFirstTimeOut",
1845
- "appOpenAdsTimeOut",
1846
- "maxRetryCount",
1847
- "retrySecondsAr",
1848
- "appOpenPerSession",
1849
- "interstitialPerSession",
1850
- "appOpenFirstTimeOut"
1851
- ];
1852
-
1853
-
1854
-
1855
-
1856
-
1857
- let admobConfigInJson;
1858
-
1859
- try {
1860
- admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1861
- } catch (err) {
1862
- console.error("āŒ Failed to read admob-ad-configuration.json", err);
1863
- process.exit(1);
1864
- }
1865
-
1866
- // āœ… Validate config object exists
1867
- if (!admobConfigInJson.config) {
1868
- console.error('āŒ "config" object is missing in admob-ad-configuration.json');
1869
- process.exit(1);
1870
- }
1871
-
1872
-
1873
- const admobConfigMinVersion="1.5"
1874
-
1875
- if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1876
- console.error(`āŒ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1877
- process.exit(1);
1878
- }
1879
-
1880
-
1881
- const config = admobConfigInJson.config;
1882
-
1883
- // āœ… Find missing properties
1884
- const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1885
- key => !(key in config)
1886
- );
1887
-
1888
-
1889
-
1890
- if (missingKeys.length > 0) {
1891
- console.error("āŒ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1892
-
1893
- missingKeys.forEach(k => console.error(" - " + k));
1894
- process.exit(1);
1895
- }
1896
-
1897
-
1898
- console.log('āœ… All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1899
- }
1900
-
1901
-
1902
-
1903
- function ensureGitignoreEntry(entry) {
1904
- const gitignorePath = path.join(process.cwd(), '.gitignore');
1905
-
1906
- // If .gitignore doesn't exist, create it
1907
- if (!fs.existsSync(gitignorePath)) {
1908
- fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
1909
- console.log(`āœ… .gitignore created and added: ${entry}`);
1910
- return;
1911
- }
1912
-
1913
- const content = fs.readFileSync(gitignorePath, 'utf8');
1914
-
1915
- // Normalize lines (trim + remove trailing slashes for comparison)
1916
- const lines = content
1917
- .split(/\r?\n/)
1918
- .map(l => l.trim());
1919
-
1920
- const normalizedEntry = entry.replace(/\/$/, '');
1921
-
1922
- const exists = lines.some(
1923
- line => line.replace(/\/$/, '') === normalizedEntry
1924
- );
1925
-
1926
- if (exists) {
1927
- console.log(`ā„¹ļø .gitignore already contains: ${entry}`);
1928
- return;
1929
- }
1930
-
1931
- // Ensure file ends with newline
1932
- const separator = content.endsWith('\n') ? '' : '\n';
1933
-
1934
- fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
1935
- console.log(`āœ… Added to .gitignore: ${entry}`);
1936
- }
1937
-
1938
-
1939
- ensureGitignoreEntry('buildCodeplay/');
1940
-
1941
-
1942
- // Run the validation
1943
- (async () => {
1944
-
1945
- await loadPluginVersions(); // šŸ”„ NEW
1946
-
1947
- await checkPlugins();
1948
- checkAndupdateDropInViteConfig();
1949
- checkAdmobConfigurationProperty()
1950
- })();
1951
-
1952
-
1953
- // ======================================================
1954
- // Validate theme folder location (src/js/theme is NOT allowed)
1955
- // ======================================================
1956
-
1957
- function validateThemeFolderLocation() {
1958
- const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
1959
- const newThemePath = path.join(process.cwd(), 'src', 'theme');
1960
-
1961
- // āŒ Block old structure
1962
- if (fs.existsSync(oldThemePath)) {
1963
- console.error(
1964
- '\nāŒ INVALID PROJECT STRUCTURE DETECTED\n' +
1965
- '--------------------------------------------------\n' +
1966
- 'The "theme" folder must NOT be inside:\n' +
1967
- ' src/js/theme\n\n' +
1968
- 'āœ… Correct location is:\n' +
1969
- ' src/theme\n\n' +
1970
- 'šŸ›‘ Please move the folder and re-run the build.\n'
1971
- );
1972
- process.exit(1);
1973
- }
1974
-
1975
- // āš ļø Optional warning if new theme folder is missing
1976
- if (!fs.existsSync(newThemePath)) {
1977
- console.warn(
1978
- '\nāš ļø WARNING: "src/theme" folder not found.\n' +
1979
- 'If your app uses themes, please ensure it exists.\n'
1980
- );
1981
- } else {
1982
- console.log('āœ… Theme folder structure validated (src/theme).');
1983
- }
1984
- }
1985
- validateThemeFolderLocation()
1986
-
1987
-
1988
-
1989
- const validateAndRestoreSignDetails=()=>{
1990
-
1991
- // Read config file
1992
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1993
-
1994
- // Ensure android and buildOptions exist
1995
- if (!config.android) config.android = {};
1996
- if (!config.android.buildOptions) config.android.buildOptions = {};
1997
-
1998
- // Update only if changed
1999
- let updated = false;
2000
-
2001
- if (config.android.buildOptions.releaseType !== 'AAB') {
2002
- config.android.buildOptions.releaseType = 'AAB';
2003
- updated = true;
2004
- }
2005
-
2006
- if (config.android.buildOptions.signingType !== 'jarsigner') {
2007
- config.android.buildOptions.signingType = 'jarsigner';
2008
- updated = true;
2009
- }
2010
-
2011
- // Write back only if modified
2012
- if (updated) {
2013
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
2014
- console.log('capacitor.config.json updated successfully.');
2015
- } else {
2016
- console.log('No changes needed.');
2017
- }
2018
-
2019
- }
2020
-
2021
- validateAndRestoreSignDetails()
2022
-
2023
-
2024
- /*
2025
- Release Notes
2026
-
2027
- 5.1
2028
- Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
2029
-
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const plist = require('plist');
4
+
5
+
6
+
7
+ const { execSync } = require("child_process");
8
+
9
+
10
+
11
+
12
+ const { readFileSync } = require("fs");
13
+
14
+ const ENABLE_AUTO_UPDATE = true;
15
+ const USE_LIVE_SERVER_VERSION = true;
16
+
17
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
18
+ const updateLogFile = path.join(process.cwd(), "", "plugin-update-log.txt");
19
+
20
+ // Expected plugin list with minimum versions
21
+ /* const requiredPlugins = [
22
+
23
+ { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '2.0', required: true, baseDir: 'js',mandatoryUpdate: true},
24
+
25
+
26
+ { pattern: /common-(\d+\.\d+)(?:-beta-(\d+))?\.js$/, minVersion: '6.0', required: true, baseDir: 'js',mandatoryUpdate: true },
27
+
28
+ { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
29
+ { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: true },
30
+ { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js',mandatoryUpdate: false },
31
+ { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true, baseDir: 'js',mandatoryUpdate: false },
32
+ { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.3', required: true, baseDir: 'js',mandatoryUpdate: false },
33
+ { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.1', required: true, baseDir: 'js',mandatoryUpdate: true },
34
+ { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.7', required: true, baseDir: 'js',mandatoryUpdate: true },
35
+
36
+ // New added plugins
37
+ { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js',mandatoryUpdate: false },
38
+ { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js',mandatoryUpdate: false },
39
+ { pattern: /common-(\d+\.\d+)\.less$/, minVersion: '1.6', required: true, baseDir: 'assets/css',mandatoryUpdate: false },
40
+
41
+
42
+ // New folders
43
+ { pattern: /IAP-(\d+\.\d+)$/, minVersion: '2.8', isFolder: true , required: true, baseDir: 'js/Ads',mandatoryUpdate: true },
44
+ { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.9', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
45
+ { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true, required: true, baseDir: 'js',mandatoryUpdate: true },
46
+ { pattern: /theme-(\d+\.\d+)$/, minVersion: '3.3', isFolder: true , required: true, baseDir: 'theme',mandatoryUpdate: true },
47
+
48
+
49
+ { pattern: /certificatejs-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true , required: true, baseDir: 'certificate',mandatoryUpdate: true }
50
+
51
+ ]; */
52
+
53
+
54
+ function requireOrInstall(packageName) {
55
+ try {
56
+ return require(packageName);
57
+ } catch (err) {
58
+
59
+ console.log(`šŸ“¦ "${packageName}" not found. Installing automatically...`);
60
+
61
+ try {
62
+ execSync(`npm install ${packageName}`, { stdio: "inherit" });
63
+ console.log(`āœ… "${packageName}" installed successfully.`);
64
+ } catch (installErr) {
65
+ console.error(`āŒ Failed to install "${packageName}".`);
66
+ process.exit(1);
67
+ }
68
+
69
+ // Try loading again
70
+ return require(packageName);
71
+ }
72
+ }
73
+
74
+ const AdmZip = requireOrInstall("adm-zip");
75
+
76
+
77
+
78
+ const pkg = require(path.join(process.cwd(), 'node_modules', 'codeplay-common', 'package.json'));
79
+
80
+ const pluginName = pkg.name;
81
+ const pluginVersion = pkg.version;
82
+
83
+ let updateLogs = [];
84
+
85
+ function writeUpdateLine(message) {
86
+ updateLogs.push(message);
87
+ }
88
+
89
+ const MAX_LOG_BLOCKS = 50;
90
+
91
+ function saveUpdateLogs() {
92
+
93
+ if (updateLogs.length === 0) return;
94
+
95
+ const logDir = path.dirname(updateLogFile);
96
+
97
+ if (!fs.existsSync(logDir)) {
98
+ fs.mkdirSync(logDir, { recursive: true });
99
+ }
100
+
101
+ const now = new Date();
102
+
103
+ const formattedTime = now.toLocaleString('en-GB', {
104
+ day: '2-digit',
105
+ month: '2-digit',
106
+ year: 'numeric',
107
+ hour: '2-digit',
108
+ minute: '2-digit',
109
+ hour12: true
110
+ }).replace(',', '').replace(/\//g, '-');
111
+
112
+ let newBlock = `${pluginName}: ${pluginVersion}\n[${formattedTime}]\n`;
113
+
114
+ updateLogs.forEach(line => {
115
+ newBlock += `${line}\n`;
116
+ });
117
+
118
+ newBlock += "\n";
119
+
120
+ let existingLog = "";
121
+
122
+ if (fs.existsSync(updateLogFile)) {
123
+ existingLog = fs.readFileSync(updateLogFile, "utf8");
124
+ }
125
+
126
+ let combinedLog = newBlock + existingLog;
127
+
128
+ // Split blocks by plugin header
129
+ const blocks = combinedLog.split(/\n(?=codeplay-common:)/);
130
+
131
+ // Keep only latest 50
132
+ const trimmed = blocks.slice(0, MAX_LOG_BLOCKS).join("\n");
133
+
134
+ fs.writeFileSync(updateLogFile, trimmed);
135
+
136
+ }
137
+
138
+
139
+
140
+
141
+
142
+ const versionsFile = path.join(__dirname, "versions.json");
143
+
144
+ function loadRequiredPlugins() {
145
+
146
+ if (!fs.existsSync(versionsFile)) {
147
+ console.error("āŒ versions.json not found");
148
+ process.exit(1);
149
+ }
150
+
151
+ const json = JSON.parse(fs.readFileSync(versionsFile, "utf8"));
152
+
153
+ return json.plugins.map(p => ({
154
+ ...p,
155
+ pattern: new RegExp(p.pattern)
156
+ }));
157
+
158
+ }
159
+
160
+ let requiredPlugins = loadRequiredPlugins();
161
+
162
+
163
+
164
+
165
+
166
+
167
+ async function downloadAndExtractZip(url, destFolder) {
168
+
169
+ const zipPath = destFolder + ".zip";
170
+
171
+ await downloadFile(url, zipPath);
172
+
173
+ const zip = new AdmZip(zipPath);
174
+ zip.extractAllTo(destFolder, true);
175
+
176
+ fs.unlinkSync(zipPath);
177
+
178
+ }
179
+
180
+
181
+
182
+
183
+
184
+
185
+
186
+ //Check codeplay-common latest version installed or not Start
187
+ //const { execSync } = require('child_process');
188
+
189
+
190
+ function getInstalledVersion(packageName) {
191
+ try {
192
+ const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
193
+ if (fs.existsSync(packageJsonPath)) {
194
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
195
+ return packageJson.version;
196
+ }
197
+ } catch (error) {
198
+ return null;
199
+ }
200
+ return null;
201
+ }
202
+
203
+ function getLatestVersion(packageName) {
204
+ try {
205
+ return execSync(`npm view ${packageName} version`).toString().trim();
206
+ } catch (error) {
207
+ console.error(`Failed to fetch latest version for ${packageName}`);
208
+ return null;
209
+ }
210
+ }
211
+
212
+ function checkPackageVersion() {
213
+ const packageName = 'codeplay-common';
214
+ const installedVersion = getInstalledVersion(packageName);
215
+ const latestVersion = getLatestVersion(packageName);
216
+
217
+ if (!installedVersion) {
218
+ console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
219
+ process.exit(1);
220
+ }
221
+
222
+ if (installedVersion !== latestVersion) {
223
+ console.error(`\x1b[31m${packageName} is outdated (installed: ${installedVersion}, latest: ${latestVersion}). Please update it.\x1b[0m\n\x1b[33mUse 'npm uninstall codeplay-common ; npm i codeplay-common'\x1b[0m`);
224
+ process.exit(1);
225
+ }
226
+
227
+ console.log(`${packageName} is up to date (version ${installedVersion}).`);
228
+ }
229
+
230
+ // Run package version check before executing the main script
231
+ try {
232
+ checkPackageVersion();
233
+ } catch (error) {
234
+ console.error(error.message);
235
+ process.exit(1);
236
+ }
237
+
238
+ //Check codeplay-common latest version installed or not END
239
+
240
+
241
+
242
+ function compareWithBeta(installedVersion, minVersion, isBeta) {
243
+ const baseCompare = compareVersions(installedVersion, minVersion);
244
+
245
+ if (!isBeta) {
246
+ // Stable version → normal compare
247
+ return baseCompare;
248
+ }
249
+
250
+ // Beta version logic
251
+ if (baseCompare > 0) return 1; // 5.3-beta > 5.2
252
+ if (baseCompare < 0) return -1; // 5.1-beta < 5.2
253
+
254
+ // Same version but beta → LOWER than stable
255
+ return -1; // 5.2-beta < 5.2
256
+ }
257
+
258
+
259
+
260
+
261
+ const checkAppUniqueId=()=>{
262
+
263
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
264
+
265
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
266
+ const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
267
+ const orientation = config.android?.ORIENTATION;
268
+
269
+
270
+ let logErrorMessage="";
271
+
272
+ // 1ļøāƒ£ Check if it’s missing
273
+ if (RESIZEABLE_ACTIVITY === undefined) {
274
+ logErrorMessage+='āŒ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
275
+ }
276
+
277
+ // 2ļøāƒ£ Check if it’s not boolean (true/false only)
278
+ else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
279
+ logErrorMessage+='āŒ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
280
+ }
281
+
282
+
283
+
284
+ if (!orientation) {
285
+ logErrorMessage+='āŒ Missing android.ORIENTATION option in capacitor.config.json.\n';
286
+ }
287
+
288
+ else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
289
+ {
290
+ logErrorMessage+='āŒ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
291
+ }
292
+
293
+
294
+ if (!appUniqueId) {
295
+ logErrorMessage+='āŒ APP_UNIQUE_ID is missing in capacitor.config.json.';
296
+ }
297
+
298
+ else if (!Number.isInteger(appUniqueId)) {
299
+ logErrorMessage+='āŒ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
300
+ }
301
+
302
+
303
+
304
+ if(logErrorMessage!="")
305
+ {
306
+ console.error(logErrorMessage);
307
+ process.exit(1)
308
+ }
309
+
310
+
311
+ console.log(`āœ… APP_UNIQUE_ID is valid: ${appUniqueId}`);
312
+
313
+ }
314
+
315
+ checkAppUniqueId();
316
+
317
+
318
+
319
+
320
+
321
+
322
+
323
+ //@Codemirror check and install/uninstall the packages START
324
+ //const fs = require("fs");
325
+ //const path = require("path");
326
+ //const { execSync } = require("child_process");
327
+
328
+ const baseDir = path.join(__dirname, "..", "src", "js");
329
+
330
+ // Step 1: Find highest versioned folder like `editor-1.6`
331
+ const editorDirs = fs.readdirSync(baseDir)
332
+ .filter(name => /^editor-\d+\.\d+$/.test(name))
333
+ .sort((a, b) => {
334
+ const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
335
+ const [aMajor, aMinor] = getVersion(a);
336
+ const [bMajor, bMinor] = getVersion(b);
337
+ return bMajor - aMajor || bMinor - aMinor;
338
+ });
339
+
340
+ if (editorDirs.length === 0) {
341
+
342
+ console.log("@Codemirror used editor(s) are not found")
343
+ //console.error("āŒ No editor-x.x folders found in src/js.");
344
+ //process.exit(1);
345
+ }
346
+ else
347
+ {
348
+
349
+ const latestEditorDir = editorDirs.sort((a, b) => {
350
+ const versionA = parseFloat(a.split('-')[1]);
351
+ const versionB = parseFloat(b.split('-')[1]);
352
+ return versionB - versionA;
353
+ })[0];
354
+
355
+ //const latestEditorDir = editorDirs[editorDirs.length - 1];
356
+ const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
357
+
358
+ if (!fs.existsSync(runJsPath)) {
359
+ console.error(`āŒ run.js not found in ${latestEditorDir}`);
360
+ process.exit(1);
361
+ }
362
+
363
+ // Step 2: Execute the run.js file
364
+ console.log(`šŸš€ Executing ${runJsPath}...`);
365
+ execSync(`node "${runJsPath}"`, { stdio: "inherit" });
366
+ }
367
+
368
+ //@Codemirror check and install/uninstall the packages END
369
+
370
+
371
+
372
+
373
+
374
+
375
+
376
+
377
+
378
+
379
+
380
+
381
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
382
+
383
+ const os = require('os');
384
+
385
+ const saveToGalleryAndSaveFileCheck_iOS = () => {
386
+
387
+ // List of paths to scan
388
+ const SCAN_PATHS = [
389
+ path.resolve(__dirname, '../src/certificate'),
390
+ path.resolve(__dirname, '../src/pages'),
391
+ path.resolve(__dirname, '../src/js'),
392
+ path.resolve(__dirname, '../src/app.f7')
393
+ ];
394
+
395
+ // Directory to exclude
396
+ const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
397
+
398
+ const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
399
+
400
+
401
+ // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
402
+ const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
403
+
404
+ // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
405
+ const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
406
+
407
+
408
+
409
+
410
+
411
+ const ALLOWED_EXTENSIONS = ['.js', '.f7'];
412
+ const isMac = os.platform() === 'darwin';
413
+
414
+ let iosImportFound = false;
415
+ let androidImportFound = false;
416
+
417
+ // Files to skip completely (full or partial match)
418
+ const SKIP_FILES = [
419
+ 'pdf-3.11.174.min.js',
420
+ 'pdf.worker-3.11.174.min.js'
421
+ ,'index.browser.js'
422
+ ];
423
+
424
+
425
+ function scanDirectory(dir) {
426
+
427
+ /*
428
+ //######################### DO NOT DELETE THIS - START [Appid base validation] #####################################
429
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
430
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
431
+ if (appUniqueId == "206") return;
432
+ //######################### DO NOT DELETE THIS - END [Appid base validation] #####################################
433
+ */
434
+
435
+ const stat = fs.statSync(dir);
436
+
437
+ if (stat.isFile()) {
438
+
439
+ // šŸ”„ Skip files in SKIP_FILES array
440
+ const baseName = path.basename(dir);
441
+ if (SKIP_FILES.includes(baseName)) {
442
+ // Just skip silently
443
+ return;
444
+ }
445
+
446
+ // Only scan allowed file extensions
447
+ if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
448
+ process.stdout.write(`\ršŸ” Scanning: ${dir} `);
449
+
450
+ const content = fs.readFileSync(dir, 'utf8');
451
+
452
+ if (IOS_FILE_REGEX.test(content)) {
453
+ iosImportFound = true;
454
+ if (!isMac) {
455
+ console.error(`\nāŒ ERROR: iOS-specific import detected in: ${dir}`);
456
+ console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
457
+ process.exit(1);
458
+ }
459
+ }
460
+ else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
461
+ androidImportFound = true;
462
+ }
463
+ }
464
+ }
465
+ else if (stat.isDirectory()) {
466
+ if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
467
+
468
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
469
+ for (let entry of entries) {
470
+ scanDirectory(path.join(dir, entry.name));
471
+ }
472
+ }
473
+ }
474
+
475
+
476
+ // Run scan on all specified paths
477
+ for (let scanPath of SCAN_PATHS) {
478
+ if (fs.existsSync(scanPath)) {
479
+ scanDirectory(scanPath);
480
+ }
481
+ }
482
+
483
+
484
+
485
+ /* // Check src folder
486
+ if (!fs.existsSync(ROOT_DIR)) {
487
+ console.warn(`āš ļø Warning: 'src' directory not found at: ${ROOT_DIR}`);
488
+ return;
489
+ } */
490
+
491
+ //scanDirectory(ROOT_DIR);
492
+
493
+ // iOS Checks
494
+ if (isMac && !iosImportFound) {
495
+ console.warn(`āš ļø WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
496
+ process.exit(1);
497
+ } else if (isMac && iosImportFound) {
498
+ console.log('āœ… iOS version detected for macOS build.');
499
+ } else if (!iosImportFound) {
500
+ console.log('āœ… No iOS-specific imports detected for non-macOS.');
501
+ }
502
+
503
+ // Android Checks
504
+ if (androidImportFound) {
505
+ console.log("šŸ“± Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
506
+
507
+ if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
508
+ console.error("āŒ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
509
+ return;
510
+ }
511
+
512
+ let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
513
+
514
+ if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
515
+ console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
516
+
517
+ manifestContent = manifestContent.replace(
518
+ /<application([^>]*)>/,
519
+ (match, attrs) => {
520
+ if (attrs.includes('android:requestLegacyExternalStorage')) return match;
521
+ return `<application${attrs} android:requestLegacyExternalStorage="true">`;
522
+ }
523
+ );
524
+
525
+ fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
526
+ console.log("āœ… android:requestLegacyExternalStorage=\"true\" added successfully.");
527
+ } else {
528
+ console.log("ā„¹ļø android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
529
+ }
530
+ } else {
531
+ console.log("āœ… No Android saveToGalleryAndSaveAnyFile imports detected.");
532
+ }
533
+ };
534
+
535
+ saveToGalleryAndSaveFileCheck_iOS();
536
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
537
+
538
+
539
+
540
+
541
+
542
+
543
+
544
+
545
+
546
+
547
+
548
+
549
+
550
+ /*
551
+ // Clean up AppleDouble files (._*) created by macOS START
552
+ if (process.platform === 'darwin') {
553
+ try {
554
+ console.log('🧹 Cleaning up AppleDouble files (._*)...');
555
+ execSync(`find . -name '._*' -delete`);
556
+ console.log('āœ… AppleDouble files removed.');
557
+ } catch (err) {
558
+ console.warn('āš ļø Failed to remove AppleDouble files:', err.message);
559
+ }
560
+ } else {
561
+ console.log('ā„¹ļø Skipping AppleDouble cleanup — not a macOS machine.');
562
+ }
563
+
564
+ // Clean up AppleDouble files (._*) created by macOS END
565
+ */
566
+
567
+
568
+
569
+
570
+
571
+
572
+ //In routes.js file check static import START
573
+
574
+ const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
575
+ const routesContent = fs.readFileSync(routesPath, 'utf-8');
576
+
577
+ let inBlockComment = false;
578
+ const lines = routesContent.split('\n');
579
+
580
+ const allowedImport = `import HomePage from '../pages/home.f7';`;
581
+ const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
582
+ const badImports = [];
583
+
584
+ lines.forEach((line, index) => {
585
+ const trimmed = line.trim();
586
+
587
+ // Handle block comment start and end
588
+ if (trimmed.startsWith('/*')) inBlockComment = true;
589
+ if (inBlockComment && trimmed.endsWith('*/')) {
590
+ inBlockComment = false;
591
+ return;
592
+ }
593
+
594
+ // Skip if inside block comment or line comment
595
+ if (inBlockComment || trimmed.startsWith('//')) return;
596
+
597
+ // Match static .f7 import
598
+ if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
599
+ badImports.push({ line: trimmed, number: index + 1 });
600
+ }
601
+ });
602
+
603
+ if (badImports.length > 0) {
604
+ console.error('\nāŒ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
605
+ console.error(`āš ļø Only this static import is allowed:\n ${allowedImport}\n`);
606
+ console.error(`šŸ”§ Please convert other imports to async dynamic imports like this:\n`);
607
+ console.error(`
608
+
609
+ import HomePage from '../pages/home.f7';
610
+
611
+ const routes = [
612
+ {
613
+ path: '/',
614
+ component:HomePage,
615
+ },
616
+ {
617
+ path: '/ProfilePage/',
618
+ async async({ resolve }) {
619
+ const page = await import('../pages/profile.f7');
620
+ resolve({ component: page.default });
621
+ },
622
+ }]
623
+ `);
624
+
625
+ badImports.forEach(({ line, number }) => {
626
+ console.error(`${number}: ${line}`);
627
+ });
628
+
629
+ process.exit(1);
630
+ } else {
631
+ console.log('āœ… routes.js passed the .f7 import check.');
632
+ }
633
+
634
+ //In routes.js file check static import END
635
+
636
+
637
+
638
+
639
+
640
+
641
+
642
+
643
+
644
+
645
+
646
+
647
+
648
+ // Check and change the "BridgeWebViewClient.java" file START
649
+ /*
650
+ For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
651
+ */
652
+
653
+
654
+ const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
655
+
656
+ // Read the file
657
+ if (!fs.existsSync(bridgeWebViewClientFilePath)) {
658
+ console.error('āŒ Error: BridgeWebViewClient.java not found.');
659
+ process.exit(1);
660
+ }
661
+
662
+ let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
663
+
664
+ // Define old and new code
665
+ const oldCodeStart = `@Override
666
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
667
+ super.onRenderProcessGone(view, detail);
668
+ boolean result = false;
669
+
670
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
671
+ if (webViewListeners != null) {
672
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
673
+ result = listener.onRenderProcessGone(view, detail) || result;
674
+ }
675
+ }
676
+
677
+ return result;
678
+ }`;
679
+
680
+ const newCode = `@Override
681
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
682
+ super.onRenderProcessGone(view, detail);
683
+
684
+ boolean result = false;
685
+
686
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
687
+ if (webViewListeners != null) {
688
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
689
+ result = listener.onRenderProcessGone(view, detail) || result;
690
+ }
691
+ }
692
+
693
+ if (!result) {
694
+ // If no one handled it, handle it ourselves!
695
+
696
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
697
+ if (detail.didCrash()) {
698
+ //Log.e("CapacitorWebView", "WebView crashed internally!");
699
+ } else {
700
+ //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
701
+ }
702
+ }*/
703
+
704
+ view.post(() -> {
705
+ Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
706
+ });
707
+
708
+ view.reload(); // Safely reload WebView
709
+
710
+ return true; // We handled it
711
+ }
712
+
713
+ return result;
714
+ }`;
715
+
716
+ // Step 1: Update method if needed
717
+ let updated = false;
718
+
719
+ if (fileContent.includes(oldCodeStart)) {
720
+ console.log('āœ… Found old onRenderProcessGone method. Replacing it...');
721
+ fileContent = fileContent.replace(oldCodeStart, newCode);
722
+ updated = true;
723
+ } else if (fileContent.includes(newCode)) {
724
+ console.log('ā„¹ļø Method already updated. No changes needed in "BridgeWebViewClient.java".');
725
+ } else {
726
+ console.error('āŒ Error: Neither old nor new code found. Unexpected content.');
727
+ process.exit(1);
728
+ }
729
+
730
+ // Step 2: Check and add import if missing
731
+ const importToast = 'import android.widget.Toast;';
732
+ if (!fileContent.includes(importToast)) {
733
+ console.log('āœ… Adding missing import for Toast...');
734
+ const importRegex = /import\s+[^;]+;/g;
735
+ const matches = [...fileContent.matchAll(importRegex)];
736
+
737
+ if (matches.length > 0) {
738
+ const lastImport = matches[matches.length - 1];
739
+ const insertPosition = lastImport.index + lastImport[0].length;
740
+ fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
741
+ updated = true;
742
+ } else {
743
+ console.error('āŒ Error: No import section found in file.');
744
+ process.exit(1);
745
+ }
746
+ } else {
747
+ console.log('ā„¹ļø Import for Toast already exists. No changes needed.');
748
+ }
749
+
750
+ // Step 3: Save if updated
751
+ if (updated) {
752
+ fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
753
+ console.log('āœ… File updated successfully.');
754
+ } else {
755
+ console.log('ā„¹ļø No changes needed.');
756
+ }
757
+
758
+
759
+
760
+
761
+ // Check and change the "BridgeWebViewClient.java" file END
762
+
763
+
764
+
765
+
766
+
767
+
768
+
769
+
770
+ /*
771
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
772
+
773
+ // Build the path dynamically like you requested
774
+ const gradlePath = path.join(
775
+ process.cwd(),
776
+ 'android',
777
+ 'build.gradle'
778
+ );
779
+
780
+ // Read the existing build.gradle
781
+ let gradleContent = fs.readFileSync(gradlePath, 'utf8');
782
+
783
+ // Add `ext.kotlin_version` if it's not already there
784
+ if (!gradleContent.includes('ext.kotlin_version')) {
785
+ gradleContent = gradleContent.replace(
786
+ /buildscript\s*{/,
787
+ `buildscript {\n ext.kotlin_version = '2.1.0'`
788
+ );
789
+ }
790
+
791
+ // Add Kotlin classpath if it's not already there
792
+ if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
793
+ gradleContent = gradleContent.replace(
794
+ /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
795
+ `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
796
+ );
797
+ }
798
+
799
+ // Write back the modified content
800
+ fs.writeFileSync(gradlePath, gradleContent, 'utf8');
801
+
802
+ console.log('āœ… Kotlin version updated in build.gradle.');
803
+
804
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
805
+ */
806
+
807
+
808
+
809
+
810
+
811
+
812
+
813
+
814
+ let _admobConfig;
815
+
816
+
817
+
818
+ const androidPlatformPath = path.join(process.cwd(), 'android');
819
+ const iosPlatformPath = path.join(process.cwd(), 'ios');
820
+ const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
821
+ const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
822
+ const resourcesPath = path.join(process.cwd(), 'resources', 'res');
823
+ const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
824
+ const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
825
+
826
+ function fileExists(filePath) {
827
+ return fs.existsSync(filePath);
828
+ }
829
+
830
+ function copyFolderSync(source, target) {
831
+ if (!fs.existsSync(target)) {
832
+ fs.mkdirSync(target, { recursive: true });
833
+ }
834
+
835
+ fs.readdirSync(source).forEach(file => {
836
+ const sourceFile = path.join(source, file);
837
+ const targetFile = path.join(target, file);
838
+
839
+ if (fs.lstatSync(sourceFile).isDirectory()) {
840
+ copyFolderSync(sourceFile, targetFile);
841
+ } else {
842
+ fs.copyFileSync(sourceFile, targetFile);
843
+ }
844
+ });
845
+ }
846
+
847
+ function checkAndCopyResources() {
848
+ if (fileExists(resourcesPath)) {
849
+ copyFolderSync(resourcesPath, androidResPath);
850
+ console.log('āœ… Successfully copied resources/res to android/app/src/main/res.');
851
+ } else {
852
+ console.log('resources/res folder not found.');
853
+
854
+ if (fileExists(localNotificationsPluginPath)) {
855
+ throw new Error('āŒ resources/res is required for @capacitor/local-notifications. Stopping execution.');
856
+ }
857
+ }
858
+ }
859
+
860
+
861
+
862
+
863
+
864
+
865
+
866
+
867
+ function getAdMobConfig() {
868
+ if (!fileExists(configPath)) {
869
+ throw new Error('āŒ capacitor.config.json not found. Ensure this is a Capacitor project.');
870
+ }
871
+
872
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
873
+ const admobConfig = config.plugins?.AdMob;
874
+
875
+ if (!admobConfig) {
876
+ throw new Error('āŒ AdMob configuration is missing in capacitor.config.json.');
877
+ }
878
+
879
+ // Default to true if ADMOB_ENABLED is not specified
880
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
881
+
882
+ if (!isEnabled) {
883
+ return { ADMOB_ENABLED: false }; // Skip further validation
884
+ }
885
+
886
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
887
+ throw new Error(' āŒ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
888
+ }
889
+
890
+ return {
891
+ ADMOB_ENABLED: true,
892
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
893
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
894
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
895
+ };
896
+ }
897
+
898
+ function validateAndroidBuildOptions() {
899
+
900
+
901
+ if (!fileExists(configPath)) {
902
+ console.log('āŒ capacitor.config.json not found. Ensure this is a Capacitor project.');
903
+ process.exit(1);
904
+ }
905
+
906
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
907
+
908
+ const targetAppId=config.appId
909
+
910
+ const buildOptions = config.android?.buildOptions;
911
+
912
+ if (!buildOptions) {
913
+ console.log('āŒ Missing android.buildOptions in capacitor.config.json.');
914
+ process.exit(1);
915
+ }
916
+
917
+ const requiredProps = [
918
+ 'keystorePath',
919
+ 'keystorePassword',
920
+ 'keystoreAlias',
921
+ 'keystoreAliasPassword',
922
+ 'releaseType',
923
+ 'signingType'
924
+ ];
925
+
926
+ const missing = requiredProps.filter(prop => !buildOptions[prop]);
927
+
928
+ if (missing.length > 0) {
929
+ console.log('āŒ Missing properties android.buildOptions in capacitor.config.json.');
930
+ process.exit(1);
931
+ }
932
+
933
+
934
+ const keystorePath=buildOptions.keystorePath
935
+ const keyFileName = path.basename(keystorePath);
936
+
937
+
938
+
939
+ const keystoreMap = {
940
+ "gameskey.jks": [
941
+ "com.cube.blaster",
942
+ ],
943
+ "htmleditorkeystoke.jks": [
944
+ "com.HTML.AngularJS.Codeplay",
945
+ "com.html.codeplay.pro",
946
+ "com.bootstrap.code.play",
947
+ "com.kids.learning.master",
948
+ "com.Simple.Barcode.Scanner",
949
+ "com.FAShtmlcssjs.editor"
950
+ ]
951
+ };
952
+
953
+ // find which keystore is required for the given targetAppId
954
+ let requiredKey = "newappskey.jks"; // default
955
+ for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
956
+ if (appIds.includes(targetAppId)) {
957
+ requiredKey = keyFile;
958
+ break;
959
+ }
960
+ }
961
+
962
+ // validate
963
+ if (keyFileName !== requiredKey) {
964
+ console.log(`āŒ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
965
+ process.exit(1);
966
+ }
967
+
968
+
969
+
970
+
971
+
972
+ // optionally return them
973
+ //return buildOptions;
974
+ }
975
+
976
+ function updatePluginXml(admobConfig) {
977
+ if (!fileExists(pluginPath)) {
978
+ console.error(' āŒ plugin.xml not found. Ensure the plugin is installed.');
979
+ return;
980
+ }
981
+
982
+ let pluginContent = fs.readFileSync(pluginPath, 'utf8');
983
+
984
+ pluginContent = pluginContent
985
+ .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
986
+ .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
987
+
988
+ fs.writeFileSync(pluginPath, pluginContent, 'utf8');
989
+ console.log('āœ… AdMob IDs successfully updated in plugin.xml');
990
+ }
991
+
992
+ function updateInfoPlist(admobConfig) {
993
+ if (!fileExists(infoPlistPath)) {
994
+ console.error(' āŒ Info.plist not found. Ensure you have built the iOS project.');
995
+ return;
996
+ }
997
+
998
+ const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
999
+ const plistData = plist.parse(plistContent);
1000
+
1001
+ plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
1002
+ plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
1003
+ plistData.GADDelayAppMeasurementInit = true;
1004
+
1005
+ const updatedPlistContent = plist.build(plistData);
1006
+ fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
1007
+ console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
1008
+ }
1009
+
1010
+
1011
+ try {
1012
+ if (!fileExists(configPath)) {
1013
+ throw new Error(' āŒ capacitor.config.json not found. Skipping setup.');
1014
+ }
1015
+
1016
+ if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
1017
+ throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
1018
+ }
1019
+
1020
+ checkAndCopyResources();
1021
+
1022
+
1023
+
1024
+ _admobConfig = getAdMobConfig();
1025
+
1026
+
1027
+
1028
+
1029
+
1030
+ // Proceed only if ADMOB_ENABLED is true
1031
+ if (_admobConfig.ADMOB_ENABLED) {
1032
+ if (fileExists(androidPlatformPath)) {
1033
+ updatePluginXml(_admobConfig);
1034
+ }
1035
+
1036
+ if (fileExists(iosPlatformPath)) {
1037
+ updateInfoPlist(_admobConfig);
1038
+ }
1039
+ }
1040
+
1041
+
1042
+ } catch (error) {
1043
+ console.error(error.message);
1044
+ process.exit(1); // Stop execution if there's a critical error
1045
+ }
1046
+
1047
+
1048
+
1049
+ validateAndroidBuildOptions();
1050
+
1051
+
1052
+
1053
+
1054
+
1055
+
1056
+ // Check all the codeplays plugins version START
1057
+
1058
+
1059
+ const readline = require('readline');
1060
+
1061
+
1062
+ //const srcDir = path.join(__dirname, 'src');
1063
+ const srcDir = path.join(process.cwd(), 'src');
1064
+ let outdatedPlugins = [];
1065
+
1066
+ function parseVersion(ver) {
1067
+ return ver.split('.').map(n => parseInt(n, 10));
1068
+ }
1069
+
1070
+ function compareVersions(v1, v2) {
1071
+ const [a1, b1] = parseVersion(v1);
1072
+ const [a2, b2] = parseVersion(v2);
1073
+ if (a1 !== a2) return a1 - a2;
1074
+ return b1 - b2;
1075
+ }
1076
+
1077
+ function walkSync(dir, filelist = []) {
1078
+ fs.readdirSync(dir).forEach(file => {
1079
+ const fullPath = path.join(dir, file);
1080
+ const stat = fs.statSync(fullPath);
1081
+ if (stat.isDirectory()) {
1082
+ walkSync(fullPath, filelist);
1083
+ } else {
1084
+ filelist.push(fullPath);
1085
+ }
1086
+ });
1087
+ return filelist;
1088
+ }
1089
+
1090
+
1091
+
1092
+ function getSearchRoot(plugin) {
1093
+ return path.join(srcDir, plugin.baseDir || 'js');
1094
+ }
1095
+
1096
+
1097
+
1098
+
1099
+
1100
+
1101
+
1102
+
1103
+
1104
+
1105
+
1106
+
1107
+
1108
+
1109
+
1110
+
1111
+
1112
+
1113
+
1114
+
1115
+ /*############################################## AUTO DOWNLOAD FROM SERVER START #####################################*/
1116
+
1117
+ // ============================================================
1118
+ // šŸ”„ AUTO PLUGIN UPDATE SYSTEM (MANDATORY UPDATES)
1119
+ // ============================================================
1120
+
1121
+ const https = require("https");
1122
+
1123
+ /**
1124
+ * Check if file exists on server using HEAD request
1125
+ */
1126
+ function urlExists(url) {
1127
+ return new Promise(resolve => {
1128
+ const req = https.request(url, { method: "HEAD" }, res => {
1129
+ resolve(res.statusCode === 200);
1130
+ });
1131
+
1132
+ req.on("error", () => resolve(false));
1133
+ req.end();
1134
+ });
1135
+ }
1136
+
1137
+ /**
1138
+ * Download file from server
1139
+ */
1140
+ function downloadFile(url, dest) {
1141
+ return new Promise((resolve, reject) => {
1142
+ const file = fs.createWriteStream(dest);
1143
+
1144
+ https.get(url, response => {
1145
+ if (response.statusCode !== 200) {
1146
+ reject("Download failed");
1147
+ return;
1148
+ }
1149
+
1150
+ response.pipe(file);
1151
+
1152
+ file.on("finish", () => {
1153
+ file.close(resolve);
1154
+ });
1155
+ }).on("error", err => {
1156
+ fs.unlink(dest, () => {});
1157
+ reject(err);
1158
+ });
1159
+ });
1160
+ }
1161
+
1162
+ /**
1163
+ * Update imports across src folder
1164
+ * Replaces old filename → new filename
1165
+ */
1166
+ /**
1167
+ * Update imports across project
1168
+ * Replaces old filename → new filename
1169
+ */
1170
+
1171
+ const VITE_ALIAS_ONLY = [
1172
+ "common",
1173
+ "admob-emi",
1174
+ "localization",
1175
+ "theme",
1176
+ "certificatejs",
1177
+ "ffmpeg"
1178
+ ];
1179
+
1180
+ function updateImports(oldName, newName) {
1181
+
1182
+ const projectRoot = process.cwd();
1183
+
1184
+ const filesToScan = [
1185
+ path.join(projectRoot, "vite.config.js"),
1186
+ path.join(projectRoot, "vite.config.mjs")
1187
+ ];
1188
+
1189
+ const srcDir = path.join(projectRoot, "src");
1190
+
1191
+ // scan vite config
1192
+ filesToScan.forEach(file => {
1193
+
1194
+ if (!fs.existsSync(file)) return;
1195
+
1196
+ let content = fs.readFileSync(file, "utf8");
1197
+
1198
+ if (content.includes(oldName)) {
1199
+
1200
+ content = content.split(oldName).join(newName);
1201
+
1202
+ fs.writeFileSync(file, content);
1203
+
1204
+ console.log(`āœļø Updated alias in ${path.basename(file)}`);
1205
+ }
1206
+
1207
+ });
1208
+
1209
+ // scan src files
1210
+ function walk(dir) {
1211
+
1212
+ fs.readdirSync(dir).forEach(file => {
1213
+
1214
+ if (["node_modules","android","ios","dist",".git"].includes(file))
1215
+ return;
1216
+
1217
+ const full = path.join(dir, file);
1218
+ const stat = fs.statSync(full);
1219
+
1220
+ if (stat.isDirectory()) {
1221
+ walk(full);
1222
+ }
1223
+
1224
+ else if (
1225
+ (full.endsWith(".js") ||
1226
+ full.endsWith(".f7") ||
1227
+ full.endsWith(".mjs")) &&
1228
+ !full.endsWith(".min.js")
1229
+ ) {
1230
+
1231
+ let content = fs.readFileSync(full, "utf8");
1232
+
1233
+ if (content.includes(oldName)) {
1234
+
1235
+ content = content.split(oldName).join(newName);
1236
+
1237
+ fs.writeFileSync(full, content);
1238
+
1239
+ console.log(`āœļø Updated import in ${path.relative(projectRoot, full)}`);
1240
+ }
1241
+
1242
+ }
1243
+
1244
+ });
1245
+
1246
+ }
1247
+
1248
+ if (fs.existsSync(srcDir)) {
1249
+ walk(srcDir);
1250
+ }
1251
+
1252
+ }
1253
+
1254
+
1255
+ /**
1256
+ * Auto-update a plugin file
1257
+ * Returns TRUE if success
1258
+ * Returns FALSE if fallback to manual needed
1259
+ */
1260
+
1261
+
1262
+ let _serverVersions = null;
1263
+ async function fetchVersions() {
1264
+
1265
+ if (_serverVersions) return _serverVersions;
1266
+
1267
+ return new Promise((resolve) => {
1268
+
1269
+ https.get(
1270
+ "https://htmlcodeplay.com/code-play-plugin/versions.json",
1271
+ { timeout: 5000 },
1272
+ res => {
1273
+
1274
+ let data = "";
1275
+
1276
+ res.on("data", chunk => data += chunk);
1277
+
1278
+ res.on("end", () => {
1279
+
1280
+ try {
1281
+
1282
+ _serverVersions = JSON.parse(data);
1283
+
1284
+ resolve(_serverVersions);
1285
+
1286
+ } catch {
1287
+
1288
+ resolve(null);
1289
+
1290
+ }
1291
+
1292
+ });
1293
+
1294
+ }
1295
+
1296
+ ).on("error", () => resolve(null));
1297
+
1298
+ });
1299
+
1300
+ }
1301
+
1302
+
1303
+
1304
+ async function autoUpdatePlugin(pluginDef, pluginInfo) {
1305
+
1306
+ const versions = await fetchVersions();
1307
+
1308
+ if (!versions) {
1309
+ console.log("āš ļø versions.json not reachable");
1310
+ return false;
1311
+ }
1312
+
1313
+ const oldFullPath = path.join(srcDir, pluginInfo.name);
1314
+ const oldFileName = path.basename(oldFullPath);
1315
+
1316
+ //const oldFileName = path.basename(oldFullPath);
1317
+ const oldVersionFile = oldFileName;
1318
+
1319
+
1320
+ const ext = path.extname(oldFileName); // .js or .less
1321
+ //const baseName = oldFileName.replace(/-\d+\.\d+.*$/, "");
1322
+ const baseName = oldFileName.replace(/-\d+\.\d+.*$/, '').replace(/\.(js|less)$/, '');
1323
+
1324
+ // version lookup key
1325
+ let pluginKey = baseName;
1326
+
1327
+
1328
+ // Only common plugin has js and less variants
1329
+ if (baseName === "common") {
1330
+ if (ext === ".js") pluginKey = "common-js";
1331
+ if (ext === ".less") pluginKey = "common-less";
1332
+ }
1333
+
1334
+ const latestVersion = versions[pluginKey];
1335
+
1336
+ if (!latestVersion) {
1337
+ console.log(`āŒ No version entry for ${baseName}`);
1338
+ return false;
1339
+ }
1340
+
1341
+ // ===============================
1342
+ // FOLDER PLUGIN UPDATE
1343
+ // ===============================
1344
+ if (pluginDef.isFolder) {
1345
+
1346
+ const zipName = `${baseName}-${latestVersion}.zip`;
1347
+ const url = `https://htmlcodeplay.com/code-play-plugin/${zipName}`;
1348
+
1349
+ const destRoot = path.join(srcDir, pluginDef.destDir || pluginDef.baseDir || '');
1350
+ const oldPath = path.join(destRoot, pluginInfo.name);
1351
+ const newPath = path.join(destRoot, `${baseName}-${latestVersion}`);
1352
+
1353
+ if (!(await urlExists(url))) return false;
1354
+
1355
+ fs.rmSync(oldPath, { recursive: true, force: true });
1356
+
1357
+ await downloadAndExtractZip(url, newPath);
1358
+
1359
+ // šŸ”„ FIX: update imports
1360
+ updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1361
+
1362
+ console.log(`āœ… Folder updated → ${baseName}-${latestVersion}`);
1363
+
1364
+ return true;
1365
+ }
1366
+ // ===============================
1367
+ // FILE PLUGIN UPDATE
1368
+ // ===============================
1369
+
1370
+ const pluginDir = path.dirname(oldFullPath);
1371
+
1372
+ // Only this plugin has ios variant
1373
+ const IOS_VARIANT_PLUGINS = [
1374
+ "saveToGalleryAndSaveAnyFile"
1375
+ ];
1376
+
1377
+ /* let variants = [
1378
+ `${baseName}-${latestVersion}.js`
1379
+ ]; */
1380
+
1381
+ //const ext = path.extname(oldFileName);
1382
+ const variants = [`${baseName.replace(ext,'')}-${latestVersion}${ext}`];
1383
+
1384
+
1385
+ if (IOS_VARIANT_PLUGINS.includes(baseName)) {
1386
+ variants.push(`${baseName}-${latestVersion}-ios.js`);
1387
+ }
1388
+
1389
+ let downloaded = [];
1390
+
1391
+ // Download files
1392
+ for (const fileName of variants) {
1393
+
1394
+ const url = `https://htmlcodeplay.com/code-play-plugin/${fileName}`;
1395
+
1396
+ console.log(`šŸ” Checking latest: ${fileName}`);
1397
+
1398
+ if (await urlExists(url)) {
1399
+
1400
+ const destPath = path.join(pluginDir, fileName);
1401
+
1402
+ await downloadFile(url, destPath);
1403
+
1404
+ downloaded.push(fileName);
1405
+
1406
+ console.log(`⬇ Downloaded → ${fileName}`);
1407
+
1408
+ //writeUpdateLine(`Downloaded: ${fileName}`);
1409
+
1410
+ }
1411
+ }
1412
+
1413
+ if (downloaded.length === 0) {
1414
+ console.log(`āŒ No files downloaded for ${baseName}`);
1415
+ return false;
1416
+ }
1417
+
1418
+ // Remove ONLY versioned files (safe)
1419
+ //const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\.js$`);
1420
+ const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\${ext}$`);
1421
+
1422
+ const existingFiles = fs.readdirSync(pluginDir);
1423
+
1424
+ existingFiles.forEach(file => {
1425
+
1426
+ if (
1427
+ versionPattern.test(file) &&
1428
+ !downloaded.includes(file)
1429
+ ) {
1430
+
1431
+ const oldPath = path.join(pluginDir, file);
1432
+
1433
+ fs.unlinkSync(oldPath);
1434
+
1435
+ console.log(`šŸ—‘ Removed old file → ${file}`);
1436
+ //writeUpdateLine(`Removed old file: ${file}`);
1437
+ }
1438
+
1439
+ });
1440
+
1441
+ //const newFileName = `${baseName}-${latestVersion}.js`;
1442
+ const newFileName = `${baseName}-${latestVersion}${ext}`;
1443
+
1444
+ writeUpdateLine(`${oldVersionFile} -> ${newFileName}`);
1445
+
1446
+ updateImports(oldFileName, newFileName);
1447
+ //updateImports(baseName, `${baseName}-${latestVersion}.js`);
1448
+ //updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1449
+
1450
+ //console.log(`āœ… Updated → ${newFileName}`);
1451
+ //console.log(`āœ… Updated → ${baseName}-${latestVersion}`);
1452
+
1453
+ return true;
1454
+ }
1455
+
1456
+
1457
+
1458
+
1459
+ /*############################################## AUTO DOWNLOAD FROM SERVER END #####################################*/
1460
+
1461
+
1462
+
1463
+
1464
+
1465
+
1466
+
1467
+
1468
+
1469
+
1470
+
1471
+
1472
+
1473
+
1474
+
1475
+
1476
+
1477
+
1478
+ async function loadPluginVersions() {
1479
+
1480
+ if (!USE_LIVE_SERVER_VERSION) {
1481
+ console.log("ā„¹ļø Using local plugin versions (offline mode).");
1482
+ return;
1483
+ }
1484
+
1485
+ console.log("🌐 Fetching plugin versions from server...");
1486
+
1487
+ const versions = await fetchVersions();
1488
+
1489
+ if (!versions || typeof versions !== "object") {
1490
+ console.log("āš ļø Server unavailable or invalid versions.json. Falling back to local versions.");
1491
+ return;
1492
+ }
1493
+
1494
+ requiredPlugins.forEach(plugin => {
1495
+
1496
+ if (!plugin.name) return;
1497
+
1498
+ if (versions[plugin.name]) {
1499
+ plugin.minVersion = versions[plugin.name];
1500
+ }
1501
+
1502
+ });
1503
+
1504
+ console.log("āœ… Plugin versions loaded from server.");
1505
+
1506
+ }
1507
+
1508
+
1509
+
1510
+ let hasMandatoryUpdate = false;
1511
+ function checkPlugins() {
1512
+ return new Promise(async (resolve, reject) => {
1513
+ const files = walkSync(srcDir);
1514
+ const outdatedPlugins = [];
1515
+ let hasMandatoryUpdate = false;
1516
+
1517
+ for (const plugin of requiredPlugins) {
1518
+ const searchRoot = getSearchRoot(plugin);
1519
+
1520
+ // ---------- Folder plugins ----------
1521
+ if (plugin.isFolder) {
1522
+ if (!fs.existsSync(searchRoot)) continue;
1523
+
1524
+ const subDirs = fs.readdirSync(searchRoot)
1525
+ .map(name => path.join(searchRoot, name))
1526
+ .filter(p => fs.statSync(p).isDirectory());
1527
+
1528
+ for (const dir of subDirs) {
1529
+ const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
1530
+ const match = plugin.pattern.exec(relativePath);
1531
+
1532
+ if (match) {
1533
+ const currentVersion = match[1];
1534
+
1535
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
1536
+ outdatedPlugins.push({
1537
+ name: relativePath,
1538
+ currentVersion,
1539
+ requiredVersion: plugin.minVersion,
1540
+ mandatoryUpdate: plugin.mandatoryUpdate === true
1541
+ });
1542
+
1543
+ if (plugin.mandatoryUpdate) {
1544
+ hasMandatoryUpdate = true;
1545
+ }
1546
+ }
1547
+ }
1548
+ }
1549
+ continue;
1550
+ }
1551
+
1552
+ // ---------- File plugins ----------
1553
+ const matchedFile = files.find(file =>
1554
+ file.startsWith(searchRoot) && plugin.pattern.test(file)
1555
+ );
1556
+
1557
+ if (matchedFile) {
1558
+ const match = plugin.pattern.exec(matchedFile);
1559
+ if (match) {
1560
+ const currentVersion = match[1];
1561
+ const isBeta = !!match[2];
1562
+
1563
+ const cmp = plugin.pattern.source.includes('beta')
1564
+ ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1565
+ : compareVersions(currentVersion, plugin.minVersion);
1566
+
1567
+ if (cmp < 0) {
1568
+ outdatedPlugins.push({
1569
+ name: path.relative(srcDir, matchedFile),
1570
+ currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1571
+ requiredVersion: plugin.minVersion,
1572
+ mandatoryUpdate: plugin.mandatoryUpdate === true
1573
+ });
1574
+
1575
+ if (plugin.mandatoryUpdate) {
1576
+ hasMandatoryUpdate = true;
1577
+ }
1578
+ }
1579
+ }
1580
+ }
1581
+ }
1582
+
1583
+ // ---------- Result handling ----------
1584
+ if (outdatedPlugins.length > 0) {
1585
+ console.log('\nā— The following plugins are outdated:\n');
1586
+
1587
+ outdatedPlugins.forEach( p => {
1588
+ const tag = p.mandatoryUpdate ? 'šŸ”„ MANDATORY' : '';
1589
+ console.log(
1590
+ ` āš ļø - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion}) ${tag}`
1591
+ );
1592
+ });
1593
+
1594
+ // 🚨 Mandatory update → stop build
1595
+ /* if (hasMandatoryUpdate) {
1596
+ console.log('\n🚫 One or more plugins require a mandatory update.');
1597
+ console.log('āŒ Build cancelled. Please update mandatory plugins and try again.');
1598
+ process.exit(1);
1599
+ } */
1600
+
1601
+
1602
+
1603
+
1604
+
1605
+ if (hasMandatoryUpdate) {
1606
+
1607
+ //--------------------------------------------------
1608
+ // 🚫 AUTO UPDATE DISABLED
1609
+ //--------------------------------------------------
1610
+ if (!ENABLE_AUTO_UPDATE) {
1611
+ console.log("\n🚫 Auto-update disabled.");
1612
+ console.log("āŒ Manual update required.");
1613
+ process.exit(1);
1614
+ }
1615
+
1616
+ //--------------------------------------------------
1617
+ // šŸ”„ AUTO UPDATE ENABLED
1618
+ //--------------------------------------------------
1619
+ console.log("\nšŸ”„ Mandatory plugins outdated. Trying auto-update...\n");
1620
+
1621
+
1622
+
1623
+ let autoFailed = false;
1624
+
1625
+ for (const p of outdatedPlugins.filter(x => x.mandatoryUpdate)) {
1626
+
1627
+ const pluginDef = requiredPlugins.find(def =>
1628
+ def.pattern.test(p.name)
1629
+ );
1630
+
1631
+ if (!pluginDef) continue;
1632
+
1633
+ const success = await autoUpdatePlugin(
1634
+ pluginDef,
1635
+ p
1636
+ );
1637
+
1638
+ if (!success) {
1639
+ autoFailed = true;
1640
+
1641
+ const pluginDef = requiredPlugins.find(def =>
1642
+ def.pattern.test(p.name)
1643
+ );
1644
+
1645
+ console.log(`āŒ Manual update required for ${p.name}`);
1646
+
1647
+ if (pluginDef) {
1648
+ console.log(`šŸ‘‰ Required minimum version: ${pluginDef.minVersion}`);
1649
+ }
1650
+ }
1651
+ }
1652
+
1653
+ // 🚨 Fallback to manual if any failed
1654
+ if (autoFailed) {
1655
+ console.log('\n🚫 One or more plugins require manual update.');
1656
+ console.log('āŒ Build cancelled. Please update mandatory plugins.');
1657
+ process.exit(1);
1658
+ }
1659
+
1660
+ console.log('\nšŸŽ‰ All mandatory plugins auto-updated! Rechecking plugins...\n');
1661
+
1662
+ // Re-run plugin check so outdated list becomes empty
1663
+ await checkPlugins();
1664
+ return;
1665
+ }
1666
+
1667
+
1668
+
1669
+
1670
+
1671
+
1672
+ // Optional updates → ask user
1673
+ const rl = readline.createInterface({
1674
+ input: process.stdin,
1675
+ output: process.stdout
1676
+ });
1677
+
1678
+ rl.question(
1679
+ '\nAre you sure you want to continue without updating these plugins? (y/n): ',
1680
+ answer => {
1681
+ rl.close();
1682
+
1683
+ if (answer.toLowerCase() !== 'y') {
1684
+ console.log('\nāŒ Build cancelled due to outdated plugins.');
1685
+ process.exit(1);
1686
+ } else {
1687
+ console.log('\nāœ… Continuing build...');
1688
+ resolve();
1689
+ }
1690
+ }
1691
+ );
1692
+ } else {
1693
+ console.log('āœ… All plugin versions are up to date.');
1694
+ saveUpdateLogs();
1695
+ resolve();
1696
+ }
1697
+ });
1698
+ }
1699
+
1700
+
1701
+
1702
+
1703
+
1704
+
1705
+
1706
+
1707
+ // Check all the codeplays plugins version START
1708
+
1709
+
1710
+
1711
+
1712
+ // ====================================================================
1713
+ // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
1714
+ // ====================================================================
1715
+
1716
+
1717
+
1718
+ const checkAndupdateDropInViteConfig = () => {
1719
+
1720
+ const possibleFiles = [
1721
+ "vite.config.js",
1722
+ "vite.config.mjs"
1723
+ ];
1724
+
1725
+ // Detect existing config file
1726
+ const viteConfigPath = possibleFiles
1727
+ .map(file => path.join(process.cwd(), file))
1728
+ .find(filePath => fs.existsSync(filePath));
1729
+
1730
+ if (!viteConfigPath) {
1731
+ console.warn("āš ļø No vite config found. Skipping.");
1732
+ return;
1733
+ }
1734
+
1735
+ //console.log("šŸ“„ Using:", viteConfigPath.split("/").pop());
1736
+
1737
+ let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1738
+
1739
+ // Skip if already exists
1740
+ if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1741
+ console.log("ā„¹ļø vite.config.(m)js already Updated. Skipping...");
1742
+ return;
1743
+ }
1744
+
1745
+ console.log("šŸ”§ Adding esbuild.drop ...");
1746
+
1747
+ // If esbuild block exists
1748
+ if (/esbuild\s*:\s*{/.test(viteContent)) {
1749
+ viteContent = viteContent.replace(
1750
+ /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1751
+ (full, inner, indent) => {
1752
+
1753
+ let lines = inner
1754
+ .split("\n")
1755
+ .map(l => l.trim())
1756
+ .filter(Boolean);
1757
+
1758
+ // Fix last comma
1759
+ if (lines.length > 0) {
1760
+ lines[lines.length - 1] =
1761
+ lines[lines.length - 1].replace(/,+$/, "") + ",";
1762
+ }
1763
+
1764
+ // Re-indent
1765
+ lines = lines.map(l => indent + " " + l);
1766
+
1767
+ // Add drop
1768
+ lines.push(`${indent} drop: ['console','debugger'],`);
1769
+
1770
+ return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1771
+ }
1772
+ );
1773
+ }
1774
+
1775
+ // If esbuild missing
1776
+ else {
1777
+ viteContent = viteContent.replace(
1778
+ /export default defineConfig\s*\(\s*{/,
1779
+ m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1780
+ );
1781
+ }
1782
+
1783
+ fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1784
+ console.log("āœ… vite.config.(m)js Updated successfully.");
1785
+ };
1786
+
1787
+
1788
+
1789
+
1790
+
1791
+
1792
+
1793
+
1794
+
1795
+
1796
+ const compareVersion = (v1, v2) => {
1797
+ const a = v1.split(".").map(Number);
1798
+ const b = v2.split(".").map(Number);
1799
+
1800
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
1801
+ const num1 = a[i] || 0;
1802
+ const num2 = b[i] || 0;
1803
+ if (num1 > num2) return 1;
1804
+ if (num1 < num2) return -1;
1805
+ }
1806
+ return 0;
1807
+ };
1808
+
1809
+
1810
+
1811
+
1812
+ const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1813
+
1814
+ const checkAdmobConfigurationProperty=()=>{
1815
+
1816
+
1817
+ if (!_admobConfig.ADMOB_ENABLED)
1818
+ {
1819
+ console.log("ā„¹ļø Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1820
+ return;
1821
+ }
1822
+
1823
+
1824
+ const REQUIRED_CONFIG_KEYS = [
1825
+ "isKidsApp",
1826
+ "isTesting",
1827
+ "isConsoleLogEnabled",
1828
+ "bannerEnabled",
1829
+ "interstitialEnabled",
1830
+ "appOpenEnabled",
1831
+ "rewardVideoEnabled",
1832
+ "rewardInterstitialEnabled",
1833
+ "collapsibleEnabled",
1834
+ "isLandScape",
1835
+ "isOverlappingEnable",
1836
+ "bannerTypeAndroid",
1837
+ "bannerTypeiOS",
1838
+ "bannerTopSpaceColor",
1839
+ "interstitialLoadScreenTextColor",
1840
+ "interstitialLoadScreenBackgroundColor",
1841
+ "beforeBannerSpace",
1842
+ "whenShow",
1843
+ "minimumClick",
1844
+ "interstitialTimeOut",
1845
+ "interstitialFirstTimeOut",
1846
+ "appOpenAdsTimeOut",
1847
+ "maxRetryCount",
1848
+ "retrySecondsAr",
1849
+ "appOpenPerSession",
1850
+ "interstitialPerSession",
1851
+ "appOpenFirstTimeOut"
1852
+ ];
1853
+
1854
+
1855
+
1856
+
1857
+
1858
+ let admobConfigInJson;
1859
+
1860
+ try {
1861
+ admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1862
+ } catch (err) {
1863
+ console.error("āŒ Failed to read admob-ad-configuration.json", err);
1864
+ process.exit(1);
1865
+ }
1866
+
1867
+ // āœ… Validate config object exists
1868
+ if (!admobConfigInJson.config) {
1869
+ console.error('āŒ "config" object is missing in admob-ad-configuration.json');
1870
+ process.exit(1);
1871
+ }
1872
+
1873
+
1874
+ const admobConfigMinVersion="1.5"
1875
+
1876
+ if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1877
+ console.error(`āŒ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1878
+ process.exit(1);
1879
+ }
1880
+
1881
+
1882
+ const config = admobConfigInJson.config;
1883
+
1884
+ // āœ… Find missing properties
1885
+ const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1886
+ key => !(key in config)
1887
+ );
1888
+
1889
+
1890
+
1891
+ if (missingKeys.length > 0) {
1892
+ console.error("āŒ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1893
+
1894
+ missingKeys.forEach(k => console.error(" - " + k));
1895
+ process.exit(1);
1896
+ }
1897
+
1898
+
1899
+ console.log('āœ… All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1900
+ }
1901
+
1902
+
1903
+
1904
+ function ensureGitignoreEntry(entry) {
1905
+ const gitignorePath = path.join(process.cwd(), '.gitignore');
1906
+
1907
+ // If .gitignore doesn't exist, create it
1908
+ if (!fs.existsSync(gitignorePath)) {
1909
+ fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
1910
+ console.log(`āœ… .gitignore created and added: ${entry}`);
1911
+ return;
1912
+ }
1913
+
1914
+ const content = fs.readFileSync(gitignorePath, 'utf8');
1915
+
1916
+ // Normalize lines (trim + remove trailing slashes for comparison)
1917
+ const lines = content
1918
+ .split(/\r?\n/)
1919
+ .map(l => l.trim());
1920
+
1921
+ const normalizedEntry = entry.replace(/\/$/, '');
1922
+
1923
+ const exists = lines.some(
1924
+ line => line.replace(/\/$/, '') === normalizedEntry
1925
+ );
1926
+
1927
+ if (exists) {
1928
+ console.log(`ā„¹ļø .gitignore already contains: ${entry}`);
1929
+ return;
1930
+ }
1931
+
1932
+ // Ensure file ends with newline
1933
+ const separator = content.endsWith('\n') ? '' : '\n';
1934
+
1935
+ fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
1936
+ console.log(`āœ… Added to .gitignore: ${entry}`);
1937
+ }
1938
+
1939
+
1940
+ ensureGitignoreEntry('buildCodeplay/');
1941
+
1942
+
1943
+ // Run the validation
1944
+ (async () => {
1945
+
1946
+ await loadPluginVersions(); // šŸ”„ NEW
1947
+
1948
+ await checkPlugins();
1949
+ checkAndupdateDropInViteConfig();
1950
+ checkAdmobConfigurationProperty()
1951
+ })();
1952
+
1953
+
1954
+ // ======================================================
1955
+ // Validate theme folder location (src/js/theme is NOT allowed)
1956
+ // ======================================================
1957
+
1958
+ function validateThemeFolderLocation() {
1959
+ const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
1960
+ const newThemePath = path.join(process.cwd(), 'src', 'theme');
1961
+
1962
+ // āŒ Block old structure
1963
+ if (fs.existsSync(oldThemePath)) {
1964
+ console.error(
1965
+ '\nāŒ INVALID PROJECT STRUCTURE DETECTED\n' +
1966
+ '--------------------------------------------------\n' +
1967
+ 'The "theme" folder must NOT be inside:\n' +
1968
+ ' src/js/theme\n\n' +
1969
+ 'āœ… Correct location is:\n' +
1970
+ ' src/theme\n\n' +
1971
+ 'šŸ›‘ Please move the folder and re-run the build.\n'
1972
+ );
1973
+ process.exit(1);
1974
+ }
1975
+
1976
+ // āš ļø Optional warning if new theme folder is missing
1977
+ if (!fs.existsSync(newThemePath)) {
1978
+ console.warn(
1979
+ '\nāš ļø WARNING: "src/theme" folder not found.\n' +
1980
+ 'If your app uses themes, please ensure it exists.\n'
1981
+ );
1982
+ } else {
1983
+ console.log('āœ… Theme folder structure validated (src/theme).');
1984
+ }
1985
+ }
1986
+ validateThemeFolderLocation()
1987
+
1988
+
1989
+
1990
+ const validateAndRestoreSignDetails=()=>{
1991
+
1992
+ // Read config file
1993
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1994
+
1995
+ // Ensure android and buildOptions exist
1996
+ if (!config.android) config.android = {};
1997
+ if (!config.android.buildOptions) config.android.buildOptions = {};
1998
+
1999
+ // Update only if changed
2000
+ let updated = false;
2001
+
2002
+ if (config.android.buildOptions.releaseType !== 'AAB') {
2003
+ config.android.buildOptions.releaseType = 'AAB';
2004
+ updated = true;
2005
+ }
2006
+
2007
+ if (config.android.buildOptions.signingType !== 'jarsigner') {
2008
+ config.android.buildOptions.signingType = 'jarsigner';
2009
+ updated = true;
2010
+ }
2011
+
2012
+ // Write back only if modified
2013
+ if (updated) {
2014
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
2015
+ console.log('capacitor.config.json updated successfully.');
2016
+ } else {
2017
+ console.log('No changes needed.');
2018
+ }
2019
+
2020
+ }
2021
+
2022
+ validateAndRestoreSignDetails()
2023
+
2024
+
2025
+ /*
2026
+ Release Notes
2027
+
2028
+ 5.1
2029
+ Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
2030
+
2030
2031
  */