@mandujs/core 0.9.31 → 0.9.37

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,278 @@
1
+ /**
2
+ * FS Routes Types
3
+ *
4
+ * 파일 시스템 기반 라우팅 타입 정의
5
+ *
6
+ * @module router/fs-types
7
+ */
8
+
9
+ import type { RouteKind, HydrationConfig, HttpMethod } from "../spec/schema";
10
+
11
+ // ═══════════════════════════════════════════════════════════════════════════
12
+ // Segment Types
13
+ // ═══════════════════════════════════════════════════════════════════════════
14
+
15
+ /**
16
+ * 라우트 세그먼트 타입
17
+ */
18
+ export type SegmentType =
19
+ | "static" // 정적 세그먼트 (예: "blog")
20
+ | "dynamic" // 동적 세그먼트 (예: "[slug]")
21
+ | "catchAll" // Catch-all 세그먼트 (예: "[...path]")
22
+ | "optionalCatchAll" // Optional catch-all (예: "[[...path]]")
23
+ | "group"; // 라우트 그룹 (예: "(marketing)")
24
+
25
+ /**
26
+ * 파싱된 라우트 세그먼트
27
+ */
28
+ export interface RouteSegment {
29
+ /** 원본 세그먼트 이름 */
30
+ raw: string;
31
+
32
+ /** 세그먼트 타입 */
33
+ type: SegmentType;
34
+
35
+ /** 파라미터 이름 (동적 세그먼트의 경우) */
36
+ paramName?: string;
37
+ }
38
+
39
+ // ═══════════════════════════════════════════════════════════════════════════
40
+ // File Types
41
+ // ═══════════════════════════════════════════════════════════════════════════
42
+
43
+ /**
44
+ * 스캔된 파일 타입
45
+ */
46
+ export type ScannedFileType =
47
+ | "page" // page.tsx - 페이지 컴포넌트
48
+ | "layout" // layout.tsx - 레이아웃
49
+ | "route" // route.ts - API 핸들러
50
+ | "loading" // loading.tsx - 로딩 UI
51
+ | "error" // error.tsx - 에러 UI
52
+ | "not-found" // not-found.tsx - 404 UI
53
+ | "island"; // *.island.tsx - Island 컴포넌트
54
+
55
+ /**
56
+ * 스캔된 파일 정보
57
+ */
58
+ export interface ScannedFile {
59
+ /** 절대 경로 */
60
+ absolutePath: string;
61
+
62
+ /** 라우트 루트 기준 상대 경로 */
63
+ relativePath: string;
64
+
65
+ /** 파일 타입 */
66
+ type: ScannedFileType;
67
+
68
+ /** 파싱된 경로 세그먼트 */
69
+ segments: RouteSegment[];
70
+
71
+ /** 파일 확장자 */
72
+ extension: string;
73
+ }
74
+
75
+ // ═══════════════════════════════════════════════════════════════════════════
76
+ // Route Config Types
77
+ // ═══════════════════════════════════════════════════════════════════════════
78
+
79
+ /**
80
+ * FS Routes에서 생성된 라우트 설정
81
+ */
82
+ export interface FSRouteConfig {
83
+ /** 라우트 ID (자동 생성) */
84
+ id: string;
85
+
86
+ /** 파싱된 경로 세그먼트 */
87
+ segments: RouteSegment[];
88
+
89
+ /** URL 패턴 (예: "/blog/:slug") */
90
+ pattern: string;
91
+
92
+ /** 라우트 종류 */
93
+ kind: RouteKind;
94
+
95
+ /** HTTP 메서드 (API 라우트용) */
96
+ methods?: HttpMethod[];
97
+
98
+ /** 페이지 컴포넌트 모듈 경로 */
99
+ componentModule?: string;
100
+
101
+ /** API 핸들러 모듈 경로 */
102
+ module: string;
103
+
104
+ /** Island 컴포넌트 모듈 경로 */
105
+ clientModule?: string;
106
+
107
+ /** 적용할 레이아웃 체인 */
108
+ layoutChain: string[];
109
+
110
+ /** 로딩 UI 모듈 경로 */
111
+ loadingModule?: string;
112
+
113
+ /** 에러 UI 모듈 경로 */
114
+ errorModule?: string;
115
+
116
+ /** Hydration 설정 */
117
+ hydration?: HydrationConfig;
118
+
119
+ /** 원본 파일 경로 */
120
+ sourceFile: string;
121
+ }
122
+
123
+ // ═══════════════════════════════════════════════════════════════════════════
124
+ // Scanner Config Types
125
+ // ═══════════════════════════════════════════════════════════════════════════
126
+
127
+ /**
128
+ * FS Routes 스캐너 설정
129
+ */
130
+ export interface FSScannerConfig {
131
+ /** 라우트 루트 디렉토리 (기본: "app") */
132
+ routesDir: string;
133
+
134
+ /** 지원 확장자 (기본: [".tsx", ".ts", ".jsx", ".js"]) */
135
+ extensions: string[];
136
+
137
+ /** 제외 패턴 (glob) */
138
+ exclude: string[];
139
+
140
+ /** Island 파일 접미사 (기본: ".island") */
141
+ islandSuffix: string;
142
+
143
+ /** 레거시 매니페스트 경로 (병합용) */
144
+ legacyManifestPath?: string;
145
+
146
+ /** 레거시 매니페스트와 병합 여부 */
147
+ mergeWithLegacy: boolean;
148
+ }
149
+
150
+ /**
151
+ * 기본 스캐너 설정
152
+ */
153
+ export const DEFAULT_SCANNER_CONFIG: FSScannerConfig = {
154
+ routesDir: "app",
155
+ extensions: [".tsx", ".ts", ".jsx", ".js"],
156
+ exclude: [
157
+ "**/*.test.ts",
158
+ "**/*.test.tsx",
159
+ "**/*.spec.ts",
160
+ "**/*.spec.tsx",
161
+ "**/_*/**", // 비공개 폴더
162
+ "**/node_modules/**",
163
+ ],
164
+ islandSuffix: ".island",
165
+ legacyManifestPath: "spec/routes.manifest.json",
166
+ mergeWithLegacy: true,
167
+ };
168
+
169
+ // ═══════════════════════════════════════════════════════════════════════════
170
+ // Scan Result Types
171
+ // ═══════════════════════════════════════════════════════════════════════════
172
+
173
+ /**
174
+ * 디렉토리 스캔 결과
175
+ */
176
+ export interface ScanResult {
177
+ /** 스캔된 파일 목록 */
178
+ files: ScannedFile[];
179
+
180
+ /** 생성된 라우트 설정 */
181
+ routes: FSRouteConfig[];
182
+
183
+ /** 에러 목록 */
184
+ errors: ScanError[];
185
+
186
+ /** 스캔 통계 */
187
+ stats: ScanStats;
188
+ }
189
+
190
+ /**
191
+ * 스캔 에러
192
+ */
193
+ export interface ScanError {
194
+ /** 에러 타입 */
195
+ type: "invalid_segment" | "duplicate_route" | "file_read_error" | "pattern_conflict";
196
+
197
+ /** 에러 메시지 */
198
+ message: string;
199
+
200
+ /** 관련 파일 경로 */
201
+ filePath?: string;
202
+
203
+ /** 충돌하는 파일 경로 (duplicate_route의 경우) */
204
+ conflictsWith?: string;
205
+ }
206
+
207
+ /**
208
+ * 스캔 통계
209
+ */
210
+ export interface ScanStats {
211
+ /** 총 스캔 파일 수 */
212
+ totalFiles: number;
213
+
214
+ /** 페이지 수 */
215
+ pageCount: number;
216
+
217
+ /** API 라우트 수 */
218
+ apiCount: number;
219
+
220
+ /** 레이아웃 수 */
221
+ layoutCount: number;
222
+
223
+ /** Island 수 */
224
+ islandCount: number;
225
+
226
+ /** 스캔 소요 시간 (ms) */
227
+ scanTime: number;
228
+ }
229
+
230
+ // ═══════════════════════════════════════════════════════════════════════════
231
+ // Pattern Constants
232
+ // ═══════════════════════════════════════════════════════════════════════════
233
+
234
+ /**
235
+ * 파일명 패턴
236
+ */
237
+ export const FILE_PATTERNS = {
238
+ /** 페이지 파일 */
239
+ page: /^page\.(tsx?|jsx?)$/,
240
+
241
+ /** 레이아웃 파일 */
242
+ layout: /^layout\.(tsx?|jsx?)$/,
243
+
244
+ /** API 라우트 파일 */
245
+ route: /^route\.(ts|js)$/,
246
+
247
+ /** 로딩 UI 파일 */
248
+ loading: /^loading\.(tsx?|jsx?)$/,
249
+
250
+ /** 에러 UI 파일 */
251
+ error: /^error\.(tsx?|jsx?)$/,
252
+
253
+ /** 404 파일 */
254
+ notFound: /^not-found\.(tsx?|jsx?)$/,
255
+
256
+ /** Island 파일 */
257
+ island: /\.island\.(tsx?|jsx?)$/,
258
+ } as const;
259
+
260
+ /**
261
+ * 세그먼트 패턴
262
+ */
263
+ export const SEGMENT_PATTERNS = {
264
+ /** 동적 세그먼트: [param] */
265
+ dynamic: /^\[([^\[\]\.]+)\]$/,
266
+
267
+ /** Catch-all: [...param] */
268
+ catchAll: /^\[\.\.\.([^\[\]]+)\]$/,
269
+
270
+ /** Optional catch-all: [[...param]] */
271
+ optionalCatchAll: /^\[\[\.\.\.([^\[\]]+)\]\]$/,
272
+
273
+ /** 라우트 그룹: (name) */
274
+ group: /^\(([^()]+)\)$/,
275
+
276
+ /** 비공개 폴더: _name */
277
+ private: /^_/,
278
+ } as const;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * FS Routes Module
3
+ *
4
+ * 파일 시스템 기반 라우팅 시스템
5
+ *
6
+ * @module router
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { scanRoutes, generateManifest, watchFSRoutes } from "@mandujs/core/router";
11
+ *
12
+ * // 간편 스캔
13
+ * const result = await scanRoutes("/path/to/project");
14
+ * console.log(result.routes);
15
+ *
16
+ * // 매니페스트 생성
17
+ * const { manifest } = await generateManifest("/path/to/project", {
18
+ * outputPath: ".mandu/manifest.json"
19
+ * });
20
+ *
21
+ * // 감시 모드
22
+ * const watcher = await watchFSRoutes("/path/to/project", {
23
+ * onChange: (result) => console.log("Routes updated!")
24
+ * });
25
+ * ```
26
+ */
27
+
28
+ // Types
29
+ export type {
30
+ // Segment types
31
+ SegmentType,
32
+ RouteSegment,
33
+
34
+ // File types
35
+ ScannedFileType,
36
+ ScannedFile,
37
+
38
+ // Route config
39
+ FSRouteConfig,
40
+
41
+ // Scanner config
42
+ FSScannerConfig,
43
+
44
+ // Results
45
+ ScanResult,
46
+ ScanError,
47
+ ScanStats,
48
+ } from "./fs-types";
49
+
50
+ export { DEFAULT_SCANNER_CONFIG, FILE_PATTERNS, SEGMENT_PATTERNS } from "./fs-types";
51
+
52
+ // Pattern utilities
53
+ export {
54
+ parseSegment,
55
+ parseSegments,
56
+ segmentsToPattern,
57
+ pathToPattern,
58
+ detectFileType,
59
+ isPrivateFolder,
60
+ isGroupFolder,
61
+ generateRouteId,
62
+ calculateRoutePriority,
63
+ sortRoutesByPriority,
64
+ validateSegments,
65
+ patternsConflict,
66
+ } from "./fs-patterns";
67
+
68
+ // Scanner
69
+ export { FSScanner, createFSScanner, scanRoutes } from "./fs-scanner";
70
+
71
+ // Generator
72
+ export type { GenerateResult, GenerateOptions, RouteChangeCallback, FSRoutesWatcher } from "./fs-routes";
73
+
74
+ export {
75
+ fsRouteToRouteSpec,
76
+ scanResultToManifest,
77
+ mergeManifests,
78
+ generateManifest,
79
+ watchFSRoutes,
80
+ formatRoutesForCLI,
81
+ } from "./fs-routes";
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Mandu Boundary Components
3
+ *
4
+ * Loading (Suspense) 및 Error (ErrorBoundary) UI 래퍼
5
+ *
6
+ * @module runtime/boundary
7
+ */
8
+
9
+ import React, { Suspense, Component, type ReactNode, type ErrorInfo } from "react";
10
+
11
+ // ═══════════════════════════════════════════════════════════════════════════
12
+ // Types
13
+ // ═══════════════════════════════════════════════════════════════════════════
14
+
15
+ export interface LoadingBoundaryProps {
16
+ /** 로딩 중 표시할 컴포넌트 */
17
+ fallback: ReactNode;
18
+ /** 자식 컴포넌트 */
19
+ children: ReactNode;
20
+ }
21
+
22
+ export interface ErrorBoundaryProps {
23
+ /** 에러 발생 시 표시할 컴포넌트 */
24
+ fallback: React.ComponentType<ErrorFallbackProps>;
25
+ /** 자식 컴포넌트 */
26
+ children: ReactNode;
27
+ /** 에러 발생 시 콜백 */
28
+ onError?: (error: Error, errorInfo: ErrorInfo) => void;
29
+ }
30
+
31
+ export interface ErrorFallbackProps {
32
+ /** 발생한 에러 */
33
+ error: Error;
34
+ /** 에러 정보 */
35
+ errorInfo?: ErrorInfo;
36
+ /** 리셋 함수 (에러 상태 초기화) */
37
+ resetError: () => void;
38
+ }
39
+
40
+ interface ErrorBoundaryState {
41
+ hasError: boolean;
42
+ error: Error | null;
43
+ errorInfo: ErrorInfo | null;
44
+ }
45
+
46
+ // ═══════════════════════════════════════════════════════════════════════════
47
+ // Loading Boundary (Suspense Wrapper)
48
+ // ═══════════════════════════════════════════════════════════════════════════
49
+
50
+ /**
51
+ * Loading Boundary - Suspense 래퍼
52
+ *
53
+ * @example
54
+ * ```tsx
55
+ * <LoadingBoundary fallback={<Loading />}>
56
+ * <AsyncComponent />
57
+ * </LoadingBoundary>
58
+ * ```
59
+ */
60
+ export function LoadingBoundary({ fallback, children }: LoadingBoundaryProps): JSX.Element {
61
+ return <Suspense fallback={fallback}>{children}</Suspense>;
62
+ }
63
+
64
+ // ═══════════════════════════════════════════════════════════════════════════
65
+ // Error Boundary (Class Component)
66
+ // ═══════════════════════════════════════════════════════════════════════════
67
+
68
+ /**
69
+ * Error Boundary - 에러 캐치 및 fallback UI 표시
70
+ *
71
+ * @example
72
+ * ```tsx
73
+ * <ErrorBoundary fallback={ErrorFallback}>
74
+ * <RiskyComponent />
75
+ * </ErrorBoundary>
76
+ * ```
77
+ */
78
+ export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
79
+ constructor(props: ErrorBoundaryProps) {
80
+ super(props);
81
+ this.state = {
82
+ hasError: false,
83
+ error: null,
84
+ errorInfo: null,
85
+ };
86
+ }
87
+
88
+ static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
89
+ return { hasError: true, error };
90
+ }
91
+
92
+ componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
93
+ this.setState({ errorInfo });
94
+ this.props.onError?.(error, errorInfo);
95
+ }
96
+
97
+ resetError = (): void => {
98
+ this.setState({
99
+ hasError: false,
100
+ error: null,
101
+ errorInfo: null,
102
+ });
103
+ };
104
+
105
+ render(): ReactNode {
106
+ const { hasError, error, errorInfo } = this.state;
107
+ const { fallback: Fallback, children } = this.props;
108
+
109
+ if (hasError && error) {
110
+ return (
111
+ <Fallback
112
+ error={error}
113
+ errorInfo={errorInfo ?? undefined}
114
+ resetError={this.resetError}
115
+ />
116
+ );
117
+ }
118
+
119
+ return children;
120
+ }
121
+ }
122
+
123
+ // ═══════════════════════════════════════════════════════════════════════════
124
+ // Default Fallback Components
125
+ // ═══════════════════════════════════════════════════════════════════════════
126
+
127
+ /**
128
+ * 기본 로딩 컴포넌트
129
+ */
130
+ export function DefaultLoading(): JSX.Element {
131
+ return (
132
+ <div
133
+ style={{
134
+ display: "flex",
135
+ justifyContent: "center",
136
+ alignItems: "center",
137
+ padding: "2rem",
138
+ color: "#666",
139
+ }}
140
+ >
141
+ <div>Loading...</div>
142
+ </div>
143
+ );
144
+ }
145
+
146
+ /**
147
+ * 기본 에러 컴포넌트
148
+ */
149
+ export function DefaultError({ error, resetError }: ErrorFallbackProps): JSX.Element {
150
+ return (
151
+ <div
152
+ style={{
153
+ padding: "2rem",
154
+ backgroundColor: "#fff3f3",
155
+ border: "1px solid #ffcccc",
156
+ borderRadius: "8px",
157
+ margin: "1rem",
158
+ }}
159
+ >
160
+ <h2 style={{ color: "#cc0000", marginTop: 0 }}>Something went wrong</h2>
161
+ <pre
162
+ style={{
163
+ backgroundColor: "#f5f5f5",
164
+ padding: "1rem",
165
+ borderRadius: "4px",
166
+ overflow: "auto",
167
+ fontSize: "0.875rem",
168
+ }}
169
+ >
170
+ {error.message}
171
+ </pre>
172
+ <button
173
+ onClick={resetError}
174
+ style={{
175
+ marginTop: "1rem",
176
+ padding: "0.5rem 1rem",
177
+ backgroundColor: "#cc0000",
178
+ color: "white",
179
+ border: "none",
180
+ borderRadius: "4px",
181
+ cursor: "pointer",
182
+ }}
183
+ >
184
+ Try again
185
+ </button>
186
+ </div>
187
+ );
188
+ }
189
+
190
+ // ═══════════════════════════════════════════════════════════════════════════
191
+ // Combined Boundary
192
+ // ═══════════════════════════════════════════════════════════════════════════
193
+
194
+ export interface PageBoundaryProps {
195
+ /** 로딩 컴포넌트 (옵션) */
196
+ loadingComponent?: ReactNode;
197
+ /** 에러 컴포넌트 (옵션) */
198
+ errorComponent?: React.ComponentType<ErrorFallbackProps>;
199
+ /** 자식 컴포넌트 */
200
+ children: ReactNode;
201
+ /** 에러 발생 시 콜백 */
202
+ onError?: (error: Error, errorInfo: ErrorInfo) => void;
203
+ }
204
+
205
+ /**
206
+ * Page Boundary - Loading + Error 래퍼
207
+ *
208
+ * @example
209
+ * ```tsx
210
+ * <PageBoundary
211
+ * loadingComponent={<CustomLoading />}
212
+ * errorComponent={CustomError}
213
+ * >
214
+ * <PageContent />
215
+ * </PageBoundary>
216
+ * ```
217
+ */
218
+ export function PageBoundary({
219
+ loadingComponent,
220
+ errorComponent,
221
+ children,
222
+ onError,
223
+ }: PageBoundaryProps): JSX.Element {
224
+ const LoadingFallback = loadingComponent ?? <DefaultLoading />;
225
+ const ErrorFallback = errorComponent ?? DefaultError;
226
+
227
+ return (
228
+ <ErrorBoundary fallback={ErrorFallback} onError={onError}>
229
+ <LoadingBoundary fallback={LoadingFallback}>{children}</LoadingBoundary>
230
+ </ErrorBoundary>
231
+ );
232
+ }
@@ -7,3 +7,4 @@ export * from "./compose";
7
7
  export * from "./lifecycle";
8
8
  export * from "./trace";
9
9
  export * from "./logger";
10
+ export * from "./boundary";
@@ -138,6 +138,41 @@ describe("Wildcard Matching", () => {
138
138
  expect(result!.params).toEqual({ [WILDCARD_PARAM_KEY]: "a/b/c" });
139
139
  });
140
140
 
141
+ test("matches named wildcard with remaining path", () => {
142
+ const router = createRouter([
143
+ makeRoute("docs", "/docs/:path*"),
144
+ ]);
145
+
146
+ const result = router.match("/docs/a/b/c");
147
+
148
+ expect(result).not.toBeNull();
149
+ expect(result!.route.id).toBe("docs");
150
+ expect(result!.params).toEqual({ path: "a/b/c" });
151
+ });
152
+
153
+ test("optional wildcard matches base path without param", () => {
154
+ const router = createRouter([
155
+ makeRoute("docs", "/docs/:path*?"),
156
+ ]);
157
+
158
+ const result = router.match("/docs");
159
+
160
+ expect(result).not.toBeNull();
161
+ expect(result!.route.id).toBe("docs");
162
+ expect(result!.params).toEqual({});
163
+ });
164
+
165
+ test("optional wildcard matches with remaining path", () => {
166
+ const router = createRouter([
167
+ makeRoute("docs", "/docs/:path*?"),
168
+ ]);
169
+
170
+ const result = router.match("/docs/intro");
171
+
172
+ expect(result).not.toBeNull();
173
+ expect(result!.params).toEqual({ path: "intro" });
174
+ });
175
+
141
176
  test("wildcard with single segment", () => {
142
177
  const router = createRouter([
143
178
  makeRoute("docs", "/docs/*"),
@@ -308,6 +343,24 @@ describe("Validation Errors", () => {
308
343
  expect((e as RouterError).code).toBe("WILDCARD_NOT_LAST");
309
344
  }
310
345
  });
346
+
347
+ test("throws ROUTE_CONFLICT for wildcard conflicts", () => {
348
+ expect(() => {
349
+ createRouter([
350
+ makeRoute("files-legacy", "/files/*"),
351
+ makeRoute("files-named", "/files/:path*"),
352
+ ]);
353
+ }).toThrow(RouterError);
354
+
355
+ try {
356
+ createRouter([
357
+ makeRoute("files-legacy", "/files/*"),
358
+ makeRoute("files-named", "/files/:path*"),
359
+ ]);
360
+ } catch (e) {
361
+ expect((e as RouterError).code).toBe("ROUTE_CONFLICT");
362
+ }
363
+ });
311
364
  });
312
365
 
313
366
  // ═══════════════════════════════════════════════════════════════════════════