📦 facebook / react-native

📄 build.js · 449 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449/**
 * 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
 */

require('../shared/babelRegister').registerForScript();

const {PACKAGES_DIR, REPO_ROOT} = require('../shared/consts');
const {
  buildConfig,
  getBabelConfig,
  getBuildOptions,
  getTypeScriptCompilerOptions,
} = require('./config');
const babel = require('@babel/core');
const translate = require('flow-api-translator');
const {promises: fs} = require('fs');
const micromatch = require('micromatch');
const path = require('path');
const prettier = require('prettier');
const {globSync} = require('tinyglobby');
const ts = require('typescript');
const {parseArgs, styleText} = require('util');

const SRC_DIR = 'src';
const BUILD_DIR = 'dist';
const JS_FILES_PATTERN = '**/*.js';
const IGNORE_PATTERN = '**/__{tests,mocks,fixtures}__/**';

const config = {
  allowPositionals: true,
  options: {
    validate: {type: 'boolean'},
    help: {type: 'boolean'},
  },
};

async function build() {
  const {
    positionals: packageNames,
    values: {validate, help},
    /* $FlowFixMe[incompatible-type] Natural Inference rollout. See
     * https://fburl.com/workplace/6291gfvu */
  } = parseArgs(config);

  if (help) {
    console.log(`
  Usage: node ./scripts/build/build.js <packages>

  Build packages (shared monorepo build setup).

  By default, builds all packages defined in ./scripts/build/config.js. If a
  a package list is provided, builds only those specified.

  Options:
    --validate        Validate that no build artifacts have been accidentally
                      committed.
    `);
    process.exitCode = 0;
    return;
  }

  if (!validate) {
    console.log(
      '\n' + styleText(['bold', 'inverse'], 'Building packages') + '\n',
    );
  }

  const packagesToBuild = packageNames.length
    ? packageNames.filter(packageName => packageName in buildConfig.packages)
    : Object.keys(buildConfig.packages);

  let ok = true;
  for (const packageName of packagesToBuild) {
    if (validate) {
      ok &&= await checkPackage(packageName);
    } else {
      await buildPackage(packageName);
    }
  }

  process.exitCode = ok ? 0 : 1;
}

async function checkPackage(packageName /*: string */) /*: Promise<boolean> */ {
  const artifacts = await exportedBuildArtifacts(packageName);
  if (artifacts.length > 0) {
    console.log(
      `${styleText('bgRed', packageName)}: has been built and the ${styleText('bold', 'build artifacts')} committed to the repository. This will break Flow checks.`,
    );
    return false;
  }
  return true;
}

async function buildPackage(packageName /*: string */) {
  try {
    const {emitTypeScriptDefs} = getBuildOptions(packageName);
    const entryPoints = await getEntryPoints(packageName);

    const files = globSync('**/*', {
      cwd: path.resolve(PACKAGES_DIR, packageName, SRC_DIR),
      onlyFiles: true,
      absolute: true,
    }).filter(
      file =>
        !entryPoints.has(file) &&
        !entryPoints.has(file.replace(/\.js$/, '.flow.js')),
    );

    process.stdout.write(
      `${packageName} ${styleText('dim', '.').repeat(72 - packageName.length)} `,
    );

    // Build regular files
    for (const file of files) {
      await buildFile(path.normalize(file), {
        silent: true,
      });
    }

    // Build entry point files
    for (const entryPoint of entryPoints) {
      await buildFile(path.normalize(entryPoint), {
        silent: true,
      });
    }

    // Validate program for emitted .d.ts files
    if (emitTypeScriptDefs) {
      validateTypeScriptDefs(packageName);
    }

    process.stdout.write(
      styleText(['reset', 'inverse', 'bold', 'green'], ' DONE '),
    );
  } catch (e) {
    process.stdout.write(
      styleText(['reset', 'inverse', 'bold', 'red'], ' FAIL ') + '\n',
    );
    throw e;
  } finally {
    process.stdout.write('\n');
  }
}

