codeplay-common 4.11.41-alpha.4 → 4.11.41-alpha.5

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
@@ -38,6 +38,34 @@ launch themes and drawables are preserved and reported for app-specific review.
38
38
  Rebuild the APK to receive native splash changes; installation alone cannot
39
39
  change an already installed app.
40
40
 
41
+ ### App-owned native splash branding
42
+
43
+ The AI setup command is distributed by the separate AGENTS server archive at
44
+ `AGENTS/AI-Native-Splash-and-Display-Icon.txt`; this npm package never copies AGENTS.
45
+ For a Capacitor 9 app, the command creates an app-owned
46
+ `splashscreens/profile.json` and native Canvas sources under `splashscreens/native/` after
47
+ reviewing that app's icon, colors, startup flow, and protected-file rules.
48
+ `buildCodeplay/` contains package-managed scripts only, because installing this
49
+ package can replace its contents.
50
+ Without a profile, installation reports that AI setup is needed and leaves
51
+ the app's existing custom splash alone.
52
+
53
+ With a profile, installation and `capacitor:sync:after` run
54
+ `buildCodeplay/native-splash-sync.cjs`. The script reads the configured source
55
+ in `resources/`, creates a 512px native splash WebP and six correctly sized
56
+ adaptive launcher foreground WebPs, and restores app-owned Java sources after
57
+ Android platform recreation. It rewrites files only when their bytes differ.
58
+ The app-specific native readiness integration remains app-owned. The profile's
59
+ `approvedIconSha256` records the icon approved with the AI design. If the icon
60
+ changes, derived assets refresh automatically and the script requests AI
61
+ review of the splash colors and composition.
62
+
63
+ Run `node buildCodeplay/native-splash-sync.cjs --validate` to check resources,
64
+ 15 loader branches, and absence of preview controls. Add
65
+ `--apk path/to/app.apk` to verify that packaged icon bytes match the current
66
+ resources. Device validation is still required for visual clarity and startup
67
+ behavior. `sharp` is used only during build setup and is not packaged in APKs.
68
+
41
69
  Version 4.11.37 adds the `/buildCodeplay` Vite alias during installation and
42
70
  before-build setup, including upgrades of existing generated wrappers. This
43
71
  lets Huawei privacy startup modules load during Live Reload when the app's
