@mandujs/core 0.18.18 → 0.18.20

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mandujs/core",
3
- "version": "0.18.18",
3
+ "version": "0.18.20",
4
4
  "description": "Mandu Framework Core - Spec, Generator, Guard, Runtime",
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -19,6 +19,11 @@ export interface DevBundlerOptions {
19
19
  onRebuild?: (result: RebuildResult) => void;
20
20
  /** 에러 콜백 */
21
21
  onError?: (error: Error, routeId?: string) => void;
22
+ /**
23
+ * SSR 파일 변경 콜백 (page.tsx, layout.tsx 등)
24
+ * 클라이언트 번들 리빌드 없이 서버 핸들러 재등록이 필요한 경우 호출
25
+ */
26
+ onSSRChange?: (filePath: string) => void;
22
27
  /**
23
28
  * 추가 watch 디렉토리 (공통 컴포넌트 등)
24
29
  * 상대 경로 또는 절대 경로 모두 지원
@@ -75,6 +80,7 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
75
80
  manifest,
76
81
  onRebuild,
77
82
  onError,
83
+ onSSRChange,
78
84
  watchDirs: customWatchDirs = [],
79
85
  disableDefaultWatchDirs = false,
80
86
  } = options;
@@ -94,6 +100,7 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
94
100
 
95
101
  // clientModule 경로에서 routeId 매핑 생성
96
102
  const clientModuleToRoute = new Map<string, string>();
103
+ const serverModuleSet = new Set<string>(); // SSR 모듈 (page.tsx, layout.tsx)
97
104
  const watchDirs = new Set<string>();
98
105
  const commonWatchDirs = new Set<string>(); // 공통 디렉토리 (전체 재빌드 트리거)
99
106
 
@@ -117,6 +124,20 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
117
124
  // 감시할 디렉토리 추가
118
125
  watchDirs.add(dir);
119
126
  }
127
+
128
+ // SSR 모듈 등록 (page.tsx, layout.tsx) — #151
129
+ if (route.componentModule) {
130
+ const absPath = path.resolve(rootDir, route.componentModule).replace(/\\/g, "/");
131
+ serverModuleSet.add(absPath);
132
+ watchDirs.add(path.dirname(path.resolve(rootDir, route.componentModule)));
133
+ }
134
+ if (route.layoutChain) {
135
+ for (const layoutPath of route.layoutChain) {
136
+ const absPath = path.resolve(rootDir, layoutPath).replace(/\\/g, "/");
137
+ serverModuleSet.add(absPath);
138
+ watchDirs.add(path.dirname(path.resolve(rootDir, layoutPath)));
139
+ }
140
+ }
120
141
  }
121
142
 
122
143
  // spec/slots 디렉토리도 추가
@@ -248,7 +269,14 @@ export async function startDevBundler(options: DevBundlerOptions): Promise<DevBu
248
269
  }
249
270
  }
250
271
 
251
- if (!routeId) return;
272
+ if (!routeId) {
273
+ // SSR 모듈 변경 감지 (page.tsx, layout.tsx) — #151
274
+ if (onSSRChange && serverModuleSet.has(normalizedPath)) {
275
+ console.log(`\n🔄 SSR file changed: ${path.basename(changedFile)}`);
276
+ onSSRChange(normalizedPath);
277
+ }
278
+ return;
279
+ }
252
280
 
253
281
  const route = manifest.routes.find((r) => r.id === routeId);
254
282
  if (!route || !route.clientModule) return;
@@ -1,512 +1,549 @@
1
- /**
2
- * FS Routes Scanner
3
- *
4
- * 파일 시스템을 스캔하여 라우트 파일을 탐지
5
- *
6
- * @module router/fs-scanner
7
- */
8
-
9
- import { stat } from "fs/promises";
10
- import { join, relative, basename, extname } from "path";
11
- import type {
12
- ScannedFile,
13
- FSScannerConfig,
14
- ScanResult,
15
- ScanError,
16
- ScanStats,
17
- FSRouteConfig,
18
- } from "./fs-types";
19
- import { DEFAULT_SCANNER_CONFIG } from "./fs-types";
20
- import {
21
- parseSegments,
22
- segmentsToPattern,
23
- detectFileType,
24
- isPrivateFolder,
25
- generateRouteId,
26
- validateSegments,
27
- sortRoutesByPriority,
28
- getPatternShape,
29
- } from "./fs-patterns";
30
-
31
- // ═══════════════════════════════════════════════════════════════════════════
32
- // Scanner Class
33
- // ═══════════════════════════════════════════════════════════════════════════
34
-
35
- /**
36
- * FS Routes 스캐너
37
- *
38
- * @example
39
- * const scanner = new FSScanner({ routesDir: "app" });
40
- * const result = await scanner.scan("/path/to/project");
41
- */
42
- export class FSScanner {
43
- private config: FSScannerConfig;
44
- private excludeMatchers: RegExp[];
45
-
46
- constructor(config: Partial<FSScannerConfig> = {}) {
47
- this.config = { ...DEFAULT_SCANNER_CONFIG, ...config };
48
- this.excludeMatchers = this.config.exclude.map(globToRegExp);
49
- }
50
-
51
- /**
52
- * 디렉토리 스캔 수행
53
- *
54
- * @param rootDir 프로젝트 루트 디렉토리
55
- * @returns 스캔 결과
56
- */
57
- async scan(rootDir: string): Promise<ScanResult> {
58
- const startTime = Date.now();
59
- const routesDir = join(rootDir, this.config.routesDir);
60
-
61
- const files: ScannedFile[] = [];
62
- const errors: ScanError[] = [];
63
-
64
- // 라우트 디렉토리 존재 확인
65
- try {
66
- const dirStat = await stat(routesDir);
67
- if (!dirStat.isDirectory()) {
68
- errors.push({
69
- type: "file_read_error",
70
- message: `${this.config.routesDir} is not a directory`,
71
- filePath: routesDir,
72
- });
73
- return this.createEmptyResult(errors, Date.now() - startTime);
74
- }
75
- } catch {
76
- // 디렉토리가 없으면 빈 결과 반환 (에러 아님)
77
- return this.createEmptyResult([], Date.now() - startTime);
78
- }
79
-
80
- // Bun.Glob 기반 스캔
81
- await this.scanWithGlob(rootDir, routesDir, files, errors);
82
-
83
- // 라우트 설정 생성
84
- const { routes, routeErrors } = await this.createRouteConfigs(files, rootDir);
85
- errors.push(...routeErrors);
86
-
87
- // 통계 계산
88
- const stats = this.calculateStats(files, routes, Date.now() - startTime);
89
-
90
- return {
91
- files,
92
- routes: sortRoutesByPriority(routes),
93
- errors,
94
- stats,
95
- };
96
- }
97
-
98
- /**
99
- * Bun.Glob 기반 스캔
100
- */
101
- private async scanWithGlob(
102
- rootDir: string,
103
- routesRoot: string,
104
- files: ScannedFile[],
105
- errors: ScanError[]
106
- ): Promise<void> {
107
- const routesDirPattern = this.config.routesDir.replace(/\\/g, "/").replace(/\/+$/, "");
108
- const extensions = this.config.extensions
109
- .map((ext) => ext.replace(/^\./, ""))
110
- .filter(Boolean)
111
- .join(",");
112
-
113
- if (!routesDirPattern || !extensions) {
114
- return;
115
- }
116
-
117
- const pattern = `${routesDirPattern}/**/*.{${extensions}}`;
118
- const glob = new Bun.Glob(pattern);
119
- const foundFiles: string[] = [];
120
-
121
- try {
122
- for await (const filePath of glob.scan({ cwd: rootDir, absolute: true })) {
123
- foundFiles.push(filePath);
124
- }
125
- } catch (error) {
126
- errors.push({
127
- type: "file_read_error",
128
- message: `Failed to scan directory: ${error instanceof Error ? error.message : String(error)}`,
129
- filePath: routesRoot,
130
- });
131
- return;
132
- }
133
-
134
- foundFiles.sort((a, b) => a.localeCompare(b));
135
-
136
- for (const fullPath of foundFiles) {
137
- const relativePath = relative(routesRoot, fullPath).replace(/\\/g, "/");
138
- if (relativePath.startsWith("..")) {
139
- continue;
140
- }
141
-
142
- if (this.isExcluded(relativePath, false)) {
143
- continue;
144
- }
145
-
146
- if (this.hasPrivateSegment(relativePath)) {
147
- continue;
148
- }
149
-
150
- const pathSegments = relativePath.split("/");
151
- if (pathSegments.includes("node_modules")) {
152
- continue;
153
- }
154
-
155
- const fileName = basename(fullPath);
156
- const ext = extname(fileName);
157
- if (!this.config.extensions.includes(ext)) {
158
- continue;
159
- }
160
-
161
- const fileType = detectFileType(fileName, this.config.islandSuffix);
162
- if (!fileType) {
163
- continue;
164
- }
165
-
166
- const segments = parseSegments(relativePath);
167
- const validation = validateSegments(segments);
168
- if (!validation.valid) {
169
- errors.push({
170
- type: "invalid_segment",
171
- message: validation.error!,
172
- filePath: fullPath,
173
- });
174
- continue;
175
- }
176
-
177
- files.push({
178
- absolutePath: fullPath,
179
- relativePath,
180
- type: fileType,
181
- segments,
182
- extension: ext,
183
- });
184
- }
185
- }
186
-
187
- /**
188
- * 스캔된 파일에서 라우트 설정 생성
189
- */
190
- private async createRouteConfigs(
191
- files: ScannedFile[],
192
- rootDir: string
193
- ): Promise<{ routes: FSRouteConfig[]; routeErrors: ScanError[] }> {
194
- const routes: FSRouteConfig[] = [];
195
- const routeErrors: ScanError[] = [];
196
-
197
- // 패턴별 라우트 매핑 (중복/충돌 감지용)
198
- const patternMap = new Map<string, FSRouteConfig>();
199
- const shapeMap = new Map<string, FSRouteConfig>();
200
-
201
- // 파일 맵 수집 (single pass)
202
- const layoutMap = new Map<string, ScannedFile>();
203
- const loadingMap = new Map<string, ScannedFile>();
204
- const errorMap = new Map<string, ScannedFile>();
205
- const islandMap = new Map<string, ScannedFile[]>();
206
- const routeFiles: ScannedFile[] = [];
207
-
208
- for (const file of files) {
209
- const dirPath = this.getDirPath(file.relativePath);
210
-
211
- switch (file.type) {
212
- case "layout":
213
- layoutMap.set(dirPath, file);
214
- break;
215
- case "loading":
216
- loadingMap.set(dirPath, file);
217
- break;
218
- case "error":
219
- errorMap.set(dirPath, file);
220
- break;
221
- case "island": {
222
- const existing = islandMap.get(dirPath);
223
- if (existing) {
224
- existing.push(file);
225
- } else {
226
- islandMap.set(dirPath, [file]);
227
- }
228
- break;
229
- }
230
- case "page":
231
- case "route":
232
- routeFiles.push(file);
233
- break;
234
- default:
235
- break;
236
- }
237
- }
238
-
239
- // 페이지 및 API 라우트 처리
240
- for (const file of routeFiles) {
241
- const pattern = segmentsToPattern(file.segments);
242
- const patternShape = getPatternShape(pattern);
243
- const routeId = generateRouteId(file.relativePath);
244
- const modulePath = join(this.config.routesDir, file.relativePath);
245
-
246
- // 중복 패턴 체크
247
- const existingRoute = patternMap.get(pattern);
248
- if (existingRoute) {
249
- routeErrors.push({
250
- type: "duplicate_route",
251
- message: `Duplicate route pattern "${pattern}"`,
252
- filePath: file.absolutePath,
253
- conflictsWith: existingRoute.sourceFile,
254
- });
255
- continue;
256
- }
257
-
258
- // 패턴 충돌 체크 (파라미터 이름만 다른 경우 등)
259
- const conflictingRoute = shapeMap.get(patternShape);
260
- if (conflictingRoute) {
261
- routeErrors.push({
262
- type: "pattern_conflict",
263
- message: `Route pattern "${pattern}" conflicts with "${conflictingRoute.pattern}"`,
264
- filePath: file.absolutePath,
265
- conflictsWith: conflictingRoute.sourceFile,
266
- });
267
- continue;
268
- }
269
-
270
- // 레이아웃 체인 구성
271
- const layoutChain = this.resolveLayoutChain(file.segments, layoutMap);
272
-
273
- // Island 파일 찾기 (같은 디렉토리)
274
- const dirPath = this.getDirPath(file.relativePath);
275
- const islands = islandMap.get(dirPath);
276
-
277
- // clientModule 결정: island 파일 또는 "use client"가 있는 page 자체
278
- let clientModule: string | undefined;
279
- if (islands?.[0]) {
280
- // 우선순위: 명시적 island 파일
281
- clientModule = join(this.config.routesDir, islands[0].relativePath);
282
- } else if (file.type === "page") {
283
- // page 파일 자체에서 "use client" 확인
284
- try {
285
- const fileContent = await Bun.file(file.absolutePath).text();
286
- const hasUseClient = /^\s*["']use client["']/m.test(fileContent);
287
- if (hasUseClient) {
288
- clientModule = modulePath;
289
- }
290
- } catch {
291
- // 파일 읽기 실패 시 무시
292
- }
293
- }
294
-
295
- // 로딩/에러 모듈 찾기
296
- const loadingModule = this.findClosestSpecialFile(file.segments, loadingMap);
297
- const errorModule = this.findClosestSpecialFile(file.segments, errorMap);
298
-
299
- const route: FSRouteConfig = {
300
- id: routeId,
301
- segments: file.segments,
302
- pattern,
303
- kind: file.type === "page" ? "page" : "api",
304
- module: modulePath,
305
- componentModule: file.type === "page" ? modulePath : undefined,
306
- clientModule,
307
- layoutChain,
308
- loadingModule,
309
- errorModule,
310
- sourceFile: file.absolutePath,
311
- };
312
-
313
- // API 라우트의 경우 methods 추가 (기본값)
314
- if (file.type === "route") {
315
- route.methods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
316
- }
317
-
318
- routes.push(route);
319
- patternMap.set(pattern, route);
320
- shapeMap.set(patternShape, route);
321
- }
322
-
323
- return { routes, routeErrors };
324
- }
325
-
326
- /**
327
- * 레이아웃 체인 해결
328
- */
329
- private resolveLayoutChain(
330
- segments: ScannedFile["segments"],
331
- layoutMap: Map<string, ScannedFile>
332
- ): string[] {
333
- const chain: string[] = [];
334
-
335
- // 루트 레이아웃
336
- const rootLayout = layoutMap.get(".");
337
- if (rootLayout) {
338
- chain.push(join(this.config.routesDir, rootLayout.relativePath).replace(/\\/g, "/"));
339
- }
340
-
341
- // 중첩 레이아웃
342
- let currentPath = "";
343
- for (const segment of segments) {
344
- currentPath = currentPath ? `${currentPath}/${segment.raw}` : segment.raw;
345
- const layout = layoutMap.get(currentPath);
346
- if (layout) {
347
- chain.push(join(this.config.routesDir, layout.relativePath).replace(/\\/g, "/"));
348
- }
349
- }
350
-
351
- return chain;
352
- }
353
-
354
- /**
355
- * 가장 가까운 특수 파일 찾기
356
- */
357
- private findClosestSpecialFile(
358
- segments: ScannedFile["segments"],
359
- fileMap: Map<string, ScannedFile>
360
- ): string | undefined {
361
- // 현재 경로부터 루트까지 역순 탐색
362
- let currentPath = segments.map((s) => s.raw).join("/");
363
-
364
- while (currentPath) {
365
- const file = fileMap.get(currentPath);
366
- if (file) {
367
- return join(this.config.routesDir, file.relativePath).replace(/\\/g, "/");
368
- }
369
- // 상위 디렉토리로
370
- const lastSlash = currentPath.lastIndexOf("/");
371
- currentPath = lastSlash > 0 ? currentPath.slice(0, lastSlash) : "";
372
- }
373
-
374
- // 루트 체크
375
- const rootFile = fileMap.get(".");
376
- return rootFile ? join(this.config.routesDir, rootFile.relativePath).replace(/\\/g, "/") : undefined;
377
- }
378
-
379
- /**
380
- * 상대 경로에서 디렉토리 경로 추출 (루트는 ".")
381
- */
382
- private getDirPath(relativePath: string): string {
383
- const normalized = relativePath.replace(/\\/g, "/");
384
- const lastSlash = normalized.lastIndexOf("/");
385
- return lastSlash === -1 ? "." : normalized.slice(0, lastSlash);
386
- }
387
-
388
- /**
389
- * 경로에 비공개 폴더가 포함되어 있는지 확인
390
- */
391
- private hasPrivateSegment(relativePath: string): boolean {
392
- const normalized = relativePath.replace(/\\/g, "/");
393
- const segments = normalized.split("/").slice(0, -1);
394
- return segments.some((segment) => isPrivateFolder(segment));
395
- }
396
-
397
- /**
398
- * 제외 패턴 적용 여부
399
- */
400
- private isExcluded(relativePath: string, isDir: boolean): boolean {
401
- if (this.excludeMatchers.length === 0) return false;
402
-
403
- const normalized = relativePath.replace(/\\/g, "/");
404
- const candidates = isDir
405
- ? [normalized, normalized.endsWith("/") ? normalized : `${normalized}/`]
406
- : [normalized];
407
-
408
- return this.excludeMatchers.some((matcher) => candidates.some((path) => matcher.test(path)));
409
- }
410
-
411
- /**
412
- * 결과 생성
413
- */
414
- private createEmptyResult(errors: ScanError[], scanTime: number): ScanResult {
415
- return {
416
- files: [],
417
- routes: [],
418
- errors,
419
- stats: {
420
- totalFiles: 0,
421
- pageCount: 0,
422
- apiCount: 0,
423
- layoutCount: 0,
424
- islandCount: 0,
425
- scanTime,
426
- },
427
- };
428
- }
429
-
430
- /**
431
- * 통계 계산
432
- */
433
- private calculateStats(
434
- files: ScannedFile[],
435
- routes: FSRouteConfig[],
436
- scanTime: number
437
- ): ScanStats {
438
- return {
439
- totalFiles: files.length,
440
- pageCount: routes.filter((r) => r.kind === "page").length,
441
- apiCount: routes.filter((r) => r.kind === "api").length,
442
- layoutCount: files.filter((f) => f.type === "layout").length,
443
- islandCount: files.filter((f) => f.type === "island").length,
444
- scanTime,
445
- };
446
- }
447
- }
448
-
449
- // ═══════════════════════════════════════════════════════════════════════════
450
- // Glob Utilities
451
- // ═══════════════════════════════════════════════════════════════════════════
452
-
453
- function globToRegExp(glob: string): RegExp {
454
- let regex = "^";
455
- let i = 0;
456
-
457
- while (i < glob.length) {
458
- const char = glob[i];
459
-
460
- if (char === "*") {
461
- const nextChar = glob[i + 1];
462
- const nextNextChar = glob[i + 2];
463
- if (nextChar === "*" && nextNextChar === "/") {
464
- // "**/" -> match any path prefix (including empty)
465
- regex += "(?:.*/)?";
466
- i += 2;
467
- } else if (nextChar === "*") {
468
- // "**" -> match any path (including "/")
469
- while (glob[i + 1] === "*") i++;
470
- regex += ".*";
471
- } else {
472
- // "*" -> match within a segment
473
- regex += "[^/]*";
474
- }
475
- } else if (char === "?") {
476
- regex += "[^/]";
477
- } else {
478
- regex += escapeRegex(char);
479
- }
480
-
481
- i++;
482
- }
483
-
484
- regex += "$";
485
- return new RegExp(regex);
486
- }
487
-
488
- function escapeRegex(char: string): string {
489
- return /[\\^$.*+?()[\]{}|]/.test(char) ? `\\${char}` : char;
490
- }
491
-
492
- // ═══════════════════════════════════════════════════════════════════════════
493
- // Factory Function
494
- // ═══════════════════════════════════════════════════════════════════════════
495
-
496
- /**
497
- * 스캐너 생성 팩토리 함수
498
- */
499
- export function createFSScanner(config: Partial<FSScannerConfig> = {}): FSScanner {
500
- return new FSScanner(config);
501
- }
502
-
503
- /**
504
- * 간편 스캔 함수
505
- */
506
- export async function scanRoutes(
507
- rootDir: string,
508
- config: Partial<FSScannerConfig> = {}
509
- ): Promise<ScanResult> {
510
- const scanner = createFSScanner(config);
511
- return scanner.scan(rootDir);
512
- }
1
+ /**
2
+ * FS Routes Scanner
3
+ *
4
+ * 파일 시스템을 스캔하여 라우트 파일을 탐지
5
+ *
6
+ * @module router/fs-scanner
7
+ */
8
+
9
+ import { stat } from "fs/promises";
10
+ import { join, relative, basename, extname } from "path";
11
+ import type {
12
+ ScannedFile,
13
+ FSScannerConfig,
14
+ ScanResult,
15
+ ScanError,
16
+ ScanStats,
17
+ FSRouteConfig,
18
+ } from "./fs-types";
19
+ import { DEFAULT_SCANNER_CONFIG } from "./fs-types";
20
+ import {
21
+ parseSegments,
22
+ segmentsToPattern,
23
+ detectFileType,
24
+ isPrivateFolder,
25
+ generateRouteId,
26
+ validateSegments,
27
+ sortRoutesByPriority,
28
+ getPatternShape,
29
+ } from "./fs-patterns";
30
+
31
+ // ═══════════════════════════════════════════════════════════════════════════
32
+ // Scanner Class
33
+ // ═══════════════════════════════════════════════════════════════════════════
34
+
35
+ /**
36
+ * FS Routes 스캐너
37
+ *
38
+ * @example
39
+ * const scanner = new FSScanner({ routesDir: "app" });
40
+ * const result = await scanner.scan("/path/to/project");
41
+ */
42
+ export class FSScanner {
43
+ private config: FSScannerConfig;
44
+ private excludeMatchers: RegExp[];
45
+
46
+ constructor(config: Partial<FSScannerConfig> = {}) {
47
+ this.config = { ...DEFAULT_SCANNER_CONFIG, ...config };
48
+ this.excludeMatchers = this.config.exclude.map(globToRegExp);
49
+ }
50
+
51
+ /**
52
+ * 디렉토리 스캔 수행
53
+ *
54
+ * @param rootDir 프로젝트 루트 디렉토리
55
+ * @returns 스캔 결과
56
+ */
57
+ async scan(rootDir: string): Promise<ScanResult> {
58
+ const startTime = Date.now();
59
+ const routesDir = join(rootDir, this.config.routesDir);
60
+
61
+ const files: ScannedFile[] = [];
62
+ const errors: ScanError[] = [];
63
+
64
+ // 라우트 디렉토리 존재 확인
65
+ try {
66
+ const dirStat = await stat(routesDir);
67
+ if (!dirStat.isDirectory()) {
68
+ errors.push({
69
+ type: "file_read_error",
70
+ message: `${this.config.routesDir} is not a directory`,
71
+ filePath: routesDir,
72
+ });
73
+ return this.createEmptyResult(errors, Date.now() - startTime);
74
+ }
75
+ } catch {
76
+ // 디렉토리가 없으면 빈 결과 반환 (에러 아님)
77
+ return this.createEmptyResult([], Date.now() - startTime);
78
+ }
79
+
80
+ // Bun.Glob 기반 스캔
81
+ await this.scanWithGlob(rootDir, routesDir, files, errors);
82
+
83
+ // 라우트 설정 생성
84
+ const { routes, routeErrors } = await this.createRouteConfigs(files, rootDir);
85
+ errors.push(...routeErrors);
86
+
87
+ // 통계 계산
88
+ const stats = this.calculateStats(files, routes, Date.now() - startTime);
89
+
90
+ return {
91
+ files,
92
+ routes: sortRoutesByPriority(routes),
93
+ errors,
94
+ stats,
95
+ };
96
+ }
97
+
98
+ /**
99
+ * Bun.Glob 기반 스캔
100
+ */
101
+ private async scanWithGlob(
102
+ rootDir: string,
103
+ routesRoot: string,
104
+ files: ScannedFile[],
105
+ errors: ScanError[]
106
+ ): Promise<void> {
107
+ const routesDirPattern = this.config.routesDir.replace(/\\/g, "/").replace(/\/+$/, "");
108
+ const extensions = this.config.extensions
109
+ .map((ext) => ext.replace(/^\./, ""))
110
+ .filter(Boolean)
111
+ .join(",");
112
+
113
+ if (!routesDirPattern || !extensions) {
114
+ return;
115
+ }
116
+
117
+ const pattern = `${routesDirPattern}/**/*.{${extensions}}`;
118
+ const glob = new Bun.Glob(pattern);
119
+ const foundFiles: string[] = [];
120
+
121
+ try {
122
+ for await (const filePath of glob.scan({ cwd: rootDir, absolute: true })) {
123
+ foundFiles.push(filePath);
124
+ }
125
+ } catch (error) {
126
+ errors.push({
127
+ type: "file_read_error",
128
+ message: `Failed to scan directory: ${error instanceof Error ? error.message : String(error)}`,
129
+ filePath: routesRoot,
130
+ });
131
+ return;
132
+ }
133
+
134
+ foundFiles.sort((a, b) => a.localeCompare(b));
135
+
136
+ for (const fullPath of foundFiles) {
137
+ const relativePath = relative(routesRoot, fullPath).replace(/\\/g, "/");
138
+ if (relativePath.startsWith("..")) {
139
+ continue;
140
+ }
141
+
142
+ if (this.isExcluded(relativePath, false)) {
143
+ continue;
144
+ }
145
+
146
+ if (this.hasPrivateSegment(relativePath)) {
147
+ continue;
148
+ }
149
+
150
+ const pathSegments = relativePath.split("/");
151
+ if (pathSegments.includes("node_modules")) {
152
+ continue;
153
+ }
154
+
155
+ const fileName = basename(fullPath);
156
+ const ext = extname(fileName);
157
+ if (!this.config.extensions.includes(ext)) {
158
+ continue;
159
+ }
160
+
161
+ const fileType = detectFileType(fileName, this.config.islandSuffix);
162
+ if (!fileType) {
163
+ continue;
164
+ }
165
+
166
+ const segments = parseSegments(relativePath);
167
+ const validation = validateSegments(segments);
168
+ if (!validation.valid) {
169
+ errors.push({
170
+ type: "invalid_segment",
171
+ message: validation.error!,
172
+ filePath: fullPath,
173
+ });
174
+ continue;
175
+ }
176
+
177
+ files.push({
178
+ absolutePath: fullPath,
179
+ relativePath,
180
+ type: fileType,
181
+ segments,
182
+ extension: ext,
183
+ });
184
+ }
185
+ }
186
+
187
+ /**
188
+ * 스캔된 파일에서 라우트 설정 생성
189
+ */
190
+ private async createRouteConfigs(
191
+ files: ScannedFile[],
192
+ rootDir: string
193
+ ): Promise<{ routes: FSRouteConfig[]; routeErrors: ScanError[] }> {
194
+ const routes: FSRouteConfig[] = [];
195
+ const routeErrors: ScanError[] = [];
196
+
197
+ // 패턴별 라우트 매핑 (중복/충돌 감지용)
198
+ const patternMap = new Map<string, FSRouteConfig>();
199
+ const shapeMap = new Map<string, FSRouteConfig>();
200
+
201
+ // 파일 맵 수집 (single pass)
202
+ const layoutMap = new Map<string, ScannedFile>();
203
+ const loadingMap = new Map<string, ScannedFile>();
204
+ const errorMap = new Map<string, ScannedFile>();
205
+ const islandMap = new Map<string, ScannedFile[]>();
206
+ const routeFiles: ScannedFile[] = [];
207
+
208
+ for (const file of files) {
209
+ const dirPath = this.getDirPath(file.relativePath);
210
+
211
+ switch (file.type) {
212
+ case "layout":
213
+ layoutMap.set(dirPath, file);
214
+ break;
215
+ case "loading":
216
+ loadingMap.set(dirPath, file);
217
+ break;
218
+ case "error":
219
+ errorMap.set(dirPath, file);
220
+ break;
221
+ case "island": {
222
+ const existing = islandMap.get(dirPath);
223
+ if (existing) {
224
+ existing.push(file);
225
+ } else {
226
+ islandMap.set(dirPath, [file]);
227
+ }
228
+ break;
229
+ }
230
+ case "page":
231
+ case "route":
232
+ routeFiles.push(file);
233
+ break;
234
+ default:
235
+ break;
236
+ }
237
+ }
238
+
239
+ // 페이지 및 API 라우트 처리
240
+ for (const file of routeFiles) {
241
+ const pattern = segmentsToPattern(file.segments);
242
+ const patternShape = getPatternShape(pattern);
243
+ const routeId = generateRouteId(file.relativePath);
244
+ const modulePath = join(this.config.routesDir, file.relativePath);
245
+
246
+ // 중복 패턴 체크
247
+ const existingRoute = patternMap.get(pattern);
248
+ if (existingRoute) {
249
+ routeErrors.push({
250
+ type: "duplicate_route",
251
+ message: `Duplicate route pattern "${pattern}"`,
252
+ filePath: file.absolutePath,
253
+ conflictsWith: existingRoute.sourceFile,
254
+ });
255
+ continue;
256
+ }
257
+
258
+ // 패턴 충돌 체크 (파라미터 이름만 다른 경우 등)
259
+ const conflictingRoute = shapeMap.get(patternShape);
260
+ if (conflictingRoute) {
261
+ routeErrors.push({
262
+ type: "pattern_conflict",
263
+ message: `Route pattern "${pattern}" conflicts with "${conflictingRoute.pattern}"`,
264
+ filePath: file.absolutePath,
265
+ conflictsWith: conflictingRoute.sourceFile,
266
+ });
267
+ continue;
268
+ }
269
+
270
+ // 레이아웃 체인 구성
271
+ const layoutChain = this.resolveLayoutChain(file.segments, layoutMap);
272
+
273
+ // Island 파일 찾기 (같은 디렉토리)
274
+ const dirPath = this.getDirPath(file.relativePath);
275
+ const islands = islandMap.get(dirPath);
276
+
277
+ // clientModule 결정: island 파일 또는 "use client"가 있는 page 자체
278
+ let clientModule: string | undefined;
279
+ let pageFileContent: string | null = null;
280
+
281
+ if (file.type === "page") {
282
+ try {
283
+ pageFileContent = await Bun.file(file.absolutePath).text();
284
+ } catch {
285
+ pageFileContent = null;
286
+ }
287
+ }
288
+
289
+ if (islands?.[0]) {
290
+ // 우선순위: 명시적 island 파일
291
+ clientModule = join(this.config.routesDir, islands[0].relativePath);
292
+
293
+ // SSR shell + island placeholder 패턴은 hydration mismatch 위험이 매우 높으므로 에러로 처리
294
+ if (pageFileContent && this.hasHydrationShellMismatchRisk(pageFileContent, islands[0].relativePath)) {
295
+ routeErrors.push({
296
+ type: "hydration_shell_mismatch_risk",
297
+ message:
298
+ `Hydration mismatch risk detected in \"${file.relativePath}\": ` +
299
+ `page.tsx renders an SSR shell while hydration is delegated to \"${islands[0].relativePath}\". ` +
300
+ `Use a single render tree for first paint (e.g. route entry directly exports island component).`,
301
+ filePath: file.absolutePath,
302
+ conflictsWith: islands[0].absolutePath,
303
+ });
304
+ }
305
+ } else if (file.type === "page" && pageFileContent) {
306
+ // page 파일 자체에서 "use client" 확인
307
+ const hasUseClient = /^\s*["']use client["']/m.test(pageFileContent);
308
+ if (hasUseClient) {
309
+ clientModule = modulePath;
310
+ }
311
+ }
312
+
313
+ // 로딩/에러 모듈 찾기
314
+ const loadingModule = this.findClosestSpecialFile(file.segments, loadingMap);
315
+ const errorModule = this.findClosestSpecialFile(file.segments, errorMap);
316
+
317
+ const route: FSRouteConfig = {
318
+ id: routeId,
319
+ segments: file.segments,
320
+ pattern,
321
+ kind: file.type === "page" ? "page" : "api",
322
+ module: modulePath,
323
+ componentModule: file.type === "page" ? modulePath : undefined,
324
+ clientModule,
325
+ layoutChain,
326
+ loadingModule,
327
+ errorModule,
328
+ sourceFile: file.absolutePath,
329
+ };
330
+
331
+ // API 라우트의 경우 methods 추가 (기본값)
332
+ if (file.type === "route") {
333
+ route.methods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
334
+ }
335
+
336
+ routes.push(route);
337
+ patternMap.set(pattern, route);
338
+ shapeMap.set(patternShape, route);
339
+ }
340
+
341
+ return { routes, routeErrors };
342
+ }
343
+
344
+ private hasHydrationShellMismatchRisk(pageContent: string, _islandRelativePath: string): boolean {
345
+ // import문에서 island 모듈의 변수명을 직접 파싱
346
+ const importMatch = pageContent.match(
347
+ /import\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\s+["'][^"']*\.island(?:\.(?:tsx?|jsx?))?["']/
348
+ );
349
+
350
+ if (!importMatch) {
351
+ return false;
352
+ }
353
+
354
+ const islandVarName = importMatch[1];
355
+
356
+ // 대표적인 anti-pattern:
357
+ // import X from "./page.island" + {typeof X !== 'undefined' && null}
358
+ return new RegExp(
359
+ `typeof\\s+${islandVarName}\\s*!==\\s*["']undefined["']\\s*&&\\s*null`
360
+ ).test(pageContent);
361
+ }
362
+
363
+ /**
364
+ * 레이아웃 체인 해결
365
+ */
366
+ private resolveLayoutChain(
367
+ segments: ScannedFile["segments"],
368
+ layoutMap: Map<string, ScannedFile>
369
+ ): string[] {
370
+ const chain: string[] = [];
371
+
372
+ // 루트 레이아웃
373
+ const rootLayout = layoutMap.get(".");
374
+ if (rootLayout) {
375
+ chain.push(join(this.config.routesDir, rootLayout.relativePath).replace(/\\/g, "/"));
376
+ }
377
+
378
+ // 중첩 레이아웃
379
+ let currentPath = "";
380
+ for (const segment of segments) {
381
+ currentPath = currentPath ? `${currentPath}/${segment.raw}` : segment.raw;
382
+ const layout = layoutMap.get(currentPath);
383
+ if (layout) {
384
+ chain.push(join(this.config.routesDir, layout.relativePath).replace(/\\/g, "/"));
385
+ }
386
+ }
387
+
388
+ return chain;
389
+ }
390
+
391
+ /**
392
+ * 가장 가까운 특수 파일 찾기
393
+ */
394
+ private findClosestSpecialFile(
395
+ segments: ScannedFile["segments"],
396
+ fileMap: Map<string, ScannedFile>
397
+ ): string | undefined {
398
+ // 현재 경로부터 루트까지 역순 탐색
399
+ let currentPath = segments.map((s) => s.raw).join("/");
400
+
401
+ while (currentPath) {
402
+ const file = fileMap.get(currentPath);
403
+ if (file) {
404
+ return join(this.config.routesDir, file.relativePath).replace(/\\/g, "/");
405
+ }
406
+ // 상위 디렉토리로
407
+ const lastSlash = currentPath.lastIndexOf("/");
408
+ currentPath = lastSlash > 0 ? currentPath.slice(0, lastSlash) : "";
409
+ }
410
+
411
+ // 루트 체크
412
+ const rootFile = fileMap.get(".");
413
+ return rootFile ? join(this.config.routesDir, rootFile.relativePath).replace(/\\/g, "/") : undefined;
414
+ }
415
+
416
+ /**
417
+ * 상대 경로에서 디렉토리 경로 추출 (루트는 ".")
418
+ */
419
+ private getDirPath(relativePath: string): string {
420
+ const normalized = relativePath.replace(/\\/g, "/");
421
+ const lastSlash = normalized.lastIndexOf("/");
422
+ return lastSlash === -1 ? "." : normalized.slice(0, lastSlash);
423
+ }
424
+
425
+ /**
426
+ * 경로에 비공개 폴더가 포함되어 있는지 확인
427
+ */
428
+ private hasPrivateSegment(relativePath: string): boolean {
429
+ const normalized = relativePath.replace(/\\/g, "/");
430
+ const segments = normalized.split("/").slice(0, -1);
431
+ return segments.some((segment) => isPrivateFolder(segment));
432
+ }
433
+
434
+ /**
435
+ * 제외 패턴 적용 여부
436
+ */
437
+ private isExcluded(relativePath: string, isDir: boolean): boolean {
438
+ if (this.excludeMatchers.length === 0) return false;
439
+
440
+ const normalized = relativePath.replace(/\\/g, "/");
441
+ const candidates = isDir
442
+ ? [normalized, normalized.endsWith("/") ? normalized : `${normalized}/`]
443
+ : [normalized];
444
+
445
+ return this.excludeMatchers.some((matcher) => candidates.some((path) => matcher.test(path)));
446
+ }
447
+
448
+ /**
449
+ * 빈 결과 생성
450
+ */
451
+ private createEmptyResult(errors: ScanError[], scanTime: number): ScanResult {
452
+ return {
453
+ files: [],
454
+ routes: [],
455
+ errors,
456
+ stats: {
457
+ totalFiles: 0,
458
+ pageCount: 0,
459
+ apiCount: 0,
460
+ layoutCount: 0,
461
+ islandCount: 0,
462
+ scanTime,
463
+ },
464
+ };
465
+ }
466
+
467
+ /**
468
+ * 통계 계산
469
+ */
470
+ private calculateStats(
471
+ files: ScannedFile[],
472
+ routes: FSRouteConfig[],
473
+ scanTime: number
474
+ ): ScanStats {
475
+ return {
476
+ totalFiles: files.length,
477
+ pageCount: routes.filter((r) => r.kind === "page").length,
478
+ apiCount: routes.filter((r) => r.kind === "api").length,
479
+ layoutCount: files.filter((f) => f.type === "layout").length,
480
+ islandCount: files.filter((f) => f.type === "island").length,
481
+ scanTime,
482
+ };
483
+ }
484
+ }
485
+
486
+ // ═══════════════════════════════════════════════════════════════════════════
487
+ // Glob Utilities
488
+ // ═══════════════════════════════════════════════════════════════════════════
489
+
490
+ function globToRegExp(glob: string): RegExp {
491
+ let regex = "^";
492
+ let i = 0;
493
+
494
+ while (i < glob.length) {
495
+ const char = glob[i];
496
+
497
+ if (char === "*") {
498
+ const nextChar = glob[i + 1];
499
+ const nextNextChar = glob[i + 2];
500
+ if (nextChar === "*" && nextNextChar === "/") {
501
+ // "**/" -> match any path prefix (including empty)
502
+ regex += "(?:.*/)?";
503
+ i += 2;
504
+ } else if (nextChar === "*") {
505
+ // "**" -> match any path (including "/")
506
+ while (glob[i + 1] === "*") i++;
507
+ regex += ".*";
508
+ } else {
509
+ // "*" -> match within a segment
510
+ regex += "[^/]*";
511
+ }
512
+ } else if (char === "?") {
513
+ regex += "[^/]";
514
+ } else {
515
+ regex += escapeRegex(char);
516
+ }
517
+
518
+ i++;
519
+ }
520
+
521
+ regex += "$";
522
+ return new RegExp(regex);
523
+ }
524
+
525
+ function escapeRegex(char: string): string {
526
+ return /[\\^$.*+?()[\]{}|]/.test(char) ? `\\${char}` : char;
527
+ }
528
+
529
+ // ═══════════════════════════════════════════════════════════════════════════
530
+ // Factory Function
531
+ // ═══════════════════════════════════════════════════════════════════════════
532
+
533
+ /**
534
+ * 스캐너 생성 팩토리 함수
535
+ */
536
+ export function createFSScanner(config: Partial<FSScannerConfig> = {}): FSScanner {
537
+ return new FSScanner(config);
538
+ }
539
+
540
+ /**
541
+ * 간편 스캔 함수
542
+ */
543
+ export async function scanRoutes(
544
+ rootDir: string,
545
+ config: Partial<FSScannerConfig> = {}
546
+ ): Promise<ScanResult> {
547
+ const scanner = createFSScanner(config);
548
+ return scanner.scan(rootDir);
549
+ }
@@ -184,7 +184,7 @@ export interface ScanResult {
184
184
  */
185
185
  export interface ScanError {
186
186
  /** 에러 타입 */
187
- type: "invalid_segment" | "duplicate_route" | "file_read_error" | "pattern_conflict";
187
+ type: "invalid_segment" | "duplicate_route" | "file_read_error" | "pattern_conflict" | "hydration_shell_mismatch_risk";
188
188
 
189
189
  /** 에러 메시지 */
190
190
  message: string;
@@ -1168,6 +1168,7 @@ function startBunServerWithFallback(options: {
1168
1168
  port: 0,
1169
1169
  hostname,
1170
1170
  fetch,
1171
+ idleTimeout: 255,
1171
1172
  });
1172
1173
  return { server, port: server.port ?? 0, attempts: 0 };
1173
1174
  }
@@ -1182,6 +1183,7 @@ function startBunServerWithFallback(options: {
1182
1183
  port: candidate,
1183
1184
  hostname,
1184
1185
  fetch,
1186
+ idleTimeout: 255,
1185
1187
  });
1186
1188
  return { server, port: server.port ?? candidate, attempts: attempt };
1187
1189
  } catch (error) {