{"size": 9635, "ext": "js", "max_stars_repo_path": "node_modules/pico-s3/dist/client.js", "max_stars_repo_name": "mdsid22/mdsid", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "node_modules/pico-s3/dist/client.js", "max_issues_repo_name": "mdsid22/mdsid", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "node_modules/pico-s3/dist/client.js", "max_forks_repo_name": "mdsid22/mdsid", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 49.9222797927, "max_line_length": 361, "alphanum_fraction": 0.634353918}
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getObjectEtag = exports.objectExists = exports.getObjectMetadata = exports.deleteObject = exports.getObject = exports.getObjectDataUrl = exports.getObjectBuffer = exports.getTextFile = exports.getObjectBinary = exports.upload = exports.s3Request = exports.getCloudUrl = exports.resolvePath = exports.CLOUD_PROVIDERS = exports.FileNotFoundError = void 0;
const axios_1 = __importDefault(require("axios"));
const aws4_1 = __importDefault(require("aws4"));
const db = require('debug')('pico-s3');
const err = require('debug')('pico-s3:error');
class FileNotFoundError extends Error {
    constructor(message) {
        super(message);
        this.name = "FileNotFoundError";
    }
}
exports.FileNotFoundError = FileNotFoundError;
var CLOUD_PROVIDERS;
(function (CLOUD_PROVIDERS) {
    CLOUD_PROVIDERS["GCP"] = "GCP";
    CLOUD_PROVIDERS["WASABI"] = "WASABI";
    CLOUD_PROVIDERS["AWS"] = "AWS";
})(CLOUD_PROVIDERS = exports.CLOUD_PROVIDERS || (exports.CLOUD_PROVIDERS = {}));
const resolvePath = (options) => {
    //remove leading and trailing slash from options.directory
    const directory = options.directory ? options.directory.replace(/^\/|\/$/g, "") : "";
    return options.directory ? `${directory}/${options.filename}` : `${options.filename}`;
};
exports.resolvePath = resolvePath;
/**
 * Please submit a new issue if you need another s3 compatible provider.
 */
