superjs-core 0.3.3 → 0.3.4
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/dist/error/index.d.ts +148 -0
- package/dist/error/index.js +115 -0
- package/dist/error/index.js.map +1 -0
- package/dist/index-BgG21uJC.d.ts +166 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +506 -0
- package/dist/index.js.map +1 -1
- package/dist/logger/index.d.ts +1 -0
- package/dist/logger/index.js +214 -0
- package/dist/logger/index.js.map +1 -0
- package/dist/logger/transports.d.ts +1 -0
- package/dist/logger/transports.js +122 -0
- package/dist/logger/transports.js.map +1 -0
- package/dist/validation/index.d.ts +106 -0
- package/dist/validation/index.js +183 -0
- package/dist/validation/index.js.map +1 -0
- package/package.json +17 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { h as LogFn, L as LogLevel, a as Logger, i as LoggerOptions, T as Transport, c as consoleTransport, b as createBufferedTransport, d as createConsoleTransport, e as createFileTransport, f as createJsonTransport, l as logger } from '../index-BgG21uJC.js';
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
+
}) : x)(function(x) {
|
|
4
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
// src/logger/logger.ts
|
|
9
|
+
var LEVEL_ORDER = { debug: 0, info: 1, warn: 2, error: 3 };
|
|
10
|
+
var Logger = class _Logger {
|
|
11
|
+
_level;
|
|
12
|
+
_name;
|
|
13
|
+
_transport;
|
|
14
|
+
_extraMeta;
|
|
15
|
+
constructor(options) {
|
|
16
|
+
this._level = options?.level ?? "info";
|
|
17
|
+
this._name = options?.name;
|
|
18
|
+
this._transport = options?.transport ?? consoleTransport;
|
|
19
|
+
this._extraMeta = /* @__PURE__ */ Object.create(null);
|
|
20
|
+
}
|
|
21
|
+
_shouldLog(target) {
|
|
22
|
+
return LEVEL_ORDER[this._level] <= LEVEL_ORDER[target];
|
|
23
|
+
}
|
|
24
|
+
_log(level, message, meta) {
|
|
25
|
+
if (level !== "error" && !this._shouldLog(level)) return;
|
|
26
|
+
const merged = /* @__PURE__ */ Object.create(null);
|
|
27
|
+
for (const key of Object.keys(this._extraMeta)) {
|
|
28
|
+
merged[key] = this._extraMeta[key];
|
|
29
|
+
}
|
|
30
|
+
if (meta !== void 0) {
|
|
31
|
+
for (const key of Object.keys(meta)) {
|
|
32
|
+
merged[key] = meta[key];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const label = this._name !== void 0 ? `[${this._name}] ${message}` : message;
|
|
36
|
+
const finalMeta = Object.keys(merged).length > 0 ? merged : void 0;
|
|
37
|
+
this._transport.log(level, label, finalMeta);
|
|
38
|
+
}
|
|
39
|
+
/** Log at `debug` level. Only emitted when the current level is `'debug'`. */
|
|
40
|
+
debug = (message, meta) => this._log("debug", message, meta);
|
|
41
|
+
/** Log at `info` level. Emitted when level is `'debug'` or `'info'`. */
|
|
42
|
+
info = (message, meta) => this._log("info", message, meta);
|
|
43
|
+
/** Log at `warn` level. Emitted when level is `'debug'`, `'info'`, or `'warn'`. */
|
|
44
|
+
warn = (message, meta) => this._log("warn", message, meta);
|
|
45
|
+
/** Log at `error` level. Always emitted regardless of current level. */
|
|
46
|
+
error = (message, meta) => this._log("error", message, meta);
|
|
47
|
+
/**
|
|
48
|
+
* Creates a child logger that inherits the parent's level, name, and transport,
|
|
49
|
+
* but merges `extraMeta` into every log call. Child metadata is shallow-merged
|
|
50
|
+
* on top of the parent's inherited metadata.
|
|
51
|
+
*
|
|
52
|
+
* @param extraMeta - Additional context to include in every log entry.
|
|
53
|
+
*/
|
|
54
|
+
child(extraMeta) {
|
|
55
|
+
const child = new _Logger({
|
|
56
|
+
level: this._level,
|
|
57
|
+
name: this._name,
|
|
58
|
+
transport: this._transport
|
|
59
|
+
});
|
|
60
|
+
const inherited = /* @__PURE__ */ Object.create(null);
|
|
61
|
+
for (const key of Object.keys(this._extraMeta)) {
|
|
62
|
+
inherited[key] = this._extraMeta[key];
|
|
63
|
+
}
|
|
64
|
+
for (const key of Object.keys(extraMeta)) {
|
|
65
|
+
inherited[key] = extraMeta[key];
|
|
66
|
+
}
|
|
67
|
+
child._extraMeta = inherited;
|
|
68
|
+
return child;
|
|
69
|
+
}
|
|
70
|
+
/** Updates the minimum log level for this instance. */
|
|
71
|
+
setLevel(level) {
|
|
72
|
+
this._level = level;
|
|
73
|
+
}
|
|
74
|
+
/** Returns the current minimum log level. */
|
|
75
|
+
getLevel() {
|
|
76
|
+
return this._level;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Creates a new named Logger.
|
|
80
|
+
* Convenience shorthand for `new Logger({ ...options, name })`.
|
|
81
|
+
*
|
|
82
|
+
* @param name - The name tag shown in log output.
|
|
83
|
+
* @param options - Additional configuration.
|
|
84
|
+
*/
|
|
85
|
+
static create(name, options) {
|
|
86
|
+
return new _Logger({ ...options, name });
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
var consoleTransport = {
|
|
90
|
+
log(level, message, meta) {
|
|
91
|
+
const metaStr = meta !== void 0 && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : "";
|
|
92
|
+
console.log(`[${level.toUpperCase()}] ${message}${metaStr}`);
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
var logger = new Logger();
|
|
96
|
+
|
|
97
|
+
// src/logger/transports.ts
|
|
98
|
+
var LEVEL_COLORS = {
|
|
99
|
+
debug: "\x1B[90m",
|
|
100
|
+
info: "\x1B[34m",
|
|
101
|
+
warn: "\x1B[33m",
|
|
102
|
+
error: "\x1B[31m"
|
|
103
|
+
};
|
|
104
|
+
var RESET = "\x1B[0m";
|
|
105
|
+
function createConsoleTransport(options) {
|
|
106
|
+
const useColors = options?.colors !== false;
|
|
107
|
+
const showTimestamp = options?.timestamp ?? false;
|
|
108
|
+
return {
|
|
109
|
+
log(level, message, meta) {
|
|
110
|
+
const parts = [];
|
|
111
|
+
if (showTimestamp) {
|
|
112
|
+
parts.push((/* @__PURE__ */ new Date()).toISOString());
|
|
113
|
+
}
|
|
114
|
+
if (useColors) {
|
|
115
|
+
const color = LEVEL_COLORS[level];
|
|
116
|
+
parts.push(`${color}[${level.toUpperCase()}]${RESET}`);
|
|
117
|
+
} else {
|
|
118
|
+
parts.push(`[${level.toUpperCase()}]`);
|
|
119
|
+
}
|
|
120
|
+
parts.push(message);
|
|
121
|
+
if (meta !== void 0 && Object.keys(meta).length > 0) {
|
|
122
|
+
parts.push(JSON.stringify(meta));
|
|
123
|
+
}
|
|
124
|
+
console.log(parts.join(" "));
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function createJsonTransport(options) {
|
|
129
|
+
const writeStream = options?.stream ?? (typeof process !== "undefined" && typeof process.stdout !== "undefined" && typeof process.stdout.write === "function" ? process.stdout : void 0);
|
|
130
|
+
return {
|
|
131
|
+
log(level, message, meta) {
|
|
132
|
+
const entry = {
|
|
133
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
134
|
+
level,
|
|
135
|
+
message
|
|
136
|
+
};
|
|
137
|
+
if (meta !== void 0 && Object.keys(meta).length > 0) {
|
|
138
|
+
entry.meta = meta;
|
|
139
|
+
}
|
|
140
|
+
const line = JSON.stringify(entry);
|
|
141
|
+
if (writeStream !== void 0) {
|
|
142
|
+
writeStream.write(line + "\n");
|
|
143
|
+
} else {
|
|
144
|
+
console.log(line);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
function createFileTransport(filename, _options) {
|
|
150
|
+
let fs = null;
|
|
151
|
+
try {
|
|
152
|
+
if (typeof process !== "undefined" && process.versions?.node) {
|
|
153
|
+
const m = __require("fs");
|
|
154
|
+
fs = m;
|
|
155
|
+
}
|
|
156
|
+
} catch {
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
log(level, message, meta) {
|
|
160
|
+
if (fs === null) return;
|
|
161
|
+
const metaStr = meta !== void 0 && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : "";
|
|
162
|
+
const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] [${level.toUpperCase()}] ${message}${metaStr}
|
|
163
|
+
`;
|
|
164
|
+
try {
|
|
165
|
+
fs.appendFileSync(filename, line);
|
|
166
|
+
} catch {
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
function createBufferedTransport(transport, options) {
|
|
172
|
+
const maxSize = options?.maxSize ?? 100;
|
|
173
|
+
const flushIntervalMs = options?.flushIntervalMs ?? 5e3;
|
|
174
|
+
const buffer = [];
|
|
175
|
+
let timer;
|
|
176
|
+
function flush() {
|
|
177
|
+
if (timer !== void 0) {
|
|
178
|
+
clearTimeout(timer);
|
|
179
|
+
timer = void 0;
|
|
180
|
+
}
|
|
181
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
182
|
+
const entry = buffer[i];
|
|
183
|
+
transport.log(entry.level, entry.message, entry.meta);
|
|
184
|
+
}
|
|
185
|
+
buffer.length = 0;
|
|
186
|
+
}
|
|
187
|
+
function scheduleFlush() {
|
|
188
|
+
if (timer !== void 0 || flushIntervalMs <= 0) return;
|
|
189
|
+
timer = setTimeout(() => {
|
|
190
|
+
timer = void 0;
|
|
191
|
+
flush();
|
|
192
|
+
}, flushIntervalMs);
|
|
193
|
+
}
|
|
194
|
+
return {
|
|
195
|
+
log(level, message, meta) {
|
|
196
|
+
buffer.push({ level, message, meta });
|
|
197
|
+
if (buffer.length >= maxSize) {
|
|
198
|
+
flush();
|
|
199
|
+
} else {
|
|
200
|
+
scheduleFlush();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
export {
|
|
206
|
+
Logger,
|
|
207
|
+
consoleTransport,
|
|
208
|
+
createBufferedTransport,
|
|
209
|
+
createConsoleTransport,
|
|
210
|
+
createFileTransport,
|
|
211
|
+
createJsonTransport,
|
|
212
|
+
logger
|
|
213
|
+
};
|
|
214
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/logger/logger.ts","../../src/logger/transports.ts"],"sourcesContent":["/**\n * Represents the severity level of a log entry.\n * Ordered from least to most severe: debug < info < warn < error.\n */\nexport type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\n/**\n * Log function signature bound to a specific severity level.\n */\nexport type LogFn = (message: string, meta?: Record<string, unknown>) => void\n\n/**\n * Configuration options for creating a Logger instance.\n */\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info'). */\n level?: LogLevel\n /** Optional name tag prepended to every message as `[name]`. */\n name?: string\n /** Custom transport; defaults to {@link consoleTransport}. */\n transport?: Transport\n}\n\n/**\n * A transport handles the formatted output of log entries.\n * Implementations write to stdout, files, buffers, or remote services.\n */\nexport interface Transport {\n log(level: LogLevel, message: string, meta?: Record<string, unknown>): void\n}\n\nconst LEVEL_ORDER: Record<LogLevel, number> = { debug: 0, info: 1, warn: 2, error: 3 }\n\n/**\n * Structured logger with level filtering, child loggers, and pluggable transport.\n *\n * @example\n * ```ts\n * const log = new Logger({ level: 'debug', name: 'app' })\n * log.info('server started', { port: 3000 })\n *\n * const child = log.child({ requestId: 'abc-123' })\n * child.warn('slow query', { durationMs: 450 })\n * ```\n */\nexport class Logger {\n private _level: LogLevel\n private _name?: string\n private _transport: Transport\n private _extraMeta: Record<string, unknown>\n\n constructor(options?: LoggerOptions) {\n this._level = options?.level ?? 'info'\n this._name = options?.name\n this._transport = options?.transport ?? consoleTransport\n this._extraMeta = Object.create(null)\n }\n\n private _shouldLog(target: LogLevel): boolean {\n return LEVEL_ORDER[this._level] <= LEVEL_ORDER[target]\n }\n\n private _log(level: LogLevel, message: string, meta?: Record<string, unknown>): void {\n if (level !== 'error' && !this._shouldLog(level)) return\n\n const merged: Record<string, unknown> = Object.create(null)\n for (const key of Object.keys(this._extraMeta)) {\n merged[key] = (this._extraMeta as Record<string, unknown>)[key]!\n }\n if (meta !== undefined) {\n for (const key of Object.keys(meta)) {\n merged[key] = meta[key]!\n }\n }\n\n const label = this._name !== undefined ? `[${this._name}] ${message}` : message\n const finalMeta = Object.keys(merged).length > 0 ? merged : undefined\n this._transport.log(level, label, finalMeta)\n }\n\n /** Log at `debug` level. Only emitted when the current level is `'debug'`. */\n debug: LogFn = (message, meta?) => this._log('debug', message, meta)\n\n /** Log at `info` level. Emitted when level is `'debug'` or `'info'`. */\n info: LogFn = (message, meta?) => this._log('info', message, meta)\n\n /** Log at `warn` level. Emitted when level is `'debug'`, `'info'`, or `'warn'`. */\n warn: LogFn = (message, meta?) => this._log('warn', message, meta)\n\n /** Log at `error` level. Always emitted regardless of current level. */\n error: LogFn = (message, meta?) => this._log('error', message, meta)\n\n /**\n * Creates a child logger that inherits the parent's level, name, and transport,\n * but merges `extraMeta` into every log call. Child metadata is shallow-merged\n * on top of the parent's inherited metadata.\n *\n * @param extraMeta - Additional context to include in every log entry.\n */\n child(extraMeta: Record<string, unknown>): Logger {\n const child = new Logger({\n level: this._level,\n name: this._name,\n transport: this._transport,\n })\n const inherited: Record<string, unknown> = Object.create(null)\n for (const key of Object.keys(this._extraMeta)) {\n inherited[key] = (this._extraMeta as Record<string, unknown>)[key]!\n }\n for (const key of Object.keys(extraMeta)) {\n inherited[key] = extraMeta[key]!\n }\n child._extraMeta = inherited\n return child\n }\n\n /** Updates the minimum log level for this instance. */\n setLevel(level: LogLevel): void {\n this._level = level\n }\n\n /** Returns the current minimum log level. */\n getLevel(): LogLevel {\n return this._level\n }\n\n /**\n * Creates a new named Logger.\n * Convenience shorthand for `new Logger({ ...options, name })`.\n *\n * @param name - The name tag shown in log output.\n * @param options - Additional configuration.\n */\n static create(name: string, options?: LoggerOptions): Logger {\n return new Logger({ ...options, name })\n }\n}\n\n/**\n * Default transport that writes formatted log lines to `console.log`.\n *\n * Output format: `[LEVEL] message {meta}`\n *\n * When a logger has a name, the format becomes: `[LEVEL] [name] message {meta}`\n */\nexport const consoleTransport: Transport = {\n log(level, message, meta) {\n const metaStr =\n meta !== undefined && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : ''\n console.log(`[${level.toUpperCase()}] ${message}${metaStr}`)\n },\n}\n\n/**\n * Default logger instance at `'info'` level with no name.\n */\nexport const logger: Logger = new Logger()\n","import type { LogLevel } from './logger.js'\n\n/**\n * A transport handles the formatted output of log entries.\n */\nexport interface Transport {\n log(level: LogLevel, message: string, meta?: Record<string, unknown>): void\n}\n\nconst LEVEL_COLORS: Record<LogLevel, string> = {\n debug: '\\x1b[90m',\n info: '\\x1b[34m',\n warn: '\\x1b[33m',\n error: '\\x1b[31m',\n}\n\nconst RESET = '\\x1b[0m'\n\n/**\n * Creates a console transport that writes formatted log lines to `console.log`.\n *\n * The level prefix is optionally colored using ANSI escape codes:\n * - `debug` → gray\n * - `info` → blue\n * - `warn` → yellow\n * - `error` → red\n *\n * @param options - Configuration for the console transport.\n * @param options.colors - Enable ANSI color output (default: `true`).\n * @param options.timestamp - Prepend an ISO-8601 timestamp (default: `false`).\n */\nexport function createConsoleTransport(options?: {\n colors?: boolean\n timestamp?: boolean\n}): Transport {\n const useColors = options?.colors !== false\n const showTimestamp = options?.timestamp ?? false\n\n return {\n log(level, message, meta) {\n const parts: string[] = []\n\n if (showTimestamp) {\n parts.push(new Date().toISOString())\n }\n\n if (useColors) {\n const color = LEVEL_COLORS[level]\n parts.push(`${color}[${level.toUpperCase()}]${RESET}`)\n } else {\n parts.push(`[${level.toUpperCase()}]`)\n }\n\n parts.push(message)\n\n if (meta !== undefined && Object.keys(meta).length > 0) {\n parts.push(JSON.stringify(meta))\n }\n\n console.log(parts.join(' '))\n },\n }\n}\n\n/**\n * Creates a transport that outputs structured JSON lines.\n *\n * Each log entry is serialized as a single JSON object with\n * `timestamp`, `level`, `message`, and optional `meta` fields.\n *\n * @param options - Configuration for the JSON transport.\n * @param options.stream - A writable stream (e.g. `process.stdout`).\n * Defaults to `process.stdout` in Node.js, falls\n * back to `console.log` in browsers.\n */\nexport function createJsonTransport(options?: {\n stream?: { write(data: string): void }\n}): Transport {\n const writeStream =\n options?.stream ??\n (typeof process !== 'undefined' &&\n typeof process.stdout !== 'undefined' &&\n typeof process.stdout.write === 'function'\n ? (process.stdout as { write(data: string): void })\n : undefined)\n\n return {\n log(level, message, meta) {\n const entry: Record<string, unknown> = {\n timestamp: new Date().toISOString(),\n level,\n message,\n }\n if (meta !== undefined && Object.keys(meta).length > 0) {\n entry.meta = meta\n }\n const line = JSON.stringify(entry)\n if (writeStream !== undefined) {\n writeStream.write(line + '\\n')\n } else {\n console.log(line)\n }\n },\n }\n}\n\n/**\n * Creates a transport that appends log entries to a file.\n *\n * Each line is formatted as: `[timestamp] [LEVEL] message {meta}`\n *\n * ⚠️ Node.js only. Silently discards log entries when `fs` is unavailable\n * (browsers, Deno, Bun — though Bun supports `fs`).\n *\n * @param filename - Path to the log file.\n * @param options - Configuration for the file transport.\n * @param options.maxSize - Maximum file size in bytes before rotation\n * (default: 10 MB). **Note:** rotation is not\n * yet implemented; this is reserved for future use.\n */\nexport function createFileTransport(\n filename: string,\n _options?: { maxSize?: number },\n): Transport {\n // Try to resolve fs synchronously at construction time\n // Uses process.versions.node as a heuristic for Node.js environment\n let fs: { appendFileSync: (path: string, data: string) => void } | null = null\n try {\n if (typeof process !== 'undefined' && process.versions?.node) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const m = require('fs') as { appendFileSync: (path: string, data: string) => void }\n fs = m\n }\n } catch {\n // fs unavailable (browser, edge runtime)\n }\n\n return {\n log(level, message, meta) {\n if (fs === null) return\n\n const metaStr =\n meta !== undefined && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : ''\n const line = `[${new Date().toISOString()}] [${level.toUpperCase()}] ${message}${metaStr}\\n`\n\n try {\n fs.appendFileSync(filename, line)\n } catch {\n // Silently drop if write fails (disk full, permissions, etc.)\n }\n },\n }\n}\n\n/**\n * Creates a buffered transport that batches log entries and flushes them\n * to the underlying transport when either the buffer size or flush interval\n * is reached (whichever comes first).\n *\n * Useful for reducing I/O pressure in high-throughput scenarios.\n *\n * @param transport - The underlying transport to flush to.\n * @param options - Configuration for the buffer.\n * @param options.maxSize - Maximum number of entries before forced flush\n * (default: 100).\n * @param options.flushIntervalMs - How often to auto-flush in milliseconds\n * (default: 5000). Set to `0` to disable\n * interval flushing.\n */\nexport function createBufferedTransport(\n transport: Transport,\n options?: { maxSize?: number; flushIntervalMs?: number },\n): Transport {\n const maxSize = options?.maxSize ?? 100\n const flushIntervalMs = options?.flushIntervalMs ?? 5000\n\n const buffer: Array<{\n level: LogLevel\n message: string\n meta?: Record<string, unknown>\n }> = []\n\n let timer: ReturnType<typeof setTimeout> | undefined\n\n function flush(): void {\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n for (let i = 0; i < buffer.length; i++) {\n const entry = buffer[i]!\n transport.log(entry.level, entry.message, entry.meta)\n }\n buffer.length = 0\n }\n\n function scheduleFlush(): void {\n if (timer !== undefined || flushIntervalMs <= 0) return\n timer = setTimeout((): void => {\n timer = undefined\n flush()\n }, flushIntervalMs)\n }\n\n return {\n log(level, message, meta) {\n buffer.push({ level, message, meta })\n if (buffer.length >= maxSize) {\n flush()\n } else {\n scheduleFlush()\n }\n },\n }\n}\n"],"mappings":";;;;;;;;AA+BA,IAAM,cAAwC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,EAAE;AAc9E,IAAM,SAAN,MAAM,QAAO;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,YAAY,SAAyB;AACnC,SAAK,SAAS,SAAS,SAAS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SAAS,IAAI,IAAI,KAAK,UAAU,IAAI,CAAC,KAAK;AACpF,YAAM,OAAO,KAAI,oBAAI,KAAK,GAAE,YAAY,CAAC,MAAM,MAAM,YAAY,CAAC,KAAK,OAAO,GAAG,OAAO;AAAA;AAExF,UAAI;AACF,WAAG,eAAe,UAAU,IAAI;AAAA,MAClC,QAAQ;AAAA,MAER;AAAA,IACF;AAAA,EACF;AACF;AAiBO,SAAS,wBACd,WACA,SACW;AACX,QAAM,UAAU,SAAS,WAAW;AACpC,QAAM,kBAAkB,SAAS,mBAAmB;AAEpD,QAAM,SAID,CAAC;AAEN,MAAI;AAEJ,WAAS,QAAc;AACrB,QAAI,UAAU,QAAW;AACvB,mBAAa,KAAK;AAClB,cAAQ;AAAA,IACV;AACA,aAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,YAAM,QAAQ,OAAO,CAAC;AACtB,gBAAU,IAAI,MAAM,OAAO,MAAM,SAAS,MAAM,IAAI;AAAA,IACtD;AACA,WAAO,SAAS;AAAA,EAClB;AAEA,WAAS,gBAAsB;AAC7B,QAAI,UAAU,UAAa,mBAAmB,EAAG;AACjD,YAAQ,WAAW,MAAY;AAC7B,cAAQ;AACR,YAAM;AAAA,IACR,GAAG,eAAe;AAAA,EACpB;AAEA,SAAO;AAAA,IACL,IAAI,OAAO,SAAS,MAAM;AACxB,aAAO,KAAK,EAAE,OAAO,SAAS,KAAK,CAAC;AACpC,UAAI,OAAO,UAAU,SAAS;AAC5B,cAAM;AAAA,MACR,OAAO;AACL,sBAAc;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { g as Transport, b as createBufferedTransport, d as createConsoleTransport, e as createFileTransport, f as createJsonTransport } from '../index-BgG21uJC.js';
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
2
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
3
|
+
}) : x)(function(x) {
|
|
4
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
5
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
// src/logger/transports.ts
|
|
9
|
+
var LEVEL_COLORS = {
|
|
10
|
+
debug: "\x1B[90m",
|
|
11
|
+
info: "\x1B[34m",
|
|
12
|
+
warn: "\x1B[33m",
|
|
13
|
+
error: "\x1B[31m"
|
|
14
|
+
};
|
|
15
|
+
var RESET = "\x1B[0m";
|
|
16
|
+
function createConsoleTransport(options) {
|
|
17
|
+
const useColors = options?.colors !== false;
|
|
18
|
+
const showTimestamp = options?.timestamp ?? false;
|
|
19
|
+
return {
|
|
20
|
+
log(level, message, meta) {
|
|
21
|
+
const parts = [];
|
|
22
|
+
if (showTimestamp) {
|
|
23
|
+
parts.push((/* @__PURE__ */ new Date()).toISOString());
|
|
24
|
+
}
|
|
25
|
+
if (useColors) {
|
|
26
|
+
const color = LEVEL_COLORS[level];
|
|
27
|
+
parts.push(`${color}[${level.toUpperCase()}]${RESET}`);
|
|
28
|
+
} else {
|
|
29
|
+
parts.push(`[${level.toUpperCase()}]`);
|
|
30
|
+
}
|
|
31
|
+
parts.push(message);
|
|
32
|
+
if (meta !== void 0 && Object.keys(meta).length > 0) {
|
|
33
|
+
parts.push(JSON.stringify(meta));
|
|
34
|
+
}
|
|
35
|
+
console.log(parts.join(" "));
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function createJsonTransport(options) {
|
|
40
|
+
const writeStream = options?.stream ?? (typeof process !== "undefined" && typeof process.stdout !== "undefined" && typeof process.stdout.write === "function" ? process.stdout : void 0);
|
|
41
|
+
return {
|
|
42
|
+
log(level, message, meta) {
|
|
43
|
+
const entry = {
|
|
44
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
45
|
+
level,
|
|
46
|
+
message
|
|
47
|
+
};
|
|
48
|
+
if (meta !== void 0 && Object.keys(meta).length > 0) {
|
|
49
|
+
entry.meta = meta;
|
|
50
|
+
}
|
|
51
|
+
const line = JSON.stringify(entry);
|
|
52
|
+
if (writeStream !== void 0) {
|
|
53
|
+
writeStream.write(line + "\n");
|
|
54
|
+
} else {
|
|
55
|
+
console.log(line);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
function createFileTransport(filename, _options) {
|
|
61
|
+
let fs = null;
|
|
62
|
+
try {
|
|
63
|
+
if (typeof process !== "undefined" && process.versions?.node) {
|
|
64
|
+
const m = __require("fs");
|
|
65
|
+
fs = m;
|
|
66
|
+
}
|
|
67
|
+
} catch {
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
log(level, message, meta) {
|
|
71
|
+
if (fs === null) return;
|
|
72
|
+
const metaStr = meta !== void 0 && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : "";
|
|
73
|
+
const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] [${level.toUpperCase()}] ${message}${metaStr}
|
|
74
|
+
`;
|
|
75
|
+
try {
|
|
76
|
+
fs.appendFileSync(filename, line);
|
|
77
|
+
} catch {
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function createBufferedTransport(transport, options) {
|
|
83
|
+
const maxSize = options?.maxSize ?? 100;
|
|
84
|
+
const flushIntervalMs = options?.flushIntervalMs ?? 5e3;
|
|
85
|
+
const buffer = [];
|
|
86
|
+
let timer;
|
|
87
|
+
function flush() {
|
|
88
|
+
if (timer !== void 0) {
|
|
89
|
+
clearTimeout(timer);
|
|
90
|
+
timer = void 0;
|
|
91
|
+
}
|
|
92
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
93
|
+
const entry = buffer[i];
|
|
94
|
+
transport.log(entry.level, entry.message, entry.meta);
|
|
95
|
+
}
|
|
96
|
+
buffer.length = 0;
|
|
97
|
+
}
|
|
98
|
+
function scheduleFlush() {
|
|
99
|
+
if (timer !== void 0 || flushIntervalMs <= 0) return;
|
|
100
|
+
timer = setTimeout(() => {
|
|
101
|
+
timer = void 0;
|
|
102
|
+
flush();
|
|
103
|
+
}, flushIntervalMs);
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
log(level, message, meta) {
|
|
107
|
+
buffer.push({ level, message, meta });
|
|
108
|
+
if (buffer.length >= maxSize) {
|
|
109
|
+
flush();
|
|
110
|
+
} else {
|
|
111
|
+
scheduleFlush();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
export {
|
|
117
|
+
createBufferedTransport,
|
|
118
|
+
createConsoleTransport,
|
|
119
|
+
createFileTransport,
|
|
120
|
+
createJsonTransport
|
|
121
|
+
};
|
|
122
|
+
//# sourceMappingURL=transports.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/logger/transports.ts"],"sourcesContent":["import type { LogLevel } from './logger.js'\n\n/**\n * A transport handles the formatted output of log entries.\n */\nexport interface Transport {\n log(level: LogLevel, message: string, meta?: Record<string, unknown>): void\n}\n\nconst LEVEL_COLORS: Record<LogLevel, string> = {\n debug: '\\x1b[90m',\n info: '\\x1b[34m',\n warn: '\\x1b[33m',\n error: '\\x1b[31m',\n}\n\nconst RESET = '\\x1b[0m'\n\n/**\n * Creates a console transport that writes formatted log lines to `console.log`.\n *\n * The level prefix is optionally colored using ANSI escape codes:\n * - `debug` → gray\n * - `info` → blue\n * - `warn` → yellow\n * - `error` → red\n *\n * @param options - Configuration for the console transport.\n * @param options.colors - Enable ANSI color output (default: `true`).\n * @param options.timestamp - Prepend an ISO-8601 timestamp (default: `false`).\n */\nexport function createConsoleTransport(options?: {\n colors?: boolean\n timestamp?: boolean\n}): Transport {\n const useColors = options?.colors !== false\n const showTimestamp = options?.timestamp ?? false\n\n return {\n log(level, message, meta) {\n const parts: string[] = []\n\n if (showTimestamp) {\n parts.push(new Date().toISOString())\n }\n\n if (useColors) {\n const color = LEVEL_COLORS[level]\n parts.push(`${color}[${level.toUpperCase()}]${RESET}`)\n } else {\n parts.push(`[${level.toUpperCase()}]`)\n }\n\n parts.push(message)\n\n if (meta !== undefined && Object.keys(meta).length > 0) {\n parts.push(JSON.stringify(meta))\n }\n\n console.log(parts.join(' '))\n },\n }\n}\n\n/**\n * Creates a transport that outputs structured JSON lines.\n *\n * Each log entry is serialized as a single JSON object with\n * `timestamp`, `level`, `message`, and optional `meta` fields.\n *\n * @param options - Configuration for the JSON transport.\n * @param options.stream - A writable stream (e.g. `process.stdout`).\n * Defaults to `process.stdout` in Node.js, falls\n * back to `console.log` in browsers.\n */\nexport function createJsonTransport(options?: {\n stream?: { write(data: string): void }\n}): Transport {\n const writeStream =\n options?.stream ??\n (typeof process !== 'undefined' &&\n typeof process.stdout !== 'undefined' &&\n typeof process.stdout.write === 'function'\n ? (process.stdout as { write(data: string): void })\n : undefined)\n\n return {\n log(level, message, meta) {\n const entry: Record<string, unknown> = {\n timestamp: new Date().toISOString(),\n level,\n message,\n }\n if (meta !== undefined && Object.keys(meta).length > 0) {\n entry.meta = meta\n }\n const line = JSON.stringify(entry)\n if (writeStream !== undefined) {\n writeStream.write(line + '\\n')\n } else {\n console.log(line)\n }\n },\n }\n}\n\n/**\n * Creates a transport that appends log entries to a file.\n *\n * Each line is formatted as: `[timestamp] [LEVEL] message {meta}`\n *\n * ⚠️ Node.js only. Silently discards log entries when `fs` is unavailable\n * (browsers, Deno, Bun — though Bun supports `fs`).\n *\n * @param filename - Path to the log file.\n * @param options - Configuration for the file transport.\n * @param options.maxSize - Maximum file size in bytes before rotation\n * (default: 10 MB). **Note:** rotation is not\n * yet implemented; this is reserved for future use.\n */\nexport function createFileTransport(\n filename: string,\n _options?: { maxSize?: number },\n): Transport {\n // Try to resolve fs synchronously at construction time\n // Uses process.versions.node as a heuristic for Node.js environment\n let fs: { appendFileSync: (path: string, data: string) => void } | null = null\n try {\n if (typeof process !== 'undefined' && process.versions?.node) {\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n const m = require('fs') as { appendFileSync: (path: string, data: string) => void }\n fs = m\n }\n } catch {\n // fs unavailable (browser, edge runtime)\n }\n\n return {\n log(level, message, meta) {\n if (fs === null) return\n\n const metaStr =\n meta !== undefined && Object.keys(meta).length > 0 ? ` ${JSON.stringify(meta)}` : ''\n const line = `[${new Date().toISOString()}] [${level.toUpperCase()}] ${message}${metaStr}\\n`\n\n try {\n fs.appendFileSync(filename, line)\n } catch {\n // Silently drop if write fails (disk full, permissions, etc.)\n }\n },\n }\n}\n\n/**\n * Creates a buffered transport that batches log entries and flushes them\n * to the underlying transport when either the buffer size or flush interval\n * is reached (whichever comes first).\n *\n * Useful for reducing I/O pressure in high-throughput scenarios.\n *\n * @param transport - The underlying transport to flush to.\n * @param options - Configuration for the buffer.\n * @param options.maxSize - Maximum number of entries before forced flush\n * (default: 100).\n * @param options.flushIntervalMs - How often to auto-flush in milliseconds\n * (default: 5000). Set to `0` to disable\n * interval flushing.\n */\nexport function createBufferedTransport(\n transport: Transport,\n options?: { maxSize?: number; flushIntervalMs?: number },\n): Transport {\n const maxSize = options?.maxSize ?? 100\n const flushIntervalMs = options?.flushIntervalMs ?? 5000\n\n const buffer: Array<{\n level: LogLevel\n message: string\n meta?: Record<string, unknown>\n }> = []\n\n let timer: ReturnType<typeof setTimeout> | undefined\n\n function flush(): void {\n if (timer !== undefined) {\n clearTimeout(timer)\n timer = undefined\n }\n for (let i = 0; i < buffer.length; i++) {\n const entry = buffer[i]!\n transport.log(entry.level, entry.message, entry.meta)\n }\n buffer.length = 0\n }\n\n function scheduleFlush(): void {\n if (timer !== undefined || flushIntervalMs <= 0) return\n timer = setTimeout((): void => {\n timer = undefined\n flush()\n }, flushIntervalMs)\n }\n\n return {\n log(level, message, meta) {\n buffer.push({ level, message, meta })\n if (buffer.length >= maxSize) {\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AAG,eAAe;AAAA,EACpB;AAEA,SAAO;AAAA,IACL,IAAI,OAAO,SAAS,MAAM;AACxB,aAAO,KAAK,EAAE,OAAO,SAAS,KAAK,CAAC;AACpC,UAAI,OAAO,UAAU,SAAS;AAC5B,cAAM;AAAA,MACR,OAAO;AACL,sBAAc;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Validates an Indonesian NIK (Nomor Induk Kependudukan / Resident Identity Number).
|
|
3
|
+
*
|
|
4
|
+
* A valid NIK:
|
|
5
|
+
* - Must be exactly 16 digits
|
|
6
|
+
* - Structure: PP CC DD DDMMYY SSSS
|
|
7
|
+
* - PP: Province code (2 digits)
|
|
8
|
+
* - CC: City code (2 digits)
|
|
9
|
+
* - DD: District code (2 digits)
|
|
10
|
+
* - DDMMYY: Birth date (6 digits; for women the day is incremented by 40)
|
|
11
|
+
* - SSSS: Serial number (4 digits)
|
|
12
|
+
* - The birth date must correspond to a valid calendar date
|
|
13
|
+
*
|
|
14
|
+
* @param value - The NIK string (digits only or with dots)
|
|
15
|
+
* @returns `true` if the value is a valid NIK
|
|
16
|
+
*
|
|
17
|
+
* @example isNIK('3201010203940001') // => true (male, born 2 March 1994)
|
|
18
|
+
* @example isNIK('3201015203940001') // => true (female, born 12 March 1994)
|
|
19
|
+
* @example isNIK('1234567890123456') // => false (invalid birth date)
|
|
20
|
+
* @example isNIK('320101') // => false (too short)
|
|
21
|
+
*/
|
|
22
|
+
declare function isNIK(value: string): boolean;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Validates an Indonesian NPWP (Nomor Pokok Wajib Pajak / Tax Identification Number).
|
|
26
|
+
*
|
|
27
|
+
* A valid NPWP:
|
|
28
|
+
* - Must be 15 or 16 digits (formatted: `XX.XXX.XXX.X-XXX.XXX` or plain digits)
|
|
29
|
+
* - The last digit is a checksum computed from the preceding digits
|
|
30
|
+
*
|
|
31
|
+
* The checksum uses a weighted-sum algorithm with a repeating weight pattern of
|
|
32
|
+
* `[3, 7, 1]`. The computed checksum must equal the last digit.
|
|
33
|
+
*
|
|
34
|
+
* @param value - The NPWP string (formatted with dots & dash, or plain digits)
|
|
35
|
+
* @returns `true` if the value is a valid NPWP
|
|
36
|
+
*
|
|
37
|
+
* @example isNPWP('12.345.678.9-012.344') // => true
|
|
38
|
+
* @example isNPWP('123456789012344') // => true (plain digits)
|
|
39
|
+
* @example isNPWP('12.345.678.9-012.345') // => false (invalid checksum)
|
|
40
|
+
*/
|
|
41
|
+
declare function isNPWP(value: string): boolean;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Validates a phone number.
|
|
45
|
+
*
|
|
46
|
+
* For Indonesian numbers (`country = 'id'`):
|
|
47
|
+
* - Accepted formats: `08xx…`, `+628xx…`, `628xx…`
|
|
48
|
+
* - Must start with a valid operator prefix:
|
|
49
|
+
* 0811-0819, 0821-0829, 0851-0859, 0877-0879, 0895-0899
|
|
50
|
+
* - 10–13 digits after the country code
|
|
51
|
+
*
|
|
52
|
+
* For generic numbers (`country = 'any'`):
|
|
53
|
+
* - Any string with 10–15 digits is accepted
|
|
54
|
+
*
|
|
55
|
+
* @param value - The phone number string
|
|
56
|
+
* @param country - Country to validate against (`'id'` or `'any'`; default `'id'`)
|
|
57
|
+
* @returns `true` if the value is a valid phone number
|
|
58
|
+
*
|
|
59
|
+
* @example isPhone('08123456789') // => true
|
|
60
|
+
* @example isPhone('+628123456789') // => true
|
|
61
|
+
* @example isPhone('628123456789') // => true
|
|
62
|
+
* @example isPhone('081234567') // => false (too short)
|
|
63
|
+
* @example isPhone('089123456789') // => false (invalid prefix 91)
|
|
64
|
+
*/
|
|
65
|
+
declare function isPhone(value: string, country?: 'id' | 'any'): boolean;
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* RFC‑compliant email address validation.
|
|
69
|
+
*
|
|
70
|
+
* Validation rules:
|
|
71
|
+
* - Total length ≤ 254 characters
|
|
72
|
+
* - Local part ≤ 64 characters; supports quoted strings (including escaped
|
|
73
|
+
* characters), unquoted letters / digits / `!#$%&'*+/=?^_`{|}~-`, and dots
|
|
74
|
+
* (no leading, trailing, or consecutive dots)
|
|
75
|
+
* - Domain part ≤ 255 characters; valid DNS labels separated by dots, each
|
|
76
|
+
* label ≤ 63 characters, no leading/trailing hyphens, at least two labels
|
|
77
|
+
*
|
|
78
|
+
* @param value - The email address string
|
|
79
|
+
* @returns `true` if the value is a syntactically valid email address
|
|
80
|
+
*
|
|
81
|
+
* @example isEmail('user@example.com') // => true
|
|
82
|
+
* @example isEmail('user.name+tag@example.co.id') // => true
|
|
83
|
+
* @example isEmail('"quoted@local"@example.com') // => true
|
|
84
|
+
* @example isEmail('not-an-email') // => false
|
|
85
|
+
*/
|
|
86
|
+
declare function isEmail(value: string): boolean;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Validates a URL.
|
|
90
|
+
*
|
|
91
|
+
* A valid URL:
|
|
92
|
+
* - Must use the `http` or `https` protocol
|
|
93
|
+
* - Must have a valid hostname (DNS name, IPv4, IPv6 literal, or `localhost`)
|
|
94
|
+
* - May include an optional port, path, query string, and fragment
|
|
95
|
+
*
|
|
96
|
+
* @param value - The URL string
|
|
97
|
+
* @returns `true` if the value is a valid http/https URL
|
|
98
|
+
*
|
|
99
|
+
* @example isURL('https://example.com') // => true
|
|
100
|
+
* @example isURL('http://example.com:8080/path?q=1#f') // => true
|
|
101
|
+
* @example isURL('ftp://example.com') // => false
|
|
102
|
+
* @example isURL('not-a-url') // => false
|
|
103
|
+
*/
|
|
104
|
+
declare function isURL(value: string): boolean;
|
|
105
|
+
|
|
106
|
+
export { isEmail, isNIK, isNPWP, isPhone, isURL };
|