async function buildFile(
  file /*: string */,
  options /*: {silent?: boolean, destPath?: string}*/ = {},
) {
  const {silent = false} = options;
  const packageName = getPackageName(file);
  const buildPath = getBuildPath(file);
  const {emitFlowDefs, emitTypeScriptDefs} = getBuildOptions(packageName);

  const logResult = ({copied, desc} /*: {copied: boolean, desc?: string} */) =>
    silent ||
    console.log(
      styleText('dim', '  - ') +
        path.relative(PACKAGES_DIR, file) +
        (copied ? ' -> ' + path.relative(PACKAGES_DIR, buildPath) : ' ') +
        (desc != null ? ' (' + desc + ')' : ''),
    );

  if (micromatch.isMatch(file, IGNORE_PATTERN)) {
    logResult({copied: false, desc: 'ignore'});
    return;
  }

  await fs.mkdir(path.dirname(buildPath), {recursive: true});

  if (!micromatch.isMatch(file, JS_FILES_PATTERN)) {
    await fs.copyFile(file, buildPath);
    logResult({copied: true, desc: 'copy'});
    return;
  }

  const source = await fs.readFile(file, 'utf-8');
  const prettierConfig = {parser: 'babel'};

  // Transform source file using Babel
  const transformed = await prettier.format(
    (await babel.transformFileAsync(file, getBabelConfig(packageName))).code,
    /* $FlowFixMe[incompatible-type] Natural Inference rollout. See
     * https://fburl.com/workplace/6291gfvu */
    prettierConfig,
  );
  await fs.writeFile(buildPath, transformed);

  // Translate source Flow types for each type definition target
  if (/@flow/.test(source)) {
    try {
      await Promise.all([
        emitFlowDefs
          ? fs.writeFile(
              buildPath + '.flow',
              await translate.translateFlowToFlowDef(source, prettierConfig),
            )
          : null,
        emitTypeScriptDefs
          ? fs.writeFile(
              buildPath.replace(/\.js$/, '') + '.d.ts',
              await translate.translateFlowToTSDef(source, prettierConfig),
            )
          : null,
      ]);
    } catch (e) {
      e.message = `Error translating ${path.relative(PACKAGES_DIR, file)}:\n${e.message}`;
      throw e;
    }
  }

  logResult({copied: true});
}

/*::
type PackageJson = {
  name: string,
  exports?: {[subpath: string]: string | mixed},
};
*/

function isStringOnly(entries /*: mixed */) /*: entries is string */ {
  return typeof entries === 'string';
}

async function exportedBuildArtifacts(
  packageName /*: string */,
) /*: Promise<string[]> */ {
  const packagePath = path.resolve(PACKAGES_DIR, packageName, 'package.json');
  const pkg /*: PackageJson */ = JSON.parse(
    await fs.readFile(packagePath, 'utf8'),
  );
  if (pkg.exports == null) {
    throw new Error(
      packageName +
        ' does not define an "exports" field in its package.json. As part ' +
        'of the build setup, this field must be used in order to rewrite ' +
        'paths to built files in production.',
    );
  }

  return Object.values(pkg.exports)
    .filter(isStringOnly)
    .filter(filepath =>
      path.dirname(filepath).split(path.sep).includes(BUILD_DIR),
    );
}

/**
 * Get the set of Flow entry points to build.
 *
 * As a convention, we use a .js/.flow.js file pair for each package entry
 * point, with the .js file being a Babel wrapper that can be used directly in
 * the monorepo. On build, we drop this wrapper and emit a single file from the
 * .flow.js contents.
 *
 * index.js ──────►(removed)
 *              ┌─►index.js
 * index.flow.js├─►index.d.ts
 *              └─►index.js.flow
 */
