@mandujs/core 0.12.1 → 0.13.0

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 (177) hide show
  1. package/README.ko.md +304 -304
  2. package/README.md +653 -653
  3. package/package.json +8 -8
  4. package/src/brain/architecture/analyzer.ts +28 -26
  5. package/src/brain/doctor/analyzer.ts +1 -1
  6. package/src/bundler/build.ts +91 -91
  7. package/src/bundler/css.ts +302 -302
  8. package/src/bundler/dev.ts +0 -1
  9. package/src/change/history.ts +3 -3
  10. package/src/change/snapshot.ts +10 -9
  11. package/src/change/transaction.ts +2 -2
  12. package/src/client/Link.tsx +227 -227
  13. package/src/client/globals.ts +44 -44
  14. package/src/client/hooks.ts +267 -267
  15. package/src/client/index.ts +5 -5
  16. package/src/client/island.ts +8 -8
  17. package/src/client/router.ts +435 -435
  18. package/src/client/runtime.ts +23 -23
  19. package/src/client/serialize.ts +404 -404
  20. package/src/client/window-state.ts +101 -101
  21. package/src/config/mandu.ts +94 -96
  22. package/src/config/validate.ts +213 -215
  23. package/src/config/watcher.ts +311 -311
  24. package/src/constants.ts +40 -40
  25. package/src/content/content-layer.ts +314 -314
  26. package/src/content/content.test.ts +433 -433
  27. package/src/content/data-store.ts +245 -245
  28. package/src/content/digest.ts +133 -133
  29. package/src/content/index.ts +164 -164
  30. package/src/content/loader-context.ts +172 -172
  31. package/src/content/loaders/api.ts +216 -216
  32. package/src/content/loaders/file.ts +169 -169
  33. package/src/content/loaders/glob.ts +252 -252
  34. package/src/content/loaders/index.ts +34 -34
  35. package/src/content/loaders/types.ts +137 -137
  36. package/src/content/meta-store.ts +209 -209
  37. package/src/content/types.ts +282 -282
  38. package/src/content/watcher.ts +135 -135
  39. package/src/contract/client-safe.test.ts +42 -42
  40. package/src/contract/client-safe.ts +114 -114
  41. package/src/contract/client.ts +16 -16
  42. package/src/contract/define.ts +459 -459
  43. package/src/contract/handler.ts +10 -10
  44. package/src/contract/normalize.test.ts +276 -276
  45. package/src/contract/normalize.ts +404 -404
  46. package/src/contract/registry.test.ts +206 -206
  47. package/src/contract/registry.ts +568 -568
  48. package/src/contract/schema.ts +48 -48
  49. package/src/contract/types.ts +58 -58
  50. package/src/contract/validator.ts +32 -32
  51. package/src/devtools/ai/context-builder.ts +375 -375
  52. package/src/devtools/ai/index.ts +25 -25
  53. package/src/devtools/ai/mcp-connector.ts +465 -465
  54. package/src/devtools/client/catchers/error-catcher.ts +327 -327
  55. package/src/devtools/client/catchers/index.ts +18 -18
  56. package/src/devtools/client/catchers/network-proxy.ts +363 -363
  57. package/src/devtools/client/components/index.ts +39 -39
  58. package/src/devtools/client/components/kitchen-root.tsx +362 -362
  59. package/src/devtools/client/components/mandu-character.tsx +241 -241
  60. package/src/devtools/client/components/overlay.tsx +368 -368
  61. package/src/devtools/client/components/panel/errors-panel.tsx +259 -259
  62. package/src/devtools/client/components/panel/guard-panel.tsx +244 -244
  63. package/src/devtools/client/components/panel/index.ts +32 -32
  64. package/src/devtools/client/components/panel/islands-panel.tsx +304 -304
  65. package/src/devtools/client/components/panel/network-panel.tsx +292 -292
  66. package/src/devtools/client/components/panel/panel-container.tsx +259 -259
  67. package/src/devtools/client/filters/context-filters.ts +282 -282
  68. package/src/devtools/client/filters/index.ts +16 -16
  69. package/src/devtools/client/index.ts +63 -63
  70. package/src/devtools/client/persistence.ts +335 -335
  71. package/src/devtools/client/state-manager.ts +478 -478
  72. package/src/devtools/design-tokens.ts +263 -263
  73. package/src/devtools/hook/create-hook.ts +207 -207
  74. package/src/devtools/hook/index.ts +13 -13
  75. package/src/devtools/index.ts +439 -439
  76. package/src/devtools/init.ts +266 -266
  77. package/src/devtools/protocol.ts +237 -237
  78. package/src/devtools/server/index.ts +17 -17
  79. package/src/devtools/server/source-context.ts +444 -444
  80. package/src/devtools/types.ts +319 -319
  81. package/src/devtools/worker/index.ts +25 -25
  82. package/src/devtools/worker/redaction-worker.ts +222 -222
  83. package/src/devtools/worker/worker-manager.ts +409 -409
  84. package/src/error/classifier.ts +2 -2
  85. package/src/error/domains.ts +265 -265
  86. package/src/error/formatter.ts +32 -32
  87. package/src/error/result.ts +46 -46
  88. package/src/error/stack-analyzer.ts +5 -0
  89. package/src/error/types.ts +6 -6
  90. package/src/errors/extractor.ts +409 -409
  91. package/src/errors/index.ts +19 -19
  92. package/src/filling/auth.ts +308 -308
  93. package/src/filling/context.ts +569 -569
  94. package/src/filling/deps.ts +238 -238
  95. package/src/generator/contract-glue.ts +2 -1
  96. package/src/generator/generate.ts +12 -10
  97. package/src/generator/index.ts +3 -3
  98. package/src/generator/templates.ts +80 -79
  99. package/src/guard/analyzer.ts +360 -360
  100. package/src/guard/ast-analyzer.ts +806 -806
  101. package/src/guard/auto-correct.ts +1 -1
  102. package/src/guard/check.ts +128 -128
  103. package/src/guard/contract-guard.ts +9 -9
  104. package/src/guard/file-type.test.ts +24 -24
  105. package/src/guard/healing.ts +2 -0
  106. package/src/guard/index.ts +2 -0
  107. package/src/guard/negotiation.ts +430 -4
  108. package/src/guard/presets/atomic.ts +70 -70
  109. package/src/guard/presets/clean.ts +77 -77
  110. package/src/guard/presets/cqrs.test.ts +175 -0
  111. package/src/guard/presets/cqrs.ts +107 -0
  112. package/src/guard/presets/fsd.ts +79 -79
  113. package/src/guard/presets/hexagonal.ts +68 -68
  114. package/src/guard/presets/index.ts +291 -288
  115. package/src/guard/reporter.ts +445 -445
  116. package/src/guard/rules.ts +12 -12
  117. package/src/guard/statistics.ts +578 -578
  118. package/src/guard/suggestions.ts +358 -352
  119. package/src/guard/types.ts +348 -347
  120. package/src/guard/validator.ts +834 -834
  121. package/src/guard/watcher.ts +404 -404
  122. package/src/index.ts +1 -0
  123. package/src/intent/index.ts +310 -310
  124. package/src/island/index.ts +304 -304
  125. package/src/logging/index.ts +22 -22
  126. package/src/logging/transports.ts +365 -365
  127. package/src/paths.test.ts +47 -0
  128. package/src/paths.ts +47 -0
  129. package/src/plugins/index.ts +38 -38
  130. package/src/plugins/registry.ts +377 -377
  131. package/src/plugins/types.ts +363 -363
  132. package/src/report/build.ts +1 -1
  133. package/src/report/index.ts +1 -1
  134. package/src/router/fs-patterns.ts +387 -387
  135. package/src/router/fs-routes.ts +344 -401
  136. package/src/router/fs-scanner.ts +497 -497
  137. package/src/router/fs-types.ts +270 -278
  138. package/src/router/index.ts +81 -81
  139. package/src/runtime/boundary.tsx +232 -232
  140. package/src/runtime/compose.ts +222 -222
  141. package/src/runtime/lifecycle.ts +381 -381
  142. package/src/runtime/logger.test.ts +345 -345
  143. package/src/runtime/logger.ts +677 -677
  144. package/src/runtime/router.test.ts +476 -476
  145. package/src/runtime/router.ts +105 -105
  146. package/src/runtime/security.ts +155 -155
  147. package/src/runtime/server.ts +24 -24
  148. package/src/runtime/session-key.ts +328 -328
  149. package/src/runtime/ssr.ts +367 -367
  150. package/src/runtime/streaming-ssr.ts +1245 -1245
  151. package/src/runtime/trace.ts +144 -144
  152. package/src/seo/index.ts +214 -214
  153. package/src/seo/integration/ssr.ts +307 -307
  154. package/src/seo/render/basic.ts +427 -427
  155. package/src/seo/render/index.ts +143 -143
  156. package/src/seo/render/jsonld.ts +539 -539
  157. package/src/seo/render/opengraph.ts +191 -191
  158. package/src/seo/render/robots.ts +116 -116
  159. package/src/seo/render/sitemap.ts +137 -137
  160. package/src/seo/render/twitter.ts +126 -126
  161. package/src/seo/resolve/index.ts +353 -353
  162. package/src/seo/resolve/opengraph.ts +143 -143
  163. package/src/seo/resolve/robots.ts +73 -73
  164. package/src/seo/resolve/title.ts +94 -94
  165. package/src/seo/resolve/twitter.ts +73 -73
  166. package/src/seo/resolve/url.ts +97 -97
  167. package/src/seo/routes/index.ts +290 -290
  168. package/src/seo/types.ts +575 -575
  169. package/src/slot/validator.ts +39 -39
  170. package/src/spec/index.ts +3 -3
  171. package/src/spec/load.ts +76 -76
  172. package/src/spec/lock.ts +56 -56
  173. package/src/utils/bun.ts +8 -8
  174. package/src/utils/lru-cache.ts +75 -75
  175. package/src/utils/safe-io.ts +188 -188
  176. package/src/utils/string-safe.ts +298 -298
  177. package/src/watcher/rules.ts +5 -5
