"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true,
});
exports.DiskCacheManager = void 0;
var _rootRelativeCacheKeys = _interopRequireDefault(
  require("../lib/rootRelativeCacheKeys")
);
var _gracefulFs = require("graceful-fs");
var _os = require("os");
var _path = _interopRequireDefault(require("path"));
var _v = require("v8");
function _interopRequireDefault(obj) {
  return obj && obj.__esModule ? obj : { default: obj };
}
const DEFAULT_PREFIX = "metro-file-map";
const DEFAULT_DIRECTORY = (0, _os.tmpdir)();
class DiskCacheManager {
  constructor({ buildParameters, cacheDirectory, cacheFilePrefix }) {
    this._cachePath = DiskCacheManager.getCacheFilePath(
      buildParameters,
      cacheFilePrefix,
      cacheDirectory
    );
  }
  static getCacheFilePath(buildParameters, cacheFilePrefix, cacheDirectory) {
    const { rootDirHash, relativeConfigHash } = (0,
    _rootRelativeCacheKeys.default)(buildParameters);
    return _path.default.join(
      cacheDirectory ?? DEFAULT_DIRECTORY,
      `${
        cacheFilePrefix ?? DEFAULT_PREFIX
      }-${rootDirHash}-${relativeConfigHash}`
    );
  }
  getCacheFilePath() {
    return this._cachePath;
  }
  async read() {
    try {
      return (0, _v.deserialize)(
        (0, _gracefulFs.readFileSync)(this._cachePath)
      );
    } catch (e) {
      if (e?.code === "ENOENT") {
        return null;
      }
      throw e;
    }
  }
  async write(dataSnapshot, { changed, removed }) {
    if (changed.size > 0 || removed.size > 0) {
      (0, _gracefulFs.writeFileSync)(
        this._cachePath,
        (0, _v.serialize)(dataSnapshot)
      );
    }
  }
}
exports.DiskCacheManager = DiskCacheManager;
