@mandujs/core 0.9.41 → 0.9.43

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 (71) hide show
  1. package/README.ko.md +1 -1
  2. package/README.md +1 -1
  3. package/package.json +1 -1
  4. package/src/bundler/build.ts +91 -73
  5. package/src/bundler/css.ts +283 -0
  6. package/src/bundler/dev.ts +31 -6
  7. package/src/bundler/index.ts +1 -0
  8. package/src/client/globals.ts +44 -0
  9. package/src/client/index.ts +5 -4
  10. package/src/client/island.ts +8 -13
  11. package/src/client/router.ts +33 -41
  12. package/src/client/runtime.ts +23 -51
  13. package/src/client/window-state.ts +101 -0
  14. package/src/config/index.ts +1 -0
  15. package/src/config/mandu.ts +45 -9
  16. package/src/config/validate.ts +158 -0
  17. package/src/constants.ts +25 -0
  18. package/src/contract/client.ts +4 -3
  19. package/src/contract/define.ts +459 -0
  20. package/src/devtools/ai/context-builder.ts +375 -0
  21. package/src/devtools/ai/index.ts +25 -0
  22. package/src/devtools/ai/mcp-connector.ts +465 -0
  23. package/src/devtools/client/catchers/error-catcher.ts +327 -0
  24. package/src/devtools/client/catchers/index.ts +18 -0
  25. package/src/devtools/client/catchers/network-proxy.ts +363 -0
  26. package/src/devtools/client/components/index.ts +39 -0
  27. package/src/devtools/client/components/kitchen-root.tsx +362 -0
  28. package/src/devtools/client/components/mandu-character.tsx +241 -0
  29. package/src/devtools/client/components/overlay.tsx +368 -0
  30. package/src/devtools/client/components/panel/errors-panel.tsx +259 -0
  31. package/src/devtools/client/components/panel/guard-panel.tsx +244 -0
  32. package/src/devtools/client/components/panel/index.ts +32 -0
  33. package/src/devtools/client/components/panel/islands-panel.tsx +304 -0
  34. package/src/devtools/client/components/panel/network-panel.tsx +292 -0
  35. package/src/devtools/client/components/panel/panel-container.tsx +259 -0
  36. package/src/devtools/client/filters/context-filters.ts +282 -0
  37. package/src/devtools/client/filters/index.ts +16 -0
  38. package/src/devtools/client/index.ts +63 -0
  39. package/src/devtools/client/persistence.ts +335 -0
  40. package/src/devtools/client/state-manager.ts +478 -0
  41. package/src/devtools/design-tokens.ts +263 -0
  42. package/src/devtools/hook/create-hook.ts +207 -0
  43. package/src/devtools/hook/index.ts +13 -0
  44. package/src/devtools/index.ts +439 -0
  45. package/src/devtools/init.ts +266 -0
  46. package/src/devtools/protocol.ts +237 -0
  47. package/src/devtools/server/index.ts +17 -0
  48. package/src/devtools/server/source-context.ts +444 -0
  49. package/src/devtools/types.ts +319 -0
  50. package/src/devtools/worker/index.ts +25 -0
  51. package/src/devtools/worker/redaction-worker.ts +222 -0
  52. package/src/devtools/worker/worker-manager.ts +409 -0
  53. package/src/error/formatter.ts +28 -24
  54. package/src/error/index.ts +13 -9
  55. package/src/error/result.ts +46 -0
  56. package/src/error/types.ts +6 -4
  57. package/src/filling/filling.ts +6 -5
  58. package/src/guard/check.ts +60 -56
  59. package/src/guard/types.ts +3 -1
  60. package/src/guard/watcher.ts +10 -1
  61. package/src/index.ts +81 -0
  62. package/src/intent/index.ts +310 -0
  63. package/src/island/index.ts +304 -0
  64. package/src/router/fs-patterns.ts +7 -0
  65. package/src/router/fs-routes.ts +20 -8
  66. package/src/router/fs-scanner.ts +117 -133
  67. package/src/runtime/server.ts +189 -61
  68. package/src/runtime/ssr.ts +14 -4
  69. package/src/runtime/streaming-ssr.ts +15 -4
  70. package/src/utils/bun.ts +8 -0
  71. package/src/utils/lru-cache.ts +75 -0
