"use strict";Object.defineProperty(exports, "__esModule", { value: true });exports.readBlob = exports.listBlobs = exports.writeBlob = void 0;var fs = _interopRequireWildcard(require("fs"));
var path = _interopRequireWildcard(require("path"));
var _util = require("util");

var _writeFileAtomic = _interopRequireDefault(require("write-file-atomic"));




var _utils = require("../utils");function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}function _interopRequireWildcard(obj) {if (obj && obj.__esModule) {return obj;} else {var newObj = {};if (obj != null) {for (var key in obj) {if (Object.prototype.hasOwnProperty.call(obj, key)) {var desc = Object.defineProperty && Object.getOwnPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : {};if (desc.get || desc.set) {Object.defineProperty(newObj, key, desc);} else {newObj[key] = obj[key];}}}}newObj.default = obj;return newObj;}}const readDir = (0, _util.promisify)(fs.readdir);const readFile = (0, _util.promisify)(fs.readFile);

const getBlobDir = appDir => path.join(appDir, 'blob');

const writeBlob = async (
appDir,
data,
ext) =>
{
  const hash = (0, _utils.sha256)(data);
  const blobDir = getBlobDir(appDir);
  const encoding = typeof data === 'string' ? 'utf-8' : undefined;
  return new Promise((resolve, reject) => {
    _writeFileAtomic.default.sync(path.join(blobDir, `${hash}${ext}`), data, {
      encoding });

    resolve(hash);
  });
};exports.writeBlob = writeBlob;

const listBlobs = async (appDir, ext) => {
  const blobDir = getBlobDir(appDir);
  const files = await readDir(blobDir);
  return files.
  filter(filename => filename.endsWith(ext)).
  map(filename => filename.replace(/\.[a-zA-Z0-9]+$/, ''));
};exports.listBlobs = listBlobs;

const readBlob = async (appDir, hash) => {
  const blobDir = getBlobDir(appDir);
  const paths = await readDir(blobDir);
  const filename = path.join(blobDir, paths.find(p => p.startsWith(hash)));
  const buf = await readFile(filename);
  if ((0, _utils.sha256)(buf) !== hash) {
    // FIXME
    // unlink
    // report error
    return;
  }
  return buf;
};exports.readBlob = readBlob;