"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const debug_1 = require("debug");
const debug = debug_1.default('axm:profiling');
const module_1 = require("../utils/module");
const configuration_1 = require("../configuration");
class ProfilingHeapFallback {
    constructor() {
        this.MODULE_NAME = 'v8-profiler-node8';
        this.FALLBACK_MODULE_NAME = 'v8-profiler';
    }
    init() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            let path;
            let moduleName = this.MODULE_NAME;
            try {
                path = yield module_1.default.getModulePath(this.MODULE_NAME);
            }
            catch (e) {
                try {
                    moduleName = this.FALLBACK_MODULE_NAME;
                    path = yield module_1.default.getModulePath(this.FALLBACK_MODULE_NAME);
                }
                catch (err) {
                    configuration_1.default.configureModule({
                        heapdump: false
                    });
                    throw new Error('Profiler not loaded !');
                }
            }
            this.profiler = module_1.default.loadModule(path, moduleName);
            const enable = !(this.profiler instanceof Error);
            configuration_1.default.configureModule({
                heapdump: enable
            });
        });
    }
    destroy() {
        debug('Profiler destroyed !');
    }
    start() {
        this.snapshot = this.profiler.takeSnapshot('km-heap-snapshot');
    }
    stop() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            return this.getProfileInfo();
        });
    }
    takeSnapshot() {
        return tslib_1.__awaiter(this, void 0, void 0, function* () {
            this.start();
            return this.stop();
        });
    }
    getProfileInfo() {
        return new Promise(resolve => {
            let buffer = '';
            this.snapshot.serialize((data, length) => {
                buffer += data;
            }, () => {
                this.snapshot.delete();
                resolve(buffer);
            });
        }).then((buffer) => {
            return buffer;
        });
    }
}
exports.default = ProfilingHeapFallback;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicHJvZmlsaW5nSGVhcEZhbGxiYWNrLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3Byb2ZpbGluZy9wcm9maWxpbmdIZWFwRmFsbGJhY2sudHMiXSwibmFtZXMiOltdLCJtYXBwaW5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