codeplay-common 1.8.6 → 1.8.8

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,839 +1,890 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const plist = require('plist');
4
-
5
-
6
- // Expected plugin list with minimum versions
7
- const requiredPlugins = [
8
- { pattern: /backbutton-(\d+\.\d+)\.js$/, minVersion: '1.4', required: true },
9
- { pattern: /common-(\d+\.\d+)\.js$/, minVersion: '4.0', required: true },
10
- { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true },
11
- { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.3', required: true },
12
- { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true },
13
- { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true },
14
- { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.1', required: true },
15
- { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '2.5', required: true },
16
- { pattern: /Ads[\/\\]IAP-(\d+\.\d+)$/, minVersion: '2.5', isFolder: true , required: true},
17
- { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '2.8', required: true }
18
- ];
19
-
20
-
21
-
22
-
23
-
24
-
25
- //Check codeplay-common latest version installed or not Start
26
- const { execSync } = require('child_process');
27
-
28
- function getInstalledVersion(packageName) {
29
- try {
30
- const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
31
- if (fs.existsSync(packageJsonPath)) {
32
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
33
- return packageJson.version;
34
- }
35
- } catch (error) {
36
- return null;
37
- }
38
- return null;
39
- }
40
-
41
- function getLatestVersion(packageName) {
42
- try {
43
- return execSync(`npm view ${packageName} version`).toString().trim();
44
- } catch (error) {
45
- console.error(`Failed to fetch latest version for ${packageName}`);
46
- return null;
47
- }
48
- }
49
-
50
- function checkPackageVersion() {
51
- const packageName = 'codeplay-common';
52
- const installedVersion = getInstalledVersion(packageName);
53
- const latestVersion = getLatestVersion(packageName);
54
-
55
- if (!installedVersion) {
56
- console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
57
- process.exit(1);
58
- }
59
-
60
- if (installedVersion !== latestVersion) {
61
- 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`);
62
- process.exit(1);
63
- }
64
-
65
- console.log(`${packageName} is up to date (version ${installedVersion}).`);
66
- }
67
-
68
- // Run package version check before executing the main script
69
- try {
70
- checkPackageVersion();
71
- } catch (error) {
72
- console.error(error.message);
73
- process.exit(1);
74
- }
75
-
76
- //Check codeplay-common latest version installed or not END
77
-
78
-
79
-
80
-
81
-
82
-
83
-
84
-
85
-
86
- //@Codemirror check and install/uninstall the packages START
87
- //const fs = require("fs");
88
- //const path = require("path");
89
- //const { execSync } = require("child_process");
90
-
91
- const baseDir = path.join(__dirname, "..", "src", "js");
92
-
93
- // Step 1: Find highest versioned folder like `editor-1.6`
94
- const editorDirs = fs.readdirSync(baseDir)
95
- .filter(name => /^editor-\d+\.\d+$/.test(name))
96
- .sort((a, b) => {
97
- const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
98
- const [aMajor, aMinor] = getVersion(a);
99
- const [bMajor, bMinor] = getVersion(b);
100
- return bMajor - aMajor || bMinor - aMinor;
101
- });
102
-
103
- if (editorDirs.length === 0) {
104
-
105
- console.log("@Codemirror used editor(s) are not found")
106
- //console.error("❌ No editor-x.x folders found in src/js.");
107
- //process.exit(1);
108
- }
109
- else
110
- {
111
-
112
- const latestEditorDir = editorDirs.sort((a, b) => {
113
- const versionA = parseFloat(a.split('-')[1]);
114
- const versionB = parseFloat(b.split('-')[1]);
115
- return versionB - versionA;
116
- })[0];
117
-
118
- //const latestEditorDir = editorDirs[editorDirs.length - 1];
119
- const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
120
-
121
- if (!fs.existsSync(runJsPath)) {
122
- console.error(`❌ run.js not found in ${latestEditorDir}`);
123
- process.exit(1);
124
- }
125
-
126
- // Step 2: Execute the run.js file
127
- console.log(`🚀 Executing ${runJsPath}...`);
128
- execSync(`node "${runJsPath}"`, { stdio: "inherit" });
129
- }
130
-
131
- //@Codemirror check and install/uninstall the packages END
132
-
133
-
134
-
135
-
136
-
137
-
138
-
139
-
140
-
141
-
142
-
143
-
144
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
145
-
146
- const os = require('os');
147
-
148
- const saveToGalleryAndSaveFileCheck_iOS = () => {
149
- const ROOT_DIR = path.resolve(__dirname, '../src');
150
-
151
- const IOS_FILE_REGEX = /(?:import|require)?\s*\(?['"].*saveToGalleryAndSaveAnyFile-\d+(\.\d+)?-ios\.js['"]\)?/;
152
- const ALLOWED_EXTENSIONS = ['.js', '.f7'];
153
- const isMac = os.platform() === 'darwin';
154
-
155
- let iosImportFound = false;
156
-
157
- function scanDirectory(dir) {
158
- const entries = fs.readdirSync(dir, { withFileTypes: true });
159
-
160
- for (let entry of entries) {
161
- const fullPath = path.join(dir, entry.name);
162
-
163
- if (entry.isDirectory()) {
164
- if (entry.name === 'node_modules') continue;
165
- scanDirectory(fullPath);
166
- } else if (
167
- entry.isFile() &&
168
- ALLOWED_EXTENSIONS.some(ext => fullPath.endsWith(ext))
169
- ) {
170
- const content = fs.readFileSync(fullPath, 'utf8');
171
- const matches = content.match(IOS_FILE_REGEX);
172
- if (matches) {
173
- iosImportFound = true;
174
- //console.error(`\n❌❌❌ BIG ERROR: iOS-specific import detected in: ${fullPath}`);
175
- //console.error(`🔍 Matched: ${matches[0]}\n`);
176
- if (!isMac) {
177
- console.error(`\n❌❌❌ BIG ERROR: iOS-specific import detected in: ${fullPath}`);
178
- console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
179
- process.exit(1);
180
- }
181
- }
182
- }
183
- }
184
- }
185
-
186
- // Check if src folder exists first
187
- if (!fs.existsSync(ROOT_DIR)) {
188
- console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
189
- return;
190
- }
191
-
192
- scanDirectory(ROOT_DIR);
193
-
194
- if (isMac && !iosImportFound) {
195
- console.warn(`\x1b[31m\n⚠️⚠️⚠️ WARNING: You're on macOS but no iOS-specific file (saveToGalleryAndSaveAnyFile-x.x-ios.js) was found.\x1b[0m`);
196
- console.warn(`👉 You may want to double-check your imports for the iOS platform.\n`);
197
- process.exit(1);
198
- } else if (isMac && iosImportFound) {
199
- console.log('✅ iOS file detected as expected for macOS.');
200
- } else if (!iosImportFound) {
201
- console.log('✅ No iOS-specific file imports detected for non-macOS.');
202
- }
203
- };
204
-
205
- saveToGalleryAndSaveFileCheck_iOS();
206
- // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
207
-
208
-
209
-
210
-
211
-
212
-
213
-
214
-
215
-
216
-
217
-
218
-
219
-
220
- /*
221
- // Clean up AppleDouble files (._*) created by macOS START
222
- if (process.platform === 'darwin') {
223
- try {
224
- console.log('🧹 Cleaning up AppleDouble files (._*)...');
225
- execSync(`find . -name '._*' -delete`);
226
- console.log('✅ AppleDouble files removed.');
227
- } catch (err) {
228
- console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
229
- }
230
- } else {
231
- console.log('ℹ️ Skipping AppleDouble cleanup not a macOS machine.');
232
- }
233
-
234
- // Clean up AppleDouble files (._*) created by macOS END
235
- */
236
-
237
-
238
-
239
-
240
-
241
-
242
- //In routes.js file check static import START
243
-
244
- const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
245
- const routesContent = fs.readFileSync(routesPath, 'utf-8');
246
-
247
- let inBlockComment = false;
248
- const lines = routesContent.split('\n');
249
-
250
- const allowedImport = `import HomePage from '../pages/home.f7';`;
251
- const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
252
- const badImports = [];
253
-
254
- lines.forEach((line, index) => {
255
- const trimmed = line.trim();
256
-
257
- // Handle block comment start and end
258
- if (trimmed.startsWith('/*')) inBlockComment = true;
259
- if (inBlockComment && trimmed.endsWith('*/')) {
260
- inBlockComment = false;
261
- return;
262
- }
263
-
264
- // Skip if inside block comment or line comment
265
- if (inBlockComment || trimmed.startsWith('//')) return;
266
-
267
- // Match static .f7 import
268
- if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
269
- badImports.push({ line: trimmed, number: index + 1 });
270
- }
271
- });
272
-
273
- if (badImports.length > 0) {
274
- console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
275
- console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
276
- console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
277
- console.error(`
278
-
279
- import HomePage from '../pages/home.f7';
280
-
281
- const routes = [
282
- {
283
- path: '/',
284
- component:HomePage,
285
- },
286
- {
287
- path: '/ProfilePage/',
288
- async async({ resolve }) {
289
- const page = await import('../pages/profile.f7');
290
- resolve({ component: page.default });
291
- },
292
- }]
293
- `);
294
-
295
- badImports.forEach(({ line, number }) => {
296
- console.error(`${number}: ${line}`);
297
- });
298
-
299
- process.exit(1);
300
- } else {
301
- console.log('✅ routes.js passed the .f7 import check.');
302
- }
303
-
304
- //In routes.js file check static import END
305
-
306
-
307
-
308
-
309
-
310
-
311
-
312
-
313
-
314
-
315
-
316
-
317
-
318
- // Check and change the "BridgeWebViewClient.java" file START
319
- /*
320
- For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
321
- */
322
-
323
-
324
- const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
325
-
326
- // Read the file
327
- if (!fs.existsSync(bridgeWebViewClientFilePath)) {
328
- console.error('❌ Error: BridgeWebViewClient.java not found.');
329
- process.exit(1);
330
- }
331
-
332
- let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
333
-
334
- // Define old and new code
335
- const oldCodeStart = `@Override
336
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
337
- super.onRenderProcessGone(view, detail);
338
- boolean result = false;
339
-
340
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
341
- if (webViewListeners != null) {
342
- for (WebViewListener listener : bridge.getWebViewListeners()) {
343
- result = listener.onRenderProcessGone(view, detail) || result;
344
- }
345
- }
346
-
347
- return result;
348
- }`;
349
-
350
- const newCode = `@Override
351
- public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
352
- super.onRenderProcessGone(view, detail);
353
-
354
- boolean result = false;
355
-
356
- List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
357
- if (webViewListeners != null) {
358
- for (WebViewListener listener : bridge.getWebViewListeners()) {
359
- result = listener.onRenderProcessGone(view, detail) || result;
360
- }
361
- }
362
-
363
- if (!result) {
364
- // If no one handled it, handle it ourselves!
365
-
366
- /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
367
- if (detail.didCrash()) {
368
- //Log.e("CapacitorWebView", "WebView crashed internally!");
369
- } else {
370
- //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
371
- }
372
- }*/
373
-
374
- view.post(() -> {
375
- Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
376
- });
377
-
378
- view.reload(); // Safely reload WebView
379
-
380
- return true; // We handled it
381
- }
382
-
383
- return result;
384
- }`;
385
-
386
- // Step 1: Update method if needed
387
- let updated = false;
388
-
389
- if (fileContent.includes(oldCodeStart)) {
390
- console.log('✅ Found old onRenderProcessGone method. Replacing it...');
391
- fileContent = fileContent.replace(oldCodeStart, newCode);
392
- updated = true;
393
- } else if (fileContent.includes(newCode)) {
394
- console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
395
- } else {
396
- console.error('❌ Error: Neither old nor new code found. Unexpected content.');
397
- process.exit(1);
398
- }
399
-
400
- // Step 2: Check and add import if missing
401
- const importToast = 'import android.widget.Toast;';
402
- if (!fileContent.includes(importToast)) {
403
- console.log('✅ Adding missing import for Toast...');
404
- const importRegex = /import\s+[^;]+;/g;
405
- const matches = [...fileContent.matchAll(importRegex)];
406
-
407
- if (matches.length > 0) {
408
- const lastImport = matches[matches.length - 1];
409
- const insertPosition = lastImport.index + lastImport[0].length;
410
- fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
411
- updated = true;
412
- } else {
413
- console.error('❌ Error: No import section found in file.');
414
- process.exit(1);
415
- }
416
- } else {
417
- console.log('ℹ️ Import for Toast already exists. No changes needed.');
418
- }
419
-
420
- // Step 3: Save if updated
421
- if (updated) {
422
- fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
423
- console.log('✅ File updated successfully.');
424
- } else {
425
- console.log('ℹ️ No changes needed.');
426
- }
427
-
428
-
429
-
430
-
431
- // Check and change the "BridgeWebViewClient.java" file END
432
-
433
-
434
-
435
-
436
-
437
-
438
-
439
-
440
-
441
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
442
-
443
- // Build the path dynamically like you requested
444
- const gradlePath = path.join(
445
- process.cwd(),
446
- 'android',
447
- 'build.gradle'
448
- );
449
-
450
- // Read the existing build.gradle
451
- let gradleContent = fs.readFileSync(gradlePath, 'utf8');
452
-
453
- // Add `ext.kotlin_version` if it's not already there
454
- if (!gradleContent.includes('ext.kotlin_version')) {
455
- gradleContent = gradleContent.replace(
456
- /buildscript\s*{/,
457
- `buildscript {\n ext.kotlin_version = '2.1.0'`
458
- );
459
- }
460
-
461
- // Add Kotlin classpath if it's not already there
462
- if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
463
- gradleContent = gradleContent.replace(
464
- /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
465
- `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
466
- );
467
- }
468
-
469
- // Write back the modified content
470
- fs.writeFileSync(gradlePath, gradleContent, 'utf8');
471
-
472
- console.log('✅ Kotlin version updated in build.gradle.');
473
-
474
- // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
475
-
476
-
477
-
478
-
479
-
480
-
481
-
482
-
483
-
484
-
485
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
486
- const androidPlatformPath = path.join(process.cwd(), 'android');
487
- const iosPlatformPath = path.join(process.cwd(), 'ios');
488
- const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
489
- const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
490
- const resourcesPath = path.join(process.cwd(), 'resources', 'res');
491
- const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
492
- const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
493
-
494
- function fileExists(filePath) {
495
- return fs.existsSync(filePath);
496
- }
497
-
498
- function copyFolderSync(source, target) {
499
- if (!fs.existsSync(target)) {
500
- fs.mkdirSync(target, { recursive: true });
501
- }
502
-
503
- fs.readdirSync(source).forEach(file => {
504
- const sourceFile = path.join(source, file);
505
- const targetFile = path.join(target, file);
506
-
507
- if (fs.lstatSync(sourceFile).isDirectory()) {
508
- copyFolderSync(sourceFile, targetFile);
509
- } else {
510
- fs.copyFileSync(sourceFile, targetFile);
511
- }
512
- });
513
- }
514
-
515
- function checkAndCopyResources() {
516
- if (fileExists(resourcesPath)) {
517
- copyFolderSync(resourcesPath, androidResPath);
518
- console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
519
- } else {
520
- console.log('resources/res folder not found.');
521
-
522
- if (fileExists(localNotificationsPluginPath)) {
523
- throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
524
- }
525
- }
526
- }
527
-
528
-
529
-
530
- function getAdMobConfig() {
531
- if (!fileExists(configPath)) {
532
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
533
- }
534
-
535
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
536
- const admobConfig = config.plugins?.AdMob;
537
-
538
- if (!admobConfig) {
539
- throw new Error(' AdMob configuration is missing in capacitor.config.json.');
540
- }
541
-
542
- // Default to true if ADMOB_ENABLED is not specified
543
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
544
-
545
- if (!isEnabled) {
546
- return { ADMOB_ENABLED: false }; // Skip further validation
547
- }
548
-
549
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
550
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
551
- }
552
-
553
- return {
554
- ADMOB_ENABLED: true,
555
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
556
- APP_ID_IOS: admobConfig.APP_ID_IOS,
557
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
558
- };
559
- }
560
-
561
- function validateAndroidBuildOptions() {
562
-
563
-
564
- if (!fileExists(configPath)) {
565
- console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
566
- process.exit(1);
567
- }
568
-
569
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
570
-
571
- const targetAppId=config.appId
572
-
573
- const buildOptions = config.android?.buildOptions;
574
-
575
- if (!buildOptions) {
576
- console.log('❌ Missing android.buildOptions in capacitor.config.json.');
577
- process.exit(1);
578
- }
579
-
580
- const requiredProps = [
581
- 'keystorePath',
582
- 'keystorePassword',
583
- 'keystoreAlias',
584
- 'keystoreAliasPassword',
585
- 'releaseType',
586
- 'signingType'
587
- ];
588
-
589
- const missing = requiredProps.filter(prop => !buildOptions[prop]);
590
-
591
- if (missing.length > 0) {
592
- console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
593
- process.exit(1);
594
- }
595
-
596
-
597
- const keystorePath=buildOptions.keystorePath
598
- const keyFileName = path.basename(keystorePath);
599
-
600
-
601
-
602
- const keystoreMap = {
603
- "gameskey.jks": [
604
- "com.cube.blaster",
605
- ],
606
- "htmleditorkeystoke.jks": [
607
- "com.HTML.AngularJS.Codeplay",
608
- "com.html.codeplay.pro",
609
- "com.bootstrap.code.play",
610
- "com.kids.learning.master",
611
- "com.Simple.Barcode.Scanner"
612
- ]
613
- };
614
-
615
- // find which keystore is required for the given targetAppId
616
- let requiredKey = "newappskey.jks"; // default
617
- for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
618
- if (appIds.includes(targetAppId)) {
619
- requiredKey = keyFile;
620
- break;
621
- }
622
- }
623
-
624
- // validate
625
- if (keyFileName !== requiredKey) {
626
- console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
627
- process.exit(1);
628
- }
629
-
630
-
631
-
632
-
633
-
634
- // optionally return them
635
- //return buildOptions;
636
- }
637
-
638
- function updatePluginXml(admobConfig) {
639
- if (!fileExists(pluginPath)) {
640
- console.error(' plugin.xml not found. Ensure the plugin is installed.');
641
- return;
642
- }
643
-
644
- let pluginContent = fs.readFileSync(pluginPath, 'utf8');
645
-
646
- pluginContent = pluginContent
647
- .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
648
- .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
649
-
650
- fs.writeFileSync(pluginPath, pluginContent, 'utf8');
651
- console.log('✅ AdMob IDs successfully updated in plugin.xml');
652
- }
653
-
654
- function updateInfoPlist(admobConfig) {
655
- if (!fileExists(infoPlistPath)) {
656
- console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
657
- return;
658
- }
659
-
660
- const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
661
- const plistData = plist.parse(plistContent);
662
-
663
- plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
664
- plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
665
- plistData.GADDelayAppMeasurementInit = true;
666
-
667
- const updatedPlistContent = plist.build(plistData);
668
- fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
669
- console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
670
- }
671
-
672
- try {
673
- if (!fileExists(configPath)) {
674
- throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
675
- }
676
-
677
- if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
678
- throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
679
- }
680
-
681
- checkAndCopyResources();
682
-
683
- const admobConfig = getAdMobConfig();
684
-
685
-
686
-
687
-
688
- // Proceed only if ADMOB_ENABLED is true
689
- if (admobConfig.ADMOB_ENABLED) {
690
- if (fileExists(androidPlatformPath)) {
691
- updatePluginXml(admobConfig);
692
- }
693
-
694
- if (fileExists(iosPlatformPath)) {
695
- updateInfoPlist(admobConfig);
696
- }
697
- }
698
-
699
-
700
- } catch (error) {
701
- console.error(error.message);
702
- process.exit(1); // Stop execution if there's a critical error
703
- }
704
-
705
-
706
-
707
- validateAndroidBuildOptions();
708
-
709
-
710
-
711
-
712
-
713
-
714
- // Check all the codeplays plugins version START
715
-
716
-
717
- const readline = require('readline');
718
-
719
-
720
- //const srcDir = path.join(__dirname, 'src');
721
- const srcDir = path.join(process.cwd(), 'src');
722
- let outdatedPlugins = [];
723
-
724
- function parseVersion(ver) {
725
- return ver.split('.').map(n => parseInt(n, 10));
726
- }
727
-
728
- function compareVersions(v1, v2) {
729
- const [a1, b1] = parseVersion(v1);
730
- const [a2, b2] = parseVersion(v2);
731
- if (a1 !== a2) return a1 - a2;
732
- return b1 - b2;
733
- }
734
-
735
- function walkSync(dir, filelist = []) {
736
- fs.readdirSync(dir).forEach(file => {
737
- const fullPath = path.join(dir, file);
738
- const stat = fs.statSync(fullPath);
739
- if (stat.isDirectory()) {
740
- walkSync(fullPath, filelist);
741
- } else {
742
- filelist.push(fullPath);
743
- }
744
- });
745
- return filelist;
746
- }
747
-
748
- function checkPlugins() {
749
- const files = walkSync(srcDir);
750
-
751
- for (const plugin of requiredPlugins) {
752
- if (plugin.isFolder) {
753
-
754
- let baseFolder = path.join(srcDir,'js', 'Ads'); // <- use known folder name
755
-
756
- if (fs.existsSync(baseFolder)) {
757
- const subDirs = fs.readdirSync(baseFolder)
758
- .map(name => path.join(baseFolder, name))
759
- .filter(p => fs.statSync(p).isDirectory());
760
-
761
- for (const dir of subDirs) {
762
- const relativePath = path.relative(srcDir, dir).replace(/\\/g, '/'); // e.g. Ads/IAP-2.0
763
- const match = plugin.pattern.exec(relativePath);
764
- if (match) {
765
- const currentVersion = match[1];
766
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
767
- outdatedPlugins.push({
768
- name: relativePath,
769
- currentVersion,
770
- requiredVersion: plugin.minVersion
771
- });
772
- }
773
- }
774
- }
775
- }
776
- continue;
777
- }
778
-
779
- const matchedFile = files.find(file => plugin.pattern.test(file));
780
- if (matchedFile) {
781
- const match = plugin.pattern.exec(matchedFile);
782
- if (match) {
783
- const currentVersion = match[1];
784
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
785
- outdatedPlugins.push({
786
- name: path.relative(__dirname, matchedFile),
787
- currentVersion,
788
- requiredVersion: plugin.minVersion
789
- });
790
- }
791
- }
792
- }
793
- }
794
-
795
- if (outdatedPlugins.length > 0) {
796
- console.log('\n❗ The following plugins are outdated:');
797
- outdatedPlugins.forEach(p => {
798
- console.log(` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion})`);
799
- });
800
-
801
- const rl = readline.createInterface({
802
- input: process.stdin,
803
- output: process.stdout
804
- });
805
-
806
- rl.question('\nAre you sure you want to continue without updating these plugins? (y/n): ', answer => {
807
- if (answer.toLowerCase() !== 'y') {
808
- console.log('\n❌ Build cancelled due to outdated plugins.');
809
- process.exit(1);
810
- } else {
811
- console.log('\n✅ Continuing build...');
812
- rl.close();
813
- }
814
- });
815
- } else {
816
- console.log('✅ All plugin versions are up to date.');
817
- }
818
- }
819
-
820
- // Run the validation
821
- checkPlugins();
822
-
823
-
824
-
825
-
826
- // Check all the codeplays plugins version START
827
-
828
-
829
-
830
-
831
-
832
-
833
-
834
-
835
-
836
-
837
-
838
-
839
-
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const plist = require('plist');
4
+
5
+
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.4', required: true },
14
+ { pattern: /common-(\d+\.\d+)\.js$/, minVersion: '4.0', required: true },
15
+ { pattern: /localization_settings-(\d+\.\d+)\.js$/, minVersion: '1.1', required: true },
16
+ { pattern: /localization-(\d+\.\d+)\.js$/, minVersion: '1.3', required: true },
17
+ { pattern: /localNotification-(\d+\.\d+)\.js$/, minVersion: '2.2', required: true },
18
+ { pattern: /localNotification_AppSettings-(\d+\.\d+)\.js$/, minVersion: '1.0', required: true },
19
+ { pattern: /onesignal-(\d+\.\d+)\.js$/, minVersion: '2.1', required: true },
20
+ { pattern: /saveToGalleryAndSaveAnyFile-(\d+\.\d+)(-ios)?\.js$/, minVersion: '2.5', required: true },
21
+ { pattern: /Ads[\/\\]IAP-(\d+\.\d+)$/, minVersion: '2.5', isFolder: true , required: true},
22
+ { pattern: /Ads[\/\\]admob-emi-(\d+\.\d+)\.js$/, minVersion: '2.8', required: true }
23
+ ];
24
+
25
+
26
+
27
+
28
+
29
+
30
+ //Check codeplay-common latest version installed or not Start
31
+ const { execSync } = require('child_process');
32
+
33
+ function getInstalledVersion(packageName) {
34
+ try {
35
+ const packageJsonPath = path.join(process.cwd(), 'node_modules', packageName, 'package.json');
36
+ if (fs.existsSync(packageJsonPath)) {
37
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
38
+ return packageJson.version;
39
+ }
40
+ } catch (error) {
41
+ return null;
42
+ }
43
+ return null;
44
+ }
45
+
46
+ function getLatestVersion(packageName) {
47
+ try {
48
+ return execSync(`npm view ${packageName} version`).toString().trim();
49
+ } catch (error) {
50
+ console.error(`Failed to fetch latest version for ${packageName}`);
51
+ return null;
52
+ }
53
+ }
54
+
55
+ function checkPackageVersion() {
56
+ const packageName = 'codeplay-common';
57
+ const installedVersion = getInstalledVersion(packageName);
58
+ const latestVersion = getLatestVersion(packageName);
59
+
60
+ if (!installedVersion) {
61
+ console.error(`${packageName} is not installed. Please install it using "npm install ${packageName}".`);
62
+ process.exit(1);
63
+ }
64
+
65
+ if (installedVersion !== latestVersion) {
66
+ 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`);
67
+ process.exit(1);
68
+ }
69
+
70
+ console.log(`${packageName} is up to date (version ${installedVersion}).`);
71
+ }
72
+
73
+ // Run package version check before executing the main script
74
+ try {
75
+ checkPackageVersion();
76
+ } catch (error) {
77
+ console.error(error.message);
78
+ process.exit(1);
79
+ }
80
+
81
+ //Check codeplay-common latest version installed or not END
82
+
83
+
84
+
85
+
86
+
87
+
88
+
89
+
90
+
91
+ //@Codemirror check and install/uninstall the packages START
92
+ //const fs = require("fs");
93
+ //const path = require("path");
94
+ //const { execSync } = require("child_process");
95
+
96
+ const baseDir = path.join(__dirname, "..", "src", "js");
97
+
98
+ // Step 1: Find highest versioned folder like `editor-1.6`
99
+ const editorDirs = fs.readdirSync(baseDir)
100
+ .filter(name => /^editor-\d+\.\d+$/.test(name))
101
+ .sort((a, b) => {
102
+ const getVersion = str => str.match(/(\d+)\.(\d+)/).slice(1).map(Number);
103
+ const [aMajor, aMinor] = getVersion(a);
104
+ const [bMajor, bMinor] = getVersion(b);
105
+ return bMajor - aMajor || bMinor - aMinor;
106
+ });
107
+
108
+ if (editorDirs.length === 0) {
109
+
110
+ console.log("@Codemirror used editor(s) are not found")
111
+ //console.error("❌ No editor-x.x folders found in src/js.");
112
+ //process.exit(1);
113
+ }
114
+ else
115
+ {
116
+
117
+ const latestEditorDir = editorDirs.sort((a, b) => {
118
+ const versionA = parseFloat(a.split('-')[1]);
119
+ const versionB = parseFloat(b.split('-')[1]);
120
+ return versionB - versionA;
121
+ })[0];
122
+
123
+ //const latestEditorDir = editorDirs[editorDirs.length - 1];
124
+ const runJsPath = path.join(baseDir, latestEditorDir, "run.js");
125
+
126
+ if (!fs.existsSync(runJsPath)) {
127
+ console.error(`❌ run.js not found in ${latestEditorDir}`);
128
+ process.exit(1);
129
+ }
130
+
131
+ // Step 2: Execute the run.js file
132
+ console.log(`🚀 Executing ${runJsPath}...`);
133
+ execSync(`node "${runJsPath}"`, { stdio: "inherit" });
134
+ }
135
+
136
+ //@Codemirror check and install/uninstall the packages END
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+
148
+
149
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists START
150
+
151
+ const os = require('os');
152
+
153
+ const saveToGalleryAndSaveFileCheck_iOS = () => {
154
+ const ROOT_DIR = path.resolve(__dirname, '../src');
155
+ const ANDROID_MANIFEST_PATH = path.resolve(__dirname, '../android/app/src/main/AndroidManifest.xml');
156
+
157
+
158
+ // Match iOS-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5-ios.js) not in comments
159
+ const IOS_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*-ios\.js['"]/m;
160
+
161
+ // Match Android-specific imports (e.g., saveToGalleryAndSaveAnyFile-2.5.js) not in comments
162
+ const ANDROID_FILE_REGEX = /^(?!\s*\/\/).*['"](?:.*\/)?saveToGalleryAndSaveAnyFile-\d+(\.\d+)*\.js['"]/m;
163
+
164
+
165
+
166
+
167
+
168
+ const ALLOWED_EXTENSIONS = ['.js', '.f7'];
169
+ const isMac = os.platform() === 'darwin';
170
+
171
+ let iosImportFound = false;
172
+ let androidImportFound = false;
173
+
174
+ function scanDirectory(dir) {
175
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
176
+
177
+ for (let entry of entries) {
178
+ const fullPath = path.join(dir, entry.name);
179
+
180
+ if (entry.isDirectory()) {
181
+ if (entry.name === 'node_modules') continue;
182
+ scanDirectory(fullPath);
183
+ } else if (entry.isFile() && ALLOWED_EXTENSIONS.some(ext => fullPath.endsWith(ext))) {
184
+ const content = fs.readFileSync(fullPath, 'utf8');
185
+
186
+ // Detect iOS version file imports
187
+ if (IOS_FILE_REGEX.test(content)) {
188
+ iosImportFound = true;
189
+ if (!isMac) {
190
+ console.error(`\n❌ ERROR: iOS-specific import detected in: ${fullPath}`);
191
+ console.error(`🚫 STOPPED: This file should not be imported in Android/Windows/Linux builds.\n`);
192
+ process.exit(1);
193
+ }
194
+ }
195
+
196
+ // Detect Android version file imports (but ignore iOS ones)
197
+ else if (ANDROID_FILE_REGEX.test(content) && !content.includes('-ios.js')) {
198
+ androidImportFound = true;
199
+ }
200
+ }
201
+ }
202
+ }
203
+
204
+ // Check src folder
205
+ if (!fs.existsSync(ROOT_DIR)) {
206
+ console.warn(`⚠️ Warning: 'src' directory not found at: ${ROOT_DIR}`);
207
+ return;
208
+ }
209
+
210
+ scanDirectory(ROOT_DIR);
211
+
212
+ // iOS Checks
213
+ if (isMac && !iosImportFound) {
214
+ console.warn(`⚠️ WARNING: You're on macOS but no iOS version (saveToGalleryAndSaveAnyFile-x.x-ios.js) found.`);
215
+ process.exit(1);
216
+ } else if (isMac && iosImportFound) {
217
+ console.log('✅ iOS version detected for macOS build.');
218
+ } else if (!iosImportFound) {
219
+ console.log('✅ No iOS-specific imports detected for non-macOS.');
220
+ }
221
+
222
+ // Android Checks
223
+ if (androidImportFound) {
224
+ console.log("📱 Android version of saveToGalleryAndSaveAnyFile detected. Checking AndroidManifest.xml...");
225
+
226
+ if (!fs.existsSync(ANDROID_MANIFEST_PATH)) {
227
+ console.error("❌ AndroidManifest.xml not found. Cannot add requestLegacyExternalStorage attribute.");
228
+ return;
229
+ }
230
+
231
+ let manifestContent = fs.readFileSync(ANDROID_MANIFEST_PATH, 'utf8');
232
+
233
+ if (!manifestContent.includes('android:requestLegacyExternalStorage="true"')) {
234
+ console.log("Adding android:requestLegacyExternalStorage=\"true\" to <application> tag...");
235
+
236
+ manifestContent = manifestContent.replace(
237
+ /<application([^>]*)>/,
238
+ (match, attrs) => {
239
+ if (attrs.includes('android:requestLegacyExternalStorage')) return match;
240
+ return `<application${attrs} android:requestLegacyExternalStorage="true">`;
241
+ }
242
+ );
243
+
244
+ fs.writeFileSync(ANDROID_MANIFEST_PATH, manifestContent, 'utf8');
245
+ console.log("✅ android:requestLegacyExternalStorage=\"true\" added successfully.");
246
+ } else {
247
+ console.log("ℹ️ android:requestLegacyExternalStorage already exists in AndroidManifest.xml.");
248
+ }
249
+ } else {
250
+ console.log("✅ No Android saveToGalleryAndSaveAnyFile imports detected.");
251
+ }
252
+ };
253
+
254
+ saveToGalleryAndSaveFileCheck_iOS();
255
+ // saveToGalleryAndSaveAnyFile-x.x-ios.js file check for android and return error if exists END
256
+
257
+
258
+
259
+
260
+
261
+
262
+
263
+
264
+
265
+
266
+
267
+
268
+
269
+ /*
270
+ // Clean up AppleDouble files (._*) created by macOS START
271
+ if (process.platform === 'darwin') {
272
+ try {
273
+ console.log('🧹 Cleaning up AppleDouble files (._*)...');
274
+ execSync(`find . -name '._*' -delete`);
275
+ console.log('✅ AppleDouble files removed.');
276
+ } catch (err) {
277
+ console.warn('⚠️ Failed to remove AppleDouble files:', err.message);
278
+ }
279
+ } else {
280
+ console.log('ℹ️ Skipping AppleDouble cleanup — not a macOS machine.');
281
+ }
282
+
283
+ // Clean up AppleDouble files (._*) created by macOS END
284
+ */
285
+
286
+
287
+
288
+
289
+
290
+
291
+ //In routes.js file check static import START
292
+
293
+ const routesPath = path.join(process.cwd(), 'src', 'js', 'routes.js');
294
+ const routesContent = fs.readFileSync(routesPath, 'utf-8');
295
+
296
+ let inBlockComment = false;
297
+ const lines = routesContent.split('\n');
298
+
299
+ const allowedImport = `import HomePage from '../pages/home.f7';`;
300
+ const badImportRegex = /^[ \t]*import\s+[\w{}*,\s]*\s+from\s+['"].+\.f7['"]\s*;/;
301
+ const badImports = [];
302
+
303
+ lines.forEach((line, index) => {
304
+ const trimmed = line.trim();
305
+
306
+ // Handle block comment start and end
307
+ if (trimmed.startsWith('/*')) inBlockComment = true;
308
+ if (inBlockComment && trimmed.endsWith('*/')) {
309
+ inBlockComment = false;
310
+ return;
311
+ }
312
+
313
+ // Skip if inside block comment or line comment
314
+ if (inBlockComment || trimmed.startsWith('//')) return;
315
+
316
+ // Match static .f7 import
317
+ if (badImportRegex.test(trimmed) && trimmed !== allowedImport) {
318
+ badImports.push({ line: trimmed, number: index + 1 });
319
+ }
320
+ });
321
+
322
+ if (badImports.length > 0) {
323
+ console.error('\n❌ ERROR: Detected disallowed static imports of .f7 files in routes.js\n');
324
+ console.error(`⚠️ Only this static import is allowed:\n ${allowedImport}\n`);
325
+ console.error(`🔧 Please convert other imports to async dynamic imports like this:\n`);
326
+ console.error(`
327
+
328
+ import HomePage from '../pages/home.f7';
329
+
330
+ const routes = [
331
+ {
332
+ path: '/',
333
+ component:HomePage,
334
+ },
335
+ {
336
+ path: '/ProfilePage/',
337
+ async async({ resolve }) {
338
+ const page = await import('../pages/profile.f7');
339
+ resolve({ component: page.default });
340
+ },
341
+ }]
342
+ `);
343
+
344
+ badImports.forEach(({ line, number }) => {
345
+ console.error(`${number}: ${line}`);
346
+ });
347
+
348
+ process.exit(1);
349
+ } else {
350
+ console.log('✅ routes.js passed the .f7 import check.');
351
+ }
352
+
353
+ //In routes.js file check static import END
354
+
355
+
356
+
357
+
358
+
359
+
360
+
361
+
362
+
363
+
364
+
365
+
366
+
367
+ // Check and change the "BridgeWebViewClient.java" file START
368
+ /*
369
+ For crash issue due to low memory problem, we need to modify the onRenderProcessGone method in BridgeWebViewClient.java.
370
+ */
371
+
372
+
373
+ const bridgeWebViewClientFilePath = path.join(process.cwd(), 'node_modules', '@capacitor/android/capacitor/src/main/java/com/getcapacitor', 'BridgeWebViewClient.java');
374
+
375
+ // Read the file
376
+ if (!fs.existsSync(bridgeWebViewClientFilePath)) {
377
+ console.error('❌ Error: BridgeWebViewClient.java not found.');
378
+ process.exit(1);
379
+ }
380
+
381
+ let fileContent = fs.readFileSync(bridgeWebViewClientFilePath, 'utf8');
382
+
383
+ // Define old and new code
384
+ const oldCodeStart = `@Override
385
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
386
+ super.onRenderProcessGone(view, detail);
387
+ boolean result = false;
388
+
389
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
390
+ if (webViewListeners != null) {
391
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
392
+ result = listener.onRenderProcessGone(view, detail) || result;
393
+ }
394
+ }
395
+
396
+ return result;
397
+ }`;
398
+
399
+ const newCode = `@Override
400
+ public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) {
401
+ super.onRenderProcessGone(view, detail);
402
+
403
+ boolean result = false;
404
+
405
+ List<WebViewListener> webViewListeners = bridge.getWebViewListeners();
406
+ if (webViewListeners != null) {
407
+ for (WebViewListener listener : bridge.getWebViewListeners()) {
408
+ result = listener.onRenderProcessGone(view, detail) || result;
409
+ }
410
+ }
411
+
412
+ if (!result) {
413
+ // If no one handled it, handle it ourselves!
414
+
415
+ /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
416
+ if (detail.didCrash()) {
417
+ //Log.e("CapacitorWebView", "WebView crashed internally!");
418
+ } else {
419
+ //Log.w("CapacitorWebView", "WebView was killed by system (low memory) internally!");
420
+ }
421
+ }*/
422
+
423
+ view.post(() -> {
424
+ Toast.makeText(view.getContext(), "Reloading due to low memory issue", Toast.LENGTH_SHORT).show();
425
+ });
426
+
427
+ view.reload(); // Safely reload WebView
428
+
429
+ return true; // We handled it
430
+ }
431
+
432
+ return result;
433
+ }`;
434
+
435
+ // Step 1: Update method if needed
436
+ let updated = false;
437
+
438
+ if (fileContent.includes(oldCodeStart)) {
439
+ console.log('✅ Found old onRenderProcessGone method. Replacing it...');
440
+ fileContent = fileContent.replace(oldCodeStart, newCode);
441
+ updated = true;
442
+ } else if (fileContent.includes(newCode)) {
443
+ console.log('ℹ️ Method already updated. No changes needed in "BridgeWebViewClient.java".');
444
+ } else {
445
+ console.error('❌ Error: Neither old nor new code found. Unexpected content.');
446
+ process.exit(1);
447
+ }
448
+
449
+ // Step 2: Check and add import if missing
450
+ const importToast = 'import android.widget.Toast;';
451
+ if (!fileContent.includes(importToast)) {
452
+ console.log('✅ Adding missing import for Toast...');
453
+ const importRegex = /import\s+[^;]+;/g;
454
+ const matches = [...fileContent.matchAll(importRegex)];
455
+
456
+ if (matches.length > 0) {
457
+ const lastImport = matches[matches.length - 1];
458
+ const insertPosition = lastImport.index + lastImport[0].length;
459
+ fileContent = fileContent.slice(0, insertPosition) + `\n${importToast}` + fileContent.slice(insertPosition);
460
+ updated = true;
461
+ } else {
462
+ console.error('❌ Error: No import section found in file.');
463
+ process.exit(1);
464
+ }
465
+ } else {
466
+ console.log('ℹ️ Import for Toast already exists. No changes needed.');
467
+ }
468
+
469
+ // Step 3: Save if updated
470
+ if (updated) {
471
+ fs.writeFileSync(bridgeWebViewClientFilePath, fileContent, 'utf8');
472
+ console.log('✅ File updated successfully.');
473
+ } else {
474
+ console.log('ℹ️ No changes needed.');
475
+ }
476
+
477
+
478
+
479
+
480
+ // Check and change the "BridgeWebViewClient.java" file END
481
+
482
+
483
+
484
+
485
+
486
+
487
+
488
+
489
+
490
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file START
491
+
492
+ // Build the path dynamically like you requested
493
+ const gradlePath = path.join(
494
+ process.cwd(),
495
+ 'android',
496
+ 'build.gradle'
497
+ );
498
+
499
+ // Read the existing build.gradle
500
+ let gradleContent = fs.readFileSync(gradlePath, 'utf8');
501
+
502
+ // Add `ext.kotlin_version` if it's not already there
503
+ if (!gradleContent.includes('ext.kotlin_version')) {
504
+ gradleContent = gradleContent.replace(
505
+ /buildscript\s*{/,
506
+ `buildscript {\n ext.kotlin_version = '2.1.0'`
507
+ );
508
+ }
509
+
510
+ // Add Kotlin classpath if it's not already there
511
+ if (!gradleContent.includes('org.jetbrains.kotlin:kotlin-gradle-plugin')) {
512
+ gradleContent = gradleContent.replace(
513
+ /dependencies\s*{([\s\S]*?)classpath 'com.android.tools.build:gradle:8.7.2'/,
514
+ `dependencies {\n classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version")\n$1classpath 'com.android.tools.build:gradle:8.7.2'`
515
+ );
516
+ }
517
+
518
+ // Write back the modified content
519
+ fs.writeFileSync(gradlePath, gradleContent, 'utf8');
520
+
521
+ console.log('✅ Kotlin version updated in build.gradle.');
522
+
523
+ // To resolve the kotlin version issue, we need to update the kotlin version in the build.gradle file END
524
+
525
+
526
+
527
+
528
+
529
+
530
+
531
+
532
+
533
+
534
+
535
+
536
+
537
+ const androidPlatformPath = path.join(process.cwd(), 'android');
538
+ const iosPlatformPath = path.join(process.cwd(), 'ios');
539
+ const pluginPath = path.join(process.cwd(), 'node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
540
+ const infoPlistPath = path.join(process.cwd(), 'ios', 'App', 'App', 'Info.plist');
541
+ const resourcesPath = path.join(process.cwd(), 'resources', 'res');
542
+ const androidResPath = path.join(process.cwd(), 'android', 'app', 'src', 'main', 'res');
543
+ const localNotificationsPluginPath = path.join(process.cwd(), 'node_modules', '@capacitor', 'local-notifications');
544
+
545
+ function fileExists(filePath) {
546
+ return fs.existsSync(filePath);
547
+ }
548
+
549
+ function copyFolderSync(source, target) {
550
+ if (!fs.existsSync(target)) {
551
+ fs.mkdirSync(target, { recursive: true });
552
+ }
553
+
554
+ fs.readdirSync(source).forEach(file => {
555
+ const sourceFile = path.join(source, file);
556
+ const targetFile = path.join(target, file);
557
+
558
+ if (fs.lstatSync(sourceFile).isDirectory()) {
559
+ copyFolderSync(sourceFile, targetFile);
560
+ } else {
561
+ fs.copyFileSync(sourceFile, targetFile);
562
+ }
563
+ });
564
+ }
565
+
566
+ function checkAndCopyResources() {
567
+ if (fileExists(resourcesPath)) {
568
+ copyFolderSync(resourcesPath, androidResPath);
569
+ console.log('✅ Successfully copied resources/res to android/app/src/main/res.');
570
+ } else {
571
+ console.log('resources/res folder not found.');
572
+
573
+ if (fileExists(localNotificationsPluginPath)) {
574
+ throw new Error('❌ resources/res is required for @capacitor/local-notifications. Stopping execution.');
575
+ }
576
+ }
577
+ }
578
+
579
+
580
+
581
+ function getAdMobConfig() {
582
+ if (!fileExists(configPath)) {
583
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
584
+ }
585
+
586
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
587
+ const admobConfig = config.plugins?.AdMob;
588
+
589
+ if (!admobConfig) {
590
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
591
+ }
592
+
593
+ // Default to true if ADMOB_ENABLED is not specified
594
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
595
+
596
+ if (!isEnabled) {
597
+ return { ADMOB_ENABLED: false }; // Skip further validation
598
+ }
599
+
600
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
601
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
602
+ }
603
+
604
+ return {
605
+ ADMOB_ENABLED: true,
606
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
607
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
608
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
609
+ };
610
+ }
611
+
612
+ function validateAndroidBuildOptions() {
613
+
614
+
615
+ if (!fileExists(configPath)) {
616
+ console.log('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
617
+ process.exit(1);
618
+ }
619
+
620
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
621
+
622
+ const targetAppId=config.appId
623
+
624
+ const buildOptions = config.android?.buildOptions;
625
+
626
+ if (!buildOptions) {
627
+ console.log('❌ Missing android.buildOptions in capacitor.config.json.');
628
+ process.exit(1);
629
+ }
630
+
631
+ const requiredProps = [
632
+ 'keystorePath',
633
+ 'keystorePassword',
634
+ 'keystoreAlias',
635
+ 'keystoreAliasPassword',
636
+ 'releaseType',
637
+ 'signingType'
638
+ ];
639
+
640
+ const missing = requiredProps.filter(prop => !buildOptions[prop]);
641
+
642
+ if (missing.length > 0) {
643
+ console.log('❌ Missing properties android.buildOptions in capacitor.config.json.');
644
+ process.exit(1);
645
+ }
646
+
647
+
648
+ const keystorePath=buildOptions.keystorePath
649
+ const keyFileName = path.basename(keystorePath);
650
+
651
+
652
+
653
+ const keystoreMap = {
654
+ "gameskey.jks": [
655
+ "com.cube.blaster",
656
+ ],
657
+ "htmleditorkeystoke.jks": [
658
+ "com.HTML.AngularJS.Codeplay",
659
+ "com.html.codeplay.pro",
660
+ "com.bootstrap.code.play",
661
+ "com.kids.learning.master",
662
+ "com.Simple.Barcode.Scanner"
663
+ ]
664
+ };
665
+
666
+ // find which keystore is required for the given targetAppId
667
+ let requiredKey = "newappskey.jks"; // default
668
+ for (const [keyFile, appIds] of Object.entries(keystoreMap)) {
669
+ if (appIds.includes(targetAppId)) {
670
+ requiredKey = keyFile;
671
+ break;
672
+ }
673
+ }
674
+
675
+ // validate
676
+ if (keyFileName !== requiredKey) {
677
+ console.log(`❌ The keystore path is mismatched. Expected ${requiredKey} for ${targetAppId}, but got ${keyFileName}`);
678
+ process.exit(1);
679
+ }
680
+
681
+
682
+
683
+
684
+
685
+ // optionally return them
686
+ //return buildOptions;
687
+ }
688
+
689
+ function updatePluginXml(admobConfig) {
690
+ if (!fileExists(pluginPath)) {
691
+ console.error(' ❌ plugin.xml not found. Ensure the plugin is installed.');
692
+ return;
693
+ }
694
+
695
+ let pluginContent = fs.readFileSync(pluginPath, 'utf8');
696
+
697
+ pluginContent = pluginContent
698
+ .replace(/<preference name="APP_ID_ANDROID" default=".*?" \/>/, `<preference name="APP_ID_ANDROID" default="${admobConfig.APP_ID_ANDROID}" />`)
699
+ .replace(/<preference name="APP_ID_IOS" default=".*?" \/>/, `<preference name="APP_ID_IOS" default="${admobConfig.APP_ID_IOS}" />`);
700
+
701
+ fs.writeFileSync(pluginPath, pluginContent, 'utf8');
702
+ console.log('✅ AdMob IDs successfully updated in plugin.xml');
703
+ }
704
+
705
+ function updateInfoPlist(admobConfig) {
706
+ if (!fileExists(infoPlistPath)) {
707
+ console.error(' ❌ Info.plist not found. Ensure you have built the iOS project.');
708
+ return;
709
+ }
710
+
711
+ const plistContent = fs.readFileSync(infoPlistPath, 'utf8');
712
+ const plistData = plist.parse(plistContent);
713
+
714
+ plistData.GADApplicationIdentifier = admobConfig.APP_ID_IOS;
715
+ plistData.NSUserTrackingUsageDescription = 'This identifier will be used to deliver personalized ads to you.';
716
+ plistData.GADDelayAppMeasurementInit = true;
717
+
718
+ const updatedPlistContent = plist.build(plistData);
719
+ fs.writeFileSync(infoPlistPath, updatedPlistContent, 'utf8');
720
+ console.log('AdMob IDs and additional configurations successfully updated in Info.plist');
721
+ }
722
+
723
+ try {
724
+ if (!fileExists(configPath)) {
725
+ throw new Error(' ❌ capacitor.config.json not found. Skipping setup.');
726
+ }
727
+
728
+ if (!fileExists(androidPlatformPath) && !fileExists(iosPlatformPath)) {
729
+ throw new Error('Neither Android nor iOS platforms are found. Ensure platforms are added to your Capacitor project.');
730
+ }
731
+
732
+ checkAndCopyResources();
733
+
734
+ const admobConfig = getAdMobConfig();
735
+
736
+
737
+
738
+
739
+ // Proceed only if ADMOB_ENABLED is true
740
+ if (admobConfig.ADMOB_ENABLED) {
741
+ if (fileExists(androidPlatformPath)) {
742
+ updatePluginXml(admobConfig);
743
+ }
744
+
745
+ if (fileExists(iosPlatformPath)) {
746
+ updateInfoPlist(admobConfig);
747
+ }
748
+ }
749
+
750
+
751
+ } catch (error) {
752
+ console.error(error.message);
753
+ process.exit(1); // Stop execution if there's a critical error
754
+ }
755
+
756
+
757
+
758
+ validateAndroidBuildOptions();
759
+
760
+
761
+
762
+
763
+
764
+
765
+ // Check all the codeplays plugins version START
766
+
767
+
768
+ const readline = require('readline');
769
+
770
+
771
+ //const srcDir = path.join(__dirname, 'src');
772
+ const srcDir = path.join(process.cwd(), 'src');
773
+ let outdatedPlugins = [];
774
+
775
+ function parseVersion(ver) {
776
+ return ver.split('.').map(n => parseInt(n, 10));
777
+ }
778
+
779
+ function compareVersions(v1, v2) {
780
+ const [a1, b1] = parseVersion(v1);
781
+ const [a2, b2] = parseVersion(v2);
782
+ if (a1 !== a2) return a1 - a2;
783
+ return b1 - b2;
784
+ }
785
+
786
+ function walkSync(dir, filelist = []) {
787
+ fs.readdirSync(dir).forEach(file => {
788
+ const fullPath = path.join(dir, file);
789
+ const stat = fs.statSync(fullPath);
790
+ if (stat.isDirectory()) {
791
+ walkSync(fullPath, filelist);
792
+ } else {
793
+ filelist.push(fullPath);
794
+ }
795
+ });
796
+ return filelist;
797
+ }
798
+
799
+ function checkPlugins() {
800
+ const files = walkSync(srcDir);
801
+
802
+ for (const plugin of requiredPlugins) {
803
+ if (plugin.isFolder) {
804
+
805
+ let baseFolder = path.join(srcDir,'js', 'Ads'); // <- use known folder name
806
+
807
+ if (fs.existsSync(baseFolder)) {
808
+ const subDirs = fs.readdirSync(baseFolder)
809
+ .map(name => path.join(baseFolder, name))
810
+ .filter(p => fs.statSync(p).isDirectory());
811
+
812
+ for (const dir of subDirs) {
813
+ const relativePath = path.relative(srcDir, dir).replace(/\\/g, '/'); // e.g. Ads/IAP-2.0
814
+ const match = plugin.pattern.exec(relativePath);
815
+ if (match) {
816
+ const currentVersion = match[1];
817
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
818
+ outdatedPlugins.push({
819
+ name: relativePath,
820
+ currentVersion,
821
+ requiredVersion: plugin.minVersion
822
+ });
823
+ }
824
+ }
825
+ }
826
+ }
827
+ continue;
828
+ }
829
+
830
+ const matchedFile = files.find(file => plugin.pattern.test(file));
831
+ if (matchedFile) {
832
+ const match = plugin.pattern.exec(matchedFile);
833
+ if (match) {
834
+ const currentVersion = match[1];
835
+ if (compareVersions(currentVersion, plugin.minVersion) < 0) {
836
+ outdatedPlugins.push({
837
+ name: path.relative(__dirname, matchedFile),
838
+ currentVersion,
839
+ requiredVersion: plugin.minVersion
840
+ });
841
+ }
842
+ }
843
+ }
844
+ }
845
+
846
+ if (outdatedPlugins.length > 0) {
847
+ console.log('\n❗ The following plugins are outdated:');
848
+ outdatedPlugins.forEach(p => {
849
+ console.log(` ❌ - ${p.name} (Current: ${p.currentVersion}, Required: ${p.requiredVersion})`);
850
+ });
851
+
852
+ const rl = readline.createInterface({
853
+ input: process.stdin,
854
+ output: process.stdout
855
+ });
856
+
857
+ rl.question('\nAre you sure you want to continue without updating these plugins? (y/n): ', answer => {
858
+ if (answer.toLowerCase() !== 'y') {
859
+ console.log('\n❌ Build cancelled due to outdated plugins.');
860
+ process.exit(1);
861
+ } else {
862
+ console.log('\n✅ Continuing build...');
863
+ rl.close();
864
+ }
865
+ });
866
+ } else {
867
+ console.log('✅ All plugin versions are up to date.');
868
+ }
869
+ }
870
+
871
+ // Run the validation
872
+ checkPlugins();
873
+
874
+
875
+
876
+
877
+ // Check all the codeplays plugins version START
878
+
879
+
880
+
881
+
882
+
883
+
884
+
885
+
886
+
887
+
888
+
889
+
890
+