@mandujs/core 0.18.18 → 0.18.19
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 +1 -1
- package/src/router/fs-scanner.ts +549 -512
- package/src/router/fs-types.ts +1 -1
package/package.json
CHANGED
package/src/router/fs-scanner.ts
CHANGED
|
@@ -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
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
//
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
):
|
|
438
|
-
return
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
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
|
+
}
|
package/src/router/fs-types.ts
CHANGED
|
@@ -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;
|