@mks2508/better-logger 2.0.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/.claude/settings.local.json +6 -1
  2. package/CHANGELOG.json +93 -1
  3. package/CHANGELOG.md +127 -0
  4. package/CLAUDE.md +14 -1
  5. package/README.md +111 -20
  6. package/bun.lock +333 -0
  7. package/dist/Logger.d.ts +851 -0
  8. package/dist/Logger.d.ts.map +1 -0
  9. package/dist/ScopedLogger.d.ts +57 -0
  10. package/dist/ScopedLogger.d.ts.map +1 -0
  11. package/dist/chunks/Logger-BCfx_yCK.js +2 -0
  12. package/dist/chunks/Logger-BCfx_yCK.js.map +1 -0
  13. package/dist/chunks/Logger-C126NTrD.js +4269 -0
  14. package/dist/chunks/Logger-C126NTrD.js.map +1 -0
  15. package/dist/chunks/RemoteLogHandler-CjWpWZGl.js +33 -0
  16. package/dist/chunks/RemoteLogHandler-CjWpWZGl.js.map +1 -0
  17. package/dist/chunks/RemoteLogHandler-ymkQ97xl.js +2 -0
  18. package/dist/chunks/RemoteLogHandler-ymkQ97xl.js.map +1 -0
  19. package/dist/chunks/environment-Ba5kShbx.js +4 -0
  20. package/dist/chunks/environment-Ba5kShbx.js.map +1 -0
  21. package/dist/chunks/environment-TI2ByCPT.js +1209 -0
  22. package/dist/chunks/environment-TI2ByCPT.js.map +1 -0
  23. package/dist/chunks/formatting-Blwy-f0W.js +2 -0
  24. package/dist/chunks/formatting-Blwy-f0W.js.map +1 -0
  25. package/dist/chunks/formatting-CuNUqGks.js +380 -0
  26. package/dist/chunks/formatting-CuNUqGks.js.map +1 -0
  27. package/dist/cli/CommandProcessor.d.ts +100 -0
  28. package/dist/cli/CommandProcessor.d.ts.map +1 -0
  29. package/dist/cli/commands/ConfigCommand.d.ts +14 -0
  30. package/dist/cli/commands/ConfigCommand.d.ts.map +1 -0
  31. package/dist/cli/commands/ExportCommand.d.ts +48 -0
  32. package/dist/cli/commands/ExportCommand.d.ts.map +1 -0
  33. package/dist/cli/commands/HistoryCommand.d.ts +47 -0
  34. package/dist/cli/commands/HistoryCommand.d.ts.map +1 -0
  35. package/dist/cli/commands/StatusCommand.d.ts +30 -0
  36. package/dist/cli/commands/StatusCommand.d.ts.map +1 -0
  37. package/dist/cli/commands/ThemeCommand.d.ts +30 -0
  38. package/dist/cli/commands/ThemeCommand.d.ts.map +1 -0
  39. package/dist/cli/help.d.ts +12 -0
  40. package/dist/cli/help.d.ts.map +1 -0
  41. package/dist/cli/index.d.ts +15 -0
  42. package/dist/cli/index.d.ts.map +1 -0
  43. package/dist/constants.d.ts +227 -0
  44. package/dist/constants.d.ts.map +1 -0
  45. package/dist/core.cjs +2 -0
  46. package/dist/core.cjs.map +1 -0
  47. package/dist/core.d.ts +127 -0
  48. package/dist/core.d.ts.map +1 -0
  49. package/dist/core.js +291 -0
  50. package/dist/core.js.map +1 -0
  51. package/dist/example.d.ts +18 -0
  52. package/dist/example.d.ts.map +1 -0
  53. package/dist/exports-module.d.ts +196 -0
  54. package/dist/exports-module.d.ts.map +1 -0
  55. package/dist/exports.cjs +2 -0
  56. package/dist/exports.cjs.map +1 -0
  57. package/dist/exports.js +238 -0
  58. package/dist/exports.js.map +1 -0
  59. package/dist/handlers/AnalyticsLogHandler.d.ts +8 -0
  60. package/dist/handlers/AnalyticsLogHandler.d.ts.map +1 -0
  61. package/dist/handlers/ExportLogHandler.d.ts +100 -0
  62. package/dist/handlers/ExportLogHandler.d.ts.map +1 -0
  63. package/dist/handlers/FileLogHandler.d.ts +33 -0
  64. package/dist/handlers/FileLogHandler.d.ts.map +1 -0
  65. package/dist/handlers/RemoteLogHandler.d.ts +11 -0
  66. package/dist/handlers/RemoteLogHandler.d.ts.map +1 -0
  67. package/dist/handlers/index.d.ts +8 -0
  68. package/dist/handlers/index.d.ts.map +1 -0
  69. package/dist/hooks/HookManager.d.ts +21 -0
  70. package/dist/hooks/HookManager.d.ts.map +1 -0
  71. package/dist/hooks/index.d.ts +2 -0
  72. package/dist/hooks/index.d.ts.map +1 -0
  73. package/dist/index.cjs +2 -0
  74. package/dist/index.cjs.map +1 -0
  75. package/dist/index.d.ts +144 -0
  76. package/dist/index.d.ts.map +1 -0
  77. package/dist/index.js +478 -0
  78. package/dist/index.js.map +1 -0
  79. package/dist/main.d.ts +2 -0
  80. package/dist/main.d.ts.map +1 -0
  81. package/dist/serializers/SerializerRegistry.d.ts +16 -0
  82. package/dist/serializers/SerializerRegistry.d.ts.map +1 -0
  83. package/dist/serializers/index.d.ts +2 -0
  84. package/dist/serializers/index.d.ts.map +1 -0
  85. package/dist/styling/LogStyleBuilder.d.ts +146 -0
  86. package/dist/styling/LogStyleBuilder.d.ts.map +1 -0
  87. package/dist/styling/SemanticStyles.d.ts +178 -0
  88. package/dist/styling/SemanticStyles.d.ts.map +1 -0
  89. package/dist/styling/SmartPresets.d.ts +22 -0
  90. package/dist/styling/SmartPresets.d.ts.map +1 -0
  91. package/dist/styling/StyleBuilder.d.ts +140 -0
  92. package/dist/styling/StyleBuilder.d.ts.map +1 -0
  93. package/dist/styling/StyleCache.d.ts +42 -0
  94. package/dist/styling/StyleCache.d.ts.map +1 -0
  95. package/dist/styling/banners.d.ts +42 -0
  96. package/dist/styling/banners.d.ts.map +1 -0
  97. package/dist/styling/index.d.ts +10 -0
  98. package/dist/styling/index.d.ts.map +1 -0
  99. package/dist/styling/themes.d.ts +7 -0
  100. package/dist/styling/themes.d.ts.map +1 -0
  101. package/dist/styling-module.d.ts +178 -0
  102. package/dist/styling-module.d.ts.map +1 -0
  103. package/dist/styling.cjs +2 -0
  104. package/dist/styling.cjs.map +1 -0
  105. package/dist/styling.js +146 -0
  106. package/dist/styling.js.map +1 -0
  107. package/dist/terminal/terminal-renderer.d.ts +63 -0
  108. package/dist/terminal/terminal-renderer.d.ts.map +1 -0
  109. package/dist/transports/ConsoleTransport.d.ts +9 -0
  110. package/dist/transports/ConsoleTransport.d.ts.map +1 -0
  111. package/dist/transports/FileTransport.d.ts +15 -0
  112. package/dist/transports/FileTransport.d.ts.map +1 -0
  113. package/dist/transports/HttpTransport.d.ts +16 -0
  114. package/dist/transports/HttpTransport.d.ts.map +1 -0
  115. package/dist/transports/TransportManager.d.ts +14 -0
  116. package/dist/transports/TransportManager.d.ts.map +1 -0
  117. package/dist/transports/index.d.ts +5 -0
  118. package/dist/transports/index.d.ts.map +1 -0
  119. package/dist/types/core.d.ts +272 -0
  120. package/dist/types/core.d.ts.map +1 -0
  121. package/dist/types/handlers.d.ts +85 -0
  122. package/dist/types/handlers.d.ts.map +1 -0
  123. package/dist/types/hooks.d.ts +36 -0
  124. package/dist/types/hooks.d.ts.map +1 -0
  125. package/dist/types/index.d.ts +11 -0
  126. package/dist/types/index.d.ts.map +1 -0
  127. package/dist/types/serializers.d.ts +25 -0
  128. package/dist/types/serializers.d.ts.map +1 -0
  129. package/dist/types/transports.d.ts +47 -0
  130. package/dist/types/transports.d.ts.map +1 -0
  131. package/dist/utils/adapter.d.ts +48 -0
  132. package/dist/utils/adapter.d.ts.map +1 -0
  133. package/dist/utils/ansi-colors.d.ts +156 -0
  134. package/dist/utils/ansi-colors.d.ts.map +1 -0
  135. package/dist/utils/environment-detector.d.ts +35 -0
  136. package/dist/utils/environment-detector.d.ts.map +1 -0
  137. package/dist/utils/environment.d.ts +47 -0
  138. package/dist/utils/environment.d.ts.map +1 -0
  139. package/dist/utils/formatting.d.ts +58 -0
  140. package/dist/utils/formatting.d.ts.map +1 -0
  141. package/dist/utils/index.d.ts +8 -0
  142. package/dist/utils/index.d.ts.map +1 -0
  143. package/dist/utils/opentui-detection.d.ts +34 -0
  144. package/dist/utils/opentui-detection.d.ts.map +1 -0
  145. package/dist/utils/output.d.ts +46 -0
  146. package/dist/utils/output.d.ts.map +1 -0
  147. package/dist/utils/stackTrace.d.ts +6 -0
  148. package/dist/utils/stackTrace.d.ts.map +1 -0
  149. package/dist/utils/timestamps.d.ts +20 -0
  150. package/dist/utils/timestamps.d.ts.map +1 -0
  151. package/dist/vite.svg +1 -0
  152. package/docs/API.md +227 -0
  153. package/package.json +1 -1
  154. package/packages/core/package.json +1 -1
  155. package/src/Logger.ts +391 -102
  156. package/src/ScopedLogger.ts +78 -318
  157. package/src/hooks/HookManager.ts +177 -0
  158. package/src/hooks/index.ts +1 -0
  159. package/src/index.ts +77 -2
  160. package/src/serializers/SerializerRegistry.ts +173 -0
  161. package/src/serializers/index.ts +1 -0
  162. package/src/styling/StyleCache.ts +131 -0
  163. package/src/transports/ConsoleTransport.ts +28 -0
  164. package/src/transports/FileTransport.ts +53 -0
  165. package/src/transports/HttpTransport.ts +56 -0
  166. package/src/transports/TransportManager.ts +130 -0
  167. package/src/transports/index.ts +4 -0
  168. package/src/types/core.ts +46 -0
  169. package/src/types/hooks.ts +45 -0
  170. package/src/types/index.ts +39 -1
  171. package/src/types/serializers.ts +30 -0
  172. package/src/types/transports.ts +52 -0
