codeplay-common 3.1.5 → 3.1.6

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,2035 +1,2035 @@
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
- updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1360
-
1361
- // āœ… ADD THIS
1362
- writeUpdateLine(`${pluginInfo.name} -> ${baseName}-${latestVersion}`);
1363
-
1364
- console.log(`āœ… Folder updated → ${baseName}-${latestVersion}`);
1365
-
1366
- return true;
1367
- }
1368
- // ===============================
1369
- // FILE PLUGIN UPDATE
1370
- // ===============================
1371
-
1372
- const pluginDir = path.dirname(oldFullPath);
1373
-
1374
- // Only this plugin has ios variant
1375
- const IOS_VARIANT_PLUGINS = [
1376
- "saveToGalleryAndSaveAnyFile"
1377
- ];
1378
-
1379
- /* let variants = [
1380
- `${baseName}-${latestVersion}.js`
1381
- ]; */
1382
-
1383
- //const ext = path.extname(oldFileName);
1384
- const variants = [`${baseName.replace(ext,'')}-${latestVersion}${ext}`];
1385
-
1386
-
1387
- if (IOS_VARIANT_PLUGINS.includes(baseName)) {
1388
- variants.push(`${baseName}-${latestVersion}-ios.js`);
1389
- }
1390
-
1391
- let downloaded = [];
1392
-
1393
- // Download files
1394
- for (const fileName of variants) {
1395
-
1396
- const url = `https://htmlcodeplay.com/code-play-plugin/${fileName}`;
1397
-
1398
- console.log(`šŸ” Checking latest: ${fileName}`);
1399
-
1400
- if (await urlExists(url)) {
1401
-
1402
- const destPath = path.join(pluginDir, fileName);
1403
-
1404
- await downloadFile(url, destPath);
1405
-
1406
- downloaded.push(fileName);
1407
-
1408
- console.log(`⬇ Downloaded → ${fileName}`);
1409
-
1410
- //writeUpdateLine(`Downloaded: ${fileName}`);
1411
-
1412
- }
1413
- }
1414
-
1415
- if (downloaded.length === 0) {
1416
- console.log(`āŒ No files downloaded for ${baseName}`);
1417
- return false;
1418
- }
1419
-
1420
- // Remove ONLY versioned files (safe)
1421
- //const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\.js$`);
1422
- const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\${ext}$`);
1423
-
1424
- const existingFiles = fs.readdirSync(pluginDir);
1425
-
1426
- existingFiles.forEach(file => {
1427
-
1428
- if (
1429
- versionPattern.test(file) &&
1430
- !downloaded.includes(file)
1431
- ) {
1432
-
1433
- const oldPath = path.join(pluginDir, file);
1434
-
1435
- fs.unlinkSync(oldPath);
1436
-
1437
- console.log(`šŸ—‘ Removed old file → ${file}`);
1438
- //writeUpdateLine(`Removed old file: ${file}`);
1439
- }
1440
-
1441
- });
1442
-
1443
- //const newFileName = `${baseName}-${latestVersion}.js`;
1444
- const newFileName = `${baseName}-${latestVersion}${ext}`;
1445
-
1446
- writeUpdateLine(`${oldVersionFile} -> ${newFileName}`);
1447
-
1448
- updateImports(oldFileName, newFileName);
1449
- //updateImports(baseName, `${baseName}-${latestVersion}.js`);
1450
- //updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1451
-
1452
- //console.log(`āœ… Updated → ${newFileName}`);
1453
- //console.log(`āœ… Updated → ${baseName}-${latestVersion}`);
1454
-
1455
- return true;
1456
- }
1457
-
1458
-
1459
-
1460
-
1461
- /*############################################## AUTO DOWNLOAD FROM SERVER END #####################################*/
1462
-
1463
-
1464
-
1465
-
1466
-
1467
-
1468
-
1469
-
1470
-
1471
-
1472
-
1473
-
1474
-
1475
-
1476
-
1477
-
1478
-
1479
-
1480
- async function loadPluginVersions() {
1481
-
1482
- if (!USE_LIVE_SERVER_VERSION) {
1483
- console.log("ā„¹ļø Using local plugin versions (offline mode).");
1484
- return;
1485
- }
1486
-
1487
- console.log("🌐 Fetching plugin versions from server...");
1488
-
1489
- const versions = await fetchVersions();
1490
-
1491
- if (!versions || typeof versions !== "object") {
1492
- console.log("āš ļø Server unavailable or invalid versions.json. Falling back to local versions.");
1493
- return;
1494
- }
1495
-
1496
- requiredPlugins.forEach(plugin => {
1497
-
1498
- if (!plugin.name) return;
1499
-
1500
- if (versions[plugin.name]) {
1501
- plugin.minVersion = versions[plugin.name];
1502
- }
1503
-
1504
- });
1505
-
1506
- console.log("āœ… Plugin versions loaded from server.");
1507
-
1508
- }
1509
-
1510
-
1511
-
1512
- let hasMandatoryUpdate = false;
1513
- function checkPlugins() {
1514
- return new Promise(async (resolve, reject) => {
1515
- const files = walkSync(srcDir);
1516
- const outdatedPlugins = [];
1517
- let hasMandatoryUpdate = false;
1518
-
1519
- for (const plugin of requiredPlugins) {
1520
- const searchRoot = getSearchRoot(plugin);
1521
-
1522
- // ---------- Folder plugins ----------
1523
- if (plugin.isFolder) {
1524
- if (!fs.existsSync(searchRoot)) continue;
1525
-
1526
- const subDirs = fs.readdirSync(searchRoot)
1527
- .map(name => path.join(searchRoot, name))
1528
- .filter(p => fs.statSync(p).isDirectory());
1529
-
1530
- for (const dir of subDirs) {
1531
- const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
1532
- const match = plugin.pattern.exec(relativePath);
1533
-
1534
- if (match) {
1535
- const currentVersion = match[1];
1536
-
1537
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
1538
- outdatedPlugins.push({
1539
- name: relativePath,
1540
- currentVersion,
1541
- requiredVersion: plugin.minVersion,
1542
- mandatoryUpdate: plugin.mandatoryUpdate === true
1543
- });
1544
-
1545
- if (plugin.mandatoryUpdate) {
1546
- hasMandatoryUpdate = true;
1547
- }
1548
- }
1549
- }
1550
- }
1551
- continue;
1552
- }
1553
-
1554
- // ---------- File plugins ----------
1555
- const matchedFile = files.find(file =>
1556
- file.startsWith(searchRoot) && plugin.pattern.test(file)
1557
- );
1558
-
1559
- if (matchedFile) {
1560
- const match = plugin.pattern.exec(matchedFile);
1561
- if (match) {
1562
- const currentVersion = match[1];
1563
- const isBeta = !!match[2];
1564
-
1565
- const cmp = plugin.pattern.source.includes('beta')
1566
- ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1567
- : compareVersions(currentVersion, plugin.minVersion);
1568
-
1569
- if (cmp < 0) {
1570
- outdatedPlugins.push({
1571
- name: path.relative(srcDir, matchedFile),
1572
- currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1573
- requiredVersion: plugin.minVersion,
1574
- mandatoryUpdate: plugin.mandatoryUpdate === true
1575
- });
1576
-
1577
- if (plugin.mandatoryUpdate) {
1578
- hasMandatoryUpdate = true;
1579
- }
1580
- }
1581
- }
1582
- }
1583
- }
1584
-
1585
- // ---------- Result handling ----------
1586
- if (outdatedPlugins.length > 0) {
1587
- console.log('\nā— The following plugins are outdated:\n');
1588
-
1589
- outdatedPlugins.forEach( p => {
1590
- const tag = p.mandatoryUpdate ? 'šŸ”„ MANDATORY' : '';
1591
- console.log(
1592
- ` āš ļø - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion}) ${tag}`
1593
- );
1594
- });
1595
-
1596
- // 🚨 Mandatory update → stop build
1597
- /* if (hasMandatoryUpdate) {
1598
- console.log('\n🚫 One or more plugins require a mandatory update.');
1599
- console.log('āŒ Build cancelled. Please update mandatory plugins and try again.');
1600
- process.exit(1);
1601
- } */
1602
-
1603
-
1604
-
1605
-
1606
-
1607
- if (hasMandatoryUpdate) {
1608
-
1609
- //--------------------------------------------------
1610
- // 🚫 AUTO UPDATE DISABLED
1611
- //--------------------------------------------------
1612
- if (!ENABLE_AUTO_UPDATE) {
1613
- console.log("\n🚫 Auto-update disabled.");
1614
- console.log("āŒ Manual update required.");
1615
- process.exit(1);
1616
- }
1617
-
1618
- //--------------------------------------------------
1619
- // šŸ”„ AUTO UPDATE ENABLED
1620
- //--------------------------------------------------
1621
- console.log("\nšŸ”„ Mandatory plugins outdated. Trying auto-update...\n");
1622
-
1623
-
1624
-
1625
- let autoFailed = false;
1626
-
1627
- for (const p of outdatedPlugins.filter(x => x.mandatoryUpdate)) {
1628
-
1629
- const pluginDef = requiredPlugins.find(def =>
1630
- def.pattern.test(p.name)
1631
- );
1632
-
1633
- if (!pluginDef) continue;
1634
-
1635
- const success = await autoUpdatePlugin(
1636
- pluginDef,
1637
- p
1638
- );
1639
-
1640
- if (!success) {
1641
- autoFailed = true;
1642
-
1643
- const pluginDef = requiredPlugins.find(def =>
1644
- def.pattern.test(p.name)
1645
- );
1646
-
1647
- console.log(`āŒ Manual update required for ${p.name}`);
1648
-
1649
- if (pluginDef) {
1650
- console.log(`šŸ‘‰ Required minimum version: ${pluginDef.minVersion}`);
1651
- }
1652
- }
1653
- }
1654
-
1655
- // 🚨 Fallback to manual if any failed
1656
- if (autoFailed) {
1657
- console.log('\n🚫 One or more plugins require manual update.');
1658
- console.log('āŒ Build cancelled. Please update mandatory plugins.');
1659
- process.exit(1);
1660
- }
1661
-
1662
- console.log('\nšŸŽ‰ All mandatory plugins auto-updated! Rechecking plugins...\n');
1663
-
1664
- // Re-run plugin check so outdated list becomes empty
1665
- await checkPlugins();
1666
- return;
1667
- }
1668
-
1669
-
1670
-
1671
-
1672
-
1673
-
1674
- // Optional updates → ask user
1675
- const rl = readline.createInterface({
1676
- input: process.stdin,
1677
- output: process.stdout
1678
- });
1679
-
1680
- rl.question(
1681
- '\nAre you sure you want to continue without updating these plugins? (y/n): ',
1682
- answer => {
1683
- rl.close();
1684
-
1685
- if (answer.toLowerCase() !== 'y') {
1686
- console.log('\nāŒ Build cancelled due to outdated plugins.');
1687
- process.exit(1);
1688
- } else {
1689
- console.log('\nāœ… Continuing build...');
1690
- resolve();
1691
- }
1692
- }
1693
- );
1694
- } else {
1695
- console.log('āœ… All plugin versions are up to date.');
1696
- saveUpdateLogs();
1697
- resolve();
1698
- }
1699
- });
1700
- }
1701
-
1702
-
1703
-
1704
-
1705
-
1706
-
1707
-
1708
-
1709
- // Check all the codeplays plugins version START
1710
-
1711
-
1712
-
1713
-
1714
- // ====================================================================
1715
- // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
1716
- // ====================================================================
1717
-
1718
-
1719
-
1720
- const checkAndupdateDropInViteConfig = () => {
1721
-
1722
- const possibleFiles = [
1723
- "vite.config.js",
1724
- "vite.config.mjs"
1725
- ];
1726
-
1727
- // Detect existing config file
1728
- const viteConfigPath = possibleFiles
1729
- .map(file => path.join(process.cwd(), file))
1730
- .find(filePath => fs.existsSync(filePath));
1731
-
1732
- if (!viteConfigPath) {
1733
- console.warn("āš ļø No vite config found. Skipping.");
1734
- return;
1735
- }
1736
-
1737
- //console.log("šŸ“„ Using:", viteConfigPath.split("/").pop());
1738
-
1739
- let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1740
-
1741
- // Skip if already exists
1742
- if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1743
- console.log("ā„¹ļø vite.config.(m)js already Updated. Skipping...");
1744
- return;
1745
- }
1746
-
1747
- console.log("šŸ”§ Adding esbuild.drop ...");
1748
-
1749
- // If esbuild block exists
1750
- if (/esbuild\s*:\s*{/.test(viteContent)) {
1751
- viteContent = viteContent.replace(
1752
- /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1753
- (full, inner, indent) => {
1754
-
1755
- let lines = inner
1756
- .split("\n")
1757
- .map(l => l.trim())
1758
- .filter(Boolean);
1759
-
1760
- // Fix last comma
1761
- if (lines.length > 0) {
1762
- lines[lines.length - 1] =
1763
- lines[lines.length - 1].replace(/,+$/, "") + ",";
1764
- }
1765
-
1766
- // Re-indent
1767
- lines = lines.map(l => indent + " " + l);
1768
-
1769
- // Add drop
1770
- lines.push(`${indent} drop: ['console','debugger'],`);
1771
-
1772
- return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1773
- }
1774
- );
1775
- }
1776
-
1777
- // If esbuild missing
1778
- else {
1779
- viteContent = viteContent.replace(
1780
- /export default defineConfig\s*\(\s*{/,
1781
- m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1782
- );
1783
- }
1784
-
1785
- fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1786
- console.log("āœ… vite.config.(m)js Updated successfully.");
1787
- };
1788
-
1789
-
1790
-
1791
-
1792
-
1793
-
1794
-
1795
-
1796
-
1797
-
1798
- const compareVersion = (v1, v2) => {
1799
- const a = v1.split(".").map(Number);
1800
- const b = v2.split(".").map(Number);
1801
-
1802
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
1803
- const num1 = a[i] || 0;
1804
- const num2 = b[i] || 0;
1805
- if (num1 > num2) return 1;
1806
- if (num1 < num2) return -1;
1807
- }
1808
- return 0;
1809
- };
1810
-
1811
-
1812
-
1813
-
1814
- const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1815
-
1816
- const checkAdmobConfigurationProperty=()=>{
1817
-
1818
-
1819
- if (!_admobConfig.ADMOB_ENABLED)
1820
- {
1821
- console.log("ā„¹ļø Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1822
- return;
1823
- }
1824
-
1825
-
1826
- const REQUIRED_CONFIG_KEYS = [
1827
- "isKidsApp",
1828
- "isTesting",
1829
- "isConsoleLogEnabled",
1830
- "bannerEnabled",
1831
- "interstitialEnabled",
1832
- "appOpenEnabled",
1833
- "rewardVideoEnabled",
1834
- "rewardInterstitialEnabled",
1835
- "collapsibleEnabled",
1836
- "isLandScape",
1837
- "isOverlappingEnable",
1838
- "bannerTypeAndroid",
1839
- "bannerTypeiOS",
1840
- "bannerTopSpaceColor",
1841
- "interstitialLoadScreenTextColor",
1842
- "interstitialLoadScreenBackgroundColor",
1843
- "beforeBannerSpace",
1844
- "whenShow",
1845
- "minimumClick",
1846
- "interstitialTimeOut",
1847
- "interstitialFirstTimeOut",
1848
- "appOpenAdsTimeOut",
1849
- "maxRetryCount",
1850
- "retrySecondsAr",
1851
- "appOpenPerSession",
1852
- "interstitialPerSession",
1853
- "appOpenFirstTimeOut"
1854
- ];
1855
-
1856
-
1857
-
1858
-
1859
-
1860
- let admobConfigInJson;
1861
-
1862
- try {
1863
- admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1864
- } catch (err) {
1865
- console.error("āŒ Failed to read admob-ad-configuration.json", err);
1866
- process.exit(1);
1867
- }
1868
-
1869
- // āœ… Validate config object exists
1870
- if (!admobConfigInJson.config) {
1871
- console.error('āŒ "config" object is missing in admob-ad-configuration.json');
1872
- process.exit(1);
1873
- }
1874
-
1875
-
1876
- const admobConfigMinVersion="1.5"
1877
-
1878
- if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1879
- console.error(`āŒ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1880
- process.exit(1);
1881
- }
1882
-
1883
-
1884
- const config = admobConfigInJson.config;
1885
-
1886
- // āœ… Find missing properties
1887
- const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1888
- key => !(key in config)
1889
- );
1890
-
1891
-
1892
-
1893
- if (missingKeys.length > 0) {
1894
- console.error("āŒ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1895
-
1896
- missingKeys.forEach(k => console.error(" - " + k));
1897
- process.exit(1);
1898
- }
1899
-
1900
-
1901
- console.log('āœ… All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1902
- }
1903
-
1904
-
1905
-
1906
- function ensureGitignoreEntry(entry) {
1907
- const gitignorePath = path.join(process.cwd(), '.gitignore');
1908
-
1909
- // If .gitignore doesn't exist, create it
1910
- if (!fs.existsSync(gitignorePath)) {
1911
- fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
1912
- console.log(`āœ… .gitignore created and added: ${entry}`);
1913
- return;
1914
- }
1915
-
1916
- const content = fs.readFileSync(gitignorePath, 'utf8');
1917
-
1918
- // Normalize lines (trim + remove trailing slashes for comparison)
1919
- const lines = content
1920
- .split(/\r?\n/)
1921
- .map(l => l.trim());
1922
-
1923
- const normalizedEntry = entry.replace(/\/$/, '');
1924
-
1925
- const exists = lines.some(
1926
- line => line.replace(/\/$/, '') === normalizedEntry
1927
- );
1928
-
1929
- if (exists) {
1930
- console.log(`ā„¹ļø .gitignore already contains: ${entry}`);
1931
- return;
1932
- }
1933
-
1934
- // Ensure file ends with newline
1935
- const separator = content.endsWith('\n') ? '' : '\n';
1936
-
1937
- fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
1938
- console.log(`āœ… Added to .gitignore: ${entry}`);
1939
- }
1940
-
1941
-
1942
- ensureGitignoreEntry('buildCodeplay/');
1943
-
1944
-
1945
- // Run the validation
1946
- (async () => {
1947
-
1948
- await loadPluginVersions(); // šŸ”„ NEW
1949
-
1950
- await checkPlugins();
1951
- checkAndupdateDropInViteConfig();
1952
- checkAdmobConfigurationProperty()
1953
- })();
1954
-
1955
-
1956
- // ======================================================
1957
- // Validate theme folder location (src/js/theme is NOT allowed)
1958
- // ======================================================
1959
-
1960
- function validateThemeFolderLocation() {
1961
- const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
1962
- const newThemePath = path.join(process.cwd(), 'src', 'theme');
1963
-
1964
- // āŒ Block old structure
1965
- if (fs.existsSync(oldThemePath)) {
1966
- console.error(
1967
- '\nāŒ INVALID PROJECT STRUCTURE DETECTED\n' +
1968
- '--------------------------------------------------\n' +
1969
- 'The "theme" folder must NOT be inside:\n' +
1970
- ' src/js/theme\n\n' +
1971
- 'āœ… Correct location is:\n' +
1972
- ' src/theme\n\n' +
1973
- 'šŸ›‘ Please move the folder and re-run the build.\n'
1974
- );
1975
- process.exit(1);
1976
- }
1977
-
1978
- // āš ļø Optional warning if new theme folder is missing
1979
- if (!fs.existsSync(newThemePath)) {
1980
- console.warn(
1981
- '\nāš ļø WARNING: "src/theme" folder not found.\n' +
1982
- 'If your app uses themes, please ensure it exists.\n'
1983
- );
1984
- } else {
1985
- console.log('āœ… Theme folder structure validated (src/theme).');
1986
- }
1987
- }
1988
- validateThemeFolderLocation()
1989
-
1990
-
1991
-
1992
- const validateAndRestoreSignDetails=()=>{
1993
-
1994
- // Read config file
1995
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1996
-
1997
- // Ensure android and buildOptions exist
1998
- if (!config.android) config.android = {};
1999
- if (!config.android.buildOptions) config.android.buildOptions = {};
2000
-
2001
- // Update only if changed
2002
- let updated = false;
2003
-
2004
- if (config.android.buildOptions.releaseType !== 'AAB') {
2005
- config.android.buildOptions.releaseType = 'AAB';
2006
- updated = true;
2007
- }
2008
-
2009
- if (config.android.buildOptions.signingType !== 'jarsigner') {
2010
- config.android.buildOptions.signingType = 'jarsigner';
2011
- updated = true;
2012
- }
2013
-
2014
- // Write back only if modified
2015
- if (updated) {
2016
- fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
2017
- console.log('capacitor.config.json updated successfully.');
2018
- } else {
2019
- console.log('No changes needed.');
2020
- }
2021
-
2022
- }
2023
-
2024
- validateAndRestoreSignDetails()
2025
-
2026
-
2027
- execSync('node buildCodeplay/fix-onesignal-plugin.js', { stdio: 'inherit' });
2028
-
2029
- /*
2030
- Release Notes
2031
-
2032
- 5.1
2033
- Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
2034
-
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
+ updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1360
+
1361
+ // āœ… ADD THIS
1362
+ writeUpdateLine(`${pluginInfo.name} -> ${baseName}-${latestVersion}`);
1363
+
1364
+ console.log(`āœ… Folder updated → ${baseName}-${latestVersion}`);
1365
+
1366
+ return true;
1367
+ }
1368
+ // ===============================
1369
+ // FILE PLUGIN UPDATE
1370
+ // ===============================
1371
+
1372
+ const pluginDir = path.dirname(oldFullPath);
1373
+
1374
+ // Only this plugin has ios variant
1375
+ const IOS_VARIANT_PLUGINS = [
1376
+ "saveToGalleryAndSaveAnyFile"
1377
+ ];
1378
+
1379
+ /* let variants = [
1380
+ `${baseName}-${latestVersion}.js`
1381
+ ]; */
1382
+
1383
+ //const ext = path.extname(oldFileName);
1384
+ const variants = [`${baseName.replace(ext,'')}-${latestVersion}${ext}`];
1385
+
1386
+
1387
+ if (IOS_VARIANT_PLUGINS.includes(baseName)) {
1388
+ variants.push(`${baseName}-${latestVersion}-ios.js`);
1389
+ }
1390
+
1391
+ let downloaded = [];
1392
+
1393
+ // Download files
1394
+ for (const fileName of variants) {
1395
+
1396
+ const url = `https://htmlcodeplay.com/code-play-plugin/${fileName}`;
1397
+
1398
+ console.log(`šŸ” Checking latest: ${fileName}`);
1399
+
1400
+ if (await urlExists(url)) {
1401
+
1402
+ const destPath = path.join(pluginDir, fileName);
1403
+
1404
+ await downloadFile(url, destPath);
1405
+
1406
+ downloaded.push(fileName);
1407
+
1408
+ console.log(`⬇ Downloaded → ${fileName}`);
1409
+
1410
+ //writeUpdateLine(`Downloaded: ${fileName}`);
1411
+
1412
+ }
1413
+ }
1414
+
1415
+ if (downloaded.length === 0) {
1416
+ console.log(`āŒ No files downloaded for ${baseName}`);
1417
+ return false;
1418
+ }
1419
+
1420
+ // Remove ONLY versioned files (safe)
1421
+ //const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\.js$`);
1422
+ const versionPattern = new RegExp(`^${baseName}-\\d+\\.\\d+(-ios)?\\${ext}$`);
1423
+
1424
+ const existingFiles = fs.readdirSync(pluginDir);
1425
+
1426
+ existingFiles.forEach(file => {
1427
+
1428
+ if (
1429
+ versionPattern.test(file) &&
1430
+ !downloaded.includes(file)
1431
+ ) {
1432
+
1433
+ const oldPath = path.join(pluginDir, file);
1434
+
1435
+ fs.unlinkSync(oldPath);
1436
+
1437
+ console.log(`šŸ—‘ Removed old file → ${file}`);
1438
+ //writeUpdateLine(`Removed old file: ${file}`);
1439
+ }
1440
+
1441
+ });
1442
+
1443
+ //const newFileName = `${baseName}-${latestVersion}.js`;
1444
+ const newFileName = `${baseName}-${latestVersion}${ext}`;
1445
+
1446
+ writeUpdateLine(`${oldVersionFile} -> ${newFileName}`);
1447
+
1448
+ updateImports(oldFileName, newFileName);
1449
+ //updateImports(baseName, `${baseName}-${latestVersion}.js`);
1450
+ //updateImports(pluginInfo.name, `${baseName}-${latestVersion}`);
1451
+
1452
+ //console.log(`āœ… Updated → ${newFileName}`);
1453
+ //console.log(`āœ… Updated → ${baseName}-${latestVersion}`);
1454
+
1455
+ return true;
1456
+ }
1457
+
1458
+
1459
+
1460
+
1461
+ /*############################################## AUTO DOWNLOAD FROM SERVER END #####################################*/
1462
+
1463
+
1464
+
1465
+
1466
+
1467
+
1468
+
1469
+
1470
+
1471
+
1472
+
1473
+
1474
+
1475
+
1476
+
1477
+
1478
+
1479
+
1480
+ async function loadPluginVersions() {
1481
+
1482
+ if (!USE_LIVE_SERVER_VERSION) {
1483
+ console.log("ā„¹ļø Using local plugin versions (offline mode).");
1484
+ return;
1485
+ }
1486
+
1487
+ console.log("🌐 Fetching plugin versions from server...");
1488
+
1489
+ const versions = await fetchVersions();
1490
+
1491
+ if (!versions || typeof versions !== "object") {
1492
+ console.log("āš ļø Server unavailable or invalid versions.json. Falling back to local versions.");
1493
+ return;
1494
+ }
1495
+
1496
+ requiredPlugins.forEach(plugin => {
1497
+
1498
+ if (!plugin.name) return;
1499
+
1500
+ if (versions[plugin.name]) {
1501
+ plugin.minVersion = versions[plugin.name];
1502
+ }
1503
+
1504
+ });
1505
+
1506
+ console.log("āœ… Plugin versions loaded from server.");
1507
+
1508
+ }
1509
+
1510
+
1511
+
1512
+ let hasMandatoryUpdate = false;
1513
+ function checkPlugins() {
1514
+ return new Promise(async (resolve, reject) => {
1515
+ const files = walkSync(srcDir);
1516
+ const outdatedPlugins = [];
1517
+ let hasMandatoryUpdate = false;
1518
+
1519
+ for (const plugin of requiredPlugins) {
1520
+ const searchRoot = getSearchRoot(plugin);
1521
+
1522
+ // ---------- Folder plugins ----------
1523
+ if (plugin.isFolder) {
1524
+ if (!fs.existsSync(searchRoot)) continue;
1525
+
1526
+ const subDirs = fs.readdirSync(searchRoot)
1527
+ .map(name => path.join(searchRoot, name))
1528
+ .filter(p => fs.statSync(p).isDirectory());
1529
+
1530
+ for (const dir of subDirs) {
1531
+ const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
1532
+ const match = plugin.pattern.exec(relativePath);
1533
+
1534
+ if (match) {
1535
+ const currentVersion = match[1];
1536
+
1537
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
1538
+ outdatedPlugins.push({
1539
+ name: relativePath,
1540
+ currentVersion,
1541
+ requiredVersion: plugin.minVersion,
1542
+ mandatoryUpdate: plugin.mandatoryUpdate === true
1543
+ });
1544
+
1545
+ if (plugin.mandatoryUpdate) {
1546
+ hasMandatoryUpdate = true;
1547
+ }
1548
+ }
1549
+ }
1550
+ }
1551
+ continue;
1552
+ }
1553
+
1554
+ // ---------- File plugins ----------
1555
+ const matchedFile = files.find(file =>
1556
+ file.startsWith(searchRoot) && plugin.pattern.test(file)
1557
+ );
1558
+
1559
+ if (matchedFile) {
1560
+ const match = plugin.pattern.exec(matchedFile);
1561
+ if (match) {
1562
+ const currentVersion = match[1];
1563
+ const isBeta = !!match[2];
1564
+
1565
+ const cmp = plugin.pattern.source.includes('beta')
1566
+ ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1567
+ : compareVersions(currentVersion, plugin.minVersion);
1568
+
1569
+ if (cmp < 0) {
1570
+ outdatedPlugins.push({
1571
+ name: path.relative(srcDir, matchedFile),
1572
+ currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1573
+ requiredVersion: plugin.minVersion,
1574
+ mandatoryUpdate: plugin.mandatoryUpdate === true
1575
+ });
1576
+
1577
+ if (plugin.mandatoryUpdate) {
1578
+ hasMandatoryUpdate = true;
1579
+ }
1580
+ }
1581
+ }
1582
+ }
1583
+ }
1584
+
1585
+ // ---------- Result handling ----------
1586
+ if (outdatedPlugins.length > 0) {
1587
+ console.log('\nā— The following plugins are outdated:\n');
1588
+
1589
+ outdatedPlugins.forEach( p => {
1590
+ const tag = p.mandatoryUpdate ? 'šŸ”„ MANDATORY' : '';
1591
+ console.log(
1592
+ ` āš ļø - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion}) ${tag}`
1593
+ );
1594
+ });
1595
+
1596
+ // 🚨 Mandatory update → stop build
1597
+ /* if (hasMandatoryUpdate) {
1598
+ console.log('\n🚫 One or more plugins require a mandatory update.');
1599
+ console.log('āŒ Build cancelled. Please update mandatory plugins and try again.');
1600
+ process.exit(1);
1601
+ } */
1602
+
1603
+
1604
+
1605
+
1606
+
1607
+ if (hasMandatoryUpdate) {
1608
+
1609
+ //--------------------------------------------------
1610
+ // 🚫 AUTO UPDATE DISABLED
1611
+ //--------------------------------------------------
1612
+ if (!ENABLE_AUTO_UPDATE) {
1613
+ console.log("\n🚫 Auto-update disabled.");
1614
+ console.log("āŒ Manual update required.");
1615
+ process.exit(1);
1616
+ }
1617
+
1618
+ //--------------------------------------------------
1619
+ // šŸ”„ AUTO UPDATE ENABLED
1620
+ //--------------------------------------------------
1621
+ console.log("\nšŸ”„ Mandatory plugins outdated. Trying auto-update...\n");
1622
+
1623
+
1624
+
1625
+ let autoFailed = false;
1626
+
1627
+ for (const p of outdatedPlugins.filter(x => x.mandatoryUpdate)) {
1628
+
1629
+ const pluginDef = requiredPlugins.find(def =>
1630
+ def.pattern.test(p.name)
1631
+ );
1632
+
1633
+ if (!pluginDef) continue;
1634
+
1635
+ const success = await autoUpdatePlugin(
1636
+ pluginDef,
1637
+ p
1638
+ );
1639
+
1640
+ if (!success) {
1641
+ autoFailed = true;
1642
+
1643
+ const pluginDef = requiredPlugins.find(def =>
1644
+ def.pattern.test(p.name)
1645
+ );
1646
+
1647
+ console.log(`āŒ Manual update required for ${p.name}`);
1648
+
1649
+ if (pluginDef) {
1650
+ console.log(`šŸ‘‰ Required minimum version: ${pluginDef.minVersion}`);
1651
+ }
1652
+ }
1653
+ }
1654
+
1655
+ // 🚨 Fallback to manual if any failed
1656
+ if (autoFailed) {
1657
+ console.log('\n🚫 One or more plugins require manual update.');
1658
+ console.log('āŒ Build cancelled. Please update mandatory plugins.');
1659
+ process.exit(1);
1660
+ }
1661
+
1662
+ console.log('\nšŸŽ‰ All mandatory plugins auto-updated! Rechecking plugins...\n');
1663
+
1664
+ // Re-run plugin check so outdated list becomes empty
1665
+ await checkPlugins();
1666
+ return;
1667
+ }
1668
+
1669
+
1670
+
1671
+
1672
+
1673
+
1674
+ // Optional updates → ask user
1675
+ const rl = readline.createInterface({
1676
+ input: process.stdin,
1677
+ output: process.stdout
1678
+ });
1679
+
1680
+ rl.question(
1681
+ '\nAre you sure you want to continue without updating these plugins? (y/n): ',
1682
+ answer => {
1683
+ rl.close();
1684
+
1685
+ if (answer.toLowerCase() !== 'y') {
1686
+ console.log('\nāŒ Build cancelled due to outdated plugins.');
1687
+ process.exit(1);
1688
+ } else {
1689
+ console.log('\nāœ… Continuing build...');
1690
+ resolve();
1691
+ }
1692
+ }
1693
+ );
1694
+ } else {
1695
+ console.log('āœ… All plugin versions are up to date.');
1696
+ saveUpdateLogs();
1697
+ resolve();
1698
+ }
1699
+ });
1700
+ }
1701
+
1702
+
1703
+
1704
+
1705
+
1706
+
1707
+
1708
+
1709
+ // Check all the codeplays plugins version START
1710
+
1711
+
1712
+
1713
+
1714
+ // ====================================================================
1715
+ // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
1716
+ // ====================================================================
1717
+
1718
+
1719
+
1720
+ const checkAndupdateDropInViteConfig = () => {
1721
+
1722
+ const possibleFiles = [
1723
+ "vite.config.js",
1724
+ "vite.config.mjs"
1725
+ ];
1726
+
1727
+ // Detect existing config file
1728
+ const viteConfigPath = possibleFiles
1729
+ .map(file => path.join(process.cwd(), file))
1730
+ .find(filePath => fs.existsSync(filePath));
1731
+
1732
+ if (!viteConfigPath) {
1733
+ console.warn("āš ļø No vite config found. Skipping.");
1734
+ return;
1735
+ }
1736
+
1737
+ //console.log("šŸ“„ Using:", viteConfigPath.split("/").pop());
1738
+
1739
+ let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1740
+
1741
+ // Skip if already exists
1742
+ if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1743
+ console.log("ā„¹ļø vite.config.(m)js already Updated. Skipping...");
1744
+ return;
1745
+ }
1746
+
1747
+ console.log("šŸ”§ Adding esbuild.drop ...");
1748
+
1749
+ // If esbuild block exists
1750
+ if (/esbuild\s*:\s*{/.test(viteContent)) {
1751
+ viteContent = viteContent.replace(
1752
+ /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1753
+ (full, inner, indent) => {
1754
+
1755
+ let lines = inner
1756
+ .split("\n")
1757
+ .map(l => l.trim())
1758
+ .filter(Boolean);
1759
+
1760
+ // Fix last comma
1761
+ if (lines.length > 0) {
1762
+ lines[lines.length - 1] =
1763
+ lines[lines.length - 1].replace(/,+$/, "") + ",";
1764
+ }
1765
+
1766
+ // Re-indent
1767
+ lines = lines.map(l => indent + " " + l);
1768
+
1769
+ // Add drop
1770
+ lines.push(`${indent} drop: ['console','debugger'],`);
1771
+
1772
+ return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1773
+ }
1774
+ );
1775
+ }
1776
+
1777
+ // If esbuild missing
1778
+ else {
1779
+ viteContent = viteContent.replace(
1780
+ /export default defineConfig\s*\(\s*{/,
1781
+ m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1782
+ );
1783
+ }
1784
+
1785
+ fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1786
+ console.log("āœ… vite.config.(m)js Updated successfully.");
1787
+ };
1788
+
1789
+
1790
+
1791
+
1792
+
1793
+
1794
+
1795
+
1796
+
1797
+
1798
+ const compareVersion = (v1, v2) => {
1799
+ const a = v1.split(".").map(Number);
1800
+ const b = v2.split(".").map(Number);
1801
+
1802
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
1803
+ const num1 = a[i] || 0;
1804
+ const num2 = b[i] || 0;
1805
+ if (num1 > num2) return 1;
1806
+ if (num1 < num2) return -1;
1807
+ }
1808
+ return 0;
1809
+ };
1810
+
1811
+
1812
+
1813
+
1814
+ const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1815
+
1816
+ const checkAdmobConfigurationProperty=()=>{
1817
+
1818
+
1819
+ if (!_admobConfig.ADMOB_ENABLED)
1820
+ {
1821
+ console.log("ā„¹ļø Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1822
+ return;
1823
+ }
1824
+
1825
+
1826
+ const REQUIRED_CONFIG_KEYS = [
1827
+ "isKidsApp",
1828
+ "isTesting",
1829
+ "isConsoleLogEnabled",
1830
+ "bannerEnabled",
1831
+ "interstitialEnabled",
1832
+ "appOpenEnabled",
1833
+ "rewardVideoEnabled",
1834
+ "rewardInterstitialEnabled",
1835
+ "collapsibleEnabled",
1836
+ "isLandScape",
1837
+ "isOverlappingEnable",
1838
+ "bannerTypeAndroid",
1839
+ "bannerTypeiOS",
1840
+ "bannerTopSpaceColor",
1841
+ "interstitialLoadScreenTextColor",
1842
+ "interstitialLoadScreenBackgroundColor",
1843
+ "beforeBannerSpace",
1844
+ "whenShow",
1845
+ "minimumClick",
1846
+ "interstitialTimeOut",
1847
+ "interstitialFirstTimeOut",
1848
+ "appOpenAdsTimeOut",
1849
+ "maxRetryCount",
1850
+ "retrySecondsAr",
1851
+ "appOpenPerSession",
1852
+ "interstitialPerSession",
1853
+ "appOpenFirstTimeOut"
1854
+ ];
1855
+
1856
+
1857
+
1858
+
1859
+
1860
+ let admobConfigInJson;
1861
+
1862
+ try {
1863
+ admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1864
+ } catch (err) {
1865
+ console.error("āŒ Failed to read admob-ad-configuration.json", err);
1866
+ process.exit(1);
1867
+ }
1868
+
1869
+ // āœ… Validate config object exists
1870
+ if (!admobConfigInJson.config) {
1871
+ console.error('āŒ "config" object is missing in admob-ad-configuration.json');
1872
+ process.exit(1);
1873
+ }
1874
+
1875
+
1876
+ const admobConfigMinVersion="1.5"
1877
+
1878
+ if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1879
+ console.error(`āŒ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1880
+ process.exit(1);
1881
+ }
1882
+
1883
+
1884
+ const config = admobConfigInJson.config;
1885
+
1886
+ // āœ… Find missing properties
1887
+ const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1888
+ key => !(key in config)
1889
+ );
1890
+
1891
+
1892
+
1893
+ if (missingKeys.length > 0) {
1894
+ console.error("āŒ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1895
+
1896
+ missingKeys.forEach(k => console.error(" - " + k));
1897
+ process.exit(1);
1898
+ }
1899
+
1900
+
1901
+ console.log('āœ… All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1902
+ }
1903
+
1904
+
1905
+
1906
+ function ensureGitignoreEntry(entry) {
1907
+ const gitignorePath = path.join(process.cwd(), '.gitignore');
1908
+
1909
+ // If .gitignore doesn't exist, create it
1910
+ if (!fs.existsSync(gitignorePath)) {
1911
+ fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
1912
+ console.log(`āœ… .gitignore created and added: ${entry}`);
1913
+ return;
1914
+ }
1915
+
1916
+ const content = fs.readFileSync(gitignorePath, 'utf8');
1917
+
1918
+ // Normalize lines (trim + remove trailing slashes for comparison)
1919
+ const lines = content
1920
+ .split(/\r?\n/)
1921
+ .map(l => l.trim());
1922
+
1923
+ const normalizedEntry = entry.replace(/\/$/, '');
1924
+
1925
+ const exists = lines.some(
1926
+ line => line.replace(/\/$/, '') === normalizedEntry
1927
+ );
1928
+
1929
+ if (exists) {
1930
+ console.log(`ā„¹ļø .gitignore already contains: ${entry}`);
1931
+ return;
1932
+ }
1933
+
1934
+ // Ensure file ends with newline
1935
+ const separator = content.endsWith('\n') ? '' : '\n';
1936
+
1937
+ fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
1938
+ console.log(`āœ… Added to .gitignore: ${entry}`);
1939
+ }
1940
+
1941
+
1942
+ ensureGitignoreEntry('buildCodeplay/');
1943
+
1944
+
1945
+ // Run the validation
1946
+ (async () => {
1947
+
1948
+ await loadPluginVersions(); // šŸ”„ NEW
1949
+
1950
+ await checkPlugins();
1951
+ checkAndupdateDropInViteConfig();
1952
+ checkAdmobConfigurationProperty()
1953
+ })();
1954
+
1955
+
1956
+ // ======================================================
1957
+ // Validate theme folder location (src/js/theme is NOT allowed)
1958
+ // ======================================================
1959
+
1960
+ function validateThemeFolderLocation() {
1961
+ const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
1962
+ const newThemePath = path.join(process.cwd(), 'src', 'theme');
1963
+
1964
+ // āŒ Block old structure
1965
+ if (fs.existsSync(oldThemePath)) {
1966
+ console.error(
1967
+ '\nāŒ INVALID PROJECT STRUCTURE DETECTED\n' +
1968
+ '--------------------------------------------------\n' +
1969
+ 'The "theme" folder must NOT be inside:\n' +
1970
+ ' src/js/theme\n\n' +
1971
+ 'āœ… Correct location is:\n' +
1972
+ ' src/theme\n\n' +
1973
+ 'šŸ›‘ Please move the folder and re-run the build.\n'
1974
+ );
1975
+ process.exit(1);
1976
+ }
1977
+
1978
+ // āš ļø Optional warning if new theme folder is missing
1979
+ if (!fs.existsSync(newThemePath)) {
1980
+ console.warn(
1981
+ '\nāš ļø WARNING: "src/theme" folder not found.\n' +
1982
+ 'If your app uses themes, please ensure it exists.\n'
1983
+ );
1984
+ } else {
1985
+ console.log('āœ… Theme folder structure validated (src/theme).');
1986
+ }
1987
+ }
1988
+ validateThemeFolderLocation()
1989
+
1990
+
1991
+
1992
+ const validateAndRestoreSignDetails=()=>{
1993
+
1994
+ // Read config file
1995
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
1996
+
1997
+ // Ensure android and buildOptions exist
1998
+ if (!config.android) config.android = {};
1999
+ if (!config.android.buildOptions) config.android.buildOptions = {};
2000
+
2001
+ // Update only if changed
2002
+ let updated = false;
2003
+
2004
+ if (config.android.buildOptions.releaseType !== 'AAB') {
2005
+ config.android.buildOptions.releaseType = 'AAB';
2006
+ updated = true;
2007
+ }
2008
+
2009
+ if (config.android.buildOptions.signingType !== 'jarsigner') {
2010
+ config.android.buildOptions.signingType = 'jarsigner';
2011
+ updated = true;
2012
+ }
2013
+
2014
+ // Write back only if modified
2015
+ if (updated) {
2016
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
2017
+ console.log('capacitor.config.json updated successfully.');
2018
+ } else {
2019
+ console.log('No changes needed.');
2020
+ }
2021
+
2022
+ }
2023
+
2024
+ validateAndRestoreSignDetails()
2025
+
2026
+
2027
+ execSync('node buildCodeplay/fix-onesignal-plugin.js', { stdio: 'inherit' });
2028
+
2029
+ /*
2030
+ Release Notes
2031
+
2032
+ 5.1
2033
+ Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
2034
+
2035
2035
  */