🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@deepracticex/logger

Package Overview
Dependencies
Maintainers
2
Versions
19
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@deepracticex/logger - npm Package Compare versions

Comparing version
1.1.2
to
1.2.0
+169
-211
dist/index.cjs

@@ -6,5 +6,2 @@ "use strict";

var __hasOwnProp = Object.prototype.hasOwnProperty;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {

@@ -24,233 +21,194 @@ for (var name in all)

// src/core/test-adapter.ts
var test_adapter_exports = {};
__export(test_adapter_exports, {
clearTestLogs: () => clearTestLogs,
createTestLogger: () => createTestLogger,
getTestLogs: () => getTestLogs,
getTestLogsByLevel: () => getTestLogsByLevel,
getTestLogsCount: () => getTestLogsCount
// src/index.ts
var index_exports = {};
__export(index_exports, {
ConsoleLogger: () => ConsoleLogger,
LoggerFactoryImpl: () => LoggerFactoryImpl,
createLogger: () => createLogger,
setLoggerFactory: () => setLoggerFactory
});
function getMinLogLevel(level = "info") {
return LOG_LEVEL_PRIORITY[level];
}
function shouldLog(level, minLevel) {
return LOG_LEVEL_PRIORITY[level] >= minLevel;
}
function createLogEntry(level, args, shouldOutput, minLevel) {
if (!shouldLog(level, minLevel)) {
return;
module.exports = __toCommonJS(index_exports);
// src/ConsoleLogger.ts
var ConsoleLogger = class _ConsoleLogger {
name;
level;
colors;
timestamps;
static COLORS = {
DEBUG: "\x1B[36m",
INFO: "\x1B[32m",
WARN: "\x1B[33m",
ERROR: "\x1B[31m",
RESET: "\x1B[0m"
};
constructor(name, options = {}) {
this.name = name;
this.level = options.level ?? "info";
this.colors = options.colors ?? this.isNodeEnvironment();
this.timestamps = options.timestamps ?? true;
}
let message;
let context;
if (args.length === 1) {
if (typeof args[0] === "string") {
message = args[0];
debug(message, context) {
if (this.isDebugEnabled()) {
this.log("DEBUG", message, context);
}
}
info(message, context) {
if (this.isInfoEnabled()) {
this.log("INFO", message, context);
}
}
warn(message, context) {
if (this.isWarnEnabled()) {
this.log("WARN", message, context);
}
}
error(message, context) {
if (this.isErrorEnabled()) {
if (message instanceof Error) {
this.log("ERROR", message.message, { ...context, stack: message.stack });
} else {
this.log("ERROR", message, context);
}
}
}
isDebugEnabled() {
return this.getLevelValue(this.level) <= this.getLevelValue("debug");
}
isInfoEnabled() {
return this.getLevelValue(this.level) <= this.getLevelValue("info");
}
isWarnEnabled() {
return this.getLevelValue(this.level) <= this.getLevelValue("warn");
}
isErrorEnabled() {
return this.getLevelValue(this.level) <= this.getLevelValue("error");
}
getLevelValue(level) {
const levels = {
debug: 0,
info: 1,
warn: 2,
error: 3,
silent: 4
};
return levels[level];
}
log(level, message, context) {
const parts = [];
if (this.timestamps) {
parts.push((/* @__PURE__ */ new Date()).toISOString());
}
if (this.colors) {
const color = _ConsoleLogger.COLORS[level];
parts.push(`${color}${level.padEnd(5)}${_ConsoleLogger.COLORS.RESET}`);
} else {
context = args[0];
message = JSON.stringify(args[0]);
parts.push(level.padEnd(5));
}
} else if (args.length >= 2) {
if (typeof args[0] === "object" && args[0] !== null) {
context = args[0];
message = args.slice(1).join(" ");
parts.push(`[${this.name}]`);
parts.push(message);
const logLine = parts.join(" ");
const consoleMethod = this.getConsoleMethod(level);
if (context && Object.keys(context).length > 0) {
consoleMethod(logLine, context);
} else {
message = args.join(" ");
consoleMethod(logLine);
}
} else {
message = "";
}
capturedLogs.push({
level,
message,
context,
timestamp: Date.now()
});
if (shouldOutput) {
const consoleMethod = level === "fatal" ? "error" : level;
const logFn = console[consoleMethod] || console.log;
if (context) {
logFn(`[${level.toUpperCase()}]`, context, message);
} else {
logFn(`[${level.toUpperCase()}]`, message);
getConsoleMethod(level) {
switch (level) {
case "DEBUG":
return console.debug.bind(console);
case "INFO":
return console.info.bind(console);
case "WARN":
return console.warn.bind(console);
case "ERROR":
return console.error.bind(console);
default:
return console.log.bind(console);
}
}
}
function createTestLogger(config = {}) {
const shouldOutput = config.console === true;
const minLevel = getMinLogLevel(config.level);
return {
trace: (...args) => createLogEntry("trace", args, shouldOutput, minLevel),
debug: (...args) => createLogEntry("debug", args, shouldOutput, minLevel),
info: (...args) => createLogEntry("info", args, shouldOutput, minLevel),
warn: (...args) => createLogEntry("warn", args, shouldOutput, minLevel),
error: (...args) => createLogEntry("error", args, shouldOutput, minLevel),
fatal: (...args) => createLogEntry("fatal", args, shouldOutput, minLevel)
};
}
function getTestLogs() {
return [...capturedLogs];
}
function getTestLogsByLevel(level) {
return capturedLogs.filter((log) => log.level === level);
}
function clearTestLogs() {
capturedLogs.length = 0;
}
function getTestLogsCount() {
return capturedLogs.length;
}
var capturedLogs, LOG_LEVEL_PRIORITY;
var init_test_adapter = __esm({
"src/core/test-adapter.ts"() {
"use strict";
capturedLogs = [];
LOG_LEVEL_PRIORITY = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
isNodeEnvironment() {
return typeof process !== "undefined" && process.versions?.node !== void 0;
}
});
};
// src/core/console-adapter.ts
var console_adapter_exports = {};
__export(console_adapter_exports, {
createConsoleLogger: () => createConsoleLogger
});
function createConsoleLogger(config = {}) {
const finalConfig = { ...defaultConfig, ...config };
const levelThreshold = LOG_LEVELS[finalConfig.level || "info"];
const name = finalConfig.name || "app";
const formatMessage = (level, ...args) => {
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;
return `${prefix} ${args.join(" ")}`;
// src/LoggerFactoryImpl.ts
var externalFactory = null;
var factoryVersion = 0;
var LoggerFactoryImpl = class {
static loggers = /* @__PURE__ */ new Map();
static config = {
defaultLevel: "info"
};
const shouldLog2 = (level) => {
return LOG_LEVELS[level] >= levelThreshold;
};
const logMethod = (level, consoleMethod) => {
return (...args) => {
if (!shouldLog2(level)) return;
if (!finalConfig.console) return;
const message = formatMessage(level, ...args);
consoleMethod(message);
};
};
return {
trace: logMethod("trace", console.log),
debug: logMethod("debug", console.log),
info: logMethod("info", console.info),
warn: logMethod("warn", console.warn),
error: logMethod("error", console.error),
fatal: logMethod("fatal", console.error)
};
}
var LOG_LEVELS, defaultConfig;
var init_console_adapter = __esm({
"src/core/console-adapter.ts"() {
"use strict";
LOG_LEVELS = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
defaultConfig = {
level: "info",
console: true,
colors: true,
name: "app"
};
static getLogger(nameOrClass) {
const name = typeof nameOrClass === "string" ? nameOrClass : nameOrClass.name;
if (this.loggers.has(name)) {
return this.loggers.get(name);
}
const lazyLogger = this.createLazyLogger(name);
this.loggers.set(name, lazyLogger);
return lazyLogger;
}
});
// src/index.ts
var index_exports = {};
__export(index_exports, {
DefaultLogger: () => DefaultLogger,
createLogger: () => createLogger
});
module.exports = __toCommonJS(index_exports);
// src/core/adapter-factory.ts
function detectEnvironment() {
if (typeof process !== "undefined" && (process.env.VITEST === "true" || process.env.JEST_WORKER_ID !== void 0 || process.env.NODE_ENV === "test")) {
return "test";
static configure(config) {
this.config = { ...this.config, ...config };
}
if (typeof globalThis !== "undefined" && "caches" in globalThis && "Request" in globalThis && "Response" in globalThis) {
return "cloudflare-workers";
static reset() {
this.loggers.clear();
this.config = { defaultLevel: "info" };
externalFactory = null;
factoryVersion++;
}
if (typeof process !== "undefined" && process.versions && process.versions.node) {
return "nodejs";
static createLazyLogger(name) {
let realLogger = null;
let loggerVersion = -1;
const getRealLogger = () => {
if (!realLogger || loggerVersion !== factoryVersion) {
realLogger = this.createLogger(name);
loggerVersion = factoryVersion;
}
return realLogger;
};
return {
name,
level: this.config.defaultLevel || "info",
debug: (message, context) => getRealLogger().debug(message, context),
info: (message, context) => getRealLogger().info(message, context),
warn: (message, context) => getRealLogger().warn(message, context),
error: (message, context) => getRealLogger().error(message, context),
isDebugEnabled: () => getRealLogger().isDebugEnabled(),
isInfoEnabled: () => getRealLogger().isInfoEnabled(),
isWarnEnabled: () => getRealLogger().isWarnEnabled(),
isErrorEnabled: () => getRealLogger().isErrorEnabled()
};
}
return "browser";
}
async function createLoggerAdapter(config = {}) {
const env = config.environment || detectEnvironment();
if (env === "test") {
const { createTestLogger: createTestLogger2 } = await Promise.resolve().then(() => (init_test_adapter(), test_adapter_exports));
return createTestLogger2(config);
} else if (env === "nodejs") {
const adapterPath = "./pino-adapter.js";
const { createPinoLogger } = await import(
/* @vite-ignore */
adapterPath
);
return createPinoLogger(config);
} else {
const { createConsoleLogger: createConsoleLogger2 } = await Promise.resolve().then(() => (init_console_adapter(), console_adapter_exports));
return createConsoleLogger2(config);
}
}
// src/api/logger.ts
var DefaultLogger = class {
adapter;
initPromise;
constructor(config = {}) {
this.initPromise = createLoggerAdapter(config).then((adapter) => {
this.adapter = adapter;
static createLogger(name) {
if (externalFactory) {
return externalFactory.getLogger(name);
}
if (this.config.defaultImplementation) {
return this.config.defaultImplementation(name);
}
return new ConsoleLogger(name, {
level: this.config.defaultLevel,
...this.config.consoleOptions
});
}
// All methods are typed as `any` for maximum flexibility
trace = async (...args) => {
await this.initPromise;
this.adapter.trace(...args);
};
debug = async (...args) => {
await this.initPromise;
this.adapter.debug(...args);
};
info = async (...args) => {
await this.initPromise;
this.adapter.info(...args);
};
warn = async (...args) => {
await this.initPromise;
this.adapter.warn(...args);
};
error = async (...args) => {
await this.initPromise;
this.adapter.error(...args);
};
fatal = async (...args) => {
await this.initPromise;
this.adapter.fatal(...args);
};
};
function createLogger(config = {}) {
return new DefaultLogger(config);
function setLoggerFactory(factory) {
externalFactory = factory;
LoggerFactoryImpl.reset();
externalFactory = factory;
}
function createLogger(name) {
return LoggerFactoryImpl.getLogger(name);
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
DefaultLogger,
createLogger
ConsoleLogger,
LoggerFactoryImpl,
createLogger,
setLoggerFactory
});
//# sourceMappingURL=index.cjs.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/core/test-adapter.ts","../src/core/console-adapter.ts","../src/index.ts","../src/core/adapter-factory.ts","../src/api/logger.ts"],"sourcesContent":["/**\n * Test adapter - In-memory logger for testing environments\n * Captures all logs in memory for inspection and assertion\n */\nimport type { LoggerConfig, LogLevel } from \"~/types/index.js\";\n\nexport interface CapturedLog {\n level: LogLevel;\n message: string;\n context?: Record<string, any>;\n timestamp: number;\n}\n\n/**\n * Global log storage for test environment\n * Shared across all test logger instances in the same process\n */\nconst capturedLogs: CapturedLog[] = [];\n\n/**\n * Log level priority mapping for filtering\n */\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\n/**\n * Get current log level priority\n */\nfunction getMinLogLevel(level: LogLevel = \"info\"): number {\n return LOG_LEVEL_PRIORITY[level];\n}\n\n/**\n * Check if a log level should be recorded based on config\n */\nfunction shouldLog(level: LogLevel, minLevel: number): boolean {\n return LOG_LEVEL_PRIORITY[level] >= minLevel;\n}\n\n/**\n * Create a log entry and optionally output to console\n */\nfunction createLogEntry(\n level: LogLevel,\n args: any[],\n shouldOutput: boolean,\n minLevel: number,\n): void {\n // Check if this level should be logged\n if (!shouldLog(level, minLevel)) {\n return;\n }\n\n let message: string;\n let context: Record<string, any> | undefined;\n\n // Parse arguments - support both (message) and (context, message) patterns\n if (args.length === 1) {\n if (typeof args[0] === \"string\") {\n message = args[0];\n } else {\n context = args[0];\n message = JSON.stringify(args[0]);\n }\n } else if (args.length >= 2) {\n // First arg might be context object\n if (typeof args[0] === \"object\" && args[0] !== null) {\n context = args[0];\n message = args.slice(1).join(\" \");\n } else {\n message = args.join(\" \");\n }\n } else {\n message = \"\";\n }\n\n // Always capture in memory\n capturedLogs.push({\n level,\n message,\n context,\n timestamp: Date.now(),\n });\n\n // Optionally output to console\n if (shouldOutput) {\n const consoleMethod = level === \"fatal\" ? \"error\" : level;\n const logFn = (console as any)[consoleMethod] || console.log;\n\n if (context) {\n logFn(`[${level.toUpperCase()}]`, context, message);\n } else {\n logFn(`[${level.toUpperCase()}]`, message);\n }\n }\n}\n\n/**\n * Create a test logger instance\n */\nexport function createTestLogger(config: LoggerConfig = {}): any {\n // Default: silent in tests (console: false), unless explicitly enabled\n const shouldOutput = config.console === true;\n const minLevel = getMinLogLevel(config.level);\n\n return {\n trace: (...args: any[]) =>\n createLogEntry(\"trace\", args, shouldOutput, minLevel),\n debug: (...args: any[]) =>\n createLogEntry(\"debug\", args, shouldOutput, minLevel),\n info: (...args: any[]) =>\n createLogEntry(\"info\", args, shouldOutput, minLevel),\n warn: (...args: any[]) =>\n createLogEntry(\"warn\", args, shouldOutput, minLevel),\n error: (...args: any[]) =>\n createLogEntry(\"error\", args, shouldOutput, minLevel),\n fatal: (...args: any[]) =>\n createLogEntry(\"fatal\", args, shouldOutput, minLevel),\n };\n}\n\n/**\n * Get all captured logs\n */\nexport function getTestLogs(): CapturedLog[] {\n return [...capturedLogs];\n}\n\n/**\n * Get logs filtered by level\n */\nexport function getTestLogsByLevel(level: LogLevel): CapturedLog[] {\n return capturedLogs.filter((log) => log.level === level);\n}\n\n/**\n * Clear all captured logs\n */\nexport function clearTestLogs(): void {\n capturedLogs.length = 0;\n}\n\n/**\n * Get the count of captured logs\n */\nexport function getTestLogsCount(): number {\n return capturedLogs.length;\n}\n","/**\n * Console logger adapter - for edge runtimes and browsers\n */\nimport type { LoggerConfig } from \"~/types/config.js\";\nimport type { LogLevel } from \"~/types/logger.js\";\n\ninterface ConsoleLoggerInstance {\n trace: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n fatal: (...args: any[]) => void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\nconst defaultConfig: LoggerConfig = {\n level: \"info\",\n console: true,\n colors: true,\n name: \"app\",\n};\n\n/**\n * Create a console-based logger instance for edge runtimes\n */\nexport function createConsoleLogger(\n config: LoggerConfig = {},\n): ConsoleLoggerInstance {\n const finalConfig = { ...defaultConfig, ...config };\n const levelThreshold = LOG_LEVELS[finalConfig.level || \"info\"];\n const name = finalConfig.name || \"app\";\n\n const formatMessage = (level: LogLevel, ...args: any[]): string => {\n const timestamp = new Date().toISOString();\n const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;\n return `${prefix} ${args.join(\" \")}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return LOG_LEVELS[level] >= levelThreshold;\n };\n\n const logMethod = (level: LogLevel, consoleMethod: any) => {\n return (...args: any[]) => {\n if (!shouldLog(level)) return;\n if (!finalConfig.console) return;\n\n const message = formatMessage(level, ...args);\n consoleMethod(message);\n };\n };\n\n return {\n trace: logMethod(\"trace\", console.log),\n debug: logMethod(\"debug\", console.log),\n info: logMethod(\"info\", console.info),\n warn: logMethod(\"warn\", console.warn),\n error: logMethod(\"error\", console.error),\n fatal: logMethod(\"fatal\", console.error),\n };\n}\n","/**\n * @deepracticex/logger\n *\n * Unified logging solution with environment-aware adapters\n * - Pino for Node.js (high performance, structured logging)\n * - Console adapter for edge runtimes (Cloudflare Workers, Deno, browser)\n * - Zero side effects: no instances created at module load time\n * - Explicit configuration: users must explicitly create logger instances\n */\n\n// Export core API only\nexport { DefaultLogger, createLogger } from \"~/api/logger.js\";\n\n// Export types\nexport type { Logger, LoggerConfig, LogLevel } from \"~/types/index.js\";\n","/**\n * Logger adapter factory - auto-detect environment and create appropriate logger\n */\nimport type { LoggerConfig, RuntimeEnvironment } from \"~/types/config.js\";\n\n/**\n * Detect the current runtime environment\n */\nexport function detectEnvironment(): RuntimeEnvironment {\n // Priority 0: Check for test environment (vitest, jest, etc.)\n // Test environments should use in-memory test adapter\n if (\n typeof process !== \"undefined\" &&\n (process.env.VITEST === \"true\" ||\n process.env.JEST_WORKER_ID !== undefined ||\n process.env.NODE_ENV === \"test\")\n ) {\n return \"test\";\n }\n\n // Priority 1: Check for Cloudflare Workers specific globals\n // Workers have caches API - this is the most reliable indicator\n // If these globals exist, it's definitely Cloudflare Workers runtime\n if (\n typeof globalThis !== \"undefined\" &&\n \"caches\" in globalThis &&\n \"Request\" in globalThis &&\n \"Response\" in globalThis\n ) {\n // Presence of Workers globals is sufficient - return immediately\n // Don't check fs/process as they're unreliable in wrangler dev with nodejs_compat\n return \"cloudflare-workers\";\n }\n\n // Priority 2: Check for Node.js\n if (\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node\n ) {\n return \"nodejs\";\n }\n\n // Fallback to browser\n return \"browser\";\n}\n\n/**\n * Create appropriate logger adapter based on environment\n *\n * Uses dynamic import() to conditionally load adapters based on runtime.\n * Tree-shaking in production builds ensures unused adapters are removed.\n */\nexport async function createLoggerAdapter(\n config: LoggerConfig = {},\n): Promise<any> {\n const env = config.environment || detectEnvironment();\n\n if (env === \"test\") {\n // Test adapter for vitest/jest - in-memory, silent by default\n const { createTestLogger } = await import(\"./test-adapter.js\");\n return createTestLogger(config);\n } else if (env === \"nodejs\") {\n // Use string concatenation to hide import from bundler static analysis\n // This prevents edge runtime bundlers from including Node.js-only dependencies\n const adapterPath = \"./pino-adapter\" + \".js\";\n const { createPinoLogger } = await import(/* @vite-ignore */ adapterPath);\n return createPinoLogger(config);\n } else {\n // Console adapter is safe for all environments\n const { createConsoleLogger } = await import(\"./console-adapter.js\");\n return createConsoleLogger(config);\n }\n}\n","/**\n * Default logger implementation\n */\nimport type { Logger, LoggerConfig } from \"~/types/index.js\";\nimport { createLoggerAdapter } from \"~/core/adapter-factory.js\";\n\nexport class DefaultLogger implements Logger {\n private adapter: any;\n private initPromise: Promise<void>;\n\n constructor(config: LoggerConfig = {}) {\n // Initialize adapter asynchronously\n this.initPromise = createLoggerAdapter(config).then((adapter) => {\n this.adapter = adapter;\n });\n }\n\n // All methods are typed as `any` for maximum flexibility\n trace: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.trace as any)(...args);\n };\n\n debug: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.debug as any)(...args);\n };\n\n info: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.info as any)(...args);\n };\n\n warn: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.warn as any)(...args);\n };\n\n error: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.error as any)(...args);\n };\n\n fatal: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.fatal as any)(...args);\n };\n}\n\n/**\n * Factory function to create a logger instance\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n return new DefaultLogger(config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkCA,SAAS,eAAe,QAAkB,QAAgB;AACxD,SAAO,mBAAmB,KAAK;AACjC;AAKA,SAAS,UAAU,OAAiB,UAA2B;AAC7D,SAAO,mBAAmB,KAAK,KAAK;AACtC;AAKA,SAAS,eACP,OACA,MACA,cACA,UACM;AAEN,MAAI,CAAC,UAAU,OAAO,QAAQ,GAAG;AAC/B;AAAA,EACF;AAEA,MAAI;AACJ,MAAI;AAGJ,MAAI,KAAK,WAAW,GAAG;AACrB,QAAI,OAAO,KAAK,CAAC,MAAM,UAAU;AAC/B,gBAAU,KAAK,CAAC;AAAA,IAClB,OAAO;AACL,gBAAU,KAAK,CAAC;AAChB,gBAAU,KAAK,UAAU,KAAK,CAAC,CAAC;AAAA,IAClC;AAAA,EACF,WAAW,KAAK,UAAU,GAAG;AAE3B,QAAI,OAAO,KAAK,CAAC,MAAM,YAAY,KAAK,CAAC,MAAM,MAAM;AACnD,gBAAU,KAAK,CAAC;AAChB,gBAAU,KAAK,MAAM,CAAC,EAAE,KAAK,GAAG;AAAA,IAClC,OAAO;AACL,gBAAU,KAAK,KAAK,GAAG;AAAA,IACzB;AAAA,EACF,OAAO;AACL,cAAU;AAAA,EACZ;AAGA,eAAa,KAAK;AA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AAa,UAAU,SAAgB;AACrC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,MAAc,GAAG,IAAI;AAAA,EACrC;AAAA,EAEA,OAAY,UAAU,SAAgB;AACpC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,KAAa,GAAG,IAAI;AAAA,EACpC;AAAA,EAEA,OAAY,UAAU,SAAgB;AACpC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,KAAa,GAAG,IAAI;AAAA,EACpC;AAAA,EAEA,QAAa,UAAU,SAAgB;AACrC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,MAAc,GAAG,IAAI;AAAA,EACrC;AAAA,EAEA,QAAa,UAAU,SAAgB;AACrC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,MAAc,GAAG,IAAI;AAAA,EACrC;AACF;AAKO,SAAS,aAAa,SAAuB,CAAC,GAAW;AAC9D,SAAO,IAAI,cAAc,MAAM;AACjC;","names":["shouldLog","createTestLogger","createConsoleLogger"]}
{"version":3,"sources":["../src/index.ts","../src/ConsoleLogger.ts","../src/LoggerFactoryImpl.ts"],"sourcesContent":["/**\n * Logger module\n *\n * Provides lazy-initialized logging with pluggable backends.\n *\n * @example\n * ```typescript\n * import { createLogger } from \"commonxjs/logger\";\n *\n * // Safe at module level (before Runtime configured)\n * const logger = createLogger(\"engine/AgentEngine\");\n *\n * // Later, at runtime\n * logger.info(\"Agent initialized\", { agentId: \"xxx\" });\n * ```\n */\n\nexport type { LogLevel, LogContext, Logger, LoggerFactory } from \"./types\";\nexport { ConsoleLogger, type ConsoleLoggerOptions } from \"./ConsoleLogger\";\nexport {\n LoggerFactoryImpl,\n type LoggerFactoryConfig,\n setLoggerFactory,\n createLogger,\n} from \"./LoggerFactoryImpl\";\n","/**\n * ConsoleLogger - Default logger implementation\n *\n * Simple console-based logger with color support.\n * Used as fallback when no custom LoggerFactory is provided.\n */\n\nimport type { Logger, LogContext, LogLevel } from \"./types\";\n\nexport interface ConsoleLoggerOptions {\n level?: LogLevel;\n colors?: boolean;\n timestamps?: boolean;\n}\n\nexport class ConsoleLogger implements Logger {\n readonly name: string;\n readonly level: LogLevel;\n private readonly colors: boolean;\n private readonly timestamps: boolean;\n\n private static readonly COLORS = {\n DEBUG: \"\\x1b[36m\",\n INFO: \"\\x1b[32m\",\n WARN: \"\\x1b[33m\",\n ERROR: \"\\x1b[31m\",\n RESET: \"\\x1b[0m\",\n };\n\n constructor(name: string, options: ConsoleLoggerOptions = {}) {\n this.name = name;\n this.level = options.level ?? \"info\";\n this.colors = options.colors ?? this.isNodeEnvironment();\n this.timestamps = options.timestamps ?? true;\n }\n\n debug(message: string, context?: LogContext): void {\n if (this.isDebugEnabled()) {\n this.log(\"DEBUG\", message, context);\n }\n }\n\n info(message: string, context?: LogContext): void {\n if (this.isInfoEnabled()) {\n this.log(\"INFO\", message, context);\n }\n }\n\n warn(message: string, context?: LogContext): void {\n if (this.isWarnEnabled()) {\n this.log(\"WARN\", message, context);\n }\n }\n\n error(message: string | Error, context?: LogContext): void {\n if (this.isErrorEnabled()) {\n if (message instanceof Error) {\n this.log(\"ERROR\", message.message, { ...context, stack: message.stack });\n } else {\n this.log(\"ERROR\", message, context);\n }\n }\n }\n\n isDebugEnabled(): boolean {\n return this.getLevelValue(this.level) <= this.getLevelValue(\"debug\");\n }\n\n isInfoEnabled(): boolean {\n return this.getLevelValue(this.level) <= this.getLevelValue(\"info\");\n }\n\n isWarnEnabled(): boolean {\n return this.getLevelValue(this.level) <= this.getLevelValue(\"warn\");\n }\n\n isErrorEnabled(): boolean {\n return this.getLevelValue(this.level) <= this.getLevelValue(\"error\");\n }\n\n private getLevelValue(level: LogLevel): number {\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n silent: 4,\n };\n return levels[level];\n }\n\n private log(level: string, message: string, context?: LogContext): void {\n const parts: string[] = [];\n\n if (this.timestamps) {\n parts.push(new Date().toISOString());\n }\n\n if (this.colors) {\n const color = ConsoleLogger.COLORS[level as keyof typeof ConsoleLogger.COLORS];\n parts.push(`${color}${level.padEnd(5)}${ConsoleLogger.COLORS.RESET}`);\n } else {\n parts.push(level.padEnd(5));\n }\n\n parts.push(`[${this.name}]`);\n parts.push(message);\n\n const logLine = parts.join(\" \");\n const consoleMethod = this.getConsoleMethod(level);\n\n if (context && Object.keys(context).length > 0) {\n consoleMethod(logLine, context);\n } else {\n consoleMethod(logLine);\n }\n }\n\n private getConsoleMethod(level: string): (...args: unknown[]) => void {\n switch (level) {\n case \"DEBUG\":\n return console.debug.bind(console);\n case \"INFO\":\n return console.info.bind(console);\n case \"WARN\":\n return console.warn.bind(console);\n case \"ERROR\":\n return console.error.bind(console);\n default:\n return console.log.bind(console);\n }\n }\n\n private isNodeEnvironment(): boolean {\n return typeof process !== \"undefined\" && process.versions?.node !== undefined;\n }\n}\n","/**\n * LoggerFactoryImpl - Central factory for creating logger instances\n *\n * Implements lazy initialization pattern:\n * - createLogger() can be called at module level (before config)\n * - Real logger is created on first use\n * - External LoggerFactory can be injected via Runtime\n */\n\nimport type { Logger, LoggerFactory, LogContext, LogLevel } from \"./types\";\nimport { ConsoleLogger, type ConsoleLoggerOptions } from \"./ConsoleLogger\";\n\n// External factory injected via Runtime\nlet externalFactory: LoggerFactory | null = null;\n\n// Version counter to invalidate cached real loggers\nlet factoryVersion = 0;\n\nexport interface LoggerFactoryConfig {\n defaultImplementation?: (name: string) => Logger;\n defaultLevel?: LogLevel;\n consoleOptions?: Omit<ConsoleLoggerOptions, \"level\">;\n}\n\n/**\n * Internal LoggerFactory implementation\n *\n * Uses lazy proxy pattern to allow module-level createLogger() calls.\n */\nexport class LoggerFactoryImpl {\n private static loggers: Map<string, Logger> = new Map();\n private static config: LoggerFactoryConfig = {\n defaultLevel: \"info\",\n };\n\n static getLogger(nameOrClass: string | (new (...args: unknown[]) => unknown)): Logger {\n const name = typeof nameOrClass === \"string\" ? nameOrClass : nameOrClass.name;\n\n if (this.loggers.has(name)) {\n return this.loggers.get(name)!;\n }\n\n const lazyLogger = this.createLazyLogger(name);\n this.loggers.set(name, lazyLogger);\n return lazyLogger;\n }\n\n static configure(config: LoggerFactoryConfig): void {\n this.config = { ...this.config, ...config };\n }\n\n static reset(): void {\n this.loggers.clear();\n this.config = { defaultLevel: \"info\" };\n externalFactory = null;\n factoryVersion++; // Invalidate all cached real loggers\n }\n\n private static createLazyLogger(name: string): Logger {\n let realLogger: Logger | null = null;\n let loggerVersion = -1; // Track which factory version created this logger\n\n const getRealLogger = (): Logger => {\n // Recreate logger if factory version changed (setLoggerFactory was called)\n if (!realLogger || loggerVersion !== factoryVersion) {\n realLogger = this.createLogger(name);\n loggerVersion = factoryVersion;\n }\n return realLogger;\n };\n\n return {\n name,\n level: this.config.defaultLevel || \"info\",\n debug: (message: string, context?: LogContext) => getRealLogger().debug(message, context),\n info: (message: string, context?: LogContext) => getRealLogger().info(message, context),\n warn: (message: string, context?: LogContext) => getRealLogger().warn(message, context),\n error: (message: string | Error, context?: LogContext) =>\n getRealLogger().error(message, context),\n isDebugEnabled: () => getRealLogger().isDebugEnabled(),\n isInfoEnabled: () => getRealLogger().isInfoEnabled(),\n isWarnEnabled: () => getRealLogger().isWarnEnabled(),\n isErrorEnabled: () => getRealLogger().isErrorEnabled(),\n };\n }\n\n private static createLogger(name: string): Logger {\n if (externalFactory) {\n return externalFactory.getLogger(name);\n }\n\n if (this.config.defaultImplementation) {\n return this.config.defaultImplementation(name);\n }\n\n return new ConsoleLogger(name, {\n level: this.config.defaultLevel,\n ...this.config.consoleOptions,\n });\n }\n}\n\n/**\n * Set external LoggerFactory (called by Runtime initialization)\n */\nexport function setLoggerFactory(factory: LoggerFactory): void {\n externalFactory = factory;\n LoggerFactoryImpl.reset();\n externalFactory = factory;\n}\n\n/**\n * Create a logger instance\n *\n * Safe to call at module level before Runtime is configured.\n * Uses lazy initialization - actual logger is created on first use.\n *\n * @param name - Logger name (hierarchical, e.g., \"engine/AgentEngine\")\n * @returns Logger instance (lazy proxy)\n */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A,MACA,OAAO,KAAK,OAAO,gBAAgB;AAAA,MACnC,OAAO,CAAC,SAAiB,YAAyB,cAAc,EAAE,MAAM,SAAS,OAAO;AAAA,MACxF,MAAM,CAAC,SAAiB,YAAyB,cAAc,EAAE,KAAK,SAAS,OAAO;AAAA,MACtF,MAAM,CAAC,SAAiB,YAAyB,cAAc,EAAE,KAAK,SAAS,OAAO;AAAA,MACtF,OAAO,CAAC,SAAyB,YAC/B,cAAc,EAAE,MAAM,SAAS,OAAO;AAAA,MACxC,gBAAgB,MAAM,cAAc,EAAE,eAAe;AAAA,MACrD,eAAe,MAAM,cAAc,EAAE,cAAc;AAAA,MACnD,eAAe,MAAM,cAAc,EAAE,cAAc;AAAA,MACnD,gBAAgB,MAAM,cAAc,EAAE,eAAe;AAAA,IACvD;AAAA,EACF;AAAA,EAEA,OAAe,aAAa,MAAsB;AAChD,QAAI,iBAAiB;AACnB,aAAO,gBAAgB,UAAU,IAAI;AAAA,IACvC;AAEA,QAAI,KAAK,OAAO,uBAAuB;AACrC,aAAO,KAAK,OAAO,sBAAsB,IAAI;AAAA,IAC/C;AAEA,WAAO,IAAI,cAAc,MAAM;AAAA,MAC7B,OAAO,KAAK,OAAO;AAAA,MACnB,GAAG,KAAK,OAAO;AAAA,IACjB,CAAC;AAAA,EACH;AACF;AAKO,SAAS,iBAAiB,SAA8B;AAC7D,oBAAkB;AAClB,oBAAkB,MAAM;AACxB,oBAAkB;AACpB;AAWO,SAAS,aAAa,MAAsB;AACjD,SAAO,kBAAkB,UAAU,IAAI;AACzC;","names":[]}

@@ -1,24 +0,112 @@

import { a as Logger, L as LoggerConfig } from './logger-Lmm6XEQc.cjs';
export { b as LogLevel } from './logger-Lmm6XEQc.cjs';
/**
* Logger Types
*
* Type definitions for the logging system.
*/
/**
* Log level
*/
type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
/**
* Log context - additional metadata for log entries
*/
type LogContext = Record<string, unknown>;
/**
* Logger interface
*/
interface Logger {
readonly name: string;
readonly level: LogLevel;
debug(message: string, context?: LogContext): void;
info(message: string, context?: LogContext): void;
warn(message: string, context?: LogContext): void;
error(message: string | Error, context?: LogContext): void;
isDebugEnabled(): boolean;
isInfoEnabled(): boolean;
isWarnEnabled(): boolean;
isErrorEnabled(): boolean;
}
/**
* Logger factory interface
*/
interface LoggerFactory {
getLogger(name: string): Logger;
}
/**
* Default logger implementation
* ConsoleLogger - Default logger implementation
*
* Simple console-based logger with color support.
* Used as fallback when no custom LoggerFactory is provided.
*/
declare class DefaultLogger implements Logger {
private adapter;
private initPromise;
constructor(config?: LoggerConfig);
trace: any;
debug: any;
info: any;
warn: any;
error: any;
fatal: any;
interface ConsoleLoggerOptions {
level?: LogLevel;
colors?: boolean;
timestamps?: boolean;
}
declare class ConsoleLogger implements Logger {
readonly name: string;
readonly level: LogLevel;
private readonly colors;
private readonly timestamps;
private static readonly COLORS;
constructor(name: string, options?: ConsoleLoggerOptions);
debug(message: string, context?: LogContext): void;
info(message: string, context?: LogContext): void;
warn(message: string, context?: LogContext): void;
error(message: string | Error, context?: LogContext): void;
isDebugEnabled(): boolean;
isInfoEnabled(): boolean;
isWarnEnabled(): boolean;
isErrorEnabled(): boolean;
private getLevelValue;
private log;
private getConsoleMethod;
private isNodeEnvironment;
}
/**
* Factory function to create a logger instance
* LoggerFactoryImpl - Central factory for creating logger instances
*
* Implements lazy initialization pattern:
* - createLogger() can be called at module level (before config)
* - Real logger is created on first use
* - External LoggerFactory can be injected via Runtime
*/
declare function createLogger(config?: LoggerConfig): Logger;
export { DefaultLogger, Logger, LoggerConfig, createLogger };
interface LoggerFactoryConfig {
defaultImplementation?: (name: string) => Logger;
defaultLevel?: LogLevel;
consoleOptions?: Omit<ConsoleLoggerOptions, "level">;
}
/**
* Internal LoggerFactory implementation
*
* Uses lazy proxy pattern to allow module-level createLogger() calls.
*/
declare class LoggerFactoryImpl {
private static loggers;
private static config;
static getLogger(nameOrClass: string | (new (...args: unknown[]) => unknown)): Logger;
static configure(config: LoggerFactoryConfig): void;
static reset(): void;
private static createLazyLogger;
private static createLogger;
}
/**
* Set external LoggerFactory (called by Runtime initialization)
*/
declare function setLoggerFactory(factory: LoggerFactory): void;
/**
* Create a logger instance
*
* Safe to call at module level before Runtime is configured.
* Uses lazy initialization - actual logger is created on first use.
*
* @param name - Logger name (hierarchical, e.g., "engine/AgentEngine")
* @returns Logger instance (lazy proxy)
*/
declare function createLogger(name: string): Logger;
export { ConsoleLogger, type ConsoleLoggerOptions, type LogContext, type LogLevel, type Logger, type LoggerFactory, type LoggerFactoryConfig, LoggerFactoryImpl, createLogger, setLoggerFactory };

@@ -1,24 +0,112 @@

import { a as Logger, L as LoggerConfig } from './logger-Lmm6XEQc.js';
export { b as LogLevel } from './logger-Lmm6XEQc.js';
/**
* Logger Types
*
* Type definitions for the logging system.
*/
/**
* Log level
*/
type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
/**
* Log context - additional metadata for log entries
*/
type LogContext = Record<string, unknown>;
/**
* Logger interface
*/
interface Logger {
readonly name: string;
readonly level: LogLevel;
debug(message: string, context?: LogContext): void;
info(message: string, context?: LogContext): void;
warn(message: string, context?: LogContext): void;
error(message: string | Error, context?: LogContext): void;
isDebugEnabled(): boolean;
isInfoEnabled(): boolean;
isWarnEnabled(): boolean;
isErrorEnabled(): boolean;
}
/**
* Logger factory interface
*/
interface LoggerFactory {
getLogger(name: string): Logger;
}
/**
* Default logger implementation
* ConsoleLogger - Default logger implementation
*
* Simple console-based logger with color support.
* Used as fallback when no custom LoggerFactory is provided.
*/
declare class DefaultLogger implements Logger {
private adapter;
private initPromise;
constructor(config?: LoggerConfig);
trace: any;
debug: any;
info: any;
warn: any;
error: any;
fatal: any;
interface ConsoleLoggerOptions {
level?: LogLevel;
colors?: boolean;
timestamps?: boolean;
}
declare class ConsoleLogger implements Logger {
readonly name: string;
readonly level: LogLevel;
private readonly colors;
private readonly timestamps;
private static readonly COLORS;
constructor(name: string, options?: ConsoleLoggerOptions);
debug(message: string, context?: LogContext): void;
info(message: string, context?: LogContext): void;
warn(message: string, context?: LogContext): void;
error(message: string | Error, context?: LogContext): void;
isDebugEnabled(): boolean;
isInfoEnabled(): boolean;
isWarnEnabled(): boolean;
isErrorEnabled(): boolean;
private getLevelValue;
private log;
private getConsoleMethod;
private isNodeEnvironment;
}
/**
* Factory function to create a logger instance
* LoggerFactoryImpl - Central factory for creating logger instances
*
* Implements lazy initialization pattern:
* - createLogger() can be called at module level (before config)
* - Real logger is created on first use
* - External LoggerFactory can be injected via Runtime
*/
declare function createLogger(config?: LoggerConfig): Logger;
export { DefaultLogger, Logger, LoggerConfig, createLogger };
interface LoggerFactoryConfig {
defaultImplementation?: (name: string) => Logger;
defaultLevel?: LogLevel;
consoleOptions?: Omit<ConsoleLoggerOptions, "level">;
}
/**
* Internal LoggerFactory implementation
*
* Uses lazy proxy pattern to allow module-level createLogger() calls.
*/
declare class LoggerFactoryImpl {
private static loggers;
private static config;
static getLogger(nameOrClass: string | (new (...args: unknown[]) => unknown)): Logger;
static configure(config: LoggerFactoryConfig): void;
static reset(): void;
private static createLazyLogger;
private static createLogger;
}
/**
* Set external LoggerFactory (called by Runtime initialization)
*/
declare function setLoggerFactory(factory: LoggerFactory): void;
/**
* Create a logger instance
*
* Safe to call at module level before Runtime is configured.
* Uses lazy initialization - actual logger is created on first use.
*
* @param name - Logger name (hierarchical, e.g., "engine/AgentEngine")
* @returns Logger instance (lazy proxy)
*/
declare function createLogger(name: string): Logger;
export { ConsoleLogger, type ConsoleLoggerOptions, type LogContext, type LogLevel, type Logger, type LoggerFactory, type LoggerFactoryConfig, LoggerFactoryImpl, createLogger, setLoggerFactory };

@@ -1,233 +0,182 @@

var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __esm = (fn, res) => function __init() {
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
// src/core/test-adapter.ts
var test_adapter_exports = {};
__export(test_adapter_exports, {
clearTestLogs: () => clearTestLogs,
createTestLogger: () => createTestLogger,
getTestLogs: () => getTestLogs,
getTestLogsByLevel: () => getTestLogsByLevel,
getTestLogsCount: () => getTestLogsCount
});
function getMinLogLevel(level = "info") {
return LOG_LEVEL_PRIORITY[level];
}
function shouldLog(level, minLevel) {
return LOG_LEVEL_PRIORITY[level] >= minLevel;
}
function createLogEntry(level, args, shouldOutput, minLevel) {
if (!shouldLog(level, minLevel)) {
return;
// src/ConsoleLogger.ts
var ConsoleLogger = class _ConsoleLogger {
name;
level;
colors;
timestamps;
static COLORS = {
DEBUG: "\x1B[36m",
INFO: "\x1B[32m",
WARN: "\x1B[33m",
ERROR: "\x1B[31m",
RESET: "\x1B[0m"
};
constructor(name, options = {}) {
this.name = name;
this.level = options.level ?? "info";
this.colors = options.colors ?? this.isNodeEnvironment();
this.timestamps = options.timestamps ?? true;
}
let message;
let context;
if (args.length === 1) {
if (typeof args[0] === "string") {
message = args[0];
debug(message, context) {
if (this.isDebugEnabled()) {
this.log("DEBUG", message, context);
}
}
info(message, context) {
if (this.isInfoEnabled()) {
this.log("INFO", message, context);
}
}
warn(message, context) {
if (this.isWarnEnabled()) {
this.log("WARN", message, context);
}
}
error(message, context) {
if (this.isErrorEnabled()) {
if (message instanceof Error) {
this.log("ERROR", message.message, { ...context, stack: message.stack });
} else {
this.log("ERROR", message, context);
}
}
}
isDebugEnabled() {
return this.getLevelValue(this.level) <= this.getLevelValue("debug");
}
isInfoEnabled() {
return this.getLevelValue(this.level) <= this.getLevelValue("info");
}
isWarnEnabled() {
return this.getLevelValue(this.level) <= this.getLevelValue("warn");
}
isErrorEnabled() {
return this.getLevelValue(this.level) <= this.getLevelValue("error");
}
getLevelValue(level) {
const levels = {
debug: 0,
info: 1,
warn: 2,
error: 3,
silent: 4
};
return levels[level];
}
log(level, message, context) {
const parts = [];
if (this.timestamps) {
parts.push((/* @__PURE__ */ new Date()).toISOString());
}
if (this.colors) {
const color = _ConsoleLogger.COLORS[level];
parts.push(`${color}${level.padEnd(5)}${_ConsoleLogger.COLORS.RESET}`);
} else {
context = args[0];
message = JSON.stringify(args[0]);
parts.push(level.padEnd(5));
}
} else if (args.length >= 2) {
if (typeof args[0] === "object" && args[0] !== null) {
context = args[0];
message = args.slice(1).join(" ");
parts.push(`[${this.name}]`);
parts.push(message);
const logLine = parts.join(" ");
const consoleMethod = this.getConsoleMethod(level);
if (context && Object.keys(context).length > 0) {
consoleMethod(logLine, context);
} else {
message = args.join(" ");
consoleMethod(logLine);
}
} else {
message = "";
}
capturedLogs.push({
level,
message,
context,
timestamp: Date.now()
});
if (shouldOutput) {
const consoleMethod = level === "fatal" ? "error" : level;
const logFn = console[consoleMethod] || console.log;
if (context) {
logFn(`[${level.toUpperCase()}]`, context, message);
} else {
logFn(`[${level.toUpperCase()}]`, message);
getConsoleMethod(level) {
switch (level) {
case "DEBUG":
return console.debug.bind(console);
case "INFO":
return console.info.bind(console);
case "WARN":
return console.warn.bind(console);
case "ERROR":
return console.error.bind(console);
default:
return console.log.bind(console);
}
}
}
function createTestLogger(config = {}) {
const shouldOutput = config.console === true;
const minLevel = getMinLogLevel(config.level);
return {
trace: (...args) => createLogEntry("trace", args, shouldOutput, minLevel),
debug: (...args) => createLogEntry("debug", args, shouldOutput, minLevel),
info: (...args) => createLogEntry("info", args, shouldOutput, minLevel),
warn: (...args) => createLogEntry("warn", args, shouldOutput, minLevel),
error: (...args) => createLogEntry("error", args, shouldOutput, minLevel),
fatal: (...args) => createLogEntry("fatal", args, shouldOutput, minLevel)
};
}
function getTestLogs() {
return [...capturedLogs];
}
function getTestLogsByLevel(level) {
return capturedLogs.filter((log) => log.level === level);
}
function clearTestLogs() {
capturedLogs.length = 0;
}
function getTestLogsCount() {
return capturedLogs.length;
}
var capturedLogs, LOG_LEVEL_PRIORITY;
var init_test_adapter = __esm({
"src/core/test-adapter.ts"() {
"use strict";
capturedLogs = [];
LOG_LEVEL_PRIORITY = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
isNodeEnvironment() {
return typeof process !== "undefined" && process.versions?.node !== void 0;
}
});
};
// src/core/console-adapter.ts
var console_adapter_exports = {};
__export(console_adapter_exports, {
createConsoleLogger: () => createConsoleLogger
});
function createConsoleLogger(config = {}) {
const finalConfig = { ...defaultConfig, ...config };
const levelThreshold = LOG_LEVELS[finalConfig.level || "info"];
const name = finalConfig.name || "app";
const formatMessage = (level, ...args) => {
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;
return `${prefix} ${args.join(" ")}`;
// src/LoggerFactoryImpl.ts
var externalFactory = null;
var factoryVersion = 0;
var LoggerFactoryImpl = class {
static loggers = /* @__PURE__ */ new Map();
static config = {
defaultLevel: "info"
};
const shouldLog2 = (level) => {
return LOG_LEVELS[level] >= levelThreshold;
};
const logMethod = (level, consoleMethod) => {
return (...args) => {
if (!shouldLog2(level)) return;
if (!finalConfig.console) return;
const message = formatMessage(level, ...args);
consoleMethod(message);
};
};
return {
trace: logMethod("trace", console.log),
debug: logMethod("debug", console.log),
info: logMethod("info", console.info),
warn: logMethod("warn", console.warn),
error: logMethod("error", console.error),
fatal: logMethod("fatal", console.error)
};
}
var LOG_LEVELS, defaultConfig;
var init_console_adapter = __esm({
"src/core/console-adapter.ts"() {
"use strict";
LOG_LEVELS = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
defaultConfig = {
level: "info",
console: true,
colors: true,
name: "app"
};
static getLogger(nameOrClass) {
const name = typeof nameOrClass === "string" ? nameOrClass : nameOrClass.name;
if (this.loggers.has(name)) {
return this.loggers.get(name);
}
const lazyLogger = this.createLazyLogger(name);
this.loggers.set(name, lazyLogger);
return lazyLogger;
}
});
// src/core/adapter-factory.ts
function detectEnvironment() {
if (typeof process !== "undefined" && (process.env.VITEST === "true" || process.env.JEST_WORKER_ID !== void 0 || process.env.NODE_ENV === "test")) {
return "test";
static configure(config) {
this.config = { ...this.config, ...config };
}
if (typeof globalThis !== "undefined" && "caches" in globalThis && "Request" in globalThis && "Response" in globalThis) {
return "cloudflare-workers";
static reset() {
this.loggers.clear();
this.config = { defaultLevel: "info" };
externalFactory = null;
factoryVersion++;
}
if (typeof process !== "undefined" && process.versions && process.versions.node) {
return "nodejs";
static createLazyLogger(name) {
let realLogger = null;
let loggerVersion = -1;
const getRealLogger = () => {
if (!realLogger || loggerVersion !== factoryVersion) {
realLogger = this.createLogger(name);
loggerVersion = factoryVersion;
}
return realLogger;
};
return {
name,
level: this.config.defaultLevel || "info",
debug: (message, context) => getRealLogger().debug(message, context),
info: (message, context) => getRealLogger().info(message, context),
warn: (message, context) => getRealLogger().warn(message, context),
error: (message, context) => getRealLogger().error(message, context),
isDebugEnabled: () => getRealLogger().isDebugEnabled(),
isInfoEnabled: () => getRealLogger().isInfoEnabled(),
isWarnEnabled: () => getRealLogger().isWarnEnabled(),
isErrorEnabled: () => getRealLogger().isErrorEnabled()
};
}
return "browser";
}
async function createLoggerAdapter(config = {}) {
const env = config.environment || detectEnvironment();
if (env === "test") {
const { createTestLogger: createTestLogger2 } = await Promise.resolve().then(() => (init_test_adapter(), test_adapter_exports));
return createTestLogger2(config);
} else if (env === "nodejs") {
const adapterPath = "./pino-adapter.js";
const { createPinoLogger } = await import(
/* @vite-ignore */
adapterPath
);
return createPinoLogger(config);
} else {
const { createConsoleLogger: createConsoleLogger2 } = await Promise.resolve().then(() => (init_console_adapter(), console_adapter_exports));
return createConsoleLogger2(config);
}
}
// src/api/logger.ts
var DefaultLogger = class {
adapter;
initPromise;
constructor(config = {}) {
this.initPromise = createLoggerAdapter(config).then((adapter) => {
this.adapter = adapter;
static createLogger(name) {
if (externalFactory) {
return externalFactory.getLogger(name);
}
if (this.config.defaultImplementation) {
return this.config.defaultImplementation(name);
}
return new ConsoleLogger(name, {
level: this.config.defaultLevel,
...this.config.consoleOptions
});
}
// All methods are typed as `any` for maximum flexibility
trace = async (...args) => {
await this.initPromise;
this.adapter.trace(...args);
};
debug = async (...args) => {
await this.initPromise;
this.adapter.debug(...args);
};
info = async (...args) => {
await this.initPromise;
this.adapter.info(...args);
};
warn = async (...args) => {
await this.initPromise;
this.adapter.warn(...args);
};
error = async (...args) => {
await this.initPromise;
this.adapter.error(...args);
};
fatal = async (...args) => {
await this.initPromise;
this.adapter.fatal(...args);
};
};
function createLogger(config = {}) {
return new DefaultLogger(config);
function setLoggerFactory(factory) {
externalFactory = factory;
LoggerFactoryImpl.reset();
externalFactory = factory;
}
function createLogger(name) {
return LoggerFactoryImpl.getLogger(name);
}
export {
DefaultLogger,
createLogger
ConsoleLogger,
LoggerFactoryImpl,
createLogger,
setLoggerFactory
};
//# sourceMappingURL=index.js.map

@@ -1,1 +0,1 @@

{"version":3,"sources":["../src/core/test-adapter.ts","../src/core/console-adapter.ts","../src/core/adapter-factory.ts","../src/api/logger.ts"],"sourcesContent":["/**\n * Test adapter - In-memory logger for testing environments\n * Captures all logs in memory for inspection and assertion\n */\nimport type { LoggerConfig, LogLevel } from \"~/types/index.js\";\n\nexport interface CapturedLog {\n level: LogLevel;\n message: string;\n context?: Record<string, any>;\n timestamp: number;\n}\n\n/**\n * Global log storage for test environment\n * Shared across all test logger instances in the same process\n */\nconst capturedLogs: CapturedLog[] = [];\n\n/**\n * Log level priority mapping for filtering\n */\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\n/**\n * Get current log level priority\n */\nfunction getMinLogLevel(level: LogLevel = \"info\"): number {\n return LOG_LEVEL_PRIORITY[level];\n}\n\n/**\n * Check if a log level should be recorded based on config\n */\nfunction shouldLog(level: LogLevel, minLevel: number): boolean {\n return LOG_LEVEL_PRIORITY[level] >= minLevel;\n}\n\n/**\n * Create a log entry and optionally output to console\n */\nfunction createLogEntry(\n level: LogLevel,\n args: any[],\n shouldOutput: boolean,\n minLevel: number,\n): void {\n // Check if this level should be logged\n if (!shouldLog(level, minLevel)) {\n return;\n }\n\n let message: string;\n let context: Record<string, any> | undefined;\n\n // Parse arguments - support both (message) and (context, message) patterns\n if (args.length === 1) {\n if (typeof args[0] === \"string\") {\n message = args[0];\n } else {\n context = args[0];\n message = JSON.stringify(args[0]);\n }\n } else if (args.length >= 2) {\n // First arg might be context object\n if (typeof args[0] === \"object\" && args[0] !== null) {\n context = args[0];\n message = args.slice(1).join(\" \");\n } else {\n message = args.join(\" \");\n }\n } else {\n message = \"\";\n }\n\n // Always capture in memory\n capturedLogs.push({\n level,\n message,\n context,\n timestamp: Date.now(),\n });\n\n // Optionally output to console\n if (shouldOutput) {\n const consoleMethod = level === \"fatal\" ? \"error\" : level;\n const logFn = (console as any)[consoleMethod] || console.log;\n\n if (context) {\n logFn(`[${level.toUpperCase()}]`, context, message);\n } else {\n logFn(`[${level.toUpperCase()}]`, message);\n }\n }\n}\n\n/**\n * Create a test logger instance\n */\nexport function createTestLogger(config: LoggerConfig = {}): any {\n // Default: silent in tests (console: false), unless explicitly enabled\n const shouldOutput = config.console === true;\n const minLevel = getMinLogLevel(config.level);\n\n return {\n trace: (...args: any[]) =>\n createLogEntry(\"trace\", args, shouldOutput, minLevel),\n debug: (...args: any[]) =>\n createLogEntry(\"debug\", args, shouldOutput, minLevel),\n info: (...args: any[]) =>\n createLogEntry(\"info\", args, shouldOutput, minLevel),\n warn: (...args: any[]) =>\n createLogEntry(\"warn\", args, shouldOutput, minLevel),\n error: (...args: any[]) =>\n createLogEntry(\"error\", args, shouldOutput, minLevel),\n fatal: (...args: any[]) =>\n createLogEntry(\"fatal\", args, shouldOutput, minLevel),\n };\n}\n\n/**\n * Get all captured logs\n */\nexport function getTestLogs(): CapturedLog[] {\n return [...capturedLogs];\n}\n\n/**\n * Get logs filtered by level\n */\nexport function getTestLogsByLevel(level: LogLevel): CapturedLog[] {\n return capturedLogs.filter((log) => log.level === level);\n}\n\n/**\n * Clear all captured logs\n */\nexport function clearTestLogs(): void {\n capturedLogs.length = 0;\n}\n\n/**\n * Get the count of captured logs\n */\nexport function getTestLogsCount(): number {\n return capturedLogs.length;\n}\n","/**\n * Console logger adapter - for edge runtimes and browsers\n */\nimport type { LoggerConfig } from \"~/types/config.js\";\nimport type { LogLevel } from \"~/types/logger.js\";\n\ninterface ConsoleLoggerInstance {\n trace: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n fatal: (...args: any[]) => void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\nconst defaultConfig: LoggerConfig = {\n level: \"info\",\n console: true,\n colors: true,\n name: \"app\",\n};\n\n/**\n * Create a console-based logger instance for edge runtimes\n */\nexport function createConsoleLogger(\n config: LoggerConfig = {},\n): ConsoleLoggerInstance {\n const finalConfig = { ...defaultConfig, ...config };\n const levelThreshold = LOG_LEVELS[finalConfig.level || \"info\"];\n const name = finalConfig.name || \"app\";\n\n const formatMessage = (level: LogLevel, ...args: any[]): string => {\n const timestamp = new Date().toISOString();\n const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;\n return `${prefix} ${args.join(\" \")}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return LOG_LEVELS[level] >= levelThreshold;\n };\n\n const logMethod = (level: LogLevel, consoleMethod: any) => {\n return (...args: any[]) => {\n if (!shouldLog(level)) return;\n if (!finalConfig.console) return;\n\n const message = formatMessage(level, ...args);\n consoleMethod(message);\n };\n };\n\n return {\n trace: logMethod(\"trace\", console.log),\n debug: logMethod(\"debug\", console.log),\n info: logMethod(\"info\", console.info),\n warn: logMethod(\"warn\", console.warn),\n error: logMethod(\"error\", console.error),\n fatal: logMethod(\"fatal\", console.error),\n };\n}\n","/**\n * Logger adapter factory - auto-detect environment and create appropriate logger\n */\nimport type { LoggerConfig, RuntimeEnvironment } from \"~/types/config.js\";\n\n/**\n * Detect the current runtime environment\n */\nexport function detectEnvironment(): RuntimeEnvironment {\n // Priority 0: Check for test environment (vitest, jest, etc.)\n // Test environments should use in-memory test adapter\n if (\n typeof process !== \"undefined\" &&\n (process.env.VITEST === \"true\" ||\n process.env.JEST_WORKER_ID !== undefined ||\n process.env.NODE_ENV === \"test\")\n ) {\n return \"test\";\n }\n\n // Priority 1: Check for Cloudflare Workers specific globals\n // Workers have caches API - this is the most reliable indicator\n // If these globals exist, it's definitely Cloudflare Workers runtime\n if (\n typeof globalThis !== \"undefined\" &&\n \"caches\" in globalThis &&\n \"Request\" in globalThis &&\n \"Response\" in globalThis\n ) {\n // Presence of Workers globals is sufficient - return immediately\n // Don't check fs/process as they're unreliable in wrangler dev with nodejs_compat\n return \"cloudflare-workers\";\n }\n\n // Priority 2: Check for Node.js\n if (\n typeof process !== \"undefined\" &&\n process.versions &&\n process.versions.node\n ) {\n return \"nodejs\";\n }\n\n // Fallback to browser\n return \"browser\";\n}\n\n/**\n * Create appropriate logger adapter based on environment\n *\n * Uses dynamic import() to conditionally load adapters based on runtime.\n * Tree-shaking in production builds ensures unused adapters are removed.\n */\nexport async function createLoggerAdapter(\n config: LoggerConfig = {},\n): Promise<any> {\n const env = config.environment || detectEnvironment();\n\n if (env === \"test\") {\n // Test adapter for vitest/jest - in-memory, silent by default\n const { createTestLogger } = await import(\"./test-adapter.js\");\n return createTestLogger(config);\n } else if (env === \"nodejs\") {\n // Use string concatenation to hide import from bundler static analysis\n // This prevents edge runtime bundlers from including Node.js-only dependencies\n const adapterPath = \"./pino-adapter\" + \".js\";\n const { createPinoLogger } = await import(/* @vite-ignore */ adapterPath);\n return createPinoLogger(config);\n } else {\n // Console adapter is safe for all environments\n const { createConsoleLogger } = await import(\"./console-adapter.js\");\n return createConsoleLogger(config);\n }\n}\n","/**\n * Default logger implementation\n */\nimport type { Logger, LoggerConfig } from \"~/types/index.js\";\nimport { createLoggerAdapter } from \"~/core/adapter-factory.js\";\n\nexport class DefaultLogger implements Logger {\n private adapter: any;\n private initPromise: Promise<void>;\n\n constructor(config: LoggerConfig = {}) {\n // Initialize adapter asynchronously\n this.initPromise = createLoggerAdapter(config).then((adapter) => {\n this.adapter = adapter;\n });\n }\n\n // All methods are typed as `any` for maximum flexibility\n trace: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.trace as any)(...args);\n };\n\n debug: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.debug as any)(...args);\n };\n\n info: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.info as any)(...args);\n };\n\n warn: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.warn as any)(...args);\n };\n\n error: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.error as any)(...args);\n };\n\n fatal: any = async (...args: any[]) => {\n await this.initPromise;\n (this.adapter.fatal as any)(...args);\n };\n}\n\n/**\n * Factory function to create a logger instance\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n return new DefaultLogger(config);\n}\n"],"mappings":";;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAkCA,SAAS,eAAe,QAAkB,QAAgB;AACxD,SAAO,mBAAmB,KAAK;AACjC;AAKA,SAAS,UAAU,OAAiB,UAA2B;AAC7D,SAAO,mBAAmB,KAAK,KAAK;AACtC;AAKA,SAAS,eACP,OACA,MACA,cACA,UACM;AAEN,MAAI,CAAC,UAAU,OAAO,QAAQ,GAAG;AAC/B;AAAA,EACF;AAEA,MAAI;AACJ,MAAI;AAGJ,MAAI,KAAK,WAAW,GAAG;AACrB,QAAI,OAAO,KAAK,CAAC,MAAM,UAAU;AAC/B,gBAAU,KAAK,CAAC;AAAA,IAClB,OAAO;AACL,gBAAU,KAAK,CAAC;AAChB,gBAAU,KAAK,UAAU,KAAK,CAAC,CAAC;AAAA,IAClC;AAAA,EACF,WAAW,KAAK,UAAU,GAAG;AAE3B,QAAI,OAAO,KAAK,CAAC,MAA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KAAK,CAAC,YAAY;AAC/D,WAAK,UAAU;AAAA,IACjB,CAAC;AAAA,EACH;AAAA;AAAA,EAGA,QAAa,UAAU,SAAgB;AACrC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,MAAc,GAAG,IAAI;AAAA,EACrC;AAAA,EAEA,QAAa,UAAU,SAAgB;AACrC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,MAAc,GAAG,IAAI;AAAA,EACrC;AAAA,EAEA,OAAY,UAAU,SAAgB;AACpC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,KAAa,GAAG,IAAI;AAAA,EACpC;AAAA,EAEA,OAAY,UAAU,SAAgB;AACpC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,KAAa,GAAG,IAAI;AAAA,EACpC;AAAA,EAEA,QAAa,UAAU,SAAgB;AACrC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,MAAc,GAAG,IAAI;AAAA,EACrC;AAAA,EAEA,QAAa,UAAU,SAAgB;AACrC,UAAM,KAAK;AACX,IAAC,KAAK,QAAQ,MAAc,GAAG,IAAI;AAAA,EACrC;AACF;AAKO,SAAS,aAAa,SAAuB,CAAC,GAAW;AAC9D,SAAO,IAAI,cAAc,MAAM;AACjC;","names":["shouldLog","createTestLogger","createConsoleLogger"]}
{"version":3,"sources":["../src/ConsoleLogger.ts","../src/LoggerFactoryImpl.ts"],"sourcesContent":["/**\n * ConsoleLogger - Default logger implementation\n *\n * Simple console-based logger with color support.\n * Used as fallback when no custom LoggerFactory is provided.\n */\n\nimport type { Logger, LogContext, LogLevel } from \"./types\";\n\nexport interface ConsoleLoggerOptions {\n level?: LogLevel;\n colors?: boolean;\n timestamps?: boolean;\n}\n\nexport class ConsoleLogger implements Logger {\n readonly name: string;\n readonly level: LogLevel;\n private readonly colors: boolean;\n private readonly timestamps: boolean;\n\n private static readonly COLORS = {\n DEBUG: \"\\x1b[36m\",\n INFO: \"\\x1b[32m\",\n WARN: \"\\x1b[33m\",\n ERROR: \"\\x1b[31m\",\n RESET: \"\\x1b[0m\",\n };\n\n constructor(name: string, options: ConsoleLoggerOptions = {}) {\n this.name = name;\n this.level = options.level ?? \"info\";\n this.colors = options.colors ?? this.isNodeEnvironment();\n this.timestamps = options.timestamps ?? true;\n }\n\n debug(message: string, context?: LogContext): void {\n if (this.isDebugEnabled()) {\n this.log(\"DEBUG\", message, context);\n }\n }\n\n info(message: string, context?: LogContext): void {\n if (this.isInfoEnabled()) {\n this.log(\"INFO\", message, context);\n }\n }\n\n warn(message: string, context?: LogContext): void {\n if (this.isWarnEnabled()) {\n this.log(\"WARN\", message, context);\n }\n }\n\n error(message: string | Error, context?: LogContext): void {\n if (this.isErrorEnabled()) {\n if (message instanceof Error) {\n this.log(\"ERROR\", message.message, { ...context, stack: message.stack });\n } else {\n this.log(\"ERROR\", message, context);\n }\n }\n }\n\n isDebugEnabled(): boolean {\n return this.getLevelValue(this.level) <= this.getLevelValue(\"debug\");\n }\n\n isInfoEnabled(): boolean {\n return this.getLevelValue(this.level) <= this.getLevelValue(\"info\");\n }\n\n isWarnEnabled(): boolean {\n return this.getLevelValue(this.level) <= this.getLevelValue(\"warn\");\n }\n\n isErrorEnabled(): boolean {\n return this.getLevelValue(this.level) <= this.getLevelValue(\"error\");\n }\n\n private getLevelValue(level: LogLevel): number {\n const levels: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n silent: 4,\n };\n return levels[level];\n }\n\n private log(level: string, message: string, context?: LogContext): void {\n const parts: string[] = [];\n\n if (this.timestamps) {\n parts.push(new Date().toISOString());\n }\n\n if (this.colors) {\n const color = ConsoleLogger.COLORS[level as keyof typeof ConsoleLogger.COLORS];\n parts.push(`${color}${level.padEnd(5)}${ConsoleLogger.COLORS.RESET}`);\n } else {\n parts.push(level.padEnd(5));\n }\n\n parts.push(`[${this.name}]`);\n parts.push(message);\n\n const logLine = parts.join(\" \");\n const consoleMethod = this.getConsoleMethod(level);\n\n if (context && Object.keys(context).length > 0) {\n consoleMethod(logLine, context);\n } else {\n consoleMethod(logLine);\n }\n }\n\n private getConsoleMethod(level: string): (...args: unknown[]) => void {\n switch (level) {\n case \"DEBUG\":\n return console.debug.bind(console);\n case \"INFO\":\n return console.info.bind(console);\n case \"WARN\":\n return console.warn.bind(console);\n case \"ERROR\":\n return console.error.bind(console);\n default:\n return console.log.bind(console);\n }\n }\n\n private isNodeEnvironment(): boolean {\n return typeof process !== \"undefined\" && process.versions?.node !== undefined;\n }\n}\n","/**\n * LoggerFactoryImpl - Central factory for creating logger instances\n *\n * Implements lazy initialization pattern:\n * - createLogger() can be called at module level (before config)\n * - Real logger is created on first use\n * - External LoggerFactory can be injected via Runtime\n */\n\nimport type { Logger, LoggerFactory, LogContext, LogLevel } from \"./types\";\nimport { ConsoleLogger, type ConsoleLoggerOptions } from \"./ConsoleLogger\";\n\n// External factory injected via Runtime\nlet externalFactory: LoggerFactory | null = null;\n\n// Version counter to invalidate cached real loggers\nlet factoryVersion = 0;\n\nexport interface LoggerFactoryConfig {\n defaultImplementation?: (name: string) => Logger;\n defaultLevel?: LogLevel;\n consoleOptions?: Omit<ConsoleLoggerOptions, \"level\">;\n}\n\n/**\n * Internal LoggerFactory implementation\n *\n * Uses lazy proxy pattern to allow module-level createLogger() calls.\n */\nexport class LoggerFactoryImpl {\n private static loggers: Map<string, Logger> = new Map();\n private static config: LoggerFactoryConfig = {\n defaultLevel: \"info\",\n };\n\n static getLogger(nameOrClass: string | (new (...args: unknown[]) => unknown)): Logger {\n const name = typeof nameOrClass === \"string\" ? nameOrClass : nameOrClass.name;\n\n if (this.loggers.has(name)) {\n return this.loggers.get(name)!;\n }\n\n const lazyLogger = this.createLazyLogger(name);\n this.loggers.set(name, lazyLogger);\n return lazyLogger;\n }\n\n static configure(config: LoggerFactoryConfig): void {\n this.config = { ...this.config, ...config };\n }\n\n static reset(): void {\n this.loggers.clear();\n this.config = { defaultLevel: \"info\" };\n externalFactory = null;\n factoryVersion++; // Invalidate all cached real loggers\n }\n\n private static createLazyLogger(name: string): Logger {\n let realLogger: Logger | null = null;\n let loggerVersion = -1; // Track which factory version created this logger\n\n const getRealLogger = (): Logger => {\n // Recreate logger if factory version changed (setLoggerFactory was called)\n if (!realLogger || loggerVersion !== factoryVersion) {\n realLogger = this.createLogger(name);\n loggerVersion = factoryVersion;\n }\n return realLogger;\n };\n\n return {\n name,\n level: this.config.defaultLevel || \"info\",\n debug: (message: string, context?: LogContext) => getRealLogger().debug(message, context),\n info: (message: string, context?: LogContext) => getRealLogger().info(message, context),\n warn: (message: string, context?: LogContext) => getRealLogger().warn(message, context),\n error: (message: string | Error, context?: LogContext) =>\n getRealLogger().error(message, context),\n isDebugEnabled: () => getRealLogger().isDebugEnabled(),\n isInfoEnabled: () => getRealLogger().isInfoEnabled(),\n isWarnEnabled: () => getRealLogger().isWarnEnabled(),\n isErrorEnabled: () => getRealLogger().isErrorEnabled(),\n };\n }\n\n private static createLogger(name: string): Logger {\n if (externalFactory) {\n return externalFactory.getLogger(name);\n }\n\n if (this.config.defaultImplementation) {\n return this.config.defaultImplementation(name);\n }\n\n return new ConsoleLogger(name, {\n level: this.config.defaultLevel,\n ...this.config.consoleOptions,\n });\n }\n}\n\n/**\n * Set external LoggerFactory (called by Runtime initialization)\n */\nexport function setLoggerFactory(factory: LoggerFactory): void {\n externalFactory = factory;\n LoggerFactoryImpl.reset();\n externalFactory = factory;\n}\n\n/**\n * Create a logger instance\n *\n * Safe to call at module level before Runtime is configured.\n * Uses lazy initialization - actual logger is created on first use.\n *\n * @param name - Logger name (hierarchical, e.g., \"engine/AgentEngine\")\n * @returns Logger instance (lazy proxy)\n */\nexport function createLogger(name: string): Logger {\n return LoggerFactoryImpl.getLogger(name);\n}\n"],"mappings":";AAeO,IAAM,gBAAN,MAAM,eAAgC;AAAA,EAClC;AAAA,EACA;AAAA,EACQ;AAAA,EACA;AAAA,EAEjB,OAAwB,SAAS;AAAA,IAC/B,OAAO;AAAA,IACP,MAAM;AAAA,IACN,M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MAAM,SAAS,OAAO;AAAA,MACxC,gBAAgB,MAAM,cAAc,EAAE,eAAe;AAAA,MACrD,eAAe,MAAM,cAAc,EAAE,cAAc;AAAA,MACnD,eAAe,MAAM,cAAc,EAAE,cAAc;AAAA,MACnD,gBAAgB,MAAM,cAAc,EAAE,eAAe;AAAA,IACvD;AAAA,EACF;AAAA,EAEA,OAAe,aAAa,MAAsB;AAChD,QAAI,iBAAiB;AACnB,aAAO,gBAAgB,UAAU,IAAI;AAAA,IACvC;AAEA,QAAI,KAAK,OAAO,uBAAuB;AACrC,aAAO,KAAK,OAAO,sBAAsB,IAAI;AAAA,IAC/C;AAEA,WAAO,IAAI,cAAc,MAAM;AAAA,MAC7B,OAAO,KAAK,OAAO;AAAA,MACnB,GAAG,KAAK,OAAO;AAAA,IACjB,CAAC;AAAA,EACH;AACF;AAKO,SAAS,iBAAiB,SAA8B;AAC7D,oBAAkB;AAClB,oBAAkB,MAAM;AACxB,oBAAkB;AACpB;AAWO,SAAS,aAAa,MAAsB;AACjD,SAAO,kBAAkB,UAAU,IAAI;AACzC;","names":[]}
{
"name": "@deepracticex/logger",
"version": "1.1.2",
"description": "AI-First logging library for intelligent agents - Universal, observable, and designed for the age of AI",
"version": "1.2.0",
"description": "Lazy-initialized logging with pluggable backends",
"type": "module",
"main": "./dist/index.js",
"main": "./dist/index.cjs",
"module": "./dist/index.js",

@@ -14,65 +14,16 @@ "types": "./dist/index.d.ts",

"require": "./dist/index.cjs"
},
"./nodejs": {
"types": "./dist/nodejs.d.ts",
"import": "./dist/nodejs.js",
"require": "./dist/nodejs.cjs"
},
"./cloudflare-workers": {
"types": "./dist/cloudflare-workers.d.ts",
"import": "./dist/cloudflare-workers.js",
"require": "./dist/cloudflare-workers.cjs"
},
"./browser": {
"types": "./dist/browser.d.ts",
"import": "./dist/browser.js",
"require": "./dist/browser.cjs"
},
"./test": {
"types": "./dist/test.d.ts",
"import": "./dist/test.js",
"require": "./dist/test.cjs"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"clean": "rimraf dist",
"test": "bun test",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"test:dev": "vitest",
"test:ci": "vitest run --coverage"
"clean": "rm -rf dist"
},
"dependencies": {
"pino": "^9.9.0",
"pino-pretty": "^13.1.1"
},
"files": [
"dist",
"package.json",
"README.md"
],
"keywords": [
"logger",
"logging",
"ai",
"agent",
"ai-first",
"observability",
"universal",
"nodejs",
"cloudflare-workers",
"browser",
"test",
"vitest"
],
"author": "Deepractice",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/Deepractice/Logent"
},
"devDependencies": {
"@deepracticex/vitest-cucumber": "^1.2.0"
"publishConfig": {
"access": "public"
}
}
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/browser.ts
var browser_exports = {};
__export(browser_exports, {
createLogger: () => createLogger
});
module.exports = __toCommonJS(browser_exports);
// src/core/console-adapter.ts
var LOG_LEVELS = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
var defaultConfig = {
level: "info",
console: true,
colors: true,
name: "app"
};
function createConsoleLogger(config = {}) {
const finalConfig = { ...defaultConfig, ...config };
const levelThreshold = LOG_LEVELS[finalConfig.level || "info"];
const name = finalConfig.name || "app";
const formatMessage = (level, ...args) => {
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;
return `${prefix} ${args.join(" ")}`;
};
const shouldLog = (level) => {
return LOG_LEVELS[level] >= levelThreshold;
};
const logMethod = (level, consoleMethod) => {
return (...args) => {
if (!shouldLog(level)) return;
if (!finalConfig.console) return;
const message = formatMessage(level, ...args);
consoleMethod(message);
};
};
return {
trace: logMethod("trace", console.log),
debug: logMethod("debug", console.log),
info: logMethod("info", console.info),
warn: logMethod("warn", console.warn),
error: logMethod("error", console.error),
fatal: logMethod("fatal", console.error)
};
}
// src/browser.ts
function createLogger(config = {}) {
return createConsoleLogger({ ...config, environment: "browser" });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createLogger
});
//# sourceMappingURL=browser.cjs.map
{"version":3,"sources":["../src/browser.ts","../src/core/console-adapter.ts"],"sourcesContent":["/**\n * Browser platform entry point\n * Directly uses console adapter for client-side logging\n */\nimport { createConsoleLogger } from \"./core/console-adapter.js\";\nimport type { LoggerConfig, Logger } from \"./types/index.js\";\n\n/**\n * Create logger for browser runtime\n * Always uses console-based logging\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n // Force environment to prevent any detection logic\n return createConsoleLogger({ ...config, environment: \"browser\" });\n}\n\nexport type { Logger, LoggerConfig };\n","/**\n * Console logger adapter - for edge runtimes and browsers\n */\nimport type { LoggerConfig } from \"~/types/config.js\";\nimport type { LogLevel } from \"~/types/logger.js\";\n\ninterface ConsoleLoggerInstance {\n trace: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n fatal: (...args: any[]) => void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\nconst defaultConfig: LoggerConfig = {\n level: \"info\",\n console: true,\n colors: true,\n name: \"app\",\n};\n\n/**\n * Create a console-based logger instance for edge runtimes\n */\nexport function createConsoleLogger(\n config: LoggerConfig = {},\n): ConsoleLoggerInstance {\n const finalConfig = { ...defaultConfig, ...config };\n const levelThreshold = LOG_LEVELS[finalConfig.level || \"info\"];\n const name = finalConfig.name || \"app\";\n\n const formatMessage = (level: LogLevel, ...args: any[]): string => {\n const timestamp = new Date().toISOString();\n const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;\n return `${prefix} ${args.join(\" \")}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return LOG_LEVELS[level] >= levelThreshold;\n };\n\n const logMethod = (level: LogLevel, consoleMethod: any) => {\n return (...args: any[]) => {\n if (!shouldLog(level)) return;\n if (!finalConfig.console) return;\n\n const message = formatMessage(level, ...args);\n consoleMethod(message);\n };\n };\n\n return {\n trace: logMethod(\"trace\", console.log),\n debug: logMethod(\"debug\", console.log),\n info: logMethod(\"info\", console.info),\n warn: logMethod(\"warn\", console.warn),\n error: logMethod(\"error\", console.error),\n fatal: logMethod(\"fatal\", console.error),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeA,IAAM,aAAuC;AAAA,EAC3C,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AAEA,IAAM,gBAA8B;AAAA,EAClC,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AACR;AAKO,SAAS,oBACd,SAAuB,CAAC,GACD;AACvB,QAAM,cAAc,EAAE,GAAG,eAAe,GAAG,OAAO;AAClD,QAAM,iBAAiB,WAAW,YAAY,SAAS,MAAM;AAC7D,QAAM,OAAO,YAAY,QAAQ;AAEjC,QAAM,gBAAgB,CAAC,UAAoB,SAAwB;AACjE,UAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AACzC,UAAM,SAAS,IAAI,SAAS,MAAM,MAAM,YAAY,CAAC,MAAM,IAAI;AAC/D,WAAO,GAAG,MAAM,IAAI,KAAK,KAAK,GAAG,CAAC;AAAA,EACpC;AAEA,QAAM,YAAY,CAAC,UAA6B;AAC9C,WAAO,WAAW,KAAK,KAAK;AAAA,EAC9B;AAEA,QAAM,YAAY,CAAC,OAAiB,kBAAuB;AACzD,WAAO,IAAI,SAAgB;AACzB,UAAI,CAAC,UAAU,KAAK,EAAG;AACvB,UAAI,CAAC,YAAY,QAAS;AAE1B,YAAM,UAAU,cAAc,OAAO,GAAG,IAAI;AAC5C,oBAAc,OAAO;AAAA,IACvB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,UAAU,SAAS,QAAQ,GAAG;AAAA,IACrC,OAAO,UAAU,SAAS,QAAQ,GAAG;AAAA,IACrC,MAAM,UAAU,QAAQ,QAAQ,IAAI;AAAA,IACpC,MAAM,UAAU,QAAQ,QAAQ,IAAI;AAAA,IACpC,OAAO,UAAU,SAAS,QAAQ,KAAK;AAAA,IACvC,OAAO,UAAU,SAAS,QAAQ,KAAK;AAAA,EACzC;AACF;;;AD1DO,SAAS,aAAa,SAAuB,CAAC,GAAW;AAE9D,SAAO,oBAAoB,EAAE,GAAG,QAAQ,aAAa,UAAU,CAAC;AAClE;","names":[]}
import { L as LoggerConfig, a as Logger } from './logger-Lmm6XEQc.cjs';
/**
* Create logger for browser runtime
* Always uses console-based logging
*/
declare function createLogger(config?: LoggerConfig): Logger;
export { Logger, LoggerConfig, createLogger };
import { L as LoggerConfig, a as Logger } from './logger-Lmm6XEQc.js';
/**
* Create logger for browser runtime
* Always uses console-based logging
*/
declare function createLogger(config?: LoggerConfig): Logger;
export { Logger, LoggerConfig, createLogger };
// src/core/console-adapter.ts
var LOG_LEVELS = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
var defaultConfig = {
level: "info",
console: true,
colors: true,
name: "app"
};
function createConsoleLogger(config = {}) {
const finalConfig = { ...defaultConfig, ...config };
const levelThreshold = LOG_LEVELS[finalConfig.level || "info"];
const name = finalConfig.name || "app";
const formatMessage = (level, ...args) => {
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;
return `${prefix} ${args.join(" ")}`;
};
const shouldLog = (level) => {
return LOG_LEVELS[level] >= levelThreshold;
};
const logMethod = (level, consoleMethod) => {
return (...args) => {
if (!shouldLog(level)) return;
if (!finalConfig.console) return;
const message = formatMessage(level, ...args);
consoleMethod(message);
};
};
return {
trace: logMethod("trace", console.log),
debug: logMethod("debug", console.log),
info: logMethod("info", console.info),
warn: logMethod("warn", console.warn),
error: logMethod("error", console.error),
fatal: logMethod("fatal", console.error)
};
}
// src/browser.ts
function createLogger(config = {}) {
return createConsoleLogger({ ...config, environment: "browser" });
}
export {
createLogger
};
//# sourceMappingURL=browser.js.map
{"version":3,"sources":["../src/core/console-adapter.ts","../src/browser.ts"],"sourcesContent":["/**\n * Console logger adapter - for edge runtimes and browsers\n */\nimport type { LoggerConfig } from \"~/types/config.js\";\nimport type { LogLevel } from \"~/types/logger.js\";\n\ninterface ConsoleLoggerInstance {\n trace: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n fatal: (...args: any[]) => void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\nconst defaultConfig: LoggerConfig = {\n level: \"info\",\n console: true,\n colors: true,\n name: \"app\",\n};\n\n/**\n * Create a console-based logger instance for edge runtimes\n */\nexport function createConsoleLogger(\n config: LoggerConfig = {},\n): ConsoleLoggerInstance {\n const finalConfig = { ...defaultConfig, ...config };\n const levelThreshold = LOG_LEVELS[finalConfig.level || \"info\"];\n const name = finalConfig.name || \"app\";\n\n const formatMessage = (level: LogLevel, ...args: any[]): string => {\n const timestamp = new Date().toISOString();\n const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;\n return `${prefix} ${args.join(\" \")}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return LOG_LEVELS[level] >= levelThreshold;\n };\n\n const logMethod = (level: LogLevel, consoleMethod: any) => {\n return (...args: any[]) => {\n if (!shouldLog(level)) return;\n if (!finalConfig.console) return;\n\n const message = formatMessage(level, ...args);\n consoleMethod(message);\n };\n };\n\n return {\n trace: logMethod(\"trace\", console.log),\n debug: logMethod(\"debug\", console.log),\n info: logMethod(\"info\", console.info),\n warn: logMethod(\"warn\", console.warn),\n error: logMethod(\"error\", console.error),\n fatal: logMethod(\"fatal\", console.error),\n };\n}\n","/**\n * Browser platform entry point\n * Directly uses console adapter for client-side logging\n */\nimport { createConsoleLogger } from \"./core/console-adapter.js\";\nimport type { LoggerConfig, Logger } from \"./types/index.js\";\n\n/**\n * Create logger for browser runtime\n * Always uses console-based logging\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n // Force environment to prevent any detection logic\n return createConsoleLogger({ ...config, environment: \"browser\" });\n}\n\nexport type { Logger, LoggerConfig };\n"],"mappings":";AAeA,IAAM,aAAuC;AAAA,EAC3C,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AAEA,IAAM,gBAA8B;AAAA,EAClC,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AACR;AAKO,SAAS,oBACd,SAAuB,CAAC,GACD;AACvB,QAAM,cAAc,EAAE,GAAG,eAAe,GAAG,OAAO;AAClD,QAAM,iBAAiB,WAAW,YAAY,SAAS,MAAM;AAC7D,QAAM,OAAO,YAAY,QAAQ;AAEjC,QAAM,gBAAgB,CAAC,UAAoB,SAAwB;AACjE,UAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AACzC,UAAM,SAAS,IAAI,SAAS,MAAM,MAAM,YAAY,CAAC,MAAM,IAAI;AAC/D,WAAO,GAAG,MAAM,IAAI,KAAK,KAAK,GAAG,CAAC;AAAA,EACpC;AAEA,QAAM,YAAY,CAAC,UAA6B;AAC9C,WAAO,WAAW,KAAK,KAAK;AAAA,EAC9B;AAEA,QAAM,YAAY,CAAC,OAAiB,kBAAuB;AACzD,WAAO,IAAI,SAAgB;AACzB,UAAI,CAAC,UAAU,KAAK,EAAG;AACvB,UAAI,CAAC,YAAY,QAAS;AAE1B,YAAM,UAAU,cAAc,OAAO,GAAG,IAAI;AAC5C,oBAAc,OAAO;AAAA,IACvB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,UAAU,SAAS,QAAQ,GAAG;AAAA,IACrC,OAAO,UAAU,SAAS,QAAQ,GAAG;AAAA,IACrC,MAAM,UAAU,QAAQ,QAAQ,IAAI;AAAA,IACpC,MAAM,UAAU,QAAQ,QAAQ,IAAI;AAAA,IACpC,OAAO,UAAU,SAAS,QAAQ,KAAK;AAAA,IACvC,OAAO,UAAU,SAAS,QAAQ,KAAK;AAAA,EACzC;AACF;;;AC1DO,SAAS,aAAa,SAAuB,CAAC,GAAW;AAE9D,SAAO,oBAAoB,EAAE,GAAG,QAAQ,aAAa,UAAU,CAAC;AAClE;","names":[]}
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/cloudflare-workers.ts
var cloudflare_workers_exports = {};
__export(cloudflare_workers_exports, {
createLogger: () => createLogger
});
module.exports = __toCommonJS(cloudflare_workers_exports);
// src/core/console-adapter.ts
var LOG_LEVELS = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
var defaultConfig = {
level: "info",
console: true,
colors: true,
name: "app"
};
function createConsoleLogger(config = {}) {
const finalConfig = { ...defaultConfig, ...config };
const levelThreshold = LOG_LEVELS[finalConfig.level || "info"];
const name = finalConfig.name || "app";
const formatMessage = (level, ...args) => {
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;
return `${prefix} ${args.join(" ")}`;
};
const shouldLog = (level) => {
return LOG_LEVELS[level] >= levelThreshold;
};
const logMethod = (level, consoleMethod) => {
return (...args) => {
if (!shouldLog(level)) return;
if (!finalConfig.console) return;
const message = formatMessage(level, ...args);
consoleMethod(message);
};
};
return {
trace: logMethod("trace", console.log),
debug: logMethod("debug", console.log),
info: logMethod("info", console.info),
warn: logMethod("warn", console.warn),
error: logMethod("error", console.error),
fatal: logMethod("fatal", console.error)
};
}
// src/cloudflare-workers.ts
function createLogger(config = {}) {
return createConsoleLogger({ ...config, environment: "cloudflare-workers" });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createLogger
});
//# sourceMappingURL=cloudflare-workers.cjs.map
{"version":3,"sources":["../src/cloudflare-workers.ts","../src/core/console-adapter.ts"],"sourcesContent":["/**\n * Cloudflare Workers platform entry point\n * Directly uses console adapter - no dynamic detection or pino dependencies\n */\nimport { createConsoleLogger } from \"./core/console-adapter.js\";\nimport type { LoggerConfig, Logger } from \"./types/index.js\";\n\n/**\n * Create logger for Cloudflare Workers runtime\n * Always uses console-based logging\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n // Force environment to prevent any detection logic\n return createConsoleLogger({ ...config, environment: \"cloudflare-workers\" });\n}\n\nexport type { Logger, LoggerConfig };\n","/**\n * Console logger adapter - for edge runtimes and browsers\n */\nimport type { LoggerConfig } from \"~/types/config.js\";\nimport type { LogLevel } from \"~/types/logger.js\";\n\ninterface ConsoleLoggerInstance {\n trace: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n fatal: (...args: any[]) => void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\nconst defaultConfig: LoggerConfig = {\n level: \"info\",\n console: true,\n colors: true,\n name: \"app\",\n};\n\n/**\n * Create a console-based logger instance for edge runtimes\n */\nexport function createConsoleLogger(\n config: LoggerConfig = {},\n): ConsoleLoggerInstance {\n const finalConfig = { ...defaultConfig, ...config };\n const levelThreshold = LOG_LEVELS[finalConfig.level || \"info\"];\n const name = finalConfig.name || \"app\";\n\n const formatMessage = (level: LogLevel, ...args: any[]): string => {\n const timestamp = new Date().toISOString();\n const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;\n return `${prefix} ${args.join(\" \")}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return LOG_LEVELS[level] >= levelThreshold;\n };\n\n const logMethod = (level: LogLevel, consoleMethod: any) => {\n return (...args: any[]) => {\n if (!shouldLog(level)) return;\n if (!finalConfig.console) return;\n\n const message = formatMessage(level, ...args);\n consoleMethod(message);\n };\n };\n\n return {\n trace: logMethod(\"trace\", console.log),\n debug: logMethod(\"debug\", console.log),\n info: logMethod(\"info\", console.info),\n warn: logMethod(\"warn\", console.warn),\n error: logMethod(\"error\", console.error),\n fatal: logMethod(\"fatal\", console.error),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeA,IAAM,aAAuC;AAAA,EAC3C,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AAEA,IAAM,gBAA8B;AAAA,EAClC,OAAO;AAAA,EACP,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM;AACR;AAKO,SAAS,oBACd,SAAuB,CAAC,GACD;AACvB,QAAM,cAAc,EAAE,GAAG,eAAe,GAAG,OAAO;AAClD,QAAM,iBAAiB,WAAW,YAAY,SAAS,MAAM;AAC7D,QAAM,OAAO,YAAY,QAAQ;AAEjC,QAAM,gBAAgB,CAAC,UAAoB,SAAwB;AACjE,UAAM,aAAY,oBAAI,KAAK,GAAE,YAAY;AACzC,UAAM,SAAS,IAAI,SAAS,MAAM,MAAM,YAAY,CAAC,MAAM,IAAI;AAC/D,WAAO,GAAG,MAAM,IAAI,KAAK,KAAK,GAAG,CAAC;AAAA,EACpC;AAEA,QAAM,YAAY,CAAC,UAA6B;AAC9C,WAAO,WAAW,KAAK,KAAK;AAAA,EAC9B;AAEA,QAAM,YAAY,CAAC,OAAiB,kBAAuB;AACzD,WAAO,IAAI,SAAgB;AACzB,UAAI,CAAC,UAAU,KAAK,EAAG;AACvB,UAAI,CAAC,YAAY,QAAS;AAE1B,YAAM,UAAU,cAAc,OAAO,GAAG,IAAI;AAC5C,oBAAc,OAAO;AAAA,IACvB;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,UAAU,SAAS,QAAQ,GAAG;AAAA,IACrC,OAAO,UAAU,SAAS,QAAQ,GAAG;AAAA,IACrC,MAAM,UAAU,QAAQ,QAAQ,IAAI;AAAA,IACpC,MAAM,UAAU,QAAQ,QAAQ,IAAI;AAAA,IACpC,OAAO,UAAU,SAAS,QAAQ,KAAK;AAAA,IACvC,OAAO,UAAU,SAAS,QAAQ,KAAK;AAAA,EACzC;AACF;;;AD1DO,SAAS,aAAa,SAAuB,CAAC,GAAW;AAE9D,SAAO,oBAAoB,EAAE,GAAG,QAAQ,aAAa,qBAAqB,CAAC;AAC7E;","names":[]}
import { L as LoggerConfig, a as Logger } from './logger-Lmm6XEQc.cjs';
/**
* Create logger for Cloudflare Workers runtime
* Always uses console-based logging
*/
declare function createLogger(config?: LoggerConfig): Logger;
export { Logger, LoggerConfig, createLogger };
import { L as LoggerConfig, a as Logger } from './logger-Lmm6XEQc.js';
/**
* Create logger for Cloudflare Workers runtime
* Always uses console-based logging
*/
declare function createLogger(config?: LoggerConfig): Logger;
export { Logger, LoggerConfig, createLogger };
// src/core/console-adapter.ts
var LOG_LEVELS = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
var defaultConfig = {
level: "info",
console: true,
colors: true,
name: "app"
};
function createConsoleLogger(config = {}) {
const finalConfig = { ...defaultConfig, ...config };
const levelThreshold = LOG_LEVELS[finalConfig.level || "info"];
const name = finalConfig.name || "app";
const formatMessage = (level, ...args) => {
const timestamp = (/* @__PURE__ */ new Date()).toISOString();
const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;
return `${prefix} ${args.join(" ")}`;
};
const shouldLog = (level) => {
return LOG_LEVELS[level] >= levelThreshold;
};
const logMethod = (level, consoleMethod) => {
return (...args) => {
if (!shouldLog(level)) return;
if (!finalConfig.console) return;
const message = formatMessage(level, ...args);
consoleMethod(message);
};
};
return {
trace: logMethod("trace", console.log),
debug: logMethod("debug", console.log),
info: logMethod("info", console.info),
warn: logMethod("warn", console.warn),
error: logMethod("error", console.error),
fatal: logMethod("fatal", console.error)
};
}
// src/cloudflare-workers.ts
function createLogger(config = {}) {
return createConsoleLogger({ ...config, environment: "cloudflare-workers" });
}
export {
createLogger
};
//# sourceMappingURL=cloudflare-workers.js.map
{"version":3,"sources":["../src/core/console-adapter.ts","../src/cloudflare-workers.ts"],"sourcesContent":["/**\n * Console logger adapter - for edge runtimes and browsers\n */\nimport type { LoggerConfig } from \"~/types/config.js\";\nimport type { LogLevel } from \"~/types/logger.js\";\n\ninterface ConsoleLoggerInstance {\n trace: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n fatal: (...args: any[]) => void;\n}\n\nconst LOG_LEVELS: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\nconst defaultConfig: LoggerConfig = {\n level: \"info\",\n console: true,\n colors: true,\n name: \"app\",\n};\n\n/**\n * Create a console-based logger instance for edge runtimes\n */\nexport function createConsoleLogger(\n config: LoggerConfig = {},\n): ConsoleLoggerInstance {\n const finalConfig = { ...defaultConfig, ...config };\n const levelThreshold = LOG_LEVELS[finalConfig.level || \"info\"];\n const name = finalConfig.name || \"app\";\n\n const formatMessage = (level: LogLevel, ...args: any[]): string => {\n const timestamp = new Date().toISOString();\n const prefix = `[${timestamp}] [${level.toUpperCase()}] [${name}]`;\n return `${prefix} ${args.join(\" \")}`;\n };\n\n const shouldLog = (level: LogLevel): boolean => {\n return LOG_LEVELS[level] >= levelThreshold;\n };\n\n const logMethod = (level: LogLevel, consoleMethod: any) => {\n return (...args: any[]) => {\n if (!shouldLog(level)) return;\n if (!finalConfig.console) return;\n\n const message = formatMessage(level, ...args);\n consoleMethod(message);\n };\n };\n\n return {\n trace: logMethod(\"trace\", console.log),\n debug: logMethod(\"debug\", console.log),\n info: logMethod(\"info\", console.info),\n warn: logMethod(\"warn\", console.warn),\n error: logMethod(\"error\", console.error),\n fatal: logMethod(\"fatal\", console.error),\n };\n}\n","/**\n * Cloudflare Workers platform entry point\n * Directly uses console adapter - no dynamic detection or pino dependencies\n */\nimport { createConsoleLogger } from \"./core/console-adapter.js\";\nimport type { LoggerConfig, Logger } from \"./types/index.js\";\n\n/**\n * Create logger for Cloudflare Workers runtime\n * Always uses console-based logging\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n // Force environment to prevent any detection logic\n return createConsoleLogger({ ...config, environment: \"cloudflare-workers\" });\n}\n\nexport type { Logger, LoggerConfig };\n"],"mappings":";AAeA,IAAM,aAAuC;AAAA,EAC3C,OAAO;AAAA,EACP,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AACT;AAEA,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test";
/**
* Logger configuration interface
*/
interface LoggerConfig {
/**
* Log level threshold
* @default "info"
*/
level?: "trace" | "debug" | "info" | "warn" | "error" | "fatal";
/**
* Enable console output
* @default true
*/
console?: boolean;
/**
* File logging configuration
* @default { dirname: "~/.deepractice/logs" }
*/
file?: boolean | {
dirname?: string;
};
/**
* Enable colored output
* @default true
*/
colors?: boolean;
/**
* Package/service name for identification
* @default "app"
*/
name?: string;
/**
* Explicitly specify the runtime environment
* If not provided, will auto-detect
* @default auto-detect
*/
environment?: RuntimeEnvironment;
}
/**
* Logger interface - all methods accept any arguments for maximum flexibility
*/
interface Logger {
/**
* Log trace level message
*/
trace: any;
/**
* Log debug level message
*/
debug: any;
/**
* Log info level message
*/
info: any;
/**
* Log warning level message
*/
warn: any;
/**
* Log error level message
*/
error: any;
/**
* Log fatal level message
*/
fatal: any;
}
/**
* Log level type
*/
type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
export type { LoggerConfig as L, Logger as a, LogLevel as b };
/**
* Runtime environment type
*/
type RuntimeEnvironment = "nodejs" | "cloudflare-workers" | "browser" | "test";
/**
* Logger configuration interface
*/
interface LoggerConfig {
/**
* Log level threshold
* @default "info"
*/
level?: "trace" | "debug" | "info" | "warn" | "error" | "fatal";
/**
* Enable console output
* @default true
*/
console?: boolean;
/**
* File logging configuration
* @default { dirname: "~/.deepractice/logs" }
*/
file?: boolean | {
dirname?: string;
};
/**
* Enable colored output
* @default true
*/
colors?: boolean;
/**
* Package/service name for identification
* @default "app"
*/
name?: string;
/**
* Explicitly specify the runtime environment
* If not provided, will auto-detect
* @default auto-detect
*/
environment?: RuntimeEnvironment;
}
/**
* Logger interface - all methods accept any arguments for maximum flexibility
*/
interface Logger {
/**
* Log trace level message
*/
trace: any;
/**
* Log debug level message
*/
debug: any;
/**
* Log info level message
*/
info: any;
/**
* Log warning level message
*/
warn: any;
/**
* Log error level message
*/
error: any;
/**
* Log fatal level message
*/
fatal: any;
}
/**
* Log level type
*/
type LogLevel = "trace" | "debug" | "info" | "warn" | "error" | "fatal";
export type { LoggerConfig as L, Logger as a, LogLevel as b };
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/nodejs.ts
var nodejs_exports = {};
__export(nodejs_exports, {
createLogger: () => createLogger
});
module.exports = __toCommonJS(nodejs_exports);
// src/core/pino-adapter.ts
var import_pino = __toESM(require("pino"), 1);
var import_path2 = __toESM(require("path"), 1);
var import_os = __toESM(require("os"), 1);
var import_fs = __toESM(require("fs"), 1);
// src/core/caller-tracker.ts
var import_path = __toESM(require("path"), 1);
function getCallerInfo(packageName) {
const stack = new Error().stack || "";
const stackLines = stack.split("\n");
for (let i = 2; i < stackLines.length; i++) {
const line = stackLines[i];
if (line && !line.includes("node_modules/pino") && !line.includes("packages/logger") && !line.includes("@deepracticex/logger")) {
const match = line.match(/at\s+(?:.*?\s+)?\(?(.*?):(\d+):(\d+)\)?/);
if (match && match[1] && match[2]) {
const fullPath = match[1];
const lineNum = parseInt(match[2], 10);
const filename = import_path.default.basename(fullPath);
return {
package: packageName,
file: filename,
line: lineNum
};
}
}
}
return { package: packageName, file: "unknown", line: 0 };
}
// src/core/pino-adapter.ts
var defaultConfig = {
level: process.env.LOG_LEVEL || "info",
console: true,
file: {
dirname: import_path2.default.join(import_os.default.homedir(), ".deepractice", "logs")
},
colors: true,
name: "app"
};
function createPinoLogger(config = {}) {
const finalConfig = { ...defaultConfig, ...config };
if (finalConfig.file) {
const fileConfig = typeof finalConfig.file === "object" ? finalConfig.file : {};
const logDir = fileConfig.dirname || import_path2.default.join(import_os.default.homedir(), ".deepractice", "logs");
if (!import_fs.default.existsSync(logDir)) {
import_fs.default.mkdirSync(logDir, { recursive: true });
}
}
const isElectron = process.versions && "electron" in process.versions;
const isTest = process.env.NODE_ENV === "test" || process.env.VITEST === "true";
if (isElectron || isTest || process.env.DEEPRACTICE_NO_WORKERS === "true") {
if (finalConfig.file) {
const fileConfig = typeof finalConfig.file === "object" ? finalConfig.file : {};
const logDir = fileConfig.dirname || import_path2.default.join(import_os.default.homedir(), ".deepractice", "logs");
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
const logPath = import_path2.default.join(logDir, `deepractice-${today}.log`);
const dest = import_pino.default.destination({
dest: logPath,
sync: true
});
return (0, import_pino.default)(
{
level: finalConfig.level || "info",
base: { pid: process.pid },
mixin: () => getCallerInfo(finalConfig.name || "app"),
formatters: {
level: (label) => {
return { level: label };
},
log: (obj) => {
const { package: pkg, file, line, ...rest } = obj;
return {
...rest,
location: pkg && file ? `${pkg} [${file}:${line}]` : void 0
};
}
}
},
dest
);
} else {
return (0, import_pino.default)({
level: finalConfig.level || "info",
base: { pid: process.pid },
mixin: () => getCallerInfo(finalConfig.name || "app"),
formatters: {
level: (label) => {
return { level: label };
},
log: (obj) => {
const { package: pkg, file, line, ...rest } = obj;
return {
...rest,
location: pkg && file ? `${pkg} [${file}:${line}]` : void 0
};
}
}
});
}
} else {
const targets = [];
if (finalConfig.console) {
targets.push({
target: "pino-pretty",
level: finalConfig.level,
options: {
// MCP stdio mode disables colors to avoid ANSI escape codes
colorize: process.env.MCP_TRANSPORT === "stdio" ? false : finalConfig.colors,
translateTime: "SYS:yyyy-mm-dd HH:MM:ss.l",
ignore: "hostname,pid,package,file,line",
destination: 2,
// stderr (fd 2) - MCP best practice
messageFormat: "{package} [{file}:{line}] {msg}"
}
});
}
if (finalConfig.file) {
const fileConfig = typeof finalConfig.file === "object" ? finalConfig.file : {};
const logDir = fileConfig.dirname || import_path2.default.join(import_os.default.homedir(), ".deepractice", "logs");
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
targets.push({
target: "pino/file",
level: finalConfig.level,
options: {
destination: import_path2.default.join(logDir, `deepractice-${today}.log`)
}
});
targets.push({
target: "pino/file",
level: "error",
options: {
destination: import_path2.default.join(logDir, `deepractice-error-${today}.log`)
}
});
}
if (targets.length > 0) {
return (0, import_pino.default)({
level: finalConfig.level || "info",
base: { pid: process.pid },
mixin: () => getCallerInfo(finalConfig.name || "app"),
transport: {
targets
}
});
}
}
return (0, import_pino.default)({
level: finalConfig.level || "info",
base: { pid: process.pid },
mixin: () => getCallerInfo(finalConfig.name || "app")
});
}
// src/nodejs.ts
function createLogger(config = {}) {
return createPinoLogger({ ...config, environment: "nodejs" });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createLogger
});
//# sourceMappingURL=nodejs.cjs.map
{"version":3,"sources":["../src/nodejs.ts","../src/core/pino-adapter.ts","../src/core/caller-tracker.ts"],"sourcesContent":["/**\n * Node.js platform entry point (default)\n * Directly uses Pino adapter for production-grade logging\n */\nimport { createPinoLogger } from \"./core/pino-adapter.js\";\nimport type { LoggerConfig, Logger } from \"./types/index.js\";\n\n/**\n * Create logger for Node.js runtime\n * Always uses Pino for structured logging with file support\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n // Force environment to prevent any detection logic\n return createPinoLogger({ ...config, environment: \"nodejs\" });\n}\n\nexport type { Logger, LoggerConfig };\n","/**\n * Pino logger adapter - internal implementation\n */\nimport pino from \"pino\";\nimport path from \"path\";\nimport os from \"os\";\nimport fs from \"fs\";\nimport type { LoggerConfig } from \"~/types/config.js\";\nimport { getCallerInfo } from \"~/core/caller-tracker.js\";\n\nconst defaultConfig: LoggerConfig = {\n level: (process.env.LOG_LEVEL as any) || \"info\",\n console: true,\n file: {\n dirname: path.join(os.homedir(), \".deepractice\", \"logs\"),\n },\n colors: true,\n name: \"app\",\n};\n\n/**\n * Create a Pino logger instance\n */\nexport function createPinoLogger(config: LoggerConfig = {}): pino.Logger {\n const finalConfig = { ...defaultConfig, ...config };\n\n // Ensure log directory exists\n if (finalConfig.file) {\n const fileConfig =\n typeof finalConfig.file === \"object\" ? finalConfig.file : {};\n const logDir =\n fileConfig.dirname || path.join(os.homedir(), \".deepractice\", \"logs\");\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n }\n\n // For Electron desktop app, avoid worker thread issues\n const isElectron = process.versions && \"electron\" in process.versions;\n const isTest =\n process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\";\n\n if (isElectron || isTest || process.env.DEEPRACTICE_NO_WORKERS === \"true\") {\n // For Electron: use sync mode to avoid worker thread issues\n if (finalConfig.file) {\n const fileConfig =\n typeof finalConfig.file === \"object\" ? finalConfig.file : {};\n const logDir =\n fileConfig.dirname || path.join(os.homedir(), \".deepractice\", \"logs\");\n const today = new Date().toISOString().split(\"T\")[0];\n const logPath = path.join(logDir, `deepractice-${today}.log`);\n\n const dest = pino.destination({\n dest: logPath,\n sync: true,\n });\n\n return pino(\n {\n level: finalConfig.level || \"info\",\n base: { pid: process.pid },\n mixin: () => getCallerInfo(finalConfig.name || \"app\"),\n formatters: {\n level: (label) => {\n return { level: label };\n },\n log: (obj) => {\n const { package: pkg, file, line, ...rest } = obj;\n return {\n ...rest,\n location: pkg && file ? `${pkg} [${file}:${line}]` : undefined,\n };\n },\n },\n },\n dest,\n );\n } else {\n return pino({\n level: finalConfig.level || \"info\",\n base: { pid: process.pid },\n mixin: () => getCallerInfo(finalConfig.name || \"app\"),\n formatters: {\n level: (label) => {\n return { level: label };\n },\n log: (obj) => {\n const { package: pkg, file, line, ...rest } = obj;\n return {\n ...rest,\n location: pkg && file ? `${pkg} [${file}:${line}]` : undefined,\n };\n },\n },\n });\n }\n } else {\n // Use transports for non-Electron environments (better for servers)\n const targets: any[] = [];\n\n // Console transport\n if (finalConfig.console) {\n targets.push({\n target: \"pino-pretty\",\n level: finalConfig.level,\n options: {\n // MCP stdio mode disables colors to avoid ANSI escape codes\n colorize:\n process.env.MCP_TRANSPORT === \"stdio\" ? false : finalConfig.colors,\n translateTime: \"SYS:yyyy-mm-dd HH:MM:ss.l\",\n ignore: \"hostname,pid,package,file,line\",\n destination: 2, // stderr (fd 2) - MCP best practice\n messageFormat: \"{package} [{file}:{line}] {msg}\",\n },\n });\n }\n\n // File transport\n if (finalConfig.file) {\n const fileConfig =\n typeof finalConfig.file === \"object\" ? finalConfig.file : {};\n const logDir =\n fileConfig.dirname || path.join(os.homedir(), \".deepractice\", \"logs\");\n const today = new Date().toISOString().split(\"T\")[0];\n\n targets.push({\n target: \"pino/file\",\n level: finalConfig.level,\n options: {\n destination: path.join(logDir, `deepractice-${today}.log`),\n },\n });\n\n // Separate error log\n targets.push({\n target: \"pino/file\",\n level: \"error\",\n options: {\n destination: path.join(logDir, `deepractice-error-${today}.log`),\n },\n });\n }\n\n // Create logger with transports\n if (targets.length > 0) {\n return pino({\n level: finalConfig.level || \"info\",\n base: { pid: process.pid },\n mixin: () => getCallerInfo(finalConfig.name || \"app\"),\n transport: {\n targets,\n },\n });\n }\n }\n\n // Fallback to basic logger\n return pino({\n level: finalConfig.level || \"info\",\n base: { pid: process.pid },\n mixin: () => getCallerInfo(finalConfig.name || \"app\"),\n });\n}\n","/**\n * Caller location tracking utility\n */\nimport path from \"path\";\n\nexport interface CallerInfo {\n package: string;\n file: string;\n line: number;\n}\n\n/**\n * Get caller information from stack trace\n */\nexport function getCallerInfo(packageName: string): CallerInfo {\n const stack = new Error().stack || \"\";\n const stackLines = stack.split(\"\\n\");\n\n // Find first non-logger stack frame\n for (let i = 2; i < stackLines.length; i++) {\n const line = stackLines[i];\n if (\n line &&\n !line.includes(\"node_modules/pino\") &&\n !line.includes(\"packages/logger\") &&\n !line.includes(\"@deepracticex/logger\")\n ) {\n const match = line.match(/at\\s+(?:.*?\\s+)?\\(?(.*?):(\\d+):(\\d+)\\)?/);\n if (match && match[1] && match[2]) {\n const fullPath = match[1];\n const lineNum = parseInt(match[2], 10);\n const filename = path.basename(fullPath);\n\n return {\n package: packageName,\n file: filename,\n line: lineNum,\n };\n }\n }\n }\n\n return { package: packageName, file: \"unknown\", line: 0 };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGA,kBAAiB;AACjB,IAAAA,eAAiB;AACjB,gBAAe;AACf,gBAAe;;;ACHf,kBAAiB;AAWV,SAAS,cAAc,aAAiC;AAC7D,QAAM,QAAQ,IAAI,MAAM,EAAE,SAAS;AACnC,QAAM,aAAa,MAAM,MAAM,IAAI;AAGnC,WAAS,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;AAC1C,UAAM,OAAO,WAAW,CAAC;AACzB,QACE,QACA,CAAC,KAAK,SAAS,mBAAmB,KAClC,CAAC,KAAK,SAAS,iBAAiB,KAChC,CAAC,KAAK,SAAS,sBAAsB,GACrC;AACA,YAAM,QAAQ,KAAK,MAAM,yCAAyC;AAClE,UAAI,SAAS,MAAM,CAAC,KAAK,MAAM,CAAC,GAAG;AACjC,cAAM,WAAW,MAAM,CAAC;AACxB,cAAM,UAAU,SAAS,MAAM,CAAC,GAAG,EAAE;AACrC,cAAM,WAAW,YAAAC,QAAK,SAAS,QAAQ;AAEvC,eAAO;AAAA,UACL,SAAS;AAAA,UACT,MAAM;AAAA,UAC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SAAuB,CAAC,GAAW;AAE9D,SAAO,iBAAiB,EAAE,GAAG,QAAQ,aAAa,SAAS,CAAC;AAC9D;","names":["import_path","path","path","os","fs","pino"]}
import { L as LoggerConfig, a as Logger } from './logger-Lmm6XEQc.cjs';
/**
* Create logger for Node.js runtime
* Always uses Pino for structured logging with file support
*/
declare function createLogger(config?: LoggerConfig): Logger;
export { Logger, LoggerConfig, createLogger };
import { L as LoggerConfig, a as Logger } from './logger-Lmm6XEQc.js';
/**
* Create logger for Node.js runtime
* Always uses Pino for structured logging with file support
*/
declare function createLogger(config?: LoggerConfig): Logger;
export { Logger, LoggerConfig, createLogger };
// src/core/pino-adapter.ts
import pino from "pino";
import path2 from "path";
import os from "os";
import fs from "fs";
// src/core/caller-tracker.ts
import path from "path";
function getCallerInfo(packageName) {
const stack = new Error().stack || "";
const stackLines = stack.split("\n");
for (let i = 2; i < stackLines.length; i++) {
const line = stackLines[i];
if (line && !line.includes("node_modules/pino") && !line.includes("packages/logger") && !line.includes("@deepracticex/logger")) {
const match = line.match(/at\s+(?:.*?\s+)?\(?(.*?):(\d+):(\d+)\)?/);
if (match && match[1] && match[2]) {
const fullPath = match[1];
const lineNum = parseInt(match[2], 10);
const filename = path.basename(fullPath);
return {
package: packageName,
file: filename,
line: lineNum
};
}
}
}
return { package: packageName, file: "unknown", line: 0 };
}
// src/core/pino-adapter.ts
var defaultConfig = {
level: process.env.LOG_LEVEL || "info",
console: true,
file: {
dirname: path2.join(os.homedir(), ".deepractice", "logs")
},
colors: true,
name: "app"
};
function createPinoLogger(config = {}) {
const finalConfig = { ...defaultConfig, ...config };
if (finalConfig.file) {
const fileConfig = typeof finalConfig.file === "object" ? finalConfig.file : {};
const logDir = fileConfig.dirname || path2.join(os.homedir(), ".deepractice", "logs");
if (!fs.existsSync(logDir)) {
fs.mkdirSync(logDir, { recursive: true });
}
}
const isElectron = process.versions && "electron" in process.versions;
const isTest = process.env.NODE_ENV === "test" || process.env.VITEST === "true";
if (isElectron || isTest || process.env.DEEPRACTICE_NO_WORKERS === "true") {
if (finalConfig.file) {
const fileConfig = typeof finalConfig.file === "object" ? finalConfig.file : {};
const logDir = fileConfig.dirname || path2.join(os.homedir(), ".deepractice", "logs");
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
const logPath = path2.join(logDir, `deepractice-${today}.log`);
const dest = pino.destination({
dest: logPath,
sync: true
});
return pino(
{
level: finalConfig.level || "info",
base: { pid: process.pid },
mixin: () => getCallerInfo(finalConfig.name || "app"),
formatters: {
level: (label) => {
return { level: label };
},
log: (obj) => {
const { package: pkg, file, line, ...rest } = obj;
return {
...rest,
location: pkg && file ? `${pkg} [${file}:${line}]` : void 0
};
}
}
},
dest
);
} else {
return pino({
level: finalConfig.level || "info",
base: { pid: process.pid },
mixin: () => getCallerInfo(finalConfig.name || "app"),
formatters: {
level: (label) => {
return { level: label };
},
log: (obj) => {
const { package: pkg, file, line, ...rest } = obj;
return {
...rest,
location: pkg && file ? `${pkg} [${file}:${line}]` : void 0
};
}
}
});
}
} else {
const targets = [];
if (finalConfig.console) {
targets.push({
target: "pino-pretty",
level: finalConfig.level,
options: {
// MCP stdio mode disables colors to avoid ANSI escape codes
colorize: process.env.MCP_TRANSPORT === "stdio" ? false : finalConfig.colors,
translateTime: "SYS:yyyy-mm-dd HH:MM:ss.l",
ignore: "hostname,pid,package,file,line",
destination: 2,
// stderr (fd 2) - MCP best practice
messageFormat: "{package} [{file}:{line}] {msg}"
}
});
}
if (finalConfig.file) {
const fileConfig = typeof finalConfig.file === "object" ? finalConfig.file : {};
const logDir = fileConfig.dirname || path2.join(os.homedir(), ".deepractice", "logs");
const today = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
targets.push({
target: "pino/file",
level: finalConfig.level,
options: {
destination: path2.join(logDir, `deepractice-${today}.log`)
}
});
targets.push({
target: "pino/file",
level: "error",
options: {
destination: path2.join(logDir, `deepractice-error-${today}.log`)
}
});
}
if (targets.length > 0) {
return pino({
level: finalConfig.level || "info",
base: { pid: process.pid },
mixin: () => getCallerInfo(finalConfig.name || "app"),
transport: {
targets
}
});
}
}
return pino({
level: finalConfig.level || "info",
base: { pid: process.pid },
mixin: () => getCallerInfo(finalConfig.name || "app")
});
}
// src/nodejs.ts
function createLogger(config = {}) {
return createPinoLogger({ ...config, environment: "nodejs" });
}
export {
createLogger
};
//# sourceMappingURL=nodejs.js.map
{"version":3,"sources":["../src/core/pino-adapter.ts","../src/core/caller-tracker.ts","../src/nodejs.ts"],"sourcesContent":["/**\n * Pino logger adapter - internal implementation\n */\nimport pino from \"pino\";\nimport path from \"path\";\nimport os from \"os\";\nimport fs from \"fs\";\nimport type { LoggerConfig } from \"~/types/config.js\";\nimport { getCallerInfo } from \"~/core/caller-tracker.js\";\n\nconst defaultConfig: LoggerConfig = {\n level: (process.env.LOG_LEVEL as any) || \"info\",\n console: true,\n file: {\n dirname: path.join(os.homedir(), \".deepractice\", \"logs\"),\n },\n colors: true,\n name: \"app\",\n};\n\n/**\n * Create a Pino logger instance\n */\nexport function createPinoLogger(config: LoggerConfig = {}): pino.Logger {\n const finalConfig = { ...defaultConfig, ...config };\n\n // Ensure log directory exists\n if (finalConfig.file) {\n const fileConfig =\n typeof finalConfig.file === \"object\" ? finalConfig.file : {};\n const logDir =\n fileConfig.dirname || path.join(os.homedir(), \".deepractice\", \"logs\");\n if (!fs.existsSync(logDir)) {\n fs.mkdirSync(logDir, { recursive: true });\n }\n }\n\n // For Electron desktop app, avoid worker thread issues\n const isElectron = process.versions && \"electron\" in process.versions;\n const isTest =\n process.env.NODE_ENV === \"test\" || process.env.VITEST === \"true\";\n\n if (isElectron || isTest || process.env.DEEPRACTICE_NO_WORKERS === \"true\") {\n // For Electron: use sync mode to avoid worker thread issues\n if (finalConfig.file) {\n const fileConfig =\n typeof finalConfig.file === \"object\" ? finalConfig.file : {};\n const logDir =\n fileConfig.dirname || path.join(os.homedir(), \".deepractice\", \"logs\");\n const today = new Date().toISOString().split(\"T\")[0];\n const logPath = path.join(logDir, `deepractice-${today}.log`);\n\n const dest = pino.destination({\n dest: logPath,\n sync: true,\n });\n\n return pino(\n {\n level: finalConfig.level || \"info\",\n base: { pid: process.pid },\n mixin: () => getCallerInfo(finalConfig.name || \"app\"),\n formatters: {\n level: (label) => {\n return { level: label };\n },\n log: (obj) => {\n const { package: pkg, file, line, ...rest } = obj;\n return {\n ...rest,\n location: pkg && file ? `${pkg} [${file}:${line}]` : undefined,\n };\n },\n },\n },\n dest,\n );\n } else {\n return pino({\n level: finalConfig.level || \"info\",\n base: { pid: process.pid },\n mixin: () => getCallerInfo(finalConfig.name || \"app\"),\n formatters: {\n level: (label) => {\n return { level: label };\n },\n log: (obj) => {\n const { package: pkg, file, line, ...rest } = obj;\n return {\n ...rest,\n location: pkg && file ? `${pkg} [${file}:${line}]` : undefined,\n };\n },\n },\n });\n }\n } else {\n // Use transports for non-Electron environments (better for servers)\n const targets: any[] = [];\n\n // Console transport\n if (finalConfig.console) {\n targets.push({\n target: \"pino-pretty\",\n level: finalConfig.level,\n options: {\n // MCP stdio mode disables colors to avoid ANSI escape codes\n colorize:\n process.env.MCP_TRANSPORT === \"stdio\" ? false : finalConfig.colors,\n translateTime: \"SYS:yyyy-mm-dd HH:MM:ss.l\",\n ignore: \"hostname,pid,package,file,line\",\n destination: 2, // stderr (fd 2) - MCP best practice\n messageFormat: \"{package} [{file}:{line}] {msg}\",\n },\n });\n }\n\n // File transport\n if (finalConfig.file) {\n const fileConfig =\n typeof finalConfig.file === \"object\" ? finalConfig.file : {};\n const logDir =\n fileConfig.dirname || path.join(os.homedir(), \".deepractice\", \"logs\");\n const today = new Date().toISOString().split(\"T\")[0];\n\n targets.push({\n target: \"pino/file\",\n level: finalConfig.level,\n options: {\n destination: path.join(logDir, `deepractice-${today}.log`),\n },\n });\n\n // Separate error log\n targets.push({\n target: \"pino/file\",\n level: \"error\",\n options: {\n destination: path.join(logDir, `deepractice-error-${today}.log`),\n },\n });\n }\n\n // Create logger with transports\n if (targets.length > 0) {\n return pino({\n level: finalConfig.level || \"info\",\n base: { pid: process.pid },\n mixin: () => getCallerInfo(finalConfig.name || \"app\"),\n transport: {\n targets,\n },\n });\n }\n }\n\n // Fallback to basic logger\n return pino({\n level: finalConfig.level || \"info\",\n base: { pid: process.pid },\n mixin: () => getCallerInfo(finalConfig.name || \"app\"),\n });\n}\n","/**\n * Caller location tracking utility\n */\nimport path from \"path\";\n\nexport interface CallerInfo {\n package: string;\n file: string;\n line: number;\n}\n\n/**\n * Get caller information from stack trace\n */\nexport function getCallerInfo(packageName: string): CallerInfo {\n const stack = new Error().stack || \"\";\n const stackLines = stack.split(\"\\n\");\n\n // Find first non-logger stack frame\n for (let i = 2; i < stackLines.length; i++) {\n const line = stackLines[i];\n if (\n line &&\n !line.includes(\"node_modules/pino\") &&\n !line.includes(\"packages/logger\") &&\n !line.includes(\"@deepracticex/logger\")\n ) {\n const match = line.match(/at\\s+(?:.*?\\s+)?\\(?(.*?):(\\d+):(\\d+)\\)?/);\n if (match && match[1] && match[2]) {\n const fullPath = match[1];\n const lineNum = parseInt(match[2], 10);\n const filename = path.basename(fullPath);\n\n return {\n package: packageName,\n file: filename,\n line: lineNum,\n };\n }\n }\n }\n\n return { package: packageName, file: \"unknown\", line: 0 };\n}\n","/**\n * Node.js platform entry point (default)\n * Directly uses Pino adapter for production-grade logging\n */\nimport { createPinoLogger } from \"./core/pino-adapter.js\";\nimport type { LoggerConfig, Logger } from \"./types/index.js\";\n\n/**\n * Create logger for Node.js runtime\n * Always uses Pino for structured logging with file support\n */\nexport function createLogger(config: LoggerConfig = {}): Logger {\n // Force environment to prevent any detection logic\n return createPinoLogger({ ...config, environment: \"nodejs\" });\n}\n\nexport type { Logger, LoggerConfig };\n"],"mappings":";AAGA,OAAO,UAAU;AACjB,OAAOA,WAAU;AACjB,OAAO,QAAQ;AACf,OAAO,QAAQ;;;ACHf,OAAO,UAAU;AAWV,SAAS,cAAc,aAAiC;AAC7D,QAAM,QAAQ,IAAI,MAAM,EAAE,SA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,YAAY,SAAS;AAAA,QAC5B,MAAM,EAAE,KAAK,QAAQ,IAAI;AAAA,QACzB,OAAO,MAAM,cAAc,YAAY,QAAQ,KAAK;AAAA,QACpD,WAAW;AAAA,UACT;AAAA,QACF;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AAGA,SAAO,KAAK;AAAA,IACV,OAAO,YAAY,SAAS;AAAA,IAC5B,MAAM,EAAE,KAAK,QAAQ,IAAI;AAAA,IACzB,OAAO,MAAM,cAAc,YAAY,QAAQ,KAAK;AAAA,EACtD,CAAC;AACH;;;AEvJO,SAAS,aAAa,SAAuB,CAAC,GAAW;AAE9D,SAAO,iBAAiB,EAAE,GAAG,QAAQ,aAAa,SAAS,CAAC;AAC9D;","names":["path","path"]}
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/test.ts
var test_exports = {};
__export(test_exports, {
clearTestLogs: () => clearTestLogs,
createLogger: () => createLogger,
createTestLogger: () => createTestLogger2,
getTestLogs: () => getTestLogs,
getTestLogsByLevel: () => getTestLogsByLevel,
getTestLogsCount: () => getTestLogsCount
});
module.exports = __toCommonJS(test_exports);
// src/core/test-adapter.ts
var capturedLogs = [];
var LOG_LEVEL_PRIORITY = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
function getMinLogLevel(level = "info") {
return LOG_LEVEL_PRIORITY[level];
}
function shouldLog(level, minLevel) {
return LOG_LEVEL_PRIORITY[level] >= minLevel;
}
function createLogEntry(level, args, shouldOutput, minLevel) {
if (!shouldLog(level, minLevel)) {
return;
}
let message;
let context;
if (args.length === 1) {
if (typeof args[0] === "string") {
message = args[0];
} else {
context = args[0];
message = JSON.stringify(args[0]);
}
} else if (args.length >= 2) {
if (typeof args[0] === "object" && args[0] !== null) {
context = args[0];
message = args.slice(1).join(" ");
} else {
message = args.join(" ");
}
} else {
message = "";
}
capturedLogs.push({
level,
message,
context,
timestamp: Date.now()
});
if (shouldOutput) {
const consoleMethod = level === "fatal" ? "error" : level;
const logFn = console[consoleMethod] || console.log;
if (context) {
logFn(`[${level.toUpperCase()}]`, context, message);
} else {
logFn(`[${level.toUpperCase()}]`, message);
}
}
}
function createTestLogger(config = {}) {
const shouldOutput = config.console === true;
const minLevel = getMinLogLevel(config.level);
return {
trace: (...args) => createLogEntry("trace", args, shouldOutput, minLevel),
debug: (...args) => createLogEntry("debug", args, shouldOutput, minLevel),
info: (...args) => createLogEntry("info", args, shouldOutput, minLevel),
warn: (...args) => createLogEntry("warn", args, shouldOutput, minLevel),
error: (...args) => createLogEntry("error", args, shouldOutput, minLevel),
fatal: (...args) => createLogEntry("fatal", args, shouldOutput, minLevel)
};
}
function getTestLogs() {
return [...capturedLogs];
}
function getTestLogsByLevel(level) {
return capturedLogs.filter((log) => log.level === level);
}
function clearTestLogs() {
capturedLogs.length = 0;
}
function getTestLogsCount() {
return capturedLogs.length;
}
// src/test.ts
function createTestLogger2(config = {}) {
return createTestLogger(config);
}
function createLogger(config = {}) {
return createTestLogger({
...config,
environment: "test"
});
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
clearTestLogs,
createLogger,
createTestLogger,
getTestLogs,
getTestLogsByLevel,
getTestLogsCount
});
//# sourceMappingURL=test.cjs.map
{"version":3,"sources":["../src/test.ts","../src/core/test-adapter.ts"],"sourcesContent":["/**\n * Test environment entry point\n * Provides in-memory logger for testing with inspection utilities\n */\nimport type { LoggerConfig } from \"~/types/index.js\";\nimport { createTestLogger as createTestLoggerAdapter } from \"~/core/test-adapter.js\";\n\n// Export test utilities\nexport {\n getTestLogs,\n getTestLogsByLevel,\n clearTestLogs,\n getTestLogsCount,\n type CapturedLog,\n} from \"~/core/test-adapter.js\";\n\n/**\n * Create a test logger instance\n * Uses synchronous test adapter for immediate log capture\n */\nexport function createTestLogger(config: LoggerConfig = {}): any {\n return createTestLoggerAdapter(config);\n}\n\n/**\n * Create a logger for test environment\n * This is the main export that tests should use\n */\nexport function createLogger(config: LoggerConfig = {}): any {\n return createTestLoggerAdapter({\n ...config,\n environment: \"test\",\n });\n}\n\n// Re-export types\nexport type { LoggerConfig, Logger, LogLevel } from \"~/types/index.js\";\n","/**\n * Test adapter - In-memory logger for testing environments\n * Captures all logs in memory for inspection and assertion\n */\nimport type { LoggerConfig, LogLevel } from \"~/types/index.js\";\n\nexport interface CapturedLog {\n level: LogLevel;\n message: string;\n context?: Record<string, any>;\n timestamp: number;\n}\n\n/**\n * Global log storage for test environment\n * Shared across all test logger instances in the same process\n */\nconst capturedLogs: CapturedLog[] = [];\n\n/**\n * Log level priority mapping for filtering\n */\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\n/**\n * Get current log level priority\n */\nfunction getMinLogLevel(level: LogLevel = \"info\"): number {\n return LOG_LEVEL_PRIORITY[level];\n}\n\n/**\n * Check if a log level should be recorded based on config\n */\nfunction shouldLog(level: LogLevel, minLevel: number): boolean {\n return LOG_LEVEL_PRIORITY[level] >= minLevel;\n}\n\n/**\n * Create a log entry and optionally output to console\n */\nfunction createLogEntry(\n level: LogLevel,\n args: any[],\n shouldOutput: boolean,\n minLevel: number,\n): void {\n // Check if this level should be logged\n if (!shouldLog(level, minLevel)) {\n return;\n }\n\n let message: string;\n let context: Record<string, any> | undefined;\n\n // Parse arguments - support both (message) and (context, message) patterns\n if (args.length === 1) {\n if (typeof args[0] === \"string\") {\n message = args[0];\n } else {\n context = args[0];\n message = JSON.stringify(args[0]);\n }\n } else if (args.length >= 2) {\n // First arg might be context object\n if (typeof args[0] === \"object\" && args[0] !== null) {\n context = args[0];\n message = args.slice(1).join(\" \");\n } else {\n message = args.join(\" \");\n }\n } else {\n message = \"\";\n }\n\n // Always capture in memory\n capturedLogs.push({\n level,\n message,\n context,\n timestamp: Date.now(),\n });\n\n // Optionally output to console\n if (shouldOutput) {\n const consoleMethod = level === \"fatal\" ? \"error\" : level;\n const logFn = (console as any)[consoleMethod] || console.log;\n\n if (context) {\n logFn(`[${level.toUpperCase()}]`, context, message);\n } else {\n logFn(`[${level.toUpperCase()}]`, message);\n }\n }\n}\n\n/**\n * Create a test logger instance\n */\nexport function createTestLogger(config: LoggerConfig = {}): any {\n // Default: silent in tests (console: false), unless explicitly enabled\n const shouldOutput = config.console === true;\n const minLevel = getMinLogLevel(config.level);\n\n return {\n trace: (...args: any[]) =>\n createLogEntry(\"trace\", args, shouldOutput, minLevel),\n debug: (...args: any[]) =>\n createLogEntry(\"debug\", args, shouldOutput, minLevel),\n info: (...args: any[]) =>\n createLogEntry(\"info\", args, shouldOutput, minLevel),\n warn: (...args: any[]) =>\n createLogEntry(\"warn\", args, shouldOutput, minLevel),\n error: (...args: any[]) =>\n createLogEntry(\"error\", args, shouldOutput, minLevel),\n fatal: (...args: any[]) =>\n createLogEntry(\"fatal\", args, shouldOutput, minLevel),\n };\n}\n\n/**\n * Get all captured logs\n */\nexport function getTestLogs(): CapturedLog[] {\n return [...capturedLogs];\n}\n\n/**\n * Get logs filtered by level\n */\nexport function getTestLogsByLevel(level: LogLevel): CapturedLog[] {\n return capturedLogs.filter((log) => log.level === level);\n}\n\n/**\n * Clear all captured logs\n */\nexport function clearTestLogs(): void {\n capturedLogs.length = 0;\n}\n\n/**\n * Get the count of captured logs\n */\nexport function getTestLogsCount(): number {\n return capturedLogs.length;\n}\n"],"mappings":";;;;;;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AC,KAAK,SAAS,OAAO;AAAA,IACpD,OAAO;AACL,YAAM,IAAI,MAAM,YAAY,CAAC,KAAK,OAAO;AAAA,IAC3C;AAAA,EACF;AACF;AAKO,SAAS,iBAAiB,SAAuB,CAAC,GAAQ;AAE/D,QAAM,eAAe,OAAO,YAAY;AACxC,QAAM,WAAW,eAAe,OAAO,KAAK;AAE5C,SAAO;AAAA,IACL,OAAO,IAAI,SACT,eAAe,SAAS,MAAM,cAAc,QAAQ;AAAA,IACtD,OAAO,IAAI,SACT,eAAe,SAAS,MAAM,cAAc,QAAQ;AAAA,IACtD,MAAM,IAAI,SACR,eAAe,QAAQ,MAAM,cAAc,QAAQ;AAAA,IACrD,MAAM,IAAI,SACR,eAAe,QAAQ,MAAM,cAAc,QAAQ;AAAA,IACrD,OAAO,IAAI,SACT,eAAe,SAAS,MAAM,cAAc,QAAQ;AAAA,IACtD,OAAO,IAAI,SACT,eAAe,SAAS,MAAM,cAAc,QAAQ;AAAA,EACxD;AACF;AAKO,SAAS,cAA6B;AAC3C,SAAO,CAAC,GAAG,YAAY;AACzB;AAKO,SAAS,mBAAmB,OAAgC;AACjE,SAAO,aAAa,OAAO,CAAC,QAAQ,IAAI,UAAU,KAAK;AACzD;AAKO,SAAS,gBAAsB;AACpC,eAAa,SAAS;AACxB;AAKO,SAAS,mBAA2B;AACzC,SAAO,aAAa;AACtB;;;ADrIO,SAASC,kBAAiB,SAAuB,CAAC,GAAQ;AAC/D,SAAO,iBAAwB,MAAM;AACvC;AAMO,SAAS,aAAa,SAAuB,CAAC,GAAQ;AAC3D,SAAO,iBAAwB;AAAA,IAC7B,GAAG;AAAA,IACH,aAAa;AAAA,EACf,CAAC;AACH;","names":["createTestLogger","createTestLogger"]}
import { b as LogLevel, L as LoggerConfig } from './logger-Lmm6XEQc.cjs';
export { a as Logger } from './logger-Lmm6XEQc.cjs';
/**
* Test adapter - In-memory logger for testing environments
* Captures all logs in memory for inspection and assertion
*/
interface CapturedLog {
level: LogLevel;
message: string;
context?: Record<string, any>;
timestamp: number;
}
/**
* Get all captured logs
*/
declare function getTestLogs(): CapturedLog[];
/**
* Get logs filtered by level
*/
declare function getTestLogsByLevel(level: LogLevel): CapturedLog[];
/**
* Clear all captured logs
*/
declare function clearTestLogs(): void;
/**
* Get the count of captured logs
*/
declare function getTestLogsCount(): number;
/**
* Test environment entry point
* Provides in-memory logger for testing with inspection utilities
*/
/**
* Create a test logger instance
* Uses synchronous test adapter for immediate log capture
*/
declare function createTestLogger(config?: LoggerConfig): any;
/**
* Create a logger for test environment
* This is the main export that tests should use
*/
declare function createLogger(config?: LoggerConfig): any;
export { type CapturedLog, LogLevel, LoggerConfig, clearTestLogs, createLogger, createTestLogger, getTestLogs, getTestLogsByLevel, getTestLogsCount };
import { b as LogLevel, L as LoggerConfig } from './logger-Lmm6XEQc.js';
export { a as Logger } from './logger-Lmm6XEQc.js';
/**
* Test adapter - In-memory logger for testing environments
* Captures all logs in memory for inspection and assertion
*/
interface CapturedLog {
level: LogLevel;
message: string;
context?: Record<string, any>;
timestamp: number;
}
/**
* Get all captured logs
*/
declare function getTestLogs(): CapturedLog[];
/**
* Get logs filtered by level
*/
declare function getTestLogsByLevel(level: LogLevel): CapturedLog[];
/**
* Clear all captured logs
*/
declare function clearTestLogs(): void;
/**
* Get the count of captured logs
*/
declare function getTestLogsCount(): number;
/**
* Test environment entry point
* Provides in-memory logger for testing with inspection utilities
*/
/**
* Create a test logger instance
* Uses synchronous test adapter for immediate log capture
*/
declare function createTestLogger(config?: LoggerConfig): any;
/**
* Create a logger for test environment
* This is the main export that tests should use
*/
declare function createLogger(config?: LoggerConfig): any;
export { type CapturedLog, LogLevel, LoggerConfig, clearTestLogs, createLogger, createTestLogger, getTestLogs, getTestLogsByLevel, getTestLogsCount };
// src/core/test-adapter.ts
var capturedLogs = [];
var LOG_LEVEL_PRIORITY = {
trace: 0,
debug: 1,
info: 2,
warn: 3,
error: 4,
fatal: 5
};
function getMinLogLevel(level = "info") {
return LOG_LEVEL_PRIORITY[level];
}
function shouldLog(level, minLevel) {
return LOG_LEVEL_PRIORITY[level] >= minLevel;
}
function createLogEntry(level, args, shouldOutput, minLevel) {
if (!shouldLog(level, minLevel)) {
return;
}
let message;
let context;
if (args.length === 1) {
if (typeof args[0] === "string") {
message = args[0];
} else {
context = args[0];
message = JSON.stringify(args[0]);
}
} else if (args.length >= 2) {
if (typeof args[0] === "object" && args[0] !== null) {
context = args[0];
message = args.slice(1).join(" ");
} else {
message = args.join(" ");
}
} else {
message = "";
}
capturedLogs.push({
level,
message,
context,
timestamp: Date.now()
});
if (shouldOutput) {
const consoleMethod = level === "fatal" ? "error" : level;
const logFn = console[consoleMethod] || console.log;
if (context) {
logFn(`[${level.toUpperCase()}]`, context, message);
} else {
logFn(`[${level.toUpperCase()}]`, message);
}
}
}
function createTestLogger(config = {}) {
const shouldOutput = config.console === true;
const minLevel = getMinLogLevel(config.level);
return {
trace: (...args) => createLogEntry("trace", args, shouldOutput, minLevel),
debug: (...args) => createLogEntry("debug", args, shouldOutput, minLevel),
info: (...args) => createLogEntry("info", args, shouldOutput, minLevel),
warn: (...args) => createLogEntry("warn", args, shouldOutput, minLevel),
error: (...args) => createLogEntry("error", args, shouldOutput, minLevel),
fatal: (...args) => createLogEntry("fatal", args, shouldOutput, minLevel)
};
}
function getTestLogs() {
return [...capturedLogs];
}
function getTestLogsByLevel(level) {
return capturedLogs.filter((log) => log.level === level);
}
function clearTestLogs() {
capturedLogs.length = 0;
}
function getTestLogsCount() {
return capturedLogs.length;
}
// src/test.ts
function createTestLogger2(config = {}) {
return createTestLogger(config);
}
function createLogger(config = {}) {
return createTestLogger({
...config,
environment: "test"
});
}
export {
clearTestLogs,
createLogger,
createTestLogger2 as createTestLogger,
getTestLogs,
getTestLogsByLevel,
getTestLogsCount
};
//# sourceMappingURL=test.js.map
{"version":3,"sources":["../src/core/test-adapter.ts","../src/test.ts"],"sourcesContent":["/**\n * Test adapter - In-memory logger for testing environments\n * Captures all logs in memory for inspection and assertion\n */\nimport type { LoggerConfig, LogLevel } from \"~/types/index.js\";\n\nexport interface CapturedLog {\n level: LogLevel;\n message: string;\n context?: Record<string, any>;\n timestamp: number;\n}\n\n/**\n * Global log storage for test environment\n * Shared across all test logger instances in the same process\n */\nconst capturedLogs: CapturedLog[] = [];\n\n/**\n * Log level priority mapping for filtering\n */\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n trace: 0,\n debug: 1,\n info: 2,\n warn: 3,\n error: 4,\n fatal: 5,\n};\n\n/**\n * Get current log level priority\n */\nfunction getMinLogLevel(level: LogLevel = \"info\"): number {\n return LOG_LEVEL_PRIORITY[level];\n}\n\n/**\n * Check if a log level should be recorded based on config\n */\nfunction shouldLog(level: LogLevel, minLevel: number): boolean {\n return LOG_LEVEL_PRIORITY[level] >= minLevel;\n}\n\n/**\n * Create a log entry and optionally output to console\n */\nfunction createLogEntry(\n level: LogLevel,\n args: any[],\n shouldOutput: boolean,\n minLevel: number,\n): void {\n // Check if this level should be logged\n if (!shouldLog(level, minLevel)) {\n return;\n }\n\n let message: string;\n let context: Record<string, any> | undefined;\n\n // Parse arguments - support both (message) and (context, message) patterns\n if (args.length === 1) {\n if (typeof args[0] === \"string\") {\n message = args[0];\n } else {\n context = args[0];\n message = JSON.stringify(args[0]);\n }\n } else if (args.length >= 2) {\n // First arg might be context object\n if (typeof args[0] === \"object\" && args[0] !== null) {\n context = args[0];\n message = args.slice(1).join(\" \");\n } else {\n message = args.join(\" \");\n }\n } else {\n message = \"\";\n }\n\n // Always capture in memory\n capturedLogs.push({\n level,\n message,\n context,\n timestamp: Date.now(),\n });\n\n // Optionally output to console\n if (shouldOutput) {\n const consoleMethod = level === \"fatal\" ? \"error\" : level;\n const logFn = (console as any)[consoleMethod] || console.log;\n\n if (context) {\n logFn(`[${level.toUpperCase()}]`, context, message);\n } else {\n logFn(`[${level.toUpperCase()}]`, message);\n }\n }\n}\n\n/**\n * Create a test logger instance\n */\nexport function createTestLogger(config: LoggerConfig = {}): any {\n // Default: silent in tests (console: false), unless explicitly enabled\n const shouldOutput = config.console === true;\n const minLevel = getMinLogLevel(config.level);\n\n return {\n trace: (...args: any[]) =>\n createLogEntry(\"trace\", args, shouldOutput, minLevel),\n debug: (...args: any[]) =>\n createLogEntry(\"debug\", args, shouldOutput, minLevel),\n info: (...args: any[]) =>\n createLogEntry(\"info\", args, shouldOutput, minLevel),\n warn: (...args: any[]) =>\n createLogEntry(\"warn\", args, shouldOutput, minLevel),\n error: (...args: any[]) =>\n createLogEntry(\"error\", args, shouldOutput, minLevel),\n fatal: (...args: any[]) =>\n createLogEntry(\"fatal\", args, shouldOutput, minLevel),\n };\n}\n\n/**\n * Get all captured logs\n */\nexport function getTestLogs(): CapturedLog[] {\n return [...capturedLogs];\n}\n\n/**\n * Get logs filtered by level\n */\nexport function getTestLogsByLevel(level: LogLevel): CapturedLog[] {\n return capturedLogs.filter((log) => log.level === level);\n}\n\n/**\n * Clear all captured logs\n */\nexport function clearTestLogs(): void {\n capturedLogs.length = 0;\n}\n\n/**\n * Get the count of captured logs\n */\nexport function getTestLogsCount(): number {\n return capturedLogs.length;\n}\n","/**\n * Test environment entry point\n * Provides in-memory logger for testing with inspection utilities\n */\nimport type { LoggerConfig } from \"~/types/index.js\";\nimport { createTestLogger as createTestLoggerAdapter } from \"~/core/test-adapter.js\";\n\n// Export test utilities\nexport {\n getTestLogs,\n getTestLogsByLevel,\n clearTestLogs,\n getTestLogsCount,\n type CapturedLog,\n} from \"~/core/test-adapter.js\";\n\n/**\n * Create a test logger instance\n * Uses synchronous test adapter for immediate log capture\n */\nexport function createTestLogger(config: LoggerConfig = {}): any {\n return createTestLoggerAdapter(config);\n}\n\n/**\n * Create a logger for test environment\n * This is the main export that tests should use\n */\nexport function createLogger(config: LoggerConfig = {}): any {\n return createTestLoggerAdapter({\n ...config,\n environment: \"test\",\n });\n}\n\n// Re-export types\nexport type { LoggerConfig, Logger, LogLevel } from \"~/types/index.js\";\n"],"mappings":";AAiBA,IAA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,EACF;AACF;AAKO,SAAS,iBAAiB,SAAuB,CAAC,GAAQ;AAE/D,QAAM,eAAe,OAAO,YAAY;AACxC,QAAM,WAAW,eAAe,OAAO,KAAK;AAE5C,SAAO;AAAA,IACL,OAAO,IAAI,SACT,eAAe,SAAS,MAAM,cAAc,QAAQ;AAAA,IACtD,OAAO,IAAI,SACT,eAAe,SAAS,MAAM,cAAc,QAAQ;AAAA,IACtD,MAAM,IAAI,SACR,eAAe,QAAQ,MAAM,cAAc,QAAQ;AAAA,IACrD,MAAM,IAAI,SACR,eAAe,QAAQ,MAAM,cAAc,QAAQ;AAAA,IACrD,OAAO,IAAI,SACT,eAAe,SAAS,MAAM,cAAc,QAAQ;AAAA,IACtD,OAAO,IAAI,SACT,eAAe,SAAS,MAAM,cAAc,QAAQ;AAAA,EACxD;AACF;AAKO,SAAS,cAA6B;AAC3C,SAAO,CAAC,GAAG,YAAY;AACzB;AAKO,SAAS,mBAAmB,OAAgC;AACjE,SAAO,aAAa,OAAO,CAAC,QAAQ,IAAI,UAAU,KAAK;AACzD;AAKO,SAAS,gBAAsB;AACpC,eAAa,SAAS;AACxB;AAKO,SAAS,mBAA2B;AACzC,SAAO,aAAa;AACtB;;;ACrIO,SAASA,kBAAiB,SAAuB,CAAC,GAAQ;AAC/D,SAAO,iBAAwB,MAAM;AACvC;AAMO,SAAS,aAAa,SAAuB,CAAC,GAAQ;AAC3D,SAAO,iBAAwB;AAAA,IAC7B,GAAG;AAAA,IACH,aAAa;AAAA,EACf,CAAC;AACH;","names":["createTestLogger"]}
# @deepracticex/logger
Universal logging system for all JavaScript runtimes - Node.js, Cloudflare Workers, Browser, and more.
## Features
- 🌍 **Universal** - Works in Node.js, Cloudflare Workers, Browser, and other JavaScript runtimes
- 🎯 **Platform-Specific Optimizations** - Pino for Node.js, lightweight console for edge/browser
- 📦 **Tree-Shakeable** - Only bundles the code you need for your platform
- 🎨 **Pretty Console Output** - Color support with automatic MCP stdio detection
- 📁 **File Logging** - Daily rotation for Node.js (when enabled)
- 📍 **Caller Location Tracking** - Automatic file/line tracking
- 🔧 **TypeScript Support** - Full type safety
- ⚡ **Zero Config** - Sensible defaults, customizable when needed
## Installation
```bash
pnpm add @deepracticex/logger
```
## Platform-Specific Entry Points
Choose the right entry point for your platform:
### Node.js (Default)
```typescript
// Uses Pino for high performance logging
import { createLogger } from "@deepracticex/logger";
// or explicitly
import { createLogger } from "@deepracticex/logger/nodejs";
const logger = createLogger({
level: "info",
name: "my-service",
console: true,
file: true, // File logging with daily rotation
});
logger.info("Server started");
```
### Cloudflare Workers
```typescript
// Uses lightweight console adapter (no Node.js dependencies)
import { createLogger } from "@deepracticex/logger/cloudflare-workers";
const logger = createLogger({
level: "info",
name: "my-worker",
console: true,
});
logger.info("Request handled");
```
### Browser
```typescript
// Uses browser-optimized console adapter
import { createLogger } from "@deepracticex/logger/browser";
const logger = createLogger({
level: "debug",
name: "my-app",
console: true,
colors: true,
});
logger.info("App initialized");
```
### Test Environment (Vitest/Jest)
```typescript
// Uses in-memory test adapter with log capture
import {
createLogger,
getTestLogs,
clearTestLogs,
} from "@deepracticex/logger/test";
const logger = createLogger({
level: "debug",
name: "my-service",
console: false, // Silent by default in tests
});
// Your test code
logger.info("test message");
// Assert logs were captured
const logs = getTestLogs();
expect(logs).toHaveLength(1);
expect(logs[0].message).toBe("test message");
// Clean up between tests
clearTestLogs();
```
## Quick Start
### Default Logger (Node.js)
```typescript
import { info, warn, error, debug } from "@deepracticex/logger";
info("Server started");
warn("Low memory");
error("Connection failed");
debug("Debug info");
```
### Custom Logger
```typescript
import { createLogger } from "@deepracticex/logger";
const logger = createLogger({
level: "debug",
name: "@deepracticex/my-service",
console: true,
file: {
dirname: "/var/log/myapp",
},
colors: true,
});
logger.info("Custom logger initialized");
```
## Configuration
### LoggerConfig
```typescript
interface LoggerConfig {
// Log level (default: 'info')
level?: "fatal" | "error" | "warn" | "info" | "debug" | "trace";
// Package/service name (default: 'app')
name?: string;
// Console output (default: true)
console?: boolean;
// File logging - Node.js only (default: false)
file?:
| boolean
| {
dirname?: string; // Log directory (default: ~/.deepractice/logs)
};
// Color support (default: true, auto-disabled in MCP stdio)
colors?: boolean;
}
```
### Environment Variables
- `LOG_LEVEL` - Set log level (default: 'info')
- `MCP_TRANSPORT=stdio` - Auto-disable colors for MCP stdio mode
- `DEEPRACTICE_NO_WORKERS=true` - Force sync mode (useful for Electron)
## Log Levels
- `fatal` - Critical errors that require immediate attention
- `error` - Errors that need to be fixed
- `warn` - Warnings about potential issues
- `info` - General information (default)
- `debug` - Detailed debug information
- `trace` - Very verbose trace information
## Platform Details
### Node.js
Uses [Pino](https://github.com/pinojs/pino) for high-performance logging:
- File logging with daily rotation
- Automatic caller location tracking
- Worker threads for better performance
- MCP stdio mode detection
**File Structure:**
```
~/.deepractice/logs/
├── deepractice-2025-10-13.log # All logs
└── deepractice-error-2025-10-13.log # Error logs only
```
### Cloudflare Workers
Uses lightweight console adapter:
- Minimal bundle size (~1.5KB)
- No Node.js dependencies
- Full logging API compatibility
- Works with Wrangler dev and production
### Browser
Uses browser-optimized console adapter:
- Native console API
- Color support
- Source map integration
- DevTools friendly
### Test Environment
Uses in-memory test adapter:
- Auto-detected in vitest/jest (via `VITEST=true` or `NODE_ENV=test`)
- Silent by default (no console output)
- Captures all logs in memory for assertions
- Zero I/O overhead for fast tests
- Utilities: `getTestLogs()`, `clearTestLogs()`, `getTestLogsByLevel()`
**Usage in tests:**
```typescript
import {
createLogger,
getTestLogs,
clearTestLogs,
} from "@deepracticex/logger/test";
describe("my feature", () => {
const logger = createLogger();
afterEach(() => {
clearTestLogs(); // Clean up between tests
});
it("should log messages", () => {
logger.info("test started");
logger.warn("warning message");
const logs = getTestLogs();
expect(logs).toHaveLength(2);
expect(logs[0].level).toBe("info");
});
});
```
**Auto-detection:**
When running in vitest, the default `@deepracticex/logger` import automatically uses the test adapter:
```typescript
// Automatically uses test adapter in vitest
import { createLogger } from "@deepracticex/logger";
const logger = createLogger(); // No console output in tests
```
**Enable console output for debugging:**
```typescript
// Show logs in test output
const logger = createLogger({ console: true });
// Or run with verbose reporter
// pnpm test -- --reporter=verbose
```
## Examples
### Node.js Service
```typescript
import { createLogger } from "@deepracticex/logger";
const logger = createLogger({
level: process.env.LOG_LEVEL || "info",
name: "@deepracticex/api-server",
console: true,
file: {
dirname: "./logs",
},
});
logger.info({ port: 3000 }, "Server started");
logger.error({ err: error }, "Database connection failed");
```
### Cloudflare Worker
```typescript
import { createLogger } from "@deepracticex/logger/cloudflare-workers";
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const logger = createLogger({
name: "my-worker",
level: env.LOG_LEVEL || "info",
});
logger.info({ url: request.url }, "Request received");
try {
// Handle request
return new Response("OK");
} catch (error) {
logger.error({ error }, "Request failed");
return new Response("Error", { status: 500 });
}
},
};
```
### Browser App
```typescript
import { createLogger } from "@deepracticex/logger/browser";
const logger = createLogger({
name: "my-app",
level: "debug",
colors: true,
});
logger.info("App initialized");
document.addEventListener("click", (e) => {
logger.debug({ target: e.target }, "User clicked");
});
```
## Architecture
The logger uses a multi-adapter architecture with automatic runtime detection:
1. **Pino Adapter** - For Node.js (high performance, file support)
2. **Console Adapter** - For edge/browser (lightweight, universal)
3. **Test Adapter** - For test environments (in-memory, inspectable)
Platform-specific entry points ensure only the necessary adapter is bundled:
```
@deepracticex/logger → Auto-detect → appropriate adapter
@deepracticex/logger/nodejs → nodejs.ts → pino-adapter
@deepracticex/logger/cloudflare-workers → cloudflare-workers.ts → console-adapter
@deepracticex/logger/browser → browser.ts → console-adapter
@deepracticex/logger/test → test.ts → test-adapter
```
**Auto-detection priority:**
1. Test environment (VITEST=true or NODE_ENV=test) → test adapter
2. Cloudflare Workers (caches API present) → console adapter
3. Node.js (process.versions.node) → pino adapter
4. Fallback → console adapter (browser)
## Bundle Size
- Node.js: Full pino functionality (~200KB with dependencies)
- Cloudflare Workers: ~1.5KB (console adapter only)
- Browser: ~1.5KB (console adapter only)
- Test: ~2KB (test adapter with inspection utilities)
## FAQ
### Why platform-specific entry points?
This allows bundlers (esbuild, webpack, etc.) to tree-shake unused code. If you use the Cloudflare Workers entry, the 200KB+ pino dependency won't be included in your bundle.
### Can I use the same logger across different files?
Yes! Create a logger module:
```typescript
// src/infrastructure/logger/index.ts
import { createLogger } from "@deepracticex/logger/cloudflare-workers";
export const logger = createLogger({
name: "my-app",
level: "info",
});
```
Then import everywhere:
```typescript
import { logger } from "~/infrastructure/logger";
logger.info("Hello from any file!");
```
### Does it work with monorepos?
Yes! Each package can use the appropriate entry point:
```typescript
// apps/api (Node.js)
import { createLogger } from "@deepracticex/logger";
// apps/worker (Cloudflare)
import { createLogger } from "@deepracticex/logger/cloudflare-workers";
// apps/web (Browser)
import { createLogger } from "@deepracticex/logger/browser";
```
### How do I use it in tests?
The logger automatically detects test environments (vitest/jest) and uses the test adapter:
```typescript
// Automatically silent in tests
import { createLogger } from "@deepracticex/logger";
const logger = createLogger();
logger.info("message"); // Captured, but no console output
```
To inspect logs in tests:
```typescript
import {
createLogger,
getTestLogs,
clearTestLogs,
} from "@deepracticex/logger/test";
const logger = createLogger();
logger.info("test message");
const logs = getTestLogs();
expect(logs[0].message).toBe("test message");
clearTestLogs(); // Clean up
```
### How do I see logs when debugging tests?
Use vitest's verbose reporter:
```bash
pnpm test -- --reporter=verbose
```
Or enable console output explicitly:
```typescript
const logger = createLogger({ console: true });
```
## License
MIT