@@ -0,0 +1,4269 @@
1
+ import { h as getAdaptiveColor, A as ADAPTIVE_COLORS, b as StyleBuilder, j as BUFFER_LIMITS, k as generateLogId, l as parseTimeInput, m as formatDisplayTime, n as safeStringify, o as escapeHtml, q as EXPORT_FORMATS, D as DEFAULT_CONFIG$1, r as setupThemeChangeListener, t as getEnvironment, p as parseStackTrace, f as formatTimestamp, c as createStyledOutput, S as StylePresets } from "./environment-TI2ByCPT.js";
2
+ const DEFAULT_CONFIG = {
3
+ maxDepth: 5,
4
+ circular: "placeholder",
5
+ preserveUndefined: false
6
+ };
7
+ class SerializerRegistry {
8
+ serializers = /* @__PURE__ */ new Map();
9
+ config;
10
+ constructor(config = {}) {
11
+ this.config = { ...DEFAULT_CONFIG, ...config };
12
+ this.registerDefaults();
13
+ }
14
+ registerDefaults() {
15
+ this.add(Error, (err) => ({
16
+ name: err.name,
17
+ message: err.message,
18
+ stack: err.stack?.split("\n").slice(0, 10),
19
+ ...err.cause ? { cause: this.serialize(err.cause) } : {}
20
+ }), 100);
21
+ this.add(Date, (date) => ({
22
+ iso: date.toISOString(),
23
+ timestamp: date.getTime()
24
+ }), 90);
25
+ this.add(RegExp, (regex) => ({
26
+ pattern: regex.source,
27
+ flags: regex.flags
28
+ }), 90);
29
+ this.add(Map, (map, ctx) => {
30
+ const obj = {};
31
+ map.forEach((value, key) => {
32
+ const keyStr = typeof key === "object" ? JSON.stringify(key) : String(key);
33
+ obj[keyStr] = this.serializeInternal(value, {
34
+ ...ctx,
35
+ depth: ctx.depth + 1,
36
+ path: [...ctx.path, keyStr]
37
+ });
38
+ });
39
+ return { __type: "Map", entries: obj };
40
+ }, 80);
41
+ this.add(Set, (set, ctx) => ({
42
+ __type: "Set",
43
+ values: Array.from(set).map(
44
+ (v, i) => this.serializeInternal(v, {
45
+ ...ctx,
46
+ depth: ctx.depth + 1,
47
+ path: [...ctx.path, `[${i}]`]
48
+ })
49
+ )
50
+ }), 80);
51
+ if (typeof Buffer !== "undefined") {
52
+ this.add(Buffer, (buf) => ({
53
+ __type: "Buffer",
54
+ length: buf.length,
55
+ preview: buf.slice(0, 50).toString("hex")
56
+ }), 70);
57
+ }
58
+ }
59
+ add(type, serializer, priority = 50) {
60
+ this.serializers.set(type, { type, serializer, priority });
61
+ }
62
+ remove(type) {
63
+ return this.serializers.delete(type);
64
+ }
65
+ has(type) {
66
+ return this.serializers.has(type);
67
+ }
68
+ getAll() {
69
+ return Array.from(this.serializers.values()).sort((a, b) => (b.priority ?? 50) - (a.priority ?? 50));
70
+ }
71
+ findSerializer(value) {
72
+ const sorted = this.getAll();
73
+ for (const entry of sorted) {
74
+ if (value instanceof entry.type) {
75
+ return entry;
76
+ }
77
+ }
78
+ return null;
79
+ }
80
+ serializeInternal(value, context) {
81
+ if (value === null) return null;
82
+ if (value === void 0) return this.config.preserveUndefined ? void 0 : "[undefined]";
83
+ if (typeof value === "function") return `[Function: ${value.name || "anonymous"}]`;
84
+ if (typeof value !== "object") return value;
85
+ if (context.depth >= this.config.maxDepth) {
86
+ return "[Max Depth]";
87
+ }
88
+ if (context.seen.has(value)) {
89
+ switch (this.config.circular) {
90
+ case "error":
91
+ throw new Error(`Circular reference at ${context.path.join(".")}`);
92
+ case "skip":
93
+ return void 0;
94
+ case "placeholder":
95
+ default:
96
+ return "[Circular]";
97
+ }
98
+ }
99
+ context.seen.add(value);
100
+ const serializer = this.findSerializer(value);
101
+ if (serializer) {
102
+ return serializer.serializer(value, context);
103
+ }
104
+ if (Array.isArray(value)) {
105
+ return value.map(
106
+ (item, i) => this.serializeInternal(item, {
107
+ ...context,
108
+ depth: context.depth + 1,
109
+ path: [...context.path, `[${i}]`]
110
+ })
111
+ );
112
+ }
113
+ const result = {};
114
+ for (const [key, val] of Object.entries(value)) {
115
+ result[key] = this.serializeInternal(val, {
116
+ ...context,
117
+ depth: context.depth + 1,
118
+ path: [...context.path, key]
119
+ });
120
+ }
121
+ return result;
122
+ }
123
+ serialize(value, config) {
124
+ const mergedConfig = { ...this.config, ...config };
125
+ return this.serializeInternal(value, {
126
+ depth: 0,
127
+ maxDepth: mergedConfig.maxDepth,
128
+ path: [],
129
+ seen: /* @__PURE__ */ new WeakSet()
130
+ });
131
+ }
132
+ }
133
+ function generateId() {
134
+ return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
135
+ }
136
+ class HookManager {
137
+ hooks = /* @__PURE__ */ new Map();
138
+ middlewares = [];
139
+ constructor() {
140
+ this.hooks.set("beforeLog", []);
141
+ this.hooks.set("afterLog", []);
142
+ this.hooks.set("onError", []);
143
+ }
144
+ on(event, callback, priority = 50) {
145
+ const registration = {
146
+ id: generateId(),
147
+ event,
148
+ callback,
149
+ priority,
150
+ once: false
151
+ };
152
+ const hooks = this.hooks.get(event);
153
+ hooks.push(registration);
154
+ hooks.sort((a, b) => b.priority - a.priority);
155
+ return () => this.removeHook(event, registration.id);
156
+ }
157
+ once(event, callback, priority = 50) {
158
+ const registration = {
159
+ id: generateId(),
160
+ event,
161
+ callback,
162
+ priority,
163
+ once: true
164
+ };
165
+ const hooks = this.hooks.get(event);
166
+ hooks.push(registration);
167
+ hooks.sort((a, b) => b.priority - a.priority);
168
+ return () => this.removeHook(event, registration.id);
169
+ }
170
+ off(event, callback) {
171
+ const hooks = this.hooks.get(event);
172
+ if (!hooks) return false;
173
+ const index = hooks.findIndex((h) => h.callback === callback);
174
+ if (index >= 0) {
175
+ hooks.splice(index, 1);
176
+ return true;
177
+ }
178
+ return false;
179
+ }
180
+ removeHook(event, id) {
181
+ const hooks = this.hooks.get(event);
182
+ if (hooks) {
183
+ const index = hooks.findIndex((h) => h.id === id);
184
+ if (index >= 0) {
185
+ hooks.splice(index, 1);
186
+ }
187
+ }
188
+ }
189
+ use(middleware, priority = 50) {
190
+ const registration = {
191
+ id: generateId(),
192
+ fn: middleware,
193
+ priority
194
+ };
195
+ this.middlewares.push(registration);
196
+ this.middlewares.sort((a, b) => b.priority - a.priority);
197
+ return () => {
198
+ const index = this.middlewares.findIndex((m) => m.id === registration.id);
199
+ if (index >= 0) {
200
+ this.middlewares.splice(index, 1);
201
+ }
202
+ };
203
+ }
204
+ async emit(event, entry) {
205
+ const hooks = this.hooks.get(event) || [];
206
+ let currentEntry = { ...entry };
207
+ const toRemove = [];
208
+ for (const hook of hooks) {
209
+ try {
210
+ const result = await hook.callback(currentEntry);
211
+ if (result) {
212
+ currentEntry = { ...currentEntry, ...result };
213
+ }
214
+ if (hook.once) {
215
+ toRemove.push(hook.id);
216
+ }
217
+ } catch (error) {
218
+ if (event !== "onError") {
219
+ await this.emit("onError", {
220
+ ...currentEntry,
221
+ error,
222
+ hookEvent: event
223
+ });
224
+ }
225
+ }
226
+ }
227
+ toRemove.forEach((id) => this.removeHook(event, id));
228
+ return currentEntry;
229
+ }
230
+ async process(entry) {
231
+ let currentEntry = { ...entry };
232
+ currentEntry = await this.emit("beforeLog", currentEntry);
233
+ if (this.middlewares.length > 0) {
234
+ let index = 0;
235
+ const executeNext = async () => {
236
+ if (index < this.middlewares.length) {
237
+ const middleware = this.middlewares[index++];
238
+ if (middleware) {
239
+ await middleware.fn(currentEntry, executeNext);
240
+ }
241
+ }
242
+ };
243
+ await executeNext();
244
+ }
245
+ return currentEntry;
246
+ }
247
+ async afterProcess(entry) {
248
+ await this.emit("afterLog", entry);
249
+ }
250
+ clear() {
251
+ this.hooks.forEach((hooks) => hooks.length = 0);
252
+ this.middlewares.length = 0;
253
+ }
254
+ getStats() {
255
+ return {
256
+ hooks: {
257
+ beforeLog: this.hooks.get("beforeLog")?.length || 0,
258
+ afterLog: this.hooks.get("afterLog")?.length || 0,
259
+ onError: this.hooks.get("onError")?.length || 0
260
+ },
261
+ middlewares: this.middlewares.length
262
+ };
263
+ }
264
+ }
265
+ const LOG_LEVELS = {
266
+ debug: 0,
267
+ info: 1,
268
+ warn: 2,
269
+ error: 3,
270
+ critical: 4
271
+ };
272
+ function generateTransportId() {
273
+ return `transport-${Date.now()}-${Math.random().toString(36).substr(2, 6)}`;
274
+ }
275
+ class TransportManager {
276
+ transports = /* @__PURE__ */ new Map();
277
+ defaultLevel = "info";
278
+ constructor(defaultLevel) {
279
+ if (defaultLevel) {
280
+ this.defaultLevel = defaultLevel;
281
+ }
282
+ }
283
+ add(target) {
284
+ const id = generateTransportId();
285
+ const level = target.level || this.defaultLevel;
286
+ let transport;
287
+ if (typeof target.target === "string") {
288
+ throw new Error(`String transport targets not supported. Use inline transport object.`);
289
+ } else {
290
+ transport = target.target;
291
+ }
292
+ const entry = {
293
+ id,
294
+ transport,
295
+ options: target.options || {},
296
+ level,
297
+ levelValue: LOG_LEVELS[level]
298
+ };
299
+ this.transports.set(id, entry);
300
+ return id;
301
+ }
302
+ remove(id) {
303
+ const entry = this.transports.get(id);
304
+ if (entry) {
305
+ entry.transport.close?.();
306
+ return this.transports.delete(id);
307
+ }
308
+ return false;
309
+ }
310
+ async write(record) {
311
+ const promises = [];
312
+ for (const entry of this.transports.values()) {
313
+ if (record.levelValue < entry.levelValue) {
314
+ continue;
315
+ }
316
+ let transformedRecord = record;
317
+ if (entry.options.transform) {
318
+ const result2 = entry.options.transform(record);
319
+ if (result2 === null) continue;
320
+ transformedRecord = result2;
321
+ }
322
+ const result = entry.transport.write(transformedRecord);
323
+ if (result instanceof Promise) {
324
+ promises.push(result);
325
+ }
326
+ }
327
+ await Promise.all(promises);
328
+ }
329
+ async flush() {
330
+ const promises = [];
331
+ for (const entry of this.transports.values()) {
332
+ if (entry.transport.flush) {
333
+ const result = entry.transport.flush();
334
+ if (result instanceof Promise) {
335
+ promises.push(result);
336
+ }
337
+ }
338
+ }
339
+ await Promise.all(promises);
340
+ }
341
+ async close() {
342
+ await this.flush();
343
+ const promises = [];
344
+ for (const entry of this.transports.values()) {
345
+ if (entry.transport.close) {
346
+ const result = entry.transport.close();
347
+ if (result instanceof Promise) {
348
+ promises.push(result);
349
+ }
350
+ }
351
+ }
352
+ await Promise.all(promises);
353
+ this.transports.clear();
354
+ }
355
+ get count() {
356
+ return this.transports.size;
357
+ }
358
+ list() {
359
+ return Array.from(this.transports.keys());
360
+ }
361
+ }
362
+ const THEME_PRESETS = {
363
+ default: {
364
+ debug: {
365
+ emoji: "🐞",
366
+ label: "DEBUG",
367
+ background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
368
+ color: "#ffffff",
369
+ border: "1px solid #667eea",
370
+ shadow: "0 2px 4px rgba(102, 126, 234, 0.3)"
371
+ },
372
+ info: {
373
+ emoji: "ℹ️",
374
+ label: "INFO",
375
+ background: "linear-gradient(135deg, #74b9ff 0%, #0984e3 100%)",
376
+ color: "#ffffff",
377
+ border: "1px solid #74b9ff",
378
+ shadow: "0 2px 4px rgba(116, 185, 255, 0.3)"
379
+ },
380
+ warn: {
381
+ emoji: "⚠️",
382
+ label: "WARN",
383
+ background: "linear-gradient(135deg, #fdcb6e 0%, #e17055 100%)",
384
+ color: "#2d3436",
385
+ border: "1px solid #fdcb6e",
386
+ shadow: "0 2px 4px rgba(253, 203, 110, 0.3)"
387
+ },
388
+ error: {
389
+ emoji: "❌",
390
+ label: "ERROR",
391
+ background: "linear-gradient(135deg, #e84393 0%, #d63031 100%)",
392
+ color: "#ffffff",
393
+ border: "1px solid #e84393",
394
+ shadow: "0 2px 4px rgba(232, 67, 147, 0.3)"
395
+ },
396
+ success: {
397
+ emoji: "✅",
398
+ label: "SUCCESS",
399
+ background: "linear-gradient(135deg, #00b894 0%, #00a085 100%)",
400
+ color: "#ffffff",
401
+ border: "1px solid #00b894",
402
+ shadow: "0 2px 4px rgba(0, 184, 148, 0.3)"
403
+ },
404
+ critical: {
405
+ emoji: "🔥",
406
+ label: "CRITICAL",
407
+ background: "linear-gradient(135deg, #ff3838 0%, #ff1744 100%)",
408
+ color: "#ffffff",
409
+ border: "2px solid #ff3838",
410
+ shadow: "0 4px 8px rgba(255, 56, 56, 0.5)"
411
+ }
412
+ },
413
+ dark: {
414
+ debug: {
415
+ emoji: "🌙",
416
+ label: "DEBUG",
417
+ background: "linear-gradient(135deg, #2d3748 0%, #4a5568 100%)",
418
+ color: "#e2e8f0",
419
+ border: "1px solid #4a5568",
420
+ shadow: "0 2px 4px rgba(45, 55, 72, 0.8)"
421
+ },
422
+ info: {
423
+ emoji: "💡",
424
+ label: "INFO",
425
+ background: "linear-gradient(135deg, #1a202c 0%, #2d3748 100%)",
426
+ color: "#90cdf4",
427
+ border: "1px solid #3182ce",
428
+ shadow: "0 2px 4px rgba(26, 32, 44, 0.8)"
429
+ },
430
+ warn: {
431
+ emoji: "⚡",
432
+ label: "WARN",
433
+ background: "linear-gradient(135deg, #744210 0%, #975a16 100%)",
434
+ color: "#faf089",
435
+ border: "1px solid #d69e2e",
436
+ shadow: "0 2px 4px rgba(116, 66, 16, 0.8)"
437
+ },
438
+ error: {
439
+ emoji: "💀",
440
+ label: "ERROR",
441
+ background: "linear-gradient(135deg, #742a2a 0%, #9b2c2c 100%)",
442
+ color: "#feb2b2",
443
+ border: "1px solid #e53e3e",
444
+ shadow: "0 2px 4px rgba(116, 42, 42, 0.8)"
445
+ },
446
+ success: {
447
+ emoji: "🎯",
448
+ label: "SUCCESS",
449
+ background: "linear-gradient(135deg, #276749 0%, #2f855a 100%)",
450
+ color: "#9ae6b4",
451
+ border: "1px solid #38a169",
452
+ shadow: "0 2px 4px rgba(39, 103, 73, 0.8)"
453
+ },
454
+ critical: {
455
+ emoji: "💥",
456
+ label: "CRITICAL",
457
+ background: "linear-gradient(135deg, #1a1a1a 0%, #ff0000 100%)",
458
+ color: "#ffffff",
459
+ border: "2px solid #ff0000",
460
+ shadow: "0 4px 8px rgba(255, 0, 0, 0.9)"
461
+ }
462
+ },
463
+ neon: {
464
+ debug: {
465
+ emoji: "⚡",
466
+ label: "DEBUG",
467
+ background: "linear-gradient(135deg, #0f3460 0%, #e94560 100%)",
468
+ color: "#00ffff",
469
+ border: "1px solid #00ffff",
470
+ shadow: "0 0 10px rgba(0, 255, 255, 0.5)"
471
+ },
472
+ info: {
473
+ emoji: "🔮",
474
+ label: "INFO",
475
+ background: "linear-gradient(135deg, #16213e 0%, #0f3460 100%)",
476
+ color: "#00ff41",
477
+ border: "1px solid #00ff41",
478
+ shadow: "0 0 10px rgba(0, 255, 65, 0.5)"
479
+ },
480
+ warn: {
481
+ emoji: "⚠️",
482
+ label: "WARN",
483
+ background: "linear-gradient(135deg, #533a03 0%, #e94560 100%)",
484
+ color: "#ffff00",
485
+ border: "1px solid #ffff00",
486
+ shadow: "0 0 10px rgba(255, 255, 0, 0.5)"
487
+ },
488
+ error: {
489
+ emoji: "💥",
490
+ label: "ERROR",
491
+ background: "linear-gradient(135deg, #5c0a0a 0%, #ff073a 100%)",
492
+ color: "#ff073a",
493
+ border: "1px solid #ff073a",
494
+ shadow: "0 0 10px rgba(255, 7, 58, 0.8)"
495
+ },
496
+ success: {
497
+ emoji: "✨",
498
+ label: "SUCCESS",
499
+ background: "linear-gradient(135deg, #0a5c0a 0%, #39ff14 100%)",
500
+ color: "#39ff14",
501
+ border: "1px solid #39ff14",
502
+ shadow: "0 0 10px rgba(57, 255, 20, 0.8)"
503
+ },
504
+ critical: {
505
+ emoji: "🌟",
506
+ label: "CRITICAL",
507
+ background: "linear-gradient(135deg, #000000 0%, #ff0080 100%)",
508
+ color: "#ff0080",
509
+ border: "2px solid #ff0080",
510
+ shadow: "0 0 20px rgba(255, 0, 128, 1)"
511
+ }
512
+ },
513
+ minimal: {
514
+ debug: {
515
+ emoji: "",
516
+ label: "DEBUG",
517
+ background: "#f7fafc",
518
+ color: "#4a5568",
519
+ border: "1px solid #e2e8f0",
520
+ shadow: "none"
521
+ },
522
+ info: {
523
+ emoji: "",
524
+ label: "INFO",
525
+ background: "#ebf8ff",
526
+ color: "#2b6cb0",
527
+ border: "1px solid #bee3f8",
528
+ shadow: "none"
529
+ },
530
+ warn: {
531
+ emoji: "",
532
+ label: "WARN",
533
+ background: "#fffbf0",
534
+ color: "#c05621",
535
+ border: "1px solid #fed7aa",
536
+ shadow: "none"
537
+ },
538
+ error: {
539
+ emoji: "",
540
+ label: "ERROR",
541
+ background: "#fef5f5",
542
+ color: "#c53030",
543
+ border: "1px solid #fca5a5",
544
+ shadow: "none"
545
+ },
546
+ success: {
547
+ emoji: "",
548
+ label: "SUCCESS",
549
+ background: "#f0fff4",
550
+ color: "#2f855a",
551
+ border: "1px solid #9ae6b4",
552
+ shadow: "none"
553
+ },
554
+ critical: {
555
+ emoji: "",
556
+ label: "CRITICAL",
557
+ background: "#fef5f5",
558
+ color: "#e53e3e",
559
+ border: "2px solid #f56565",
560
+ shadow: "none"
561
+ }
562
+ },
563
+ // Additional theme variants can be added here
564
+ light: {
565
+ debug: {
566
+ emoji: "🔍",
567
+ label: "DEBUG",
568
+ background: "linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)",
569
+ color: "#1565c0",
570
+ border: "1px solid #90caf9",
571
+ shadow: "0 1px 3px rgba(33, 150, 243, 0.2)"
572
+ },
573
+ info: {
574
+ emoji: "ℹ️",
575
+ label: "INFO",
576
+ background: "linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%)",
577
+ color: "#7b1fa2",
578
+ border: "1px solid #ce93d8",
579
+ shadow: "0 1px 3px rgba(156, 39, 176, 0.2)"
580
+ },
581
+ warn: {
582
+ emoji: "⚠️",
583
+ label: "WARN",
584
+ background: "linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%)",
585
+ color: "#f57c00",
586
+ border: "1px solid #ffcc02",
587
+ shadow: "0 1px 3px rgba(255, 152, 0, 0.2)"
588
+ },
589
+ error: {
590
+ emoji: "❌",
591
+ label: "ERROR",
592
+ background: "linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%)",
593
+ color: "#d32f2f",
594
+ border: "1px solid #f44336",
595
+ shadow: "0 1px 3px rgba(244, 67, 54, 0.2)"
596
+ },
597
+ success: {
598
+ emoji: "✅",
599
+ label: "SUCCESS",
600
+ background: "linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%)",
601
+ color: "#388e3c",
602
+ border: "1px solid #4caf50",
603
+ shadow: "0 1px 3px rgba(76, 175, 80, 0.2)"
604
+ },
605
+ critical: {
606
+ emoji: "🚨",
607
+ label: "CRITICAL",
608
+ background: "linear-gradient(135deg, #fce4ec 0%, #f8bbd9 100%)",
609
+ color: "#c2185b",
610
+ border: "2px solid #e91e63",
611
+ shadow: "0 2px 6px rgba(233, 30, 99, 0.3)"
612
+ }
613
+ },
614
+ cyberpunk: {
615
+ debug: {
616
+ emoji: "🤖",
617
+ label: "DEBUG",
618
+ background: "linear-gradient(135deg, #0d1b2a 0%, #415a77 100%)",
619
+ color: "#00d4aa",
620
+ border: "1px solid #00d4aa",
621
+ shadow: "0 0 15px rgba(0, 212, 170, 0.4)"
622
+ },
623
+ info: {
624
+ emoji: "🔗",
625
+ label: "INFO",
626
+ background: "linear-gradient(135deg, #1b263b 0%, #0d1b2a 100%)",
627
+ color: "#00b4d8",
628
+ border: "1px solid #00b4d8",
629
+ shadow: "0 0 15px rgba(0, 180, 216, 0.4)"
630
+ },
631
+ warn: {
632
+ emoji: "⚡",
633
+ label: "WARN",
634
+ background: "linear-gradient(135deg, #f72585 0%, #b5179e 100%)",
635
+ color: "#ffff3f",
636
+ border: "1px solid #ffff3f",
637
+ shadow: "0 0 15px rgba(255, 255, 63, 0.4)"
638
+ },
639
+ error: {
640
+ emoji: "💀",
641
+ label: "ERROR",
642
+ background: "linear-gradient(135deg, #7209b7 0%, #480ca8 100%)",
643
+ color: "#ff006e",
644
+ border: "1px solid #ff006e",
645
+ shadow: "0 0 15px rgba(255, 0, 110, 0.6)"
646
+ },
647
+ success: {
648
+ emoji: "⚡",
649
+ label: "SUCCESS",
650
+ background: "linear-gradient(135deg, #003566 0%, #001d3d 100%)",
651
+ color: "#00f5ff",
652
+ border: "1px solid #00f5ff",
653
+ shadow: "0 0 15px rgba(0, 245, 255, 0.4)"
654
+ },
655
+ critical: {
656
+ emoji: "💥",
657
+ label: "CRITICAL",
658
+ background: "linear-gradient(135deg, #000000 0%, #ff0040 100%)",
659
+ color: "#ff0040",
660
+ border: "2px solid #ff0040",
661
+ shadow: "0 0 25px rgba(255, 0, 64, 0.8)"
662
+ }
663
+ }
664
+ };
665
+ const BANNER_VARIANTS = {
666
+ simple: {
667
+ text: "🚀 ADVANCED LOGGER v2.0.0 - State-of-the-art Console Styling 🚀",
668
+ style: "background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 20px; border-radius: 8px; font-weight: bold; font-size: 14px;"
669
+ },
670
+ ascii: {
671
+ text: `
672
+ ___ ____ _ __ ___ _ __ _____ _____ ____ __ ___ _____ _____ _____ ____
673
+ / _ \\ / __ \\| | / / / _ \\ | \\ | |/ ____| ____| _ \\ | | / _ \\ / ____| ___| _ | _ \\
674
+ / /_\\ \\ / / _\` | |/ / / /_\\ \\ | \\| | | | |__ | | | | | | / / \\ \\| | __| |_ | |_| | |_) |
675
+ | _ || | (_| | < | _ | | . \` | | | __| | | | | | | | | | | | |_ | _| | /| _ <
676
+ | | | |\\ \\__,_|_|\\_\\ | | | | | |\\ | |___| |____| |_| | | |__\\ \\_/ /| |__| | |___| |\\ \\| |_) |
677
+ \\_| |_/ \\____/ \\_| |_/ |_| \\_|\\_____|______|____/ |_____/\\___/ \\_____|_____|_| \\_|____/
678
+
679
+ Advanced Logger v2.0.0 - Console Excellence`,
680
+ style: 'font-family: "Courier New", Consolas, Monaco, monospace; color: #667eea; font-size: 11px; line-height: 1.2;'
681
+ },
682
+ unicode: {
683
+ text: `
684
+ ╔══════════════════════════════════════════════════════════════════════════╗
685
+ ║ 🚀 ADVANCED LOGGER v2.0.0 ║
686
+ ║ State-of-the-art Console Styling ║
687
+ ╚══════════════════════════════════════════════════════════════════════════╝`,
688
+ style: 'font-family: "Courier New", Consolas, Monaco, monospace; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px; font-size: 12px; line-height: 1.3;'
689
+ },
690
+ svg: {
691
+ text: " ",
692
+ style: `
693
+ background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 400 80'><defs><linearGradient id='grad' x1='0%' y1='0%' x2='100%' y2='0%'><stop offset='0%' style='stop-color:%23667eea'/><stop offset='100%' style='stop-color:%23764ba2'/></linearGradient></defs><rect width='100%' height='100%' fill='url(%23grad)' rx='8'/><text x='200' y='30' text-anchor='middle' fill='white' font-family='monospace' font-size='14' font-weight='bold'>🚀 ADVANCED LOGGER</text><text x='200' y='50' text-anchor='middle' fill='white' font-family='monospace' font-size='12'>State-of-the-art Console Styling</text><text x='200' y='65' text-anchor='middle' fill='white' font-family='monospace' font-size='10'>v2.0.0</text></svg>");
694
+ background-repeat: no-repeat;
695
+ background-size: 400px 80px;
696
+ padding: 40px 200px;
697
+ color: transparent;
698
+ display: inline-block;
699
+ border-radius: 8px;
700
+ `
701
+ },
702
+ animated: {
703
+ text: " 🚀 ADVANCED LOGGER v2.0.0 ",
704
+ style: `
705
+ background: linear-gradient(-45deg, #667eea, #764ba2, #667eea, #764ba2);
706
+ background-size: 400% 400%;
707
+ color: white;
708
+ padding: 15px 25px;
709
+ border-radius: 10px;
710
+ font-weight: bold;
711
+ font-size: 14px;
712
+ font-family: monospace;
713
+ animation: gradientShift 3s ease infinite;
714
+ display: inline-block;
715
+ `
716
+ }
717
+ };
718
+ const THEME_BANNERS = {
719
+ default: {
720
+ simple: "🚀 ADVANCED LOGGER v2.0.0 - State-of-the-art Console Styling 🚀",
721
+ style: "background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 12px 20px; border-radius: 8px; font-weight: bold;"
722
+ },
723
+ dark: {
724
+ simple: "🌙 ADVANCED LOGGER v2.0.0 - Dark Mode Console Excellence 🌙",
725
+ style: "background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%); color: #e2e8f0; padding: 12px 20px; border-radius: 8px; font-weight: bold; border: 1px solid #4a5568;"
726
+ },
727
+ neon: {
728
+ simple: "⚡ ADVANCED LOGGER v2.0.0 - Cyberpunk Console Experience ⚡",
729
+ style: "background: linear-gradient(135deg, #0f3460 0%, #e94560 100%); color: #00ffff; padding: 12px 20px; border-radius: 8px; font-weight: bold; text-shadow: 0 0 10px #00ffff;"
730
+ },
731
+ minimal: {
732
+ simple: "ADVANCED LOGGER v2.0.0 - Clean Console Styling",
733
+ style: "background: #f7fafc; color: #2d3748; padding: 8px 16px; border: 1px solid #e2e8f0; border-radius: 4px; font-weight: 500;"
734
+ },
735
+ light: {
736
+ simple: "☀️ ADVANCED LOGGER v2.0.0 - Bright Console Styling ☀️",
737
+ style: "background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); color: #495057; padding: 12px 20px; border-radius: 8px; font-weight: bold; border: 1px solid #dee2e6;"
738
+ },
739
+ cyberpunk: {
740
+ simple: "🤖 ADVANCED LOGGER v2.0.0 - Neural Console Interface 🤖",
741
+ style: "background: linear-gradient(135deg, #0d1b2a 0%, #415a77 100%); color: #00d4aa; padding: 12px 20px; border-radius: 8px; font-weight: bold; text-shadow: 0 0 10px #00d4aa; border: 1px solid #00d4aa;"
742
+ }
743
+ };
744
+ function detectBannerCapabilities() {
745
+ const userAgent = navigator.userAgent;
746
+ const isChrome = /Chrome/.test(userAgent);
747
+ const isFirefox = /Firefox/.test(userAgent);
748
+ const isSafari = /Safari/.test(userAgent) && !/Chrome/.test(userAgent);
749
+ const supportsSVG = !!document.createElementNS && !!document.createElementNS("http://www.w3.org/2000/svg", "svg").createSVGRect;
750
+ const supportsAnimations = typeof document !== "undefined" && "animationName" in document.createElement("div").style;
751
+ if (supportsAnimations && isChrome) {
752
+ return "animated";
753
+ } else if (supportsSVG && (isChrome || isFirefox)) {
754
+ return "svg";
755
+ } else if (isChrome || isFirefox) {
756
+ return "unicode";
757
+ } else if (isSafari) {
758
+ return "ascii";
759
+ }
760
+ return "simple";
761
+ }
762
+ function displayInitBanner(bannerType) {
763
+ const selectedType = bannerType || detectBannerCapabilities();
764
+ const banner = BANNER_VARIANTS[selectedType];
765
+ if (selectedType === "animated") {
766
+ const style = document.createElement("style");
767
+ style.textContent = `
768
+ @keyframes gradientShift {
769
+ 0% { background-position: 0% 50%; }
770
+ 50% { background-position: 100% 50%; }
771
+ 100% { background-position: 0% 50%; }
772
+ }
773
+ `;
774
+ document.head.appendChild(style);
775
+ }
776
+ console.log(`%c${banner.text}`, banner.style);
777
+ const features = [
778
+ "🎨 Advanced CSS Console Styling",
779
+ "📍 Automatic Stack Trace Parsing",
780
+ "🔧 Scoped Loggers & Prefixes",
781
+ "⚡ Performance Timers",
782
+ "🎯 Verbosity Filtering",
783
+ "🔌 Extensible Handlers",
784
+ "📱 Modern TypeScript Patterns",
785
+ "📤 Export & Clipboard Support"
786
+ ];
787
+ console.group(`%c✨ Features`, "background: #f8f9fa; color: #495057; padding: 4px 8px; border-radius: 4px; font-weight: bold;");
788
+ features.forEach((feature) => {
789
+ console.log(`%c${feature}`, "color: #6c757d; font-size: 13px;");
790
+ });
791
+ console.groupEnd();
792
+ console.log("");
793
+ }
794
+ class BaseStyler {
795
+ builder;
796
+ constructor(builder = new StyleBuilder()) {
797
+ this.builder = builder;
798
+ }
799
+ /**
800
+ * Primary brand color (typically blue)
801
+ */
802
+ primary() {
803
+ return this.color("#007bff");
804
+ }
805
+ /**
806
+ * Secondary color (typically gray)
807
+ */
808
+ secondary() {
809
+ return this.color("#6c757d");
810
+ }
811
+ /**
812
+ * Accent color for highlights
813
+ */
814
+ accent() {
815
+ return this.color("#17a2b8");
816
+ }
817
+ /**
818
+ * Muted/subtle color - automatically adaptive
819
+ */
820
+ muted() {
821
+ const mutedColors = { light: "#6c757d", dark: "#a0aec0" };
822
+ return this.color(getAdaptiveColor(mutedColors));
823
+ }
824
+ /**
825
+ * Success color (green)
826
+ */
827
+ success() {
828
+ return this.color("#28a745");
829
+ }
830
+ /**
831
+ * Warning color (yellow/orange)
832
+ */
833
+ warning() {
834
+ return this.color("#ffc107");
835
+ }
836
+ /**
837
+ * Danger/error color (red)
838
+ */
839
+ danger() {
840
+ return this.color("#dc3545");
841
+ }
842
+ /**
843
+ * Monospace font family
844
+ */
845
+ mono() {
846
+ this.builder.font('Monaco, Consolas, "Courier New", monospace');
847
+ return this;
848
+ }
849
+ /**
850
+ * System font family
851
+ */
852
+ system() {
853
+ this.builder.font('system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif');
854
+ return this;
855
+ }
856
+ /**
857
+ * Readable font optimized for text
858
+ */
859
+ readable() {
860
+ this.builder.font('Georgia, "Times New Roman", serif');
861
+ return this;
862
+ }
863
+ /**
864
+ * Compact spacing
865
+ */
866
+ compact() {
867
+ this.builder.padding("1px 4px").margin("0 1px");
868
+ return this;
869
+ }
870
+ /**
871
+ * Spacious layout
872
+ */
873
+ spacious() {
874
+ this.builder.padding("6px 12px").margin("2px 4px");
875
+ return this;
876
+ }
877
+ /**
878
+ * Inline display
879
+ */
880
+ inline() {
881
+ this.builder.display("inline-block");
882
+ return this;
883
+ }
884
+ /**
885
+ * Glass morphism effect
886
+ */
887
+ glassmorphic() {
888
+ this.builder.css("backdrop-filter", "blur(10px)").css("background", "rgba(255, 255, 255, 0.1)").border("1px solid rgba(255, 255, 255, 0.2)").rounded("8px");
889
+ return this;
890
+ }
891
+ /**
892
+ * Neon glow effect
893
+ */
894
+ neon() {
895
+ const neonColor = "#00ffff";
896
+ this.builder.color(neonColor).border(`1px solid ${neonColor}`).shadow(`0 0 10px ${neonColor}, 0 0 20px ${neonColor}`).css("text-shadow", `0 0 5px ${neonColor}`);
897
+ return this;
898
+ }
899
+ /**
900
+ * Gradient background
901
+ */
902
+ gradient(from = "#667eea", to = "#764ba2") {
903
+ this.builder.bg(`linear-gradient(135deg, ${from} 0%, ${to} 100%)`);
904
+ return this;
905
+ }
906
+ /**
907
+ * Bold text
908
+ */
909
+ bold() {
910
+ this.builder.bold();
911
+ return this;
912
+ }
913
+ /**
914
+ * Set color with automatic adaptation
915
+ */
916
+ color(color) {
917
+ this.builder.color(color);
918
+ return this;
919
+ }
920
+ /**
921
+ * Build the final CSS string
922
+ */
923
+ build() {
924
+ return this.builder.build();
925
+ }
926
+ }
927
+ class TimestampStyler extends BaseStyler {
928
+ /**
929
+ * Default timestamp style - subtle and informative
930
+ */
931
+ default() {
932
+ this.muted().mono();
933
+ this.builder.size("11px");
934
+ return this;
935
+ }
936
+ /**
937
+ * Hide timestamp
938
+ */
939
+ hidden() {
940
+ this.builder.display("none");
941
+ return this;
942
+ }
943
+ /**
944
+ * Minimal timestamp (just time, no date)
945
+ */
946
+ minimal() {
947
+ this.muted().mono();
948
+ this.builder.size("10px").opacity(0.7);
949
+ return this;
950
+ }
951
+ /**
952
+ * Set font size
953
+ */
954
+ size(size) {
955
+ this.builder.size(size);
956
+ return this;
957
+ }
958
+ }
959
+ class LevelStyler extends BaseStyler {
960
+ /**
961
+ * Colorful gradient badge
962
+ */
963
+ badge() {
964
+ this.builder.padding("2px 8px").rounded("4px").bold().color("#ffffff");
965
+ return this;
966
+ }
967
+ /**
968
+ * Glowing effect for dark themes
969
+ */
970
+ glowing() {
971
+ return this.neon().badge();
972
+ }
973
+ /**
974
+ * Minimal flat style
975
+ */
976
+ flat() {
977
+ this.builder.padding("1px 6px").rounded("2px").border("1px solid currentColor").css("background", "transparent");
978
+ return this;
979
+ }
980
+ /**
981
+ * Uppercase text
982
+ */
983
+ uppercase() {
984
+ this.builder.uppercase();
985
+ return this;
986
+ }
987
+ }
988
+ class PrefixStyler extends BaseStyler {
989
+ /**
990
+ * Dark theme prefix
991
+ */
992
+ dark() {
993
+ const prefixColors = { light: "#2d3748", dark: "#4a5568" };
994
+ const textColors = { light: "#e2e8f0", dark: "#f7fafc" };
995
+ this.builder.bg(getAdaptiveColor(prefixColors)).color(getAdaptiveColor(textColors)).padding("2px 6px").rounded("3px").bold().mono().size("11px");
996
+ return this;
997
+ }
998
+ /**
999
+ * Light theme prefix
1000
+ */
1001
+ light() {
1002
+ this.builder.bg("#f8f9fa").color("#495057").padding("2px 6px").rounded("3px").bold().mono().size("11px").border("1px solid #dee2e6");
1003
+ return this;
1004
+ }
1005
+ /**
1006
+ * Compact prefix
1007
+ */
1008
+ compact() {
1009
+ this.builder.padding("1px 4px").size("10px").rounded("2px");
1010
+ return this;
1011
+ }
1012
+ }
1013
+ class MessageStyler extends BaseStyler {
1014
+ /**
1015
+ * Readable message text - automatically adaptive
1016
+ */
1017
+ readable() {
1018
+ this.builder.color(getAdaptiveColor(ADAPTIVE_COLORS.messageText)).system().size("14px");
1019
+ return this;
1020
+ }
1021
+ /**
1022
+ * Code-style monospace text
1023
+ */
1024
+ code() {
1025
+ this.builder.mono().size("13px").color(getAdaptiveColor(ADAPTIVE_COLORS.messageText)).bg("rgba(0, 0, 0, 0.05)").padding("1px 4px").rounded("3px");
1026
+ return this;
1027
+ }
1028
+ /**
1029
+ * Large, prominent text
1030
+ */
1031
+ large() {
1032
+ this.builder.size("16px").color(getAdaptiveColor(ADAPTIVE_COLORS.messageText));
1033
+ return this;
1034
+ }
1035
+ }
1036
+ class LocationStyler extends BaseStyler {
1037
+ /**
1038
+ * Subtle location info - automatically adaptive
1039
+ */
1040
+ subtle() {
1041
+ this.builder.color(getAdaptiveColor(ADAPTIVE_COLORS.location)).mono().size("11px").opacity(0.7);
1042
+ return this;
1043
+ }
1044
+ /**
1045
+ * Hide location info
1046
+ */
1047
+ hidden() {
1048
+ this.builder.display("none");
1049
+ return this;
1050
+ }
1051
+ /**
1052
+ * Clickable style (for IDE integration)
1053
+ */
1054
+ clickable() {
1055
+ this.subtle();
1056
+ this.builder.css("text-decoration", "underline").cursor("pointer");
1057
+ return this;
1058
+ }
1059
+ }
1060
+ class LogStyleBuilder {
1061
+ logStyles = {};
1062
+ logger;
1063
+ constructor(logger) {
1064
+ this.logger = logger;
1065
+ }
1066
+ /**
1067
+ * Configure timestamp styling
1068
+ */
1069
+ timestamp() {
1070
+ return new TimestampStyleBuilderProxy(this);
1071
+ }
1072
+ /**
1073
+ * Configure level badge styling
1074
+ */
1075
+ level() {
1076
+ return new LevelStyleBuilderProxy(this);
1077
+ }
1078
+ /**
1079
+ * Configure prefix styling
1080
+ */
1081
+ prefix() {
1082
+ return new PrefixStyleBuilderProxy(this);
1083
+ }
1084
+ /**
1085
+ * Configure message text styling
1086
+ */
1087
+ message() {
1088
+ return new MessageStyleBuilderProxy(this);
1089
+ }
1090
+ /**
1091
+ * Configure location info styling
1092
+ */
1093
+ location() {
1094
+ return new LocationStyleBuilderProxy(this);
1095
+ }
1096
+ /**
1097
+ * Use a predefined preset
1098
+ */
1099
+ usePreset(presetName) {
1100
+ console.warn(`Preset '${presetName}' will be available in next implementation phase`);
1101
+ return this;
1102
+ }
1103
+ /**
1104
+ * Customize with partial configuration
1105
+ */
1106
+ customize(overrides) {
1107
+ this.logStyles = { ...this.logStyles, ...overrides };
1108
+ return this;
1109
+ }
1110
+ /**
1111
+ * Set layout spacing
1112
+ */
1113
+ spacing(type) {
1114
+ if (!this.logStyles.layout) {
1115
+ this.logStyles.layout = { spacing: type };
1116
+ } else {
1117
+ this.logStyles.layout.spacing = type;
1118
+ }
1119
+ switch (type) {
1120
+ case "compact":
1121
+ this.logStyles.layout.innerPadding = "1px";
1122
+ this.logStyles.layout.outerMargin = "0px";
1123
+ break;
1124
+ case "spacious":
1125
+ this.logStyles.layout.innerPadding = "4px";
1126
+ this.logStyles.layout.outerMargin = "2px";
1127
+ break;
1128
+ default:
1129
+ this.logStyles.layout.innerPadding = "2px";
1130
+ this.logStyles.layout.outerMargin = "1px";
1131
+ }
1132
+ return this;
1133
+ }
1134
+ /**
1135
+ * Set backdrop filter for glassmorphism effects
1136
+ */
1137
+ backdrop(filter) {
1138
+ this.logStyles.backdrop = filter;
1139
+ return this;
1140
+ }
1141
+ /**
1142
+ * Set overall transparency
1143
+ */
1144
+ transparency(value) {
1145
+ this.logStyles.transparency = Math.max(0, Math.min(1, value));
1146
+ return this;
1147
+ }
1148
+ /**
1149
+ * Apply the configured styles to the logger
1150
+ */
1151
+ apply() {
1152
+ this.logger._customLogStyles = this.logStyles;
1153
+ console.log("Applied log styles:", this.logStyles);
1154
+ }
1155
+ /**
1156
+ * Get current configuration (for debugging)
1157
+ */
1158
+ getConfig() {
1159
+ return { ...this.logStyles };
1160
+ }
1161
+ /**
1162
+ * Internal method to update part configuration
1163
+ */
1164
+ _updatePartConfig(part, styles) {
1165
+ if (part === "layout" || part === "backdrop" || part === "transparency") {
1166
+ return;
1167
+ }
1168
+ if (!this.logStyles[part]) {
1169
+ this.logStyles[part] = {};
1170
+ }
1171
+ this.logStyles[part].style = styles;
1172
+ }
1173
+ }
1174
+ class PartStyleBuilderProxy {
1175
+ parentBuilder;
1176
+ partName;
1177
+ constructor(parentBuilder, partName) {
1178
+ this.parentBuilder = parentBuilder;
1179
+ this.partName = partName;
1180
+ }
1181
+ /**
1182
+ * Return to the main builder for chaining other parts
1183
+ */
1184
+ and() {
1185
+ return this.parentBuilder;
1186
+ }
1187
+ /**
1188
+ * Apply styles and finish configuration
1189
+ */
1190
+ apply() {
1191
+ this.parentBuilder.apply();
1192
+ }
1193
+ /**
1194
+ * Helper to apply styles to the parent builder
1195
+ */
1196
+ applyStyles(styler) {
1197
+ const styles = styler.build();
1198
+ this.parentBuilder._updatePartConfig(this.partName, styles);
1199
+ return this;
1200
+ }
1201
+ }
1202
+ class TimestampStyleBuilderProxy extends PartStyleBuilderProxy {
1203
+ constructor(parentBuilder) {
1204
+ super(parentBuilder, "timestamp");
1205
+ }
1206
+ default() {
1207
+ return this.applyStyles(new TimestampStyler().default());
1208
+ }
1209
+ hidden() {
1210
+ return this.applyStyles(new TimestampStyler().hidden());
1211
+ }
1212
+ minimal() {
1213
+ return this.applyStyles(new TimestampStyler().minimal());
1214
+ }
1215
+ muted() {
1216
+ return this.applyStyles(new TimestampStyler().muted());
1217
+ }
1218
+ mono() {
1219
+ return this.applyStyles(new TimestampStyler().mono());
1220
+ }
1221
+ compact() {
1222
+ return this.applyStyles(new TimestampStyler().compact());
1223
+ }
1224
+ }
1225
+ class LevelStyleBuilderProxy extends PartStyleBuilderProxy {
1226
+ constructor(parentBuilder) {
1227
+ super(parentBuilder, "level");
1228
+ }
1229
+ badge() {
1230
+ return this.applyStyles(new LevelStyler().badge());
1231
+ }
1232
+ gradient(from, to) {
1233
+ return this.applyStyles(new LevelStyler().gradient(from, to));
1234
+ }
1235
+ glowing() {
1236
+ return this.applyStyles(new LevelStyler().glowing());
1237
+ }
1238
+ flat() {
1239
+ return this.applyStyles(new LevelStyler().flat());
1240
+ }
1241
+ bold() {
1242
+ return this.applyStyles(new LevelStyler().bold());
1243
+ }
1244
+ uppercase() {
1245
+ return this.applyStyles(new LevelStyler().uppercase());
1246
+ }
1247
+ neon() {
1248
+ return this.applyStyles(new LevelStyler().neon());
1249
+ }
1250
+ }
1251
+ class PrefixStyleBuilderProxy extends PartStyleBuilderProxy {
1252
+ constructor(parentBuilder) {
1253
+ super(parentBuilder, "prefix");
1254
+ }
1255
+ dark() {
1256
+ return this.applyStyles(new PrefixStyler().dark());
1257
+ }
1258
+ light() {
1259
+ return this.applyStyles(new PrefixStyler().light());
1260
+ }
1261
+ compact() {
1262
+ return this.applyStyles(new PrefixStyler().compact());
1263
+ }
1264
+ muted() {
1265
+ return this.applyStyles(new PrefixStyler().muted());
1266
+ }
1267
+ mono() {
1268
+ return this.applyStyles(new PrefixStyler().mono());
1269
+ }
1270
+ }
1271
+ class MessageStyleBuilderProxy extends PartStyleBuilderProxy {
1272
+ constructor(parentBuilder) {
1273
+ super(parentBuilder, "message");
1274
+ }
1275
+ readable() {
1276
+ return this.applyStyles(new MessageStyler().readable());
1277
+ }
1278
+ code() {
1279
+ return this.applyStyles(new MessageStyler().code());
1280
+ }
1281
+ large() {
1282
+ return this.applyStyles(new MessageStyler().large());
1283
+ }
1284
+ system() {
1285
+ return this.applyStyles(new MessageStyler().system());
1286
+ }
1287
+ mono() {
1288
+ return this.applyStyles(new MessageStyler().mono());
1289
+ }
1290
+ }
1291
+ class LocationStyleBuilderProxy extends PartStyleBuilderProxy {
1292
+ constructor(parentBuilder) {
1293
+ super(parentBuilder, "location");
1294
+ }
1295
+ subtle() {
1296
+ return this.applyStyles(new LocationStyler().subtle());
1297
+ }
1298
+ hidden() {
1299
+ return this.applyStyles(new LocationStyler().hidden());
1300
+ }
1301
+ clickable() {
1302
+ return this.applyStyles(new LocationStyler().clickable());
1303
+ }
1304
+ muted() {
1305
+ return this.applyStyles(new LocationStyler().muted());
1306
+ }
1307
+ mono() {
1308
+ return this.applyStyles(new LocationStyler().mono());
1309
+ }
1310
+ }
1311
+ function createLogStyleBuilder(logger) {
1312
+ return new LogStyleBuilder(logger);
1313
+ }
1314
+ const SMART_PRESETS = {
1315
+ /**
1316
+ * Default preset - works perfectly out-of-the-box
1317
+ * Clean, readable, automatically adaptive to dark/light themes
1318
+ */
1319
+ default: {
1320
+ layout: {
1321
+ spacing: "normal",
1322
+ innerPadding: "2px",
1323
+ outerMargin: "1px"
1324
+ },
1325
+ timestamp: {
1326
+ show: true,
1327
+ color: "auto",
1328
+ // Automatically adaptive
1329
+ font: "Monaco, Consolas, monospace",
1330
+ size: "11px"
1331
+ },
1332
+ level: {
1333
+ show: true,
1334
+ style: "badge",
1335
+ uppercase: false,
1336
+ padding: "2px 8px"
1337
+ },
1338
+ prefix: {
1339
+ show: true,
1340
+ style: "dark",
1341
+ // Automatically adaptive
1342
+ padding: "2px 6px"
1343
+ },
1344
+ message: {
1345
+ show: true,
1346
+ color: "auto",
1347
+ // Automatically adaptive
1348
+ font: "system-ui, -apple-system, sans-serif",
1349
+ size: "14px"
1350
+ },
1351
+ location: {
1352
+ show: true,
1353
+ color: "auto",
1354
+ // Automatically adaptive
1355
+ font: "Monaco, Consolas, monospace",
1356
+ size: "11px"
1357
+ }
1358
+ },
1359
+ /**
1360
+ * Cyberpunk preset - neon colors, glowing effects, dark theme
1361
+ */
1362
+ cyberpunk: {
1363
+ layout: {
1364
+ spacing: "compact",
1365
+ innerPadding: "1px",
1366
+ outerMargin: "0px"
1367
+ },
1368
+ timestamp: {
1369
+ show: true,
1370
+ color: "#00ffff",
1371
+ font: "Monaco, Consolas, monospace",
1372
+ size: "10px",
1373
+ style: "neon"
1374
+ },
1375
+ level: {
1376
+ show: true,
1377
+ style: "glowing",
1378
+ uppercase: true,
1379
+ padding: "2px 8px"
1380
+ },
1381
+ prefix: {
1382
+ show: true,
1383
+ color: "#ff0080",
1384
+ background: "rgba(255, 0, 128, 0.1)",
1385
+ border: "1px solid #ff0080",
1386
+ style: "neon"
1387
+ },
1388
+ message: {
1389
+ show: true,
1390
+ color: "#00ff41",
1391
+ font: "Monaco, Consolas, monospace",
1392
+ size: "13px"
1393
+ },
1394
+ location: {
1395
+ show: false
1396
+ // Hidden for cleaner look
1397
+ },
1398
+ backdrop: "blur(2px)",
1399
+ transparency: 0.9
1400
+ },
1401
+ /**
1402
+ * Glassmorphism preset - modern blur effects, transparency
1403
+ */
1404
+ glassmorphism: {
1405
+ layout: {
1406
+ spacing: "spacious",
1407
+ innerPadding: "4px",
1408
+ outerMargin: "2px"
1409
+ },
1410
+ timestamp: {
1411
+ show: true,
1412
+ color: "auto",
1413
+ font: "system-ui, sans-serif",
1414
+ size: "11px",
1415
+ style: "glassmorphic"
1416
+ },
1417
+ level: {
1418
+ show: true,
1419
+ style: "glassmorphic",
1420
+ uppercase: false,
1421
+ padding: "4px 12px"
1422
+ },
1423
+ prefix: {
1424
+ show: true,
1425
+ style: "glassmorphic",
1426
+ padding: "3px 8px"
1427
+ },
1428
+ message: {
1429
+ show: true,
1430
+ color: "auto",
1431
+ font: "system-ui, sans-serif",
1432
+ size: "14px"
1433
+ },
1434
+ location: {
1435
+ show: true,
1436
+ color: "auto",
1437
+ font: "system-ui, sans-serif",
1438
+ size: "11px",
1439
+ style: "glassmorphic"
1440
+ },
1441
+ backdrop: "blur(10px)",
1442
+ transparency: 0.8
1443
+ },
1444
+ /**
1445
+ * Minimal preset - clean, no decorations, maximum readability
1446
+ */
1447
+ minimal: {
1448
+ layout: {
1449
+ spacing: "compact",
1450
+ innerPadding: "0px",
1451
+ outerMargin: "0px"
1452
+ },
1453
+ timestamp: {
1454
+ show: false
1455
+ // Hidden for minimal look
1456
+ },
1457
+ level: {
1458
+ show: true,
1459
+ style: "flat",
1460
+ uppercase: true,
1461
+ padding: "0px 4px",
1462
+ border: "none",
1463
+ background: "transparent"
1464
+ },
1465
+ prefix: {
1466
+ show: true,
1467
+ style: "flat",
1468
+ padding: "0px 4px",
1469
+ border: "none",
1470
+ background: "transparent"
1471
+ },
1472
+ message: {
1473
+ show: true,
1474
+ color: "auto",
1475
+ font: "system-ui, sans-serif",
1476
+ size: "14px"
1477
+ },
1478
+ location: {
1479
+ show: false
1480
+ // Hidden for minimal look
1481
+ }
1482
+ },
1483
+ /**
1484
+ * Debug preset - monospace, detailed, compact for development
1485
+ */
1486
+ debug: {
1487
+ layout: {
1488
+ spacing: "compact",
1489
+ innerPadding: "1px",
1490
+ outerMargin: "0px"
1491
+ },
1492
+ timestamp: {
1493
+ show: true,
1494
+ color: "auto",
1495
+ font: "Monaco, Consolas, monospace",
1496
+ size: "10px"
1497
+ },
1498
+ level: {
1499
+ show: true,
1500
+ style: "compact",
1501
+ uppercase: true,
1502
+ padding: "1px 4px",
1503
+ font: "Monaco, Consolas, monospace",
1504
+ size: "10px"
1505
+ },
1506
+ prefix: {
1507
+ show: true,
1508
+ style: "compact",
1509
+ padding: "1px 4px",
1510
+ font: "Monaco, Consolas, monospace",
1511
+ size: "10px"
1512
+ },
1513
+ message: {
1514
+ show: true,
1515
+ color: "auto",
1516
+ font: "Monaco, Consolas, monospace",
1517
+ size: "12px"
1518
+ },
1519
+ location: {
1520
+ show: true,
1521
+ color: "auto",
1522
+ font: "Monaco, Consolas, monospace",
1523
+ size: "10px",
1524
+ style: "clickable"
1525
+ }
1526
+ },
1527
+ /**
1528
+ * Production preset - clean, essential info only
1529
+ */
1530
+ production: {
1531
+ layout: {
1532
+ spacing: "normal",
1533
+ innerPadding: "2px",
1534
+ outerMargin: "1px"
1535
+ },
1536
+ timestamp: {
1537
+ show: true,
1538
+ color: "auto",
1539
+ font: "system-ui, sans-serif",
1540
+ size: "11px"
1541
+ },
1542
+ level: {
1543
+ show: true,
1544
+ style: "badge",
1545
+ uppercase: false,
1546
+ padding: "2px 6px"
1547
+ },
1548
+ prefix: {
1549
+ show: false
1550
+ // Hidden in production
1551
+ },
1552
+ message: {
1553
+ show: true,
1554
+ color: "auto",
1555
+ font: "system-ui, sans-serif",
1556
+ size: "14px"
1557
+ },
1558
+ location: {
1559
+ show: false
1560
+ // Hidden in production
1561
+ }
1562
+ }
1563
+ };
1564
+ function getSmartPreset(name) {
1565
+ return SMART_PRESETS[name] || null;
1566
+ }
1567
+ function getAvailablePresets() {
1568
+ return Object.keys(SMART_PRESETS);
1569
+ }
1570
+ function hasPreset(name) {
1571
+ return name in SMART_PRESETS;
1572
+ }
1573
+ class ScopedLogger {
1574
+ parent;
1575
+ scopeName;
1576
+ badgeList = [];
1577
+ contextStack = [];
1578
+ _timers;
1579
+ constructor(parent, scopeName) {
1580
+ this.parent = parent;
1581
+ this.scopeName = scopeName;
1582
+ }
1583
+ get timers() {
1584
+ if (!this._timers) this._timers = /* @__PURE__ */ new Map();
1585
+ return this._timers;
1586
+ }
1587
+ getBindings() {
1588
+ return {
1589
+ scope: this.getScopePrefix(),
1590
+ badges: this.badgeList.length > 0 ? [...this.badgeList] : void 0
1591
+ };
1592
+ }
1593
+ getScopePrefix() {
1594
+ if (this.contextStack.length === 0) return this.scopeName;
1595
+ return [this.scopeName, ...this.contextStack].join(":");
1596
+ }
1597
+ badges(badges) {
1598
+ this.badgeList = [...badges];
1599
+ return this;
1600
+ }
1601
+ badge(badge) {
1602
+ if (!this.badgeList.includes(badge)) {
1603
+ this.badgeList.push(badge);
1604
+ }
1605
+ return this;
1606
+ }
1607
+ clearBadges() {
1608
+ this.badgeList = [];
1609
+ return this;
1610
+ }
1611
+ style(presetName) {
1612
+ this.parent.setTheme(presetName);
1613
+ return this;
1614
+ }
1615
+ context(contextName) {
1616
+ return new ContextLogger(this, contextName);
1617
+ }
1618
+ time(label) {
1619
+ this.timers.set(label, {
1620
+ label: `${this.scopeName}:${label}`,
1621
+ startTime: performance.now()
1622
+ });
1623
+ }
1624
+ timeEnd(label) {
1625
+ const timer = this.timers.get(label);
1626
+ if (!timer) {
1627
+ this.warn(`Timer '${label}' not found`);
1628
+ return void 0;
1629
+ }
1630
+ const elapsed = performance.now() - timer.startTime;
1631
+ this.timers.delete(label);
1632
+ this.success(`Timer: ${label} - ${elapsed.toFixed(2)}ms`);
1633
+ return elapsed;
1634
+ }
1635
+ debug(...args) {
1636
+ this.parent.logWithBindings(this.getBindings(), "debug", ...args);
1637
+ }
1638
+ info(...args) {
1639
+ this.parent.logWithBindings(this.getBindings(), "info", ...args);
1640
+ }
1641
+ warn(...args) {
1642
+ this.parent.logWithBindings(this.getBindings(), "warn", ...args);
1643
+ }
1644
+ error(...args) {
1645
+ this.parent.logWithBindings(this.getBindings(), "error", ...args);
1646
+ }
1647
+ success(...args) {
1648
+ const bindings = this.getBindings();
1649
+ this.parent.logWithBindings(bindings, "info", ...args);
1650
+ }
1651
+ critical(...args) {
1652
+ this.parent.logWithBindings(this.getBindings(), "critical", ...args);
1653
+ }
1654
+ trace(...args) {
1655
+ this.parent.logWithBindings(this.getBindings(), "debug", ...args);
1656
+ console.trace(`[${this.scopeName}]`);
1657
+ }
1658
+ _pushContext(context) {
1659
+ this.contextStack.push(context);
1660
+ }
1661
+ _popContext() {
1662
+ this.contextStack.pop();
1663
+ }
1664
+ }
1665
+ class APILogger extends ScopedLogger {
1666
+ constructor(parent, apiName) {
1667
+ super(parent, `API:${apiName}`);
1668
+ this.badge("API");
1669
+ }
1670
+ slow(message, duration) {
1671
+ this.badge("SLOW");
1672
+ const msg = duration ? `${message} (${duration}ms)` : message;
1673
+ this.warn(msg);
1674
+ }
1675
+ rateLimit(message) {
1676
+ this.badge("RATE_LIMIT");
1677
+ this.warn(message);
1678
+ }
1679
+ auth(message) {
1680
+ this.badge("AUTH");
1681
+ this.error(message);
1682
+ }
1683
+ deprecated(message) {
1684
+ this.badge("DEPRECATED");
1685
+ this.warn(message);
1686
+ }
1687
+ }
1688
+ class ComponentLogger extends ScopedLogger {
1689
+ constructor(parent, componentName) {
1690
+ super(parent, componentName);
1691
+ this.badge("COMPONENT");
1692
+ }
1693
+ lifecycle(event, message) {
1694
+ this.badge("LIFECYCLE");
1695
+ const msg = message ? `${event}: ${message}` : event;
1696
+ this.info(msg);
1697
+ }
1698
+ stateChange(from, to, data) {
1699
+ this.badge("STATE");
1700
+ const msg = `${from} → ${to}`;
1701
+ if (data) {
1702
+ this.info(msg, data);
1703
+ } else {
1704
+ this.info(msg);
1705
+ }
1706
+ }
1707
+ propsChange(changes) {
1708
+ this.badge("PROPS");
1709
+ this.debug("Props changed:", changes);
1710
+ }
1711
+ }
1712
+ class ContextLogger {
1713
+ parentLogger;
1714
+ contextName;
1715
+ constructor(parentLogger, contextName) {
1716
+ this.parentLogger = parentLogger;
1717
+ this.contextName = contextName;
1718
+ }
1719
+ run(fn) {
1720
+ this.parentLogger._pushContext(this.contextName);
1721
+ try {
1722
+ return fn();
1723
+ } finally {
1724
+ this.parentLogger._popContext();
1725
+ }
1726
+ }
1727
+ async runAsync(fn) {
1728
+ this.parentLogger._pushContext(this.contextName);
1729
+ try {
1730
+ return await fn();
1731
+ } finally {
1732
+ this.parentLogger._popContext();
1733
+ }
1734
+ }
1735
+ start() {
1736
+ this.parentLogger._pushContext(this.contextName);
1737
+ }
1738
+ end() {
1739
+ this.parentLogger._popContext();
1740
+ }
1741
+ debug(...args) {
1742
+ this.parentLogger.debug(...args);
1743
+ }
1744
+ info(...args) {
1745
+ this.parentLogger.info(...args);
1746
+ }
1747
+ warn(...args) {
1748
+ this.parentLogger.warn(...args);
1749
+ }
1750
+ error(...args) {
1751
+ this.parentLogger.error(...args);
1752
+ }
1753
+ success(...args) {
1754
+ this.parentLogger.success(...args);
1755
+ }
1756
+ critical(...args) {
1757
+ this.parentLogger.critical(...args);
1758
+ }
1759
+ }
1760
+ class ExportLogHandler {
1761
+ buffer = [];
1762
+ maxSize;
1763
+ groupDepth = 0;
1764
+ currentGroup;
1765
+ constructor(maxSize = BUFFER_LIMITS.DEFAULT_SIZE) {
1766
+ this.maxSize = Math.min(Math.max(maxSize, BUFFER_LIMITS.MIN_SIZE), BUFFER_LIMITS.MAX_SIZE);
1767
+ }
1768
+ /**
1769
+ * Handle incoming log and store in buffer
1770
+ */
1771
+ handle(level, message, args, metadata) {
1772
+ const entry = {
1773
+ id: generateLogId(),
1774
+ timestamp: metadata.timestamp,
1775
+ level,
1776
+ prefix: metadata.prefix,
1777
+ message,
1778
+ args,
1779
+ location: metadata.stackInfo,
1780
+ groupInfo: this.groupDepth > 0 ? {
1781
+ depth: this.groupDepth,
1782
+ groupName: this.currentGroup
1783
+ } : void 0
1784
+ };
1785
+ this.buffer.push(entry);
1786
+ if (this.buffer.length > this.maxSize) {
1787
+ this.buffer.shift();
1788
+ }
1789
+ }
1790
+ /**
1791
+ * Set group tracking for nested logs
1792
+ */
1793
+ setGroupInfo(depth, groupName) {
1794
+ this.groupDepth = depth;
1795
+ this.currentGroup = groupName;
1796
+ }
1797
+ /**
1798
+ * Get buffer statistics
1799
+ */
1800
+ getBufferStats() {
1801
+ const levelCounts = this.buffer.reduce((acc, entry) => {
1802
+ const currentCount = acc[entry.level] ? acc[entry.level] : 0;
1803
+ acc[entry.level] = currentCount + 1;
1804
+ return acc;
1805
+ }, {});
1806
+ let oldestLog;
1807
+ let newestLog;
1808
+ if (this.buffer.length > 0) {
1809
+ const firstEntry = this.buffer[0];
1810
+ const lastEntry = this.buffer[this.buffer.length - 1];
1811
+ if (firstEntry && firstEntry.timestamp) {
1812
+ oldestLog = new Date(firstEntry.timestamp);
1813
+ }
1814
+ if (lastEntry && lastEntry.timestamp) {
1815
+ newestLog = new Date(lastEntry.timestamp);
1816
+ }
1817
+ }
1818
+ return {
1819
+ size: this.buffer.length,
1820
+ maxSize: this.maxSize,
1821
+ usage: this.buffer.length / this.maxSize * 100,
1822
+ oldestLog,
1823
+ newestLog,
1824
+ levelCounts: {
1825
+ debug: levelCounts.debug ? levelCounts.debug : 0,
1826
+ info: levelCounts.info ? levelCounts.info : 0,
1827
+ warn: levelCounts.warn ? levelCounts.warn : 0,
1828
+ error: levelCounts.error ? levelCounts.error : 0,
1829
+ critical: levelCounts.critical ? levelCounts.critical : 0
1830
+ }
1831
+ };
1832
+ }
1833
+ /**
1834
+ * Clear the buffer
1835
+ */
1836
+ clearBuffer() {
1837
+ this.buffer = [];
1838
+ }
1839
+ /**
1840
+ * Set buffer size (with limits)
1841
+ */
1842
+ setBufferSize(size) {
1843
+ this.maxSize = Math.min(Math.max(size, BUFFER_LIMITS.MIN_SIZE), BUFFER_LIMITS.MAX_SIZE);
1844
+ if (this.buffer.length > this.maxSize) {
1845
+ this.buffer = this.buffer.slice(-this.maxSize);
1846
+ }
1847
+ }
1848
+ /**
1849
+ * Filter logs based on criteria
1850
+ */
1851
+ filterLogs(filters = {}) {
1852
+ let filtered = [...this.buffer];
1853
+ if (filters.levels?.length) {
1854
+ filtered = filtered.filter((entry) => filters.levels.includes(entry.level));
1855
+ }
1856
+ if (filters.prefixes?.length) {
1857
+ filtered = filtered.filter(
1858
+ (entry) => entry.prefix && filters.prefixes.includes(entry.prefix)
1859
+ );
1860
+ }
1861
+ if (filters.excludePrefixes?.length) {
1862
+ filtered = filtered.filter(
1863
+ (entry) => !entry.prefix || !filters.excludePrefixes.includes(entry.prefix)
1864
+ );
1865
+ }
1866
+ if (filters.since) {
1867
+ const sinceDate = parseTimeInput(filters.since);
1868
+ filtered = filtered.filter((entry) => new Date(entry.timestamp) >= sinceDate);
1869
+ }
1870
+ if (filters.until) {
1871
+ const untilDate = parseTimeInput(filters.until);
1872
+ filtered = filtered.filter((entry) => new Date(entry.timestamp) <= untilDate);
1873
+ }
1874
+ if (filters.withStackTrace) {
1875
+ filtered = filtered.filter((entry) => entry.location);
1876
+ }
1877
+ if (filters.errorsOnly) {
1878
+ filtered = filtered.filter((entry) => entry.level === "error" || entry.level === "critical");
1879
+ }
1880
+ if (filters.search) {
1881
+ const searchTerm = filters.search.toLowerCase();
1882
+ filtered = filtered.filter(
1883
+ (entry) => entry.message.toLowerCase().includes(searchTerm) || entry.args.some(
1884
+ (arg) => String(arg).toLowerCase().includes(searchTerm)
1885
+ )
1886
+ );
1887
+ }
1888
+ if (filters.last) {
1889
+ filtered = filtered.slice(-filters.last);
1890
+ }
1891
+ if (filters.first) {
1892
+ filtered = filtered.slice(0, filters.first);
1893
+ }
1894
+ return filtered;
1895
+ }
1896
+ /**
1897
+ * Export logs in JSON format
1898
+ */
1899
+ exportJSON(logs, options) {
1900
+ const data = logs.map((entry) => ({
1901
+ timestamp: entry.timestamp,
1902
+ level: entry.level,
1903
+ prefix: entry.prefix,
1904
+ message: entry.message,
1905
+ ...options.minimal ? {} : {
1906
+ args: entry.args.slice(1),
1907
+ location: entry.location,
1908
+ groupInfo: entry.groupInfo
1909
+ }
1910
+ }));
1911
+ return options.compact ? JSON.stringify(data) : JSON.stringify(data, null, 2);
1912
+ }
1913
+ /**
1914
+ * Export logs in CSV format
1915
+ */
1916
+ exportCSV(logs, options) {
1917
+ const headers = options.minimal ? ["Timestamp", "Level", "Prefix", "Message"] : ["Timestamp", "Level", "Prefix", "Message", "File", "Line", "Args"];
1918
+ const rows = logs.map((entry) => {
1919
+ const baseRow = [
1920
+ formatDisplayTime(new Date(entry.timestamp), "full"),
1921
+ entry.level.toUpperCase(),
1922
+ entry.prefix || "",
1923
+ `"${entry.message.replace(/"/g, '""')}"`
1924
+ ];
1925
+ if (!options.minimal) {
1926
+ baseRow.push(
1927
+ entry.location?.file || "",
1928
+ entry.location?.line?.toString() || "",
1929
+ `"${safeStringify(entry.args.slice(1)).replace(/"/g, '""')}"`
1930
+ );
1931
+ }
1932
+ return baseRow;
1933
+ });
1934
+ return [headers.join(","), ...rows.map((row) => row.join(","))].join("\n");
1935
+ }
1936
+ /**
1937
+ * Export logs in Markdown format
1938
+ */
1939
+ exportMarkdown(logs, options) {
1940
+ const now = /* @__PURE__ */ new Date();
1941
+ let content = `# Log Export - ${formatDisplayTime(now, "full")}
1942
+
1943
+ `;
1944
+ if (!options.minimal) {
1945
+ const summary = this.getBufferStats();
1946
+ content += `## Summary
1947
+ `;
1948
+ content += `- **Total logs**: ${logs.length}
1949
+ `;
1950
+ content += `- **Errors**: ${summary.levelCounts.error + summary.levelCounts.critical}
1951
+ `;
1952
+ content += `- **Warnings**: ${summary.levelCounts.warn}
1953
+
1954
+ `;
1955
+ }
1956
+ if (options.groupBy === "level") {
1957
+ const grouped = logs.reduce((acc, entry) => {
1958
+ const level = entry.level;
1959
+ if (!acc[level]) {
1960
+ acc[level] = [];
1961
+ }
1962
+ const levelArray = acc[level];
1963
+ if (levelArray) {
1964
+ levelArray.push(entry);
1965
+ }
1966
+ return acc;
1967
+ }, {});
1968
+ Object.entries(grouped).forEach(([level, entries]) => {
1969
+ const emoji = this.getLevelEmoji(level);
1970
+ content += `## ${emoji} ${level.toUpperCase()} (${entries.length})
1971
+
1972
+ `;
1973
+ entries.forEach((entry) => {
1974
+ const time = formatDisplayTime(new Date(entry.timestamp), "time-only");
1975
+ const location = entry.location ? ` (${entry.location.file}:${entry.location.line})` : "";
1976
+ const prefix = entry.prefix ? ` **${entry.prefix}**:` : "";
1977
+ content += `- \`${time}\`${prefix} ${entry.message}${location}
1978
+ `;
1979
+ });
1980
+ content += "\n";
1981
+ });
1982
+ } else {
1983
+ content += "## Logs\n\n";
1984
+ logs.forEach((entry) => {
1985
+ const time = formatDisplayTime(new Date(entry.timestamp), "time-only");
1986
+ const emoji = this.getLevelEmoji(entry.level);
1987
+ const location = entry.location ? ` (${entry.location.file}:${entry.location.line})` : "";
1988
+ const prefix = entry.prefix ? ` **${entry.prefix}**:` : "";
1989
+ content += `- \`${time}\` ${emoji}${prefix} ${entry.message}${location}
1990
+ `;
1991
+ });
1992
+ }
1993
+ return content;
1994
+ }
1995
+ /**
1996
+ * Export logs in plain text format
1997
+ */
1998
+ exportPlain(logs, options) {
1999
+ return logs.map((entry) => {
2000
+ const time = formatDisplayTime(new Date(entry.timestamp), options.minimal ? "time-only" : "short");
2001
+ const level = entry.level.toUpperCase().padEnd(8);
2002
+ const prefix = entry.prefix ? `[${entry.prefix}] ` : "";
2003
+ const location = !options.minimal && entry.location ? ` (${entry.location.file}:${entry.location.line})` : "";
2004
+ return `${time} ${level} ${prefix}${entry.message}${location}`;
2005
+ }).join("\n");
2006
+ }
2007
+ /**
2008
+ * Export logs in HTML format
2009
+ */
2010
+ exportHTML(logs, _options) {
2011
+ const title = `Log Export - ${formatDisplayTime(/* @__PURE__ */ new Date(), "full")}`;
2012
+ let html = `<!DOCTYPE html>
2013
+ <html lang="en">
2014
+ <head>
2015
+ <meta charset="UTF-8">
2016
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
2017
+ <title>${title}</title>
2018
+ <style>
2019
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 20px; line-height: 1.6; }
2020
+ .header { border-bottom: 2px solid #ddd; padding-bottom: 20px; margin-bottom: 20px; }
2021
+ .log-entry { margin: 5px 0; padding: 8px; border-radius: 4px; font-family: 'Monaco', 'Consolas', monospace; }
2022
+ .timestamp { color: #666; font-size: 0.9em; }
2023
+ .level { font-weight: bold; padding: 2px 6px; border-radius: 3px; margin: 0 8px; }
2024
+ .prefix { background: #2d3748; color: #e2e8f0; padding: 2px 6px; border-radius: 3px; margin: 0 8px; }
2025
+ .location { color: #718096; font-size: 0.9em; }
2026
+ .debug { background: #f0f4ff; }
2027
+ .info { background: #f0f9ff; }
2028
+ .warn { background: #fffbeb; }
2029
+ .error { background: #fef2f2; }
2030
+ .critical { background: #fef2f2; border-left: 4px solid #dc2626; }
2031
+ .level.debug { background: #667eea; color: white; }
2032
+ .level.info { background: #74b9ff; color: white; }
2033
+ .level.warn { background: #fdcb6e; color: #2d3436; }
2034
+ .level.error { background: #e84393; color: white; }
2035
+ .level.critical { background: #ff3838; color: white; }
2036
+ </style>
2037
+ </head>
2038
+ <body>
2039
+ <div class="header">
2040
+ <h1>${title}</h1>
2041
+ <p>Generated by Advanced Logger v2.0.0</p>
2042
+ </div>
2043
+ <div class="logs">`;
2044
+ logs.forEach((entry) => {
2045
+ const time = formatDisplayTime(new Date(entry.timestamp), "full");
2046
+ const location = entry.location ? ` <span class="location">(${escapeHtml(entry.location.file)}:${entry.location.line})</span>` : "";
2047
+ const prefix = entry.prefix ? ` <span class="prefix">${escapeHtml(entry.prefix)}</span>` : "";
2048
+ html += `
2049
+ <div class="log-entry ${entry.level}">
2050
+ <span class="timestamp">${time}</span>
2051
+ <span class="level ${entry.level}">${entry.level.toUpperCase()}</span>
2052
+ ${prefix}
2053
+ <span class="message">${escapeHtml(entry.message)}</span>
2054
+ ${location}
2055
+ </div>`;
2056
+ });
2057
+ html += `
2058
+ </div>
2059
+ </body>
2060
+ </html>`;
2061
+ return html;
2062
+ }
2063
+ /**
2064
+ * Get emoji for log level
2065
+ */
2066
+ getLevelEmoji(level) {
2067
+ const emojis = {
2068
+ debug: "🐞",
2069
+ info: "ℹ️",
2070
+ warn: "⚠️",
2071
+ error: "❌",
2072
+ critical: "🔥"
2073
+ };
2074
+ return emojis[level] || "";
2075
+ }
2076
+ /**
2077
+ * Main export function
2078
+ */
2079
+ export(format, filters = {}, options = {}) {
2080
+ const filteredLogs = this.filterLogs(filters);
2081
+ let data;
2082
+ switch (format) {
2083
+ case "json":
2084
+ data = this.exportJSON(filteredLogs, options);
2085
+ break;
2086
+ case "csv":
2087
+ data = this.exportCSV(filteredLogs, options);
2088
+ break;
2089
+ case "markdown":
2090
+ data = this.exportMarkdown(filteredLogs, options);
2091
+ break;
2092
+ case "plain":
2093
+ data = this.exportPlain(filteredLogs, options);
2094
+ break;
2095
+ case "html":
2096
+ data = this.exportHTML(filteredLogs, options);
2097
+ break;
2098
+ default:
2099
+ throw new Error(`Unsupported export format: ${format}`);
2100
+ }
2101
+ return {
2102
+ format,
2103
+ data,
2104
+ metadata: {
2105
+ totalLogs: this.buffer.length,
2106
+ filteredLogs: filteredLogs.length,
2107
+ exportedAt: (/* @__PURE__ */ new Date()).toISOString(),
2108
+ filters,
2109
+ options
2110
+ }
2111
+ };
2112
+ }
2113
+ /**
2114
+ * Copy to clipboard with fallback
2115
+ */
2116
+ async copyToClipboard(format, filters = {}, options = {}) {
2117
+ const result = this.export(format, filters, options);
2118
+ try {
2119
+ if (navigator.clipboard && window.isSecureContext) {
2120
+ await navigator.clipboard.writeText(result.data);
2121
+ return true;
2122
+ } else {
2123
+ const textArea = document.createElement("textarea");
2124
+ textArea.value = result.data;
2125
+ textArea.style.position = "fixed";
2126
+ textArea.style.opacity = "0";
2127
+ document.body.appendChild(textArea);
2128
+ textArea.focus();
2129
+ textArea.select();
2130
+ const success = document.execCommand("copy");
2131
+ document.body.removeChild(textArea);
2132
+ return success;
2133
+ }
2134
+ } catch (error) {
2135
+ console.error("Failed to copy to clipboard:", error);
2136
+ return false;
2137
+ }
2138
+ }
2139
+ /**
2140
+ * Get all logs (for debugging)
2141
+ */
2142
+ getAllLogs() {
2143
+ return [...this.buffer];
2144
+ }
2145
+ /**
2146
+ * Save export to file with download prompt
2147
+ */
2148
+ async saveToFile(format, filters = {}, options = {}) {
2149
+ try {
2150
+ const result = this.export(format, filters, options);
2151
+ const blob = new Blob([result.data], {
2152
+ type: this.getMimeType(format)
2153
+ });
2154
+ const url = URL.createObjectURL(blob);
2155
+ const a = document.createElement("a");
2156
+ const filename = this.generateFilename(format, filters);
2157
+ a.href = url;
2158
+ a.download = filename;
2159
+ a.style.display = "none";
2160
+ document.body.appendChild(a);
2161
+ a.click();
2162
+ document.body.removeChild(a);
2163
+ URL.revokeObjectURL(url);
2164
+ return true;
2165
+ } catch (error) {
2166
+ console.error("Failed to save file:", error);
2167
+ return false;
2168
+ }
2169
+ }
2170
+ /**
2171
+ * Get MIME type for format
2172
+ */
2173
+ getMimeType(format) {
2174
+ const mimeTypes = {
2175
+ json: "application/json",
2176
+ csv: "text/csv",
2177
+ markdown: "text/markdown",
2178
+ plain: "text/plain",
2179
+ html: "text/html"
2180
+ };
2181
+ return mimeTypes[format] || "text/plain";
2182
+ }
2183
+ /**
2184
+ * Generate filename with timestamp
2185
+ */
2186
+ generateFilename(format, filters) {
2187
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-").slice(0, -5);
2188
+ const prefix = filters.prefixes?.length === 1 ? `_${filters.prefixes[0]}` : "";
2189
+ const extension = format === "markdown" ? "md" : format;
2190
+ return `logs${prefix}_${timestamp}.${extension}`;
2191
+ }
2192
+ /**
2193
+ * Stream logs to external endpoint
2194
+ */
2195
+ async streamToEndpoint(endpoint, filters = {}, options = {}) {
2196
+ try {
2197
+ const logs = this.filterLogs(filters);
2198
+ const batchSize = options.batchSize || 100;
2199
+ const format = options.format || "json";
2200
+ for (let i = 0; i < logs.length; i += batchSize) {
2201
+ const batch = logs.slice(i, i + batchSize);
2202
+ const result = this.export(format, {}, { compact: true });
2203
+ const headers = {
2204
+ "Content-Type": "application/json"
2205
+ };
2206
+ if (options.apiKey) {
2207
+ headers["Authorization"] = `Bearer ${options.apiKey}`;
2208
+ }
2209
+ const response = await fetch(endpoint, {
2210
+ method: "POST",
2211
+ headers,
2212
+ body: JSON.stringify({
2213
+ logs: batch,
2214
+ metadata: {
2215
+ batchIndex: Math.floor(i / batchSize),
2216
+ totalBatches: Math.ceil(logs.length / batchSize),
2217
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2218
+ }
2219
+ })
2220
+ });
2221
+ if (!response.ok) {
2222
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
2223
+ }
2224
+ }
2225
+ return true;
2226
+ } catch (error) {
2227
+ console.error("Failed to stream logs:", error);
2228
+ return false;
2229
+ }
2230
+ }
2231
+ /**
2232
+ * Create export with metadata enrichment
2233
+ */
2234
+ exportWithMetadata(format, filters = {}, options = {}) {
2235
+ const baseResult = this.export(format, filters, options);
2236
+ const bufferStats = this.getBufferStats();
2237
+ return {
2238
+ ...baseResult,
2239
+ metadata: {
2240
+ ...baseResult.metadata,
2241
+ bufferStats,
2242
+ performance: {
2243
+ memoryUsage: this.estimateMemoryUsage(),
2244
+ processingTime: Date.now()
2245
+ },
2246
+ system: {
2247
+ userAgent: typeof navigator !== "undefined" ? navigator.userAgent : "Node.js",
2248
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2249
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone
2250
+ }
2251
+ }
2252
+ };
2253
+ }
2254
+ /**
2255
+ * Estimate memory usage of buffer
2256
+ */
2257
+ estimateMemoryUsage() {
2258
+ const sampleEntry = this.buffer[0];
2259
+ if (!sampleEntry) return 0;
2260
+ const sampleSize = JSON.stringify(sampleEntry).length;
2261
+ return sampleSize * this.buffer.length;
2262
+ }
2263
+ }
2264
+ class CommandProcessor {
2265
+ commands = /* @__PURE__ */ new Map();
2266
+ aliases = /* @__PURE__ */ new Map();
2267
+ plugins = /* @__PURE__ */ new Map();
2268
+ history = [];
2269
+ maxHistorySize = 100;
2270
+ isInteractiveMode = false;
2271
+ /**
2272
+ * Register a command
2273
+ */
2274
+ registerCommand(command) {
2275
+ this.commands.set(command.name, command);
2276
+ if (command.aliases) {
2277
+ for (const alias of command.aliases) {
2278
+ this.aliases.set(alias, command.name);
2279
+ }
2280
+ }
2281
+ }
2282
+ /**
2283
+ * Register a plugin
2284
+ */
2285
+ registerPlugin(plugin, logger) {
2286
+ if (this.plugins.has(plugin.name)) {
2287
+ throw new Error(`Plugin ${plugin.name} is already registered`);
2288
+ }
2289
+ this.plugins.set(plugin.name, plugin);
2290
+ for (const command of plugin.commands) {
2291
+ this.registerCommand(command);
2292
+ }
2293
+ if (plugin.initialize && logger) {
2294
+ plugin.initialize(this, logger);
2295
+ }
2296
+ }
2297
+ /**
2298
+ * Unregister a plugin
2299
+ */
2300
+ unregisterPlugin(pluginName) {
2301
+ const plugin = this.plugins.get(pluginName);
2302
+ if (!plugin) return;
2303
+ for (const command of plugin.commands) {
2304
+ this.commands.delete(command.name);
2305
+ if (command.aliases) {
2306
+ for (const alias of command.aliases) {
2307
+ this.aliases.delete(alias);
2308
+ }
2309
+ }
2310
+ }
2311
+ if (plugin.cleanup) {
2312
+ plugin.cleanup();
2313
+ }
2314
+ this.plugins.delete(pluginName);
2315
+ }
2316
+ /**
2317
+ * Get all registered commands
2318
+ */
2319
+ getCommands() {
2320
+ return Array.from(this.commands.values());
2321
+ }
2322
+ /**
2323
+ * Get a specific command
2324
+ */
2325
+ getCommand(name) {
2326
+ let command = this.commands.get(name);
2327
+ if (command) return command;
2328
+ const aliasTarget = this.aliases.get(name);
2329
+ if (aliasTarget) {
2330
+ return this.commands.get(aliasTarget);
2331
+ }
2332
+ return void 0;
2333
+ }
2334
+ /**
2335
+ * Get command history
2336
+ */
2337
+ getHistory() {
2338
+ return [...this.history];
2339
+ }
2340
+ /**
2341
+ * Clear command history
2342
+ */
2343
+ clearHistory() {
2344
+ this.history = [];
2345
+ }
2346
+ /**
2347
+ * Get registered plugins
2348
+ */
2349
+ getPlugins() {
2350
+ return Array.from(this.plugins.values());
2351
+ }
2352
+ /**
2353
+ * Enter interactive mode
2354
+ */
2355
+ enterInteractiveMode(logger) {
2356
+ this.isInteractiveMode = true;
2357
+ logger.info("🔧 Interactive CLI mode activated. Type /exit to quit, /help for commands.");
2358
+ if (typeof window !== "undefined") {
2359
+ this.setupBrowserInteractiveMode(logger);
2360
+ }
2361
+ }
2362
+ /**
2363
+ * Exit interactive mode
2364
+ */
2365
+ exitInteractiveMode() {
2366
+ this.isInteractiveMode = false;
2367
+ }
2368
+ /**
2369
+ * Setup browser interactive mode
2370
+ */
2371
+ setupBrowserInteractiveMode(logger) {
2372
+ window.cli = (commandString) => {
2373
+ return this.processCommand(`/${commandString}`, logger);
2374
+ };
2375
+ logger.info('💡 Use cli("command") to execute CLI commands in browser console.');
2376
+ }
2377
+ /**
2378
+ * Process a CLI command
2379
+ */
2380
+ async processCommand(commandString, logger) {
2381
+ if (!commandString.startsWith("/")) {
2382
+ logger.error("Invalid command. Commands must start with /");
2383
+ this.addToHistory(commandString, false);
2384
+ return;
2385
+ }
2386
+ const parts = commandString.slice(1).split(" ");
2387
+ const commandName = parts[0] || "";
2388
+ const args = parts.slice(1).join(" ");
2389
+ const command = this.getCommand(commandName);
2390
+ if (!command) {
2391
+ logger.error(`Unknown command: ${commandName}. Type /help for available commands.`);
2392
+ const suggestions = this.getSuggestions(commandName);
2393
+ if (suggestions.length > 0) {
2394
+ logger.info(`📋 Did you mean: ${suggestions.slice(0, 3).join(", ")}?`);
2395
+ }
2396
+ this.addToHistory(commandString, false);
2397
+ return;
2398
+ }
2399
+ try {
2400
+ await command.execute(args || "", logger);
2401
+ this.addToHistory(commandString, true);
2402
+ } catch (error) {
2403
+ logger.error(`Command '${commandName}' failed:`, error);
2404
+ this.addToHistory(commandString, false);
2405
+ }
2406
+ }
2407
+ /**
2408
+ * Add command to history
2409
+ */
2410
+ addToHistory(command, success) {
2411
+ this.history.unshift({
2412
+ command,
2413
+ timestamp: /* @__PURE__ */ new Date(),
2414
+ success
2415
+ });
2416
+ if (this.history.length > this.maxHistorySize) {
2417
+ this.history = this.history.slice(0, this.maxHistorySize);
2418
+ }
2419
+ }
2420
+ /**
2421
+ * Get command suggestions for partial matches
2422
+ */
2423
+ getSuggestions(partial) {
2424
+ const commandNames = Array.from(this.commands.keys());
2425
+ return commandNames.filter((name) => name.startsWith(partial));
2426
+ }
2427
+ }
2428
+ class ConfigCommand {
2429
+ name = "config";
2430
+ description = "Show or update logger configuration";
2431
+ usage = "/config [json|key=value,...]";
2432
+ execute(args, logger) {
2433
+ if (!args) {
2434
+ this.showStatus(logger);
2435
+ return;
2436
+ }
2437
+ try {
2438
+ if (args.startsWith("{")) {
2439
+ const config = JSON.parse(args);
2440
+ this.applyConfig(config, logger);
2441
+ } else {
2442
+ const pairs = args.split(",").map((pair) => pair.trim().split("="));
2443
+ const config = {};
2444
+ pairs.forEach(([key, value]) => {
2445
+ if (key && value) {
2446
+ config[key.trim()] = value.trim().replace(/["']/g, "");
2447
+ }
2448
+ });
2449
+ this.applyConfig(config, logger);
2450
+ }
2451
+ } catch (error) {
2452
+ logger.error("Invalid config format. Use JSON or key=value pairs:", error);
2453
+ logger.info('Examples: /config {"theme":"dark"} or /config theme=neon,verbosity=debug');
2454
+ }
2455
+ }
2456
+ showStatus(logger) {
2457
+ const statusData = {
2458
+ theme: logger.getConfig().theme || "default",
2459
+ verbosity: logger.getConfig().verbosity,
2460
+ colors: logger.getConfig().enableColors,
2461
+ timestamps: logger.getConfig().enableTimestamps,
2462
+ stackTrace: logger.getConfig().enableStackTrace,
2463
+ globalPrefix: logger.getConfig().globalPrefix || "none",
2464
+ bannerType: logger.getConfig().bannerType || "simple",
2465
+ handlers: logger.getHandlers().length
2466
+ };
2467
+ logger.group("⚙️ Logger Configuration");
2468
+ logger.table(statusData);
2469
+ logger.groupEnd();
2470
+ }
2471
+ applyConfig(config, logger) {
2472
+ const validKeys = ["theme", "verbosity", "enableColors", "enableTimestamps", "enableStackTrace", "globalPrefix", "bannerType"];
2473
+ const applied = [];
2474
+ Object.entries(config).forEach(([key, value]) => {
2475
+ if (validKeys.includes(key)) {
2476
+ if (key === "theme" && typeof value === "string") {
2477
+ logger.setTheme(value);
2478
+ applied.push(`${key}=${value}`);
2479
+ } else if (key === "bannerType" && typeof value === "string") {
2480
+ logger.setBannerType(value);
2481
+ applied.push(`${key}=${value}`);
2482
+ } else if (key === "verbosity") {
2483
+ logger.setVerbosity(value);
2484
+ applied.push(`${key}=${value}`);
2485
+ } else if (key === "globalPrefix") {
2486
+ logger.setGlobalPrefix(value);
2487
+ applied.push(`${key}=${value}`);
2488
+ } else {
2489
+ logger.updateConfig({ [key]: value });
2490
+ applied.push(`${key}=${value}`);
2491
+ }
2492
+ } else {
2493
+ logger.warn(`Invalid config key: ${key}`);
2494
+ }
2495
+ });
2496
+ if (applied.length > 0) {
2497
+ logger.success(`Configuration updated: ${applied.join(", ")}`);
2498
+ }
2499
+ }
2500
+ }
2501
+ class ThemesCommand {
2502
+ name = "themes";
2503
+ description = "Show available theme presets";
2504
+ usage = "/themes";
2505
+ execute(_args, logger) {
2506
+ logger.group("🎨 Available Themes");
2507
+ Object.keys(THEME_PRESETS).forEach((themeName) => {
2508
+ const preview = THEME_PRESETS[themeName];
2509
+ const previewStyle = new StyleBuilder().bg(preview.info.background).color(preview.info.color).padding("4px 8px").rounded("4px").border(preview.info.border).build();
2510
+ console.log(`%c${themeName}`, previewStyle, `- ${themeName} theme preview`);
2511
+ });
2512
+ logger.groupEnd();
2513
+ }
2514
+ }
2515
+ class BannersCommand {
2516
+ name = "banners";
2517
+ description = "Show available banner types";
2518
+ usage = "/banners";
2519
+ execute(_args, logger) {
2520
+ logger.group("🖼️ Available Banner Types");
2521
+ Object.keys(BANNER_VARIANTS).forEach((bannerName) => {
2522
+ const banner = BANNER_VARIANTS[bannerName];
2523
+ console.log(`%c${bannerName}`, "font-weight: bold; color: #667eea;");
2524
+ console.log(`%cPreview:`, "color: #666; font-size: 12px;");
2525
+ if (bannerName === "simple") {
2526
+ console.log(`%c${banner.text}`, banner.style);
2527
+ } else if (bannerName === "ascii") {
2528
+ console.log(`%c${banner.text.split("\n").slice(1, 4).join("\n")}...`, "font-family: monospace; color: #667eea; font-size: 10px;");
2529
+ } else if (bannerName === "unicode") {
2530
+ console.log(`%c${banner.text}`, banner.style);
2531
+ } else {
2532
+ console.log(`%c${bannerName} banner`, "color: #666; font-style: italic;");
2533
+ }
2534
+ });
2535
+ logger.groupEnd();
2536
+ }
2537
+ }
2538
+ class BannerCommand {
2539
+ name = "banner";
2540
+ description = "Change or show current banner type";
2541
+ usage = "/banner [type]";
2542
+ execute(args, logger) {
2543
+ if (!args) {
2544
+ logger.showBanner();
2545
+ return;
2546
+ }
2547
+ if (args in BANNER_VARIANTS) {
2548
+ logger.setBannerType(args);
2549
+ logger.showBanner();
2550
+ } else {
2551
+ logger.error(`Invalid banner type: ${args}. Available: ${Object.keys(BANNER_VARIANTS).join(", ")}`);
2552
+ }
2553
+ }
2554
+ }
2555
+ class StatusCommand {
2556
+ name = "status";
2557
+ description = "Show current logger status and configuration";
2558
+ usage = "/status";
2559
+ execute(_args, logger) {
2560
+ const config = logger.getConfig();
2561
+ const statusData = {
2562
+ theme: config.theme ? config.theme : "default",
2563
+ verbosity: config.verbosity,
2564
+ colors: config.enableColors,
2565
+ timestamps: config.enableTimestamps,
2566
+ stackTrace: config.enableStackTrace,
2567
+ globalPrefix: config.globalPrefix ? config.globalPrefix : "none",
2568
+ bannerType: config.bannerType ? config.bannerType : "simple",
2569
+ handlers: logger.getHandlers().length,
2570
+ bufferSize: config.bufferSize ? config.bufferSize : 1e3
2571
+ };
2572
+ logger.group("⚙️ Logger Configuration");
2573
+ logger.table(statusData);
2574
+ logger.groupEnd();
2575
+ const exportHandler = logger.getExportHandler();
2576
+ if (exportHandler) {
2577
+ const bufferStats = exportHandler.getBufferStats();
2578
+ logger.group("📊 Buffer Statistics");
2579
+ logger.table({
2580
+ size: `${bufferStats.size}/${bufferStats.maxSize}`,
2581
+ usage: `${bufferStats.usage.toFixed(1)}%`,
2582
+ oldestLog: bufferStats.oldestLog ? bufferStats.oldestLog.toISOString() : "None",
2583
+ newestLog: bufferStats.newestLog ? bufferStats.newestLog.toISOString() : "None",
2584
+ errorCount: bufferStats.levelCounts.error + bufferStats.levelCounts.critical,
2585
+ warningCount: bufferStats.levelCounts.warn
2586
+ });
2587
+ logger.groupEnd();
2588
+ }
2589
+ }
2590
+ }
2591
+ class ResetCommand {
2592
+ name = "reset";
2593
+ description = "Reset logger configuration to defaults";
2594
+ usage = "/reset";
2595
+ execute(_args, logger) {
2596
+ logger.resetConfig();
2597
+ }
2598
+ }
2599
+ class DemoCommand {
2600
+ name = "demo";
2601
+ description = "Show comprehensive feature demonstration";
2602
+ usage = "/demo";
2603
+ execute(_args, logger) {
2604
+ logger.group("🎪 Advanced Logger Demo");
2605
+ logger.debug("Debug message with detailed information");
2606
+ logger.info("Informational message about system state");
2607
+ logger.warn("Warning about deprecated feature");
2608
+ logger.error("Error processing user request");
2609
+ logger.success("Operation completed successfully");
2610
+ logger.critical("Critical system failure detected");
2611
+ logger.group("📊 Advanced Features Demo");
2612
+ logger.table([
2613
+ { feature: "Styled Console", status: "✅ Active", performance: "Excellent" },
2614
+ { feature: "Theme System", status: "✅ Active", performance: "Great" },
2615
+ { feature: "CLI Interface", status: "✅ Active", performance: "Good" },
2616
+ { feature: "Export System", status: "✅ Active", performance: "Excellent" }
2617
+ ]);
2618
+ logger.time("demo-operation");
2619
+ setTimeout(() => {
2620
+ logger.timeEnd("demo-operation");
2621
+ }, 100);
2622
+ logger.logWithSVG("SVG Demo");
2623
+ logger.logAnimated("🌟 Animated Logger Demo 🌟", 2);
2624
+ logger.groupEnd();
2625
+ logger.groupEnd();
2626
+ logger.info("Demo completed! Check the console for styled output.");
2627
+ }
2628
+ }
2629
+ function parseArguments(args) {
2630
+ const filters = {};
2631
+ const options = {};
2632
+ let format;
2633
+ if (!args.trim()) return { filters, options };
2634
+ const argParts = args.match(/(?:[^\s"]+|"[^"]*")+/g) || [];
2635
+ for (let i = 0; i < argParts.length; i++) {
2636
+ const arg = argParts[i];
2637
+ if (!arg) {
2638
+ continue;
2639
+ }
2640
+ if (i === 0 && !arg.startsWith("--") && arg in EXPORT_FORMATS) {
2641
+ format = arg;
2642
+ continue;
2643
+ }
2644
+ if (arg.startsWith("--")) {
2645
+ const [flag, value] = arg.slice(2).split("=");
2646
+ switch (flag) {
2647
+ case "level":
2648
+ case "levels":
2649
+ if (value) {
2650
+ filters.levels = value.split(",").map((l) => l.trim());
2651
+ }
2652
+ break;
2653
+ case "since":
2654
+ if (value) filters.since = value;
2655
+ break;
2656
+ case "until":
2657
+ if (value) filters.until = value;
2658
+ break;
2659
+ case "prefix":
2660
+ case "prefixes":
2661
+ if (value) {
2662
+ filters.prefixes = value.split(",").map((p) => p.trim());
2663
+ }
2664
+ break;
2665
+ case "exclude-prefix":
2666
+ case "exclude-prefixes":
2667
+ if (value) {
2668
+ filters.excludePrefixes = value.split(",").map((p) => p.trim());
2669
+ }
2670
+ break;
2671
+ case "last":
2672
+ if (value) filters.last = parseInt(value, 10);
2673
+ break;
2674
+ case "first":
2675
+ if (value) filters.first = parseInt(value, 10);
2676
+ break;
2677
+ case "search":
2678
+ if (value) filters.search = value.replace(/['"]/g, "");
2679
+ break;
2680
+ case "with-stack":
2681
+ filters.withStackTrace = true;
2682
+ break;
2683
+ case "errors-only":
2684
+ filters.errorsOnly = true;
2685
+ break;
2686
+ case "group-by":
2687
+ if (value) {
2688
+ filters.groupBy = value;
2689
+ options.groupBy = value;
2690
+ }
2691
+ break;
2692
+ case "minimal":
2693
+ options.minimal = true;
2694
+ break;
2695
+ case "compact":
2696
+ options.compact = true;
2697
+ break;
2698
+ case "styled":
2699
+ options.styled = true;
2700
+ break;
2701
+ }
2702
+ }
2703
+ }
2704
+ return { filters, options, format };
2705
+ }
2706
+ class ExportCommand {
2707
+ name = "export";
2708
+ description = "Export logs to various formats";
2709
+ usage = "/export <format> [--filter=value] [--option]";
2710
+ execute(args, logger) {
2711
+ const exportHandler = logger.getExportHandler();
2712
+ if (!exportHandler) {
2713
+ logger.error("Export handler not available. Make sure ExportLogHandler is registered.");
2714
+ return;
2715
+ }
2716
+ const { filters, options, format } = parseArguments(args);
2717
+ if (!format) {
2718
+ logger.error("Format required. Available formats: " + Object.keys(EXPORT_FORMATS).join(", "));
2719
+ logger.info("Usage: /export <format> [--filter=value]");
2720
+ logger.info("Example: /export json --level=error,warn --last=50");
2721
+ return;
2722
+ }
2723
+ try {
2724
+ const result = exportHandler.export(format, filters, options);
2725
+ logger.success(`✅ Export completed: ${result.metadata.filteredLogs} logs exported in ${format} format`);
2726
+ if (result.data.length < 1e3) {
2727
+ logger.group(`📄 Preview (${format.toUpperCase()})`);
2728
+ console.log(result.data);
2729
+ logger.groupEnd();
2730
+ } else {
2731
+ logger.info(`📄 Export size: ${(result.data.length / 1024).toFixed(2)}KB`);
2732
+ }
2733
+ logger.table({
2734
+ format: result.format,
2735
+ totalLogs: result.metadata.totalLogs,
2736
+ filtered: result.metadata.filteredLogs,
2737
+ exported: result.metadata.exportedAt
2738
+ });
2739
+ } catch (error) {
2740
+ logger.error("Export failed:", error);
2741
+ }
2742
+ }
2743
+ }
2744
+ class CopyCommand {
2745
+ name = "copy";
2746
+ description = "Copy logs to clipboard";
2747
+ usage = "/copy <format> [--filter=value] [--option]";
2748
+ async execute(args, logger) {
2749
+ const exportHandler = logger.getExportHandler();
2750
+ if (!exportHandler) {
2751
+ logger.error("Export handler not available. Make sure ExportLogHandler is registered.");
2752
+ return;
2753
+ }
2754
+ const { filters, options, format } = parseArguments(args);
2755
+ if (!format) {
2756
+ logger.error("Format required. Available formats: " + Object.keys(EXPORT_FORMATS).join(", "));
2757
+ logger.info("Usage: /copy <format> [--filter=value]");
2758
+ logger.info("Example: /copy plain --level=error --last=25");
2759
+ return;
2760
+ }
2761
+ try {
2762
+ const success = await exportHandler.copyToClipboard(format, filters, options);
2763
+ if (success) {
2764
+ const result = exportHandler.export(format, filters, options);
2765
+ logger.success(`📋 Copied ${result.metadata.filteredLogs} logs to clipboard (${format} format)`);
2766
+ } else {
2767
+ logger.error("Failed to copy to clipboard. Browser may not support clipboard API.");
2768
+ }
2769
+ } catch (error) {
2770
+ logger.error("Copy failed:", error);
2771
+ }
2772
+ }
2773
+ }
2774
+ class BufferSizeCommand {
2775
+ name = "buffer-size";
2776
+ description = "Set log buffer size";
2777
+ usage = "/buffer-size <size>";
2778
+ execute(args, logger) {
2779
+ const exportHandler = logger.getExportHandler();
2780
+ if (!exportHandler) {
2781
+ logger.error("Export handler not available.");
2782
+ return;
2783
+ }
2784
+ const size = parseInt(args.trim(), 10);
2785
+ if (isNaN(size) || size <= 0) {
2786
+ logger.error("Invalid buffer size. Must be a positive number.");
2787
+ logger.info("Example: /buffer-size 2000");
2788
+ return;
2789
+ }
2790
+ exportHandler.setBufferSize(size);
2791
+ logger.success(`Buffer size set to ${size}`);
2792
+ }
2793
+ }
2794
+ class ClearBufferCommand {
2795
+ name = "clear-buffer";
2796
+ description = "Clear the log buffer";
2797
+ usage = "/clear-buffer";
2798
+ execute(_args, logger) {
2799
+ const exportHandler = logger.getExportHandler();
2800
+ if (!exportHandler) {
2801
+ logger.error("Export handler not available.");
2802
+ return;
2803
+ }
2804
+ const stats = exportHandler.getBufferStats();
2805
+ exportHandler.clearBuffer();
2806
+ logger.success(`✅ Buffer cleared. Removed ${stats.size} log entries.`);
2807
+ }
2808
+ }
2809
+ class BufferInfoCommand {
2810
+ name = "buffer-info";
2811
+ description = "Show buffer statistics and information";
2812
+ usage = "/buffer-info";
2813
+ execute(_args, logger) {
2814
+ const exportHandler = logger.getExportHandler();
2815
+ if (!exportHandler) {
2816
+ logger.error("Export handler not available.");
2817
+ return;
2818
+ }
2819
+ const stats = exportHandler.getBufferStats();
2820
+ logger.group("📊 Buffer Information");
2821
+ logger.table({
2822
+ size: `${stats.size}/${stats.maxSize}`,
2823
+ usage: `${stats.usage.toFixed(1)}%`,
2824
+ oldestLog: stats.oldestLog?.toLocaleString() || "None",
2825
+ newestLog: stats.newestLog?.toLocaleString() || "None"
2826
+ });
2827
+ logger.group("📈 Log Level Counts");
2828
+ logger.table(stats.levelCounts);
2829
+ logger.groupEnd();
2830
+ logger.groupEnd();
2831
+ }
2832
+ }
2833
+ class HelpCommand {
2834
+ name = "help";
2835
+ description = "Show CLI help and available commands";
2836
+ usage = "/help [command]";
2837
+ execute(_args, logger) {
2838
+ const helpStyle = new StyleBuilder().bg("linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%)").color("#495057").padding("15px 20px").rounded("8px").border("1px solid #dee2e6").font("Monaco, Consolas, monospace").size("13px").build();
2839
+ const helpText = `
2840
+ ╭─────────────── ADVANCED LOGGER CLI COMMANDS ─────────────────╮
2841
+ │ │
2842
+ │ CONFIGURATION │
2843
+ │ /config Show current configuration │
2844
+ │ /config {json} Apply JSON configuration │
2845
+ │ /config key=val Apply key-value configuration │
2846
+ │ /themes Show available themes │
2847
+ │ /banners Show available banner types │
2848
+ │ /banner [type] Change/show banner type │
2849
+ │ /status Show logger status & buffer stats │
2850
+ │ /demo Show feature demonstration │
2851
+ │ /reset Reset to default configuration │
2852
+ │ │
2853
+ │ EXPORT & CLIPBOARD │
2854
+ │ /export <format> Export logs (json|csv|md|plain|html) │
2855
+ │ /copy <format> Copy logs to clipboard │
2856
+ │ /buffer-size N Set log buffer size │
2857
+ │ /buffer-info Show buffer statistics │
2858
+ │ /clear-buffer Clear stored logs │
2859
+ │ │
2860
+ │ EXPORT FILTERS (for export/copy commands) │
2861
+ │ --level error,warn Filter by log levels │
2862
+ │ --since 2h Logs from last 2 hours │
2863
+ │ --until 1h Logs until 1 hour ago │
2864
+ │ --prefix API,DB Filter by prefixes │
2865
+ │ --exclude-prefix INT Exclude prefixes │
2866
+ │ --last 50 Last 50 logs only │
2867
+ │ --first 25 First 25 logs only │
2868
+ │ --search "error" Search in log messages │
2869
+ │ --with-stack Only logs with stack traces │
2870
+ │ --errors-only Only error + critical logs │
2871
+ │ --group-by level Group by level/prefix/hour │
2872
+ │ │
2873
+ │ EXPORT OPTIONS │
2874
+ │ --minimal Minimal output format │
2875
+ │ --compact Remove extra whitespace │
2876
+ │ --styled Include styling (HTML format) │
2877
+ │ │
2878
+ ├──────────────────── CONFIGURATION OPTIONS ─────────────────┤
2879
+ │ │
2880
+ │ theme: default | dark | light | neon | minimal | cyberpunk│
2881
+ │ bannerType: simple | ascii | unicode | svg | animated │
2882
+ │ verbosity: debug | info | warn | error | critical | silent│
2883
+ │ enableColors: true | false │
2884
+ │ enableTimestamps: true | false │
2885
+ │ enableStackTrace: true | false │
2886
+ │ globalPrefix: "string" │
2887
+ │ bufferSize: number (50-10000) │
2888
+ │ │
2889
+ ├──────────────────────── EXAMPLES ──────────────────────────┤
2890
+ │ │
2891
+ │ Basic Configuration: │
2892
+ │ /config {"theme":"dark","verbosity":"debug"} │
2893
+ │ /config theme=neon,bufferSize=2000 │
2894
+ │ /banner animated Change to animated banner │
2895
+ │ │
2896
+ │ Export Examples: │
2897
+ │ /export json --level=error,warn --last=25 │
2898
+ │ /export csv --since=2h --prefix=API │
2899
+ │ /export markdown --group-by=level --errors-only │
2900
+ │ /export html --styled --since=1h │
2901
+ │ │
2902
+ │ Clipboard Examples: │
2903
+ │ /copy plain --minimal --last=10 │
2904
+ │ /copy json --search="authentication" --compact │
2905
+ │ /copy csv --since=30m --exclude-prefix=DEBUG │
2906
+ │ │
2907
+ │ Buffer Management: │
2908
+ │ /buffer-size 5000 Increase buffer to 5000 logs │
2909
+ │ /buffer-info Show detailed buffer statistics │
2910
+ │ /clear-buffer Clear all stored logs │
2911
+ │ │
2912
+ │ Time Formats: │
2913
+ │ --since=2h 2 hours ago │
2914
+ │ --since=30m 30 minutes ago │
2915
+ │ --since=1d 1 day ago │
2916
+ │ --since="2024-01-01T10:00:00Z" Specific ISO date │
2917
+ │ │
2918
+ ╰─────────────────────────────────────────────────────────────╯`;
2919
+ console.log(`%c${helpText}`, helpStyle);
2920
+ logger.group("💡 Quick Tips");
2921
+ const tips = [
2922
+ "Use /demo to see all logger features in action",
2923
+ "Logs are automatically stored in a circular buffer for export",
2924
+ "Export formats: JSON (structured), CSV (Excel), Markdown (readable), Plain (simple), HTML (styled)",
2925
+ "Time filters support relative (2h, 30m) and absolute (ISO) formats",
2926
+ 'Combine multiple filters: /export json --level=error --since=1h --search="auth"',
2927
+ "Use /copy for quick clipboard access instead of /export"
2928
+ ];
2929
+ tips.forEach((tip) => {
2930
+ logger.info(`• ${tip}`);
2931
+ });
2932
+ logger.groupEnd();
2933
+ }
2934
+ }
2935
+ class HistoryCommand {
2936
+ name = "history";
2937
+ description = "Show command execution history";
2938
+ usage = "/history [limit] - Show recent commands (default: 10)";
2939
+ category = "system";
2940
+ aliases = ["hist", "h"];
2941
+ execute(args, logger) {
2942
+ const processor = logger.cliProcessor;
2943
+ if (!processor) {
2944
+ logger.error("CLI processor not available");
2945
+ return;
2946
+ }
2947
+ const limit = parseInt(args) || 10;
2948
+ const history = processor.getHistory().slice(0, limit);
2949
+ if (history.length === 0) {
2950
+ logger.info("📝 No command history available");
2951
+ return;
2952
+ }
2953
+ logger.info(`📋 Last ${history.length} commands:`);
2954
+ history.forEach((entry, index) => {
2955
+ const status = entry.success ? "✅" : "❌";
2956
+ const time = entry.timestamp.toLocaleTimeString();
2957
+ logger.info(`${status} [${time}] ${entry.command}`);
2958
+ });
2959
+ }
2960
+ }
2961
+ class ClearHistoryCommand {
2962
+ name = "clearhistory";
2963
+ description = "Clear command execution history";
2964
+ usage = "/clearhistory - Remove all command history";
2965
+ category = "system";
2966
+ aliases = ["clrhist"];
2967
+ execute(args, logger) {
2968
+ const processor = logger.cliProcessor;
2969
+ if (!processor) {
2970
+ logger.error("CLI processor not available");
2971
+ return;
2972
+ }
2973
+ processor.clearHistory();
2974
+ logger.success("🗑️ Command history cleared");
2975
+ }
2976
+ }
2977
+ class InteractiveCommand {
2978
+ name = "interactive";
2979
+ description = "Enter interactive CLI mode";
2980
+ usage = "/interactive - Start interactive command mode";
2981
+ category = "system";
2982
+ aliases = ["i", "repl"];
2983
+ execute(args, logger) {
2984
+ const processor = logger.cliProcessor;
2985
+ if (!processor) {
2986
+ logger.error("CLI processor not available");
2987
+ return;
2988
+ }
2989
+ processor.enterInteractiveMode(logger);
2990
+ }
2991
+ }
2992
+ class PluginsCommand {
2993
+ name = "plugins";
2994
+ description = "List loaded CLI plugins";
2995
+ usage = "/plugins - Show all registered plugins";
2996
+ category = "system";
2997
+ aliases = ["plug"];
2998
+ execute(args, logger) {
2999
+ const processor = logger.cliProcessor;
3000
+ if (!processor) {
3001
+ logger.error("CLI processor not available");
3002
+ return;
3003
+ }
3004
+ const plugins = processor.getPlugins();
3005
+ if (plugins.length === 0) {
3006
+ logger.info("🔌 No plugins registered");
3007
+ return;
3008
+ }
3009
+ logger.info(`🔌 Loaded plugins (${plugins.length}):`);
3010
+ plugins.forEach((plugin) => {
3011
+ logger.info(` 📦 ${plugin.name} v${plugin.version} - ${plugin.description}`);
3012
+ logger.info(` Commands: ${plugin.commands.map((c) => c.name).join(", ")}`);
3013
+ });
3014
+ }
3015
+ }
3016
+ function createDefaultCLI() {
3017
+ const processor = new CommandProcessor();
3018
+ processor.registerCommand(new HelpCommand());
3019
+ processor.registerCommand(new ConfigCommand());
3020
+ processor.registerCommand(new ThemesCommand());
3021
+ processor.registerCommand(new BannersCommand());
3022
+ processor.registerCommand(new BannerCommand());
3023
+ processor.registerCommand(new StatusCommand());
3024
+ processor.registerCommand(new ResetCommand());
3025
+ processor.registerCommand(new DemoCommand());
3026
+ processor.registerCommand(new ExportCommand());
3027
+ processor.registerCommand(new CopyCommand());
3028
+ processor.registerCommand(new BufferSizeCommand());
3029
+ processor.registerCommand(new ClearBufferCommand());
3030
+ processor.registerCommand(new BufferInfoCommand());
3031
+ processor.registerCommand(new HistoryCommand());
3032
+ processor.registerCommand(new ClearHistoryCommand());
3033
+ processor.registerCommand(new InteractiveCommand());
3034
+ processor.registerCommand(new PluginsCommand());
3035
+ return processor;
3036
+ }
3037
+ let LEVEL_STYLES = THEME_PRESETS.default;
3038
+ class Logger {
3039
+ config;
3040
+ scopedPrefix;
3041
+ handlers = [];
3042
+ timers = /* @__PURE__ */ new Map();
3043
+ groupDepth = 0;
3044
+ exportHandler;
3045
+ cliProcessor;
3046
+ themeChangeListener;
3047
+ badgeList = [];
3048
+ displaySettings = {
3049
+ showTimestamp: true,
3050
+ showLocation: true,
3051
+ showBadges: true
3052
+ };
3053
+ serializerRegistry;
3054
+ hookManager;
3055
+ transportManager;
3056
+ /**
3057
+ * Crea una nueva instancia del Logger
3058
+ *
3059
+ * @param {Partial<LoggerConfig>} config - Configuración opcional del logger
3060
+ *
3061
+ * @example
3062
+ * // Logger con configuración personalizada
3063
+ * const logger = new Logger({
3064
+ * theme: 'neon',
3065
+ * globalPrefix: 'MiApp',
3066
+ * verbosity: 'debug',
3067
+ * bufferSize: 1000
3068
+ * });
3069
+ */
3070
+ constructor(config = {}) {
3071
+ this.config = {
3072
+ ...DEFAULT_CONFIG$1,
3073
+ ...config
3074
+ };
3075
+ this.serializerRegistry = new SerializerRegistry();
3076
+ this.hookManager = new HookManager();
3077
+ if (this.config.bufferSize) {
3078
+ this.exportHandler = new ExportLogHandler(this.config.bufferSize);
3079
+ this.handlers.push(this.exportHandler);
3080
+ }
3081
+ this.cliProcessor = createDefaultCLI();
3082
+ if (this.config.autoDetectTheme) {
3083
+ this.setupAutoThemeDetection();
3084
+ }
3085
+ }
3086
+ // ===== PRIVATE HELPER METHODS =====
3087
+ /**
3088
+ * Configura la detección automática de tema con listener de cambios
3089
+ * @private
3090
+ * @description Detecta automáticamente si el navegador está en modo claro u oscuro
3091
+ */
3092
+ setupAutoThemeDetection() {
3093
+ if (this.themeChangeListener) {
3094
+ this.themeChangeListener();
3095
+ this.themeChangeListener = null;
3096
+ }
3097
+ this.themeChangeListener = setupThemeChangeListener((theme) => {
3098
+ this.debug(`DevTools theme changed to: ${theme}`);
3099
+ });
3100
+ }
3101
+ // ===== CONFIGURATION METHODS =====
3102
+ /**
3103
+ * Obtiene la configuración actual del logger
3104
+ *
3105
+ * @returns {LoggerConfig} Configuración completa actual
3106
+ *
3107
+ * @example
3108
+ * const config = logger.getConfig();
3109
+ * console.log('Verbosidad actual:', config.verbosity);
3110
+ * console.log('Tema actual:', config.theme);
3111
+ *
3112
+ * @since 0.3.0
3113
+ */
3114
+ getConfig() {
3115
+ return { ...this.config };
3116
+ }
3117
+ /**
3118
+ * Actualiza la configuración del logger
3119
+ *
3120
+ * @param {Partial<LoggerConfig>} updates - Propiedades a actualizar
3121
+ *
3122
+ * @example
3123
+ * logger.updateConfig({
3124
+ * verbosity: 'debug',
3125
+ * enableTimestamps: false,
3126
+ * theme: 'cyberpunk'
3127
+ * });
3128
+ *
3129
+ * @since 0.3.0
3130
+ */
3131
+ updateConfig(updates) {
3132
+ const previousAutoDetect = this.config.autoDetectTheme;
3133
+ this.config = { ...this.config, ...updates };
3134
+ if (updates.autoDetectTheme !== void 0 && updates.autoDetectTheme !== previousAutoDetect) {
3135
+ if (updates.autoDetectTheme) {
3136
+ this.setupAutoThemeDetection();
3137
+ } else if (this.themeChangeListener) {
3138
+ this.themeChangeListener();
3139
+ this.themeChangeListener = null;
3140
+ }
3141
+ }
3142
+ }
3143
+ /**
3144
+ * Establece el prefijo global para todos los mensajes de log
3145
+ *
3146
+ * @param {string} prefix - Prefijo a usar
3147
+ *
3148
+ * @example
3149
+ * logger.setGlobalPrefix('MiApp');
3150
+ * logger.info('Iniciado'); // [MiApp] Iniciado
3151
+ *
3152
+ * @since 0.3.0
3153
+ */
3154
+ setGlobalPrefix(prefix) {
3155
+ this.config.globalPrefix = prefix;
3156
+ }
3157
+ /**
3158
+ * Establece el nivel de verbosidad para filtrar la salida de logs
3159
+ *
3160
+ * @param {Verbosity} level - Nivel mínimo a mostrar ('debug' | 'info' | 'warn' | 'error' | 'critical' | 'silent')
3161
+ *
3162
+ * @example
3163
+ * logger.setVerbosity('warn'); // Solo muestra warn, error y critical
3164
+ * logger.setVerbosity('debug'); // Muestra todos los niveles
3165
+ * logger.setVerbosity('silent'); // No muestra nada
3166
+ *
3167
+ * @since 0.3.0
3168
+ */
3169
+ setVerbosity(level) {
3170
+ this.config.verbosity = level;
3171
+ }
3172
+ /**
3173
+ * Establece el tema del logger
3174
+ *
3175
+ * @param {ThemeVariant} theme - Tema a aplicar ('default' | 'dark' | 'light' | 'neon' | 'minimal' | 'cyberpunk')
3176
+ *
3177
+ * @example
3178
+ * logger.setTheme('neon'); // Tema con colores neón
3179
+ * logger.setTheme('minimal'); // Tema minimalista
3180
+ * logger.setTheme('cyberpunk'); // Tema cyberpunk con efectos
3181
+ *
3182
+ * @since 0.3.0
3183
+ */
3184
+ setTheme(theme) {
3185
+ if (hasPreset(theme)) {
3186
+ this.preset(theme);
3187
+ return;
3188
+ }
3189
+ if (theme in THEME_PRESETS) {
3190
+ LEVEL_STYLES = THEME_PRESETS[theme];
3191
+ this.config.theme = theme;
3192
+ if (theme in THEME_BANNERS) {
3193
+ const themeBanner = THEME_BANNERS[theme];
3194
+ console.log(`%c${themeBanner.simple}`, themeBanner.style);
3195
+ }
3196
+ this.success(`Theme changed to: ${theme}`);
3197
+ } else {
3198
+ this.error(`Invalid theme: ${theme}. Available:`, [...getAvailablePresets(), ...Object.keys(THEME_PRESETS)]);
3199
+ }
3200
+ }
3201
+ /**
3202
+ * Establece el tipo de banner para mostrar en la inicialización
3203
+ *
3204
+ * @param {BannerType} bannerType - Tipo de banner ('simple' | 'ascii' | 'unicode' | 'svg' | 'animated')
3205
+ *
3206
+ * @example
3207
+ * logger.setBannerType('ascii'); // Banner con arte ASCII
3208
+ * logger.setBannerType('unicode'); // Banner con caracteres Unicode
3209
+ * logger.setBannerType('animated'); // Banner con animación
3210
+ *
3211
+ * @since 0.3.0
3212
+ */
3213
+ setBannerType(bannerType) {
3214
+ this.config.bannerType = bannerType;
3215
+ this.success(`Banner type changed to: ${bannerType}`);
3216
+ }
3217
+ /**
3218
+ * Reinicia el logger a la configuración por defecto
3219
+ *
3220
+ * @example
3221
+ * logger.resetConfig();
3222
+ * // Todo vuelve a la configuración inicial
3223
+ *
3224
+ * @since 0.3.0
3225
+ */
3226
+ resetConfig() {
3227
+ if (this.themeChangeListener) {
3228
+ this.themeChangeListener();
3229
+ this.themeChangeListener = null;
3230
+ }
3231
+ this.config = { ...DEFAULT_CONFIG$1 };
3232
+ LEVEL_STYLES = THEME_PRESETS.default;
3233
+ if (this.config.autoDetectTheme) {
3234
+ this.setupAutoThemeDetection();
3235
+ }
3236
+ this.success("Logger configuration reset to defaults");
3237
+ }
3238
+ /**
3239
+ * Método de limpieza para eliminar listeners y liberar recursos
3240
+ *
3241
+ * @example
3242
+ * // Antes de cerrar la aplicación
3243
+ * logger.cleanup();
3244
+ *
3245
+ * @since 0.3.0
3246
+ */
3247
+ cleanup() {
3248
+ if (this.themeChangeListener) {
3249
+ this.themeChangeListener();
3250
+ this.themeChangeListener = null;
3251
+ }
3252
+ this.transportManager?.close().catch(() => {
3253
+ });
3254
+ }
3255
+ // ===== SIMPLIFIED API =====
3256
+ /**
3257
+ * Aplica un preset inteligente - funciona perfectamente sin configuración
3258
+ *
3259
+ * @param {string} name - Nombre del preset a aplicar
3260
+ *
3261
+ * @example
3262
+ * // Presets disponibles
3263
+ * logger.preset('default'); // Limpio y adaptativo
3264
+ * logger.preset('cyberpunk'); // Colores neón, efectos brillantes
3265
+ * logger.preset('glassmorphism'); // Efectos de blur modernos
3266
+ * logger.preset('minimal'); // Minimalista y elegante
3267
+ * logger.preset('debug'); // Modo desarrollo detallado
3268
+ * logger.preset('production'); // Optimizado para producción
3269
+ *
3270
+ * @since 0.3.0
3271
+ */
3272
+ preset(name) {
3273
+ if (!hasPreset(name)) {
3274
+ this.error(`Unknown preset: ${name}. Available presets:`, getAvailablePresets());
3275
+ return;
3276
+ }
3277
+ const presetConfig = getSmartPreset(name);
3278
+ if (presetConfig) {
3279
+ this.displaySettings.showTimestamp = presetConfig.timestamp?.show ?? true;
3280
+ this.displaySettings.showLocation = presetConfig.location?.show ?? true;
3281
+ this._activePreset = presetConfig;
3282
+ this._activePresetName = name;
3283
+ if (getEnvironment() === "browser") {
3284
+ this.success(`Applied preset: ${name}`);
3285
+ }
3286
+ }
3287
+ }
3288
+ /**
3289
+ * Lista todos los presets disponibles
3290
+ *
3291
+ * @returns {string[]} Array con nombres de presets disponibles
3292
+ *
3293
+ * @example
3294
+ * const disponibles = logger.presets();
3295
+ * console.log(disponibles); // ['default', 'cyberpunk', 'glassmorphism', ...]
3296
+ *
3297
+ * @since 0.3.0
3298
+ */
3299
+ presets() {
3300
+ return getAvailablePresets();
3301
+ }
3302
+ // ===== TOGGLE METHODS =====
3303
+ /**
3304
+ * Oculta el timestamp en los logs
3305
+ *
3306
+ * @example
3307
+ * logger.hideTimestamp();
3308
+ * logger.info('Sin marca de tiempo'); // Sin timestamp visible
3309
+ *
3310
+ * @since 0.3.0
3311
+ */
3312
+ hideTimestamp() {
3313
+ this.displaySettings.showTimestamp = false;
3314
+ this.success("Timestamp hidden");
3315
+ }
3316
+ /**
3317
+ * Muestra el timestamp en los logs
3318
+ *
3319
+ * @example
3320
+ * logger.showTimestamp();
3321
+ * logger.info('Con marca de tiempo'); // [2024-01-15 10:30:45] Con marca de tiempo
3322
+ *
3323
+ * @since 0.3.0
3324
+ */
3325
+ showTimestamp() {
3326
+ this.displaySettings.showTimestamp = true;
3327
+ this.success("Timestamp shown");
3328
+ }
3329
+ /**
3330
+ * Oculta la información de ubicación (archivo:línea) en los logs
3331
+ *
3332
+ * @example
3333
+ * logger.hideLocation();
3334
+ * logger.debug('Sin ubicación'); // Sin mostrar archivo:línea
3335
+ *
3336
+ * @since 0.3.0
3337
+ */
3338
+ hideLocation() {
3339
+ this.displaySettings.showLocation = false;
3340
+ this.success("Location info hidden");
3341
+ }
3342
+ /**
3343
+ * Muestra la información de ubicación (archivo:línea) en los logs
3344
+ *
3345
+ * @example
3346
+ * logger.showLocation();
3347
+ * logger.debug('Con ubicación'); // app.js:42 Con ubicación
3348
+ *
3349
+ * @since 0.3.0
3350
+ */
3351
+ showLocation() {
3352
+ this.displaySettings.showLocation = true;
3353
+ this.success("Location info shown");
3354
+ }
3355
+ /**
3356
+ * Oculta los badges en los logs
3357
+ *
3358
+ * @example
3359
+ * logger.hideBadges();
3360
+ * const api = logger.api('REST');
3361
+ * api.info('Sin badges'); // Sin mostrar [API] [REST]
3362
+ *
3363
+ * @since 0.3.0
3364
+ */
3365
+ hideBadges() {
3366
+ this.displaySettings.showBadges = false;
3367
+ this.success("Badges hidden");
3368
+ }
3369
+ /**
3370
+ * Muestra los badges en los logs
3371
+ *
3372
+ * @example
3373
+ * logger.showBadges();
3374
+ * const api = logger.api('GraphQL');
3375
+ * api.info('Con badges'); // [API] [GraphQL] Con badges
3376
+ *
3377
+ * @since 0.3.0
3378
+ */
3379
+ showBadges() {
3380
+ this.displaySettings.showBadges = true;
3381
+ this.success("Badges shown");
3382
+ }
3383
+ /**
3384
+ * Establece múltiples badges para los logs
3385
+ *
3386
+ * @param {string[]} badges - Array de badges a mostrar
3387
+ * @returns {this} Logger instance para encadenamiento
3388
+ *
3389
+ * @example
3390
+ * logger.badges(['v3', 'stable']).info('Release publicado');
3391
+ * logger.badges(['API', 'v2']).warn('Endpoint deprecado');
3392
+ *
3393
+ * @since 3.0.0
3394
+ */
3395
+ badges(badges2) {
3396
+ this.badgeList = [...badges2];
3397
+ return this;
3398
+ }
3399
+ /**
3400
+ * Añade un badge individual a la lista
3401
+ *
3402
+ * @param {string} badge - Badge a añadir
3403
+ * @returns {this} Logger instance para encadenamiento
3404
+ *
3405
+ * @example
3406
+ * logger.badge('DEBUG').badge('AUTH').info('Token validado');
3407
+ *
3408
+ * @since 3.0.0
3409
+ */
3410
+ badge(badge2) {
3411
+ if (!this.badgeList.includes(badge2)) {
3412
+ this.badgeList.push(badge2);
3413
+ }
3414
+ return this;
3415
+ }
3416
+ /**
3417
+ * Limpia todos los badges activos
3418
+ *
3419
+ * @returns {this} Logger instance para encadenamiento
3420
+ *
3421
+ * @example
3422
+ * logger.clearBadges().info('Sin badges');
3423
+ *
3424
+ * @since 3.0.0
3425
+ */
3426
+ clearBadges() {
3427
+ this.badgeList = [];
3428
+ return this;
3429
+ }
3430
+ // ===== SCOPED LOGGERS =====
3431
+ component(name) {
3432
+ return new ComponentLogger(this, name);
3433
+ }
3434
+ api(name) {
3435
+ return new APILogger(this, name);
3436
+ }
3437
+ scope(name) {
3438
+ return new ScopedLogger(this, name);
3439
+ }
3440
+ // ===== SIMPLE CUSTOMIZATION =====
3441
+ /**
3442
+ * Personalización simple con configuración mínima
3443
+ *
3444
+ * @param {Object} overrides - Opciones de personalización
3445
+ * @param {Object} overrides.message - Configuración del mensaje
3446
+ * @param {Object} overrides.timestamp - Configuración del timestamp
3447
+ * @param {Object} overrides.location - Configuración de ubicación
3448
+ * @param {Object} overrides.level - Configuración del nivel
3449
+ * @param {Object} overrides.prefix - Configuración del prefijo
3450
+ * @param {string} overrides.spacing - Espaciado: 'compact' | 'normal' | 'spacious'
3451
+ *
3452
+ * @example
3453
+ * logger.customize({
3454
+ * message: { color: '#00ff00', size: '16px' },
3455
+ * timestamp: { show: false },
3456
+ * spacing: 'compact'
3457
+ * });
3458
+ *
3459
+ * @since 0.3.0
3460
+ */
3461
+ customize(overrides) {
3462
+ if (overrides.timestamp?.show !== void 0) {
3463
+ this.displaySettings.showTimestamp = overrides.timestamp.show;
3464
+ }
3465
+ if (overrides.location?.show !== void 0) {
3466
+ this.displaySettings.showLocation = overrides.location.show;
3467
+ }
3468
+ if (overrides.prefix?.show !== void 0) ;
3469
+ this._customization = overrides;
3470
+ this.success("Customization applied");
3471
+ }
3472
+ /**
3473
+ * Access advanced styling API (for power users)
3474
+ */
3475
+ styles() {
3476
+ return createLogStyleBuilder(this);
3477
+ }
3478
+ // ===== HANDLER MANAGEMENT =====
3479
+ /**
3480
+ * Añade un handler personalizado para extender funcionalidad
3481
+ *
3482
+ * @param {ILogHandler} handler - Handler que implementa ILogHandler
3483
+ *
3484
+ * @example
3485
+ * // Handler personalizado para enviar logs a servidor
3486
+ * const remoteHandler = new RemoteLogHandler('https://api.ejemplo.com/logs');
3487
+ * logger.addHandler(remoteHandler);
3488
+ *
3489
+ * @example
3490
+ * // Handler para guardar en archivo
3491
+ * const fileHandler = new FileLogHandler('./app.log');
3492
+ * logger.addHandler(fileHandler);
3493
+ *
3494
+ * @since 0.3.0
3495
+ */
3496
+ addHandler(handler) {
3497
+ this.handlers.push(handler);
3498
+ }
3499
+ /**
3500
+ * Obtiene todos los handlers registrados
3501
+ *
3502
+ * @returns {ILogHandler[]} Array de handlers activos
3503
+ * @since 0.3.0
3504
+ */
3505
+ getHandlers() {
3506
+ return [...this.handlers];
3507
+ }
3508
+ /**
3509
+ * Obtiene el handler de exportación si está disponible
3510
+ *
3511
+ * @returns {ExportLogHandler | undefined} Handler de exportación o undefined
3512
+ * @since 0.3.0
3513
+ */
3514
+ getExportHandler() {
3515
+ return this.exportHandler;
3516
+ }
3517
+ // ===== SERIALIZERS =====
3518
+ /**
3519
+ * Añade un serializador personalizado para un tipo específico
3520
+ *
3521
+ * @param type - Constructor del tipo a serializar
3522
+ * @param serializer - Función de serialización
3523
+ * @param priority - Prioridad (mayor = primero)
3524
+ *
3525
+ * @example
3526
+ * logger.addSerializer(Error, (err) => ({
3527
+ * name: err.name,
3528
+ * message: err.message,
3529
+ * stack: err.stack?.split('\n').slice(0, 5)
3530
+ * }));
3531
+ *
3532
+ * @since 3.0.0
3533
+ */
3534
+ addSerializer(type, serializer, priority) {
3535
+ this.serializerRegistry.add(type, serializer, priority);
3536
+ }
3537
+ /**
3538
+ * Elimina un serializador registrado
3539
+ *
3540
+ * @param type - Constructor del tipo a remover
3541
+ * @returns true si se eliminó
3542
+ *
3543
+ * @since 3.0.0
3544
+ */
3545
+ removeSerializer(type) {
3546
+ return this.serializerRegistry.remove(type);
3547
+ }
3548
+ /**
3549
+ * Obtiene el registry de serializadores
3550
+ *
3551
+ * @returns SerializerRegistry
3552
+ * @since 3.0.0
3553
+ */
3554
+ getSerializerRegistry() {
3555
+ return this.serializerRegistry;
3556
+ }
3557
+ // ===== HOOKS & MIDDLEWARE =====
3558
+ /**
3559
+ * Registra un hook para un evento
3560
+ *
3561
+ * @param event - Evento: 'beforeLog' | 'afterLog' | 'onError'
3562
+ * @param callback - Función a ejecutar
3563
+ * @param priority - Prioridad (mayor = primero)
3564
+ * @returns Función para desregistrar
3565
+ *
3566
+ * @example
3567
+ * const unsubscribe = logger.on('beforeLog', (entry) => {
3568
+ * entry.correlationId = getCorrelationId();
3569
+ * return entry;
3570
+ * });
3571
+ *
3572
+ * @since 3.0.0
3573
+ */
3574
+ on(event, callback, priority) {
3575
+ return this.hookManager.on(event, callback, priority);
3576
+ }
3577
+ /**
3578
+ * Registra un hook que se ejecuta solo una vez
3579
+ *
3580
+ * @param event - Evento: 'beforeLog' | 'afterLog' | 'onError'
3581
+ * @param callback - Función a ejecutar
3582
+ * @param priority - Prioridad (mayor = primero)
3583
+ * @returns Función para desregistrar
3584
+ *
3585
+ * @since 3.0.0
3586
+ */
3587
+ once(event, callback, priority) {
3588
+ return this.hookManager.once(event, callback, priority);
3589
+ }
3590
+ /**
3591
+ * Elimina un hook registrado
3592
+ *
3593
+ * @param event - Evento del hook
3594
+ * @param callback - Callback a remover
3595
+ * @returns true si se eliminó
3596
+ *
3597
+ * @since 3.0.0
3598
+ */
3599
+ off(event, callback) {
3600
+ return this.hookManager.off(event, callback);
3601
+ }
3602
+ /**
3603
+ * Añade un middleware al pipeline
3604
+ *
3605
+ * @param middleware - Función middleware
3606
+ * @param priority - Prioridad (mayor = primero)
3607
+ * @returns Función para desregistrar
3608
+ *
3609
+ * @example
3610
+ * logger.use((entry, next) => {
3611
+ * entry.requestId = asyncLocalStorage.getStore()?.requestId;
3612
+ * next();
3613
+ * });
3614
+ *
3615
+ * @since 3.0.0
3616
+ */
3617
+ use(middleware, priority) {
3618
+ return this.hookManager.use(middleware, priority);
3619
+ }
3620
+ /**
3621
+ * Obtiene el HookManager
3622
+ *
3623
+ * @returns HookManager
3624
+ * @since 3.0.0
3625
+ */
3626
+ getHookManager() {
3627
+ return this.hookManager;
3628
+ }
3629
+ // ===== TRANSPORTS =====
3630
+ /**
3631
+ * Añade un transport para envío de logs
3632
+ *
3633
+ * @param target - Configuración del transport
3634
+ * @returns ID único del transport
3635
+ *
3636
+ * @example
3637
+ * // File transport
3638
+ * logger.addTransport({
3639
+ * target: 'file',
3640
+ * options: { destination: '/var/log/app.log' }
3641
+ * });
3642
+ *
3643
+ * @example
3644
+ * // HTTP transport con batching
3645
+ * logger.addTransport({
3646
+ * target: 'http',
3647
+ * options: {
3648
+ * url: 'https://logs.example.com',
3649
+ * batchSize: 100,
3650
+ * flushInterval: 5000
3651
+ * },
3652
+ * level: 'warn'
3653
+ * });
3654
+ *
3655
+ * @since 3.0.0
3656
+ */
3657
+ addTransport(target) {
3658
+ if (!this.transportManager) {
3659
+ this.transportManager = new TransportManager();
3660
+ }
3661
+ return this.transportManager.add(target);
3662
+ }
3663
+ /**
3664
+ * Elimina un transport
3665
+ *
3666
+ * @param id - ID del transport a remover
3667
+ * @returns true si se eliminó
3668
+ *
3669
+ * @since 3.0.0
3670
+ */
3671
+ removeTransport(id) {
3672
+ return this.transportManager?.remove(id) ?? false;
3673
+ }
3674
+ /**
3675
+ * Fuerza el flush de todos los transports
3676
+ *
3677
+ * @returns Promise que resuelve cuando todos los buffers están vaciados
3678
+ *
3679
+ * @since 3.0.0
3680
+ */
3681
+ async flushTransports() {
3682
+ await this.transportManager?.flush();
3683
+ }
3684
+ /**
3685
+ * Cierra todos los transports
3686
+ *
3687
+ * @returns Promise que resuelve cuando todos están cerrados
3688
+ *
3689
+ * @since 3.0.0
3690
+ */
3691
+ async closeTransports() {
3692
+ await this.transportManager?.close();
3693
+ }
3694
+ /**
3695
+ * Obtiene el TransportManager
3696
+ *
3697
+ * @returns TransportManager o undefined si no hay transports
3698
+ * @since 3.0.0
3699
+ */
3700
+ getTransportManager() {
3701
+ return this.transportManager;
3702
+ }
3703
+ // ===== CORE LOGGING METHODS =====
3704
+ /**
3705
+ * Verifica si un nivel de log debe mostrarse según la verbosidad actual
3706
+ * @private
3707
+ * @param {LogLevel} level - Nivel de log a verificar
3708
+ * @returns {boolean} True si debe mostrarse, false si no
3709
+ */
3710
+ shouldLog(level) {
3711
+ if (this.config.verbosity === "silent") return false;
3712
+ const levels = { debug: 0, info: 1, warn: 2, error: 3, critical: 4 };
3713
+ return levels[level] >= levels[this.config.verbosity];
3714
+ }
3715
+ /**
3716
+ * Obtiene el prefijo efectivo (global + scope)
3717
+ * @private
3718
+ * @returns {string | undefined} Prefijo combinado o undefined
3719
+ */
3720
+ getEffectivePrefix() {
3721
+ const parts = [this.config.globalPrefix, this.scopedPrefix].filter(Boolean);
3722
+ return parts.length > 0 ? parts.join(":") : void 0;
3723
+ }
3724
+ /**
3725
+ * Método central de logging que maneja estilos y formato
3726
+ * @protected
3727
+ * @param {LogLevel} level - Nivel del log
3728
+ * @param {...any} args - Argumentos a loggear
3729
+ */
3730
+ log(level, ...args) {
3731
+ if (!this.shouldLog(level)) return;
3732
+ const stackInfo = this.config.enableStackTrace ? parseStackTrace() : null;
3733
+ const prefix = this.getEffectivePrefix();
3734
+ const timestamp = formatTimestamp();
3735
+ const serializedArgs = args.map((arg) => this.serializerRegistry.serialize(arg));
3736
+ let message = serializedArgs.length > 0 ? String(serializedArgs[0]) : "";
3737
+ if (this.badgeList.length > 0 && this.displaySettings.showBadges) {
3738
+ const badgePrefix = this.badgeList.map((b) => `[${b}]`).join("");
3739
+ message = badgePrefix + " " + message;
3740
+ }
3741
+ const additionalArgs = serializedArgs.slice(1);
3742
+ let hookEntry = {
3743
+ level,
3744
+ message,
3745
+ args: serializedArgs,
3746
+ timestamp,
3747
+ prefix,
3748
+ stackInfo: stackInfo || void 0
3749
+ };
3750
+ this.hookManager.emit("beforeLog", hookEntry).then((processed) => {
3751
+ message = processed.message;
3752
+ }).catch(() => {
3753
+ });
3754
+ const [format, ...styles2] = createStyledOutput(
3755
+ level,
3756
+ LEVEL_STYLES,
3757
+ prefix,
3758
+ message,
3759
+ this.displaySettings.showLocation ? stackInfo : null,
3760
+ this.config.autoDetectTheme,
3761
+ this._activePreset,
3762
+ this._activePresetName
3763
+ );
3764
+ const groupIndent = " ".repeat(this.groupDepth);
3765
+ const finalFormat = groupIndent + format;
3766
+ if (additionalArgs.length > 0) {
3767
+ console.log(finalFormat, ...styles2, ...additionalArgs);
3768
+ } else {
3769
+ console.log(finalFormat, ...styles2);
3770
+ }
3771
+ if (this.exportHandler) {
3772
+ this.exportHandler.setGroupInfo(this.groupDepth);
3773
+ }
3774
+ const metadata = {
3775
+ timestamp,
3776
+ level,
3777
+ prefix,
3778
+ stackInfo: stackInfo ? stackInfo : void 0
3779
+ };
3780
+ this.handlers.forEach((handler) => {
3781
+ try {
3782
+ handler.handle(level, message, serializedArgs, metadata);
3783
+ } catch (error2) {
3784
+ console.error("Log handler failed:", error2);
3785
+ }
3786
+ });
3787
+ if (this.transportManager) {
3788
+ const levelValues = {
3789
+ debug: 0,
3790
+ info: 1,
3791
+ warn: 2,
3792
+ error: 3,
3793
+ critical: 4
3794
+ };
3795
+ const record = {
3796
+ level,
3797
+ levelValue: levelValues[level],
3798
+ time: Date.now(),
3799
+ msg: message,
3800
+ prefix,
3801
+ location: stackInfo ? {
3802
+ file: stackInfo.file,
3803
+ line: stackInfo.line,
3804
+ column: stackInfo.column,
3805
+ function: stackInfo.function
3806
+ } : void 0
3807
+ };
3808
+ this.transportManager.write(record).catch(() => {
3809
+ });
3810
+ }
3811
+ this.hookManager.emit("afterLog", hookEntry).catch(() => {
3812
+ });
3813
+ }
3814
+ logWithBindings(bindings, level, ...args) {
3815
+ if (!this.shouldLog(level)) return;
3816
+ let prefix = "";
3817
+ if (bindings.badges?.length) {
3818
+ prefix += bindings.badges.map((b) => `[${b}]`).join("");
3819
+ }
3820
+ if (bindings.scope) {
3821
+ prefix += `[${bindings.scope}] `;
3822
+ }
3823
+ if (prefix && args.length > 0) {
3824
+ args[0] = prefix + String(args[0]);
3825
+ }
3826
+ this.log(level, ...args);
3827
+ }
3828
+ debug(...args) {
3829
+ this.log("debug", ...args);
3830
+ }
3831
+ /**
3832
+ * Registra mensajes informativos
3833
+ *
3834
+ * @param {...any} args - Mensajes y datos informativos
3835
+ *
3836
+ * @example
3837
+ * logger.info('Servidor iniciado en puerto 3000');
3838
+ * logger.info('Usuario conectado:', userId);
3839
+ * logger.info('Procesando', totalItems, 'elementos');
3840
+ *
3841
+ * @since 0.3.0
3842
+ */
3843
+ info(...args) {
3844
+ this.log("info", ...args);
3845
+ }
3846
+ /**
3847
+ * Registra mensajes de advertencia
3848
+ *
3849
+ * @param {...any} args - Mensajes de advertencia
3850
+ *
3851
+ * @example
3852
+ * logger.warn('Memoria al 85% de capacidad');
3853
+ * logger.warn('API deprecada, usar v2');
3854
+ * logger.warn('Reintentos agotados:', maxRetries);
3855
+ *
3856
+ * @since 0.3.0
3857
+ */
3858
+ warn(...args) {
3859
+ this.log("warn", ...args);
3860
+ }
3861
+ /**
3862
+ * Registra mensajes de error
3863
+ *
3864
+ * @param {...any} args - Mensajes de error y stack traces
3865
+ *
3866
+ * @example
3867
+ * logger.error('Fallo en conexión a base de datos');
3868
+ * logger.error('Error al procesar:', error.message, error.stack);
3869
+ * logger.error('Código de error:', errorCode);
3870
+ *
3871
+ * @since 0.3.0
3872
+ */
3873
+ error(...args) {
3874
+ this.log("error", ...args);
3875
+ }
3876
+ /**
3877
+ * Registra mensajes de éxito (nivel info especial)
3878
+ *
3879
+ * @param {...any} args - Mensajes de operaciones exitosas
3880
+ *
3881
+ * @example
3882
+ * logger.success('Base de datos conectada');
3883
+ * logger.success('Usuario creado con ID:', userId);
3884
+ * logger.success('✓ Tests pasados: 42/42');
3885
+ *
3886
+ * @since 0.3.0
3887
+ */
3888
+ success(...args) {
3889
+ if (!this.shouldLog("info")) return;
3890
+ const stackInfo = this.config.enableStackTrace ? parseStackTrace() : null;
3891
+ const prefix = this.getEffectivePrefix();
3892
+ const message = args.length > 0 ? String(args[0]) : "";
3893
+ const additionalArgs = args.slice(1);
3894
+ const [format, ...styles2] = createStyledOutput(
3895
+ "info",
3896
+ LEVEL_STYLES,
3897
+ prefix,
3898
+ message,
3899
+ this.displaySettings.showLocation ? stackInfo : null,
3900
+ this.config.autoDetectTheme,
3901
+ this._activePreset,
3902
+ this._activePresetName
3903
+ );
3904
+ const successStyle = LEVEL_STYLES.success;
3905
+ let emoji = "✅";
3906
+ let label = "SUCCESS";
3907
+ if (successStyle) {
3908
+ if (successStyle.emoji) {
3909
+ emoji = successStyle.emoji;
3910
+ }
3911
+ if (successStyle.label) {
3912
+ label = successStyle.label;
3913
+ }
3914
+ }
3915
+ const successFormat = format.replace(/ℹ️ INFO/, `${emoji} ${label}`);
3916
+ const groupIndent = " ".repeat(this.groupDepth);
3917
+ const finalFormat = groupIndent + successFormat;
3918
+ if (additionalArgs.length > 0) {
3919
+ console.log(finalFormat, ...styles2, ...additionalArgs);
3920
+ } else {
3921
+ console.log(finalFormat, ...styles2);
3922
+ }
3923
+ const metadata = {
3924
+ timestamp: formatTimestamp(),
3925
+ level: "info",
3926
+ prefix,
3927
+ stackInfo: stackInfo ? stackInfo : void 0
3928
+ };
3929
+ this.handlers.forEach((handler) => {
3930
+ try {
3931
+ handler.handle("info", message, args, metadata);
3932
+ } catch (error2) {
3933
+ console.error("Log handler failed:", error2);
3934
+ }
3935
+ });
3936
+ }
3937
+ /**
3938
+ * Registra información de trace (debugging detallado)
3939
+ *
3940
+ * @param {...any} args - Datos detallados para debugging
3941
+ *
3942
+ * @example
3943
+ * logger.trace('Entrando en función processData');
3944
+ * logger.trace('Stack completo:', new Error().stack);
3945
+ *
3946
+ * @since 0.3.0
3947
+ */
3948
+ trace(...args) {
3949
+ this.log("debug", ...args);
3950
+ if (this.shouldLog("debug")) {
3951
+ console.trace(...args);
3952
+ }
3953
+ }
3954
+ /**
3955
+ * Registra errores críticos (prioridad más alta)
3956
+ *
3957
+ * @param {...any} args - Errores críticos del sistema
3958
+ *
3959
+ * @example
3960
+ * logger.critical('Sistema caído - reinicio inmediato requerido');
3961
+ * logger.critical('Pérdida de datos detectada');
3962
+ * logger.critical('Brecha de seguridad:', securityError);
3963
+ *
3964
+ * @since 0.3.0
3965
+ */
3966
+ critical(...args) {
3967
+ this.log("critical", ...args);
3968
+ }
3969
+ // ===== ADVANCED LOGGING FEATURES =====
3970
+ /**
3971
+ * Muestra datos en formato de tabla
3972
+ *
3973
+ * @param {any} data - Datos a mostrar (array de objetos o matriz)
3974
+ * @param {string[]} columns - Columnas específicas a mostrar (opcional)
3975
+ *
3976
+ * @example
3977
+ * const usuarios = [
3978
+ * { id: 1, nombre: 'Juan', edad: 30 },
3979
+ * { id: 2, nombre: 'María', edad: 25 }
3980
+ * ];
3981
+ * logger.table(usuarios);
3982
+ * logger.table(usuarios, ['nombre', 'edad']); // Solo estas columnas
3983
+ *
3984
+ * @since 0.3.0
3985
+ */
3986
+ table(data, columns) {
3987
+ if (!this.shouldLog("info")) return;
3988
+ const prefix = this.getEffectivePrefix();
3989
+ const tableStyle = StylePresets.accent().build();
3990
+ const format = `%c📊 TABLE${prefix ? ` [${prefix}]` : ""}`;
3991
+ console.log(format, tableStyle);
3992
+ if (columns) {
3993
+ console.table(data, columns);
3994
+ } else {
3995
+ console.table(data);
3996
+ }
3997
+ }
3998
+ /**
3999
+ * Inicia un grupo colapsable en la consola
4000
+ *
4001
+ * @param {string} label - Etiqueta del grupo
4002
+ * @param {boolean} collapsed - Si el grupo inicia colapsado (default: false)
4003
+ *
4004
+ * @example
4005
+ * logger.group('Procesando usuarios');
4006
+ * logger.info('Usuario 1 procesado');
4007
+ * logger.info('Usuario 2 procesado');
4008
+ * logger.groupEnd();
4009
+ *
4010
+ * @example
4011
+ * // Grupo colapsado por defecto
4012
+ * logger.group('Detalles adicionales', true);
4013
+ * logger.debug('Información detallada aquí');
4014
+ * logger.groupEnd();
4015
+ *
4016
+ * @since 0.3.0
4017
+ */
4018
+ group(label, collapsed = false) {
4019
+ const groupStyle = new StyleBuilder().bg("linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%)").color("#1565c0").border("1px solid #90caf9").padding("4px 12px").rounded("6px").bold().build();
4020
+ const format = `%c📁 ${label}`;
4021
+ if (collapsed) {
4022
+ console.groupCollapsed(format, groupStyle);
4023
+ } else {
4024
+ console.group(format, groupStyle);
4025
+ }
4026
+ this.groupDepth++;
4027
+ }
4028
+ /**
4029
+ * Finaliza el grupo actual de la consola
4030
+ *
4031
+ * @example
4032
+ * logger.group('Operaciones');
4033
+ * logger.info('Operación 1');
4034
+ * logger.info('Operación 2');
4035
+ * logger.groupEnd(); // Cierra el grupo
4036
+ *
4037
+ * @since 0.3.0
4038
+ */
4039
+ groupEnd() {
4040
+ if (this.groupDepth > 0) {
4041
+ console.groupEnd();
4042
+ this.groupDepth--;
4043
+ }
4044
+ }
4045
+ // ===== PERFORMANCE TIMING =====
4046
+ /**
4047
+ * Inicia un temporizador con la etiqueta dada
4048
+ *
4049
+ * @param {string} label - Etiqueta identificadora del temporizador
4050
+ *
4051
+ * @example
4052
+ * logger.time('proceso-datos');
4053
+ * // ... operación costosa ...
4054
+ * logger.timeEnd('proceso-datos'); // ⏱️ Timer ended: proceso-datos - 1523.45ms
4055
+ *
4056
+ * @since 0.3.0
4057
+ */
4058
+ time(label) {
4059
+ const timer = {
4060
+ label,
4061
+ startTime: performance.now()
4062
+ };
4063
+ this.timers.set(label, timer);
4064
+ const timerStyle = StylePresets.warning().build();
4065
+ console.log(`%c⏱️ Timer started: ${label}`, timerStyle);
4066
+ }
4067
+ /**
4068
+ * Finaliza un temporizador y muestra el tiempo transcurrido
4069
+ *
4070
+ * @param {string} label - Etiqueta del temporizador a finalizar
4071
+ *
4072
+ * @example
4073
+ * logger.time('consulta-db');
4074
+ * await consultarBaseDatos();
4075
+ * logger.timeEnd('consulta-db'); // ⏱️ Timer ended: consulta-db - 234.56ms
4076
+ *
4077
+ * @since 0.3.0
4078
+ */
4079
+ timeEnd(label) {
4080
+ const timer = this.timers.get(label);
4081
+ if (!timer) {
4082
+ this.warn(`Timer '${label}' does not exist`);
4083
+ return;
4084
+ }
4085
+ const elapsed = performance.now() - timer.startTime;
4086
+ this.timers.delete(label);
4087
+ const timerStyle = StylePresets.success().build();
4088
+ console.log(`%c⏱️ Timer ended: ${label} - ${elapsed.toFixed(2)}ms`, timerStyle);
4089
+ }
4090
+ // ===== ADVANCED VISUAL FEATURES =====
4091
+ /**
4092
+ * Muestra un banner con el tipo especificado o configurado
4093
+ *
4094
+ * @param {BannerType} bannerType - Tipo de banner (opcional)
4095
+ *
4096
+ * @example
4097
+ * logger.showBanner('ascii'); // Banner ASCII art
4098
+ * logger.showBanner('unicode'); // Banner con caracteres Unicode
4099
+ * logger.showBanner('svg'); // Banner con gráfico SVG
4100
+ * logger.showBanner(); // Usa el tipo configurado
4101
+ *
4102
+ * @since 0.3.0
4103
+ */
4104
+ showBanner(bannerType) {
4105
+ const effectiveBannerType = bannerType ? bannerType : this.config.bannerType;
4106
+ displayInitBanner(effectiveBannerType);
4107
+ }
4108
+ /**
4109
+ * Registra mensaje con imagen SVG de fondo
4110
+ *
4111
+ * @param {string} message - Mensaje a mostrar
4112
+ * @param {string} svgContent - Contenido SVG personalizado (opcional)
4113
+ * @param {StyleOptions} options - Opciones de estilo (ancho, alto, padding)
4114
+ *
4115
+ * @example
4116
+ * // SVG automático con gradiente
4117
+ * logger.logWithSVG('🎆 Bienvenido a Better Logger');
4118
+ *
4119
+ * @example
4120
+ * // SVG personalizado
4121
+ * const customSVG = '<svg>...</svg>';
4122
+ * logger.logWithSVG('Logo', customSVG, { width: 400, height: 100 });
4123
+ *
4124
+ * @since 0.3.0
4125
+ */
4126
+ logWithSVG(message, svgContent, options = {}) {
4127
+ const { width = 300, height = 60, padding = "30px 150px" } = options;
4128
+ let svgDataUri = "";
4129
+ if (svgContent) {
4130
+ const encodedSVG = encodeURIComponent(svgContent);
4131
+ svgDataUri = `data:image/svg+xml,${encodedSVG}`;
4132
+ } else {
4133
+ const defaultSVG = `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${width} ${height}'><defs><linearGradient id='grad' x1='0%' y1='0%' x2='100%' y2='0%'><stop offset='0%' style='stop-color:%23667eea'/><stop offset='100%' style='stop-color:%23764ba2'/></linearGradient></defs><rect width='100%' height='100%' fill='url(%23grad)' rx='4'/><text x='${width / 2}' y='${height / 2 + 5}' text-anchor='middle' fill='white' font-family='monospace' font-size='14' font-weight='bold'>${message}</text></svg>`;
4134
+ svgDataUri = `data:image/svg+xml,${encodeURIComponent(defaultSVG)}`;
4135
+ }
4136
+ const svgStyle = new StyleBuilder().bg(`url("${svgDataUri}") no-repeat center center`).padding(padding).color("transparent").rounded("4px").build();
4137
+ console.log(`%c${message}`, svgStyle);
4138
+ }
4139
+ /**
4140
+ * Registra mensaje con gradiente animado de fondo
4141
+ *
4142
+ * @param {string} message - Mensaje a animar
4143
+ * @param {number} duration - Duración de la animación en segundos (default: 3)
4144
+ *
4145
+ * @example
4146
+ * logger.logAnimated('🌈 Animación en progreso');
4147
+ * logger.logAnimated('Cargando...', 5); // Animación de 5 segundos
4148
+ *
4149
+ * @since 0.3.0
4150
+ */
4151
+ logAnimated(message, duration = 3) {
4152
+ if (!document.getElementById("logger-animations")) {
4153
+ const style = document.createElement("style");
4154
+ style.id = "logger-animations";
4155
+ style.textContent = `
4156
+ @keyframes loggerGradient {
4157
+ 0% { background-position: 0% 50%; }
4158
+ 50% { background-position: 100% 50%; }
4159
+ 100% { background-position: 0% 50%; }
4160
+ }
4161
+ `;
4162
+ document.head.appendChild(style);
4163
+ }
4164
+ const animatedStyle = new StyleBuilder().bg("linear-gradient(-45deg, #667eea, #764ba2, #667eea, #764ba2)").css("background-size", "400% 400%").color("#ffffff").padding("12px 20px").rounded("8px").bold().font("Monaco, Consolas, monospace").animation(`loggerGradient ${duration}s ease infinite`).display("inline-block").build();
4165
+ console.log(`%c${message}`, animatedStyle);
4166
+ }
4167
+ /**
4168
+ * Agrupa logs por una propiedad específica usando Object.groupBy (cuando esté disponible)
4169
+ *
4170
+ * @param {T[]} items - Array de elementos a agrupar
4171
+ * @param {Function} groupBy - Función que retorna la clave de agrupación
4172
+ *
4173
+ * @example
4174
+ * const ventas = [
4175
+ * { producto: 'Laptop', categoria: 'Electrónica', precio: 1200 },
4176
+ * { producto: 'Mouse', categoria: 'Electrónica', precio: 25 },
4177
+ * { producto: 'Libro', categoria: 'Literatura', precio: 15 }
4178
+ * ];
4179
+ * logger.logGrouped(ventas, item => item.categoria);
4180
+ *
4181
+ * @since 0.3.0
4182
+ */
4183
+ logGrouped(items, groupBy) {
4184
+ try {
4185
+ let grouped;
4186
+ if (Object.groupBy) {
4187
+ grouped = Object.groupBy(items, groupBy);
4188
+ } else {
4189
+ grouped = items.reduce((acc, item) => {
4190
+ const key = groupBy(item);
4191
+ if (!acc[key]) {
4192
+ acc[key] = [];
4193
+ }
4194
+ acc[key].push(item);
4195
+ return acc;
4196
+ }, {});
4197
+ }
4198
+ Object.entries(grouped).forEach(([group2, groupItems]) => {
4199
+ this.group(`Group: ${group2}`);
4200
+ this.table(groupItems);
4201
+ this.groupEnd();
4202
+ });
4203
+ } catch {
4204
+ this.info("Grouped data:", items);
4205
+ }
4206
+ }
4207
+ // ===== CLI SYSTEM =====
4208
+ /**
4209
+ * Procesador de comandos CLI para configuración y exportación del logger
4210
+ *
4211
+ * @param {string} command - Comando CLI a ejecutar
4212
+ * @returns {Promise<void>}
4213
+ *
4214
+ * @example
4215
+ * // Comandos disponibles
4216
+ * await logger.cli('export json'); // Exporta logs en JSON
4217
+ * await logger.cli('export csv'); // Exporta logs en CSV
4218
+ * await logger.cli('theme list'); // Lista temas disponibles
4219
+ * await logger.cli('theme set neon'); // Cambia al tema neon
4220
+ * await logger.cli('config show'); // Muestra configuración actual
4221
+ * await logger.cli('history clear'); // Limpia historial de logs
4222
+ * await logger.cli('status'); // Muestra estado del logger
4223
+ * await logger.cli('help'); // Muestra ayuda de comandos
4224
+ *
4225
+ * @since 0.3.0
4226
+ */
4227
+ async cli(command) {
4228
+ if (!this.cliProcessor) {
4229
+ this.error("CLI processor not initialized");
4230
+ return;
4231
+ }
4232
+ await this.cliProcessor.processCommand(command, this);
4233
+ }
4234
+ }
4235
+ let _defaultLogger = null;
4236
+ function getDefaultLogger() {
4237
+ if (!_defaultLogger) {
4238
+ _defaultLogger = new Logger({
4239
+ verbosity: "info",
4240
+ enableColors: true,
4241
+ enableTimestamps: true,
4242
+ enableStackTrace: true,
4243
+ bufferSize: 1e3
4244
+ // Enable export functionality by default
4245
+ });
4246
+ try {
4247
+ displayInitBanner();
4248
+ } catch (error2) {
4249
+ }
4250
+ }
4251
+ return _defaultLogger;
4252
+ }
4253
+ getDefaultLogger();
4254
+ export {
4255
+ APILogger as A,
4256
+ BANNER_VARIANTS as B,
4257
+ ComponentLogger as C,
4258
+ ExportLogHandler as E,
4259
+ HookManager as H,
4260
+ Logger as L,
4261
+ SerializerRegistry as S,
4262
+ THEME_PRESETS as T,
4263
+ THEME_BANNERS as a,
4264
+ TransportManager as b,
4265
+ ScopedLogger as c,
4266
+ ContextLogger as d,
4267
+ displayInitBanner as e
4268
+ };
4269
+ //# sourceMappingURL=Logger-C126NTrD.js.map