@mandujs/core 0.3.4 → 0.4.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.
- package/package.json +2 -1
- package/src/bundler/build.ts +609 -0
- package/src/bundler/index.ts +7 -0
- package/src/bundler/types.ts +100 -0
- package/src/client/index.ts +68 -0
- package/src/client/island.ts +197 -0
- package/src/client/runtime.ts +335 -0
- package/src/filling/filling.ts +76 -5
- package/src/index.ts +1 -0
- package/src/runtime/ssr.ts +142 -2
- package/src/spec/schema.ts +132 -0
package/src/filling/filling.ts
CHANGED
|
@@ -15,10 +15,14 @@ export type Guard = (ctx: ManduContext) => symbol | Response | Promise<symbol |
|
|
|
15
15
|
/** HTTP methods */
|
|
16
16
|
export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "HEAD" | "OPTIONS";
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
/** Loader function type - SSR 데이터 로딩 */
|
|
19
|
+
export type Loader<T = unknown> = (ctx: ManduContext) => T | Promise<T>;
|
|
20
|
+
|
|
21
|
+
interface FillingConfig<TLoaderData = unknown> {
|
|
19
22
|
handlers: Map<HttpMethod, Handler>;
|
|
20
23
|
guards: Guard[];
|
|
21
24
|
methodGuards: Map<HttpMethod, Guard[]>;
|
|
25
|
+
loader?: Loader<TLoaderData>;
|
|
22
26
|
}
|
|
23
27
|
|
|
24
28
|
/**
|
|
@@ -30,14 +34,64 @@ interface FillingConfig {
|
|
|
30
34
|
* .get(ctx => ctx.ok({ message: 'Hello!' }))
|
|
31
35
|
* .post(ctx => ctx.created({ id: 1 }))
|
|
32
36
|
* ```
|
|
37
|
+
*
|
|
38
|
+
* @example with loader
|
|
39
|
+
* ```typescript
|
|
40
|
+
* export default Mandu.filling<{ todos: Todo[] }>()
|
|
41
|
+
* .loader(async (ctx) => {
|
|
42
|
+
* const todos = await db.todos.findMany();
|
|
43
|
+
* return { todos };
|
|
44
|
+
* })
|
|
45
|
+
* .get(ctx => ctx.ok(ctx.get('loaderData')))
|
|
46
|
+
* ```
|
|
33
47
|
*/
|
|
34
|
-
export class ManduFilling {
|
|
35
|
-
private config: FillingConfig = {
|
|
48
|
+
export class ManduFilling<TLoaderData = unknown> {
|
|
49
|
+
private config: FillingConfig<TLoaderData> = {
|
|
36
50
|
handlers: new Map(),
|
|
37
51
|
guards: [],
|
|
38
52
|
methodGuards: new Map(),
|
|
39
53
|
};
|
|
40
54
|
|
|
55
|
+
// ============================================
|
|
56
|
+
// 🥟 SSR Loader
|
|
57
|
+
// ============================================
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Define SSR data loader
|
|
61
|
+
* 페이지 렌더링 전 서버에서 데이터를 로드합니다.
|
|
62
|
+
* 로드된 데이터는 클라이언트로 전달되어 hydration에 사용됩니다.
|
|
63
|
+
*
|
|
64
|
+
* @example
|
|
65
|
+
* ```typescript
|
|
66
|
+
* .loader(async (ctx) => {
|
|
67
|
+
* const todos = await db.todos.findMany();
|
|
68
|
+
* return { todos, user: ctx.get('user') };
|
|
69
|
+
* })
|
|
70
|
+
* ```
|
|
71
|
+
*/
|
|
72
|
+
loader(loaderFn: Loader<TLoaderData>): this {
|
|
73
|
+
this.config.loader = loaderFn;
|
|
74
|
+
return this;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Execute loader and return data
|
|
79
|
+
* @internal Used by SSR runtime
|
|
80
|
+
*/
|
|
81
|
+
async executeLoader(ctx: ManduContext): Promise<TLoaderData | undefined> {
|
|
82
|
+
if (!this.config.loader) {
|
|
83
|
+
return undefined;
|
|
84
|
+
}
|
|
85
|
+
return await this.config.loader(ctx);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Check if loader is defined
|
|
90
|
+
*/
|
|
91
|
+
hasLoader(): boolean {
|
|
92
|
+
return !!this.config.loader;
|
|
93
|
+
}
|
|
94
|
+
|
|
41
95
|
// ============================================
|
|
42
96
|
// 🥟 HTTP Method Handlers
|
|
43
97
|
// ============================================
|
|
@@ -242,9 +296,26 @@ export const Mandu = {
|
|
|
242
296
|
* export default Mandu.filling()
|
|
243
297
|
* .get(ctx => ctx.ok({ message: 'Hello!' }))
|
|
244
298
|
* ```
|
|
299
|
+
*
|
|
300
|
+
* @example with loader data type
|
|
301
|
+
* ```typescript
|
|
302
|
+
* import { Mandu } from '@mandujs/core'
|
|
303
|
+
*
|
|
304
|
+
* interface LoaderData {
|
|
305
|
+
* todos: Todo[];
|
|
306
|
+
* user: User | null;
|
|
307
|
+
* }
|
|
308
|
+
*
|
|
309
|
+
* export default Mandu.filling<LoaderData>()
|
|
310
|
+
* .loader(async (ctx) => {
|
|
311
|
+
* const todos = await db.todos.findMany();
|
|
312
|
+
* return { todos, user: null };
|
|
313
|
+
* })
|
|
314
|
+
* .get(ctx => ctx.ok(ctx.get('loaderData')))
|
|
315
|
+
* ```
|
|
245
316
|
*/
|
|
246
|
-
filling(): ManduFilling {
|
|
247
|
-
return new ManduFilling();
|
|
317
|
+
filling<TLoaderData = unknown>(): ManduFilling<TLoaderData> {
|
|
318
|
+
return new ManduFilling<TLoaderData>();
|
|
248
319
|
},
|
|
249
320
|
|
|
250
321
|
/**
|
package/src/index.ts
CHANGED
package/src/runtime/ssr.ts
CHANGED
|
@@ -1,14 +1,120 @@
|
|
|
1
1
|
import { renderToString } from "react-dom/server";
|
|
2
2
|
import type { ReactElement } from "react";
|
|
3
|
+
import type { BundleManifest } from "../bundler/types";
|
|
4
|
+
import type { HydrationConfig, HydrationPriority } from "../spec/schema";
|
|
3
5
|
|
|
4
6
|
export interface SSROptions {
|
|
5
7
|
title?: string;
|
|
6
8
|
lang?: string;
|
|
9
|
+
/** 서버에서 로드한 데이터 (클라이언트로 전달) */
|
|
10
|
+
serverData?: Record<string, unknown>;
|
|
11
|
+
/** Hydration 설정 */
|
|
12
|
+
hydration?: HydrationConfig;
|
|
13
|
+
/** 번들 매니페스트 */
|
|
14
|
+
bundleManifest?: BundleManifest;
|
|
15
|
+
/** 라우트 ID (island 식별용) */
|
|
16
|
+
routeId?: string;
|
|
17
|
+
/** 추가 head 태그 */
|
|
18
|
+
headTags?: string;
|
|
19
|
+
/** 추가 body 끝 태그 */
|
|
20
|
+
bodyEndTags?: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* SSR 데이터를 안전하게 직렬화
|
|
25
|
+
*/
|
|
26
|
+
function serializeServerData(data: Record<string, unknown>): string {
|
|
27
|
+
// XSS 방지를 위한 이스케이프
|
|
28
|
+
const json = JSON.stringify(data)
|
|
29
|
+
.replace(/</g, "\\u003c")
|
|
30
|
+
.replace(/>/g, "\\u003e")
|
|
31
|
+
.replace(/&/g, "\\u0026")
|
|
32
|
+
.replace(/'/g, "\\u0027");
|
|
33
|
+
|
|
34
|
+
return `<script id="__MANDU_DATA__" type="application/json">${json}</script>
|
|
35
|
+
<script>window.__MANDU_DATA__ = JSON.parse(document.getElementById('__MANDU_DATA__').textContent);</script>`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Hydration 스크립트 태그 생성
|
|
40
|
+
*/
|
|
41
|
+
function generateHydrationScripts(
|
|
42
|
+
routeId: string,
|
|
43
|
+
manifest: BundleManifest
|
|
44
|
+
): string {
|
|
45
|
+
const scripts: string[] = [];
|
|
46
|
+
|
|
47
|
+
// Runtime 로드
|
|
48
|
+
if (manifest.shared.runtime) {
|
|
49
|
+
scripts.push(`<script type="module" src="${manifest.shared.runtime}"></script>`);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Vendor 로드
|
|
53
|
+
if (manifest.shared.vendor) {
|
|
54
|
+
scripts.push(`<script type="module" src="${manifest.shared.vendor}"></script>`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Island 번들 로드
|
|
58
|
+
const bundle = manifest.bundles[routeId];
|
|
59
|
+
if (bundle) {
|
|
60
|
+
// Preload (선택적)
|
|
61
|
+
scripts.push(`<link rel="modulepreload" href="${bundle.js}">`);
|
|
62
|
+
scripts.push(`<script type="module" src="${bundle.js}"></script>`);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return scripts.join("\n");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Island 래퍼로 컨텐츠 감싸기
|
|
70
|
+
*/
|
|
71
|
+
export function wrapWithIsland(
|
|
72
|
+
content: string,
|
|
73
|
+
routeId: string,
|
|
74
|
+
priority: HydrationPriority = "visible"
|
|
75
|
+
): string {
|
|
76
|
+
return `<div data-mandu-island="${routeId}" data-mandu-priority="${priority}">${content}</div>`;
|
|
7
77
|
}
|
|
8
78
|
|
|
9
79
|
export function renderToHTML(element: ReactElement, options: SSROptions = {}): string {
|
|
10
|
-
const {
|
|
11
|
-
|
|
80
|
+
const {
|
|
81
|
+
title = "Mandu App",
|
|
82
|
+
lang = "ko",
|
|
83
|
+
serverData,
|
|
84
|
+
hydration,
|
|
85
|
+
bundleManifest,
|
|
86
|
+
routeId,
|
|
87
|
+
headTags = "",
|
|
88
|
+
bodyEndTags = "",
|
|
89
|
+
} = options;
|
|
90
|
+
|
|
91
|
+
let content = renderToString(element);
|
|
92
|
+
|
|
93
|
+
// Island 래퍼 적용 (hydration 필요 시)
|
|
94
|
+
const needsHydration =
|
|
95
|
+
hydration && hydration.strategy !== "none" && routeId && bundleManifest;
|
|
96
|
+
|
|
97
|
+
if (needsHydration) {
|
|
98
|
+
content = wrapWithIsland(content, routeId, hydration.priority);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// 서버 데이터 스크립트
|
|
102
|
+
let dataScript = "";
|
|
103
|
+
if (serverData && routeId) {
|
|
104
|
+
const wrappedData = {
|
|
105
|
+
[routeId]: {
|
|
106
|
+
serverData,
|
|
107
|
+
timestamp: Date.now(),
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
dataScript = serializeServerData(wrappedData);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Hydration 스크립트
|
|
114
|
+
let hydrationScripts = "";
|
|
115
|
+
if (needsHydration && bundleManifest) {
|
|
116
|
+
hydrationScripts = generateHydrationScripts(routeId, bundleManifest);
|
|
117
|
+
}
|
|
12
118
|
|
|
13
119
|
return `<!doctype html>
|
|
14
120
|
<html lang="${lang}">
|
|
@@ -16,9 +122,13 @@ export function renderToHTML(element: ReactElement, options: SSROptions = {}): s
|
|
|
16
122
|
<meta charset="UTF-8">
|
|
17
123
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
18
124
|
<title>${title}</title>
|
|
125
|
+
${headTags}
|
|
19
126
|
</head>
|
|
20
127
|
<body>
|
|
21
128
|
<div id="root">${content}</div>
|
|
129
|
+
${dataScript}
|
|
130
|
+
${hydrationScripts}
|
|
131
|
+
${bodyEndTags}
|
|
22
132
|
</body>
|
|
23
133
|
</html>`;
|
|
24
134
|
}
|
|
@@ -36,3 +146,33 @@ export function renderSSR(element: ReactElement, options: SSROptions = {}): Resp
|
|
|
36
146
|
const html = renderToHTML(element, options);
|
|
37
147
|
return createHTMLResponse(html);
|
|
38
148
|
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Hydration이 포함된 SSR 렌더링
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```typescript
|
|
155
|
+
* const response = await renderWithHydration(
|
|
156
|
+
* <TodoList todos={todos} />,
|
|
157
|
+
* {
|
|
158
|
+
* title: "할일 목록",
|
|
159
|
+
* routeId: "todos",
|
|
160
|
+
* serverData: { todos },
|
|
161
|
+
* hydration: { strategy: "island", priority: "visible" },
|
|
162
|
+
* bundleManifest,
|
|
163
|
+
* }
|
|
164
|
+
* );
|
|
165
|
+
* ```
|
|
166
|
+
*/
|
|
167
|
+
export async function renderWithHydration(
|
|
168
|
+
element: ReactElement,
|
|
169
|
+
options: SSROptions & {
|
|
170
|
+
routeId: string;
|
|
171
|
+
serverData: Record<string, unknown>;
|
|
172
|
+
hydration: HydrationConfig;
|
|
173
|
+
bundleManifest: BundleManifest;
|
|
174
|
+
}
|
|
175
|
+
): Promise<Response> {
|
|
176
|
+
const html = renderToHTML(element, options);
|
|
177
|
+
return createHTMLResponse(html);
|
|
178
|
+
}
|
package/src/spec/schema.ts
CHANGED
|
@@ -1,16 +1,90 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
|
|
3
|
+
// ========== Hydration 설정 ==========
|
|
4
|
+
|
|
5
|
+
export const HydrationStrategy = z.enum(["none", "island", "full", "progressive"]);
|
|
6
|
+
export type HydrationStrategy = z.infer<typeof HydrationStrategy>;
|
|
7
|
+
|
|
8
|
+
export const HydrationPriority = z.enum(["immediate", "visible", "idle", "interaction"]);
|
|
9
|
+
export type HydrationPriority = z.infer<typeof HydrationPriority>;
|
|
10
|
+
|
|
11
|
+
export const HydrationConfig = z.object({
|
|
12
|
+
/**
|
|
13
|
+
* Hydration 전략
|
|
14
|
+
* - none: 순수 Static HTML (JS 없음)
|
|
15
|
+
* - island: Slot 영역만 hydrate (기본값)
|
|
16
|
+
* - full: 전체 페이지 hydrate
|
|
17
|
+
* - progressive: 점진적 hydrate
|
|
18
|
+
*/
|
|
19
|
+
strategy: HydrationStrategy,
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Hydration 우선순위
|
|
23
|
+
* - immediate: 페이지 로드 즉시
|
|
24
|
+
* - visible: 뷰포트에 보일 때 (기본값)
|
|
25
|
+
* - idle: 브라우저 idle 시
|
|
26
|
+
* - interaction: 사용자 상호작용 시
|
|
27
|
+
*/
|
|
28
|
+
priority: HydrationPriority.default("visible"),
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 번들 preload 여부
|
|
32
|
+
*/
|
|
33
|
+
preload: z.boolean().default(false),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
export type HydrationConfig = z.infer<typeof HydrationConfig>;
|
|
37
|
+
|
|
38
|
+
// ========== Loader 설정 ==========
|
|
39
|
+
|
|
40
|
+
export const LoaderConfig = z.object({
|
|
41
|
+
/**
|
|
42
|
+
* SSR 시 데이터 로딩 타임아웃 (ms)
|
|
43
|
+
*/
|
|
44
|
+
timeout: z.number().positive().default(5000),
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 로딩 실패 시 fallback 데이터
|
|
48
|
+
*/
|
|
49
|
+
fallback: z.record(z.unknown()).optional(),
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
export type LoaderConfig = z.infer<typeof LoaderConfig>;
|
|
53
|
+
|
|
54
|
+
// ========== Route 설정 ==========
|
|
55
|
+
|
|
3
56
|
export const RouteKind = z.enum(["page", "api"]);
|
|
4
57
|
export type RouteKind = z.infer<typeof RouteKind>;
|
|
5
58
|
|
|
59
|
+
export const HttpMethod = z.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]);
|
|
60
|
+
export type HttpMethod = z.infer<typeof HttpMethod>;
|
|
61
|
+
|
|
6
62
|
export const RouteSpec = z
|
|
7
63
|
.object({
|
|
8
64
|
id: z.string().min(1, "id는 필수입니다"),
|
|
9
65
|
pattern: z.string().startsWith("/", "pattern은 /로 시작해야 합니다"),
|
|
10
66
|
kind: RouteKind,
|
|
67
|
+
|
|
68
|
+
// HTTP 메서드 (API용)
|
|
69
|
+
methods: z.array(HttpMethod).optional(),
|
|
70
|
+
|
|
71
|
+
// 서버 모듈 (generated route handler)
|
|
11
72
|
module: z.string().min(1, "module 경로는 필수입니다"),
|
|
73
|
+
|
|
74
|
+
// 페이지 컴포넌트 모듈 (generated)
|
|
12
75
|
componentModule: z.string().optional(),
|
|
76
|
+
|
|
77
|
+
// 서버 슬롯 (비즈니스 로직)
|
|
13
78
|
slotModule: z.string().optional(),
|
|
79
|
+
|
|
80
|
+
// 클라이언트 슬롯 (interactive 로직) [NEW]
|
|
81
|
+
clientModule: z.string().optional(),
|
|
82
|
+
|
|
83
|
+
// Hydration 설정 [NEW]
|
|
84
|
+
hydration: HydrationConfig.optional(),
|
|
85
|
+
|
|
86
|
+
// Loader 설정 [NEW]
|
|
87
|
+
loader: LoaderConfig.optional(),
|
|
14
88
|
})
|
|
15
89
|
.refine(
|
|
16
90
|
(route) => {
|
|
@@ -23,10 +97,25 @@ export const RouteSpec = z
|
|
|
23
97
|
message: "kind가 'page'인 경우 componentModule은 필수입니다",
|
|
24
98
|
path: ["componentModule"],
|
|
25
99
|
}
|
|
100
|
+
)
|
|
101
|
+
.refine(
|
|
102
|
+
(route) => {
|
|
103
|
+
// clientModule이 있으면 hydration.strategy가 none이 아니어야 함
|
|
104
|
+
if (route.clientModule && route.hydration?.strategy === "none") {
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
return true;
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
message: "clientModule이 있으면 hydration.strategy는 'none'이 아니어야 합니다",
|
|
111
|
+
path: ["hydration"],
|
|
112
|
+
}
|
|
26
113
|
);
|
|
27
114
|
|
|
28
115
|
export type RouteSpec = z.infer<typeof RouteSpec>;
|
|
29
116
|
|
|
117
|
+
// ========== Manifest ==========
|
|
118
|
+
|
|
30
119
|
export const RoutesManifest = z
|
|
31
120
|
.object({
|
|
32
121
|
version: z.number().int().positive(),
|
|
@@ -56,3 +145,46 @@ export const RoutesManifest = z
|
|
|
56
145
|
);
|
|
57
146
|
|
|
58
147
|
export type RoutesManifest = z.infer<typeof RoutesManifest>;
|
|
148
|
+
|
|
149
|
+
// ========== 유틸리티 함수 ==========
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* 기본 hydration 설정 반환
|
|
153
|
+
*/
|
|
154
|
+
export function getDefaultHydration(route: RouteSpec): HydrationConfig {
|
|
155
|
+
// clientModule이 있으면 island, 없으면 none
|
|
156
|
+
if (route.clientModule) {
|
|
157
|
+
return {
|
|
158
|
+
strategy: "island",
|
|
159
|
+
priority: "visible",
|
|
160
|
+
preload: false,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
strategy: "none",
|
|
165
|
+
priority: "visible",
|
|
166
|
+
preload: false,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* 라우트의 실제 hydration 설정 반환 (기본값 적용)
|
|
172
|
+
*/
|
|
173
|
+
export function getRouteHydration(route: RouteSpec): HydrationConfig {
|
|
174
|
+
if (route.hydration) {
|
|
175
|
+
return {
|
|
176
|
+
strategy: route.hydration.strategy,
|
|
177
|
+
priority: route.hydration.priority ?? "visible",
|
|
178
|
+
preload: route.hydration.preload ?? false,
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
return getDefaultHydration(route);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Hydration이 필요한 라우트인지 확인
|
|
186
|
+
*/
|
|
187
|
+
export function needsHydration(route: RouteSpec): boolean {
|
|
188
|
+
const hydration = getRouteHydration(route);
|
|
189
|
+
return route.kind === "page" && hydration.strategy !== "none";
|
|
190
|
+
}
|