Bundler.js.flow 1.74 KB
Newer Older
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
/**
 * Copyright (c) Facebook, Inc. and its 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
 */

'use strict';

const DependencyGraph = require('./node-haste/DependencyGraph');
const Transformer = require('./DeltaBundler/Transformer');

import type {TransformOptions} from './DeltaBundler/Worker';
import type {TransformResultWithSource} from './DeltaBundler';
import type {ConfigT} from 'metro-config/src/configTypes.flow';

export type BundlerOptions = $ReadOnly<{|
  watch?: boolean,
|}>;

class Bundler {
  _depGraphPromise: Promise<DependencyGraph>;
  _transformer: Transformer;

  constructor(config: ConfigT, options?: BundlerOptions) {
    this._depGraphPromise = DependencyGraph.load(config, options);

    this._depGraphPromise
      .then((dependencyGraph: DependencyGraph) => {
        this._transformer = new Transformer(
          config,
          dependencyGraph.getSha1.bind(dependencyGraph),
        );
      })
      .catch(error => {
        console.error('Failed to construct transformer: ', error);
      });
  }

  async end(): Promise<void> {
    const dependencyGraph = await this._depGraphPromise;

    this._transformer.end();
    dependencyGraph.getWatcher().end();
  }

  getDependencyGraph(): Promise<DependencyGraph> {
    return this._depGraphPromise;
  }

  async transformFile(
    filePath: string,
    transformOptions: TransformOptions,
  ): Promise<TransformResultWithSource<>> {
    // We need to be sure that the DependencyGraph has been initialized.
    // TODO: Remove this ugly hack!
    await this._depGraphPromise;

    return this._transformer.transformFile(filePath, transformOptions);
  }
}

module.exports = Bundler;