@rapidd/core 2.1.2 → 2.1.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.
@@ -0,0 +1,237 @@
1
+ import { appendFileSync, mkdirSync, existsSync } from 'fs';
2
+ import path from 'path';
3
+
4
+ // ── Types ────────────────────────────────────────────────────────────────────
5
+
6
+ export type LogLevel = 'essential' | 'fine' | 'finest';
7
+
8
+ // ── Level Config ─────────────────────────────────────────────────────────────
9
+
10
+ const LEVELS: LogLevel[] = ['essential', 'fine', 'finest'];
11
+
12
+ function parseLevel(value: string | undefined): LogLevel {
13
+ if (value && LEVELS.includes(value as LogLevel)) {
14
+ return value as LogLevel;
15
+ }
16
+ return 'essential';
17
+ }
18
+
19
+ // ── State ────────────────────────────────────────────────────────────────────
20
+
21
+ const _level: LogLevel = parseLevel(process.env.LOG_LEVEL);
22
+ const _silent: boolean = process.env.NODE_ENV === 'test';
23
+ const _logDir: string = process.env.LOG_DIR ?? 'logs';
24
+
25
+ // ── File Writing ─────────────────────────────────────────────────────────────
26
+
27
+ let _dirChecked = false;
28
+
29
+ function ensureLogDir(): void {
30
+ if (_dirChecked || !_logDir) return;
31
+ const dir = path.isAbsolute(_logDir) ? _logDir : path.join(process.cwd(), _logDir);
32
+ if (!existsSync(dir)) {
33
+ mkdirSync(dir, { recursive: true });
34
+ }
35
+ _dirChecked = true;
36
+ }
37
+
38
+ function writeToFile(filename: string, line: string): void {
39
+ if (!_logDir) return;
40
+ try {
41
+ ensureLogDir();
42
+ const dir = path.isAbsolute(_logDir) ? _logDir : path.join(process.cwd(), _logDir);
43
+ appendFileSync(path.join(dir, filename), line + '\n');
44
+ } catch {
45
+ // Silently ignore file write failures — don't crash the app for logging
46
+ }
47
+ }
48
+
49
+ // ── Formatting ───────────────────────────────────────────────────────────────
50
+
51
+ function timestamp(): string {
52
+ return new Date().toISOString();
53
+ }
54
+
55
+ function formatData(data: unknown[]): string {
56
+ if (data.length === 0) return '';
57
+ const parts = data.map(d => {
58
+ if (d === null || d === undefined) return String(d);
59
+ if (typeof d === 'object') {
60
+ try { return JSON.stringify(d); } catch { return String(d); }
61
+ }
62
+ return String(d);
63
+ });
64
+ return ' ' + parts.join(' ');
65
+ }
66
+
67
+ function formatDataPretty(data: unknown[]): string {
68
+ if (data.length === 0) return '';
69
+ const parts = data.map(d => {
70
+ if (d === null || d === undefined) return String(d);
71
+ if (typeof d === 'object') {
72
+ try { return JSON.stringify(d, null, 2); } catch { return String(d); }
73
+ }
74
+ return String(d);
75
+ });
76
+ return '\n' + parts.join('\n');
77
+ }
78
+
79
+ function formatHeaders(headers: Record<string, unknown>): string {
80
+ return Object.entries(headers)
81
+ .filter(([, v]) => v !== undefined)
82
+ .map(([k, v]) => ` ${k}: ${Array.isArray(v) ? v.join(', ') : v}`)
83
+ .join('\n');
84
+ }
85
+
86
+ function formatBody(body: unknown): string {
87
+ if (body === null || body === undefined) return ' (empty)';
88
+ if (typeof body === 'string') {
89
+ try {
90
+ return ' ' + JSON.stringify(JSON.parse(body), null, 2).replace(/\n/g, '\n ');
91
+ } catch {
92
+ return ' ' + body;
93
+ }
94
+ }
95
+ if (typeof body === 'object') {
96
+ try {
97
+ return ' ' + JSON.stringify(body, null, 2).replace(/\n/g, '\n ');
98
+ } catch {
99
+ return ' ' + String(body);
100
+ }
101
+ }
102
+ return ' ' + String(body);
103
+ }
104
+
105
+ function formatError(error: Error | string | unknown): { message: string; toString: string; stack: string } {
106
+ if (error instanceof Error) {
107
+ return {
108
+ message: error.message,
109
+ toString: error.toString(),
110
+ stack: error.stack || error.toString(),
111
+ };
112
+ }
113
+ const str = String(error);
114
+ return { message: str, toString: str, stack: str };
115
+ }
116
+
117
+ // ── Logger ───────────────────────────────────────────────────────────────────
118
+
119
+ export const Logger = {
120
+ log(message: string, ...data: unknown[]): void {
121
+ if (_silent) return;
122
+
123
+ let output: string;
124
+ switch (_level) {
125
+ case 'essential':
126
+ output = `[${timestamp()}] [LOG] ${message}`;
127
+ break;
128
+ case 'fine':
129
+ output = `[${timestamp()}] [LOG] ${message}${formatData(data)}`;
130
+ break;
131
+ case 'finest':
132
+ output = `[${timestamp()}] [LOG] ${message}${formatDataPretty(data)}`;
133
+ break;
134
+ }
135
+
136
+ console.log(output);
137
+ writeToFile('app.log', output);
138
+ },
139
+
140
+ warn(message: string, ...data: unknown[]): void {
141
+ if (_silent) return;
142
+
143
+ let output: string;
144
+ switch (_level) {
145
+ case 'essential':
146
+ output = `[${timestamp()}] [WARN] ${message}`;
147
+ break;
148
+ case 'fine':
149
+ output = `[${timestamp()}] [WARN] ${message}${formatData(data)}`;
150
+ break;
151
+ case 'finest':
152
+ output = `[${timestamp()}] [WARN] ${message}${formatDataPretty(data)}`;
153
+ break;
154
+ }
155
+
156
+ console.warn(output);
157
+ writeToFile('app.log', output);
158
+ },
159
+
160
+ error(error: Error | string | unknown, ...data: unknown[]): void {
161
+ if (_silent) return;
162
+
163
+ const err = formatError(error);
164
+ let output: string;
165
+
166
+ switch (_level) {
167
+ case 'essential':
168
+ output = `[${timestamp()}] [ERROR] ${err.message}`;
169
+ break;
170
+ case 'fine':
171
+ output = `[${timestamp()}] [ERROR] ${err.toString}${formatData(data)}`;
172
+ break;
173
+ case 'finest':
174
+ output = `[${timestamp()}] [ERROR] ${err.stack}${formatDataPretty(data)}`;
175
+ break;
176
+ }
177
+
178
+ console.error(output);
179
+ writeToFile('error.log', output);
180
+ },
181
+
182
+ request(info: {
183
+ method: string;
184
+ url: string;
185
+ status: number;
186
+ time: number;
187
+ ip?: string;
188
+ contentLength?: string;
189
+ userId?: string | number;
190
+ userAgent?: string;
191
+ requestHeaders?: Record<string, unknown>;
192
+ requestBody?: unknown;
193
+ responseHeaders?: Record<string, unknown>;
194
+ responseBody?: unknown;
195
+ }): void {
196
+ if (_silent) return;
197
+
198
+ const { method, url, status, time } = info;
199
+ const timeStr = `${time.toFixed(0)}ms`;
200
+ let output: string;
201
+
202
+ switch (_level) {
203
+ case 'essential':
204
+ output = `[${timestamp()}] ${method} ${url} ${status} ${timeStr}`;
205
+ break;
206
+ case 'fine':
207
+ output = `[${timestamp()}] ${method} ${url} ${status} ${timeStr} | ${info.ip || '-'}${info.userId ? ` | user:${info.userId}` : ''}`;
208
+ break;
209
+ case 'finest': {
210
+ const lines = [`[${timestamp()}] ${method} ${url} ${status} ${timeStr} | ${info.ip || '-'}${info.userId ? ` | user:${info.userId}` : ''}`];
211
+ if (info.requestHeaders) {
212
+ lines.push(' ── Request Headers');
213
+ lines.push(formatHeaders(info.requestHeaders));
214
+ }
215
+ if (info.requestBody !== undefined && info.requestBody !== null) {
216
+ lines.push(' ── Request Body');
217
+ lines.push(formatBody(info.requestBody));
218
+ }
219
+ if (info.responseHeaders) {
220
+ lines.push(' ── Response Headers');
221
+ lines.push(formatHeaders(info.responseHeaders));
222
+ }
223
+ if (info.responseBody !== undefined && info.responseBody !== null) {
224
+ lines.push(' ── Response Body');
225
+ lines.push(formatBody(info.responseBody));
226
+ }
227
+ output = lines.join('\n');
228
+ break;
229
+ }
230
+ }
231
+
232
+ console.log(output);
233
+ writeToFile('access.log', output);
234
+ },
235
+ };
236
+
237
+ export default Logger;
@@ -4,6 +4,9 @@ export type { ServiceConfig, EndpointConfig, AuthConfig, RequestOptions, ApiResp
4
4
  export { Mailer } from './Mailer';
5
5
  export type { EmailConfig, EmailOptions, EmailAttachment, EmailResult } from './Mailer';
6
6
 
7
+ export { Logger } from './Logger';
8
+ export type { LogLevel } from './Logger';
9
+
7
10
  export const env = {
8
11
  isProduction: () => process.env.NODE_ENV === 'production',
9
12
  isDevelopment: () => __filename.endsWith('.ts') || process.env.NODE_ENV === 'development',