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        if (platform === 'web') return metadata;
33
34        return {
35          ...metadata,
36          [platform]: {
37            // Get the filename for each platform's bundle.
38            bundle: path.join('bundles', fileNames[platform]!),
39            // Collect all of the assets and convert them to the serial format.
40            assets: bundle.assets
41              .map(
42                (asset) =>
43                  // Each asset has multiple hashes which we convert and then flatten.
44                  asset.fileHashes?.map((hash) => ({
45                    path: path.join('assets', hash),
46                    ext: asset.type,
47                  }))
48              )
49              .filter(Boolean)
50              .flat(),
51          },
52        };
53      },
54      {}
55    ) as FileMetadata,
56  };
57}
58