๐Ÿ“ฆ facebook / react-native

๐Ÿ“„ compose-framework.js ยท 260 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260/**
 * 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
 * @format
 */

const {HEADERS_FOLDER, TARGET_FOLDER} = require('./constants');
const {execSync} = require('child_process');
const fs = require('fs');
const path = require('path');

/*::
import type { Dependency, Platform } from './types';
*/

/**
 * Composes the final XCFramework from the artifacts in the build folder
 */
async function createFramework(
  scheme /*: string */,
  configuration /*: string */,
  dependencies /*: $ReadOnlyArray<Dependency> */,
  rootFolder /*: string */,
  buildFolder /*: string */,
  identity /*: ?string */,
) {
  console.log('โœ… Composing iOS XCFramework...');

  // Get the build destination path from the prebuild step
  const frameworksOutputFolder = path.join(buildFolder, 'Build', 'Products');
  const frameworks = fs.readdirSync(frameworksOutputFolder);
  console.log('Frameworks found:', frameworks.join(', '));

  const frameworkPaths = frameworks.map(framework =>
    path.join(frameworksOutputFolder, framework),
  );

  const output = path.join(rootFolder, `${scheme}.xcframework`);

  // Check if output already exists and delete it
  fs.rmSync(output, {recursive: true, force: true});

  console.log('Output path:', output);

  const frameworksArgs = frameworkPaths
    .map(
      framework =>
        `-framework ${path.join(
          framework,
          'PackageFrameworks',
          `${scheme}.framework`,
        )}`,
    )
    .join(' ');

  const command = `xcodebuild -create-xcframework ${frameworksArgs} -output ${output} `;
  execSync(command, {stdio: 'inherit'});

  // Copy bundles into the framework
  copyBundles(scheme, dependencies, output, frameworkPaths);

  // Copy Symbols to symbols folder - copy before headers since we're using the folders inside the xcframework
  // to get the arch slices.
  copySymbols(scheme, output, frameworkPaths);

  // Copy headers to the framework - start by building the Header folder
  copyHeaders(scheme, dependencies, rootFolder);

  if (identity) {
    signXCFramework(identity, output);
  }
}

/**
 * Copies headers needed from the package to a Header folder that we'll pass to
 * each framework arch type
 */
function copyHeaders(
  scheme /*: string */,
  dependencies /*: $ReadOnlyArray<Dependency> */,
  rootFolder /*: string */,
) {
  console.log('Copying header files for dependencies...');

  // Create and clean the header folder
  const headeDestinationFolder = path.join(
    rootFolder,
    `${scheme}.xcframework`,
    'Headers',
  );
  fs.rmSync(headeDestinationFolder, {force: true, recursive: true});
  fs.mkdirSync(headeDestinationFolder, {recursive: true});

  // Now we can go through all dependencies and copy header files for each depencendy
  dependencies.forEach(dep => {
    const depHeaders = path.join(
      rootFolder,
      dep.name,
      TARGET_FOLDER,
      HEADERS_FOLDER,
    );

    // Copy all header files from the dependency to headerTempFolder
    execSync(`cp -r ${depHeaders}/* ${headeDestinationFolder}/`);
  });
}

/**
 * Copies the bundles in the source frameworks to the target xcframework inside the xcframework's Resources folder
 */
