UNPKG

pinia-logger

Version:
63 lines 3.09 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PiniaLogger = void 0; const formatTime = (date = new Date()) => { const hours = date.getHours().toString().padStart(2, "0"); const minutes = date.getMinutes().toString().padStart(2, "0"); const seconds = date.getSeconds().toString().padStart(2, "0"); const milliseconds = date.getMilliseconds().toString(); return `${hours}:${minutes}:${seconds}:${milliseconds}`; }; const defaultOptions = { logErrors: true, disabled: false, expanded: true, showStoreName: true, showDuration: false, showTime: true, showPineapple: true, actions: undefined, filter: () => true, }; const PiniaLogger = (config = defaultOptions) => (ctx) => { const options = Object.assign(Object.assign(Object.assign({}, defaultOptions), config), (typeof ctx.options.logger === "object" ? ctx.options.logger : {})); const logger = config.logger || console; if (options.disabled || ctx.options.logger === false) return; ctx.store.$onAction((action) => { var _a; if (Array.isArray(options.actions) && !((_a = options.actions) === null || _a === void 0 ? void 0 : _a.includes(action.name))) return; const startTime = Date.now(); const prevState = Object.assign({}, ctx.store.$state); const log = (isError, error) => { const endTime = Date.now(); const duration = endTime - startTime + "ms"; const nextState = Object.assign({}, ctx.store.$state); const storeName = action.store.$id; const title = `action ${options.showPineapple ? `🍍 ` : ""}${options.showStoreName ? `[${storeName}] ` : ""}${action.name} ${isError ? `failed ${options.showDuration ? `after ${duration} ` : ""}` : ""}${options.showTime ? `@ ${formatTime()}` : ""}`; logger[options.expanded ? "group" : "groupCollapsed"](`%c${title}`, `font-weight: bold; ${isError ? "color: #ed4981;" : ""}`); logger.log("%cprev state", "font-weight: bold; color: grey;", prevState); logger.log("%caction", "font-weight: bold; color: #69B7FF;", Object.assign(Object.assign(Object.assign({ type: action.name, args: action.args.length > 0 ? Object.assign({}, action.args) : undefined }, (options.showStoreName && { store: action.store.$id })), (options.showDuration && { duration })), (isError && { error }))); logger.log("%cnext state", "font-weight: bold; color: #4caf50;", nextState); logger.groupEnd(); }; action.after(() => { var _a; const canLog = (_a = (options.filter && options.filter(action))) !== null && _a !== void 0 ? _a : false; if (canLog) log(); }); if (options.logErrors) { action.onError((error) => { log(true, error); }); } }); }; exports.PiniaLogger = PiniaLogger; exports.default = exports.PiniaLogger; //# sourceMappingURL=index.js.map