UNPKG

performance-monitor-logger

Version:

## Instalação

2,303 lines 115 kB
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common/http'), require('rxjs/operators')) :
    typeof define === 'function' && define.amd ? define('performance-monitor-logger', ['exports', '@angular/core', '@angular/common/http', 'rxjs/operators'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['performance-monitor-logger'] = {}, global.ng.core, global.ng.common.http, global.rxjs.operators));
}(this, (function (exports, i0, http, operators) { 'use strict';

    var PerformanceMonitorComponent = /** @class */ (function () {
        function PerformanceMonitorComponent() {
        }
        PerformanceMonitorComponent.prototype.ngOnInit = function () { };
        return PerformanceMonitorComponent;
    }());
    PerformanceMonitorComponent.decorators = [
        { type: i0.Component, args: [{
                    selector: 'lib-performanceMonitorLogger',
                    template: " <p>performance-monitor-logger works!</p> "
                },] }
    ];
    PerformanceMonitorComponent.ctorParameters = function () { return []; };

    // performance-monitor.module.ts
    var PerformanceMonitorModule = /** @class */ (function () {
        function PerformanceMonitorModule() {
        }
        return PerformanceMonitorModule;
    }());
    PerformanceMonitorModule.decorators = [
        { type: i0.NgModule, args: [{
                    declarations: [PerformanceMonitorComponent],
                    imports: [],
                    exports: [PerformanceMonitorComponent],
                },] }
    ];

    var PerformanceMonitorService = /** @class */ (function () {
        function PerformanceMonitorService() {
        }
        return PerformanceMonitorService;
    }());
    PerformanceMonitorService.ɵprov = i0.ɵɵdefineInjectable({ factory: function PerformanceMonitorService_Factory() { return new PerformanceMonitorService(); }, token: PerformanceMonitorService, providedIn: "root" });
    PerformanceMonitorService.decorators = [
        { type: i0.Injectable, args: [{
                    providedIn: 'root'
                },] }
    ];
    PerformanceMonitorService.ctorParameters = function () { return []; };

    /******************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b)
                if (Object.prototype.hasOwnProperty.call(b, p))
                    d[p] = b[p]; };
        return extendStatics(d, b);
    };
    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    var __assign = function () {
        __assign = Object.assign || function __assign(t) {
            for (var s, i = 1, n = arguments.length; i < n; i++) {
                s = arguments[i];
                for (var p in s)
                    if (Object.prototype.hasOwnProperty.call(s, p))
                        t[p] = s[p];
            }
            return t;
        };
        return __assign.apply(this, arguments);
    };
    function __rest(s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }
    function __decorate(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;
    }
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
        function accept(f) { if (f !== void 0 && typeof f !== "function")
            throw new TypeError("Function expected"); return f; }
        var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
        var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
        var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
        var _, done = false;
        for (var i = decorators.length - 1; i >= 0; i--) {
            var context = {};
            for (var p in contextIn)
                context[p] = p === "access" ? {} : contextIn[p];
            for (var p in contextIn.access)
                context.access[p] = contextIn.access[p];
            context.addInitializer = function (f) { if (done)
                throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
            var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
            if (kind === "accessor") {
                if (result === void 0)
                    continue;
                if (result === null || typeof result !== "object")
                    throw new TypeError("Object expected");
                if (_ = accept(result.get))
                    descriptor.get = _;
                if (_ = accept(result.set))
                    descriptor.set = _;
                if (_ = accept(result.init))
                    initializers.unshift(_);
            }
            else if (_ = accept(result)) {
                if (kind === "field")
                    initializers.unshift(_);
                else
                    descriptor[key] = _;
            }
        }
        if (target)
            Object.defineProperty(target, contextIn.name, descriptor);
        done = true;
    }
    ;
    function __runInitializers(thisArg, initializers, value) {
        var useValue = arguments.length > 2;
        for (var i = 0; i < initializers.length; i++) {
            value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
        }
        return useValue ? value : void 0;
    }
    ;
    function __propKey(x) {
        return typeof x === "symbol" ? x : "".concat(x);
    }
    ;
    function __setFunctionName(f, name, prefix) {
        if (typeof name === "symbol")
            name = name.description ? "[".concat(name.description, "]") : "";
        return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
    }
    ;
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    function __awaiter(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());
        });
    }
    function __generator(thisArg, body) {
        var _ = { label: 0, sent: function () { if (t[0] & 1)
                throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
        return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
        function verb(n) { return function (v) { return step([n, v]); }; }
        function step(op) {
            if (f)
                throw new TypeError("Generator is already executing.");
            while (g && (g = 0, op[0] && (_ = 0)), _)
                try {
                    if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
                        return t;
                    if (y = 0, t)
                        op = [op[0] & 2, t.value];
                    switch (op[0]) {
                        case 0:
                        case 1:
                            t = op;
                            break;
                        case 4:
                            _.label++;
                            return { value: op[1], done: false };
                        case 5:
                            _.label++;
                            y = op[1];
                            op = [0];
                            continue;
                        case 7:
                            op = _.ops.pop();
                            _.trys.pop();
                            continue;
                        default:
                            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                                _ = 0;
                                continue;
                            }
                            if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
                                _.label = op[1];
                                break;
                            }
                            if (op[0] === 6 && _.label < t[1]) {
                                _.label = t[1];
                                t = op;
                                break;
                            }
                            if (t && _.label < t[2]) {
                                _.label = t[2];
                                _.ops.push(op);
                                break;
                            }
                            if (t[2])
                                _.ops.pop();
                            _.trys.pop();
                            continue;
                    }
                    op = body.call(thisArg, _);
                }
                catch (e) {
                    op = [6, e];
                    y = 0;
                }
                finally {
                    f = t = 0;
                }
            if (op[0] & 5)
                throw op[1];
            return { value: op[0] ? op[1] : void 0, done: true };
        }
    }
    var __createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        var desc = Object.getOwnPropertyDescriptor(m, k);
        if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function () { return m[k]; } };
        }
        Object.defineProperty(o, k2, desc);
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                __createBinding(o, m, p);
    }
    function __values(o) {
        var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
        if (m)
            return m.call(o);
        if (o && typeof o.length === "number")
            return {
                next: function () {
                    if (o && i >= o.length)
                        o = void 0;
                    return { value: o && o[i++], done: !o };
                }
            };
        throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
    }
    function __read(o, n) {
        var m = typeof Symbol === "function" && o[Symbol.iterator];
        if (!m)
            return o;
        var i = m.call(o), r, ar = [], e;
        try {
            while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
                ar.push(r.value);
        }
        catch (error) {
            e = { error: error };
        }
        finally {
            try {
                if (r && !r.done && (m = i["return"]))
                    m.call(i);
            }
            finally {
                if (e)
                    throw e.error;
            }
        }
        return ar;
    }
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2)
            for (var i = 0, l = from.length, ar; i < l; i++) {
                if (ar || !(i in from)) {
                    if (!ar)
                        ar = Array.prototype.slice.call(from, 0, i);
                    ar[i] = from[i];
                }
            }
        return to.concat(ar || Array.prototype.slice.call(from));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
        function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
        function verb(n, f) { if (g[n]) {
            i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); };
            if (f)
                i[n] = f(i[n]);
        } }
        function resume(n, v) { try {
            step(g[n](v));
        }
        catch (e) {
            settle(q[0][3], e);
        } }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) { if (f(v), q.shift(), q.length)
            resume(q[0][0], q[0][1]); }
    }
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }
    }
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    var ownKeys = function (o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o)
                if (Object.prototype.hasOwnProperty.call(o, k))
                    ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k = ownKeys(mod), i = 0; i < k.length; i++)
                if (k[i] !== "default")
                    __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    }
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }
    function __classPrivateFieldIn(state, receiver) {
        if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function"))
            throw new TypeError("Cannot use 'in' operator on non-object");
        return typeof state === "function" ? receiver === state : state.has(receiver);
    }
    function __addDisposableResource(env, value, async) {
        if (value !== null && value !== void 0) {
            if (typeof value !== "object" && typeof value !== "function")
                throw new TypeError("Object expected.");
            var dispose, inner;
            if (async) {
                if (!Symbol.asyncDispose)
                    throw new TypeError("Symbol.asyncDispose is not defined.");
                dispose = value[Symbol.asyncDispose];
            }
            if (dispose === void 0) {
                if (!Symbol.dispose)
                    throw new TypeError("Symbol.dispose is not defined.");
                dispose = value[Symbol.dispose];
                if (async)
                    inner = dispose;
            }
            if (typeof dispose !== "function")
                throw new TypeError("Object not disposable.");
            if (inner)
                dispose = function () { try {
                    inner.call(this);
                }
                catch (e) {
                    return Promise.reject(e);
                } };
            env.stack.push({ value: value, dispose: dispose, async: async });
        }
        else if (async) {
            env.stack.push({ async: true });
        }
        return value;
    }
    var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
        var e = new Error(message);
        return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
    };
    function __disposeResources(env) {
        function fail(e) {
            env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
            env.hasError = true;
        }
        var r, s = 0;
        function next() {
            while (r = env.stack.pop()) {
                try {
                    if (!r.async && s === 1)
                        return s = 0, env.stack.push(r), Promise.resolve().then(next);
                    if (r.dispose) {
                        var result = r.dispose.call(r.value);
                        if (r.async)
                            return s |= 2, Promise.resolve(result).then(next, function (e) { fail(e); return next(); });
                    }
                    else
                        s |= 1;
                }
                catch (e) {
                    fail(e);
                }
            }
            if (s === 1)
                return env.hasError ? Promise.reject(env.error) : Promise.resolve();
            if (env.hasError)
                throw env.error;
        }
        return next();
    }
    function __rewriteRelativeImportExtension(path, preserveJsx) {
        if (typeof path === "string" && /^\.\.?\//.test(path)) {
            return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
                return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
            });
        }
        return path;
    }
    var tslib_es6 = {
        __extends: __extends,
        __assign: __assign,
        __rest: __rest,
        __decorate: __decorate,
        __param: __param,
        __esDecorate: __esDecorate,
        __runInitializers: __runInitializers,
        __propKey: __propKey,
        __setFunctionName: __setFunctionName,
        __metadata: __metadata,
        __awaiter: __awaiter,
        __generator: __generator,
        __createBinding: __createBinding,
        __exportStar: __exportStar,
        __values: __values,
        __read: __read,
        __spread: __spread,
        __spreadArrays: __spreadArrays,
        __spreadArray: __spreadArray,
        __await: __await,
        __asyncGenerator: __asyncGenerator,
        __asyncDelegator: __asyncDelegator,
        __asyncValues: __asyncValues,
        __makeTemplateObject: __makeTemplateObject,
        __importStar: __importStar,
        __importDefault: __importDefault,
        __classPrivateFieldGet: __classPrivateFieldGet,
        __classPrivateFieldSet: __classPrivateFieldSet,
        __classPrivateFieldIn: __classPrivateFieldIn,
        __addDisposableResource: __addDisposableResource,
        __disposeResources: __disposeResources,
        __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,
    };

    var LogsPerformatico = /** @class */ (function () {
        function LogsPerformatico(serviceName) {
            if (serviceName === void 0) { serviceName = 'Service'; }
            this.monitoramentoAtivo = true; // Começa ativo na primeira vez
            // 📊 Propriedades do Sistema
            this.performanceTimers = new Map();
            this.performanceSummary = new Map();
            this.httpRequests = new Map();
            // 🆕 Stack para contexto de função monitorada
            this.functionContextStack = [];
            this.eventContextStack = [];
            this.timerStack = [];
            // 🆕 Estado de atividade para fechamento inteligente de contexto de UI
            this.lastTimerActivityAt = null;
            this.firstTimerInEventAt = null;
            this.currentEventBeginAt = null;
            // 🔒 Controle de funções já instrumentadas
            this.instrumentedFns = new WeakMap();
            this.serviceName = serviceName;
        }
        /**
         * Registra requisição HTTP associando à função monitorada ativa (se houver)
         * @param payload Dados da requisição
         */
        LogsPerformatico.prototype.registerHttpRequest = function (authReq, tempo, error) {
            if (error === void 0) { error = false; }
            var _a, _b;
            // Nome robusto da operação HTTP
            var nome = '(desconhecido)';
            try {
                var byBodyName = (_a = authReq === null || authReq === void 0 ? void 0 : authReq.body) === null || _a === void 0 ? void 0 : _a.name;
                var bySql = this.extrairNomeDeSQL((_b = authReq === null || authReq === void 0 ? void 0 : authReq.body) === null || _b === void 0 ? void 0 : _b.sqlInstruction);
                var method = (authReq === null || authReq === void 0 ? void 0 : authReq.method) || 'HTTP';
                var url = authReq === null || authReq === void 0 ? void 0 : authReq.url;
                // Usa nome planejado (body/sql), senão fallback para método + último segmento da URL
                if (byBodyName) {
                    nome = byBodyName;
                }
                else if (bySql) {
                    nome = bySql;
                }
                else if (url) {
                    var cleanUrl = String(url).split('?')[0];
                    var segs = cleanUrl.split('/').filter(Boolean);
                    var tail = segs[segs.length - 1] || cleanUrl;
                    nome = method + " " + tail;
                }
                else {
                    nome = method;
                }
            }
            catch (_c) { }
            var currentEvent = this.eventContextStack.length
                ? this.eventContextStack[this.eventContextStack.length - 1]
                : undefined;
            var key = currentEvent ? currentEvent + " | " + nome : nome;
            var atual = this.httpRequests.get(key) || {
                tempoTotal: 0,
                execucoes: 0,
                errors: 0,
            };
            atual.tempoTotal += Number.isFinite(tempo) ? tempo : 0;
            atual.execucoes += 1;
            if (error)
                atual.errors += 1;
            this.httpRequests.set(key, atual);
        };
        // Função auxiliar para extrair nome da função de um SQL, ex: PACK_PARMGEN.CONSULTA_PARAMETRO(...)
        LogsPerformatico.prototype.extrairNomeDeSQL = function (sql) {
            if (!sql)
                return null;
            var match = sql.match(/([A-Z0-9_]+\.[A-Z0-9_]+)/i);
            return match ? match[1] : null;
        };
        /**
         * 🚀 Mensagem de boas-vindas do sistema
         */
        LogsPerformatico.prototype.showWelcomeMessage = function () {
            console.log("%cSISTEMA DE MONITORAMENTO DE PERFORMANCE", 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
        };
        /**
         * ⏱️ Inicia cronômetro para uma operação
         * @param operationName Nome da operação a ser monitorada
         */
        LogsPerformatico.prototype.startTimer = function (operationName) {
            if (!this.monitoramentoAtivo)
                return;
            // Se for a primeira operação, abre borda visual
            if (this.performanceTimers.size === 0 &&
                this.performanceSummary.size === 0) {
                var border = '═'.repeat(56);
                console.log("%cIN\u00CDCIO DO MONITORAMENTO DE PERFORMANCE", 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
            }
            this.performanceTimers.set(operationName, Date.now());
            // Empilha contexto de função monitorada
            this.functionContextStack.push(operationName);
            // Adiciona contexto ao stack para medir tempo exclusivo
            var currentEvent = this.eventContextStack.length
                ? this.eventContextStack[0] // usa rótulo raiz do fluxo do usuário
                : undefined;
            // Se a operação vier como pack.metodo, usamos pack como evento e metodo como nome
            var parts = String(operationName).split('.');
            var displayEvent;
            var displayName;
            if (parts.length >= 2) {
                displayEvent = parts[0];
                displayName = parts[parts.length - 1];
            }
            else {
                // Sem prefixo (pack) no nome — exibe apenas o método
                displayEvent = undefined;
                displayName = operationName;
            }
            var fullName = displayEvent
                ? displayEvent + " | " + displayName
                : displayName;
            // Registra atividade de timer para controle de janela do evento
            var nowStart = Date.now();
            if (currentEvent && this.firstTimerInEventAt === null) {
                this.firstTimerInEventAt = nowStart;
            }
            this.lastTimerActivityAt = nowStart;
            this.timerStack.push({
                name: operationName,
                start: nowStart,
                childElapsed: 0,
                event: currentEvent,
                fullName: fullName,
            });
            console.log("\u2551 [IN\u00CDCIO] " + fullName + " - " + new Date().toLocaleTimeString());
        };
        /**
         * 🏁 Finaliza cronômetro e exibe resultado com emoji
         * @param operationName Nome da operação
         * @param customMessage Mensagem customizada opcional (ex: para erros)
         * @param customThresholds Thresholds customizados para esta operação específica
         */
        LogsPerformatico.prototype.endTimer = function (operationName, customMessage, customThresholds) {
            var _a, _b, _c, _d, _e, _f;
            if (!this.monitoramentoAtivo)
                return;
            // Usa pilha de contexto para calcular tempo exclusivo (exclui filhos)
            var now = Date.now();
            var ctx = this.timerStack.length
                ? this.timerStack[this.timerStack.length - 1]
                : undefined;
            if (!ctx || ctx.name !== operationName) {
                // Busca robusta caso encerramento fora de ordem
                var foundIndex = -1;
                for (var i = this.timerStack.length - 1; i >= 0; i--) {
                    if (this.timerStack[i].name === operationName) {
                        foundIndex = i;
                        break;
                    }
                }
                if (foundIndex === -1) {
                    console.warn("\u26A0\uFE0F Timer n\u00E3o encontrado para: " + operationName);
                    return;
                }
                ctx = this.timerStack[foundIndex];
                this.timerStack.splice(foundIndex, 1);
            }
            else {
                this.timerStack.pop();
            }
            // Atualiza atividade de timers (para lógica de fechamento por silêncio)
            this.lastTimerActivityAt = now;
            var inclusiveElapsed = now - ctx.start;
            var exclusiveElapsed = Math.max(0, inclusiveElapsed - ctx.childElapsed);
            // Propaga tempo do filho para o pai (para excluir na contagem do pai)
            var parent = this.timerStack[this.timerStack.length - 1];
            if (parent) {
                parent.childElapsed += inclusiveElapsed;
            }
            // Remove referência antiga baseada em Map (mantida para compatibilidade)
            this.performanceTimers.delete(operationName);
            // Desempilha contexto de função monitorada (somente se topo)
            if (this.functionContextStack[this.functionContextStack.length - 1] ===
                operationName) {
                this.functionContextStack.pop();
            }
            // Determina status baseado no tempo exclusivo
            var _g = this.getPerformanceStatus(exclusiveElapsed, customThresholds, (_a = ctx.fullName) !== null && _a !== void 0 ? _a : (ctx.event ? ctx.event + " | " + operationName : operationName)), emoji = _g.emoji, status = _g.status, color = _g.color;
            // Log com emoji e cor (com mensagem customizada se fornecida)
            var message = customMessage
                ? ((_b = ctx.fullName) !== null && _b !== void 0 ? _b : (ctx.event ? ctx.event + " | " + operationName : operationName)) + " - " + customMessage
                : "" + ((_c = ctx.fullName) !== null && _c !== void 0 ? _c : (ctx.event ? ctx.event + " | " + operationName : operationName));
            var fixedStatus = ("[" + status + "]").padEnd(5);
            var fixedMessage = message.padEnd(10);
            var fixedTime = exclusiveElapsed.toString().padStart(5);
            console.log("\u2551 %c" + emoji + " " + fixedStatus + " " + fixedMessage + " - " + fixedTime + "ms ", color);
            // Mostra thresholds customizados se estiverem sendo usados
            if (customThresholds &&
                (customThresholds.ok ||
                    customThresholds.lento ||
                    customThresholds.critico)) {
                console.log("\u2699\uFE0F Thresholds customizados: OK<" + ((_d = customThresholds.ok) !== null && _d !== void 0 ? _d : 500) + "ms, LENTO<" + ((_e = customThresholds.lento) !== null && _e !== void 0 ? _e : 2000) + "ms");
            }
            // Atualiza sumário com tempo exclusivo
            this.updatePerformanceSummary((_f = ctx.fullName) !== null && _f !== void 0 ? _f : (ctx.event ? ctx.event + " | " + operationName : operationName), exclusiveElapsed, customThresholds);
        };
        /**
         * 🎨 Determina status de performance baseado no tempo
         * @param elapsedTime Tempo decorrido em milissegundos
         * @param customThresholds Thresholds customizados para esta operação específica
         * @param operationName Nome da operação (para calcular thresholds dinâmicos)
         * @returns Objeto com emoji, status e cor
         */
        LogsPerformatico.prototype.getPerformanceStatus = function (elapsedTime, customThresholds, operationName) {
            var _a, _b, _c;
            var okThreshold;
            var lentoThreshold;
            var criticoThreshold;
            if (customThresholds &&
                (customThresholds.ok ||
                    customThresholds.lento ||
                    customThresholds.critico)) {
                // Usa thresholds customizados se fornecidos
                okThreshold = (_a = customThresholds.ok) !== null && _a !== void 0 ? _a : 500;
                lentoThreshold = (_b = customThresholds.lento) !== null && _b !== void 0 ? _b : 2000;
                criticoThreshold = (_c = customThresholds.critico) !== null && _c !== void 0 ? _c : Number.MAX_SAFE_INTEGER;
            }
            else if (operationName) {
                // Calcula thresholds dinâmicos baseados na quantidade de execuções
                var stats = this.performanceSummary.get(operationName);
                // Corrige: soma +1 para considerar a execução atual
                var executionCount = stats ? stats.count + 1 : 1;
                var dynamicThresholds = this.calculateDynamicThresholds(executionCount);
                okThreshold = dynamicThresholds.ok;
                lentoThreshold = dynamicThresholds.lento;
                criticoThreshold = dynamicThresholds.critico;
            }
            else {
                // Usa thresholds padrões
                okThreshold = 500;
                lentoThreshold = 2000;
                criticoThreshold = Number.MAX_SAFE_INTEGER;
            }
            if (elapsedTime < okThreshold) {
                return {
                    emoji: '🟢',
                    status: 'OK',
                    color: 'color: green; font-weight: bold;',
                };
            }
            else if (elapsedTime < lentoThreshold) {
                return {
                    emoji: '🟡',
                    status: 'LENTO',
                    color: 'color: orange; font-weight: bold;',
                };
            }
            else {
                return {
                    emoji: '🔴',
                    status: 'CRÍTICO',
                    color: 'color: red; font-weight: bold;',
                };
            }
        };
        /**
         * 📈 Atualiza estatísticas de performance para o sumário
         * @param operationName Nome da operação
         * @param elapsedTime Tempo decorrido em milissegundos
         * @param customThresholds Thresholds customizados para armazenar (opcional)
         */
        LogsPerformatico.prototype.updatePerformanceSummary = function (operationName, elapsedTime, customThresholds) {
            var existing = this.performanceSummary.get(operationName);
            if (existing) {
                existing.count++;
                existing.totalTime += elapsedTime;
                existing.minTime = Math.min(existing.minTime, elapsedTime);
                existing.maxTime = Math.max(existing.maxTime, elapsedTime);
                // Atualiza thresholds customizados se fornecidos
                if (customThresholds &&
                    (customThresholds.ok ||
                        customThresholds.lento ||
                        customThresholds.critico)) {
                    existing.customThresholds = customThresholds;
                }
            }
            else {
                this.performanceSummary.set(operationName, {
                    count: 1,
                    totalTime: elapsedTime,
                    minTime: elapsedTime,
                    maxTime: elapsedTime,
                    customThresholds: customThresholds,
                });
            }
            // Não faz mais nada aqui, relatório só manual
        };
        /**
         * 📊 Exibe relatório resumido de todas as operações (compactado)
         */
        LogsPerformatico.prototype.showPerformanceSummary = function (showFullDetails) {
            var _this = this;
            if (showFullDetails === void 0) { showFullDetails = false; }
            // Fecha borda do monitoramento ao gerar relatório
            console.log('%c RELATÓRIO DE PERFORMANCE', 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
            if (this.performanceSummary.size === 0) {
                console.log('%c Nenhuma operação monitorada ainda.', 'color: gray; font-style: italic;');
                return;
            }
            var sortedEntries = Array.from(this.performanceSummary.entries()).sort(function (a, b) { return b[1].maxTime - a[1].maxTime; });
            var table = Object.fromEntries(sortedEntries.map(function (_g) {
                var _h = __read(_g, 2), operation = _h[0], stats = _h[1];
                var avgTime = Math.round(stats.totalTime / stats.count);
                var _j = _this.getPerformanceStatus(avgTime, stats.customThresholds, operation), emoji = _j.emoji, status = _j.status;
                return [
                    operation,
                    {
                        Execuções: stats.count,
                        'Média(ms)': (avgTime + "ms (" + status + ") " + emoji).trim(),
                        'Mínimo(ms)': stats.minTime,
                        'Máximo(ms)': stats.maxTime,
                        'Total(ms)': stats.totalTime,
                    },
                ];
            }));
            console.table(table);
            // Removido: agora a análise detalhada é chamada apenas pelo botão
        };
        /**
         * 📑 Exibe relatório detalhado de requisições HTTP agrupadas por função
         */
        LogsPerformatico.prototype.showHttpRequestsReport = function () {
            console.log("%cRELAT\u00D3RIO DETALHADO DE REQUISI\u00C7\u00D5ES HTTP", 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
            if (this.httpRequests.size === 0) {
                console.log('Nenhuma requisição HTTP registrada.');
                return;
            }
            var tabela = Object.fromEntries(Array.from(this.httpRequests.entries())
                .sort(function (a, b) { return b[1].tempoTotal - a[1].tempoTotal; })
                .map(function (_g) {
                var _h = __read(_g, 2), nome = _h[0], dados = _h[1];
                return [
                    nome,
                    {
                        Execuções: dados.execucoes,
                        Média: Math.round(dados.tempoTotal / dados.execucoes) + "ms",
                        'Tempo Total': Math.round(dados.tempoTotal) + "ms",
                        Erros: dados.errors,
                    },
                ];
            }));
            console.table(tabela);
        };
        /**
         * 🔍 Gera análise detalhada de performance
         */
        LogsPerformatico.prototype.generateDetailedAnalysis = function () {
            var _this = this;
            // Título discreto
            console.log('%cANÁLISE DETALHADA DE PERFORMANCE', 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
            console.log('');
            if (this.performanceSummary.size === 0) {
                console.log('%cNenhuma operação registrada para análise.', 'color: #bbb; font-style: italic; font-size: 14px; padding: 4px 0 4px 10px;');
                return;
            }
            var _g = this.categorizeOperations(), criticalOperations = _g.criticalOperations, slowOperations = _g.slowOperations, fastOperations = _g.fastOperations;
            // Helper para bloco discreto com texto claro
            var printBlock = function (color, emoji, operation, avg, extra) {
                var style = "border-left: 4px solid " + color + "; padding: 2px 0 2px 10px; margin: 2px 0 2px 0; font-size: 14px; color: #fff; background: none; font-weight: normal;";
                console.log(("%c" + emoji + " " + operation + "  -  " + avg + "ms (m\u00E9dia)  " + extra).trim(), style);
            };
            if (criticalOperations.length > 0) {
                console.log('%c🔴 CRÍTICAS ( > 2000ms)', 'color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;');
                criticalOperations.forEach(function (_g) {
                    var _h = __read(_g, 2), operation = _h[0], stats = _h[1];
                    var avg = Math.round(stats.totalTime / stats.count);
                    var emoji = _this.getPerformanceStatus(avg, stats.customThresholds, operation).emoji;
                    printBlock('#c53030', emoji, operation, avg, '| otimizar urgente');
                });
            }
            if (slowOperations.length > 0) {
                console.log('%c🟡 LENTAS (500ms - 2000ms)', 'color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;');
                slowOperations.forEach(function (_g) {
                    var _h = __read(_g, 2), operation = _h[0], stats = _h[1];
                    var avg = Math.round(stats.totalTime / stats.count);
                    var emoji = _this.getPerformanceStatus(avg, stats.customThresholds, operation).emoji;
                    printBlock('#b7791f', emoji, operation, avg, '| pode ser melhorada');
                });
            }
            if (fastOperations.length > 0) {
                console.log('%c🟢 RÁPIDAS ( < 500ms)', 'color: #fff; font-size: 14px; font-weight: bold; margin-top: 10px;');
                fastOperations.forEach(function (_g) {
                    var _h = __read(_g, 2), operation = _h[0], stats = _h[1];
                    var avg = Math.round(stats.totalTime / stats.count);
                    var emoji = _this.getPerformanceStatus(avg, stats.customThresholds, operation).emoji;
                    printBlock('#38a169', emoji, operation, avg, '| excelente');
                });
            }
            // Recomendações
            console.log('%cRecomendações:', 'color: #fff; font-size: 13px; font-weight: bold; margin-top: 14px; padding: 2px 0 2px 0;');
            if (criticalOperations.length > 0) {
                console.log('%c• Priorize a otimização das operações críticas.', 'color: #fff; font-size: 13px; font-weight: normal;');
                console.log('%c• Considere implementar cache ou otimizar consultas SQL para essas operações.', 'color: #fff; font-size: 13px; font-weight: normal;');
            }
            if (slowOperations.length > 0) {
                console.log('%c• Operações lentas podem se beneficiar de índices no banco de dados.', 'color: #fff; font-size: 13px; font-weight: normal;');
            }
            if (criticalOperations.length === 0 && slowOperations.length === 0) {
                console.log('%c• Todas as operações estão com performance excelente!', 'color: #fff; font-size: 13px; font-weight: normal;');
            }
            // Score
            var totalOperations = this.performanceSummary.size;
            var fastCount = fastOperations.length;
            var performanceScore = totalOperations > 0
                ? Math.round((fastCount / totalOperations) * 100)
                : 100;
            var scoreColor = performanceScore >= 80
                ? '#38a169'
                : performanceScore >= 60
                    ? '#f6e05e'
                    : '#c53030';
            var scoreMsg = performanceScore >= 80
                ? 'Excelente! A maioria das operações está performando bem.'
                : performanceScore >= 60
                    ? 'Médio. Há espaço para melhorias de performance.'
                    : 'Crítico. Muitas operações precisam de otimização urgente.';
            console.log("%cScore de performance: " + performanceScore + "%", "color: #fff; background: " + scoreColor + "; font-size: 14px; font-weight: bold; margin-top: 10px; padding: 2px 8px; border-radius: 3px;");
            console.log("%c" + scoreMsg, "color: #fff; font-size: 13px; font-weight: normal; margin-bottom: 8px;");
            console.log('');
        };
        /**
         * 📋 Categoriza operações por performance
         * @returns Objeto com arrays de operações categorizadas
         */
        LogsPerformatico.prototype.categorizeOperations = function () {
            var criticalOperations = Array.from(this.performanceSummary.entries()).filter(function (_g) {
                var _h = __read(_g, 2), _ = _h[0], stats = _h[1];
                return stats.totalTime / stats.count > 2000;
            });
            var slowOperations = Array.from(this.performanceSummary.entries()).filter(function (_g) {
                var _h = __read(_g, 2), _ = _h[0], stats = _h[1];
                var avg = stats.totalTime / stats.count;
                return avg >= 500 && avg <= 2000;
            });
            var fastOperations = Array.from(this.performanceSummary.entries()).filter(function (_g) {
                var _h = __read(_g, 2), _ = _h[0], stats = _h[1];
                return stats.totalTime / stats.count < 500;
            });
            return { criticalOperations: criticalOperations, slowOperations: slowOperations, fastOperations: fastOperations };
        };
        /**
         * 💡 Exibe recomendações baseadas na análise
         * @param criticalOperations Array de operações críticas
         * @param slowOperations Array de operações lentas
         */
        LogsPerformatico.prototype.showRecommendations = function (criticalOperations, slowOperations) {
            console.log('RECOMENDAÇÕES:');
            if (criticalOperations.length > 0) {
                console.log('   Priorize a otimização das operações críticas.');
                console.log('   Considere implementar cache ou otimizar consultas SQL para essas operações.');
            }
            if (slowOperations.length > 0) {
                console.log('   Operações lentas podem se beneficiar de índices no banco de dados.');
            }
            if (criticalOperations.length === 0 && slowOperations.length === 0) {
                console.log('   Todas as operações estão com performance excelente!');
            }
        };
        /**
         * 📊 Exibe score de performance
         * @param fastOperationsCount Número de operações rápidas
         */
        LogsPerformatico.prototype.showPerformanceScore = function (fastOperationsCount) {
            var totalOperations = this.performanceSummary.size;
            var performanceScore = Math.round((fastOperationsCount / totalOperations) * 100);
            console.log("SCORE DE PERFORMANCE: " + performanceScore + "%");
            if (performanceScore >= 80) {
                console.log('Excelente! A maioria das operações está performando bem.');
            }
            else if (performanceScore >= 60) {
                console.log('Médio. Há espaço para melhorias de performance.');
            }
            else {
                console.log('Crítico. Muitas operações precisam de otimização urgente.');
            }
        };
        // ===== API PÚBLICA =====
        /**
         * 📊 Método público para exibir relatório de performance
         * Pode ser chamado no console do navegador para análise
         */
        LogsPerformatico.prototype.getPerformanceReport = function () {
            this.showPerformanceSummary();
        };
        /**
         * 🏷️ Controla contexto de evento atual (ex.: AppInit, Click)
         */
        LogsPerformatico.prototype.beginEventContext = function (label) {
            if (label) {
                // Se não há contexto aberto, inicia uma nova janela raiz
                if (this.eventContextStack.length === 0) {
                    this.currentEventBeginAt = Date.now();
                    this.firstTimerInEventAt = null;
                    this.lastTimerActivityAt = null;
                }
                this.eventContextStack.push(label);
            }
        };
        LogsPerformatico.prototype.endEventContext = function () {
            if (this.eventContextStack.length > 0) {
                this.eventContextStack.pop();
            }
        };
        LogsPerformatico.prototype.runInEventContext = function (label, fn) {
            return __awaiter(this, void 0, void 0, function () {
                var result;
                return __generator(this, function (_g) {
                    switch (_g.label) {
                        case 0:
                            this.beginEventContext(label);
                            _g.label = 1;
                        case 1:
                            _g.trys.push([1, , 3, 4]);
                            result = fn();
                            return [4 /*yield*/, Promise.resolve(result)];
                        case 2: return [2 /*return*/, _g.sent()];
                        case 3:
                            this.endEventContext();
                            return [7 /*endfinally*/];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        };
        /**
         * 🧹 Método público para limpar dados de performance
         * Útil para resetar estatísticas e começar nova análise
         */
        LogsPerformatico.prototype.resetPerformanceData = function () {
            this.performanceTimers.clear();
            this.performanceSummary.clear();
            this.httpRequests.clear();
            // Mensagem estilizada de limpeza
            console.log('%c🧹 [CLEANUP] Dados de performance limpos', 'color: #fff; background: #43248bff; font-size: 13px; font-weight: bold; border-radius: 4px; padding: 4px 12px; margin: 6px 0;');
        };
        /**
         * ⏰ Configura o delay para relatório por inatividade
         * @param seconds Número de segundos de inatividade para mostrar relatório
         */
        LogsPerformatico.prototype.setInactivityDelay = function (seconds) {
            // Desabilitado
            console.log('⏰ Relatório por inatividade está desabilitado.');
        };
        /**
         * 🔇 Desabilita relatório automático por inatividade
         */
        LogsPerformatico.prototype.disableInactivityReport = function () {
            // Desabilitado
            console.log('🔇 Relatório por inatividade já está desabilitado');
        };
        /**
         * ⚙️ Configura o threshold para relatório automático
         * @param threshold Número de operações para mostrar relatório automaticamente
         */
        LogsPerformatico.prototype.setAutoReportThreshold = function (threshold) {
            // Desabilitado
            console.log('⚙️ Threshold para relatório automático está desabilitado.');
        };
        /**
         * 🔇 Desabilita relatório automático
         */
        LogsPerformatico.prototype.disableAutoReport = function () {
            // Desabilitado
            console.log('🔇 Relatório automático desabilitado');
        };
        /**
         * 📈 Obtém estatísticas resumidas sem exibir no console
         * @returns Objeto com estatísticas de performance
         */
        LogsPerformatico.prototype.getStatistics = function () {
            var _g = this.categorizeOperations(), criticalOperations = _g.criticalOperations, slowOperations = _g.slowOperations, fastOperations = _g.fastOperations;
            var totalOperations = this.performanceSummary.size;
            var totalTime = 0;
            var totalCount = 0;
            this.performanceSummary.forEach(function (stats) {
                totalTime += stats.totalTime;
                totalCount += stats.count;
            });
            var averageTime = totalCount > 0 ? Math.round(totalTime / totalCount) : 0;
            var performanceScore = totalOperations > 0
                ? Math.round((fastOperations.length / totalOperations) * 100)
                : 100;
            return {
                totalOperations: totalOperations,
                averageTime: averageTime,
                fastOperations: fastOperations.length,
                slowOperations: slowOperations.length,
                criticalOperations: criticalOperations.length,
                performanceScore: performanceScore,
            };
        };
        /**
         * 🎯 Obtém dados de uma operação específica
         * @param operationName Nome da operação
         * @returns Estatísticas da operação ou null se não encontrada
         */
        LogsPerformatico.prototype.getOperationStats = function (operationName) {
            var baseStats = this.performanceSummary.get(operationName);
            if (!baseStats)
                return null;
            // Extrai nomes das requisições HTTP como array de strings
            var httpRequestEntry = this.httpRequests.get(operationName);
            var httpCalls = httpRequestEntry ? [operationName] : [];
            return Object.assign(Object.assign({}, baseStats), { httpCalls: httpCalls });
        };
        /**
         * 📋 Lista todas as operações monitoradas
         * @returns Array com nomes das operações
         */
        LogsPerformatico.prototype.getMonitoredOperations = function () {
            return Array.from(this.performanceSummary.keys());
        };
        /**
         * 🔄 Verifica se há timers ativos
         * @returns true se há timers em execução
         */
        LogsPerformatico.prototype.hasActiveTimers = function () {
            return this.timerStack.length > 0;
        };
        /**
         * 🗑️ Limpa apenas os timers ativos (não as estatísticas)
         */
        LogsPerformatico.prototype.clearActiveTimers = function () {
            this.performanceTimers.clear();
            this.timerStack = [];
            this.functionContextStack = [];
            console.log('%c🗑️ [CLEANUP] Timers ativos limpos', 'color: #fff; background: #23272f; font-size: 13px; font-weight: bold; border-radius: 4px; padding: 4px 12px; margin: 6px 0;');
        };
        // ===== AUTO‑INSTRUMENTAÇÃO (sem decorators) =====
        /**
         * 🔌 Instrumenta todas as funções públicas de um objeto/instância sem alterar assinatura
         * @param obj Objeto ou instância a instrumentar
         * @param options Filtros e ajustes de nome
         */
        LogsPerformatico.prototype.instrumentObject = function (obj, options) {
            var _this = this;
            if (!obj || typeof obj !== 'object')
                return;
            var opt = Object.assign({ preserveToString: true }, options);
            var shouldInclude = function (name) {
                var inc = opt.include;
                var exc = opt.exclude;
                var match = function (p) { return typeof p === 'string' ? name.includes(p) : p.test(name); };
                var okInc = !inc || inc.some(match);
                var okExc = exc ? !exc.some(match) : true;
                return okInc && okExc;
            };
            var instrumentProp = function (target, key, path) {
                try {
                    var value = target[key];
                    if (typeof value !== 'function')
                        return;
                    var original = value;
                    if (original.__pm_instrumented)
                        return;
                    if (!shouldInclude(key))
                        return;
                    var opBase = key;
                    var opName = opt.nameTransform
                        ? opt.nameTransform(opBase, path)
                        : opBase;
                    var wrapped = _this.createWrapper(original, opName, opt.preserveToString);
                    // Sombra no objeto (não altera prototype global)
                    Object.defineProperty(target, key, {
                        value: wrapped,
                        writable: true,
                        configurable: true,
                    });
                }
                catch (_a) { }
            };
            // Instrumenta próprias propriedades
            Object.getOwnPropertyNames(obj).forEach(function (k) { return instrumentProp(obj, k, [k]); });
            // Instrumenta métodos do prototype (sobrescrevendo no instance)
            var proto = Object.getPrototypeOf(obj);
            if (proto && proto !== Object.prototype) {
                Object.getOwnPropertyNames(proto)
                    .filter(function (k) { return k !== 'constructor'; })
                    .forEach(function (k) { return instrumentProp(obj, k, [k]); });
            }
        };
        /**
         * 🌐 Instrumenta funções em um namespace (ex.: window) com filtros e profundidade
         * @param root Objeto raiz (ex.: window)
         * @param options include/exclude, nameTransform, preserveToString, maxDepth
         */
        LogsPerformatico.prototype.instrumentNamespace = function (root, options) {
            var _this = this;
            if (!root || typeof root !== 'object')
                return;
            var opt = Object.assign({ preserveToString: true, maxDepth: 2 }, options);
            var shouldInclude = function (name) {
                var inc = opt.include;
                var exc = opt.exclude;
                var match = function (p) { return typeof p === 'string' ? name.includes(p) : p.test(name); };
                var okInc = !inc || inc.some(match);
                var okExc = exc ? !exc.some(match) : true;
                return okInc && okExc;
            };
            var visited = new WeakSet();
            var walk = function (node, depth, path) {
                var e_1, _g;
                if (!node || typeof node !== 'object')
                    return;
                if (visited.has(node))
                    return;
                visited.add(node);
                if (depth > (opt.maxDepth || 2))
                    return;
                var keys = [];
                try {
                    keys.push.apply(keys, __spread(Object.getOwnPropertyNames(node)));
                }
                catch (_a) { }
                try {
                    for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) {
                        var key = keys_1_1.value;
                        var value = void 0;
                        try {
                            value = node[key];
                        }
                        catch (_b) {
                            continue;
                        }
                        if (typeof value === 'function') {
                            var original = value;
                            if (original.__pm_instrumented)
                                continue;
                            if (!shouldInclude(key))
                                continue;
                            var opBase = key;
                            var opName = opt.nameTransform
                                ? opt.nameTransform(opBase, path.concat(key))
                                : opBase;
                            var wrapped = _this.createWrapper(original, opName, opt.preserveToString);
                            // Tenta sobrescrever função no namespace
                            try {
                                Object.defineProperty(node, key, {
                                    value: wrapped,
                                    writable: true,
                                    configurable: true,
                                });
                            }
                            catch (_c) { }
                        }
                        else if (typeof value === 'object' && value) {
                            // Recurse
                            walk(value, depth + 1, path.concat(key));
                        }
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (keys_1_1 && !keys_1_1.done && (_g = keys_1.return)) _g.call(keys_1);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
            };
            walk(root, 0, []);
        };
        /**
         * 🪝 Envolve a função setService(target.setService) para instrumentar o serviço passado
         * @param target Objeto que possui setService(service)
         * @param label Rótulo usado no nome das operações (ex.: "packTela")
         * @param options Opções de instrumentação (nameTransform, exclude, etc.)
         */
        LogsPerformatico.prototype.hookSetService = function (target, label, options) {
            var _a;
            if (!target || typeof target !== 'object')
                return;
            var fn = target.setService;
            if (typeof fn !== 'function')
                return;
            var alreadyHooked = fn.__pm_setservice_hooked;
            if (alreadyHooked)
                return;
            var opt = Object.assign({ preserveToString: true, exclude: ['constructor'] }, options);
            var labelFinal = label ||
                (((_a = target === null || target === void 0 ? void 0 : target.constructor) === null || _a === void 0 ? void 0 : _a.name) ? String(target.constructor.name) : 'service');
            // Garante que o label (pack) entre na path[0] quando houver nameTransform customizado
            var nameTransform = opt.nameTransform
                ? function (n, path) { return opt.nameTransform(n, [labelFinal].concat(path || [])); }
                : function (n) { return labelFinal + "." + n; };
            var original = fn;
            var logger = this;
            var wrapped = function (serviceInstance) {
                var rest = [];
                for (var _i = 1; _i < arguments.length; _i++) {
                    rest[_i - 1] = arguments[_i];
                }
                try {
                    // Instrumenta o próprio objeto alvo (pack), pois são seus métodos que queremos medir
                    var packObj = this || target;
                    if (packObj && typeof packObj === 'object') {
                        var alreadyInstrumentedPack = packObj
                            .__pm_pack_instrumented;
                        if (!alreadyInstrumentedPack) {
                            logger.instrumentObject(packObj, Object.assign(Object.assign({}, opt), { nameTransform: nameTransform }));
                            try {
                                Object.defineProperty(packObj, '__pm_pack_instrumented', {
                                    value: true,
                                    configurable: true,
                                    enumerable: false,
                                    writable: false,
                                });
                            }
                            catch (_a) { }
                        }
                    }
                }
                catch (_b) { }
                return original.apply(this, __spread([serviceInstance], rest));
            };
            // marca como hookado para evitar duplicação
            wrapped.__pm_setservice_hooked = true;
            try {
                Object.defineProperty(target, 'setService', {
                    value: wrapped,
                    writable: true,
                    configurable: true,
                });
            }
            catch (_b) { }
            // Instrumenta imediatamente o pack (cobre casos onde setService já foi chamado antes do hook)
            try {
                var packObj = target;
                var alreadyInstrumentedPack = packObj.__pm_pack_instrumented;
                if (!alreadyInstrumentedPack) {
                    this.instrumentObject(packObj, Object.assign(Object.assign({}, opt), { nameTransform: nameTransform }));
                    Object.defineProperty(packObj, '__pm_pack_instrumented', {
                        value: true,
                        configurable: true,
                        enumerable: false,
                        writable: false,
                    });
                }
            }
            catch (_c) { }
        };
        /**
         * 🪝 Hook de setService para vários alvos em uma única chamada
         * @param targets Mapa de label -> objeto que contém setService
         * @param options Opções de instrumentação
         */
        LogsPerformatico.prototype.hookSetServiceBulk = function (targets, options) {
            var e_2, _g;
            if (!targets || typeof targets !== 'object')
                return;
            var _loop_1 = function (label, obj) {
                var hasSetService = !!(obj && typeof obj.setService === 'function');
                if (hasSetService) {
                    this_1.hookSetService(obj, label, options);
                }
                else if (obj && typeof obj === 'object') {
                    // Instrumenta objetos sem setService usando o label como prefixo
                    var opt_1 = Object.assign({}, options);
                    var nameTransform = opt_1.nameTransform
                        ? function (n, path) { return opt_1.nameTransform(n, [String(label)].concat(path || [])); }
                        : function (n) { return String(label) + "." + n; };
                    this_1.instrumentObject(obj, Object.assign(Object.assign({}, opt_1), { nameTransform: nameTransform, exclude: __spread(['constructor'], (opt_1.exclude || [])) }));
                }
            };
            var this_1 = this;
            try {
                for (var _h = __values(Object.entries(targets)), _j = _h.next(); !_j.done; _j = _h.next()) {
                    var _k = __read(_j.value, 2), label = _k[0], obj = _k[1];
                    _loop_1(label, obj);
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_j && !_j.done && (_g = _h.return)) _g.call(_h);
                }
                finally { if (e_2) throw e_2.error; }
            }
        };
        /**
         * 🌐 Varre um namespace e aplica hook em qualquer função setService encontrada
         * @param root Objeto raiz (ex.: window, module scope wrapper, etc.)
         * @param options Filtros e regras de nomeação
         */
        LogsPerformatico.prototype.hookSetServiceNamespace = function (root, options) {
            var _this = this;
            if (!root || typeof root !== 'object')
                return;
            var opt = Object.assign({ preserveToString: true, exclude: ['constructor'], maxWalkDepth: 2 }, options);
            var shouldIncludeObj = function (pathStr) {
                var inc = opt.includeObjects;
                var exc = opt.excludeObjects;
                var match = function (p) { return typeof p === 'string' ? pathStr.includes(p) : p.test(pathStr); };
                var okInc = !inc || inc.some(match);
                var okExc = exc ? !exc.some(match) : true;
                return okInc && okExc;
            };
            var visited = new WeakSet();
            var walk = function (node, depth, path) {
                var e_3, _g;
                if (!node || typeof node !== 'object')
                    return;
                if (visited.has(node))
                    return;
                visited.add(node);
                if (depth > (opt.maxWalkDepth || 2))
                    return;
                var keys = [];
                try {
                    keys.push.apply(keys, __spread(Object.getOwnPropertyNames(node)));
                }
                catch (_a) { }
                try {
                    for (var keys_2 = __values(keys), keys_2_1 = keys_2.next(); !keys_2_1.done; keys_2_1 = keys_2.next()) {
                        var key = keys_2_1.value;
                        var value = void 0;
                        try {
                            value = node[key];
                        }
                        catch (_b) {
                            continue;
                        }
                        var pathNow = path.concat(key);
                        var pathStr = pathNow.join('.');
                        if (value && typeof value === 'object') {
                            // Se o objeto tiver setService, aplica hook
                            var fn = value.setService;
                            if (typeof fn === 'function' && shouldIncludeObj(pathStr)) {
                                var labelFromPath = opt.labelFromPath || (function (p) { return p.join('.'); });
                                _this.hookSetService(value, labelFromPath(pathNow), opt);
                            }
                            // Continua a varredura
                            walk(value, depth + 1, pathNow);
                        }
                    }
                }
                catch (e_3_1) { e_3 = { error: e_3_1 }; }
                finally {
                    try {
                        if (keys_2_1 && !keys_2_1.done && (_g = keys_2.return)) _g.call(keys_2);
                    }
                    finally { if (e_3) throw e_3.error; }
                }
            };
            walk(root, 0, []);
        };
        // ===== Helpers =====
        /**
         * Cria wrapper que inicia/encerra timer preservando contexto e toString()
         */
        LogsPerformatico.prototype.createWrapper = function (original, opName, preserveToString) {
            // Idempotência: reutiliza wrapper se já existir
            var existing = this.instrumentedFns.get(original);
            if (existing)
                return existing;
            var logger = this;
            var wrapped = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                // Determina nome final com fallback ao nome do arquivo (pack) via stacktrace
                var finalName = opName;
                try {
                    var parts = String(opName).split('.');
                    var methodName = parts[parts.length - 1];
                    var prefix = parts.length > 1 ? parts[0] : undefined;
                    if (!prefix || prefix.toLowerCase() === methodName.toLowerCase()) {
                        var fileLabel = logger.guessFileLabelFromStack();
                        if (fileLabel) {
                            finalName = fileLabel + "." + methodName;
                        }
                    }
                }
                catch (_a) { }
                // Herda label do evento ativo (já garantido pelo logger)
                logger.startTimer(finalName);
                try {
                    var result = original.apply(this, args);
                    if (result && typeof result.then === 'function') {
                        // Promises/async
                        return result.finally(function () {
                            logger.endTimer(finalName);
                        });
                    }
                    else {
                        logger.endTimer(finalName);
                        return result;
                    }
                }
                catch (e) {
                    logger.endTimer(finalName, 'erro');
                    throw e;
                }
            };
            // Marca instrumentado
            original.__pm_instrumented = true;
            wrapped.__pm_instrumented = true;
            // Preserva toString() para compatibilidade com regex
            if (preserveToString) {
                try {
                    Object.defineProperty(wrapped, 'toString', {
                        value: function () {
                            return original.toString();
                        },
                        writable: false,
                        configurable: true,
                    });
                }
                catch (_a) { }
            }
            // Tenta igualar o nome (nem sempre é possível)
            try {
                Object.defineProperty(wrapped, 'name', {
                    value: original.name || opName,
                    configurable: true,
                });
            }
            catch (_b) { }
            this.instrumentedFns.set(original, wrapped);
            return wrapped;
        };
        /**
         * 🔎 Tenta inferir o nome do arquivo (pack) a partir do stacktrace
         * Preferência por nomes que começam com "pack"
         */
        LogsPerformatico.prototype.guessFileLabelFromStack = function () {
            var e_4, _g;
            try {
                var err = new Error();
                var stack = String(err.stack || '');
                var lines = stack.split('\n');
                var candidates = [];
                try {
                    for (var lines_1 = __values(lines), lines_1_1 = lines_1.next(); !lines_1_1.done; lines_1_1 = lines_1.next()) {
                        var line = lines_1_1.value;
                        var m = line.match(/[\\\/]([A-Za-z0-9_-]+)\.(?:ts|js)(?::\d+:\d+|\?|$)/);
                        if (m && m[1]) {
                            var base = m[1];
                            if (/^pack/i.test(base)) {
                                return base;
                            }
                            candidates.push(base);
                        }
                    }
                }
                catch (e_4_1) { e_4 = { error: e_4_1 }; }
                finally {
                    try {
                        if (lines_1_1 && !lines_1_1.done && (_g = lines_1.return)) _g.call(lines_1);
                    }
                    finally { if (e_4) throw e_4.error; }
                }
                return candidates[0];
            }
            catch (_a) {
                return undefined;
            }
        };
        /**
         * 💾 Exporta dados de performance para JSON
         * @returns String JSON com todos os dados
         */
        LogsPerformatico.prototype.exportData = function () {
            var data = {
                timestamp: new Date().toISOString(),
                serviceName: this.serviceName,
                statistics: this.getStatistics(),
                operations: Array.from(this.performanceSummary.entries()).map(function (_g) {
                    var _h = __read(_g, 2), name = _h[0], stats = _h[1];
                    return (Object.assign(Object.assign({ name: name }, stats), { averageTime: Math.round(stats.totalTime / stats.count) }));
                }),
            };
            return JSON.stringify(data, null, 2);
        };
        /**
         * 🎯 Calcula thresholds dinâmicos baseados na quantidade de execuções
         * @param executionCount Número de execuções da operação
         * @returns Objeto com thresholds calculados dinamicamente
         */
        LogsPerformatico.prototype.calculateDynamicThresholds = function (executionCount) {
            if (executionCount === 1) {
                // Primeira execução - expectativas mais relaxadas
                return {
                    ok: 1000,
                    lento: 2000,
                    critico: 2000,
                };
            }
            else if (executionCount <= 5) {
                // Até 5 execuções - sistema ainda aquecendo
                return {
                    ok: 500,
                    lento: 1000,
                    critico: 1000,
                };
            }
            else if (executionCount <= 10) {
                // Até 10 execuções - sistema otimizado
                return {
                    ok: 100,
                    lento: 250,
                    critico: 250,
                };
            }
            else {
                // Acima de 10 execuções - expectativas altas
                return {
                    ok: 20,
                    lento: 60,
                    critico: 60,
                };
            }
        };
        LogsPerformatico.prototype.injectMonitorButton = function () {
            var _this = this;
            if (document.getElementById('btn-monitorar-performance'))
                return;
            // ====== ESTILO MODERNO E BOTÃO DE OLHO ======
            var BUTTON_COLOR = '#23272f'; // cinza escuro elegante
            var BUTTON_TEXT_COLOR = '#f3f4f6';
            var BUTTON_RADIUS = '8px';
            var BUTTON_FONT_SIZE = '13px';
            var BUTTON_PADDING = '10px 5px';
            var BUTTON_WIDTH = '210px';
            var BUTTON_HEIGHT = '44px';
            var BUTTON_BOX_SHADOW = '0 2px 12px #0002';
            var BUTTON_BORDER = '1px solid #353a40';
            // Container para animação
            var container = document.createElement('div');
            container.id = 'performance-monitor-container';
            Object.assign(container.style, {
                position: 'fixed',
                bottom: '5px',
                left: '50px',
                zIndex: '9999',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'flex-end',
                transition: 'transform 0.5s cubic-bezier(.4,2,.6,1)',
                gap: '10px',
            });
            // Função para criar botões padronizados
            var criarBotao = function (id, texto) {
                var btn = document.createElement('button');
                btn.id = id;
                btn.innerText = texto;
                Object.assign(btn.style, {
                    width: BUTTON_WIDTH,
                    height: BUTTON_HEIGHT,
                    background: BUTTON_COLOR,
                    color: BUTTON_TEXT_COLOR,
                    borderRadius: BUTTON_RADIUS,
                    border: BUTTON_BORDER,
                    padding: BUTTON_PADDING,
                    fontSize: BUTTON_FONT_SIZE,
                    fontWeight: '600',
                    cursor: 'pointer',
                    boxShadow: BUTTON_BOX_SHADOW,
                    letterSpacing: '0.01em',
                    textAlign: 'center',
                    transition: 'background 0.2s, color 0.2s, transform 0.5s cubic-bezier(.4,2,.6,1)',
                });
                btn.onmouseenter = function () {
                    btn.style.background = '#353a40';
                    btn.style.color = '#fff';
                };
                btn.onmouseleave = function () {
                    btn.style.background = BUTTON_COLOR;
                    btn.style.color = BUTTON_TEXT_COLOR;
                };
                return btn;
            };
            // Botões principais
            var btnMain = criarBotao('btn-monitorar-performance', 'Parar monitoramento');
            var btnFinalizar = criarBotao('btn-finalizar-monitoramento', 'Finalizar monitoramento');
            var btnRequisicoesDetalhadas = criarBotao('btn-req-detalhadas-performance', 'Requisições detalhadas');
            var btnAnaliseDetalhada = criarBotao('btn-analise-detalhada-performance', 'Análise detalhada');
            var btnRelatorioEvento = criarBotao('btn-relatorio-evento-performance', 'Relatório separado');
            // Inicialmente escondidos
            btnRequisicoesDetalhadas.style.display = 'none';
            btnAnaliseDetalhada.style.display = 'none';
            btnFinalizar.style.display = 'none';
            btnRelatorioEvento.style.display = 'none';
            // Botão de esconder/mostrar com ícone de olho (fora do container)
            var btnToggle = document.createElement('button');
            btnToggle.id = 'btn-toggle-performance';
            btnToggle.innerHTML = "\n    <img\n      src=\"https://cdn-icons-png.flaticon.com/512/565/565655.png\"\n      alt=\"esconder\"\n      style=\"width:15px; height:15px; vertical-align:middle; filter: invert(1);\"\n    />\n    ";
            Object.assign(btnToggle.style, {
                width: '38px',
                height: '38px',
                background: '#23272f',
                color: '#f3f4f6',
                borderRadius: '50%',
                border: BUTTON_BORDER,
                fontSize: '20px',
                fontWeight: 'bold',
                cursor: 'pointer',
                boxShadow: BUTTON_BOX_SHADOW,
                position: 'fixed',
                left: '5px',
                bottom: '5px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                zIndex: '10000',
            });
            btnToggle.onmouseenter = function () {
                btnToggle.style.background = '#353a40';
                btnToggle.style.color = '#fff';
            };
            btnToggle.onmouseleave = function () {
                btnToggle.style.background = '#23272f';
                btnToggle.style.color = '#f3f4f6';
            };
            var hidden = false;
            btnToggle.onclick = function () {
                hidden = !hidden;
                if (hidden) {
                    container.style.display = 'none';
                    btnToggle.innerHTML = "\n    <img\n      src=\"https://cdn-icons-png.flaticon.com/512/159/159604.png\"\n      alt=\"mostrar\"\n      style=\"width:15px; height:15px; vertical-align:middle; filter: invert(1);\"\n    />\n  ";
                }
                else {
                    container.style.display = 'flex';
                    btnToggle.innerHTML = "\n    <img\n      src=\"https://cdn-icons-png.flaticon.com/512/565/565655.png\"\n      alt=\"esconder\"\n      style=\"width:15px; height:15px; vertical-align:middle; filter: invert(1);\"\n    />\n  ";
                }
            };
            // Estado dos botões
            var estado = 'monitorando';
            var atualizarBotoes = function (novoEstado) {
                estado = novoEstado;
                switch (estado) {
                    case 'inativo':
                        btnMain.innerText = 'Iniciar monitoramento';
                        _this.monitoramentoAtivo = false;
                        btnFinalizar.style.display = 'none';
                        btnRequisicoesDetalhadas.style.display = 'none';
                        btnAnaliseDetalhada.style.display = 'none';
                        btnRelatorioEvento.style.display = 'none';
                        break;
                    case 'monitorando':
                        btnMain.innerText = 'Parar monitoramento';
                        _this.monitoramentoAtivo = true;
                        btnFinalizar.style.display = 'none';
                        btnRequisicoesDetalhadas.style.display = 'none';
                        btnAnaliseDetalhada.style.display = 'none';
                        btnRelatorioEvento.style.display = 'none';
                        break;
                    case 'relatorio':
                        btnMain.innerText = 'Gerar relatório';
                        _this.monitoramentoAtivo = false;
                        btnFinalizar.style.display = 'none';
                        btnRequisicoesDetalhadas.style.display = 'block';
                        btnAnaliseDetalhada.style.display = 'block';
                        btnRelatorioEvento.style.display = 'block';
                        break;
                    case 'relatorio_gerado':
                        btnMain.innerText = 'Gerar relatório';
                        _this.monitoramentoAtivo = false;
                        btnFinalizar.style.display = 'block';
                        btnRequisicoesDetalhadas.style.display = 'block';
                        btnAnaliseDetalhada.style.display = 'block';
                        btnRelatorioEvento.style.display = 'block';
                        break;
                }
            };
            // Ações dos botões
            btnMain.onclick = function () {
                if (estado === 'inativo') {
                    _this.resetPerformanceData();
                    _this.showWelcomeMessage();
                    atualizarBotoes('monitorando');
                }
                else if (estado === 'monitorando') {
                    atualizarBotoes('relatorio');
                }
                else if (estado === 'relatorio' || estado === 'relatorio_gerado') {
                    _this.showPerformanceSummary(false);
                    atualizarBotoes('relatorio_gerado');
                }
            };
            btnFinalizar.onclick = function () {
                _this.resetPerformanceData();
                atualizarBotoes('inativo');
            };
            // Apêndice
            this.showWelcomeMessage();
            container.appendChild(btnMain);
            container.appendChild(btnRequisicoesDetalhadas);
            container.appendChild(btnRelatorioEvento);
            container.appendChild(btnAnaliseDetalhada);
            container.appendChild(btnFinalizar);
            document.body.appendChild(container);
            document.body.appendChild(btnToggle);
            // Ação do botão de requisições detalhadas
            btnRequisicoesDetalhadas.onclick = function () {
                _this.showHttpRequestsReport();
            };
            // Ação do botão de análise detalhada
            btnAnaliseDetalhada.onclick = function () {
                _this.generateDetailedAnalysis();
            };
            // Ação do relatório por evento
            btnRelatorioEvento.onclick = function () {
                _this.showEventReport(true);
            };
            // ====== Captura automática de eventos de UI para separar por evento ======
            try {
                // Evita adicionar múltiplos listeners
                var anyWindow = window;
                if (!anyWindow.__pm_auto_ui_listeners_added) {
                    anyWindow.__pm_auto_ui_listeners_added = true;
                    var describeTarget_1 = function (el, ev) {
                        try {
                            var isKeyboard = typeof KeyboardEvent !== 'undefined' &&
                                ev instanceof KeyboardEvent;
                            var keyPart = isKeyboard && ev.key
                                ? "[" + ev.key + "]"
                                : '';
                            if (!el || typeof el !== 'object')
                                return "ui" + keyPart;
                            var tag = (el.tagName || el.nodeName || '').toString().toLowerCase() ||
                                'element';
                            var id = el.id ? "#" + el.id : '';
                            var rawClass = typeof el.className === 'string'
                                ? el.className
                                : el.classList &&
                                    typeof el.classList === 'object' &&
                                    typeof el.classList.toString === 'function'
                                    ? el.classList.toString()
                                    : '';
                            var filtered = rawClass
                                .split(' ')
                                .filter(function (c) { return c && !c.startsWith('ng-') && !c.startsWith('cdk-'); })
                                .slice(0, 2)
                                .join('.');
                            var cls = filtered ? "." + filtered : '';
                            var includeText = tag === 'button' || tag === 'a';
                            var txt = includeText && typeof el.innerText === 'string'
                                ? el.innerText.trim().slice(0, 30)
                                : '';
                            return "" + tag + id + cls + keyPart + (txt ? ":\"" + txt + "\"" : '');
                        }
                        catch (_a) {
                            return 'ui';
                        }
                    };
                    var uiEventEndTimer_1 = null;
                    var uiEventEndInterval_1 = null;
                    var startUiEventContext_1 = function (label) {
                        if (uiEventEndTimer_1) {
                            clearTimeout(uiEventEndTimer_1);
                            uiEventEndTimer_1 = null;
                        }
                        if (uiEventEndInterval_1) {
                            clearInterval(uiEventEndInterval_1);
                            uiEventEndInterval_1 = null;
                        }
                        _this.beginEventContext(label);
                        // Se já há um contexto aberto, não cria nova janela de encerramento (evento aninhado)
                        if (_this.eventContextStack.length > 1) {
                            return;
                        }
                        // Janela inteligente: espera primeiro timer e fecha após período de silêncio
                        var MAX_WINDOW_MS = 60000;
                        var GRACE_MS = 2000; // tempo para permitir timers que começam depois
                        var QUIET_MS = 600; // tempo sem atividade para considerar fluxo encerrado
                        uiEventEndInterval_1 = setInterval(function () {
                            var _a, _b;
                            var now = Date.now();
                            var active = _this.hasActiveTimers();
                            var beginAt = (_a = _this.currentEventBeginAt) !== null && _a !== void 0 ? _a : now;
                            var hasStarted = _this.firstTimerInEventAt !== null;
                            var graceExceeded = now - beginAt > GRACE_MS;
                            var lastActivity = (_b = _this.lastTimerActivityAt) !== null && _b !== void 0 ? _b : beginAt;
                            var quietEnough = hasStarted && !active && now - lastActivity > QUIET_MS;
                            var exceededMax = now - beginAt > MAX_WINDOW_MS;
                            if (quietEnough || (!hasStarted && graceExceeded) || exceededMax) {
                                _this.endEventContext();
                                clearInterval(uiEventEndInterval_1);
                                uiEventEndInterval_1 = null;
                            }
                        }, 250);
                        // Fallback: fecha no máximo após MAX_WINDOW_MS
                        uiEventEndTimer_1 = setTimeout(function () {
                            if (uiEventEndInterval_1) {
                                clearInterval(uiEventEndInterval_1);
                                uiEventEndInterval_1 = null;
                            }
                            _this.endEventContext();
                            uiEventEndTimer_1 = null;
                        }, MAX_WINDOW_MS);
                    };
                    ['click', 'submit', 'change', 'keydown'].forEach(function (type) {
                        document.addEventListener(type, function (ev) {
                            var target = ev.target;
                            var label = "UserInput:" + type + " " + describeTarget_1(target, ev);
                            startUiEventContext_1(label);
                        }, true // captura cedo na fase de captura
                        );
                    });
                    // Contexto inicial para operações de inicialização da tela
                    this.beginEventContext('AppInit');
                    setTimeout(function () { return _this.endEventContext(); }, 3000);
                }
            }
            catch (e) {
                // Evita quebrar caso ambiente não permita acesso ao document
                console.warn('[PerformanceMonitor] Falha ao ativar captura automática de UI:', e);
            }
        };
        LogsPerformatico.prototype.showEventReport = function (includeHttp) {
            var _this = this;
            if (includeHttp === void 0) { includeHttp = true; }
            console.log('%cRELATÓRIO POR EVENTO', 'color: #bbc7c8ff; font-size: 18px; font-weight: bold; text-shadow: 1px 1px #000; background-color: #43248bff; border-radius: 5px; padding: 10px 20px;');
            if (this.performanceSummary.size === 0) {
                console.log('Nenhuma operação monitorada ainda.');
                return;
            }
            var events = new Map();
            this.performanceSummary.forEach(function (stats, fullName) {
                var parts = fullName.split(' | ');
                var event = parts.length > 1 ? parts[0] : 'SemEvento';
                var opName = parts.length > 1 ? parts.slice(1).join(' | ') : fullName;
                if (!events.has(event)) {
                    events.set(event, { totalTime: 0, totalExec: 0, operations: [] });
                }
                var group = events.get(event);
                group.totalTime += stats.totalTime;
                group.totalExec += stats.count;
                group.operations.push({ name: opName, stats: stats });
            });
            var overallTime = 0;
            var overallExec = 0;
            Array.from(events.entries())
                .sort(function (a, b) { return b[1].totalTime - a[1].totalTime; })
                .forEach(function (_g) {
                var _h = __read(_g, 2), event = _h[0], group = _h[1];
                overallTime += group.totalTime;
                overallExec += group.totalExec;
                console.log("%cEVENTO: " + event + "  |  Tempo: " + Math.round(group.totalTime) + "ms  |  Execu\u00E7\u00F5es: " + group.totalExec, 'color: #fff; background: #28647b; font-size: 13px; font-weight: bold; border-radius: 4px; padding: 3px 8px;');
                var table = Object.fromEntries(group.operations
                    .sort(function (a, b) { return b.stats.totalTime - a.stats.totalTime; })
                    .map(function (_g) {
                    var name = _g.name, stats = _g.stats;
                    var avgTime = Math.round(stats.totalTime / stats.count);
                    var _h = _this.getPerformanceStatus(avgTime, stats.customThresholds, name), emoji = _h.emoji, status = _h.status;
                    return [
                        name,
                        {
                            Execuções: stats.count,
                            'Média(ms)': (avgTime + "ms (" + status + ") " + emoji).trim(),
                            'Mínimo(ms)': stats.minTime,
                            'Máximo(ms)': stats.maxTime,
                            'Total(ms)': Math.round(stats.totalTime),
                        },
                    ];
                }));
                console.table(table);
                if (includeHttp) {
                    var httpTable_1 = {};
                    _this.httpRequests.forEach(function (dados, key) {
                        var parts = key.split(' | ');
                        var httpEvent = parts.length > 1 ? parts[0] : 'SemEvento';
                        var httpName = parts.length > 1 ? parts.slice(1).join(' | ') : key;
                        if (httpEvent === event) {
                            httpTable_1[httpName] = {
                                Execuções: dados.execucoes,
                                Média: Math.round(dados.tempoTotal / Math.max(dados.execucoes, 1)) + "ms",
                                'Tempo Total': Math.round(dados.tempoTotal) + "ms",
                                Erros: dados.errors,
                            };
                        }
                    });
                    var hasHttpRows = Object.keys(httpTable_1).length > 0;
                    if (hasHttpRows) {
                        console.log("%cHTTP (" + event + ")", 'color: #fff; background: #28336b; font-size: 12px; font-weight: bold; border-radius: 4px; padding: 2px 8px;');
                        console.table(httpTable_1);
                    }
                }
            });
            console.log("%cTOTAL GERAL: " + Math.round(overallTime) + "ms  |  Execu\u00E7\u00F5es: " + overallExec, 'color: #fff; background: #43248bff; font-size: 14px; font-weight: bold; border-radius: 4px; padding: 4px 12px; margin-top: 8px;');
        };
        return LogsPerformatico;
    }());
    /**
     * 🏭 Factory function para criar instância do LogsPerformatico
     * @param serviceName Nome do serviço (para logs personalizados)
     * @returns Nova instância de LogsPerformatico
     */
    function createPerformanceLogger(serviceName) {
        if (serviceName === void 0) { serviceName = 'Service'; }
        return new LogsPerformatico(serviceName);
    }

    var GlobalPerformanceLogger = createPerformanceLogger('GLOBAL');
    // Implementação unificada
    function PerformanceMonitor(options) {
        return function (target, propertyKey, descriptor) {
            var e_1, _a;
            // --- CASO 1: Class Decorator ---
            // Se propertyKey e descriptor forem undefined, estamos decorando uma classe
            if (!propertyKey && !descriptor) {
                var constructor = target;
                var opts = options;
                var excludeList = (typeof opts === 'object' && (opts === null || opts === void 0 ? void 0 : opts.exclude)) || [];
                var prefix = (typeof opts === 'object' && (opts === null || opts === void 0 ? void 0 : opts.prefix)) || '';
                var _loop_1 = function (prop) {
                    // Ignora construtor e itens excluídos
                    if (prop === 'constructor' || excludeList.includes(prop)) {
                        return "continue";
                    }
                    var propDesc = Object.getOwnPropertyDescriptor(constructor.prototype, prop);
                    // Verifica se é método
                    if (propDesc && typeof propDesc.value === 'function') {
                        var originalMethod_1 = propDesc.value;
                        var opName_1 = prefix ? prefix + "." + prop : prop;
                        // Substitui o método original pelo wrapper
                        propDesc.value = function () {
                            var args = [];
                            for (var _i = 0; _i < arguments.length; _i++) {
                                args[_i] = arguments[_i];
                            }
                            var instanceLogger = this
                                .performanceLogger;
                            var logger = instanceLogger || GlobalPerformanceLogger;
                            if (!logger) {
                                return originalMethod_1.apply(this, args);
                            }
                            logger.startTimer(opName_1);
                            var result;
                            try {
                                result = originalMethod_1.apply(this, args);
                            }
                            catch (err) {
                                // Em caso de erro síncrono, finaliza timer e re-lança
                                logger.endTimer(opName_1);
                                throw err;
                            }
                            // Verifica se é Promise (assíncrono)
                            if (result && typeof result.then === 'function') {
                                return result
                                    .then(function (res) {
                                    logger.endTimer(opName_1);
                                    return res;
                                })
                                    .catch(function (err) {
                                    logger.endTimer(opName_1);
                                    throw err;
                                });
                            }
                            else {
                                // Síncrono
                                logger.endTimer(opName_1);
                                return result;
                            }
                        };
                        // Redefine a propriedade no prototype
                        Object.defineProperty(constructor.prototype, prop, propDesc);
                    }
                };
                try {
                    // Itera sobre todas as propriedades do prototype da classe
                    for (var _b = __values(Object.getOwnPropertyNames(constructor.prototype)), _c = _b.next(); !_c.done; _c = _b.next()) {
                        var prop = _c.value;
                        _loop_1(prop);
                    }
                }
                catch (e_1_1) { e_1 = { error: e_1_1 }; }
                finally {
                    try {
                        if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                    }
                    finally { if (e_1) throw e_1.error; }
                }
                return; // Retorna void para Class Decorator
            }
            // --- CASO 2: Method Decorator ---
            if (!descriptor)
                return; // Segurança
            var originalMethod = descriptor.value;
            var opName;
            var customMethod;
            var customThresholds;
            var eventLabel;
            // Parsing simples para method options
            if (typeof options === 'object' &&
                options !== null &&
                !('exclude' in options) &&
                !('prefix' in options)) {
                var opts = options;
                opName = opts.name || propertyKey;
                customMethod = opts.method;
                customThresholds = {
                    ok: opts.ok,
                    lento: opts.lento,
                    critico: opts.critico,
                };
                eventLabel = opts.event;
            }
            else if (typeof options === 'function') {
                opName = options.name || propertyKey;
                customMethod = options;
            }
            else if (typeof options === 'string') {
                opName = options;
            }
            else {
                opName = propertyKey;
            }
            descriptor.value = function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                var instanceLogger = this
                    .performanceLogger;
                var logger = instanceLogger || GlobalPerformanceLogger;
                if (logger) {
                    if (eventLabel) {
                        logger.beginEventContext(eventLabel);
                    }
                    logger.startTimer(opName);
                    var result = void 0;
                    try {
                        var methodToCall = customMethod || originalMethod;
                        result = methodToCall.apply(this, args);
                    }
                    catch (err) {
                        logger.endTimer(opName, undefined, customThresholds);
                        if (eventLabel)
                            logger.endEventContext();
                        throw err;
                    }
                    if (result && typeof result.then === 'function') {
                        return result
                            .then(function (res) {
                            logger.endTimer(opName, undefined, customThresholds);
                            if (eventLabel)
                                logger.endEventContext();
                            return res;
                        })
                            .catch(function (err) {
                            logger.endTimer(opName, undefined, customThresholds);
                            if (eventLabel)
                                logger.endEventContext();
                            throw err;
                        });
                    }
                    else {
                        logger.endTimer(opName, undefined, customThresholds);
                        if (eventLabel)
                            logger.endEventContext();
                        return result;
                    }
                }
                else {
                    var methodToCall = customMethod || originalMethod;
                    return methodToCall.apply(this, args);
                }
            };
            return descriptor;
        };
    }

    var PerformanceMonitorInterceptor = /** @class */ (function () {
        function PerformanceMonitorInterceptor() {
        }
        PerformanceMonitorInterceptor.prototype.intercept = function (req, next) {
            var _a;
            // Ignora arquivos de assets
            if (!req.url.startsWith('./assets')) {
                // 🔹 Recupera dados da sessão
                var tela = sessionStorage.getItem('idTela');
                if (!tela) {
                    tela = 'SEL041';
                    sessionStorage.setItem('idTela', tela);
                }
                var cdUsuario = (_a = sessionStorage.getItem('cdUsuario')) !== null && _a !== void 0 ? _a : '';
                // 🔹 Clona a requisição adicionando headers
                var authReq_1 = req.clone({
                    headers: req.headers
                        .set('tela_id', tela)
                        .set('tela', 'SEL041')
                        .set('user', cdUsuario),
                });
                var start_1 = performance.now();
                return next.handle(authReq_1).pipe(operators.tap({
                    next: function (event) {
                        var _a, _b;
                        if (event instanceof http.HttpResponse) {
                            var tempo = performance.now() - start_1;
                            // ✅ Verificação segura do body e suas propriedades
                            var operationType = ((_a = authReq_1.body) === null || _a === void 0 ? void 0 : _a.operationType) || 'UNKNOWN';
                            var operationName = ((_b = authReq_1.body) === null || _b === void 0 ? void 0 : _b.name) || '';
                            console.log("%c\uD83D\uDFE2 [HTTP] " + operationType + " " + (operationType === 'SELECT_FULL' ? '' : operationName) + " - " + tempo.toFixed(1) + "ms", 'color: #7048cfff; font-weight: bold;');
                            GlobalPerformanceLogger.registerHttpRequest(authReq_1, tempo, false);
                        }
                    },
                    error: function (error) {
                        var _a, _b;
                        var tempo = performance.now() - start_1;
                        // ✅ Verificação segura do body e suas propriedades
                        var operationType = ((_a = authReq_1.body) === null || _a === void 0 ? void 0 : _a.operationType) || 'UNKNOWN';
                        var operationName = ((_b = authReq_1.body) === null || _b === void 0 ? void 0 : _b.name) || '';
                        console.groupCollapsed("%c\uD83D\uDD34 [HTTP] " + operationType + " " + operationName + " - " + tempo.toFixed(1) + "ms", 'color: #7048cfff; font-weight: bold;');
                        console.error(error);
                        console.groupEnd();
                        GlobalPerformanceLogger.registerHttpRequest(authReq_1, tempo, true);
                    },
                }));
            }
            // Requisição de asset, passa direto
            return next.handle(req);
        };
        return PerformanceMonitorInterceptor;
    }());
    PerformanceMonitorInterceptor.decorators = [
        { type: i0.Injectable }
    ];

    /*
     * Public API Surface of performance-monitor
     */

    /**
     * Generated bundle index. Do not edit.
     */

    exports.GlobalPerformanceLogger = GlobalPerformanceLogger;
    exports.PerformanceMonitor = PerformanceMonitor;
    exports.PerformanceMonitorComponent = PerformanceMonitorComponent;
    exports.PerformanceMonitorInterceptor = PerformanceMonitorInterceptor;
    exports.PerformanceMonitorModule = PerformanceMonitorModule;
    exports.PerformanceMonitorService = PerformanceMonitorService;
    exports.ɵa = LogsPerformatico;
    exports.ɵb = createPerformanceLogger;

    Object.defineProperty(exports, '__esModule', { value: true });

})));
//# sourceMappingURL=performance-monitor-logger.umd.js.map