async function getEntryPoints(
  packageName /*: string */,
) /*: Promise<Set<string>> */ {
  const packagePath = path.resolve(PACKAGES_DIR, packageName, 'package.json');
  const pkg /*: PackageJson */ = JSON.parse(
    await fs.readFile(packagePath, 'utf8'),
  );
  const entryPoints /*: Set<string> */ = new Set();

  if (pkg.exports == null) {
    throw new Error(
      packageName +
        ' does not define an "exports" field in its package.json. As part ' +
        'of the build setup, this field must be used in order to rewrite ' +
        'paths to built files in production.',
    );
  }

  const exportsEntries = Object.entries(pkg.exports);

  for (const [subpath, targetOrConditionsObject] of exportsEntries) {
    const targets /*: string[] */ = [];
    if (
      typeof targetOrConditionsObject === 'object' &&
      targetOrConditionsObject != null
    ) {
      for (const [condition, target] of Object.entries(
        targetOrConditionsObject,
      )) {
        if (typeof target !== 'string') {
          throw new Error(
            `Invalid exports field in package.json for ${packageName}. ` +
              `exports["${subpath}"]["${condition}"] must be a string target.`,
          );
        }
        targets.push(target);
      }
    } else {
      if (typeof targetOrConditionsObject !== 'string') {
        throw new Error(
          `Invalid exports field in package.json for ${packageName}. ` +
            `exports["${subpath}"] must be a string target.`,
        );
      }
      targets.push(targetOrConditionsObject);
    }

    for (const target of targets) {
      // Skip non-JS files
      if (!target.endsWith('.js')) {
        continue;
      }

      if (target.includes('*')) {
        console.warn(
          `${styleText('yellow', 'Warning')}: Encountered subpath pattern ${subpath}` +
            ` in package.json exports for ${packageName}. Matched entry points ` +
            'will not be validated.',
        );
        continue;
      }

      if (target.endsWith('.flow.js')) {
        throw new Error(
          `Package ${packageName} defines exports["${subpath}"] = "${target}". ` +
            'Expecting a .js wrapper file. See other monorepo packages for examples.',
        );
      }

      // Our special case for wrapper files that need to be stripped
      const resolvedTarget = path.resolve(PACKAGES_DIR, packageName, target);
      const resolvedFlowTarget = resolvedTarget.replace(/\.js$/, '.flow.js');

      try {
        await Promise.all([
          fs.access(resolvedTarget),
          fs.access(resolvedFlowTarget),
        ]);
      } catch {
        throw new Error(
          `${resolvedFlowTarget} does not exist when building ${packageName}.

From package.json exports["${subpath}"]:
  - found:   ${path.relative(REPO_ROOT, resolvedTarget)}
  - missing: ${path.relative(REPO_ROOT, resolvedFlowTarget)}

This is needed so users can directly import this entry point from the monorepo.`,
        );
      }

      entryPoints.add(resolvedFlowTarget);
    }
  }

  return entryPoints;
}

function getPackageName(file /*: string */) /*: string */ {
  return path.relative(PACKAGES_DIR, file).split(path.sep)[0];
}

function getBuildPath(file /*: string */) /*: string */ {
  const packageDir = path.join(PACKAGES_DIR, getPackageName(file));

  return path.join(
    packageDir,
    file
      .replace(path.join(packageDir, SRC_DIR), BUILD_DIR)
      .replace('.flow.js', '.js'),
  );
}

function validateTypeScriptDefs(packageName /*: string */) {
  const files = globSync('**/*.d.ts', {
    cwd: path.resolve(PACKAGES_DIR, packageName, BUILD_DIR),
    absolute: true,
    onlyFiles: true,
  });
  const compilerOptions = {
    ...getTypeScriptCompilerOptions(packageName),
    noEmit: true,
    skipLibCheck: false,
  };
  const program = ts.createProgram(
    files,
    ts.convertCompilerOptionsFromJson(
      compilerOptions,
      path.resolve(PACKAGES_DIR, packageName),
    ),
  );
  const emitResult = program.emit();

  if (emitResult.diagnostics.length) {
    for (const diagnostic of emitResult.diagnostics) {
      if (diagnostic.file != null) {
        let {line, character} = ts.getLineAndCharacterOfPosition(
          diagnostic.file,
          diagnostic.start,
        );
        let message = ts.flattenDiagnosticMessageText(
          diagnostic.messageText,
          '\n',
        );
        console.log(
          // $FlowFixMe[incompatible-use] Type refined above
          `${diagnostic.file.fileName} (${line + 1},${
            character + 1
          }): ${message}`,
        );
      } else {
        console.log(
          ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
        );
      }
    }

    throw new Error(
      'Failing build because TypeScript errors were encountered for ' +
        'generated type definitions.',
    );
  }
}

module.exports = {
  buildFile,
  getBuildPath,
  BUILD_DIR,
  PACKAGES_DIR,
  SRC_DIR,
};

if (require.main === module) {
  build().catch(error => {
    if (error.name === 'ExpectedTranslationError') {
      console.error(error.message);
    } else {
      console.error(error.stack);
    }
    process.exitCode = 1;
  });
}