1import path from 'path';
2
3import { BundleOutput } from './fork-bundleAsync';
4
5export type BundlePlatform = 'android' | 'ios';
6
7type PlatformMetadataAsset = { path: string; ext: string };
8
9type PlatformMetadata = { bundle: string; assets: PlatformMetadataAsset[] };
10
11type FileMetadata = {
12  [key in BundlePlatform]: PlatformMetadata;
13};
14
15export function createMetadataJson({
16  bundles,
17  fileNames,
18}: {
19  bundles: Partial<Record<BundlePlatform, Pick<BundleOutput, 'assets'>>>;
20  fileNames: Record<string, string>;
21}): {
22  version: 0;
23  bundler: 'metro';
24  fileMetadata: FileMetadata;
25} {
26  // Build metadata.json
27  return {
28    version: 0,
29    bundler: 'metro',
30    fileMetadata: Object.entries(bundles).reduce<Record<string, Partial<PlatformMetadata>>>(
31      (metadata, [platform, bundle]) => ({
32        ...metadata,
33        [platform]: {
34          // Get the filename for each platform's bundle.
35          bundle: path.join('bundles', fileNames[platform]!),
36          // Collect all of the assets and convert them to the serial format.
37          assets: bundle.assets
38            .map((asset) =>
39              // Each asset has multiple hashes which we convert and then flatten.
40              asset.fileHashes?.map((hash) => ({
41                path: path.join('assets', hash),
42                ext: asset.type,
43              }))
44            )
45            .filter(Boolean)
46            .flat(),
47        },
48      }),
49      {}
50    ) as FileMetadata,
51  };
52}
53