codeplay-common 4.11.22 → 4.11.23

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.
package/README.md CHANGED
@@ -1,5 +1,80 @@
1
1
  # codeplay-common
2
2
 
3
+ ## VK / RuStore builds (4.11.23)
4
+
5
+ Before-build 7.8 preserves the original Vite build settings when adding tree-shaking
6
+ inside the generated store wrapper. It also repairs the exact treeshake-only build
7
+ override created by the earlier migration; custom wrapper build settings are retained.
8
+
9
+ IAP imports use `@iap/<module>.js`. Installation configures the Vite alias; before-build
10
+ automatically migrates versioned IAP import paths without confirmation, after module
11
+ downloads and generators. Static/dynamic imports, re-exports and require calls are
12
+ covered. Comments, plain strings and Framework7 templates are preserved. Vite selects
13
+ the newest installed IAP folder containing IAP-state.js for all callers, so the existing
14
+ VK controller can use IAP 4.8 without a hardcoded 4.9 dependency. Missing imported
15
+ modules stop migration before source changes. No new IAP package is created or downloaded
16
+ by this alias helper; the existing server updater still owns version updates.
17
+ Protected AdMob controllers are excluded from source migration. A Vite resolver
18
+ maps their existing versioned IAP imports to the same installed folder without
19
+ editing or increasing the AdMob version. Existing local AdMob versions are retained.
20
+
21
+ Publish `capacitor-codeplay-rustore-ads` **0.1.1 first**, then this package **4.11.23**.
22
+ The new build preparation upgrades the old VK 0.1.0 banner implementation when
23
+ selected, installs only the selected ad provider, removes Google Billing for
24
+ Android stores 4/10, adds store 10 commands, and configures Vite's store ID and
25
+ provider alias for build and live reload. RuStore release sync sends the store
26
+ name for lookup by the updated Codeplay server. Amazon messages are store-scoped.
27
+
28
+ Each consuming app must use Capacitor 8, the shared `@admob` interface and a
29
+ current `Ads/IAP-x.x/IAP-state.js` integration. Older direct AdMob imports or IAP
30
+ integrations require updating first; this is not a universal migration of old apps.
31
+ Opt in through the app's `capacitor.config.json`:
32
+
33
+ ```json
34
+ "RuAds": {
35
+ "VK_ADS_ENABLED": true,
36
+ "STORE_IDS": [4, 10]
37
+ }
38
+ ```
39
+
40
+ Place this section under `plugins`. Copy the first versioned controller folder
41
+ manually to `src/js/Ads/vk-ads-<version>/vk-ads.js`. This package never creates or
42
+ ships a VK controller. Selecting VK without a complete controller reports an error.
43
+ The resolver selects the highest complete installed numeric folder version.
44
+ Installing/updating this package or running before-build creates only a missing
45
+ `src/js/Ads/vk-ad-configuration.json`. Existing configuration is preserved.
46
+ Fill the app's own HuaweiStore/RuStore publisher IDs; shipped defaults are zero.
47
+ Set `config.isTesting=true` for official demo slots. Finalrelease warns and saves
48
+ it as false before a VK release. Configuration stays outside the versioned folder
49
+ so controller updates preserve each app's IDs.
50
+
51
+ The existing folder updater handles subsequent VK versions. Add this key to the
52
+ server's `https://htmlcodeplay.com/code-play-plugin/versions.json`:
53
+
54
+ ```json
55
+ "vk-ads": "1.0"
56
+ ```
57
+
58
+ Upload `vk-ads-1.0.zip` beside that manifest, with `vk-ads.js` directly at the ZIP
59
+ root, following the existing folder-plugin ZIP format. For the next release,
60
+ upload the new ZIP and raise only the server entry, for example to `"1.1"`.
61
+ Before-build downloads higher advertised versions for existing VK installations,
62
+ updates references using the shared updater, and preserves the app configuration.
63
+ No codeplay-common path/version change is needed. Server deployment is manual.
64
+
65
+ Missing RuAds settings preserve AdMob selection. iOS store 6 keeps AdMob; the VK
66
+ plugin has a separate iOS API but this app adapter enables VK only on Android.
67
+ App-open/native/PiP formats remain disabled for VK. Native package changes need
68
+ a rebuilt install; changing live-reload JavaScript alone cannot replace plugins.
69
+ Explicitly disabled providers use an SDK-free controller, preserve task continuations
70
+ and never grant ad rewards. They do not require the VK adapter or IAP imports.
71
+
72
+ Release credentials are not distributed. Existing consumer release-sync config
73
+ is preserved; new consumers should set `CODEPLAY_RELEASE_SYNC_TOKEN` securely.
74
+ Do not copy publisher IDs or credentials from another app. VK creates app/slot
75
+ names using `<uniqueid>. <app name>`. Real ad serving requires separate publisher
76
+ setup and is not guaranteed by successful SDK integration or demo ads.
77
+
3
78
  ## Android system bars (4.11.22)
4
79
 
5
80
  Installation and before-build migrate installed `capacitor-codeplay-system-bars` 1.0.1 to avoid calling `Window.setNavigationBarColor` on Android 15+. Existing inset protection views, keyboard handling, icon appearance and older Android compatibility remain intact. Missing plugins are skipped; unexpected native source requires review. Before-build removes `@capacitor/status-bar` only when parsed app sources confirm modern `SystemBars` usage without legacy references. Apps with active legacy calls or unparseable source retain the dependency and report why. The existing app parser is reused; no dependency is added. Run normal Capacitor sync after dependency cleanup. Native changes require a rebuilt install; older Android compatibility code can still trigger Play static warnings.
@@ -1,4 +1,10 @@
1
- // Version 7.2: migrate Android 15 navigation-bar colors and remove unused legacy StatusBar plugins.
1
+ // Version 7.8: preserve original Vite build settings through the generated store wrapper.
2
+ // Version 7.7: migrate versioned IAP imports to the dynamic @iap Vite alias without prompting.
3
+ // Version 7.6: resolve VK folder versions dynamically and update through the shared server manifest.
4
+ // Version 7.5: exclude transitive Google billing from Huawei and RuStore builds.
5
+ // Version 7.4: install only the current store's advertising provider before building.
6
+ // Version 7.3: select RuAds for Huawei/RuStore and isolate native advertising providers.
7
+ // Version 7.2: migrate Android 15 navigation-bar colors and remove unused legacy StatusBar plugins.
2
8
  // Version 7.1: require confirmation before continuing with local versions when the server check fails.
3
9
  // Version 7.0: prepare shared splash readiness and migrate the legacy splash theme.
4
10
  // Version 6.9: preserve configured notification icons during Android resource shrinking.
