@mandujs/core 0.13.0 → 0.13.1

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 (155) hide show
  1. package/README.ko.md +4 -4
  2. package/README.md +653 -653
  3. package/package.json +1 -1
  4. package/src/bundler/build.ts +91 -91
  5. package/src/bundler/css.ts +302 -302
  6. package/src/client/Link.tsx +227 -227
  7. package/src/client/globals.ts +44 -44
  8. package/src/client/hooks.ts +267 -267
  9. package/src/client/index.ts +5 -5
  10. package/src/client/island.ts +8 -8
  11. package/src/client/router.ts +435 -435
  12. package/src/client/runtime.ts +23 -23
  13. package/src/client/serialize.ts +404 -404
  14. package/src/client/window-state.ts +101 -101
  15. package/src/config/mandu.ts +9 -0
  16. package/src/config/validate.ts +12 -0
  17. package/src/config/watcher.ts +311 -311
  18. package/src/constants.ts +40 -40
  19. package/src/content/content-layer.ts +314 -314
  20. package/src/content/content.test.ts +433 -433
  21. package/src/content/data-store.ts +245 -245
  22. package/src/content/digest.ts +133 -133
  23. package/src/content/index.ts +164 -164
  24. package/src/content/loader-context.ts +172 -172
  25. package/src/content/loaders/api.ts +216 -216
  26. package/src/content/loaders/file.ts +169 -169
  27. package/src/content/loaders/glob.ts +252 -252
  28. package/src/content/loaders/index.ts +34 -34
  29. package/src/content/loaders/types.ts +137 -137
  30. package/src/content/meta-store.ts +209 -209
  31. package/src/content/types.ts +282 -282
  32. package/src/content/watcher.ts +135 -135
  33. package/src/contract/client-safe.test.ts +42 -42
  34. package/src/contract/client-safe.ts +114 -114
  35. package/src/contract/client.ts +16 -16
  36. package/src/contract/define.ts +459 -459
  37. package/src/contract/handler.ts +10 -10
  38. package/src/contract/normalize.test.ts +276 -276
  39. package/src/contract/normalize.ts +404 -404
  40. package/src/contract/registry.test.ts +206 -206
  41. package/src/contract/registry.ts +568 -568
  42. package/src/contract/schema.ts +48 -48
  43. package/src/contract/types.ts +58 -58
  44. package/src/contract/validator.ts +32 -32
  45. package/src/devtools/ai/context-builder.ts +375 -375
  46. package/src/devtools/ai/index.ts +25 -25
  47. package/src/devtools/ai/mcp-connector.ts +465 -465
  48. package/src/devtools/client/catchers/error-catcher.ts +327 -327
  49. package/src/devtools/client/catchers/index.ts +18 -18
  50. package/src/devtools/client/catchers/network-proxy.ts +363 -363
  51. package/src/devtools/client/components/index.ts +39 -39
  52. package/src/devtools/client/components/kitchen-root.tsx +362 -362
  53. package/src/devtools/client/components/mandu-character.tsx +241 -241
  54. package/src/devtools/client/components/overlay.tsx +368 -368
  55. package/src/devtools/client/components/panel/errors-panel.tsx +259 -259
  56. package/src/devtools/client/components/panel/guard-panel.tsx +244 -244
  57. package/src/devtools/client/components/panel/index.ts +32 -32
  58. package/src/devtools/client/components/panel/islands-panel.tsx +304 -304
  59. package/src/devtools/client/components/panel/network-panel.tsx +292 -292
  60. package/src/devtools/client/components/panel/panel-container.tsx +259 -259
  61. package/src/devtools/client/filters/context-filters.ts +282 -282
  62. package/src/devtools/client/filters/index.ts +16 -16
  63. package/src/devtools/client/index.ts +63 -63
  64. package/src/devtools/client/persistence.ts +335 -335
  65. package/src/devtools/client/state-manager.ts +478 -478
  66. package/src/devtools/design-tokens.ts +263 -263
  67. package/src/devtools/hook/create-hook.ts +207 -207
  68. package/src/devtools/hook/index.ts +13 -13
  69. package/src/devtools/index.ts +439 -439
  70. package/src/devtools/init.ts +266 -266
  71. package/src/devtools/protocol.ts +237 -237
  72. package/src/devtools/server/index.ts +17 -17
  73. package/src/devtools/server/source-context.ts +444 -444
  74. package/src/devtools/types.ts +319 -319
  75. package/src/devtools/worker/index.ts +25 -25
  76. package/src/devtools/worker/redaction-worker.ts +222 -222
  77. package/src/devtools/worker/worker-manager.ts +409 -409
  78. package/src/error/domains.ts +265 -265
  79. package/src/error/result.ts +46 -46
  80. package/src/error/types.ts +6 -6
  81. package/src/errors/extractor.ts +409 -409
  82. package/src/errors/index.ts +19 -19
  83. package/src/filling/auth.ts +308 -308
  84. package/src/filling/context.ts +24 -1
  85. package/src/filling/deps.ts +238 -238
  86. package/src/filling/index.ts +2 -0
  87. package/src/filling/sse.test.ts +168 -0
  88. package/src/filling/sse.ts +162 -0
  89. package/src/generator/index.ts +3 -3
  90. package/src/guard/analyzer.ts +360 -360
  91. package/src/guard/ast-analyzer.ts +806 -806
  92. package/src/guard/contract-guard.ts +9 -9
  93. package/src/guard/file-type.test.ts +24 -24
  94. package/src/guard/presets/atomic.ts +70 -70
  95. package/src/guard/presets/clean.ts +77 -77
  96. package/src/guard/presets/fsd.ts +79 -79
  97. package/src/guard/presets/hexagonal.ts +68 -68
  98. package/src/guard/presets/index.ts +291 -291
  99. package/src/guard/reporter.ts +445 -445
  100. package/src/guard/rules.ts +12 -12
  101. package/src/guard/statistics.ts +578 -578
  102. package/src/guard/suggestions.ts +358 -358
  103. package/src/guard/types.ts +348 -348
  104. package/src/guard/validator.ts +834 -834
  105. package/src/guard/watcher.ts +404 -404
  106. package/src/index.ts +6 -1
  107. package/src/intent/index.ts +310 -310
  108. package/src/island/index.ts +304 -304
  109. package/src/logging/index.ts +22 -22
  110. package/src/logging/transports.ts +365 -365
  111. package/src/plugins/index.ts +38 -38
  112. package/src/plugins/registry.ts +377 -377
  113. package/src/plugins/types.ts +363 -363
  114. package/src/report/index.ts +1 -1
  115. package/src/router/fs-patterns.ts +387 -387
  116. package/src/router/fs-scanner.ts +497 -497
  117. package/src/runtime/boundary.tsx +232 -232
  118. package/src/runtime/compose.ts +222 -222
  119. package/src/runtime/escape.ts +44 -0
  120. package/src/runtime/lifecycle.ts +381 -381
  121. package/src/runtime/logger.test.ts +345 -345
  122. package/src/runtime/logger.ts +677 -677
  123. package/src/runtime/router.test.ts +476 -476
  124. package/src/runtime/router.ts +105 -105
  125. package/src/runtime/security.ts +155 -155
  126. package/src/runtime/server.ts +257 -0
  127. package/src/runtime/session-key.ts +328 -328
  128. package/src/runtime/ssr.ts +16 -21
  129. package/src/runtime/streaming-ssr.ts +24 -33
  130. package/src/runtime/trace.ts +144 -144
  131. package/src/seo/index.ts +214 -214
  132. package/src/seo/integration/ssr.ts +307 -307
  133. package/src/seo/render/basic.ts +427 -427
  134. package/src/seo/render/index.ts +143 -143
  135. package/src/seo/render/jsonld.ts +539 -539
  136. package/src/seo/render/opengraph.ts +191 -191
  137. package/src/seo/render/robots.ts +116 -116
  138. package/src/seo/render/sitemap.ts +137 -137
  139. package/src/seo/render/twitter.ts +126 -126
  140. package/src/seo/resolve/index.ts +353 -353
  141. package/src/seo/resolve/opengraph.ts +143 -143
  142. package/src/seo/resolve/robots.ts +73 -73
  143. package/src/seo/resolve/title.ts +94 -94
  144. package/src/seo/resolve/twitter.ts +73 -73
  145. package/src/seo/resolve/url.ts +97 -97
  146. package/src/seo/routes/index.ts +290 -290
  147. package/src/seo/types.ts +575 -575
  148. package/src/slot/validator.ts +39 -39
  149. package/src/spec/index.ts +3 -3
  150. package/src/spec/load.ts +76 -76
  151. package/src/spec/lock.ts +56 -56
  152. package/src/utils/bun.ts +8 -8
  153. package/src/utils/lru-cache.ts +75 -75
  154. package/src/utils/safe-io.ts +188 -188
  155. package/src/utils/string-safe.ts +298 -298
