Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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<RunBuildOptions['output']>;
const runBuildMock: JestMockFn<
[config: unknown, options: RunBuildOptions],
Promise<RunBuildResult>,
> = 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<BundleOutput['build']>,
ReturnType<BundleOutput['build']>,
>(async () => bundle),
save: jest.fn<
Parameters<BundleOutput['save']>,
ReturnType<BundleOutput['save']>,
>(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),
);
});
Original file line number Diff line number Diff line change
@@ -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');
});
17 changes: 16 additions & 1 deletion packages/community-cli-plugin/src/commands/bundle/buildBundle.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -95,14 +96,28 @@ async function buildBundleWithConfig(
sourceMapUrl = path.basename(sourceMapUrl);
}

const output = bundleImpl ?? metroBundle;
const runBuildOptions: RunBuildOptions = {
assets: args.assetsDest != null,
bundleOut: args.bundleOutput,
customResolverOptions,
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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down
Loading