@mandujs/core 0.10.0 → 0.12.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.
@@ -1,10 +1,13 @@
1
1
  /**
2
2
  * Mandu Filling - 만두소 🥟
3
3
  * 체이닝 API로 비즈니스 로직 정의
4
+ *
5
+ * DNA-002: 의존성 주입 패턴 지원
4
6
  */
5
7
 
6
8
  import { ManduContext, ValidationError } from "./context";
7
9
  import { AuthenticationError, AuthorizationError } from "./auth";
10
+ import { type FillingDeps, globalDeps } from "./deps";
8
11
  import { ErrorClassifier, formatErrorResponse, ErrorCode } from "../error";
9
12
  import { TIMEOUTS } from "../constants";
10
13
  import { createContract, type ContractDefinition, type ContractInstance } from "../contract";
@@ -310,9 +313,10 @@ export class ManduFilling<TLoaderData = unknown> {
310
313
  request: Request,
311
314
  params: Record<string, string> = {},
312
315
  routeContext?: { routeId: string; pattern: string },
313
- options?: ExecuteOptions
316
+ options?: ExecuteOptions & { deps?: FillingDeps }
314
317
  ): Promise<Response> {
315
- const ctx = new ManduContext(request, params);
318
+ const deps = options?.deps ?? globalDeps.get();
319
+ const ctx = new ManduContext(request, params, deps);
316
320
  const method = request.method.toUpperCase() as HttpMethod;
317
321
  const handler = this.config.handlers.get(method);
318
322
  if (!handler) {
@@ -1,5 +1,7 @@
1
1
  /**
2
2
  * Mandu Filling Module - 만두소 🥟
3
+ *
4
+ * DNA-002: 의존성 주입 패턴 지원
3
5
  */
4
6
 
5
7
  export { ManduContext, ValidationError, CookieManager } from "./context";
@@ -19,3 +21,19 @@ export {
19
21
  createRoleGuard,
20
22
  } from "./auth";
21
23
  export type { BaseUser, UserWithRole, UserWithRoles } from "./auth";
24
+
25
+ // DNA-002: Dependency Injection
26
+ export {
27
+ createDefaultDeps,
28
+ createMockDeps,
29
+ mergeDeps,
30
+ globalDeps,
31
+ } from "./deps";
32
+ export type {
33
+ FillingDeps,
34
+ DbDeps,
35
+ CacheDeps,
36
+ LoggerDeps,
37
+ EventBusDeps,
38
+ InjectDeps,
39
+ } from "./deps";
package/src/index.ts CHANGED
@@ -5,7 +5,8 @@ export * from "./guard";
5
5
  export * from "./report";
6
6
  export * from "./filling";
7
7
  export * from "./change";
8
- export * from "./error";
8
+ export * from "./errors";
9
+ export * from "./logging";
9
10
  export * from "./slot";
10
11
  export * from "./bundler";
11
12
  export * from "./contract";
@@ -0,0 +1,22 @@
1
+ /**
2
+ * DNA-008: Structured Logging System
3
+ *
4
+ * 구조화된 로깅 시스템
5
+ * - Transport 기반 다중 출력
6
+ * - 동적 전송 추가/제거
7
+ * - 레벨별 필터링
8
+ */
9
+
10
+ export {
11
+ transportRegistry,
12
+ attachLogTransport,
13
+ detachLogTransport,
14
+ entryToTransportRecord,
15
+ createConsoleTransport,
16
+ createBufferTransport,
17
+ createFilteredTransport,
18
+ createBatchTransport,
19
+ type LogTransport,
20
+ type LogTransportRecord,
21
+ type TransportRegistration,
22
+ } from "./transports.js";
@@ -0,0 +1,365 @@
1
+ /**
2
+ * DNA-008: Structured Logging - Transport System
3
+ *
4
+ * 로그 전송 레지스트리
5
+ * - 다중 전송 지원 (콘솔, 파일, 외부 서비스)
6
+ * - 동적 전송 추가/제거
7
+ * - 레벨별 필터링
8
+ */
9
+
10
+ import type { LogLevel, LogEntry } from "../runtime/logger.js";
11
+
12
+ /**
13
+ * 로그 전송 레코드 (Transport에 전달되는 데이터)
14
+ */
15
+ export interface LogTransportRecord {
16
+ /** 타임스탬프 (ISO 문자열) */
17
+ timestamp: string;
18
+ /** 로그 레벨 */
19
+ level: LogLevel;
20
+ /** 요청 ID */
21
+ requestId?: string;
22
+ /** HTTP 메서드 */
23
+ method?: string;
24
+ /** 요청 경로 */
25
+ path?: string;
26
+ /** HTTP 상태 코드 */
27
+ status?: number;
28
+ /** 응답 시간 (ms) */
29
+ duration?: number;
30
+ /** 에러 정보 */
31
+ error?: {
32
+ message: string;
33
+ stack?: string;
34
+ code?: string;
35
+ };
36
+ /** 커스텀 메타데이터 */
37
+ meta?: Record<string, unknown>;
38
+ /** 느린 요청 여부 */
39
+ slow?: boolean;
40
+ /** 원본 LogEntry (필요시 접근) */
41
+ raw?: LogEntry;
42
+ }
43
+
44
+ /**
45
+ * 로그 전송 함수 타입
46
+ */
47
+ export type LogTransport = (record: LogTransportRecord) => void | Promise<void>;
48
+
49
+ /**
50
+ * 전송 등록 정보
51
+ */
52
+ export interface TransportRegistration {
53
+ /** 전송 ID */
54
+ id: string;
55
+ /** 전송 함수 */
56
+ transport: LogTransport;
57
+ /** 최소 로그 레벨 (이 레벨 이상만 전송) */
58
+ minLevel?: LogLevel;
59
+ /** 활성화 여부 */
60
+ enabled: boolean;
61
+ }
62
+
63
+ /**
64
+ * 로그 레벨 우선순위
65
+ */
66
+ const LEVEL_PRIORITY: Record<LogLevel, number> = {
67
+ debug: 0,
68
+ info: 1,
69
+ warn: 2,
70
+ error: 3,
71
+ };
72
+
73
+ /**
74
+ * 전역 전송 레지스트리
75
+ */
76
+ class TransportRegistry {
77
+ private transports = new Map<string, TransportRegistration>();
78
+
79
+ /**
80
+ * 전송 추가
81
+ *
82
+ * @example
83
+ * ```ts
84
+ * attachLogTransport("file", async (record) => {
85
+ * await appendFile("app.log", JSON.stringify(record) + "\n");
86
+ * });
87
+ * ```
88
+ */
89
+ attach(
90
+ id: string,
91
+ transport: LogTransport,
92
+ options: { minLevel?: LogLevel; enabled?: boolean } = {}
93
+ ): void {
94
+ this.transports.set(id, {
95
+ id,
96
+ transport,
97
+ minLevel: options.minLevel,
98
+ enabled: options.enabled ?? true,
99
+ });
100
+ }
101
+
102
+ /**
103
+ * 전송 제거
104
+ */
105
+ detach(id: string): boolean {
106
+ return this.transports.delete(id);
107
+ }
108
+
109
+ /**
110
+ * 전송 활성화/비활성화
111
+ */
112
+ setEnabled(id: string, enabled: boolean): void {
113
+ const registration = this.transports.get(id);
114
+ if (registration) {
115
+ registration.enabled = enabled;
116
+ }
117
+ }
118
+
119
+ /**
120
+ * 모든 전송에 로그 전달
121
+ */
122
+ async dispatch(record: LogTransportRecord): Promise<void> {
123
+ const recordLevel = LEVEL_PRIORITY[record.level];
124
+
125
+ const promises: Promise<void>[] = [];
126
+
127
+ for (const registration of this.transports.values()) {
128
+ if (!registration.enabled) continue;
129
+
130
+ // 레벨 필터링
131
+ if (registration.minLevel) {
132
+ const minLevel = LEVEL_PRIORITY[registration.minLevel];
133
+ if (recordLevel < minLevel) continue;
134
+ }
135
+
136
+ try {
137
+ const result = registration.transport(record);
138
+ if (result instanceof Promise) {
139
+ promises.push(result.catch((err) => {
140
+ console.error(`[Log Transport] Error in ${registration.id}:`, err);
141
+ }));
142
+ }
143
+ } catch (err) {
144
+ console.error(`[Log Transport] Error in ${registration.id}:`, err);
145
+ }
146
+ }
147
+
148
+ await Promise.all(promises);
149
+ }
150
+
151
+ /**
152
+ * 동기적으로 모든 전송에 로그 전달 (비동기 전송은 fire-and-forget)
153
+ */
154
+ dispatchSync(record: LogTransportRecord): void {
155
+ const recordLevel = LEVEL_PRIORITY[record.level];
156
+
157
+ for (const registration of this.transports.values()) {
158
+ if (!registration.enabled) continue;
159
+
160
+ if (registration.minLevel) {
161
+ const minLevel = LEVEL_PRIORITY[registration.minLevel];
162
+ if (recordLevel < minLevel) continue;
163
+ }
164
+
165
+ try {
166
+ const result = registration.transport(record);
167
+ if (result instanceof Promise) {
168
+ // 비동기 결과는 무시 (fire-and-forget)
169
+ result.catch((err) => {
170
+ console.error(`[Log Transport] Error in ${registration.id}:`, err);
171
+ });
172
+ }
173
+ } catch (err) {
174
+ console.error(`[Log Transport] Error in ${registration.id}:`, err);
175
+ }
176
+ }
177
+ }
178
+
179
+ /**
180
+ * 등록된 전송 목록
181
+ */
182
+ list(): TransportRegistration[] {
183
+ return Array.from(this.transports.values());
184
+ }
185
+
186
+ /**
187
+ * 전송 존재 여부
188
+ */
189
+ has(id: string): boolean {
190
+ return this.transports.has(id);
191
+ }
192
+
193
+ /**
194
+ * 모든 전송 제거
195
+ */
196
+ clear(): void {
197
+ this.transports.clear();
198
+ }
199
+
200
+ /**
201
+ * 전송 개수
202
+ */
203
+ get size(): number {
204
+ return this.transports.size;
205
+ }
206
+ }
207
+
208
+ /**
209
+ * 전역 전송 레지스트리 인스턴스
210
+ */
211
+ export const transportRegistry = new TransportRegistry();
212
+
213
+ /**
214
+ * 로그 전송 추가 (편의 함수)
215
+ *
216
+ * @example
217
+ * ```ts
218
+ * // 파일 전송
219
+ * attachLogTransport("file", async (record) => {
220
+ * await fs.appendFile("app.log", JSON.stringify(record) + "\n");
221
+ * }, { minLevel: "info" });
222
+ *
223
+ * // 외부 서비스 전송
224
+ * attachLogTransport("datadog", async (record) => {
225
+ * await fetch("https://http-intake.logs.datadoghq.com/...", {
226
+ * method: "POST",
227
+ * body: JSON.stringify(record),
228
+ * });
229
+ * }, { minLevel: "warn" });
230
+ * ```
231
+ */
232
+ export function attachLogTransport(
233
+ id: string,
234
+ transport: LogTransport,
235
+ options?: { minLevel?: LogLevel; enabled?: boolean }
236
+ ): void {
237
+ transportRegistry.attach(id, transport, options);
238
+ }
239
+
240
+ /**
241
+ * 로그 전송 제거 (편의 함수)
242
+ */
243
+ export function detachLogTransport(id: string): boolean {
244
+ return transportRegistry.detach(id);
245
+ }
246
+
247
+ /**
248
+ * LogEntry를 LogTransportRecord로 변환
249
+ */
250
+ export function entryToTransportRecord(entry: LogEntry): LogTransportRecord {
251
+ return {
252
+ timestamp: entry.timestamp,
253
+ level: entry.level,
254
+ requestId: entry.requestId,
255
+ method: entry.method,
256
+ path: entry.path,
257
+ status: entry.status,
258
+ duration: entry.duration,
259
+ error: entry.error ? {
260
+ message: entry.error.message,
261
+ stack: entry.error.stack,
262
+ } : undefined,
263
+ slow: entry.slow,
264
+ raw: entry,
265
+ };
266
+ }
267
+
268
+ // ============================================
269
+ // Built-in Transports
270
+ // ============================================
271
+
272
+ /**
273
+ * 콘솔 전송 (기본)
274
+ */
275
+ export function createConsoleTransport(options: {
276
+ format?: "json" | "pretty";
277
+ } = {}): LogTransport {
278
+ const { format = "pretty" } = options;
279
+
280
+ return (record) => {
281
+ const output = format === "json"
282
+ ? JSON.stringify(record)
283
+ : `[${record.timestamp}] ${record.level.toUpperCase()} ${record.method ?? ""} ${record.path ?? ""} ${record.status ?? ""} ${record.duration ? record.duration.toFixed(0) + "ms" : ""}`;
284
+
285
+ switch (record.level) {
286
+ case "error":
287
+ console.error(output);
288
+ break;
289
+ case "warn":
290
+ console.warn(output);
291
+ break;
292
+ default:
293
+ console.log(output);
294
+ }
295
+ };
296
+ }
297
+
298
+ /**
299
+ * 메모리 버퍼 전송 (테스트용)
300
+ */
301
+ export function createBufferTransport(buffer: LogTransportRecord[]): LogTransport {
302
+ return (record) => {
303
+ buffer.push(record);
304
+ };
305
+ }
306
+
307
+ /**
308
+ * 필터링 전송 래퍼
309
+ */
310
+ export function createFilteredTransport(
311
+ transport: LogTransport,
312
+ filter: (record: LogTransportRecord) => boolean
313
+ ): LogTransport {
314
+ return (record) => {
315
+ if (filter(record)) {
316
+ return transport(record);
317
+ }
318
+ };
319
+ }
320
+
321
+ /**
322
+ * 배치 전송 (성능 최적화)
323
+ */
324
+ export function createBatchTransport(
325
+ flush: (records: LogTransportRecord[]) => void | Promise<void>,
326
+ options: {
327
+ maxSize?: number;
328
+ flushInterval?: number;
329
+ } = {}
330
+ ): { transport: LogTransport; flush: () => Promise<void>; stop: () => void } {
331
+ const { maxSize = 100, flushInterval = 5000 } = options;
332
+
333
+ const buffer: LogTransportRecord[] = [];
334
+ let timer: ReturnType<typeof setInterval> | null = null;
335
+
336
+ const doFlush = async () => {
337
+ if (buffer.length === 0) return;
338
+ const records = buffer.splice(0, buffer.length);
339
+ await flush(records);
340
+ };
341
+
342
+ timer = setInterval(() => {
343
+ doFlush().catch((err) => {
344
+ console.error("[Batch Transport] Flush error:", err);
345
+ });
346
+ }, flushInterval);
347
+
348
+ return {
349
+ transport: (record) => {
350
+ buffer.push(record);
351
+ if (buffer.length >= maxSize) {
352
+ doFlush().catch((err) => {
353
+ console.error("[Batch Transport] Flush error:", err);
354
+ });
355
+ }
356
+ },
357
+ flush: doFlush,
358
+ stop: () => {
359
+ if (timer) {
360
+ clearInterval(timer);
361
+ timer = null;
362
+ }
363
+ },
364
+ };
365
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * DNA-001: Plugin System
3
+ *
4
+ * Mandu 플러그인 시스템
5
+ * - Guard 프리셋 플러그인
6
+ * - 빌드 플러그인
7
+ * - 로거 전송 플러그인
8
+ * - MCP 도구 플러그인
9
+ * - 미들웨어 플러그인
10
+ */
11
+
12
+ export {
13
+ PluginRegistry,
14
+ globalPluginRegistry,
15
+ definePlugin,
16
+ } from "./registry";
17
+
18
+ export type {
19
+ Plugin,
20
+ PluginApi,
21
+ PluginCategory,
22
+ PluginMeta,
23
+ PluginHooks,
24
+ GuardPresetPlugin,
25
+ GuardRule,
26
+ GuardRuleContext,
27
+ GuardViolation,
28
+ LayerDefinition,
29
+ ImportInfo,
30
+ ExportInfo,
31
+ BuildPlugin,
32
+ BuildContext,
33
+ BuildResult,
34
+ LoggerTransportPlugin,
35
+ LogEntry,
36
+ McpToolPlugin,
37
+ MiddlewarePlugin,
38
+ } from "./types";