@@ -1,497 +1,497 @@
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 } = 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 createRouteConfigs(
191
- files: ScannedFile[],
192
- rootDir: string
193
- ): { 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
- const clientModule = islands?.[0]
277
- ? join(this.config.routesDir, islands[0].relativePath)
278
- : undefined;
279
-
280
- // 로딩/에러 모듈 찾기
281
- const loadingModule = this.findClosestSpecialFile(file.segments, loadingMap);
282
- const errorModule = this.findClosestSpecialFile(file.segments, errorMap);
283
-
284
- const route: FSRouteConfig = {
285
- id: routeId,
286
- segments: file.segments,
287
- pattern,
288
- kind: file.type === "page" ? "page" : "api",
289
- module: modulePath,
290
- componentModule: file.type === "page" ? modulePath : undefined,
291
- clientModule,
292
- layoutChain,
293
- loadingModule,
294
- errorModule,
295
- sourceFile: file.absolutePath,
296
- };
297
-
298
- // API 라우트의 경우 methods 추가 (기본값)
299
- if (file.type === "route") {
300
- route.methods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
301
- }
302
-
303
- routes.push(route);
304
- patternMap.set(pattern, route);
305
- shapeMap.set(patternShape, route);
306
- }
307
-
308
- return { routes, routeErrors };
309
- }
310
-
311
- /**
312
- * 레이아웃 체인 해결
313
- */
314
- private resolveLayoutChain(
315
- segments: ScannedFile["segments"],
316
- layoutMap: Map<string, ScannedFile>
317
- ): string[] {
318
- const chain: string[] = [];
319
-
320
- // 루트 레이아웃
321
- const rootLayout = layoutMap.get(".");
322
- if (rootLayout) {
323
- chain.push(join(this.config.routesDir, rootLayout.relativePath));
324
- }
325
-
326
- // 중첩 레이아웃
327
- let currentPath = "";
328
- for (const segment of segments) {
329
- currentPath = currentPath ? `${currentPath}/${segment.raw}` : segment.raw;
330
- const layout = layoutMap.get(currentPath);
331
- if (layout) {
332
- chain.push(join(this.config.routesDir, layout.relativePath));
333
- }
334
- }
335
-
336
- return chain;
337
- }
338
-
339
- /**
340
- * 가장 가까운 특수 파일 찾기
341
- */
342
- private findClosestSpecialFile(
343
- segments: ScannedFile["segments"],
344
- fileMap: Map<string, ScannedFile>
345
- ): string | undefined {
346
- // 현재 경로부터 루트까지 역순 탐색
347
- let currentPath = segments.map((s) => s.raw).join("/");
348
-
349
- while (currentPath) {
350
- const file = fileMap.get(currentPath);
351
- if (file) {
352
- return join(this.config.routesDir, file.relativePath);
353
- }
354
- // 상위 디렉토리로
355
- const lastSlash = currentPath.lastIndexOf("/");
356
- currentPath = lastSlash > 0 ? currentPath.slice(0, lastSlash) : "";
357
- }
358
-
359
- // 루트 체크
360
- const rootFile = fileMap.get(".");
361
- return rootFile ? join(this.config.routesDir, rootFile.relativePath) : undefined;
362
- }
363
-
364
- /**
365
- * 상대 경로에서 디렉토리 경로 추출 (루트는 ".")
366
- */
367
- private getDirPath(relativePath: string): string {
368
- const normalized = relativePath.replace(/\\/g, "/");
369
- const lastSlash = normalized.lastIndexOf("/");
370
- return lastSlash === -1 ? "." : normalized.slice(0, lastSlash);
371
- }
372
-
373
- /**
374
- * 경로에 비공개 폴더가 포함되어 있는지 확인
375
- */
376
- private hasPrivateSegment(relativePath: string): boolean {
377
- const normalized = relativePath.replace(/\\/g, "/");
378
- const segments = normalized.split("/").slice(0, -1);
379
- return segments.some((segment) => isPrivateFolder(segment));
380
- }
381
-
382
- /**
383
- * 제외 패턴 적용 여부
384
- */
385
- private isExcluded(relativePath: string, isDir: boolean): boolean {
386
- if (this.excludeMatchers.length === 0) return false;
387
-
388
- const normalized = relativePath.replace(/\\/g, "/");
389
- const candidates = isDir
390
- ? [normalized, normalized.endsWith("/") ? normalized : `${normalized}/`]
391
- : [normalized];
392
-
393
- return this.excludeMatchers.some((matcher) => candidates.some((path) => matcher.test(path)));
394
- }
395
-
396
- /**
397
- * 빈 결과 생성
398
- */
399
- private createEmptyResult(errors: ScanError[], scanTime: number): ScanResult {
400
- return {
401
- files: [],
402
- routes: [],
403
- errors,
404
- stats: {
405
- totalFiles: 0,
406
- pageCount: 0,
407
- apiCount: 0,
408
- layoutCount: 0,
409
- islandCount: 0,
410
- scanTime,
411
- },
412
- };
413
- }
414
-
415
- /**
416
- * 통계 계산
417
- */
418
- private calculateStats(
419
- files: ScannedFile[],
420
- routes: FSRouteConfig[],
421
- scanTime: number
422
- ): ScanStats {
423
- return {
424
- totalFiles: files.length,
425
- pageCount: routes.filter((r) => r.kind === "page").length,
426
- apiCount: routes.filter((r) => r.kind === "api").length,
427
- layoutCount: files.filter((f) => f.type === "layout").length,
428
- islandCount: files.filter((f) => f.type === "island").length,
429
- scanTime,
430
- };
431
- }
432
- }
433
-
434
- // ═══════════════════════════════════════════════════════════════════════════
435
- // Glob Utilities
436
- // ═══════════════════════════════════════════════════════════════════════════
437
-
438
- function globToRegExp(glob: string): RegExp {
439
- let regex = "^";
440
- let i = 0;
441
-
442
- while (i < glob.length) {
443
- const char = glob[i];
444
-
445
- if (char === "*") {
446
- const nextChar = glob[i + 1];
447
- const nextNextChar = glob[i + 2];
448
- if (nextChar === "*" && nextNextChar === "/") {
449
- // "**/" -> match any path prefix (including empty)
450
- regex += "(?:.*/)?";
451
- i += 2;
452
- } else if (nextChar === "*") {
453
- // "**" -> match any path (including "/")
454
- while (glob[i + 1] === "*") i++;
455
- regex += ".*";
456
- } else {
457
- // "*" -> match within a segment
458
- regex += "[^/]*";
459
- }
460
- } else if (char === "?") {
461
- regex += "[^/]";
462
- } else {
463
- regex += escapeRegex(char);
464
- }
465
-
466
- i++;
467
- }
468
-
469
- regex += "$";
470
- return new RegExp(regex);
471
- }
472
-
473
- function escapeRegex(char: string): string {
474
- return /[\\^$.*+?()[\]{}|]/.test(char) ? `\\${char}` : char;
475
- }
476
-
477
- // ═══════════════════════════════════════════════════════════════════════════
478
- // Factory Function
479
- // ═══════════════════════════════════════════════════════════════════════════
480
-
481
- /**
482
- * 스캐너 생성 팩토리 함수
483
- */
484
- export function createFSScanner(config: Partial<FSScannerConfig> = {}): FSScanner {
485
- return new FSScanner(config);
486
- }
487
-
488
- /**
489
- * 간편 스캔 함수
490
- */
491
- export async function scanRoutes(
492
- rootDir: string,
493
- config: Partial<FSScannerConfig> = {}
494
- ): Promise<ScanResult> {
495
- const scanner = createFSScanner(config);
496
- return scanner.scan(rootDir);
497
- }
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 } = 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 createRouteConfigs(
191
+ files: ScannedFile[],
192
+ rootDir: string
193
+ ): { 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
+ const clientModule = islands?.[0]
277
+ ? join(this.config.routesDir, islands[0].relativePath)
278
+ : undefined;
279
+
280
+ // 로딩/에러 모듈 찾기
281
+ const loadingModule = this.findClosestSpecialFile(file.segments, loadingMap);
282
+ const errorModule = this.findClosestSpecialFile(file.segments, errorMap);
283
+
284
+ const route: FSRouteConfig = {
285
+ id: routeId,
286
+ segments: file.segments,
287
+ pattern,
288
+ kind: file.type === "page" ? "page" : "api",
289
+ module: modulePath,
290
+ componentModule: file.type === "page" ? modulePath : undefined,
291
+ clientModule,
292
+ layoutChain,
293
+ loadingModule,
294
+ errorModule,
295
+ sourceFile: file.absolutePath,
296
+ };
297
+
298
+ // API 라우트의 경우 methods 추가 (기본값)
299
+ if (file.type === "route") {
300
+ route.methods = ["GET", "POST", "PUT", "PATCH", "DELETE"];
301
+ }
302
+
303
+ routes.push(route);
304
+ patternMap.set(pattern, route);
305
+ shapeMap.set(patternShape, route);
306
+ }
307
+
308
+ return { routes, routeErrors };
309
+ }
310
+
311
+ /**
312
+ * 레이아웃 체인 해결
313
+ */
314
+ private resolveLayoutChain(
315
+ segments: ScannedFile["segments"],
316
+ layoutMap: Map<string, ScannedFile>
317
+ ): string[] {
318
+ const chain: string[] = [];
319
+
320
+ // 루트 레이아웃
321
+ const rootLayout = layoutMap.get(".");
322
+ if (rootLayout) {
323
+ chain.push(join(this.config.routesDir, rootLayout.relativePath));
324
+ }
325
+
326
+ // 중첩 레이아웃
327
+ let currentPath = "";
328
+ for (const segment of segments) {
329
+ currentPath = currentPath ? `${currentPath}/${segment.raw}` : segment.raw;
330
+ const layout = layoutMap.get(currentPath);
331
+ if (layout) {
332
+ chain.push(join(this.config.routesDir, layout.relativePath));
333
+ }
334
+ }
335
+
336
+ return chain;
337
+ }
338
+
339
+ /**
340
+ * 가장 가까운 특수 파일 찾기
341
+ */
342
+ private findClosestSpecialFile(
343
+ segments: ScannedFile["segments"],
344
+ fileMap: Map<string, ScannedFile>
345
+ ): string | undefined {
346
+ // 현재 경로부터 루트까지 역순 탐색
347
+ let currentPath = segments.map((s) => s.raw).join("/");
348
+
349
+ while (currentPath) {
350
+ const file = fileMap.get(currentPath);
351
+ if (file) {
352
+ return join(this.config.routesDir, file.relativePath);
353
+ }
354
+ // 상위 디렉토리로
355
+ const lastSlash = currentPath.lastIndexOf("/");
356
+ currentPath = lastSlash > 0 ? currentPath.slice(0, lastSlash) : "";
357
+ }
358
+
359
+ // 루트 체크
360
+ const rootFile = fileMap.get(".");
361
+ return rootFile ? join(this.config.routesDir, rootFile.relativePath) : undefined;
362
+ }
363
+
364
+ /**
365
+ * 상대 경로에서 디렉토리 경로 추출 (루트는 ".")
366
+ */
367
+ private getDirPath(relativePath: string): string {
368
+ const normalized = relativePath.replace(/\\/g, "/");
369
+ const lastSlash = normalized.lastIndexOf("/");
370
+ return lastSlash === -1 ? "." : normalized.slice(0, lastSlash);
371
+ }
372
+
373
+ /**
374
+ * 경로에 비공개 폴더가 포함되어 있는지 확인
375
+ */
376
+ private hasPrivateSegment(relativePath: string): boolean {
377
+ const normalized = relativePath.replace(/\\/g, "/");
378
+ const segments = normalized.split("/").slice(0, -1);
379
+ return segments.some((segment) => isPrivateFolder(segment));
380
+ }
381
+
382
+ /**
383
+ * 제외 패턴 적용 여부
384
+ */
385
+ private isExcluded(relativePath: string, isDir: boolean): boolean {
386
+ if (this.excludeMatchers.length === 0) return false;
387
+
388
+ const normalized = relativePath.replace(/\\/g, "/");
389
+ const candidates = isDir
390
+ ? [normalized, normalized.endsWith("/") ? normalized : `${normalized}/`]
391
+ : [normalized];
392
+
393
+ return this.excludeMatchers.some((matcher) => candidates.some((path) => matcher.test(path)));
394
+ }
395
+
396
+ /**
397
+ * 빈 결과 생성
398
+ */
399
+ private createEmptyResult(errors: ScanError[], scanTime: number): ScanResult {
400
+ return {
401
+ files: [],
402
+ routes: [],
403
+ errors,
404
+ stats: {
405
+ totalFiles: 0,
406
+ pageCount: 0,
407
+ apiCount: 0,
408
+ layoutCount: 0,
409
+ islandCount: 0,
410
+ scanTime,
411
+ },
412
+ };
413
+ }
414
+
415
+ /**
416
+ * 통계 계산
417
+ */
418
+ private calculateStats(
419
+ files: ScannedFile[],
420
+ routes: FSRouteConfig[],
421
+ scanTime: number
422
+ ): ScanStats {
423
+ return {
424
+ totalFiles: files.length,
425
+ pageCount: routes.filter((r) => r.kind === "page").length,
426
+ apiCount: routes.filter((r) => r.kind === "api").length,
427
+ layoutCount: files.filter((f) => f.type === "layout").length,
428
+ islandCount: files.filter((f) => f.type === "island").length,
429
+ scanTime,
430
+ };
431
+ }
432
+ }
433
+
434
+ // ═══════════════════════════════════════════════════════════════════════════
435
+ // Glob Utilities
436
+ // ═══════════════════════════════════════════════════════════════════════════
437
+
438
+ function globToRegExp(glob: string): RegExp {
439
+ let regex = "^";
440
+ let i = 0;
441
+
442
+ while (i < glob.length) {
443
+ const char = glob[i];
444
+
445
+ if (char === "*") {
446
+ const nextChar = glob[i + 1];
447
+ const nextNextChar = glob[i + 2];
448
+ if (nextChar === "*" && nextNextChar === "/") {
449
+ // "**/" -> match any path prefix (including empty)
450
+ regex += "(?:.*/)?";
451
+ i += 2;
452
+ } else if (nextChar === "*") {
453
+ // "**" -> match any path (including "/")
454
+ while (glob[i + 1] === "*") i++;
455
+ regex += ".*";
456
+ } else {
457
+ // "*" -> match within a segment
458
+ regex += "[^/]*";
459
+ }
460
+ } else if (char === "?") {
461
+ regex += "[^/]";
462
+ } else {
463
+ regex += escapeRegex(char);
464
+ }
465
+
466
+ i++;
467
+ }
468
+
469
+ regex += "$";
470
+ return new RegExp(regex);
471
+ }
472
+
473
+ function escapeRegex(char: string): string {
474
+ return /[\\^$.*+?()[\]{}|]/.test(char) ? `\\${char}` : char;
475
+ }
476
+
477
+ // ═══════════════════════════════════════════════════════════════════════════
478
+ // Factory Function
479
+ // ═══════════════════════════════════════════════════════════════════════════
480
+
481
+ /**
482
+ * 스캐너 생성 팩토리 함수
483
+ */
484
+ export function createFSScanner(config: Partial<FSScannerConfig> = {}): FSScanner {
485
+ return new FSScanner(config);
486
+ }
487
+
488
+ /**
489
+ * 간편 스캔 함수
490
+ */
491
+ export async function scanRoutes(
492
+ rootDir: string,
493
+ config: Partial<FSScannerConfig> = {}
494
+ ): Promise<ScanResult> {
495
+ const scanner = createFSScanner(config);
496
+ return scanner.scan(rootDir);
497
+ }