@@ -0,0 +1,195 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const crypto = require('crypto');
4
+
5
+ const densities = { ldpi: 81, mdpi: 108, hdpi: 162, xhdpi: 216, xxhdpi: 324, xxxhdpi: 432 };
6
+ const fromCommon = (root, name) => require(require.resolve(name, {
7
+ paths: [root, path.join(root, 'node_modules', 'codeplay-common'), path.resolve(__dirname, '../..')],
8
+ }));
9
+
10
+ function inside(root, relative) {
11
+ if (typeof relative !== 'string' || path.isAbsolute(relative)) throw new Error('Native splash path must be relative.');
12
+ const target = path.resolve(root, relative);
13
+ if (!target.startsWith(path.resolve(root) + path.sep)) throw new Error('Native splash path escapes the app.');
14
+ return target;
15
+ }
16
+
17
+ function writeChanged(target, bytes) {
18
+ fs.mkdirSync(path.dirname(target), { recursive: true });
19
+ if (fs.existsSync(target) && fs.readFileSync(target).equals(bytes)) return false;
20
+ fs.writeFileSync(target, bytes);
21
+ return true;
22
+ }
23
+
24
+ async function syncNativeSplash(projectRoot, { log = console.log, sharp: imageTool } = {}) {
25
+ const root = path.resolve(projectRoot);
26
+ const packageFile = path.join(root, 'package.json');
27
+ if (!fs.existsSync(packageFile)) return { status: 'no-package' };
28
+ const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf8'));
29
+ const capacitor = pkg.dependencies?.['@capacitor/core'] || pkg.devDependencies?.['@capacitor/core'] || '';
30
+ if (Number(capacitor.match(/\d+/)?.[0]) !== 9) return { status: 'not-capacitor-9' };
31
+ const profileFile = path.join(root, 'splashscreens', 'profile.json');
32
+ if (!fs.existsSync(profileFile)) {
33
+ log('codeplay-common: native splash and display icon branding not configured; run AGENTS/AI-Native-Splash-and-Display-Icon.txt for this app.');
34
+ return { status: 'needs-ai-setup' };
35
+ }
36
+ const profile = JSON.parse(fs.readFileSync(profileFile, 'utf8'));
37
+ if (profile.schemaVersion !== 1 || profile.loaderCount !== 15 ||
38
+ !Array.isArray(profile.loaderIds) || profile.loaderIds.length !== 15 ||
39
+ !profile.loaderIds.every(id => typeof id === 'string' && id.length > 0) ||
40
+ new Set(profile.loaderIds).size !== 15 ||
41
+ typeof profile.title !== 'string' || !profile.title.trim() ||
42
+ !profile.colors || !/^[a-f0-9]{64}$/i.test(profile.approvedIconSha256 || '') ||
43
+ !profile.javaPackage || !profile.nativeSourceDir) {
44
+ throw new Error('Native splash profile needs branded title/colors, approved icon hash, Java sources, and 15 unique loaders.');
45
+ }
46
+ const source = inside(root, profile.iconSource);
47
+ if (!source.startsWith(path.join(root, 'resources') + path.sep)) throw new Error('Native splash icon must come from resources/.');
48
+ if (!fs.existsSync(source) || fs.lstatSync(source).isSymbolicLink()) throw new Error(`Native splash icon source is missing or linked: ${profile.iconSource}`);
49
+ const sourceBytes = fs.readFileSync(source);
50
+ const sourceHash = crypto.createHash('sha256').update(sourceBytes).digest('hex');
51
+ const image = imageTool || fromCommon(root, 'sharp');
52
+ const metadata = await image(sourceBytes).metadata();
53
+ if (metadata.width < 512 || metadata.height < 512) throw new Error('Native splash icon source must be at least 512 x 512 pixels.');
54
+
55
+ const res = path.join(root, 'android', 'app', 'src', 'main', 'res');
56
+ if (!fs.existsSync(res)) {
57
+ log('codeplay-common: Android platform absent; native splash sources retained for the next sync.');
58
+ return { status: 'no-android', sourceHash };
59
+ }
60
+ let changed = 0;
61
+ const icon = await image(sourceBytes).resize(512, 512, { fit: 'contain', background: '#00000000' })
62
+ .webp({ quality: 95, effort: 6 }).toBuffer();
63
+ if (writeChanged(path.join(res, 'drawable-nodpi', 'launch_brand_icon.webp'), icon)) changed++;
64
+ for (const [density, size] of Object.entries(densities)) {
65
+ const output = await image(sourceBytes).resize(size, size, { fit: 'contain', background: '#00000000' })
66
+ .webp({ quality: 95, effort: 6 }).toBuffer();
67
+ const targetDir = path.join(res, `mipmap-${density}`);
68
+ if (writeChanged(path.join(targetDir, 'ic_launcher_foreground.webp'), output)) changed++;
69
+ const oldPng = path.join(targetDir, 'ic_launcher_foreground.png');
70
+ if (fs.existsSync(oldPng)) { fs.unlinkSync(oldPng); changed++; }
71
+ }
72
+ {
73
+ if (!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)+$/.test(profile.javaPackage)) throw new Error('Invalid native splash Java package.');
74
+ const javaSource = inside(root, profile.nativeSourceDir);
75
+ if (!javaSource.startsWith(path.join(root, 'splashscreens') + path.sep)) throw new Error('App-owned native splash Java must be under splashscreens/.');
76
+ const javaTarget = path.join(root, 'android', 'app', 'src', 'main', 'java', ...profile.javaPackage.split('.'));
77
+ for (const filename of ['MainActivity.java', 'CodeplayLaunchView.java', 'LaunchOverlayPlugin.java']) {
78
+ const input = path.join(javaSource, filename);
79
+ if (!fs.existsSync(input)) throw new Error(`Native splash Java source missing: ${input}`);
80
+ const body = fs.readFileSync(input);
81
+ if (!body.toString('utf8').includes(`package ${profile.javaPackage};`)) throw new Error(`Native splash Java package mismatch: ${input}`);
82
+ if (writeChanged(path.join(javaTarget, filename), body)) changed++;
83
+ }
84
+ }
85
+ const needsAiReview = Boolean(profile.approvedIconSha256 && profile.approvedIconSha256 !== sourceHash);
86
+ if (needsAiReview) log('codeplay-common: icon changed; native icon assets regenerated. Re-run AGENTS/AI-Native-Splash-and-Display-Icon.txt to review splash colors and composition.');
87
+ log(`codeplay-common: native splash ${changed ? 'updated' : 'verified'} (${changed} resource/source changes).`);
88
+ return { status: changed ? 'updated' : 'verified', changed, sourceHash, needsAiReview };
89
+ }
90
+
91
+ async function validateNativeSplash(projectRoot, { apk, sharp: imageTool } = {}) {
92
+ const root = path.resolve(projectRoot);
93
+ const issues = [];
94
+ const profileFile = path.join(root, 'splashscreens', 'profile.json');
95
+ if (!fs.existsSync(profileFile)) return { ok: false, issues: ['Native splash AI profile is missing.'] };
96
+ const profile = JSON.parse(fs.readFileSync(profileFile, 'utf8'));
97
+ if (profile.loaderCount !== 15 || !Array.isArray(profile.loaderIds) ||
98
+ profile.loaderIds.length !== 15 || new Set(profile.loaderIds).size !== 15) {
99
+ issues.push('Profile must contain 15 unique loaders.');
100
+ }
101
+ const source = inside(root, profile.iconSource);
102
+ if (!fs.existsSync(source)) return { ok: false, issues: ['Current icon source is missing.'] };
103
+ const sourceBytes = fs.readFileSync(source);
104
+ const sourceHash = crypto.createHash('sha256').update(sourceBytes).digest('hex');
105
+ if (profile.approvedIconSha256 && profile.approvedIconSha256 !== sourceHash) {
106
+ issues.push('Icon source changed since AI branding approval. Re-run AGENTS/AI-Native-Splash-and-Display-Icon.txt.');
107
+ }
108
+ const image = imageTool || fromCommon(root, 'sharp');
109
+ const res = path.join(root, 'android', 'app', 'src', 'main', 'res');
110
+ if (!fs.existsSync(res)) issues.push('Android platform is absent.');
111
+ else {
112
+ for (const [density, size] of Object.entries(densities)) {
113
+ const file = path.join(res, `mipmap-${density}`, 'ic_launcher_foreground.webp');
114
+ if (!fs.existsSync(file)) { issues.push(`Missing ${density} adaptive icon.`); continue; }
115
+ const meta = await image(fs.readFileSync(file)).metadata();
116
+ if (meta.width !== size || meta.height !== size) issues.push(`Incorrect ${density} adaptive icon dimensions.`);
117
+ const expected = await image(sourceBytes).resize(size, size, { fit: 'contain', background: '#00000000' })
118
+ .webp({ quality: 95, effort: 6 }).toBuffer();
119
+ if (!fs.readFileSync(file).equals(expected)) issues.push(`Stale ${density} adaptive icon.`);
120
+ }
121
+ const splashIcon = path.join(res, 'drawable-nodpi', 'launch_brand_icon.webp');
122
+ if (!fs.existsSync(splashIcon)) issues.push('Native splash icon is missing.');
123
+ else {
124
+ const meta = await image(fs.readFileSync(splashIcon)).metadata();
125
+ if (meta.width !== 512 || meta.height !== 512) issues.push('Native splash icon must be 512 x 512.');
126
+ const expected = await image(sourceBytes).resize(512, 512, { fit: 'contain', background: '#00000000' })
127
+ .webp({ quality: 95, effort: 6 }).toBuffer();
128
+ if (!fs.readFileSync(splashIcon).equals(expected)) issues.push('Stale native splash icon.');
129
+ }
130
+ }
131
+ if (profile.nativeSourceDir) {
132
+ const java = inside(root, profile.nativeSourceDir);
133
+ if (!java.startsWith(path.join(root, 'splashscreens') + path.sep)) issues.push('Native splash Java source must be under splashscreens/.');
134
+ const loader = path.join(java, 'CodeplayLaunchView.java');
135
+ const activity = path.join(java, 'MainActivity.java');
136
+ const plugin = path.join(java, 'LaunchOverlayPlugin.java');
137
+ if (![loader, activity, plugin].every(fs.existsSync)) issues.push('App-owned native splash Java sources are incomplete.');
138
+ else {
139
+ const body = fs.readFileSync(loader, 'utf8');
140
+ const cases = [...body.matchAll(/\bcase\s+(\d+)\s*:/g)].map(match => Number(match[1]));
141
+ if (!/LOADER_COUNT\s*=\s*15\b/.test(body) ||
142
+ !Array.from({ length: 14 }, (_, i) => i).every(i => cases.includes(i)) ||
143
+ !/\bdefault\s*:/.test(body)) issues.push('Native view does not contain 15 loader branches.');
144
+ if (/previewMode|\bPREV\b|\bNEXT\b|\bCLOSE\b/.test(body)) issues.push('Preview controls are present in native source.');
145
+ if (!fs.readFileSync(activity, 'utf8').includes('hideLaunchOverlay')) issues.push('Native overlay hide method is missing.');
146
+ if (!fs.readFileSync(plugin, 'utf8').includes('@CapacitorPlugin')) issues.push('Launch overlay plugin is missing.');
147
+ if (profile.javaPackage) {
148
+ const target = path.join(root, 'android', 'app', 'src', 'main', 'java', ...profile.javaPackage.split('.'));
149
+ for (const name of ['MainActivity.java', 'CodeplayLaunchView.java', 'LaunchOverlayPlugin.java']) {
150
+ const output = path.join(target, name);
151
+ if (!fs.existsSync(output) || !fs.readFileSync(output).equals(fs.readFileSync(path.join(java, name))))
152
+ issues.push(`Android native splash source is missing or stale: ${name}.`);
153
+ }
154
+ }
155
+ }
156
+ }
157
+ if (apk) {
158
+ const zip = new (fromCommon(root, 'adm-zip'))(path.resolve(apk));
159
+ for (const density of Object.keys(densities)) {
160
+ const entry = zip.getEntry(`res/mipmap-${density}-v4/ic_launcher_foreground.webp`);
161
+ if (!entry) issues.push(`APK missing ${density} adaptive icon.`);
162
+ else if (fs.existsSync(path.join(res, `mipmap-${density}`, 'ic_launcher_foreground.webp')) &&
163
+ !entry.getData().equals(fs.readFileSync(path.join(res, `mipmap-${density}`, 'ic_launcher_foreground.webp'))))
164
+ issues.push(`APK has stale ${density} adaptive icon.`);
165
+ }
166
+ const entry = zip.getEntry('res/drawable-nodpi-v4/launch_brand_icon.webp');
167
+ if (!entry) issues.push('APK missing native splash icon.');
168
+ else if (fs.existsSync(path.join(res, 'drawable-nodpi', 'launch_brand_icon.webp')) &&
169
+ !entry.getData().equals(fs.readFileSync(path.join(res, 'drawable-nodpi', 'launch_brand_icon.webp'))))
170
+ issues.push('APK has stale native splash icon.');
171
+ }
172
+ return { ok: issues.length === 0, sourceHash, issues };
173
+ }
174
+
175
+ if (require.main === module) {
176
+ const root = path.resolve(__dirname, '..');
177
+ const apkIndex = process.argv.indexOf('--apk');
178
+ const validate = process.argv.includes('--validate') || process.argv.includes('--validate-if-configured');
179
+ const conditional = process.argv.includes('--validate-if-configured');
180
+ const configured = fs.existsSync(path.join(root, 'splashscreens', 'profile.json'));
181
+ const task = validate && (!conditional || configured)
182
+ ? validateNativeSplash(root, { apk: apkIndex >= 0 ? process.argv[apkIndex + 1] : undefined })
183
+ : conditional ? Promise.resolve({ ok: true }) : syncNativeSplash(root);
184
+ task.then(result => {
185
+ if (validate) {
186
+ console.log(result.ok ? 'Native splash validation passed.' : result.issues.join('\n'));
187
+ if (!result.ok) process.exitCode = 1;
188
+ }
189
+ }).catch(error => {
190
+ console.error(error.message);
191
+ process.exitCode = 1;
192
+ });
193
+ }
194
+
195
+ module.exports = { syncNativeSplash, validateNativeSplash, densities };
@@ -10,7 +10,9 @@ const tasks = {
10
10
  'final-release': 'node finalrelease',
11
11
  };
