@asaidimu/utils-logger 1.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.
package/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Saidimu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,267 @@
1
+ # @asaidimu/utils-logger
2
+
3
+ A robust, structured logging library for TypeScript/JavaScript applications. It provides a context-aware logger with support for multiple sinks (console, event bus, custom destinations), hierarchical child loggers, and advanced error formatting—all designed to simplify observability in complex systems.
4
+
5
+ ---
6
+
7
+ ## Features
8
+
9
+ - **Structured Logging** – Logs are consistent objects with `level`, `event`, `timestamp`, `data`, and `context` fields.
10
+ - **Log Levels** – `trace`, `debug`, `info`, `warn`, `error` with priority filtering.
11
+ - **Context Propagation** – Attach contextual metadata to a logger; child loggers inherit and merge context.
12
+ - **Pluggable Sinks** – Send logs to one or multiple destinations (console, event bus, files, etc.).
13
+ - **Built‑in Sinks** – `ConsoleSink` (stdout/stderr) and `EventBusSink` (integrates with an event bus).
14
+ - **Fuzz Logger** – Generate random logs for testing and performance benchmarking.
15
+ - **Error‑Aware** – Automatically extracts structured fields from `SystemError` and plain `Error` objects.
16
+ - **Type‑Safe** – Written in TypeScript with full type definitions included.
17
+
18
+ ---
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install @asaidimu/utils-logger
24
+ ```
25
+
26
+ > **Peer dependency**: `ws` (`^8.21.0`) is required if you use the `UnsecureWebSocketServerSink` with WebSocket‑based buses. Install it separately if needed.
27
+ > **Peer dependency**: `@asaidimu/utils-events` (`^1.2.0`) is required if you use the `EventBusSink` Install it separately if needed.
28
+
29
+ ---
30
+
31
+ ## Quick Start
32
+
33
+ ```typescript
34
+ import { Logger, ConsoleSink } from "@asaidimu/utils-logger";
35
+
36
+ // Create a logger that writes to the console
37
+ const logger = new Logger([new ConsoleSink()], {
38
+ app: "my-service",
39
+ environment: "development",
40
+ });
41
+
42
+ // Basic logging
43
+ logger.info("user_logged_in", { userId: "123", ip: "192.168.1.1" });
44
+
45
+ // Error logging
46
+ try {
47
+ // ...
48
+ } catch (err) {
49
+ logger.error("database_query_failed", err);
50
+ }
51
+
52
+ // Child logger with additional context
53
+ const childLogger = logger.child({ requestId: "abc-123" });
54
+ childLogger.debug("processing_payment", { amount: 99.99 });
55
+ ```
56
+
57
+ ---
58
+
59
+ ## Core Concepts
60
+
61
+ ### Logger
62
+
63
+ The main entry point implementing the `SystemLogger` interface. It holds a set of sinks, a base context, and methods for each log level.
64
+
65
+ ### Sinks
66
+
67
+ A sink is any object implementing the `LogSink` interface:
68
+
69
+ ```typescript
70
+ interface LogSink {
71
+ write(record: SystemLog): void | Promise<void>;
72
+ }
73
+ ```
74
+
75
+ When a log is emitted, it is passed to **all** registered sinks concurrently. If a sink returns a `Promise`, it is awaited (with `Promise.all`) but errors are swallowed to prevent logging failures from crashing the application.
76
+
77
+ ### Context
78
+
79
+ Context is an arbitrary object attached to every log record. It is useful for adding static metadata like service name, environment, or trace IDs. Child loggers merge new context onto the parent’s context.
80
+
81
+ ---
82
+
83
+ ## Built‑in Sinks
84
+
85
+ ### ConsoleSink
86
+
87
+ Writes formatted log lines to `stdout` or `stderr`. It automatically detects the runtime:
88
+
89
+ - In Node.js, uses `process.stdout.write` / `process.stderr.write`.
90
+ - In browsers, falls back to `console.log`, `console.error`, etc.
91
+
92
+ **Options**
93
+
94
+ | Option | Type | Description |
95
+ | --------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------- |
96
+ | `pipeMap` | `Partial<Record<LogLevel, ConsolePipe>>` | Override the output stream for specific levels (default: `warn`/`error` → `stderr`, others → `stdout`). |
97
+ | `format` | `(record: SystemLog) => string` | Custom string formatter. Default produces `[ISO timestamp] LEVEL event ctx=... data=...`. |
98
+
99
+ **Example**
100
+
101
+ ```typescript
102
+ const consoleSink = new ConsoleSink({
103
+ pipeMap: { error: "stdout" }, // send errors to stdout
104
+ format: (r) => `[${r.level}] ${r.event}`,
105
+ });
106
+ ```
107
+
108
+ ### EventBusSink
109
+
110
+ Routes logs to an event bus, either statically or dynamically. This is useful for cross‑component communication, WebSocket broadcasts, or centralised log aggregation.
111
+
112
+ **Requirements**
113
+
114
+ - An event bus that implements the `EventBus<TEventMap>` interface (from `@asaidimu/utils-events`). The event map defines the allowed event names and their payload shapes.
115
+
116
+ **Static Routing** – All logs go to a fixed event name.
117
+
118
+ ```typescript
119
+ import { EventBusSink } from '@asaidimu/utils-logger';
120
+
121
+ const eventBus = /* your event bus instance */;
122
+
123
+ const sink = new EventBusSink(eventBus, {
124
+ event: 'system:log', // static event name
125
+ map: (record) => ({ // optional mapping
126
+ level: record.level,
127
+ message: record.event,
128
+ timestamp: record.timestamp,
129
+ extra: record.data
130
+ })
131
+ });
132
+ ```
133
+
134
+ **Dynamic Routing** – Choose the event name per log record.
135
+
136
+ ```typescript
137
+ const sink = new EventBusSink(eventBus, {
138
+ resolve: (record) => {
139
+ // Route based on log level or event name
140
+ return record.level === "error" ? "error:log" : "info:log";
141
+ },
142
+ map: (record, eventName) => ({
143
+ // eventName is the resolved name
144
+ severity: record.level,
145
+ details: record.data,
146
+ }),
147
+ });
148
+ ```
149
+
150
+ The sink guards against exceptions so that failures in event emission do not break the logging flow.
151
+
152
+ ---
153
+
154
+ ## Fuzz
155
+
156
+ A helper class that generates random log entries at random intervals. Useful for load testing, demo environments, or stress‑testing your logging pipeline.
157
+
158
+ ```typescript
159
+ import { Fuzz } from "@asaidimu/utils-logger";
160
+ import { Logger, ConsoleSink } from "@asaidimu/utils-logger";
161
+
162
+ const realLogger = new Logger([new ConsoleSink()]);
163
+ const fuzz = new Fuzz(realLogger, {
164
+ minIntervalMs: 200,
165
+ maxIntervalMs: 1500,
166
+ allowedLevels: ["info", "warn", "error"],
167
+ eventRegistry: {
168
+ info: ["user_login", "order_placed", "payment_success"],
169
+ error: ["db_timeout", "stripe_failure"],
170
+ },
171
+ });
172
+
173
+ // Start emitting random logs every 200–1500ms
174
+ fuzz.start();
175
+
176
+ // Later, stop
177
+ fuzz.stop();
178
+ ```
179
+
180
+ **Options**
181
+
182
+ | Option | Type | Default | Description |
183
+ | --------------- | ------------------------------------- | ----------------------------------------- | ------------------------------------------------------------------------------------- |
184
+ | `minIntervalMs` | `number` | `100` | Minimum delay between logs (ms). |
185
+ | `maxIntervalMs` | `number` | `1000` | Maximum delay between logs (ms). |
186
+ | `allowedLevels` | `LogLevel[]` | `['trace','debug','info','warn','error']` | Which levels may be emitted. |
187
+ | `eventRegistry` | `Partial<Record<LogLevel, string[]>>` | `{}` | Custom event name pools per level. If empty, random hacker‑style names are generated. |
188
+
189
+ ---
190
+
191
+ ## API Reference
192
+
193
+ ### `SystemLogger` Interface
194
+
195
+ | Method | Description |
196
+ | -------------------------------------------- | --------------------------------------------------------------------------- |
197
+ | `trace(event: string, data?: object): void` | Log at `trace` level. |
198
+ | `debug(event: string, data?: object): void` | Log at `debug` level. |
199
+ | `info(event: string, data?: object): void` | Log at `info` level. |
200
+ | `log(event: string, data?: object): void` | Alias for `info`. |
201
+ | `warn(event: string, data?: object): void` | Log at `warn` level. |
202
+ | `error(event: string, data?: unknown): void` | Log at `error` level. `data` can be an `Error` object (see Error handling). |
203
+ | `write(record: SystemLog): void` | Write a pre‑constructed `SystemLog` record directly. |
204
+ | `child(context: object): SystemLogger` | Create a child logger with additional context (merged over parent). |
205
+
206
+ ### `Logger` Class
207
+
208
+ The concrete implementation. Constructor:
209
+
210
+ ```typescript
211
+ new Logger(sinks: LogSink[], context?: object)
212
+ ```
213
+
214
+ All methods from `SystemLogger` are available.
215
+
216
+ ### `LogSink` Interface
217
+
218
+ ```typescript
219
+ interface LogSink {
220
+ write(record: SystemLog): void | Promise<void>;
221
+ }
222
+ ```
223
+
224
+ Implement this to create custom sinks (e.g., file, HTTP, Sentry, etc.).
225
+
226
+ ### `SystemLog` Structure
227
+
228
+ | Field | Type | Description |
229
+ | ----------- | ---------- | ---------------------------------------------------- |
230
+ | `level` | `LogLevel` | Severity level. |
231
+ | `event` | `string` | Distinct event name (e.g., `"user_login"`). |
232
+ | `data` | `object` | (Optional) Payload specific to the log. |
233
+ | `context` | `object` | (Optional) Static metadata from the logger instance. |
234
+ | `timestamp` | `number` | Unix timestamp in milliseconds (auto‑generated). |
235
+
236
+ ### `LogLevel`
237
+
238
+ ```typescript
239
+ type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
240
+ ```
241
+
242
+ Priority order (low to high): `trace` (10), `debug` (20), `info` (30), `warn` (40), `error` (50). The constant `LogLevelPriority` provides these numeric values.
243
+
244
+ ---
245
+
246
+ ## Error Handling
247
+
248
+ When you pass an `Error` object (or any subclass) to `logger.error()`, the logger automatically extracts structured information:
249
+
250
+ - For plain `Error`: it captures `name`, `message`, and `stack`.
251
+ - For `SystemError` (from `@asaidimu/utils-error`): it additionally extracts `code`, `category`, `severity`, `path`, `operation`, `issues`, `httpStatus`, `action`, and `cause`.
252
+
253
+ All extracted fields are placed under the `error` key in the log’s `data` property, ensuring consistent error reporting across your system.
254
+
255
+ ---
256
+
257
+ ## License
258
+
259
+ MIT © [Saidimu](https://github.com/asaidimu)
260
+
261
+ ---
262
+
263
+ ## Contributing & Issues
264
+
265
+ Found a bug or want to suggest an improvement? Please open an issue on the [GitHub repository](https://github.com/asaidimu/erp-utils/issues).
266
+
267
+ For more details, visit the [homepage](https://github.com/asaidimu/erp-utils/tree/main/src/logger).
package/index.d.mts ADDED
@@ -0,0 +1,334 @@
1
+ import { WebSocketServer } from 'ws';
2
+
3
+ /**
4
+ * Represents the severity level of a system log entry.
5
+ * Levels are ordered by increasing severity: trace, debug, info, warn, error.
6
+ */
7
+ type LogLevel = "trace" | "debug" | "info" | "warn" | "error";
8
+ /**
9
+ * Defines a destination where system logs are outputted or processed.
10
+ * Custom sinks (e.g., File, Logstash, Sentry) must implement this interface.
11
+ */
12
+ interface LogSink {
13
+ /**
14
+ * Dispatches a structured log entry to the underlying destination.
15
+ *
16
+ * @param record - The complete log object containing metadata and payload.
17
+ * @returns A void or Promise that resolves when the log has been safely handed off.
18
+ */
19
+ write(record: SystemLog): void | Promise<void>;
20
+ }
21
+ /**
22
+ * Structure representing a fully contextualized system log entry ready for sinking.
23
+ */
24
+ interface SystemLog {
25
+ /** The severity level of the log. */
26
+ level: LogLevel;
27
+ /** A clear, human-readable string identifying the distinct event (e.g., "user_login_failed"). */
28
+ event: string;
29
+ /** Additional structured data specific to this log instantiation. */
30
+ data?: object;
31
+ /** Contextual data shared across the logger instance (e.g., traceIds, environment). */
32
+ context?: object;
33
+ /** Epoch timestamp in milliseconds denoting when the log event occurred. */
34
+ timestamp: number;
35
+ }
36
+ /**
37
+ * Primary logger interface providing level-specific log dispatching and context-chaining.
38
+ */
39
+ interface SystemLogger {
40
+ /** Logs high-volume, extremely fine-grained diagnostic details. */
41
+ trace(event: string, data?: object): void;
42
+ /** Logs diagnostic information useful during local development or debugging. */
43
+ debug(event: string, data?: object): void;
44
+ /** Logs standard operational events that track the healthy flow of the system. */
45
+ info(event: string, data?: object): void;
46
+ /** Alias for the `info` logging method. */
47
+ log(event: string, data?: object): void;
48
+ /** Logs non-fatal operational anomalies or conditions that deserve attention. */
49
+ warn(event: string, data?: object): void;
50
+ /** Logs critical errors, failures, or exceptions preventing a transaction/process. */
51
+ error(event: string, data?: unknown): void;
52
+ /**
53
+ * Directly forwards a pre-constructed `SystemLog` record through the logger's pipeline.
54
+ * Combines instance context before outputting.
55
+ */
56
+ write(record: SystemLog): void;
57
+ /**
58
+ * Generates a new `SystemLogger` instance that shares the existing sinks and parent
59
+ * context, deeply merging the newly provided context on top.
60
+ *
61
+ * @param context - The metadata to append to all subsequent logs emitted by the child logger.
62
+ */
63
+ child(context: object): SystemLogger;
64
+ }
65
+ /**
66
+ * Numeric priority weights mapping to `LogLevel` values.
67
+ * Useful for filtering logs below a specific severity threshold.
68
+ */
69
+ declare const LogLevelPriority: Record<LogLevel, number>;
70
+ /**
71
+ * Concrete implementation of the `SystemLogger` interface.
72
+ * Handles active context-aggregation, standardized formatting of localized error payloads,
73
+ * and safe dispatch handling for downstream sinks.
74
+ */
75
+ declare class Logger implements SystemLogger {
76
+ private context;
77
+ private sink;
78
+ /**
79
+ * Initializes a new instance of the core Logger wrapper.
80
+ * * @param sinks - An array of outputs where logs generated by this instance will be sent.
81
+ * @param context - Base contextual metadata to affix across all downstream log events.
82
+ */
83
+ constructor(sinks: Array<LogSink>, context?: object);
84
+ /**
85
+ * Safely updates or assigns the core logging sink.
86
+ * Used internally to re-attach existing sink structures to spawned child logger instances.
87
+ */
88
+ private setSink;
89
+ /**
90
+ * Extracts structural tracking fields from standard JavaScript errors and advanced domain `SystemError` objects.
91
+ * Ensures call-stacks and metadata parameters map clean object parameters without blowing up standard logging pipelines.
92
+ * * @param err - The Error object or descendant instance to format.
93
+ * @returns An object payload mapped under standard keys ready for insertion into a log.
94
+ */
95
+ private extractErrorData;
96
+ /**
97
+ * Core dispatcher compiling standard schema variables, timestamps, contexts,
98
+ * and payloads prior to writing to the underlying `LogSink`.
99
+ * * @internal
100
+ */
101
+ private emit;
102
+ trace(event: string, data?: object): void;
103
+ debug(event: string, data?: object): void;
104
+ info(event: string, data?: object): void;
105
+ log(event: string, data?: object): void;
106
+ warn(event: string, data?: object): void;
107
+ error(event: string, data?: unknown): void;
108
+ /**
109
+ * Writes an externally built log record into the logging framework sink.
110
+ * Merges local logger metadata onto incoming payloads with priority leaning toward overriding parameters.
111
+ */
112
+ write(record: SystemLog): void;
113
+ /**
114
+ * Spawns a child logger instance carrying over pre-defined context parameters.
115
+ * Context configurations defined down-stream overwrite conflicting identifiers.
116
+ */
117
+ child(context: object): SystemLogger;
118
+ }
119
+
120
+ /** Standard system descriptor streams for console outputs. */
121
+ type ConsolePipe = "stdout" | "stderr";
122
+ /** Configuration options modifying behavior of the `ConsoleSink`. */
123
+ interface ConsoleSinkOptions {
124
+ /** Optional override mapping log levels to specific output pipes (`stdout` or `stderr`). */
125
+ pipeMap?: Partial<Record<LogLevel, ConsolePipe>>;
126
+ /** Custom transformation callback converting a `SystemLog` payload into a printable string string. */
127
+ format?: (record: SystemLog) => string;
128
+ }
129
+ /**
130
+ * A `LogSink` implementation that writes formatted log strings to terminal stdout/stderr channels.
131
+ * Automatically switches between runtime capabilities (Node.js `process.stdout` or generic global `console`).
132
+ */
133
+ declare class ConsoleSink implements LogSink {
134
+ private pipeMap;
135
+ private format;
136
+ /**
137
+ * Initializes a new instance of the `ConsoleSink`.
138
+ * * @param options - Configuration definitions for custom formats and piping targets.
139
+ */
140
+ constructor(options?: ConsoleSinkOptions);
141
+ /**
142
+ * Processes a log record and flushes it immediately to the runtime stream.
143
+ * Non-stringifiable context or data entries will fallback to standard JSON representations.
144
+ */
145
+ write(record: SystemLog): void;
146
+ }
147
+
148
+ /**
149
+ * Interface defining the shape of the EventBus.
150
+ * @template TEventMap - A record mapping event names to their respective payload types.
151
+ */
152
+ interface EventBus<TEventMap extends Record<string, any>> {
153
+ /**
154
+ * Subscribes to a specific event by name.
155
+ * @param eventName - The name of the event to subscribe to.
156
+ * @param callback - The function to call when the event is emitted.
157
+ * @param options - Extra options to determine the behaviour of the
158
+ * subscription
159
+ * @returns A function to unsubscribe from the event.
160
+ */
161
+ subscribe: <TEventName extends keyof TEventMap>(eventName: TEventName, callback: (payload: TEventMap[TEventName]) => void, options?: SubscribeOptions) => () => void;
162
+ /**
163
+ * Subscribes to an event and automatically unsubscribes after it fires once.
164
+ * @param eventName - The name of the event to subscribe to.
165
+ * @param callback - The function to call when the event is emitted.
166
+ * @returns A function to cancel the one-shot subscription before it fires.
167
+ */
168
+ once: <TEventName extends keyof TEventMap>(eventName: TEventName, callback: (payload: TEventMap[TEventName]) => void, options?: SubscribeOptions) => () => void;
169
+ /**
170
+ * Emits an event with a payload to all subscribed listeners.
171
+ * @param event - An object containing the event name and payload.
172
+ */
173
+ emit: <TEventName extends keyof TEventMap>(event: {
174
+ name: TEventName;
175
+ payload: TEventMap[TEventName];
176
+ }) => void;
177
+ /**
178
+ * Retrieves metrics about event bus usage.
179
+ * @returns An object containing various metrics.
180
+ */
181
+ metrics: () => EventMetrics;
182
+ /**
183
+ * Clears all subscriptions and resets metrics.
184
+ *
185
+ * After calling `clear()`, the bus is fully reset and can be reused
186
+ * cross-tab communication is re-established if it was previously enabled.
187
+ *
188
+ * @param options - Optional configuration object.
189
+ * @param options.permanent - If `true`, the bus becomes permanently unusable after clearing.
190
+ * Defaults to `false`.
191
+ * @returns {void}
192
+ */
193
+ clear: (options?: {
194
+ permanent?: boolean;
195
+ }) => void;
196
+ }
197
+ /**
198
+ * Interface defining the metrics tracked by the EventBus.
199
+ */
200
+ interface EventMetrics {
201
+ /** Total number of events emitted (both sync and deferred paths). */
202
+ totalEvents: number;
203
+ /** Number of active subscriptions across all event names. */
204
+ activeSubscriptions: number;
205
+ /** Map of event names to their emission counts. */
206
+ eventCounts: Map<string, number>;
207
+ /** Average duration of event dispatch in milliseconds. */
208
+ averageEmitDuration: number;
209
+ }
210
+ interface SubscribeOptions {
211
+ /**
212
+ * Debounce delay in milliseconds. When multiple events arrive in quick
213
+ * succession, the callback runs only after the quiet period ends, using the
214
+ * latest payload. Default = no debouncing.
215
+ */
216
+ debounce?: number;
217
+ }
218
+
219
+ /**
220
+ * Configuration options for the EventBusSink when routing all logs to a single,
221
+ * static event channel on the EventBus.
222
+ */
223
+ interface StaticRouteOptions<TEventMap extends Record<string, any>, TEventName extends keyof TEventMap> {
224
+ /** The fixed event name on the bus where all logs will be published. */
225
+ event: TEventName;
226
+ /** * Transforms the `SystemLog` into the format expected by the target event's payload.
227
+ * If omitted, the raw `SystemLog` is passed (requires type compatibility).
228
+ */
229
+ map?: (record: SystemLog) => TEventMap[TEventName];
230
+ }
231
+ /**
232
+ * Configuration options for the EventBusSink when routing logs dynamically
233
+ * across various event channels based on log record properties.
234
+ */
235
+ interface DynamicRouteOptions<TEventMap extends Record<string, any>> {
236
+ /** A resolver callback that determines which event channel on the bus to target for a given log. */
237
+ resolve: (record: SystemLog) => keyof TEventMap;
238
+ /** * Transforms the `SystemLog` into the payload format expected by the resolved event channel.
239
+ * If omitted, the raw `SystemLog` is forwarded.
240
+ */
241
+ map?: (record: SystemLog, eventName: keyof TEventMap) => TEventMap[keyof TEventMap];
242
+ }
243
+ /**
244
+ * A `LogSink` implementation that translates and forwards `SystemLog` records
245
+ * into an application-wide or cross-tab `EventBus`.
246
+ * * @template TEventMap - The schema defining available event names and payloads on the target bus.
247
+ */
248
+ declare class EventBusSink<TEventMap extends Record<string, any>> implements LogSink {
249
+ private eventBus;
250
+ private resolveEventName;
251
+ private mapPayload;
252
+ /**
253
+ * Initializes the EventBusSink using a static event channel definition.
254
+ */
255
+ constructor(eventBus: EventBus<TEventMap>, options: StaticRouteOptions<TEventMap, keyof TEventMap>);
256
+ /**
257
+ * Initializes the EventBusSink using a dynamic event resolution function.
258
+ */
259
+ constructor(eventBus: EventBus<TEventMap>, options: DynamicRouteOptions<TEventMap>);
260
+ /**
261
+ * Dispatches the incoming system log to the configured EventBus channel.
262
+ * Wraps operations in a guard block to ensure event bus payload mapping anomalies
263
+ * or downstream listener execution crashes do not disrupt the critical logger pathway.
264
+ * * @param record - The structural log entry processed by the parent logger.
265
+ */
266
+ write(record: SystemLog): void;
267
+ }
268
+
269
+ type FuzzEventRegistry = Record<LogLevel, string[]>;
270
+ interface FakerFuzzOptions {
271
+ minIntervalMs?: number;
272
+ maxIntervalMs?: number;
273
+ allowedLevels?: LogLevel[];
274
+ eventRegistry?: Partial<FuzzEventRegistry>;
275
+ }
276
+ declare class Fuzz {
277
+ private logger;
278
+ private minIntervalMs;
279
+ private maxIntervalMs;
280
+ private allowedLevels;
281
+ private eventRegistry;
282
+ private timer;
283
+ private isRunning;
284
+ constructor(targetLogger: SystemLogger, options?: FakerFuzzOptions);
285
+ start(): void;
286
+ stop(): void;
287
+ private scheduleNextTick;
288
+ private getEventName;
289
+ private emitRandomLog;
290
+ }
291
+
292
+ /**
293
+ * Configuration options for the UnsecureWebSocketServerSink.
294
+ */
295
+ interface UnsecureWebSocketSinkOptions {
296
+ /**
297
+ * An optional filter function to determine if a log should be broadcasted.
298
+ */
299
+ filter?: (record: SystemLog) => boolean;
300
+ /**
301
+ * Custom serialization function to transform the log before wire transmission.
302
+ * Defaults to standard `JSON.stringify`.
303
+ */
304
+ serialize?: (record: SystemLog) => string;
305
+ }
306
+ /**
307
+ * A `LogSink` implementation that broadcasts structured system logs in real-time
308
+ * to all connected WebSocket clients without verifying credentials.
309
+ * * @deprecated **SECURITY WARNING:** This sink performs no authentication or token validation.
310
+ * Do not expose this server to the public internet. Use exclusively for local development
311
+ * or behind heavily isolated VPC/internal network infrastructure.
312
+ */
313
+ declare class UnsecureWebSocketServerSink implements LogSink {
314
+ private wss;
315
+ private filter?;
316
+ private serialize;
317
+ /**
318
+ * @param wss - An instantiated and running WebSocketServer instance.
319
+ * @param options - Configuration options for filtering and formatting the socket stream.
320
+ */
321
+ constructor(wss: WebSocketServer, options?: UnsecureWebSocketSinkOptions);
322
+ /**
323
+ * Broadcasts the incoming system log to all open, unauthenticated WebSocket clients.
324
+ * * @param record - The structural log entry processed by the parent logger.
325
+ */
326
+ write(record: SystemLog): void;
327
+ private handleClientError;
328
+ /**
329
+ * Periodically checks for and prunes "ghost" connections.
330
+ */
331
+ private initializeHeartbeat;
332
+ }
333
+
334
+ export { type ConsolePipe, ConsoleSink, type ConsoleSinkOptions, type DynamicRouteOptions, EventBusSink, type FakerFuzzOptions, Fuzz, type FuzzEventRegistry, type LogLevel, LogLevelPriority, type LogSink, Logger, type StaticRouteOptions, type SystemLog, type SystemLogger, UnsecureWebSocketServerSink, type UnsecureWebSocketSinkOptions };