diff --git a/packages/community-cli-plugin/src/commands/bundle/__tests__/buildBundle-test.js b/packages/community-cli-plugin/src/commands/bundle/__tests__/buildBundle-test.js new file mode 100644 index 000000000000..997088cc4c21 --- /dev/null +++ b/packages/community-cli-plugin/src/commands/bundle/__tests__/buildBundle-test.js @@ -0,0 +1,154 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import type {BundleCommandArgs} from '../buildBundle'; +import type {RunBuildOptions, RunBuildResult} from 'metro'; + +import {unstable_buildBundleWithConfig as buildBundle} from '../buildBundle'; +import {getDefaultConfig} from 'metro-config'; +import * as metroBundle from 'metro/private/shared/output/bundle'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +jest.mock('metro', () => ({runBuild: jest.fn()})); + +let directory: string; +let args: BundleCommandArgs; +let bundle: RunBuildResult; +type BundleOutput = NonNullable; +const runBuildMock: JestMockFn< + [config: unknown, options: RunBuildOptions], + Promise, +> = jest.requireMock('metro').runBuild; + +beforeEach(() => { + jest.useRealTimers(); + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-build-bundle-')); + args = { + entryFile: 'index.js', + platform: 'ios', + dev: false, + resetCache: false, + resetGlobalCache: false, + bundleOutput: path.join(directory, 'output', 'main.jsbundle'), + sourcemapUseAbsolutePath: false, + verbose: false, + unstableTransformProfile: 'default', + }; + bundle = { + code: 'console.log("café");', + map: JSON.stringify({ + version: 3, + sources: [path.join(directory, 'index.js')], + names: [], + mappings: '', + }), + }; + jest.spyOn(console, 'warn').mockImplementation(() => {}); + // Simulate runBuild's output contract, but use the real output writer. + runBuildMock.mockReset(); + runBuildMock.mockImplementation(async (_config, options: RunBuildOptions) => { + const {bundleOut, platform} = options; + if (bundleOut == null || platform == null) { + throw new Error('Expected explicit bundle output and platform'); + } + await (options.output ?? metroBundle).save( + bundle, + { + bundleOutput: bundleOut, + sourcemapOutput: options.sourceMapOut, + dev: options.dev, + platform, + }, + () => {}, + ); + return bundle; + }); +}); + +afterEach(() => { + jest.restoreAllMocks(); + jest.clearAllMocks(); + fs.rmSync(directory, {recursive: true, force: true}); +}); + +test('honors the requested bundle encoding', async () => { + args.bundleEncoding = 'utf16le'; + + await buildBundle(args, await getDefaultConfig(directory)); + + expect(fs.readFileSync(args.bundleOutput)).toEqual( + Buffer.from(bundle.code, 'utf16le'), + ); +}); + +test('keeps UTF-8 output when no encoding is specified', async () => { + await buildBundle(args, await getDefaultConfig(directory)); + + expect(fs.readFileSync(args.bundleOutput)).toEqual( + Buffer.from(bundle.code, 'utf8'), + ); +}); + +test.each([false, true])( + 'relativizes source paths in a source map (indexed: %s)', + async indexed => { + const map = JSON.parse(bundle.map); + if (indexed) { + bundle.map = JSON.stringify({ + version: 3, + sections: [{offset: {line: 0, column: 0}, map}], + }); + } + const sourcemapOutput = path.join(directory, 'output', 'main.map'); + args.sourcemapOutput = sourcemapOutput; + args.sourcemapSourcesRoot = directory; + + await buildBundle(args, await getDefaultConfig(directory)); + + const written = JSON.parse(fs.readFileSync(sourcemapOutput, 'utf8')); + expect(indexed ? written.sections[0].map.sources : written.sources).toEqual( + ['index.js'], + ); + }, +); + +test('preserves a custom output implementation and its save options', async () => { + args.bundleEncoding = 'ascii'; + args.sourcemapOutput = path.join(directory, 'output', 'main.map'); + args.sourcemapSourcesRoot = directory; + const output = { + build: jest.fn< + Parameters, + ReturnType, + >(async () => bundle), + save: jest.fn< + Parameters, + ReturnType, + >(async () => {}), + }; + + await buildBundle(args, await getDefaultConfig(directory), output); + + expect(runBuildMock.mock.calls[0][1].output?.build).toBe(output.build); + expect(output.save).toHaveBeenCalledWith( + bundle, + { + bundleOutput: args.bundleOutput, + sourcemapOutput: args.sourcemapOutput, + dev: args.dev, + platform: args.platform, + bundleEncoding: 'ascii', + sourcemapSourcesRoot: directory, + }, + expect.any(Function), + ); +}); diff --git a/packages/community-cli-plugin/src/commands/bundle/__tests__/saveAssets-test.js b/packages/community-cli-plugin/src/commands/bundle/__tests__/saveAssets-test.js new file mode 100644 index 000000000000..dcb9fef77f7f --- /dev/null +++ b/packages/community-cli-plugin/src/commands/bundle/__tests__/saveAssets-test.js @@ -0,0 +1,92 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @flow strict-local + * @format + */ + +import saveAssets from '../saveAssets'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; + +let directory: string; + +beforeEach(() => { + jest.useRealTimers(); + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'rn-save-assets-')); + jest.spyOn(console, 'info').mockImplementation(() => {}); + jest.spyOn(console, 'error').mockImplementation(() => {}); +}); + +afterEach(() => { + jest.restoreAllMocks(); + fs.rmSync(directory, {recursive: true, force: true}); +}); + +function makeAsset(type: string) { + const file = path.join(directory, `icon.${type}`); + fs.writeFileSync(file, 'asset contents'); + return { + __packager_asset: true, + fileSystemLocation: directory, + httpServerLocation: '/assets', + width: 1, + height: 1, + scales: [1], + files: [file], + hash: 'hash', + name: 'icon', + type, + }; +} + +test('rejects when the requested iOS asset catalog is missing', async () => { + const assetsDest = path.join(directory, 'output'); + const catalogDest = path.join(directory, 'missing-catalog'); + + await expect( + saveAssets([makeAsset('gif')], 'ios', assetsDest, catalogDest), + ).rejects.toThrow( + `Could not find asset catalog 'RNAssets.xcassets' in ${catalogDest}`, + ); + expect(fs.existsSync(assetsDest)).toBe(false); +}); + +test('saves catalog images and copies non-catalog assets', async () => { + const assetsDest = path.join(directory, 'output'); + const catalogDest = path.join(directory, 'catalog'); + const imageset = path.join(catalogDest, 'RNAssets.xcassets', 'icon.imageset'); + fs.mkdirSync(path.dirname(imageset), {recursive: true}); + + await saveAssets( + [makeAsset('png'), makeAsset('gif')], + 'ios', + assetsDest, + catalogDest, + ); + + expect(fs.readFileSync(path.join(imageset, 'icon.png'), 'utf8')).toBe( + 'asset contents', + ); + expect( + JSON.parse(fs.readFileSync(path.join(imageset, 'Contents.json'), 'utf8')) + .images, + ).toEqual([{filename: 'icon.png', idiom: 'universal', scale: '1x'}]); + expect( + fs.readFileSync(path.join(assetsDest, 'assets', 'icon.gif'), 'utf8'), + ).toBe('asset contents'); +}); + +test('copies loose assets when no asset catalog is requested', async () => { + const assetsDest = path.join(directory, 'output'); + + await saveAssets([makeAsset('gif')], 'ios', assetsDest); + + expect( + fs.readFileSync(path.join(assetsDest, 'assets', 'icon.gif'), 'utf8'), + ).toBe('asset contents'); +}); diff --git a/packages/community-cli-plugin/src/commands/bundle/buildBundle.js b/packages/community-cli-plugin/src/commands/bundle/buildBundle.js index c6e38af5e2c2..6c22aa94d201 100644 --- a/packages/community-cli-plugin/src/commands/bundle/buildBundle.js +++ b/packages/community-cli-plugin/src/commands/bundle/buildBundle.js @@ -15,6 +15,7 @@ import loadMetroConfig from '../../utils/loadMetroConfig'; import parseKeyValueParamArray from '../../utils/parseKeyValueParamArray'; import saveAssets from './saveAssets'; import {runBuild} from 'metro'; +import * as metroBundle from 'metro/private/shared/output/bundle'; import {promises as fs} from 'node:fs'; import path from 'node:path'; import {styleText} from 'node:util'; @@ -95,6 +96,7 @@ async function buildBundleWithConfig( sourceMapUrl = path.basename(sourceMapUrl); } + const output = bundleImpl ?? metroBundle; const runBuildOptions: RunBuildOptions = { assets: args.assetsDest != null, bundleOut: args.bundleOutput, @@ -102,7 +104,20 @@ async function buildBundleWithConfig( dev: args.dev, entry: args.entryFile, minify: args.minify !== undefined ? args.minify : !args.dev, - output: bundleImpl, + output: { + ...output, + // runBuild only forwards a subset of the CLI's output options to save. + save: (bundle, options, log) => + output.save( + bundle, + { + ...options, + bundleEncoding: args.bundleEncoding, + sourcemapSourcesRoot: args.sourcemapSourcesRoot, + }, + log, + ), + }, platform: args.platform, sourceMap: args.sourcemapOutput != null, sourceMapOut: args.sourcemapOutput, diff --git a/packages/community-cli-plugin/src/commands/bundle/saveAssets.js b/packages/community-cli-plugin/src/commands/bundle/saveAssets.js index c8487aef66c8..78ef5b9fd8ce 100644 --- a/packages/community-cli-plugin/src/commands/bundle/saveAssets.js +++ b/packages/community-cli-plugin/src/commands/bundle/saveAssets.js @@ -22,7 +22,6 @@ import getAssetDestPathAndroid from './getAssetDestPathAndroid'; import getAssetDestPathIOS from './getAssetDestPathIOS'; import fs from 'node:fs'; import path from 'node:path'; -import {styleText} from 'node:util'; type CopiedFiles = { [src: string]: string, @@ -64,10 +63,9 @@ async function saveAssets( // remove unused scales from the optimized bundle. const catalogDir = path.join(assetCatalogDest, 'RNAssets.xcassets'); if (!fs.existsSync(catalogDir)) { - console.error( - `${styleText('red', 'error')}: Could not find asset catalog 'RNAssets.xcassets' in ${assetCatalogDest}. Make sure to create it if it does not exist.`, + throw new Error( + `Could not find asset catalog 'RNAssets.xcassets' in ${assetCatalogDest}. Make sure to create it if it does not exist.`, ); - return; } console.info('Adding images to asset catalog', catalogDir);