"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.installBrowsersWithProgressBar = installBrowsersWithProgressBar;

var _fs = _interopRequireDefault(require("fs"));

var _path = _interopRequireDefault(require("path"));

var _properLockfile = _interopRequireDefault(require("proper-lockfile"));

var _registry = require("../utils/registry");

var browserFetcher = _interopRequireWildcard(require("./browserFetcher"));

var _utils = require("../utils/utils");

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * Copyright Microsoft Corporation. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const fsExistsAsync = filePath => _fs.default.promises.readFile(filePath).then(() => true).catch(e => false);

const PACKAGE_PATH = _path.default.join(__dirname, '..', '..');

async function installBrowsersWithProgressBar(browserNames = _registry.Registry.currentPackageRegistry().installByDefault()) {
  // PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD should have a value of 0 or 1
  if ((0, _utils.getAsBooleanFromENV)('PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD')) {
    browserFetcher.logPolitely('Skipping browsers download because `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` env variable is set');
    return false;
  }

  await _fs.default.promises.mkdir(_registry.registryDirectory, {
    recursive: true
  });

  const lockfilePath = _path.default.join(_registry.registryDirectory, '__dirlock');

  const releaseLock = await _properLockfile.default.lock(_registry.registryDirectory, {
    retries: {
      retries: 10,
      // Retry 20 times during 10 minutes with
      // exponential back-off.
      // See documentation at: https://www.npmjs.com/package/retry#retrytimeoutsoptions
      factor: 1.27579
    },
    onCompromised: err => {
      throw new Error(`${err.message} Path: ${lockfilePath}`);
    },
    lockfilePath
  });

  const linksDir = _path.default.join(_registry.registryDirectory, '.links');

  try {
    await _fs.default.promises.mkdir(linksDir, {
      recursive: true
    });
    await _fs.default.promises.writeFile(_path.default.join(linksDir, (0, _utils.calculateSha1)(PACKAGE_PATH)), PACKAGE_PATH);
    await validateCache(linksDir, browserNames);
  } finally {
    await releaseLock();
  }
}

async function validateCache(linksDir, browserNames) {
  // 1. Collect used downloads and package descriptors.
  const usedBrowserPaths = new Set();

  for (const fileName of await _fs.default.promises.readdir(linksDir)) {
    const linkPath = _path.default.join(linksDir, fileName);

    let linkTarget = '';

    try {
      linkTarget = (await _fs.default.promises.readFile(linkPath)).toString();
      const linkRegistry = new _registry.Registry(linkTarget);

      for (const browserName of _registry.allBrowserNames) {
        if (!linkRegistry.isSupportedBrowser(browserName)) continue;
        const usedBrowserPath = linkRegistry.browserDirectory(browserName);
        const browserRevision = linkRegistry.revision(browserName); // Old browser installations don't have marker file.

        const shouldHaveMarkerFile = browserName === 'chromium' && browserRevision >= 786218 || browserName === 'firefox' && browserRevision >= 1128 || browserName === 'webkit' && browserRevision >= 1307 || // All new applications have a marker file right away.
        browserName !== 'firefox' && browserName !== 'chromium' && browserName !== 'webkit';
        if (!shouldHaveMarkerFile || (await fsExistsAsync(markerFilePath(usedBrowserPath)))) usedBrowserPaths.add(usedBrowserPath);
      }
    } catch (e) {
      await _fs.default.promises.unlink(linkPath).catch(e => {});
    }
  } // 2. Delete all unused browsers.


  if (!(0, _utils.getAsBooleanFromENV)('PLAYWRIGHT_SKIP_BROWSER_GC')) {
    let downloadedBrowsers = (await _fs.default.promises.readdir(_registry.registryDirectory)).map(file => _path.default.join(_registry.registryDirectory, file));
    downloadedBrowsers = downloadedBrowsers.filter(file => (0, _registry.isBrowserDirectory)(file));
    const directories = new Set(downloadedBrowsers);

    for (const browserDirectory of usedBrowserPaths) directories.delete(browserDirectory);

    for (const directory of directories) browserFetcher.logPolitely('Removing unused browser at ' + directory);

    await (0, _utils.removeFolders)([...directories]);
  } // 3. Install missing browsers for this package.


  const myRegistry = _registry.Registry.currentPackageRegistry();

  for (const browserName of browserNames) {
    await browserFetcher.downloadBrowserWithProgressBar(myRegistry, browserName).catch(e => {
      throw new Error(`Failed to download ${browserName}, caused by\n${e.stack}`);
    });
    await _fs.default.promises.writeFile(markerFilePath(myRegistry.browserDirectory(browserName)), '');
  }
}

function markerFilePath(browserDirectory) {
  return _path.default.join(browserDirectory, 'INSTALLATION_COMPLETE');
}
//# sourceMappingURL=installer.js.map