@@ -0,0 +1,465 @@
1
+ /**
2
+ * Mandu Kitchen DevTools - MCP Connector
3
+ * @version 1.1.0
4
+ *
5
+ * Model Context Protocol (MCP) 연동
6
+ * - AI 에이전트와의 통신
7
+ * - 컨텍스트 전달
8
+ * - 수정 제안 수신
9
+ */
10
+
11
+ import type { AIContextPayload, NormalizedError } from '../types';
12
+ import { AIContextBuilder, getContextBuilder } from './context-builder';
13
+
14
+ // ============================================================================
15
+ // Types
16
+ // ============================================================================
17
+
18
+ export interface MCPConnectorOptions {
19
+ /** MCP 서버 URL */
20
+ serverUrl?: string;
21
+ /** 연결 타임아웃 (ms) */
22
+ connectionTimeout?: number;
23
+ /** 요청 타임아웃 (ms) */
24
+ requestTimeout?: number;
25
+ /** 자동 재연결 */
26
+ autoReconnect?: boolean;
27
+ /** 재연결 간격 (ms) */
28
+ reconnectInterval?: number;
29
+ /** 최대 재연결 시도 횟수 */
30
+ maxReconnectAttempts?: number;
31
+ }
32
+
33
+ export interface MCPMessage {
34
+ id: string;
35
+ type: 'request' | 'response' | 'notification';
36
+ method?: string;
37
+ params?: unknown;
38
+ result?: unknown;
39
+ error?: {
40
+ code: number;
41
+ message: string;
42
+ data?: unknown;
43
+ };
44
+ }
45
+
46
+ export interface AnalysisRequest {
47
+ context: AIContextPayload;
48
+ options?: {
49
+ includeFixSuggestion?: boolean;
50
+ includeExplanation?: boolean;
51
+ language?: string;
52
+ };
53
+ }
54
+
55
+ export interface AnalysisResponse {
56
+ success: boolean;
57
+ analysis?: {
58
+ rootCause: string;
59
+ explanation: string;
60
+ severity: 'critical' | 'high' | 'medium' | 'low';
61
+ category: string;
62
+ };
63
+ fixSuggestion?: {
64
+ description: string;
65
+ code?: string;
66
+ file?: string;
67
+ lineRange?: [number, number];
68
+ confidence: number;
69
+ };
70
+ relatedDocs?: Array<{
71
+ title: string;
72
+ url: string;
73
+ }>;
74
+ error?: string;
75
+ }
76
+
77
+ export type MCPConnectionStatus =
78
+ | 'disconnected'
79
+ | 'connecting'
80
+ | 'connected'
81
+ | 'error';
82
+
83
+ // ============================================================================
84
+ // Constants
85
+ // ============================================================================
86
+
87
+ const DEFAULT_OPTIONS: Required<MCPConnectorOptions> = {
88
+ serverUrl: 'ws://localhost:3333/mcp',
89
+ connectionTimeout: 5000,
90
+ requestTimeout: 30000,
91
+ autoReconnect: true,
92
+ reconnectInterval: 3000,
93
+ maxReconnectAttempts: 5,
94
+ };
95
+
96
+ // ============================================================================
97
+ // MCP Connector
98
+ // ============================================================================
99
+
100
+ export class MCPConnector {
101
+ private options: Required<MCPConnectorOptions>;
102
+ private ws: WebSocket | null = null;
103
+ private status: MCPConnectionStatus = 'disconnected';
104
+ private requestIdCounter = 0;
105
+ private pendingRequests = new Map<
106
+ string,
107
+ {
108
+ resolve: (result: unknown) => void;
109
+ reject: (error: Error) => void;
110
+ timeout: ReturnType<typeof setTimeout>;
111
+ }
112
+ >();
113
+ private reconnectAttempts = 0;
114
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
115
+ private statusListeners = new Set<(status: MCPConnectionStatus) => void>();
116
+ private contextBuilder: AIContextBuilder;
117
+
118
+ constructor(options: MCPConnectorOptions = {}) {
119
+ this.options = { ...DEFAULT_OPTIONS, ...options };
120
+ this.contextBuilder = getContextBuilder();
121
+ }
122
+
123
+ // --------------------------------------------------------------------------
124
+ // Connection Management
125
+ // --------------------------------------------------------------------------
126
+
127
+ /**
128
+ * MCP 서버에 연결
129
+ */
130
+ connect(): Promise<void> {
131
+ return new Promise((resolve, reject) => {
132
+ if (this.status === 'connected' && this.ws) {
133
+ resolve();
134
+ return;
135
+ }
136
+
137
+ this.setStatus('connecting');
138
+
139
+ const timeout = setTimeout(() => {
140
+ reject(new Error('Connection timeout'));
141
+ this.handleConnectionError(new Error('Connection timeout'));
142
+ }, this.options.connectionTimeout);
143
+
144
+ try {
145
+ this.ws = new WebSocket(this.options.serverUrl);
146
+
147
+ this.ws.onopen = () => {
148
+ clearTimeout(timeout);
149
+ this.setStatus('connected');
150
+ this.reconnectAttempts = 0;
151
+ resolve();
152
+ };
153
+
154
+ this.ws.onclose = () => {
155
+ this.handleDisconnect();
156
+ };
157
+
158
+ this.ws.onerror = (event) => {
159
+ clearTimeout(timeout);
160
+ this.handleConnectionError(new Error('WebSocket error'));
161
+ reject(new Error('WebSocket connection failed'));
162
+ };
163
+
164
+ this.ws.onmessage = (event) => {
165
+ this.handleMessage(event.data);
166
+ };
167
+ } catch (error) {
168
+ clearTimeout(timeout);
169
+ this.handleConnectionError(
170
+ error instanceof Error ? error : new Error(String(error))
171
+ );
172
+ reject(error);
173
+ }
174
+ });
175
+ }
176
+
177
+ /**
178
+ * 연결 종료
179
+ */
180
+ disconnect(): void {
181
+ if (this.reconnectTimer) {
182
+ clearTimeout(this.reconnectTimer);
183
+ this.reconnectTimer = null;
184
+ }
185
+
186
+ if (this.ws) {
187
+ this.ws.close();
188
+ this.ws = null;
189
+ }
190
+
191
+ // 대기 중인 요청 모두 reject
192
+ for (const [id, pending] of this.pendingRequests) {
193
+ clearTimeout(pending.timeout);
194
+ pending.reject(new Error('Connection closed'));
195
+ }
196
+ this.pendingRequests.clear();
197
+
198
+ this.setStatus('disconnected');
199
+ }
200
+
201
+ /**
202
+ * 연결 상태 조회
203
+ */
204
+ getStatus(): MCPConnectionStatus {
205
+ return this.status;
206
+ }
207
+
208
+ /**
209
+ * 상태 변경 리스너 등록
210
+ */
211
+ onStatusChange(
212
+ listener: (status: MCPConnectionStatus) => void
213
+ ): () => void {
214
+ this.statusListeners.add(listener);
215
+ return () => this.statusListeners.delete(listener);
216
+ }
217
+
218
+ // --------------------------------------------------------------------------
219
+ // MCP Methods
220
+ // --------------------------------------------------------------------------
221
+
222
+ /**
223
+ * 에러 분석 요청
224
+ */
225
+ async analyzeError(
226
+ error: NormalizedError,
227
+ options?: AnalysisRequest['options']
228
+ ): Promise<AnalysisResponse> {
229
+ // 컨텍스트 빌드
230
+ const context = await this.contextBuilder.buildContext(error);
231
+
232
+ return this.sendRequest<AnalysisResponse>('mandu/analyze', {
233
+ context,
234
+ options: {
235
+ includeFixSuggestion: true,
236
+ includeExplanation: true,
237
+ language: 'ko',
238
+ ...options,
239
+ },
240
+ });
241
+ }
242
+
243
+ /**
244
+ * 수정 제안 요청
245
+ */
246
+ async getSuggestion(
247
+ error: NormalizedError,
248
+ codeContext: string
249
+ ): Promise<AnalysisResponse['fixSuggestion']> {
250
+ const result = await this.sendRequest<{
251
+ suggestion: AnalysisResponse['fixSuggestion'];
252
+ }>('mandu/suggest', {
253
+ error: {
254
+ message: error.message,
255
+ type: error.type,
256
+ source: error.source,
257
+ line: error.line,
258
+ },
259
+ codeContext,
260
+ });
261
+
262
+ return result.suggestion;
263
+ }
264
+
265
+ /**
266
+ * 관련 문서 검색
267
+ */
268
+ async searchDocs(
269
+ query: string
270
+ ): Promise<AnalysisResponse['relatedDocs']> {
271
+ const result = await this.sendRequest<{
272
+ docs: AnalysisResponse['relatedDocs'];
273
+ }>('mandu/docs', { query });
274
+
275
+ return result.docs;
276
+ }
277
+
278
+ /**
279
+ * 클립보드용 컨텍스트 생성
280
+ * (AI 에이전트에 붙여넣기 위한 포맷)
281
+ */
282
+ async formatForClipboard(error: NormalizedError): Promise<string> {
283
+ const context = await this.contextBuilder.buildContext(error);
284
+
285
+ const parts: string[] = [
286
+ '## Error Report',
287
+ '',
288
+ `**Type**: ${error.type}`,
289
+ `**Severity**: ${error.severity}`,
290
+ `**Message**: ${error.message}`,
291
+ '',
292
+ ];
293
+
294
+ if (error.source) {
295
+ parts.push(`**Location**: ${error.source}:${error.line ?? '?'}:${error.column ?? '?'}`);
296
+ parts.push('');
297
+ }
298
+
299
+ if (error.stack) {
300
+ parts.push('### Stack Trace');
301
+ parts.push('```');
302
+ parts.push(error.stack);
303
+ parts.push('```');
304
+ parts.push('');
305
+ }
306
+
307
+ if (context.codeContext?.snippet) {
308
+ parts.push('### Source Code');
309
+ parts.push('```typescript');
310
+ parts.push(context.codeContext.snippet.content);
311
+ parts.push('```');
312
+ parts.push('');
313
+ }
314
+
315
+ if (context.island) {
316
+ parts.push('### Island Info');
317
+ parts.push(`- Name: ${context.island.name}`);
318
+ parts.push(`- Status: ${context.island.status}`);
319
+ parts.push(`- Strategy: ${context.island.strategy}`);
320
+ parts.push('');
321
+ }
322
+
323
+ if (context.recentErrors && context.recentErrors.length > 0) {
324
+ parts.push('### Recent Related Errors');
325
+ for (const e of context.recentErrors) {
326
+ const timeAgo = Math.round((Date.now() - e.timestamp) / 1000);
327
+ parts.push(`- ${e.message} (${timeAgo}s ago)`);
328
+ }
329
+ parts.push('');
330
+ }
331
+
332
+ parts.push('---');
333
+ parts.push(`*Generated by Mandu Kitchen DevTools v${context.devtools.version}*`);
334
+
335
+ return parts.join('\n');
336
+ }
337
+
338
+ // --------------------------------------------------------------------------
339
+ // Internal
340
+ // --------------------------------------------------------------------------
341
+
342
+ private setStatus(status: MCPConnectionStatus): void {
343
+ if (this.status !== status) {
344
+ this.status = status;
345
+ for (const listener of this.statusListeners) {
346
+ try {
347
+ listener(status);
348
+ } catch {
349
+ // 리스너 에러 무시
350
+ }
351
+ }
352
+ }
353
+ }
354
+
355
+ private handleMessage(data: string): void {
356
+ try {
357
+ const message: MCPMessage = JSON.parse(data);
358
+
359
+ if (message.type === 'response' && message.id) {
360
+ const pending = this.pendingRequests.get(message.id);
361
+ if (pending) {
362
+ clearTimeout(pending.timeout);
363
+ this.pendingRequests.delete(message.id);
364
+
365
+ if (message.error) {
366
+ pending.reject(new Error(message.error.message));
367
+ } else {
368
+ pending.resolve(message.result);
369
+ }
370
+ }
371
+ }
372
+ } catch (error) {
373
+ console.warn('[Mandu Kitchen] Failed to parse MCP message:', error);
374
+ }
375
+ }
376
+
377
+ private handleDisconnect(): void {
378
+ this.ws = null;
379
+
380
+ if (this.options.autoReconnect && this.status !== 'disconnected') {
381
+ this.setStatus('error');
382
+ this.scheduleReconnect();
383
+ } else {
384
+ this.setStatus('disconnected');
385
+ }
386
+ }
387
+
388
+ private handleConnectionError(error: Error): void {
389
+ console.warn('[Mandu Kitchen] MCP connection error:', error.message);
390
+ this.setStatus('error');
391
+
392
+ if (this.options.autoReconnect) {
393
+ this.scheduleReconnect();
394
+ }
395
+ }
396
+
397
+ private scheduleReconnect(): void {
398
+ if (this.reconnectAttempts >= this.options.maxReconnectAttempts) {
399
+ console.warn('[Mandu Kitchen] Max reconnection attempts reached');
400
+ this.setStatus('disconnected');
401
+ return;
402
+ }
403
+
404
+ this.reconnectAttempts++;
405
+ console.log(
406
+ `[Mandu Kitchen] Reconnecting in ${this.options.reconnectInterval}ms (attempt ${this.reconnectAttempts}/${this.options.maxReconnectAttempts})`
407
+ );
408
+
409
+ this.reconnectTimer = setTimeout(() => {
410
+ this.connect().catch(() => {
411
+ // 에러는 handleConnectionError에서 처리됨
412
+ });
413
+ }, this.options.reconnectInterval);
414
+ }
415
+
416
+ private async sendRequest<T>(method: string, params: unknown): Promise<T> {
417
+ if (!this.ws || this.status !== 'connected') {
418
+ throw new Error('Not connected to MCP server');
419
+ }
420
+
421
+ const id = `req-${++this.requestIdCounter}`;
422
+
423
+ return new Promise<T>((resolve, reject) => {
424
+ const timeout = setTimeout(() => {
425
+ this.pendingRequests.delete(id);
426
+ reject(new Error('Request timeout'));
427
+ }, this.options.requestTimeout);
428
+
429
+ this.pendingRequests.set(id, {
430
+ resolve: resolve as (result: unknown) => void,
431
+ reject,
432
+ timeout,
433
+ });
434
+
435
+ const message: MCPMessage = {
436
+ id,
437
+ type: 'request',
438
+ method,
439
+ params,
440
+ };
441
+
442
+ this.ws!.send(JSON.stringify(message));
443
+ });
444
+ }
445
+ }
446
+
447
+ // ============================================================================
448
+ // Singleton Instance
449
+ // ============================================================================
450
+
451
+ let globalMCPConnector: MCPConnector | null = null;
452
+
453
+ export function getMCPConnector(options?: MCPConnectorOptions): MCPConnector {
454
+ if (!globalMCPConnector) {
455
+ globalMCPConnector = new MCPConnector(options);
456
+ }
457
+ return globalMCPConnector;
458
+ }
459
+
460
+ export function destroyMCPConnector(): void {
461
+ if (globalMCPConnector) {
462
+ globalMCPConnector.disconnect();
463
+ globalMCPConnector = null;
464
+ }
465
+ }