@mandujs/core 0.42.0 → 0.43.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 (87) hide show
  1. package/package.json +21 -4
  2. package/src/auth/__tests__/login.test.ts +420 -419
  3. package/src/auth/__tests__/reset.test.ts +296 -296
  4. package/src/brain/adapters/anthropic-oauth.ts +421 -420
  5. package/src/brain/adapters/index.ts +2 -1
  6. package/src/brain/adapters/ollama.ts +1 -1
  7. package/src/brain/adapters/openai-oauth.ts +534 -533
  8. package/src/brain/brain.ts +2 -1
  9. package/src/brain/redactor.ts +196 -196
  10. package/src/bundler/__tests__/cli-bench-utils.test.ts +149 -149
  11. package/src/bundler/__tests__/cold-start.test.ts +504 -504
  12. package/src/bundler/__tests__/fast-refresh.test.ts +607 -606
  13. package/src/bundler/__tests__/hdr.test.ts +1 -1
  14. package/src/bundler/analyzer.ts +958 -958
  15. package/src/bundler/build.ts +104 -14
  16. package/src/bundler/dev.ts +125 -0
  17. package/src/bundler/hmr-types.ts +1 -0
  18. package/src/bundler/plugins/__tests__/react-compiler-lint.test.ts +110 -0
  19. package/src/bundler/plugins/index.ts +14 -0
  20. package/src/bundler/plugins/react-compiler-lint.ts +253 -0
  21. package/src/bundler/plugins/react-compiler.ts +162 -0
  22. package/src/bundler/types.ts +12 -0
  23. package/src/change/integrity.ts +2 -1
  24. package/src/client/index.ts +10 -0
  25. package/src/client/island.ts +38 -11
  26. package/src/client/router.ts +6 -1
  27. package/src/config/mandu.ts +57 -0
  28. package/src/config/validate.ts +42 -0
  29. package/src/content/collection.ts +844 -809
  30. package/src/content/content-layer.ts +316 -314
  31. package/src/content/content.test.ts +433 -433
  32. package/src/content/digest.ts +133 -133
  33. package/src/content/generate-types.ts +168 -168
  34. package/src/content/index.ts +6 -1
  35. package/src/content/llms-txt.ts +277 -277
  36. package/src/contract/define.ts +474 -474
  37. package/src/contract/route-helpers.ts +2 -1
  38. package/src/contract/zod-utils.ts +158 -155
  39. package/src/db/index.ts +513 -513
  40. package/src/desktop/__tests__/smoke.test.ts +100 -100
  41. package/src/desktop/webview-fallback.ts +583 -583
  42. package/src/desktop/window.ts +3 -1
  43. package/src/dev-error-overlay/overlay-client.ts +300 -300
  44. package/src/devtools/ai/mcp-connector.ts +499 -498
  45. package/src/devtools/client/components/kitchen-root.tsx +7 -2
  46. package/src/email/resend.ts +163 -163
  47. package/src/guard/__tests__/tsgolint-bridge.test.ts +347 -0
  48. package/src/guard/ast-analyzer.ts +806 -806
  49. package/src/guard/graph.ts +898 -898
  50. package/src/guard/index.ts +16 -0
  51. package/src/guard/statistics.ts +578 -578
  52. package/src/guard/tsgolint-bridge.ts +512 -0
  53. package/src/i18n/locale-resolver.ts +214 -214
  54. package/src/id/__tests__/id.test.ts +120 -120
  55. package/src/intent/index.ts +321 -321
  56. package/src/island/index.ts +39 -23
  57. package/src/kitchen/api/contract-api.ts +15 -8
  58. package/src/kitchen/kitchen-ui.ts +2137 -2137
  59. package/src/lockfile/index.ts +3 -2
  60. package/src/middleware/oauth/__tests__/oauth.test.ts +575 -574
  61. package/src/middleware/rate-limit/__tests__/rate-limit.test.ts +642 -642
  62. package/src/middleware/secure/index.ts +417 -417
  63. package/src/observability/metrics.ts +334 -334
  64. package/src/observability/tracing.ts +694 -694
  65. package/src/openapi/generator.ts +1 -1
  66. package/src/perf/user-marks.ts +553 -553
  67. package/src/plugins/registry.ts +387 -387
  68. package/src/resource/ddl/diff.ts +392 -392
  69. package/src/resource/ddl/snapshot.ts +448 -447
  70. package/src/resource/generator-schema.ts +477 -476
  71. package/src/resource/parser.ts +4 -2
  72. package/src/resource/schema.ts +1 -1
  73. package/src/router/fs-patterns.ts +422 -422
  74. package/src/runtime/fast-refresh-types.ts +126 -128
  75. package/src/runtime/image-handler.ts +206 -195
  76. package/src/runtime/router.test.ts +476 -476
  77. package/src/runtime/security.ts +155 -155
  78. package/src/runtime/server.ts +36 -19
  79. package/src/runtime/session-key.ts +328 -328
  80. package/src/scheduler/__tests__/scheduler.test.ts +514 -514
  81. package/src/seo/resolve/index.ts +353 -353
  82. package/src/spec/load.ts +1 -1
  83. package/src/testing/reporter.ts +676 -676
  84. package/src/testing/server.ts +196 -196
  85. package/src/testing/snapshot.ts +444 -444
  86. package/src/utils/__tests__/lru-cache.test.ts +186 -186
  87. package/src/utils/bun.ts +8 -8
