"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.RegistryService = void 0;
const fs_1 = require("fs");
const inversify_1 = require("inversify");
const path_1 = __importDefault(require("path"));
const rimraf_1 = __importDefault(require("rimraf"));
const tar_1 = __importDefault(require("tar"));
const util_1 = require("util");
const config_js_1 = require("../../config.js");
const logger_js_1 = require("../../logger.js");
const extension_js_1 = require("../extension.js");
const api_request_js_1 = require("./api-request.js");
const rimrafAsync = (0, util_1.promisify)(rimraf_1.default);
const EXTENSIONS_DIR = (0, config_js_1.stringConfig)('EXTENSIONS_DIR', path_1.default.join(process.cwd(), '.tmp/extensions'));
let RegistryService = class RegistryService {
    constructor(config, api, logger) {
        this.config = config;
        this.api = api;
        this.logger = logger;
    }
    async listExtensions() {
        const res = await this.api.get('/ExtensionRegistry/list');
        return res.data;
    }
    async queryVersion(name, versionRange) {
        const res = await this.api.get('/ExtensionRegistry/queryVersion', {
            query: {
                name,
                versionRange,
            }
        });
        return res;
    }
    async loadExtension(name, versionRange) {
        return await this._loadExtensionWithRetry(name, versionRange, 3);
    }
    async _loadExtensionWithRetry(name, versionRange, attempts) {
        const { version } = await this.queryVersion(name, versionRange);
        const dir = this.getExtensionDir(name, version);
        const dirExists = await fs_1.promises.stat(dir).then(s => s.isDirectory()).catch(() => false);
        try {
            if (!dirExists) {
                await fs_1.promises.mkdir(dir, { recursive: true });
                const buffer = await this.loadExtensionBundle(name, version);
                const tarballFile = path_1.default.join(this.getExtensionsRoot(), `${name}@${version}.tar`);
                await fs_1.promises.mkdir(path_1.default.dirname(tarballFile), { recursive: true });
                await fs_1.promises.writeFile(tarballFile, buffer);
                await tar_1.default.x({
                    file: tarballFile,
                    cwd: dir,
                });
            }
            return await extension_js_1.Extension.load(dir);
        }
        catch (error) {
            if (attempts > 0) {
                this.logger.warn(`Failed to load extension ${name}, will keep trying`, {
                    error,
                    dir,
                    dirExists,
                });
                await rimrafAsync(dir).catch(() => { });
                return await this._loadExtensionWithRetry(name, versionRange, attempts - 1);
            }
            throw error;
        }
    }
    async loadExtensionBundle(name, version) {
        const res = await this.api.get('/ExtensionRegistry/loadBundle', {
            query: {
                name,
                version,
            }
        });
        return Buffer.from(res.tarballBase64, 'base64');
    }
    getExtensionsRoot() {
        return this.config.get(EXTENSIONS_DIR);
    }
    getExtensionDir(name, version) {
        return path_1.default.join(this.getExtensionsRoot(), name, version);
    }
};
RegistryService = __decorate([
    (0, inversify_1.injectable)(),
    __param(0, (0, inversify_1.inject)(config_js_1.Configuration)),
    __param(1, (0, inversify_1.inject)(api_request_js_1.ApiRequest)),
    __param(2, (0, inversify_1.inject)(logger_js_1.Logger)),
    __metadata("design:paramtypes", [config_js_1.Configuration,
        api_request_js_1.ApiRequest,
        logger_js_1.Logger])
], RegistryService);
exports.RegistryService = RegistryService;
//# sourceMappingURL=registry.js.map