@@ -16,6 +22,7 @@ try {
16
22
 
17
23
  const fs = require('fs');
18
24
  const path = require('path');
25
+ const ruAdsBuild = require('./ruads.cjs');
19
26
  const plist = require('plist');
20
27
 
21
28
  // Edit only build.rollupOptions.treeshake in the exported Vite config.
@@ -123,7 +130,32 @@ const migrateViteTreeShaking = (content) => {
123
130
  if (exported >= 0) exported += 4;
124
131
  }
125
132
  if (exported < 0) throw new Error('No supported Vite config export found; file preserved.');
126
- const config = findConfig(exported);
133
+ const exportedConfig = findConfig(exported);
134
+ // setup-ruads wraps the consumer configuration and spreads it into a new
135
+ // returned object. Edit the original declaration so build options remain
136
+ // inherited instead of adding a replacement build object to that wrapper.
137
+ const original = tokens.findIndex((token, i) => token.value === 'const'
138
+ && value(i + 1) === 'codeplayOriginalViteConfig' && value(i + 2) === '=');
139
+ const config = original >= 0 ? findConfig(original + 3) : exportedConfig;
140
+ if (original >= 0 && config !== exportedConfig) {
141
+ // Repair only the exact treeshake-only override emitted by the old migration.
142
+ // Preserve any other build customizations made to the generated wrapper.
143
+ const wrapperBuild = properties(exportedConfig).find(property => property.name === 'build');
144
+ if (wrapperBuild && value(wrapperBuild.first) === '{' && pairs.get(wrapperBuild.first) === wrapperBuild.end - 1) {
145
+ const buildProperties = properties(wrapperBuild.first);
146
+ const rollup = buildProperties[0];
147
+ if (buildProperties.length === 1 && rollup.name === 'rollupOptions' && value(rollup.first) === '{'
148
+ && pairs.get(rollup.first) === rollup.end - 1) {
149
+ const options = properties(rollup.first);
150
+ const treeshake = options[0];
151
+ if (options.length === 1 && treeshake.name === 'treeshake'
152
+ && value(treeshake.first) === 'true' && treeshake.end === treeshake.first + 1) {
153
+ edits.push({ start: tokens[wrapperBuild.start].start,
154
+ end: wrapperBuild.comma ? tokens[wrapperBuild.end].end : tokens[wrapperBuild.end - 1].end, text: '' });
155
+ }
156
+ }
157
+ }
158
+ }
127
159
  const build = properties(config).filter(property => property.name === 'build').at(-1);
128
160
  if (!build) append(config, 'build: { rollupOptions: { treeshake: true } }');
129
161
  else {
@@ -159,7 +191,7 @@ const migrateIapStartup = (content, bootstrapImport) => {
159
191
  let next = content;
160
192
  const bootstrapPattern = /import\s*\{\s*initIAP\s*\}\s*from\s*['"][^'"]*\/IAP-bootstrap\.js['"]\s*;?/;
161
193
  if (!bootstrapPattern.test(next)) {
162
- next = next.replace(/import\s*\{([^}]*)\}\s*from\s*(['"])([^'"]*\/IAP-\d+(?:\.\d+)*\/IAP-check-And-LoadAd\.js)\2\s*;?/g,
194
+ next = next.replace(/import\s*\{([^}]*)\}\s*from\s*(['"])((?:[^'"]*\/IAP-\d+(?:\.\d+)*\/|@iap\/)IAP-check-And-LoadAd\.js)\2\s*;?/g,
163
195
  (match, names, quote, source) => {
164
196
  const imports = names.split(',').map(name => name.trim()).filter(Boolean);
165
197
  if (!imports.includes('initIAP')) return match;
@@ -1699,6 +1731,7 @@ function getAdMobConfig() {
1699
1731
  }
1700
1732
 
1701
1733
  const isEnabled =
1734
+ ruAdsBuild.getAdProvider(capacitorConfig, process.env.VITE_STORE_ID, buildPlatform) === 'admob' &&
1702
1735
  nextGenAdmobConfig.enabled !== false &&
1703
1736
  legacyAdmobConfig.ADMOB_ENABLED !== false;
1704
1737
 
@@ -2492,6 +2525,7 @@ if (pluginDef.isFolder) {
2492
2525
  fs.mkdirSync(stagingRoot, { recursive: true });
2493
2526
  const staging = fs.mkdtempSync(path.join(stagingRoot, 'package-'));
2494
2527
  await downloadAndExtractZip(url, staging);
2528
+ if (baseName === 'vk-ads' && (!fs.existsSync(path.join(staging, 'vk-ads.js')) || !fs.statSync(path.join(staging, 'vk-ads.js')).isFile() || fs.statSync(path.join(staging, 'vk-ads.js')).size === 0)) throw new Error('Invalid VK archive: vk-ads.js is missing or empty; existing sources preserved.');
2495
2529
  if (baseName === 'IAP' && ['IAP-check-And-LoadAd.js', 'IAP-bootstrap.js', 'IAP-state.js', 'IAP-store.js'].some(name => !fs.existsSync(path.join(staging, name)))) throw new Error('Invalid IAP archive');
2496
2530
  if (fs.existsSync(newPath)) throw new Error('Replacement folder already exists; existing sources preserved.');
2497
2531
  fs.renameSync(staging, newPath);
@@ -2690,12 +2724,16 @@ function checkPlugins() {
2690
2724
 
2691
2725
  for (const dir of subDirs) {
2692
2726
  const relativePath = path.relative(searchRoot, dir).replace(/\\/g, '/');
2727
+ if (plugin.name === 'vk-ads') {
2728
+ const latestVk = ruAdsBuild.findLatestVkController(process.cwd());
2729
+ if (latestVk && path.basename(path.dirname(latestVk)) !== relativePath) continue;
2730
+ }
2693
2731
  const match = plugin.pattern.exec(relativePath);
2694
2732
 
2695
2733
  if (match) {
2696
2734
  const currentVersion = match[1];
2697
2735
 
2698
- if (compareVersions(currentVersion, plugin.minVersion) < 0) {
2736
+ if ((plugin.name === 'vk-ads' ? compareVersionStrings(currentVersion, plugin.minVersion) : compareVersions(currentVersion, plugin.minVersion)) < 0) {
2699
2737
  outdatedPlugins.push({
2700
2738
  name: relativePath,
2701
2739
  currentVersion,
@@ -3131,28 +3169,7 @@ const syncViteTreeShaking = () => {
3131
3169
  }
3132
3170
  };
3133
3171
 
3134
- const getLatestIapDir = () => {
3135
- const adsDir = path.join(process.cwd(), "src", "js", "Ads");
3136
-
3137
- if (!fs.existsSync(adsDir)) return null;
3138
-
3139
- const iapDirs = fs.readdirSync(adsDir, { withFileTypes: true })
3140
- .filter(entry => entry.isDirectory() && /^IAP-\d+(\.\d+)*$/.test(entry.name))
3141
- .map(entry => entry.name)
3142
- .sort((a, b) => {
3143
- const versionA = a.match(/(\d+(?:\.\d+)*)/)[1].split(".").map(Number);
3144
- const versionB = b.match(/(\d+(?:\.\d+)*)/)[1].split(".").map(Number);
3145
-
3146
- for (let i = 0; i < Math.max(versionA.length, versionB.length); i++) {
3147
- const diff = (versionB[i] || 0) - (versionA[i] || 0);
3148
- if (diff !== 0) return diff;
3149
- }
3150
-
3151
- return 0;
3152
- });
3153
-
3154
- return iapDirs.length > 0 ? path.join(adsDir, iapDirs[0]) : null;
3155
- };
3172
+ const getLatestIapDir = () => require('./iap-alias.cjs').findLatestIapDirectory(process.cwd());
3156
3173
 
3157
3174
  const getAnalyticsConfig = () => {
3158
3175
  const config = fs.existsSync(configPath)
@@ -3535,6 +3552,8 @@ const ensureAdmobNextgenFiles = async () => {
3535
3552
  };
3536
3553
 
3537
3554
  const syncAdmobNextgenMigration = async () => {
3555
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
3556
+ if (ruAdsBuild.getAdProvider(config, process.env.VITE_STORE_ID, buildPlatform) !== 'admob') return;
3538
3557
  syncAdmobNextgenPackage();
3539
3558
  await ensureAdmobNextgenFiles();
3540
3559
  syncAdmobAliasInViteConfig();
@@ -4074,9 +4093,11 @@ const syncAmazonFireWebViewDependency = (enabled) => {
4074
4093
  fs.writeFileSync(androidAppBuildGradlePath, nextContent, "utf8");
4075
4094
  }
4076
4095
 
4077
- console.log(enabled
4078
- ? "✅ Amazon Fire WebView compatibility dependency enabled for Store ID 7."
4079
- : "ℹ️ Amazon Fire WebView compatibility dependency disabled for this store.");
4096
+ if (getCurrentStoreId() === 7) {
4097
+ console.log(enabled
4098
+ ? "✅ Amazon Fire WebView compatibility dependency enabled for Store ID 7."
4099
+ : "ℹ️ Amazon Fire WebView compatibility dependency disabled for this store.");
4100
+ }
4080
4101
  };
4081
4102
 
4082
4103
  function syncAndroidAdIdPermission() {
@@ -4191,7 +4212,8 @@ const syncRevenueCatIapSetup = () => {
4191
4212
  }
4192
4213
 
4193
4214
  if (packageChanged) {
4194
- runNpmCommand("npx cap sync");
4215
+ ruAdsBuild.withNativeAdProvider(process.cwd(), getCurrentStoreId(), buildPlatform,
4216
+ () => runNpmCommand(`npx cap sync ${buildPlatform}`));
4195
4217
  }
4196
4218
  };
4197
4219
 
@@ -4698,7 +4720,8 @@ async function main() {
4698
4720
  buildPackage.scripts = buildScripts;
4699
4721
  fs.writeFileSync(packageJsonPath, JSON.stringify(buildPackage, null, 2) + '\n');
4700
4722
  }
4701
- require('./splash-setup.cjs').syncSplashSetup(process.cwd());
4723
+ require('./splash-setup.cjs').syncSplashSetup(process.cwd());
4724
+ require('./setup-ruads.cjs').syncRuAdsSetup(process.cwd());
4702
4725
  validateThemeFolderLocation();
4703
4726
  validateAndRestoreSignDetails();
4704
4727
  ensureMandatoryCapacitorPlugins();
@@ -4706,13 +4729,17 @@ async function main() {
4706
4729
  await loadPluginVersions(); // 🔥 NEW
4707
4730
  await syncAgentInstructions();
4708
4731
  if (!skipOnlineVersionChecks) await checkPlugins();
4732
+ // Validate only the selected provider after the shared folder updater finishes.
4733
+ ruAdsBuild.controllerPath(JSON.parse(fs.readFileSync(path.join(process.cwd(), 'capacitor.config.json'), 'utf8')),
4734
+ getCurrentStoreId(), buildPlatform, null);
4709
4735
  // Downloads may add a newer helper or source files containing legacy imports.
4710
4736
  await saveToGalleryAndSaveFileCheck_iOS();
4711
4737
 
4738
+ const adPackagesChanged = ruAdsBuild.syncAdProviderPackages(process.cwd(), runNpmCommand);
4712
4739
  await syncAdmobNextgenMigration();
4713
- syncCodeplaySystemBarsPackage();
4714
- require('./migrate-system-bars.cjs').migrateSystemBars();
4715
- const legacyStatusBar = await require('./migrate-system-bars.cjs').migrateLegacyStatusBar();
4740
+ syncCodeplaySystemBarsPackage();
4741
+ require('./migrate-system-bars.cjs').migrateSystemBars();
4742
+ const legacyStatusBar = await require('./migrate-system-bars.cjs').migrateLegacyStatusBar();
4716
4743
  if (legacyStatusBar.status === 'retained') console.warn('Legacy StatusBar plugin retained:', legacyStatusBar.references.join(', '));
4717
4744
  syncSystemBarsSafeAreaMigration();
4718
4745
  ensureIapStartupOnHomePage();
@@ -4720,10 +4747,17 @@ async function main() {
4720
4747
  syncFirebaseAnalyticsSetup();
4721
4748
  checkAndupdateDropInViteConfig();
4722
4749
  syncViteTreeShaking();
4750
+ sourceFileInventory = null;
4751
+ require('./iap-alias.cjs').syncIapAliases(process.cwd(), getSourceFiles());
4723
4752
  checkAdmobConfigurationProperty();
4724
4753
  syncAndroidAdIdPermission();
4725
4754
  syncAndroidBuildOptimization();
4726
4755
  syncAndroidCordovaResourceKeep();
4756
+ require('./store-billing.cjs').syncStoreBillingPolicy(process.cwd(), getCurrentStoreId(), buildPlatform);
4757
+ if (adPackagesChanged) {
4758
+ ruAdsBuild.withNativeAdProvider(process.cwd(), getCurrentStoreId(), buildPlatform,
4759
+ () => runNpmCommand(`npx cap sync ${buildPlatform}`));
4760
+ }
4727
4761
  }
4728
4762
 
4729
4763
  await main();
@@ -0,0 +1,45 @@
1
+ // Shared ad interface for builds with both native providers disabled.
2
+ const ignore = () => {};
3
+ const unavailable = async () => false;
4
+ const hidden = async () => true;
5
+ export const _isVideoLoad = false;
6
+ export const _isRewardInterstitialLoad = false;
7
+ export const _isNativeAdLoaded = false;
8
+ export const _bannerAdHeight = 0;
9
+ export const adjustWebViewForBanner = ignore;
10
+ export const hideGoogleBannerAd = hidden;
11
+ export const showGoogleBannerAd = unavailable;
12
+ export const canRequestAppAds = () => false;
13
+ export const getAdPrivacyOptionsState = () => ({ supported: false, requirementStatus: 'NOT_REQUIRED', loading: false, error: false, canRetry: false });
14
+ export const isAdPrivacyOptionsRequired = () => false;
15
+ export const requestAppAdConsent = unavailable;
16
+ export const adsOnDeviceReady = unavailable;
17
+ export const showAppAdPrivacyOptions = unavailable;
18
+ export const refreshAppAdConsent = showAppAdPrivacyOptions;
19
+ export async function withAdPrivacyChoices(callback) {
20
+ if (typeof callback === 'function') await callback();
21
+ }
22
+ export const disableFor_IAP_Subscription = ignore;
23
+ export const enableFor_IAP_Subscription = ignore;
24
+ export const disableFor_CREDIT_Subscription = ignore;
25
+ export const showRewardVideo = unavailable;
26
+ export async function levelWinInterstitial(callback) {
27
+ if (typeof callback === 'function') await callback();
28
+ return false;
29
+ }
30
+ export const runInterstitialTaskTransition = levelWinInterstitial;
31
+ export const disableAppOpenAd = ignore;
32
+ export const enableAppOpenAd = ignore;
33
+ export const noAppOpenShowUntilResume = ignore;
34
+ export const showRewardInterstitial = unavailable;
35
+ export const showNativeAd = unavailable;
36
+ export const showNativeAdInElement = showNativeAd;
37
+ export const hideNativeAd = hidden;
38
+ export const hideNativeAdInElement = hideNativeAd;
39
+ export const loadPictureInPictureAd = unavailable;
40
+ export const showPictureInPictureAd = loadPictureInPictureAd;
41
+ export const hidePictureInPictureAd = hidden;
42
+ export const destroyPictureInPictureAd = hidePictureInPictureAd;
43
+ export const removePictureInPictureAd = destroyPictureInPictureAd;
44
+ export const getPictureInPictureAdState = () => ({ loading: false, loaded: false, showing: false, fullscreen: false, adUnitId: '', error: null });
45
+ export const addPictureInPictureAdListener = () => ({ remove: ignore });
@@ -0,0 +1,108 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ function findLatestIapDirectory(projectRoot = process.cwd()) {
5
+ const ads = path.join(projectRoot, 'src/js/Ads');
6
+ if (!fs.existsSync(ads)) return null;
7
+ const folder = fs.readdirSync(ads, { withFileTypes: true })
8
+ .filter(entry => entry.isDirectory() && /^IAP-\d+(?:\.\d+)*$/.test(entry.name)
9
+ && fs.existsSync(path.join(ads, entry.name, 'IAP-state.js'))
10
+ && fs.statSync(path.join(ads, entry.name, 'IAP-state.js')).isFile())
11
+ .map(entry => entry.name).sort((a, b) => b.localeCompare(a, undefined, { numeric: true }))[0];
12
+ return folder ? path.join(ads, folder) : null;
13
+ }
14
+
15
+ // Resolve old protected controllers without rewriting their source or version.
16
+ function legacyIapPlugin(projectRoot = process.cwd()) {
17
+ return {
18
+ name: 'codeplay-legacy-iap-imports',
19
+ enforce: 'pre',
20
+ async resolveId(source, importer) {
21
+ const match = /^(?:(?:\.\.?\/)+|@\/|\/src\/)(?:[^?#]*\/)?IAP-\d+(?:\.\d+)*\/([^?#]+)([?#].*)?$/.exec(source);
22
+ if (!match) return null;
23
+ const directory = findLatestIapDirectory(projectRoot);
24
+ if (!directory) throw new Error('Cannot resolve legacy IAP import: no installed IAP-state.js.');
25
+ const target = path.resolve(directory, match[1]);
26
+ if (!target.startsWith(directory + path.sep) || !fs.existsSync(target) || !fs.statSync(target).isFile()) throw new Error(`Missing IAP module: ${source}`);
27
+ return this.resolve(target + (match[2] || ''), importer, { skipSelf: true });
28
+ },
29
+ };
30
+ }
31
+
32
+ // Reuse the before-build source inventory and gallery migration's import scanner.
33
+ // Only module specifiers are changed; comments, text and F7 markup are preserved.
34
+ function syncIapAliases(projectRoot = process.cwd(), files = []) {
35
+ const directory = findLatestIapDirectory(projectRoot);
36
+ const plans = [];
37
+ for (const file of files) {
38
+ if (file.split(path.sep).some(part => /^admob-nextgen-\d+(?:\.\d+)*$/.test(part)) || /^admob-emi-nextgen-\d+(?:\.\d+)*\.js$/.test(path.basename(file))) continue;
39
+ if (!/\.(?:js|mjs|cjs|ts|tsx|jsx|f7|vue)$/.test(file) || file.endsWith('.min.js')) continue;
40
+ const original = fs.readFileSync(file, 'utf8');
41
+ let script = original;
42
+ if (/\.(f7|vue)$/.test(file)) {
43
+ script = original.replace(/[^\r\n]/g, ' ');
44
+ for (const match of original.matchAll(/<script\b[^>]*>([\s\S]*?)<\/script\s*>/gi)) {
45
+ const start = match.index + match[0].indexOf('>') + 1;
46
+ script = script.slice(0, start) + match[1] + script.slice(start + match[1].length);
47
+ }
48
+ }
49
+ const code = script.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|(['"`])(?:\\[\s\S]|(?!\1)[^\\])*\1/g,
50
+ (match, quote) => quote ? match : match.replace(/[^\r\n]/g, ' '));
51
+ const imports = /(['"`])(?:\\[\s\S]|(?!\1)[^\\])*\1|\b(?:import\s+(?:[^;'"`]*?\s+from\s*)?|export\s+[^;'"`]*?\s+from\s*|(?:import|require)\s*\(\s*)(['"])([^'"\r\n]+)\2/g;
52
+ const replacements = [];
53
+ for (const match of code.matchAll(imports)) {
54
+ const specifier = match[3];
55
+ if (!specifier) continue;
56
+ const versioned = /^(?:(?:\.\.?\/)+|@\/|\/src\/)(?:[^?#]*\/)?IAP-\d+(?:\.\d+)*\/([^?#]+)([?#].*)?$/.exec(specifier);
57
+ const aliased = /^@iap\/([^?#]+)([?#].*)?$/.exec(specifier);
58
+ if (!versioned && !aliased) continue;
59
+ if (!directory) throw new Error(`Cannot configure @iap: no installed IAP folder with IAP-state.js (${file}).`);
60
+ const module = (versioned || aliased)[1];
61
+ const target = path.resolve(directory, module);
62
+ if (!target.startsWith(directory + path.sep) || !fs.existsSync(target) || !fs.statSync(target).isFile()) throw new Error(`Missing @iap/${module} in ${directory}; update the compatible IAP package first.`);
63
+ if (versioned) {
64
+ const start = match.index + match[0].lastIndexOf(specifier);
65
+ replacements.push({ start, length: specifier.length, value: `@iap/${module}${versioned[2] || ''}` });
66
+ }
67
+ }
68
+ let updated = original;
69
+ for (const edit of replacements.reverse()) updated = updated.slice(0, edit.start) + edit.value + updated.slice(edit.start + edit.length);
70
+ if (updated !== original) plans.push({ file, updated });
71
+ }
72
+ const vite = ['vite.config.mjs', 'vite.config.js'].map(name => path.join(projectRoot, name)).find(file => fs.existsSync(file));
73
+ if (directory && vite) {
74
+ let original = fs.readFileSync(vite, 'utf8');
75
+ const saved = original;
76
+ if (!original.includes('codeplayIapAliases.findLatestIapDirectory(')) {
77
+ const code = original.replace(/\/\/[^\r\n]*|\/\*[\s\S]*?\*\/|(['"`])(?:\\[\s\S]|(?!\1)[^\\])*\1/g,
78
+ (match, quote) => quote ? match : match.replace(/[^\r\n]/g, ' '));
79
+ const header = /\balias\s*:\s*([\[{])/.exec(code);
80
+ if (!header) throw new Error('Cannot configure @iap: Vite needs a resolve.alias object or array.');
81
+ if (/['"]@iap['"]\s*[:,]/.test(code)) throw new Error('Cannot replace a custom @iap alias automatically; use codeplayIapAliases.findLatestIapDirectory().');
82
+ const entry = header[1] === '{'
83
+ ? "'@iap': codeplayIapAliases.findLatestIapDirectory(),"
84
+ : "{ find: '@iap', replacement: codeplayIapAliases.findLatestIapDirectory() },";
85
+ const offset = header.index + header[0].length;
86
+ const newline = original.includes('\r\n') ? '\r\n' : '\n';
87
+ const updated = original.slice(0, offset) + newline + ' ' + entry + original.slice(offset);
88
+ original = `import codeplayIapAliases from './buildCodeplay/iap-alias.cjs';${newline}${updated}`;
89
+ }
90
+ if (!original.includes('codeplayIapAliases.legacyIapPlugin(')) {
91
+ const plugins = /\bplugins\s*:\s*\[/.exec(original);
92
+ if (plugins) {
93
+ const offset = plugins.index + plugins[0].length;
94
+ original = original.slice(0, offset) + '\n codeplayIapAliases.legacyIapPlugin(),' + original.slice(offset);
95
+ } else {
96
+ const resolve = /\bresolve\s*:/.exec(original);
97
+ if (!resolve) throw new Error('Cannot configure legacy IAP resolution: Vite resolve settings missing.');
98
+ original = original.slice(0, resolve.index) + 'plugins: [codeplayIapAliases.legacyIapPlugin()],\n' + original.slice(resolve.index);
99
+ }
100
+ }
101
+ if (saved !== original) plans.push({ file: vite, updated: original });
102
+ }
103
+ // Validate the complete migration before writing. No confirmation is needed.
104
+ for (const plan of plans) fs.writeFileSync(plan.file, plan.updated);
105
+ return plans.map(plan => path.relative(projectRoot, plan.file));
106
+ }
107
+
108
+ module.exports = { findLatestIapDirectory, legacyIapPlugin, syncIapAliases };
@@ -0,0 +1,3 @@
1
+ # MyTracker checks for BillingClient/Purchase classes and disables its Google
2
+ # purchase helper when absent. These optional classes are excluded on stores 4/10.
3
+ -dontwarn com.android.billingclient.**
@@ -22,7 +22,7 @@ function updateBuildScripts(scripts) {
22
22
  }
23
23
  if (!next.build) next.build = `${tasks['before-build']} && ${tasks['package-id']} && cross-env NODE_ENV=production vite build --logLevel warn`;
24
24
  else if (!next.build.includes(tasks['before-build'])) next.build = `${tasks['before-build']} && ${next.build}`;
25
- for (const id of [1, 2, 3, 4, 5, 7, 8]) {
25
+ for (const id of [1, 2, 3, 4, 5, 7, 8, 10]) {
26
26
  const key = `build:storeid${id}`;
27
27
  if (!next[key]) next[key] = `vite build --mode storeid${id}`;
28
28
  if (!next[key].includes(tasks['before-build'])) next[key] = `cross-env VITE_STORE_ID=${id} ${tasks['before-build']} && cross-env VITE_STORE_ID=${id} ${next[key]}`;
@@ -1,4 +1,4 @@
1
- {
2
- "url": "https://htmlcodeplay.com/codeplay/api/v1/release/sync",
3
- "token": "b_TiY0Lu7q7Yb0Kx9djVxA6ST8k4CFiwFQNxgci7AAU"
4
- }
1
+ {
2
+ "url": "https://htmlcodeplay.com/codeplay/api/v1/release/sync",
3
+ "token": ""
4
+ }
@@ -0,0 +1,111 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { execFileSync } = require('child_process');
4
+
5
+ const VK_PACKAGE = 'capacitor-codeplay-rustore-ads';
6
+ const ADMOB_PACKAGE = 'capacitor-admob-nextgen';
7
+
8
+ // A missing RuAds section preserves the existing provider on every store.
9
+ function getAdProvider(config, storeId, platform = 'android') {
10
+ const id = Number(storeId || 1);
11
+ const ru = config.plugins?.RuAds;
12
+ const assigned = platform !== 'ios' && [4, 10].includes(id)
13
+ && (ru?.STORE_IDS || []).map(Number).includes(id);
14
+ if (assigned) return ru.VK_ADS_ENABLED === true ? 'vk' : 'none';
15
+ return config.plugins?.AdMob?.ADMOB_ENABLED === false ? 'none' : 'admob';
16
+ }
17
+
18
+ function findLatestVkController(projectRoot = process.cwd()) {
19
+ const ads = path.join(projectRoot, 'src/js/Ads');
20
+ const pattern = /^vk-ads-(\d+(?:\.\d+)*)$/;
21
+ if (!fs.existsSync(ads)) return null;
22
+ const folders = fs.readdirSync(ads, { withFileTypes: true }).filter(entry => entry.isDirectory() && pattern.test(entry.name))
23
+ .map(entry => entry.name).sort((a, b) => b.match(pattern)[1].localeCompare(a.match(pattern)[1], undefined, { numeric: true }));
24
+ const folder = folders.find(name => {
25
+ const file = path.join(ads, name, 'vk-ads.js');
26
+ return fs.existsSync(file) && fs.statSync(file).isFile() && fs.statSync(file).size > 0;
27
+ });
28
+ return folder ? `./src/js/Ads/${folder}/vk-ads.js` : null;
29
+ }
30
+
31
+ function controllerPath(config, storeId, platform, admobPath, projectRoot = process.cwd()) {
32
+ const provider = getAdProvider(config, storeId, platform);
33
+ if (provider === 'admob') return admobPath;
34
+ if (provider === 'none') return './buildCodeplay/disabled-ads.mjs';
35
+ const controller = findLatestVkController(projectRoot);
36
+ if (!controller) throw new Error('VK ads is enabled but no complete src/js/Ads/vk-ads-<version>/vk-ads.js exists. Copy the versioned VK folder manually first; later updates use the server versions.json entry "vk-ads".');
37
+ return controller;
38
+ }
39
+
40
+ function prepareReleaseAds(projectRoot, storeId, platform = 'android', warn = console.warn) {
41
+ const capacitorConfig = JSON.parse(fs.readFileSync(path.join(projectRoot, 'capacitor.config.json')));
42
+ if (getAdProvider(capacitorConfig, storeId, platform) !== 'vk') return false;
43
+ const file = path.join(projectRoot, 'src/js/Ads/vk-ad-configuration.json');
44
+ const original = fs.readFileSync(file, 'utf8');
45
+ const configuration = JSON.parse(original);
46
+ if (configuration.config?.isTesting !== true) return false;
47
+ warn('\x1b[33m⚠️ VK test ads are enabled. Automatically setting config.isTesting to false in src/js/Ads/vk-ad-configuration.json before release.\x1b[0m');
48
+ configuration.config.isTesting = false;
49
+ const newline = original.includes('\r\n') ? '\r\n' : '\n';
50
+ fs.writeFileSync(file, (JSON.stringify(configuration, null, 2) + '\n').replaceAll('\n', newline));
51
+ return true;
52
+ }
53
+
54
+ function includedPackages(config, pkg, platform, provider) {
55
+ const existing = config[platform]?.includePlugins ?? config.includePlugins;
56
+ const packages = existing || [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {})];
57
+ return [...new Set(packages.filter(name => ![VK_PACKAGE, ADMOB_PACKAGE].includes(name))
58
+ .concat(provider === 'vk' ? [VK_PACKAGE] : provider === 'admob' ? [ADMOB_PACKAGE] : []))];
59
+ }
60
+
61
+ function syncAdProviderPackages(projectRoot = process.cwd(), run) {
62
+ const config = JSON.parse(fs.readFileSync(path.join(projectRoot, 'capacitor.config.json')));
63
+ const provider = getAdProvider(config, process.env.VITE_STORE_ID, process.env.CODEPLAY_BUILD_PLATFORM);
64
+ const selected = provider === 'vk' ? VK_PACKAGE : provider === 'admob' ? ADMOB_PACKAGE : null;
65
+ const readPackage = () => JSON.parse(fs.readFileSync(path.join(projectRoot, 'package.json')));
66
+ const installed = name => fs.existsSync(path.join(projectRoot, 'node_modules', name, 'package.json'));
67
+ const execute = args => {
68
+ if (run) run(`npm ${args.join(' ')}`);
69
+ else execFileSync(process.platform === 'win32' ? 'npm.cmd' : 'npm', args,
70
+ { cwd: projectRoot, stdio: 'inherit', shell: process.platform === 'win32' });
71
+ };
72
+ let changed = false;
73
+ for (const name of [ADMOB_PACKAGE, VK_PACKAGE]) {
74
+ const pkg = readPackage();
75
+ if (name !== selected && (pkg.dependencies?.[name] || pkg.devDependencies?.[name] || installed(name))) {
76
+ execute(['uninstall', name]);
77
+ changed = true;
78
+ }
79
+ }
80
+ const pkg = readPackage();
81
+ const vkVersion = selected === VK_PACKAGE && installed(selected)
82
+ ? JSON.parse(fs.readFileSync(path.join(projectRoot, 'node_modules', selected, 'package.json'))).version : null;
83
+ const [major, minor, patch] = String(vkVersion || '').split('.').map(Number);
84
+ const oldVk = vkVersion && major === 0 && (minor < 1 || (minor === 1 && patch < 1));
85
+ if (selected && (!pkg.dependencies?.[selected] || !installed(selected) || oldVk)) {
86
+ const version = oldVk ? '^0.1.1' : pkg.dependencies?.[selected] || (selected === VK_PACKAGE ? '^0.1.1' : '');
87
+ execute(['install', version ? `${selected}@${version}` : selected, '--save']);
88
+ changed = true;
89
+ }
90
+ return changed;
91
+ }
92
+
93
+ // includePlugins is scoped to cap sync; always restore the caller's configuration.
94
+ // Filtering affects both Capacitor and Cordova discovery without uninstalling other providers.
95
+ function withNativeAdProvider(projectRoot, storeId, platform, action) {
96
+ const configPath = path.join(projectRoot, 'capacitor.config.json');
97
+ const original = fs.readFileSync(configPath, 'utf8');
98
+ const config = JSON.parse(original);
99
+ const pkg = JSON.parse(fs.readFileSync(path.join(projectRoot, 'package.json')));
100
+ const provider = getAdProvider(config, storeId, platform);
101
+ const targets = platform ? [platform] : ['android', 'ios'];
102
+ for (const target of targets) {
103
+ config[target] = { ...config[target], includePlugins: includedPackages(config, pkg, target,
104
+ getAdProvider(config, storeId, target)) };
105
+ }
106
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n');
107
+ try { return action(provider); }
108
+ finally { fs.writeFileSync(configPath, original); }
109
+ }
110
+
111
+ module.exports = { getAdProvider, controllerPath, findLatestVkController, prepareReleaseAds, includedPackages, syncAdProviderPackages, withNativeAdProvider };
@@ -0,0 +1,49 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ function syncRuAdsSetup(projectRoot, { runtimeRoot } = {}) {
5
+ const config = JSON.parse(fs.readFileSync(path.join(projectRoot, 'capacitor.config.json')));
6
+ const vite = ['vite.config.mjs', 'vite.config.js'].map(name => path.join(projectRoot, name)).find(file => fs.existsSync(file));
7
+ if (vite) {
8
+ const source = fs.readFileSync(vite, 'utf8');
9
+ if (!source.includes('ruAdsBuild.controllerPath(') && !source.includes('codeplayOriginalViteConfig')) {
10
+ if (!/^[ \t]*export\s+default\s+/m.test(source)) throw new Error('Cannot configure RuAds: Vite must have a default configuration export.');
11
+ const wrapped = source.replace(/^[ \t]*export\s+default\s+/m, 'const codeplayOriginalViteConfig = ');
12
+ fs.writeFileSync(vite, `import ruAdsBuild from './buildCodeplay/ruads.cjs';
13
+ import { readFileSync as codeplayReadConfig } from 'node:fs';
14
+ import { resolve as codeplayResolve } from 'node:path';
15
+ ${wrapped}
16
+ export default async (environment) => {
17
+ const base = await (typeof codeplayOriginalViteConfig === 'function'
18
+ ? codeplayOriginalViteConfig(environment) : codeplayOriginalViteConfig);
19
+ const settings = JSON.parse(codeplayReadConfig(codeplayResolve('capacitor.config.json'), 'utf8'));
20
+ const storeId = process.env.VITE_STORE_ID || '1';
21
+ const platform = process.env.CODEPLAY_BUILD_PLATFORM || (storeId === '6' ? 'ios' : 'android');
22
+ const aliases = base.resolve?.alias || {};
23
+ const current = Array.isArray(aliases) ? aliases.find(item => item.find === '@admob')?.replacement : aliases['@admob'];
24
+ const provider = ruAdsBuild.getAdProvider(settings, storeId, platform);
25
+ if (!current && provider === 'vk') {
26
+ throw new Error('VK ads requires the shared @admob alias. Update this app integration first.');
27
+ }
28
+ const selected = current && (provider === 'admob' ? current : codeplayResolve(ruAdsBuild.controllerPath(settings, storeId, platform, current)));
29
+ const alias = !selected ? aliases : Array.isArray(aliases)
30
+ ? aliases.map(item => item.find === '@admob' ? { ...item, replacement: selected } : item)
31
+ : { ...aliases, '@admob': selected };
32
+ return { ...base, resolve: { ...base.resolve, alias }, define: { ...base.define,
33
+ 'import.meta.env.VITE_STORE_ID': JSON.stringify(storeId),
34
+ 'import.meta.env.VITE_RUADS_ENABLED': JSON.stringify(provider === 'vk') } };
35
+ };
36
+ `);
37
+ }
38
+ }
39
+ const ru = config.plugins?.RuAds;
40
+ if (ru?.VK_ADS_ENABLED !== true || !(ru.STORE_IDS || []).some(id => [4, 10].includes(Number(id)))) return;
41
+ const ads = path.join(projectRoot, 'src/js/Ads');
42
+ const configuration = path.join(ads, 'vk-ad-configuration.json');
43
+ if (fs.existsSync(configuration)) return;
44
+ const runtime = runtimeRoot || path.join(projectRoot, 'node_modules/codeplay-common/runtime/vk-ads');
45
+ fs.mkdirSync(ads, { recursive: true });
46
+ fs.copyFileSync(path.join(runtime, 'vk-ad-configuration.json'), configuration);
47
+ }
48
+
49
+ module.exports = { syncRuAdsSetup };
@@ -0,0 +1,43 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const start = '// BEGIN CODEPLAY NON-GOOGLE STORE BILLING';
5
+ const end = '// END CODEPLAY NON-GOOGLE STORE BILLING';
6
+ const block = `${start}
7
+ configurations.configureEach {
8
+ exclude group: 'com.android.billingclient'
9
+ }
10
+ android.buildTypes.configureEach {
11
+ proguardFile file('../../buildCodeplay/non-google-billing.pro')
12
+ }
13
+ ${end}`;
14
+
15
+ function syncStoreBillingPolicy(projectRoot, storeId, platform = 'android') {
16
+ if (platform !== 'android') return false;
17
+ const excluded = [4, 10].includes(Number(storeId));
18
+ const gradle = path.join(projectRoot, 'android/app/build.gradle');
19
+ if (!fs.existsSync(gradle)) return false;
20
+ const original = fs.readFileSync(gradle, 'utf8');
21
+ const newline = original.includes('\r\n') ? '\r\n' : '\n';
22
+ const clean = original.replace(new RegExp(`${start}[\\s\\S]*?${end}\\r?\\n?`, 'g'), '');
23
+ const updated = excluded
24
+ ? `${clean.trimEnd()}${newline}${newline}${block.replaceAll('\n', newline)}${newline}`
25
+ : clean;
26
+ let changed = updated !== original;
27
+ if (changed) fs.writeFileSync(gradle, updated);
28
+
29
+ // The excluded library supplies its own permission. Also remove any explicit
30
+ // app declaration; other permissions and supported-store billing stay intact.
31
+ const manifest = path.join(projectRoot, 'android/app/src/main/AndroidManifest.xml');
32
+ if (excluded && fs.existsSync(manifest)) {
33
+ const current = fs.readFileSync(manifest, 'utf8');
34
+ const next = current.replace(/^[ \t]*<uses-permission\b(?=[^>]*\bandroid:name\s*=\s*(['"])com\.android\.vending\.BILLING\1)[^>]*\/\s*>[ \t]*(?:\r?\n)?/gm, '');
35
+ if (next !== current) {
36
+ fs.writeFileSync(manifest, next);
37
+ changed = true;
38
+ }
39
+ }
40
+ return changed;
41
+ }
42
+
43
+ module.exports = { syncStoreBillingPolicy };
@@ -1,5 +1,6 @@
1
1
  {
2
2
  "plugins":[
3
+ {"name":"vk-ads","pattern":"vk-ads-(\\d+(?:\\.\\d+)*)$","minVersion":"1.0","baseDir":"js/Ads","mandatoryUpdate":true,"isFolder":true},
3
4
  {"name":"backbutton","pattern":"backbutton-(\\d+\\.\\d+)\\.js$","minVersion":"2.1","baseDir":"js","mandatoryUpdate":true},
4
5
  {"name":"common-js","pattern":"common-(\\d+\\.\\d+)(?:-beta-(\\d+))?\\.js$","minVersion":"6.7","baseDir":"js","mandatoryUpdate":true},
5
6
 
@@ -3,6 +3,7 @@ Can be run like
3
3
  node finalrelease
4
4
  node finalrelease 1
5
5
  node finalrelease "1,2,7"
6
+ node finalrelease 10 // RuStore signed AAB (9 is reserved for desktop)
6
7
  */
7
8
 
8
9
  import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
@@ -18,6 +19,7 @@ import { syncAndroidR8Rules } from './buildCodeplay/fix-optimize-builld/restore-
18
19
  const fs = require('fs'); */
19
20
 
20
21
  import fs from 'fs';
22
+ import ruAdsBuild from './buildCodeplay/ruads.cjs';
21
23
  import path from 'path';
22
24
 
23
25
  const __filename = fileURLToPath(import.meta.url);
@@ -179,6 +181,9 @@ function checkProductionAdmobAlias() {
179
181
  }
180
182
 
181
183
  const activeAlias = activeAliases[0];
184
+ if (capacitorConfig.plugins?.RuAds && !viteConfigContent.includes('ruAdsBuild.controllerPath(')) {
185
+ throw new Error('RuAds requires the store-aware controller selector in Vite.');
186
+ }
182
187
  if (!productionAliasPattern.test(activeAlias)) {
183
188
  console.error(`❌ FINAL RELEASE BLOCKED: @admob currently points to '${activeAlias}'.`);
184
189
  console.error(" It must point to './src/js/Ads/admob-nextgen-x.x/admob-emi-nextgen.js', not a test AdMob file.");
@@ -216,11 +221,12 @@ const storeNames = {
216
221
  "4": "HuaweiStore",
217
222
  "5": "OppoStore",
218
223
  //"6": "iOSStore",
219
- "8": "VivoStore"
224
+ "8": "VivoStore",
225
+ "10": "RuStore"
220
226
  };
221
227
 
222
228
 
223
- //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
229
+ //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore 9=> Desktop (not built here) 10=> RuStore
224
230
 
225
231
 
226
232
 
@@ -254,9 +260,16 @@ if (existsSync(releaseSyncConfigPath)) {
254
260
  }
255
261
  const RELEASE_SYNC_URL = process.env.CODEPLAY_RELEASE_SYNC_URL || releaseSyncConfig.url || 'https://htmlcodeplay.com/codeplay/api/v1/release/sync';
256
262
  const RELEASE_SYNC_TOKEN = process.env.CODEPLAY_RELEASE_SYNC_TOKEN || releaseSyncConfig.token || '';
263
+ // RuStore is resolved by name on the server; numeric IDs remain server-owned.
257
264
  const RELEASE_PLATFORM_IDS = { PlayStore: 1, SamsungStore: 13, AmazonStore: 17, MiStore: 15, HuaweiStore: 12, OppoStore: 14, VivoStore: 16 };
258
265
 
259
266
  function syncReleaseToCodeplay(storeName, finalVersionName, finalVersionCode, releasedDate) {
267
+ const platformId = RELEASE_PLATFORM_IDS[storeName];
268
+ const platformName = storeName === 'RuStore' ? 'RuStore' : null;
269
+ if (!platformName && (!Number.isInteger(platformId) || platformId <= 0)) {
270
+ console.warn(`⚠️ Codeplay release sync skipped for unknown store ${storeName}.`);
271
+ return;
272
+ }
260
273
  if (!RELEASE_SYNC_TOKEN) {
261
274
  console.warn(`⚠️ Codeplay release sync skipped: add a token to ${releaseSyncConfigPath}.`);
262
275
  return;
@@ -273,7 +286,7 @@ function syncReleaseToCodeplay(storeName, finalVersionName, finalVersionCode, re
273
286
  status: 1,
274
287
  folder_name: path.basename(process.cwd()),
275
288
  app_unique_id: String(_appUniqueId || ''),
276
- platform_id: RELEASE_PLATFORM_IDS[storeName],
289
+ ...(platformName ? { platform_name: platformName } : { platform_id: platformId }),
277
290
  });
278
291
  try {
279
292
  const response = execFileSync('curl.exe', ['-sS', '--fail-with-body', '-X', 'POST', RELEASE_SYNC_URL,
@@ -922,11 +935,11 @@ function setAmazonWindowExtensionsDependency(enabled, { cleanup = false } = {})
922
935
  writeFileSync(gradleFilePath, nextGradleContent, 'utf8');
923
936
  }
924
937
 
925
- console.log(enabled
926
- ? '✅ Added Amazon Fire WebView compatibility dependency for Store ID 7.'
927
- : cleanup
928
- ? 'ℹ️ Removed temporary Amazon Fire WebView compatibility dependency after build cleanup.'
929
- : 'ℹ️ Amazon Fire WebView compatibility dependency is not included for this build.');
938
+ if (enabled) {
939
+ console.log('✅ Added Amazon Fire WebView compatibility dependency for Store ID 7.');
940
+ } else if (cleanup && nextGradleContent !== currentGradleContent) {
941
+ console.log('ℹ️ Removed temporary Amazon Fire WebView compatibility dependency after build cleanup.');
942
+ }
930
943
  }
931
944
 
932
945
  const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
@@ -1168,8 +1181,15 @@ rl.question('Enter new versionCode (press enter to keep current): ', (newVersion
1168
1181
  console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
1169
1182
  }
1170
1183
 
1184
+ const releaseAdConfig = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
1185
+ const provider = ruAdsBuild.getAdProvider(releaseAdConfig, id, 'android');
1186
+ console.log(`Advertising provider for ${storeName}: ${provider}`);
1187
+ ruAdsBuild.prepareReleaseAds(__dirname, id, 'android');
1188
+ if (provider === 'vk') ruAdsBuild.controllerPath(releaseAdConfig, id, 'android', null, __dirname);
1189
+
1171
1190
  // Run the Vite build
1172
- execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
1191
+ execSync(`npm run build:storeid${id}`, { stdio: 'inherit',
1192
+ env: { ...process.env, VITE_STORE_ID: String(id), CODEPLAY_BUILD_PLATFORM: 'android' } });
1173
1193
 
1174
1194
 
1175
1195
 
@@ -1209,7 +1229,9 @@ rl.question('Enter new versionCode (press enter to keep current): ', (newVersion
1209
1229
  execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' }); */
1210
1230
 
1211
1231
 
1212
- execSync('npx cap sync android', { stdio: 'inherit' });
1232
+ ruAdsBuild.withNativeAdProvider(__dirname, id, 'android', () =>
1233
+ execSync('npx cap sync android', { stdio: 'inherit',
1234
+ env: { ...process.env, VITE_STORE_ID: String(id), CODEPLAY_BUILD_PLATFORM: 'android' } }));
1213
1235
 
1214
1236
  if (!baselineProfileChecked) {
1215
1237
  await checkBaselineProfileBeforeRelease();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codeplay-common",
3
- "version": "4.11.22",
3
+ "version": "4.11.23",
4
4
  "description": "Common build scripts and files",
5
5
  "scripts": {
6
6
  "postinstall": "node scripts/sync-files.js",
@@ -0,0 +1,39 @@
1
+ {
2
+ "VERSION": "1.2",
3
+ "android": {
4
+ "HuaweiStore": {
5
+ "appId": 0,
6
+ "bannerSlotId": 0,
7
+ "interstitialSlotId": 0,
8
+ "rewardedSlotId": 0
9
+ },
10
+ "RuStore": {
11
+ "appId": 0,
12
+ "bannerSlotId": 0,
13
+ "interstitialSlotId": 0,
14
+ "rewardedSlotId": 0
15
+ }
16
+ },
17
+ "config": {
18
+ "isTesting": false,
19
+ "bannerEnabled": true,
20
+ "bannerSize": "320x50",
21
+ "bannerDisabledPages": [],
22
+ "bannerStartupDelayMs": 3000,
23
+ "interstitialEnabled": true,
24
+ "interstitialStartupDelayMs": 30000,
25
+ "minimumClick": 2,
26
+ "interstitialFirstTimeOutMs": 252000,
27
+ "interstitialTimeOutMs": 360000,
28
+ "interstitialPerSession": 8,
29
+ "rewardVideoEnabled": true,
30
+ "userAgeRestricted": false,
31
+ "retryDelayMs": 30000,
32
+ "debug": false
33
+ },
34
+ "testid": {
35
+ "bannerSlotId": 794557,
36
+ "interstitialSlotId": 6481,
37
+ "rewardedSlotId": 45101
38
+ }
39
+ }
@@ -0,0 +1,78 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { pathToFileURL } = require('node:url');
6
+ const { syncIapAliases, findLatestIapDirectory, legacyIapPlugin } = require('../files/buildCodeplay/iap-alias.cjs');
7
+
8
+ function fixture(alias = '{}') {
9
+ const base = path.resolve(process.env.CODEPLAY_TEST_ROOT || path.join(__dirname, '../agent-temp'));
10
+ fs.mkdirSync(base, { recursive: true });
11
+ const root = fs.mkdtempSync(path.join(base, 'iap-alias-'));
12
+ const write = (name, value) => { const file = path.join(root, name); fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, value); return file; };
13
+ write('buildCodeplay/iap-alias.cjs', fs.readFileSync(path.join(__dirname, '../files/buildCodeplay/iap-alias.cjs')));
14
+ write('src/js/Ads/IAP-4.8/IAP-state.js', 'export const shouldBlockIapAds = () => false;');
15
+ write('src/js/Ads/IAP-4.8/IAP-bootstrap.js', 'export const initIAP = () => {};');
16
+ write('vite.config.mjs', `export default async () => ({ resolve: { alias: ${alias} }, define: { preserved: true } });`);
17
+ return { root, write };
18
+ }
19
+
20
+ test('migrates imports and re-exports without changing comments, text or F7 templates; repeat is stable', () => {
21
+ const f = fixture();
22
+ const file = f.write('src/pages/home.f7', `<template><div>import '../IAP-4.9/IAP-state.js'</div></template>\n<script>\n// import '../IAP-4.9/IAP-state.js'\nconst text = "../IAP-4.9/IAP-state.js";\nimport { shouldBlockIapAds } from '../js/Ads/IAP-4.9/IAP-state.js';\nconst module = import('@/js/Ads/IAP-4.9/IAP-bootstrap.js');\nexport { initIAP } from '../js/Ads/IAP-4.9/IAP-bootstrap.js';\n</script>`);
23
+ assert.equal(syncIapAliases(f.root, [file]).length, 2);
24
+ const result = fs.readFileSync(file, 'utf8');
25
+ assert.ok(result.includes("from '@iap/IAP-state.js'"));
26
+ assert.ok(result.includes("import('@iap/IAP-bootstrap.js')"));
27
+ assert.ok(result.includes("from '@iap/IAP-bootstrap.js'"));
28
+ assert.ok(result.includes('// import \'../IAP-4.9/IAP-state.js\''));
29
+ assert.ok(result.includes('const text = "../IAP-4.9/IAP-state.js"'));
30
+ assert.ok(result.includes('<div>import \'../IAP-4.9/IAP-state.js\'</div>'));
31
+ assert.deepEqual(syncIapAliases(f.root, [file]), []);
32
+ });
33
+
34
+ test('Vite object and array aliases resolve IAP 4.8 and change automatically when a newer folder appears', async () => {
35
+ const previous = process.cwd();
36
+ try {
37
+ for (const aliases of ["{'@existing':'/unchanged'}", "[{ find: '@existing', replacement: '/unchanged' }]"]) {
38
+ const f = fixture(aliases); syncIapAliases(f.root); process.chdir(f.root);
39
+ const { default: configure } = await import(pathToFileURL(path.join(f.root, 'vite.config.mjs')).href);
40
+ const selected = config => Array.isArray(config.resolve.alias) ? config.resolve.alias.find(a => a.find === '@iap').replacement : config.resolve.alias['@iap'];
41
+ assert.equal(selected(await configure({})), path.join(f.root, 'src/js/Ads/IAP-4.8'));
42
+ f.write('src/js/Ads/IAP-4.10/IAP-state.js', '// newest state');
43
+ f.write('src/js/Ads/IAP-5.0/README.txt', 'incomplete');
44
+ assert.equal(selected(await configure({})), path.join(f.root, 'src/js/Ads/IAP-4.10'));
45
+ assert.equal((await configure({})).define.preserved, true);
46
+ assert.equal(findLatestIapDirectory(f.root), path.join(f.root, 'src/js/Ads/IAP-4.10'));
47
+ }
48
+ } finally { process.chdir(previous); }
49
+ });
50
+
51
+ test('missing IAP modules fail before any source or Vite changes', () => {
52
+ const f = fixture();
53
+ const source = "import { x } from '../IAP-4.9/missing.js';";
54
+ const file = f.write('src/caller.js', source);
55
+ const vite = fs.readFileSync(path.join(f.root, 'vite.config.mjs'), 'utf8');
56
+ assert.throws(() => syncIapAliases(f.root, [file]), /Missing @iap\/missing.js/);
57
+ assert.equal(fs.readFileSync(file, 'utf8'), source);
58
+ assert.equal(fs.readFileSync(path.join(f.root, 'vite.config.mjs'), 'utf8'), vite);
59
+ });
60
+
61
+ test('apps without IAP are left unchanged', () => {
62
+ const f = fixture(); fs.unlinkSync(path.join(f.root, 'src/js/Ads/IAP-4.8/IAP-state.js'));
63
+ assert.equal(findLatestIapDirectory(f.root), null);
64
+ assert.deepEqual(syncIapAliases(f.root), []);
65
+ });
66
+
67
+ test('protected AdMob source stays unchanged and legacy imports resolve to installed IAP', async () => {
68
+ const f = fixture();
69
+ const original = "import { shouldBlockIapAds } from '../IAP-4.9/IAP-state.js';";
70
+ const file = f.write('src/js/Ads/admob-nextgen-4.7/admob-emi-nextgen.js', original);
71
+ syncIapAliases(f.root, [file]);
72
+ assert.equal(fs.readFileSync(file, 'utf8'), original);
73
+ const plugin = legacyIapPlugin(f.root);
74
+ const resolver = { resolve: async target => ({ id: target }) };
75
+ const result = await plugin.resolveId.call(resolver, '../IAP-4.9/IAP-state.js', file);
76
+ assert.equal(result.id, path.join(f.root, 'src/js/Ads/IAP-4.8/IAP-state.js'));
77
+ assert.equal(await plugin.resolveId.call(resolver, '@capacitor/core', file), null);
78
+ });
@@ -0,0 +1,162 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { pathToFileURL } = require('node:url');
6
+ const { syncRuAdsSetup } = require('../files/buildCodeplay/setup-ruads.cjs');
7
+ const { syncAdProviderPackages } = require('../files/buildCodeplay/ruads.cjs');
8
+ const runtimeRoot = path.resolve(__dirname, '../runtime/vk-ads');
9
+
10
+ function fixture(alias = "{'@admob':'/fixture/admob.js'}") {
11
+ const base = path.resolve(process.env.CODEPLAY_TEST_ROOT || path.join(__dirname, '../agent-temp'));
12
+ fs.mkdirSync(base, { recursive: true });
13
+ const root = fs.mkdtempSync(path.join(base, 'ruads-'));
14
+ const write = (file, value) => {
15
+ const target = path.join(root, file); fs.mkdirSync(path.dirname(target), { recursive: true });
16
+ fs.writeFileSync(target, typeof value === 'string' ? value : JSON.stringify(value));
17
+ };
18
+ write('package.json', { name: 'fixture', type: 'module', dependencies: {} });
19
+ write('capacitor.config.json', { appId: 'fixture.app', plugins: { AdMob: { ADMOB_ENABLED: true }, RuAds: { VK_ADS_ENABLED: true, STORE_IDS: [4, 10] } } });
20
+ write('src/js/Ads/IAP-4.7/IAP-state.js', 'export const shouldBlockIapAds = () => false;');
21
+ write('vite.config.mjs', `export default async () => ({resolve:{alias:${alias}}, define:{fixture:'true'}});`);
22
+ write('buildCodeplay/ruads.cjs', fs.readFileSync(path.resolve(__dirname, '../files/buildCodeplay/ruads.cjs'), 'utf8'));
23
+ return { root, write };
24
+ }
25
+
26
+ test('first setup creates only zero-ID config and preserves manually supplied controller and IDs', () => {
27
+ const f = fixture();
28
+ syncRuAdsSetup(f.root, { runtimeRoot });
29
+ const config = path.join(f.root, 'src/js/Ads/vk-ad-configuration.json');
30
+ const defaults = JSON.parse(fs.readFileSync(config));
31
+ assert.deepEqual(Object.values(defaults.android).map(store => store.bannerSlotId), [0, 0]);
32
+ assert.equal(defaults.config.isTesting, false);
33
+ const adapter = path.join(f.root, 'src/js/Ads/vk-ads-1.0/vk-ads.js');
34
+ assert.equal(fs.existsSync(adapter), false);
35
+ const { controllerPath } = require('../files/buildCodeplay/ruads.cjs');
36
+ assert.throws(() => controllerPath(JSON.parse(fs.readFileSync(path.join(f.root, 'capacitor.config.json'))), 10, 'android', '/admob.js', f.root), /Copy the versioned VK folder manually first/);
37
+ f.write('src/js/Ads/vk-ads-1.0/vk-ads.js', '// manually supplied controller');
38
+ f.write('src/js/Ads/vk-ad-configuration.json', { custom: true });
39
+ fs.appendFileSync(adapter, '\n// consumer customization\n');
40
+ const before = fs.readFileSync(path.join(f.root, 'vite.config.mjs'), 'utf8');
41
+ syncRuAdsSetup(f.root, { runtimeRoot });
42
+ assert.deepEqual(JSON.parse(fs.readFileSync(config)), { custom: true });
43
+ assert.ok(fs.readFileSync(adapter, 'utf8').endsWith('// consumer customization\n'));
44
+ assert.equal(fs.readFileSync(path.join(f.root, 'vite.config.mjs'), 'utf8'), before);
45
+ });
46
+
47
+ test('legacy opt-out preserves AdMob and disabled providers need no VK runtime or IAP', async () => {
48
+ const legacy = fixture();
49
+ legacy.write('capacitor.config.json', { plugins: { AdMob: { ADMOB_ENABLED: true } } });
50
+ syncRuAdsSetup(legacy.root, { runtimeRoot });
51
+ assert.equal(fs.existsSync(path.join(legacy.root, 'src/js/Ads/vk-ads-1.0/vk-ads.js')), false);
52
+ const disabled = fixture();
53
+ disabled.write('capacitor.config.json', { plugins: { RuAds: { VK_ADS_ENABLED: false, STORE_IDS: [4, 10] } } });
54
+ syncRuAdsSetup(disabled.root, { runtimeRoot });
55
+ assert.equal(fs.existsSync(path.join(disabled.root, 'src/js/Ads/vk-ads-1.0/vk-ads.js')), false);
56
+ const { controllerPath } = require('../files/buildCodeplay/ruads.cjs');
57
+ assert.equal(controllerPath({ plugins: { AdMob: { ADMOB_ENABLED: false } } }, 1, 'android', '/admob.js'), './buildCodeplay/disabled-ads.mjs');
58
+ assert.equal(controllerPath({ plugins: { RuAds: { VK_ADS_ENABLED: false, STORE_IDS: [10] } } }, 10, 'android', '/admob.js'), './buildCodeplay/disabled-ads.mjs');
59
+ const controller = await import('../files/buildCodeplay/disabled-ads.mjs');
60
+ let continued = 0; let rewarded = 0;
61
+ await controller.levelWinInterstitial(() => continued++);
62
+ await controller.runInterstitialTaskTransition(() => continued++);
63
+ await controller.showRewardVideo(() => rewarded++);
64
+ await controller.showRewardInterstitial(() => rewarded++);
65
+ assert.equal(continued, 2); assert.equal(rewarded, 0);
66
+ assert.equal(controller.canRequestAppAds(), false);
67
+ });
68
+
69
+ test('Vite selects one store/provider for object and array aliases', async () => {
70
+ const previous = { cwd: process.cwd(), store: process.env.VITE_STORE_ID, platform: process.env.CODEPLAY_BUILD_PLATFORM };
71
+ try {
72
+ delete process.env.CODEPLAY_BUILD_PLATFORM;
73
+ for (const alias of ["{'@admob':'/fixture/admob.js'}", "[{find:'@admob',replacement:'/fixture/admob.js'}]"]) {
74
+ const f = fixture(alias);
75
+ f.write('src/js/Ads/vk-ads-1.9/vk-ads.js', '// old controller');
76
+ f.write('src/js/Ads/vk-ads-1.10/vk-ads.js', '// newer controller');
77
+ f.write('src/js/Ads/vk-ads-2.0/README.txt', 'incomplete folder');
78
+ syncRuAdsSetup(f.root, { runtimeRoot }); process.chdir(f.root);
79
+ const { default: configure } = await import(pathToFileURL(path.join(f.root, 'vite.config.mjs')).href);
80
+ for (const id of ['1', '4', '10', '6']) {
81
+ process.env.VITE_STORE_ID = id;
82
+ const config = await configure({ mode: 'development' });
83
+ const selected = Array.isArray(config.resolve.alias) ? config.resolve.alias[0].replacement : config.resolve.alias['@admob'];
84
+ assert.equal(config.define['import.meta.env.VITE_STORE_ID'], JSON.stringify(id));
85
+ assert.equal(config.define['import.meta.env.VITE_RUADS_ENABLED'], JSON.stringify(['4', '10'].includes(id)));
86
+ assert.equal(selected, ['4', '10'].includes(id) ? path.resolve(f.root, 'src/js/Ads/vk-ads-1.10/vk-ads.js') : '/fixture/admob.js');
87
+ assert.equal(config.define.fixture, 'true');
88
+ }
89
+ f.write('capacitor.config.json', { plugins: { AdMob: { ADMOB_ENABLED: false } } });
90
+ process.env.VITE_STORE_ID = '1';
91
+ const disabled = await configure({ mode: 'production' });
92
+ const selected = Array.isArray(disabled.resolve.alias) ? disabled.resolve.alias[0].replacement : disabled.resolve.alias['@admob'];
93
+ assert.equal(selected, path.resolve(f.root, 'buildCodeplay/disabled-ads.mjs'));
94
+ assert.equal(disabled.define['import.meta.env.VITE_RUADS_ENABLED'], 'false');
95
+ }
96
+ } finally {
97
+ process.chdir(previous.cwd);
98
+ for (const [key, value] of [['VITE_STORE_ID', previous.store], ['CODEPLAY_BUILD_PLATFORM', previous.platform]]) {
99
+ if (value === undefined) delete process.env[key]; else process.env[key] = value;
100
+ }
101
+ }
102
+ });
103
+
104
+ test('installer distributes all RuStore helpers and preserves release credentials', () => {
105
+ const f = fixture();
106
+ f.write('buildCodeplay/release-sync.config.json', { token: 'consumer-owned' });
107
+ require('./sync-files.js').install({ projectRoot: f.root, copyAssets: false });
108
+ for (const file of ['ruads.cjs', 'setup-ruads.cjs', 'disabled-ads.mjs', 'store-billing.cjs', 'non-google-billing.pro']) assert.ok(fs.existsSync(path.join(f.root, 'buildCodeplay', file)));
109
+ assert.ok(JSON.parse(fs.readFileSync(path.join(f.root, 'package.json'))).scripts['build:storeid10']);
110
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.root, 'buildCodeplay/release-sync.config.json'))).token, 'consumer-owned');
111
+ });
112
+
113
+ test('existing VK 0.1.0 is upgraded to the fixed native plugin before building', () => {
114
+ const f = fixture();
115
+ f.write('package.json', { dependencies: { 'capacitor-codeplay-rustore-ads': '0.1.0' } });
116
+ f.write('node_modules/capacitor-codeplay-rustore-ads/package.json', { version: '0.1.0' });
117
+ const previous = process.env.VITE_STORE_ID; process.env.VITE_STORE_ID = '10';
118
+ try {
119
+ const commands = [];
120
+ assert.equal(syncAdProviderPackages(f.root, command => commands.push(command)), true);
121
+ assert.deepEqual(commands, ['npm install capacitor-codeplay-rustore-ads@^0.1.1 --save']);
122
+ } finally { if (previous === undefined) delete process.env.VITE_STORE_ID; else process.env.VITE_STORE_ID = previous; }
123
+ });
124
+
125
+ test('shared folder updater installs the advertised VK version and preserves app config', async () => {
126
+ const vm = require('node:vm');
127
+ const source = fs.readFileSync(path.resolve(__dirname, '../files/buildCodeplay/codeplayBeforeBuild.js'), 'utf8');
128
+ const updater = source.slice(source.indexOf('async function autoUpdatePlugin('), source.indexOf('/*############################################## AUTO DOWNLOAD FROM SERVER END'));
129
+ const definition = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../files/buildCodeplay/versions.json'))).plugins.find(item => item.name === 'vk-ads');
130
+ assert.equal(definition.isFolder, true);
131
+ assert.equal(definition.mandatoryUpdate, true);
132
+ assert.ok(new RegExp(definition.pattern).test('vk-ads-1.10'));
133
+ for (const validArchive of [true, false]) {
134
+ const f = fixture();
135
+ f.write('src/js/Ads/vk-ads-1.9/vk-ads.js', '// installed controller');
136
+ f.write('src/js/Ads/vk-ad-configuration.json', { android: { RuStore: { bannerSlotId: 12345 } } });
137
+ const migrated = [];
138
+ const context = vm.createContext({
139
+ fs, path, srcDir: path.join(f.root, 'src'), process: { cwd: () => f.root },
140
+ console: { log() {} }, sourceFileInventory: null,
141
+ fetchVersions: async () => ({ 'vk-ads': '1.10' }),
142
+ urlExists: async url => { assert.equal(url, 'https://htmlcodeplay.com/code-play-plugin/vk-ads-1.10.zip'); return true; },
143
+ downloadAndExtractZip: async (_url, destination) => {
144
+ fs.writeFileSync(path.join(destination, validArchive ? 'vk-ads.js' : 'invalid.txt'), '// server controller');
145
+ },
146
+ updateImports: (from, to) => migrated.push([from, to]), writeUpdateLine() {},
147
+ });
148
+ vm.runInContext(updater, context);
149
+ const update = () => context.autoUpdatePlugin(definition, { name: 'vk-ads-1.9' });
150
+ if (validArchive) {
151
+ assert.equal(await update(), true);
152
+ assert.equal(fs.readFileSync(path.join(f.root, 'src/js/Ads/vk-ads-1.10/vk-ads.js'), 'utf8'), '// server controller');
153
+ assert.deepEqual(migrated, [['vk-ads-1.9', 'vk-ads-1.10']]);
154
+ assert.equal(fs.existsSync(path.join(f.root, 'src/js/Ads/vk-ads-1.9')), false);
155
+ } else {
156
+ await assert.rejects(update, /Invalid VK archive/);
157
+ assert.equal(fs.readFileSync(path.join(f.root, 'src/js/Ads/vk-ads-1.9/vk-ads.js'), 'utf8'), '// installed controller');
158
+ assert.deepEqual(migrated, []);
159
+ }
160
+ assert.equal(JSON.parse(fs.readFileSync(path.join(f.root, 'src/js/Ads/vk-ad-configuration.json'))).android.RuStore.bannerSlotId, 12345);
161
+ }
162
+ });
@@ -98,6 +98,10 @@ function install(options = {}) {
98
98
  }
99
99
  }
100
100
  require('../files/buildCodeplay/splash-setup.cjs').syncSplashSetup(projectRoot);
101
+ require('../files/buildCodeplay/setup-ruads.cjs').syncRuAdsSetup(projectRoot, {
102
+ runtimeRoot: path.resolve(__dirname, '../runtime/vk-ads'),
103
+ });
104
+ require('../files/buildCodeplay/iap-alias.cjs').syncIapAliases(projectRoot);
101
105
  migrateAppConfigurator(projectRoot);
102
106
  require('../files/buildCodeplay/migrate-system-bars.cjs').migrateSystemBars(projectRoot);
103
107
  syncAndroidR8Rules(projectRoot, { installGradleHook: true });
@@ -0,0 +1,92 @@
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const vm = require('node:vm');
6
+ const { pathToFileURL } = require('node:url');
7
+ const { install } = require('./sync-files.js');
8
+
9
+ function fixture(configuration) {
10
+ const base = path.resolve(process.env.CODEPLAY_TEST_ROOT || path.join(__dirname, '../agent-temp'));
11
+ fs.mkdirSync(base, { recursive: true });
12
+ const root = fs.mkdtempSync(path.join(base, 'vite-settings-'));
13
+ fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({ name: 'vite-fixture', scripts: {}, dependencies: {} }));
14
+ fs.writeFileSync(path.join(root, 'capacitor.config.json'), JSON.stringify({ appId: 'fixture.app', plugins: {
15
+ AdMob: { ADMOB_ENABLED: true }, RuAds: { VK_ADS_ENABLED: true, STORE_IDS: [4, 10] },
16
+ } }));
17
+ fs.mkdirSync(path.join(root, 'src/js/Ads/vk-ads-1.3'), { recursive: true });
18
+ fs.writeFileSync(path.join(root, 'src/js/Ads/vk-ads-1.3/vk-ads.js'), '// manually installed VK controller');
19
+ fs.writeFileSync(path.join(root, 'vite.config.mjs'), configuration);
20
+ install({ projectRoot: root, copyAssets: false });
21
+ // Run the real before-build migration after the real installer. Loading the
22
+ // full before-build CLI would also install SDKs and change native platforms.
23
+ const source = fs.readFileSync(path.join(root, 'buildCodeplay/codeplayBeforeBuild.js'), 'utf8');
24
+ const migration = source.slice(source.indexOf('const migrateViteTreeShaking ='), source.indexOf('// BEGIN IAP BUILD MIGRATION'));
25
+ const migrate = vm.runInNewContext(migration + '\nmigrateViteTreeShaking;');
26
+ return { root, file: path.join(root, 'vite.config.mjs'), migrate };
27
+ }
28
+
29
+ const alias = "resolve: { alias: { '@admob': '/original-admob.js' } }";
30
+ const build = { outDir: '../www', minify: 'terser', sourcemap: true, emptyOutDir: false,
31
+ target: 'es2022', rollupOptions: { external: ['preserved-module'], output: { entryFileNames: 'custom-[name].js' } } };
32
+
33
+ test('installer and before-build preserve build settings for object/function/defineConfig exports and all ad providers', async () => {
34
+ const previous = { cwd: process.cwd(), store: process.env.VITE_STORE_ID, platform: process.env.CODEPLAY_BUILD_PLATFORM };
35
+ try {
36
+ delete process.env.CODEPLAY_BUILD_PLATFORM;
37
+ const config = `{ build: ${JSON.stringify(build)}, ${alias}, define: { custom: 'true' } }`;
38
+ for (const source of [`export default ${config};`, `export default async () => (${config});`, `const defineConfig = c => c;\nexport default defineConfig(${config});`]) {
39
+ const f = fixture(source);
40
+ const updated = f.migrate(fs.readFileSync(f.file, 'utf8'));
41
+ assert.equal(f.migrate(updated), updated);
42
+ fs.writeFileSync(f.file, updated);
43
+ process.chdir(f.root);
44
+ const { default: configure } = await import(pathToFileURL(f.file).href);
45
+ for (const store of ['1', '4', '10']) {
46
+ process.env.VITE_STORE_ID = store;
47
+ const resolved = await configure({ mode: 'production' });
48
+ assert.deepEqual(resolved.build, { ...build, rollupOptions: { ...build.rollupOptions, treeshake: true } });
49
+ assert.equal(resolved.define.custom, 'true');
50
+ assert.equal(resolved.define['import.meta.env.VITE_STORE_ID'], JSON.stringify(store));
51
+ assert.equal(resolved.resolve.alias['@admob'], store === '1' ? '/original-admob.js' : path.join(f.root, 'src/js/Ads/vk-ads-1.3/vk-ads.js'));
52
+ }
53
+ }
54
+ } finally {
55
+ process.chdir(previous.cwd);
56
+ for (const [key, value] of [['VITE_STORE_ID', previous.store], ['CODEPLAY_BUILD_PLATFORM', previous.platform]]) {
57
+ if (value === undefined) delete process.env[key]; else process.env[key] = value;
58
+ }
59
+ }
60
+ });
61
+
62
+ test('migration preserves custom treeshake options and repairs only the previous generated override', async () => {
63
+ const custom = { ...build, rollupOptions: { ...build.rollupOptions, treeshake: { moduleSideEffects: false } } };
64
+ const f = fixture(`export default { build: ${JSON.stringify(custom)}, ${alias} };`);
65
+ let source = fs.readFileSync(f.file, 'utf8');
66
+ source = source.replace('return { ...base,', 'return { ...base, build: { rollupOptions: { treeshake: true } },');
67
+ const updated = f.migrate(source);
68
+ assert.ok(!updated.includes('...base, build:'));
69
+ assert.equal(f.migrate(updated), updated);
70
+ fs.writeFileSync(f.file, updated);
71
+ const previous = process.cwd();
72
+ try {
73
+ process.chdir(f.root);
74
+ const { default: configure } = await import(pathToFileURL(f.file).href);
75
+ assert.deepEqual((await configure({})).build, custom);
76
+ } finally { process.chdir(previous); }
77
+ const customized = source.replace('build: { rollupOptions: { treeshake: true } },', "build: { outDir: '/custom-wrapper', rollupOptions: { treeshake: true } },");
78
+ assert.ok(f.migrate(customized).includes("outDir: '/custom-wrapper'"));
79
+ });
80
+
81
+ test('missing build/rollup settings are added to the original config; unwrapped configs still migrate', () => {
82
+ const f = fixture(`export default { ${alias} };`);
83
+ const updated = f.migrate(fs.readFileSync(f.file, 'utf8'));
84
+ assert.match(updated, /codeplayOriginalViteConfig\s*=\s*\{[\s\S]*build:/);
85
+ assert.ok(!updated.includes('...base, build:'));
86
+ assert.equal(f.migrate(updated), updated);
87
+ const plain = `export default { build: { outDir: '../www', rollupOptions: { treeshake: false, external: ['keep'] } } };`;
88
+ const result = f.migrate(plain);
89
+ assert.ok(result.includes("outDir: '../www'"));
90
+ assert.ok(result.includes("external: ['keep']"));
91
+ assert.ok(result.includes('treeshake: true'));
92
+ });