codeplay-common 2.1.18 → 2.1.20

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,1301 +1,1338 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const plist = require('plist');
4
-
5
- const { readFileSync } = require("fs");
6
-
7
-
8
-
9
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
10
-
11
- // Expected plugin list with minimum versions
12
- const requiredPlugins = [
13
- { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.6', required: true, baseDir: 'js' },
14
-
15
- /*/common-(\d+\.\d+)\.js$/*/
16
- { pattern: /common-(\d+\.\d+)(?:-beta-(\d+))?\.js$/, minVersion: '5.2', required: true, baseDir: 'js' },
17
-
18
- { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js' },
19
- { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.3', required: true, baseDir: 'js' },
20
- { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js' },
21
- { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true, baseDir: 'js' },
22
- { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js' },
23
- { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.0', required: true, baseDir: 'js' },
24
- { pattern: /Ads[\/\\]IAP-(\d+\.\d+)$/, minVersion: '2.5', isFolder: true , required: true, baseDir: 'js' },
25
- { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.3', required: true, baseDir: 'js' },
26
-
27
- // New added plugins
28
- { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js' },
29
- { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js' },
30
-
31
- { pattern: /common-(\d+\.\d+)\.less$/, minVersion: '1.5', required: true, baseDir: 'assets/css' },
32
-
33
-
34
- // New folders
35
- { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.8', isFolder: true, required: true, baseDir: 'js' },
36
- { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.3', isFolder: true, required: true, baseDir: 'js' },
37
- { pattern: /theme-(\d+\.\d+)$/, minVersion: '1.6', isFolder: true , required: true, baseDir: 'js' },
38
-
39
-
40
- { pattern: /certificatejs-(\d+\.\d+)$/, minVersion: '1.4', isFolder: true , required: true, baseDir: 'certificate' }
41
-
42
- ];
43
-
44
-
45
-
46
-
47
-
48
-
49
- //Check codeplay-common latest version installed or not Start
50
- const { execSync } = require('child_process');
51
-
52
- function getInstalledVersion(packageName) {
53
- try {
54
- const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
55
- if (fs.existsSync(packageJsonPath)) {
56
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
57
- return packageJson.version;
58
- }
59
- } catch (error) {
60
- return null;
61
- }
62
- return null;
63
- }
64
-
65
- function getLatestVersion(packageName) {
66
- try {
67
- return execSync(`npm view ${packageName} version`).toString().trim();
68
- } catch (error) {
69
- console.error(`Failed to fetch latest version for ${packageName}`);
70
- return null;
71
- }
72
- }
73
-
74
- function checkPackageVersion() {
75
- const packageName = 'codeplay-common';
76
- const installedVersion = getInstalledVersion(packageName);
77
- const latestVersion = getLatestVersion(packageName);
78
-
79
- if (!installedVersion) {
80
- console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
81
- process.exit(1);
82
- }
83
-
84
- if (installedVersion !== latestVersion) {
85
- 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`);
86
- process.exit(1);
87
- }
88
-
89
- console.log(`${packageName} is up to date (version ${installedVersion}).`);
90
- }
91
-
92
- // Run package version check before executing the main script
93
- try {
94
- checkPackageVersion();
95
- } catch (error) {
96
- console.error(error.message);
97
- process.exit(1);
98
- }
99
-
100
- //Check codeplay-common latest version installed or not END
101
-
102
-
103
-
104
- function compareWithBeta(installedVersion, minVersion, isBeta) {
105
- const baseCompare = compareVersions(installedVersion, minVersion);
106
-
107
- if (!isBeta) {
108
- // Stable version → normal compare
109
- return baseCompare;
110
- }
111
-
112
- // Beta version logic
113
- if (baseCompare > 0) return 1; // 5.3-beta > 5.2
114
- if (baseCompare < 0) return -1; // 5.1-beta < 5.2
115
-
116
- // Same version but beta → LOWER than stable
117
- return -1; // 5.2-beta < 5.2
118
- }
119
-
120
-
121
-
122
-
123
- const checkAppUniqueId=()=>{
124
-
125
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
126
-
127
- const appUniqueId = config.android?.APP_UNIQUE_ID;
128
- const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
129
- const orientation = config.android?.ORIENTATION;
130
-
131
-
132
- let logErrorMessage="";
133
-
134
- // 1️⃣ Check if it’s missing
135
- if (RESIZEABLE_ACTIVITY === undefined) {
136
- logErrorMessage+='❌ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
137
- }
138
-
139
- // 2️⃣ Check if it’s not boolean (true/false only)
140
- else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
141
- logErrorMessage+='❌ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
142
- }
143
-
144
-
145
-
146
- if (!orientation) {
147
- logErrorMessage+='❌ Missing android.ORIENTATION option in capacitor.config.json.\n';
148
- }
149
-
150
- else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
151
- {
152
- logErrorMessage+='❌ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
153
- }
154
-
155
-
156
- if (!appUniqueId) {
157
- logErrorMessage+='❌ APP_UNIQUE_ID is missing in capacitor.config.json.';
158
- }
159
-
160
- else if (!Number.isInteger(appUniqueId)) {
161
- logErrorMessage+='❌ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
162
- }
163
-
164
-
165
-
166
- if(logErrorMessage!="")
167
- {
168
- console.error(logErrorMessage);
169
- process.exit(1)
170
- }
171
-
172
-
173
- console.log(`✅ APP_UNIQUE_ID is valid: ${appUniqueId}`);
174
-
175
- }
176
-
177
- checkAppUniqueId();
178
-
179
-
180
-
181
-
182
-
183
-
184
-
185
- //@Codemirror check and install/uninstall the packages START
186
- //const fs = require("fs");
187
- //const path = require("path");
188
- //const { execSync } = require("child_process");
189
-
190
- const baseDir = path.join(__dirname, "..", "src", "js");
191
-
192
- // Step 1: Find highest versioned folder like `editor-1.6`
193
- const editorDirs = fs.readdirSync(baseDir)
194
- .filter(name => /^editor-\d+\.\d+$/.test(name))
195
- .sort((a, b) => {
196
- const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
197
- const [aMajor, aMinor] = getVersion(a);
198
- const [bMajor, bMinor] = getVersion(b);
199
- return bMajor - aMajor || bMinor - aMinor;
200
- });
201
-
202
- if (editorDirs.length === 0) {
203
-
204
- console.log("@Codemirror used editor(s) are not found")
205
- //console.error("❌ No editor-x.x folders found in src/js.");
206
- //process.exit(1);
207
- }
208
- else
209
- {
210
-
211
- const latestEditorDir = editorDirs.sort((a, b) => {
212
- const versionA = parseFloat(a.split('-')[1]);
213
- const versionB = parseFloat(b.split('-')[1]);
214
- return versionB - versionA;
215
- })[0];
216
-
217
- //const latestEditorDir = editorDirs[editorDirs.length - 1];
218
- const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
219
-
220
- if (!fs.existsSync(runJsPath)) {
221
- console.error(`❌ run.js not found in ${latestEditorDir}`);
222
- process.exit(1);
223
- }
224
-
225
- // Step 2: Execute the run.js file
226
- console.log(`🚀 Executing ${runJsPath}...`);
227
- execSync(`node "${runJsPath}"`, { stdio: "inherit" });
228
- }
229
-
230
- //@Codemirror check and install/uninstall the packages END
231
-
232
-
233
-
234
-
235
-
236
-
237
-
238
-
239
-
240
-
241
-
242
-
243
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
244
-
245
- const os = require('os');
246
-
247
- const saveToGalleryAndSaveFileCheck_iOS = () => {
248
-
249
- // List of paths to scan
250
- const SCAN_PATHS = [
251
- path.resolve(__dirname, '../src/certificate'),
252
- path.resolve(__dirname, '../src/pages'),
253
- path.resolve(__dirname, '../src/js'),
254
- path.resolve(__dirname, '../src/app.f7')
255
- ];
256
-
257
- // Directory to exclude
258
- const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
259
-
260
- const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
261
-
262
-
263
- // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
264
- const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
265
-
266
- // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
267
- const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
268
-
269
-
270
-
271
-
272
-
273
- const ALLOWED_EXTENSIONS = ['.js', '.f7'];
274
- const isMac = os.platform() === 'darwin';
275
-
276
- let iosImportFound = false;
277
- let androidImportFound = false;
278
-
279
- // Files to skip completely (full or partial match)
280
- const SKIP_FILES = [
281
- 'pdf-3.11.174.min.js',
282
- 'pdf.worker-3.11.174.min.js'
283
- ,'index.browser.js'
284
- ];
285
-
286
-
287
- function scanDirectory(dir) {
288
-
289
- /*
290
- //######################### DO NOT DELETE THIS - START [Appid base validation] #####################################
291
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
292
- const appUniqueId = config.android?.APP_UNIQUE_ID;
293
- if (appUniqueId == "206") return;
294
- //######################### DO NOT DELETE THIS - END [Appid base validation] #####################################
295
- */
296
-
297
- const stat = fs.statSync(dir);
298
-
299
- if (stat.isFile()) {
300
-
301
- // 🔥 Skip files in SKIP_FILES array
302
- const baseName = path.basename(dir);
303
- if (SKIP_FILES.includes(baseName)) {
304
- // Just skip silently
305
- return;
306
- }
307
-
308
- // Only scan allowed file extensions
309
- if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
310
- process.stdout.write(`\r🔍 Scanning: ${dir} `);
311
-
312
- const content = fs.readFileSync(dir, 'utf8');
313
-
314
- if (IOS_FILE_REGEX.test(content)) {
315
- iosImportFound = true;
316
- if (!isMac) {
317
- console.error(`\n❌ ERROR: iOS-specific import detected in: ${dir}`);
318
- console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
319
- process.exit(1);
320
- }
321
- }
322
- else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
323
- androidImportFound = true;
324
- }
325
- }
326
- }
327
- else if (stat.isDirectory()) {
328
- if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
329
-
330
- const entries = fs.readdirSync(dir, { withFileTypes: true });
331
- for (let entry of entries) {
332
- scanDirectory(path.join(dir, entry.name));
333
- }
334
- }
335
- }
336
-
337
-
338
- // Run scan on all specified paths
339
- for (let scanPath of SCAN_PATHS) {
340
- if (fs.existsSync(scanPath)) {
341
- scanDirectory(scanPath);
342
- }
343
- }
344
-
345
-
346
-
347
- /* // Check src folder
348
- if (!fs.existsSync(ROOT_DIR)) {
349
- console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
350
- return;
351
- } */
352
-
353
- //scanDirectory(ROOT_DIR);
354
-
355
- // iOS Checks
356
- if (isMac && !iosImportFound) {
357
- console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
358
- process.exit(1);
359
- } else if (isMac && iosImportFound) {
360
- console.log('✅ iOS version detected for macOS build.');
361
- } else if (!iosImportFound) {
362
- console.log('✅ No iOS-specific imports detected for non-macOS.');
363
- }
364
-
365
- // Android Checks
366
- if (androidImportFound) {
367
- console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
368
-
369
- if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
370
- console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
371
- return;
372
- }
373
-
374
- let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
375
-
376
- if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
377
- console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
378
-
379
- manifestContent = manifestContent.replace(
380
- /<application([^>]*)>/,
381
- (match, attrs) => {
382
- if (attrs.includes('android:requestLegacyExternalStorage')) return match;
383
- return `<application${attrs} android:requestLegacyExternalStorage="true">`;
384
- }
385
- );
386
-
387
- fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
388
- console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
389
- } else {
390
- console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
391
- }
392
- } else {
393
- console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
394
- }
395
- };
396
-
397
- saveToGalleryAndSaveFileCheck_iOS();
398
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
399
-
400
-
401
-
402
-
403
-
404
-
405
-
406
-
407
-
408
-
409
-
410
-
411
-
412
- /*
413
- // Clean up AppleDouble files (._*) created by macOS START
414
- if (process.platform === 'darwin') {
415
- try {
416
- console.log('🧹 Cleaning up AppleDouble files (._*)...');
417
- execSync(`find . -name '._*' -delete`);
418
- console.log('✅ AppleDouble files removed.');
419
- } catch (err) {
420
- console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
421
- }
422
- } else {
423
- console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
424
- }
425
-
426
- // Clean up AppleDouble files (._*) created by macOS END
427
- */
428
-
429
-
430
-
431
-
432
-
433
-
434
- //In routes.js file check static import START
435
-
436
- const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
437
- const routesContent = fs.readFileSync(routesPath, 'utf-8');
438
-
439
- let inBlockComment = false;
440
- const lines = routesContent.split('\n');
441
-
442
- const allowedImport = `import HomePage from '../pages/home.f7';`;
443
- const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
444
- const badImports = [];
445
-
446
- lines.forEach((line, index) => {
447
- const trimmed = line.trim();
448
-
449
- // Handle block comment start and end
450
- if (trimmed.startsWith('/*')) inBlockComment = true;
451
- if (inBlockComment && trimmed.endsWith('*/')) {
452
- inBlockComment = false;
453
- return;
454
- }
455
-
456
- // Skip if inside block comment or line comment
457
- if (inBlockComment || trimmed.startsWith('//')) return;
458
-
459
- // Match static .f7 import
460
- if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
461
- badImports.push({ line: trimmed, number: index + 1 });
462
- }
463
- });
464
-
465
- if (badImports.length > 0) {
466
- console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
467
- console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
468
- console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
469
- console.error(`
470
-
471
- import HomePage from '../pages/home.f7';
472
-
473
- const routes = [
474
- {
475
- path: '/',
476
- component:HomePage,
477
- },
478
- {
479
- path: '/ProfilePage/',
480
- async async({ resolve }) {
481
- const page = await import('../pages/profile.f7');
482
- resolve({ component: page.default });
483
- },
484
- }]
485
- `);
486
-
487
- badImports.forEach(({ line, number }) => {
488
- console.error(`${number}: ${line}`);
489
- });
490
-
491
- process.exit(1);
492
- } else {
493
- console.log('✅ routes.js passed the .f7 import check.');
494
- }
495
-
496
- //In routes.js file check static import END
497
-
498
-
499
-
500
-
501
-
502
-
503
-
504
-
505
-
506
-
507
-
508
-
509
-
510
- // Check and change the "BridgeWebViewClient.java" file START
511
- /*
512
- For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
513
- */
514
-
515
-
516
- const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
517
-
518
- // Read the file
519
- if (!fs.existsSync(bridgeWebViewClientFilePath)) {
520
- console.error('❌ Error: BridgeWebViewClient.java not found.');
521
- process.exit(1);
522
- }
523
-
524
- let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
525
-
526
- // Define old and new code
527
- const oldCodeStart = `@Override
528
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
529
- super.onRenderProcessGone(view, detail);
530
- boolean result = false;
531
-
532
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
533
- if (webViewListeners != null) {
534
- for (WebViewListener listener : bridge.getWebViewListeners()) {
535
- result = listener.onRenderProcessGone(view, detail) || result;
536
- }
537
- }
538
-
539
- return result;
540
- }`;
541
-
542
- const newCode = `@Override
543
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
544
- super.onRenderProcessGone(view, detail);
545
-
546
- boolean result = false;
547
-
548
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
549
- if (webViewListeners != null) {
550
- for (WebViewListener listener : bridge.getWebViewListeners()) {
551
- result = listener.onRenderProcessGone(view, detail) || result;
552
- }
553
- }
554
-
555
- if (!result) {
556
- // If no one handled it, handle it ourselves!
557
-
558
- /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
559
- if (detail.didCrash()) {
560
- //Log.e("CapacitorWebView", "WebView crashed internally!");
561
- } else {
562
- //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
563
- }
564
- }*/
565
-
566
- view.post(() -> {
567
- Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
568
- });
569
-
570
- view.reload(); // Safely reload WebView
571
-
572
- return true; // We handled it
573
- }
574
-
575
- return result;
576
- }`;
577
-
578
- // Step 1: Update method if needed
579
- let updated = false;
580
-
581
- if (fileContent.includes(oldCodeStart)) {
582
- console.log('✅ Found old onRenderProcessGone method. Replacing it...');
583
- fileContent = fileContent.replace(oldCodeStart, newCode);
584
- updated = true;
585
- } else if (fileContent.includes(newCode)) {
586
- console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
587
- } else {
588
- console.error('❌ Error: Neither old nor new code found. Unexpected content.');
589
- process.exit(1);
590
- }
591
-
592
- // Step 2: Check and add import if missing
593
- const importToast = 'import android.widget.Toast;';
594
- if (!fileContent.includes(importToast)) {
595
- console.log('✅ Adding missing import for Toast...');
596
- const importRegex = /import\s+[^;]+;/g;
597
- const matches = [...fileContent.matchAll(importRegex)];
598
-
599
- if (matches.length > 0) {
600
- const lastImport = matches[matches.length - 1];
601
- const insertPosition = lastImport.index + lastImport[0].length;
602
- fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
603
- updated = true;
604
- } else {
605
- console.error('❌ Error: No import section found in file.');
606
- process.exit(1);
607
- }
608
- } else {
609
- console.log('ℹ️ Import for Toast already exists. No changes needed.');
610
- }
611
-
612
- // Step 3: Save if updated
613
- if (updated) {
614
- fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
615
- console.log('✅ File updated successfully.');
616
- } else {
617
- console.log('ℹ️ No changes needed.');
618
- }
619
-
620
-
621
-
622
-
623
- // Check and change the "BridgeWebViewClient.java" file END
624
-
625
-
626
-
627
-
628
-
629
-
630
-
631
-
632
- /*
633
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
634
-
635
- // Build the path dynamically like you requested
636
- const gradlePath = path.join(
637
- process.cwd(),
638
- 'android',
639
- 'build.gradle'
640
- );
641
-
642
- // Read the existing build.gradle
643
- let gradleContent = fs.readFileSync(gradlePath, 'utf8');
644
-
645
- // Add `ext.kotlin_version` if it's not already there
646
- if (!gradleContent.includes('ext.kotlin_version')) {
647
- gradleContent = gradleContent.replace(
648
- /buildscript\s*{/,
649
- `buildscript {\n ext.kotlin_version = '2.1.0'`
650
- );
651
- }
652
-
653
- // Add Kotlin classpath if it's not already there
654
- if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
655
- gradleContent = gradleContent.replace(
656
- /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
657
- `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
658
- );
659
- }
660
-
661
- // Write back the modified content
662
- fs.writeFileSync(gradlePath, gradleContent, 'utf8');
663
-
664
- console.log('✅ Kotlin version updated in build.gradle.');
665
-
666
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
667
- */
668
-
669
-
670
-
671
-
672
-
673
-
674
-
675
-
676
- let _admobConfig;
677
-
678
-
679
-
680
- const androidPlatformPath = path.join(process.cwd(), 'android');
681
- const iosPlatformPath = path.join(process.cwd(), 'ios');
682
- const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
683
- const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
684
- const resourcesPath = path.join(process.cwd(), 'resources', 'res');
685
- const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
686
- const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
687
-
688
- function fileExists(filePath) {
689
- return fs.existsSync(filePath);
690
- }
691
-
692
- function copyFolderSync(source, target) {
693
- if (!fs.existsSync(target)) {
694
- fs.mkdirSync(target, { recursive: true });
695
- }
696
-
697
- fs.readdirSync(source).forEach(file => {
698
- const sourceFile = path.join(source, file);
699
- const targetFile = path.join(target, file);
700
-
701
- if (fs.lstatSync(sourceFile).isDirectory()) {
702
- copyFolderSync(sourceFile, targetFile);
703
- } else {
704
- fs.copyFileSync(sourceFile, targetFile);
705
- }
706
- });
707
- }
708
-
709
- function checkAndCopyResources() {
710
- if (fileExists(resourcesPath)) {
711
- copyFolderSync(resourcesPath, androidResPath);
712
- console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
713
- } else {
714
- console.log('resources/res folder not found.');
715
-
716
- if (fileExists(localNotificationsPluginPath)) {
717
- throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
718
- }
719
- }
720
- }
721
-
722
-
723
-
724
-
725
-
726
-
727
-
728
-
729
- function getAdMobConfig() {
730
- if (!fileExists(configPath)) {
731
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
732
- }
733
-
734
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
735
- const admobConfig = config.plugins?.AdMob;
736
-
737
- if (!admobConfig) {
738
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
739
- }
740
-
741
- // Default to true if ADMOB_ENABLED is not specified
742
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
743
-
744
- if (!isEnabled) {
745
- return { ADMOB_ENABLED: false }; // Skip further validation
746
- }
747
-
748
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
749
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
750
- }
751
-
752
- return {
753
- ADMOB_ENABLED: true,
754
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
755
- APP_ID_IOS: admobConfig.APP_ID_IOS,
756
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
757
- };
758
- }
759
-
760
- function validateAndroidBuildOptions() {
761
-
762
-
763
- if (!fileExists(configPath)) {
764
- console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
765
- process.exit(1);
766
- }
767
-
768
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
769
-
770
- const targetAppId=config.appId
771
-
772
- const buildOptions = config.android?.buildOptions;
773
-
774
- if (!buildOptions) {
775
- console.log('❌ Missing android.buildOptions in capacitor.config.json.');
776
- process.exit(1);
777
- }
778
-
779
- const requiredProps = [
780
- 'keystorePath',
781
- 'keystorePassword',
782
- 'keystoreAlias',
783
- 'keystoreAliasPassword',
784
- 'releaseType',
785
- 'signingType'
786
- ];
787
-
788
- const missing = requiredProps.filter(prop => !buildOptions[prop]);
789
-
790
- if (missing.length > 0) {
791
- console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
792
- process.exit(1);
793
- }
794
-
795
-
796
- const keystorePath=buildOptions.keystorePath
797
- const keyFileName = path.basename(keystorePath);
798
-
799
-
800
-
801
- const keystoreMap = {
802
- "gameskey.jks": [
803
- "com.cube.blaster",
804
- ],
805
- "htmleditorkeystoke.jks": [
806
- "com.HTML.AngularJS.Codeplay",
807
- "com.html.codeplay.pro",
808
- "com.bootstrap.code.play",
809
- "com.kids.learning.master",
810
- "com.Simple.Barcode.Scanner"
811
- ]
812
- };
813
-
814
- // find which keystore is required for the given targetAppId
815
- let requiredKey = "newappskey.jks"; // default
816
- for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
817
- if (appIds.includes(targetAppId)) {
818
- requiredKey = keyFile;
819
- break;
820
- }
821
- }
822
-
823
- // validate
824
- if (keyFileName !== requiredKey) {
825
- console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
826
- process.exit(1);
827
- }
828
-
829
-
830
-
831
-
832
-
833
- // optionally return them
834
- //return buildOptions;
835
- }
836
-
837
- function updatePluginXml(admobConfig) {
838
- if (!fileExists(pluginPath)) {
839
- console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
840
- return;
841
- }
842
-
843
- let pluginContent = fs.readFileSync(pluginPath, 'utf8');
844
-
845
- pluginContent = pluginContent
846
- .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
847
- .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
848
-
849
- fs.writeFileSync(pluginPath, pluginContent, 'utf8');
850
- console.log('✅ AdMob IDs successfully updated in plugin.xml');
851
- }
852
-
853
- function updateInfoPlist(admobConfig) {
854
- if (!fileExists(infoPlistPath)) {
855
- console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
856
- return;
857
- }
858
-
859
- const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
860
- const plistData = plist.parse(plistContent);
861
-
862
- plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
863
- plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
864
- plistData.GADDelayAppMeasurementInit = true;
865
-
866
- const updatedPlistContent = plist.build(plistData);
867
- fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
868
- console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
869
- }
870
-
871
-
872
- try {
873
- if (!fileExists(configPath)) {
874
- throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
875
- }
876
-
877
- if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
878
- throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
879
- }
880
-
881
- checkAndCopyResources();
882
-
883
-
884
-
885
- _admobConfig = getAdMobConfig();
886
-
887
-
888
-
889
-
890
-
891
- // Proceed only if ADMOB_ENABLED is true
892
- if (_admobConfig.ADMOB_ENABLED) {
893
- if (fileExists(androidPlatformPath)) {
894
- updatePluginXml(_admobConfig);
895
- }
896
-
897
- if (fileExists(iosPlatformPath)) {
898
- updateInfoPlist(_admobConfig);
899
- }
900
- }
901
-
902
-
903
- } catch (error) {
904
- console.error(error.message);
905
- process.exit(1); // Stop execution if there's a critical error
906
- }
907
-
908
-
909
-
910
- validateAndroidBuildOptions();
911
-
912
-
913
-
914
-
915
-
916
-
917
- // Check all the codeplays plugins version START
918
-
919
-
920
- const readline = require('readline');
921
-
922
-
923
- //const srcDir = path.join(__dirname, 'src');
924
- const srcDir = path.join(process.cwd(), 'src');
925
- let outdatedPlugins = [];
926
-
927
- function parseVersion(ver) {
928
- return ver.split('.').map(n => parseInt(n, 10));
929
- }
930
-
931
- function compareVersions(v1, v2) {
932
- const [a1, b1] = parseVersion(v1);
933
- const [a2, b2] = parseVersion(v2);
934
- if (a1 !== a2) return a1 - a2;
935
- return b1 - b2;
936
- }
937
-
938
- function walkSync(dir, filelist = []) {
939
- fs.readdirSync(dir).forEach(file => {
940
- const fullPath = path.join(dir, file);
941
- const stat = fs.statSync(fullPath);
942
- if (stat.isDirectory()) {
943
- walkSync(fullPath, filelist);
944
- } else {
945
- filelist.push(fullPath);
946
- }
947
- });
948
- return filelist;
949
- }
950
-
951
-
952
-
953
- function getSearchRoot(plugin) {
954
- return path.join(srcDir, plugin.baseDir || 'js');
955
- }
956
-
957
- function checkPlugins() {
958
- return new Promise((resolve, reject) => {
959
- const files = walkSync(srcDir);
960
-
961
- for (const plugin of requiredPlugins) {
962
- const searchRoot = getSearchRoot(plugin);
963
-
964
- if (plugin.isFolder) {
965
- if (!fs.existsSync(searchRoot)) continue;
966
-
967
- const subDirs = fs.readdirSync(searchRoot)
968
- .map(name => path.join(searchRoot, name))
969
- .filter(p => fs.statSync(p).isDirectory());
970
-
971
- for (const dir of subDirs) {
972
- const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
973
- const match = plugin.pattern.exec(relativePath);
974
-
975
- if (match) {
976
- const currentVersion = match[1];
977
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
978
- outdatedPlugins.push({
979
- name: relativePath,
980
- currentVersion,
981
- requiredVersion: plugin.minVersion
982
- });
983
- }
984
- }
985
- }
986
- continue;
987
- }
988
-
989
- const matchedFile = files.find(file =>
990
- file.startsWith(searchRoot) && plugin.pattern.test(file)
991
- );
992
-
993
- if (matchedFile) {
994
- const match = plugin.pattern.exec(matchedFile);
995
- if (match) {
996
- const currentVersion = match[1];
997
- const isBeta = !!match[2];
998
-
999
- const cmp = plugin.pattern.source.includes('beta')
1000
- ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1001
- : compareVersions(currentVersion, plugin.minVersion);
1002
-
1003
- if (cmp < 0) {
1004
- outdatedPlugins.push({
1005
- name: path.relative(srcDir, matchedFile),
1006
- currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1007
- requiredVersion: plugin.minVersion
1008
- });
1009
- }
1010
- }
1011
- }
1012
- }
1013
-
1014
- if (outdatedPlugins.length > 0) {
1015
- console.log('\n❗ The following plugins are outdated:');
1016
- outdatedPlugins.forEach(p => {
1017
- console.log(` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion})`);
1018
- });
1019
-
1020
- const rl = readline.createInterface({
1021
- input: process.stdin,
1022
- output: process.stdout
1023
- });
1024
-
1025
- rl.question('\nAre you sure you want to continue without updating these plugins? (y/n): ', answer => {
1026
- rl.close();
1027
-
1028
- if (answer.toLowerCase() !== 'y') {
1029
- console.log('\n❌ Build cancelled due to outdated plugins.');
1030
- process.exit(1);
1031
- } else {
1032
- console.log('\n✅ Continuing build...');
1033
- resolve();
1034
- }
1035
- });
1036
- } else {
1037
- console.log('✅ All plugin versions are up to date.');
1038
- resolve();
1039
- }
1040
- });
1041
- }
1042
-
1043
-
1044
-
1045
-
1046
-
1047
-
1048
-
1049
-
1050
- // Check all the codeplays plugins version START
1051
-
1052
-
1053
-
1054
-
1055
- // ====================================================================
1056
- // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
1057
- // ====================================================================
1058
-
1059
-
1060
-
1061
- const checkAndupdateDropInViteConfig = () => {
1062
-
1063
- const possibleFiles = [
1064
- "vite.config.js",
1065
- "vite.config.mjs"
1066
- ];
1067
-
1068
- // Detect existing config file
1069
- const viteConfigPath = possibleFiles
1070
- .map(file => path.join(process.cwd(), file))
1071
- .find(filePath => fs.existsSync(filePath));
1072
-
1073
- if (!viteConfigPath) {
1074
- console.warn("⚠️ No vite config found. Skipping.");
1075
- return;
1076
- }
1077
-
1078
- //console.log("📄 Using:", viteConfigPath.split("/").pop());
1079
-
1080
- let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1081
-
1082
- // Skip if already exists
1083
- if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1084
- console.log("ℹ️ vite.config.(m)js already Updated. Skipping...");
1085
- return;
1086
- }
1087
-
1088
- console.log("🔧 Adding esbuild.drop ...");
1089
-
1090
- // If esbuild block exists
1091
- if (/esbuild\s*:\s*{/.test(viteContent)) {
1092
- viteContent = viteContent.replace(
1093
- /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1094
- (full, inner, indent) => {
1095
-
1096
- let lines = inner
1097
- .split("\n")
1098
- .map(l => l.trim())
1099
- .filter(Boolean);
1100
-
1101
- // Fix last comma
1102
- if (lines.length > 0) {
1103
- lines[lines.length - 1] =
1104
- lines[lines.length - 1].replace(/,+$/, "") + ",";
1105
- }
1106
-
1107
- // Re-indent
1108
- lines = lines.map(l => indent + " " + l);
1109
-
1110
- // Add drop
1111
- lines.push(`${indent} drop: ['console','debugger'],`);
1112
-
1113
- return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1114
- }
1115
- );
1116
- }
1117
-
1118
- // If esbuild missing
1119
- else {
1120
- viteContent = viteContent.replace(
1121
- /export default defineConfig\s*\(\s*{/,
1122
- m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1123
- );
1124
- }
1125
-
1126
- fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1127
- console.log("✅ vite.config.(m)js Updated successfully.");
1128
- };
1129
-
1130
-
1131
-
1132
-
1133
-
1134
-
1135
-
1136
-
1137
-
1138
-
1139
- const compareVersion = (v1, v2) => {
1140
- const a = v1.split(".").map(Number);
1141
- const b = v2.split(".").map(Number);
1142
-
1143
- for (let i = 0; i < Math.max(a.length, b.length); i++) {
1144
- const num1 = a[i] || 0;
1145
- const num2 = b[i] || 0;
1146
- if (num1 > num2) return 1;
1147
- if (num1 < num2) return -1;
1148
- }
1149
- return 0;
1150
- };
1151
-
1152
-
1153
-
1154
-
1155
- const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1156
-
1157
- const checkAdmobConfigurationProperty=()=>{
1158
-
1159
-
1160
- if (!_admobConfig.ADMOB_ENABLED)
1161
- {
1162
- console.log("ℹ️ Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1163
- return;
1164
- }
1165
-
1166
-
1167
- const REQUIRED_CONFIG_KEYS = [
1168
- "isKidsApp",
1169
- "isTesting",
1170
- "isConsoleLogEnabled",
1171
- "bannerEnabled",
1172
- "interstitialEnabled",
1173
- "appOpenEnabled",
1174
- "rewardVideoEnabled",
1175
- "rewardInterstitialEnabled",
1176
- "collapsibleEnabled",
1177
- "isLandScape",
1178
- "overlappingHeight",
1179
- "isOverlappingEnable",
1180
- "bannerTypeAndroid",
1181
- "bannerTypeiOS",
1182
- "bannerTopSpaceColor",
1183
- "interstitialLoadScreenTextColor",
1184
- "interstitialLoadScreenBackgroundColor",
1185
- "beforeBannerSpace",
1186
- "whenShow",
1187
- "minimumClick",
1188
- "interstitialTimeOut",
1189
- "interstitialFirstTimeOut",
1190
- "appOpenAdsTimeOut",
1191
- "maxRetryCount",
1192
- "retrySecondsAr",
1193
- "appOpenPerSession",
1194
- "interstitialPerSession",
1195
- "appOpenFirstTimeOut"
1196
- ];
1197
-
1198
-
1199
-
1200
-
1201
-
1202
- let admobConfigInJson;
1203
-
1204
- try {
1205
- admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1206
- } catch (err) {
1207
- console.error("❌ Failed to read admob-ad-configuration.json", err);
1208
- process.exit(1);
1209
- }
1210
-
1211
- // ✅ Validate config object exists
1212
- if (!admobConfigInJson.config) {
1213
- console.error('❌ "config" object is missing in admob-ad-configuration.json');
1214
- process.exit(1);
1215
- }
1216
-
1217
-
1218
- const admobConfigMinVersion="1.4"
1219
-
1220
- if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1221
- console.error(`❌ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1222
- process.exit(1);
1223
- }
1224
-
1225
-
1226
- const config = admobConfigInJson.config;
1227
-
1228
- // ✅ Find missing properties
1229
- const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1230
- key => !(key in config)
1231
- );
1232
-
1233
-
1234
-
1235
- if (missingKeys.length > 0) {
1236
- console.error("❌ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1237
-
1238
- missingKeys.forEach(k => console.error(" - " + k));
1239
- process.exit(1);
1240
- }
1241
-
1242
-
1243
- console.log('✅ All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1244
- }
1245
-
1246
-
1247
-
1248
- function ensureGitignoreEntry(entry) {
1249
- const gitignorePath = path.join(process.cwd(), '.gitignore');
1250
-
1251
- // If .gitignore doesn't exist, create it
1252
- if (!fs.existsSync(gitignorePath)) {
1253
- fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
1254
- console.log(`✅ .gitignore created and added: ${entry}`);
1255
- return;
1256
- }
1257
-
1258
- const content = fs.readFileSync(gitignorePath, 'utf8');
1259
-
1260
- // Normalize lines (trim + remove trailing slashes for comparison)
1261
- const lines = content
1262
- .split(/\r?\n/)
1263
- .map(l => l.trim());
1264
-
1265
- const normalizedEntry = entry.replace(/\/$/, '');
1266
-
1267
- const exists = lines.some(
1268
- line => line.replace(/\/$/, '') === normalizedEntry
1269
- );
1270
-
1271
- if (exists) {
1272
- console.log(`ℹ️ .gitignore already contains: ${entry}`);
1273
- return;
1274
- }
1275
-
1276
- // Ensure file ends with newline
1277
- const separator = content.endsWith('\n') ? '' : '\n';
1278
-
1279
- fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
1280
- console.log(`✅ Added to .gitignore: ${entry}`);
1281
- }
1282
-
1283
-
1284
- ensureGitignoreEntry('buildCodeplay/');
1285
-
1286
-
1287
- // Run the validation
1288
- (async () => {
1289
- await checkPlugins();
1290
- checkAndupdateDropInViteConfig();
1291
- checkAdmobConfigurationProperty()
1292
- })();
1293
-
1294
-
1295
- /*
1296
- Release Notes
1297
-
1298
- 5.1
1299
- Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
1300
-
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const plist = require('plist');
4
+
5
+ const { readFileSync } = require("fs");
6
+
7
+
8
+
9
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
10
+
11
+ // Expected plugin list with minimum versions
12
+ const requiredPlugins = [
13
+ { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.6', required: true, baseDir: 'js' },
14
+
15
+ /*/common-(\d+\.\d+)\.js$/*/
16
+ { pattern: /common-(\d+\.\d+)(?:-beta-(\d+))?\.js$/, minVersion: '5.3', required: true, baseDir: 'js' },
17
+
18
+ { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js' },
19
+ { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.3', required: true, baseDir: 'js' },
20
+ { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true, baseDir: 'js' },
21
+ { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true, baseDir: 'js' },
22
+ { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.3', required: true, baseDir: 'js' },
23
+ { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '3.0', required: true, baseDir: 'js' },
24
+ { pattern: /Ads[\/\\]IAP-(\d+\.\d+)$/, minVersion: '2.5', isFolder: true , required: true, baseDir: 'js' },
25
+ { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '3.3', required: true, baseDir: 'js' },
26
+
27
+ // New added plugins
28
+ { pattern: /video-player-(\d+\.\d+)\.js$/, minVersion: '1.5', required: true, baseDir: 'js' },
29
+ { pattern: /image-cropper-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true, baseDir: 'js' },
30
+
31
+ { pattern: /common-(\d+\.\d+)\.less$/, minVersion: '1.5', required: true, baseDir: 'assets/css' },
32
+
33
+
34
+ // New folders
35
+ { pattern: /editor-(\d+\.\d+)$/, minVersion: '1.9', isFolder: true, required: true, baseDir: 'js' },
36
+ { pattern: /ffmpeg-(\d+\.\d+)$/, minVersion: '1.3', isFolder: true, required: true, baseDir: 'js' },
37
+ { pattern: /theme-(\d+\.\d+)$/, minVersion: '1.9', isFolder: true , required: true, baseDir: 'theme' },
38
+
39
+
40
+ { pattern: /certificatejs-(\d+\.\d+)$/, minVersion: '1.4', isFolder: true , required: true, baseDir: 'certificate' }
41
+
42
+ ];
43
+
44
+
45
+
46
+
47
+
48
+
49
+ //Check codeplay-common latest version installed or not Start
50
+ const { execSync } = require('child_process');
51
+
52
+ function getInstalledVersion(packageName) {
53
+ try {
54
+ const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
55
+ if (fs.existsSync(packageJsonPath)) {
56
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
57
+ return packageJson.version;
58
+ }
59
+ } catch (error) {
60
+ return null;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ function getLatestVersion(packageName) {
66
+ try {
67
+ return execSync(`npm view ${packageName} version`).toString().trim();
68
+ } catch (error) {
69
+ console.error(`Failed to fetch latest version for ${packageName}`);
70
+ return null;
71
+ }
72
+ }
73
+
74
+ function checkPackageVersion() {
75
+ const packageName = 'codeplay-common';
76
+ const installedVersion = getInstalledVersion(packageName);
77
+ const latestVersion = getLatestVersion(packageName);
78
+
79
+ if (!installedVersion) {
80
+ console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
81
+ process.exit(1);
82
+ }
83
+
84
+ if (installedVersion !== latestVersion) {
85
+ 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`);
86
+ process.exit(1);
87
+ }
88
+
89
+ console.log(`${packageName} is up to date (version ${installedVersion}).`);
90
+ }
91
+
92
+ // Run package version check before executing the main script
93
+ try {
94
+ checkPackageVersion();
95
+ } catch (error) {
96
+ console.error(error.message);
97
+ process.exit(1);
98
+ }
99
+
100
+ //Check codeplay-common latest version installed or not END
101
+
102
+
103
+
104
+ function compareWithBeta(installedVersion, minVersion, isBeta) {
105
+ const baseCompare = compareVersions(installedVersion, minVersion);
106
+
107
+ if (!isBeta) {
108
+ // Stable version → normal compare
109
+ return baseCompare;
110
+ }
111
+
112
+ // Beta version logic
113
+ if (baseCompare > 0) return 1; // 5.3-beta > 5.2
114
+ if (baseCompare < 0) return -1; // 5.1-beta < 5.2
115
+
116
+ // Same version but beta → LOWER than stable
117
+ return -1; // 5.2-beta < 5.2
118
+ }
119
+
120
+
121
+
122
+
123
+ const checkAppUniqueId=()=>{
124
+
125
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
126
+
127
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
128
+ const RESIZEABLE_ACTIVITY = config.android?.RESIZEABLE_ACTIVITY;
129
+ const orientation = config.android?.ORIENTATION;
130
+
131
+
132
+ let logErrorMessage="";
133
+
134
+ // 1️⃣ Check if it’s missing
135
+ if (RESIZEABLE_ACTIVITY === undefined) {
136
+ logErrorMessage+='❌ Missing android.RESIZEABLE_ACTIVITY option in capacitor.config.json.\n';
137
+ }
138
+
139
+ // 2️⃣ Check if it’s not boolean (true/false only)
140
+ else if (typeof RESIZEABLE_ACTIVITY !== 'boolean') {
141
+ logErrorMessage+='❌ Invalid android.RESIZEABLE_ACTIVITY value. Please use only true or false (without quotes).\n';
142
+ }
143
+
144
+
145
+
146
+ if (!orientation) {
147
+ logErrorMessage+='❌ Missing android.ORIENTATION option in capacitor.config.json.\n';
148
+ }
149
+
150
+ else if(orientation!="portrait" && orientation!="landscape" && orientation!="auto")
151
+ {
152
+ logErrorMessage+='❌ Spelling mistake in android.ORIENTATION option in capacitor.config.json. Please use only ["portrait" "landscape" "auto"]\n';
153
+ }
154
+
155
+
156
+ if (!appUniqueId) {
157
+ logErrorMessage+='❌ APP_UNIQUE_ID is missing in capacitor.config.json.';
158
+ }
159
+
160
+ else if (!Number.isInteger(appUniqueId)) {
161
+ logErrorMessage+='❌ APP_UNIQUE_ID must be an integer. Example: 1, 2, 3, etc.';
162
+ }
163
+
164
+
165
+
166
+ if(logErrorMessage!="")
167
+ {
168
+ console.error(logErrorMessage);
169
+ process.exit(1)
170
+ }
171
+
172
+
173
+ console.log(`✅ APP_UNIQUE_ID is valid: ${appUniqueId}`);
174
+
175
+ }
176
+
177
+ checkAppUniqueId();
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+ //@Codemirror check and install/uninstall the packages START
186
+ //const fs = require("fs");
187
+ //const path = require("path");
188
+ //const { execSync } = require("child_process");
189
+
190
+ const baseDir = path.join(__dirname, "..", "src", "js");
191
+
192
+ // Step 1: Find highest versioned folder like `editor-1.6`
193
+ const editorDirs = fs.readdirSync(baseDir)
194
+ .filter(name => /^editor-\d+\.\d+$/.test(name))
195
+ .sort((a, b) => {
196
+ const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
197
+ const [aMajor, aMinor] = getVersion(a);
198
+ const [bMajor, bMinor] = getVersion(b);
199
+ return bMajor - aMajor || bMinor - aMinor;
200
+ });
201
+
202
+ if (editorDirs.length === 0) {
203
+
204
+ console.log("@Codemirror used editor(s) are not found")
205
+ //console.error("❌ No editor-x.x folders found in src/js.");
206
+ //process.exit(1);
207
+ }
208
+ else
209
+ {
210
+
211
+ const latestEditorDir = editorDirs.sort((a, b) => {
212
+ const versionA = parseFloat(a.split('-')[1]);
213
+ const versionB = parseFloat(b.split('-')[1]);
214
+ return versionB - versionA;
215
+ })[0];
216
+
217
+ //const latestEditorDir = editorDirs[editorDirs.length - 1];
218
+ const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
219
+
220
+ if (!fs.existsSync(runJsPath)) {
221
+ console.error(`❌ run.js not found in ${latestEditorDir}`);
222
+ process.exit(1);
223
+ }
224
+
225
+ // Step 2: Execute the run.js file
226
+ console.log(`🚀 Executing ${runJsPath}...`);
227
+ execSync(`node "${runJsPath}"`, { stdio: "inherit" });
228
+ }
229
+
230
+ //@Codemirror check and install/uninstall the packages END
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
244
+
245
+ const os = require('os');
246
+
247
+ const saveToGalleryAndSaveFileCheck_iOS = () => {
248
+
249
+ // List of paths to scan
250
+ const SCAN_PATHS = [
251
+ path.resolve(__dirname, '../src/certificate'),
252
+ path.resolve(__dirname, '../src/pages'),
253
+ path.resolve(__dirname, '../src/js'),
254
+ path.resolve(__dirname, '../src/app.f7')
255
+ ];
256
+
257
+ // Directory to exclude
258
+ const EXCLUDED_DIR = path.resolve(__dirname, '../src/js/Ads');
259
+
260
+ const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
261
+
262
+
263
+ // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
264
+ const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
265
+
266
+ // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
267
+ const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
268
+
269
+
270
+
271
+
272
+
273
+ const ALLOWED_EXTENSIONS = ['.js', '.f7'];
274
+ const isMac = os.platform() === 'darwin';
275
+
276
+ let iosImportFound = false;
277
+ let androidImportFound = false;
278
+
279
+ // Files to skip completely (full or partial match)
280
+ const SKIP_FILES = [
281
+ 'pdf-3.11.174.min.js',
282
+ 'pdf.worker-3.11.174.min.js'
283
+ ,'index.browser.js'
284
+ ];
285
+
286
+
287
+ function scanDirectory(dir) {
288
+
289
+ /*
290
+ //######################### DO NOT DELETE THIS - START [Appid base validation] #####################################
291
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
292
+ const appUniqueId = config.android?.APP_UNIQUE_ID;
293
+ if (appUniqueId == "206") return;
294
+ //######################### DO NOT DELETE THIS - END [Appid base validation] #####################################
295
+ */
296
+
297
+ const stat = fs.statSync(dir);
298
+
299
+ if (stat.isFile()) {
300
+
301
+ // 🔥 Skip files in SKIP_FILES array
302
+ const baseName = path.basename(dir);
303
+ if (SKIP_FILES.includes(baseName)) {
304
+ // Just skip silently
305
+ return;
306
+ }
307
+
308
+ // Only scan allowed file extensions
309
+ if (ALLOWED_EXTENSIONS.some(ext => dir.endsWith(ext))) {
310
+ process.stdout.write(`\r🔍 Scanning: ${dir} `);
311
+
312
+ const content = fs.readFileSync(dir, 'utf8');
313
+
314
+ if (IOS_FILE_REGEX.test(content)) {
315
+ iosImportFound = true;
316
+ if (!isMac) {
317
+ console.error(`\n❌ ERROR: iOS-specific import detected in: ${dir}`);
318
+ console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
319
+ process.exit(1);
320
+ }
321
+ }
322
+ else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
323
+ androidImportFound = true;
324
+ }
325
+ }
326
+ }
327
+ else if (stat.isDirectory()) {
328
+ if (dir === EXCLUDED_DIR || path.basename(dir) === 'node_modules') return;
329
+
330
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
331
+ for (let entry of entries) {
332
+ scanDirectory(path.join(dir, entry.name));
333
+ }
334
+ }
335
+ }
336
+
337
+
338
+ // Run scan on all specified paths
339
+ for (let scanPath of SCAN_PATHS) {
340
+ if (fs.existsSync(scanPath)) {
341
+ scanDirectory(scanPath);
342
+ }
343
+ }
344
+
345
+
346
+
347
+ /* // Check src folder
348
+ if (!fs.existsSync(ROOT_DIR)) {
349
+ console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
350
+ return;
351
+ } */
352
+
353
+ //scanDirectory(ROOT_DIR);
354
+
355
+ // iOS Checks
356
+ if (isMac && !iosImportFound) {
357
+ console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
358
+ process.exit(1);
359
+ } else if (isMac && iosImportFound) {
360
+ console.log('✅ iOS version detected for macOS build.');
361
+ } else if (!iosImportFound) {
362
+ console.log('✅ No iOS-specific imports detected for non-macOS.');
363
+ }
364
+
365
+ // Android Checks
366
+ if (androidImportFound) {
367
+ console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
368
+
369
+ if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
370
+ console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
371
+ return;
372
+ }
373
+
374
+ let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
375
+
376
+ if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
377
+ console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
378
+
379
+ manifestContent = manifestContent.replace(
380
+ /<application([^>]*)>/,
381
+ (match, attrs) => {
382
+ if (attrs.includes('android:requestLegacyExternalStorage')) return match;
383
+ return `<application${attrs} android:requestLegacyExternalStorage="true">`;
384
+ }
385
+ );
386
+
387
+ fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
388
+ console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
389
+ } else {
390
+ console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
391
+ }
392
+ } else {
393
+ console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
394
+ }
395
+ };
396
+
397
+ saveToGalleryAndSaveFileCheck_iOS();
398
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
399
+
400
+
401
+
402
+
403
+
404
+
405
+
406
+
407
+
408
+
409
+
410
+
411
+
412
+ /*
413
+ // Clean up AppleDouble files (._*) created by macOS START
414
+ if (process.platform === 'darwin') {
415
+ try {
416
+ console.log('🧹 Cleaning up AppleDouble files (._*)...');
417
+ execSync(`find . -name '._*' -delete`);
418
+ console.log('✅ AppleDouble files removed.');
419
+ } catch (err) {
420
+ console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
421
+ }
422
+ } else {
423
+ console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
424
+ }
425
+
426
+ // Clean up AppleDouble files (._*) created by macOS END
427
+ */
428
+
429
+
430
+
431
+
432
+
433
+
434
+ //In routes.js file check static import START
435
+
436
+ const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
437
+ const routesContent = fs.readFileSync(routesPath, 'utf-8');
438
+
439
+ let inBlockComment = false;
440
+ const lines = routesContent.split('\n');
441
+
442
+ const allowedImport = `import HomePage from '../pages/home.f7';`;
443
+ const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
444
+ const badImports = [];
445
+
446
+ lines.forEach((line, index) => {
447
+ const trimmed = line.trim();
448
+
449
+ // Handle block comment start and end
450
+ if (trimmed.startsWith('/*')) inBlockComment = true;
451
+ if (inBlockComment && trimmed.endsWith('*/')) {
452
+ inBlockComment = false;
453
+ return;
454
+ }
455
+
456
+ // Skip if inside block comment or line comment
457
+ if (inBlockComment || trimmed.startsWith('//')) return;
458
+
459
+ // Match static .f7 import
460
+ if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
461
+ badImports.push({ line: trimmed, number: index + 1 });
462
+ }
463
+ });
464
+
465
+ if (badImports.length > 0) {
466
+ console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
467
+ console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
468
+ console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
469
+ console.error(`
470
+
471
+ import HomePage from '../pages/home.f7';
472
+
473
+ const routes = [
474
+ {
475
+ path: '/',
476
+ component:HomePage,
477
+ },
478
+ {
479
+ path: '/ProfilePage/',
480
+ async async({ resolve }) {
481
+ const page = await import('../pages/profile.f7');
482
+ resolve({ component: page.default });
483
+ },
484
+ }]
485
+ `);
486
+
487
+ badImports.forEach(({ line, number }) => {
488
+ console.error(`${number}: ${line}`);
489
+ });
490
+
491
+ process.exit(1);
492
+ } else {
493
+ console.log('✅ routes.js passed the .f7 import check.');
494
+ }
495
+
496
+ //In routes.js file check static import END
497
+
498
+
499
+
500
+
501
+
502
+
503
+
504
+
505
+
506
+
507
+
508
+
509
+
510
+ // Check and change the "BridgeWebViewClient.java" file START
511
+ /*
512
+ For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
513
+ */
514
+
515
+
516
+ const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
517
+
518
+ // Read the file
519
+ if (!fs.existsSync(bridgeWebViewClientFilePath)) {
520
+ console.error('❌ Error: BridgeWebViewClient.java not found.');
521
+ process.exit(1);
522
+ }
523
+
524
+ let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
525
+
526
+ // Define old and new code
527
+ const oldCodeStart = `@Override
528
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
529
+ super.onRenderProcessGone(view, detail);
530
+ boolean result = false;
531
+
532
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
533
+ if (webViewListeners != null) {
534
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
535
+ result = listener.onRenderProcessGone(view, detail) || result;
536
+ }
537
+ }
538
+
539
+ return result;
540
+ }`;
541
+
542
+ const newCode = `@Override
543
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
544
+ super.onRenderProcessGone(view, detail);
545
+
546
+ boolean result = false;
547
+
548
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
549
+ if (webViewListeners != null) {
550
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
551
+ result = listener.onRenderProcessGone(view, detail) || result;
552
+ }
553
+ }
554
+
555
+ if (!result) {
556
+ // If no one handled it, handle it ourselves!
557
+
558
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
559
+ if (detail.didCrash()) {
560
+ //Log.e("CapacitorWebView", "WebView crashed internally!");
561
+ } else {
562
+ //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
563
+ }
564
+ }*/
565
+
566
+ view.post(() -> {
567
+ Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
568
+ });
569
+
570
+ view.reload(); // Safely reload WebView
571
+
572
+ return true; // We handled it
573
+ }
574
+
575
+ return result;
576
+ }`;
577
+
578
+ // Step 1: Update method if needed
579
+ let updated = false;
580
+
581
+ if (fileContent.includes(oldCodeStart)) {
582
+ console.log('✅ Found old onRenderProcessGone method. Replacing it...');
583
+ fileContent = fileContent.replace(oldCodeStart, newCode);
584
+ updated = true;
585
+ } else if (fileContent.includes(newCode)) {
586
+ console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
587
+ } else {
588
+ console.error('❌ Error: Neither old nor new code found. Unexpected content.');
589
+ process.exit(1);
590
+ }
591
+
592
+ // Step 2: Check and add import if missing
593
+ const importToast = 'import android.widget.Toast;';
594
+ if (!fileContent.includes(importToast)) {
595
+ console.log('✅ Adding missing import for Toast...');
596
+ const importRegex = /import\s+[^;]+;/g;
597
+ const matches = [...fileContent.matchAll(importRegex)];
598
+
599
+ if (matches.length > 0) {
600
+ const lastImport = matches[matches.length - 1];
601
+ const insertPosition = lastImport.index + lastImport[0].length;
602
+ fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
603
+ updated = true;
604
+ } else {
605
+ console.error('❌ Error: No import section found in file.');
606
+ process.exit(1);
607
+ }
608
+ } else {
609
+ console.log('ℹ️ Import for Toast already exists. No changes needed.');
610
+ }
611
+
612
+ // Step 3: Save if updated
613
+ if (updated) {
614
+ fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
615
+ console.log('✅ File updated successfully.');
616
+ } else {
617
+ console.log('ℹ️ No changes needed.');
618
+ }
619
+
620
+
621
+
622
+
623
+ // Check and change the "BridgeWebViewClient.java" file END
624
+
625
+
626
+
627
+
628
+
629
+
630
+
631
+
632
+ /*
633
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
634
+
635
+ // Build the path dynamically like you requested
636
+ const gradlePath = path.join(
637
+ process.cwd(),
638
+ 'android',
639
+ 'build.gradle'
640
+ );
641
+
642
+ // Read the existing build.gradle
643
+ let gradleContent = fs.readFileSync(gradlePath, 'utf8');
644
+
645
+ // Add `ext.kotlin_version` if it's not already there
646
+ if (!gradleContent.includes('ext.kotlin_version')) {
647
+ gradleContent = gradleContent.replace(
648
+ /buildscript\s*{/,
649
+ `buildscript {\n ext.kotlin_version = '2.1.0'`
650
+ );
651
+ }
652
+
653
+ // Add Kotlin classpath if it's not already there
654
+ if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
655
+ gradleContent = gradleContent.replace(
656
+ /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
657
+ `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
658
+ );
659
+ }
660
+
661
+ // Write back the modified content
662
+ fs.writeFileSync(gradlePath, gradleContent, 'utf8');
663
+
664
+ console.log('✅ Kotlin version updated in build.gradle.');
665
+
666
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
667
+ */
668
+
669
+
670
+
671
+
672
+
673
+
674
+
675
+
676
+ let _admobConfig;
677
+
678
+
679
+
680
+ const androidPlatformPath = path.join(process.cwd(), 'android');
681
+ const iosPlatformPath = path.join(process.cwd(), 'ios');
682
+ const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
683
+ const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
684
+ const resourcesPath = path.join(process.cwd(), 'resources', 'res');
685
+ const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
686
+ const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
687
+
688
+ function fileExists(filePath) {
689
+ return fs.existsSync(filePath);
690
+ }
691
+
692
+ function copyFolderSync(source, target) {
693
+ if (!fs.existsSync(target)) {
694
+ fs.mkdirSync(target, { recursive: true });
695
+ }
696
+
697
+ fs.readdirSync(source).forEach(file => {
698
+ const sourceFile = path.join(source, file);
699
+ const targetFile = path.join(target, file);
700
+
701
+ if (fs.lstatSync(sourceFile).isDirectory()) {
702
+ copyFolderSync(sourceFile, targetFile);
703
+ } else {
704
+ fs.copyFileSync(sourceFile, targetFile);
705
+ }
706
+ });
707
+ }
708
+
709
+ function checkAndCopyResources() {
710
+ if (fileExists(resourcesPath)) {
711
+ copyFolderSync(resourcesPath, androidResPath);
712
+ console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
713
+ } else {
714
+ console.log('resources/res folder not found.');
715
+
716
+ if (fileExists(localNotificationsPluginPath)) {
717
+ throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
718
+ }
719
+ }
720
+ }
721
+
722
+
723
+
724
+
725
+
726
+
727
+
728
+
729
+ function getAdMobConfig() {
730
+ if (!fileExists(configPath)) {
731
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
732
+ }
733
+
734
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
735
+ const admobConfig = config.plugins?.AdMob;
736
+
737
+ if (!admobConfig) {
738
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
739
+ }
740
+
741
+ // Default to true if ADMOB_ENABLED is not specified
742
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
743
+
744
+ if (!isEnabled) {
745
+ return { ADMOB_ENABLED: false }; // Skip further validation
746
+ }
747
+
748
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
749
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
750
+ }
751
+
752
+ return {
753
+ ADMOB_ENABLED: true,
754
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
755
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
756
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
757
+ };
758
+ }
759
+
760
+ function validateAndroidBuildOptions() {
761
+
762
+
763
+ if (!fileExists(configPath)) {
764
+ console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
765
+ process.exit(1);
766
+ }
767
+
768
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
769
+
770
+ const targetAppId=config.appId
771
+
772
+ const buildOptions = config.android?.buildOptions;
773
+
774
+ if (!buildOptions) {
775
+ console.log('❌ Missing android.buildOptions in capacitor.config.json.');
776
+ process.exit(1);
777
+ }
778
+
779
+ const requiredProps = [
780
+ 'keystorePath',
781
+ 'keystorePassword',
782
+ 'keystoreAlias',
783
+ 'keystoreAliasPassword',
784
+ 'releaseType',
785
+ 'signingType'
786
+ ];
787
+
788
+ const missing = requiredProps.filter(prop => !buildOptions[prop]);
789
+
790
+ if (missing.length > 0) {
791
+ console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
792
+ process.exit(1);
793
+ }
794
+
795
+
796
+ const keystorePath=buildOptions.keystorePath
797
+ const keyFileName = path.basename(keystorePath);
798
+
799
+
800
+
801
+ const keystoreMap = {
802
+ "gameskey.jks": [
803
+ "com.cube.blaster",
804
+ ],
805
+ "htmleditorkeystoke.jks": [
806
+ "com.HTML.AngularJS.Codeplay",
807
+ "com.html.codeplay.pro",
808
+ "com.bootstrap.code.play",
809
+ "com.kids.learning.master",
810
+ "com.Simple.Barcode.Scanner"
811
+ ]
812
+ };
813
+
814
+ // find which keystore is required for the given targetAppId
815
+ let requiredKey = "newappskey.jks"; // default
816
+ for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
817
+ if (appIds.includes(targetAppId)) {
818
+ requiredKey = keyFile;
819
+ break;
820
+ }
821
+ }
822
+
823
+ // validate
824
+ if (keyFileName !== requiredKey) {
825
+ console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
826
+ process.exit(1);
827
+ }
828
+
829
+
830
+
831
+
832
+
833
+ // optionally return them
834
+ //return buildOptions;
835
+ }
836
+
837
+ function updatePluginXml(admobConfig) {
838
+ if (!fileExists(pluginPath)) {
839
+ console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
840
+ return;
841
+ }
842
+
843
+ let pluginContent = fs.readFileSync(pluginPath, 'utf8');
844
+
845
+ pluginContent = pluginContent
846
+ .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
847
+ .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
848
+
849
+ fs.writeFileSync(pluginPath, pluginContent, 'utf8');
850
+ console.log('✅ AdMob IDs successfully updated in plugin.xml');
851
+ }
852
+
853
+ function updateInfoPlist(admobConfig) {
854
+ if (!fileExists(infoPlistPath)) {
855
+ console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
856
+ return;
857
+ }
858
+
859
+ const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
860
+ const plistData = plist.parse(plistContent);
861
+
862
+ plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
863
+ plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
864
+ plistData.GADDelayAppMeasurementInit = true;
865
+
866
+ const updatedPlistContent = plist.build(plistData);
867
+ fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
868
+ console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
869
+ }
870
+
871
+
872
+ try {
873
+ if (!fileExists(configPath)) {
874
+ throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
875
+ }
876
+
877
+ if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
878
+ throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
879
+ }
880
+
881
+ checkAndCopyResources();
882
+
883
+
884
+
885
+ _admobConfig = getAdMobConfig();
886
+
887
+
888
+
889
+
890
+
891
+ // Proceed only if ADMOB_ENABLED is true
892
+ if (_admobConfig.ADMOB_ENABLED) {
893
+ if (fileExists(androidPlatformPath)) {
894
+ updatePluginXml(_admobConfig);
895
+ }
896
+
897
+ if (fileExists(iosPlatformPath)) {
898
+ updateInfoPlist(_admobConfig);
899
+ }
900
+ }
901
+
902
+
903
+ } catch (error) {
904
+ console.error(error.message);
905
+ process.exit(1); // Stop execution if there's a critical error
906
+ }
907
+
908
+
909
+
910
+ validateAndroidBuildOptions();
911
+
912
+
913
+
914
+
915
+
916
+
917
+ // Check all the codeplays plugins version START
918
+
919
+
920
+ const readline = require('readline');
921
+
922
+
923
+ //const srcDir = path.join(__dirname, 'src');
924
+ const srcDir = path.join(process.cwd(), 'src');
925
+ let outdatedPlugins = [];
926
+
927
+ function parseVersion(ver) {
928
+ return ver.split('.').map(n => parseInt(n, 10));
929
+ }
930
+
931
+ function compareVersions(v1, v2) {
932
+ const [a1, b1] = parseVersion(v1);
933
+ const [a2, b2] = parseVersion(v2);
934
+ if (a1 !== a2) return a1 - a2;
935
+ return b1 - b2;
936
+ }
937
+
938
+ function walkSync(dir, filelist = []) {
939
+ fs.readdirSync(dir).forEach(file => {
940
+ const fullPath = path.join(dir, file);
941
+ const stat = fs.statSync(fullPath);
942
+ if (stat.isDirectory()) {
943
+ walkSync(fullPath, filelist);
944
+ } else {
945
+ filelist.push(fullPath);
946
+ }
947
+ });
948
+ return filelist;
949
+ }
950
+
951
+
952
+
953
+ function getSearchRoot(plugin) {
954
+ return path.join(srcDir, plugin.baseDir || 'js');
955
+ }
956
+
957
+ function checkPlugins() {
958
+ return new Promise((resolve, reject) => {
959
+ const files = walkSync(srcDir);
960
+
961
+ for (const plugin of requiredPlugins) {
962
+ const searchRoot = getSearchRoot(plugin);
963
+
964
+ if (plugin.isFolder) {
965
+ if (!fs.existsSync(searchRoot)) continue;
966
+
967
+ const subDirs = fs.readdirSync(searchRoot)
968
+ .map(name => path.join(searchRoot, name))
969
+ .filter(p => fs.statSync(p).isDirectory());
970
+
971
+ for (const dir of subDirs) {
972
+ const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
973
+ const match = plugin.pattern.exec(relativePath);
974
+
975
+ if (match) {
976
+ const currentVersion = match[1];
977
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
978
+ outdatedPlugins.push({
979
+ name: relativePath,
980
+ currentVersion,
981
+ requiredVersion: plugin.minVersion
982
+ });
983
+ }
984
+ }
985
+ }
986
+ continue;
987
+ }
988
+
989
+ const matchedFile = files.find(file =>
990
+ file.startsWith(searchRoot) && plugin.pattern.test(file)
991
+ );
992
+
993
+ if (matchedFile) {
994
+ const match = plugin.pattern.exec(matchedFile);
995
+ if (match) {
996
+ const currentVersion = match[1];
997
+ const isBeta = !!match[2];
998
+
999
+ const cmp = plugin.pattern.source.includes('beta')
1000
+ ? compareWithBeta(currentVersion, plugin.minVersion, isBeta)
1001
+ : compareVersions(currentVersion, plugin.minVersion);
1002
+
1003
+ if (cmp < 0) {
1004
+ outdatedPlugins.push({
1005
+ name: path.relative(srcDir, matchedFile),
1006
+ currentVersion: isBeta ? `${currentVersion}-beta` : currentVersion,
1007
+ requiredVersion: plugin.minVersion
1008
+ });
1009
+ }
1010
+ }
1011
+ }
1012
+ }
1013
+
1014
+ if (outdatedPlugins.length > 0) {
1015
+ console.log('\n❗ The following plugins are outdated:');
1016
+ outdatedPlugins.forEach(p => {
1017
+ console.log(` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion})`);
1018
+ });
1019
+
1020
+ const rl = readline.createInterface({
1021
+ input: process.stdin,
1022
+ output: process.stdout
1023
+ });
1024
+
1025
+ rl.question('\nAre you sure you want to continue without updating these plugins? (y/n): ', answer => {
1026
+ rl.close();
1027
+
1028
+ if (answer.toLowerCase() !== 'y') {
1029
+ console.log('\n❌ Build cancelled due to outdated plugins.');
1030
+ process.exit(1);
1031
+ } else {
1032
+ console.log('\n✅ Continuing build...');
1033
+ resolve();
1034
+ }
1035
+ });
1036
+ } else {
1037
+ console.log('✅ All plugin versions are up to date.');
1038
+ resolve();
1039
+ }
1040
+ });
1041
+ }
1042
+
1043
+
1044
+
1045
+
1046
+
1047
+
1048
+
1049
+
1050
+ // Check all the codeplays plugins version START
1051
+
1052
+
1053
+
1054
+
1055
+ // ====================================================================
1056
+ // AUTO-ADD esbuild.drop: ['console','debugger'] to vite.config.js / mjs
1057
+ // ====================================================================
1058
+
1059
+
1060
+
1061
+ const checkAndupdateDropInViteConfig = () => {
1062
+
1063
+ const possibleFiles = [
1064
+ "vite.config.js",
1065
+ "vite.config.mjs"
1066
+ ];
1067
+
1068
+ // Detect existing config file
1069
+ const viteConfigPath = possibleFiles
1070
+ .map(file => path.join(process.cwd(), file))
1071
+ .find(filePath => fs.existsSync(filePath));
1072
+
1073
+ if (!viteConfigPath) {
1074
+ console.warn("⚠️ No vite config found. Skipping.");
1075
+ return;
1076
+ }
1077
+
1078
+ //console.log("📄 Using:", viteConfigPath.split("/").pop());
1079
+
1080
+ let viteContent = fs.readFileSync(viteConfigPath, "utf8");
1081
+
1082
+ // Skip if already exists
1083
+ if (/drop\s*:\s*\[.*['"]console['"].*\]/.test(viteContent)) {
1084
+ console.log("ℹ️ vite.config.(m)js already Updated. Skipping...");
1085
+ return;
1086
+ }
1087
+
1088
+ console.log("🔧 Adding esbuild.drop ...");
1089
+
1090
+ // If esbuild block exists
1091
+ if (/esbuild\s*:\s*{/.test(viteContent)) {
1092
+ viteContent = viteContent.replace(
1093
+ /esbuild\s*:\s*{([\s\S]*?)(^ {0,8})}/m,
1094
+ (full, inner, indent) => {
1095
+
1096
+ let lines = inner
1097
+ .split("\n")
1098
+ .map(l => l.trim())
1099
+ .filter(Boolean);
1100
+
1101
+ // Fix last comma
1102
+ if (lines.length > 0) {
1103
+ lines[lines.length - 1] =
1104
+ lines[lines.length - 1].replace(/,+$/, "") + ",";
1105
+ }
1106
+
1107
+ // Re-indent
1108
+ lines = lines.map(l => indent + " " + l);
1109
+
1110
+ // Add drop
1111
+ lines.push(`${indent} drop: ['console','debugger'],`);
1112
+
1113
+ return `esbuild: {\n${lines.join("\n")}\n${indent}}`;
1114
+ }
1115
+ );
1116
+ }
1117
+
1118
+ // If esbuild missing
1119
+ else {
1120
+ viteContent = viteContent.replace(
1121
+ /export default defineConfig\s*\(\s*{/,
1122
+ m => `${m}\n esbuild: {\n drop: ['console','debugger'],\n },`
1123
+ );
1124
+ }
1125
+
1126
+ fs.writeFileSync(viteConfigPath, viteContent, "utf8");
1127
+ console.log("✅ vite.config.(m)js Updated successfully.");
1128
+ };
1129
+
1130
+
1131
+
1132
+
1133
+
1134
+
1135
+
1136
+
1137
+
1138
+
1139
+ const compareVersion = (v1, v2) => {
1140
+ const a = v1.split(".").map(Number);
1141
+ const b = v2.split(".").map(Number);
1142
+
1143
+ for (let i = 0; i < Math.max(a.length, b.length); i++) {
1144
+ const num1 = a[i] || 0;
1145
+ const num2 = b[i] || 0;
1146
+ if (num1 > num2) return 1;
1147
+ if (num1 < num2) return -1;
1148
+ }
1149
+ return 0;
1150
+ };
1151
+
1152
+
1153
+
1154
+
1155
+ const admobConfigPath = path.join('src', 'js','Ads', 'admob-ad-configuration.json');
1156
+
1157
+ const checkAdmobConfigurationProperty=()=>{
1158
+
1159
+
1160
+ if (!_admobConfig.ADMOB_ENABLED)
1161
+ {
1162
+ console.log("ℹ️ Admob is not enabled so 'admob-ad-configuration.json' checking is skipping...");
1163
+ return;
1164
+ }
1165
+
1166
+
1167
+ const REQUIRED_CONFIG_KEYS = [
1168
+ "isKidsApp",
1169
+ "isTesting",
1170
+ "isConsoleLogEnabled",
1171
+ "bannerEnabled",
1172
+ "interstitialEnabled",
1173
+ "appOpenEnabled",
1174
+ "rewardVideoEnabled",
1175
+ "rewardInterstitialEnabled",
1176
+ "collapsibleEnabled",
1177
+ "isLandScape",
1178
+ "overlappingHeight",
1179
+ "isOverlappingEnable",
1180
+ "bannerTypeAndroid",
1181
+ "bannerTypeiOS",
1182
+ "bannerTopSpaceColor",
1183
+ "interstitialLoadScreenTextColor",
1184
+ "interstitialLoadScreenBackgroundColor",
1185
+ "beforeBannerSpace",
1186
+ "whenShow",
1187
+ "minimumClick",
1188
+ "interstitialTimeOut",
1189
+ "interstitialFirstTimeOut",
1190
+ "appOpenAdsTimeOut",
1191
+ "maxRetryCount",
1192
+ "retrySecondsAr",
1193
+ "appOpenPerSession",
1194
+ "interstitialPerSession",
1195
+ "appOpenFirstTimeOut"
1196
+ ];
1197
+
1198
+
1199
+
1200
+
1201
+
1202
+ let admobConfigInJson;
1203
+
1204
+ try {
1205
+ admobConfigInJson = JSON.parse(readFileSync(admobConfigPath, "utf8"));
1206
+ } catch (err) {
1207
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
1208
+ process.exit(1);
1209
+ }
1210
+
1211
+ // ✅ Validate config object exists
1212
+ if (!admobConfigInJson.config) {
1213
+ console.error('❌ "config" object is missing in admob-ad-configuration.json');
1214
+ process.exit(1);
1215
+ }
1216
+
1217
+
1218
+ const admobConfigMinVersion="1.4"
1219
+
1220
+ if (compareVersion(admobConfigInJson.VERSION, admobConfigMinVersion) < 0) {
1221
+ console.error(`❌ Please use at-least version ${admobConfigMinVersion} in "src/js/Ads/admob-ad-configuration.json"`);
1222
+ process.exit(1);
1223
+ }
1224
+
1225
+
1226
+ const config = admobConfigInJson.config;
1227
+
1228
+ // ✅ Find missing properties
1229
+ const missingKeys = REQUIRED_CONFIG_KEYS.filter(
1230
+ key => !(key in config)
1231
+ );
1232
+
1233
+
1234
+
1235
+ if (missingKeys.length > 0) {
1236
+ console.error("❌ Missing required configuration keys. Please check it in 'src/js/Ads/admob-ad-configuration.json'");
1237
+
1238
+ missingKeys.forEach(k => console.error(" - " + k));
1239
+ process.exit(1);
1240
+ }
1241
+
1242
+
1243
+ console.log('✅ All keys exist. in "admob-ad-configuration.json file" Configuration looks good.');
1244
+ }
1245
+
1246
+
1247
+
1248
+ function ensureGitignoreEntry(entry) {
1249
+ const gitignorePath = path.join(process.cwd(), '.gitignore');
1250
+
1251
+ // If .gitignore doesn't exist, create it
1252
+ if (!fs.existsSync(gitignorePath)) {
1253
+ fs.writeFileSync(gitignorePath, `${entry}\n`, 'utf8');
1254
+ console.log(`✅ .gitignore created and added: ${entry}`);
1255
+ return;
1256
+ }
1257
+
1258
+ const content = fs.readFileSync(gitignorePath, 'utf8');
1259
+
1260
+ // Normalize lines (trim + remove trailing slashes for comparison)
1261
+ const lines = content
1262
+ .split(/\r?\n/)
1263
+ .map(l => l.trim());
1264
+
1265
+ const normalizedEntry = entry.replace(/\/$/, '');
1266
+
1267
+ const exists = lines.some(
1268
+ line => line.replace(/\/$/, '') === normalizedEntry
1269
+ );
1270
+
1271
+ if (exists) {
1272
+ console.log(`ℹ️ .gitignore already contains: ${entry}`);
1273
+ return;
1274
+ }
1275
+
1276
+ // Ensure file ends with newline
1277
+ const separator = content.endsWith('\n') ? '' : '\n';
1278
+
1279
+ fs.appendFileSync(gitignorePath, `${separator}${entry}\n`, 'utf8');
1280
+ console.log(`✅ Added to .gitignore: ${entry}`);
1281
+ }
1282
+
1283
+
1284
+ ensureGitignoreEntry('buildCodeplay/');
1285
+
1286
+
1287
+ // Run the validation
1288
+ (async () => {
1289
+ await checkPlugins();
1290
+ checkAndupdateDropInViteConfig();
1291
+ checkAdmobConfigurationProperty()
1292
+ })();
1293
+
1294
+
1295
+ // ======================================================
1296
+ // Validate theme folder location (src/js/theme is NOT allowed)
1297
+ // ======================================================
1298
+
1299
+ function validateThemeFolderLocation() {
1300
+ const oldThemePath = path.join(process.cwd(), 'src', 'js', 'theme');
1301
+ const newThemePath = path.join(process.cwd(), 'src', 'theme');
1302
+
1303
+ // ❌ Block old structure
1304
+ if (fs.existsSync(oldThemePath)) {
1305
+ console.error(
1306
+ '\n❌ INVALID PROJECT STRUCTURE DETECTED\n' +
1307
+ '--------------------------------------------------\n' +
1308
+ 'The "theme" folder must NOT be inside:\n' +
1309
+ ' src/js/theme\n\n' +
1310
+ '✅ Correct location is:\n' +
1311
+ ' src/theme\n\n' +
1312
+ '🛑 Please move the folder and re-run the build.\n'
1313
+ );
1314
+ process.exit(1);
1315
+ }
1316
+
1317
+ // ⚠️ Optional warning if new theme folder is missing
1318
+ if (!fs.existsSync(newThemePath)) {
1319
+ console.warn(
1320
+ '\n⚠️ WARNING: "src/theme" folder not found.\n' +
1321
+ 'If your app uses themes, please ensure it exists.\n'
1322
+ );
1323
+ } else {
1324
+ console.log('✅ Theme folder structure validated (src/theme).');
1325
+ }
1326
+ }
1327
+ validateThemeFolderLocation()
1328
+
1329
+
1330
+
1331
+
1332
+ /*
1333
+ Release Notes
1334
+
1335
+ 5.1
1336
+ Kotlin version update is commented. Previously admob is not worked if not update the kotlin version to higher version
1337
+
1301
1338
  */