function copyBundles(
  scheme /*: string */,
  dependencies /*: $ReadOnlyArray<Dependency> */,
  outputFolder /*:string*/,
  frameworkPaths /*:Array<string>*/,
) {
  console.log('Copying bundles to the framework...');
  // Let's precalculate the target folder. It is the xcframework's output folder with
  // all its targets.
  const targetArchFolders = fs
    .readdirSync(outputFolder)
    .map(p => path.join(outputFolder, p))
    .filter(p => fs.statSync(p).isDirectory());
  // For each framework (in frameworkPaths), copy the bundles from the source folder.
  // A bundle is the name of the framework + _ + target name + .bundle. We can
  // check if the target has a bundle by checking if it defines one or more resources.
  frameworkPaths.forEach(frameworkPath => {
    const frameworkPlatforms = getArchsFromFramework(
      path.join(
        frameworkPath,
        'PackageFrameworks',
        scheme + '.framework',
        scheme,
      ),
    );

    dependencies.forEach(dep => {
      const resources = dep.files.resources;
      if (!resources || resources.length === 0) {
        return;
      }
      // Get bundle source folder
      const bundleName = `${scheme}_${dep.name}.bundle`;
      const sourceBundlePath = path.join(frameworkPath, bundleName);
      if (fs.existsSync(sourceBundlePath)) {
        // Target folder - needs to be copied to the resulting framework
        const targetFolder = targetArchFolders.find(
          targetArchFolder =>
            getArchsFromFramework(
              path.join(targetArchFolder, scheme + '.framework', scheme),
            ) === frameworkPlatforms,
        );
        if (targetFolder) {
          console.log(
            `  ${path.relative(outputFolder, sourceBundlePath)} โ†’ ${path.basename(targetFolder)}`,
          );
          const targetBundlePath = path.join(
            targetFolder,
            `${scheme}.framework`,
            bundleName,
          );

          // A bundle is a directory, so we need to copy the whole directory
          execSync(`cp -r "${sourceBundlePath}/" "${targetBundlePath}"`);
        } else {
          throw Error(
            `Could not find target architecture for folder ${path.relative(outputFolder, frameworkPath)}. Expected to find ${frameworkPlatforms}`,
          );
        }
      } else {
        console.warn(`Bundle ${sourceBundlePath} not found`);
      }
    });
  });
}

function copySymbols(
  scheme /*: string */,
  outputFolder /*:string*/,
  frameworkPaths /*:Array<string>*/,
) {
  console.log('Copying dSym files...');

  const targetArchFolders = fs
    .readdirSync(outputFolder)
    .map(p => path.join(outputFolder, p))
    .filter(p => fs.statSync(p).isDirectory());

  // For each framework (in frameworkPaths), copy the symbols from the source folder.
  frameworkPaths.forEach(frameworkPath => {
    const frameworkPlatforms = getArchsFromFramework(
      path.join(
        frameworkPath,
        'PackageFrameworks',
        scheme + '.framework',
        scheme,
      ),
    );

    // Find the correct target folder based on the current architectures
    const targetFolder = targetArchFolders.find(
      targetArchFolder =>
        frameworkPlatforms ===
        getArchsFromFramework(
          path.join(targetArchFolder, scheme + '.framework', scheme),
        ),
    );

    if (!targetFolder) {
      throw new Error(`Could not find target folder for ${frameworkPath}`);
    }
    const sourceSymbolPath = path.join(
      frameworkPath,
      scheme + '.framework.dSYM',
    );
    if (!fs.existsSync(sourceSymbolPath)) {
      throw new Error(`dSYM folder ${sourceSymbolPath} not found`);
    }

    const archName = path.basename(targetFolder);
    console.log(
      ` ${path.relative(outputFolder, sourceSymbolPath)} โ†’ ${archName}`,
    );

    const targetSymbolPath = path.join(
      outputFolder,
      '..',
      'Symbols',
      archName,
      scheme + '.framework.dSYM',
    );
    fs.mkdirSync(targetSymbolPath, {recursive: true});
    execSync(`cp -r "${sourceSymbolPath}/" "${targetSymbolPath}"`);
  });
}

function getArchsFromFramework(frameworkPath /*:string*/) {
  return execSync(`vtool -show-build ${frameworkPath}|grep platform`)
    .toString()
    .split('\n')
    .map(p => p.trim().split(' ')[1])
    .sort((a, b) => a.localeCompare(b))
    .join(' ');
}

function signXCFramework(
  identity /*: string */,
  xcframeworkPath /*: string */,
) {
  console.log('Signing XCFramework...');
  const command = `codesign --timestamp --sign "${identity}" ${xcframeworkPath}`;
  execSync(command, {stdio: 'inherit'});
}

module.exports = {createFramework};