@@ -1,569 +1,569 @@
1
- /**
2
- * Mandu Context - 만두 접시 🥟
3
- * Request/Response를 래핑하여 편리한 API 제공
4
- *
5
- * DNA-002: 의존성 주입 패턴 지원
6
- */
7
-
8
- import type { ZodSchema } from "zod";
9
- import type { ContractSchema, ContractMethod } from "../contract/schema";
10
- import type { InferBody, InferHeaders, InferParams, InferQuery, InferResponse } from "../contract/types";
11
- import { ContractValidator, type ContractValidatorOptions } from "../contract/validator";
12
- import { type FillingDeps, createDefaultDeps, globalDeps } from "./deps";
13
-
14
- type ContractInput<
15
- TContract extends ContractSchema,
16
- TMethod extends ContractMethod,
17
- > = {
18
- query: InferQuery<TContract, TMethod>;
19
- body: InferBody<TContract, TMethod>;
20
- params: InferParams<TContract, TMethod>;
21
- headers: InferHeaders<TContract, TMethod>;
22
- };
23
-
24
- // ========== Cookie Types ==========
25
-
26
- export interface CookieOptions {
27
- /** 쿠키 만료 시간 (Date 객체 또는 문자열) */
28
- expires?: Date | string;
29
- /** 쿠키 유효 기간 (초) */
30
- maxAge?: number;
31
- /** 쿠키 도메인 */
32
- domain?: string;
33
- /** 쿠키 경로 */
34
- path?: string;
35
- /** HTTPS에서만 전송 */
36
- secure?: boolean;
37
- /** JavaScript에서 접근 불가 */
38
- httpOnly?: boolean;
39
- /** Same-Site 정책 */
40
- sameSite?: "strict" | "lax" | "none";
41
- /** 파티션 키 (CHIPS) */
42
- partitioned?: boolean;
43
- }
44
-
45
- /**
46
- * Cookie Manager - 쿠키 읽기/쓰기 관리
47
- */
48
- export class CookieManager {
49
- private requestCookies: Map<string, string>;
50
- private responseCookies: Map<string, { value: string; options: CookieOptions }>;
51
- private deletedCookies: Set<string>;
52
-
53
- constructor(request: Request) {
54
- this.requestCookies = this.parseRequestCookies(request);
55
- this.responseCookies = new Map();
56
- this.deletedCookies = new Set();
57
- }
58
-
59
- private parseRequestCookies(request: Request): Map<string, string> {
60
- const cookies = new Map<string, string>();
61
- const cookieHeader = request.headers.get("cookie");
62
-
63
- if (cookieHeader) {
64
- const pairs = cookieHeader.split(";");
65
- for (const pair of pairs) {
66
- const [name, ...rest] = pair.trim().split("=");
67
- if (name) {
68
- const rawValue = rest.join("=");
69
- try {
70
- cookies.set(name, decodeURIComponent(rawValue));
71
- } catch {
72
- // 잘못된 URL 인코딩 시 원본 값 사용
73
- cookies.set(name, rawValue);
74
- }
75
- }
76
- }
77
- }
78
-
79
- return cookies;
80
- }
81
-
82
- /**
83
- * 쿠키 값 읽기
84
- * @example
85
- * const session = ctx.cookies.get('session');
86
- */
87
- get(name: string): string | undefined {
88
- return this.requestCookies.get(name);
89
- }
90
-
91
- /**
92
- * 쿠키 존재 여부 확인
93
- */
94
- has(name: string): boolean {
95
- return this.requestCookies.has(name);
96
- }
97
-
98
- /**
99
- * 모든 쿠키 가져오기
100
- */
101
- getAll(): Record<string, string> {
102
- return Object.fromEntries(this.requestCookies);
103
- }
104
-
105
- /**
106
- * 쿠키 설정
107
- * @example
108
- * ctx.cookies.set('session', 'abc123', { httpOnly: true, maxAge: 3600 });
109
- */
110
- set(name: string, value: string, options: CookieOptions = {}): void {
111
- this.responseCookies.set(name, { value, options });
112
- this.deletedCookies.delete(name);
113
- }
114
-
115
- /**
116
- * 쿠키 삭제
117
- * @example
118
- * ctx.cookies.delete('session');
119
- */
120
- delete(name: string, options: Pick<CookieOptions, "domain" | "path"> = {}): void {
121
- this.responseCookies.delete(name);
122
- this.deletedCookies.add(name);
123
- // 삭제용 쿠키 설정 (maxAge=0)
124
- this.responseCookies.set(name, {
125
- value: "",
126
- options: {
127
- ...options,
128
- maxAge: 0,
129
- expires: new Date(0),
130
- },
131
- });
132
- }
133
-
134
- /**
135
- * Set-Cookie 헤더 값들 생성
136
- */
137
- getSetCookieHeaders(): string[] {
138
- const headers: string[] = [];
139
-
140
- for (const [name, { value, options }] of this.responseCookies) {
141
- headers.push(this.serializeCookie(name, value, options));
142
- }
143
-
144
- return headers;
145
- }
146
-
147
- /**
148
- * 쿠키를 Set-Cookie 헤더 형식으로 직렬화
149
- */
150
- private serializeCookie(name: string, value: string, options: CookieOptions): string {
151
- const parts: string[] = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];
152
-
153
- if (options.maxAge !== undefined) {
154
- parts.push(`Max-Age=${options.maxAge}`);
155
- }
156
-
157
- if (options.expires) {
158
- const expires =
159
- options.expires instanceof Date
160
- ? options.expires.toUTCString()
161
- : options.expires;
162
- parts.push(`Expires=${expires}`);
163
- }
164
-
165
- if (options.domain) {
166
- parts.push(`Domain=${options.domain}`);
167
- }
168
-
169
- if (options.path) {
170
- parts.push(`Path=${options.path}`);
171
- } else {
172
- parts.push("Path=/"); // 기본값
173
- }
174
-
175
- if (options.secure) {
176
- parts.push("Secure");
177
- }
178
-
179
- if (options.httpOnly) {
180
- parts.push("HttpOnly");
181
- }
182
-
183
- if (options.sameSite) {
184
- parts.push(`SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`);
185
- }
186
-
187
- if (options.partitioned) {
188
- parts.push("Partitioned");
189
- }
190
-
191
- return parts.join("; ");
192
- }
193
-
194
- /**
195
- * Response에 Set-Cookie 헤더들 적용
196
- */
197
- applyToResponse(response: Response): Response {
198
- const setCookieHeaders = this.getSetCookieHeaders();
199
-
200
- if (setCookieHeaders.length === 0) {
201
- return response;
202
- }
203
-
204
- // Headers를 복사하여 수정
205
- const newHeaders = new Headers(response.headers);
206
-
207
- for (const setCookie of setCookieHeaders) {
208
- newHeaders.append("Set-Cookie", setCookie);
209
- }
210
-
211
- return new Response(response.body, {
212
- status: response.status,
213
- statusText: response.statusText,
214
- headers: newHeaders,
215
- });
216
- }
217
-
218
- /**
219
- * 응답에 적용할 쿠키가 있는지 확인
220
- */
221
- hasPendingCookies(): boolean {
222
- return this.responseCookies.size > 0;
223
- }
224
- }
225
-
226
- // ========== ManduContext ==========
227
-
228
- export class ManduContext {
229
- private store: Map<string, unknown> = new Map();
230
- private _params: Record<string, string>;
231
- private _query: Record<string, string>;
232
- private _cookies: CookieManager;
233
- private _deps: FillingDeps;
234
-
235
- constructor(
236
- public readonly request: Request,
237
- params: Record<string, string> = {},
238
- deps?: FillingDeps
239
- ) {
240
- this._params = params;
241
- this._query = this.parseQuery();
242
- this._cookies = new CookieManager(request);
243
- this._deps = deps ?? globalDeps.get();
244
- }
245
-
246
- /**
247
- * DNA-002: 의존성 접근
248
- *
249
- * @example
250
- * ```ts
251
- * // 데이터베이스 쿼리
252
- * const users = await ctx.deps.db?.query("SELECT * FROM users");
253
- *
254
- * // 캐시 사용
255
- * const cached = await ctx.deps.cache?.get("user:123");
256
- *
257
- * // 로깅
258
- * ctx.deps.logger?.info("User logged in", { userId });
259
- *
260
- * // 현재 시간 (테스트에서 목킹 가능)
261
- * const now = ctx.deps.now?.() ?? new Date();
262
- * ```
263
- */
264
- get deps(): FillingDeps {
265
- return this._deps;
266
- }
267
-
268
- private parseQuery(): Record<string, string> {
269
- const url = new URL(this.request.url);
270
- const query: Record<string, string> = {};
271
- url.searchParams.forEach((value, key) => {
272
- query[key] = value;
273
- });
274
- return query;
275
- }
276
-
277
- // ============================================
278
- // 🥟 Request 읽기
279
- // ============================================
280
-
281
- /** Path parameters (e.g., /users/:id → { id: '123' }) */
282
- get params(): Record<string, string> {
283
- return this._params;
284
- }
285
-
286
- /** Query parameters (e.g., ?name=mandu → { name: 'mandu' }) */
287
- get query(): Record<string, string> {
288
- return this._query;
289
- }
290
-
291
- /** Request headers */
292
- get headers(): Headers {
293
- return this.request.headers;
294
- }
295
-
296
- /** HTTP method */
297
- get method(): string {
298
- return this.request.method;
299
- }
300
-
301
- /** Request URL */
302
- get url(): string {
303
- return this.request.url;
304
- }
305
-
306
- /** Shorthand for request */
307
- get req(): Request {
308
- return this.request;
309
- }
310
-
311
- /**
312
- * Cookie Manager
313
- * @example
314
- * // 쿠키 읽기
315
- * const session = ctx.cookies.get('session');
316
- *
317
- * // 쿠키 설정
318
- * ctx.cookies.set('session', 'abc123', { httpOnly: true, maxAge: 3600 });
319
- *
320
- * // 쿠키 삭제
321
- * ctx.cookies.delete('session');
322
- */
323
- get cookies(): CookieManager {
324
- return this._cookies;
325
- }
326
-
327
- /**
328
- * Parse request body with optional Zod validation
329
- * @example
330
- * const data = await ctx.body() // any
331
- * const data = await ctx.body(UserSchema) // typed & validated
332
- */
333
- async body<T = unknown>(schema?: ZodSchema<T>): Promise<T> {
334
- const contentType = this.request.headers.get("content-type") || "";
335
- let data: unknown;
336
-
337
- if (contentType.includes("application/json")) {
338
- data = await this.request.json();
339
- } else if (contentType.includes("application/x-www-form-urlencoded")) {
340
- const formData = await this.request.formData();
341
- data = Object.fromEntries(formData.entries());
342
- } else if (contentType.includes("multipart/form-data")) {
343
- const formData = await this.request.formData();
344
- data = Object.fromEntries(formData.entries());
345
- } else {
346
- data = await this.request.text();
347
- }
348
-
349
- if (schema) {
350
- const result = schema.safeParse(data);
351
- if (!result.success) {
352
- throw new ValidationError(result.error.errors);
353
- }
354
- return result.data;
355
- }
356
-
357
- return data as T;
358
- }
359
-
360
- /**
361
- * Parse and validate request input via Contract
362
- * @example
363
- * const input = await ctx.input(userContract, "POST", { id: "123" })
364
- */
365
- async input<
366
- TContract extends ContractSchema,
367
- TMethod extends ContractMethod,
368
- >(
369
- contract: TContract,
370
- method: TMethod,
371
- pathParams: Record<string, string> = {},
372
- options: ContractValidatorOptions = {}
373
- ): Promise<ContractInput<TContract, TMethod>> {
374
- const validator = new ContractValidator(contract, options);
375
- const result = await validator.validateAndNormalizeRequest(
376
- this.request,
377
- method,
378
- pathParams
379
- );
380
-
381
- if (!result.success) {
382
- throw new ValidationError(result.errors ?? []);
383
- }
384
-
385
- return (result.data ?? {}) as ContractInput<TContract, TMethod>;
386
- }
387
-
388
- // ============================================
389
- // 🥟 Response 보내기
390
- // ============================================
391
-
392
- /**
393
- * Response에 쿠키 헤더 적용 (내부 사용)
394
- */
395
- private withCookies(response: Response): Response {
396
- if (this._cookies.hasPendingCookies()) {
397
- return this._cookies.applyToResponse(response);
398
- }
399
- return response;
400
- }
401
-
402
- /** 200 OK */
403
- ok<T>(data: T): Response {
404
- return this.json(data, 200);
405
- }
406
-
407
- /** 201 Created */
408
- created<T>(data: T): Response {
409
- return this.json(data, 201);
410
- }
411
-
412
- /** 204 No Content */
413
- noContent(): Response {
414
- return this.withCookies(new Response(null, { status: 204 }));
415
- }
416
-
417
- /** 400 Bad Request */
418
- error(message: string, details?: unknown): Response {
419
- return this.json({ status: "error", message, details }, 400);
420
- }
421
-
422
- /** 401 Unauthorized */
423
- unauthorized(message: string = "Unauthorized"): Response {
424
- return this.json({ status: "error", message }, 401);
425
- }
426
-
427
- /** 403 Forbidden */
428
- forbidden(message: string = "Forbidden"): Response {
429
- return this.json({ status: "error", message }, 403);
430
- }
431
-
432
- /** 404 Not Found */
433
- notFound(message: string = "Not Found"): Response {
434
- return this.json({ status: "error", message }, 404);
435
- }
436
-
437
- /** 500 Internal Server Error */
438
- fail(message: string = "Internal Server Error"): Response {
439
- return this.json({ status: "error", message }, 500);
440
- }
441
-
442
- /** Custom JSON response */
443
- json<T>(data: T, status: number = 200): Response {
444
- const response = Response.json(data, { status });
445
- return this.withCookies(response);
446
- }
447
-
448
- /**
449
- * Validate and send response via Contract
450
- * @example
451
- * return ctx.output(userContract, 200, { data: users })
452
- */
453
- output<
454
- TContract extends ContractSchema,
455
- TStatus extends keyof TContract["response"],
456
- >(
457
- contract: TContract,
458
- status: TStatus,
459
- data: InferResponse<TContract, TStatus>,
460
- options: ContractValidatorOptions = {}
461
- ): Response {
462
- const validator = new ContractValidator(contract, options);
463
- const result = validator.validateResponse(data, Number(status));
464
-
465
- if (!result.success) {
466
- if (options.mode === "strict") {
467
- const errorResponse = Response.json(
468
- {
469
- errorType: "CONTRACT_VIOLATION",
470
- code: "MANDU_C001",
471
- message: "Response does not match contract schema",
472
- summary: "응답이 Contract 스키마와 일치하지 않습니다",
473
- statusCode: Number(status),
474
- violations: result.errors,
475
- timestamp: new Date().toISOString(),
476
- },
477
- { status: 500 }
478
- );
479
- return this.withCookies(errorResponse);
480
- }
481
-
482
- console.warn(
483
- "\x1b[33m[Mandu] Contract violation in response:\x1b[0m",
484
- result.errors
485
- );
486
- }
487
-
488
- const payload = result.success ? result.data : data;
489
- return this.json(payload as InferResponse<TContract, TStatus>, Number(status));
490
- }
491
-
492
- /** 200 OK with Contract validation */
493
- okContract<TContract extends ContractSchema>(
494
- contract: TContract,
495
- data: InferResponse<TContract, 200>,
496
- options: ContractValidatorOptions = {}
497
- ): Response {
498
- return this.output(contract, 200 as keyof TContract["response"], data, options);
499
- }
500
-
501
- /** 201 Created with Contract validation */
502
- createdContract<TContract extends ContractSchema>(
503
- contract: TContract,
504
- data: InferResponse<TContract, 201>,
505
- options: ContractValidatorOptions = {}
506
- ): Response {
507
- return this.output(contract, 201 as keyof TContract["response"], data, options);
508
- }
509
-
510
- /** Custom text response */
511
- text(data: string, status: number = 200): Response {
512
- const response = new Response(data, {
513
- status,
514
- headers: { "Content-Type": "text/plain" },
515
- });
516
- return this.withCookies(response);
517
- }
518
-
519
- /** Custom HTML response */
520
- html(data: string, status: number = 200): Response {
521
- const response = new Response(data, {
522
- status,
523
- headers: { "Content-Type": "text/html" },
524
- });
525
- return this.withCookies(response);
526
- }
527
-
528
- /** Redirect response */
529
- redirect(url: string, status: 301 | 302 | 307 | 308 = 302): Response {
530
- const response = Response.redirect(url, status);
531
- return this.withCookies(response);
532
- }
533
-
534
- // ============================================
535
- // 🥟 상태 저장 (Lifecycle → Handler 전달)
536
- // ============================================
537
-
538
- /** Store value for later use */
539
- set<T>(key: string, value: T): void {
540
- this.store.set(key, value);
541
- }
542
-
543
- /** Get stored value */
544
- get<T>(key: string): T | undefined {
545
- return this.store.get(key) as T | undefined;
546
- }
547
-
548
- /** Check if key exists */
549
- has(key: string): boolean {
550
- return this.store.has(key);
551
- }
552
- }
553
-
554
- /** Route context for error reporting */
555
- export interface ValidationRouteContext {
556
- routeId: string;
557
- pattern: string;
558
- }
559
-
560
- /** Validation error with details */
561
- export class ValidationError extends Error {
562
- constructor(
563
- public readonly errors: unknown[],
564
- public readonly routeContext?: ValidationRouteContext
565
- ) {
566
- super("Validation failed");
567
- this.name = "ValidationError";
568
- }
569
- }
1
+ /**
2
+ * Mandu Context - 만두 접시 🥟
3
+ * Request/Response를 래핑하여 편리한 API 제공
4
+ *
5
+ * DNA-002: 의존성 주입 패턴 지원
6
+ */
7
+
8
+ import type { ZodSchema } from "zod";
9
+ import type { ContractSchema, ContractMethod } from "../contract/schema";
10
+ import type { InferBody, InferHeaders, InferParams, InferQuery, InferResponse } from "../contract/types";
11
+ import { ContractValidator, type ContractValidatorOptions } from "../contract/validator";
12
+ import { type FillingDeps, createDefaultDeps, globalDeps } from "./deps";
13
+
14
+ type ContractInput<
15
+ TContract extends ContractSchema,
16
+ TMethod extends ContractMethod,
17
+ > = {
18
+ query: InferQuery<TContract, TMethod>;
19
+ body: InferBody<TContract, TMethod>;
20
+ params: InferParams<TContract, TMethod>;
21
+ headers: InferHeaders<TContract, TMethod>;
22
+ };
23
+
24
+ // ========== Cookie Types ==========
25
+
26
+ export interface CookieOptions {
27
+ /** 쿠키 만료 시간 (Date 객체 또는 문자열) */
28
+ expires?: Date | string;
29
+ /** 쿠키 유효 기간 (초) */
30
+ maxAge?: number;
31
+ /** 쿠키 도메인 */
32
+ domain?: string;
33
+ /** 쿠키 경로 */
34
+ path?: string;
35
+ /** HTTPS에서만 전송 */
36
+ secure?: boolean;
37
+ /** JavaScript에서 접근 불가 */
38
+ httpOnly?: boolean;
39
+ /** Same-Site 정책 */
40
+ sameSite?: "strict" | "lax" | "none";
41
+ /** 파티션 키 (CHIPS) */
42
+ partitioned?: boolean;
43
+ }
44
+
45
+ /**
46
+ * Cookie Manager - 쿠키 읽기/쓰기 관리
47
+ */
48
+ export class CookieManager {
49
+ private requestCookies: Map<string, string>;
50
+ private responseCookies: Map<string, { value: string; options: CookieOptions }>;
51
+ private deletedCookies: Set<string>;
52
+
53
+ constructor(request: Request) {
54
+ this.requestCookies = this.parseRequestCookies(request);
55
+ this.responseCookies = new Map();
56
+ this.deletedCookies = new Set();
57
+ }
58
+
59
+ private parseRequestCookies(request: Request): Map<string, string> {
60
+ const cookies = new Map<string, string>();
61
+ const cookieHeader = request.headers.get("cookie");
62
+
63
+ if (cookieHeader) {
64
+ const pairs = cookieHeader.split(";");
65
+ for (const pair of pairs) {
66
+ const [name, ...rest] = pair.trim().split("=");
67
+ if (name) {
68
+ const rawValue = rest.join("=");
69
+ try {
70
+ cookies.set(name, decodeURIComponent(rawValue));
71
+ } catch {
72
+ // 잘못된 URL 인코딩 시 원본 값 사용
73
+ cookies.set(name, rawValue);
74
+ }
75
+ }
76
+ }
77
+ }
78
+
79
+ return cookies;
80
+ }
81
+
82
+ /**
83
+ * 쿠키 값 읽기
84
+ * @example
85
+ * const session = ctx.cookies.get('session');
86
+ */
87
+ get(name: string): string | undefined {
88
+ return this.requestCookies.get(name);
89
+ }
90
+
91
+ /**
92
+ * 쿠키 존재 여부 확인
93
+ */
94
+ has(name: string): boolean {
95
+ return this.requestCookies.has(name);
96
+ }
97
+
98
+ /**
99
+ * 모든 쿠키 가져오기
100
+ */
101
+ getAll(): Record<string, string> {
102
+ return Object.fromEntries(this.requestCookies);
103
+ }
104
+
105
+ /**
106
+ * 쿠키 설정
107
+ * @example
108
+ * ctx.cookies.set('session', 'abc123', { httpOnly: true, maxAge: 3600 });
109
+ */
110
+ set(name: string, value: string, options: CookieOptions = {}): void {
111
+ this.responseCookies.set(name, { value, options });
112
+ this.deletedCookies.delete(name);
113
+ }
114
+
115
+ /**
116
+ * 쿠키 삭제
117
+ * @example
118
+ * ctx.cookies.delete('session');
119
+ */
120
+ delete(name: string, options: Pick<CookieOptions, "domain" | "path"> = {}): void {
121
+ this.responseCookies.delete(name);
122
+ this.deletedCookies.add(name);
123
+ // 삭제용 쿠키 설정 (maxAge=0)
124
+ this.responseCookies.set(name, {
125
+ value: "",
126
+ options: {
127
+ ...options,
128
+ maxAge: 0,
129
+ expires: new Date(0),
130
+ },
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Set-Cookie 헤더 값들 생성
136
+ */
137
+ getSetCookieHeaders(): string[] {
138
+ const headers: string[] = [];
139
+
140
+ for (const [name, { value, options }] of this.responseCookies) {
141
+ headers.push(this.serializeCookie(name, value, options));
142
+ }
143
+
144
+ return headers;
145
+ }
146
+
147
+ /**
148
+ * 쿠키를 Set-Cookie 헤더 형식으로 직렬화
149
+ */
150
+ private serializeCookie(name: string, value: string, options: CookieOptions): string {
151
+ const parts: string[] = [`${encodeURIComponent(name)}=${encodeURIComponent(value)}`];
152
+
153
+ if (options.maxAge !== undefined) {
154
+ parts.push(`Max-Age=${options.maxAge}`);
155
+ }
156
+
157
+ if (options.expires) {
158
+ const expires =
159
+ options.expires instanceof Date
160
+ ? options.expires.toUTCString()
161
+ : options.expires;
162
+ parts.push(`Expires=${expires}`);
163
+ }
164
+
165
+ if (options.domain) {
166
+ parts.push(`Domain=${options.domain}`);
167
+ }
168
+
169
+ if (options.path) {
170
+ parts.push(`Path=${options.path}`);
171
+ } else {
172
+ parts.push("Path=/"); // 기본값
173
+ }
174
+
175
+ if (options.secure) {
176
+ parts.push("Secure");
177
+ }
178
+
179
+ if (options.httpOnly) {
180
+ parts.push("HttpOnly");
181
+ }
182
+
183
+ if (options.sameSite) {
184
+ parts.push(`SameSite=${options.sameSite.charAt(0).toUpperCase() + options.sameSite.slice(1)}`);
185
+ }
186
+
187
+ if (options.partitioned) {
188
+ parts.push("Partitioned");
189
+ }
190
+
191
+ return parts.join("; ");
192
+ }
193
+
194
+ /**
195
+ * Response에 Set-Cookie 헤더들 적용
196
+ */
197
+ applyToResponse(response: Response): Response {
198
+ const setCookieHeaders = this.getSetCookieHeaders();
199
+
200
+ if (setCookieHeaders.length === 0) {
201
+ return response;
202
+ }
203
+
204
+ // Headers를 복사하여 수정
205
+ const newHeaders = new Headers(response.headers);
206
+
207
+ for (const setCookie of setCookieHeaders) {
208
+ newHeaders.append("Set-Cookie", setCookie);
209
+ }
210
+
211
+ return new Response(response.body, {
212
+ status: response.status,
213
+ statusText: response.statusText,
214
+ headers: newHeaders,
215
+ });
216
+ }
217
+
218
+ /**
219
+ * 응답에 적용할 쿠키가 있는지 확인
220
+ */
221
+ hasPendingCookies(): boolean {
222
+ return this.responseCookies.size > 0;
223
+ }
224
+ }
225
+
226
+ // ========== ManduContext ==========
227
+
228
+ export class ManduContext {
229
+ private store: Map<string, unknown> = new Map();
230
+ private _params: Record<string, string>;
231
+ private _query: Record<string, string>;
232
+ private _cookies: CookieManager;
233
+ private _deps: FillingDeps;
234
+
235
+ constructor(
236
+ public readonly request: Request,
237
+ params: Record<string, string> = {},
238
+ deps?: FillingDeps
239
+ ) {
240
+ this._params = params;
241
+ this._query = this.parseQuery();
242
+ this._cookies = new CookieManager(request);
243
+ this._deps = deps ?? globalDeps.get();
244
+ }
245
+
246
+ /**
247
+ * DNA-002: 의존성 접근
248
+ *
249
+ * @example
250
+ * ```ts
251
+ * // 데이터베이스 쿼리
252
+ * const users = await ctx.deps.db?.query("SELECT * FROM users");
253
+ *
254
+ * // 캐시 사용
255
+ * const cached = await ctx.deps.cache?.get("user:123");
256
+ *
257
+ * // 로깅
258
+ * ctx.deps.logger?.info("User logged in", { userId });
259
+ *
260
+ * // 현재 시간 (테스트에서 목킹 가능)
261
+ * const now = ctx.deps.now?.() ?? new Date();
262
+ * ```
263
+ */
264
+ get deps(): FillingDeps {
265
+ return this._deps;
266
+ }
267
+
268
+ private parseQuery(): Record<string, string> {
269
+ const url = new URL(this.request.url);
270
+ const query: Record<string, string> = {};
271
+ url.searchParams.forEach((value, key) => {
272
+ query[key] = value;
273
+ });
274
+ return query;
275
+ }
276
+
277
+ // ============================================
278
+ // 🥟 Request 읽기
279
+ // ============================================
280
+
281
+ /** Path parameters (e.g., /users/:id → { id: '123' }) */
282
+ get params(): Record<string, string> {
283
+ return this._params;
284
+ }
285
+
286
+ /** Query parameters (e.g., ?name=mandu → { name: 'mandu' }) */
287
+ get query(): Record<string, string> {
288
+ return this._query;
289
+ }
290
+
291
+ /** Request headers */
292
+ get headers(): Headers {
293
+ return this.request.headers;
294
+ }
295
+
296
+ /** HTTP method */
297
+ get method(): string {
298
+ return this.request.method;
299
+ }
300
+
301
+ /** Request URL */
302
+ get url(): string {
303
+ return this.request.url;
304
+ }
305
+
306
+ /** Shorthand for request */
307
+ get req(): Request {
308
+ return this.request;
309
+ }
310
+
311
+ /**
312
+ * Cookie Manager
313
+ * @example
314
+ * // 쿠키 읽기
315
+ * const session = ctx.cookies.get('session');
316
+ *
317
+ * // 쿠키 설정
318
+ * ctx.cookies.set('session', 'abc123', { httpOnly: true, maxAge: 3600 });
319
+ *
320
+ * // 쿠키 삭제
321
+ * ctx.cookies.delete('session');
322
+ */
323
+ get cookies(): CookieManager {
324
+ return this._cookies;
325
+ }
326
+
327
+ /**
328
+ * Parse request body with optional Zod validation
329
+ * @example
330
+ * const data = await ctx.body() // any
331
+ * const data = await ctx.body(UserSchema) // typed & validated
332
+ */
333
+ async body<T = unknown>(schema?: ZodSchema<T>): Promise<T> {
334
+ const contentType = this.request.headers.get("content-type") || "";
335
+ let data: unknown;
336
+
337
+ if (contentType.includes("application/json")) {
338
+ data = await this.request.json();
339
+ } else if (contentType.includes("application/x-www-form-urlencoded")) {
340
+ const formData = await this.request.formData();
341
+ data = Object.fromEntries(formData.entries());
342
+ } else if (contentType.includes("multipart/form-data")) {
343
+ const formData = await this.request.formData();
344
+ data = Object.fromEntries(formData.entries());
345
+ } else {
346
+ data = await this.request.text();
347
+ }
348
+
349
+ if (schema) {
350
+ const result = schema.safeParse(data);
351
+ if (!result.success) {
352
+ throw new ValidationError(result.error.errors);
353
+ }
354
+ return result.data;
355
+ }
356
+
357
+ return data as T;
358
+ }
359
+
360
+ /**
361
+ * Parse and validate request input via Contract
362
+ * @example
363
+ * const input = await ctx.input(userContract, "POST", { id: "123" })
364
+ */
365
+ async input<
366
+ TContract extends ContractSchema,
367
+ TMethod extends ContractMethod,
368
+ >(
369
+ contract: TContract,
370
+ method: TMethod,
371
+ pathParams: Record<string, string> = {},
372
+ options: ContractValidatorOptions = {}
373
+ ): Promise<ContractInput<TContract, TMethod>> {
374
+ const validator = new ContractValidator(contract, options);
375
+ const result = await validator.validateAndNormalizeRequest(
376
+ this.request,
377
+ method,
378
+ pathParams
379
+ );
380
+
381
+ if (!result.success) {
382
+ throw new ValidationError(result.errors ?? []);
383
+ }
384
+
385
+ return (result.data ?? {}) as ContractInput<TContract, TMethod>;
386
+ }
387
+
388
+ // ============================================
389
+ // 🥟 Response 보내기
390
+ // ============================================
391
+
392
+ /**
393
+ * Response에 쿠키 헤더 적용 (내부 사용)
394
+ */
395
+ private withCookies(response: Response): Response {
396
+ if (this._cookies.hasPendingCookies()) {
397
+ return this._cookies.applyToResponse(response);
398
+ }
399
+ return response;
400
+ }
401
+
402
+ /** 200 OK */
403
+ ok<T>(data: T): Response {
404
+ return this.json(data, 200);
405
+ }
406
+
407
+ /** 201 Created */
408
+ created<T>(data: T): Response {
409
+ return this.json(data, 201);
410
+ }
411
+
412
+ /** 204 No Content */
413
+ noContent(): Response {
414
+ return this.withCookies(new Response(null, { status: 204 }));
415
+ }
416
+
417
+ /** 400 Bad Request */
418
+ error(message: string, details?: unknown): Response {
419
+ return this.json({ status: "error", message, details }, 400);
420
+ }
421
+
422
+ /** 401 Unauthorized */
423
+ unauthorized(message: string = "Unauthorized"): Response {
424
+ return this.json({ status: "error", message }, 401);
425
+ }
426
+
427
+ /** 403 Forbidden */
428
+ forbidden(message: string = "Forbidden"): Response {
429
+ return this.json({ status: "error", message }, 403);
430
+ }
431
+
432
+ /** 404 Not Found */
433
+ notFound(message: string = "Not Found"): Response {
434
+ return this.json({ status: "error", message }, 404);
435
+ }
436
+
437
+ /** 500 Internal Server Error */
438
+ fail(message: string = "Internal Server Error"): Response {
439
+ return this.json({ status: "error", message }, 500);
440
+ }
441
+
442
+ /** Custom JSON response */
443
+ json<T>(data: T, status: number = 200): Response {
444
+ const response = Response.json(data, { status });
445
+ return this.withCookies(response);
446
+ }
447
+
448
+ /**
449
+ * Validate and send response via Contract
450
+ * @example
451
+ * return ctx.output(userContract, 200, { data: users })
452
+ */
453
+ output<
454
+ TContract extends ContractSchema,
455
+ TStatus extends keyof TContract["response"],
456
+ >(
457
+ contract: TContract,
458
+ status: TStatus,
459
+ data: InferResponse<TContract, TStatus>,
460
+ options: ContractValidatorOptions = {}
461
+ ): Response {
462
+ const validator = new ContractValidator(contract, options);
463
+ const result = validator.validateResponse(data, Number(status));
464
+
465
+ if (!result.success) {
466
+ if (options.mode === "strict") {
467
+ const errorResponse = Response.json(
468
+ {
469
+ errorType: "CONTRACT_VIOLATION",
470
+ code: "MANDU_C001",
471
+ message: "Response does not match contract schema",
472
+ summary: "응답이 Contract 스키마와 일치하지 않습니다",
473
+ statusCode: Number(status),
474
+ violations: result.errors,
475
+ timestamp: new Date().toISOString(),
476
+ },
477
+ { status: 500 }
478
+ );
479
+ return this.withCookies(errorResponse);
480
+ }
481
+
482
+ console.warn(
483
+ "\x1b[33m[Mandu] Contract violation in response:\x1b[0m",
484
+ result.errors
485
+ );
486
+ }
487
+
488
+ const payload = result.success ? result.data : data;
489
+ return this.json(payload as InferResponse<TContract, TStatus>, Number(status));
490
+ }
491
+
492
+ /** 200 OK with Contract validation */
493
+ okContract<TContract extends ContractSchema>(
494
+ contract: TContract,
495
+ data: InferResponse<TContract, 200>,
496
+ options: ContractValidatorOptions = {}
497
+ ): Response {
498
+ return this.output(contract, 200 as keyof TContract["response"], data, options);
499
+ }
500
+
501
+ /** 201 Created with Contract validation */
502
+ createdContract<TContract extends ContractSchema>(
503
+ contract: TContract,
504
+ data: InferResponse<TContract, 201>,
505
+ options: ContractValidatorOptions = {}
506
+ ): Response {
507
+ return this.output(contract, 201 as keyof TContract["response"], data, options);
508
+ }
509
+
510
+ /** Custom text response */
511
+ text(data: string, status: number = 200): Response {
512
+ const response = new Response(data, {
513
+ status,
514
+ headers: { "Content-Type": "text/plain" },
515
+ });
516
+ return this.withCookies(response);
517
+ }
518
+
519
+ /** Custom HTML response */
520
+ html(data: string, status: number = 200): Response {
521
+ const response = new Response(data, {
522
+ status,
523
+ headers: { "Content-Type": "text/html" },
524
+ });
525
+ return this.withCookies(response);
526
+ }
527
+
528
+ /** Redirect response */
529
+ redirect(url: string, status: 301 | 302 | 307 | 308 = 302): Response {
530
+ const response = Response.redirect(url, status);
531
+ return this.withCookies(response);
532
+ }
533
+
534
+ // ============================================
535
+ // 🥟 상태 저장 (Lifecycle → Handler 전달)
536
+ // ============================================
537
+
538
+ /** Store value for later use */
539
+ set<T>(key: string, value: T): void {
540
+ this.store.set(key, value);
541
+ }
542
+
543
+ /** Get stored value */
544
+ get<T>(key: string): T | undefined {
545
+ return this.store.get(key) as T | undefined;
546
+ }
547
+
548
+ /** Check if key exists */
549
+ has(key: string): boolean {
550
+ return this.store.has(key);
551
+ }
552
+ }
553
+
554
+ /** Route context for error reporting */
555
+ export interface ValidationRouteContext {
556
+ routeId: string;
557
+ pattern: string;
558
+ }
559
+
560
+ /** Validation error with details */
561
+ export class ValidationError extends Error {
562
+ constructor(
563
+ public readonly errors: unknown[],
564
+ public readonly routeContext?: ValidationRouteContext
565
+ ) {
566
+ super("Validation failed");
567
+ this.name = "ValidationError";
568
+ }
569
+ }