@@ -1,474 +1,474 @@
1
- /**
2
- * Mandu Contract Definition - Contract-First 개발
3
- *
4
- * @example
5
- * ```ts
6
- * import { defineContract } from '@mandujs/core';
7
- *
8
- * export const userContract = defineContract({
9
- * getUser: {
10
- * method: 'GET',
11
- * path: '/api/users/:id',
12
- * input: z.object({ id: z.string() }),
13
- * output: z.object({ name: z.string(), email: z.string() }),
14
- * },
15
- * createUser: {
16
- * method: 'POST',
17
- * path: '/api/users',
18
- * input: z.object({ name: z.string(), email: z.string() }),
19
- * output: z.object({ id: z.string() }),
20
- * },
21
- * });
22
- *
23
- * // 자동 생성됨:
24
- * // - API 핸들러 타입
25
- * // - 클라이언트 훅
26
- * // - OpenAPI 스펙
27
- * ```
28
- */
29
-
30
- import { z, type ZodType, type ZodObject, type ZodRawShape } from 'zod';
31
- import {
32
- getZodTypeName,
33
- getZodInnerType,
34
- getZodArrayElementType,
35
- getZodObjectShape,
36
- getZodEnumValues,
37
- getZodChecks,
38
- isZodRequired,
39
- } from './zod-utils';
40
-
41
- // ============================================================================
42
- // Types
43
- // ============================================================================
44
-
45
- export type ContractMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
46
-
47
- export interface EndpointDefinition<
48
- TInput extends ZodType = ZodType,
49
- TOutput extends ZodType = ZodType,
50
- TParams extends ZodType = ZodType,
51
- > {
52
- /** HTTP 메서드 */
53
- method: ContractMethod;
54
- /** API 경로 */
55
- path: string;
56
- /** URL 파라미터 스키마 */
57
- params?: TParams;
58
- /** 요청 바디/쿼리 스키마 */
59
- input?: TInput;
60
- /** 응답 스키마 */
61
- output: TOutput;
62
- /** 가능한 에러 코드 */
63
- errors?: readonly string[];
64
- /** 설명 */
65
- description?: string;
66
- /** 태그 (OpenAPI grouping) */
67
- tags?: string[];
68
- }
69
-
70
- export type ContractDefinition = Record<string, EndpointDefinition>;
71
-
72
- // ============================================================================
73
- // Contract Metadata
74
- // ============================================================================
75
-
76
- export interface ContractMeta<T extends ContractDefinition> {
77
- __contract: true;
78
- __name: string;
79
- __endpoints: T;
80
- __version: string;
81
- }
82
-
83
- export type Contract<T extends ContractDefinition> = T & ContractMeta<T>;
84
-
85
- // ============================================================================
86
- // defineContract() - Contract 정의
87
- // ============================================================================
88
-
89
- let contractCounter = 0;
90
-
91
- /**
92
- * Contract 정의
93
- *
94
- * Contract는 API의 명세(specification)입니다.
95
- * - 타입 안전한 API 호출
96
- * - 자동 코드 생성의 기반
97
- * - OpenAPI 문서 자동 생성
98
- */
99
- export function defineContract<T extends ContractDefinition>(
100
- endpoints: T,
101
- options?: {
102
- name?: string;
103
- version?: string;
104
- }
105
- ): Contract<T> {
106
- const name = options?.name || `contract_${++contractCounter}`;
107
- const version = options?.version || '1.0.0';
108
-
109
- const contract = endpoints as Contract<T>;
110
- contract.__contract = true;
111
- contract.__name = name;
112
- contract.__endpoints = endpoints;
113
- contract.__version = version;
114
-
115
- return contract;
116
- }
117
-
118
- // ============================================================================
119
- // isContract() - Contract 체크
120
- // ============================================================================
121
-
122
- export function isContract<T extends ContractDefinition>(
123
- value: unknown
124
- ): value is Contract<T> {
125
- return (
126
- typeof value === 'object' &&
127
- value !== null &&
128
- (value as ContractMeta<ContractDefinition>).__contract === true
129
- );
130
- }
131
-
132
- // ============================================================================
133
- // Type Inference Utilities
134
- // ============================================================================
135
-
136
- /** Contract에서 Input 타입 추출 */
137
- export type ContractInput<
138
- C extends ContractMeta<ContractDefinition>,
139
- K extends keyof C['__endpoints']
140
- > = C['__endpoints'][K]['input'] extends ZodType<infer T> ? T : never;
141
-
142
- /** Contract에서 Output 타입 추출 */
143
- export type ContractOutput<
144
- C extends ContractMeta<ContractDefinition>,
145
- K extends keyof C['__endpoints']
146
- > = C['__endpoints'][K]['output'] extends ZodType<infer T> ? T : never;
147
-
148
- /** Contract에서 Params 타입 추출 */
149
- export type ContractParams<
150
- C extends ContractMeta<ContractDefinition>,
151
- K extends keyof C['__endpoints']
152
- > = C['__endpoints'][K]['params'] extends ZodType<infer T> ? T : never;
153
-
154
- // ============================================================================
155
- // Code Generation Templates
156
- // ============================================================================
157
-
158
- /**
159
- * Contract에서 API 핸들러 코드 생성
160
- */
161
- export function generateApiHandler<T extends ContractDefinition>(
162
- contract: Contract<T>,
163
- endpointName: keyof T
164
- ): string {
165
- const endpoint = contract.__endpoints[endpointName as string];
166
- if (!endpoint) {
167
- throw new Error(`Endpoint "${String(endpointName)}" not found in contract`);
168
- }
169
-
170
- const { method, path, input, output, description } = endpoint;
171
-
172
- return `
173
- import { Mandu } from '@mandujs/core';
174
- import { z } from 'zod';
175
-
176
- /**
177
- * ${description || endpointName as string}
178
- * ${method} ${path}
179
- */
180
- export default Mandu.filling()
181
- ${input ? `.onParse(async (ctx) => {
182
- // Input validation is automatic via ctx.body()
183
- })` : ''}
184
- .${method.toLowerCase()}(async (ctx) => {
185
- ${input ? `const body = await ctx.body(/* your input schema */);
186
- if (!body.success) {
187
- return ctx.error('Validation failed', body.error);
188
- }
189
- const data = body.data;` : ''}
190
-
191
- // TODO: Implement your logic here
192
-
193
- return ctx.ok({
194
- // TODO: Return your response
195
- });
196
- });
197
- `.trim();
198
- }
199
-
200
- /**
201
- * Contract에서 React Query 훅 생성
202
- */
203
- export function generateClientHook<T extends ContractDefinition>(
204
- contract: Contract<T>,
205
- endpointName: keyof T
206
- ): string {
207
- const endpoint = contract.__endpoints[endpointName as string];
208
- if (!endpoint) {
209
- throw new Error(`Endpoint "${String(endpointName)}" not found in contract`);
210
- }
211
-
212
- const { method, path, description } = endpoint;
213
- const hookName = `use${String(endpointName).charAt(0).toUpperCase() + String(endpointName).slice(1)}`;
214
- const isQuery = method === 'GET';
215
-
216
- if (isQuery) {
217
- return `
218
- import { useQuery, type UseQueryOptions } from '@tanstack/react-query';
219
- import type { ContractInput, ContractOutput } from '@mandujs/core';
220
- import { contract } from '../contracts';
221
-
222
- type Input = ContractInput<typeof contract, '${String(endpointName)}'>;
223
- type Output = ContractOutput<typeof contract, '${String(endpointName)}'>;
224
-
225
- /**
226
- * ${description || endpointName as string}
227
- */
228
- export function ${hookName}(
229
- params: Input,
230
- options?: Omit<UseQueryOptions<Output>, 'queryKey' | 'queryFn'>
231
- ) {
232
- return useQuery({
233
- queryKey: ['${String(endpointName)}', params],
234
- queryFn: async () => {
235
- const res = await fetch(\`${path.replace(/:(\w+)/g, '${params.$1}')}\`);
236
- if (!res.ok) throw new Error('API Error');
237
- return res.json() as Promise<Output>;
238
- },
239
- ...options,
240
- });
241
- }
242
- `.trim();
243
- } else {
244
- return `
245
- import { useMutation, type UseMutationOptions } from '@tanstack/react-query';
246
- import type { ContractInput, ContractOutput } from '@mandujs/core';
247
- import { contract } from '../contracts';
248
-
249
- type Input = ContractInput<typeof contract, '${String(endpointName)}'>;
250
- type Output = ContractOutput<typeof contract, '${String(endpointName)}'>;
251
-
252
- /**
253
- * ${description || endpointName as string}
254
- */
255
- export function ${hookName}(
256
- options?: Omit<UseMutationOptions<Output, Error, Input>, 'mutationFn'>
257
- ) {
258
- return useMutation({
259
- mutationFn: async (input: Input) => {
260
- const res = await fetch('${path}', {
261
- method: '${method}',
262
- headers: { 'Content-Type': 'application/json' },
263
- body: JSON.stringify(input),
264
- });
265
- if (!res.ok) throw new Error('API Error');
266
- return res.json() as Promise<Output>;
267
- },
268
- ...options,
269
- });
270
- }
271
- `.trim();
272
- }
273
- }
274
-
275
- /**
276
- * Contract에서 전체 코드 생성
277
- */
278
- export function generateAllFromContract<T extends ContractDefinition>(
279
- contract: Contract<T>
280
- ): {
281
- handlers: Record<string, string>;
282
- hooks: Record<string, string>;
283
- types: string;
284
- } {
285
- const handlers: Record<string, string> = {};
286
- const hooks: Record<string, string> = {};
287
-
288
- for (const name of Object.keys(contract.__endpoints)) {
289
- handlers[name] = generateApiHandler(contract, name);
290
- hooks[name] = generateClientHook(contract, name);
291
- }
292
-
293
- const types = generateTypeDefinitions(contract);
294
-
295
- return { handlers, hooks, types };
296
- }
297
-
298
- /**
299
- * Contract에서 타입 정의 생성
300
- */
301
- export function generateTypeDefinitions<T extends ContractDefinition>(
302
- contract: Contract<T>
303
- ): string {
304
- const lines: string[] = [
305
- `// Auto-generated types for ${contract.__name}`,
306
- `// Version: ${contract.__version}`,
307
- '',
308
- 'import { z } from "zod";',
309
- '',
310
- ];
311
-
312
- for (const [name, endpoint] of Object.entries(contract.__endpoints)) {
313
- const typeName = name.charAt(0).toUpperCase() + name.slice(1);
314
-
315
- if (endpoint.input) {
316
- lines.push(`export type ${typeName}Input = z.infer<typeof ${name}InputSchema>;`);
317
- }
318
- if (endpoint.output) {
319
- lines.push(`export type ${typeName}Output = z.infer<typeof ${name}OutputSchema>;`);
320
- }
321
- if (endpoint.params) {
322
- lines.push(`export type ${typeName}Params = z.infer<typeof ${name}ParamsSchema>;`);
323
- }
324
- lines.push('');
325
- }
326
-
327
- return lines.join('\n');
328
- }
329
-
330
- // ============================================================================
331
- // OpenAPI Generation
332
- // ============================================================================
333
-
334
- /**
335
- * Contract에서 OpenAPI 스펙 생성
336
- */
337
- export function generateOpenAPISpec<T extends ContractDefinition>(
338
- contract: Contract<T>,
339
- options?: {
340
- title?: string;
341
- version?: string;
342
- servers?: Array<{ url: string; description?: string }>;
343
- }
344
- ): Record<string, unknown> {
345
- const paths: Record<string, Record<string, unknown>> = {};
346
-
347
- for (const [name, endpoint] of Object.entries(contract.__endpoints)) {
348
- const { method, path, input, output, description, tags, errors } = endpoint;
349
-
350
- if (!paths[path]) {
351
- paths[path] = {};
352
- }
353
-
354
- paths[path][method.toLowerCase()] = {
355
- operationId: name,
356
- summary: description || name,
357
- tags: tags || [],
358
- ...(input && ['POST', 'PUT', 'PATCH'].includes(method)
359
- ? {
360
- requestBody: {
361
- required: true,
362
- content: {
363
- 'application/json': {
364
- schema: { $ref: `#/components/schemas/${name}Input` },
365
- },
366
- },
367
- },
368
- }
369
- : {}),
370
- responses: {
371
- '200': {
372
- description: 'Success',
373
- content: {
374
- 'application/json': {
375
- schema: { $ref: `#/components/schemas/${name}Output` },
376
- },
377
- },
378
- },
379
- ...(errors?.reduce(
380
- (acc, error) => ({
381
- ...acc,
382
- [getStatusCode(error)]: {
383
- description: error,
384
- },
385
- }),
386
- {}
387
- ) || {}),
388
- },
389
- };
390
- }
391
-
392
- return {
393
- openapi: '3.0.3',
394
- info: {
395
- title: options?.title || contract.__name,
396
- version: options?.version || contract.__version,
397
- },
398
- servers: options?.servers || [{ url: '/' }],
399
- paths,
400
- components: {
401
- schemas: generateSchemas(contract),
402
- },
403
- };
404
- }
405
-
406
- function generateSchemas<T extends ContractDefinition>(
407
- contract: Contract<T>
408
- ): Record<string, unknown> {
409
- const schemas: Record<string, unknown> = {};
410
-
411
- for (const [name, endpoint] of Object.entries(contract.__endpoints)) {
412
- if (endpoint.input) {
413
- schemas[`${name}Input`] = zodToOpenAPI(endpoint.input);
414
- }
415
- if (endpoint.output) {
416
- schemas[`${name}Output`] = zodToOpenAPI(endpoint.output);
417
- }
418
- }
419
-
420
- return schemas;
421
- }
422
-
423
- function zodToOpenAPI(schema: ZodType): Record<string, unknown> {
424
- const typeName = getZodTypeName(schema);
425
-
426
- switch (typeName) {
427
- case 'ZodString':
428
- return { type: 'string' };
429
- case 'ZodNumber':
430
- return { type: 'number' };
431
- case 'ZodBoolean':
432
- return { type: 'boolean' };
433
- case 'ZodArray': {
434
- const elementType = getZodArrayElementType(schema);
435
- return { type: 'array', items: elementType ? zodToOpenAPI(elementType) : {} };
436
- }
437
- case 'ZodObject': {
438
- const properties: Record<string, unknown> = {};
439
- const required: string[] = [];
440
- const shape = getZodObjectShape(schema) ?? {};
441
- for (const [key, value] of Object.entries(shape)) {
442
- properties[key] = zodToOpenAPI(value);
443
- if (isZodRequired(value)) {
444
- required.push(key);
445
- }
446
- }
447
- return { type: 'object', properties, required };
448
- }
449
- case 'ZodOptional': {
450
- const inner = getZodInnerType(schema);
451
- return inner ? zodToOpenAPI(inner) : {};
452
- }
453
- case 'ZodNullable': {
454
- const inner = getZodInnerType(schema);
455
- return { ...(inner ? zodToOpenAPI(inner) : {}), nullable: true };
456
- }
457
- case 'ZodEnum':
458
- return { type: 'string', enum: getZodEnumValues(schema) };
459
- default:
460
- return { type: 'object' };
461
- }
462
- }
463
-
464
- function getStatusCode(error: string): string {
465
- const map: Record<string, string> = {
466
- NOT_FOUND: '404',
467
- UNAUTHORIZED: '401',
468
- FORBIDDEN: '403',
469
- RATE_LIMITED: '429',
470
- BAD_REQUEST: '400',
471
- INTERNAL_ERROR: '500',
472
- };
473
- return map[error] || '400';
474
- }
1
+ /**
2
+ * Mandu Contract Definition - Contract-First 개발
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * import { defineContract } from '@mandujs/core';
7
+ *
8
+ * export const userContract = defineContract({
9
+ * getUser: {
10
+ * method: 'GET',
11
+ * path: '/api/users/:id',
12
+ * input: z.object({ id: z.string() }),
13
+ * output: z.object({ name: z.string(), email: z.string() }),
14
+ * },
15
+ * createUser: {
16
+ * method: 'POST',
17
+ * path: '/api/users',
18
+ * input: z.object({ name: z.string(), email: z.string() }),
19
+ * output: z.object({ id: z.string() }),
20
+ * },
21
+ * });
22
+ *
23
+ * // 자동 생성됨:
24
+ * // - API 핸들러 타입
25
+ * // - 클라이언트 훅
26
+ * // - OpenAPI 스펙
27
+ * ```
28
+ */
29
+
30
+ import { z, type ZodType, type ZodObject, type ZodRawShape } from 'zod';
31
+ import {
32
+ getZodTypeName,
33
+ getZodInnerType,
34
+ getZodArrayElementType,
35
+ getZodObjectShape,
36
+ getZodEnumValues,
37
+ getZodChecks,
38
+ isZodRequired,
39
+ } from './zod-utils';
40
+
41
+ // ============================================================================
42
+ // Types
43
+ // ============================================================================
44
+
45
+ export type ContractMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
46
+
47
+ export interface EndpointDefinition<
48
+ TInput extends ZodType = ZodType,
49
+ TOutput extends ZodType = ZodType,
50
+ TParams extends ZodType = ZodType,
51
+ > {
52
+ /** HTTP 메서드 */
53
+ method: ContractMethod;
54
+ /** API 경로 */
55
+ path: string;
56
+ /** URL 파라미터 스키마 */
57
+ params?: TParams;
58
+ /** 요청 바디/쿼리 스키마 */
59
+ input?: TInput;
60
+ /** 응답 스키마 */
61
+ output: TOutput;
62
+ /** 가능한 에러 코드 */
63
+ errors?: readonly string[];
64
+ /** 설명 */
65
+ description?: string;
66
+ /** 태그 (OpenAPI grouping) */
67
+ tags?: string[];
68
+ }
69
+
70
+ export type ContractDefinition = Record<string, EndpointDefinition>;
71
+
72
+ // ============================================================================
73
+ // Contract Metadata
74
+ // ============================================================================
75
+
76
+ export interface ContractMeta<T extends ContractDefinition> {
77
+ __contract: true;
78
+ __name: string;
79
+ __endpoints: T;
80
+ __version: string;
81
+ }
82
+
83
+ export type Contract<T extends ContractDefinition> = T & ContractMeta<T>;
84
+
85
+ // ============================================================================
86
+ // defineContract() - Contract 정의
87
+ // ============================================================================
88
+
89
+ let contractCounter = 0;
90
+
91
+ /**
92
+ * Contract 정의
93
+ *
94
+ * Contract는 API의 명세(specification)입니다.
95
+ * - 타입 안전한 API 호출
96
+ * - 자동 코드 생성의 기반
97
+ * - OpenAPI 문서 자동 생성
98
+ */
99
+ export function defineContract<T extends ContractDefinition>(
100
+ endpoints: T,
101
+ options?: {
102
+ name?: string;
103
+ version?: string;
104
+ }
105
+ ): Contract<T> {
106
+ const name = options?.name || `contract_${++contractCounter}`;
107
+ const version = options?.version || '1.0.0';
108
+
109
+ const contract = endpoints as Contract<T>;
110
+ contract.__contract = true;
111
+ contract.__name = name;
112
+ contract.__endpoints = endpoints;
113
+ contract.__version = version;
114
+
115
+ return contract;
116
+ }
117
+
118
+ // ============================================================================
119
+ // isContract() - Contract 체크
120
+ // ============================================================================
121
+
122
+ export function isContract<T extends ContractDefinition>(
123
+ value: unknown
124
+ ): value is Contract<T> {
125
+ return (
126
+ typeof value === 'object' &&
127
+ value !== null &&
128
+ (value as ContractMeta<ContractDefinition>).__contract === true
129
+ );
130
+ }
131
+
132
+ // ============================================================================
133
+ // Type Inference Utilities
134
+ // ============================================================================
135
+
136
+ /** Contract에서 Input 타입 추출 */
137
+ export type ContractInput<
138
+ C extends ContractMeta<ContractDefinition>,
139
+ K extends keyof C['__endpoints']
140
+ > = C['__endpoints'][K]['input'] extends ZodType<infer T> ? T : never;
141
+
142
+ /** Contract에서 Output 타입 추출 */
143
+ export type ContractOutput<
144
+ C extends ContractMeta<ContractDefinition>,
145
+ K extends keyof C['__endpoints']
146
+ > = C['__endpoints'][K]['output'] extends ZodType<infer T> ? T : never;
147
+
148
+ /** Contract에서 Params 타입 추출 */
149
+ export type ContractParams<
150
+ C extends ContractMeta<ContractDefinition>,
151
+ K extends keyof C['__endpoints']
152
+ > = C['__endpoints'][K]['params'] extends ZodType<infer T> ? T : never;
153
+
154
+ // ============================================================================
155
+ // Code Generation Templates
156
+ // ============================================================================
157
+
158
+ /**
159
+ * Contract에서 API 핸들러 코드 생성
160
+ */
161
+ export function generateApiHandler<T extends ContractDefinition>(
162
+ contract: Contract<T>,
163
+ endpointName: keyof T
164
+ ): string {
165
+ const endpoint = contract.__endpoints[endpointName as string];
166
+ if (!endpoint) {
167
+ throw new Error(`Endpoint "${String(endpointName)}" not found in contract`);
168
+ }
169
+
170
+ const { method, path, input, output, description } = endpoint;
171
+
172
+ return `
173
+ import { Mandu } from '@mandujs/core';
174
+ import { z } from 'zod';
175
+
176
+ /**
177
+ * ${description || endpointName as string}
178
+ * ${method} ${path}
179
+ */
180
+ export default Mandu.filling()
181
+ ${input ? `.onParse(async (ctx) => {
182
+ // Input validation is automatic via ctx.body()
183
+ })` : ''}
184
+ .${method.toLowerCase()}(async (ctx) => {
185
+ ${input ? `const body = await ctx.body(/* your input schema */);
186
+ if (!body.success) {
187
+ return ctx.error('Validation failed', body.error);
188
+ }
189
+ const data = body.data;` : ''}
190
+
191
+ // TODO: Implement your logic here
192
+
193
+ return ctx.ok({
194
+ // TODO: Return your response
195
+ });
196
+ });
197
+ `.trim();
198
+ }
199
+
200
+ /**
201
+ * Contract에서 React Query 훅 생성
202
+ */
203
+ export function generateClientHook<T extends ContractDefinition>(
204
+ contract: Contract<T>,
205
+ endpointName: keyof T
206
+ ): string {
207
+ const endpoint = contract.__endpoints[endpointName as string];
208
+ if (!endpoint) {
209
+ throw new Error(`Endpoint "${String(endpointName)}" not found in contract`);
210
+ }
211
+
212
+ const { method, path, description } = endpoint;
213
+ const hookName = `use${String(endpointName).charAt(0).toUpperCase() + String(endpointName).slice(1)}`;
214
+ const isQuery = method === 'GET';
215
+
216
+ if (isQuery) {
217
+ return `
218
+ import { useQuery, type UseQueryOptions } from '@tanstack/react-query';
219
+ import type { ContractInput, ContractOutput } from '@mandujs/core';
220
+ import { contract } from '../contracts';
221
+
222
+ type Input = ContractInput<typeof contract, '${String(endpointName)}'>;
223
+ type Output = ContractOutput<typeof contract, '${String(endpointName)}'>;
224
+
225
+ /**
226
+ * ${description || endpointName as string}
227
+ */
228
+ export function ${hookName}(
229
+ params: Input,
230
+ options?: Omit<UseQueryOptions<Output>, 'queryKey' | 'queryFn'>
231
+ ) {
232
+ return useQuery({
233
+ queryKey: ['${String(endpointName)}', params],
234
+ queryFn: async () => {
235
+ const res = await fetch(\`${path.replace(/:(\w+)/g, '${params.$1}')}\`);
236
+ if (!res.ok) throw new Error('API Error');
237
+ return res.json() as Promise<Output>;
238
+ },
239
+ ...options,
240
+ });
241
+ }
242
+ `.trim();
243
+ } else {
244
+ return `
245
+ import { useMutation, type UseMutationOptions } from '@tanstack/react-query';
246
+ import type { ContractInput, ContractOutput } from '@mandujs/core';
247
+ import { contract } from '../contracts';
248
+
249
+ type Input = ContractInput<typeof contract, '${String(endpointName)}'>;
250
+ type Output = ContractOutput<typeof contract, '${String(endpointName)}'>;
251
+
252
+ /**
253
+ * ${description || endpointName as string}
254
+ */
255
+ export function ${hookName}(
256
+ options?: Omit<UseMutationOptions<Output, Error, Input>, 'mutationFn'>
257
+ ) {
258
+ return useMutation({
259
+ mutationFn: async (input: Input) => {
260
+ const res = await fetch('${path}', {
261
+ method: '${method}',
262
+ headers: { 'Content-Type': 'application/json' },
263
+ body: JSON.stringify(input),
264
+ });
265
+ if (!res.ok) throw new Error('API Error');
266
+ return res.json() as Promise<Output>;
267
+ },
268
+ ...options,
269
+ });
270
+ }
271
+ `.trim();
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Contract에서 전체 코드 생성
277
+ */
278
+ export function generateAllFromContract<T extends ContractDefinition>(
279
+ contract: Contract<T>
280
+ ): {
281
+ handlers: Record<string, string>;
282
+ hooks: Record<string, string>;
283
+ types: string;
284
+ } {
285
+ const handlers: Record<string, string> = {};
286
+ const hooks: Record<string, string> = {};
287
+
288
+ for (const name of Object.keys(contract.__endpoints)) {
289
+ handlers[name] = generateApiHandler(contract, name);
290
+ hooks[name] = generateClientHook(contract, name);
291
+ }
292
+
293
+ const types = generateTypeDefinitions(contract);
294
+
295
+ return { handlers, hooks, types };
296
+ }
297
+
298
+ /**
299
+ * Contract에서 타입 정의 생성
300
+ */
301
+ export function generateTypeDefinitions<T extends ContractDefinition>(
302
+ contract: Contract<T>
303
+ ): string {
304
+ const lines: string[] = [
305
+ `// Auto-generated types for ${contract.__name}`,
306
+ `// Version: ${contract.__version}`,
307
+ '',
308
+ 'import { z } from "zod";',
309
+ '',
310
+ ];
311
+
312
+ for (const [name, endpoint] of Object.entries(contract.__endpoints)) {
313
+ const typeName = name.charAt(0).toUpperCase() + name.slice(1);
314
+
315
+ if (endpoint.input) {
316
+ lines.push(`export type ${typeName}Input = z.infer<typeof ${name}InputSchema>;`);
317
+ }
318
+ if (endpoint.output) {
319
+ lines.push(`export type ${typeName}Output = z.infer<typeof ${name}OutputSchema>;`);
320
+ }
321
+ if (endpoint.params) {
322
+ lines.push(`export type ${typeName}Params = z.infer<typeof ${name}ParamsSchema>;`);
323
+ }
324
+ lines.push('');
325
+ }
326
+
327
+ return lines.join('\n');
328
+ }
329
+
330
+ // ============================================================================
331
+ // OpenAPI Generation
332
+ // ============================================================================
333
+
334
+ /**
335
+ * Contract에서 OpenAPI 스펙 생성
336
+ */
337
+ export function generateOpenAPISpec<T extends ContractDefinition>(
338
+ contract: Contract<T>,
339
+ options?: {
340
+ title?: string;
341
+ version?: string;
342
+ servers?: Array<{ url: string; description?: string }>;
343
+ }
344
+ ): Record<string, unknown> {
345
+ const paths: Record<string, Record<string, unknown>> = {};
346
+
347
+ for (const [name, endpoint] of Object.entries(contract.__endpoints)) {
348
+ const { method, path, input, output, description, tags, errors } = endpoint;
349
+
350
+ if (!paths[path]) {
351
+ paths[path] = {};
352
+ }
353
+
354
+ paths[path][method.toLowerCase()] = {
355
+ operationId: name,
356
+ summary: description || name,
357
+ tags: tags || [],
358
+ ...(input && ['POST', 'PUT', 'PATCH'].includes(method)
359
+ ? {
360
+ requestBody: {
361
+ required: true,
362
+ content: {
363
+ 'application/json': {
364
+ schema: { $ref: `#/components/schemas/${name}Input` },
365
+ },
366
+ },
367
+ },
368
+ }
369
+ : {}),
370
+ responses: {
371
+ '200': {
372
+ description: 'Success',
373
+ content: {
374
+ 'application/json': {
375
+ schema: { $ref: `#/components/schemas/${name}Output` },
376
+ },
377
+ },
378
+ },
379
+ ...(errors?.reduce(
380
+ (acc, error) => ({
381
+ ...acc,
382
+ [getStatusCode(error)]: {
383
+ description: error,
384
+ },
385
+ }),
386
+ {}
387
+ ) || {}),
388
+ },
389
+ };
390
+ }
391
+
392
+ return {
393
+ openapi: '3.0.3',
394
+ info: {
395
+ title: options?.title || contract.__name,
396
+ version: options?.version || contract.__version,
397
+ },
398
+ servers: options?.servers || [{ url: '/' }],
399
+ paths,
400
+ components: {
401
+ schemas: generateSchemas(contract),
402
+ },
403
+ };
404
+ }
405
+
406
+ function generateSchemas<T extends ContractDefinition>(
407
+ contract: Contract<T>
408
+ ): Record<string, unknown> {
409
+ const schemas: Record<string, unknown> = {};
410
+
411
+ for (const [name, endpoint] of Object.entries(contract.__endpoints)) {
412
+ if (endpoint.input) {
413
+ schemas[`${name}Input`] = zodToOpenAPI(endpoint.input);
414
+ }
415
+ if (endpoint.output) {
416
+ schemas[`${name}Output`] = zodToOpenAPI(endpoint.output);
417
+ }
418
+ }
419
+
420
+ return schemas;
421
+ }
422
+
423
+ function zodToOpenAPI(schema: ZodType): Record<string, unknown> {
424
+ const typeName = getZodTypeName(schema);
425
+
426
+ switch (typeName) {
427
+ case 'ZodString':
428
+ return { type: 'string' };
429
+ case 'ZodNumber':
430
+ return { type: 'number' };
431
+ case 'ZodBoolean':
432
+ return { type: 'boolean' };
433
+ case 'ZodArray': {
434
+ const elementType = getZodArrayElementType(schema);
435
+ return { type: 'array', items: elementType ? zodToOpenAPI(elementType) : {} };
436
+ }
437
+ case 'ZodObject': {
438
+ const properties: Record<string, unknown> = {};
439
+ const required: string[] = [];
440
+ const shape = getZodObjectShape(schema) ?? {};
441
+ for (const [key, value] of Object.entries(shape)) {
442
+ properties[key] = zodToOpenAPI(value);
443
+ if (isZodRequired(value)) {
444
+ required.push(key);
445
+ }
446
+ }
447
+ return { type: 'object', properties, required };
448
+ }
449
+ case 'ZodOptional': {
450
+ const inner = getZodInnerType(schema);
451
+ return inner ? zodToOpenAPI(inner) : {};
452
+ }
453
+ case 'ZodNullable': {
454
+ const inner = getZodInnerType(schema);
455
+ return { ...(inner ? zodToOpenAPI(inner) : {}), nullable: true };
456
+ }
457
+ case 'ZodEnum':
458
+ return { type: 'string', enum: getZodEnumValues(schema) };
459
+ default:
460
+ return { type: 'object' };
461
+ }
462
+ }
463
+
464
+ function getStatusCode(error: string): string {
465
+ const map: Record<string, string> = {
466
+ NOT_FOUND: '404',
467
+ UNAUTHORIZED: '401',
468
+ FORBIDDEN: '403',
469
+ RATE_LIMITED: '429',
470
+ BAD_REQUEST: '400',
471
+ INTERNAL_ERROR: '500',
472
+ };
473
+ return map[error] || '400';
474
+ }