@oxy.so/app-preset 1.0.0

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/metro/index.js ADDED
@@ -0,0 +1,215 @@
1
+ /**
2
+ * @oxy.so/app-preset — Metro config factory.
3
+ *
4
+ * Lifts the shared Metro configuration every Oxy Expo app used to copy-paste:
5
+ * monorepo watch folders, the block list, symlink + package-exports resolution
6
+ * (required by @oxy.so/bloom's subpath exports), the web-font/wasm asset
7
+ * extensions, the release minifier tuning, and the NativeWind wrapper.
8
+ *
9
+ * Usage — a three-line metro.config.js:
10
+ *
11
+ * const { createOxyMetroConfig } = require('@oxy.so/app-preset/metro');
12
+ * module.exports = createOxyMetroConfig(__dirname, {
13
+ * sharedTypesPackage: '@myapp/shared-types',
14
+ * });
15
+ *
16
+ * @param {string} projectRoot Absolute path to the app package (pass `__dirname`).
17
+ * @param {object} [options]
18
+ * @param {string} [options.sharedTypesPackage] Bare name of the app's
19
+ * `packages/shared-types` workspace package. When set, it is aliased to the
20
+ * monorepo `packages/shared-types` dir and its `src` is added to the block
21
+ * list (so Metro never bundles the un-built TypeScript source).
22
+ * @param {string} [options.cssInput='./global.css'] NativeWind CSS entry point.
23
+ * @param {(string|RegExp)[]} [options.extraBlockList=[]] Extra Metro
24
+ * `blockList` patterns appended to the Oxy defaults.
25
+ * @param {boolean} [options.dropConsole=false] Strip console calls from the
26
+ * production web bundle. Hermes native bundles do not use Metro's minifier.
27
+ * @param {string} [options.svgTransformerPath] Resolved SVG transformer path.
28
+ * When set, `svg` moves from asset extensions to source extensions.
29
+ * @param {Record<string,string>} [options.extraNodeModules={}] Extra aliases.
30
+ * @param {string[]} [options.extraWatchFolders=[]] Additional watch roots.
31
+ * @param {string[]} [options.extraAssetExts=[]] Additional asset extensions.
32
+ * @param {string[]} [options.extraSourceExts=[]] Additional source extensions.
33
+ * @returns {import('metro-config').MetroConfig}
34
+ */
35
+ const { getDefaultConfig } = require('expo/metro-config');
36
+ const { withNativeWind } = require('nativewind/metro');
37
+ const path = require('path');
38
+
39
+ function blockPath(dir) {
40
+ const resolved = path.resolve(dir);
41
+ return new RegExp(`${resolved.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}/.*`);
42
+ }
43
+
44
+ function unique(values) {
45
+ return [...new Set(values)];
46
+ }
47
+
48
+ function createOxyMetroConfig(projectRoot, options = {}) {
49
+ const {
50
+ sharedTypesPackage,
51
+ cssInput = './global.css',
52
+ extraBlockList = [],
53
+ dropConsole = false,
54
+ svgTransformerPath,
55
+ extraNodeModules: configuredExtraNodeModules = {},
56
+ extraWatchFolders = [],
57
+ extraAssetExts = [],
58
+ extraSourceExts = [],
59
+ } = options;
60
+
61
+ const monorepoRoot = path.resolve(projectRoot, '../..');
62
+ const config = getDefaultConfig(projectRoot);
63
+
64
+ config.projectRoot = projectRoot;
65
+
66
+ // Include the monorepo root so Metro resolves hoisted deps in root node_modules/.
67
+ config.watchFolders = unique([monorepoRoot, ...extraWatchFolders.map((folder) => path.resolve(folder))]);
68
+
69
+ const blockList = [
70
+ blockPath(path.join(monorepoRoot, 'packages/backend')),
71
+ blockPath(path.join(monorepoRoot, 'docs')),
72
+ // Sibling git worktrees live under <monorepoRoot>/.worktrees and each carries a
73
+ // full node_modules; leaving them watchable makes Metro's file crawler walk
74
+ // hundreds of thousands of extra directories and time out starting watch mode.
75
+ blockPath(path.join(monorepoRoot, '.worktrees')),
76
+ /\.expo\/.*/,
77
+ /\.expo-shared\/.*/,
78
+ /\.metro\/.*/,
79
+ /\.cache\/.*/,
80
+ /node_modules\/\.cache\/.*/,
81
+ /\.tsbuildinfo$/,
82
+ /.*\.expo\/types\/.*/,
83
+ /__tests__\/.*/,
84
+ /\.test\.(js|ts|tsx|jsx)$/,
85
+ /\.spec\.(js|ts|tsx|jsx)$/,
86
+ /\.md$/,
87
+ /(?:^|[/\\])README(?:\.[^/\\]+)?$/,
88
+ ...extraBlockList.map((pattern) => typeof pattern === 'string' ? blockPath(pattern) : pattern),
89
+ ];
90
+
91
+ const extraNodeModules = {};
92
+ if (sharedTypesPackage) {
93
+ const sharedTypesDir = path.join(monorepoRoot, 'packages/shared-types');
94
+ blockList.push(blockPath(path.join(sharedTypesDir, 'src')));
95
+ extraNodeModules[sharedTypesPackage] = sharedTypesDir;
96
+ }
97
+
98
+ config.resolver = {
99
+ ...config.resolver,
100
+ blockList,
101
+ extraNodeModules: {
102
+ ...config.resolver.extraNodeModules,
103
+ ...extraNodeModules,
104
+ ...configuredExtraNodeModules,
105
+ },
106
+ // Resolve from the app's node_modules first, then the monorepo root (hoisted deps).
107
+ nodeModulesPaths: [
108
+ path.join(projectRoot, 'node_modules'),
109
+ path.join(monorepoRoot, 'node_modules'),
110
+ ],
111
+ // Enable symlinks for workspace resolution.
112
+ unstable_enableSymlinks: true,
113
+ // Enable package.json "exports" resolution (required by @oxy.so/bloom subpath exports).
114
+ unstable_enablePackageExports: true,
115
+ sourceExts: unique([
116
+ ...config.resolver.sourceExts,
117
+ 'ts',
118
+ 'tsx',
119
+ ...(svgTransformerPath ? ['svg'] : []),
120
+ ...extraSourceExts,
121
+ ]),
122
+ // Bloom imports `.woff2`/`.woff` fonts directly from JS on web; Metro does not
123
+ // include them in default assetExts. SVGs stay ASSETS (metro's default): the
124
+ // apps `require('*.svg')` them as image URIs (e.g. `<Image source={require(
125
+ // '…/empty.svg')} />`) — there is no react-native-svg-transformer configured,
126
+ // so removing `svg` from assetExts leaves it unresolvable (breaks the build).
127
+ assetExts: [
128
+ ...config.resolver.assetExts.filter((extension) => !svgTransformerPath || extension !== 'svg'),
129
+ 'wasm',
130
+ 'woff2',
131
+ 'woff',
132
+ ...extraAssetExts,
133
+ ],
134
+ };
135
+ config.resolver.assetExts = unique(config.resolver.assetExts);
136
+
137
+ config.transformer = {
138
+ ...config.transformer,
139
+ ...(svgTransformerPath ? { babelTransformerPath: svgTransformerPath } : {}),
140
+ minifierConfig: {
141
+ ...config.transformer?.minifierConfig,
142
+ keep_classnames: false,
143
+ keep_fnames: false,
144
+ mangle: {
145
+ keep_classnames: false,
146
+ keep_fnames: false,
147
+ },
148
+ output: {
149
+ ascii_only: true,
150
+ quote_style: 3,
151
+ wrap_iife: true,
152
+ },
153
+ sourceMap: {
154
+ includeSources: false,
155
+ },
156
+ toplevel: false,
157
+ compress: {
158
+ arguments: true,
159
+ dead_code: true,
160
+ drop_console: dropConsole,
161
+ drop_debugger: true,
162
+ ecma: 2020,
163
+ evaluate: true,
164
+ inline: 1,
165
+ passes: 3,
166
+ reduce_funcs: true,
167
+ reduce_vars: true,
168
+ unsafe: false,
169
+ unsafe_comps: false,
170
+ unsafe_math: false,
171
+ unsafe_methods: false,
172
+ },
173
+ },
174
+ };
175
+
176
+ return withNativeWind(config, {
177
+ input: cssInput,
178
+ inlineRem: 16,
179
+ inlineVariables: false,
180
+ });
181
+ }
182
+
183
+ /**
184
+ * Wraps a NativeWind Metro config with the Bloom single-instance rewrite and the
185
+ * web `ws` shim. In hoisted monorepos the same Bloom version is duplicated under
186
+ * root `node_modules` and each app's local `node_modules`; two copies mean two
187
+ * React Context objects, so `<BloomThemeProvider>` (services) does not satisfy
188
+ * `useTheme()` (app code) and the app crashes.
189
+ */
190
+ function withBloomSingleInstance(nativeWindConfig, projectRoot) {
191
+ const parentResolveRequest = nativeWindConfig.resolver.resolveRequest;
192
+ const bloomOrigin = path.join(projectRoot, 'package.json');
193
+
194
+ nativeWindConfig.resolver.resolveRequest = (context, moduleName, platform) => {
195
+ if (platform === 'web' && (moduleName === 'ws' || moduleName === 'node:ws')) {
196
+ return { type: 'empty' };
197
+ }
198
+
199
+ const resolveContext =
200
+ moduleName === '@oxy.so/bloom' || moduleName.startsWith('@oxy.so/bloom/')
201
+ ? { ...context, originModulePath: bloomOrigin }
202
+ : context;
203
+
204
+ return parentResolveRequest(resolveContext, moduleName, platform);
205
+ };
206
+
207
+ return nativeWindConfig;
208
+ }
209
+
210
+ function createOxyMetroConfigWithBloom(projectRoot, options = {}) {
211
+ const nativeWindConfig = createOxyMetroConfig(projectRoot, options);
212
+ return withBloomSingleInstance(nativeWindConfig, projectRoot);
213
+ }
214
+
215
+ module.exports = { createOxyMetroConfig: createOxyMetroConfigWithBloom, withBloomSingleInstance };
package/package.json ADDED
@@ -0,0 +1,119 @@
1
+ {
2
+ "name": "@oxy.so/app-preset",
3
+ "version": "1.0.0",
4
+ "description": "The Oxy distro of Expo — centralized Expo config plugin, Metro/Babel/ESLint factories, Tailwind base CSS and TypeScript bases shared by every Oxy app (Mention, Homiio, Allo, accounts, …). A zero-build package: apps replace copy-pasted config with a single dependency bump.",
5
+ "main": "./app.plugin.js",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "exports": {
10
+ ".": "./app.plugin.js",
11
+ "./app.plugin.js": "./app.plugin.js",
12
+ "./plugin/withOxyAppPreset": "./plugin/withOxyAppPreset.js",
13
+ "./plugin/withSharedUserId": "./plugin/withSharedUserId.js",
14
+ "./plugin/withOxyKeychain": "./plugin/withOxyKeychain.js",
15
+ "./plugin/withOxyBuildProperties": "./plugin/withOxyBuildProperties.js",
16
+ "./plugin/withOxyAndroidRelease": "./plugin/withOxyAndroidRelease.js",
17
+ "./plugin/withOxyAndroidWebp": "./plugin/withOxyAndroidWebp.js",
18
+ "./plugin/withOxyUpdates": "./plugin/withOxyUpdates.js",
19
+ "./metro": "./metro/index.js",
20
+ "./babel": "./babel/index.js",
21
+ "./eslint": "./eslint/index.js",
22
+ "./base.css": "./css/base.css",
23
+ "./css/base.css": "./css/base.css",
24
+ "./tsconfig/base.json": "./tsconfig/base.json",
25
+ "./tsconfig/frontend.json": "./tsconfig/frontend.json",
26
+ "./tsconfig/backend.json": "./tsconfig/backend.json",
27
+ "./package.json": "./package.json"
28
+ },
29
+ "files": [
30
+ "NOTICE",
31
+ "app.plugin.js",
32
+ "plugin",
33
+ "metro",
34
+ "babel",
35
+ "eslint",
36
+ "certs",
37
+ "css",
38
+ "tsconfig",
39
+ "README.md"
40
+ ],
41
+ "keywords": [
42
+ "oxyhq",
43
+ "expo",
44
+ "react-native",
45
+ "config-plugin",
46
+ "metro",
47
+ "babel",
48
+ "nativewind",
49
+ "preset"
50
+ ],
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "https://github.com/oxyhq/sdk",
54
+ "directory": "packages/app-preset"
55
+ },
56
+ "author": "OxyHQ",
57
+ "license": "Apache-2.0",
58
+ "homepage": "https://oxy.so",
59
+ "engines": {
60
+ "node": ">=18.0.0"
61
+ },
62
+ "scripts": {
63
+ "prepublishOnly": "node ../../scripts/assert-bun-publish.mjs",
64
+ "test": "node --test __tests__/*.test.js"
65
+ },
66
+ "//peerDependencies": "THE TWO @oxy.so PEERS ARE DELIBERATE. This package couples to them by FILE PATH, not by API: `css/base.css` imports `@oxy.so/bloom/design-tokens/theme.css`, and `plugin/withOxyAppPreset.js` optionally requires `@oxy.so/services/plugins/withSharedIdentityReader`. Services is exact-pinned so every preset release names the one SDK generation whose plugin path was verified. Bloom retains a measured floor and a breaking-major cap. Never replace either constraint with `*` or an uncapped range.",
67
+ "peerDependencies": {
68
+ "@oxy.so/bloom": "^1.0.0",
69
+ "@oxy.so/services": "1.0.0",
70
+ "babel-plugin-module-resolver": "*",
71
+ "babel-preset-expo": "*",
72
+ "eslint": ">=9.0.0",
73
+ "eslint-config-expo": "*",
74
+ "expo": ">=56.0.0",
75
+ "expo-build-properties": "*",
76
+ "nativewind": ">=5.0.0-preview.0",
77
+ "react-native-worklets": "*",
78
+ "sharp": ">=0.33.0",
79
+ "tailwindcss": ">=4.0.0"
80
+ },
81
+ "devDependencies": {
82
+ "expo": "^57.0.6"
83
+ },
84
+ "peerDependenciesMeta": {
85
+ "@oxy.so/bloom": {
86
+ "optional": true
87
+ },
88
+ "@oxy.so/services": {
89
+ "optional": true
90
+ },
91
+ "babel-plugin-module-resolver": {
92
+ "optional": true
93
+ },
94
+ "babel-preset-expo": {
95
+ "optional": true
96
+ },
97
+ "eslint": {
98
+ "optional": true
99
+ },
100
+ "eslint-config-expo": {
101
+ "optional": true
102
+ },
103
+ "expo-build-properties": {
104
+ "optional": true
105
+ },
106
+ "nativewind": {
107
+ "optional": true
108
+ },
109
+ "react-native-worklets": {
110
+ "optional": true
111
+ },
112
+ "sharp": {
113
+ "optional": true
114
+ },
115
+ "tailwindcss": {
116
+ "optional": true
117
+ }
118
+ }
119
+ }
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Expo Config Plugin: withOxyAndroidRelease
3
+ *
4
+ * Owns the two parts of `android/app/build.gradle`'s `release` buildType that
5
+ * `expo-build-properties` cannot express. Everything it CAN express (ABIs via
6
+ * `buildArchs`, proguard rules via `extraProguardRules`, minify/shrink/SDK
7
+ * levels) belongs in the app's build-properties block — do not duplicate those
8
+ * here.
9
+ *
10
+ * `android/` is gitignored and regenerated by `expo prebuild`, so these edits
11
+ * have to live in a plugin or they are lost on the next prebuild.
12
+ *
13
+ * 1. R8 optimization passes
14
+ * Expo generates `getDefaultProguardFile("proguard-android.txt")`, whose
15
+ * only meaningful line is `-dontoptimize`. Swapping to the `-optimize`
16
+ * variant drops that and adds `-allowaccessmodification`, which is what lets
17
+ * R8 inline and merge classes. Worth a few MB of dex on a typical Oxy app.
18
+ *
19
+ * 2. Release signing
20
+ * Expo generates `signingConfig signingConfigs.debug` for release, and Play
21
+ * rejects a debug-signed AAB. The real credentials are read from Gradle
22
+ * properties (set in the developer's `~/.gradle/gradle.properties` or CI
23
+ * secrets) so nothing secret ever lands in the repo. When those properties
24
+ * are absent the build falls back to the debug keystore, so a contributor
25
+ * without the keystore can still build — which is exactly why the shipped
26
+ * artefact's certificate must ALWAYS be verified (`keytool -printcert
27
+ * -jarfile <aab>` / `apksigner verify --print-certs <apk>`) rather than
28
+ * assumed.
29
+ *
30
+ * The certificate MUST be the shared Oxy ecosystem one: every Oxy app sets
31
+ * `android:sharedUserId="so.oxy.shared"` (see withSharedUserId) and Android
32
+ * requires every app sharing that UID to be signed with the SAME
33
+ * certificate. An app-specific key breaks "sign in once, use everywhere" and
34
+ * makes the app refuse to install next to its siblings.
35
+ *
36
+ * @param {import('expo/config').ExpoConfig} config
37
+ */
38
+
39
+ const { withAppBuildGradle } = require('expo/config-plugins');
40
+
41
+ /** Gradle property names holding the release signing material. */
42
+ const STORE_FILE = 'OXY_UPLOAD_STORE_FILE';
43
+ const STORE_PASSWORD = 'OXY_UPLOAD_STORE_PASSWORD';
44
+ const KEY_ALIAS = 'OXY_UPLOAD_KEY_ALIAS';
45
+ const KEY_PASSWORD = 'OXY_UPLOAD_KEY_PASSWORD';
46
+
47
+ const DEFAULT_PROGUARD = 'getDefaultProguardFile("proguard-android.txt")';
48
+ const OPTIMIZED_PROGUARD = 'getDefaultProguardFile("proguard-android-optimize.txt")';
49
+
50
+ const DEBUG_SIGNING_CONFIG = 'signingConfig signingConfigs.debug';
51
+ const CONDITIONAL_SIGNING_CONFIG =
52
+ `signingConfig project.hasProperty('${STORE_FILE}') ? signingConfigs.release : signingConfigs.debug`;
53
+
54
+ const RELEASE_SIGNING_CONFIG = ` release {
55
+ // Populated only when the Oxy release keystore properties are
56
+ // available; otherwise this config stays empty and the release
57
+ // buildType falls back to signingConfigs.debug below.
58
+ if (project.hasProperty('${STORE_FILE}')) {
59
+ storeFile file(project.property('${STORE_FILE}'))
60
+ storePassword project.property('${STORE_PASSWORD}')
61
+ keyAlias project.property('${KEY_ALIAS}')
62
+ keyPassword project.property('${KEY_PASSWORD}')
63
+ }
64
+ }
65
+ `;
66
+
67
+ function useOptimizedProguardFile(contents) {
68
+ if (contents.includes(OPTIMIZED_PROGUARD)) return contents;
69
+ if (!contents.includes(DEFAULT_PROGUARD)) {
70
+ throw new Error(
71
+ `[withOxyAndroidRelease] Could not find ${DEFAULT_PROGUARD} in app/build.gradle. ` +
72
+ 'The Expo template changed — update this plugin instead of editing android/ by hand.',
73
+ );
74
+ }
75
+ return contents.replace(DEFAULT_PROGUARD, OPTIMIZED_PROGUARD);
76
+ }
77
+
78
+ function addReleaseSigningConfig(contents) {
79
+ if (contents.includes(CONDITIONAL_SIGNING_CONFIG)) return contents;
80
+
81
+ // Declare signingConfigs.release immediately after the generated debug entry.
82
+ const debugSigningBlock = /(signingConfigs\s*\{\s*\n\s*debug\s*\{[\s\S]*?\n\s{8}\}\n)/;
83
+ if (!debugSigningBlock.test(contents)) {
84
+ throw new Error(
85
+ '[withOxyAndroidRelease] Could not find the generated signingConfigs.debug block in ' +
86
+ 'app/build.gradle. The Expo template changed — update this plugin.',
87
+ );
88
+ }
89
+ const next = contents.replace(debugSigningBlock, `$1${RELEASE_SIGNING_CONFIG}`);
90
+
91
+ // Point the release buildType at it. The debug buildType also contains
92
+ // `signingConfig signingConfigs.debug`, so only replace the occurrence that
93
+ // follows the `release {` marker.
94
+ const releaseBuildType = next.indexOf('release {', next.indexOf('buildTypes'));
95
+ if (releaseBuildType === -1) {
96
+ throw new Error(
97
+ '[withOxyAndroidRelease] Could not find the release buildType in app/build.gradle.',
98
+ );
99
+ }
100
+ const target = next.indexOf(DEBUG_SIGNING_CONFIG, releaseBuildType);
101
+ if (target === -1) {
102
+ throw new Error(
103
+ '[withOxyAndroidRelease] Could not find the release buildType signingConfig line.',
104
+ );
105
+ }
106
+ return (
107
+ next.slice(0, target) +
108
+ CONDITIONAL_SIGNING_CONFIG +
109
+ next.slice(target + DEBUG_SIGNING_CONFIG.length)
110
+ );
111
+ }
112
+
113
+ module.exports = function withOxyAndroidRelease(config) {
114
+ return withAppBuildGradle(config, (config) => {
115
+ if (config.modResults.language !== 'groovy') {
116
+ throw new Error(
117
+ `[withOxyAndroidRelease] Expected a Groovy app/build.gradle, got ${config.modResults.language}.`,
118
+ );
119
+ }
120
+ config.modResults.contents = addReleaseSigningConfig(
121
+ useOptimizedProguardFile(config.modResults.contents),
122
+ );
123
+ return config;
124
+ });
125
+ };
@@ -0,0 +1,198 @@
1
+ /**
2
+ * Expo Config Plugin: withOxyAndroidWebp
3
+ *
4
+ * Re-encodes the bitmap resources under `android/app/src/main/res` to real
5
+ * lossless WebP. Expo's generators emit PNG regardless of the extension they
6
+ * write it to, which costs the app twice:
7
+ *
8
+ * - Launcher icons land as `mipmap-*​/*.webp` holding PNG bytes. AAPT2 stores
9
+ * `.webp` entries UNCOMPRESSED, so the archive carries a whole PNG with zero
10
+ * deflate.
11
+ * - Splash images land as honest `drawable-*​/*.png`, which AAPT2 does deflate.
12
+ * Converting them (and renaming to `.webp`) still wins against the DEFLATED
13
+ * png. Renaming is safe because an Android resource is addressed by its
14
+ * filename without the extension: `@drawable/splashscreen_logo` resolves
15
+ * either way.
16
+ *
17
+ * WHY THIS EXISTS — do not delete it as redundant:
18
+ * `@expo/image-utils` is supposed to use sharp (which honours the requested
19
+ * output format) and only fall back to Jimp (which always emits PNG:
20
+ * `Image.js` -> `resizeAsync` -> `jimp.getBufferAsync('image/png')`) when sharp
21
+ * is unavailable. That fallback is ALWAYS taken, because of a bug in
22
+ * `findSharpBinAsync` (`@expo/image-utils/build/sharp.js`):
23
+ *
24
+ * 109: let _sharpInstance = null;
25
+ * 129: const sharpInstance = sharpPath ? require(sharpPath) : null;
26
+ * 133: typeof _sharpInstance?.versions?.vips === 'string') {
27
+ * 135: _sharpInstance = sharpInstance;
28
+ *
29
+ * Line 133 guards on the module-level cache `_sharpInstance` — null on a cold
30
+ * call — instead of the `sharpInstance` loaded on line 129, and the only
31
+ * assignment to that cache (line 135) sits INSIDE the block that guard
32
+ * protects. The block is therefore unreachable, `isAvailableAsync()` always
33
+ * returns false, and no amount of installing `sharp` or `sharp-cli` changes it
34
+ * (both verified). The bug is still present in the newest published
35
+ * `@expo/image-utils` (0.11.4). This plugin calls sharp directly, so it is
36
+ * unaffected. Once upstream fixes line 133, this plugin becomes a no-op rather
37
+ * than a conflict: it skips files that are already WebP.
38
+ *
39
+ * REGISTRATION ORDER: register this FIRST in the app's `plugins` array so that
40
+ * it RUNS LAST. `withMod`'s `interceptingMod` awaits its own action and only
41
+ * then calls `nextMod` (the previously registered mod), so the mod chain
42
+ * executes in reverse registration order — and this has to run after every
43
+ * image generator (splash screens included), or a generator that rewrites a
44
+ * `.png` after the conversion leaves the tree with both a `.png` and a `.webp`
45
+ * claiming the same resource name.
46
+ *
47
+ * `sharp` is an optional peer dependency: apps that enable this plugin must
48
+ * install it (`bun add -d sharp`).
49
+ *
50
+ * @param {import('expo/config').ExpoConfig} config
51
+ */
52
+
53
+ const fs = require('fs/promises');
54
+ const path = require('path');
55
+ const { withDangerousMod } = require('expo/config-plugins');
56
+
57
+ const RES_DIR = path.join('app', 'src', 'main', 'res');
58
+ const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
59
+
60
+ async function exists(file) {
61
+ try {
62
+ await fs.access(file);
63
+ return true;
64
+ } catch {
65
+ return false;
66
+ }
67
+ }
68
+
69
+ /** A RIFF container tagged WEBP: bytes 0-3 `RIFF`, bytes 8-11 `WEBP`. */
70
+ function isWebp(buffer) {
71
+ return (
72
+ buffer.length >= 12 &&
73
+ buffer.toString('ascii', 0, 4) === 'RIFF' &&
74
+ buffer.toString('ascii', 8, 12) === 'WEBP'
75
+ );
76
+ }
77
+
78
+ async function collectBitmapFiles(directory) {
79
+ const entries = await fs.readdir(directory, { withFileTypes: true });
80
+ const files = [];
81
+ for (const entry of entries) {
82
+ const entryPath = path.join(directory, entry.name);
83
+ if (entry.isDirectory()) {
84
+ files.push(...(await collectBitmapFiles(entryPath)));
85
+ } else if (entry.name.endsWith('.webp') || entry.name.endsWith('.png')) {
86
+ files.push(entryPath);
87
+ }
88
+ }
89
+ return files;
90
+ }
91
+
92
+ /**
93
+ * Decodes to raw RGBA so the two encodings can be compared pixel for pixel —
94
+ * the same guarantee as PIL's `ImageChops.difference().getbbox() is None`.
95
+ */
96
+ async function toRawRgba(sharp, buffer) {
97
+ return sharp(buffer).ensureAlpha().raw().toBuffer({ resolveWithObject: true });
98
+ }
99
+
100
+ /**
101
+ * True when both buffers render identically.
102
+ *
103
+ * Alpha must match exactly, and so must RGB on every pixel that is even
104
+ * slightly visible. RGB is deliberately NOT compared where alpha is 0: the
105
+ * colour behind a fully transparent pixel cannot be observed, and libwebp
106
+ * rewrites it during lossless encoding because a flat value compresses better.
107
+ * On a real launcher icon that accounts for every difference. Comparing the raw
108
+ * bytes instead would reject a conversion that is genuinely lossless.
109
+ */
110
+ function rendersIdentically(before, after) {
111
+ if (
112
+ before.info.width !== after.info.width ||
113
+ before.info.height !== after.info.height ||
114
+ before.info.channels !== after.info.channels
115
+ ) {
116
+ return false;
117
+ }
118
+ for (let i = 0; i < before.data.length; i += 4) {
119
+ if (before.data[i + 3] !== after.data[i + 3]) return false;
120
+ if (before.data[i + 3] === 0) continue;
121
+ if (
122
+ before.data[i] !== after.data[i] ||
123
+ before.data[i + 1] !== after.data[i + 1] ||
124
+ before.data[i + 2] !== after.data[i + 2]
125
+ ) {
126
+ return false;
127
+ }
128
+ }
129
+ return true;
130
+ }
131
+
132
+ async function convertResourceImages(projectRoot, resDir) {
133
+ let sharp;
134
+ try {
135
+ sharp = require('sharp');
136
+ } catch (error) {
137
+ throw new Error(
138
+ `[withOxyAndroidWebp] \`sharp\` is required to emit real WebP resources but could not be loaded (${error.message}). ` +
139
+ 'Install it as a devDependency of the app.',
140
+ );
141
+ }
142
+
143
+ const files = await collectBitmapFiles(resDir);
144
+ if (files.length === 0) {
145
+ // A silent no-op is the exact failure mode this plugin exists to prevent:
146
+ // it would leave everyone believing the saving is in place when it is not.
147
+ throw new Error(
148
+ `[withOxyAndroidWebp] Found no bitmap resources under ${path.relative(projectRoot, resDir)}. ` +
149
+ 'The generated resource layout changed — this plugin needs updating.',
150
+ );
151
+ }
152
+
153
+ for (const file of files) {
154
+ const source = await fs.readFile(file);
155
+ if (isWebp(source)) continue;
156
+
157
+ if (!source.subarray(0, 4).equals(PNG_MAGIC)) {
158
+ throw new Error(
159
+ `[withOxyAndroidWebp] ${path.relative(projectRoot, file)} is neither WebP nor PNG; refusing to guess its format.`,
160
+ );
161
+ }
162
+
163
+ const converted = await sharp(source).webp({ lossless: true, effort: 6 }).toBuffer();
164
+
165
+ const before = await toRawRgba(sharp, source);
166
+ const after = await toRawRgba(sharp, converted);
167
+ if (!rendersIdentically(before, after)) {
168
+ throw new Error(
169
+ `[withOxyAndroidWebp] Lossless conversion of ${path.relative(projectRoot, file)} changed a visible pixel; refusing to write it.`,
170
+ );
171
+ }
172
+
173
+ // A resource is addressed by its filename WITHOUT the extension, so a
174
+ // `.png` renamed to `.webp` keeps answering to `@drawable/<name>`. Two
175
+ // files sharing a basename in one directory would become a duplicate
176
+ // resource, so bail rather than create one.
177
+ const target = file.replace(/\.png$/, '.webp');
178
+ if (target !== file && (await exists(target))) {
179
+ throw new Error(
180
+ `[withOxyAndroidWebp] Converting ${path.relative(projectRoot, file)} would collide with an existing ${path.basename(target)}.`,
181
+ );
182
+ }
183
+
184
+ await fs.writeFile(target, converted);
185
+ if (target !== file) await fs.unlink(file);
186
+ }
187
+ }
188
+
189
+ module.exports = function withOxyAndroidWebp(config) {
190
+ return withDangerousMod(config, [
191
+ 'android',
192
+ async (config) => {
193
+ const { platformProjectRoot, projectRoot } = config.modRequest;
194
+ await convertResourceImages(projectRoot, path.join(platformProjectRoot, RES_DIR));
195
+ return config;
196
+ },
197
+ ]);
198
+ };