const PROVIDERS = {
    "GCP": {
        host: ({ bucket }) => `${bucket}.storage.googleapis.com`,
        url: ({ bucket, filename, directory }) => `https://${bucket}.storage.googleapis.com/${exports.resolvePath({ filename, directory })}`,
        res: ({ bucket, filename, directory }) => `https://storage.cloud.google.com/${bucket}/${exports.resolvePath({ filename, directory })}`
    },
    "AWS": {
        host: ({ bucket }) => `${bucket}.s3.amazonaws.com`,
        url: ({ bucket, filename, directory }) => `https://${bucket}.s3.amazonaws.com/${exports.resolvePath({ filename, directory })}`,
        res: ({ bucket, filename, directory, region }) => `https://${bucket}.s3.${region}.amazonaws.com/${exports.resolvePath({ filename, directory })}`
    },
    "WASABI": {
        host: ({ region, bucket }) => `${bucket}.s3.${region}.wasabisys.com`,
        url: ({ region, filename, directory, bucket }) => `https://${bucket}.s3.${region}.wasabisys.com/${exports.resolvePath({ filename, directory })}`,
        res: ({ bucket, filename, directory, region }) => `https://s3.${region}.wasabisys.com/${bucket}/${exports.resolvePath({ filename, directory })}`
    }
};
const getCloudUrl = (options) => PROVIDERS[options.provider].res(options);
exports.getCloudUrl = getCloudUrl;
const s3Request = (options, extendedRequestOptions) => {
    const { provider, accessKeyId, secretAccessKey } = options;
    const region = provider === CLOUD_PROVIDERS.GCP ? 'region' : options.region;
    const _ = PROVIDERS[provider];
    if (!_)
        throw new Error(`Invalid provider ${provider}. Valid providers: ${Object.keys(PROVIDERS)}`);
    const headers = Object.assign(Object.assign({}, (extendedRequestOptions === null || extendedRequestOptions === void 0 ? void 0 : extendedRequestOptions.headers) || {}), { 'x-amz-content-sha256': 'UNSIGNED-PAYLOAD' });
    extendedRequestOptions === null || extendedRequestOptions === void 0 ? true : delete extendedRequestOptions.headers;
    return axios_1.default(aws4_1.default.sign(Object.assign({ host: _.host(options), url: _.url(options), service: 's3', region,
        headers }, extendedRequestOptions), {
        accessKeyId,
        secretAccessKey
    }));
};
exports.s3Request = s3Request;
const upload = (options) => __awaiter(void 0, void 0, void 0, function* () {
    const { provider, file } = options;
    const _ = PROVIDERS[provider];
    if (!file || file === null)
        throw new Error("File isnull or undefined");
    const path = `/${exports.resolvePath(options)}`;
    try {
        const START = Date.now();
        db(`Uploading ${path} to ${provider}`);
        yield exports.s3Request(options, {
            method: 'PUT',
            path,
            data: Buffer.from(file.split(',')[1], 'base64'),
            headers: {
                'Content-Type': (file.match(/[^:\s*]\w+\/[\w-+\d.]+(?=[;| ])/) || ["application/octet-stream"])[0],
            },
        });
        const END = Date.now() - START;
        db(`${path} uploaded  to ${provider} in ${END}ms`);
        return _.res(options) || "";
    }
    catch (error) {
        err("UPLOAD ERROR", path, provider, error.message);
        throw error;
    }
});
exports.upload = upload;
const getObjectBinary = (options) => __awaiter(void 0, void 0, void 0, function* () {
    const res = yield exports.getObject(options, {
        responseType: 'arraybuffer'
    });
    return res.data;
});
exports.getObjectBinary = getObjectBinary;
const getTextFile = (options) => __awaiter(void 0, void 0, void 0, function* () {
    const buff = yield exports.getObjectBuffer(options);
    return buff.toString();
});
exports.getTextFile = getTextFile;
const getObjectBuffer = (options) => __awaiter(void 0, void 0, void 0, function* () {
    const bin = yield exports.getObjectBinary(options);
    return Buffer.from(bin, 'binary');
});
exports.getObjectBuffer = getObjectBuffer;
const getObjectDataUrl = (options) => __awaiter(void 0, void 0, void 0, function* () {
    const res = yield exports.getObject(options, {
        responseType: 'arraybuffer'
    });
    const buff = Buffer.from(res.data, 'binary');
    const dUrl = `data:${res.headers['content-type']};base64,${buff.toString('base64')}`;
    return dUrl;
});
exports.getObjectDataUrl = getObjectDataUrl;
const getObject = (options, axiosOverride) => __awaiter(void 0, void 0, void 0, function* () {
    const { provider } = options;
    const path = `/${exports.resolvePath(options)}`;
    try {
        const START = Date.now();
        db(`Downloading ${path} from ${provider}`);
        const res = yield exports.s3Request(options, Object.assign({ method: 'GET', path }, (axiosOverride || {})));
        const END = Date.now() - START;
        db(`${path} downloaded from ${provider} in ${END}ms`);
        return res;
    }
    catch (error) {
        err("GET ERROR", path, provider, error.message);
        if ((error === null || error === void 0 ? void 0 : error.response.status) === 404)
            throw new FileNotFoundError(`File ${path} not found in ${provider}`);
        else
            throw error;
    }
});
exports.getObject = getObject;
const deleteObject = (options, axiosOverride) => __awaiter(void 0, void 0, void 0, function* () {
    const { provider } = options;
    const path = `/${exports.resolvePath(options)}`;
    try {
        const START = Date.now();
        db(`Deleting ${path} from ${provider}`);
        const res = yield exports.s3Request(options, Object.assign({ method: 'DELETE', path }, (axiosOverride || {})));
        const END = Date.now() - START;
        db(`${path} deleted from ${provider} in ${END}ms`);
        return res.status === 204;
    }
    catch (error) {
        err("GET ERROR", path, provider, error.message);
        if ((error === null || error === void 0 ? void 0 : error.response.status) === 404)
            throw new FileNotFoundError(`File ${path} not found in ${provider}`);
        else
            throw error;
    }
});
exports.deleteObject = deleteObject;
const getObjectMetadata = (options, axiosOverride) => __awaiter(void 0, void 0, void 0, function* () {
    const { provider } = options;
    const path = `/${exports.resolvePath(options)}`;
    try {
        const START = Date.now();
        db(`Getting Metadata for ${path} from ${provider}`);
        const res = yield exports.s3Request(options, Object.assign({ method: 'HEAD', path }, (axiosOverride || {})));
        const END = Date.now() - START;
        db(`${path} metadata downloaded from ${provider} in ${END}ms`);
        return res.headers;
    }
    catch (error) {
        err("GET ERROR", path, provider, error.message);
        if ((error === null || error === void 0 ? void 0 : error.response.status) === 404)
            throw new FileNotFoundError(`File ${path} not found in ${provider}`);
        else
            throw error;
    }
});
exports.getObjectMetadata = getObjectMetadata;
const objectExists = (options, axiosOverride) => __awaiter(void 0, void 0, void 0, function* () { return exports.getObjectMetadata(options, axiosOverride).then(res => !!res.etag); });
exports.objectExists = objectExists;
const getObjectEtag = (options, axiosOverride) => __awaiter(void 0, void 0, void 0, function* () { return exports.getObjectMetadata(options, axiosOverride).then(res => res.etag); });
exports.getObjectEtag = getObjectEtag;