12
12
  const launchSplash = 'node buildCodeplay/sync-capacitor9-launch-splash.cjs';
13
- const syncAfter = `${tasks.splash} && ${launchSplash} && ${tasks.manifest} && node scripts-common/setup-baseline-profile.js`;
13
+ const nativeSplash = 'node buildCodeplay/native-splash-sync.cjs';
14
+ const nativeValidate = 'node buildCodeplay/native-splash-sync.cjs --validate-if-configured';
15
+ const syncAfter = `${tasks.splash} && ${nativeSplash} && ${launchSplash} && ${tasks.manifest} && node scripts-common/setup-baseline-profile.js && ${nativeValidate}`;
14
16
  function updateBuildScripts(scripts) {
15
17
  const next = { ...scripts };
16
18
  for (const key of Object.keys(next)) {
@@ -37,6 +39,14 @@ function updateBuildScripts(scripts) {
37
39
  !next['capacitor:sync:after'].includes('run-codeplay-sync-after.js')) {
38
40
  next['capacitor:sync:after'] += ` && ${launchSplash}`;
39
41
  }
42
+ if (!next['capacitor:sync:after'].split(' && ').includes(nativeSplash) &&
43
+ !next['capacitor:sync:after'].includes('run-codeplay-sync-after.js')) {
44
+ next['capacitor:sync:after'] = next['capacitor:sync:after'].replace(launchSplash, `${nativeSplash} && ${launchSplash}`);
45
+ }
46
+ if (!next['capacitor:sync:after'].split(' && ').includes(nativeValidate) &&
47
+ !next['capacitor:sync:after'].includes('run-codeplay-sync-after.js')) {
48
+ next['capacitor:sync:after'] += ` && ${nativeValidate}`;
49
+ }
40
50
  const safDependency = 'node buildCodeplay/saf-mediastore-dependency.cjs';
41
51
  const cap9Prepare = 'node node_modules/codeplay-common/scripts/prepare-capacitor-9.cjs --apply-if-cap9';
42
52
  for (const hook of ['capacitor:sync:before', 'capacitor:update:before']) {
@@ -18,10 +18,14 @@ function syncCapacitor9LaunchSplash(projectRoot) {
18
18
 
19
19
  const iconSource = path.join(projectRoot, 'resources', 'splash_icon.png');
20
20
  const iconTarget = path.join(res, 'drawable-nodpi', 'splash_icon.png');
21
- const icon = fs.existsSync(iconSource) || fs.existsSync(iconTarget)
21
+ const brandedIcon = fs.existsSync(path.join(projectRoot, 'splashscreens', 'profile.json')) &&
22
+ fs.existsSync(path.join(res, 'drawable-nodpi', 'launch_brand_icon.webp'));
23
+ const oldIcon = fs.existsSync(iconSource) || fs.existsSync(iconTarget)
22
24
  ? '@drawable/splash_icon' : '@mipmap/ic_launcher';
25
+ const icon = brandedIcon ? '@drawable/launch_brand_icon' : oldIcon;
23
26
  const background = path.join(res, 'drawable', 'launch_background.xml');
24
- const expected = `<?xml version="1.0" encoding="utf-8"?>\n<layer-list xmlns:android="http://schemas.android.com/apk/res/android">\n <item android:drawable="@android:color/white" />\n <item\n android:drawable="${icon}"\n android:gravity="center"\n android:width="220dp"\n android:height="220dp" />\n</layer-list>\n`;
27
+ const backgroundXml = (asset, size) => `<?xml version="1.0" encoding="utf-8"?>\n<layer-list xmlns:android="http://schemas.android.com/apk/res/android">\n <item android:drawable="@android:color/white" />\n <item\n android:drawable="${asset}"\n android:gravity="center"\n android:width="${size}dp"\n android:height="${size}dp" />\n</layer-list>\n`;
28
+ const expected = backgroundXml(icon, brandedIcon ? 120 : 220);
25
29
  const body = match[1];
26
30
  const original = /^\s*<item name="android:background">@drawable\/splash<\/item>\s*$/.test(body);
27
31
  const managedItems = [
@@ -31,10 +35,11 @@ function syncCapacitor9LaunchSplash(projectRoot) {
31
35
  `<item name="windowSplashScreenAnimatedIcon">${icon}</item>`,
32
36
  '<item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>',
33
37
  ];
34
- const managed = managedItems.every(item => body.includes(item)) &&
38
+ const managed = (managedItems.every(item => body.includes(item)) ||
39
+ managedItems.map(item => item.replace(icon, oldIcon)).every(item => body.includes(item))) &&
35
40
  !body.replace(/<item\b[^>]*>[^<]*<\/item>/g, '').trim();
36
41
  if (!original && !managed) return 'custom-theme';
37
- if (fs.existsSync(background) && fs.readFileSync(background, 'utf8') !== expected) return 'custom-background';
42
+ if (fs.existsSync(background) && ![expected, backgroundXml(oldIcon, 220)].includes(fs.readFileSync(background, 'utf8'))) return 'custom-background';
38
43
 
39
44
  const replacement = `<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen">\n` +
40
45
  ` <item name="android:background">@drawable/launch_background</item>\n` +
@@ -44,9 +49,9 @@ function syncCapacitor9LaunchSplash(projectRoot) {
44
49
  ` <item name="postSplashScreenTheme">@style/AppTheme.NoActionBar</item>\n` +
45
50
  ` </style>`;
46
51
  const updated = source.replace(style, replacement);
47
- if (updated === source && fs.existsSync(background)) return 'unchanged';
52
+ if (updated === source && fs.existsSync(background) && fs.readFileSync(background, 'utf8') === expected) return 'unchanged';
48
53
  fs.mkdirSync(path.dirname(background), { recursive: true });
49
- if (!fs.existsSync(background)) fs.writeFileSync(background, expected);
54
+ if (!fs.existsSync(background) || fs.readFileSync(background, 'utf8') !== expected) fs.writeFileSync(background, expected);
50
55
  if (updated !== source) fs.writeFileSync(stylesFile, updated);
51
56
  return 'updated';
52
57
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codeplay-common",
3
- "version": "4.11.41-alpha.4",
3
+ "version": "4.11.41-alpha.5",
4
4
  "description": "Common build scripts and files",
5
5
  "scripts": {
6
6
  "postinstall": "node scripts/sync-files.js",
@@ -11,6 +11,7 @@
11
11
  "adm-zip": "^0.6.1",
12
12
  "patch-package": "^8.0.1",
13
13
  "plist": "^3.1.0",
14
+ "sharp": "^0.35.5",
14
15
  "terser": "^5.51.4"
15
16
  },
16
17
  "repository": {
@@ -1,47 +1,58 @@
1
- const { test } = require('node:test');
2
- const assert = require('node:assert/strict');
3
- const fs = require('node:fs');
4
- const os = require('node:os');
5
- const path = require('node:path');
6
- const { syncCapacitor9LaunchSplash } = require('../files/buildCodeplay/sync-capacitor9-launch-splash.cjs');
7
- const { install } = require('./sync-files.js');
8
-
9
- function fixture(t, style, withIcon = true) {
10
- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codeplay-splash9-'));
11
- t.after(() => fs.rmSync(root, { recursive: true, force: true }));
12
- const write = (name, value) => {
13
- const file = path.join(root, name);
14
- fs.mkdirSync(path.dirname(file), { recursive: true });
15
- fs.writeFileSync(file, value);
16
- return file;
17
- };
18
- write('package.json', JSON.stringify({ name: 'splash-fixture', dependencies: { '@capacitor/core': '9.0.0' } }));
19
- write('capacitor.config.json', JSON.stringify({ appId: 'splash.fixture' }));
20
- write('android/app/src/main/res/values/styles.xml', `<resources>\n<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar"/>\n${style}\n</resources>\n`);
21
- if (withIcon) write('resources/splash_icon.png', 'existing app icon');
22
- return { root, write, read: name => fs.readFileSync(path.join(root, name), 'utf8') };
23
- }
24
-
25
- const defaultStyle = '<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen"><item name="android:background">@drawable/splash</item></style>';
26
-
27
- test('Capacitor 9 installation reuses the app icon and is idempotent', t => {
28
- const f = fixture(t, defaultStyle);
29
- install({ projectRoot: f.root, copyAssets: false });
30
- assert.match(f.read('android/app/src/main/res/values/styles.xml'), /windowSplashScreenAnimatedIcon">@drawable\/splash_icon/);
31
- assert.match(f.read('android/app/src/main/res/drawable/launch_background.xml'), /android:width="220dp"/);
32
- assert.ok(fs.existsSync(path.join(f.root, 'buildCodeplay/sync-capacitor9-launch-splash.cjs')));
33
- assert.match(JSON.parse(f.read('package.json')).scripts['capacitor:sync:after'], /sync-capacitor9-launch-splash\.cjs/);
34
- assert.equal(syncCapacitor9LaunchSplash(f.root), 'unchanged');
35
- });
36
-
37
- test('uses the existing launcher icon when no splash icon exists', t => {
38
- const f = fixture(t, defaultStyle, false);
39
- assert.equal(syncCapacitor9LaunchSplash(f.root), 'updated');
40
- assert.match(f.read('android/app/src/main/res/drawable/launch_background.xml'), /@mipmap\/ic_launcher/);
41
- });
42
-
43
- test('preserves custom launch themes and drawables', t => {
44
- const f = fixture(t, '<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen"><item name="windowSplashScreenAnimatedIcon">@drawable/brand</item></style>');
45
- assert.equal(syncCapacitor9LaunchSplash(f.root), 'custom-theme');
46
- assert.equal(fs.existsSync(path.join(f.root, 'android/app/src/main/res/drawable/launch_background.xml')), false);
47
- });
1
+ const { test } = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const { syncCapacitor9LaunchSplash } = require('../files/buildCodeplay/sync-capacitor9-launch-splash.cjs');
7
+ const { install } = require('./sync-files.js');
8
+
9
+ function fixture(t, style, withIcon = true) {
10
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'codeplay-splash9-'));
11
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
12
+ const write = (name, value) => {
13
+ const file = path.join(root, name);
14
+ fs.mkdirSync(path.dirname(file), { recursive: true });
15
+ fs.writeFileSync(file, value);
16
+ return file;
17
+ };
18
+ write('package.json', JSON.stringify({ name: 'splash-fixture', dependencies: { '@capacitor/core': '9.0.0' } }));
19
+ write('capacitor.config.json', JSON.stringify({ appId: 'splash.fixture' }));
20
+ write('android/app/src/main/res/values/styles.xml', `<resources>\n<style name="AppTheme.NoActionBar" parent="Theme.AppCompat.DayNight.NoActionBar"/>\n${style}\n</resources>\n`);
21
+ if (withIcon) write('resources/splash_icon.png', 'existing app icon');
22
+ return { root, write, read: name => fs.readFileSync(path.join(root, name), 'utf8') };
23
+ }
24
+
25
+ const defaultStyle = '<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen"><item name="android:background">@drawable/splash</item></style>';
26
+
27
+ test('Capacitor 9 installation reuses the app icon and is idempotent', t => {
28
+ const f = fixture(t, defaultStyle);
29
+ install({ projectRoot: f.root, copyAssets: false });
30
+ assert.match(f.read('android/app/src/main/res/values/styles.xml'), /windowSplashScreenAnimatedIcon">@drawable\/splash_icon/);
31
+ assert.match(f.read('android/app/src/main/res/drawable/launch_background.xml'), /android:width="220dp"/);
32
+ assert.ok(fs.existsSync(path.join(f.root, 'buildCodeplay/sync-capacitor9-launch-splash.cjs')));
33
+ assert.match(JSON.parse(f.read('package.json')).scripts['capacitor:sync:after'], /sync-capacitor9-launch-splash\.cjs/);
34
+ assert.equal(syncCapacitor9LaunchSplash(f.root), 'unchanged');
35
+ });
36
+
37
+ test('uses the existing launcher icon when no splash icon exists', t => {
38
+ const f = fixture(t, defaultStyle, false);
39
+ assert.equal(syncCapacitor9LaunchSplash(f.root), 'updated');
40
+ assert.match(f.read('android/app/src/main/res/drawable/launch_background.xml'), /@mipmap\/ic_launcher/);
41
+ });
42
+
43
+ test('upgrades a managed launch window when app branding is configured', t => {
44
+ const f = fixture(t, defaultStyle);
45
+ assert.equal(syncCapacitor9LaunchSplash(f.root), 'updated');
46
+ f.write('splashscreens/profile.json', '{}');
47
+ f.write('android/app/src/main/res/drawable-nodpi/launch_brand_icon.webp', 'generated icon');
48
+ assert.equal(syncCapacitor9LaunchSplash(f.root), 'updated');
49
+ assert.match(f.read('android/app/src/main/res/values/styles.xml'), /windowSplashScreenAnimatedIcon">@drawable\/launch_brand_icon/);
50
+ assert.match(f.read('android/app/src/main/res/drawable/launch_background.xml'), /android:width="120dp"/);
51
+ assert.equal(syncCapacitor9LaunchSplash(f.root), 'unchanged');
52
+ });
53
+
54
+ test('preserves custom launch themes and drawables', t => {
55
+ const f = fixture(t, '<style name="AppTheme.NoActionBarLaunch" parent="Theme.SplashScreen"><item name="windowSplashScreenAnimatedIcon">@drawable/brand</item></style>');
56
+ assert.equal(syncCapacitor9LaunchSplash(f.root), 'custom-theme');
57
+ assert.equal(fs.existsSync(path.join(f.root, 'android/app/src/main/res/drawable/launch_background.xml')), false);
58
+ });
@@ -0,0 +1,77 @@
1
+ const test = require('node:test');
2
+ const assert = require('node:assert/strict');
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+ const crypto = require('crypto');
7
+ const sharp = require('sharp');
8
+ const AdmZip = require('adm-zip');
9
+ const { syncNativeSplash, validateNativeSplash, densities } = require('../files/buildCodeplay/native-splash-sync.cjs');
10
+ const { updateBuildScripts } = require('../files/buildCodeplay/project-scripts.cjs');
11
+
12
+ test('Capacitor sync hook restores and validates the native splash once', () => {
13
+ const scripts = updateBuildScripts({ 'capacitor:sync:after': 'node buildCodeplay/manifestModification.js' });
14
+ const hook = scripts['capacitor:sync:after'];
15
+ assert.ok(hook.indexOf('native-splash-sync.cjs &&') < hook.indexOf('sync-capacitor9-launch-splash.cjs'));
16
+ assert.match(hook, /native-splash-sync\.cjs --validate-if-configured$/);
17
+ assert.equal(updateBuildScripts(scripts)['capacitor:sync:after'], hook);
18
+ });
19
+
20
+ test('native splash sync detects setup, regenerates changed icons, and validates packaged assets', async () => {
21
+ const tempRoot = path.resolve(__dirname, '..', 'agent-temp');
22
+ fs.mkdirSync(tempRoot, { recursive: true });
23
+ const root = fs.mkdtempSync(path.join(tempRoot, 'native-splash-test-'));
24
+ const write = (relative, content) => {
25
+ const file = path.join(root, relative);
26
+ fs.mkdirSync(path.dirname(file), { recursive: true });
27
+ fs.writeFileSync(file, content);
28
+ return file;
29
+ };
30
+ try {
31
+ write('package.json', JSON.stringify({ dependencies: { '@capacitor/core': '^9.0.0' } }));
32
+ assert.equal((await syncNativeSplash(root, { log() {} })).status, 'needs-ai-setup');
33
+ const source = await sharp({ create: { width: 1024, height: 1024, channels: 4, background: '#32aabb' } }).png().toBuffer();
34
+ write('resources/icon-foreground.png', source);
35
+ const hash = crypto.createHash('sha256').update(source).digest('hex');
36
+ write('splashscreens/profile.json', JSON.stringify({
37
+ schemaVersion: 1, iconSource: 'resources/icon-foreground.png', approvedIconSha256: hash,
38
+ title: 'Test App', colors: { background: '#001122', primary: '#22aabb', accent: '#ff6600' },
39
+ loaderCount: 15, loaderIds: Array.from({ length: 15 }, (_, i) => `loader-${i}`),
40
+ javaPackage: 'example.splash', nativeSourceDir: 'splashscreens/native',
41
+ }));
42
+ const pkg = 'package example.splash;\n';
43
+ write('splashscreens/native/MainActivity.java', pkg + 'void hideLaunchOverlay() {}');
44
+ write('splashscreens/native/LaunchOverlayPlugin.java', pkg + '@CapacitorPlugin');
45
+ write('splashscreens/native/CodeplayLaunchView.java', pkg +
46
+ 'int LOADER_COUNT = 15; switch (type) {' + Array.from({ length: 14 }, (_, i) => `case ${i}: break;`).join('') + 'default: break;}');
47
+ assert.equal((await syncNativeSplash(root, { log() {} })).status, 'no-android');
48
+ write('android/app/src/main/res/values/styles.xml', '<resources />');
49
+ const first = await syncNativeSplash(root, { log() {} });
50
+ assert.equal(first.status, 'updated');
51
+ assert.equal(first.needsAiReview, false);
52
+ assert.equal((await validateNativeSplash(root)).ok, true);
53
+ assert.equal((await syncNativeSplash(root, { log() {} })).status, 'verified');
54
+
55
+ const zip = new AdmZip();
56
+ const res = path.join(root, 'android/app/src/main/res');
57
+ for (const density of Object.keys(densities)) {
58
+ zip.addFile(`res/mipmap-${density}-v4/ic_launcher_foreground.webp`,
59
+ fs.readFileSync(path.join(res, `mipmap-${density}/ic_launcher_foreground.webp`)));
60
+ }
61
+ zip.addFile('res/drawable-nodpi-v4/launch_brand_icon.webp',
62
+ fs.readFileSync(path.join(res, 'drawable-nodpi/launch_brand_icon.webp')));
63
+ const apk = write('agent-temp/fixture.apk', zip.toBuffer());
64
+ assert.equal((await validateNativeSplash(root, { apk })).ok, true);
65
+
66
+ write('resources/icon-foreground.png', await sharp(source).tint('#ff6600').png().toBuffer());
67
+ assert.equal((await validateNativeSplash(root)).ok, false);
68
+ const changed = await syncNativeSplash(root, { log() {} });
69
+ assert.equal(changed.needsAiReview, true);
70
+ assert.ok((await validateNativeSplash(root, { apk })).issues.some(issue => issue.includes('stale')));
71
+ fs.unlinkSync(path.join(res, 'mipmap-hdpi/ic_launcher_foreground.webp'));
72
+ assert.equal((await syncNativeSplash(root, { log() {} })).status, 'updated');
73
+ assert.ok(fs.existsSync(path.join(res, 'mipmap-hdpi/ic_launcher_foreground.webp')));
74
+ } finally {
75
+ assert.ok(root.startsWith(tempRoot + path.sep));
76
+ }
77
+ });
@@ -115,14 +115,26 @@ function install(options = {}) {
115
115
  if (!capacitor9) require('../files/buildCodeplay/splash-setup.cjs').syncSplashSetup(projectRoot);
116
116
  if (capacitor9) {
117
117
  require('../files/buildCodeplay/sync-notification-large-icon.cjs').syncNotificationLargeIcon(projectRoot);
118
+ const profile = path.join(projectRoot, 'splashscreens', 'profile.json');
119
+ if (fs.existsSync(profile)) {
120
+ const result = require('child_process').spawnSync(process.execPath, [path.join(buildTarget, 'native-splash-sync.cjs')], {
121
+ cwd: projectRoot, stdio: 'inherit',
122
+ });
123
+ if (result.error || result.status !== 0) throw result.error || new Error('Native splash asset sync failed.');
124
+ } else console.log('codeplay-common: native splash and display icon branding needs AGENTS/AI-Native-Splash-and-Display-Icon.txt setup.');
118
125
  const splash = require('../files/buildCodeplay/sync-capacitor9-launch-splash.cjs').syncCapacitor9LaunchSplash(projectRoot);
119
126
  console.log(`codeplay-common: Capacitor 9 launch splash ${splash}.`);
127
+ if (fs.existsSync(profile) && fs.existsSync(path.join(projectRoot, 'android', 'app', 'src', 'main', 'res'))) {
128
+ const result = require('child_process').spawnSync(process.execPath,
129
+ [path.join(buildTarget, 'native-splash-sync.cjs'), '--validate'], { cwd: projectRoot, stdio: 'inherit' });
130
+ if (result.error || result.status !== 0) throw result.error || new Error('Native splash validation failed.');
131
+ }
120
132
  }
121
133
  require('../files/buildCodeplay/setup-ruads.cjs').syncRuAdsSetup(projectRoot, {
122
134
  runtimeRoot: path.resolve(__dirname, '../runtime/vk-ads'),
123
135
  });
124
136
  require('../files/buildCodeplay/iap-alias.cjs').syncIapAliases(projectRoot);
125
- migrateAppConfigurator(projectRoot);
137
+ migrateAppConfigurator(projectRoot);
126
138
  require('../files/buildCodeplay/migrate-system-bars.cjs').migrateSystemBars(projectRoot);
127
139
  syncAndroidR8Rules(projectRoot, { installGradleHook: true });
128
140
  pkg.scripts = scripts;