"use strict";
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsyncScope = void 0;
class AsyncScope {
    static scopes = new Set();
    static abortSignal;
    asyncStack = [];
    get descriptions() {
        return this.asyncStack.flatMap(({ description, messages }) => {
            const indentedMessages = messages.map(message => ` - ${message}`);
            return (description || indentedMessages.length > 0) ? [description ?? '[no description]', ...indentedMessages] :
                [];
        });
    }
    get stack() {
        if (this.asyncStack.length === 0) {
            return null;
        }
        return this.asyncStack[this.asyncStack.length - 1].frames;
    }
    push(description) {
        const stack = new Error().stack;
        if (!stack) {
            throw new Error('Could not get stack trace');
        }
        if (this.asyncStack.length === 0) {
            AsyncScope.scopes.add(this);
        }
        const frames = stack.split('\n').filter(value => !(value === 'Error' || value.includes('AsyncScope') || value.includes('runMicrotasks') ||
            value.includes('processTicksAndRejections')));
        const messages = [];
        this.asyncStack.push({ description, frames, messages });
        return messages;
    }
    pop() {
        this.asyncStack.pop();
        if (this.asyncStack.length === 0) {
            AsyncScope.scopes.delete(this);
        }
    }
    async exec(callable, description) {
        const messages = this.push(description);
        try {
            const result = await callable(messages);
            return result;
        }
        finally {
            this.pop();
        }
    }
}
exports.AsyncScope = AsyncScope;
//# sourceMappingURL=async-scope.js.map